Multiplayer agent harness for work.
Fix Sent mail account resolution (#1359)
Eve Bouffardec10fd3b2f75
diff --git a/plugins/web-ui/server/index.ts b/plugins/web-ui/server/index.tsindex b56441411..821eec71c 100644--- a/plugins/web-ui/server/index.ts+++ b/plugins/web-ui/server/index.ts@@ -2535,10 +2535,17 @@ const apiRoutes: readonly WebRoute[] = [{method: "GET",path: "/api/inbox/sent/:messageId",- handle: async ({ res, user, params }) => {+ handle: async ({ res, user, params, url }) => {if (!isInboxUser(user)) return json(res, 403, { error: "forbidden" });+ const query = new URLSearchParams();+ const accountType = url.searchParams.get("accountType");+ if (accountType) query.set("accountType", accountType);res.setHeader("Cache-Control", "no-store");- return relayCore(res, "GET", `/v1/connectors/gmail/sent/${encodeURIComponent(params.messageId!)}`);+ return relayCore(+ res,+ "GET",+ `/v1/connectors/gmail/sent/${encodeURIComponent(params.messageId!)}${query.size ? `?${query}` : ""}`,+ );},},{diff --git a/plugins/web-ui/src/sent-mail.ts b/plugins/web-ui/src/sent-mail.tsindex fb8dcf81e..d73de01bf 100644--- a/plugins/web-ui/src/sent-mail.ts+++ b/plugins/web-ui/src/sent-mail.ts@@ -35,6 +35,7 @@ interface SentMailPage {let messages: SentEmail[] = [];let nextPageToken: string | undefined;let accountEmail = "";+let accountType: SentEmail["accountType"];let loading = false;let loaded = false;let error = "";@@ -77,7 +78,7 @@ export async function openSentEmail(message: SentEmail, draw: () => void): Promiattachments: [],}: await api<NonNullable<typeof detail>>(- `/api/inbox/sent/${encodeURIComponent(message.id)}?${new URLSearchParams({ accountType: message.accountType ?? "default" })}`,+ `/api/inbox/sent/${encodeURIComponent(message.id)}?${new URLSearchParams(message.accountType ? { accountType: message.accountType } : {})}`,);if (current === detailGeneration) {detail = result;@@ -170,6 +171,7 @@ export function resetSentMail(): void {messages = [];nextPageToken = undefined;accountEmail = "";+ accountType = undefined;loading = false;loaded = false;error = "";@@ -180,18 +182,25 @@ export async function loadSentMail(draw: () => void, more = false): Promise<voidloading = true;error = "";const current = ++generation;- const params = new URLSearchParams({ accountType: "default" });- if (more && nextPageToken) params.set("pageToken", nextPageToken);+ const params = new URLSearchParams();+ if (more) {+ if (nextPageToken) params.set("pageToken", nextPageToken);+ if (accountType) params.set("accountType", accountType);+ }draw();try {const local = more ? null : await fetchLocalSentMail();const page = local ?? (await api<SentMailPage>(`/api/inbox/sent?${params}`));if (current !== generation) return;+ accountType = page.accountType ?? (more ? accountType : "default");messages = [...new Map([...(more ? messages : []),- ...page.messages.map((message) => ({ ...message, accountType: page.accountType ?? ("default" as const) })),+ ...page.messages.map((message) => ({+ ...message,+ accountType: page.accountType ?? accountType ?? "default",+ })),].map((message) => [message.id, message]),).values(),].sort((a, b) => b.sentAt - a.sentAt);diff --git a/plugins/web-ui/test/inbox-server-route.test.ts b/plugins/web-ui/test/inbox-server-route.test.tsindex b6c98f64a..e299982b0 100644--- a/plugins/web-ui/test/inbox-server-route.test.ts+++ b/plugins/web-ui/test/inbox-server-route.test.ts@@ -67,6 +67,19 @@ test("GET /api/inbox resolves the signed-in person's inbox loop, never someone eassert.equal(coreQuery(call.url, "principalId"), "alice");});+test("sent mail routes preserve Gmail account affinity", async () => {+ await fetch(`${base}/api/inbox/sent?pageToken=next&accountType=company`, { headers });+ const list = lastCallTo("/v1/connectors/gmail/sent");+ assert.ok(list);+ assert.equal(coreQuery(list.url, "pageToken"), "next");+ assert.equal(coreQuery(list.url, "accountType"), "company");++ await fetch(`${base}/api/inbox/sent/message-1?accountType=company`, { headers });+ const detail = lastCallTo("/v1/connectors/gmail/sent/message-1");+ assert.ok(detail);+ assert.equal(coreQuery(detail.url, "accountType"), "company");+});+test("POST /api/inbox/sync-cron carries the caller, not the body's claim", async () => {await fetch(`${base}/api/inbox/sync-cron`, {method: "POST",diff --git a/plugins/web-ui/test/sent-mail.test.ts b/plugins/web-ui/test/sent-mail.test.tsindex 442fa10c0..9d2ffdbcd 100644--- a/plugins/web-ui/test/sent-mail.test.ts+++ b/plugins/web-ui/test/sent-mail.test.ts@@ -57,6 +57,7 @@ test("sent view pages Gmail messages and opens the matching Google account", asyconst next = String(input).includes("pageToken=");return Response.json({accountEmail: "[email protected]",+ accountType: "company",messages: [{id: next ? "older" : "newer",@@ -71,6 +72,7 @@ test("sent view pages Gmail messages and opens the matching Google account", asy});};await loadSentMail(draw);+ assert.doesNotMatch(urls.at(-1)!, /accountType=/);assert.match(host.textContent!, /A & B/);assert.equal(host.querySelector("a"), null);await loadSentMail(draw, true);@@ -78,7 +80,7 @@ test("sent view pages Gmail messages and opens the matching Google account", asyconst sentRow = host.querySelector(".inbox-sent-row")!;assert.ok(sentRow.closest(".inbox-item")!.classList.contains("src-gmail"));assert.equal(sentRow.querySelector(".inbox-item-glyph svg")!.getAttribute("width"), "14");- assert.match(urls.at(-1)!, /accountType=default/);+ assert.match(urls.at(-1)!, /accountType=company/);assert.match(urls.at(-1)!, /pageToken=cursor/);assert.equal(host.querySelector(".inbox-sent-more"), null);let chatRequest: Record<string, unknown> = {};@@ -126,11 +128,17 @@ test("sent view pages Gmail messages and opens the matching Google account", asyassert.equal(host.querySelectorAll(".inbox-sent-row").length, 2);resetSentMail();let detailRequest = "";- globalThis.fetch = async (input) => {+ let directChatAccountType: unknown;+ globalThis.fetch = async (input, options) => {if (String(input).endsWith("/sent-seed.local.json")) return new Response(null, { status: 404 });- if (String(input).endsWith("/inbox/sent-chat")) return Response.json({ item: { id: "chat", thread: [] } });+ if (String(input).endsWith("/inbox/sent-chat")) {+ directChatAccountType = JSON.parse(String(options?.body)).accountType;+ return Response.json({ item: { id: "chat", thread: [] } });+ }detailRequest = String(input);+ assert.equal(new URL(detailRequest, location.origin).searchParams.has("accountType"), false);return Response.json({+ accountType: "company",id: "unlisted",threadId: "thread-unlisted",to: "Alex",@@ -145,7 +153,8 @@ test("sent view pages Gmail messages and opens the matching Google account", asy});};await openSentEmailById("unlisted", draw);- assert.match(detailRequest, /\/api\/inbox\/sent\/unlisted\?accountType=default$/);+ assert.match(detailRequest, /\/api\/inbox\/sent\/unlisted\?$/);+ assert.equal(directChatAccountType, "company");render(sentEmailPageTpl(draw), host);assert.match(host.textContent!, /Direct link/);assert.match(host.textContent!, /Loaded without listing/);diff --git a/src/api/routes/connectors.ts b/src/api/routes/connectors.tsindex fea4fa8f7..acbaf128e 100644--- a/src/api/routes/connectors.ts+++ b/src/api/routes/connectors.ts@@ -14,7 +14,7 @@ import {type OAuthState,} from "../../connectors/oauth.ts";import { bestOAuthTokenStatus, CONNECTOR_STATUS_ACCOUNT_TYPES } from "../../credentials/connector-status.ts";-import type { OAuthTokenStatus } from "../../credentials/keychain.ts";+import type { DerivedOAuthAuth, OAuthTokenStatus } from "../../credentials/keychain.ts";import { createEnvSecretSource } from "../../credentials/secret-source.ts";import type { ServerDeps } from "../deps.ts";import { personKey, samePerson } from "../../directory/person.ts";@@ -506,18 +506,30 @@ export async function gmailSent(ctx: ApiCtx): Promise<void> {const principal = ctx.actor?.p;ctx.res.setHeader("Cache-Control", "no-store");if (!principal) return sendJson(ctx.res, 403, { error: "forbidden", message: "Sign in to read sent mail." });- const accountType = ctx.url.searchParams.get("accountType") ?? "default";- if (!["default", "personal", "company"].includes(accountType))+ const requestedAccountType = ctx.url.searchParams.get("accountType");+ if (requestedAccountType !== null && !["default", "personal", "company"].includes(requestedAccountType))return sendJson(ctx.res, 400, { error: "bad_request" });const pageToken = ctx.url.searchParams.get("pageToken") ?? undefined;if (pageToken && pageToken.length > 2048) return sendJson(ctx.res, 400, { error: "bad_request" });try {- const auth = await ctx.deps.connectorTokens?.connectorDerivedAuth(- "gmail.googleapis.com",- principal,- accountType as AccountType,- );- if (!auth)+ let accountType: AccountType | undefined;+ let auth: DerivedOAuthAuth | null | undefined;+ let authError: unknown;+ for (const candidate of requestedAccountType+ ? [requestedAccountType as AccountType]+ : (["default", "personal", "company"] satisfies AccountType[])) {+ try {+ auth = await ctx.deps.connectorTokens?.connectorDerivedAuth("gmail.googleapis.com", principal, candidate);+ if (auth) {+ accountType = candidate;+ break;+ }+ } catch (error) {+ authError ??= error;+ }+ }+ if (!auth && authError) throw authError;+ if (!auth || !accountType)return sendJson(ctx.res, 409, {error: "not_connected",message: "Connect this Google account in Settings to see sent mail.",diff --git a/test/gmail-sent-route.test.ts b/test/gmail-sent-route.test.tsindex bde9b3199..5260383ed 100644--- a/test/gmail-sent-route.test.ts+++ b/test/gmail-sent-route.test.ts@@ -38,3 +38,50 @@ test("sent mail requires portal identity and ignores a forged principal query",assert.equal(status, 400);assert.equal(requestedPrincipal, "");});++test("sent mail resolves the connected Google account slot", async () => {+ const requestedAccountTypes: Array<string | undefined> = [];+ let status = 0;+ let body = "";+ const originalFetch = globalThis.fetch;+ globalThis.fetch = async (input) => {+ const url = new URL(String(input));+ if (url.pathname.endsWith("/messages")) return Response.json({ messages: [] });+ if (url.pathname.endsWith("/profile")) return Response.json({ emailAddress: "[email protected]" });+ return new Response(null, { status: 404 });+ };+ const ctx = {+ actor: { p: "[email protected]" },+ url: new URL("http://localhost/v1/connectors/gmail/sent"),+ params: {},+ res: {+ setHeader() {},+ writeHead(code: number) {+ status = code;+ },+ end(value: string) {+ body = value;+ },+ },+ deps: {+ connectorTokens: {+ async connectorDerivedAuth(_host: string, _principal: string, accountType?: string) {+ requestedAccountTypes.push(accountType);+ return accountType === "company" ? { accessToken: "company-token" } : null;+ },+ },+ },+ } as unknown as ApiCtx;+ try {+ await gmailSent(ctx);+ } finally {+ globalThis.fetch = originalFetch;+ }+ assert.equal(status, 200);+ assert.deepEqual(requestedAccountTypes, ["default", "personal", "company"]);+ assert.deepEqual(JSON.parse(body), {+ messages: [],+ accountEmail: "[email protected]",+ accountType: "company",+ });+});