fix(home): close /api/dispatch race by eagerly projecting freshly-appended events

Two concurrent /api/dispatch requests could both pass decide()'s
'currentRun is falsy' gate because state.applyEvent only runs when
fs.watch fires — which can lag the synchronous appendEvent by tens
of ms. Result: two bridge.dispatch events for the same project, both
inject into the same zellij tab, agent gets bombarded with two prompts.

Made appendEvent return the stamped Event (was void). The /api/dispatch
and /api/cancel handlers now eagerly apply the returned event to state
immediately after the write, before res.end. A second request arriving
between the file write and fs.watch's callback now reads post-state and
decide() returns 'wait' for the same-project case. tailLog will re-apply
the same event when fs.watch eventually fires — idempotent for the two
event kinds emitted by these handlers (bridge.dispatch just overwrites
currentRun; bridge.cancel's cancelledRunIds filter dedupes).

All other appendEvent callers ignore the return value, so void→Event is
non-breaking. 76 home/ tests still green, tsc clean.
This commit is contained in:
g-but committed 2026-05-20 07:07:18 +02:00
1 parent 6bdc08a2f6
commit bd143e2588
2 files changed
+22 -3

No files matched your search

+7 -1
View File
@@ -31,7 +31,7 @@ export const LOG_PATH = path.join(os.homedir(), `.${APP_SLUG}`, "events.jsonl");
type DistributiveOmit<T, K extends PropertyKey> = T extends unknown ? Omit<T, K> : never;
type EventPayload = DistributiveOmit<Event, "id" | "ts" | "v">;
export function appendEvent(payload: EventPayload, logPath: string = LOG_PATH): void {
export function appendEvent(payload: EventPayload, logPath: string = LOG_PATH): Event {
fs.mkdirSync(path.dirname(logPath), { recursive: true });
const event = {
v: EVENT_VERSION,
@@ -40,6 +40,12 @@ export function appendEvent(payload: EventPayload, logPath: string = LOG_PATH):
...payload,
} as Event;
fs.appendFileSync(logPath, serializeEvent(event));
// Return the stamped event so callers can eagerly project it into their
// own state without waiting for tailLog to consume the write. Closes a
// race in server.ts's /api/dispatch where back-to-back concurrent
// requests both read pre-dispatch state because fs.watch hadn't fired
// yet.
return event;
}
// ── Self-test ────────────────────────────────────────────────────────────────
+15 -2
View File
@@ -396,12 +396,20 @@ const server = http.createServer((req, res) => {
return;
}
const reason = (typeof parsed.reason === "string" && parsed.reason.slice(0, 200)) || "user cancel";
appendEvent({
const cancelled = appendEvent({
kind: "bridge.cancel",
project: projectName,
runId,
reason,
});
// Eager projection — match the /api/dispatch pattern. Closes the
// same race: a follow-up dispatch arriving before fs.watch fires
// would see stale currentRun and refuse to proceed; with eager
// apply, currentRun is already cleared (bridge.cancel projection
// matches runId and unsets it). Idempotent re-application by
// tailLog: cancelledRunIds.filter() dedupes, currentRun stays
// undefined.
state = applyEvent(state, cancelled);
res.setHeader("Content-Type", "application/json");
res.end(JSON.stringify({ ok: true, runId, reason }));
} catch (e) {
@@ -485,7 +493,7 @@ const server = http.createServer((req, res) => {
typeof parsed.adapter === "string" && (ADAPTERS as readonly string[]).includes(parsed.adapter)
? (parsed.adapter as Adapter)
: undefined;
appendEvent({
const dispatched = appendEvent({
kind: "bridge.dispatch",
project: projectName,
intent,
@@ -496,6 +504,11 @@ const server = http.createServer((req, res) => {
reason: decision.action.reason,
confidence: decision.confidence,
});
// Eagerly project so a concurrent /api/dispatch reads the post-state
// and decide() returns "wait" instead of firing a second dispatch.
// tailLog will re-apply the same event when fs.watch fires; that's
// idempotent for bridge.dispatch (just overwrites currentRun).
state = applyEvent(state, dispatched);
res.setHeader("Content-Type", "application/json");
res.end(JSON.stringify({ dispatched: true, decision, runId }));
} catch (e) {