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
feat(project-settings): per-project section shell, identity + defaults rows
enesd2a5f8d0b6d7
diff --git a/src/renderer/components/settings/SettingsPage.tsx b/src/renderer/components/settings/SettingsPage.tsxindex d69d9d67d..6ad216208 100644--- a/src/renderer/components/settings/SettingsPage.tsx+++ b/src/renderer/components/settings/SettingsPage.tsx@@ -1,9 +1,12 @@-import { useEffect, useState } from 'react'+import { useEffect, useMemo, useState } from 'react'import { createPortal } from 'react-dom'import { useEntitlement } from '../../state/entitlement'+import { useProjects } from '../../state/projects'import { SettingsSearchContext } from './context'import { SettingsSidebar } from './SettingsSidebar'-import { FIRST_SECTION_ID, type SettingsSectionId } from './nav'+import { FIRST_SECTION_ID, projectsSettingsGroup, type SettingsSectionId } from './nav'+import { projectSectionId } from './project-settings-targets'+import { ProjectSettingsSection } from './sections/ProjectSettingsSection'import { TerminalSection } from './sections/TerminalSection'import { ShellSection } from './sections/ShellSection'import { BehaviorSection } from './sections/BehaviorSection'@@ -43,6 +46,18 @@ export function SettingsPage({const [active, setActive] = useState<SettingsSectionId>(initialSection ?? FIRST_SECTION_ID)const [query, setQuery] = useState('')+ // 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])+ const extraGroups = useMemo(() => {+ const group = projectsSettingsGroup(+ openProjects.map((p) => ({ id: p.id, name: p.name, color: p.color }))+ )+ return group ? [group] : []+ }, [openProjects])+useEffect(() => {void hydrate()}, [hydrate])@@ -68,6 +83,7 @@ export function SettingsPage({onSelect={setActive}onQueryChange={setQuery}onClose={onClose}+ extraGroups={extraGroups}/><SettingsSearchContext.Provider value={query}><main className="min-w-0 flex-1 overflow-y-auto px-12 py-10">@@ -96,6 +112,13 @@ export function SettingsPage({<UpdatesSection isActive={active === 'updates'} /><PrivacySection isActive={active === 'privacy'} /><DebugSection isActive={active === 'debug'} />+ {openProjects.map((p) => (+ <ProjectSettingsSection+ key={p.id}+ projectId={p.id}+ isActive={active === projectSectionId(p.id)}+ />+ ))}</div></main></SettingsSearchContext.Provider>diff --git a/src/renderer/components/settings/sections/ProjectSettingsSection.test.tsx b/src/renderer/components/settings/sections/ProjectSettingsSection.test.tsxnew file mode 100644index 000000000..314eca409--- /dev/null+++ b/src/renderer/components/settings/sections/ProjectSettingsSection.test.tsx@@ -0,0 +1,312 @@+// @vitest-environment jsdom+import { act } from 'react'+import { createRoot, type Root } from 'react-dom/client'+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 { SettingsSearchContext } from '../context'+import { ProjectSettingsSection } from './ProjectSettingsSection'+import { useProjectSettings, type ProjectSettingsHook } from '../useProjectSettings'++;(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true++function project(over: Partial<Project> = {}): Project {+ return {+ id: 'p1',+ name: 'Alpha',+ color: '#0a84ff',+ cwd: '/repo/alpha',+ viewport: { x: 0, y: 0, zoom: 1 },+ nodes: [],+ ...over+ }+}++const EMPTY_SNAPSHOT: ProjectSettingsSnapshot = { shared: null, local: undefined }++describe('ProjectSettingsSection', () => {+ let root: Root+ let host: HTMLElement+ let read: ReturnType<typeof vi.fn>+ let writeShared: ReturnType<typeof vi.fn>+ let updateLocal: ReturnType<typeof vi.fn>+ let save: ReturnType<typeof vi.fn>++ const mount = async (node: React.JSX.Element, query = ''): Promise<void> => {+ root = createRoot(host)+ await act(async () => {+ root.render(<SettingsSearchContext.Provider value={query}>{node}</SettingsSearchContext.Provider>)+ })+ }++ const mountSection = async (+ p: Project = project(),+ { isActive = true, query = '' }: { isActive?: boolean; query?: string } = {}+ ): Promise<void> => {+ useProjects.setState({ projects: [p], activeProjectId: p.id })+ await mount(<ProjectSettingsSection projectId={p.id} isActive={isActive} />, query)+ }++ const typeInto = async (el: HTMLInputElement, value: string): Promise<void> => {+ await act(async () => {+ const setter = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')!.set!+ setter.call(el, value)+ el.dispatchEvent(new Event('input', { bubbles: true }))+ })+ }++ const nameInput = (): HTMLInputElement => host.querySelector<HTMLInputElement>('#project-name-p1')!++ /** A real blur fires `focusout`, which is what React's `onBlur` listens for. */+ const blur = async (el: HTMLElement): Promise<void> => {+ await act(async () => {+ el.dispatchEvent(new FocusEvent('focusout', { bubbles: true }))+ })+ }++ beforeEach(() => {+ host = document.createElement('div')+ document.body.appendChild(host)+ read = vi.fn(async () => EMPTY_SNAPSHOT)+ writeShared = vi.fn(async () => true)+ updateLocal = vi.fn(async () => true)+ save = vi.fn(async () => undefined)+ ;(window as unknown as { nodeTerminal: any }).nodeTerminal = {+ projectSettings: { read, writeShared, updateLocal },+ workspace: { save }+ }+ })++ afterEach(() => {+ act(() => root.unmount())+ host.remove()+ useProjects.setState({ projects: [], activeProjectId: '' })+ })++ it('titles the section with the project and shows its folder', async () => {+ await mountSection()+ expect(host.textContent).toContain('Alpha')+ expect(host.textContent).toContain('/repo/alpha')+ expect(nameInput().value).toBe('Alpha')+ expect(read).toHaveBeenCalledWith('p1')+ })++ it('shows an SSH project as user@host:path', async () => {+ await mountSection(+ project({ ssh: { server: { host: 'box', user: 'enes' } as never, remoteCwd: '/srv/app' } })+ )+ expect(host.textContent).toContain('enes@box:/srv/app')+ })++ it('renames the project on BLUR only, then saves the workspace', 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()+ 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')+ })++ it('ignores a blank rename instead of writing an unnamed project', async () => {+ await mountSection()+ await typeInto(nameInput(), ' ')+ await blur(nameInput())+ expect(useProjects.getState().getProject('p1')?.name).toBe('Alpha')+ expect(save).not.toHaveBeenCalled()+ })++ it('picks a color and persists it', async () => {+ await mountSection()+ const swatch = host.querySelector<HTMLButtonElement>('button[data-project-color="#32d74b"]')!+ await act(async () => {+ swatch.dispatchEvent(new MouseEvent('click', { bubbles: true }))+ })+ expect(useProjects.getState().getProject('p1')?.color).toBe('#32d74b')+ expect(save).toHaveBeenCalledTimes(1)+ })++ it('sets the default permission mode and clears it back to the global default', async () => {+ await mountSection()+ const select = host.querySelector<HTMLSelectElement>('#project-permission-mode-p1')!+ await act(async () => {+ const setter = Object.getOwnPropertyDescriptor(HTMLSelectElement.prototype, 'value')!.set!+ setter.call(select, 'plan')+ select.dispatchEvent(new Event('change', { bubbles: true }))+ })+ expect(useProjects.getState().getProject('p1')?.defaultPermissionMode).toBe('plan')+ await act(async () => {+ const setter = Object.getOwnPropertyDescriptor(HTMLSelectElement.prototype, 'value')!.set!+ setter.call(select, '')+ select.dispatchEvent(new Event('change', { bubbles: true }))+ })+ expect(useProjects.getState().getProject('p1')?.defaultPermissionMode).toBeUndefined()+ expect(save).toHaveBeenCalledTimes(2)+ })++ it('shows the conflict banner when the shared file is git-conflicted', async () => {+ read = vi.fn(async () => ({ shared: null, local: undefined, conflict: true }) as ProjectSettingsSnapshot)+ ;(window as unknown as { nodeTerminal: any }).nodeTerminal.projectSettings.read = read+ await mountSection()+ expect(host.textContent).toContain('conflict')+ expect(host.textContent).toContain('.nodeterm/settings.json')+ })++ it('offers no editors at all for a relay (remote) project', async () => {+ await mountSection(project({ remote: true }))+ expect(host.textContent).toContain('Alpha')+ expect(host.querySelectorAll('input, select, textarea, button')).toHaveLength(0)+ // A relay tab's project settings live on the OTHER machine — never read ours for it.+ expect(read).not.toHaveBeenCalled()+ })++ it('offers no editors for an unavailable project', async () => {+ await mountSection(project({ unavailable: true }))+ expect(host.querySelectorAll('input, select, textarea, button')).toHaveLength(0)+ expect(read).not.toHaveBeenCalled()+ })++ it('reads nothing for a section that is neither active nor matched by the search', async () => {+ await mountSection(project(), { isActive: false })+ expect(host.textContent).toBe('')+ expect(read).not.toHaveBeenCalled()+ })++ it('renders (and reads) when a search query matches the project name', async () => {+ await mountSection(project(), { isActive: false, query: 'alph' })+ expect(host.textContent).toContain('Alpha')+ expect(read).toHaveBeenCalledWith('p1')+ })+})++describe('useProjectSettings', () => {+ let root: Root+ let host: HTMLElement+ let hook: ProjectSettingsHook+ let read: ReturnType<typeof vi.fn>+ let writeShared: ReturnType<typeof vi.fn>+ let updateLocal: ReturnType<typeof vi.fn>++ function Probe({ projectId }: { projectId: string }): React.JSX.Element {+ hook = useProjectSettings(projectId)+ return <div>{hook.snapshot === 'loading' ? 'loading' : JSON.stringify(hook.resolved)}</div>+ }++ const mount = async (): Promise<void> => {+ root = createRoot(host)+ await act(async () => {+ root.render(<Probe projectId="p1" />)+ })+ }++ beforeEach(() => {+ host = document.createElement('div')+ document.body.appendChild(host)+ read = vi.fn(async () => ({+ shared: { version: 1, rev: 3, savedAt: 't', terminal: { shell: '/bin/bash', theme: 'dark' } },+ local: undefined+ }))+ writeShared = vi.fn(async () => true)+ updateLocal = vi.fn(async () => true)+ ;(window as unknown as { nodeTerminal: any }).nodeTerminal = {+ projectSettings: { read, writeShared, updateLocal },+ workspace: { save: vi.fn() }+ }+ })++ afterEach(() => {+ act(() => root.unmount())+ host.remove()+ })++ it('resolves local over shared with provenance', async () => {+ read.mockResolvedValue({+ shared: { version: 1, rev: 3, savedAt: 't', terminal: { shell: '/bin/bash', theme: 'dark' } },+ local: { terminal: { theme: 'light' } }+ })+ await mount()+ expect(hook.resolved.terminal.shell).toEqual({ value: '/bin/bash', source: 'shared' })+ expect(hook.resolved.terminal.theme).toEqual({ value: 'light', source: 'local' })+ })++ it('reports empty families while the read is still in flight', async () => {+ 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')+ expect(hook.resolved).toEqual({ setup: {}, worktree: {}, agents: {}, terminal: {} })+ await act(async () => {+ release(EMPTY_SNAPSHOT)+ })+ })++ it('writes the WHOLE document (merging the edited field) and re-reads after a save', async () => {+ await mount()+ expect(read).toHaveBeenCalledTimes(1)+ let ok = false+ await act(async () => {+ ok = await hook.saveShared({ terminal: { shell: '/bin/fish' } })+ })+ expect(ok).toBe(true)+ // The sibling field survives, and version/rev/savedAt are stripped — the store owns those.+ expect(writeShared).toHaveBeenCalledTimes(1)+ expect(writeShared).toHaveBeenCalledWith('p1', { terminal: { shell: '/bin/fish', theme: 'dark' } })+ expect(read).toHaveBeenCalledTimes(2)+ })++ 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' } },+ local: undefined+ })+ await mount()+ await act(async () => {+ await hook.saveShared({ terminal: { shell: undefined } })+ })+ expect(writeShared).toHaveBeenCalledWith('p1', {})+ })++ it('does not re-read when the write is refused', async () => {+ writeShared.mockResolvedValue(false)+ await mount()+ let ok = true+ await act(async () => {+ ok = await hook.saveShared({ terminal: { shell: '/bin/fish' } })+ })+ expect(ok).toBe(false)+ expect(read).toHaveBeenCalledTimes(1)+ })++ 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 } })+ })+ expect(updateLocal).toHaveBeenCalledWith('p1', {+ terminal: { shell: '/bin/zsh' },+ ignoreShared: { agents: true }+ })+ expect(read).toHaveBeenCalledTimes(2)+ })++ it('degrades a failed read to "nothing readable" instead of throwing', async () => {+ read.mockRejectedValue(new Error('boom'))+ await mount()+ expect(hook.snapshot).toBeNull()+ expect(hook.resolved.terminal.shell).toBeUndefined()+ })++ it('re-reads on reload()', async () => {+ await mount()+ await act(async () => {+ hook.reload()+ })+ expect(read).toHaveBeenCalledTimes(2)+ })+})diff --git a/src/renderer/components/settings/sections/ProjectSettingsSection.tsx b/src/renderer/components/settings/sections/ProjectSettingsSection.tsxnew file mode 100644index 000000000..d1d41133c--- /dev/null+++ b/src/renderer/components/settings/sections/ProjectSettingsSection.tsx@@ -0,0 +1,315 @@+import { useEffect, useMemo, useState } from 'react'+import type { Project } from '@shared/types'+import {+ ALL_PERMISSION_MODES,+ PERMISSION_MODE_LABELS,+ type AgentPermissionMode+} from '@shared/agents/config'+import { Input } from '@renderer/ui/Input'+import { Select } from '@renderer/ui/Select'+import { cn } from '@renderer/ui/cn'+import { useProjects } from '../../../state/projects'+import { useSettings } from '../../../state/settings'+import { useSystemAccount } from '../../../state/systemAccount'+import {+ NODE_COLORS,+ accountsForProject,+ sshAccountsHint,+ systemAccountDisplay+} from '../../../state/workspace'+import { FieldRow } from '../FieldRow'+import { SearchableRow } from '../SearchableRow'+import { SettingsSection } from '../SettingsSection'+import { useSettingsSearch } from '../context'+import { projectSectionId } from '../project-settings-targets'+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`.+ *+ * 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.+ */+async function persistWorkspace(): Promise<void> {+ await window.nodeTerminal.workspace.save(useProjects.getState().toWorkspace())+}++function rowsFor(name: string): Record<string, SettingsSearchEntry> {+ // The project's own name rides every row's keywords: searching a project by name has to surface+ // its controls, not just the section header.+ return {+ name: { title: 'Project name', keywords: ['rename', 'project', 'title', name] },+ folder: { title: 'Folder', keywords: ['cwd', 'path', 'directory', 'ssh', 'server', name] },+ color: { title: 'Color', keywords: ['accent', 'swatch', 'tab', 'monogram', name] },+ permission: {+ title: 'Default permission mode',+ keywords: ['claude', 'plan', 'accept edits', 'bypass', 'approval', name]+ },+ account: {+ title: 'Default Claude account',+ keywords: ['account', 'login', 'claude', 'system', name]+ }+ }+}++/** Where this project's terminals run: a local folder, or `user@host:/remote/path` for SSH. */+function projectTarget(project: Project): string {+ if (project.ssh) return `${project.ssh.server.user}@${project.ssh.server.host}:${project.ssh.remoteCwd}`+ return project.cwd || 'No folder set'+}++/**+ * One project's settings pane. Dynamic (`project-<id>`): the nav group and this list are both+ * built from the same live project list, so a section always has a row and vice versa.+ *+ * The visibility gate is evaluated HERE as well as inside `SettingsSection`, deliberately: the body+ * reads `.nodeterm/settings.json`, which for an SSH project is a network round-trip, so a pane that+ * is neither active nor matched by the search must not mount the hook at all.+ */+export function ProjectSettingsSection({+ projectId,+ isActive+}: {+ projectId: string+ isActive: boolean+}): React.JSX.Element | null {+ const project = useProjects((s) => s.projects.find((p) => p.id === projectId))+ const query = useSettingsSearch()+ const rows = useMemo(() => rowsFor(project?.name ?? ''), [project?.name])+ const entries = useMemo(() => Object.values(rows), [rows])+ if (!project) return null+ const visible = query.trim() !== '' ? entries.some((e) => matchesQuery(query, e)) : isActive+ if (!visible) return null+ // A relay tab is a live connection to ANOTHER machine's project, and an unavailable project's+ // files cannot be read at all. Both get an explanation and zero editors: `projectSettings.*`+ // here would read and write THIS machine's store, so an editor would silently edit the wrong+ // project (or nothing).+ if (project.remote || project.unavailable) {+ return <ExplanatoryProjectSection project={project} isActive={isActive} entries={entries} />+ }+ return (+ <EditableProjectSection project={project} isActive={isActive} entries={entries} rows={rows} />+ )+}++function ExplanatoryProjectSection({+ project,+ isActive,+ entries+}: {+ project: Project+ isActive: boolean+ entries: SettingsSearchEntry[]+}): React.JSX.Element {+ return (+ <SettingsSection+ id={projectSectionId(project.id)}+ title={project.name}+ isActive={isActive}+ searchEntries={entries}+ >+ <p className="text-[13px] leading-relaxed text-muted">+ {project.remote+ ? `This tab is a live connection to a project on another machine (${projectTarget(project)}). Its settings live there and are edited on that machine — nothing changed here would reach it.`+ : `This project is unavailable: its files could not be read (folder missing, server unreachable, or the file is corrupt). Reconnect or reopen it to change its settings.`}+ </p>+ </SettingsSection>+ )+}++function EditableProjectSection({+ project,+ isActive,+ entries,+ rows+}: {+ project: Project+ isActive: boolean+ entries: SettingsSearchEntry[]+ rows: Record<string, SettingsSearchEntry>+}): React.JSX.Element {+ const settings = useProjectSettings(project.id)+ const claudeAccounts = useSettings((s) => s.settings.claudeAccounts)+ const globalMode = useSettings((s) => s.settings.claudePermissionMode)+ const systemLabelSetting = useSettings((s) => s.settings.systemAccountLabel)+ const systemEmail = useSystemAccount((s) => s.email)+ const systemLabel = systemAccountDisplay(systemLabelSetting, systemEmail)+ const accounts = accountsForProject(claudeAccounts, project)+ const accountsHint = sshAccountsHint(project, accounts)++ // Editors commit on BLUR, never per keystroke: each commit is a disk write.+ const [nameDraft, setNameDraft] = useState(project.name)+ useEffect(() => setNameDraft(project.name), [project.name])++ const snapshot = settings.snapshot+ // A git-conflicted settings.json is left untouched for the user to resolve, so every editor of+ // the SHARED document is disabled while it stands (Task 4's family editors take this as their+ // `disabled`; identity/defaults below live in project.json and are unaffected).+ const conflict = snapshot !== 'loading' && snapshot?.conflict === true++ const commitName = (): void => {+ const next = nameDraft.trim()+ if (!next || next === project.name) {+ setNameDraft(project.name)+ return+ }+ useProjects.getState().renameProject(project.id, next)+ void persistWorkspace()+ }++ return (+ <SettingsSection+ id={projectSectionId(project.id)}+ title={project.name}+ description={`Settings for this project only. Name, color and defaults live in ${project.ssh ? 'the project file on the server' : '.nodeterm/project.json'}, which is shared with anyone who has the repo.`}+ isActive={isActive}+ searchEntries={entries}+ >+ {conflict ? (+ <div+ role="status"+ className="rounded-xl border border-[color:var(--warn)]/40 bg-[color:var(--warn)]/10 px-4 py-3 text-[13px] leading-relaxed text-text"+ >+ This project's <code>.nodeterm/settings.json</code> has unresolved git conflict+ markers. It is left exactly as it is — resolve the conflict in your editor, then reopen+ this pane. Shared settings cannot be edited until then.+ {/* Rendered whether or not any family editor is on screen: the pane must explain why the+ file it is about is being ignored, even before Task 4's editors exist. */}+ </div>+ ) : null}+ <SearchableRow {...rows.name}>+ <FieldRow+ label="Project name"+ description="Shown on the tab and in the project switcher."+ htmlFor={`project-name-${project.id}`}+ control={+ <Input+ id={`project-name-${project.id}`}+ className="w-72"+ value={nameDraft}+ aria-label="Project name"+ onChange={(e) => setNameDraft(e.target.value)}+ onBlur={commitName}+ onKeyDown={(e) => {+ if (e.key === 'Enter') e.currentTarget.blur()+ if (e.key === 'Escape') setNameDraft(project.name)+ }}+ />+ }+ />+ </SearchableRow>+ <SearchableRow {...rows.folder}>+ <FieldRow+ label={project.ssh ? 'Server folder' : 'Folder'}+ description="Where this project's terminals start. Change it from the project tab's menu."+ control={+ <span className="max-w-[26rem] truncate text-[13px] text-muted" title={projectTarget(project)}>+ {projectTarget(project)}+ </span>+ }+ />+ </SearchableRow>+ <SearchableRow {...rows.color}>+ <FieldRow+ label="Color"+ description="Accent for this project's tab and monogram."+ control={+ <div className="flex items-center gap-1.5">+ {NODE_COLORS.map((c) => (+ <button+ key={c}+ type="button"+ data-project-color={c}+ aria-label={`Color ${c}`}+ aria-pressed={project.color === c}+ style={{ background: c }}+ className={cn(+ 'size-5 rounded-full border-0 outline-none transition-transform hover:scale-110',+ project.color === c && 'ring-2 ring-white/80 ring-offset-2 ring-offset-transparent'+ )}+ onClick={() => {+ useProjects.getState().setProjectColor(project.id, c)+ void persistWorkspace()+ }}+ />+ ))}+ </div>+ }+ />+ </SearchableRow>+ <SearchableRow {...rows.permission}>+ <FieldRow+ label="Default permission mode"+ description="Start-up permission mode for new Claude terminal sessions in this project. Saved in the shared project file, so it travels to everyone who clones the repo."+ htmlFor={`project-permission-mode-${project.id}`}+ control={+ <Select+ id={`project-permission-mode-${project.id}`}+ aria-label="Default permission mode"+ value={project.defaultPermissionMode ?? ''}+ onChange={(e) => {+ const v = e.target.value+ useProjects+ .getState()+ .setProjectDefaultPermissionMode(+ project.id,+ v === '' ? undefined : (v as AgentPermissionMode)+ )+ void persistWorkspace()+ }}+ >+ <option value="">Use global ({PERMISSION_MODE_LABELS[globalMode]})</option>+ {ALL_PERMISSION_MODES.map((m) => (+ <option key={m} value={m}>+ {PERMISSION_MODE_LABELS[m]}+ </option>+ ))}+ </Select>+ }+ />+ </SearchableRow>+ <SearchableRow {...rows.account}>+ <FieldRow+ label="Default Claude account"+ description="Account new Claude and chat nodes in this project use."+ note={accountsHint ?? undefined}+ htmlFor={`project-account-${project.id}`}+ control={+ <Select+ id={`project-account-${project.id}`}+ aria-label="Default Claude account"+ value={project.defaultAccountId ?? ''}+ onChange={(e) => {+ const v = e.target.value+ useProjects.getState().setProjectDefaultAccount(project.id, v === '' ? undefined : v)+ void persistWorkspace()+ }}+ >+ <option value="">{systemLabel}</option>+ {accounts.map((a) => (+ <option key={a.id} value={a.id}>+ {a.label}+ </option>+ ))}+ {/* 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. */}+ {project.defaultAccountId && !accounts.some((a) => a.id === project.defaultAccountId) ? (+ <option value={project.defaultAccountId}>+ {project.defaultAccountId} (not on this machine)+ </option>+ ) : null}+ </Select>+ }+ />+ </SearchableRow>+ {/* Task 4 hangs the per-family editors (setup / worktree / agents / terminal) here; they take+ `settings.resolved`, `settings.saveShared`, `settings.saveLocal`, and `conflict` as their+ disabled flag — the hook needs no change to grow them. */}+ </SettingsSection>+ )+}diff --git a/src/renderer/components/settings/useProjectSettings.ts b/src/renderer/components/settings/useProjectSettings.tsnew file mode 100644index 000000000..21b38df70--- /dev/null+++ b/src/renderer/components/settings/useProjectSettings.ts@@ -0,0 +1,137 @@+import { useCallback, useEffect, useMemo, useRef, useState } from 'react'+import {+ resolveProjectSettings,+ type ProjectLocalSettings,+ type ProjectSettingsDoc,+ type ProjectSettingsFileV1,+ type ProjectSettingsSnapshot,+ type ResolvedProjectSettings+} from '@shared/project-settings'++/**+ * One project's `.nodeterm/settings.json` (the git-shared doc) plus this machine's local overlay,+ * as the Settings panel needs them: the raw snapshot for provenance/conflict decisions, the+ * resolved local-over-shared view for showing effective values, and two savers.+ *+ * `snapshot` is `'loading'` until the first read answers, then the snapshot, or `null` when the+ * project is unknown to the store or the read failed. A failed read is never an exception here:+ * the panel must still render its identity rows for a project whose settings file is unreadable.+ */+export interface ProjectSettingsHook {+ snapshot: ProjectSettingsSnapshot | null | 'loading'+ /** `resolveProjectSettings(local, shared)`; empty families while the first read is in flight. */+ resolved: ResolvedProjectSettings+ /**+ * Commits an edit to the GIT-SHARED document. The argument is a PATCH, merged field-by-field+ * into the document that was last read — `writeShared` is a whole-document write (it replaces+ * the file), so an editor that owns one field must not blank its siblings. A field set to+ * `undefined` is removed; a family left with no fields is removed with it, so an unset setting+ * adds no bytes to a file the whole team reads.+ *+ * Returns the store's accept/refuse answer, and re-reads on success: the store bumped `rev` and+ * may have sanitized what it wrote, so what the panel shows afterwards is the FILE, not our hope.+ */+ saveShared(doc: ProjectSettingsDoc): Promise<boolean>+ /** This machine's overlay, written whole (`undefined` clears it). Re-reads on success. */+ saveLocal(local: ProjectLocalSettings | undefined): Promise<boolean>+ reload(): void+}++/** The document half of a shared file — `version`/`rev`/`savedAt` belong to the store, which+ * re-stamps them on every write, so they never travel back through an editor. */+function docOf(shared: ProjectSettingsFileV1 | null | undefined): ProjectSettingsDoc {+ if (!shared) return {}+ const { version: _version, rev: _rev, savedAt: _savedAt, ...doc } = shared+ return doc+}++/**+ * 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.+ */+export function mergeSharedDoc(+ current: ProjectSettingsDoc,+ patch: ProjectSettingsDoc+): ProjectSettingsDoc {+ const out: Record<string, unknown> = { ...current }+ for (const family of Object.keys(patch) as (keyof ProjectSettingsDoc)[]) {+ const patchFamily = patch[family] as Record<string, unknown> | undefined+ if (patchFamily === undefined) {+ delete out[family]+ continue+ }+ const merged: Record<string, unknown> = {+ ...(current[family] as Record<string, unknown> | undefined),+ ...patchFamily+ }+ for (const key of Object.keys(merged)) if (merged[key] === undefined) delete merged[key]+ if (Object.keys(merged).length === 0) delete out[family]+ else out[family] = merged+ }+ return out as ProjectSettingsDoc+}++const EMPTY_FAMILIES = (): ResolvedProjectSettings => resolveProjectSettings(undefined, undefined)++export function useProjectSettings(projectId: string): ProjectSettingsHook {+ const [snapshot, setSnapshot] = useState<ProjectSettingsSnapshot | null | 'loading'>('loading')+ const [nonce, setNonce] = useState(0)++ // The merge base for `saveShared` must be the LATEST snapshot, 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++ useEffect(() => {+ let alive = true+ setSnapshot('loading')+ void window.nodeTerminal.projectSettings.read(projectId).then(+ (s) => {+ if (alive) setSnapshot(s)+ },+ () => {+ if (alive) setSnapshot(null)+ }+ )+ return () => {+ alive = false+ }+ }, [projectId, nonce])++ const reload = useCallback(() => setNonce((n) => n + 1), [])++ const saveShared = useCallback(+ async (doc: ProjectSettingsDoc): Promise<boolean> => {+ const 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+ },+ [projectId, reload]+ )++ const saveLocal = useCallback(+ async (local: ProjectLocalSettings | undefined): Promise<boolean> => {+ const ok = await window.nodeTerminal.projectSettings.updateLocal(projectId, local)+ if (ok) reload()+ return ok+ },+ [projectId, reload]+ )++ const resolved = useMemo(+ () =>+ snapshot && snapshot !== 'loading'+ ? resolveProjectSettings(snapshot.local, docOf(snapshot.shared))+ : EMPTY_FAMILIES(),+ [snapshot]+ )++ return { snapshot, resolved, saveShared, saveLocal, reload }+}