Files
fusion/packages/dashboard/app/components/NodesView.tsx
gsxdsm c15c78feeb feat: migrate storage from SQLite to PostgreSQL (#1793)
# Migrate storage from SQLite to PostgreSQL — full dashboard cutover

Migrates Fusion's storage layer to the embedded PostgreSQL
`AsyncDataLayer` (the default backend) and **completes the
satellite-store + feature cutover** so every dashboard and Command
Center surface works in PG mode.

## Status — every surface works in embedded-PG mode

Verified live against a running embedded-Postgres dashboard (all
**200**, zero 5xx) and gate-tested (**23 files / 99 tests** on embedded
PG, plus engine-core 294 and ci-shape 63 in the blocking merge gate;
core/engine/cli/dashboard typecheck clean).

| Area | Surfaces | State |
|---|---|---|
| Satellite stores | workflows, todos, insights, research, missions,
goals, mailbox | ✅ |
| Views | artifacts, documents, evals | ✅ |
| Command Center | activity, productivity, team, tokens, tools,
**workflows**, **github**, **signals**, **plugin-activations**, **live**
(all 10) | ✅ |
| Run execution | insight generation, research run execution | ✅
(store-path; AI step needs a provider) |
| Live updates | SSE push for mission/research/insight events | ✅ |
| Workflow editing | create / update / delete / select (+ id counter) |
✅ |
| Engine | mission autopilot, incident-signal ingestion, regression
storm-guard, agent wake-on-message | ✅ |
| Core | tasks, agents, secrets, automations, memory, chat, usage, PRs,
git | ✅ |

## Approach

Each satellite store gets an `Async<Store>` wrapper exposing the sync
store's method names over the existing `async-*-store.ts` helpers;
`get<Store>Store()` returns a `Sync | Async` union; consumers `await`
(harmless on sync), and engine/CLI paths that can't convert use
`instanceof Sync` graceful fallback. Analytics aggregators branch on
`"ping" in dbOrLayer` to run schema-qualified raw SQL over `project.*`
(snake_case) in PG. Executors/orchestrators/autopilot are
await-converted to drive the union store; the async store wrappers
extend `EventEmitter` so SSE live-push fires in both backends.

Not-yet-ported capabilities degrade gracefully (never 500) and are
individually called out in commits.

## Sync with main

The branch is kept continuously merged with `main` (currently through
FN-7845, 2026-07-12); the earlier "final rebase deferred" note no longer
applies. Use **Create a merge commit** (or squash) to land it — GitHub's
rebase-merge cannot replay a merge-maintained branch.

## Residual Review Findings

Multi-agent code review of the PostgreSQL satellite-store ports (U1–U5)
applied 3 safe fixes (see `fix(review): apply autofix feedback`). The
following are **real but gated** — recorded here as follow-up work
rather than auto-applied. All are SQLite→PostgreSQL
**concurrency/atomicity regressions**: the sync stores were immune only
by SQLite's single-writer, single-threaded-handler execution; the async
ports open multi-await read-modify-write windows. **Reachability is low
today** because the execution engines that generate concurrent same-run
mutations (insight run executor, research orchestrator/dispatcher) are
`instanceof`-gated to sync mode in PG. No process-crash class survived
(all engine fallbacks correctly guard the sync store).

- **[P1] Research `appendResearchEvent` dual-write is non-atomic**
(`packages/core/src/async-research-store.ts`, corroborated: adversarial
+ reliability). The `research_run_events` insert (own transaction) and
the `run.events` jsonb update are separate writes — a crash between
them, or two concurrent appends, splits the table count from the jsonb
array. **Fix:** perform the seq-insert and the jsonb update in one
`layer.transactionImmediate`.
- **[P1] Research run terminal-reversion via stale full-row persist**
(`async-research-store.ts` `persistResearchRun`/`updateResearchStatus`).
Concurrent `PATCH /runs/:id/status` + `POST /runs/:id/events` can revert
a terminal run to `running` by overwriting the whole row, bypassing the
transition guard. **Fix:** scoped column `UPDATE`s with a `WHERE status
…` guard, or optimistic version column.
- **[P2] `updateResearchRun`/`updateInsightRun` read-then-write TOCTOU**
— concurrent PATCHes last-writer-wins on the lifecycle merge. **Fix:**
`SELECT … FOR UPDATE` / enclosing transaction.
- **[P2] `upsertRun`/`createRunOrThrowConflict` check-then-create race**
(`async-insight-store.ts`) — two callers can each create an "active"
run. **Fix:** partial unique index on `(projectId, trigger) WHERE status
IN ('pending','running')`.
- **[P3] `createResearchRetryRun` return-value divergence** — sync
returns the pre-update `queued` snapshot; async returns the reloaded
`retry_waiting` run (persisted state is identical). Pick one side for
cross-backend parity.
- **[P2/perf] Mission `getMissionWithHierarchy`/`getMissionHealth` N+1
fan-out** — O(milestones×slices) sequential round-trips hold one pool
slot per request; can starve the pool for large hierarchies. **Fix:**
batched/joined reads.
- **Testing gaps:** no PG-mode concurrency tests (interleaved
status/event mutations), no sync↔async parity assertion for the
lifecycle-error codes, and no mission status/health rollup parity test
vs the sync `MissionStore`.

~~Out of scope (deferred): AI run *execution* (insight/research) +
mission autopilot + live SSE mission events remain sync-gated/degraded
in PG mode.~~ **Since ported** — insight/research run execution, mission
autopilot, and SSE live push all run on the async layer now, which also
makes the concurrency findings above genuinely reachable; they remain
open follow-ups.







---

## Update — 2026-07-12: production-readiness hardening & live acceptance

Everything below landed on this branch since the description above was
written:

**Production blockers from review — fixed**
- `recoverStaleTransitionPending` ported to the async layer (backend
moves write + clear the crash-safe marker; startup/maintenance sweeps no
longer throw).
- Lost-update class fixed: `atomicWriteTaskJson`/`WithAudit` write
changed columns only (full-row upserts silently resurrected stale fields
across concurrent store instances — the "task stuck unplanned forever"
bug).
- First-boot **auto-migration**: booting the PG backend over a project
with a legacy `fusion.db` migrates it automatically (loud failure,
SQLite kept as backup), and the dashboard shows a one-time **"your data
was migrated" banner** with the backup paths and a Need-help Discord
link.
- `pg_dump`/`pg_restore` discovered from common install locations for
embedded-mode backups.
- The PG suite is part of the blocking merge gate (`test:pg-gate`).

**Multi-project isolation (PR #2007, merged into this branch)**
- `project_id` partition key on tasks / archived tasks / config,
`taskProjectScope` threaded through every scan/claim/count, per-project
config rows, layer bound to the project at startup.
- Review P1 follow-up: the shared cold-storage `archive.archived_tasks`
table is also partitioned and all archived-board reads/counts/searches
are scoped.
- Schema drift self-heal generalized to schema-qualified columns so
existing databases upgrade in place.

**Other changes**
- Node settings sync **removed** in PG mode (409
`settings-sync-disabled-postgres`) — nodes share state by connecting to
the same database; auth sync kept (per-machine file).
- Perf (review findings): `listTasks` pushes column filter + ORDER BY +
LIMIT/OFFSET into SQL; `getConversation` capped to the most recent 200
messages.
- Fixed a false "operator action required" pause-abort log fired on
every successfully auto-merged task.

**Live acceptance — PASSED (2026-07-12)**
A sandboxed instance (isolated HOME, embedded PG, real Opus executor)
ran a task through the complete cycle: create → triage (AI spec) →
execute → in-review → AI squash-merge landed on the project's `main` →
done. A write+read sweep of every data surface (settings, comments,
documents, attachments + artifact bridge + artifact edit, chat with real
generation, goals, missions, agent mail, secrets, workflows, memory, CC
analytics) was green on embedded PG.

**Known remaining work**
- The per-project `config` PK re-key has no upgrade path for
pre-isolation embedded-PG databases (needs a real `DROP
CONSTRAINT`/re-key migration; fresh databases are fine).
- `pg_dump`/`pg_restore` binaries are not yet bundled in release
artifacts (PATH/common-location discovery only).
- The satellite-store concurrency findings listed above.

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Co-authored-by: Phil Larson <hello@phillarson.xyz>
Co-authored-by: fusion-merge <fusion-merge@local>
2026-07-13 19:07:58 -07:00

306 lines
12 KiB
TypeScript

import { useCallback, useEffect, useMemo, useState } from "react";
import { useTranslation } from "react-i18next";
import { Box, Plus, Server, Wifi, WifiOff, Globe, RefreshCw, X } from "lucide-react";
import "./NodesView.css";
import { useNodes } from "../hooks/useNodes";
import { useProjects } from "../hooks/useProjects";
import { useNodeSettingsSync, computeSyncState } from "../hooks/useNodeSettingsSync";
import { useMeshState } from "../hooks/useMeshState";
import { useMeshEngines } from "../hooks/useMeshEngines";
import type { ManagedDockerNodeInfo, NodeInfo, NodeUpdateInput } from "../api";
import { NodeCard } from "./NodeCard";
import { MeshTopology } from "./MeshTopology";
import { AddNodeModal, type AddNodeInput } from "./AddNodeModal";
import { DockerNodeOnboardingModal } from "./DockerNodeOnboardingModal";
import { NodeDetailModal } from "./NodeDetailModal";
import { useManagedDockerNodes } from "../hooks/useManagedDockerNodes";
import type { ManagedDockerNodeInput } from "@fusion/core";
import type { ToastType } from "../hooks/useToast";
interface NodesViewProps {
addToast: (message: string, type?: ToastType) => void;
onClose?: () => void;
}
/*
FNXC:Nodes 2026-06-19-00:00:
FN-6717 mounts Nodes inside Command Center while preserving the legacy overlay caller during migration/testing. The close affordance is overlay-only, so tab mode omits it when no onClose handler is provided.
*/
export function NodesView({ addToast, onClose }: NodesViewProps) {
const { t } = useTranslation("app");
const {
nodes,
loading,
error,
refresh,
register,
update,
unregister,
healthCheck,
patchDockerConfig,
fetchDockerDiff,
discoverRemoteProjects,
} = useNodes();
const { projects, refresh: refreshProjects } = useProjects();
const { meshState, loading: meshLoading, error: meshError } = useMeshState();
const { engines, loading: enginesLoading, error: enginesError } = useMeshEngines();
const { syncStatusMap, pushSettings, pullSettings, syncAuth, trackNode, getAuthSyncState, getAuthProviders } = useNodeSettingsSync();
const {
dockerNodes,
loading: dockerLoading,
refresh: refreshDocker,
getContainerStatus,
getLogs,
create: createDockerNode,
} = useManagedDockerNodes();
const [addModalOpen, setAddModalOpen] = useState(false);
const [dockerOnboardingOpen, setDockerOnboardingOpen] = useState(false);
const [selectedNode, setSelectedNode] = useState<NodeInfo | null>(null);
// Track remote nodes for sync status polling
useEffect(() => {
const remoteNodes = nodes.filter((node) => node.type === "remote");
for (const node of remoteNodes) {
trackNode(node.id);
}
}, [nodes, trackNode]);
useEffect(() => {
if (!selectedNode) return;
const latest = nodes.find((node) => node.id === selectedNode.id) ?? null;
setSelectedNode(latest);
}, [nodes, selectedNode]);
const stats = useMemo(() => {
const total = nodes.length;
const online = nodes.filter((node) => node.status === "online").length;
const offline = nodes.filter((node) => node.status === "offline" || node.status === "error").length;
const remote = nodes.filter((node) => node.type === "remote").length;
const synced = nodes.filter(
(node) => node.type === "remote" && syncStatusMap[node.id] && computeSyncState(syncStatusMap[node.id]).syncState === "synced"
).length;
const docker = dockerNodes.length;
return { total, online, offline, remote, synced, docker };
}, [dockerNodes.length, nodes, syncStatusMap]);
const handleRegister = useCallback(async (input: AddNodeInput) => {
await register(input);
await refreshProjects();
}, [refreshProjects, register]);
const handleCreateDockerNode = useCallback(async (input: ManagedDockerNodeInput) => {
try {
await createDockerNode(input);
addToast(t("nodes.dockerNodeCreated", `Docker node "{{name}}" created`, { name: input.name }), "success");
setDockerOnboardingOpen(false);
} catch (err) {
const message = err instanceof Error ? err.message : t("nodes.failedCreateDocker", "Failed to create Docker node");
addToast(message, "error");
throw err;
}
}, [addToast, createDockerNode, t]);
const dockerNodeMap = useMemo(() => {
const map = new Map<string, ManagedDockerNodeInfo>();
for (const dockerNode of dockerNodes) {
if (dockerNode.nodeId) {
map.set(dockerNode.nodeId, dockerNode);
}
}
return map;
}, [dockerNodes]);
const handleRefresh = useCallback(async () => {
try {
await Promise.all([refresh(), refreshDocker()]);
} catch {
addToast(t("nodes.failedRefresh", "Failed to refresh nodes"), "error");
}
}, [addToast, refresh, refreshDocker, t]);
const handleHealthCheck = useCallback(async (id: string) => {
try {
await healthCheck(id);
addToast(t("nodes.healthCheckComplete", "Node health check complete"), "success");
} catch (err) {
const message = err instanceof Error ? err.message : t("nodes.healthCheckFailed", "Health check failed");
addToast(message, "error");
}
}, [addToast, healthCheck, t]);
const handleUnregister = useCallback(async (id: string) => {
try {
await unregister(id);
addToast(t("nodes.removed", "Node removed"), "success");
if (selectedNode?.id === id) {
setSelectedNode(null);
}
} catch (err) {
const message = err instanceof Error ? err.message : t("nodes.failedRemove", "Failed to remove node");
addToast(message, "error");
}
}, [addToast, selectedNode?.id, unregister, t]);
const handleUpdate = useCallback(async (id: string, updates: NodeUpdateInput) => {
await update(id, updates);
}, [update]);
return (
<div className="nodes-view" data-testid="nodes-view">
<div className="nodes-view-header">
<div className="nodes-view-title">
<h2>
<Server size={20} />
{t("nodes.heading", "Nodes")}
</h2>
<span className="nodes-view-count">{t("nodes.registeredCount", "{{count}} registered", { count: nodes.length })}</span>
</div>
<div className="nodes-view-actions">
{onClose ? (
<button
className="btn-icon nodes-view-close"
onClick={onClose}
aria-label={t("nodes.closeAriaLabel", "Close nodes view")}
>
<X size={16} />
</button>
) : null}
<button className="btn btn-sm" onClick={() => void handleRefresh()} disabled={loading || dockerLoading}>
<RefreshCw size={14} className={loading ? "spin" : ""} />
{t("nodes.refresh", "Refresh")}
</button>
<button className="btn btn-sm" onClick={() => setAddModalOpen(true)}>
<Plus size={14} />
{t("nodes.addNode", "Add Node")}
</button>
<button className="btn btn-sm" onClick={() => setDockerOnboardingOpen(true)} title={t("nodes.addDockerNodeTitle", "Add a managed Docker node")}>
<Box size={14} />
{t("nodes.addDockerNode", "Add Docker Node")}
</button>
</div>
</div>
<div className="nodes-view-stats">
<div className="nodes-view-stat" data-testid="nodes-stat-total">
<span>{t("nodes.total", "Total")}</span>
<strong>{stats.total}</strong>
</div>
<div className="nodes-view-stat nodes-view-stat--online" data-testid="nodes-stat-online">
<span><Wifi size={14} /> {t("nodes.online", "Online")}</span>
<strong>{stats.online}</strong>
</div>
<div className="nodes-view-stat nodes-view-stat--offline" data-testid="nodes-stat-offline">
<span><WifiOff size={14} /> {t("nodes.offline", "Offline")}</span>
<strong>{stats.offline}</strong>
</div>
<div className="nodes-view-stat" data-testid="nodes-stat-remote">
<span><Globe size={14} /> {t("nodes.remote", "Remote")}</span>
<strong>{stats.remote}</strong>
</div>
<div className="nodes-view-stat nodes-view-stat--synced" data-testid="nodes-stat-synced">
<span><RefreshCw size={14} /> {t("nodes.synced", "Synced")}</span>
<strong>{stats.synced}</strong>
</div>
<div className="nodes-view-stat" data-testid="nodes-stat-docker">
<span><Box size={14} /> {t("nodes.docker", "Docker")}</span>
<strong>{stats.docker}</strong>
</div>
</div>
{(error || meshError || enginesError) && <div className="nodes-view-error">{error ?? meshError ?? enginesError}</div>}
{/* Mesh Topology Visualization */}
{!meshLoading && meshState.length > 0 && (
<section className="nodes-view-topology" aria-label={t("nodes.meshTopologyAriaLabel", "Mesh Topology")}>
<h3 className="nodes-view-section-title">{t("nodes.meshTopology", "Mesh Topology")}</h3>
{/*
FNXC:MeshSharedPg 2026-06-25-00:00:
Pass active engine connections (read from shared PG via
GET /api/mesh/engines) into MeshTopology so the view renders both the
peer graph and the live engine runtime status. enginesLoading is
tolerated: stale engine data is preferable to dropping the topology.
*/}
<MeshTopology nodes={meshState} engines={!enginesLoading ? engines : undefined} />
</section>
)}
{loading ? (
<div className="nodes-view-grid">
{Array.from({ length: 4 }).map((_, index) => (
<div key={index} className="node-card node-card--loading" aria-hidden />
))}
</div>
) : nodes.length === 0 ? (
<div className="nodes-view-empty">
<p>{t("nodes.noRegistered", "No nodes are registered yet.")}</p>
<button className="btn btn-primary" onClick={() => setAddModalOpen(true)}>
<Plus size={14} />
{t("nodes.addFirstNode", "Add First Node")}
</button>
</div>
) : (
<div className="nodes-view-grid">
{nodes.map((node) => {
const nodeSyncStatus = node.type === "remote" && syncStatusMap[node.id]
? computeSyncState(syncStatusMap[node.id])
: undefined;
return (
<NodeCard
key={node.id}
node={node}
projects={projects}
onHealthCheck={(id) => { void handleHealthCheck(id); }}
onEdit={(selected) => setSelectedNode(selected)}
onRemove={(id) => { void handleUnregister(id); }}
isLoading={loading}
syncStatus={nodeSyncStatus}
authSyncState={node.type === "remote" ? getAuthSyncState(node.id) : undefined}
authSyncProviders={node.type === "remote" ? getAuthProviders(node.id) : undefined}
managedDockerNode={dockerNodeMap.get(node.id)}
/>
);
})}
</div>
)}
<AddNodeModal
isOpen={addModalOpen}
onClose={() => setAddModalOpen(false)}
onSubmit={handleRegister}
onDiscoverRemoteProjects={discoverRemoteProjects}
addToast={addToast}
projects={projects}
/>
<DockerNodeOnboardingModal
isOpen={dockerOnboardingOpen}
onClose={() => setDockerOnboardingOpen(false)}
onSubmit={handleCreateDockerNode}
addToast={addToast}
/>
<NodeDetailModal
isOpen={selectedNode !== null}
onClose={() => setSelectedNode(null)}
node={selectedNode}
projects={projects}
onUpdate={handleUpdate}
onHealthCheck={handleHealthCheck}
addToast={addToast}
syncStatus={selectedNode?.type === "remote" && selectedNode && syncStatusMap[selectedNode.id]
? computeSyncState(syncStatusMap[selectedNode.id])
: undefined}
onPushSettings={pushSettings}
onPullSettings={pullSettings}
onSyncAuth={syncAuth}
managedDockerNode={selectedNode ? dockerNodeMap.get(selectedNode.id) : undefined}
onFetchContainerStatus={getContainerStatus}
onFetchLogs={getLogs}
onUpdateDockerConfig={patchDockerConfig}
onFetchDockerConfigDiff={fetchDockerDiff}
/>
</div>
);
}