Multiplayer agent harness for work.
Take Inbox Slack photos from the org directory (#2325)
Regan Belld40b6e6e2c2a
diff --git a/src/directory/directory-store.ts b/src/directory/directory-store.tsindex 225935495..60504d221 100644--- a/src/directory/directory-store.ts+++ b/src/directory/directory-store.ts@@ -59,6 +59,7 @@ export interface DirectoryStore {list(): Promise<DirectoryMember[]>;listChannels(): Promise<DirectoryChannel[]>;get(principalId: string): Promise<DirectoryMember | null>;+ getBySlackId(slackId: string): Promise<DirectoryMember | null>;resolve(query: string): Promise<RecipientResolution>;resolveChannel(query: string): Promise<ChannelResolution>;channelMember(channelId: string, principalId: string): Promise<boolean>;@@ -309,6 +310,9 @@ export function createDirectoryStore(): DirectoryStore {async get(principalId) {return members.find((m) => samePerson(m.principalId, principalId)) ?? null;},+ async getBySlackId(slackId) {+ return members.find((m) => (m.slackId ?? m.principalId) === slackId) ?? null;+ },async resolve(query) {const bySlackId = members.find((x) => x.slackId && x.slackId === query.trim());if (bySlackId) return { kind: "one", member: bySlackId };diff --git a/src/directory/postgres-directory-store.ts b/src/directory/postgres-directory-store.tsindex f485e824d..6b969a1aa 100644--- a/src/directory/postgres-directory-store.ts+++ b/src/directory/postgres-directory-store.ts@@ -672,6 +672,15 @@ export function createPostgresDirectoryStore(connectionString: string): Directorreturn rows.length ? memberRow(rows[0]!) : null;},+ async getBySlackId(slackId) {+ const rows = await q(+ `SELECT ${MEMBER_COLS} FROM directory_members+ WHERE org_id = $1 AND (slack_id = $2 OR (slack_id IS NULL AND principal_id = $2)) LIMIT 1`,+ [orgId, slackId],+ );+ return rows.length ? memberRow(rows[0]!) : null;+ },+async resolve(query) {const bySlackId = await q(`SELECT ${MEMBER_COLS} FROM directory_members WHERE org_id = $1 AND slack_id = $2 LIMIT 1`,diff --git a/src/loops/inbox-loop.ts b/src/loops/inbox-loop.tsindex 374df55f0..7006d25df 100644--- a/src/loops/inbox-loop.ts+++ b/src/loops/inbox-loop.ts@@ -7,7 +7,7 @@ const INBOX_LOOP_NAME = "Inbox";const INBOX_LOOP_SURFACE = "inbox";-export const INBOX_SYNC_TASK_VERSION = 5;+export const INBOX_SYNC_TASK_VERSION = 6;export const INBOX_SYNC_DEFAULT_EVERY_MS = 15 * 60 * 1000;@@ -25,7 +25,7 @@ export function renderInboxSyncTask(loopId: string): string {- Closed-loop detection: BEFORE scanning for new items, re-read the exact source conversation of EVERY unresolved item (held, pending, processed, or failed), regardless of lastScanAt, age, read/unread state, or whether Gmail still labels it INBOX. The intake watermark is NOT a reconciliation watermark. If the LATEST message is FROM THE USER THEMSELVES — their own Slack userId on Slack, or their own email address in the From line on Gmail — they already replied outside QM, so POST $AGENT_API_URL/v1/loops/${loopId}/items/<itemId>/action with {"kind":"replied","args":{"text":"<their message, <=200 chars>","sourceAt":<reply timestamp in ms>}} to close it. Ignore Gmail drafts and recognize SENT messages, including send-as aliases. Only close when the reply is newer than the waiting message and there is no later inbound ask. If a source read fails or is incomplete, retain the item and retry later; do not treat it as resolved. This applies to both Gmail and Slack items. Do NOT reopen or redraft an item the user has already answered.2. Keep a lastScanAt watermark in a state file on your workspace (e.g. ~/workspace/inbox-sync/STATE.md); scan each connected source since that watermark (fall back to ~3 days on first run), and advance the watermark only after a successful pass, so outages and missed fires backfill instead of leaving silent gaps. Skip a source whose app is not connected. Judge "waiting on a reply" like a good chief of staff, with a deliberate asymmetry: (a) NEEDS REPLY: direct questions, requests, intros, and personal messages that expect acknowledgment; when in any doubt, this bucket. (b) PROBABLY RESOLVED: the transcript reads closed (a thanks, a "sounds good", a thread someone else already answered) but a reasonable person might still send a word; post the item anyway with "probablyResolved": true in the item body and a draft included; the UI shows these in a muted section. NEVER silently drop a human conversation you judged resolved; demote it instead. (c) SKIP entirely: only unmistakable machine noise (newsletters, receipts, calendar notices, bot chatter). Human words never skip; the lowest they go is probablyResolved.- Gmail (use the google-workspace skill): INBOX threads where the LAST message is inbound and the user is in To or Cc. sourceKey = the Gmail threadId. Record gmail metadata: threadId, messageId, the RFC-2822 Message-ID header (rfcMessageId), subject, and the reply recipients (to = reply-all sender+others minus the user; cc as appropriate).- - Slack (use your Slack access as the user): unanswered DMs, @mentions, and thread replies addressed to the user. ONE ITEM PER CONVERSATION, never per message: for unthreaded DMs and group DMs sourceKey = the channelId alone (two people posting in the same group DM is ONE item, refreshed with the latest state and a single draft answering everything outstanding); for all threaded asks sourceKey = channelId:threadTs (channelId:ts of a top-level message anchoring its own thread). Record slack metadata: channelId, channelLabel ("#channel" or "DM with <name>"), ts (the LATEST waiting message), isDirectMessage from Slack conversations.info is_im/is_mpim (NEVER infer group DMs from C/G ID prefixes), and threadTs for every threaded ask. For a top-level CHANNEL mention, threadTs is the original mentioned message ts, even before anyone replies. Preserve that anchor forever: unrelated channel chatter must not replace, refresh, or resolve this item. Read conversations.replies for that root, not the channel tail. For mentions inside a thread, include the root and only that thread. Relevant messages immediately before/after a channel mention may be included in context with nearby:true; never label these as thread replies, and never include unrelated neighboring messages.+ - Slack (use your Slack access as the user): unanswered DMs, @mentions, and thread replies addressed to the user. ONE ITEM PER CONVERSATION, never per message: for unthreaded DMs and group DMs sourceKey = the channelId alone (two people posting in the same group DM is ONE item, refreshed with the latest state and a single draft answering everything outstanding); for all threaded asks sourceKey = channelId:threadTs (channelId:ts of a top-level message anchoring its own thread). Record slack metadata: channelId, channelLabel ("#channel" or "DM with <name>"), ts (the LATEST waiting message), userId (the Slack user id of that message's sender), isDirectMessage from Slack conversations.info is_im/is_mpim (NEVER infer group DMs from C/G ID prefixes), and threadTs for every threaded ask. For a top-level CHANNEL mention, threadTs is the original mentioned message ts, even before anyone replies. Preserve that anchor forever: unrelated channel chatter must not replace, refresh, or resolve this item. Read conversations.replies for that root, not the channel tail. For mentions inside a thread, include the root and only that thread. Relevant messages immediately before/after a channel mention may be included in context with nearby:true; never label these as thread replies, and never include unrelated neighboring messages.3. For each new or refreshed item, investigate before drafting: read the whole thread, and check whatever context makes the reply substantive (calendar for scheduling asks, earlier email/Slack history for open questions). Draft the reply in the user's own voice — for email follow the email-draft-in-voice skill (build the voice profile first if it is missing); for Slack match how the user actually writes in Slack (check their recent messages: register, length, punctuation). Punctuation hard rule: never use em dashes or en dashes in a draft; use a comma, period, or "..." instead, and re-read every draft before posting to strip any that slipped in.4. POST $AGENT_API_URL/v1/loops/${loopId}/items with {"items": [...]}. Each item: source ("gmail"|"slack"), sourceKey, title (subject or channel label), from (display name), fromDetail (address or @handle), snippet (the full text of the waiting message, never shortened or ellipsized), context (up to 6 prior thread messages as {author, at, text}), receivedAt (ms epoch of the waiting message), externalUrl (deep link to the original in Gmail/Slack), draft ({to, cc, subject, body} for gmail — body plain text; {body} for slack), and the gmail/slack metadata block from step 2. IMAGES: when a thread message carries image attachments, include an "images" array of their https URLs (Slack: url_private; up to 4) on the matching context entry, and on the item itself for the waiting message — the UI proxies and renders them inline as the user's own eyes would see them in Slack/Gmail.5. Found nothing new and changed nothing? Finish silently. Only raise your voice on a real fault (a connector that errors repeatedly) — and then only briefly.`;diff --git a/src/loops/inbox-source-refresh.ts b/src/loops/inbox-source-refresh.tsindex b46da9c5e..8210c9d01 100644--- a/src/loops/inbox-source-refresh.ts+++ b/src/loops/inbox-source-refresh.ts@@ -8,10 +8,12 @@ import type { LoopItemLedger } from "./item-ledger.ts";import { isResolved } from "./ledger-view.ts";import { isObj, tokenFor, type ConnectorTokenSource } from "./sources/adapter.ts";import { normalizeSlackApiUrl } from "../slack/config.ts";+import type { DirectoryStore } from "../directory/directory-store.ts";interface RefreshDeps {items: LoopItemLedger;tokens: ConnectorTokenSource;+ directory: Pick<DirectoryStore, "getBySlackId">;featureFlags: Pick<FeatureFlagStore, "enabled">;errors?: ErrorLog;fetchImpl?: typeof fetch;@@ -82,18 +84,13 @@ export function createInboxSourceRefresh(deps: RefreshDeps): InboxSourceRefreshreturn body;}- async function slackInfo(- owner: string,- path: string,- token: string,- deadline?: number,- ): Promise<Record<string, unknown>> {+ async function slackInfo(owner: string, path: string, token: string): Promise<Record<string, unknown>> {const key = `${owner}:${path}`;const cached = info.get(key);if (cached) return cached;const pending = infoRunning.get(key);if (pending) return pending;- const task = get(owner, "slack", path, token, deadline)+ const task = get(owner, "slack", path, token).then((value) => {info.set(key, value);return value;@@ -120,13 +117,14 @@ export function createInboxSourceRefresh(deps: RefreshDeps): InboxSourceRefreshfunction messageParticipant(message: Record<string, unknown>): SlackParticipant | undefined {const bot = isObj(message.bot_profile) ? message.bot_profile : {};+ const profile = isObj(message.user_profile) ? message.user_profile : {};let id = typeof message.user === "string" ? message.user : undefined;if (!id && typeof message.bot_id === "string") id = `bot:${message.bot_id}`;if (!id) return;- const avatarUrl = isObj(bot.icons) ? imageUrl(bot.icons) : undefined;+ const avatarUrl = imageUrl(isObj(bot.icons) ? bot.icons : profile);return {id,- name: String(bot.name || message.username || id),+ name: String(bot.name || profile.display_name || profile.real_name || message.username || id),...(avatarUrl ? { avatarUrl } : {}),};}@@ -134,9 +132,7 @@ export function createInboxSourceRefresh(deps: RefreshDeps): InboxSourceRefreshasync function participants(owner: string,ids: string[],- token: string,previous: SlackParticipant[],- deadline?: number,): Promise<{ people: SlackParticipant[]; refreshAt: number }> {let complete = true;const people = await Promise.all(@@ -144,16 +140,10 @@ export function createInboxSourceRefresh(deps: RefreshDeps): InboxSourceRefreshconst saved = previous.find((person) => person.id === id) ?? { id, name: id };if (id.startsWith("bot:")) return saved;try {- const result = await slackInfo(owner, `users.info?user=${encodeURIComponent(id)}`, token, deadline);- if (!isObj(result.user)) throw new Error("Slack profile is unavailable.");- const user = result.user;- const profile = isObj(user.profile) ? user.profile : {};- const avatarUrl = imageUrl(profile) ?? saved.avatarUrl;- return {- id,- name: String(profile.display_name || profile.real_name || user.real_name || user.name || saved.name),- ...(avatarUrl ? { avatarUrl } : {}),- };+ const member = await deps.directory.getBySlackId(id);+ if (!member) return saved;+ const avatarUrl = member.avatarUrl?.startsWith("https://") ? member.avatarUrl : saved.avatarUrl;+ return { id, name: member.displayName || saved.name, ...(avatarUrl ? { avatarUrl } : {}) };} catch (error) {recordFailure(owner, `Slack profile ${id}`, error);complete = false;@@ -170,43 +160,12 @@ export function createInboxSourceRefresh(deps: RefreshDeps): InboxSourceRefreshif (typeof payload.slackAvatarsRefreshAt === "number" && now() < payload.slackAvatarsRefreshAt) return;const meta = isObj(payload.slack) ? payload.slack : {};if (typeof meta.channelId !== "string" || typeof meta.ts !== "string") return;- const token = await tokenFor(deps.tokens, "slack.com", owner);- if (!token) return;- const deadline = now() + 3000;const previous = savedParticipants(payload);- let senderId = typeof meta.userId === "string" ? meta.userId : previous[0]?.id;- if (senderId?.startsWith("bot:")) senderId = undefined;- if (!senderId) {- const params = new URLSearchParams({- channel: meta.channelId,- oldest: meta.ts,- latest: meta.ts,- inclusive: "true",- limit: "1",- });- const method = typeof meta.threadTs === "string" ? "conversations.replies" : "conversations.history";- if (typeof meta.threadTs === "string") params.set("ts", meta.threadTs);- const body = await get(owner, "slack", `${method}?${params}`, token, deadline);- const message = Array.isArray(body.messages)- ? body.messages.filter(isObj).find((m) => m.ts === meta.ts)- : undefined;- const sender = message && messageParticipant(message);- if (!sender) return;- senderId = sender.id;- previous.unshift({- ...sender,- ...(sender.name === sender.id && typeof payload.from === "string" ? { name: payload.from } : {}),- });- }+ const senderId = typeof meta.userId === "string" ? meta.userId : undefined;+ if (!senderId || senderId.startsWith("bot:")) return;if (!previous.some((person) => person.id === senderId))previous.unshift({ id: senderId, name: typeof payload.from === "string" ? payload.from : senderId });- const profiles = await participants(- owner,- [senderId, ...previous.map((person) => person.id)],- token,- previous,- deadline,- );+ const profiles = await participants(owner, [senderId, ...previous.map((person) => person.id)], previous);await deps.items.annotate(item.id,{@@ -267,7 +226,7 @@ export function createInboxSourceRefresh(deps: RefreshDeps): InboxSourceRefreshconst saved = savedParticipants(payload);const sender =(waiting && messageParticipant(waiting)) ??- (typeof meta.userId === "string" ? { id: meta.userId, name: meta.userId } : saved[0]);+ (typeof meta.userId === "string" ? { id: meta.userId, name: meta.userId } : undefined);const previous = new Map(saved.map((person) => [person.id, person]));for (const message of messages) {const person = messageParticipant(message);@@ -289,7 +248,6 @@ export function createInboxSourceRefresh(deps: RefreshDeps): InboxSourceRefreshreturn person ? [person.id] : [];}),],- token,[...previous.values()],);const people = new Map([...previous.values(), ...profiles.people].map((person) => [person.id, person]));diff --git a/src/loops/sources/slack.ts b/src/loops/sources/slack.tsindex 9aa9e32a0..14ddffa35 100644--- a/src/loops/sources/slack.ts+++ b/src/loops/sources/slack.ts@@ -32,6 +32,7 @@ interface SlackMeta {ts: string;threadTs?: string;isDirectMessage?: boolean;+ userId?: string;}function parseSlackMeta(v: unknown): SlackMeta | undefined {@@ -41,11 +42,13 @@ function parseSlackMeta(v: unknown): SlackMeta | undefined {if (!channelId || !ts) return undefined;const channelLabel = clipOpt(v.channelLabel, 120);const threadTs = clipOpt(v.threadTs, 40);+ const userId = clipOpt(v.userId, 40);return {channelId,ts,...(channelLabel ? { channelLabel } : {}),...(threadTs ? { threadTs } : {}),+ ...(userId ? { userId } : {}),...(typeof v.isDirectMessage === "boolean" ? { isDirectMessage: v.isDirectMessage } : {}),};}diff --git a/src/wiring.ts b/src/wiring.tsindex 41d251ad4..332411f47 100644--- a/src/wiring.ts+++ b/src/wiring.ts@@ -3128,6 +3128,7 @@ export function serverDeps(items: built.loops.items,errors: built.errors,tokens: built.keychain,+ directory: built.directory,...(config.slack?.apiUrl ? { slackApiUrl: config.slack.apiUrl } : {}),}),}diff --git a/test/directory-store.test.ts b/test/directory-store.test.tsindex d37797bc9..b305978e8 100644--- a/test/directory-store.test.ts+++ b/test/directory-store.test.ts@@ -122,6 +122,9 @@ describe("member slackId (the real <@…> mention id for an email principal)", (assert.equal((await d.get("[email protected]"))?.avatarUrl, "https://avatars.slack-edge.com/eve.png");assert.equal((await d.get("U5"))?.slackId, undefined);assert.equal((await d.list()).find((m) => m.principalId === "[email protected]")?.slackId, "U9");+ assert.equal((await d.getBySlackId("U9"))?.principalId, "[email protected]");+ assert.equal((await d.getBySlackId("U5"))?.principalId, "U5");+ assert.equal(await d.getBySlackId("Eve"), null);const r = await d.resolve("Eve");assert.equal(r.kind === "one" && r.member.slackId, "U9");});diff --git a/test/inbox-source-refresh.test.ts b/test/inbox-source-refresh.test.tsindex 3935fe677..6ef75ae61 100644--- a/test/inbox-source-refresh.test.ts+++ b/test/inbox-source-refresh.test.ts@@ -20,6 +20,20 @@ async function fixture(source = "gmail", meta: Record<string, unknown> = { threaconst featureFlags = { enabled: async () => true };const tokens = { connectorAccessToken: async () => "synthetic-token" };const json = (body: unknown) => Response.json(body);+const ALEX = "https://avatars.slack-edge.com/alex.png";+function directoryOf(+ people: Record<string, { displayName: string; avatarUrl?: string }>,+ onLookup?: (id: string) => unknown,+) {+ return {+ getBySlackId: async (id: string) => {+ await onLookup?.(id);+ const person = people[id];+ return person ? { principalId: `${id}@x.com`, slackId: id, type: "internal" as const, ...person } : null;+ },+ };+}+const directory = directoryOf({ U1: { displayName: "Alex", avatarUrl: ALEX }, U2: { displayName: "Taylor" } });test("Gmail reply sent outside QM closes the card, ignores drafts and recognizes send-as aliases", async () => {const { items, item } = await fixture();@@ -28,6 +42,7 @@ test("Gmail reply sent outside QM closes the card, ignores drafts and recognizesfeatureFlags,items,tokens,+ directory,fetchImpl: async (url) => {reads++;assert.match(String(url), /threads\/t1\?format=metadata$/);@@ -65,6 +80,7 @@ test("an old sent message or a newer inbound message does not close a Gmail itemfeatureFlags,items,tokens,+ directory,fetchImpl: async () => json({ messages }),})("owner", [item]);assert.equal((await items.get(item.id))!.status, "ready");@@ -78,6 +94,7 @@ test("provider failure or missing connection preserves the item with an explicitfeatureFlags,items,tokens: { connectorAccessToken: async () => (connected ? "test" : null) },+ directory,fetchImpl: async () => new Response("unavailable", { status: 503 }),})("owner", [item]);const after = (await items.get(item.id))!;@@ -93,6 +110,7 @@ test("a new inbound message during a provider read wins over the older own replyfeatureFlags,items,tokens,+ directory,fetchImpl: async () => {await items.ingest([{@@ -148,6 +166,7 @@ test("top-level/private-channel mentions fetch just their root and replies, nevefeatureFlags,items,tokens,+ directory,fetchImpl: slackFetch(calls),})("owner", [item]);const after = (await items.get(item.id))!;@@ -169,6 +188,7 @@ test("Slack detects group DMs by conversation metadata, including C-prefixed IDsfeatureFlags,items,tokens,+ directory,fetchImpl: slackFetch(calls, { direct: true, own: true }),})("owner", [item]);assert.ok(calls.some((p) => p.includes("conversations.history")));@@ -181,6 +201,7 @@ test("a partial Slack thread is displayed as partial but cannot resolve an item"featureFlags,items,tokens,+ directory,fetchImpl: slackFetch([], { partial: true, own: true }),})("owner", [item]);const after = (await items.get(item.id))!;@@ -195,6 +216,7 @@ test("rate limiting is respected across different Slack items and never triggersfeatureFlags,items,tokens,+ directory,fetchImpl: async (url) => {if (String(url).includes("conversations.info")) return json({ ok: true, channel: {} });reads++;@@ -215,6 +237,7 @@ test("slow Gmail reads have a total batch budget and later cards are visited onfeatureFlags,items,tokens,+ directory,now: () => clock,fetchImpl: async () => {reads++;@@ -231,150 +254,48 @@ test("slow Gmail reads have a total batch budget and later cards are visited onassert.equal(reads, 12);});-test("Slack avatars are durable, shared across concurrent cards, and refresh without reading conversations", async () => {+test("Slack avatars come from the org directory without the owner's Slack login or conversation reads", async () => {const { items, item } = await fixture("slack", { channelId: "D1", ts: "1.0", userId: "U1" });- await items.ingest([- {- loopId: "inbox",- dedupeKey: "second",- source: "slack",- sourceAt: 2000,- sourcePayload: { slack: { channelId: "D2", ts: "2.0", userId: "U1" } },- },- ]);- let reads = 0;- const fetchImpl: typeof fetch = async (url) => {- reads++;- assert.match(String(url), /users.info\?user=U1$/);- return json({- ok: true,- user: { profile: { display_name: "Alex", image_48: "https://avatars.slack-edge.com/alex.png" } },- });- };- const refresh = createInboxSourceRefresh({ featureFlags, items, tokens, fetchImpl });- await refresh("owner", await items.byLoop("inbox"), "avatars");- assert.equal(reads, 1);+ const looked: string[] = [];+ const refresh = createInboxSourceRefresh({+ featureFlags,+ items,+ tokens: { connectorAccessToken: async () => null },+ directory: directoryOf({ U1: { displayName: "Alex", avatarUrl: ALEX } }, (id) => looked.push(id)),+ fetchImpl: async () => assert.fail("no Slack reads"),+ });+ await refresh("owner", [item], "avatars");const after = (await items.get(item.id))!;- const people = [{ id: "U1", name: "Alex", avatarUrl: "https://avatars.slack-edge.com/alex.png" }];- assert.deepEqual(after.sourcePayload?.participants, people);+ assert.deepEqual(after.sourcePayload?.participants, [{ id: "U1", name: "Alex", avatarUrl: ALEX }]);assert.equal(after.inboxPreview?.participants, undefined);- assert.equal(after.status, item.status);assert.deepEqual(after.proposal, item.proposal);assert.deepEqual(after.sourcePayload?.context, item.sourcePayload?.context);- await createInboxSourceRefresh({ featureFlags, items, tokens, fetchImpl })(- "owner",- await items.byLoop("inbox"),- "avatars",- );- assert.equal(reads, 1);- await refresh("another-owner", [item], "avatars");- assert.equal(reads, 2);+ await refresh("owner", [after], "avatars");+ assert.deepEqual(looked, ["U1"]);});-test("legacy Slack avatar lookup uses only the exact waiting message, including threaded replies", async () => {- for (const threadTs of [undefined, "0.5"]) {- const { items, item } = await fixture("slack", { channelId: "C1", ts: "1.0", ...(threadTs ? { threadTs } : {}) });- const calls: string[] = [];- await createInboxSourceRefresh({- featureFlags,- items,- tokens,- fetchImpl: async (url) => {- const u = new URL(String(url));- calls.push(u.pathname);- if (u.pathname.endsWith("users.info")) {- assert.equal(u.searchParams.get("user"), "U1");- return json({- ok: true,- user: { profile: { display_name: "Alex", image_72: "https://avatars.slack-edge.com/alex.png" } },- });- }- assert.equal(u.searchParams.get("oldest"), "1.0");- assert.equal(u.searchParams.get("latest"), "1.0");- assert.equal(u.searchParams.get("inclusive"), "true");- assert.equal(u.searchParams.get("limit"), "1");- assert.equal(u.searchParams.get("ts"), threadTs ?? null);- return json({- ok: true,- messages: [- { ts: "0.5", user: "U_ROOT" },- { ts: "1.0", user: "U1" },- ],- });- },- })("owner", [item], "avatars");- assert.match(calls[0]!, threadTs ? /conversations.replies$/ : /conversations.history$/);- assert.equal(calls.length, 2);- assert.deepEqual((await items.get(item.id))!.sourcePayload!.slack, item.sourcePayload!.slack);- assert.equal(- ((await items.get(item.id))!.sourcePayload!.participants as Array<{ avatarUrl: string }>)[0]!.avatarUrl,- "https://avatars.slack-edge.com/alex.png",- );- }-});--test("avatar lookup failure and unavailable messages preserve Inbox content and retry limits", async () => {- for (const response of [- json({ ok: true, messages: [{ ts: "9.0", user: "WRONG" }] }),- new Response("limited", { status: 429 }),- ]) {- const { items, item } = await fixture("slack", { channelId: "C1", ts: "1.0" });- let reads = 0;- const refresh = createInboxSourceRefresh({- featureFlags,- items,- tokens,- fetchImpl: async () => {- reads++;- return response.clone();- },- });- await refresh("owner", [item], "avatars");- await refresh("owner", [item], "avatars");- assert.equal(reads, 1);- assert.deepEqual(await items.get(item.id), item);- }-});--test("missing or unsafe profile photos retain initials without repeating provider reads", async () => {- for (const image_48 of [undefined, "http://example.com/photo.png", "javascript:alert(1)"]) {+test("missing or unsafe directory photos retain initials", async () => {+ for (const avatarUrl of [undefined, "http://example.com/photo.png", "javascript:alert(1)"]) {const { items, item } = await fixture("slack", { channelId: "D1", ts: "1.0", userId: "U1" });await createInboxSourceRefresh({featureFlags,items,tokens,- fetchImpl: async () => json({ ok: true, user: { profile: { display_name: "Alex", image_48 } } }),+ directory: directoryOf({ U1: { displayName: "Alex", ...(avatarUrl ? { avatarUrl } : {}) } }),})("owner", [item], "avatars");assert.deepEqual((await items.get(item.id))!.sourcePayload!.participants, [{ id: "U1", name: "Alex" }]);}});-test("avatar-only refresh does not suppress full Slack context refresh or reuse profiles across owners", async () => {+test("avatar-only refresh does not suppress full Slack context refresh", async () => {const { items, item } = await fixture("slack", { channelId: "C1", ts: "1.0", userId: "U1" });- const calls: string[] = [];- const sourceFetch = slackFetch(calls);- const refresh = createInboxSourceRefresh({- featureFlags,- items,- tokens,- fetchImpl: async (url, init) => {- const response = await sourceFetch(url, init);- if (!String(url).includes("users.info")) return response;- const body = (await response.json()) as { user: { profile: { image_48?: string } } };- body.user.profile.image_48 = "https://avatars.slack-edge.com/alex.png";- return json(body);- },- });+ const refresh = createInboxSourceRefresh({ featureFlags, items, tokens, directory, fetchImpl: slackFetch([]) });await refresh("owner", [item], "avatars");await refresh("owner", [(await items.get(item.id))!]);const after = (await items.get(item.id))!;assert.equal(after.sourcePayload?.sourceContextFetched, true);assert.equal((after.sourcePayload!.context as Array<{ authorId: string }>)[0]!.authorId, "U1");- assert.equal(- (after.sourcePayload!.context as Array<{ avatarUrl: string }>)[0]!.avatarUrl,- "https://avatars.slack-edge.com/alex.png",- );- assert.equal(calls.filter((p) => p.includes("users.info")).length, 1);+ assert.equal((after.sourcePayload!.context as Array<{ avatarUrl: string }>)[0]!.avatarUrl, ALEX);assert.equal(after.inboxPreview?.participants, undefined);});@@ -384,8 +305,8 @@ test("a newer message during an avatar lookup cannot acquire the previous senderfeatureFlags,items,tokens,- fetchImpl: async () => {- await items.ingest([+ directory: directoryOf({ U1: { displayName: "Alex", avatarUrl: ALEX } }, () =>+ items.ingest([{loopId: "inbox",dedupeKey: "ask",@@ -393,9 +314,8 @@ test("a newer message during an avatar lookup cannot acquire the previous sendersourceAt: 2000,sourcePayload: { slack: { channelId: "D1", ts: "2.0", userId: "U2" } },},- ]);- return json({ ok: true, user: { profile: { image_48: "https://avatars.slack-edge.com/old.png" } } });- },+ ]),+ ),})("owner", [item], "avatars");assert.equal((await items.get(item.id))!.sourcePayload?.participants, undefined);});@@ -406,6 +326,7 @@ test("concurrent list and detail refreshes preserve the authoritative Slack threfeatureFlags,items,tokens,+ directory,fetchImpl: slackFetch([], { direct: true }),});await Promise.all([refresh("owner", [item]), refresh("owner", [item], "avatars")]);@@ -418,55 +339,43 @@ test("partial profile failures keep saved photos and names while saving successfconst { items, item } = await fixture("slack", { channelId: "D1", ts: "1.0", userId: "U1" });const saved = { id: "U2", name: "Taylor", avatarUrl: "https://avatars.slack-edge.com/taylor.png" };await items.annotate(item.id, { participants: [{ id: "U1", name: "Alex" }, saved] });- let clock = 1000;- const fetchImpl: typeof fetch = async (url) =>- String(url).includes("user=U2")- ? new Response("unavailable", { status: 503 })- : json({- ok: true,- user: { profile: { display_name: "Alex", image_512: "https://avatars.slack-edge.com/alex.png" } },- });await createInboxSourceRefresh({featureFlags,items,tokens,- fetchImpl,- now: () => clock,+ directory: directoryOf({ U1: { displayName: "Alex", avatarUrl: ALEX } }, (id) => {+ if (id === "U2") throw new Error("directory unavailable");+ }),+ now: () => 1000,})("owner", [(await items.get(item.id))!], "avatars");const after = (await items.get(item.id))!;- assert.deepEqual(after.sourcePayload!.participants, [- { id: "U1", name: "Alex", avatarUrl: "https://avatars.slack-edge.com/alex.png" },- saved,- ]);+ assert.deepEqual(after.sourcePayload!.participants, [{ id: "U1", name: "Alex", avatarUrl: ALEX }, saved]);assert.equal(after.sourcePayload!.slackAvatarsRefreshAt, 61_000);assert.deepEqual(after.proposal, item.proposal);- clock = 62_000;- let reads = 0;+ const looked: string[] = [];await createInboxSourceRefresh({featureFlags,items,tokens,- now: () => clock,- fetchImpl: async (url) => {- reads++;- return fetchImpl(url);- },+ directory: directoryOf({ U2: { displayName: "Taylor" } }, (id) => looked.push(id)),+ now: () => 62_000,})("owner", [after], "avatars");- assert.equal(reads, 2);+ assert.deepEqual(looked, ["U1", "U2"]);});test("opening a thread retains cached photos and author names when profile reads fail", async () => {const { items, item } = await fixture("slack", { channelId: "C1", ts: "1.0", userId: "U1" });- const saved = { id: "U1", name: "Alex", avatarUrl: "https://avatars.slack-edge.com/alex.png" };+ const saved = { id: "U1", name: "Alex", avatarUrl: ALEX };await items.annotate(item.id, { participants: [saved], slackAvatarsRefreshAt: 99_000_000 });- const sourceFetch = slackFetch([]);await createInboxSourceRefresh({featureFlags,items,tokens,+ directory: directoryOf({}, () => {+ throw new Error("directory unavailable");+ }),now: () => 1000,- fetchImpl: async (url, init) =>- String(url).includes("users.info") ? new Response("unavailable", { status: 503 }) : sourceFetch(url, init),+ fetchImpl: slackFetch([]),})("owner", [(await items.get(item.id))!]);const after = (await items.get(item.id))!;assert.deepEqual(after.sourcePayload!.participants, [saved]);@@ -481,22 +390,21 @@ test("opening a thread retains cached photos and author names when profile readstest("thread profile limits prioritize the waiting sender and latest visible authors", async () => {const { items, item } = await fixture("slack", { channelId: "C1", ts: "1.0", userId: "U1" });const lookedUp: string[] = [];+ const people = Object.fromEntries(+ Array.from({ length: 12 }, (_, i) => [+ `U${i + 1}`,+ { displayName: `U${i + 1}`, avatarUrl: `https://avatars.slack-edge.com/U${i + 1}.png` },+ ]),+ );await createInboxSourceRefresh({featureFlags,items,tokens,+ directory: directoryOf(people, (id) => lookedUp.push(id)),fetchImpl: async (url) => {const u = new URL(String(url));if (u.pathname.endsWith("conversations.info")) return json({ ok: true, channel: {} });if (u.pathname.endsWith("auth.test")) return json({ ok: true, user_id: "OWNER" });- if (u.pathname.endsWith("users.info")) {- const user = u.searchParams.get("user")!;- lookedUp.push(user);- return json({- ok: true,- user: { name: user, profile: { image_24: `https://avatars.slack-edge.com/${user}.png` } },- });- }return json({ok: true,messages: Array.from({ length: 12 }, (_, i) => ({@@ -515,79 +423,39 @@ test("thread profile limits prioritize the waiting sender and latest visible autassert.ok(latest.every((message) => message.avatarUrl));});-test("legacy sender caching does not overwrite Slack metadata or reread its message", async () => {- const { items, item } = await fixture("slack", { channelId: "D1", ts: "1.0", isDirectMessage: true });- const calls: string[] = [];- let clock = 1000;- const fetchImpl: typeof fetch = async (url) => {- const path = new URL(String(url)).pathname;- calls.push(path);- if (path.endsWith("users.info"))- return json({- ok: true,- user: { name: "Alex", profile: { image_original: "https://avatars.slack-edge.com/alex.png" } },- });- return json({ ok: true, messages: [{ ts: "1.0", user: "U1" }] });- };- await createInboxSourceRefresh({- featureFlags,- items,- tokens,- fetchImpl,- now: () => clock,- })("owner", [item], "avatars");- let after = (await items.get(item.id))!;- assert.deepEqual(after.sourcePayload!.slack, { channelId: "D1", ts: "1.0", isDirectMessage: true });- clock += 86_400_001;+test("bot and external-user messages use profiles already returned by Slack", async () => {+ const { items, item } = await fixture("slack", { channelId: "C1", ts: "1.0" });await createInboxSourceRefresh({featureFlags,items,tokens,- fetchImpl,- now: () => clock,- })("owner", [after], "avatars");- after = (await items.get(item.id))!;- assert.equal(calls.filter((path) => path.endsWith("conversations.history")).length, 1);- assert.equal(calls.filter((path) => path.endsWith("users.info")).length, 2);- assert.equal((after.sourcePayload!.participants as Array<{ id: string }>)[0]!.id, "U1");-});--test("bot messages use profile icons already returned by Slack without extra profile APIs", async () => {- for (const mode of [undefined, "avatars"] as const) {- const { items, item } = await fixture("slack", { channelId: "C1", ts: "1.0" });- await createInboxSourceRefresh({- featureFlags,- items,- tokens,- fetchImpl: async (url) => {- const path = new URL(String(url)).pathname;- assert.ok(!path.endsWith("users.info") && !path.endsWith("bots.info"));- if (path.endsWith("conversations.info")) return json({ ok: true, channel: {} });- if (path.endsWith("auth.test")) return json({ ok: true, user_id: "OWNER" });- return json({- ok: true,- messages: [- {- ts: "1.0",- bot_id: "B1",- bot_profile: { name: "Build bot", icons: { image_48: "https://avatars.slack-edge.com/build.png" } },- text: "Build finished",- },- ],- });- },- })("owner", [item], mode);- const after = (await items.get(item.id))!;- assert.deepEqual(after.sourcePayload!.participants, [- { id: "bot:B1", name: "Build bot", avatarUrl: "https://avatars.slack-edge.com/build.png" },- ]);- if (mode === undefined) {- const message = (after.sourcePayload!.context as Array<Record<string, unknown>>)[0]!;- assert.equal(message.author, "Build bot");- assert.equal(message.authorId, "bot:B1");- assert.equal(message.avatarUrl, "https://avatars.slack-edge.com/build.png");- }- }+ directory,+ fetchImpl: async (url) => {+ const path = new URL(String(url)).pathname;+ assert.ok(!path.endsWith("users.info") && !path.endsWith("bots.info"));+ if (path.endsWith("conversations.info")) return json({ ok: true, channel: {} });+ if (path.endsWith("auth.test")) return json({ ok: true, user_id: "OWNER" });+ return json({+ ok: true,+ messages: [+ {+ ts: "1.0",+ bot_id: "B1",+ bot_profile: { name: "Build bot", icons: { image_48: "https://avatars.slack-edge.com/build.png" } },+ text: "Build finished",+ },+ ],+ });+ },+ })("owner", [item]);+ const after = (await items.get(item.id))!;+ assert.deepEqual(after.sourcePayload!.participants, [+ { id: "bot:B1", name: "Build bot", avatarUrl: "https://avatars.slack-edge.com/build.png" },+ ]);+ const message = (after.sourcePayload!.context as Array<Record<string, unknown>>)[0]!;+ assert.equal(message.author, "Build bot");+ assert.equal(message.authorId, "bot:B1");+ assert.equal(message.avatarUrl, "https://avatars.slack-edge.com/build.png");});test("a partial source page cannot replace the waiting sender with an unrelated author", async () => {@@ -602,37 +470,13 @@ test("a partial source page cannot replace the waiting sender with an unrelatedif (!String(url).includes("conversations.history")) return response;return json({ ok: true, messages: [{ ts: "2.0", user: "U_OTHER", text: "Newer message" }] });};- await createInboxSourceRefresh({ featureFlags, items, tokens, fetchImpl })("owner", [(await items.get(item.id))!]);+ await createInboxSourceRefresh({ featureFlags, items, tokens, directory, fetchImpl })("owner", [+ (await items.get(item.id))!,+ ]);assert.equal(((await items.get(item.id))!.sourcePayload!.participants as Array<{ id: string }>)[0]!.id, "U1");}});-test("legacy sender and profile reads share one request deadline", { timeout: 1000 }, async () => {- const { items, item } = await fixture("slack", { channelId: "D1", ts: "1.0" });- let clock = 0;- let aborted = false;- await createInboxSourceRefresh({- featureFlags,- items,- tokens,- now: () => clock,- fetchImpl: async (url, init) => {- if (String(url).includes("conversations.history")) {- clock = 2990;- return json({ ok: true, messages: [{ ts: "1.0", user: "U1" }] });- }- return new Promise<Response>((_resolve, reject) => {- init!.signal!.addEventListener("abort", () => {- aborted = true;- reject(init!.signal!.reason);- });- });- },- })("owner", [item], "avatars");- assert.equal(aborted, true);- assert.equal((await items.get(item.id))!.status, item.status);-});-test("cosmetic avatar refresh never waits for an in-flight full conversation refresh", async () => {const { items, item } = await fixture("slack", { channelId: "C1", ts: "1.0", userId: "U1" });let begin!: () => void;@@ -648,6 +492,7 @@ test("cosmetic avatar refresh never waits for an in-flight full conversation reffeatureFlags,items,tokens,+ directory,fetchImpl: async (url, init) => {if (String(url).includes("conversations.info")) {begin();@@ -685,14 +530,13 @@ test("a second core's full refresh wins over a stale cosmetic profile refresh",featureFlags,items,tokens,- fetchImpl: async () => {- begin();- await blocked;- return json({- ok: true,- user: { name: "Alex", profile: { image_48: "https://avatars.slack-edge.com/stale.png" } },- });- },+ directory: directoryOf(+ { U1: { displayName: "Stale", avatarUrl: "https://avatars.slack-edge.com/stale.png" } },+ () => {+ begin();+ return blocked;+ },+ ),})("owner", [item], "avatars");await started;const sourceFetch = slackFetch([], { own: true });@@ -701,6 +545,7 @@ test("a second core's full refresh wins over a stale cosmetic profile refresh",featureFlags,items,tokens,+ directory,fetchImpl: async (url, init) => {if (String(url).includes("auth.test")) return json({ ok: true, user_id: "OWNER" });return sourceFetch(url, init);@@ -712,7 +557,7 @@ test("a second core's full refresh wins over a stale cosmetic profile refresh",}const after = (await items.get(item.id))!;assert.deepEqual(after.sourcePayload!.participants, [- { id: "U1", name: "Alex" },+ { id: "U1", name: "Alex", avatarUrl: ALEX },{ id: "U2", name: "Taylor" },]);assert.equal(after.sourcePayload!.sourceContextFetched, true);@@ -721,22 +566,20 @@ test("a second core's full refresh wins over a stale cosmetic profile refresh",test("unverified waiting senders never inherit another context author's avatar", async () => {const { items, item } = await fixture("slack", { channelId: "D1", ts: "1.0" });- const source = createInboxSourceRefresh({+ const people = directoryOf({+ U_OTHER: { displayName: "Someone Else", avatarUrl: "https://avatars.slack-edge.com/other.png" },+ });+ await createInboxSourceRefresh({featureFlags,items,tokens,+ directory: people,fetchImpl: async (url) => {if (String(url).includes("conversations.info")) return json({ ok: true, channel: { is_im: true } });- if (String(url).includes("users.info"))- return json({- ok: true,- user: { name: "Someone Else", profile: { image_48: "https://avatars.slack-edge.com/other.png" } },- });if (String(url).includes("auth.test")) return json({ ok: true, user_id: "OWNER" });return json({ ok: true, messages: [{ ts: "2.0", user: "U_OTHER", text: "Another message" }] });},- });- await source("owner", [item]);+ })("owner", [item]);const after = (await items.get(item.id))!;assert.deepEqual(after.sourcePayload!.participants, []);assert.equal(after.sourcePayload!.slackAvatarsRefreshAt, 0);@@ -744,50 +587,53 @@ test("unverified waiting senders never inherit another context author's avatar",(after.sourcePayload!.context as Array<{ avatarUrl: string }>)[0]!.avatarUrl,"https://avatars.slack-edge.com/other.png",);- let messageReads = 0;- await createInboxSourceRefresh({- featureFlags,- items,- tokens,- fetchImpl: async (url) => {- if (String(url).includes("conversations.history")) {- messageReads++;- return json({ ok: true, messages: [{ ts: "1.0", user: "U_SENDER" }] });- }- assert.match(String(url), /users.info\?user=U_SENDER$/);- return json({- ok: true,- user: { name: "Waiting Sender", profile: { image_48: "https://avatars.slack-edge.com/sender.png" } },- });- },- })("owner", [after], "avatars");- assert.equal(messageReads, 1);- assert.deepEqual((await items.get(item.id))!.sourcePayload!.participants, [- { id: "U_SENDER", name: "Waiting Sender", avatarUrl: "https://avatars.slack-edge.com/sender.png" },- ]);});-test("profile failures retain provider diagnostics and cached avatars without exposing credentials", async () => {+test("saved participants do not supply a missing sender identity", async () => {+ for (const mode of [undefined, "avatars"] as const) {+ const { items, item } = await fixture("slack", { channelId: "D1", ts: "1.0" });+ const saved = { id: "U1", name: "Previously saved sender" };+ await items.annotate(item.id, { participants: [saved] });+ const before = (await items.get(item.id))!;+ const looked: string[] = [];+ await createInboxSourceRefresh({+ featureFlags,+ items,+ tokens,+ directory: directoryOf({ U1: { displayName: "Alex", avatarUrl: ALEX } }, (id) => looked.push(id)),+ fetchImpl: async (url) => {+ assert.notEqual(mode, "avatars");+ if (String(url).includes("conversations.info")) return json({ ok: true, channel: { is_im: true } });+ return json({ ok: true, messages: [] });+ },+ })("owner", [before], mode);+ const after = (await items.get(item.id))!;+ assert.deepEqual(looked, []);+ assert.deepEqual(after.sourcePayload!.participants, [saved]);+ if (mode === "avatars") assert.deepEqual(after, before);+ else assert.equal(after.sourcePayload!.slackAvatarsRefreshAt, 0);+ }+});++test("profile failures retain diagnostics without exposing credentials", async () => {const { createErrorLog } = await import("../src/admin/error-log.ts");for (const mode of [undefined, "avatars"] as const) {const { items, item } = await fixture("slack", { channelId: "D1", ts: "1.0", userId: "U1" });const errors = createErrorLog();- const sourceFetch = slackFetch([]);await createInboxSourceRefresh({featureFlags,items,tokens,+ directory: directoryOf({}, () => {+ throw new Error("lookup failed token=xoxb-private-credential");+ }),errors,- fetchImpl: async (url, init) => {- if (String(url).includes("users.info"))- return json({ ok: false, error: "missing_scope token=private-credential" });- return sourceFetch(url, init);- },+ fetchImpl: slackFetch([]),})("owner", [item], mode);const events = await errors.list();assert.ok(events.length > 0);assert.ok(events.every((event) => event.scopeLabel === "personal:owner"));- assert.match(events[0]!.message, /users.info: missing_scope/);+ assert.match(events[0]!.message, /Slack profile U1: lookup failed/);assert.doesNotMatch(JSON.stringify(events), /private-credential/);assert.equal((await items.get(item.id))!.status, "ready");}@@ -806,6 +652,7 @@ test("cosmetic refresh records ledger failures without rejecting the inbox reque},},tokens,+ directory,errors,fetchImpl: async () => json({ ok: true, user: { name: "Alex" } }),})("owner", [item], "avatars");@@ -835,6 +682,7 @@ test("Inbox source refresh checks the owner rollout before credentials, reads, oreturn "synthetic-token";},},+ directory,fetchImpl: slackFetch(calls),});await refresh("owner", [item], mode);@@ -843,8 +691,7 @@ test("Inbox source refresh checks the owner rollout before credentials, reads, oassert.deepEqual(await items.get(item.id), before);await flags.setEnabled("inbox_loops", "personal:owner", true, "admin");await refresh("owner", [item], mode);- assert.ok(credentials > 0);- assert.ok(calls.length > 0);+ assert.equal(credentials > 0 && calls.length > 0, mode === undefined);const enriched = (await items.get(item.id))!;assert.ok(enriched.sourcePayload?.participants);await flags.setEnabled("inbox_loops", "personal:owner", false, "admin");@@ -856,3 +703,76 @@ test("Inbox source refresh checks the owner rollout before credentials, reads, oassert.deepEqual(await items.get(item.id), enriched);}});++test("Slack-id principals and items without a known sender use only the directory", async () => {+ const { items, item } = await fixture("slack", { channelId: "D1", ts: "1.0", userId: "U1" });+ const fetchImpl: typeof fetch = async () => assert.fail("no Slack reads");+ const slackIdMode = {+ getBySlackId: async (id: string) =>+ id === "U1" ? { principalId: "U1", displayName: "Alex", type: "internal" as const, avatarUrl: ALEX } : null,+ };+ await createInboxSourceRefresh({ featureFlags, items, tokens, directory: slackIdMode, fetchImpl })(+ "owner",+ [item],+ "avatars",+ );+ assert.deepEqual((await items.get(item.id))!.sourcePayload!.participants, [+ { id: "U1", name: "Alex", avatarUrl: ALEX },+ ]);+ const legacy = await fixture("slack", { channelId: "D2", ts: "1.0" });+ await createInboxSourceRefresh({ featureFlags, items: legacy.items, tokens, directory, fetchImpl })(+ "owner",+ [legacy.item],+ "avatars",+ );+ assert.deepEqual(await legacy.items.get(legacy.item.id), legacy.item);+});++test("people outside the directory keep the profile Slack returned with their message", async () => {+ const { items, item } = await fixture("slack", { channelId: "C1", ts: "1.0" });+ await createInboxSourceRefresh({+ featureFlags,+ items,+ tokens,+ directory,+ fetchImpl: async (url) => {+ const path = new URL(String(url)).pathname;+ if (path.endsWith("conversations.info")) return json({ ok: true, channel: {} });+ if (path.endsWith("auth.test")) return json({ ok: true, user_id: "OWNER" });+ return json({+ ok: true,+ messages: [+ {+ ts: "1.0",+ user: "U_EXT",+ user_profile: { display_name: "Pat Partner", image_72: "https://avatars.slack-edge.com/pat.png" },+ text: "Hello from Slack Connect",+ },+ ],+ });+ },+ })("owner", [item]);+ const after = (await items.get(item.id))!;+ assert.deepEqual(after.sourcePayload!.participants, [+ { id: "U_EXT", name: "Pat Partner", avatarUrl: "https://avatars.slack-edge.com/pat.png" },+ ]);+ assert.equal((after.sourcePayload!.context as Array<{ author: string }>)[0]!.author, "Pat Partner");+});++test("people outside the directory without message profiles keep initials and never trigger profile API calls", async () => {+ const { items, item } = await fixture("slack", { channelId: "C1", ts: "1.0", userId: "U_EXT" });+ await createInboxSourceRefresh({+ featureFlags,+ items,+ tokens,+ directory,+ fetchImpl: async (url) => {+ const path = new URL(String(url)).pathname;+ if (path.endsWith("conversations.info")) return json({ ok: true, channel: {} });+ if (path.endsWith("auth.test")) return json({ ok: true, user_id: "OWNER" });+ assert.ok(path.endsWith("conversations.replies"));+ return json({ ok: true, messages: [{ ts: "1.0", user: "U_EXT", text: "Hello" }] });+ },+ })("owner", [item]);+ assert.deepEqual((await items.get(item.id))!.sourcePayload!.participants, [{ id: "U_EXT", name: "U_EXT" }]);+});diff --git a/test/loop-item-routes.test.ts b/test/loop-item-routes.test.tsindex ea3f38357..c6b4a5b19 100644--- a/test/loop-item-routes.test.ts+++ b/test/loop-item-routes.test.ts@@ -863,6 +863,7 @@ test("inbox list refreshes open Gmail items before returning counts, but not anofeatureFlags: { enabled: async () => true },items: w.loops.items,tokens: { connectorAccessToken: async () => "synthetic" },+ directory: { getBySlackId: async () => null },fetchImpl: async (url) => {refreshes.push(String(url));return Response.json({ messages: [{ internalDate: "2000", labelIds: ["SENT"], snippet: "Already replied" }] });@@ -1189,6 +1190,7 @@ test("an owner cannot trigger Slack avatar enrichment through item detail when Iitems: w.loops.items,featureFlags: { enabled },tokens: { connectorAccessToken: async () => assert.fail("disabled Inbox must not read credentials") },+ directory: { getBySlackId: async () => assert.fail("disabled Inbox must not read the directory") },fetchImpl: async () => assert.fail("disabled Inbox must not call Slack"),});const result = await call(w, {diff --git a/test/postgres-directory-store.test.ts b/test/postgres-directory-store.test.tsindex 7b3f80ea3..bf3f9036e 100644--- a/test/postgres-directory-store.test.ts+++ b/test/postgres-directory-store.test.ts@@ -98,6 +98,9 @@ test("pg directory: slackId round-trips through replace → get/list/resolve; aassert.equal((await store.get("[email protected]"))?.avatarUrl, "https://avatars.slack-edge.com/eve.png");assert.equal((await store.get("U5"))?.slackId, undefined);assert.equal((await store.list()).find((m) => m.principalId === "[email protected]")?.slackId, "U9");+ assert.equal((await store.getBySlackId("U9"))?.principalId, "[email protected]");+ assert.equal((await store.getBySlackId("U5"))?.principalId, "U5");+ assert.equal(await store.getBySlackId("Eve"), null);const r = await store.resolve("Eve");assert.equal(r.kind === "one" && r.member.slackId, "U9");