Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

feat(community): show a bot's last-refresh time + handled-message count

Claudette74f38792b109
diff --git a/src/shared/src/community/wake-dispatch.ts b/src/shared/src/community/wake-dispatch.ts
index 732e40155..34dae4fa5 100644
--- a/src/shared/src/community/wake-dispatch.ts
+++ b/src/shared/src/community/wake-dispatch.ts
@@ -240,11 +240,18 @@ async function writeWakeTriggerAudit(
senderHandle: `@${formatHandle(sender.name, sender.discriminator)}`,
reason: (isMention ? "mention" : "unread") as "unread" | "mention",
};
- const inserted = await botAuditLog.insertBotAuditWakeTrigger(db, {
- botId: input.botUserId,
- launchId: input.launchId,
- payload,
- });
+ // Fold the "handled this lifecycle" count bump into the SAME atomic batch as
+ // the wake_trigger audit insert+prune — one message that triggers a wake =
+ // one batched round-trip, not a separate hot-path write (Cecilia's perf red
+ // line, #533). It shares the audit batch's all-or-nothing fate: a failed
+ // audit write skips the +1 too, which is fine (a dropped increment on a D1
+ // blip is far cheaper than a per-message extra round-trip). The counter is
+ // reset to 0 at nap/session_reset (`touchBotRefreshContext`).
+ const inserted = await botAuditLog.insertBotAuditWakeTrigger(
+ db,
+ { botId: input.botUserId, launchId: input.launchId, payload },
+ [bot.bumpBotHandledMessageCountStatement(db, input.botUserId)]
+ );
if (!inserted || !env) return;
// ws-do live broadcast — best-effort, must not block the wake. `catch`
diff --git a/src/shared/src/db/queries/community/bot-audit-log.ts b/src/shared/src/db/queries/community/bot-audit-log.ts
index 78ee5bc19..9e0de1ab6 100644
--- a/src/shared/src/db/queries/community/bot-audit-log.ts
+++ b/src/shared/src/db/queries/community/bot-audit-log.ts
@@ -55,11 +55,20 @@ export type WakeTriggerPayload = {
*/
export async function insertBotActivityEventAndPrune(
db: Database,
- data: BotActivityEventInput
+ data: BotActivityEventInput,
+ /**
+ * Extra Drizzle statements to run in the SAME atomic batch as the insert +
+ * prune — lets a caller fold a companion write (e.g. the per-message
+ * `handledMessageCount` bump on a wake_trigger) into this one round-trip
+ * instead of issuing a separate hot-path write. They share the batch's
+ * all-or-nothing fate. Appended AFTER insert+prune so `results[0]` is still
+ * the insert.
+ */
+ extraStatements: unknown[] = []
): Promise<{ id: string; createdAt: string } | null> {
const insert = insertBotActivityEventStatement(db, data);
const prune = pruneBotActivityEventsStatement(db, data.botId);
- const results = (await db.batch([insert, prune] as any)) as any[];
+ const results = (await db.batch([insert, prune, ...extraStatements] as any)) as any[];
const insertResult = results?.[0];
const rows: Array<{ id: string; createdAt: string }> = Array.isArray(insertResult)
? insertResult
@@ -188,15 +197,26 @@ export async function insertBotAuditWakeTrigger(
sessionId?: string | null;
launchId?: string | null;
payload: WakeTriggerPayload;
- }
+ },
+ /**
+ * Extra Drizzle statements to fold into the SAME atomic batch as the
+ * wake_trigger insert + prune (see `insertBotActivityEventAndPrune`). The
+ * wake path uses this to bump `handledMessageCount` in the one round-trip
+ * that already writes the audit row, rather than a separate hot-path write.
+ */
+ extraStatements: unknown[] = []
): Promise<{ id: string; createdAt: string } | null> {
- return insertBotActivityEventAndPrune(db, {
- botId: data.botId,
- sessionId: data.sessionId ?? null,
- launchId: data.launchId ?? null,
- kind: "wake_trigger",
- payload: JSON.stringify(data.payload),
- });
+ return insertBotActivityEventAndPrune(
+ db,
+ {
+ botId: data.botId,
+ sessionId: data.sessionId ?? null,
+ launchId: data.launchId ?? null,
+ kind: "wake_trigger",
+ payload: JSON.stringify(data.payload),
+ },
+ extraStatements
+ );
}
/**
diff --git a/src/shared/src/db/queries/community/bot.ts b/src/shared/src/db/queries/community/bot.ts
index d33529c34..9a1669409 100644
--- a/src/shared/src/db/queries/community/bot.ts
+++ b/src/shared/src/db/queries/community/bot.ts
@@ -50,6 +50,18 @@ export type BotRow = {
description: string;
createdAt: string;
updatedAt: string;
+ /**
+ * ISO timestamp of the bot's last "refresh context" (a `nap` or owner
+ * `session_reset`), or null if it has never refreshed. Written only at the
+ * nap/session_reset audit chokepoint — a monotonic historical fact.
+ */
+ lastRefreshContextAt: string | null;
+ /**
+ * Count of messages HANDLED in the current context lifecycle — incremented
+ * once per message that triggered a wake (post-gate), reset to 0 at the same
+ * nap/session_reset chokepoint. NOT raw messages received.
+ */
+ handledMessageCount: number;
};
export type BotBinding = {
@@ -86,6 +98,8 @@ export async function listBotsForOwner(
ownerUserId: user.ownerUserId,
createdAt: user.createdAt,
updatedAt: user.updatedAt,
+ lastRefreshContextAt: user.lastRefreshContextAt,
+ handledMessageCount: user.handledMessageCount,
description: communityUserProfile.aboutMe,
machineId: communityBotBinding.machineId,
runtime: communityBotBinding.runtime,
@@ -113,6 +127,8 @@ export async function listBotsForOwner(
description: r.description ?? "",
createdAt: r.createdAt,
updatedAt: r.updatedAt,
+ lastRefreshContextAt: r.lastRefreshContextAt ?? null,
+ handledMessageCount: r.handledMessageCount ?? 0,
machineId: r.machineId,
runtime: r.runtime,
modelName: r.modelName ?? null,
@@ -137,6 +153,8 @@ export async function getBotOwnedBy(
ownerUserId: user.ownerUserId,
createdAt: user.createdAt,
updatedAt: user.updatedAt,
+ lastRefreshContextAt: user.lastRefreshContextAt,
+ handledMessageCount: user.handledMessageCount,
description: communityUserProfile.aboutMe,
machineId: communityBotBinding.machineId,
runtime: communityBotBinding.runtime,
@@ -168,6 +186,8 @@ export async function getBotOwnedBy(
description: r.description ?? "",
createdAt: r.createdAt,
updatedAt: r.updatedAt,
+ lastRefreshContextAt: r.lastRefreshContextAt ?? null,
+ handledMessageCount: r.handledMessageCount ?? 0,
machineId: r.machineId ?? null,
runtime: r.runtime ?? null,
modelName: r.modelName ?? null,
@@ -648,6 +668,46 @@ export async function updateBotModel(
return rows.length > 0;
}
+/**
+ * Record a context refresh on a bot: stamp `lastRefreshContextAt` and zero
+ * `handledMessageCount` (the current lifecycle just ended). Called at — and
+ * ONLY at — the two audit chokepoints that record a refresh: `nap`
+ * (self-initiated) and `session_reset` (owner). Keeping this the single write
+ * point is what makes both fields monotonic-per-lifecycle facts that never
+ * drift from the audit log or the live FSM. Scoped to `isBot=true` and not
+ * soft-deleted; the caller has already authorized the action (runner-key for
+ * nap, owner for reset), so no ownerUserId predicate here. `now` is injected so
+ * callers pass the same instant they wrote the audit row.
+ */
+export async function touchBotRefreshContext(
+ db: Database,
+ botId: string,
+ now: string
+): Promise<void> {
+ await db
+ .update(user)
+ .set({ lastRefreshContextAt: now, handledMessageCount: 0 })
+ .where(and(eq(user.id, botId), eq(user.isBot, true), isNull(user.deletedAt)));
+}
+
+/**
+ * Drizzle statement that increments a bot's `handledMessageCount` by one, scoped
+ * to a live bot. Exposed as a statement builder (not an awaited write) so it can
+ * be composed into the SAME `db.batch([...])` as the per-message wake_trigger
+ * audit insert — one message that triggers a wake = one batched round-trip that
+ * writes the audit row AND bumps the count, not two. The counter is reset to 0
+ * by `touchBotRefreshContext` at each nap/session_reset. Riding the audit batch
+ * means it shares that batch's all-or-nothing fate (a failed wake_trigger write
+ * skips the bump too) — acceptable: a dropped +1 on a D1 blip is far cheaper
+ * than an extra hot-path round-trip per message.
+ */
+export function bumpBotHandledMessageCountStatement(db: Database, botId: string) {
+ return db
+ .update(user)
+ .set({ handledMessageCount: sql`${user.handledMessageCount} + 1` })
+ .where(and(eq(user.id, botId), eq(user.isBot, true), isNull(user.deletedAt)));
+}
+
/**
* Soft-delete a bot atomically:
* 1. UPDATE `user` set deletedAt (scoped by ownerUserId + isBot).
diff --git a/src/shared/src/db/schema.ts b/src/shared/src/db/schema.ts
index 9780df254..d29b8b570 100644
--- a/src/shared/src/db/schema.ts
+++ b/src/shared/src/db/schema.ts
@@ -38,6 +38,17 @@ export const user = sqliteTable(
ownerUserId: text("ownerUserId").references((): AnySQLiteColumn => user.id, { onDelete: "no action" }),
deletedAt: text("deletedAt"),
discriminator: text("discriminator").notNull().default("0000"),
+ // For bots: ISO timestamp of the last "refresh context" (a `nap` or an
+ // owner `session_reset` — both reset the agent's working context). Written
+ // only at the nap/session_reset audit chokepoint, so it's a monotonic
+ // historical fact that never drifts from the audit log. NULL = never
+ // refreshed. Surfaced in the my-bots list as "last refreshed N ago".
+ lastRefreshContextAt: text("lastRefreshContextAt"),
+ // For bots: count of messages HANDLED in the current context lifecycle —
+ // incremented once per message that triggered a wake (post-gate), reset to
+ // 0 at the same nap/session_reset chokepoint. NOT raw messages received;
+ // gate-filtered messages the agent never woke for are excluded.
+ handledMessageCount: integer("handledMessageCount", { mode: "number" }).notNull().default(0),
},
(t) => [index("idx_user_ownerUserId_isBot").on(t.ownerUserId, t.isBot)]
);
diff --git a/src/shared/test/community/wake-dispatch-build.test.ts b/src/shared/test/community/wake-dispatch-build.test.ts
index dda0ffb68..49e03443f 100644
--- a/src/shared/test/community/wake-dispatch-build.test.ts
+++ b/src/shared/test/community/wake-dispatch-build.test.ts
@@ -6,8 +6,10 @@ vi.mock("../../src/db/queries/community/message", () => ({
}));
const mockGetBotWakeContext = vi.fn();
+const mockBumpBotHandledMessageCountStatement = vi.fn(() => ({ __stmt: "bump" }));
vi.mock("../../src/db/queries/community/bot", () => ({
getBotWakeContext: (...a: unknown[]) => mockGetBotWakeContext(...a),
+ bumpBotHandledMessageCountStatement: (...a: unknown[]) => mockBumpBotHandledMessageCountStatement(...a),
}));
const mockHasMentionForMessage = vi.fn();
@@ -294,6 +296,14 @@ describe("buildUnreadWakeCommand", () => {
reason: "unread",
},
});
+ // handledMessageCount rides the SAME atomic batch as the audit insert:
+ // the +1 statement is built for this bot and handed to
+ // insertBotAuditWakeTrigger as an extra batch statement — one round-trip,
+ // not a separate hot-path write (Cecilia's perf red line).
+ expect(mockBumpBotHandledMessageCountStatement).toHaveBeenCalledTimes(1);
+ expect(mockBumpBotHandledMessageCountStatement).toHaveBeenCalledWith(expect.anything(), "bot_1");
+ const [, , extraStatements] = mockInsertBotAuditWakeTrigger.mock.calls[0]!;
+ expect(extraStatements).toEqual([{ __stmt: "bump" }]);
});
it("audit reason is 'mention' when the message carries a mention row for the bot", async () => {
@@ -310,6 +320,9 @@ describe("buildUnreadWakeCommand", () => {
await buildUnreadWakeCommand(fakeDb, { messageId: "msg_1", botUserId: "bot_1" });
expect(mockInsertBotAuditWakeTrigger).not.toHaveBeenCalled();
+ // Skipped wake never handled the message → no count bump statement is even
+ // built (rides the same post-gate chokepoint as the audit write).
+ expect(mockBumpBotHandledMessageCountStatement).not.toHaveBeenCalled();
});
it("wake still fires when the audit insert throws (best-effort, MUST NOT gate the wake)", async () => {
diff --git a/src/web/migrations/0073_user_last_refresh_context_at.sql b/src/web/migrations/0073_user_last_refresh_context_at.sql
new file mode 100644
index 000000000..dc99fff6d
--- /dev/null
+++ b/src/web/migrations/0073_user_last_refresh_context_at.sql
@@ -0,0 +1,23 @@
+-- My-bots "last refresh-context" indicator (Gus request): surface on each bot
+-- how long ago it last refreshed its context. A "refresh context" is either a
+-- self-initiated `nap` or an owner-triggered `session_reset` — both reset the
+-- agent's working context, so they share one unified timestamp.
+--
+-- Written at the SAME chokepoint that records the nap/session_reset audit event
+-- (the delivery-confirmed moment), and NOWHERE else — a single write point makes
+-- it a monotonic historical-fact timestamp that can never drift from the audit
+-- log or the live FSM state (it does not reflect FSM state; it records that a
+-- refresh happened). NULL = the bot has never napped/reset.
+--
+-- On the bot's `user` row (a bot is a `user` with isBot=true), so the existing
+-- owner-scoped bot list carries it with no extra join.
+
+ALTER TABLE user ADD COLUMN lastRefreshContextAt TEXT;
+
+-- Companion counter: how many messages the agent has HANDLED within the current
+-- context (this nap/reset lifecycle). Incremented once per message that
+-- actually triggered a wake (folded into the existing per-message wake_trigger
+-- write, post-gate — so gate-filtered messages the agent never woke for are NOT
+-- counted, matching the "how many did it handle" intent). Reset to 0 at the
+-- same nap/session_reset chokepoint that stamps lastRefreshContextAt.
+ALTER TABLE user ADD COLUMN handledMessageCount INTEGER NOT NULL DEFAULT 0;
diff --git a/src/web/src/app/api/community/agent/nap/route.ts b/src/web/src/app/api/community/agent/nap/route.ts
index 95c959740..2eac17a59 100644
--- a/src/web/src/app/api/community/agent/nap/route.ts
+++ b/src/web/src/app/api/community/agent/nap/route.ts
@@ -70,7 +70,13 @@ export const POST = withAgentRunnerAuth(async (req: NextRequest, ctx) => {
}
// Audit on delivery only (mirrors reset/model-switch). No notification.
- await queries.communityBotAuditLog.insertBotAuditNap(db, { botId: ctx.botUserId })
+ // Stamp lastRefreshContextAt at the SAME chokepoint (single write point),
+ // reusing the audit row's own createdAt so the my-bots "last refreshed"
+ // indicator can never drift from the nap audit event.
+ const inserted = await queries.communityBotAuditLog.insertBotAuditNap(db, { botId: ctx.botUserId })
+ if (inserted) {
+ await queries.communityBot.touchBotRefreshContext(db, ctx.botUserId, inserted.createdAt)
+ }
return NextResponse.json({ napped: true })
})
diff --git a/src/web/src/app/api/community/bots/[id]/reset-session/route.test.ts b/src/web/src/app/api/community/bots/[id]/reset-session/route.test.ts
index b83b506f3..dda4e67a0 100644
--- a/src/web/src/app/api/community/bots/[id]/reset-session/route.test.ts
+++ b/src/web/src/app/api/community/bots/[id]/reset-session/route.test.ts
@@ -4,6 +4,7 @@ import { NextRequest } from "next/server"
const mockGetBotOwnedBy = vi.fn()
const mockGetBotWakeContext = vi.fn()
const mockInsertBotAuditSessionReset = vi.fn()
+const mockTouchBotRefreshContext = vi.fn()
const mockBroadcastToUser = vi.fn()
const mockPushAgentResetToMachine = vi.fn()
@@ -21,6 +22,7 @@ vi.mock("@alook/shared", async () => {
communityBot: {
getBotOwnedBy: (...a: unknown[]) => mockGetBotOwnedBy(...a),
getBotWakeContext: (...a: unknown[]) => mockGetBotWakeContext(...a),
+ touchBotRefreshContext: (...a: unknown[]) => mockTouchBotRefreshContext(...a),
},
communityBotAuditLog: {
insertBotAuditSessionReset: (...a: unknown[]) => mockInsertBotAuditSessionReset(...a),
@@ -122,6 +124,9 @@ describe("POST /api/community/bots/[id]/reset-session", () => {
expect(res.status).toBe(409)
expect(mockPushAgentResetToMachine).toHaveBeenCalledTimes(1)
expect(mockInsertBotAuditSessionReset).not.toHaveBeenCalled()
+ // No audit row means no refresh happened → the timestamp is not stamped
+ // either (they share the one chokepoint).
+ expect(mockTouchBotRefreshContext).not.toHaveBeenCalled()
expect(mockBroadcastToUser).not.toHaveBeenCalled()
})
@@ -152,6 +157,15 @@ describe("POST /api/community/bots/[id]/reset-session", () => {
botId: "b1",
actorId: "owner_1",
})
+ // Single-source invariant: lastRefreshContextAt is stamped exactly once, in
+ // lockstep with the audit row, reusing that row's OWN createdAt — so the
+ // my-bots "last refreshed" timestamp can never drift from the audit event.
+ expect(mockTouchBotRefreshContext).toHaveBeenCalledTimes(1)
+ expect(mockTouchBotRefreshContext).toHaveBeenCalledWith(
+ expect.anything(),
+ "b1",
+ "2026-07-24T09:00:00.000Z",
+ )
expect(mockBroadcastToUser).toHaveBeenCalledTimes(1)
expect(mockBroadcastToUser).toHaveBeenCalledWith(
"owner_1",
diff --git a/src/web/src/app/api/community/bots/[id]/reset-session/route.ts b/src/web/src/app/api/community/bots/[id]/reset-session/route.ts
index 0ef1b6d70..140863a2e 100644
--- a/src/web/src/app/api/community/bots/[id]/reset-session/route.ts
+++ b/src/web/src/app/api/community/bots/[id]/reset-session/route.ts
@@ -49,6 +49,10 @@ export const POST = withAuth(async (_req, ctx) => {
actorId: ctx.userId,
})
if (inserted) {
+ // Stamp lastRefreshContextAt at the SAME chokepoint (single write point),
+ // in lockstep with the audit row landing — the my-bots "last refreshed"
+ // indicator can never drift from the session_reset audit event.
+ await queries.communityBot.touchBotRefreshContext(db, id, inserted.createdAt)
try {
await broadcastToUser(ctx.userId, {
type: WS_EVENTS.BOT_AUDIT_EVENT,