mirror of
https://github.com/cloudflare/cloudflare-os.git
synced 2026-11-25 02:38:04 +08:00
fix(gatekeeper-google): name Chat picker conversations after their participants
The conversation picker titled every DM "Direct message", matched queries against conversation IDs, and showed a 1/1/1970 activity date where Google reports an unset time as the epoch. - Name DMs and unnamed group chats as getMetadata does, cached per picker and capped at 200, since each costs a members.list read against the project-wide quota. People lookups are batched across conversations. - Match by name only and drop the ID tail. - Treat epoch timestamps as absent.
This commit is contained in:
@@ -61,9 +61,9 @@ optional: fall back to the ID when Google omits one. The connected account's ide
|
||||
the existing sign-in profile lookup. Methods that accept an email address as input still support it.
|
||||
|
||||
Call **`space.getMetadata()`** to name a DM or unnamed group chat after its other participants,
|
||||
and to identify a DM's other participant (`peer`). Account listings and the connection picker use
|
||||
only Chat's returned metadata, with no membership lookups. Agents receive this guidance in the
|
||||
API type comments. For example:
|
||||
and to identify a DM's other participant (`peer`). Account listings use only Chat's returned
|
||||
metadata, with no membership lookups. Agents receive this guidance in the API type comments. For
|
||||
example:
|
||||
|
||||
```ts
|
||||
const info = entry.info.name ? entry.info : await entry.space.getMetadata();
|
||||
@@ -77,11 +77,16 @@ responses, so the nameless people among those are looked up in one People API `p
|
||||
call; those names need no observer check, since anyone who can open the conversation is a
|
||||
participant. When a DM's membership is ambiguous, it has no `peer`; when no source names anyone,
|
||||
the conversation stays unnamed and the ID is the fallback. A failed lookup never fails the read.
|
||||
Send approvals and connection titles name conversations the same way. Spaces and named group
|
||||
chats require no lookup. Memberships are a `kind: "user" | "group"` union. Messages list the
|
||||
users they @mention in `mentions`. Picker searches scan at most five pages; paste `spaces/ID`, a
|
||||
Chat room/DM URL, or a Chat-in-Gmail `#chat/` URL to access an exact conversation beyond that
|
||||
scan.
|
||||
Send approvals, connection titles, and the connection picker name conversations the same way.
|
||||
Spaces and named group chats require no lookup. Memberships are a `kind: "user" | "group"` union.
|
||||
Messages list the users they @mention in `mentions`.
|
||||
|
||||
The connection picker matches conversations by name only, and scans at most five pages; paste
|
||||
`spaces/ID`, a Chat room/DM URL, or a Chat-in-Gmail `#chat/` URL to access an exact conversation
|
||||
beyond that scan. It names at most 200 DMs and unnamed group chats per session, remembering each,
|
||||
because every one costs a `members.list` read against the OAuth project's shared quota of 3,000 a
|
||||
minute; the People lookups for all of them share batched calls. The rest keep a generic label.
|
||||
Google reports a never-set last activity as the epoch, which is treated as absent.
|
||||
|
||||
## Discover and operate on threads
|
||||
|
||||
@@ -239,5 +244,5 @@ conversation references, time bounds, scope filtering, and overlays. Durable `sp
|
||||
handoff uses the existing gadget restoration mechanism; it is not exercised end-to-end by the
|
||||
Chat gatekeeper suite. An identity regression checks that Chat-provided names reach message,
|
||||
thread, member, and reaction results without extra identity lookups. DM tests cover on-demand
|
||||
peer resolution, lookup-free listings and picker searches, peer selection, pagination, and
|
||||
peer resolution, lookup-free listings, picker naming and name matching, peer selection, pagination, and
|
||||
observer admission by space access.
|
||||
|
||||
@@ -144,7 +144,7 @@ describe("Chat filter construction", () => {
|
||||
});
|
||||
|
||||
describe("Chat response mapping", () => {
|
||||
it("maps a space", () => {
|
||||
it("maps a space, treating the epoch Google reports for an unset time as absent", () => {
|
||||
expect(chatSpaceInfoFromRaw({
|
||||
name: "spaces/AAAA",
|
||||
displayName: "Project",
|
||||
@@ -153,6 +153,7 @@ describe("Chat response mapping", () => {
|
||||
spaceUri: "https://chat.google.com/room/AAAA",
|
||||
spaceDetails: { description: "Planning" },
|
||||
createTime: "2024-01-01T00:00:00Z",
|
||||
lastActiveTime: "1970-01-01T00:00:00Z",
|
||||
membershipCount: { joinedDirectHumanUserCount: 7 },
|
||||
})).toEqual({
|
||||
id: "spaces/AAAA",
|
||||
|
||||
@@ -366,16 +366,16 @@ describe("Chat identities", () => {
|
||||
expect(backend.state.memberRequests).toBe(1);
|
||||
});
|
||||
|
||||
it("does not resolve participant names during picker searches", async () => {
|
||||
it("names picker DMs once, and matches them by name rather than ID", async () => {
|
||||
const backend = directMessage();
|
||||
const chat = chatHarness(backend);
|
||||
using _session = await chat.session();
|
||||
const picker = new ChatSpaceConfiguratorUI(async () => ({token: "access-token", expires: new Date(Date.now() + 60_000)}));
|
||||
expect(await picker.listChatSpaces("")).toEqual([
|
||||
{value: SPACE_ID, title: "Direct message", subtitle: "Direct message", meta: SPACE_ID},
|
||||
]);
|
||||
expect(await picker.listChatSpaces("Alice")).toEqual([]);
|
||||
expect(backend.state.memberRequests).toBe(0);
|
||||
const alice = {value: SPACE_ID, title: "Alice Smith", subtitle: "Direct message"};
|
||||
expect(await picker.listChatSpaces("")).toEqual([alice]);
|
||||
expect(await picker.listChatSpaces("alice")).toEqual([alice]);
|
||||
expect(await picker.listChatSpaces(SPACE_ID.toLowerCase())).toEqual([]);
|
||||
expect(backend.state.memberRequests).toBe(1);
|
||||
});
|
||||
|
||||
it("opens an exact conversation reference without scanning the picker listing", async () => {
|
||||
@@ -384,7 +384,7 @@ describe("Chat identities", () => {
|
||||
using _session = await chat.session();
|
||||
const picker = new ChatSpaceConfiguratorUI(async () => ({token: "access-token", expires: new Date(Date.now() + 60_000)}));
|
||||
expect(await picker.listChatSpaces(SPACE_NAME)).toEqual([
|
||||
{value: SPACE_ID, title: "Direct message", subtitle: "Direct message", meta: SPACE_ID},
|
||||
{value: SPACE_ID, title: "Alice Smith", subtitle: "Direct message"},
|
||||
]);
|
||||
expect(await picker.listChatSpaces(`https://chat.google.com/dm/${SPACE_ID}`)).toHaveLength(1);
|
||||
expect(backend.state.spaceLists).toBe(0);
|
||||
|
||||
@@ -286,10 +286,11 @@ export type ChatPage<T> = { items: T[]; nextPageToken?: string };
|
||||
|
||||
// ── Mapping to the agent-facing shapes ──────────────────────────────
|
||||
|
||||
/** Google reports an unset timestamp, such as a conversation's never-set last activity, as the epoch. */
|
||||
function chatTime(value: string | undefined): Date | undefined {
|
||||
if (!value) return undefined;
|
||||
const parsed = new Date(value);
|
||||
return Number.isNaN(parsed.valueOf()) ? undefined : parsed;
|
||||
return parsed.valueOf() > 0 ? parsed : undefined;
|
||||
}
|
||||
|
||||
const SPACE_TYPES: Record<string, ChatSpaceType> = {
|
||||
|
||||
@@ -5,51 +5,74 @@ import type { ChatSpaceInfo, ChatUser } from "./chat-types";
|
||||
const LABELLED_PARTICIPANTS = 3;
|
||||
/** Membership pages read per conversation; a DM needs one, and a group chat's label only a few names. */
|
||||
const MEMBER_PAGES = 3;
|
||||
/** Conversations whose members are read at once. */
|
||||
const MEMBER_CONCURRENCY = 8;
|
||||
/** Users one People API lookup accepts. */
|
||||
const PROFILE_BATCH = 200;
|
||||
|
||||
const LIST_FORMAT = new Intl.ListFormat("en");
|
||||
|
||||
/** Whether `describeConversation` has anything to add: a DM or an unnamed group chat. */
|
||||
/** Whether `describeConversations` has anything to add: a DM or an unnamed group chat. */
|
||||
export const needsDescription = (info: ChatSpaceInfo): boolean =>
|
||||
info.type === "directMessage" || (info.type === "groupChat" && !info.name);
|
||||
|
||||
type Participants = { count: number; shown: ChatUser[] };
|
||||
|
||||
/**
|
||||
* Name a direct message or unnamed group chat after its other participants, and identify a DM's
|
||||
* `peer`. Spaces and named group chats return unchanged, as does anything whose lookup fails.
|
||||
* Name direct messages and unnamed group chats after their other participants, and identify each
|
||||
* DM's `peer`. Spaces and named group chats return unchanged, as does anything whose lookup fails.
|
||||
*
|
||||
* Chat may omit members' display names, so nameless people are looked up in the People API.
|
||||
* Those names need no observer check: anyone who can open the conversation is a participant.
|
||||
* Chat may omit members' display names, so nameless people are looked up in the People API, in
|
||||
* one batch across every conversation. Those names need no observer check: anyone who can open a
|
||||
* conversation is a participant.
|
||||
*/
|
||||
export async function describeConversation(
|
||||
api: ChatApi, info: ChatSpaceInfo, selfId: string,
|
||||
): Promise<ChatSpaceInfo> {
|
||||
if (!needsDescription(info)) return info;
|
||||
return nameAfterParticipants(api, info, selfId).catch(() => info);
|
||||
export async function describeConversations(
|
||||
api: ChatApi, infos: readonly ChatSpaceInfo[], selfId: string,
|
||||
): Promise<ChatSpaceInfo[]> {
|
||||
const participants = await mapPooled(infos, MEMBER_CONCURRENCY, async (info): Promise<Participants | undefined> => {
|
||||
if (!needsDescription(info)) return undefined;
|
||||
const others = await otherParticipants(api, info.id, selfId).catch(() => undefined);
|
||||
if (!others || (info.type === "directMessage" && others.length !== 1)) return undefined;
|
||||
return { count: others.length, shown: others.slice(0, LABELLED_PARTICIPANTS) };
|
||||
});
|
||||
const profiles = await profileNames(api, participants.flatMap(found => found?.shown ?? []));
|
||||
return infos.map((info, i) => {
|
||||
const found = participants[i];
|
||||
return found ? nameAfter(info, found, profiles) : info;
|
||||
});
|
||||
}
|
||||
|
||||
async function nameAfterParticipants(
|
||||
/** `describeConversations` for one conversation. */
|
||||
export const describeConversation = async (
|
||||
api: ChatApi, info: ChatSpaceInfo, selfId: string,
|
||||
): Promise<ChatSpaceInfo> {
|
||||
const dm = info.type === "directMessage";
|
||||
const others = await otherParticipants(api, info.id, selfId);
|
||||
if (dm && others.length !== 1) return info;
|
||||
const shown = others.slice(0, LABELLED_PARTICIPANTS);
|
||||
const profiles = await api.profileNames(
|
||||
shown.filter(user => !user.name && user.type === "human").map(user => user.id));
|
||||
): Promise<ChatSpaceInfo> => (await describeConversations(api, [info], selfId))[0];
|
||||
|
||||
function nameAfter(info: ChatSpaceInfo, { count, shown }: Participants, profiles: Map<string, string>): ChatSpaceInfo {
|
||||
const named = shown.map(user => {
|
||||
const name = user.name ?? profiles.get(user.id);
|
||||
return name ? { ...user, name } : user;
|
||||
});
|
||||
if (dm) {
|
||||
if (info.type === "directMessage") {
|
||||
const [peer] = named;
|
||||
return { ...info, peer, ...(peer.name ? { name: peer.name } : {}) };
|
||||
}
|
||||
const names = named.flatMap(user => user.name ?? []);
|
||||
if (names.length === 0) return info;
|
||||
// memberCount includes the connected user but not apps, and the listing may be cut short.
|
||||
const rest = Math.max(others.length, (info.memberCount ?? 0) - 1) - names.length;
|
||||
const rest = Math.max(count, (info.memberCount ?? 0) - 1) - names.length;
|
||||
return { ...info, name: LIST_FORMAT.format(rest > 0 ? [...names, `${rest} more`] : names) };
|
||||
}
|
||||
|
||||
/** People API names for the nameless people among `users`; absent wherever a lookup fails. */
|
||||
async function profileNames(api: ChatApi, users: readonly ChatUser[]): Promise<Map<string, string>> {
|
||||
const ids = [...new Set(users.filter(user => !user.name && user.type === "human").map(user => user.id))];
|
||||
const batches = await Promise.all(
|
||||
Array.from({ length: Math.ceil(ids.length / PROFILE_BATCH) }, (_, i) =>
|
||||
api.profileNames(ids.slice(i * PROFILE_BATCH, (i + 1) * PROFILE_BATCH))
|
||||
.catch(() => new Map<string, string>())));
|
||||
return new Map(batches.flatMap(batch => [...batch]));
|
||||
}
|
||||
|
||||
/** The conversation's joined people and apps other than the connected user, in Chat's order. */
|
||||
async function otherParticipants(api: ChatApi, spaceName: string, selfId: string): Promise<ChatUser[]> {
|
||||
const others = new Map<string, ChatUser>();
|
||||
@@ -66,3 +89,17 @@ async function otherParticipants(api: ChatApi, spaceName: string, selfId: string
|
||||
}
|
||||
return [...others.values()];
|
||||
}
|
||||
|
||||
/** `items.map(map)` with at most `limit` calls in flight. */
|
||||
async function mapPooled<T, R>(items: readonly T[], limit: number, map: (item: T) => Promise<R>): Promise<R[]> {
|
||||
const results: R[] = [];
|
||||
let next = 0;
|
||||
const worker = async () => {
|
||||
while (next < items.length) {
|
||||
const i = next++;
|
||||
results[i] = await map(items[i]);
|
||||
}
|
||||
};
|
||||
await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker));
|
||||
return results;
|
||||
}
|
||||
|
||||
@@ -3,8 +3,9 @@ import { validateRpc } from "capnweb-validate";
|
||||
import { BigQueryApi } from "./bigquery-api";
|
||||
import { GoogleCalendarApi } from "./calendar-api";
|
||||
import { ChatApi, chatSpaceIdFromReference, isChatNoAccessError } from "./chat-api";
|
||||
import { describeConversations, needsDescription } from "./chat-names";
|
||||
import type { ChatSpaceInfo } from "./chat-types";
|
||||
import { GoogleAccessToken } from "./google-api";
|
||||
import { GoogleAccessToken, getGoogleAccountProfile } from "./google-api";
|
||||
import { AccessTokenProvider, AccessTokenRequest } from "./auth-retry";
|
||||
import { DriveApi, DriveApiDisabledError, FOLDER_MIME_TYPE } from "./drive-api";
|
||||
import type { BigQueryConfiguratorRpc } from "./configurator/bigquery-configurator-types";
|
||||
@@ -31,6 +32,14 @@ type ConfiguratorTokenGetter = (opts?: AccessTokenRequest) => Promise<GoogleAcce
|
||||
const googleTokenGetters = new WeakMap<object, ConfiguratorTokenGetter>();
|
||||
const calendarConfiguratorCaches = new WeakMap<object, Promise<ConfiguratorOption[]>>();
|
||||
const bigQueryConfiguratorCaches = new WeakMap<object, Map<string, ConfiguratorOption[]>>();
|
||||
/** Per Chat picker: the connected user's id, and each conversation already named. */
|
||||
type ChatPickerCache = { selfId?: string; described: Map<string, ChatSpaceInfo> };
|
||||
const chatConfiguratorCaches = new WeakMap<object, ChatPickerCache>();
|
||||
/**
|
||||
* Conversations one Chat picker names. Each costs a membership read against a quota the whole
|
||||
* OAuth project shares (3,000 a minute), so the rest keep their generic label.
|
||||
*/
|
||||
const CHAT_CONFIGURATOR_NAMED_MAX = 200;
|
||||
const BIGQUERY_CONFIGURATOR_CACHE_MAX_ENTRIES = 200;
|
||||
const BIGQUERY_CONFIGURATOR_EMPTY_LIST_OPTIONS = { maxPages: 1, maxResults: 200 };
|
||||
const BIGQUERY_CONFIGURATOR_SEARCH_LIST_OPTIONS = { maxPages: 5, maxResults: 1000 };
|
||||
@@ -112,17 +121,30 @@ function idTail(id: string): string {
|
||||
}
|
||||
|
||||
function chatSpaceOption(space: ChatSpaceInfo): ConfiguratorOption {
|
||||
const id = space.id.slice("spaces/".length);
|
||||
const kind = space.type === "directMessage" ? "Direct message"
|
||||
: space.type === "groupChat" ? "Group chat" : "Space";
|
||||
return {
|
||||
value: id,
|
||||
value: space.id.slice("spaces/".length),
|
||||
title: space.name ?? kind,
|
||||
subtitle: space.lastActiveAt ? `${kind} · Active ${space.lastActiveAt.toLocaleDateString()}` : kind,
|
||||
meta: idTail(id),
|
||||
};
|
||||
}
|
||||
|
||||
/** Name DMs and unnamed group chats after their participants, remembering them for the picker. */
|
||||
async function describeChatSpaces(
|
||||
target: object, api: ChatApi, infos: ChatSpaceInfo[],
|
||||
): Promise<ChatSpaceInfo[]> {
|
||||
const cache: ChatPickerCache = chatConfiguratorCaches.get(target) ?? { described: new Map() };
|
||||
chatConfiguratorCaches.set(target, cache);
|
||||
const fresh = infos.filter(info => needsDescription(info) && !cache.described.has(info.id))
|
||||
.slice(0, CHAT_CONFIGURATOR_NAMED_MAX - cache.described.size);
|
||||
if (fresh.length > 0) {
|
||||
cache.selfId ??= `users/${(await getGoogleAccountProfile(googleTokenProvider(target))).sub}`;
|
||||
for (const info of await describeConversations(api, fresh, cache.selfId)) cache.described.set(info.id, info);
|
||||
}
|
||||
return infos.map(info => cache.described.get(info.id) ?? info);
|
||||
}
|
||||
|
||||
async function listDriveFiles(
|
||||
target: object,
|
||||
query: string,
|
||||
@@ -293,11 +315,12 @@ export class ChatSpaceConfiguratorUI extends RpcTarget implements ChatSpaceConfi
|
||||
}
|
||||
|
||||
/**
|
||||
* Conversations this account has joined, filtered locally.
|
||||
* Conversations this account has joined, matched by name.
|
||||
*
|
||||
* Chat's own space search only matches named spaces, so it would hide every direct message and
|
||||
* group chat -- exactly the conversations whose id is hardest to find by hand. Scan a bounded
|
||||
* five provider pages, stopping once the picker has its 100 visible options.
|
||||
* five provider pages, naming DMs and unnamed group chats after their participants, and stop
|
||||
* once the picker has its 100 visible options.
|
||||
*/
|
||||
async listChatSpaces(query: string): Promise<ConfiguratorOption[]> {
|
||||
const api = new ChatApi(googleTokenProvider(this));
|
||||
@@ -305,20 +328,21 @@ export class ChatSpaceConfiguratorUI extends RpcTarget implements ChatSpaceConfi
|
||||
// Exact references bypass the bounded discovery scan, including conversations on later pages.
|
||||
const exact = chatSpaceIdFromReference(query);
|
||||
if (exact !== undefined) {
|
||||
let space: ChatSpaceInfo;
|
||||
try {
|
||||
const space = await api.getSpace(`spaces/${exact}`);
|
||||
return [chatSpaceOption(space)];
|
||||
space = await api.getSpace(`spaces/${exact}`);
|
||||
} catch (error) {
|
||||
if (isChatNoAccessError(error)) return [];
|
||||
throw error;
|
||||
}
|
||||
return (await describeChatSpaces(this, api, [space])).map(chatSpaceOption);
|
||||
}
|
||||
let pageToken: string | undefined;
|
||||
for (let pageNumber = 0; pageNumber < 5 && options.length < 100; pageNumber++) {
|
||||
const page = await api.listSpaces({ pageSize: query.trim() ? 200 : 100, ...(pageToken ? { pageToken } : {}) });
|
||||
options.push(...page.items
|
||||
options.push(...(await describeChatSpaces(this, api, page.items))
|
||||
.map(chatSpaceOption)
|
||||
.filter(option => optionMatches([option.title, option.subtitle, option.value], query)));
|
||||
.filter(option => optionMatches([option.title], query)));
|
||||
pageToken = page.nextPageToken;
|
||||
if (!pageToken) break;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user