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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix: consume the pending check-in atomically to avoid duplicate answers (#8907)
[._.]/ Adam Eivy7c7017b4d29d
diff --git a/server/services/telegram.js b/server/services/telegram.jsindex 12f53acf9b..1e01dc16be 100644--- a/server/services/telegram.js+++ b/server/services/telegram.js@@ -478,20 +478,30 @@ async function handleCheckinCommand(msg) {async function handleCheckinResponse(msg) {const chatId = String(msg.chat.id);cleanExpiredCheckins();+ // Captured synchronously, at dispatch time — this is THIS message's+ // outstanding question, independent of whatever else mutates+ // pendingCheckins before the queued critical section below actually runs.const pending = pendingCheckins.get(chatId);if (!pending) return;// Serialize the load -> mutate -> save cycle on a single tail so two- // concurrent responses (or a response racing sendCheckin's own read) can't- // interleave and drop one's entry (createFileWriteQueue, matching- // voice/timers.js's use of the same helper for its single JSON state file).- const recorded = await queueCheckinsWrite(async () => {+ // concurrent responses can't interleave and drop or duplicate a record+ // (createFileWriteQueue, matching voice/timers.js's use of the same helper+ // for its single JSON state file). The re-check below consumes `pending`+ // exactly once: if a second message raced this one for the SAME question,+ // whichever's critical section runs first deletes it, so the other finds it+ // already gone and skips — otherwise both would append an answer to one+ // prompt.+ const status = await queueCheckinsWrite(async () => {+ if (pendingCheckins.get(chatId) !== pending) return 'stale';+const checkins = await loadCheckins();// Bail rather than write: pushing onto the empty default would atomicWrite a// one-entry log over the whole history. The pending check-in stays pending so// the answer can be re-sent once the file is readable again.- if (!checkins) return false;+ if (!checkins) return 'unreadable';+ pendingCheckins.delete(chatId);checkins.checkins.push({id: uuidv4(),question: pending.question,@@ -507,15 +517,15 @@ async function handleCheckinResponse(msg) {}await saveCheckins(checkins);- return true;+ return 'recorded';});- if (!recorded) {+ if (status === 'stale') return; // another response already answered this question+ if (status === 'unreadable') {await bot.sendMessage(chatId, "⚠️ Couldn't read your check-in history, so I didn't record that. Nothing was overwritten — send it again once it's readable.", { parse_mode: 'HTML' });return;}- pendingCheckins.delete(chatId);await bot.sendMessage(chatId, '✅ Check-in recorded. Thanks!', { parse_mode: 'HTML' });}diff --git a/server/services/telegram.test.js b/server/services/telegram.test.jsindex 51c33a73ce..b4c7b8252b 100644--- a/server/services/telegram.test.js+++ b/server/services/telegram.test.js@@ -513,12 +513,16 @@ describe('telegram service', () => {* `handleCheckinResponse` is a `loadCheckins → push → atomicWrite` cycle. Two* concurrent invocations racing against the same on-disk state used to* interleave: both read the same pre-write snapshot, so whichever- * `atomicWrite` landed last silently discarded the other's entry. The fix- * routes the cycle through `createFileWriteQueue` so the second cycle only- * starts reading after the first has fully persisted.+ * `atomicWrite` landed last silently discarded the OTHER entry (and any+ * pre-existing history it had already read past). The fix routes the cycle+ * through `createFileWriteQueue` so the second cycle only starts reading+ * after the first has fully persisted, and re-checks the pending check-in is+ * still the one it captured before consuming it — so a genuine race (two+ * messages answering the SAME outstanding question) records the answer+ * exactly once instead of duplicating it.*/describe('checkins write queue (#8907)', () => {- it('persists both records when two check-in responses are processed concurrently', async () => {+ it('preserves prior history and records exactly one answer when two responses race the same question', async () => {const telegram = await loadTelegramActive();const { getGoals } = await import('./identity.js');getGoals.mockResolvedValue({ goals: [{ id: 'g1', title: 'Example Goal', status: 'active', progress: 40 }] });@@ -526,6 +530,10 @@ describe('telegram service', () => {await telegram.sendCheckin();h.sendMessage.mockClear();fu.writes = [];+ // Seed pre-existing history so a clobbered (rather than serialized) RMW+ // would be visible: the buggy version's stale read would drop this+ // entry from whichever write "won".+ fu.store = { checkins: [{ id: 'seed', question: 'Old Q', response: 'Old A', goalId: 'g0', askedAt: '2026-01-01T00:00:00.000Z', answeredAt: '2026-01-01T00:00:01.000Z' }] };const msgHandler = h.eventHandlers.message[0];// Fire both "responses" without awaiting between them, so both handler@@ -535,9 +543,17 @@ describe('telegram service', () => {const second = msgHandler({ chat: { id: 42 }, text: 'second response' });await Promise.all([first, second]);- expect(fu.writes).toHaveLength(2);- const finalCheckins = fu.writes[fu.writes.length - 1].data.checkins;- expect(finalCheckins.map((c) => c.response)).toEqual(['first response', 'second response']);+ // Only the winner of the race persists a write; the other finds the+ // pending check-in already consumed and skips silently (no duplicate,+ // no ack for the loser).+ expect(fu.writes).toHaveLength(1);+ expect(h.sendMessage).toHaveBeenCalledTimes(1);+ expect(h.sendMessage).toHaveBeenCalledWith('42', expect.stringContaining('Check-in recorded'), expect.anything());++ const finalCheckins = fu.writes[0].data.checkins;+ expect(finalCheckins).toHaveLength(2);+ expect(finalCheckins[0]).toMatchObject({ id: 'seed', response: 'Old A' });+ expect(finalCheckins[1]).toMatchObject({ goalId: 'g1', response: 'first response' });});});});