Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

fix([codex5-dashboard-intent-layouts]): server-side write tail for dashboard-layouts.json (codex iter-2)

[._.]/ Adam Eivye9dd4a6dbc90
diff --git a/client/src/pages/Dashboard.jsx b/client/src/pages/Dashboard.jsx
index a9237ee3ed..828f17e00b 100644
--- a/client/src/pages/Dashboard.jsx
+++ b/client/src/pages/Dashboard.jsx
@@ -56,20 +56,10 @@ export default function Dashboard() {
}, [fetchData]);
// One-shot per mount — guards against re-evaluation stomping manual picks.
+ // Serialization across concurrent writers (auto-window + manual pick +
+ // palette pick) lives server-side in dashboardLayouts.js's `layoutsWriteTail`;
+ // no client-side queue needed.
const autoSwitchedRef = useRef(false);
- // Serializes activeLayoutId writes so an auto-window PUT can't land at the
- // server after a manual pick that the user fired during the auto's flight
- // (would make the server contradict the user's intent). Matches the server-
- // side serialization convention in CLAUDE.md ("Async PATCH races on shared
- // records — serialize writes").
- const activeLayoutWriteTailRef = useRef(Promise.resolve());
- const queueActiveLayoutWrite = useCallback((id) => {
- const tail = activeLayoutWriteTailRef.current.then(() => api.setActiveDashboardLayout(id));
- // Tail must survive failures so subsequent writes still chain — but the
- // returned promise to callers keeps the rejection so they can revert.
- activeLayoutWriteTailRef.current = tail.catch(() => null);
- return tail;
- }, []);
useEffect(() => {
// `cancelled` guard prevents setState-on-unmounted warnings (and
@@ -86,11 +76,11 @@ export default function Dashboard() {
if (desiredActiveId === data.activeLayoutId) {
autoSwitchedRef.current = true;
} else {
- // Routed through the write queue so a manual pick fired during
- // this PUT's flight queues after it — the user's intent always
- // wins at the server. Mark "auto-switched" only after the PUT
- // settles so a failing server gets retried on the next mount.
- queueActiveLayoutWrite(desiredActiveId)
+ // Server's layoutsWriteTail serializes against concurrent manual
+ // picks, so this fire-and-forget can't clobber a later click. Only
+ // mark "auto-switched" after the PUT settles so a failing server
+ // gets retried on the next mount.
+ api.setActiveDashboardLayout(desiredActiveId)
.then(() => { if (!cancelled) autoSwitchedRef.current = true; })
.catch(() => {
if (cancelled) return;
@@ -206,10 +196,10 @@ export default function Dashboard() {
const previousId = activeLayoutId;
setActiveLayoutId(id);
recordManualLayoutPick(id);
- // Queued so an in-flight auto-window PUT can't land after this — the
- // user's manual pick always reaches the server last. Revert on failure
- // via functional setState so a later selection isn't clobbered.
- await queueActiveLayoutWrite(id).catch(() => {
+ // Server-side write tail serializes against any in-flight auto-window
+ // PUT so this write always lands after it. Revert via functional
+ // setState so a later selection isn't clobbered.
+ await api.setActiveDashboardLayout(id).catch(() => {
setActiveLayoutId((current) => (current === id ? previousId : current));
});
};
@@ -240,9 +230,9 @@ export default function Dashboard() {
// Lock in for the day so a window-driven auto-switch on the next mount
// doesn't bump the user off the brand-new layout they just created.
recordManualLayoutPick(id);
- // Queued so any in-flight auto-window PUT can't land after this.
- // Revert via functional setState so a later selection isn't clobbered.
- await queueActiveLayoutWrite(id).catch(() => {
+ // Server-side write tail serializes against any in-flight auto-window
+ // PUT. Revert via functional setState so a later selection isn't clobbered.
+ await api.setActiveDashboardLayout(id).catch(() => {
setActiveLayoutId((current) => (current === id ? previousId : current));
});
};
diff --git a/server/services/dashboardLayouts.js b/server/services/dashboardLayouts.js
index b294f112ca..4aa65ecf3a 100644
--- a/server/services/dashboardLayouts.js
+++ b/server/services/dashboardLayouts.js
@@ -304,66 +304,85 @@ export async function getState() {
return { activeLayoutId, layouts, limits: LIMITS };
}
-export async function setActiveLayout(id) {
- const state = await getState();
- if (!state.layouts.find((l) => l.id === id)) {
- throw makeErr(`Unknown layout id: ${id}`, ERR_NOT_FOUND);
- }
- const next = { activeLayoutId: id, layouts: state.layouts };
- await atomicWrite(STATE_PATH, next);
- return { ...next, limits: LIMITS };
+// All mutations to dashboard-layouts.json funnel through this tail so two
+// concurrent writers (e.g. an auto-window-activate PUT + a manual layout
+// save firing from the same browser, or palette + dashboard tabs) can't
+// interleave load → modify → write and lose each other's changes. Mirrors
+// the `issueWriteTail` / `cacheWriteTails` pattern documented in CLAUDE.md
+// ("Async PATCH races on shared records — serialize writes server-side").
+let layoutsWriteTail = Promise.resolve();
+const queueLayoutsWrite = (fn) => {
+ const tail = layoutsWriteTail.then(fn, fn); // run even after a prior failure
+ layoutsWriteTail = tail.then(() => null, () => null); // tail keeps chaining
+ return tail;
+};
+
+export function setActiveLayout(id) {
+ return queueLayoutsWrite(async () => {
+ const state = await getState();
+ if (!state.layouts.find((l) => l.id === id)) {
+ throw makeErr(`Unknown layout id: ${id}`, ERR_NOT_FOUND);
+ }
+ const next = { activeLayoutId: id, layouts: state.layouts };
+ await atomicWrite(STATE_PATH, next);
+ return { ...next, limits: LIMITS };
+ });
}
-export async function saveLayout(layout) {
- const state = await getState();
- const idx = state.layouts.findIndex((l) => l.id === layout.id);
- // Derive `builtIn` from BUILTIN_IDS at write-time (not from the persisted
- // flag) so a hand-edited JSON that deleted the default `ops` entry can't
- // produce a new `ops` that sanitizeLayout() later treats as built-in while
- // the write-path echoed `builtIn: false` to the client.
- const builtIn = BUILTIN_IDS.has(layout.id);
- // Partial-aware merge: `activateWindow` is preserved when the caller
- // doesn't include the key, but cleared when the caller sends `null`. The
- // existing editor's saveLayout() doesn't send activateWindow, so a vanilla
- // widget edit must NOT wipe a previously-configured morning window.
- // Mirrors the "absent vs intentionally empty" convention in CLAUDE.md.
- const existing = idx >= 0 ? state.layouts[idx] : null;
- const buildEntry = () => {
- const entry = {
- id: layout.id,
- name: layout.name,
- builtIn,
- widgets: layout.widgets,
- grid: layout.grid ?? [],
+export function saveLayout(layout) {
+ return queueLayoutsWrite(async () => {
+ const state = await getState();
+ const idx = state.layouts.findIndex((l) => l.id === layout.id);
+ // Derive `builtIn` from BUILTIN_IDS at write-time (not from the persisted
+ // flag) so a hand-edited JSON that deleted the default `ops` entry can't
+ // produce a new `ops` that sanitizeLayout() later treats as built-in while
+ // the write-path echoed `builtIn: false` to the client.
+ const builtIn = BUILTIN_IDS.has(layout.id);
+ // Partial-aware merge: `activateWindow` is preserved when the caller
+ // doesn't include the key, but cleared when the caller sends `null`. The
+ // existing editor's saveLayout() doesn't send activateWindow, so a vanilla
+ // widget edit must NOT wipe a previously-configured morning window.
+ // Mirrors the "absent vs intentionally empty" convention in CLAUDE.md.
+ const existing = idx >= 0 ? state.layouts[idx] : null;
+ const buildEntry = () => {
+ const entry = {
+ id: layout.id,
+ name: layout.name,
+ builtIn,
+ widgets: layout.widgets,
+ grid: layout.grid ?? [],
+ };
+ // `undefined` (key absent OR set undefined) means "preserve"; `null` is
+ // the explicit clear. Spread alone would clobber existing.activateWindow
+ // with undefined when the caller omits the key.
+ entry.activateWindow = layout.activateWindow !== undefined
+ ? layout.activateWindow
+ : (existing?.activateWindow ?? null);
+ return entry;
};
- // `undefined` (key absent OR set undefined) means "preserve"; `null` is
- // the explicit clear. Spread alone would clobber existing.activateWindow
- // with undefined when the caller omits the key.
- entry.activateWindow = layout.activateWindow !== undefined
- ? layout.activateWindow
- : (existing?.activateWindow ?? null);
- return entry;
- };
- const merged = idx >= 0
- ? state.layouts.map((l, i) => i === idx ? buildEntry() : l)
- : [...state.layouts, buildEntry()];
- const next = { activeLayoutId: state.activeLayoutId, layouts: merged };
- await atomicWrite(STATE_PATH, next);
- return { ...next, limits: LIMITS };
+ const merged = idx >= 0
+ ? state.layouts.map((l, i) => i === idx ? buildEntry() : l)
+ : [...state.layouts, buildEntry()];
+ const next = { activeLayoutId: state.activeLayoutId, layouts: merged };
+ await atomicWrite(STATE_PATH, next);
+ return { ...next, limits: LIMITS };
+ });
}
-export async function deleteLayout(id) {
- const state = await getState();
- const target = state.layouts.find((l) => l.id === id);
- if (!target) throw makeErr(`Unknown layout id: ${id}`, ERR_NOT_FOUND);
- if (target.builtIn) throw makeErr(`Cannot delete built-in layout: ${id}`, ERR_BUILTIN_PROTECTED);
- const remaining = state.layouts.filter((l) => l.id !== id);
- // Guard against the pathological case where the JSON was hand-edited to
- // remove every built-in — fall back to reseeding defaults rather than
- // indexing into an empty array.
- const nextLayouts = remaining.length > 0 ? remaining : DEFAULT_LAYOUTS;
- const activeLayoutId = state.activeLayoutId === id ? nextLayouts[0].id : state.activeLayoutId;
- const next = { activeLayoutId, layouts: nextLayouts };
- await atomicWrite(STATE_PATH, next);
- return { ...next, limits: LIMITS };
+export function deleteLayout(id) {
+ return queueLayoutsWrite(async () => {
+ const state = await getState();
+ const target = state.layouts.find((l) => l.id === id);
+ if (!target) throw makeErr(`Unknown layout id: ${id}`, ERR_NOT_FOUND);
+ if (target.builtIn) throw makeErr(`Cannot delete built-in layout: ${id}`, ERR_BUILTIN_PROTECTED);
+ const remaining = state.layouts.filter((l) => l.id !== id);
+ // Guard against the pathological case where the JSON was hand-edited to
+ // remove every built-in — fall back to reseeding defaults rather than
+ // indexing into an empty array.
+ const nextLayouts = remaining.length > 0 ? remaining : DEFAULT_LAYOUTS;
+ const activeLayoutId = state.activeLayoutId === id ? nextLayouts[0].id : state.activeLayoutId;
+ const next = { activeLayoutId, layouts: nextLayouts };
+ await atomicWrite(STATE_PATH, next);
+ return { ...next, limits: LIMITS };
+ });
}
diff --git a/server/services/dashboardLayouts.test.js b/server/services/dashboardLayouts.test.js
index ddd3d8b1d6..be26f9cc9f 100644
--- a/server/services/dashboardLayouts.test.js
+++ b/server/services/dashboardLayouts.test.js
@@ -110,6 +110,53 @@ describe('dashboardLayouts service', () => {
});
});
+ describe('write-tail serialization', () => {
+ const stateFile = () => STATE_FILE;
+
+ it('serializes concurrent setActiveLayout + saveLayout — both writes survive, no lost-update', async () => {
+ writeJson(stateFile(), {
+ activeLayoutId: 'default',
+ layouts: [
+ { id: 'default', name: 'Everything', builtIn: true, widgets: ['cos'], grid: [] },
+ { id: 'morning', name: 'Morning', builtIn: false, widgets: ['cos'], grid: [] },
+ ],
+ });
+ // Fire concurrently. Without serialization the second call's getState
+ // would read the file before the first call's atomicWrite, and the
+ // second call's atomicWrite would clobber the first.
+ const [resA, resB] = await Promise.all([
+ svc.setActiveLayout('morning'),
+ svc.saveLayout({ id: 'morning', name: 'Morning v2', widgets: ['cos', 'goal-progress'], grid: [] }),
+ ]);
+ // Last-queued result wins at the server.
+ const final = await svc.getState();
+ const m = final.layouts.find((l) => l.id === 'morning');
+ expect(m.name).toBe('Morning v2');
+ expect(m.widgets).toEqual(['cos', 'goal-progress']);
+ // Both writes' return shapes must be coherent (each saw committed state
+ // from its predecessor — second call's response reflects active='morning'
+ // because setActiveLayout committed first).
+ expect(resA.activeLayoutId).toBe('morning');
+ expect(resB.activeLayoutId).toBe('morning');
+ });
+
+ it('a failed write doesn\'t break the chain — subsequent writes still complete', async () => {
+ writeJson(stateFile(), {
+ activeLayoutId: 'default',
+ layouts: [{ id: 'default', name: 'Everything', builtIn: true, widgets: ['cos'], grid: [] }],
+ });
+ const [bad, good] = await Promise.allSettled([
+ svc.setActiveLayout('nonexistent'),
+ svc.saveLayout({ id: 'default', name: 'Everything v2', widgets: ['cos'], grid: [] }),
+ ]);
+ expect(bad.status).toBe('rejected');
+ expect(bad.reason?.code).toBe('NOT_FOUND');
+ expect(good.status).toBe('fulfilled');
+ const after = await svc.getState();
+ expect(after.layouts.find((l) => l.id === 'default').name).toBe('Everything v2');
+ });
+ });
+
describe('built-in layouts ship with the three new intent variants', () => {
it('seeds deep-work, health, agent-watch on first read', async () => {
const state = await svc.getState();