Skip to content

Commit cf908f7

Browse files
authored
fix(tlon): await message persistence before acknowledgement (#129090)
* fix(tlon): await message persistence before acknowledgement * test(tlon): use promise timer helper in monitor fixtures
1 parent 6f4b9a2 commit cf908f7

2 files changed

Lines changed: 101 additions & 104 deletions

File tree

‎extensions/tlon/src/monitor/index.test.ts‎

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
// Tlon monitor tests cover authentication, inbound context, and shutdown lifecycle.
22
import { createServer, type Server } from "node:http";
33
import type { AddressInfo } from "node:net";
4+
import { setImmediate } from "node:timers/promises";
45
import type { RuntimeEnv } from "openclaw/plugin-sdk/runtime";
56
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
67

@@ -201,6 +202,57 @@ describe("monitorTlonProvider authentication retry", () => {
201202
});
202203
});
203204

205+
it("awaits cumulative Tlon discovery persistence and retries failed writes", async () => {
206+
const controller = new AbortController();
207+
const runtime = { error: vi.fn(), exit: vi.fn(), log: vi.fn() } satisfies RuntimeEnv;
208+
authenticateMock.mockResolvedValueOnce("urbauth-~zod=proof");
209+
settingsManagerMock.load.mockResolvedValueOnce({
210+
groupChannels: ["chat/~zod/base"],
211+
autoAcceptGroupInvites: true,
212+
});
213+
214+
const monitor = monitorTlonProvider({ abortSignal: controller.signal, runtime });
215+
try {
216+
await vi.waitFor(() => expect(sseClientMock.connect).toHaveBeenCalledOnce());
217+
const groupSubscription = sseClientMock.subscribe.mock.calls
218+
.map(([subscription]) => subscription)
219+
.find(({ app, path }) => app === "groups" && path === "/groups/ui");
220+
if (!groupSubscription) {
221+
throw new Error("expected groups-ui subscription");
222+
}
223+
224+
const firstResult = groupSubscription.event({
225+
channels: {
226+
"chat/~zod/a": {},
227+
"chat/~zod/b": {},
228+
"chat/~zod/base": {},
229+
},
230+
join: { channels: ["chat/~zod/b", "chat/~zod/c", "heap/~zod/no"] },
231+
});
232+
expect.soft(firstResult).toBeInstanceOf(Promise);
233+
await firstResult;
234+
await setImmediate();
235+
236+
sseClientMock.poke.mockRejectedValueOnce(new Error("settings write failed"));
237+
const retryEvent = { join: { channels: ["chat/~zod/retry"] } };
238+
await Promise.resolve(groupSubscription.event(retryEvent)).catch(() => undefined);
239+
await setImmediate();
240+
await groupSubscription.event(retryEvent);
241+
242+
expect(sseClientMock.poke).toHaveBeenCalledTimes(3);
243+
expect(sseClientMock.poke.mock.calls[2]?.[0]).toMatchObject({
244+
json: {
245+
"put-entry": {
246+
value: ["chat/~zod/base", "chat/~zod/a", "chat/~zod/b", "chat/~zod/c", "chat/~zod/retry"],
247+
},
248+
},
249+
});
250+
} finally {
251+
controller.abort();
252+
await monitor;
253+
}
254+
});
255+
204256
describe("monitorTlonProvider inbound media truth", () => {
205257
it.each([
206258
{

‎extensions/tlon/src/monitor/index.ts‎

Lines changed: 49 additions & 104 deletions
Original file line numberDiff line numberDiff line change
@@ -1304,113 +1304,58 @@ export async function monitorTlonProvider(opts: MonitorTlonOpts = {}): Promise<v
13041304
await api.subscribe({
13051305
app: "groups",
13061306
path: "/groups/ui",
1307-
event: (event: unknown) => {
1308-
void (async () => {
1309-
try {
1310-
const eventRecord = asRecord(event);
1311-
// Handle group/channel join events
1312-
// Event structure: { group: { flag: "~host/group-name", ... }, channels: { ... } }
1313-
if (eventRecord) {
1314-
// Check for new channels being added to groups
1315-
const channels = asRecord(eventRecord.channels);
1316-
if (channels) {
1317-
for (const [channelNest, _channelData] of Object.entries(channels)) {
1318-
// Only monitor chat channels
1319-
if (!channelNest.startsWith("chat/")) {
1320-
continue;
1321-
}
1322-
1323-
// If this is a new channel we're not watching yet, add it
1324-
if (!watchedChannels.has(channelNest)) {
1325-
watchedChannels.add(channelNest);
1326-
runtime.log?.(
1327-
`[tlon] Auto-detected new channel (invite accepted): ${channelNest}`,
1328-
);
1329-
1330-
// Persist to settings store so it survives restarts
1331-
if (effectiveAutoAcceptGroupInvites) {
1332-
try {
1333-
const currentChannels = currentSettings.groupChannels || [];
1334-
if (!currentChannels.includes(channelNest)) {
1335-
const updatedChannels = [...currentChannels, channelNest];
1336-
// Poke settings store to persist
1337-
await api.poke({
1338-
app: "settings",
1339-
mark: "settings-event",
1340-
json: {
1341-
"put-entry": {
1342-
"bucket-key": "tlon",
1343-
"entry-key": "groupChannels",
1344-
value: updatedChannels,
1345-
desk: "moltbot",
1346-
},
1347-
},
1348-
});
1349-
runtime.log?.(`[tlon] Persisted ${channelNest} to settings store`);
1350-
}
1351-
} catch (err) {
1352-
runtime.error?.(
1353-
`[tlon] Failed to persist channel to settings: ${String(err)}`,
1354-
);
1355-
}
1356-
}
1357-
}
1358-
}
1359-
}
1307+
event: async (event: unknown) => {
1308+
try {
1309+
const eventRecord = asRecord(event);
1310+
if (!eventRecord) {
1311+
return;
1312+
}
13601313

1361-
// Also check for the "join" event structure
1362-
const join = asRecord(eventRecord.join);
1363-
if (join) {
1364-
const joinChannels = Array.isArray(join.channels) ? join.channels : [];
1365-
if (joinChannels.length > 0) {
1366-
for (const channelNest of joinChannels) {
1367-
if (typeof channelNest !== "string") {
1368-
continue;
1369-
}
1370-
if (!channelNest.startsWith("chat/")) {
1371-
continue;
1372-
}
1373-
if (!watchedChannels.has(channelNest)) {
1374-
watchedChannels.add(channelNest);
1375-
runtime.log?.(`[tlon] Auto-detected joined channel: ${channelNest}`);
1376-
1377-
// Persist to settings store
1378-
if (effectiveAutoAcceptGroupInvites) {
1379-
try {
1380-
const currentChannels = currentSettings.groupChannels || [];
1381-
if (!currentChannels.includes(channelNest)) {
1382-
const updatedChannels = [...currentChannels, channelNest];
1383-
await api.poke({
1384-
app: "settings",
1385-
mark: "settings-event",
1386-
json: {
1387-
"put-entry": {
1388-
"bucket-key": "tlon",
1389-
"entry-key": "groupChannels",
1390-
value: updatedChannels,
1391-
desk: "moltbot",
1392-
},
1393-
},
1394-
});
1395-
runtime.log?.(`[tlon] Persisted ${channelNest} to settings store`);
1396-
}
1397-
} catch (err) {
1398-
runtime.error?.(
1399-
`[tlon] Failed to persist channel to settings: ${String(err)}`,
1400-
);
1401-
}
1402-
}
1403-
}
1404-
}
1405-
}
1406-
}
1314+
const join = asRecord(eventRecord.join);
1315+
const joinedChannels = Array.isArray(join?.channels) ? join.channels : [];
1316+
const discoveredChannels = mergeUniqueStrings(
1317+
Object.keys(asRecord(eventRecord.channels) ?? {}),
1318+
joinedChannels.filter((channel): channel is string => typeof channel === "string"),
1319+
).filter((channel) => channel.startsWith("chat/"));
1320+
1321+
for (const channelNest of discoveredChannels) {
1322+
if (!watchedChannels.has(channelNest)) {
1323+
watchedChannels.add(channelNest);
1324+
runtime.log?.(`[tlon] Auto-detected new channel: ${channelNest}`);
14071325
}
1408-
} catch (error: unknown) {
1409-
runtime.error?.(
1410-
`[tlon] Error handling groups-ui event: ${formatErrorMessage(error)}`,
1411-
);
14121326
}
1413-
})();
1327+
1328+
if (!effectiveAutoAcceptGroupInvites) {
1329+
return;
1330+
}
1331+
const currentChannels = currentSettings.groupChannels ?? [];
1332+
const unpersistedChannels = discoveredChannels.filter(
1333+
(channel) => !currentChannels.includes(channel),
1334+
);
1335+
if (unpersistedChannels.length === 0) {
1336+
return;
1337+
}
1338+
const updatedChannels = mergeUniqueStrings(currentChannels, unpersistedChannels);
1339+
await api.poke({
1340+
app: "settings",
1341+
mark: "settings-event",
1342+
json: {
1343+
"put-entry": {
1344+
"bucket-key": "tlon",
1345+
"entry-key": "groupChannels",
1346+
value: updatedChannels,
1347+
desk: "moltbot",
1348+
},
1349+
},
1350+
});
1351+
// The subscription snapshot lags its poke, so keep back-to-back facts cumulative.
1352+
currentSettings = { ...currentSettings, groupChannels: updatedChannels };
1353+
runtime.log?.(`[tlon] Persisted ${unpersistedChannels.join(", ")} to settings store`);
1354+
} catch (error: unknown) {
1355+
runtime.error?.(`[tlon] Error handling groups-ui event: ${formatErrorMessage(error)}`);
1356+
// SSE advances its durable ack only after this callback resolves.
1357+
throw error;
1358+
}
14141359
},
14151360
err: (error) => {
14161361
runtime.error?.(`[tlon] Groups-ui subscription error: ${String(error)}`);

0 commit comments

Comments
 (0)