Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Show a bot's Gmail draft as a card you can edit, save or open in Gmail
milind-soni778262b8fb8f
diff --git a/packages/phone-protocol/src/email-draft.ts b/packages/phone-protocol/src/email-draft.tsnew file mode 100644index 0000000000..e32cc14f49--- /dev/null+++ b/packages/phone-protocol/src/email-draft.ts@@ -0,0 +1,45 @@+/** A Gmail draft a bot saved, drawn in chat as a card: the person reads it, edits and saves it, or opens it in Gmail to+ * send it. The server writes it after the bot's draft call succeeds; only the server edits it. */+export interface EmailDraftCardData {+ app: "gmail";+ draftId: string;+ /** The bot whose connected apps saved it, and so run its Save. */+ botId: string;+ to: string[];+ cc: string[];+ bcc: string[];+ subject: string;+ body: string;+ /** The body is HTML, drawn as text and saved back as HTML. */+ html?: true;+ /** The Gmail thread a reply draft belongs to. */+ threadId?: string;+ /** The connected account the bot named, so Save reaches the same mailbox. */+ account?: string;+ /** Gmail's own https link to the draft. */+ url?: string;+ /** Set once the bot sent it: the card then only shows what was sent. */+ sentAt?: number;+}++export interface EmailDraftField {+ /** The draft drawn as a card the person can edit or open in Gmail; `text` is the line every other client shows. */+ emailDraft?: EmailDraftCardData;+}++/** What Save sends: the whole draft as the person left it. */+export interface EmailDraftEdit {+ to: string[];+ cc: string[];+ bcc: string[];+ subject: string;+ body: string;+}++export const EMAIL_DRAFT_PATH = "/api/email-draft";+export const EMAIL_DRAFT_LIMITS = { recipients: 50, address: 320, subject: 1_000, body: 100_000 } as const;++/** Addresses typed in one field, split on commas, semicolons and new lines. */+export function splitAddresses(value: string): string[] {+ return value.split(/[,;\n]/).map((one) => one.trim()).filter(Boolean);+}diff --git a/packages/phone-protocol/src/wire.ts b/packages/phone-protocol/src/wire.tsindex ac5a800392..53c9dffd4c 100644--- a/packages/phone-protocol/src/wire.ts+++ b/packages/phone-protocol/src/wire.ts@@ -20,7 +20,7 @@ import type { ProfileRequestCardData } from "./profile-request.ts";import type { ServerTextLine, ServerTextParams } from "./server-text.ts";import type { WireTool } from "./wire-tool.ts";import type { ModelRequestCardData } from "./model-request.ts";-import type { ConnectorCardData } from "./connector-card.ts"; import type { McpChangeRequest } from "./mcp-request.ts"; import type { AppSettingCardField, WindowPrefFrame } from "./app-settings.ts";+import type { ConnectorCardData } from "./connector-card.ts"; import type { McpChangeRequest } from "./mcp-request.ts"; import type { AppSettingCardField, WindowPrefFrame } from "./app-settings.ts"; import type { EmailDraftField } from "./email-draft.ts";import type { SkillRequestCardData } from "./skill-request.ts"; import type { OutsideWriteCardField } from "./outside-write.ts";import type { QuestionRequestCardData } from "./ask-question.ts";import type { AutomationLine, RoutineRunCardData } from "./routine-run.ts";@@ -436,7 +436,7 @@ export type CardAnswerer = (export const EXCERPT_SUMMARY_HEADER = "Historical excerpts in chronological order; newer corrections override older requests. These excerpts may omit earlier details.";/** One transcript line, serialized as stored. */-export interface WireMessage extends ServerTextLine, HelperIntroField, SetupCardFields, WaitLineField, CheckBackLineField, HandoffStatusField, BugReportField {+export interface WireMessage extends ServerTextLine, HelperIntroField, SetupCardFields, WaitLineField, CheckBackLineField, HandoffStatusField, BugReportField, EmailDraftField {roomRequest?: { id: string; phase: "request" | "result" };id: string;role: "bot" | "user";diff --git a/server/email-draft-card.e2e.test.ts b/server/email-draft-card.e2e.test.tsnew file mode 100644index 0000000000..c86c2196f7--- /dev/null+++ b/server/email-draft-card.e2e.test.ts@@ -0,0 +1,264 @@+// The draft card's Save in an isolated server (docs/verification/README.md): a disposable data folder, the fake engine, and+// a loopback stand-in for Composio that holds Gmail's drafts. Nothing reaches a real Gmail or the person's own app.+import { spawn, type ChildProcess } from "node:child_process";+import { closeSync, existsSync, openSync, readFileSync, writeFileSync } from "node:fs";+import { DatabaseSync } from "node:sqlite";+import { createServer, type Server } from "node:http";+import { join } from "node:path";+import { fileURLToPath } from "node:url";+import { afterAll, beforeAll, expect, it } from "vitest";+import { launchVerificationServer, verificationServerArgs, verificationServerEnvironment, type VerificationServer } from "../scripts/control-omb.ts";+import type { EmailDraftEdit } from "../shared/email-draft.ts";+import { SessionRegistry } from "./sessions.ts";+import { waitForExit } from "./testing/cleanup.ts";+import { readRegistry, writeRegistry } from "./testing/registry.ts";++const key = "isolated-email-draft-capability";+type Draft = EmailDraftEdit;+let fixture: VerificationServer;+let child: ChildProcess;+let broker: Server;+let brokerOrigin = "";+let admin = "";+let botId = "";+let threadId = "";+/** Gmail's drafts, as the stand-in holds them. */+const gmail = new Map<string, Draft>();+/** Every Gmail tool call that reached the stand-in, in order. */+const reached: string[] = [];+const evidence: unknown[] = [];+let holdSession: Promise<void> | undefined;+let sessionEntered: (() => void) | undefined;++const api = async (method: string, path: string, body?: unknown) => {+ const response = await fetch(fixture.info.url + path, {+ method, headers: { "content-type": "application/json", authorization: `Bearer ${admin}` },+ ...(body === undefined ? {} : { body: JSON.stringify(body) }), signal: AbortSignal.timeout(20_000),+ });+ const result = { status: response.status, body: await response.json() as any };+ evidence.push({ method, path, body, result });+ return result;+};+const mint = async (thread = threadId) => {+ const response = await fetch(fixture.info.url + "/api/testing/internal-capability", {+ method: "POST", headers: { "content-type": "application/json", "x-openmausbot-test-capability": key },+ body: JSON.stringify({ botId, threadId: thread, kind: "connectors" }),+ });+ expect(response.status).toBe(201);+ return (await response.json() as any).token as string;+};+/** The bot's own Gmail call, through the server's connector relay. */+const botCall = async (slug: string, args: Record<string, unknown>, thread = threadId) => {+ const response = await fetch(fixture.info.url + "/api/internal/connectors/mcp", {+ method: "POST", headers: { "content-type": "application/json", authorization: `Bearer ${await mint(thread)}` },+ body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "COMPOSIO_MULTI_EXECUTE_TOOL", arguments: { tools: [{ tool_slug: slug, arguments: args }] } } }),+ });+ const body = await response.json() as any;+ evidence.push({ botCall: slug, args, status: response.status, isError: body.result?.isError === true });+ expect(response.status).toBe(200);+ expect(body.result?.isError).not.toBe(true);+ return body;+};+const cardsIn = async (thread = threadId) =>+ ((await api("GET", `/api/threads/${thread}/messages?limit=100`)).body.messages as any[]).filter((row) => row.emailDraft);+const draftCard = async (thread = threadId) => (await cardsIn(thread)).at(-1);+const fieldsOf = (card: any): Draft => ({ to: card.emailDraft.to, cc: card.emailDraft.cc, bcc: card.emailDraft.bcc, subject: card.emailDraft.subject, body: card.emailDraft.body });+const save = (card: any, base: Draft, draft: Draft, thread = threadId) => api("POST", "/api/email-draft", { threadId: thread, messageId: card.id, action: "save", base, draft });++beforeAll(async () => {+ broker = createServer(async (req, res) => {+ let raw = "";+ for await (const chunk of req) raw += chunk;+ const body = raw ? JSON.parse(raw) : {};+ res.setHeader("content-type", "application/json");+ if (req.url === "/v1/connectors/connected") return res.end(JSON.stringify({ services: { gmail: { connected: true } } }));+ if (req.url === "/api/tool_router/session/fixture-session") {+ if (holdSession) { sessionEntered?.(); await holdSession; }+ return res.end(JSON.stringify({ session_id: "fixture-session", mcp: { type: "http", url: brokerOrigin + "/mcp" },+ config: { user_id: "fixture-user", multi_account: { enable: true, max_accounts_per_toolkit: 10, require_explicit_selection: true } } }));+ }+ if (req.url === "/mcp") {+ const tools = body.params?.arguments?.tools;+ if (!Array.isArray(tools)) return res.end(JSON.stringify({ jsonrpc: "2.0", id: body.id, result: { content: [{ type: "text", text: "relay-ok" }] } }));+ const results = tools.map((tool: any) => {+ reached.push(tool.tool_slug);+ const args = tool.arguments ?? {};+ const respond = (response: unknown) => ({ tool_slug: tool.tool_slug, response });+ if (tool.tool_slug === "GMAIL_CREATE_EMAIL_DRAFT" || tool.tool_slug === "GMAIL_UPDATE_DRAFT") {+ const id = tool.tool_slug === "GMAIL_CREATE_EMAIL_DRAFT" ? `draft-${gmail.size + 1}` : args.draft_id;+ const was = gmail.get(id);+ if (tool.tool_slug === "GMAIL_UPDATE_DRAFT" && !was) return respond({ successful: false, error: "Draft not found" });+ // An update leaves in Gmail what it omits.+ const kept = (name: string, value: () => unknown, before: unknown) => (args[name] === undefined ? before : value());+ const to = [...kept("recipient_email", () => [args.recipient_email].filter(Boolean), was?.to.slice(0, 1) ?? []) as string[],+ ...kept("extra_recipients", () => args.extra_recipients, was?.to.slice(1) ?? []) as string[]];+ gmail.set(id, { to, cc: kept("cc", () => args.cc, was?.cc ?? []) as string[], bcc: kept("bcc", () => args.bcc, was?.bcc ?? []) as string[],+ subject: kept("subject", () => args.subject, was?.subject ?? "") as string, body: kept("body", () => args.body, was?.body ?? "") as string });+ return respond({ successful: true, data: { id, message: { id: `msg-${id}`, threadId: args.thread_id ?? "gmail-thread" } } });+ }+ if (tool.tool_slug === "GMAIL_GET_DRAFT") {+ const draft = gmail.get(args.draft_id);+ if (!draft) return respond({ successful: false, error: "Draft not found" });+ const headers = [["To", draft.to], ["Cc", draft.cc], ["Bcc", draft.bcc], ["Subject", [draft.subject]]]+ .filter(([, values]) => (values as string[]).some(Boolean)).map(([name, values]) => ({ name, value: (values as string[]).join(", ") }));+ return respond({ successful: true, data: { id: args.draft_id, message: { to: draft.to.join(", "), subject: draft.subject, messageText: draft.body, payload: { headers } } } });+ }+ return respond({ successful: false, error: "not in this fixture" });+ });+ return res.end(JSON.stringify({ jsonrpc: "2.0", id: body.id, result: { content: [{ type: "text", text: JSON.stringify({ successful: true, data: { results } }) }] } }));+ }+ return res.end(JSON.stringify({ items: [{ slug: "gmail", connected_account: { id: "fixture-account", status: "ACTIVE" } }] }));+ });+ await new Promise<void>((resolve) => broker.listen(0, "127.0.0.1", resolve));+ brokerOrigin = `http://127.0.0.1:${(broker.address() as { port: number }).port}`;+ fixture = await launchVerificationServer();+ const created = await fetch(fixture.info.url + "/api/bots", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ name: "Draft card fixture" }) });+ expect(created.status).toBe(201);+ ({ id: botId, threadId } = (await created.json() as any).bot);+ await waitForExit(fixture.child, { signal: "SIGTERM" });+ const bots = readRegistry(fixture.info.dataDir).bots;+ const saved = bots.find((row: any) => row.id === botId);+ saved.approvalMode = "full";+ for (const task of saved.tasks) task.approvalMode = "full";+ writeRegistry(fixture.info.dataDir, { bots });+ const configFile = join(fixture.info.dataDir, "config.json");+ const config = JSON.parse(readFileSync(configFile, "utf8"));+ config.signIn = { admins: ["[email protected]"] };+ config.composio = { apiKey: "ak_isolated_fixture", userId: "fixture-user", sessionId: "fixture-session" };+ writeFileSync(configFile, JSON.stringify(config));+ const sessions = new SessionRegistry({ file: join(fixture.info.dataDir, "sessions.json"), emailScopes: () => ["admin", "client"] });+ admin = sessions.issue({ label: "isolated admin", email: "[email protected]", scopes: ["admin", "client"] }).token;+ sessions.close();+ const log = openSync(fixture.info.logPath, "a", 0o600);+ const env = { ...verificationServerEnvironment({}, fixture.info.dataDir, Number(new URL(fixture.info.url).port)),+ OMB_TEST_INTERNAL_CAPABILITY_KEY: key, OMB_COMPOSIO_API: brokerOrigin + "/api", OMB_COMPOSIO_TOOLKITS_API: brokerOrigin + "/api" };+ child = spawn(process.execPath, verificationServerArgs(env), {+ cwd: fileURLToPath(new URL("..", import.meta.url)),+ env,+ stdio: ["ignore", log, log],+ });+ closeSync(log);+ const deadline = Date.now() + 20_000;+ while (Date.now() < deadline) {+ try { if ((await fetch(fixture.info.url + "/api/health")).ok) return; } catch {}+ await new Promise((resolve) => setTimeout(resolve, 20));+ }+ throw new Error("isolated email draft server did not start");+}, 40_000);++afterAll(async () => {+ const evidencePath = fixture.info.logPath + ".email-draft-card.json";+ writeFileSync(evidencePath, JSON.stringify({ fixture: fixture.info, evidence, reached, gmail: Object.fromEntries(gmail) }, null, 2));+ await waitForExit(child, { signal: "SIGTERM" });+ await fixture.close();+ await new Promise<void>((resolve) => broker.close(() => resolve()));+ console.info(JSON.stringify({ logPath: fixture.info.logPath, evidencePath, fixtureRemoved: !existsSync(fixture.info.dataDir) }));+});++const first: Draft = { to: ["[email protected]", "[email protected]"], cc: ["[email protected]"], bcc: [], subject: "Launch", body: "Hi both,\nready." };++it("shows the bot's draft as a card, and Save writes the edit to the same Gmail draft", async () => {+ await botCall("GMAIL_CREATE_EMAIL_DRAFT", { user_id: "me", recipient_email: "[email protected]", extra_recipients: ["[email protected]"], cc: ["[email protected]"], subject: "Launch", body: "Hi both,\nready." });+ const card = await draftCard();+ expect(fieldsOf(card)).toEqual(first);+ const before = reached.length;+ const edit = { ...first, subject: "Launch (final)" };+ expect((await save(card, first, edit)).status).toBe(200);+ expect(reached.slice(before)).toEqual(["GMAIL_GET_DRAFT", "GMAIL_UPDATE_DRAFT"]);+ expect(gmail.get(card.emailDraft.draftId)).toEqual(edit);+ expect(fieldsOf(await draftCard())).toEqual(edit);+});++it("saves nothing over a bot's partial update made after the edit started, and the card shows Gmail's version", async () => {+ const card = await draftCard();+ const base = fieldsOf(card);+ // The person opens Edit; the bot then changes only the recipients.+ await botCall("GMAIL_UPDATE_DRAFT", { user_id: "me", draft_id: card.emailDraft.draftId, recipient_email: "[email protected]", extra_recipients: ["[email protected]"] });+ const before = reached.length;+ const refused = await save(card, base, { ...base, subject: "Launch (typo fixed)" });+ expect(refused.status).toBe(409);+ expect(refused.body.errorKey).toBe("serverError.emailDraft.changed");+ expect(reached.slice(before)).toEqual(["GMAIL_GET_DRAFT"]);+ expect(gmail.get(card.emailDraft.draftId)).toMatchObject({ to: ["[email protected]", "[email protected]"], subject: "Launch (final)" });+ expect(fieldsOf(await draftCard())).toEqual(gmail.get(card.emailDraft.draftId));+});++it("saves nothing over a change made in Gmail itself, and the card shows it", async () => {+ const card = await draftCard();+ const base = fieldsOf(card);+ gmail.set(card.emailDraft.draftId, { ...base, body: "Edited in Gmail." });+ const before = reached.length;+ const refused = await save(card, base, { ...base, subject: "Mine" });+ expect(refused.status).toBe(409);+ expect(reached.slice(before)).toEqual(["GMAIL_GET_DRAFT"]);+ expect(gmail.get(card.emailDraft.draftId)!.subject).toBe("Launch (final)");+ expect((await draftCard()).emailDraft.body).toBe("Edited in Gmail.");+ // Edit again from what the card now shows: it saves.+ const fresh = fieldsOf(await draftCard());+ expect((await save(await draftCard(), fresh, { ...fresh, subject: "Mine" })).status).toBe(200);+ expect(gmail.get(card.emailDraft.draftId)).toEqual({ ...fresh, subject: "Mine" });+});++it("has no Send: a press to send is refused and nothing reaches Gmail", async () => {+ const card = await draftCard();+ const before = reached.length;+ const refused = await api("POST", "/api/email-draft", { threadId, messageId: card.id, action: "send", draft: fieldsOf(card) });+ expect(refused.status).toBe(400);+ expect(reached.slice(before)).toEqual([]);+});++it("saves nothing when the bot loses Gmail write access while the call is being set up", async () => {+ const card = await draftCard();+ const base = fieldsOf(card);+ const was = gmail.get(card.emailDraft.draftId);+ let release!: () => void;+ holdSession = new Promise<void>((resolve) => { release = resolve; });+ const entered = new Promise<void>((resolve) => { sessionEntered = resolve; });+ const before = reached.length;+ const pressing = save(card, base, { ...base, subject: "Not allowed" });+ await entered;+ // Permissions change after the press was checked, while the relay waits for its session.+ expect((await api("PATCH", `/api/bots/${botId}`, { connectorScopes: { apps: { gmail: "read" } } })).status).toBe(200);+ holdSession = undefined;+ release();+ const refused = await pressing;+ expect(refused.status).toBe(403);+ expect(reached.slice(before)).toEqual([]);+ expect(gmail.get(card.emailDraft.draftId)).toEqual(was);+ expect(fieldsOf(await draftCard())).toEqual(base);+ expect((await api("PATCH", `/api/bots/${botId}`, { connectorScopes: null })).status).toBe(200);+});++it("saves nothing from a card in a room, and nothing reaches Gmail", async () => {+ const made = await api("POST", "/api/groups", { name: "Draft room", memberIds: [botId], setup: { bulletin: "", defaultResponder: { kind: "member", botId } } });+ expect(made.status).toBe(201);+ const room = made.body.group.threadId as string;+ await botCall("GMAIL_CREATE_EMAIL_DRAFT", { user_id: "me", recipient_email: "[email protected]", subject: "Room draft", body: "From the room." }, room);+ const card = await draftCard(room);+ expect(card.emailDraft.subject).toBe("Room draft");+ const was = gmail.get(card.emailDraft.draftId);+ const before = reached.length;+ const refused = await save(card, fieldsOf(card), { ...fieldsOf(card), subject: "Saved from the room" }, room);+ expect(refused.status).toBe(404);+ expect(refused.body.errorKey).toBe("serverError.emailDraft.notHere");+ expect(reached.slice(before)).toEqual([]);+ expect(gmail.get(card.emailDraft.draftId)).toEqual(was);+});++it("keeps the bot's answer from Gmail when the card can't be written", async () => {+ const cardsBefore = (await cardsIn()).length;+ // Another connection holds the transcript database's write lock, so the server's card write fails.+ const lock = new DatabaseSync(join(fixture.info.dataDir, "messages.db"));+ lock.exec("BEGIN IMMEDIATE");+ let answer: any;+ try {+ answer = await botCall("GMAIL_CREATE_EMAIL_DRAFT", { user_id: "me", recipient_email: "[email protected]", subject: "Not shown", body: "Card write fails." });+ } finally {+ lock.exec("ROLLBACK");+ lock.close();+ }+ const id = `draft-${gmail.size}`;+ expect(gmail.get(id)?.subject).toBe("Not shown");+ expect(JSON.parse(answer.result.content[0].text).data.results[0].response.data.id).toBe(id);+ expect(await cardsIn()).toHaveLength(cardsBefore);+});diff --git a/server/email-draft-card.test.ts b/server/email-draft-card.test.tsnew file mode 100644index 0000000000..e1d1a9cc64--- /dev/null+++ b/server/email-draft-card.test.ts@@ -0,0 +1,457 @@+import { EventEmitter } from "node:events";+import { describe, expect, it } from "vitest";++import type { EmailDraftCardData, EmailDraftEdit } from "../shared/email-draft.ts";+import type { ConnectorCall } from "../shared/outbound.ts";+import {+ createDraftGuard, createEmailDraftRoutes, draftCardFrom, DraftRefused, showDraftAnswer, showDraftCard,+ type DraftCardStore, type DraftConnection, type EmailDraftRouteDeps,+} from "./email-draft-card.ts";+import type { RequestAuth } from "./request-auth.ts";+import type { RouteContext } from "./routes/table.ts";+import type { Message } from "./store.ts";++const auth = { kind: "loopback", scopes: ["admin", "client"] } as RequestAuth;++/** A multi-execute answer as the relay returns it. */+function answer(slug: string, response: Record<string, unknown>, id: unknown = 7): Record<string, unknown> {+ return { jsonrpc: "2.0", id, result: { content: [{ type: "text", text: JSON.stringify({ successful: true, data: { results: [{ tool_slug: slug, response }] } }) }] } };+}++const created = (over: Record<string, unknown> = {}) => answer("GMAIL_CREATE_EMAIL_DRAFT", {+ successful: true, data: { id: "r-123", message: { id: "m-1", threadId: "th-9" }, display_url: "https://mail.google.com/mail/#drafts?compose=m-1", ...over },+});++const createCall: ConnectorCall = {+ slug: "GMAIL_CREATE_EMAIL_DRAFT", account: "ca_work",+ arguments: { user_id: "me", recipient_email: "[email protected]", extra_recipients: ["[email protected]"], cc: ["[email protected]"], subject: "Launch", body: "Hi both,\nready." },+};++function memoryStore(): DraftCardStore & { rows: Message[] } {+ const rows: Message[] = [];+ let next = 0;+ return {+ rows,+ messagesFor: () => rows,+ appendMessage: (_thread, message) => { const row = { ...message, id: `m${++next}`, at: next } as Message; rows.push(row); return row; },+ patchMessage: (_thread, id, patch) => { const row = rows.find((one) => one.id === id); if (!row) return null; Object.assign(row, patch); return row; },+ };+}++describe("draftCardFrom", () => {+ it("reads the saved draft from the call and Gmail's answer", () => {+ expect(draftCardFrom([createCall], created(), "bot-1")).toEqual({+ app: "gmail", draftId: "r-123", botId: "bot-1", to: ["[email protected]", "[email protected]"], cc: ["[email protected]"], bcc: [],+ subject: "Launch", body: "Hi both,\nready.", threadId: "th-9", account: "ca_work", url: "https://mail.google.com/mail/#drafts?compose=m-1",+ });+ });+++ it("shows no card when the draft was not saved, or the batch is not one draft", () => {+ expect(draftCardFrom([createCall], answer("GMAIL_CREATE_EMAIL_DRAFT", { successful: false, error: "Invalid To header" }), "b")).toBeNull();+ expect(draftCardFrom([createCall], { jsonrpc: "2.0", id: 7, result: { isError: true, content: [{ type: "text", text: "refused" }] } }, "b")).toBeNull();+ expect(draftCardFrom([{ slug: "GMAIL_SEND_EMAIL", arguments: {} }], created(), "b")).toBeNull();+ expect(draftCardFrom([createCall, createCall], created(), "b")).toBeNull();+ });++ it("keeps only a plain https link to Gmail", () => {+ expect(draftCardFrom([createCall], created({ display_url: "javascript:alert(1)" }), "b")?.url).toBeUndefined();+ expect(draftCardFrom([createCall], created({ display_url: "https://user:[email protected]/" }), "b")?.url).toBeUndefined();+ });++ it("keeps the draft id of an update that answers without one", () => {+ const update: ConnectorCall = { slug: "GMAIL_UPDATE_DRAFT", arguments: { draft_id: "r-123", recipient_email: "[email protected]", extra_recipients: [], cc: [], bcc: [], subject: "Launch v2", body: "New", is_html: false } };+ expect(draftCardFrom([update], answer("GMAIL_UPDATE_DRAFT", { successful: true, data: {} }), "b")).toMatchObject({ draftId: "r-123", subject: "Launch v2", body: "New" });+ });++ it("keeps what an update leaves out from the card already showing the draft, and shows none without one", () => {+ const before = { ...draftCardFrom([createCall], created(), "b")!, html: true as const, body: "<p>Hi</p>" };+ const update: ConnectorCall = { slug: "GMAIL_UPDATE_DRAFT", arguments: { user_id: "me", draft_id: "r-123", subject: "Launch v2" } };+ const done = answer("GMAIL_UPDATE_DRAFT", { successful: true, data: { id: "r-123" } });+ expect(draftCardFrom([update], done, "b", (id) => (id === "r-123" ? before : undefined))).toEqual({ ...before, subject: "Launch v2" });+ expect(draftCardFrom([update], done, "b")).toBeNull();+ expect(draftCardFrom([update], done, "b", () => undefined)).toBeNull();+ });++ it("keeps the recipients an update leaves out when it names only the first or only the others", () => {+ const before = draftCardFrom([createCall], created(), "b")!;+ const shownBefore = (id: string) => (id === "r-123" ? before : undefined);+ const done = answer("GMAIL_UPDATE_DRAFT", { successful: true, data: { id: "r-123" } });+ const firstOnly: ConnectorCall = { slug: "GMAIL_UPDATE_DRAFT", arguments: { draft_id: "r-123", recipient_email: "[email protected]" } };+ expect(draftCardFrom([firstOnly], done, "b", shownBefore)?.to).toEqual(["[email protected]", "[email protected]"]);+ const othersOnly: ConnectorCall = { slug: "GMAIL_UPDATE_DRAFT", arguments: { draft_id: "r-123", extra_recipients: ["[email protected]"] } };+ expect(draftCardFrom([othersOnly], done, "b", shownBefore)?.to).toEqual(["[email protected]", "[email protected]"]);+ });++ it("shows no card for a draft with other recipients but no first one, so a later update can't drop them", () => {+ const before = draftCardFrom([createCall], created(), "b")!;+ const done = answer("GMAIL_UPDATE_DRAFT", { successful: true, data: { id: "r-123" } });+ const cleared: ConnectorCall = { slug: "GMAIL_UPDATE_DRAFT", arguments: { draft_id: "r-123", recipient_email: "" } };+ expect(draftCardFrom([cleared], done, "b", (id) => (id === "r-123" ? before : undefined))).toBeNull();+ const othersOnly: ConnectorCall = { slug: "GMAIL_CREATE_EMAIL_DRAFT", arguments: { user_id: "me", extra_recipients: ["[email protected]"], subject: "Launch", body: "Hi" } };+ expect(draftCardFrom([othersOnly], created(), "b")).toBeNull();+ });+});++describe("showDraftAnswer", () => {+ const bytesOf = (frame: unknown) => new TextEncoder().encode(JSON.stringify(frame));++ it("shows the card from an event-stream answer, and nothing from one it can't read", () => {+ const store = memoryStore();+ showDraftAnswer(store, "t1", "bot-1", [createCall], new TextEncoder().encode("{not json"), 7);+ expect(store.rows).toHaveLength(0);+ showDraftAnswer(store, "t1", "bot-1", [createCall], new TextEncoder().encode(`event: message\ndata: ${JSON.stringify(created())}\n\n`), 7);+ expect(store.rows.map((row) => row.emailDraft?.draftId)).toEqual(["r-123"]);+ });++ it("turns the card into what was sent when the bot sends that draft itself", () => {+ const store = memoryStore();+ showDraftAnswer(store, "t1", "bot-1", [createCall], bytesOf(created()), 7);+ const send: ConnectorCall = { slug: "GMAIL_SEND_DRAFT", arguments: { user_id: "me", draft_id: "r-123" } };+ showDraftAnswer(store, "t1", "bot-2", [send], bytesOf(answer("GMAIL_SEND_DRAFT", { successful: true, data: { id: "m-1" } })), 7);+ expect(store.rows[0].emailDraft?.sentAt).toBeUndefined();+ showDraftAnswer(store, "t1", "bot-1", [send], bytesOf(answer("GMAIL_SEND_DRAFT", { successful: false, error: "Not found" })), 7);+ expect(store.rows[0].emailDraft?.sentAt).toBeUndefined();+ showDraftAnswer(store, "t1", "bot-1", [send], bytesOf(answer("GMAIL_SEND_DRAFT", { successful: true, data: { id: "m-1" } })), 7);+ expect(store.rows).toHaveLength(1);+ expect(store.rows[0].emailDraft?.sentAt).toEqual(expect.any(Number));+ expect(store.rows[0].text).toBe('Email sent: "Launch" to [email protected], [email protected].');+ });+});++describe("showDraftAnswer when the card can't be written", () => {+ it("leaves the bot's finished call alone", () => {+ const store = { ...memoryStore(), appendMessage: () => { throw new Error("disk full"); } };+ expect(() => showDraftAnswer(store, "t1", "bot-1", [createCall], new TextEncoder().encode(JSON.stringify(created())), 7)).not.toThrow();+ });+});++describe("showDraftCard", () => {+ it("updates the card already showing that draft instead of adding another", () => {+ const store = memoryStore();+ const card = draftCardFrom([createCall], created(), "bot-1")!;+ showDraftCard(store, "t1", card);+ showDraftCard(store, "t1", { ...card, subject: "Launch v2" });+ expect(store.rows).toHaveLength(1);+ expect(store.rows[0]).toMatchObject({ role: "bot", serverCard: true, text: 'Draft saved in Gmail: "Launch v2" to [email protected], [email protected].' });+ expect(store.rows[0]!.emailDraft?.subject).toBe("Launch v2");+ });+});++function request(body: unknown) {+ const sent: { status?: number; body?: unknown } = {};+ const res = Object.assign(new EventEmitter(), { writableFinished: false, writableEnded: false, destroyed: false });+ const context = { req: {} as RouteContext["req"], res: res as unknown as RouteContext["res"], url: new URL("http://x/api/email-draft"), path: "/api/email-draft", method: "POST", auth,+ json: ((_res: unknown, status: number, value: unknown) => { sent.status = status; sent.body = value; }) as unknown as RouteContext["json"],+ readBody: (async () => body) as unknown as RouteContext["readBody"] } as RouteContext;+ return { context, sent };+}+++/** Composio's GMAIL_GET_DRAFT answer for a draft Gmail holds: its headers, as Gmail writes them, and its text. */+function heldAnswer(draft: EmailDraftEdit, over: Record<string, unknown> = {}): Record<string, unknown> {+ const fields: Array<[string, readonly string[]]> = [["To", draft.to], ["Cc", draft.cc], ["Bcc", draft.bcc], ["Subject", [draft.subject]]];+ const headers = fields.filter(([, values]) => values.some(Boolean)).map(([name, values]) => ({ name, value: values.join(", ") }));+ return { successful: true, data: { id: "r-123", message: { to: draft.to.join(", "), subject: draft.subject, messageText: draft.body, payload: { headers }, ...over } } };+}++/** A connection to a Gmail holding `gmail`: reading the draft answers what it holds, other tool calls answer `reply` (an+ * update that succeeds changes what it holds). It records every call it ran. */+function relayed(reply: (slug: string) => Record<string, unknown>, gate?: Promise<void>, gmail: EmailDraftEdit = { ...shownDraft }) {+ const ran: Array<{ slug: string; arguments: unknown; account?: string }> = [];+ let started!: () => void;+ const calling = new Promise<void>((resolve) => { started = resolve; });+ const connection: DraftConnection = {+ ok: true,+ relay: async (payload, _session, _signal, beforeSend) => {+ const frame = payload as { id?: unknown; method: string; params?: { arguments?: { tools?: Array<{ tool_slug: string; arguments: unknown; account?: string }> } } };+ if (frame.method === "initialize") return { status: 200, bytes: new Uint8Array(), transportSessionId: "s1" };+ if (frame.method !== "tools/call") return { status: 202, bytes: new Uint8Array() };+ const tool = frame.params!.arguments!.tools![0]!;+ beforeSend?.();+ ran.push({ slug: tool.tool_slug, arguments: tool.arguments, ...(tool.account ? { account: tool.account } : {}) });+ started();+ await gate;+ const args = tool.arguments as Record<string, unknown>;+ const result = tool.tool_slug === "GMAIL_GET_DRAFT" ? heldAnswer(gmail) : reply(tool.tool_slug);+ if (tool.tool_slug === "GMAIL_UPDATE_DRAFT" && result.successful) {+ Object.assign(gmail, { to: [args.recipient_email, ...(args.extra_recipients as string[])].filter(Boolean), cc: args.cc, bcc: args.bcc, subject: args.subject, body: args.body });+ }+ return { status: 200, bytes: new TextEncoder().encode(JSON.stringify(answer(tool.tool_slug, result, frame.id))) };+ },+ };+ return { connection, ran, calling, gmail };+}++function setup(over: Partial<EmailDraftRouteDeps> = {}, connection: DraftConnection = relayed(() => ({ successful: true, data: { id: "r-123" } })).connection) {+ const store = memoryStore();+ const guard = createDraftGuard();+ const card: EmailDraftCardData = draftCardFrom([createCall], created(), "bot-1")!;+ const row = showDraftCard(store, "t1", card)!;+ const checked: ConnectorCall[][] = [];+ const route = createEmailDraftRoutes({+ store, guard, sees: () => true, inRoom: () => false, mayChat: () => true,+ connection: async (_auth, _bot, calls) => { checked.push(calls); return connection; }, ...over,+ });+ return { store, row, route, checked, guard };+}++const edit = { to: ["[email protected]"], cc: [], bcc: ["[email protected]"], subject: "Launch (final)", body: "Ready to go." };+/** The draft as the card shows it. */+const shownDraft = { to: ["[email protected]", "[email protected]"], cc: ["[email protected]"], bcc: [], subject: "Launch", body: "Hi both,\nready." };+const save = { action: "save", base: shownDraft, draft: edit };+const READ = { slug: "GMAIL_GET_DRAFT", account: "ca_work", arguments: { user_id: "me", draft_id: "r-123", format: "full" } };+const errorKey = (sent: { body?: unknown }) => (sent.body as { errorKey?: string }).errorKey;+type Relay = Extract<DraftConnection, { ok: true }>;++describe("POST /api/email-draft", () => {+ it("saves an edit to the same draft in the same account, then shows it", async () => {+ const { connection, ran } = relayed(() => ({ successful: true, data: { id: "r-123", message: { id: "m-2" } } }));+ const { store, row, route, checked } = setup({}, connection);+ const { context, sent } = request({ threadId: "t1", messageId: row.id, ...save });+ await route(context);+ expect(sent.status).toBe(200);+ expect(ran).toEqual([READ, { slug: "GMAIL_UPDATE_DRAFT", account: "ca_work", arguments: {+ user_id: "me", draft_id: "r-123", recipient_email: "[email protected]", extra_recipients: [], cc: [], bcc: ["[email protected]"],+ subject: "Launch (final)", body: "Ready to go.", is_html: false, thread_id: "th-9",+ } }]);+ expect(checked[0]!.map((call) => call.slug)).toEqual(["GMAIL_GET_DRAFT", "GMAIL_UPDATE_DRAFT"]);+ expect(store.rows[0]!.emailDraft).toMatchObject({ ...edit, draftId: "r-123" });+ expect(store.rows[0]!.text).toBe('Draft saved in Gmail: "Launch (final)" to [email protected].');+ });++ it("has no Send: a press to send is refused and nothing goes to Gmail", async () => {+ const { store, row, route, checked } = setup();+ const { context, sent } = request({ threadId: "t1", messageId: row.id, action: "send", revision: "abc" });+ await route(context);+ expect(sent.status).toBe(400);+ expect(checked).toHaveLength(0);+ expect(store.rows[0]!.emailDraft?.sentAt).toBeUndefined();+ });++ it("saves nothing once the bot sent the draft", async () => {+ const { connection, ran } = relayed(() => ({ successful: true, data: { id: "r-123" } }));+ const { store, row, route } = setup({}, connection);+ showDraftAnswer(store, "t1", "bot-1", [{ slug: "GMAIL_SEND_DRAFT", arguments: { user_id: "me", draft_id: "r-123" } }],+ new TextEncoder().encode(JSON.stringify(answer("GMAIL_SEND_DRAFT", { successful: true, data: { id: "m-1" } }))), 7);+ const { context, sent } = request({ threadId: "t1", messageId: row.id, ...save });+ await route(context);+ expect(sent.status).toBe(409);+ expect(errorKey(sent)).toBe("serverError.emailDraft.alreadySent");+ expect(ran).toHaveLength(0);+ });++ it("runs a double tap once", async () => {+ let open!: () => void;+ const { connection, ran, calling } = relayed(() => ({ successful: true, data: { id: "r-123" } }), new Promise((resolve) => { open = resolve; }));+ const { row, route } = setup({}, connection);+ const first = request({ threadId: "t1", messageId: row.id, ...save });+ const running = route(first.context);+ await calling;+ const second = request({ threadId: "t1", messageId: row.id, ...save });+ await route(second.context);+ expect(second.sent.status).toBe(409);+ expect(errorKey(second.sent)).toBe("serverError.emailDraft.busy");+ open();+ await running;+ expect(first.sent.status).toBe(200);+ expect(ran.map((one) => one.slug)).toEqual(["GMAIL_GET_DRAFT", "GMAIL_UPDATE_DRAFT"]);+ });++ it("runs nothing for someone who can't see the conversation or write to the bot, or in a room", async () => {+ for (const over of [{ sees: () => false }, { mayChat: () => false }, { inRoom: () => true }]) {+ const { store, row, route, checked } = setup(over);+ const { context, sent } = request({ threadId: "t1", messageId: row.id, ...save });+ await route(context);+ expect(sent.status).toBe(404);+ expect(checked).toHaveLength(0);+ expect(store.rows[0]!.emailDraft).toMatchObject({ ...shownDraft, draftId: "r-123" });+ }+ });++ it("saves nothing when the bot's permissions change right before the call goes out", async () => {+ const refusal = { error: "Bot may not save Gmail drafts." };+ // Allowed when the press is checked, then taken away while the call is being set up: the check right before the+ // tool call goes out refuses it, the way the server's relay does.+ let allowed = true;+ let checkedBeforeDispatch = 0;+ const { connection: gmail, ran } = relayed(() => ({ successful: true, data: { id: "r-123" } }));+ const connection: DraftConnection = { ok: true, relay: async (payload, session, signal, beforeSend) => {+ if ((payload as { method: string }).method === "initialize") allowed = false;+ if ((payload as { method: string }).method === "tools/call") { checkedBeforeDispatch++; if (!allowed) throw new DraftRefused(refusal); }+ return (gmail as Relay).relay(payload, session, signal, beforeSend);+ } };+ const { store, row, route } = setup({}, connection);+ const { context, sent } = request({ threadId: "t1", messageId: row.id, ...save });+ await route(context);+ expect(sent).toEqual({ status: 403, body: refusal });+ expect(checkedBeforeDispatch).toBe(1);+ expect(ran).toHaveLength(0);+ expect(store.rows[0]!.emailDraft).toMatchObject({ ...shownDraft, draftId: "r-123" });+ });++ it("waits for the bot's call to the same draft, then saves nothing over the bot's change and shows it", async () => {+ const { connection, ran, gmail } = relayed(() => ({ successful: true, data: { id: "r-123" } }));+ const { store, row, route, guard } = setup({}, connection);+ let finish!: () => void;+ const update: ConnectorCall = { slug: "GMAIL_UPDATE_DRAFT", arguments: { user_id: "me", draft_id: "r-123", subject: "From the bot" } };+ // The bot's own update to the same draft is on its way to Gmail when the person presses Save.+ const botCall = guard.run(["r-123"], async () => {+ await new Promise<void>((resolve) => { finish = resolve; });+ gmail.subject = "From the bot";+ showDraftAnswer(store, "t1", "bot-1", [update], new TextEncoder().encode(JSON.stringify(answer("GMAIL_UPDATE_DRAFT", { successful: true, data: { id: "r-123" } }))), 7);+ });+ const { context, sent } = request({ threadId: "t1", messageId: row.id, ...save });+ const pressing = route(context);+ await Promise.resolve();+ expect(ran).toHaveLength(0);+ finish();+ await Promise.all([botCall, pressing]);+ // The edit started from the card before the bot's change: saving every field would undo it.+ expect(sent.status).toBe(409);+ expect(errorKey(sent)).toBe("serverError.emailDraft.changed");+ expect(ran.map((one) => one.slug)).toEqual(["GMAIL_GET_DRAFT"]);+ expect(gmail.subject).toBe("From the bot");+ expect(store.rows[0]!.emailDraft).toMatchObject({ ...shownDraft, subject: "From the bot", draftId: "r-123" });+ });++ it("says why when the Rules or the bot's app permissions refuse, and changes nothing", async () => {+ const { store, row, route } = setup({}, { ok: false, refusal: { error: "Your team's Rules don't allow Gmail." } });+ const { context, sent } = request({ threadId: "t1", messageId: row.id, ...save });+ await route(context);+ expect(sent).toEqual({ status: 403, body: { error: "Your team's Rules don't allow Gmail." } });+ expect(store.rows[0]!.emailDraft).toMatchObject({ ...shownDraft, draftId: "r-123" });+ });++ it("passes Gmail's refusal on and keeps the card live", async () => {+ const { connection } = relayed(() => ({ successful: false, error: "Requested entity was not found." }));+ const { store, row, route } = setup({}, connection);+ const { context, sent } = request({ threadId: "t1", messageId: row.id, ...save });+ await route(context);+ expect(sent.status).toBe(502);+ expect((sent.body as { error: string }).error).toContain("Requested entity was not found.");+ expect(store.rows[0]!.emailDraft).toMatchObject({ ...shownDraft, draftId: "r-123" });+ });++ it("refuses a press it can't read", async () => {+ const { row, route, checked } = setup();+ for (const body of [{ threadId: "t1", messageId: row.id, action: "delete" }, { threadId: "t1", messageId: row.id, action: "save" }]) {+ const { context, sent } = request(body);+ await route(context);+ expect(sent.status).toBe(400);+ }+ expect(checked).toHaveLength(0);+ });++ it("runs nothing when the person loses the conversation or the bot while the call is being set up", async () => {+ for (const lose of ["sees", "mayChat", "inRoom"] as const) {+ // Lost during the handshake, or during the relay's own setup right before the tool call (a session it awaits).+ for (const when of ["initialize", "tools/call"]) {+ let lost = false;+ const { connection: gmail, ran } = relayed(() => ({ successful: true, data: { id: "r-123" } }));+ const connection: DraftConnection = { ok: true, relay: async (payload, session, signal, beforeSend) => {+ if ((payload as { method: string }).method === when) lost = true;+ return (gmail as Relay).relay(payload, session, signal, beforeSend);+ } };+ const { store, row, route } = setup({+ sees: () => !(lost && lose === "sees"), mayChat: () => !(lost && lose === "mayChat"), inRoom: () => lost && lose === "inRoom",+ }, connection);+ const { context, sent } = request({ threadId: "t1", messageId: row.id, ...save });+ await route(context);+ expect(sent.status).toBe(404);+ expect(errorKey(sent)).toBe("serverError.emailDraft.notHere");+ expect(ran).toHaveLength(0);+ expect(store.rows[0]!.emailDraft).toMatchObject({ ...shownDraft, draftId: "r-123" });+ }+ }+ });++ it("saves nothing when Gmail changed since the edit started, and shows what Gmail holds instead", async () => {+ const changed = { ...shownDraft, to: ["[email protected]", "Zoe Z <[email protected]>"], body: "Changed in Gmail." };+ const { connection, ran, gmail } = relayed(() => ({ successful: true, data: { id: "r-123" } }), undefined, { ...changed });+ const { store, row, route } = setup({}, connection);+ const { context, sent } = request({ threadId: "t1", messageId: row.id, ...save });+ await route(context);+ expect(sent.status).toBe(409);+ expect(errorKey(sent)).toBe("serverError.emailDraft.changed");+ expect(ran).toEqual([READ]);+ expect(gmail).toEqual(changed);+ // The card keeps addresses only, as Save sends them to Gmail as addresses.+ expect(store.rows[0]!.emailDraft).toMatchObject({ ...changed, to: ["[email protected]", "[email protected]"], draftId: "r-123" });+ expect(store.rows[0]!.text).toBe('Draft saved in Gmail: "Launch" to [email protected], [email protected].');+ });++ it("keeps a recipient change saved from another conversation's card when an older card saves later", async () => {+ // Two conversations show the same draft. B saves new recipients; A's card still shows the old ones.+ const threads = new Map<string, Message[]>([["tA", []], ["tB", []]]);+ let next = 0;+ const store: DraftCardStore = {+ messagesFor: (thread) => threads.get(thread)!,+ appendMessage: (thread, message) => { const row = { ...message, id: `m${++next}`, at: next } as Message; threads.get(thread)!.push(row); return row; },+ patchMessage: (thread, id, patch) => { const row = threads.get(thread)!.find((one) => one.id === id); if (!row) return null; Object.assign(row, patch); return row; },+ };+ const card = draftCardFrom([createCall], created(), "bot-1")!;+ const rowA = showDraftCard(store, "tA", card)!;+ const rowB = showDraftCard(store, "tB", card)!;+ const { connection, ran, gmail } = relayed(() => ({ successful: true, data: { id: "r-123" } }));+ const route = createEmailDraftRoutes({ store, guard: createDraftGuard(), sees: () => true, inRoom: () => false, mayChat: () => true, connection: async () => connection });+ const fromB = request({ threadId: "tB", messageId: rowB.id, action: "save", base: shownDraft, draft: { ...shownDraft, to: ["[email protected]", "[email protected]"] } });+ await route(fromB.context);+ expect(fromB.sent.status).toBe(200);+ const fromA = request({ threadId: "tA", messageId: rowA.id, action: "save", base: shownDraft, draft: { ...shownDraft, subject: "Launch (typo fixed)" } });+ await route(fromA.context);+ expect(fromA.sent.status).toBe(409);+ expect(errorKey(fromA.sent)).toBe("serverError.emailDraft.changed");+ expect(ran.map((one) => one.slug)).toEqual(["GMAIL_GET_DRAFT", "GMAIL_UPDATE_DRAFT", "GMAIL_GET_DRAFT"]);+ expect(gmail.to).toEqual(["[email protected]", "[email protected]"]);+ expect(gmail.subject).toBe("Launch");+ expect(threads.get("tA")![0]!.emailDraft?.to).toEqual(["[email protected]", "[email protected]"]);+ });++ it("saves nothing when Gmail's body differs only in spacing the person would see, such as an added blank line", async () => {+ for (const body of ["Hi both,\n\nready.", "Hi both, ready.", "Hi both,\nready."]) {+ const { connection, ran, gmail } = relayed(() => ({ successful: true, data: { id: "r-123" } }), undefined, { ...shownDraft, body });+ const { store, row, route } = setup({}, connection);+ const { context, sent } = request({ threadId: "t1", messageId: row.id, ...save });+ await route(context);+ expect(sent.status).toBe(409);+ expect(errorKey(sent)).toBe("serverError.emailDraft.changed");+ expect(ran).toEqual([READ]);+ expect(gmail.body).toBe(body);+ expect(store.rows[0]!.emailDraft!.body).toBe(body);+ }+ });++ it("saves when Gmail holds the same draft written its own way: names on addresses, other order, other line endings", async () => {+ const { connection, ran } = relayed(() => ({ successful: true, data: { id: "r-123" } }), undefined,+ { ...shownDraft, to: ["Ben <[email protected]>", "\"Ana, A.\" <[email protected]>"], body: "Hi both,\r\nready.\r\n" });+ const { row, route } = setup({}, connection);+ const { context, sent } = request({ threadId: "t1", messageId: row.id, ...save });+ await route(context);+ expect(sent.status).toBe(200);+ expect(ran.map((one) => one.slug)).toEqual(["GMAIL_GET_DRAFT", "GMAIL_UPDATE_DRAFT"]);+ });++ it("saves nothing when Gmail's answer doesn't say what the draft holds", async () => {+ const full = heldAnswer(shownDraft) as { data: { message: Record<string, unknown> } };+ const { payload: _headers, ...noHeaders } = full.data.message;+ const { messageText: _text, ...noText } = full.data.message;+ for (const data of [{ id: "r-123" }, { id: "r-123", message: noHeaders }, { id: "r-123", message: noText }]) {+ const gmail = relayed(() => ({ successful: true, data: { id: "r-123" } }));+ const connection: DraftConnection = { ok: true, relay: async (payload, session, signal, beforeSend) => {+ const frame = payload as { id?: unknown; method: string };+ if (frame.method !== "tools/call") return (gmail.connection as Relay).relay(payload, session, signal, beforeSend);+ beforeSend?.();+ gmail.ran.push({ slug: "GMAIL_GET_DRAFT", arguments: {} });+ return { status: 200, bytes: new TextEncoder().encode(JSON.stringify(answer("GMAIL_GET_DRAFT", { successful: true, data }, frame.id))) };+ } };+ const { store, row, route } = setup({}, connection);+ const { context, sent } = request({ threadId: "t1", messageId: row.id, ...save });+ await route(context);+ expect(sent.status).toBe(502);+ expect(errorKey(sent)).toBe("serverError.emailDraft.unreadable");+ expect(gmail.ran.map((one) => one.slug)).toEqual(["GMAIL_GET_DRAFT"]);+ expect(store.rows[0]!.emailDraft).toMatchObject({ ...shownDraft, draftId: "r-123" });+ }+ });+});diff --git a/server/email-draft-card.ts b/server/email-draft-card.tsnew file mode 100644index 0000000000..06ad561601--- /dev/null+++ b/server/email-draft-card.ts@@ -0,0 +1,362 @@+// The draft card: after a bot's Gmail draft call succeeds, the server shows that draft in chat as a card the person can+// edit and save, or open in Gmail to send. Save runs from here through the bot's connected apps, under the same Rules and+// app permissions as the bot's own calls; no model sees or runs it.+// POST /api/email-draft {threadId, messageId, action: "save", base, draft} → {ok: true}+import { z } from "zod";++import { EMAIL_DRAFT_LIMITS, EMAIL_DRAFT_PATH, type EmailDraftCardData, type EmailDraftEdit } from "../shared/email-draft.ts";+import type { ConnectorCall } from "../shared/outbound.ts";+import { toolData } from "./connected-reads.ts";+import { parseMcpResponse } from "./connector-tools-list.ts";+import type { RequestAuth } from "./request-auth.ts";+import { PASS, type RouteHandler } from "./routes/table.ts";+import { serverLine } from "./server-lines.ts";+import type { Message } from "./store.ts";+import { userError, userErrorFields, userErrorThrown, type UserError } from "./user-errors.ts";++export const GMAIL_CREATE_DRAFT = "GMAIL_CREATE_EMAIL_DRAFT";+export const GMAIL_UPDATE_DRAFT = "GMAIL_UPDATE_DRAFT";+export const GMAIL_SEND_DRAFT = "GMAIL_SEND_DRAFT";+export const GMAIL_GET_DRAFT = "GMAIL_GET_DRAFT";+const DRAFT_TOOLS = [GMAIL_CREATE_DRAFT, GMAIL_UPDATE_DRAFT];+export const isDraftTool = (slug: string): boolean => DRAFT_TOOLS.includes(slug);+const MULTI_EXECUTE = "COMPOSIO_MULTI_EXECUTE_TOOL";+const CALL_ID = "omb-email-draft";+const CALL_TIMEOUT_MS = 60_000;++type Row = Record<string, unknown>;+const record = (value: unknown): Row | undefined => (value && typeof value === "object" && !Array.isArray(value) ? value as Row : undefined);+const text = (value: unknown): string | undefined => (typeof value === "string" && value.trim() ? value.trim() : undefined);+const list = (value: unknown): string[] => (Array.isArray(value) ? value : typeof value === "string" ? [value] : [])+ .map(text).filter((one): one is string => one !== undefined);+const httpsUrl = (value: unknown): string | undefined => {+ const url = text(value);+ if (!url) return undefined;+ try {+ const parsed = new URL(url);+ return parsed.protocol === "https:" && !parsed.username && !parsed.password ? parsed.href : undefined;+ } catch {+ return undefined;+ }+};++/** A Composio tool answer, unwrapped from `response_data` when it is wrapped. */+const answerOf = (data: unknown) => record(record(data)?.response_data) ?? record(data);++/** The card for the one draft call in `calls` the answer says succeeded, or null (none, several, or it failed). An update+ * leaves in Gmail what it omits, so each omitted field keeps its value from `shown` (the card already showing that draft);+ * with no such card an update that omits a field shows none, rather than a draft Gmail doesn't have. */+export function draftCardFrom(calls: readonly ConnectorCall[], frame: Row | null, botId: string, shown?: (draftId: string) => EmailDraftCardData | undefined): EmailDraftCardData | null {+ const drafts = calls.filter((call) => isDraftTool(call.slug));+ if (drafts.length !== 1) return null;+ const [call] = drafts;+ let data: Row | undefined;+ try {+ data = record(toolData(call.slug, frame));+ } catch {+ return null;+ }+ const args = record(call.arguments) ?? {};+ const body = answerOf(data);+ const draftId = text(body?.id) ?? (call.slug === GMAIL_UPDATE_DRAFT ? text(args.draft_id) : undefined);+ if (!draftId) return null;+ const update = call.slug === GMAIL_UPDATE_DRAFT;+ const before = update ? shown?.(draftId) : undefined;+ const given = (...keys: string[]) => !update || keys.some((key) => args[key] !== undefined);+ const fields = [given("recipient_email"), given("extra_recipients"), given("cc"), given("bcc"), given("subject"), given("body", "message_body"), given("is_html")];+ if (!before && fields.includes(false)) return null;+ const [first, rest, cc, bcc, subject, message, html] = fields;+ const threadId = text(record(body?.message)?.threadId) ?? text(args.thread_id) ?? before?.threadId;+ const url = httpsUrl(body?.display_url) ?? httpsUrl(record(body?.message)?.display_url) ?? before?.url;+ const account = call.account ?? before?.account;+ // The card's first address is the draft's recipient_email, the rest its extra_recipients (as draftCall saves them), so a+ // draft with others but no recipient_email gets no card: a later update naming only one of the two couldn't be placed.+ const recipient = first ? list(args.recipient_email) : before!.to.slice(0, 1);+ const others = rest ? list(args.extra_recipients) : before!.to.slice(1);+ if (!recipient.length && others.length) return null;+ return {+ app: "gmail", draftId, botId,+ to: [...recipient, ...others],+ cc: cc ? list(args.cc) : before!.cc,+ bcc: bcc ? list(args.bcc) : before!.bcc,+ subject: !subject ? before!.subject : typeof args.subject === "string" ? args.subject : "",+ body: !message ? before!.body : typeof args.body === "string" ? args.body : typeof args.message_body === "string" ? args.message_body : "",+ ...((html ? args.is_html === true : before!.html) ? { html: true as const } : {}),+ ...(threadId ? { threadId } : {}),+ ...(account ? { account } : {}),+ ...(url ? { url } : {}),+ };+}++/** The draft id of the one send call in `calls` the answer says succeeded, or null. */+export function sentDraftFrom(calls: readonly ConnectorCall[], frame: Row | null): string | null {+ const sends = calls.filter((call) => call.slug === GMAIL_SEND_DRAFT);+ if (sends.length !== 1) return null;+ try {+ toolData(GMAIL_SEND_DRAFT, frame);+ } catch {+ return null;+ }+ return text(record(sends[0].arguments)?.draft_id) ?? null;+}++/** The line every client without the card shows, and the bot reads back as a record. */+export function draftCardText(card: EmailDraftCardData, language?: string): string {+ const to = card.to.length ? card.to.join(", ") : serverLine(language, "server.emailDraft.noRecipient");+ const subject = card.subject.trim() || serverLine(language, "server.emailDraft.noSubject");+ return serverLine(language, card.sentAt ? "server.emailDraft.sent" : "server.emailDraft.saved", { subject, to });+}++export interface DraftCardStore {+ messagesFor(threadId: string): Message[];+ appendMessage(threadId: string, message: Omit<Message, "id" | "at">): Message;+ patchMessage(threadId: string, messageId: string, patch: Partial<Message>): Message | null;+}++const cardOf = (store: DraftCardStore, threadId: string, draftId: string, botId: string) =>+ store.messagesFor(threadId).find((message) => message.emailDraft?.draftId === draftId && message.emailDraft.botId === botId);++/** Shows `card` in the thread: a draft already on a card there gets that card updated (and live again), else a new one. */+export function showDraftCard(store: DraftCardStore, threadId: string, card: EmailDraftCardData, language?: string): Message | null {+ const shown = cardOf(store, threadId, card.draftId, card.botId);+ const fields = { text: draftCardText(card, language), emailDraft: card };+ if (shown) return store.patchMessage(threadId, shown.id, fields);+ return store.appendMessage(threadId, { role: "bot", kind: "text", serverCard: true, ...fields });+}++/** The existing drafts `calls` change or send in Gmail. */+export const draftIdsIn = (calls: readonly ConnectorCall[]): string[] =>+ calls.filter((call) => call.slug === GMAIL_UPDATE_DRAFT || call.slug === GMAIL_SEND_DRAFT)+ .map((call) => text(record(call.arguments)?.draft_id)).filter((one): one is string => one !== undefined);++/** One Gmail call per draft at a time, shared by the card's Save and the bot's own draft calls, so their changes reach+ * Gmail and the card in the same order. */+export interface DraftGuard {+ run<T>(draftIds: readonly string[], work: () => Promise<T>): Promise<T>;+}++export function createDraftGuard(): DraftGuard {+ const tails = new Map<string, Promise<unknown>>();+ const one = <T>(draftId: string, work: () => Promise<T>): Promise<T> => {+ const ran = (tails.get(draftId) ?? Promise.resolve()).then(work);+ const tail = ran.catch(() => undefined);+ tails.set(draftId, tail);+ void tail.then(() => { if (tails.get(draftId) === tail) tails.delete(draftId); });+ return ran;+ };+ return {+ // Several drafts are taken in sorted order, so two callers never each hold one the other waits for.+ run: <T>(draftIds: readonly string[], work: () => Promise<T>) =>+ [...new Set(draftIds)].sort().reduceRight((next: () => Promise<T>, draftId) => () => one(draftId, next), work)(),+ };+}++/** After the bot's relayed Gmail call succeeds (raw JSON or event-stream bytes): a saved draft shows or updates its card,+ * a draft the bot sent turns its card into what was sent. Never throws: the card only shows the call, which already ran. */+export function showDraftAnswer(store: DraftCardStore, threadId: string, botId: string, calls: readonly ConnectorCall[], bytes: Uint8Array, id: unknown, language?: string): void {+ if (!calls.some((call) => isDraftTool(call.slug) || call.slug === GMAIL_SEND_DRAFT)) return;+ let frame: Row | null;+ try {+ frame = parseMcpResponse(new TextDecoder().decode(bytes), id);+ } catch {+ return;+ }+ try {+ const card = draftCardFrom(calls, frame, botId, (draftId) => cardOf(store, threadId, draftId, botId)?.emailDraft);+ if (card) showDraftCard(store, threadId, card, language);+ const sent = sentDraftFrom(calls, frame);+ const shown = sent ? cardOf(store, threadId, sent, botId) : undefined;+ if (shown?.emailDraft && !shown.emailDraft.sentAt) {+ const next = { ...shown.emailDraft, sentAt: Date.now() };+ store.patchMessage(threadId, shown.id, { text: draftCardText(next, language), emailDraft: next });+ }+ } catch (error) {+ console.warn("email draft card: could not show the bot's Gmail draft", error);+ }+}++type Refusal = UserError | { error: string };++/** Thrown by a relay that checks the Rules, the bot's app permissions and the person's access again right before it+ * sends, and finds a refusal. */+export class DraftRefused extends Error {+ readonly refusal: Refusal;+ readonly status: number;+ constructor(refusal: Refusal, status = 403) {+ super(refusal.error);+ this.refusal = refusal;+ this.status = status;+ }+}++/** The relay to the connected-apps service a press runs through, or why it can't run. Right before it sends (after any+ * setup it awaits) it runs `beforeSend` and its own checks; either throws DraftRefused to stop the call. */+export type DraftConnection =+ | { ok: true; relay(payload: unknown, transportSessionId: string | undefined, signal: AbortSignal, beforeSend?: () => void): Promise<{ status: number; bytes: Uint8Array; transportSessionId?: string }> }+ | { ok: false; refusal: Refusal };++export interface EmailDraftRouteDeps {+ sees(auth: RequestAuth, threadId: string): boolean;+ /** A room's conversation: its draft cards are view-only. */+ inRoom(threadId: string): boolean;+ /** The person may write to this bot. */+ mayChat(auth: RequestAuth, botId: string): boolean;+ store: DraftCardStore;+ /** Shared with the bot's own draft calls. */+ guard: DraftGuard;+ /** The bot's connection for `calls`, as the person pressing: checked against the Rules and the bot's app permissions. */+ connection(auth: RequestAuth, botId: string, calls: ConnectorCall[]): Promise<DraftConnection>;+ /** The conversation's language for the card's line. */+ language?(threadId: string): string | undefined;+}++const address = z.string().trim().min(1).max(EMAIL_DRAFT_LIMITS.address);+const addresses = z.array(address).max(EMAIL_DRAFT_LIMITS.recipients);+const edit = z.object({+ to: addresses, cc: addresses, bcc: addresses,+ subject: z.string().max(EMAIL_DRAFT_LIMITS.subject), body: z.string().max(EMAIL_DRAFT_LIMITS.body),+}).strict();+/** The addresses in To/Cc/Bcc values ("Ana <[email protected]>, [email protected]"), split on commas outside quotes. */+const entriesIn = (values: readonly string[]): string[] =>+ values.flatMap((value) => value.split(/,(?=(?:[^"]*"[^"]*")*[^"]*$)/)).map((one) => one.trim()).filter(Boolean);+/** The address in an entry, without its display name ("Ana <[email protected]>" is "[email protected]"). */+const addressOf = (entry: string) => (/<([^<>]*)>\s*$/.exec(entry)?.[1] ?? entry).trim();+const bare = (entry: string) => addressOf(entry).toLowerCase();+const sameAddresses = (a: readonly string[], b: readonly string[]) =>+ JSON.stringify(entriesIn(a).map(bare).sort()) === JSON.stringify(entriesIn(b).map(bare).sort());+/** A plain body as the person reads it: Gmail's line endings and the spaces it leaves at line ends don't count; every+ * other space and blank line does. */+const bodyText = (value: string) => value.replace(/\r\n?/g, "\n").replace(/[ \t]+$/gm, "").trimEnd();++/** The draft as Gmail holds it now, from GMAIL_GET_DRAFT's answer (addresses without display names; the body only when+ * Gmail gives its text), or undefined when the answer doesn't carry the message's headers. */+export function gmailDraftOf(data: unknown): (Omit<EmailDraftEdit, "body"> & { body?: string }) | undefined {+ const message = record(answerOf(data)?.message);+ const headers = record(message?.payload)?.headers;+ if (!message || !Array.isArray(headers)) return undefined;+ const values = (name: string) => headers.map(record).filter((one) => typeof one?.name === "string" && one.name.toLowerCase() === name)+ .map((one) => (typeof one!.value === "string" ? one!.value : ""));+ const addresses = (name: string) => entriesIn(values(name)).map(addressOf).filter(Boolean);+ return {+ to: addresses("to"), cc: addresses("cc"), bcc: addresses("bcc"),+ subject: values("subject")[0] ?? "",+ ...(typeof message.messageText === "string" ? { body: message.messageText } : {}),+ };+}++/** Whether Gmail still holds `base`, the draft the person started editing from. An HTML body is not compared (the card+ * doesn't edit one); a plain one is compared line by line, so a blank line or a space added in Gmail counts. */+export function draftUnchanged(base: EmailDraftEdit, gmail: NonNullable<ReturnType<typeof gmailDraftOf>>, html: boolean): boolean {+ return sameAddresses(base.to, gmail.to) && sameAddresses(base.cc, gmail.cc) && sameAddresses(base.bcc, gmail.bcc)+ && base.subject.trim() === gmail.subject.trim() && (html || bodyText(base.body) === bodyText(gmail.body ?? ""));+}++const where = { threadId: z.string().min(1).max(200), messageId: z.string().min(1).max(200) };+// `base`: the draft as the card showed it when the person started editing, so Save can tell whether Gmail changed since.+const press = z.object({ ...where, action: z.literal("save"), base: edit, draft: edit }).strict();++/** The Composio call Save makes with the edited `draft`. */+export function draftCall(card: EmailDraftCardData, draft: EmailDraftEdit): ConnectorCall {+ const account = card.account ? { account: card.account } : {};+ const [first, ...rest] = draft.to;+ return {+ slug: GMAIL_UPDATE_DRAFT,+ arguments: {+ user_id: "me", draft_id: card.draftId, recipient_email: first ?? "", extra_recipients: rest,+ cc: draft.cc, bcc: draft.bcc, subject: draft.subject, body: draft.body, is_html: card.html === true,+ ...(card.threadId ? { thread_id: card.threadId } : {}),+ },+ ...account,+ };+}++const unreachable = (status: number) => userErrorThrown("serverError.emailDraft.unreachable", { status });++type RunCall = (call: ConnectorCall, dispatch: () => void) => Promise<unknown>;++/** Opens one MCP session for Save's calls, each with its own id and time limit. Each call's `dispatch` runs right before it goes out to+ * Gmail, and may refuse it by throwing DraftRefused. */+async function openSession(connection: Extract<DraftConnection, { ok: true }>): Promise<RunCall> {+ const opening = AbortSignal.timeout(CALL_TIMEOUT_MS);+ const init = await connection.relay({+ jsonrpc: "2.0", id: `${CALL_ID}-init`, method: "initialize",+ params: { protocolVersion: "2025-03-26", capabilities: {}, clientInfo: { name: "openmausbot-email-draft", version: "1" } },+ }, undefined, opening);+ if (init.status !== 200) throw unreachable(init.status);+ await connection.relay({ jsonrpc: "2.0", method: "notifications/initialized" }, init.transportSessionId, opening).catch(() => undefined);+ let calls = 0;+ return async (call, dispatch) => {+ const id = `${CALL_ID}-${++calls}`;+ const answer = await connection.relay({+ jsonrpc: "2.0", id, method: "tools/call",+ params: { name: MULTI_EXECUTE, arguments: { tools: [{ tool_slug: call.slug, arguments: call.arguments, ...(call.account ? { account: call.account } : {}) }] } },+ }, init.transportSessionId, AbortSignal.timeout(CALL_TIMEOUT_MS), dispatch);+ if (answer.status !== 200) throw unreachable(answer.status);+ return toolData(call.slug, parseMcpResponse(new TextDecoder().decode(answer.bytes), id));+ };+}++export function createEmailDraftRoutes(deps: EmailDraftRouteDeps): RouteHandler {+ // One press per card at a time, so a double tap saves once.+ const pressing = new Set<string>();+ return async ({ req, res, path, method, auth, json, readBody }) => {+ if (path !== EMAIL_DRAFT_PATH) return PASS;+ if (method !== "POST") return json(res, 405, { error: "Use POST." });+ let raw: unknown;+ try { raw = await readBody(req, 256_000); } catch { return json(res, 400, { error: "Send threadId, messageId and action." }); }+ const parsed = press.safeParse(raw);+ if (!parsed.success) return json(res, 400, { error: "Send threadId, messageId and action." });+ const { threadId, messageId, base, draft } = parsed.data;+ const card = () => deps.store.messagesFor(threadId).find((message) => message.id === messageId)?.emailDraft;+ const shown = deps.sees(auth, threadId) && !deps.inRoom(threadId) ? card() : undefined;+ if (!shown || !deps.mayChat(auth, shown.botId)) return json(res, 404, userError("serverError.emailDraft.notHere"));+ const key = `${threadId}:${messageId}`;+ if (pressing.has(key)) return json(res, 409, userError("serverError.emailDraft.busy"));+ pressing.add(key);+ try {+ // Run while no bot call can change this draft, so Gmail and the card take the changes in the same order.+ return await deps.guard.run([shown.draftId], async () => {+ const now = card();+ if (!now) return json(res, 404, userError("serverError.emailDraft.notHere"));+ if (now.sentAt) return json(res, 409, userError("serverError.emailDraft.alreadySent"));+ const call = draftCall(now, draft);+ const read: ConnectorCall = { slug: GMAIL_GET_DRAFT, arguments: { user_id: "me", draft_id: now.draftId, format: "full" }, ...(now.account ? { account: now.account } : {}) };+ const connection = await deps.connection(auth, now.botId, [read, call]);+ if (!connection.ok) return json(res, 403, connection.refusal);+ // The person may have lost the conversation or the bot while the call waited for the draft or was set up.+ const stillHere = () => {+ if (!deps.sees(auth, threadId) || deps.inRoom(threadId) || !deps.mayChat(auth, now.botId)) {+ throw new DraftRefused(userError("serverError.emailDraft.notHere"), 404);+ }+ };+ const show = (next: EmailDraftCardData) =>+ deps.store.patchMessage(threadId, messageId, { text: draftCardText(next, deps.language?.(threadId)), emailDraft: next });+ let data: unknown;+ try {+ const run = await openSession(connection);+ // Gmail first: another card, the bot or Gmail itself may have changed the draft since the person started+ // editing, and saving every field would undo that change. Then the card shows what Gmail holds, and nothing is saved.+ const held = gmailDraftOf(await run(read, stillHere));+ if (!held || (held.body === undefined && !now.html)) return json(res, 502, userError("serverError.emailDraft.unreadable"));+ if (!draftUnchanged(base, held, now.html === true)) {+ const latest = card();+ if (latest) show({ ...latest, to: held.to, cc: held.cc, bcc: held.bcc, subject: held.subject, ...(held.body !== undefined && !latest.html ? { body: held.body } : {}) });+ return json(res, 409, userError("serverError.emailDraft.changed"));+ }+ data = await run(call, stillHere);+ } catch (error) {+ if (error instanceof DraftRefused) return json(res, error.status, error.refusal);+ const known = userErrorFields(error);+ const message = error instanceof Error ? error.message : String(error);+ return json(res, 502, known.errorKey ? { error: message, ...known } : userError("serverError.emailDraft.refused", { detail: message.slice(0, 300) }));+ }+ const current = card();+ if (!current) return json(res, 200, { ok: true });+ show({ ...current, ...draft, draftId: text(record(data)?.id) ?? current.draftId });+ return json(res, 200, { ok: true });+ });+ } finally {+ pressing.delete(key);+ }+ };+}diff --git a/server/host/email-draft-host.ts b/server/host/email-draft-host.tsnew file mode 100644index 0000000000..bfc3084cd3--- /dev/null+++ b/server/host/email-draft-host.ts@@ -0,0 +1,59 @@+// The connection a draft card's Save runs through: the bot's connected apps, as the person pressing, checked against the+// Rules and the bot's app permissions. index.ts builds it once and hands it what it needs.+import { connectorAccessDecision, type ConnectorScopes } from "../../shared/connector-scopes.ts";+import type { ConnectorCall } from "../../shared/outbound.ts";+import type { ConnectorToolGrant } from "../../shared/wire.ts";+import * as composio from "../composio.ts";+import type { AppConfig } from "../config.ts";+import { evaluateConnectorTools } from "../connector-verdict.ts";+import { DraftRefused, type DraftConnection } from "../email-draft-card.ts";+import type { createTeamConnectionsHost } from "./team-connections-host.ts";+import type { ManagedDesktopPolicy } from "../managed-policy.ts";+import type { RequestAuth } from "../request-auth.ts";+import { userError } from "../user-errors.ts";++type Bot = { name: string; composio?: boolean; connectorTools?: Record<string, ConnectorToolGrant>; connectorScopes?: ConnectorScopes };++export interface DraftConnectionDeps {+ bot(id: string): Bot | null | undefined;+ cfg(): AppConfig;+ teamConnections: Pick<ReturnType<typeof createTeamConnectionsHost>, "personApps" | "people" | "via">;+ rules: Pick<ManagedDesktopPolicy, "appsCallRefusal">;+ /** The signed-in person's key, for their own app connections. */+ person(auth: RequestAuth & { kind: "session" }): string;+}++export function createDraftConnection(deps: DraftConnectionDeps): (auth: RequestAuth, botId: string, calls: ConnectorCall[]) => Promise<DraftConnection> {+ const appsOn = (bot: Bot | null | undefined): bot is Bot => Boolean(bot) && bot!.composio !== false && composio.configured(deps.cfg());+ return async (auth, botId, calls) => {+ if (!appsOn(deps.bot(botId))) return { ok: false, refusal: userError("serverError.emailDraft.appsOff") };+ const { teamConnections } = deps;+ // Where each person connects Gmail themselves, the person pressing uses their own; the draft is only in the mailbox that saved it.+ const own = teamConnections.personApps().includes("gmail") ? (auth.kind === "session" ? teamConnections.people.appsAccess(deps.person(auth)) : null) : undefined;+ if (own === null) return { ok: false, refusal: userError("serverError.emailDraft.ownGmail") };+ const via = teamConnections.via(own);+ const services = await composio.connectedServiceSlugs(...via).catch(() => null);+ if (!services) return { ok: false, refusal: userError("serverError.emailDraft.appsDown") };+ // The bot read fresh against the Rules and its app permissions: now, and again right before the call goes out (they+ // may change during the lookup), after the card's own check of the person.+ const refusal = () => {+ const fresh = deps.bot(botId);+ if (!appsOn(fresh)) return userError("serverError.emailDraft.appsOff");+ const rules = deps.rules.appsCallRefusal(calls, services);+ if (rules) return { error: rules };+ const allowed = connectorAccessDecision(fresh.connectorScopes, calls, services).ok+ && (fresh.connectorTools === undefined || evaluateConnectorTools(calls.map((one) => one.slug), fresh.connectorTools, services).allowed);+ return allowed ? undefined : userError("serverError.emailDraft.notAllowed", { name: fresh.name });+ };+ const now = refusal();+ if (now) return { ok: false, refusal: now };+ return {+ ok: true,+ relay: (payload, session, signal, beforeSend) => composio.relayMcp(via[0], payload as never, session, () => {+ beforeSend?.();+ const later = refusal();+ if (later) throw new DraftRefused(later);+ }, signal, via[1]),+ };+ };+}diff --git a/server/index.ts b/server/index.tsindex 95e68130c3..a06d2af790 100644--- a/server/index.ts+++ b/server/index.ts@@ -1,7 +1,7 @@// Import first: it reads a Cloud home's secrets off the launcher's pipe before any module can start a process.import { BOOT_CLOUD_SECRETS } from "./cloud-secrets-boot.ts";import { startFailureText } from "./start-failure-text.ts";-import { reserveGmailDrafts } from "./gmail-draft-policy.ts";+import { reserveGmailDrafts } from "./gmail-draft-policy.ts"; import { createDraftGuard, createEmailDraftRoutes, draftIdsIn, showDraftAnswer } from "./email-draft-card.ts"; import { createDraftConnection } from "./host/email-draft-host.ts";import { createGmailDrafts } from "./host/gmail-drafts.ts";import { AsyncLocalStorage } from "node:async_hooks";import { createHash, randomBytes, randomUUID, timingSafeEqual } from "node:crypto";@@ -11900,7 +11900,7 @@ let restartRequested = false;const cloudMoveRoutes = createCloudMoveRoutes();// `workspaceAccess` is assigned at boot, after this line: read it per request.-ROUTES.push(createHostedSlackRoutes({ bot: (id) => store.bot(id), hostedReady: () => Boolean(workspaceAccess) && entitled("admin") })); ROUTES.push(createStopLineRoutes()); ROUTES.push(createSuggestedReplyRoutes({ enabled: () => cfg.features?.suggestedReplies !== false, owns: (botId, threadId) => store.bot(botId)?.threadId === threadId || Boolean(store.taskByThread(botId, threadId)), sees: (auth, threadId) => visibleTo(viewerFor(auth)).thread(threadId), mayChat: (auth, botId) => ["chat", "edit"].includes(levelOf(auth, botId)), messages: (threadId) => store.activePath(threadId), busy: threadBusy, writer: (botId) => sideJobs.text("suggested-reply", botId) })); const skillBurgerRuns = createSkillBurgerRuns({ dataDir: DATA_DIR, host: { port: PORT, cwd: (botId, threadId) => store.taskByThread(botId, threadId)?.cwd || store.bot(botId)?.cwd || workspaceDir(botId), mint: (turn, kind) => mintInternalCapability({ ...(turn as unknown as InternalCapability), kind, depth: 0, skillAuthoring: false, createdBots: 0, openedThreads: 0 }), browser: async (turn) => { const bot = store.bot(turn.botId); return bot ? ((await browserIntegration(bot.id, bot.browserProfile, { threadId: turn.threadId, generation: turn.generation }))?.integration as { env?: Record<string, string | undefined> } | undefined) ?? null : null; }, publish: (threadId, event) => { const engine = runningTurnEngines.get(threadId); bus.publish({ ...event, provider: engine?.driverKind, providerInstanceId: engine?.instanceId } as unknown as RuntimeEvent); }, mayEditBurgers: () => !CLOUD_TEAM, connectedApps: async (turn) => { const bot = store.bot(turn.botId); if (!bot || bot.composio === false || !composio.configured(cfg)) return []; const actor = teamConnections.relayActor(turn as unknown as { threadId: string; generation: string; connectorsFor?: string }); return actor.refusal ? null : composio.connectedServiceSlugs(...teamConnections.via(actor.access)); } } }); try { const moved = migrateBotBurgers(store.bots.map((bot) => bot.id)); if (moved.length) console.log(`skill burgers: moved ${moved.length} saved by one bot into every chat`); } catch (error) { console.warn("skill burgers: could not move bots' own burgers into every chat", error); } ROUTES.push(createSkillBurgerRoutes({ messages: (threadId) => store.activePath(threadId), botIds: () => store.bots.map((bot) => bot.id), owns: (botId, threadId) => store.bot(botId)?.threadId === threadId || Boolean(store.taskByThread(botId, threadId)), sees: (auth, threadId) => visibleTo(viewerFor(auth)).thread(threadId), summarize: (botId, prompt) => sideJobs.text("skill-burger", botId)?.generateText(prompt, { timeoutMs: 10_000 }) ?? Promise.resolve(null), levelOf, actorOf: (auth) => (auth.kind === "session" ? actorKey(auth) : null), teammate: (idOrName) => { const bot = store.bot(idOrName) ?? store.bots.find((one) => one.name.toLowerCase() === idOrName.toLowerCase()); return bot ? { id: bot.id, name: bot.name, ...(bot.title ? { role: bot.title } : {}) } : undefined; }, history: skillBurgerRuns.history }));+ROUTES.push(createHostedSlackRoutes({ bot: (id) => store.bot(id), hostedReady: () => Boolean(workspaceAccess) && entitled("admin") })); ROUTES.push(createStopLineRoutes()); const draftGuard = createDraftGuard(); ROUTES.push(createEmailDraftRoutes({ store, guard: draftGuard, language: conversationLanguage, sees: (auth, threadId) => visibleTo(viewerFor(auth)).thread(threadId), inRoom: (threadId) => Boolean(store.groupByThread(threadId)), mayChat: (auth, botId) => ["chat", "edit"].includes(levelOf(auth, botId)), connection: createDraftConnection({ bot: (id) => store.bot(id), cfg: () => cfg, teamConnections, rules: managedPolicy, person: actorKey }) })); ROUTES.push(createSuggestedReplyRoutes({ enabled: () => cfg.features?.suggestedReplies !== false, owns: (botId, threadId) => store.bot(botId)?.threadId === threadId || Boolean(store.taskByThread(botId, threadId)), sees: (auth, threadId) => visibleTo(viewerFor(auth)).thread(threadId), mayChat: (auth, botId) => ["chat", "edit"].includes(levelOf(auth, botId)), messages: (threadId) => store.activePath(threadId), busy: threadBusy, writer: (botId) => sideJobs.text("suggested-reply", botId) })); const skillBurgerRuns = createSkillBurgerRuns({ dataDir: DATA_DIR, host: { port: PORT, cwd: (botId, threadId) => store.taskByThread(botId, threadId)?.cwd || store.bot(botId)?.cwd || workspaceDir(botId), mint: (turn, kind) => mintInternalCapability({ ...(turn as unknown as InternalCapability), kind, depth: 0, skillAuthoring: false, createdBots: 0, openedThreads: 0 }), browser: async (turn) => { const bot = store.bot(turn.botId); return bot ? ((await browserIntegration(bot.id, bot.browserProfile, { threadId: turn.threadId, generation: turn.generation }))?.integration as { env?: Record<string, string | undefined> } | undefined) ?? null : null; }, publish: (threadId, event) => { const engine = runningTurnEngines.get(threadId); bus.publish({ ...event, provider: engine?.driverKind, providerInstanceId: engine?.instanceId } as unknown as RuntimeEvent); }, mayEditBurgers: () => !CLOUD_TEAM, connectedApps: async (turn) => { const bot = store.bot(turn.botId); if (!bot || bot.composio === false || !composio.configured(cfg)) return []; const actor = teamConnections.relayActor(turn as unknown as { threadId: string; generation: string; connectorsFor?: string }); return actor.refusal ? null : composio.connectedServiceSlugs(...teamConnections.via(actor.access)); } } }); try { const moved = migrateBotBurgers(store.bots.map((bot) => bot.id)); if (moved.length) console.log(`skill burgers: moved ${moved.length} saved by one bot into every chat`); } catch (error) { console.warn("skill burgers: could not move bots' own burgers into every chat", error); } ROUTES.push(createSkillBurgerRoutes({ messages: (threadId) => store.activePath(threadId), botIds: () => store.bots.map((bot) => bot.id), owns: (botId, threadId) => store.bot(botId)?.threadId === threadId || Boolean(store.taskByThread(botId, threadId)), sees: (auth, threadId) => visibleTo(viewerFor(auth)).thread(threadId), summarize: (botId, prompt) => sideJobs.text("skill-burger", botId)?.generateText(prompt, { timeoutMs: 10_000 }) ?? Promise.resolve(null), levelOf, actorOf: (auth) => (auth.kind === "session" ? actorKey(auth) : null), teammate: (idOrName) => { const bot = store.bot(idOrName) ?? store.bots.find((one) => one.name.toLowerCase() === idOrName.toLowerCase()); return bot ? { id: bot.id, name: bot.name, ...(bot.title ? { role: bot.title } : {}) } : undefined; }, history: skillBurgerRuns.history }));const orgInstallStatuses = () => orgLibrary?.installStatuses() ?? new Map();ROUTES.push(createBotPresetRoutes({ presets: presetStore, orgStatuses: orgInstallStatuses })); ROUTES.push(createBotHoldRoutes({ holds: botHolds, named: (kind, id) => (kind === "bot" ? store.bot(id)?.name ?? null : store.sections.includes(id.trim()) ? id.trim() : null), stop: async (botIds) => { let stopped = 0; for (const botId of botIds) { for (const { threadId } of store.tasks(botId)) if (threadBusy(botId, threadId) || coordinator.activeDirect(threadId)) { await stopThreadForPerson(botId, threadId); stopped++; } for (const group of store.groups) if (roomThreadIds(group).some((threadId) => groupSpeakers.get(threadId)?.botId === botId)) { await interruptHeldMember(group.id, botId); stopped++; } } return stopped; }, audit: (entry, auth, req) => { if (!DESKTOP_MANAGED && adminActivityRecording()) appendAdminAction(DATA_DIR, { category: "bot", action: `${entry.kind}.${entry.paused ? "pause" : "resume"}`, target: { kind: entry.kind, id: entry.id, name: entry.name }, actor: adminActorFor(auth, req) }); }, bots: () => store.bots.map((bot) => bot.id) })); const cliLogin = createCliLogin({ sessions, refusal: () => (HOSTED_WORKSPACE ? "Sign in through the workspace portal." : null), loopbackRefusal: () => (LOOPBACK.trust === "service" ? "on this shared server a program here may not ask to sign in: run openmausbot login on your own computer" : null), environment: () => environmentDescriptor({ environmentId: ENVIRONMENT_ID, ...TEAM_LABEL, desktopManaged: DESKTOP_MANAGED, emailSignIn: !CLOUD_HOME && emailSignIn.enabled(), sharedComputers: lendingEnabled(), cloudHome: Boolean(CLOUD_HOME), cloudTeam: CLOUD_TEAM !== null, ownHome: ownHome.takesMove() }), changed: () => broadcast({ kind: "cli-login" }, { adminOnly: true }), ...(CLOUD_TEAM ? { opened: (session) => teamHost.met(session) } : {}) }); ROUTES.push(cliLogin.routes); ROUTES.push(createWorkspaceBannerRoutes({ changed: () => broadcast({ kind: "config", ...configStatus() }) })); ROUTES.unshift(createUsageCapRoutes({ view: () => usageCapGate.view(), botExists: (botId) => Boolean(store.bot(botId)), save: (usageCaps) => { saveConfig({ usageCaps }); Object.assign(cfg, loadConfig()); } })); const starterAwakeRoutes = createStarterAwakeRoutes({ awake: starterAwake }); ROUTES.push(starterAwakeRoutes);ROUTES.push(createSharedComputerRoutes({ enabled: (auth) => lendingEnabled() || (ownerLends() && ownHome.owner(auth)), computers: sharedComputers, sessionLive: (id) => sessions.isLive(id), environmentId: ENVIRONMENT_ID,@@ -14245,7 +14245,7 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {throw new Error(text);};let upstream: Awaited<ReturnType<typeof composio.relayMcp>>;- try { upstream = await composio.relayMcp(+ try { upstream = await draftGuard.run(draftIdsIn(connectorCalls), async () => { const answer = await composio.relayMcp(teamConnections.via(actor.access)[0],body,Array.isArray(req.headers["mcp-session-id"])@@ -14277,7 +14277,7 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {}const sent = files.upload ? await files.upload().catch((error: unknown) => refuseDispatch(error instanceof Error ? error.message : String(error))) : undefined; requireActiveInternalCapability(); for (const key of nextDrafts) reservedDrafts.add(key); return sent as typeof body | undefined;}, undefined, teamConnections.via(actor.access)[1],- ); } catch (error) {+ ); if (answer.status === 200 && connectorCalls.length) showDraftAnswer(store, internalCapability.threadId, internalCapability.botId, connectorCalls, answer.bytes, rpc?.id, conversationLanguage(internalCapability.threadId)); return answer; }); } catch (error) {if (dispatchRefusal) return refuseOutbound(dispatchRefusal);throw error;}diff --git a/server/request-auth.ts b/server/request-auth.tsindex 05eeb9b10c..55fbad4f16 100644--- a/server/request-auth.ts+++ b/server/request-auth.ts@@ -376,6 +376,8 @@ export const CLIENT_ALLOW: ReadonlyArray<{ methods: readonly string[]; path: Reg{ methods: ["POST"], path: /^\/api\/stop-line$/ },// One suggested next line for a conversation the caller reads and may write in (routes/suggested-reply.ts).{ methods: ["POST"], path: /^\/api\/suggested-reply$/ },+ // Save or send a draft card in a conversation the caller reads and may write in (email-draft-card.ts).+ { methods: ["POST"], path: /^\/api\/email-draft$/ },{ methods: ["POST"], path: /^\/api\/bots\/[\w-]+\/messages\/[\w-]+\/edit$/ },{ methods: ["POST", "DELETE"], path: /^\/api\/bots\/[\w-]+\/setup-request$/ }, // Set me up: what a typed /setup could do{ methods: ["POST"], path: /^\/api\/bots\/[\w-]+\/active-branch$/ },diff --git a/server/user-errors.ts b/server/user-errors.tsindex 332831c711..2988e911cf 100644--- a/server/user-errors.ts+++ b/server/user-errors.ts@@ -24,6 +24,17 @@ export const USER_ERROR = {"serverError.chat.busyVersion": "the thread is working — stop it before switching versions","serverError.forkBusy": "Wait for this conversation to finish before forking it.","serverError.forkNoText": "This conversation has no text message to fork from yet.",+ "serverError.emailDraft.notHere": "That draft is not in this conversation.",+ "serverError.emailDraft.alreadySent": "This email was already sent.",+ "serverError.emailDraft.busy": "This draft is still being saved.",+ "serverError.emailDraft.appsOff": "Connected apps are off for this bot.",+ "serverError.emailDraft.ownGmail": "Connect your own Gmail in Apps to save this draft.",+ "serverError.emailDraft.appsDown": "Apps can't be reached right now. Try again in a few minutes.",+ "serverError.emailDraft.notAllowed": "{name} may not save Gmail drafts. Change its app permissions to allow it.",+ "serverError.emailDraft.unreachable": "Gmail couldn't be reached through Apps (HTTP {status}). Try again in a few minutes.",+ "serverError.emailDraft.refused": "Gmail refused: {detail}",+ "serverError.emailDraft.changed": "This draft changed in Gmail since you started editing, so nothing was saved. The card now shows the latest version: edit it again.",+ "serverError.emailDraft.unreadable": "Gmail didn't say what this draft holds now, so nothing was saved. Try again in a few minutes.","serverError.chat.busyFresh": "the thread is working — stop it before starting fresh","serverError.chat.questionGone": "this question is no longer available","serverError.chat.askerGone": "the bot that asked this question is no longer available",diff --git a/shared/email-draft.ts b/shared/email-draft.tsnew file mode 100644index 0000000000..04f9ad0305--- /dev/null+++ b/shared/email-draft.ts@@ -0,0 +1 @@+export * from "../packages/phone-protocol/src/email-draft.ts";diff --git a/src/components/EmailDraftCard.dom.test.ts b/src/components/EmailDraftCard.dom.test.tsnew file mode 100644index 0000000000..f575eb359f--- /dev/null+++ b/src/components/EmailDraftCard.dom.test.ts@@ -0,0 +1,128 @@+// @vitest-environment happy-dom+import { act, createElement } from "react";+import { createRoot, type Root } from "react-dom/client";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { setLocale } from "@/lib/i18n";+import type { Message } from "@/state/store";++const posted = vi.hoisted(() => [] as Array<{ path: string; body: unknown }>);+/** What a press waits for before the server answers. */+const answered = vi.hoisted(() => ({ when: Promise.resolve(), fail: undefined as Error | undefined }));+vi.mock("@/state/store", async (original) => ({+ ...await original<typeof import("@/state/store")>(),+ api: async (path: string, init?: { body?: string }) => { posted.push({ path, body: JSON.parse(init?.body ?? "null") }); await answered.when; if (answered.fail) throw answered.fail; return { ok: true }; },+}));++const draft: Message = {+ id: "card-1", role: "bot", kind: "text", at: 1, text: "Draft saved in Gmail",+ emailDraft: { app: "gmail", draftId: "r-123", botId: "b1", to: ["[email protected]"], cc: ["[email protected]"], bcc: [], subject: "Launch", body: "Ready to go.", url: "https://mail.google.com/mail/#drafts?compose=m-1" },+};++let container: HTMLDivElement, root: Root;+beforeEach(() => {+ vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);+ setLocale("en");+ posted.length = 0;+ answered.when = Promise.resolve();+ answered.fail = undefined;+ container = document.createElement("div"); document.body.append(container); root = createRoot(container);+});+afterEach(async () => { await act(async () => root.unmount()); container.remove(); document.body.innerHTML = ""; vi.unstubAllGlobals(); });++async function shown(message: Message = draft, viewOnly = false) {+ const { EmailDraftCard } = await import("./EmailDraftCard");+ await act(async () => { root.render(createElement(EmailDraftCard, { message, threadId: "t1", viewOnly })); });+}++const buttonNamed = (label: string) => [...document.querySelectorAll("button")].find((one) => one.textContent === label);+const click = async (label: string) => { await act(async () => { buttonNamed(label)!.click(); }); };++function type(field: HTMLInputElement | HTMLTextAreaElement, value: string) {+ const setter = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(field), "value")!.set!;+ setter.call(field, value);+ field.dispatchEvent(new Event("input", { bubbles: true }));+}++describe("the Gmail draft card", () => {+ it("shows the draft with Edit and Open in Gmail, and no Send", async () => {+ await shown();+ const text = container.textContent ?? "";+ for (const part of ["Gmail draft", "[email protected]", "[email protected]", "Launch", "Ready to go."]) expect(text).toContain(part);+ expect([...container.querySelectorAll("button")].map((one) => one.textContent)).toEqual(["Edit", "Open in Gmail"]);+ expect(posted).toEqual([]);+ });++ it("saves an edit with each address on its own", async () => {+ await shown();+ await click("Edit");+ const [to, , , subject] = [...container.querySelectorAll("input")];+ await act(async () => { type(to!, "[email protected], [email protected]"); type(subject!, "Launch (final)"); });+ await click("Save");+ expect(posted).toEqual([{ path: "/api/email-draft", body: { threadId: "t1", messageId: "card-1", action: "save", base: {+ to: ["[email protected]"], cc: ["[email protected]"], bcc: [], subject: "Launch", body: "Ready to go.",+ }, draft: {+ to: ["[email protected]", "[email protected]"], cc: ["[email protected]"], bcc: [], subject: "Launch (final)", body: "Ready to go.",+ } } }]);+ });++ it("offers no Edit once sent, or in a room's view-only copy", async () => {+ await shown({ ...draft, emailDraft: { ...draft.emailDraft!, sentAt: 5 } });+ expect(container.textContent).toContain("Sent from Gmail");+ expect(buttonNamed("Edit")).toBeUndefined();+ await shown(draft, true);+ expect(buttonNamed("Edit")).toBeUndefined();+ expect(buttonNamed("Open in Gmail")).toBeDefined();+ });++ it("shows an HTML body as its text, never its markup", async () => {+ await shown({ ...draft, emailDraft: { ...draft.emailDraft!, html: true, body: "<p>Hello <b>Ana</b></p><script>x()</script>" } });+ expect(container.textContent).toContain("Hello Ana");+ expect(container.innerHTML).not.toContain("<b>");+ });++ it("keeps an HTML body's lines and paragraphs", async () => {+ const { draftBodyText } = await import("./EmailDraftCard");+ expect(draftBodyText({ html: true, body: "<p>Hello</p>\n <p>Ana<br>Ready?</p><ul><li>One</li><li>Two</li></ul>" })).toBe("Hello\n\nAna\nReady?\n\nOne\nTwo");+ expect(draftBodyText({ html: true, body: "<div>Hello<p>Ana</p></div>" })).toBe("Hello\n\nAna");+ expect(draftBodyText({ body: "Plain\n text" })).toBe("Plain\n text");+ });++ it("drops the editor when the draft is sent meanwhile", async () => {+ await shown();+ await click("Edit");+ expect(container.querySelectorAll("input")).toHaveLength(4);+ await shown({ ...draft, emailDraft: { ...draft.emailDraft!, sentAt: 5 } });+ expect(container.querySelectorAll("input, textarea")).toHaveLength(0);+ expect(buttonNamed("Save")).toBeUndefined();+ expect(container.textContent).toContain("Sent from Gmail");+ });++ it("locks the fields while Save runs, so nothing typed then is lost", async () => {+ let answer!: () => void;+ answered.when = new Promise((resolve) => { answer = resolve; });+ await shown();+ await click("Edit");+ await click("Save");+ const fields = [...container.querySelectorAll<HTMLInputElement | HTMLTextAreaElement>("input, textarea")];+ expect(fields).toHaveLength(5);+ expect(fields.every((field) => field.disabled)).toBe(true);+ await act(async () => { answer(); });+ expect(container.querySelectorAll("input, textarea")).toHaveLength(0);+ });++ it("closes the editor when the draft changed in Gmail, so the next edit starts from what Gmail holds", async () => {+ const { ApiError } = await import("@/state/store");+ const changed = "This draft changed in Gmail since you started editing, so nothing was saved. The card now shows the latest version: edit it again.";+ answered.fail = new ApiError(changed, 409, { error: changed, errorKey: "serverError.emailDraft.changed" });+ await shown();+ await click("Edit");+ await click("Save");+ expect(container.querySelectorAll("input, textarea")).toHaveLength(0);+ expect(container.querySelector("[role=alert]")?.textContent).toBe(changed);+ // Any other refusal keeps what was typed.+ answered.fail = new ApiError("Gmail refused: busy", 502, { error: "Gmail refused: busy" });+ await click("Edit");+ await click("Save");+ expect(container.querySelectorAll("input")).toHaveLength(4);+ });+});diff --git a/src/components/EmailDraftCard.tsx b/src/components/EmailDraftCard.tsxnew file mode 100644index 0000000000..c8e3d54c5e--- /dev/null+++ b/src/components/EmailDraftCard.tsx@@ -0,0 +1,129 @@+import { useState } from "react";++import { openExternalLink } from "@/lib/app-links";+import { t } from "@/lib/i18n";+import { api, ApiError, type Message } from "@/state/store";+import { EMAIL_DRAFT_PATH, splitAddresses, type EmailDraftCardData, type EmailDraftEdit } from "../../shared/email-draft";++const GMAIL_DRAFTS = "https://mail.google.com/mail/#drafts";++const LINES = "li, tr";+const PARAGRAPHS = "p, div, h1, h2, h3, h4, h5, h6, blockquote, pre, table, ul, ol";++/** The text an HTML body shows: what a reader sees, never its markup, with its line and paragraph breaks. */+export function draftBodyText(card: Pick<EmailDraftCardData, "body" | "html">): string {+ if (!card.html) return card.body;+ const page = new DOMParser().parseFromString(card.body, "text/html");+ const { body } = page;+ for (const element of body.querySelectorAll("script, style")) element.remove();+ // Line breaks in the markup itself draw as spaces; only <br> and blocks break lines.+ const words = page.createTreeWalker(body, NodeFilter.SHOW_TEXT);+ for (let node = words.nextNode(); node; node = words.nextNode()) if (!node.parentElement?.closest("pre")) node.nodeValue = (node.nodeValue ?? "").replace(/\s+/g, " ");+ for (const element of body.querySelectorAll("br")) element.replaceWith("\n");+ for (const element of body.querySelectorAll(LINES)) element.after("\n");+ // A block starts its own paragraph after text before it as well as before text after it: <div>Hi<p>Ana</p></div>.+ for (const element of body.querySelectorAll(PARAGRAPHS)) { element.before("\n\n"); element.after("\n\n"); }+ return (body.textContent ?? "").replace(/ *\n */g, "\n").replace(/\n{3,}/g, "\n\n").trim();+}++interface Fields { to: string; cc: string; bcc: string; subject: string; body: string }++const fieldsOf = (card: EmailDraftCardData): Fields =>+ ({ to: card.to.join(", "), cc: card.cc.join(", "), bcc: card.bcc.join(", "), subject: card.subject, body: card.body });++/** The draft as the card shows it: what an edit starts from. */+const baseOf = (card: EmailDraftCardData): EmailDraftEdit => ({ to: card.to, cc: card.cc, bcc: card.bcc, subject: card.subject, body: card.body });++export function editOf(fields: Fields): EmailDraftEdit {+ return { to: splitAddresses(fields.to), cc: splitAddresses(fields.cc), bcc: splitAddresses(fields.bcc), subject: fields.subject, body: fields.body };+}++function Line({ label, value }: { label: string; value: string }) {+ return (+ <div className="flex min-w-0 gap-2 text-[13px]">+ <span className="w-14 shrink-0 text-ink-tertiary">{label}</span>+ <bdi dir="auto" className="min-w-0 break-words text-ink">{value}</bdi>+ </div>+ );+}++function Field({ label, value, onChange, multiline, disabled }: { label: string; value: string; onChange: (value: string) => void; multiline?: boolean; disabled: boolean }) {+ const look = "w-full rounded-lg bg-inset px-2 py-1 text-[13px] text-ink outline-none focus:border-ink/40";+ return (+ <label className="flex flex-col gap-1 text-[12px] text-ink-tertiary">+ {label}+ {multiline+ ? <textarea dir="auto" rows={8} value={value} disabled={disabled} onChange={(event) => onChange(event.target.value)} className={look} />+ : <input dir="auto" value={value} disabled={disabled} onChange={(event) => onChange(event.target.value)} className={look} />}+ </label>+ );+}++export function EmailDraftCard({ threadId, message, viewOnly }: { threadId?: string; message: Message; viewOnly?: boolean }) {+ const card = message.emailDraft!;+ const [editing, setEditing] = useState<Fields | null>(null);+ // The draft as the card showed it when editing started: Save sends it, and the server saves nothing if Gmail changed since.+ const [base, setBase] = useState<EmailDraftEdit | null>(null);+ const [saving, setSaving] = useState(false);+ const [error, setError] = useState<string | null>(null);+ const live = !viewOnly && Boolean(threadId) && !card.sentAt;+ // A card sent meanwhile (the bot sent it) drops what was being edited: it only shows what was sent.+ const [sentAt, setSentAt] = useState(card.sentAt);+ if (sentAt !== card.sentAt) {+ setSentAt(card.sentAt);+ setEditing(null);+ }++ const save = async (draft: EmailDraftEdit): Promise<boolean> => {+ setSaving(true);+ setError(null);+ try {+ await api(EMAIL_DRAFT_PATH, { method: "POST", body: JSON.stringify({ threadId, messageId: message.id, action: "save", base, draft }) });+ return true;+ } catch (failure) {+ setError(failure instanceof Error ? failure.message : String(failure));+ // Changed in Gmail meanwhile: the card now shows that version, and the edit started from an older one.+ if (failure instanceof ApiError && failure.body?.errorKey === "serverError.emailDraft.changed") setEditing(null);+ return false;+ } finally {+ setSaving(false);+ }+ };++ const button = "ui-button ui-button-sm";+ return (+ <div data-email-draft={card.draftId} data-email-draft-sent={card.sentAt ? "" : undefined}+ className="flex w-full max-w-[600px] flex-col gap-2 rounded-2xl border border-hairline/45 bg-card px-3.5 py-3 shadow-sm">+ <div className="text-[12px] font-medium text-ink-tertiary">{t(card.sentAt ? "chat.emailDraft.sent" : "chat.emailDraft.title")}</div>+ {editing && live ? (+ <form className="flex flex-col gap-2" onSubmit={(event) => {+ event.preventDefault();+ void save(editOf(editing)).then((saved) => { if (saved) setEditing(null); });+ }}>+ <Field label={t("chat.emailDraft.to")} value={editing.to} onChange={(to) => setEditing({ ...editing, to })} disabled={saving} />+ <Field label={t("chat.emailDraft.cc")} value={editing.cc} onChange={(cc) => setEditing({ ...editing, cc })} disabled={saving} />+ <Field label={t("chat.emailDraft.bcc")} value={editing.bcc} onChange={(bcc) => setEditing({ ...editing, bcc })} disabled={saving} />+ <Field label={t("chat.emailDraft.subject")} value={editing.subject} onChange={(subject) => setEditing({ ...editing, subject })} disabled={saving} />+ <Field label={t("chat.emailDraft.body")} value={editing.body} onChange={(body) => setEditing({ ...editing, body })} multiline disabled={saving} />+ <div className="flex flex-wrap gap-2">+ <button type="submit" disabled={saving} className={`${button} ui-button-primary`}>{t(saving ? "common.saving" : "common.save")}</button>+ <button type="button" disabled={saving} onClick={() => { setEditing(null); setError(null); }} className={button}>{t("common.cancel")}</button>+ </div>+ </form>+ ) : (+ <>+ <Line label={t("chat.emailDraft.to")} value={card.to.join(", ") || t("chat.emailDraft.noRecipient")} />+ {card.cc.length > 0 && <Line label={t("chat.emailDraft.cc")} value={card.cc.join(", ")} />}+ {card.bcc.length > 0 && <Line label={t("chat.emailDraft.bcc")} value={card.bcc.join(", ")} />}+ <Line label={t("chat.emailDraft.subject")} value={card.subject || t("chat.emailDraft.noSubject")} />+ <p dir="auto" className="max-h-80 overflow-y-auto whitespace-pre-wrap break-words border-t border-hairline/45 pt-2 text-[14px] leading-relaxed text-ink">{draftBodyText(card)}</p>+ <div className="flex flex-wrap gap-2">+ {live && !card.html && <button type="button" disabled={saving} onClick={() => { setEditing(fieldsOf(card)); setBase(baseOf(card)); }} className={button}>{t("chat.emailDraft.edit")}</button>}+ {!card.sentAt && <button type="button" onClick={() => void openExternalLink(card.url ?? GMAIL_DRAFTS)} className={button}>{t("chat.emailDraft.openInGmail")}</button>}+ </div>+ </>+ )}+ {error && <p role="alert" dir="auto" className="text-[13px] text-danger">{error}</p>}+ </div>+ );+}diff --git a/src/components/RichMessageRow.tsx b/src/components/RichMessageRow.tsxindex 2d0fe2e522..37462fac3a 100644--- a/src/components/RichMessageRow.tsx+++ b/src/components/RichMessageRow.tsx@@ -4,6 +4,7 @@ import { t } from "@/lib/i18n";import { AppMessage } from "./app/AppMessage";import { BugReportNote } from "./BugReportNote";import { BurstCard } from "./BurstCard";+import { EmailDraftCard } from "./EmailDraftCard";import { GoalRunRow } from "./GoalRunCard";import { HelperKeySuggestion } from "./HelperKeySuggestion";import { MessageBoundary } from "./MessageBoundary";@@ -13,7 +14,7 @@ import { WidgetMessage } from "./widget/WidgetMessage";export function richRowKind(message: Message): Message["kind"] {// MausBot's follow-up is text the model reads, drawn under its intro's card row (OptionsCardRow).if (message.helperFollowup) return "options";- if (message.setupSuggestion || message.settingsCard || (message.kind === "goal.run" && message.goalRun) || (message.kind === "burst" && message.burst)) return "widget";+ if (message.setupSuggestion || message.settingsCard || message.emailDraft || (message.kind === "goal.run" && message.goalRun) || (message.kind === "burst" && message.burst)) return "widget";if (message.kind === "widget" && !message.widget) return "text";if (message.kind === "app" && !message.app) return "text";return message.kind;@@ -23,7 +24,9 @@ export function richRowKind(message: Message): Message["kind"] {export function RichMessageRow({ botId, botName, threadId, message, room }: { botId: string; botName: string; threadId?: string; message: Message; room?: boolean }) {return (<MessageBoundary fallbackText={message.text ?? ""}>- {message.settingsCard+ {message.emailDraft+ ? <EmailDraftCard threadId={threadId} message={message} viewOnly={room} />+ : message.settingsCard? <SettingsCard message={message} />: message.setupSuggestion? <HelperKeySuggestion threadId={threadId} message={message} />diff --git a/src/locales/de.json b/src/locales/de.jsonindex 12abaac458..5b4dbf2c41 100644--- a/src/locales/de.json+++ b/src/locales/de.json@@ -1,4 +1,26 @@{+ "chat.emailDraft.title": "Gmail-Entwurf",+ "chat.emailDraft.sent": "Aus Gmail gesendet",+ "chat.emailDraft.to": "An",+ "chat.emailDraft.cc": "Cc",+ "chat.emailDraft.bcc": "Bcc",+ "chat.emailDraft.subject": "Betreff",+ "chat.emailDraft.body": "Nachricht",+ "chat.emailDraft.noRecipient": "Noch kein Empfänger",+ "chat.emailDraft.noSubject": "(kein Betreff)",+ "chat.emailDraft.edit": "Bearbeiten",+ "chat.emailDraft.openInGmail": "In Gmail öffnen",+ "serverError.emailDraft.notHere": "Dieser Entwurf ist nicht in diesem Gespräch.",+ "serverError.emailDraft.alreadySent": "Diese E-Mail wurde schon gesendet.",+ "serverError.emailDraft.busy": "Dieser Entwurf wird gerade gespeichert.",+ "serverError.emailDraft.appsOff": "Verbundene Apps sind für diesen Bot aus.",+ "serverError.emailDraft.ownGmail": "Verbinde dein eigenes Gmail unter Apps, um diesen Entwurf zu speichern.",+ "serverError.emailDraft.appsDown": "Apps sind gerade nicht erreichbar. Versuch es in ein paar Minuten noch einmal.",+ "serverError.emailDraft.notAllowed": "{name} darf keine Gmail-Entwürfe speichern. Ändere dafür seine App-Berechtigungen.",+ "serverError.emailDraft.unreachable": "Gmail war über Apps nicht erreichbar (HTTP {status}). Versuch es in ein paar Minuten noch einmal.",+ "serverError.emailDraft.refused": "Gmail hat abgelehnt: {detail}",+ "serverError.emailDraft.changed": "Dieser Entwurf wurde in Gmail geändert, seit du mit dem Bearbeiten angefangen hast, darum wurde nichts gespeichert. Die Karte zeigt jetzt die neueste Fassung: bearbeite sie noch einmal.",+ "serverError.emailDraft.unreadable": "Gmail hat nicht gesagt, was dieser Entwurf jetzt enthält, darum wurde nichts gespeichert. Versuch es in ein paar Minuten noch einmal.","voice.gemini.keyPlaceholder": "Google AI Studio API-Schlüssel einfügen","voice.gemini.model": "Gemini-Sprachmodell","keys.label.geminiTts": "Gemini-Sprach-API-Schlüssel",@@ -275,6 +297,10 @@"server.rooms.becameBusy": "{bot} ist in einer anderen Unterhaltung beschäftigt geworden, daher diese Runde übersprungen","server.rooms.mentionMissed": "{bot} ist nicht in diesem Raum, die Erwähnung hat ihn also nicht erreicht. Füge ihn dem Raum hinzu, um ihn einzubeziehen.","server.rooms.archived": "{bot} ist archiviert und kann nicht antworten. Stelle ihn wieder her oder erwähne ein aktives Raummitglied.",+ "server.emailDraft.saved": "Entwurf in Gmail gespeichert: „{subject}“ an {to}.",+ "server.emailDraft.sent": "E-Mail gesendet: „{subject}“ an {to}.",+ "server.emailDraft.noRecipient": "noch kein Empfänger",+ "server.emailDraft.noSubject": "(kein Betreff)","server.rooms.sameName.two": "Zwei Bots hier heißen „{name}“: {first} und {second}. Wähle in der @-Liste den aus, den du meinst.","server.rooms.sameName.many": "{count} Bots hier heißen „{name}“: {choices}. Wähle in der @-Liste den aus, den du meinst.","server.rooms.sameName.choice": "{name}, {role}",diff --git a/src/locales/en.json b/src/locales/en.jsonindex 9cb8d9642f..3146945645 100644--- a/src/locales/en.json+++ b/src/locales/en.json@@ -423,6 +423,10 @@"server.rooms.linkedNoAnswer": "{bot} finished on {place} without an answer for this room.","server.rooms.linkedFailed": "{bot} could not answer from {place}.","server.rooms.archived": "{bot} is archived and can't respond — restore it or mention an active room member.",+ "server.emailDraft.saved": "Draft saved in Gmail: \"{subject}\" to {to}.",+ "server.emailDraft.sent": "Email sent: \"{subject}\" to {to}.",+ "server.emailDraft.noRecipient": "no recipient yet",+ "server.emailDraft.noSubject": "(no subject)","server.rooms.sameName.two": "Two bots here are named \"{name}\": {first} and {second}. Pick the one you mean from the @ list.","server.rooms.sameName.many": "{count} bots here are named \"{name}\": {choices}. Pick the one you mean from the @ list.","server.rooms.sameName.choice": "{name}, {role}",@@ -8290,6 +8294,17 @@"chat.preview.pointedAt": "Pointed at {parts}","chat.helperSuggestion.text": "Want me to sort your email for free? Add a Cloudflare Workers AI key (free tier) or a Jev key.","chat.helperSuggestion.from": "Tip from {app}",+ "chat.emailDraft.title": "Gmail draft",+ "chat.emailDraft.sent": "Sent from Gmail",+ "chat.emailDraft.to": "To",+ "chat.emailDraft.cc": "Cc",+ "chat.emailDraft.bcc": "Bcc",+ "chat.emailDraft.subject": "Subject",+ "chat.emailDraft.body": "Message",+ "chat.emailDraft.noRecipient": "No recipient yet",+ "chat.emailDraft.noSubject": "(no subject)",+ "chat.emailDraft.edit": "Edit",+ "chat.emailDraft.openInGmail": "Open in Gmail","chat.settingsCard.elsewhereDevices": "This is set on the computer itself: open MausBot there, then Settings → Devices → Private network → Your other computers.","chat.helperSuggestion.about": "A helper key lets a small model sort your mail without using your main AI. Jev (typesafe.ai) and Cloudflare Workers AI both offer one.","chat.helperSuggestion.addKey": "Add key",@@ -9924,6 +9939,17 @@"serverError.chat.busyEdit": "the thread is working — stop it before editing","serverError.forkBusy": "Wait for this conversation to finish before forking it.","serverError.forkNoText": "This conversation has no text message to fork from yet.",+ "serverError.emailDraft.notHere": "That draft is not in this conversation.",+ "serverError.emailDraft.alreadySent": "This email was already sent.",+ "serverError.emailDraft.busy": "This draft is still being saved.",+ "serverError.emailDraft.appsOff": "Connected apps are off for this bot.",+ "serverError.emailDraft.ownGmail": "Connect your own Gmail in Apps to save this draft.",+ "serverError.emailDraft.appsDown": "Apps can't be reached right now. Try again in a few minutes.",+ "serverError.emailDraft.notAllowed": "{name} may not save Gmail drafts. Change its app permissions to allow it.",+ "serverError.emailDraft.unreachable": "Gmail couldn't be reached through Apps (HTTP {status}). Try again in a few minutes.",+ "serverError.emailDraft.refused": "Gmail refused: {detail}",+ "serverError.emailDraft.changed": "This draft changed in Gmail since you started editing, so nothing was saved. The card now shows the latest version: edit it again.",+ "serverError.emailDraft.unreadable": "Gmail didn't say what this draft holds now, so nothing was saved. Try again in a few minutes.","serverError.chat.busyVersion": "the thread is working — stop it before switching versions","serverError.chat.busyFresh": "the thread is working — stop it before starting fresh","serverError.chat.questionGone": "this question is no longer available",diff --git a/src/locales/es.json b/src/locales/es.jsonindex 9a7287ba41..e51dbdba63 100644--- a/src/locales/es.json+++ b/src/locales/es.json@@ -1,4 +1,30 @@{+ "chat.emailDraft.title": "Borrador de Gmail",+ "chat.emailDraft.sent": "Enviado desde Gmail",+ "chat.emailDraft.to": "Para",+ "chat.emailDraft.cc": "Cc",+ "chat.emailDraft.bcc": "Cco",+ "chat.emailDraft.subject": "Asunto",+ "chat.emailDraft.body": "Mensaje",+ "chat.emailDraft.noRecipient": "Aún no hay destinatario",+ "chat.emailDraft.noSubject": "(sin asunto)",+ "chat.emailDraft.edit": "Editar",+ "chat.emailDraft.openInGmail": "Abrir en Gmail",+ "server.emailDraft.saved": "Borrador guardado en Gmail: \"{subject}\" para {to}.",+ "server.emailDraft.sent": "Correo enviado: \"{subject}\" para {to}.",+ "server.emailDraft.noRecipient": "aún no hay destinatario",+ "server.emailDraft.noSubject": "(sin asunto)",+ "serverError.emailDraft.notHere": "Ese borrador no está en esta conversación.",+ "serverError.emailDraft.alreadySent": "Este correo ya se envió.",+ "serverError.emailDraft.busy": "Este borrador aún se está guardando.",+ "serverError.emailDraft.appsOff": "Las apps conectadas están desactivadas para este bot.",+ "serverError.emailDraft.ownGmail": "Conecta tu propio Gmail en Apps para guardar este borrador.",+ "serverError.emailDraft.appsDown": "No se puede acceder a Apps ahora. Inténtalo de nuevo en unos minutos.",+ "serverError.emailDraft.notAllowed": "{name} no puede guardar borradores de Gmail. Cambia sus permisos de apps para permitirlo.",+ "serverError.emailDraft.unreachable": "No se pudo acceder a Gmail a través de Apps (HTTP {status}). Inténtalo de nuevo en unos minutos.",+ "serverError.emailDraft.refused": "Gmail lo rechazó: {detail}",+ "serverError.emailDraft.changed": "Este borrador cambió en Gmail desde que empezaste a editarlo, así que no se guardó nada. La tarjeta ahora muestra la versión más reciente: edítala de nuevo.",+ "serverError.emailDraft.unreadable": "Gmail no dijo qué contiene ahora este borrador, así que no se guardó nada. Inténtalo de nuevo en unos minutos.","voice.gemini.keyPlaceholder": "Pega tu clave de API de Google AI Studio","voice.gemini.model": "Modelo de voz de Gemini","keys.label.geminiTts": "Clave de API de voz de Gemini",diff --git a/src/locales/fr.json b/src/locales/fr.jsonindex 5d468a7fca..0b7249f1e1 100644--- a/src/locales/fr.json+++ b/src/locales/fr.json@@ -1,4 +1,30 @@{+ "chat.emailDraft.title": "Brouillon Gmail",+ "chat.emailDraft.sent": "Envoyé depuis Gmail",+ "chat.emailDraft.to": "À",+ "chat.emailDraft.cc": "Cc",+ "chat.emailDraft.bcc": "Cci",+ "chat.emailDraft.subject": "Objet",+ "chat.emailDraft.body": "Message",+ "chat.emailDraft.noRecipient": "Pas encore de destinataire",+ "chat.emailDraft.noSubject": "(sans objet)",+ "chat.emailDraft.edit": "Modifier",+ "chat.emailDraft.openInGmail": "Ouvrir dans Gmail",+ "server.emailDraft.saved": "Brouillon enregistré dans Gmail : « {subject} » à {to}.",+ "server.emailDraft.sent": "E-mail envoyé : « {subject} » à {to}.",+ "server.emailDraft.noRecipient": "pas encore de destinataire",+ "server.emailDraft.noSubject": "(sans objet)",+ "serverError.emailDraft.notHere": "Ce brouillon n'est pas dans cette conversation.",+ "serverError.emailDraft.alreadySent": "Cet e-mail a déjà été envoyé.",+ "serverError.emailDraft.busy": "Ce brouillon est encore en cours d'enregistrement.",+ "serverError.emailDraft.appsOff": "Les apps connectées sont désactivées pour ce bot.",+ "serverError.emailDraft.ownGmail": "Connectez votre propre Gmail dans Apps pour enregistrer ce brouillon.",+ "serverError.emailDraft.appsDown": "Apps est injoignable pour le moment. Réessayez dans quelques minutes.",+ "serverError.emailDraft.notAllowed": "{name} ne peut pas enregistrer de brouillons Gmail. Modifiez ses autorisations d'apps pour le permettre.",+ "serverError.emailDraft.unreachable": "Gmail est injoignable via Apps (HTTP {status}). Réessayez dans quelques minutes.",+ "serverError.emailDraft.refused": "Gmail a refusé : {detail}",+ "serverError.emailDraft.changed": "Ce brouillon a changé dans Gmail depuis que vous avez commencé à le modifier, donc rien n'a été enregistré. La carte affiche maintenant la dernière version : modifiez-la à nouveau.",+ "serverError.emailDraft.unreadable": "Gmail n'a pas indiqué ce que contient ce brouillon maintenant, donc rien n'a été enregistré. Réessayez dans quelques minutes.","voice.gemini.keyPlaceholder": "Collez votre clé API Google AI Studio","voice.gemini.model": "Modèle de synthèse vocale Gemini","keys.label.geminiTts": "Clé API de synthèse vocale Gemini",diff --git a/src/locales/hi.json b/src/locales/hi.jsonindex ea15287a86..d4b5b65062 100644--- a/src/locales/hi.json+++ b/src/locales/hi.json@@ -1,4 +1,30 @@{+ "chat.emailDraft.title": "Gmail ड्राफ़्ट",+ "chat.emailDraft.sent": "Gmail से भेजा गया",+ "chat.emailDraft.to": "प्रति",+ "chat.emailDraft.cc": "Cc",+ "chat.emailDraft.bcc": "Bcc",+ "chat.emailDraft.subject": "विषय",+ "chat.emailDraft.body": "संदेश",+ "chat.emailDraft.noRecipient": "अभी कोई प्राप्तकर्ता नहीं",+ "chat.emailDraft.noSubject": "(कोई विषय नहीं)",+ "chat.emailDraft.edit": "बदलें",+ "chat.emailDraft.openInGmail": "Gmail में खोलें",+ "server.emailDraft.saved": "ड्राफ़्ट Gmail में सहेजा गया: {to} को \"{subject}\"।",+ "server.emailDraft.sent": "ईमेल भेजा गया: {to} को \"{subject}\"।",+ "server.emailDraft.noRecipient": "अभी कोई प्राप्तकर्ता नहीं",+ "server.emailDraft.noSubject": "(कोई विषय नहीं)",+ "serverError.emailDraft.notHere": "वह ड्राफ़्ट इस बातचीत में नहीं है।",+ "serverError.emailDraft.alreadySent": "यह ईमेल पहले ही भेजा जा चुका है।",+ "serverError.emailDraft.busy": "यह ड्राफ़्ट अभी सहेजा जा रहा है।",+ "serverError.emailDraft.appsOff": "इस बॉट के लिए जुड़े ऐप्स बंद हैं।",+ "serverError.emailDraft.ownGmail": "यह ड्राफ़्ट सहेजने के लिए Apps में अपना Gmail जोड़ें।",+ "serverError.emailDraft.appsDown": "अभी Apps तक नहीं पहुँचा जा सकता। कुछ मिनट बाद फिर कोशिश करें।",+ "serverError.emailDraft.notAllowed": "{name} Gmail ड्राफ़्ट नहीं सहेज सकता। अनुमति देने के लिए उसकी ऐप अनुमतियाँ बदलें।",+ "serverError.emailDraft.unreachable": "Apps के ज़रिए Gmail तक नहीं पहुँचा जा सका (HTTP {status})। कुछ मिनट बाद फिर कोशिश करें।",+ "serverError.emailDraft.refused": "Gmail ने मना किया: {detail}",+ "serverError.emailDraft.changed": "आपके बदलाव शुरू करने के बाद यह ड्राफ़्ट Gmail में बदल गया, इसलिए कुछ नहीं सहेजा गया। कार्ड अब नया संस्करण दिखाता है: इसे फिर से बदलें।",+ "serverError.emailDraft.unreadable": "Gmail ने नहीं बताया कि इस ड्राफ़्ट में अब क्या है, इसलिए कुछ नहीं सहेजा गया। कुछ मिनट बाद फिर कोशिश करें।","voice.gemini.keyPlaceholder": "अपनी Google AI Studio API कुंजी पेस्ट करें","voice.gemini.model": "Gemini वाक् मॉडल","keys.label.geminiTts": "Gemini वाक् API कुंजी",diff --git a/src/locales/it.json b/src/locales/it.jsonindex 0d290b0ae9..66bcae8b34 100644--- a/src/locales/it.json+++ b/src/locales/it.json@@ -1,4 +1,30 @@{+ "chat.emailDraft.title": "Bozza di Gmail",+ "chat.emailDraft.sent": "Inviata da Gmail",+ "chat.emailDraft.to": "A",+ "chat.emailDraft.cc": "Cc",+ "chat.emailDraft.bcc": "Ccn",+ "chat.emailDraft.subject": "Oggetto",+ "chat.emailDraft.body": "Messaggio",+ "chat.emailDraft.noRecipient": "Nessun destinatario ancora",+ "chat.emailDraft.noSubject": "(nessun oggetto)",+ "chat.emailDraft.edit": "Modifica",+ "chat.emailDraft.openInGmail": "Apri in Gmail",+ "server.emailDraft.saved": "Bozza salvata in Gmail: \"{subject}\" a {to}.",+ "server.emailDraft.sent": "Email inviata: \"{subject}\" a {to}.",+ "server.emailDraft.noRecipient": "nessun destinatario ancora",+ "server.emailDraft.noSubject": "(nessun oggetto)",+ "serverError.emailDraft.notHere": "Quella bozza non è in questa conversazione.",+ "serverError.emailDraft.alreadySent": "Questa email è già stata inviata.",+ "serverError.emailDraft.busy": "Questa bozza è ancora in fase di salvataggio.",+ "serverError.emailDraft.appsOff": "Le app collegate sono disattivate per questo bot.",+ "serverError.emailDraft.ownGmail": "Collega il tuo Gmail in Apps per salvare questa bozza.",+ "serverError.emailDraft.appsDown": "Apps non è raggiungibile in questo momento. Riprova tra qualche minuto.",+ "serverError.emailDraft.notAllowed": "{name} non può salvare bozze di Gmail. Cambia i suoi permessi delle app per consentirlo.",+ "serverError.emailDraft.unreachable": "Impossibile raggiungere Gmail tramite Apps (HTTP {status}). Riprova tra qualche minuto.",+ "serverError.emailDraft.refused": "Gmail ha rifiutato: {detail}",+ "serverError.emailDraft.changed": "Questa bozza è cambiata in Gmail da quando hai iniziato a modificarla, quindi non è stato salvato nulla. La scheda ora mostra la versione più recente: modificala di nuovo.",+ "serverError.emailDraft.unreadable": "Gmail non ha detto cosa contiene ora questa bozza, quindi non è stato salvato nulla. Riprova tra qualche minuto.","connectedWorkspaces.localTitle": "Ambienti su questo computer","connectedWorkspaces.missing": "mancante","connectedWorkspaces.current": "Attuale",diff --git a/src/locales/ja.json b/src/locales/ja.jsonindex dd20356aa0..d6141cf49a 100644--- a/src/locales/ja.json+++ b/src/locales/ja.json@@ -1,4 +1,30 @@{+ "chat.emailDraft.title": "Gmail の下書き",+ "chat.emailDraft.sent": "Gmail から送信済み",+ "chat.emailDraft.to": "宛先",+ "chat.emailDraft.cc": "Cc",+ "chat.emailDraft.bcc": "Bcc",+ "chat.emailDraft.subject": "件名",+ "chat.emailDraft.body": "本文",+ "chat.emailDraft.noRecipient": "宛先はまだありません",+ "chat.emailDraft.noSubject": "(件名なし)",+ "chat.emailDraft.edit": "編集",+ "chat.emailDraft.openInGmail": "Gmail で開く",+ "server.emailDraft.saved": "Gmail に下書きを保存しました: {to} 宛ての「{subject}」。",+ "server.emailDraft.sent": "メールを送信しました: {to} 宛ての「{subject}」。",+ "server.emailDraft.noRecipient": "宛先はまだありません",+ "server.emailDraft.noSubject": "(件名なし)",+ "serverError.emailDraft.notHere": "その下書きはこの会話にありません。",+ "serverError.emailDraft.alreadySent": "このメールはすでに送信されています。",+ "serverError.emailDraft.busy": "この下書きはまだ保存中です。",+ "serverError.emailDraft.appsOff": "このボットの連携アプリはオフです。",+ "serverError.emailDraft.ownGmail": "この下書きを保存するには、アプリで自分の Gmail を接続してください。",+ "serverError.emailDraft.appsDown": "現在アプリに接続できません。数分後にもう一度お試しください。",+ "serverError.emailDraft.notAllowed": "{name} は Gmail の下書きを保存できません。許可するにはアプリの権限を変更してください。",+ "serverError.emailDraft.unreachable": "アプリ経由で Gmail に接続できませんでした (HTTP {status})。数分後にもう一度お試しください。",+ "serverError.emailDraft.refused": "Gmail が拒否しました: {detail}",+ "serverError.emailDraft.changed": "編集を始めてから Gmail でこの下書きが変更されたため、何も保存されませんでした。カードには最新の版が表示されています。もう一度編集してください。",+ "serverError.emailDraft.unreadable": "Gmail がこの下書きの現在の内容を返さなかったため、何も保存されませんでした。数分後にもう一度お試しください。","connectedWorkspaces.localTitle": "このコンピューターの環境","connectedWorkspaces.missing": "見つかりません","connectedWorkspaces.current": "使用中",diff --git a/src/locales/ko.json b/src/locales/ko.jsonindex c644de388e..c01874e49d 100644--- a/src/locales/ko.json+++ b/src/locales/ko.json@@ -1,4 +1,30 @@{+ "chat.emailDraft.title": "Gmail 임시보관 메일",+ "chat.emailDraft.sent": "Gmail에서 보냄",+ "chat.emailDraft.to": "받는 사람",+ "chat.emailDraft.cc": "참조",+ "chat.emailDraft.bcc": "숨은참조",+ "chat.emailDraft.subject": "제목",+ "chat.emailDraft.body": "메시지",+ "chat.emailDraft.noRecipient": "아직 받는 사람이 없습니다",+ "chat.emailDraft.noSubject": "(제목 없음)",+ "chat.emailDraft.edit": "편집",+ "chat.emailDraft.openInGmail": "Gmail에서 열기",+ "server.emailDraft.saved": "Gmail에 임시보관 메일 저장됨: {to}에게 \"{subject}\".",+ "server.emailDraft.sent": "이메일 보냄: {to}에게 \"{subject}\".",+ "server.emailDraft.noRecipient": "아직 받는 사람 없음",+ "server.emailDraft.noSubject": "(제목 없음)",+ "serverError.emailDraft.notHere": "그 임시보관 메일은 이 대화에 없습니다.",+ "serverError.emailDraft.alreadySent": "이 이메일은 이미 보냈습니다.",+ "serverError.emailDraft.busy": "이 임시보관 메일은 아직 저장 중입니다.",+ "serverError.emailDraft.appsOff": "이 봇의 연결된 앱이 꺼져 있습니다.",+ "serverError.emailDraft.ownGmail": "이 임시보관 메일을 저장하려면 앱에서 내 Gmail을 연결하세요.",+ "serverError.emailDraft.appsDown": "지금은 앱에 연결할 수 없습니다. 몇 분 후에 다시 시도하세요.",+ "serverError.emailDraft.notAllowed": "{name}은(는) Gmail 임시보관 메일을 저장할 수 없습니다. 허용하려면 앱 권한을 변경하세요.",+ "serverError.emailDraft.unreachable": "앱을 통해 Gmail에 연결할 수 없습니다 (HTTP {status}). 몇 분 후에 다시 시도하세요.",+ "serverError.emailDraft.refused": "Gmail이 거부했습니다: {detail}",+ "serverError.emailDraft.changed": "편집을 시작한 뒤 Gmail에서 이 임시보관 메일이 바뀌어 아무것도 저장하지 않았습니다. 카드에 최신 버전이 표시됩니다. 다시 편집하세요.",+ "serverError.emailDraft.unreadable": "Gmail이 이 임시보관 메일의 현재 내용을 알려주지 않아 아무것도 저장하지 않았습니다. 몇 분 후에 다시 시도하세요.","voice.gemini.keyPlaceholder": "Google AI Studio API 키를 붙여넣으세요","voice.gemini.model": "Gemini 음성 합성 모델","keys.label.geminiTts": "Gemini 음성 합성 API 키",diff --git a/src/locales/pl.json b/src/locales/pl.jsonindex ab87218523..a00ae1e5d0 100644--- a/src/locales/pl.json+++ b/src/locales/pl.json@@ -1,4 +1,30 @@{+ "chat.emailDraft.title": "Wersja robocza Gmaila",+ "chat.emailDraft.sent": "Wysłano z Gmaila",+ "chat.emailDraft.to": "Do",+ "chat.emailDraft.cc": "DW",+ "chat.emailDraft.bcc": "UDW",+ "chat.emailDraft.subject": "Temat",+ "chat.emailDraft.body": "Wiadomość",+ "chat.emailDraft.noRecipient": "Brak odbiorcy",+ "chat.emailDraft.noSubject": "(bez tematu)",+ "chat.emailDraft.edit": "Edytuj",+ "chat.emailDraft.openInGmail": "Otwórz w Gmailu",+ "server.emailDraft.saved": "Wersja robocza zapisana w Gmailu: „{subject}” do {to}.",+ "server.emailDraft.sent": "E-mail wysłany: „{subject}” do {to}.",+ "server.emailDraft.noRecipient": "brak odbiorcy",+ "server.emailDraft.noSubject": "(bez tematu)",+ "serverError.emailDraft.notHere": "Tej wersji roboczej nie ma w tej rozmowie.",+ "serverError.emailDraft.alreadySent": "Ten e-mail został już wysłany.",+ "serverError.emailDraft.busy": "Ta wersja robocza jest jeszcze zapisywana.",+ "serverError.emailDraft.appsOff": "Połączone aplikacje są wyłączone dla tego bota.",+ "serverError.emailDraft.ownGmail": "Połącz własnego Gmaila w Aplikacjach, aby zapisać tę wersję roboczą.",+ "serverError.emailDraft.appsDown": "Aplikacje są teraz niedostępne. Spróbuj ponownie za kilka minut.",+ "serverError.emailDraft.notAllowed": "{name} nie może zapisywać wersji roboczych w Gmailu. Zmień jego uprawnienia aplikacji, aby na to pozwolić.",+ "serverError.emailDraft.unreachable": "Nie udało się połączyć z Gmailem przez Aplikacje (HTTP {status}). Spróbuj ponownie za kilka minut.",+ "serverError.emailDraft.refused": "Gmail odmówił: {detail}",+ "serverError.emailDraft.changed": "Ta wersja robocza zmieniła się w Gmailu, odkąd zacząłeś ją edytować, więc nic nie zapisano. Karta pokazuje teraz najnowszą wersję: edytuj ją ponownie.",+ "serverError.emailDraft.unreadable": "Gmail nie podał, co teraz zawiera ta wersja robocza, więc nic nie zapisano. Spróbuj ponownie za kilka minut.","voice.gemini.keyPlaceholder": "Wklej swój klucz API Google AI Studio","voice.gemini.model": "Model syntezy mowy Gemini","keys.label.geminiTts": "Klucz API syntezy mowy Gemini",diff --git a/src/locales/pt-br.json b/src/locales/pt-br.jsonindex e571c672f3..9bebc4a6e5 100644--- a/src/locales/pt-br.json+++ b/src/locales/pt-br.json@@ -1,4 +1,30 @@{+ "chat.emailDraft.title": "Rascunho do Gmail",+ "chat.emailDraft.sent": "Enviado pelo Gmail",+ "chat.emailDraft.to": "Para",+ "chat.emailDraft.cc": "Cc",+ "chat.emailDraft.bcc": "Cco",+ "chat.emailDraft.subject": "Assunto",+ "chat.emailDraft.body": "Mensagem",+ "chat.emailDraft.noRecipient": "Nenhum destinatário ainda",+ "chat.emailDraft.noSubject": "(sem assunto)",+ "chat.emailDraft.edit": "Editar",+ "chat.emailDraft.openInGmail": "Abrir no Gmail",+ "server.emailDraft.saved": "Rascunho salvo no Gmail: \"{subject}\" para {to}.",+ "server.emailDraft.sent": "E-mail enviado: \"{subject}\" para {to}.",+ "server.emailDraft.noRecipient": "nenhum destinatário ainda",+ "server.emailDraft.noSubject": "(sem assunto)",+ "serverError.emailDraft.notHere": "Esse rascunho não está nesta conversa.",+ "serverError.emailDraft.alreadySent": "Este e-mail já foi enviado.",+ "serverError.emailDraft.busy": "Este rascunho ainda está sendo salvo.",+ "serverError.emailDraft.appsOff": "Os apps conectados estão desligados para este bot.",+ "serverError.emailDraft.ownGmail": "Conecte seu próprio Gmail em Apps para salvar este rascunho.",+ "serverError.emailDraft.appsDown": "Não foi possível acessar os Apps agora. Tente de novo em alguns minutos.",+ "serverError.emailDraft.notAllowed": "{name} não pode salvar rascunhos do Gmail. Mude as permissões de apps dele para permitir.",+ "serverError.emailDraft.unreachable": "Não foi possível acessar o Gmail pelos Apps (HTTP {status}). Tente de novo em alguns minutos.",+ "serverError.emailDraft.refused": "O Gmail recusou: {detail}",+ "serverError.emailDraft.changed": "Este rascunho mudou no Gmail desde que você começou a editar, então nada foi salvo. O cartão agora mostra a versão mais recente: edite de novo.",+ "serverError.emailDraft.unreadable": "O Gmail não informou o que este rascunho contém agora, então nada foi salvo. Tente de novo em alguns minutos.","voice.gemini.keyPlaceholder": "Cole sua chave de API do Google AI Studio","voice.gemini.model": "Modelo de voz do Gemini","keys.label.geminiTts": "Chave de API de voz do Gemini",diff --git a/src/locales/ru.json b/src/locales/ru.jsonindex 9fecfafd7e..5ce07933d1 100644--- a/src/locales/ru.json+++ b/src/locales/ru.json@@ -1,4 +1,30 @@{+ "chat.emailDraft.title": "Черновик Gmail",+ "chat.emailDraft.sent": "Отправлено из Gmail",+ "chat.emailDraft.to": "Кому",+ "chat.emailDraft.cc": "Копия",+ "chat.emailDraft.bcc": "Скрытая копия",+ "chat.emailDraft.subject": "Тема",+ "chat.emailDraft.body": "Сообщение",+ "chat.emailDraft.noRecipient": "Получателя пока нет",+ "chat.emailDraft.noSubject": "(без темы)",+ "chat.emailDraft.edit": "Изменить",+ "chat.emailDraft.openInGmail": "Открыть в Gmail",+ "server.emailDraft.saved": "Черновик сохранён в Gmail: «{subject}» для {to}.",+ "server.emailDraft.sent": "Письмо отправлено: «{subject}» для {to}.",+ "server.emailDraft.noRecipient": "получателя пока нет",+ "server.emailDraft.noSubject": "(без темы)",+ "serverError.emailDraft.notHere": "Этого черновика нет в этом разговоре.",+ "serverError.emailDraft.alreadySent": "Это письмо уже отправлено.",+ "serverError.emailDraft.busy": "Этот черновик ещё сохраняется.",+ "serverError.emailDraft.appsOff": "Подключённые приложения выключены для этого бота.",+ "serverError.emailDraft.ownGmail": "Подключите свой Gmail в разделе «Приложения», чтобы сохранить этот черновик.",+ "serverError.emailDraft.appsDown": "Приложения сейчас недоступны. Попробуйте снова через несколько минут.",+ "serverError.emailDraft.notAllowed": "{name} не может сохранять черновики Gmail. Измените его разрешения для приложений, чтобы разрешить это.",+ "serverError.emailDraft.unreachable": "Не удалось связаться с Gmail через «Приложения» (HTTP {status}). Попробуйте снова через несколько минут.",+ "serverError.emailDraft.refused": "Gmail отказал: {detail}",+ "serverError.emailDraft.changed": "Этот черновик изменился в Gmail после того, как вы начали его редактировать, поэтому ничего не сохранено. Карточка теперь показывает последнюю версию: отредактируйте её снова.",+ "serverError.emailDraft.unreadable": "Gmail не сообщил, что сейчас в этом черновике, поэтому ничего не сохранено. Попробуйте снова через несколько минут.","voice.gemini.keyPlaceholder": "Вставьте свой API-ключ Google AI Studio","voice.gemini.model": "Модель синтеза речи Gemini","keys.label.geminiTts": "API-ключ синтеза речи Gemini",diff --git a/src/locales/tr.json b/src/locales/tr.jsonindex 4f42fdbbab..163c12be70 100644--- a/src/locales/tr.json+++ b/src/locales/tr.json@@ -1,4 +1,30 @@{+ "chat.emailDraft.title": "Gmail taslağı",+ "chat.emailDraft.sent": "Gmail'den gönderildi",+ "chat.emailDraft.to": "Kime",+ "chat.emailDraft.cc": "Bilgi",+ "chat.emailDraft.bcc": "Gizli",+ "chat.emailDraft.subject": "Konu",+ "chat.emailDraft.body": "Mesaj",+ "chat.emailDraft.noRecipient": "Henüz alıcı yok",+ "chat.emailDraft.noSubject": "(konu yok)",+ "chat.emailDraft.edit": "Düzenle",+ "chat.emailDraft.openInGmail": "Gmail'de aç",+ "server.emailDraft.saved": "Taslak Gmail'e kaydedildi: {to} kişisine \"{subject}\".",+ "server.emailDraft.sent": "E-posta gönderildi: {to} kişisine \"{subject}\".",+ "server.emailDraft.noRecipient": "henüz alıcı yok",+ "server.emailDraft.noSubject": "(konu yok)",+ "serverError.emailDraft.notHere": "Bu taslak bu sohbette değil.",+ "serverError.emailDraft.alreadySent": "Bu e-posta zaten gönderildi.",+ "serverError.emailDraft.busy": "Bu taslak hâlâ kaydediliyor.",+ "serverError.emailDraft.appsOff": "Bu bot için bağlı uygulamalar kapalı.",+ "serverError.emailDraft.ownGmail": "Bu taslağı kaydetmek için Uygulamalar'da kendi Gmail'inizi bağlayın.",+ "serverError.emailDraft.appsDown": "Uygulamalar'a şu anda ulaşılamıyor. Birkaç dakika sonra tekrar deneyin.",+ "serverError.emailDraft.notAllowed": "{name} Gmail taslağı kaydedemez. İzin vermek için uygulama izinlerini değiştirin.",+ "serverError.emailDraft.unreachable": "Uygulamalar üzerinden Gmail'e ulaşılamadı (HTTP {status}). Birkaç dakika sonra tekrar deneyin.",+ "serverError.emailDraft.refused": "Gmail reddetti: {detail}",+ "serverError.emailDraft.changed": "Bu taslak, düzenlemeye başladığınızdan beri Gmail'de değişti, bu yüzden hiçbir şey kaydedilmedi. Kart artık en son sürümü gösteriyor: tekrar düzenleyin.",+ "serverError.emailDraft.unreadable": "Gmail bu taslağın şu anda ne içerdiğini söylemedi, bu yüzden hiçbir şey kaydedilmedi. Birkaç dakika sonra tekrar deneyin.","voice.gemini.keyPlaceholder": "Google AI Studio API anahtarınızı yapıştırın","voice.gemini.model": "Gemini konuşma modeli","keys.label.geminiTts": "Gemini konuşma API anahtarı",diff --git a/src/locales/uk.json b/src/locales/uk.jsonindex caa7b7ed7d..5bb32c5583 100644--- a/src/locales/uk.json+++ b/src/locales/uk.json@@ -1,4 +1,30 @@{+ "chat.emailDraft.title": "Чернетка Gmail",+ "chat.emailDraft.sent": "Надіслано з Gmail",+ "chat.emailDraft.to": "Кому",+ "chat.emailDraft.cc": "Копія",+ "chat.emailDraft.bcc": "Прихована копія",+ "chat.emailDraft.subject": "Тема",+ "chat.emailDraft.body": "Повідомлення",+ "chat.emailDraft.noRecipient": "Одержувача ще немає",+ "chat.emailDraft.noSubject": "(без теми)",+ "chat.emailDraft.edit": "Змінити",+ "chat.emailDraft.openInGmail": "Відкрити в Gmail",+ "server.emailDraft.saved": "Чернетку збережено в Gmail: «{subject}» для {to}.",+ "server.emailDraft.sent": "Лист надіслано: «{subject}» для {to}.",+ "server.emailDraft.noRecipient": "одержувача ще немає",+ "server.emailDraft.noSubject": "(без теми)",+ "serverError.emailDraft.notHere": "Цієї чернетки немає в цій розмові.",+ "serverError.emailDraft.alreadySent": "Цей лист уже надіслано.",+ "serverError.emailDraft.busy": "Ця чернетка ще зберігається.",+ "serverError.emailDraft.appsOff": "Під'єднані застосунки вимкнено для цього бота.",+ "serverError.emailDraft.ownGmail": "Під'єднайте свій Gmail у розділі «Застосунки», щоб зберегти цю чернетку.",+ "serverError.emailDraft.appsDown": "Застосунки зараз недоступні. Спробуйте ще раз за кілька хвилин.",+ "serverError.emailDraft.notAllowed": "{name} не може зберігати чернетки Gmail. Змініть його дозволи для застосунків, щоб дозволити це.",+ "serverError.emailDraft.unreachable": "Не вдалося зв'язатися з Gmail через «Застосунки» (HTTP {status}). Спробуйте ще раз за кілька хвилин.",+ "serverError.emailDraft.refused": "Gmail відмовив: {detail}",+ "serverError.emailDraft.changed": "Ця чернетка змінилася в Gmail відтоді, як ви почали її редагувати, тому нічого не збережено. Картка тепер показує найновішу версію: відредагуйте її знову.",+ "serverError.emailDraft.unreadable": "Gmail не повідомив, що зараз у цій чернетці, тому нічого не збережено. Спробуйте ще раз за кілька хвилин.","voice.gemini.keyPlaceholder": "Вставте свій API-ключ Google AI Studio","voice.gemini.model": "Модель синтезу мовлення Gemini","keys.label.geminiTts": "API-ключ синтезу мовлення Gemini",diff --git a/src/locales/vi.json b/src/locales/vi.jsonindex 0835b40bca..000659881a 100644--- a/src/locales/vi.json+++ b/src/locales/vi.json@@ -1,4 +1,30 @@{+ "chat.emailDraft.title": "Thư nháp Gmail",+ "chat.emailDraft.sent": "Đã gửi từ Gmail",+ "chat.emailDraft.to": "Đến",+ "chat.emailDraft.cc": "Cc",+ "chat.emailDraft.bcc": "Bcc",+ "chat.emailDraft.subject": "Tiêu đề",+ "chat.emailDraft.body": "Nội dung",+ "chat.emailDraft.noRecipient": "Chưa có người nhận",+ "chat.emailDraft.noSubject": "(không có tiêu đề)",+ "chat.emailDraft.edit": "Sửa",+ "chat.emailDraft.openInGmail": "Mở trong Gmail",+ "server.emailDraft.saved": "Đã lưu thư nháp trong Gmail: \"{subject}\" gửi {to}.",+ "server.emailDraft.sent": "Đã gửi email: \"{subject}\" gửi {to}.",+ "server.emailDraft.noRecipient": "chưa có người nhận",+ "server.emailDraft.noSubject": "(không có tiêu đề)",+ "serverError.emailDraft.notHere": "Thư nháp đó không có trong cuộc trò chuyện này.",+ "serverError.emailDraft.alreadySent": "Email này đã được gửi.",+ "serverError.emailDraft.busy": "Thư nháp này vẫn đang được lưu.",+ "serverError.emailDraft.appsOff": "Ứng dụng đã kết nối đang tắt cho bot này.",+ "serverError.emailDraft.ownGmail": "Kết nối Gmail của riêng bạn trong Ứng dụng để lưu thư nháp này.",+ "serverError.emailDraft.appsDown": "Hiện không thể kết nối tới Ứng dụng. Hãy thử lại sau vài phút.",+ "serverError.emailDraft.notAllowed": "{name} không được lưu thư nháp Gmail. Hãy đổi quyền ứng dụng của bot để cho phép.",+ "serverError.emailDraft.unreachable": "Không thể kết nối tới Gmail qua Ứng dụng (HTTP {status}). Hãy thử lại sau vài phút.",+ "serverError.emailDraft.refused": "Gmail từ chối: {detail}",+ "serverError.emailDraft.changed": "Thư nháp này đã thay đổi trong Gmail kể từ khi bạn bắt đầu sửa, nên chưa lưu gì. Thẻ hiện cho thấy phiên bản mới nhất: hãy sửa lại.",+ "serverError.emailDraft.unreadable": "Gmail không cho biết thư nháp này hiện chứa gì, nên chưa lưu gì. Hãy thử lại sau vài phút.","voice.gemini.keyPlaceholder": "Dán khóa API Google AI Studio của bạn","voice.gemini.model": "Mô hình giọng nói Gemini","keys.label.geminiTts": "Khóa API giọng nói Gemini",diff --git a/src/locales/zh-tw.json b/src/locales/zh-tw.jsonindex 5dfa1e0448..d12e023a01 100644--- a/src/locales/zh-tw.json+++ b/src/locales/zh-tw.json@@ -1,4 +1,30 @@{+ "chat.emailDraft.title": "Gmail 草稿",+ "chat.emailDraft.sent": "已從 Gmail 寄出",+ "chat.emailDraft.to": "收件者",+ "chat.emailDraft.cc": "副本",+ "chat.emailDraft.bcc": "密件副本",+ "chat.emailDraft.subject": "主旨",+ "chat.emailDraft.body": "內容",+ "chat.emailDraft.noRecipient": "尚無收件者",+ "chat.emailDraft.noSubject": "(無主旨)",+ "chat.emailDraft.edit": "編輯",+ "chat.emailDraft.openInGmail": "在 Gmail 中開啟",+ "server.emailDraft.saved": "已將草稿儲存到 Gmail:寄給 {to} 的「{subject}」。",+ "server.emailDraft.sent": "已寄出電子郵件:寄給 {to} 的「{subject}」。",+ "server.emailDraft.noRecipient": "尚無收件者",+ "server.emailDraft.noSubject": "(無主旨)",+ "serverError.emailDraft.notHere": "這份草稿不在此對話中。",+ "serverError.emailDraft.alreadySent": "這封電子郵件已經寄出。",+ "serverError.emailDraft.busy": "這份草稿仍在儲存中。",+ "serverError.emailDraft.appsOff": "這個機器人的已連結應用程式已關閉。",+ "serverError.emailDraft.ownGmail": "請在應用程式中連結你自己的 Gmail,才能儲存這份草稿。",+ "serverError.emailDraft.appsDown": "目前無法連線到應用程式。請過幾分鐘再試一次。",+ "serverError.emailDraft.notAllowed": "{name} 不能儲存 Gmail 草稿。請變更它的應用程式權限以允許。",+ "serverError.emailDraft.unreachable": "無法透過應用程式連線到 Gmail(HTTP {status})。請過幾分鐘再試一次。",+ "serverError.emailDraft.refused": "Gmail 拒絕了:{detail}",+ "serverError.emailDraft.changed": "你開始編輯後,這份草稿已在 Gmail 中變更,因此沒有儲存任何內容。卡片現在顯示最新版本:請重新編輯。",+ "serverError.emailDraft.unreadable": "Gmail 沒有回報這份草稿目前的內容,因此沒有儲存任何內容。請過幾分鐘再試一次。","connectedWorkspaces.localTitle": "這台電腦上的環境","connectedWorkspaces.missing": "遺失","connectedWorkspaces.current": "目前",diff --git a/src/locales/zh.json b/src/locales/zh.jsonindex d7f8f2e1bc..f4a3018b8f 100644--- a/src/locales/zh.json+++ b/src/locales/zh.json@@ -1,4 +1,30 @@{+ "chat.emailDraft.title": "Gmail 草稿",+ "chat.emailDraft.sent": "已从 Gmail 发送",+ "chat.emailDraft.to": "收件人",+ "chat.emailDraft.cc": "抄送",+ "chat.emailDraft.bcc": "密送",+ "chat.emailDraft.subject": "主题",+ "chat.emailDraft.body": "正文",+ "chat.emailDraft.noRecipient": "还没有收件人",+ "chat.emailDraft.noSubject": "(无主题)",+ "chat.emailDraft.edit": "编辑",+ "chat.emailDraft.openInGmail": "在 Gmail 中打开",+ "server.emailDraft.saved": "草稿已保存到 Gmail:发给 {to} 的“{subject}”。",+ "server.emailDraft.sent": "邮件已发送:发给 {to} 的“{subject}”。",+ "server.emailDraft.noRecipient": "还没有收件人",+ "server.emailDraft.noSubject": "(无主题)",+ "serverError.emailDraft.notHere": "这份草稿不在此对话中。",+ "serverError.emailDraft.alreadySent": "这封邮件已经发送。",+ "serverError.emailDraft.busy": "这份草稿仍在保存中。",+ "serverError.emailDraft.appsOff": "此机器人的已连接应用已关闭。",+ "serverError.emailDraft.ownGmail": "请在应用中连接你自己的 Gmail 才能保存这份草稿。",+ "serverError.emailDraft.appsDown": "现在无法连接到应用。请几分钟后再试。",+ "serverError.emailDraft.notAllowed": "{name} 不能保存 Gmail 草稿。请更改它的应用权限以允许。",+ "serverError.emailDraft.unreachable": "无法通过应用连接到 Gmail(HTTP {status})。请几分钟后再试。",+ "serverError.emailDraft.refused": "Gmail 拒绝了:{detail}",+ "serverError.emailDraft.changed": "你开始编辑后,这份草稿在 Gmail 中已更改,所以没有保存任何内容。卡片现在显示最新版本:请重新编辑。",+ "serverError.emailDraft.unreadable": "Gmail 没有说明这份草稿现在的内容,所以没有保存任何内容。请几分钟后再试。","connectedWorkspaces.localTitle": "这台电脑上的环境","connectedWorkspaces.missing": "不存在","connectedWorkspaces.current": "当前",diff --git a/src/state/store.tsx b/src/state/store.tsxindex 7d97bc8cdb..673953f9b7 100644--- a/src/state/store.tsx+++ b/src/state/store.tsx@@ -116,7 +116,7 @@ export type SecretRequestCardData = Omit<import("../../shared/wire").SecretRequeexport type ComputerControlState = { held: boolean; helpReason: string | null; help?: import("../../shared/wire").ComputerHelpRef | null };-export interface Message extends Pick<import("../../shared/wire").WireMessage, "widget" | "app" | "automated" | "waitId" | "fromApp" | "pointed" | "routedBy" | "quickModel" | "automation" | "publishedPage" | "template" | "sender" | "setupSuggestion" | "settingsCard" | "helperIntro" | "helperFollowup" | "setupOffer" | "savedSteps" | "setupChoices" | "setupChoicesPending" | "setupChoicesUpdating" | "setupRequest" | "relay" | "inbox" | "sentDirectly" | "doneWhen" | "checkBack" | "checkRound" | "handoff" | "bugReport" | "engineCompaction" | "stoppedBy" | "askedBy"> {+export interface Message extends Pick<import("../../shared/wire").WireMessage, "widget" | "app" | "automated" | "waitId" | "fromApp" | "pointed" | "routedBy" | "quickModel" | "automation" | "publishedPage" | "template" | "sender" | "setupSuggestion" | "settingsCard" | "emailDraft" | "helperIntro" | "helperFollowup" | "setupOffer" | "savedSteps" | "setupChoices" | "setupChoicesPending" | "setupChoicesUpdating" | "setupRequest" | "relay" | "inbox" | "sentDirectly" | "doneWhen" | "checkBack" | "checkRound" | "handoff" | "bugReport" | "engineCompaction" | "stoppedBy" | "askedBy"> {id: string;role: "bot" | "user";kind: "text" | "options" | "activity" | "screen" | "connector" | "secret" | "signin" | "routine.run" | "goal.run" | "burst" | "digest" | "compaction" | "call" | "widget" | "app";