Skip to content

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.

10.0 KB
Raw Blame
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import {
  resolveProjectSettings,
  type ProjectLocalSettings,
  type ProjectSettingsDoc,
  type ProjectSettingsFileV1,
  type ProjectSettingsSnapshot,
  type ResolvedProjectSettings
} from '@shared/project-settings'
import { ensureProjectLaunchInfo, invalidateProjectLaunchInfo } from '../../state/projectLaunchInfo'

/**
 * 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>
  /**
   * Commits an edit to THIS MACHINE's local overlay — a whole-document write, exactly like
   * `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: (current: ProjectLocalSettings | undefined) => 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. 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,
  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)
  /** 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 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)
  // Same hazard, same fix, for the LOCAL overlay: `saveLocal` is also a whole-document write, so
  // two local edits in one round-trip need their own pending base independent of the shared one.
  const pendingLocalRef = useRef<{ projectId: string; local: ProjectLocalSettings | undefined } | null>(
    null
  )

  useEffect(() => {
    let alive = true
    setSnapshot('loading')
    // 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
        pendingLocalRef.current = null
      }
      setSnapshot(next)
    }
    void window.nodeTerminal.projectSettings.read(projectId).then(settle, () => settle(null))
    return () => {
      alive = false
    }
  }, [projectId, nonce])

  const reload = useCallback(() => setNonce((n) => n + 1), [])

  const saveShared = useCallback(
    async (doc: ProjectSettingsDoc): Promise<boolean> => {
      const pending = pendingRef.current?.projectId === projectId ? pendingRef.current : null
      const snap = snapshotRef.current
      // 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
      // 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()
      // A shared write can change what a launch needs to know (a new/edited launchCmd, a new
      // trust-relevant shell) — drop the stale launch-info snapshot and re-warm it, same pair
      // `onTrustChanged` runs on Canvas.
      invalidateProjectLaunchInfo(projectId)
      void ensureProjectLaunchInfo(projectId)
      return true
    },
    [projectId, reload]
  )

  const saveLocal = useCallback(
    async (
      update: (current: ProjectLocalSettings | undefined) => ProjectLocalSettings | undefined
    ): Promise<boolean> => {
      const pending =
        pendingLocalRef.current?.projectId === projectId ? pendingLocalRef.current : null
      const snap = snapshotRef.current
      // 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.
      writeSeqRef.current += 1
      pendingLocalRef.current = { projectId, local: next }
      reload()
      // A local overlay change can flip which value (local vs shared) a launch would consume —
      // same re-warm as `saveShared`.
      invalidateProjectLaunchInfo(projectId)
      void ensureProjectLaunchInfo(projectId)
      return true
    },
    [projectId, reload]
  )

  const resolved = useMemo(
    () =>
      snapshot && snapshot !== 'loading'
        ? resolveProjectSettings(snapshot.local, docOf(snapshot.shared))
        : EMPTY_FAMILIES(),
    [snapshot]
  )

  return { snapshot, resolved, saveShared, saveLocal, reload }
}