Skip to content

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

Train nov22-c2: 7 contributor PRs (turn dispatch move, Linux card, outside-file reveal, waits off a Cloud, cloud computer approvals, Qt doc, Outlook mail checks) (#6988)

Milind Soni2e6c3d7757ff
diff --git a/docs/linux-desktop.md b/docs/linux-desktop.md
index 86259155ad..f750ce699b 100644
--- a/docs/linux-desktop.md
+++ b/docs/linux-desktop.md
@@ -271,6 +271,21 @@ telemetry/update-check suppression, strict driver identity, overlay-free startup
defenses remain necessary, but none substitutes for the real-seat acceptance evidence required to enable Wayland. Linux
**Auto** never routes to the user's desktop, and no Cloud or Local VM approval can authorize it.
+### Known issue: Qt apps crash during Xorg sessions on current Qt (X11)
+
+On Xorg, each local-control session creates and later removes uinput pointer and keyboard devices.
+On hosts running current Qt (reported with Qt 6.11.3, X11 platform plugin), this device churn crashes
+every Qt application on the desktop — Telegram Desktop, Kate, Krusader and flameshot all SIGSEGV in the
+same second a device is removed, without any injected input involved (a use-after-free in Qt's XCB plugin).
+Tested outcomes (trycua/cua [issue #7325](https://github.com/trycua/cua/issues/7325)): Qt 6.4 and Qt 5.15
+did not crash, while Qt 6.8.3 and 6.10.1 on Ubuntu 24.04 did. A control run without Cua crashed too, so the
+affected condition is Qt's master-pointer removal behavior rather than a specific driver version.
+The fix belongs in the driver, which creates the devices once per lifetime
+in a persistent-device mode we do not ship yet: see upstream trycua/cua
+[issue #8451](https://github.com/trycua/cua/issues/8451) and the Cinnamon variant
+[issue #8197](https://github.com/trycua/cua/issues/8197). Until the driver fix lands, treat local control
+on a current-Qt X11 desktop as crash-prone for Qt apps.
+
## Omarchy (Hyprland, experimental)
[Omarchy](https://omarchy.org) is Arch Linux with the Hyprland compositor. **This computer** works there only with
diff --git a/server/connected-reads.test.ts b/server/connected-reads.test.ts
index 41ff54b377..66824b5a70 100644
--- a/server/connected-reads.test.ts
+++ b/server/connected-reads.test.ts
@@ -2,7 +2,7 @@ import { readFileSync } from "node:fs";
import { describe, expect, it } from "vitest";
import {
- calendarsFromData, createConnectedReads, emailsFromData, eventsFromData, messageFromData, profileFromData, SourceError, threadFromData, toolData,
+ calendarsFromData, createConnectedReads, emailsFromData, eventsFromData, messageFromData, outlookMessageFromData, outlookMessagesFromData, profileFromData, SourceError, threadFromData, toolData,
} from "./connected-reads.ts";
const fixture = (name: string): unknown => JSON.parse(readFileSync(new URL(`./testing/fixtures/${name}.json`, import.meta.url), "utf8"));
@@ -249,4 +249,32 @@ describe("a check's reads", () => {
expect(asked).toBe(2);
expect(frames.filter((one) => one.slug === "GMAIL_GET_PROFILE").map((one) => one.item!.account)).toEqual(["ca_newest"]);
});
+
+ it("reads Outlook inbox messages and single messages with preview, conversation id, and shortened-page fallback", async () => {
+ const messages = [
+ { id: "o1", conversationId: "conv-1", receivedDateTime: "2026-10-22T08:00:00Z", from: { emailAddress: { name: "Ada", address: "[email protected]" } }, subject: "First", bodyPreview: "Can you review?" },
+ { id: "o2", conversationId: "conv-2", receivedDateTime: "2026-10-22T09:00:00Z", from: { emailAddress: { address: "[email protected]" } }, subject: "Second", bodyPreview: "Latest update" },
+ ];
+ expect(outlookMessagesFromData({ value: messages }).map((m) => [m.id, m.threadId, m.from, m.preview, m.app])).toEqual([
+ ["o2", "conv-2", "[email protected]", "Latest update", "outlook"],
+ ["o1", "conv-1", "Ada <[email protected]>", "Can you review?", "outlook"],
+ ]);
+ expect(outlookMessageFromData(messages[0])).toMatchObject({ id: "o1", threadId: "conv-1", from: "Ada <[email protected]>", preview: "Can you review?", app: "outlook" });
+
+ const { deps, frames } = relay({
+ OUTLOOK_LIST_MESSAGES: (args) => {
+ if (Number(args.top) > 10) return { successful: true, data_preview: { value: ["...too many"] } };
+ return { successful: true, data: { value: messages } };
+ },
+ OUTLOOK_GET_MESSAGE: (args) => (args.message_id === "gone"
+ ? { successful: false, error: "Requested entity was not found." }
+ : { successful: true, data: messages[0] }),
+ });
+ const session = createConnectedReads(deps).session();
+ const list = await session.outlookEmails(Date.parse("2026-10-22T00:00:00Z"), 20);
+ expect(list.map((m) => m.id)).toEqual(["o2", "o1"]);
+ expect(frames.filter((one) => one.slug === "OUTLOOK_LIST_MESSAGES").map((one) => Number(one.args!.top))).toEqual([20, 10]);
+ expect(await session.outlookMessage("o1")).toMatchObject({ id: "o1", app: "outlook" });
+ expect(await session.outlookMessage("gone")).toBeNull();
+ });
});
diff --git a/server/connected-reads.ts b/server/connected-reads.ts
index 51908292b1..a9fb88f71c 100644
--- a/server/connected-reads.ts
+++ b/server/connected-reads.ts
@@ -1,11 +1,11 @@
-// Reads Google Calendar events, Gmail headers and, for a one-time code, a single Gmail or Outlook message from the server
+// Reads Google Calendar events, Gmail and Outlook headers and, for a one-time code, a single Gmail or Outlook message from the server
// through the connected-apps relay, with no AI turn, as the default connected account of each app, or the one the host
// names when an app has several. Tool names, arguments and answer shapes follow Composio's documentation; the fixtures are
// not yet checked against the live service, so an answer of any other shape is an error, never an empty list.
import { findMeetingLink } from "../shared/meetings.ts";
import { parseMcpResponse } from "./connector-tools-list.ts";
-export const READ_APPS = ["gmail", "googlecalendar"] as const;
+export const READ_APPS = ["gmail", "outlook", "googlecalendar"] as const;
export type ReadApp = (typeof READ_APPS)[number];
export type MailApp = "gmail" | "outlook";
@@ -38,6 +38,7 @@ export interface EmailHeader {
from: string;
subject: string;
preview: string;
+ app?: MailApp;
}
export interface ThreadMessage {
@@ -51,11 +52,11 @@ const SIGNED_OUT = /\b(?:unauthori[sz]ed|unauthenticated|invalid[_ ]grant|expire
/** A read that failed: the app, what went wrong, and whether reconnecting the app is what fixes it. */
export class SourceError extends Error {
- readonly app: ReadApp | "outlook";
+ readonly app: ReadApp;
readonly signedOut: boolean;
/** The read named one of the app's several connected accounts, so that account is the one to check. */
readonly severalAccounts: boolean;
- constructor(app: ReadApp | "outlook", message: string, severalAccounts = false) {
+ constructor(app: ReadApp, message: string, severalAccounts = false) {
super(message);
this.app = app;
this.signedOut = SIGNED_OUT.test(message);
@@ -309,8 +310,10 @@ export function gmailBodyFromData(data: unknown): string {
}
function outlookSender(item: Record<string, unknown>): string {
- const address = record(record(item.from)?.emailAddress)?.address;
- return typeof address === "string" ? address.trim() : "";
+ const from = record(record(item.from)?.emailAddress);
+ const address = typeof from?.address === "string" ? from.address.trim() : "";
+ const name = flat(from?.name);
+ return name && address && name.toLowerCase() !== address.toLowerCase() ? `${name} <${address}>` : address;
}
function outlookReceivedAt(item: Record<string, unknown>): number {
@@ -318,16 +321,34 @@ function outlookReceivedAt(item: Record<string, unknown>): number {
return Number.isFinite(at) ? at : 0;
}
+function outlookHeader(raw: unknown): EmailHeader | null {
+ const item = record(raw);
+ if (!item || typeof item.id !== "string" || !item.id) return null;
+ const threadId = typeof item.conversationId === "string" && item.conversationId ? item.conversationId : item.id;
+ return {
+ id: item.id,
+ threadId,
+ at: outlookReceivedAt(item),
+ from: outlookSender(item),
+ subject: flat(item.subject),
+ preview: flat(item.bodyPreview).slice(0, PREVIEW_MAX),
+ app: "outlook",
+ };
+}
+
export function outlookMessagesFromData(data: unknown): EmailHeader[] {
const list = listIn(data, ["value", "messages"]);
if (!list) throw new Error("the Outlook answer had no message list");
- const headers = list.flatMap((raw): EmailHeader[] => {
- const item = record(raw);
- if (!item || typeof item.id !== "string" || !item.id) return [];
- return [{ id: item.id, threadId: item.id, at: outlookReceivedAt(item), from: outlookSender(item), subject: flat(item.subject), preview: "" }];
- });
+ const headers = list.flatMap((raw) => outlookHeader(raw) ?? []);
if (list.length > 0 && headers.length === 0) throw new Error("none of the Outlook messages could be read");
- return headers;
+ return headers.sort((a, b) => b.at - a.at);
+}
+
+export function outlookMessageFromData(data: unknown): EmailHeader {
+ const top = record(data);
+ const header = outlookHeader(record(top?.message) ?? record(top?.response_data) ?? top);
+ if (!header) throw new Error("the Outlook message could not be read");
+ return header;
}
/** An Outlook message's body text; a message with none to read is an error. */
@@ -392,11 +413,11 @@ function untilAborted<T>(promise: Promise<T>, signal: AbortSignal, onAbort: () =
}
/** The account to name per app, for apps with several connected. */
-type AppAccounts = Partial<Record<ReadApp | "outlook", string>>;
+type AppAccounts = Partial<Record<ReadApp, string>>;
export interface ConnectedReadDeps {
- /** Null when connected apps are not set up here; else which of the two apps are connected. */
- connected(): Promise<Record<ReadApp, boolean> | null>;
+ /** Null when connected apps are not set up here; else which of the read apps are connected. */
+ connected(): Promise<Partial<Record<ReadApp, boolean>> | null>;
/** The account to read for each app with several connected (Composio refuses a read that names none then); an app
* with one is left out, and its reads name no account. Asked once per session, with the bot the session reads for. */
accounts?(botId?: string): Promise<AppAccounts>;
@@ -416,6 +437,10 @@ export interface ReadSession {
thread(threadId: string): Promise<ThreadMessage[]>;
/** The connected Gmail account's own address. */
address(): Promise<string>;
+ /** Outlook's inbox since `sinceMs`, newest first, at most `limit`, without bodies. */
+ outlookEmails?(sinceMs: number, limit: number): Promise<EmailHeader[]>;
+ /** Null only when Outlook says the message is gone. */
+ outlookMessage?(messageId: string): Promise<EmailHeader | null>;
}
/** The reads for a one-time code: a message's body, never kept or passed to a bot. */
@@ -424,11 +449,13 @@ export interface MailBodySession extends ReadSession {
messageBody(messageId: string): Promise<string | null>;
/** Outlook's inbox since `sinceMs`, newest first, at most `limit`, without bodies. */
outlookEmails(sinceMs: number, limit: number): Promise<EmailHeader[]>;
+ /** Null only when Outlook says the message is gone. */
+ outlookMessage(messageId: string): Promise<EmailHeader | null>;
outlookBody(messageId: string): Promise<string>;
}
export interface ConnectedReads {
- connected(): Promise<Record<ReadApp, boolean> | null>;
+ connected(): Promise<Partial<Record<ReadApp, boolean>> | null>;
/** `botId`: the bot the reads are for, so an account limit of its own picks the account. */
session(botId?: string): ReadSession;
}
@@ -442,7 +469,7 @@ const GMAIL_PAGES = 6;
/** The account lookup one multi-request read keeps for all its requests. */
type AccountPin = { accounts?: Promise<AppAccounts> };
-const appOf = (slug: string): ReadApp | "outlook" => (slug.startsWith("GMAIL_") ? "gmail" : slug.startsWith("OUTLOOK_") ? "outlook" : "googlecalendar");
+const appOf = (slug: string): ReadApp => (slug.startsWith("GMAIL_") ? "gmail" : slug.startsWith("OUTLOOK_") ? "outlook" : "googlecalendar");
export function createConnectedReads(deps: ConnectedReadDeps): Omit<ConnectedReads, "session"> & { session(botId?: string): MailBodySession } {
const readTimeoutMs = deps.readTimeoutMs ?? READ_TIMEOUT_MS;
@@ -503,7 +530,7 @@ export function createConnectedReads(deps: ConnectedReadDeps): Omit<ConnectedRea
}
}
- function parsed<T>(app: ReadApp | "outlook", parse: () => T): T {
+ function parsed<T>(app: ReadApp, parse: () => T): T {
try {
return parse();
} catch (error) {
@@ -511,7 +538,7 @@ export function createConnectedReads(deps: ConnectedReadDeps): Omit<ConnectedRea
}
}
- function requireFinite(app: ReadApp | "outlook", ...times: number[]): void {
+ function requireFinite(app: ReadApp, ...times: number[]): void {
if (times.some((time) => !Number.isFinite(time))) throw new SourceError(app, "the time window was not a finite time");
}
@@ -594,10 +621,25 @@ export function createConnectedReads(deps: ConnectedReadDeps): Omit<ConnectedRea
},
async outlookEmails(sinceMs, limit) {
requireFinite("outlook", sinceMs);
- const data = await call(OUTLOOK_LIST_TOOL, {
- user_id: "me", folder: "inbox", top: limit, received_date_time_ge: new Date(sinceMs).toISOString(), select: ["id", "subject", "from", "receivedDateTime"],
- });
- return parsed("outlook", () => outlookMessagesFromData(data));
+ let size = limit;
+ const pin: AccountPin = {};
+ 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"],
+ }, { shortened: size > GMAIL_PAGE_MIN, pin });
+ if (data === SHORTENED) {
+ size = Math.max(GMAIL_PAGE_MIN, Math.floor(size / 2));
+ continue;
+ }
+ return parsed("outlook", () => outlookMessagesFromData(data));
+ }
+ },
+ async outlookMessage(id) {
+ const data = await call(OUTLOOK_MESSAGE_TOOL, {
+ user_id: "me", message_id: id, select: ["id", "subject", "from", "receivedDateTime", "bodyPreview", "conversationId"],
+ }, { gone: messageGone });
+ return data === GONE ? null : parsed("outlook", () => outlookMessageFromData(data));
},
async outlookBody(id) {
const data = await call(OUTLOOK_MESSAGE_TOOL, { user_id: "me", message_id: id, select: ["id", "body"] });
diff --git a/server/drivers/claude.test.ts b/server/drivers/claude.test.ts
index 3c06fc1c5e..f1869a1be0 100644
--- a/server/drivers/claude.test.ts
+++ b/server/drivers/claude.test.ts
@@ -2990,6 +2990,66 @@ describe("ClaudeDriver turns (fake CLI)", () => {
expect(instance.adapter.capabilities.localComputerMcp).toBe(true);
});
+ it("mounts a cloud computer without pre-allowing its tools", async () => {
+ await create();
+ const dump = join(scratch, "cloud-dump.json");
+ process.env.FAKE_CLAUDE_DUMP = dump;
+ await instance.adapter.sendTurn({
+ threadId: "t-cloud",
+ text: "fill in the form",
+ approvalMode: "ask",
+ integrations: {
+ localComputer: {
+ command: process.execPath,
+ args: ["/fake/harness-mcp", "computer"],
+ env: { OMB_HARNESS_URL: "http://127.0.0.1:1" },
+ platform: "linux",
+ },
+ },
+ });
+ await recorder.until((event) => event.type === "turn.completed");
+
+ const seen = JSON.parse(readFileSync(dump, "utf8"));
+ expect(seen.mcpConfig.mcpServers.computer).toBeDefined();
+ const allowed = seen.argv[seen.argv.indexOf("--allowedTools") + 1];
+ expect(allowed).not.toContain("mcp__computer");
+ });
+
+ it("asks before a cloud computer acts, with session allowance like a command", async () => {
+ await create("hang");
+ await instance.adapter.sendTurn({
+ threadId: "t-cloud-ask",
+ text: "go",
+ approvalMode: "ask",
+ integrations: {
+ localComputer: {
+ command: process.execPath,
+ args: ["/fake/harness-mcp", "computer"],
+ env: {},
+ platform: "linux",
+ },
+ },
+ });
+ await recorder.until((e) => e.type === "session.started");
+
+ const conn = connect(permissionSocketPath("t-cloud-ask"));
+ await new Promise<void>((resolve, reject) => {
+ conn.on("connect", resolve);
+ conn.on("error", reject);
+ });
+ conn.write(JSON.stringify({ t: "ask", id: "ask-1", tool: "mcp__computer__click", input: { x: 1, y: 2 } }) + "\n");
+
+ const opened = await recorder.until((e) => e.type === "request.opened" && e.requestId === "ask-1");
+ expect(opened).toMatchObject({ requestType: "permission", tool: "mcp__computer__click" });
+ expect(opened).toHaveProperty("allowSession", true);
+ expect(opened).toHaveProperty("approvalScope", undefined);
+ await instance.adapter.respondToRequest("t-cloud-ask", "ask-1", { behavior: "deny" });
+
+ conn.end();
+ await instance.adapter.interruptTurn("t-cloud-ask");
+ await recorder.until((e) => e.type === "turn.completed");
+ });
+
it("resumes with --resume when a cursor exists and reports that session id", async () => {
await create();
const dump = join(scratch, "dump.json");
diff --git a/server/drivers/claude.ts b/server/drivers/claude.ts
index 95bdb015d1..ea8bedd6e8 100644
--- a/server/drivers/claude.ts
+++ b/server/drivers/claude.ts
@@ -1081,7 +1081,7 @@ export const ClaudeDriver: ProviderDriver<ClaudeConfig> = {
if (turn.integrations?.localComputer) {
const local = turn.integrations.localComputer;
mcpServers.computer = { command: local.command, args: local.args, env: local.env };
- if (!controlsHost) allowed.push("mcp__computer");
+ // Never pre-allowed: a computer call takes the turn's permission mode, cloud box or host.
}
const cwd = turn.cwd ?? homedir(), toolSearch = claudeToolSearchSetting(cwd, turnEnvironment);
// Pre-allowed, or the CLI's own ListAgents look-alike shadows it.
diff --git a/server/host/brief.test.ts b/server/host/brief.test.ts
index c70b1f9109..1af9b9c2f7 100644
--- a/server/host/brief.test.ts
+++ b/server/host/brief.test.ts
@@ -363,4 +363,16 @@ describe("the brief", () => {
expect(await s.brief.active("desktop", "UTC")).toEqual({ returned: false });
expect(s.card()).toBeUndefined();
});
+
+ it("names Outlook in read trouble and press records for Outlook emails", async () => {
+ const s = setup();
+ await s.brief.active("desktop", "UTC");
+ const outlookEmail: EmailHeader = { id: "o1", threadId: "conv-1", at: s.now() - 5 * MINUTE, from: "Bob <[email protected]>", subject: "Invoice", preview: "Due Friday", app: "outlook" };
+ await s.brief.report({ routine: {} as never, at: s.now(), picked: [{ email: outlookEmail, why: "Due Friday.", needsReply: true }], trouble: [{ app: "outlook", signedOut: true }] });
+ expect(s.shown()).toContain("Couldn't read Outlook");
+ expect(s.shown()).toContain("Reconnect Outlook in Connected apps.");
+ const records = s.brief.pressRecords(s.chief, { type: "draft_reply", payload: { messageId: "o1" } });
+ expect(records).toContain("[Records from Outlook.");
+ expect(records).toContain("Outlook draft");
+ });
});
diff --git a/server/host/brief.ts b/server/host/brief.ts
index 77dd003f07..66ead9fbb7 100644
--- a/server/host/brief.ts
+++ b/server/host/brief.ts
@@ -63,7 +63,7 @@ const stateSchema = z.object({
card: z.object({ day: z.string().max(10), botId: id, threadId: id, messageId: id, postedAt: at }).optional(),
/** Earlier days' cards: their Dismiss presses are still the brief's own. */
earlier: z.array(z.object({ threadId: id, messageId: id })).max(EARLIER_CARDS).optional(),
- important: z.array(z.object({ messageId: id, threadId: id, at, judgedAt: at, needsReply: z.boolean() })).max(MAX_ROWS),
+ important: z.array(z.object({ messageId: id, threadId: id, at, judgedAt: at, needsReply: z.boolean(), app: z.enum(["gmail", "outlook"]).optional() })).max(MAX_ROWS),
dismissed: z.array(z.object({ messageId: id, from: z.string().max(320), at })).max(MAX_ROWS),
preps: z.array(z.object({ key: id, at })).max(MAX_ROWS),
notified: z.array(z.string().max(600)).max(200).optional(),
@@ -289,7 +289,7 @@ export function createBrief(deps: BriefDeps) {
said: { text: words("brief.row.clash", { first: oneLine(first.title, 52), second: oneLine(second.title, 52) }), note: words("brief.row.clashNote", { first: moment(first.start, "clock", zone), second: moment(second.start, "clock", zone) }) },
}));
const troubleRows: NeedRow[] = (trouble ?? []).map((one) => {
- const app = one.app === "gmail" ? "Gmail" : "Google Calendar";
+ const app = one.app === "gmail" ? "Gmail" : one.app === "outlook" ? "Outlook" : "Google Calendar";
// Several accounts connected: the newest was read and refused, so Connected apps is where to look, not a later try.
const connectedApps = one.signedOut || one.severalAccounts === true;
return { key: `trouble:${one.app}`, text: w.couldNotRead(app), note: connectedApps ? w.reconnect(app) : w.tryAgainSoon,
@@ -331,9 +331,9 @@ export function createBrief(deps: BriefDeps) {
if (!session) return;
for (const row of missing.slice(0, 12)) {
try {
- const header = await session.message(row.messageId);
+ const header = row.app === "outlook" ? await session.outlookMessage?.(row.messageId) : await session.message(row.messageId);
if (header) headers.set(row.messageId, header);
- else state.important = state.important.filter((one) => one.messageId !== row.messageId);
+ else if (header === null) state.important = state.important.filter((one) => one.messageId !== row.messageId);
} catch {
return;
}
@@ -421,7 +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 {
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 }].slice(-MAX_ROWS);
+ 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);
}
/** What the checks found that needs no AI: today's meetings, clashes, reminders, other routines, trouble, and the
@@ -445,7 +445,7 @@ export function createBrief(deps: BriefDeps) {
/** 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> {
const address = deps.address();
- const open = liveImportant(now()).filter((row) => row.needsReply);
+ const open = liveImportant(now()).filter((row) => row.needsReply && row.app !== "outlook");
if (!session || !address || !open.length) return;
for (const row of open.slice(0, 10)) {
try {
@@ -565,11 +565,14 @@ export function createBrief(deps: BriefDeps) {
const row = typeof messageId === "string" ? state.important.find((one) => one.messageId === messageId) : undefined;
if (!row) return null;
const header = headers.get(row.messageId);
+ const outlook = row.app === "outlook";
return [
- recordsBlock("Gmail", [header
+ recordsBlock(outlook ? "Outlook" : "Gmail", [header
? `id ${clean(row.messageId, 120)} · thread ${clean(row.threadId, 120)} · from ${clean(header.from, 160)} · subject ${clean(header.subject, 200)} · preview ${clean(header.preview, 300)}`
: `id ${clean(row.messageId, 120)} · thread ${clean(row.threadId, 120)}`]),
- "Write a reply to this email as a Gmail draft in the same thread, to its sender, and leave it for the person to send. Do not send it.",
+ outlook
+ ? "Write a reply to this email as an Outlook draft replying to this message, to its sender, and leave it for the person to send. Do not send it."
+ : "Write a reply to this email as a Gmail draft in the same thread, to its sender, and leave it for the person to send. Do not send it.",
].join("\n");
}
diff --git a/server/host/check-prompts.test.ts b/server/host/check-prompts.test.ts
index 0ce4b6922f..78f01b68b4 100644
--- a/server/host/check-prompts.test.ts
+++ b/server/host/check-prompts.test.ts
@@ -27,6 +27,16 @@ describe("what a watch run is told", () => {
expect(prompt).toContain("Since the last check");
expect(prompt).not.toContain("JSON");
});
+
+ it("labels Outlook emails under Outlook records, separate from Gmail", () => {
+ const outlook: EmailHeader = { id: "o1", threadId: "c1", at: 0, from: "Bob <[email protected]>", subject: "Contract", preview: "Please sign", app: "outlook" };
+ const onlyOutlook = watchPrompt({ instructions: "Check mail.", items: { mail: [outlook], prep: [], runs: [] }, dismissedFrom: [] });
+ expect(onlyOutlook).toContain("[Records from Outlook.");
+ expect(onlyOutlook).not.toContain("[Records from Gmail.");
+ const both = watchPrompt({ instructions: "Check mail.", items: { mail: [email, outlook], prep: [], runs: [] }, dismissedFrom: [] });
+ expect(both).toContain("[Records from Gmail.");
+ expect(both).toContain("[Records from Outlook.");
+ });
});
describe("reading a watch run's answer", () => {
diff --git a/server/host/check-prompts.ts b/server/host/check-prompts.ts
index d5ddd78a74..42242e7703 100644
--- a/server/host/check-prompts.ts
+++ b/server/host/check-prompts.ts
@@ -24,8 +24,16 @@ function when(ms: number, timeZone: string | undefined): string {
}
}
+const emailLine = (email: EmailHeader): string =>
+ `id ${clean(email.id, 120)} · from ${clean(email.from, 160)} · subject ${clean(email.subject, 200)} · preview ${clean(email.preview, 300)}`;
+
export function emailRecords(emails: readonly EmailHeader[]): string {
- return recordsBlock("Gmail", emails.map((email) => `id ${clean(email.id, 120)} · from ${clean(email.from, 160)} · subject ${clean(email.subject, 200)} · preview ${clean(email.preview, 300)}`));
+ const gmail = emails.filter((email) => email.app !== "outlook");
+ const outlook = emails.filter((email) => email.app === "outlook");
+ return [
+ ...(gmail.length ? [recordsBlock("Gmail", gmail.map(emailLine))] : []),
+ ...(outlook.length ? [recordsBlock("Outlook", outlook.map(emailLine))] : []),
+ ].join("\n");
}
export function meetingRecords(items: CheckItems["prep"], timeZone: string | undefined): string {
@@ -47,7 +55,7 @@ export function watchPrompt(input: { instructions: string; items: CheckItems; ti
const { items } = input;
return [
input.instructions.trim(),
- "Your checks found what is below. Work only from these records and from reading the person's Gmail and Google Calendar.",
+ "Your checks found what is below. Work only from these records and from reading the person's Gmail, Outlook and Google Calendar.",
...(items.mail.length ? [
"New emails. Pick the ones the person must not miss: one that needs a reply from them, one from someone they meet today, or one with a deadline. Judge from the sender, subject and preview.",
emailRecords(items.mail),
diff --git a/server/host/proactive.ts b/server/host/proactive.ts
index a60bf1a85d..8f99639078 100644
--- a/server/host/proactive.ts
+++ b/server/host/proactive.ts
@@ -13,7 +13,7 @@ import type { Notification } from "../../shared/notification.ts";
import type { RequestAuth } from "../request-auth.ts";
import { writeFileAtomic } from "../atomic.ts";
import type { AppConfig } from "../config.ts";
-import { createConnectedReads, READ_APPS, type ReadApp } from "../connected-reads.ts";
+import { createConnectedReads, OUTLOOK_LIST_TOOL, READ_APPS, type ReadApp } from "../connected-reads.ts";
import { evaluateConnectorTools } from "../connector-verdict.ts";
import type { DecisionRow } from "../decision-log.ts";
import type { ProviderAdapter } from "../contracts.ts";
@@ -34,7 +34,7 @@ export { WATCH_INSTRUCTIONS, WATCH_NAME } from "./default-watch.ts";
export const WATCH_FILE = "watch.json";
/** The engines whose every tool use outside a run's allowlist reaches OpenMausBot's answerer and is refused there. */
const FENCED_ENGINES = new Set(["claudeAgent"]);
-const READ_SLUG: Record<ReadApp, string> = { gmail: "GMAIL_FETCH_EMAILS", googlecalendar: "GOOGLECALENDAR_EVENTS_LIST" };
+const READ_SLUG: Record<ReadApp, string> = { gmail: "GMAIL_FETCH_EMAILS", outlook: OUTLOOK_LIST_TOOL, googlecalendar: "GOOGLECALENDAR_EVENTS_LIST" };
const ACTIVE = new Set(["queued", "running", "waiting"]);
const MAX_HANDED = 50;
const watchSchema = z.object({
diff --git a/server/host/resume-check.ts b/server/host/resume-check.ts
new file mode 100644
index 0000000000..e8bd4e37ac
--- /dev/null
+++ b/server/host/resume-check.ts
@@ -0,0 +1,33 @@
+import { createHash } from "node:crypto";
+import { DEFAULT_REBUILD_BYTES, replayToolCalls, selectReplay } from "../context-rebuild.ts";
+import type { ContextMessage } from "../delta-context.ts";
+import type { BotRecord, Message } from "../store.ts";
+
+type Compaction = NonNullable<Parameters<typeof selectReplay>[1]>["compaction"];
+
+export interface ResumeCheckDeps {
+ directContext(bot: BotRecord, threadId: string, messages: Message[]): ContextMessage[];
+ latestCompaction(messages: readonly Message[]): Compaction;
+ context(): { rebuildBytes?: number; replayToolHistory?: boolean } | undefined;
+ everyBotRules(): string | undefined;
+ sectionPrompt(section: string | undefined): string;
+}
+
+export function createResumeCheck(deps: ResumeCheckDeps) {
+ const replayInputs = (bot: BotRecord, threadId: string, activeMessages: Message[], skip: ReadonlySet<string>) => {
+ const context = deps.directContext(bot, threadId, activeMessages);
+ const record = deps.latestCompaction(activeMessages);
+ const settings = deps.context();
+ const selection = selectReplay(context, { budgetBytes: settings?.rebuildBytes ?? DEFAULT_REBUILD_BYTES, excludedIds: skip, compaction: record, tools: replayToolCalls(activeMessages, settings) });
+ return { context, replayable: context.filter((m) => !skip.has(m.id)), record, selection };
+ };
+
+ // What a resumed session keeps from its launch; Codex reasserts model and provider on resume, but an in-flight turn and an omitted effort keep the prior selection.
+ const sessionConfigFor = (bot: BotRecord, driverKind: string, model: string | undefined, effort: string | undefined) => {
+ const rules = deps.everyBotRules()?.trim();
+ const persistentConfig = [bot.name, bot.title, bot.description, deps.sectionPrompt(bot.section), ...(rules ? [rules] : []), ...(driverKind === "codex" ? [model, effort ?? null] : [])];
+ return (soul: string | undefined): string => createHash("sha256").update(JSON.stringify([...persistentConfig, soul])).digest("hex").slice(0, 16);
+ };
+
+ return { replayInputs, sessionConfigFor };
+}
diff --git a/server/host/routine-checks.test.ts b/server/host/routine-checks.test.ts
index 10556740a3..8d9b973597 100644
--- a/server/host/routine-checks.test.ts
+++ b/server/host/routine-checks.test.ts
@@ -11,19 +11,21 @@ const MINUTE = 60_000;
const dirs: string[] = [];
afterEach(() => { for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true }); });
-function setup(options: { fenced?: boolean; may?: (app: ReadApp) => boolean } = {}) {
+function setup(options: { fenced?: boolean; may?: (app: ReadApp) => boolean; connected?: Partial<Record<ReadApp, boolean>> } = {}) {
const dir = mkdtempSync(join(tmpdir(), "omb-routine-checks-"));
dirs.push(dir);
let now = Date.parse("2026-10-22T08:00:00Z");
const inbox: EmailHeader[] = [];
+ const outlookInbox: EmailHeader[] = [];
const events: CalendarEvent[] = [];
const failing: Partial<Record<ReadApp, string>> = {};
const several = new Set<ReadApp>();
const calls: string[] = [];
const runs: RoutineRun[] = [];
const reports: CheckReport[] = [];
+ const connected: Partial<Record<ReadApp, boolean>> = options.connected ?? { gmail: true, googlecalendar: true };
const reads: ConnectedReads = {
- connected: async () => ({ gmail: true, googlecalendar: true }),
+ connected: async () => connected,
session: () => ({
async address() { calls.push("address"); if (failing.gmail) throw new SourceError("gmail", failing.gmail, several.has("gmail")); return "[email protected]"; },
async events() { calls.push("events"); if (failing.googlecalendar) throw new SourceError("googlecalendar", failing.googlecalendar, several.has("googlecalendar")); return events; },
@@ -33,6 +35,11 @@ function setup(options: { fenced?: boolean; may?: (app: ReadApp) => boolean } =
const found = inbox.filter((email) => email.at >= since).sort((a, b) => b.at - a.at);
return { emails: found.slice(0, limit), more: found.length > limit };
},
+ async outlookEmails(since, limit) {
+ calls.push("outlookEmails");
+ if (failing.outlook) throw new SourceError("outlook", failing.outlook, several.has("outlook"));
+ return outlookInbox.filter((email) => email.at >= since).sort((a, b) => b.at - a.at).slice(0, limit);
+ },
async message() { return null; },
async thread() { return []; },
}),
@@ -53,13 +60,18 @@ function setup(options: { fenced?: boolean; may?: (app: ReadApp) => boolean } =
inbox.push(email);
return email;
};
+ const outlookMail = (id: string, agoMinutes: number): EmailHeader => {
+ const email: EmailHeader = { id, threadId: `conv-${id}`, at: now - agoMinutes * MINUTE, from: `Sender ${id} <${id}@outlook.test>`, subject: `Outlook ${id}`, preview: "hello", app: "outlook" };
+ outlookInbox.push(email);
+ return email;
+ };
const meeting = (id: string, startsInMinutes: number): CalendarEvent => {
const event: CalendarEvent = { id, title: id, start: now + startsInMinutes * MINUTE, end: now + (startsInMinutes + 30) * MINUTE, allDay: false, status: "confirmed", selfDeclined: false,
attendees: [{ email: "[email protected]", self: true, organizer: true }, { email: "[email protected]", self: false, organizer: false }], ownedCalendar: true };
events.push(event);
return event;
};
- return { checks, routine, mail, meeting, failing, several, calls, runs, reports, inbox, sorted, advance: (ms: number) => { now += ms; }, now: () => now, file: join(dir, CHECKS_FILE) };
+ return { checks, routine, mail, outlookMail, meeting, failing, several, calls, runs, reports, inbox, outlookInbox, sorted, advance: (ms: number) => { now += ms; }, now: () => now, file: join(dir, CHECKS_FILE) };
}
const run = (key: string, status: RoutineRun["status"], deliver?: "brief"): RoutineRun => ({
@@ -219,4 +231,38 @@ describe("a routine's checks", () => {
expect((await s.checks.check(own, { manual: false })).run).toBeUndefined();
expect(s.reports).toEqual([]);
});
+
+ it("reads Outlook emails when Outlook is connected without Gmail, and settles them once committed", async () => {
+ const s = setup({ connected: { gmail: false, outlook: true, googlecalendar: false } });
+ s.outlookMail("o1", 5);
+ s.outlookMail("o2", 2);
+ const result = await s.checks.check(s.routine(), { manual: true });
+ expect(s.calls).toEqual(["outlookEmails"]);
+ expect(result.run?.key).toMatch(/^chk-/);
+ expect(result.run!.prompt).toContain("[Records from Outlook.");
+ expect(result.run!.prompt).toContain("id o2 · from Sender o2 <[email protected]>");
+ expect(s.checks.items(result.run!.key)?.mail.map((email) => email.id)).toEqual(["o2", "o1"]);
+ // A fenced run drafts only in Gmail, so an Outlook conversation is never a draft it may write.
+ expect(s.checks.mayDraft(result.run!.key, "conv-o2", "[email protected]")).toBe(false);
+ s.checks.commit(result.run!.key);
+ s.advance(15 * MINUTE);
+ expect((await s.checks.check(s.routine(), { manual: true })).run).toBeUndefined();
+ });
+
+ it("reads both Gmail and Outlook when both are connected, and keeps the cursor back if one fails", async () => {
+ const s = setup({ connected: { gmail: true, outlook: true, googlecalendar: false } });
+ s.mail("g1", 5);
+ s.failing.outlook = "Connected account is not ACTIVE";
+ const first = await s.checks.check(s.routine({ checks: ["mail"] }), { manual: false });
+ expect(first.run).toBeDefined();
+ expect(first.trouble).toBe("Couldn't read Outlook. Reconnect it in Connected apps.");
+ expect(s.reports.at(-1)!.trouble).toEqual([{ app: "outlook", signedOut: true }]);
+ s.checks.commit(first.run!.key);
+ // Outlook recovers on the next manual run; an email that arrived before the previous check is still read because the cursor stayed back.
+ delete s.failing.outlook;
+ s.outlookMail("o1", 4);
+ s.advance(15 * MINUTE);
+ const second = await s.checks.check(s.routine({ checks: ["mail"] }), { manual: true });
+ expect(s.checks.items(second.run!.key)?.mail.map((email) => email.id)).toEqual(["o1"]);
+ });
});
diff --git a/server/host/routine-checks.ts b/server/host/routine-checks.ts
index f82ed78c22..9617716113 100644
--- a/server/host/routine-checks.ts
+++ b/server/host/routine-checks.ts
@@ -45,7 +45,7 @@ const routineStateSchema = z.object({
runsCursor: at.optional(),
address: z.string().max(320).optional(),
pending: z.record(id, pendingSchema).optional(),
- failures: z.object({ gmail: failureSchema.optional(), googlecalendar: failureSchema.optional() }).optional(),
+ failures: z.object({ gmail: failureSchema.optional(), outlook: failureSchema.optional(), googlecalendar: failureSchema.optional() }).optional(),
});
const fileSchema = z.object({ version: z.literal(1), routines: z.record(id, routineStateSchema) });
type RoutineState = z.infer<typeof routineStateSchema>;
@@ -99,7 +99,7 @@ export interface RoutineChecksDeps {
}
const ACTIVE = new Set(["queued", "running", "waiting"]);
-const appName: Record<ReadApp, string> = { gmail: "Gmail", googlecalendar: "Google Calendar" };
+const appName: Record<ReadApp, string> = { gmail: "Gmail", outlook: "Outlook", googlecalendar: "Google Calendar" };
const addressOf = (from: string): string => (/<([^<>\s]+)>/.exec(from)?.[1] ?? from).trim().toLowerCase();
/** A read that failed; `severalAccounts` when it named one of the app's several connected accounts. */
@@ -264,45 +264,77 @@ export function createRoutineChecks(deps: RoutineChecksDeps): RoutineChecks & {
}
}
- if (checks.includes("mail") && readable("gmail")) {
- try {
+ if (checks.includes("mail")) {
+ const readGmail = readable("gmail");
+ const readOutlook = readable("outlook") && typeof session.outlookEmails === "function";
+ if (readGmail || readOutlook) {
const since = emailSince({ now: at, emailCursor: entry.mailCursor });
- const { emails, more } = await session.emails(since, MAIL_READ_LIMIT);
- succeeded(entry, "gmail");
- const judged = new Set([...(entry.judged ?? []), ...held]);
- const plan = planMail({ now: at, emails, judged });
- const waiting = plan.waiting.length;
- const advanced = waiting || more ? undefined : at;
- const helpers = brief && deps.inbox?.ready() === true;
- if (helpers) report.helpersSort = true;
- const picked = helpers && plan.batch.length ? await deps.inbox!.triage(plan.batch, deps.dismissedFrom()) : null;
- if (picked) {
- // Sorted with no AI turn: every email of the batch is judged, and the picks become brief rows.
- report.picked = picked.flatMap((pick) => {
- const email = plan.batch.find((one) => one.id === pick.id);
- return email ? [{ email, why: pick.why, ...(pick.whyText ? { whyText: pick.whyText } : {}), needsReply: pick.needsReply }] : [];
- });
- entry.judged = keepNewest([...new Set([...(entry.judged ?? []), ...plan.batch.map((email) => email.id), ...plan.quiet.map((email) => email.id)])], MAX_JUDGED);
- if (plan.batch.length) deps.sorted?.(routine.id, plan.batch.length);
- // Mail an earlier run still holds keeps the cursor back, so a failed run's mail is read again.
- const heldMail = Object.values(entry.pending ?? {}).some((one) => one.mail.length > 0);
- if (advanced !== undefined && !heldMail) entry.mailCursor = advanced;
- } else if (helpers && plan.batch.length && !aiAllowed) {
- // The helper models did not answer this time and no fenced AI may sort: the mail waits for the next check.
- } else if (plan.batch.length && aiAllowed) {
- items.mail = plan.batch;
- pending.mail = [...plan.batch.map((email) => email.id), ...plan.quiet.map((email) => email.id)];
- pending.replies = plan.batch.map((email) => ({ threadId: email.threadId, to: addressOf(email.from) }));
- if (advanced !== undefined) pending.mailCursor = advanced;
- } else {
- if (plan.batch.length && !context.hold) report.unfenced = true;
- const sorted = plan.batch.length && context.hold ? [] : [...plan.batch, ...plan.quiet];
- entry.judged = keepNewest([...new Set([...(entry.judged ?? []), ...sorted.map((email) => email.id)])], MAX_JUDGED);
- if (advanced !== undefined && !(plan.batch.length && context.hold)) entry.mailCursor = advanced;
+ const found: EmailHeader[] = [];
+ let more = false;
+ let mailRead = false;
+ let mailFailed = false;
+ if (readGmail) {
+ try {
+ const gmail = await session.emails(since, MAIL_READ_LIMIT);
+ succeeded(entry, "gmail");
+ found.push(...gmail.emails);
+ more = more || gmail.more;
+ mailRead = true;
+ } catch (error) {
+ trouble.push(failed(entry, "gmail", error));
+ mailFailed = true;
+ }
+ }
+ if (readOutlook) {
+ try {
+ const outlook = await session.outlookEmails!(since, MAIL_READ_LIMIT);
+ succeeded(entry, "outlook");
+ found.push(...outlook);
+ more = more || outlook.length >= MAIL_READ_LIMIT;
+ mailRead = true;
+ } catch (error) {
+ trouble.push(failed(entry, "outlook", error));
+ mailFailed = true;
+ }
+ }
+ const skippedMail = (apps?.gmail === true && deps.mayRead(routine.botId, "gmail") && !readGmail)
+ || (apps?.outlook === true && deps.mayRead(routine.botId, "outlook") && typeof session.outlookEmails === "function" && !readOutlook);
+ if (mailRead) {
+ const emails = [...new Map(found.map((email) => [email.id, email])).values()].sort((a, b) => b.at - a.at);
+ const judged = new Set([...(entry.judged ?? []), ...held]);
+ const plan = planMail({ now: at, emails, judged });
+ const waiting = plan.waiting.length;
+ const advanced = waiting || more || mailFailed || skippedMail ? undefined : at;
+ const helpers = brief && deps.inbox?.ready() === true;
+ if (helpers) report.helpersSort = true;
+ const picked = helpers && plan.batch.length ? await deps.inbox!.triage(plan.batch, deps.dismissedFrom()) : null;
+ if (picked) {
+ // Sorted with no AI turn: every email of the batch is judged, and the picks become brief rows.
+ report.picked = picked.flatMap((pick) => {
+ const email = plan.batch.find((one) => one.id === pick.id);
+ return email ? [{ email, why: pick.why, ...(pick.whyText ? { whyText: pick.whyText } : {}), needsReply: pick.needsReply }] : [];
+ });
+ entry.judged = keepNewest([...new Set([...(entry.judged ?? []), ...plan.batch.map((email) => email.id), ...plan.quiet.map((email) => email.id)])], MAX_JUDGED);
+ if (plan.batch.length) deps.sorted?.(routine.id, plan.batch.length);
+ // Mail an earlier run still holds keeps the cursor back, so a failed run's mail is read again.
+ const heldMail = Object.values(entry.pending ?? {}).some((one) => one.mail.length > 0);
+ if (advanced !== undefined && !heldMail) entry.mailCursor = advanced;
+ } else if (helpers && plan.batch.length && !aiAllowed) {
+ // The helper models did not answer this time and no fenced AI may sort: the mail waits for the next check.
+ } else if (plan.batch.length && aiAllowed) {
+ items.mail = plan.batch;
+ pending.mail = [...plan.batch.map((email) => email.id), ...plan.quiet.map((email) => email.id)];
+ // The only draft a fenced run may write is a Gmail one, so an Outlook email gets no reply slot.
+ pending.replies = plan.batch.filter((email) => email.app !== "outlook").map((email) => ({ threadId: email.threadId, to: addressOf(email.from) }));
+ if (advanced !== undefined) pending.mailCursor = advanced;
+ } else {
+ if (plan.batch.length && !context.hold) report.unfenced = true;
+ const sorted = plan.batch.length && context.hold ? [] : [...plan.batch, ...plan.quiet];
+ entry.judged = keepNewest([...new Set([...(entry.judged ?? []), ...sorted.map((email) => email.id)])], MAX_JUDGED);
+ if (advanced !== undefined && !(plan.batch.length && context.hold)) entry.mailCursor = advanced;
+ }
+ if (brief && (waiting || more)) report.waiting = more ? true : waiting;
}
- if (brief && (waiting || more)) report.waiting = more ? true : waiting;
- } catch (error) {
- trouble.push(failed(entry, "gmail", error));
}
}
diff --git a/server/hosted-desktop.e2e.test.ts b/server/hosted-desktop.e2e.test.ts
index aa339b1cd4..e7133f9a1d 100644
--- a/server/hosted-desktop.e2e.test.ts
+++ b/server/hosted-desktop.e2e.test.ts
@@ -135,7 +135,7 @@ it("keeps the bot's own engine on the cloud computer, and a failed place never b
expect(computer.env.OMB_HARNESS_URL).toBe(fixture.info.url);
expect(JSON.stringify(sent)).not.toContain(BOAT_TOKEN);
expect(Object.keys(sent.env).filter(key => /BOAT|BOX_TOKEN|OMB_CLOUD/.test(key))).toEqual([]);
- expect(sent.argv[sent.argv.indexOf("--allowedTools") + 1].split(",")).toContain("mcp__computer");
+ expect(sent.argv[sent.argv.indexOf("--allowedTools") + 1].split(",")).not.toContain("mcp__computer");
const client = mcpClient(computer);
try {
expect((await client.request("initialize", { protocolVersion: "2024-11-05", capabilities: {}, clientInfo: { name: "fixture", version: "1" } })).result.serverInfo.name).toBe("openmausbot-computer");
diff --git a/server/index.ts b/server/index.ts
index 5e728a7391..50384d56ba 100644
--- a/server/index.ts
+++ b/server/index.ts
@@ -13,8 +13,8 @@ import { ToolResults, TOOL_RESULT_MAX_CHARS } from "./tool-results.ts";
import { basename, join } from "node:path";
import { authorizeExternalRuntime, externalRuntimeIsActive, type ExternalRuntimeGrant } from "./external-runtime.ts";
import { z } from "zod";
-import { selectReplay, replayToolCalls, DEFAULT_REBUILD_BYTES } from "./context-rebuild.ts";
-import { claudeCompactionDisabled, createConversationCompaction } from "./host/conversation-compaction.ts";
+import { DEFAULT_REBUILD_BYTES } from "./context-rebuild.ts";
+import { claudeCompactionDisabled, createConversationCompaction } from "./host/conversation-compaction.ts"; import { createResumeCheck } from "./host/resume-check.ts";
import { compactionReading } from "./context-budget.ts";
import { autoCompactWindow } from "./drivers/claude.ts";
import { RoomContextTracker, roomResetNote } from "./room-context.ts";
@@ -328,8 +328,8 @@ import { narrateTool, toUtterances } from "./tts/speech-text.ts";
import { createTtsRoutes } from "./routes/tts.ts";
import { turnStartLogLine } from "./turn-log.ts";
import { TurnStops, outwardActions, stoppedTurnOutcome, turnEvidence } from "./turn-outcome.ts";
-import { buildRecoveryText, buildTurnContext, engineIsFresh, replaysNatively } from "./turn-context.ts";
-import { Handoffs, handedStateUsable, isContextMessage, recordHanded, renderUnseen, sessionStart, unseenMessages, withUnseenMessages, type ContextMessage } from "./delta-context.ts"; import { isFreshStart, sinceFreshStart } from "./fresh-start.ts";
+import { buildRecoveryText, buildTurnContext, replaysNatively } from "./turn-context.ts"; import { resumePlan } from "./resume-plan.ts";
+import { Handoffs, isContextMessage, recordHanded, renderUnseen, sessionStart, withUnseenMessages, type ContextMessage } from "./delta-context.ts"; import { isFreshStart, sinceFreshStart } from "./fresh-start.ts";
import { extractReplayImages, extractTurnImages, nativeClips, turnMedia, videoFramesWithin } from "./turn-images.ts";
import { callTitleExcerpt } from "./thread-title.ts";
import { generateThreadTitle } from "./thread-title-generate.ts";
@@ -6964,6 +6964,7 @@ function peerReplayText(m: Message, name: string, text: string): string {
}
const { lineLabels, personPrompt, routineRunNote } = createLineLabels({ sharedChat: (threadId) => sharedMembership() && !store.groupByThread(threadId) && audienceMember(teamHost.audienceOf(threadId)) === null, userName: userNameFor, teamRole: (key) => (teamOwners.people?.list() ?? []).find((one) => personKey({ id: "", email: one.email }) === key)?.role, routineName: (threadId) => { const run = routines?.runForThread(threadId); return routines?.listRoutines().find((one) => one.id === run?.routineId)?.name; } });
+const { replayInputs, sessionConfigFor } = createResumeCheck({ directContext, latestCompaction, context: () => cfg.context, everyBotRules: () => cfg.everyBotRules, sectionPrompt: sectionContextSystemPrompt });
const compactConversation = createConversationCompaction({
store, context: () => cfg.context, directContext, latestCompaction,
nativeCompactTokens: (instance, model) => nativeCompactTokens(instance, model),
@@ -7704,37 +7705,20 @@ async function beginTurn(
if ((m.roomRequest.phase === "request" && m.roomRequest.id === opts.coordination.id) ||
(m.roomRequest.phase === "result" && coordinationChildren?.has(m.roomRequest.id))) skipTranscript.add(m.id);
}
- const context = directContext(bot, threadId, activeMessages);
+ const { context, replayable, record, selection } = replayInputs(bot, threadId, activeMessages, skipTranscript);
const contextOrder = context.map(m => m.id);
- const replayable = context.filter(m => !skipTranscript.has(m.id));
- const record = latestCompaction(activeMessages);
- const selection = selectReplay(context, { budgetBytes: cfg.context?.rebuildBytes ?? DEFAULT_REBUILD_BYTES, excludedIds: skipTranscript, compaction: record, tools: replayToolCalls(activeMessages, cfg.context) });
const transcript = selection.transcript.map(({ role, text }) => ({ role, text }));
- const contextReset = selection.compacted > 0 && record?.id !== task.appliedCompactionId;
- if (contextReset) store.patchTask(bot.id, threadId, { resumeCursors: {} });
// Engines keep a session in the folder it started in, so a thread that follows its bot to the bot's working folder starts a new one there.
- const followed = folderToFollow(bot, threadId, task.cwd, { worksInFolders: supportsWorkspaceFiles(instance.driverKind), keepsPrivateFolder: guestConfined || cloudGuestOpened(threadId) }); if (followed) store.patchTask(bot.id, threadId, { cwd: followed, resumeCursors: {} });
-
- // After a rewind the native session still holds the abandoned branch; the flag clears only once dispatched, or a failed dispatch loses the next attempt's history.
- const rewound = Boolean(task.rewound);
- const externalContextMarker = isExternalContextMarker(task.lastInstanceId)
- ? task.lastInstanceId
- : undefined;
- const fresh =
- !rewound &&
- !externalContextMarker &&
- engineIsFresh({ instanceId, lastInstanceId: task.lastInstanceId, resumeCursors: task.resumeCursors, transcript: replayable });
+ const followed = folderToFollow(bot, threadId, task.cwd, { worksInFolders: supportsWorkspaceFiles(instance.driverKind), keepsPrivateFolder: guestConfined || cloudGuestOpened(threadId) });
const strictResume = instance.adapter.capabilities.strictResume === true;
- const cursor = task.resumeCursors[instanceId];
- const handed = strictResume && !rewound && !contextReset && !fresh && !externalContextMarker && cursor !== undefined
- ? task.handedMessages?.[instanceId] : undefined;
- const unseen = handed && handedStateUsable(handed, cursor, contextOrder) ? unseenMessages(replayable, contextOrder, handed) : undefined;
- const externalUpdate = Boolean(opts?.coordination?.resumed || unseen?.some((m) => m.keep));
- // What a resumed session keeps from its launch; Codex reasserts model and provider on resume, but an in-flight turn and an omitted effort keep the prior selection.
- const persistentConfig = [bot.name, bot.title, bot.description, sectionContextSystemPrompt(bot.section), ...(cfg.everyBotRules?.trim() ? [cfg.everyBotRules.trim()] : []),
- ...(instance.driverKind === "codex" ? [model, effort ?? null] : [])];
- const sessionConfig = (soul: string | undefined) =>
- createHash("sha256").update(JSON.stringify([...persistentConfig, soul])).digest("hex").slice(0, 16);
+ const externalContextMarker = isExternalContextMarker(task.lastInstanceId) ? task.lastInstanceId : undefined;
+ const resuming = resumePlan({ task, instanceId, strictResume, compacted: selection.compacted, recordId: record?.id, folderChanged: followed !== undefined,
+ contextOrder, replayable, externalMarker: externalContextMarker, coordinationResumed: Boolean(opts?.coordination?.resumed), effort });
+ // After a rewind the native session still holds the abandoned branch; the flag clears only once dispatched, or a failed dispatch loses the next attempt's history.
+ const { contextReset, rewound, fresh, unseen, externalUpdate } = resuming;
+ if (contextReset) store.patchTask(bot.id, threadId, { resumeCursors: {} });
+ if (followed) store.patchTask(bot.id, threadId, { cwd: followed, resumeCursors: {} });
+ const sessionConfig = sessionConfigFor(bot, instance.driverKind, model, effort);
const plannedConfig = sessionConfig(bot.soul);
const skillAuthoring = skillAuthoringEnabled(cfg) && agentsMounted;
const skillCommandText = supportsWorkspaceFiles(instance.driverKind)
@@ -7750,9 +7734,7 @@ async function beginTurn(
? extractReplayImages(selection.inline, turnImages, {}, turnVideos)
: { transcript: selection.inline, images: [] };
const decideContext = (config: string) => {
- // A Codex thread keeps the last effort it was sent and no turn can clear it, so one holding a level is rebuilt, not resumed.
- const effortHeld = !effort && typeof handed?.effort === "string";
- const handedStale = Boolean(handed && (!unseen || effortHeld || (externalUpdate && handed.config !== config)));
+ const handedStale = resuming.stale(config);
const { block: unseenBlock, placed } = unseen && !handedStale ? renderUnseen(unseen) : { block: "", placed: [] };
const { turnText: contextTurnText, resume } = buildTurnContext({
text: userTurnText,
@@ -11012,7 +10994,7 @@ function connectorThread(botId: string, threadId: string) {
}
function directChatOf(botId: string, threadId: string): boolean { const source = connectorThread(botId, threadId); return source !== null && !source.group; }
function waitTurnChecks(capability: InternalCapability, sender: BotRecord): Pick<WaitRouteContext, "sourceRefusal" | "assignmentId" | "continuationAllowed" | "hostRefusal" | "guest" | "peer" | "elsewhere"> { const { threadId } = capability, place = () => { const turn = turnPlaces.get(threadId); return turn?.botId === sender.id ? turn.place : null; }, assignmentId = () => handedAssignment(capability.roomHandoffId ?? directCoordinationSettlers.get(capability.generation)?.nodeId, (id) => coordinator.node(id)), continuationAllowed = waitContinuationCheck(capability, { active: internalCapabilityIsActive, request: (id) => directRequestOwners.get(id), run: activeRoutineRunForThread, store });
- return { assignmentId, continuationAllowed, sourceRefusal: (op, assignment) => { const source = connectorThread(sender.id, threadId); return waitSourceRefusal({ owned: source !== null, room: Boolean(source?.group), depth: capability.depth, handedOff: Boolean(capability.roomHandoffId), routineRun: Boolean(activeRoutineRunForThread(threadId)), waitContinuation: continuationAllowed(), outsideDriven: outsideDrivenThread(threadId), personStarted: turnOrigin(capability).kind === "user", guest: cloudGuestDriven(threadId), op, assignmentId: assignment }); }, hostRefusal: () => hostWaitRefusal({ cloudHome: Boolean(CLOUD_HOME), hosted: HOSTED_WORKSPACE, guest: cloudGuestDriven(threadId), place: place() }), guest: () => cloudGuestDriven(threadId), peer: (name) => findWaitPeer(reachablePeers(store.bots, sender), sender.id, name), elsewhere: placesElsewhere.explain }; }
+ return { assignmentId, continuationAllowed, sourceRefusal: (op, assignment) => { const source = connectorThread(sender.id, threadId); return waitSourceRefusal({ owned: source !== null, room: Boolean(source?.group), depth: capability.depth, handedOff: Boolean(capability.roomHandoffId), routineRun: Boolean(activeRoutineRunForThread(threadId)), waitContinuation: continuationAllowed(), outsideDriven: outsideDrivenThread(threadId), personStarted: turnOrigin(capability).kind === "user", guest: cloudGuestDriven(threadId), op, assignmentId: assignment, cloudHome: Boolean(CLOUD_HOME) }); }, hostRefusal: () => hostWaitRefusal({ cloudHome: Boolean(CLOUD_HOME), hosted: HOSTED_WORKSPACE, guest: cloudGuestDriven(threadId), place: place() }), guest: () => cloudGuestDriven(threadId), peer: (name) => findWaitPeer(reachablePeers(store.bots, sender), sender.id, name), elsewhere: placesElsewhere.explain }; }
/** Read fresh every time; a line stamped via the HTTP API does not count, so a bot cannot re-arm the ceiling it just spent. */
function lastHumanRoomMessageAt(group: GroupRecord): number | undefined {
diff --git a/server/read-and-draft.test.ts b/server/read-and-draft.test.ts
index 2023926f75..586cce94d2 100644
--- a/server/read-and-draft.test.ts
+++ b/server/read-and-draft.test.ts
@@ -28,11 +28,16 @@ describe("what a read-and-draft run may do through the connected-apps relay", ()
it("reads Gmail and Calendar, describes tools, and nothing else", () => {
const never = () => false;
expect(refusedConnectorCall(call("GMAIL_FETCH_EMAILS"), never)).toBeNull();
+ expect(refusedConnectorCall(call("OUTLOOK_LIST_MESSAGES"), never)).toBeNull();
+ expect(refusedConnectorCall(call("OUTLOOK_GET_MESSAGE"), never)).toBeNull();
expect(refusedConnectorCall(call("GOOGLECALENDAR_EVENTS_LIST"), never)).toBeNull();
expect(refusedConnectorCall({ method: "tools/call", params: { name: "COMPOSIO_SEARCH_TOOLS", arguments: {} } }, never)).toBeNull();
expect(refusedConnectorCall({ method: "initialize" }, never)).toBeNull();
expect(refusedConnectorCall(call("GMAIL_SEND_EMAIL"), never)).toBe("GMAIL_SEND_EMAIL");
expect(refusedConnectorCall(call("GMAIL_DELETE_MESSAGE"), never)).toBe("GMAIL_DELETE_MESSAGE");
+ expect(refusedConnectorCall(call("OUTLOOK_SEND_EMAIL"), never)).toBe("OUTLOOK_SEND_EMAIL");
+ expect(refusedConnectorCall(call("OUTLOOK_DELETE_MESSAGE"), never)).toBe("OUTLOOK_DELETE_MESSAGE");
+ expect(refusedConnectorCall(call("OUTLOOK_REPLY_EMAIL"), never)).toBe("OUTLOOK_REPLY_EMAIL");
expect(refusedConnectorCall(call("GOOGLECALENDAR_CREATE_EVENT"), never)).toBe("GOOGLECALENDAR_CREATE_EVENT");
expect(refusedConnectorCall(call("SLACK_FETCH_CONVERSATION_HISTORY"), never)).toBe("SLACK_FETCH_CONVERSATION_HISTORY");
expect(refusedConnectorCall({ method: "tools/call", params: { name: "COMPOSIO_REMOTE_WORKBENCH", arguments: { code: "x" } } }, never)).toBe("COMPOSIO_PROXY_EXECUTE");
diff --git a/server/read-and-draft.ts b/server/read-and-draft.ts
index 57dbb4ada7..78443e7c7e 100644
--- a/server/read-and-draft.ts
+++ b/server/read-and-draft.ts
@@ -44,7 +44,7 @@ const ROUTES: ReadonlySet<string> = new Set([
/** Composio's meta tools that only describe tools; connecting an account waits for a person, so it is not here. */
const DISCOVERY: ReadonlySet<string> = new Set(["COMPOSIO_SEARCH_TOOLS", "COMPOSIO_GET_TOOL_SCHEMAS"]);
/** A read verb does not make a tool safe here: a read on another app can take a URL and carry the run's text to it. */
-const READ_APPS = ["GMAIL_", "GOOGLECALENDAR_"] as const;
+const READ_APPS = ["GMAIL_", "OUTLOOK_", "GOOGLECALENDAR_"] as const;
export const DRAFT_TOOL = "GMAIL_CREATE_EMAIL_DRAFT";
/** Fields of a draft that would add someone the reply is not to. */
const OTHER_RECIPIENTS = ["cc", "bcc", "extra_recipients", "recipients"] as const;
diff --git a/server/resume-plan.ts b/server/resume-plan.ts
new file mode 100644
index 0000000000..d4add5273c
--- /dev/null
+++ b/server/resume-plan.ts
@@ -0,0 +1,37 @@
+import { handedStateUsable, unseenMessages, type ContextMessage, type HandedState } from "./delta-context.ts";
+import { canResume, engineIsFresh } from "./turn-context.ts";
+
+export interface ResumePlanInput {
+ task: { resumeCursors: Record<string, unknown>; lastInstanceId?: string; handedMessages?: Record<string, HandedState>; rewound?: boolean; appliedCompactionId?: string };
+ instanceId: string;
+ strictResume: boolean;
+ compacted: number;
+ recordId: string | undefined;
+ folderChanged: boolean;
+ contextOrder: readonly string[];
+ replayable: Array<ContextMessage>;
+ externalMarker: string | undefined;
+ coordinationResumed: boolean;
+ effort: string | undefined;
+}
+
+export function resumePlan(input: ResumePlanInput) {
+ const { task, instanceId, externalMarker } = input;
+ const contextReset = input.compacted > 0 && input.recordId !== task.appliedCompactionId;
+ const cursors = contextReset || input.folderChanged ? {} : task.resumeCursors;
+ const rewound = Boolean(task.rewound);
+ const fresh = !rewound && !externalMarker && engineIsFresh({ instanceId, lastInstanceId: task.lastInstanceId, resumeCursors: cursors, transcript: input.replayable });
+ const cursor = cursors[instanceId];
+ const handed = input.strictResume && !rewound && !contextReset && !fresh && !externalMarker && cursor !== undefined ? task.handedMessages?.[instanceId] : undefined;
+ const unseen = handed && handedStateUsable(handed, cursor, input.contextOrder) ? unseenMessages(input.replayable, input.contextOrder, handed) : undefined;
+ const externalUpdate = Boolean(input.coordinationResumed || unseen?.some((m) => m.keep));
+ /** A Codex thread keeps the last effort it was sent and no turn can clear it, so one holding a level is rebuilt, not resumed. */
+ const stale = (config: string): boolean => {
+ const effortHeld = !input.effort && typeof handed?.effort === "string";
+ return Boolean(handed && (!unseen || effortHeld || (externalUpdate && handed.config !== config)));
+ };
+ return {
+ contextReset, rewound, fresh, cursor, handed, unseen, externalUpdate, stale,
+ resumes: (config: string): boolean => canResume({ rewound, fresh: fresh || contextReset, externallyUpdated: Boolean(externalMarker) || stale(config) }),
+ };
+}
diff --git a/server/routes/waits.test.ts b/server/routes/waits.test.ts
index f7cae2a0ad..a6ad5200dc 100644
--- a/server/routes/waits.test.ts
+++ b/server/routes/waits.test.ts
@@ -203,6 +203,19 @@ describe("the waits route", () => {
expect(waitSourceRefusal({ ...handed, owned: false, op: "create" })).toBe(WAIT_MESSAGES.notYours);
});
+ it("off a Cloud, lets the person's own request make its wait in a conversation outside work reached, and nothing else", () => {
+ const person = { owned: true, room: false, depth: 0, handedOff: false, routineRun: false, outsideDriven: true, personStarted: true, guest: false, cloudHome: false };
+ const handed = { ...person, depth: 1, assignmentId: "node-1", op: "create" as const };
+ expect(waitSourceRefusal(person)).toBeNull();
+ expect(waitSourceRefusal(handed)).toBeNull();
+ expect(waitSourceRefusal({ ...handed, op: "cancel" })).toBe(WAIT_MESSAGES.handedStop);
+ for (const other of [{ personStarted: false }, { routineRun: true }, { cloudHome: true }, { cloudHome: undefined }]) {
+ expect(waitSourceRefusal({ ...person, ...other }), JSON.stringify(other)).toBe(WAIT_MESSAGES.notPerson);
+ expect(waitSourceRefusal({ ...handed, ...other }), JSON.stringify(other)).toBe(WAIT_MESSAGES.notPerson);
+ }
+ expect(waitSourceRefusal({ ...handed, assignmentId: undefined })).toBe(WAIT_MESSAGES.notPerson);
+ });
+
it("lets a proved wait continuation create the next wait in its own direct chat", () => {
const continuation = { owned: true, room: false, depth: 0, handedOff: false, routineRun: true, outsideDriven: true, personStarted: false, guest: false, waitContinuation: true, op: "create" as const };
expect(waitSourceRefusal(continuation)).toBeNull();
diff --git a/server/routes/waits.ts b/server/routes/waits.ts
index 596ca59b1a..b99997f6aa 100644
--- a/server/routes/waits.ts
+++ b/server/routes/waits.ts
@@ -125,11 +125,15 @@ export function parseWaitRequest(body: unknown, home: string): { ok: true; reque
export function waitSourceRefusal(turn: {
owned: boolean; room: boolean; depth: number; handedOff: boolean; routineRun: boolean; outsideDriven: boolean; personStarted: boolean; guest: boolean;
op?: "create" | "cancel"; assignmentId?: string; waitContinuation?: boolean;
+ /** A Cloud home confines outside work; off a Cloud its record only stops a level travelling (outside-lineage.ts). */
+ cloudHome?: boolean;
}): string | null {
if (!turn.owned) return WAIT_MESSAGES.notYours;
if (turn.room) return WAIT_MESSAGES.room;
if (turn.waitContinuation && turn.routineRun && turn.depth === 0 && !turn.handedOff && !turn.guest && turn.op === "create") return null;
- if (turn.routineRun || turn.outsideDriven) return WAIT_MESSAGES.notPerson;
+ // Off a Cloud, mail read or work handed on from such a conversation does not undo the person's own request that started this turn.
+ const outside = turn.outsideDriven && (turn.cloudHome !== false || !turn.personStarted);
+ if (turn.routineRun || outside) return WAIT_MESSAGES.notPerson;
if (turn.depth > 0 || turn.handedOff) {
if (!turn.personStarted || turn.guest || !turn.assignmentId) return WAIT_MESSAGES.notPerson;
return turn.op === "create" ? null : WAIT_MESSAGES.handedStop;
diff --git a/server/turn-context.ts b/server/turn-context.ts
index d3c9656940..cb37a3d713 100644
--- a/server/turn-context.ts
+++ b/server/turn-context.ts
@@ -54,12 +54,16 @@ export function buildRecoveryText(input: {
].join("\n");
}
+/** Whether a turn carries on its engine's session rather than rebuilding it from the transcript. */
+export const canResume = (input: Pick<TurnContextInput, "rewound" | "fresh" | "externallyUpdated">): boolean =>
+ !input.rewound && !input.fresh && !input.externallyUpdated;
+
export function buildTurnContext(input: TurnContextInput): {
turnText: string;
resume: boolean;
} {
- const { text, transcript, rewound, fresh, externallyUpdated, replaysNatively } = input;
- const resume = !rewound && !fresh && !externallyUpdated;
+ const { text, transcript, rewound, externallyUpdated, replaysNatively } = input;
+ const resume = canResume(input);
const replay = !resume && !replaysNatively && transcript.length > 0;
if (!replay) return { turnText: text, resume };
return {
diff --git a/src/components/AttachmentPreview.test.ts b/src/components/AttachmentPreview.test.ts
index c922a937cd..031c131193 100644
--- a/src/components/AttachmentPreview.test.ts
+++ b/src/components/AttachmentPreview.test.ts
@@ -25,6 +25,7 @@ import {
useLocalFileSave,
wrappedImageIndex,
} from "./AttachmentPreview";
+import { messageFileOutsideWorkspace } from "./outside-workspace-probe";
describe("attachment image navigation", () => {
it("wraps previous and next navigation", () => {
@@ -199,6 +200,23 @@ describe("Show in folder for a file outside the workspace", () => {
});
});
+describe("messageFileOutsideWorkspace", () => {
+ it("maps an outside_workspace refusal to true and an openable path to false", async () => {
+ const refused = () => new Response(JSON.stringify({ code: "outside_workspace" }), { status: 403, headers: { "content-type": "application/json" } });
+ const opened = () => new Response(new Blob(["x"]), { status: 200, headers: { "content-type": "text/plain" } });
+ vi.stubGlobal("fetch", vi.fn()
+ .mockImplementationOnce(async () => refused())
+ .mockImplementationOnce(async () => opened()));
+ const message = { threadId: "t", messageId: "m" };
+ try {
+ await expect(messageFileOutsideWorkspace("C:\\outside\\a.js", message, new AbortController().signal)).resolves.toBe(true);
+ await expect(messageFileOutsideWorkspace("inside/a.js", message, new AbortController().signal)).resolves.toBe(false);
+ } finally {
+ vi.unstubAllGlobals();
+ }
+ });
+});
+
describe("a failed save", () => {
it("explains a file outside the working folder instead of echoing the server", () => {
const server = "the linked file is outside this conversation's workspace";
diff --git a/src/components/AttachmentPreview.tsx b/src/components/AttachmentPreview.tsx
index a313107cd3..99a1a46213 100644
--- a/src/components/AttachmentPreview.tsx
+++ b/src/components/AttachmentPreview.tsx
@@ -33,6 +33,7 @@ import {
} from "@/lib/composer-attachments";
import { cn } from "@/lib/cn";
import { t } from "@/lib/i18n";
+import { revealBridge, revealHostPath, revealProblemText, REVEALABLE_PATH } from "@/lib/reveal-host-path";
import { serverErrorText } from "@/lib/server-error";
import { CopyImageButton } from "./CopyImageButton";
import { FilePreviewButton } from "./FilePreviewButton";
@@ -416,12 +417,6 @@ export function MessageFolderFiles({ folderPath, listing, message }: {
);
}
-const REVEALABLE_PATH = /^(?:\/(?!\/)|[a-zA-Z]:[\\/])/;
-function revealBridge(): NonNullable<Window["ogb"]>["revealInFolder"] {
- const ogb = typeof window === "undefined" ? undefined : window.ogb;
- return ogb?.remoteClient?.active ? undefined : ogb?.revealInFolder;
-}
-
export function OutsideWorkspaceFile({ filePath }: { filePath: string }) {
const [problem, setProblem] = useState("");
const reveal = revealBridge();
@@ -434,13 +429,9 @@ export function OutsideWorkspaceFile({ filePath }: { filePath: string }) {
}
const show = async () => {
setProblem("");
- try {
- const result = await reveal(filePath);
- if (result === "missing") setProblem(t("attach.revealMissing"));
- else if (result !== "shown") setProblem(t("attach.revealFailed"));
- } catch {
- setProblem(t("attach.revealFailed"));
- }
+ const result = await revealHostPath(filePath);
+ const text = revealProblemText(result);
+ if (text) setProblem(text);
};
return (
<>
diff --git a/src/components/ChatMarkdown.test.ts b/src/components/ChatMarkdown.test.ts
index fd6f527611..cdb2f146c3 100644
--- a/src/components/ChatMarkdown.test.ts
+++ b/src/components/ChatMarkdown.test.ts
@@ -30,6 +30,7 @@ import { BotEditorStore, initialState, StoreProvider } from "@/state/store";
import { setLocale } from "@/lib/i18n";
import { ThreadRefsContext } from "./ThreadRefs";
import * as AttachmentPreview from "./AttachmentPreview";
+import * as OutsideWorkspaceProbe from "./outside-workspace-probe";
import { messageReferencesFile } from "../../server/message-file";
// Most of this file pins Advanced mode's chrome; the Simple code block has its own tests below.
@@ -928,10 +929,16 @@ describe("ChatMarkdown attachments", () => {
describe("a file link outside the conversation's workspace", () => {
const filePath = "C:\\Users\\Maus\\_draft\\ollama-gen.js";
- const render = (outsideWorkspace: boolean, href = filePath) => {
+ const render = (
+ outsideWorkspace: boolean,
+ href = filePath,
+ probedOutside: boolean | null = outsideWorkspace ? true : false,
+ saveFailed = outsideWorkspace,
+ ) => {
+ const probe = vi.spyOn(OutsideWorkspaceProbe, "useMessageFileOutsideWorkspace").mockReturnValue(probedOutside);
const save = vi.spyOn(AttachmentPreview, "useLocalFileSave").mockReturnValue({
- state: "failed",
- reason: "the linked file is outside this conversation's workspace",
+ state: saveFailed ? "failed" : "idle",
+ reason: outsideWorkspace ? "the linked file is outside this conversation's workspace" : "",
savedTo: "",
outsideWorkspace,
retryable: !outsideWorkspace,
@@ -944,17 +951,19 @@ describe("ChatMarkdown attachments", () => {
}));
} finally {
save.mockRestore();
+ probe.mockRestore();
}
};
const revealInFolder = vi.fn(async () => "shown" as const);
- it("offers Show in folder in the local desktop app, without printing the path", () => {
+ it("reveals the host path on the first click in the local desktop app when the probe already refused it", () => {
vi.stubGlobal("window", { ogb: { revealInFolder, remoteClient: { active: false } } });
try {
- const html = render(true);
- expect(html).toContain("This file is outside this chat&#x27;s working folder, so it can&#x27;t be saved from here");
+ const html = render(false, filePath, true);
+ expect(html).not.toContain("This file is outside this chat&#x27;s working folder, so it can&#x27;t be saved from here");
expect(html).not.toContain("the linked file is outside");
- expect(html).toContain("Show in folder");
+ expect(html).toContain('title="Show in folder"');
+ expect(html).toContain("lucide-folder-open");
expect(html).not.toContain("<code");
} finally {
vi.unstubAllGlobals();
@@ -964,8 +973,8 @@ describe("ChatMarkdown attachments", () => {
it("shows the full path as selectable text to a remote client instead", () => {
vi.stubGlobal("window", { ogb: { revealInFolder, remoteClient: { active: true } } });
try {
- const html = render(true);
- expect(html).not.toContain("Show in folder");
+ const html = render(true, filePath, null);
+ expect(html).not.toContain('title="Show in folder"');
expect(html).toMatch(/<code[^>]*select-all[^>]*>C:\\Users\\Maus\\_draft\\ollama-gen\.js<\/code>/);
} finally {
vi.unstubAllGlobals();
@@ -973,22 +982,36 @@ describe("ChatMarkdown attachments", () => {
});
it("does not offer a retry for a refusal that happens on every try", () => {
- expect(render(true)).not.toContain("lucide-rotate-ccw");
- expect(render(true, "file:///Users/maus/Desktop/designs/Posts/2026-10-08_News")).not.toContain("lucide-rotate-ccw");
- expect(render(false)).toContain("lucide-rotate-ccw");
+ vi.stubGlobal("window", { ogb: { revealInFolder, remoteClient: { active: false } } });
+ try {
+ expect(render(false, filePath, true)).not.toContain("lucide-rotate-ccw");
+ expect(render(false, "file:///Users/maus/Desktop/designs/Posts/2026-10-08_News", true)).not.toContain("lucide-rotate-ccw");
+ expect(render(false, filePath, false, true)).toContain("lucide-rotate-ccw");
+ } finally {
+ vi.unstubAllGlobals();
+ }
});
it("shows the path in a browser, which has no desktop bridge", () => {
- expect(render(true)).toContain(`>${filePath}</code>`);
+ expect(render(true, filePath, null)).toContain(`>${filePath}</code>`);
+ });
+
+ it("keeps the link usable in a browser, where nothing probes it", () => {
+ const html = render(false, filePath, null);
+ expect(html).not.toContain("animate-spin");
+ expect(html).not.toContain('disabled=""');
});
describe("a backticked folder path with a space", () => {
const folder = "D:\\Claude Works\\v3\\";
const text = `The videos are in \`${folder}\``;
- const outsideSave = () => vi.spyOn(AttachmentPreview, "useLocalFileSave").mockReturnValue({
- state: "failed", reason: "", savedTo: "", outsideWorkspace: true, retryable: false, folder: null,
- save: vi.fn(async () => undefined),
- });
+ const outsideSave = () => {
+ vi.spyOn(OutsideWorkspaceProbe, "useMessageFileOutsideWorkspace").mockReturnValue(null);
+ return vi.spyOn(AttachmentPreview, "useLocalFileSave").mockReturnValue({
+ state: "failed", reason: "", savedTo: "", outsideWorkspace: true, retryable: false, folder: null,
+ save: vi.fn(async () => undefined),
+ });
+ };
it("shows the real path in a browser, not the link's %20 spelling", () => {
const save = outsideSave();
@@ -1013,15 +1036,20 @@ describe("ChatMarkdown attachments", () => {
it("asks the desktop app to show the real folder", async () => {
const save = outsideSave();
+ const probe = vi.spyOn(OutsideWorkspaceProbe, "useMessageFileOutsideWorkspace").mockReturnValue(true);
const ogb = (window as { ogb?: unknown }).ogb;
const reveal = vi.fn(async () => "shown" as const);
(window as { ogb?: unknown }).ogb = { revealInFolder: reveal, remoteClient: { active: false } };
+ vi.spyOn(AttachmentPreview, "useLocalFileSave").mockReturnValue({
+ state: "idle", reason: "", savedTo: "", outsideWorkspace: false, retryable: false, folder: null,
+ save: vi.fn(async () => undefined),
+ });
const host = document.createElement("div");
document.body.append(host);
const root = createRoot(host);
try {
await act(async () => root.render(createElement(ChatMarkdown, { text, message: { threadId: "thread-1", messageId: "message-1" } })));
- const show = [...host.querySelectorAll("button")].find((button) => button.textContent === "Show in folder")!;
+ const show = host.querySelector('button[title="Show in folder"]') as HTMLButtonElement;
await act(async () => show.click());
expect(reveal).toHaveBeenCalledWith(folder);
} finally {
@@ -1029,19 +1057,34 @@ describe("ChatMarkdown attachments", () => {
host.remove();
(window as { ogb?: unknown }).ogb = ogb;
save.mockRestore();
+ probe.mockRestore();
}
});
});
it("leaves other failures alone", () => {
vi.stubGlobal("window", { ogb: { revealInFolder, remoteClient: { active: false } } });
+ const probe = vi.spyOn(OutsideWorkspaceProbe, "useMessageFileOutsideWorkspace").mockReturnValue(false);
+ const save = vi.spyOn(AttachmentPreview, "useLocalFileSave").mockReturnValue({
+ state: "failed",
+ reason: "the linked file is outside this conversation's workspace",
+ savedTo: "",
+ outsideWorkspace: false,
+ retryable: true,
+ folder: null,
+ save: vi.fn(async () => undefined),
+ });
try {
- const html = render(false);
+ const html = renderToStaticMarkup(createElement(ChatMarkdown, {
+ text: `[ollama-gen.js](${filePath})`, message: { threadId: "thread-1", messageId: "message-1" },
+ }));
expect(html).toContain("the linked file is outside this conversation&#x27;s workspace");
- expect(html).not.toContain("Show in folder");
+ expect(html).not.toContain('title="Show in folder"');
expect(html).not.toContain(filePath);
} finally {
vi.unstubAllGlobals();
+ save.mockRestore();
+ probe.mockRestore();
}
});
});
diff --git a/src/components/ChatMarkdown.tsx b/src/components/ChatMarkdown.tsx
index 48ceb39d45..8aed71132d 100644
--- a/src/components/ChatMarkdown.tsx
+++ b/src/components/ChatMarkdown.tsx
@@ -4,7 +4,7 @@ import Markdown, { defaultUrlTransform, type Components, type ExtraProps, type O
import remarkGfm from "remark-gfm";
import remarkMath from "remark-math";
import { fromMarkdown, type Options as MarkdownParseOptions } from "mdast-util-from-markdown";
-import { Check, Copy, Download, Eye, LoaderCircle, RotateCcw, WrapText, X } from "lucide-react";
+import { Check, Copy, Download, Eye, FolderOpen, LoaderCircle, RotateCcw, WrapText, X } from "lucide-react";
import { useCopyFeedback } from "@/lib/copy-text";
import { t } from "@/lib/i18n";
import { cn } from "@/lib/cn";
@@ -27,6 +27,8 @@ import { GITHUB_REF_ICONS, LinkHoverCard } from "@/components/LinkHoverCard";
import { useThreadLinkMenu } from "@/components/ThreadLinkMenu";
import { looksLikeThreadRefUrl, parseThreadRefUrl, resolveThreadRefAddress, remarkThreadRefs } from "../lib/thread-refs";
import { MarkdownImagePreview, MessageFolderFiles, OutsideWorkspaceFile, saveFailureText, useLocalFileSave, type MessageAttachmentContext } from "./AttachmentPreview";
+import { useMessageFileOutsideWorkspace } from "./outside-workspace-probe";
+import { canRevealHostPath, revealHostPath, revealProblemText } from "@/lib/reveal-host-path";
import { ThreadLink, ThreadRefsContext, threadLinkFromProps, type ThreadRefsValue } from "./ThreadRefs";
import { MarkdownTable } from "./MarkdownTable";
import { CodeBlock, CodePlate, codeHash } from "./CodeBlock";
@@ -363,16 +365,37 @@ function LocalFileLink({ filePath, shownPath, shownName, name, source, children,
const save = useLocalFileSave(filePath, name, message);
const preview = useHtmlPreview(filePath, shownName, message);
const revealMenu = useRevealOriginalMenu();
+ const fileOutsideWorkspace = useMessageFileOutsideWorkspace(filePath, message);
+ const revealHere = typeof window !== "undefined" && Boolean(window.ogb?.revealInFolder) && !window.ogb?.remoteClient?.active;
+ const revealOnClick = fileOutsideWorkspace === true && canRevealHostPath(shownPath) && revealHere;
+ const [revealProblem, setRevealProblem] = useState("");
if (!message) {
return <span title={t("chat.file.legacy")} className="break-words text-ink-secondary">{children}</span>;
}
+ // Only the desktop app probes; elsewhere the hook stays null and the link must stay usable.
+ const probing = revealHere && canRevealHostPath(filePath) && fileOutsideWorkspace === null;
+ const pathAction = async (event: { currentTarget: HTMLElement }) => {
+ if (preview.opens) {
+ preview.show(event);
+ return;
+ }
+ if (revealOnClick) {
+ setRevealProblem("");
+ const result = await revealHostPath(shownPath);
+ const problem = revealProblemText(result);
+ if (problem) setRevealProblem(problem);
+ return;
+ }
+ void save.save();
+ };
const label = save.state === "saving"
? t("common.saving")
: save.state === "saved"
? t("common.saved")
- : save.state === "failed"
+ : save.state === "failed" && !revealOnClick
? t("chat.retry")
: null;
+ const pathTitle = preview.opens ? preview.label : revealOnClick ? t("attach.showInFolder") : t("chat.file.saveCopy");
return (
<span dir="ltr" className="inline-flex flex-wrap items-center gap-x-1.5 [unicode-bidi:isolate]" {...revealMenu.targetProps(source)}>
@@ -382,14 +405,18 @@ function LocalFileLink({ filePath, shownPath, shownName, name, source, children,
: <FilePreviewButton path={filePath} name={shownName} message={message} />}
<button
type="button"
- onClick={preview.opens ? preview.show : () => void save.save()}
- disabled={!preview.opens && save.state === "saving"}
- title={preview.opens ? preview.label : t("chat.file.saveCopy")}
+ onClick={(event) => void pathAction(event)}
+ disabled={!preview.opens && (save.state === "saving" || probing)}
+ title={pathTitle}
className="inline-flex items-center gap-1 break-words text-start text-accent underline decoration-accent/40 hover:decoration-accent disabled:cursor-wait"
>
{children}
{preview.opens ? (
<Eye size={12} className="shrink-0" aria-hidden="true" />
+ ) : probing ? (
+ <LoaderCircle size={12} className="shrink-0 animate-spin" aria-hidden="true" />
+ ) : revealOnClick ? (
+ <FolderOpen size={12} className="shrink-0" aria-hidden="true" />
) : save.state === "saving" ? (
<LoaderCircle size={12} className="shrink-0 animate-spin" aria-hidden="true" />
) : save.state === "saved" ? (
@@ -400,6 +427,7 @@ function LocalFileLink({ filePath, shownPath, shownName, name, source, children,
<Download size={12} className="shrink-0" aria-hidden="true" />
)}
</button>
+ {revealProblem && <span role="alert" className="text-[12px] text-danger">{revealProblem}</span>}
{label && (
<span
role={save.state === "failed" ? "alert" : "status"}
@@ -409,7 +437,7 @@ function LocalFileLink({ filePath, shownPath, shownName, name, source, children,
{save.state === "failed" ? saveFailureText(save) : label}
</span>
)}
- {save.state === "failed" && save.outsideWorkspace && (
+ {save.state === "failed" && save.outsideWorkspace && !revealOnClick && (
<span className="inline-flex flex-wrap items-center gap-x-1.5 text-[12px]">
<OutsideWorkspaceFile filePath={shownPath} />
</span>
diff --git a/src/components/LinuxLocalControl.test.ts b/src/components/LinuxLocalControl.test.ts
index 9a178c1eec..c31981a082 100644
--- a/src/components/LinuxLocalControl.test.ts
+++ b/src/components/LinuxLocalControl.test.ts
@@ -55,6 +55,17 @@ describe("Linux local control on Omarchy", () => {
expect(markup).not.toContain("GNOME may also ask");
});
+ it("shows nothing on a page served by another server, whose bots can't use this desktop", () => {
+ fixture.localComputer = {
+ available: false,
+ support: "unsupported",
+ enabled: false,
+ status: "unavailable",
+ reasonCode: "remote-server",
+ } as DesktopCapabilities["localComputer"];
+ expect(renderToStaticMarkup(createElement(LinuxLocalControl))).toBe("");
+ });
+
it("keeps the Wayland safety block on other desktops", () => {
fixture.localComputer = {
available: false,
diff --git a/src/components/LinuxLocalControl.tsx b/src/components/LinuxLocalControl.tsx
index 73c892cc51..1d8f714aac 100644
--- a/src/components/LinuxLocalControl.tsx
+++ b/src/components/LinuxLocalControl.tsx
@@ -11,6 +11,7 @@ import {
import { cn } from "@/lib/cn";
import { t } from "@/lib/i18n";
+import { pageOnRemoteServer } from "@/lib/local-computer";
import { useDesktopCapabilities } from "./DesktopCapabilities";
const LINUX_GUIDE_URL =
@@ -25,7 +26,7 @@ export function LinuxLocalControl() {
const [pending, setPending] = useState<"enable" | "disable" | "retry" | null>(null);
const [error, setError] = useState<string | { key: "computer.linux.stopFailed" } | null>(null);
- if (capabilities.host.platform !== "linux") return null;
+ if (capabilities.host.platform !== "linux" || pageOnRemoteServer(capabilities)) return null;
const busy = pending !== null || local.status === "checking" || local.status === "starting";
const ready = local.available;
const waylandSafetyBlocked = local.reasonCode === "linux-wayland-seat-safety-blocked";
diff --git a/src/components/outside-workspace-probe.ts b/src/components/outside-workspace-probe.ts
new file mode 100644
index 0000000000..7ad42de664
--- /dev/null
+++ b/src/components/outside-workspace-probe.ts
@@ -0,0 +1,37 @@
+import { useEffect, useState } from "react";
+import { REVEALABLE_PATH, revealBridge } from "@/lib/reveal-host-path";
+import { requestMessageFile, type MessageAttachmentContext } from "./AttachmentPreview";
+
+/** true when the route refuses a copy into this chat's folder; false when it would stream; null when the probe failed for another reason. */
+export async function messageFileOutsideWorkspace(
+ filePath: string,
+ message: MessageAttachmentContext,
+ signal: AbortSignal,
+): Promise<boolean | null> {
+ try {
+ const response = await requestMessageFile(filePath, message, signal);
+ await response.body?.cancel();
+ return false;
+ } catch (error) {
+ if ((error as { code?: unknown } | null)?.code === "outside_workspace") return true;
+ return null;
+ }
+}
+
+export function useMessageFileOutsideWorkspace(filePath: string, message?: MessageAttachmentContext): boolean | null {
+ const [outside, setOutside] = useState<boolean | null>(null);
+ useEffect(() => {
+ const reveal = revealBridge();
+ if (!message || !reveal || !REVEALABLE_PATH.test(filePath)) {
+ setOutside(null);
+ return;
+ }
+ const controller = new AbortController();
+ setOutside(null);
+ void messageFileOutsideWorkspace(filePath, message, controller.signal).then((value) => {
+ if (!controller.signal.aborted) setOutside(value === null ? false : value);
+ });
+ return () => controller.abort();
+ }, [filePath, message?.messageId, message?.threadId]);
+ return outside;
+}
diff --git a/src/lib/reveal-host-path.ts b/src/lib/reveal-host-path.ts
new file mode 100644
index 0000000000..d5d67306a0
--- /dev/null
+++ b/src/lib/reveal-host-path.ts
@@ -0,0 +1,35 @@
+import { t } from "@/lib/i18n";
+
+/** An absolute host path the desktop's Show in folder can open. */
+export const REVEALABLE_PATH = /^(?:\/(?!\/)|[a-zA-Z]:[\\/])/;
+
+export function canRevealHostPath(filePath: string): boolean {
+ return REVEALABLE_PATH.test(filePath);
+}
+
+/** The desktop's Show in folder; absent in a browser and for a remote client. */
+export function revealBridge(): NonNullable<Window["ogb"]>["revealInFolder"] {
+ const ogb = typeof window === "undefined" ? undefined : window.ogb;
+ return ogb?.remoteClient?.active ? undefined : ogb?.revealInFolder;
+}
+
+export type RevealHostPathResult = "shown" | "missing" | "failed" | "unavailable";
+
+export async function revealHostPath(filePath: string): Promise<RevealHostPathResult> {
+ const reveal = revealBridge();
+ if (!reveal || !REVEALABLE_PATH.test(filePath)) return "unavailable";
+ try {
+ const result = await reveal(filePath);
+ if (result === "missing") return "missing";
+ if (result !== "shown") return "failed";
+ return "shown";
+ } catch {
+ return "failed";
+ }
+}
+
+export function revealProblemText(result: RevealHostPathResult): string {
+ if (result === "missing") return t("attach.revealMissing");
+ if (result === "failed") return t("attach.revealFailed");
+ return "";
+}