Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

fix(brief): read mail and no-reply senders leave the brief; a thread already answered is not waiting on a reply

AdityaUmalee3fbb218adda
diff --git a/server/connected-reads.test.ts b/server/connected-reads.test.ts
index 4332fdf9c1..18dc53c0f9 100644
--- a/server/connected-reads.test.ts
+++ b/server/connected-reads.test.ts
@@ -44,6 +44,15 @@ describe("reading Composio's answers", () => {
expect(event).toMatchObject({ id: "teams-1", joinUrl: teams });
});
+ it("reads whether Gmail and Outlook mail is still unread, and says nothing when the answer did not", () => {
+ expect(messageFromData({ messageId: "m-1", threadId: "t-1", labelIds: ["INBOX"] }).unread).toBe(false);
+ expect(threadFromData({ messages: [{ messageId: "m-1", labelIds: ["UNREAD"] }, { messageId: "m-2", labelIds: [] }, { messageId: "m-3" }] }).map((message) => message.unread))
+ .toEqual([true, false, undefined]);
+ expect(outlookMessagesFromData({ value: [{ id: "o-1", isRead: false }, { id: "o-2", isRead: true }, { id: "o-3" }] }).map((message) => message.unread))
+ .toEqual([true, false, undefined]);
+ expect(outlookMessageFromData({ id: "o-1", isRead: true }).unread).toBe(false);
+ });
+
it("reads mail headers, profiles, single messages, threads and the calendar list", () => {
const emails = emailsFromData(fixture("composio-gmail-fetch"));
expect(emails.map((email) => [email.id, email.threadId, email.from, email.subject])).toEqual([
@@ -51,6 +60,7 @@ describe("reading Composio's answers", () => {
["newsletter-1", "thread-news", "News <[email protected]>", "This week in tech"],
]);
expect(emails[0]!.preview).toBe("Can you send the Q3 numbers by Friday? Thanks");
+ expect(emails.map((email) => email.unread)).toEqual([true, undefined]);
expect(profileFromData(fixture("composio-gmail-profile"))).toBe("[email protected]");
expect(messageFromData(fixture("composio-gmail-message"))).toMatchObject({ id: "m-1", threadId: "t-1", subject: "Q3 numbers" });
expect(threadFromData(fixture("composio-gmail-thread")).map((message) => message.from)).toEqual(["[email protected]", "[email protected]"]);
diff --git a/server/connected-reads.ts b/server/connected-reads.ts
index 061743b8d8..cbbbb7bc3a 100644
--- a/server/connected-reads.ts
+++ b/server/connected-reads.ts
@@ -41,6 +41,8 @@ export interface EmailHeader {
app?: MailApp;
/** Outlook's own web address for the message. */
link?: string;
+ /** False once the person has read it; left out when the app did not say. */
+ unread?: boolean;
}
export interface ThreadMessage {
@@ -48,6 +50,7 @@ export interface ThreadMessage {
at: number;
/** The sender's lower-case address, or "" when the answer named none. */
from: string;
+ unread?: boolean;
}
const SIGNED_OUT = /\b(?:unauthori[sz]ed|unauthenticated|invalid[_ ]grant|expired|re-?connect|not connected|no connected account|not active|initiated|initializing|permission denied|forbidden|401|403)\b/i;
@@ -183,7 +186,8 @@ function oneLine(value: unknown, max: number): string {
return Array.from(flat(typeof value === "string" ? value.replace(/[^\P{C}\s]/gu, "") : "")).slice(0, max).join("").trim();
}
-function addressIn(sender: string): string {
+/** The lower-case address in a From line, or "" when it holds none. */
+export function addressIn(sender: string): string {
const candidate = (/<([^<>\s]+)>/.exec(sender)?.[1] ?? sender).trim().toLowerCase();
return ADDRESS.test(candidate) ? candidate : "";
}
@@ -256,6 +260,11 @@ function messageId(item: Record<string, unknown> | undefined): string | undefine
return typeof id === "string" && id ? id : undefined;
}
+/** Gmail's read state from the message's labels; nothing when the answer carried no labels. */
+function gmailUnread(item: Record<string, unknown>): { unread?: boolean } {
+ return Array.isArray(item.labelIds) ? { unread: item.labelIds.includes("UNREAD") } : {};
+}
+
function emailHeader(raw: unknown): EmailHeader | null {
const item = record(raw);
const id = messageId(item);
@@ -268,6 +277,7 @@ function emailHeader(raw: unknown): EmailHeader | null {
from: senderOf(item),
subject: flat(item.subject ?? preview?.subject ?? headerValue(item, "subject")),
preview: flat(preview?.body ?? item.snippet ?? item.messageText).slice(0, PREVIEW_MAX),
+ ...gmailUnread(item),
};
}
@@ -336,6 +346,7 @@ function outlookHeader(raw: unknown): EmailHeader | null {
preview: flat(item.bodyPreview).slice(0, PREVIEW_MAX),
app: "outlook",
...(typeof item.webLink === "string" && item.webLink ? { link: item.webLink } : {}),
+ ...(typeof item.isRead === "boolean" ? { unread: !item.isRead } : {}),
};
}
@@ -368,7 +379,7 @@ export function threadFromData(data: unknown): ThreadMessage[] {
const messages = list.flatMap((raw): ThreadMessage[] => {
const item = record(raw);
const id = messageId(item);
- return item && id ? [{ id, at: sentAt(item), from: addressIn(senderOf(item)) }] : [];
+ return item && id ? [{ id, at: sentAt(item), from: addressIn(senderOf(item)), ...gmailUnread(item) }] : [];
});
if (list.length > 0 && messages.length === 0) throw new Error("none of the thread's messages could be read");
return messages;
@@ -629,7 +640,7 @@ export function createConnectedReads(deps: ConnectedReadDeps): Omit<ConnectedRea
for (;;) {
const data = await call(OUTLOOK_LIST_TOOL, {
user_id: "me", folder: "inbox", top: size, received_date_time_ge: new Date(sinceMs).toISOString(),
- select: ["id", "subject", "from", "receivedDateTime", "bodyPreview", "conversationId", "webLink"],
+ select: ["id", "subject", "from", "receivedDateTime", "bodyPreview", "conversationId", "webLink", "isRead"],
}, { shortened: size > GMAIL_PAGE_MIN, pin });
if (data === SHORTENED) {
size = Math.max(GMAIL_PAGE_MIN, Math.floor(size / 2));
@@ -640,7 +651,7 @@ export function createConnectedReads(deps: ConnectedReadDeps): Omit<ConnectedRea
},
async outlookMessage(id) {
const data = await call(OUTLOOK_MESSAGE_TOOL, {
- user_id: "me", message_id: id, select: ["id", "subject", "from", "receivedDateTime", "bodyPreview", "conversationId", "webLink"],
+ user_id: "me", message_id: id, select: ["id", "subject", "from", "receivedDateTime", "bodyPreview", "conversationId", "webLink", "isRead"],
}, { gone: messageGone });
return data === GONE ? null : parsed("outlook", () => outlookMessageFromData(data));
},
diff --git a/server/host/brief.test.ts b/server/host/brief.test.ts
index de361574f8..033554e2e5 100644
--- a/server/host/brief.test.ts
+++ b/server/host/brief.test.ts
@@ -5,7 +5,7 @@ import { afterEach, describe, expect, it, vi } from "vitest";
import type { NeedsYouItem } from "../../shared/today.ts";
import { widgetActions, type WidgetRoot } from "../../shared/widget.ts";
-import type { CalendarEvent, EmailHeader } from "../connected-reads.ts";
+import type { CalendarEvent, EmailHeader, ReadSession, ThreadMessage } from "../connected-reads.ts";
import type { RequestAuth } from "../request-auth.ts";
import type { RoutineRun } from "../routines.ts";
import { Store, type Message } from "../store.ts";
@@ -25,7 +25,7 @@ const standup: CalendarEvent = {
attendees: [{ email: "[email protected]", self: true, organizer: true }, { email: "[email protected]", name: "Ada", self: false, organizer: false }],
};
-function setup(options: { hosted?: boolean; needsYou?: NeedsYouItem[]; language?: string; ideas?: string[] } = {}) {
+function setup(options: { hosted?: boolean; needsYou?: NeedsYouItem[]; language?: string; ideas?: string[]; session?: ReadSession } = {}) {
let watching = true;
const dir = mkdtempSync(join(tmpdir(), "omb-brief-"));
dirs.push(dir);
@@ -42,7 +42,7 @@ function setup(options: { hosted?: boolean; needsYou?: NeedsYouItem[]; language?
const make = () => createBrief({
store, dataDir: dir, now: () => now, hosted: options.hosted ?? false, watching: () => watching, mainThread: () => store.bot(chief.id)!.threadId, threadBusy: () => busy,
notify: (_bot, _thread, detail) => notified.push(detail), runs: () => runs, needsYou: () => options.needsYou ?? [], engineName: () => "Claude",
- hostTimeZone: () => "UTC", language: () => options.language, session: () => null, address: () => "[email protected]",
+ hostTimeZone: () => "UTC", language: () => options.language, session: () => options.session ?? null, address: () => "[email protected]",
failRun: (id, why) => failed.push([id, why]), keep: (key) => kept.push(key), items: (key) => items.get(key) ?? null,
ideas: (botId) => (botId === chief.id && options.ideas ? { ideas: options.ideas, conversations: 3 } : { ideas: [], conversations: 0 }),
});
@@ -401,3 +401,80 @@ describe("the brief", () => {
expect(s.shown()).not.toContain("mail.google.com");
});
});
+
+/** Gmail threads and Outlook messages by id, changed in place by a test. */
+function mailSession(threads: Record<string, ThreadMessage[]>, outlook: Record<string, EmailHeader | null> = {}): ReadSession {
+ return {
+ events: async () => [], emails: async () => ({ emails: [], more: false }), message: async () => null, address: async () => "[email protected]",
+ thread: async (threadId) => threads[threadId] ?? [], outlookMessage: async (id) => outlook[id] ?? null,
+ };
+}
+
+describe("the brief's email rows", () => {
+ const bob: EmailHeader = { id: "o1", threadId: "conv-1", at: 0, from: "Bob <[email protected]>", subject: "Invoice", preview: "Due Friday", app: "outlook" };
+
+ it("never lists mail already read or sent from a no-reply address", async () => {
+ const s = setup();
+ await s.brief.active("desktop", "UTC");
+ await s.brief.report({ routine: {} as never, at: s.now(), trouble: [], picked: [
+ { email: { ...ada, id: "m-read", threadId: "t-read", subject: "Already read", unread: false }, why: "Seen.", needsReply: true },
+ { email: { ...ada, id: "m-shop", threadId: "t-shop", from: "Shop <[email protected]>", subject: "Your order shipped" }, why: "Shipped.", needsReply: false },
+ { email: { ...ada, id: "m-bounce", threadId: "t-bounce", from: "[email protected]", subject: "Undeliverable" }, why: "Bounced.", needsReply: false },
+ { email: { ...ada, unread: true }, why: "Ada needs the numbers.", needsReply: true },
+ ] });
+ expect(s.shown()).toContain("Ada: Q3 numbers");
+ expect(s.shown()).not.toMatch(/Already read|Your order shipped|Undeliverable/);
+ });
+
+ it("drops a row once the person has read the mail, in Gmail or Outlook", async () => {
+ const threads: Record<string, ThreadMessage[]> = { t1: [{ id: "m1", at: 0, from: "[email protected]", unread: true }] };
+ const outlook: Record<string, EmailHeader | null> = { o1: { ...bob, unread: true } };
+ const session = mailSession(threads, outlook);
+ const s = setup();
+ await s.brief.active("desktop", "UTC");
+ await s.brief.report({ routine: {} as never, at: s.now(), trouble: [], session, picked: [{ email: ada, why: "Ada needs the numbers.", needsReply: true }, { email: bob, why: "Due Friday.", needsReply: false }] });
+ expect(s.shown()).toContain("Ada: Q3 numbers");
+ expect(s.shown()).toContain("Invoice");
+
+ threads.t1 = [{ id: "m1", at: 0, from: "[email protected]", unread: false }];
+ outlook.o1 = { ...bob, unread: false };
+ await s.brief.report({ routine: {} as never, at: s.now(), trouble: [], session });
+ expect(s.shown()).not.toContain("Q3 numbers");
+ expect(s.shown()).not.toContain("Invoice");
+ });
+
+ it("keeps a row whose read state the app did not say, waiting on a reply until the person replies after it", async () => {
+ const threads: Record<string, ThreadMessage[]> = { t1: [{ id: "m1", at: 0, from: "[email protected]" }] };
+ const session = mailSession(threads);
+ const s = setup();
+ await s.brief.active("desktop", "UTC");
+ await s.brief.report({ routine: {} as never, at: s.now(), trouble: [], session, picked: [{ email: ada, why: "Ada needs the numbers.", needsReply: true }] });
+ expect(s.shown()).toContain("Waiting on your reply · Ada needs the numbers.");
+
+ threads.t1 = [...threads.t1!, { id: "m2", at: 1, from: "[email protected]" }];
+ await s.brief.report({ routine: {} as never, at: s.now(), trouble: [], session });
+ expect(s.shown()).not.toContain("Q3 numbers");
+ });
+
+ it("does not say an email waits on a reply when the person already wrote in its thread before it", async () => {
+ const at = Date.parse("2026-10-22T07:00:00Z");
+ const session = mailSession({ t1: [{ id: "m0", at: at - 60 * MINUTE, from: "[email protected]" }, { id: "m1", at, from: "[email protected]", unread: true }] });
+ const s = setup();
+ await s.brief.active("desktop", "UTC");
+ await s.brief.report({ routine: {} as never, at: s.now(), trouble: [], session, picked: [{ email: { ...ada, at, subject: "Re: Q3 numbers" }, why: "Ada says thanks.", needsReply: true }] });
+ expect(s.shown()).toContain("Ada: Re: Q3 numbers");
+ expect(s.shown()).toContain("Ada says thanks.");
+ expect(s.shown()).not.toContain("Waiting on your reply");
+ });
+
+ it("checks a watch run's picks the same way before showing them", async () => {
+ const at = Date.parse("2026-10-22T07:00:00Z");
+ const s = setup({ session: mailSession({ t1: [{ id: "m0", at: at - 60 * MINUTE, from: "[email protected]" }, { id: "m1", at, from: "[email protected]" }] }) });
+ await s.brief.active("desktop", "UTC");
+ s.items.set("chk-1", { mail: [{ ...ada, at }, { ...ada, id: "m-shop", threadId: "t-shop", from: "[email protected]", subject: "Your order shipped" }], prep: [] });
+ await s.brief.consume(s.watchRun("chk-1", '{"important": [{"id": "m1", "why": "Ada says thanks.", "needsReply": true}, {"id": "m-shop", "why": "Shipped.", "needsReply": false}], "prep": []}'), "turn-1");
+ expect(s.shown()).toContain("Ada says thanks.");
+ expect(s.shown()).not.toContain("Waiting on your reply");
+ expect(s.shown()).not.toContain("Your order shipped");
+ });
+});
diff --git a/server/host/brief.ts b/server/host/brief.ts
index aa0cc3afcc..1acb22eea7 100644
--- a/server/host/brief.ts
+++ b/server/host/brief.ts
@@ -19,7 +19,7 @@ import { recordsBlock, clean } from "../records-block.ts";
import { ownerOrAdmin, type RequestAuth } from "../request-auth.ts";
import type { RoutineRun } from "../routines.ts";
import type { BotRecord, Message, Store } from "../store.ts";
-import { answered, localDate, qualifies, validZone } from "./check-plan.ts";
+import { answered, automatedSender, localDate, qualifies, repliedEarlier, validZone } from "./check-plan.ts";
import { parseWatchResult } from "./check-prompts.ts";
import { briefCard, clockTime, DISMISS_ACTION, DRAFT_ACTION, moment, prepCard, reminderCard, words, type BriefEmail, type BriefFacts, type BriefRow, type BuiltCard, type NeedRow } from "./brief-cards.ts";
import { briefWords, type BriefWords } from "./brief-words.ts";
@@ -333,8 +333,8 @@ export function createBrief(deps: BriefDeps) {
for (const row of missing.slice(0, 12)) {
try {
const header = row.app === "outlook" ? await session.outlookMessage?.(row.messageId) : await session.message(row.messageId);
- if (header) headers.set(row.messageId, header);
- else if (header === null) state.important = state.important.filter((one) => one.messageId !== row.messageId);
+ if (header === null || header?.unread === false) state.important = state.important.filter((one) => one.messageId !== row.messageId);
+ else if (header) headers.set(row.messageId, header);
} catch {
return;
}
@@ -421,6 +421,7 @@ export function createBrief(deps: BriefDeps) {
/** An email picked for the brief, by a watch run or by the helper models: its row, with the why kept for this process. */
function keepImportant(email: EmailHeader, why: string, needsReply: boolean, at: number, whyText?: ServerText): void {
+ if (email.unread === false || automatedSender(email.from)) return;
headers.set(email.id, { ...email, why, ...(whyText ? { whyText } : {}) });
state.important = [...state.important.filter((row) => row.messageId !== email.id), { messageId: email.id, threadId: email.threadId, at: email.at, judgedAt: at, needsReply, ...(email.app === "outlook" ? { app: "outlook" as const } : {}) }].slice(-MAX_ROWS);
}
@@ -438,23 +439,40 @@ export function createBrief(deps: BriefDeps) {
const picked = found.picked ?? [];
for (const pick of picked) keepImportant(pick.email, pick.why, pick.needsReply, found.at, pick.whyText);
if (picked.length) save();
- await followUpReplies(found.session);
+ await followUp(found.session);
if (picked.length) await render({ create: true, notify: true });
else if (state.lastActiveAt !== undefined) await render({ create: false, notify: true });
}
- /** An email waiting on a reply leaves the brief once the person has replied in its thread. */
- async function followUpReplies(session: ReadSession | undefined): Promise<void> {
+ /** An email leaves the brief once the person has read it, or replied in its thread after it. One in a thread they had
+ * already written in is not waiting on their reply. */
+ async function followUp(session: ReadSession | null | undefined): Promise<void> {
const address = deps.address();
- const open = liveImportant(now()).filter((row) => row.needsReply && row.app !== "outlook");
- if (!session || !address || !open.length) return;
+ const open = liveImportant(now());
+ if (!session || !open.length) return;
+ let changed = false;
+ const drop = (row: Important) => {
+ state.important = state.important.filter((one) => one.messageId !== row.messageId);
+ changed = true;
+ };
for (const row of open.slice(0, 10)) {
try {
- if (answered({ at: row.at }, await session.thread(row.threadId), address)) state.important = state.important.filter((one) => one.messageId !== row.messageId);
+ if (row.app === "outlook") {
+ const header = await session.outlookMessage?.(row.messageId);
+ if (header === null || header?.unread === false) drop(row);
+ continue;
+ }
+ const thread = await session.thread(row.threadId);
+ if (thread.find((message) => message.id === row.messageId)?.unread === false || (row.needsReply && answered(row, thread, address))) drop(row);
+ else if (row.needsReply && repliedEarlier(row, thread, address)) {
+ row.needsReply = false;
+ changed = true;
+ }
} catch {
- return;
+ break;
}
}
+ if (changed) save();
}
/** A watch run ended: its answer becomes rows and prep cards, or the run fails and its items go back. */
@@ -482,8 +500,10 @@ export function createBrief(deps: BriefDeps) {
}
}
deps.keep(key);
+ const picked = !result.quiet && result.important.length > 0;
+ if (picked) await followUp(deps.session());
save();
- if (!result.quiet && result.important.length) await render({ create: true, notify: true });
+ if (picked) await render({ create: true, notify: true });
}
/** The person arrived: the first open of a day, or a return after 3 hours away, shows today's brief when it has anything
diff --git a/server/host/check-plan.test.ts b/server/host/check-plan.test.ts
index 41948c25aa..4120700a3b 100644
--- a/server/host/check-plan.test.ts
+++ b/server/host/check-plan.test.ts
@@ -2,7 +2,7 @@ import { describe, expect, it } from "vitest";
import type { CalendarEvent, EmailHeader } from "../connected-reads.ts";
import {
- answered, clashes, EMAIL_MAX_AGE_MS, emailSince, FIRST_MAIL_LOOK_BACK_MS, fingerprint, mergeMeetings, nextMeetingDue, planMail, planMeetings, PREP_LEAD_MS, REMINDER_LEAD_MS, TRIAGE_BATCH,
+ answered, automatedSender, clashes, EMAIL_MAX_AGE_MS, emailSince, FIRST_MAIL_LOOK_BACK_MS, fingerprint, mergeMeetings, nextMeetingDue, planMail, planMeetings, PREP_LEAD_MS, REMINDER_LEAD_MS, repliedEarlier, TRIAGE_BATCH,
} from "./check-plan.ts";
const MINUTE = 60_000;
@@ -76,3 +76,22 @@ describe("mail", () => {
expect(answered(sent, [{ id: "r", at: now - 2 * 60 * MINUTE, from: "[email protected]" }], "[email protected]")).toBe(false);
});
});
+
+describe("mail senders and threads", () => {
+ it("knows no-reply and bounce senders, and only those", () => {
+ expect(automatedSender(from), from).toBe(true);
+ }
+ for (const from of ["Ada <[email protected]>", "[email protected]", "[email protected]", "[email protected]", "Noreply Team <[email protected]>"]) {
+ expect(automatedSender(from), from).toBe(false);
+ }
+ });
+
+ it("tells a reply before an email from one after it", () => {
+ const thread = [{ id: "a", at: now - 2 * MINUTE, from: "[email protected]" }, { id: "b", at: now - MINUTE, from: "[email protected]" }];
+ expect(repliedEarlier({ at: now - MINUTE }, thread, "[email protected]")).toBe(true);
+ expect(answered({ at: now - MINUTE }, thread, "[email protected]")).toBe(false);
+ expect(repliedEarlier({ at: now - 3 * MINUTE }, thread, "[email protected]")).toBe(false);
+ expect(repliedEarlier({ at: now - MINUTE }, thread, undefined)).toBe(false);
+ });
+});
diff --git a/server/host/check-plan.ts b/server/host/check-plan.ts
index 43f2540aad..f4dada20f7 100644
--- a/server/host/check-plan.ts
+++ b/server/host/check-plan.ts
@@ -2,7 +2,7 @@
// clash, and which new emails go to the AI to sort. Pure, so every rule is tested without a clock or a connected app.
import { createHash } from "node:crypto";
-import type { CalendarEvent, EmailHeader, ThreadMessage } from "../connected-reads.ts";
+import { addressIn, type CalendarEvent, type EmailHeader, type ThreadMessage } from "../connected-reads.ts";
const MINUTE = 60_000;
const HOUR = 60 * MINUTE;
@@ -158,6 +158,16 @@ export function planMail(input: { now: number; emails: readonly EmailHeader[]; j
return { batch: recent.slice(0, TRIAGE_BATCH), quiet, waiting: recent.slice(TRIAGE_BATCH) };
}
+/** Mail from an address nobody reads replies at (no-reply, do-not-reply, bounce notices): never one to list. */
+export function automatedSender(from: string): boolean {
+ return /^(?:no[-_.]?reply|do[-_.]?not[-_.]?reply|mailer-daemon)(?![a-z0-9])/.test(addressIn(from));
+}
+
+/** The person already wrote in the thread before this email arrived. */
+export function repliedEarlier(email: Pick<EmailHeader, "at">, thread: readonly ThreadMessage[], address: string | undefined): boolean {
+ return address !== undefined && thread.some((message) => message.at < email.at && message.from === address);
+}
+
/** The person replied in the thread after this email arrived. */
export function answered(email: Pick<EmailHeader, "at">, thread: readonly ThreadMessage[], address: string | undefined): boolean {
return address !== undefined && thread.some((message) => message.at > email.at && message.from === address);