Skip to content

armgit / qm

Public Imported from GitHub
0

Multiplayer agent harness for work.

Show Slack profile photos throughout Inbox (#2193)

Eve Bouffardc789bed98848
diff --git a/plugins/web-ui/src/inbox.ts b/plugins/web-ui/src/inbox.ts
index 6342f0474..3a2f2e987 100644
--- a/plugins/web-ui/src/inbox.ts
+++ b/plugins/web-ui/src/inbox.ts
@@ -15,6 +15,7 @@ import {
sentMailTpl,
} from "./sent-mail";
import { html, nothing, render, type TemplateResult } from "lit";
+import { keyed } from "lit/directives/keyed.js";
import { live } from "lit/directives/live.js";
import { ref } from "lit/directives/ref.js";
import {
@@ -63,6 +64,8 @@ export interface InboxDraft {
export interface InboxContextMessage {
author: string;
+ authorId?: string;
+ avatarUrl?: string;
at?: number;
text: string;
images?: string[];
@@ -119,6 +122,7 @@ export interface InboxItem {
fromDetail?: string;
snippet: string;
context?: InboxContextMessage[];
+ participants?: Participant[];
receivedAt: number;
externalUrl?: string;
draft?: InboxDraft;
@@ -127,7 +131,7 @@ export interface InboxItem {
draftSessionId?: string;
thread: LedgerThreadMessage[];
gmail?: { threadId: string; subject?: string; to?: string[]; cc?: string[] };
- slack?: { channelId: string; channelLabel?: string; ts: string; threadTs?: string };
+ slack?: { channelId: string; channelLabel?: string; ts: string; threadTs?: string; userId?: string };
sentAt?: number;
dismissedAt?: number;
repliedAt?: number;
@@ -428,6 +432,15 @@ export function toInboxItem(entry: LedgerItem): InboxItem {
sourceContextFetched: payload.sourceContextFetched === true,
sourceContextPartial: payload.sourceContextPartial === true,
...(typeof payload.sourceRefreshError === "string" ? { sourceRefreshError: payload.sourceRefreshError } : {}),
+ ...(source === "slack" && Array.isArray(payload.participants)
+ ? {
+ participants: payload.participants.flatMap((person) =>
+ person && typeof person.id === "string" && typeof person.name === "string"
+ ? [{ key: person.id, name: person.name, avatarUrl: str(person.avatarUrl) }]
+ : [],
+ ),
+ }
+ : {}),
...(Array.isArray(payload.context) ? { context: payload.context as InboxContextMessage[] } : {}),
...(str(payload.externalUrl) ? { externalUrl: payload.externalUrl as string } : {}),
...(draft ? { draft } : {}),
@@ -1119,6 +1132,7 @@ function fmtClock(ms: number): string {
interface Participant {
key: string;
name: string;
+ avatarUrl?: string;
}
function participantName(raw: string): string {
@@ -1130,12 +1144,22 @@ function participantKey(raw: string): string {
}
function participantsOf(item: InboxItem): Participant[] {
- const found = new Map<string, Participant>();
- for (const raw of [item.from, ...(item.context ?? []).map((m) => m.author)]) {
- const name = participantName(raw ?? "");
+ const slack = item.source === "slack";
+ const found = new Map<string, Participant>((slack ? (item.participants ?? []) : []).map((p) => [p.key, p]));
+ for (const message of [
+ {
+ author: item.from,
+ authorId: slack ? (item.slack?.userId ?? item.participants?.[0]?.key) : undefined,
+ avatarUrl: undefined,
+ },
+ ...(item.context ?? []),
+ ]) {
+ const name = participantName(message.author ?? "");
if (!name) continue;
- const key = participantKey(raw);
- if (!found.has(key)) found.set(key, { key, name });
+ const id = slack ? message.authorId : undefined;
+ if (slack && !id && [...found.values()].some((person) => person.name === name)) continue;
+ const key = id ?? participantKey(message.author);
+ if (!found.has(key)) found.set(key, { key, name, avatarUrl: slack ? message.avatarUrl : undefined });
}
return [...found.values()];
}
@@ -1146,6 +1170,35 @@ function avatarHue(key: string): number {
return hash;
}
+function avatarTpl(person: Participant): TemplateResult {
+ const photo = person.avatarUrl?.startsWith("https://") ? person.avatarUrl : undefined;
+ return html`<span
+ class="inbox-avatar"
+ style=${`--avatar-hue:${avatarHue(person.key)}`}
+ ${tip(person.name)}
+ aria-hidden="true"
+ >
+ ${initials(person.name)}
+ ${
+ photo
+ ? keyed(
+ photo,
+ html`<img
+ src=${photo}
+ alt=""
+ loading="lazy"
+ decoding="async"
+ referrerpolicy="no-referrer"
+ @error=${(event: Event) => {
+ (event.currentTarget as HTMLImageElement).hidden = true;
+ }}
+ />`,
+ )
+ : nothing
+ }
+ </span>`;
+}
+
const AVATARS_SHOWN = 4;
export function participantsTpl(item: InboxItem): TemplateResult | typeof nothing {
@@ -1154,12 +1207,7 @@ export function participantsTpl(item: InboxItem): TemplateResult | typeof nothin
const shown = people.length > AVATARS_SHOWN ? people.slice(0, AVATARS_SHOWN - 1) : people;
const rest = people.slice(shown.length);
return html`<span class="inbox-avatars" aria-label=${`In this conversation: ${people.map((p) => p.name).join(", ")}`}>
- ${shown.map(
- (p) =>
- html`<span class="inbox-avatar" style=${`--avatar-hue:${avatarHue(p.key)}`} ${tip(p.name)} aria-hidden="true"
- >${initials(p.name)}</span
- >`,
- )}
+ ${shown.map(avatarTpl)}
${
rest.length
? html`<span class="inbox-avatar more" ${tip(rest.map((p) => p.name).join(", "))} aria-hidden="true"
@@ -1245,6 +1293,7 @@ export function contextTpl(item: InboxItem): TemplateResult | typeof nothing {
...context.filter((m) => !item.slack || m.nearby === true),
{
author: item.from,
+ authorId: item.slack?.userId ?? (item.source === "slack" ? item.participants?.[0]?.key : undefined),
at: item.receivedAt,
text: item.snippet,
images: item.images,
@@ -1269,12 +1318,13 @@ export function contextTpl(item: InboxItem): TemplateResult | typeof nothing {
${item.sourceRefreshError ? html`<div class="inbox-source-notice" role="status">${item.sourceRefreshError}</div>` : nothing}
${item.sourceContextPartial ? html`<div class="inbox-source-notice">Showing part of this conversation. Open in Slack for the full history.</div>` : nothing}
${rows.slice(hidden).map((m) => {
- const name = participantName(m.author) || m.author;
+ const participant = item.source === "slack" ? item.participants?.find((p) => p.key === m.authorId) : undefined;
+ const author = participant?.name ?? m.author;
+ const name = participantName(author) || author;
+ const avatarUrl = participant ? participant.avatarUrl : m.avatarUrl;
return html`
<div class="inbox-context-msg ${m.reply ? "inbox-thread-reply" : ""} ${m.nearby ? "inbox-nearby-context" : ""}">
- <span class="inbox-avatar" style=${`--avatar-hue:${avatarHue(participantKey(m.author))}`} aria-hidden="true"
- >${initials(name)}</span
- >
+ ${avatarTpl({ key: m.authorId ?? participantKey(m.author), name, avatarUrl: item.source === "slack" ? avatarUrl : undefined })}
<div class="inbox-context-body">
<div class="inbox-context-head">
<span class="inbox-context-author">${name}</span>
diff --git a/plugins/web-ui/src/shell.css b/plugins/web-ui/src/shell.css
index 4be883008..116727466 100644
--- a/plugins/web-ui/src/shell.css
+++ b/plugins/web-ui/src/shell.css
@@ -9785,6 +9785,8 @@ h3.ambient-field-label {
gap: 3px;
}
.inbox-avatar {
+ position: relative;
+ overflow: hidden;
width: 20px;
height: 20px;
flex: none;
@@ -9798,6 +9800,13 @@ h3.ambient-field-label {
background: oklch(0.92 0.05 var(--avatar-hue, 250));
color: oklch(0.38 0.09 var(--avatar-hue, 250));
}
+.inbox-avatar img {
+ position: absolute;
+ inset: 0;
+ width: 100%;
+ height: 100%;
+ object-fit: cover;
+}
.inbox-avatar.more {
background: var(--secondary);
color: var(--muted-foreground);
diff --git a/plugins/web-ui/test/inbox-avatars.test.ts b/plugins/web-ui/test/inbox-avatars.test.ts
new file mode 100644
index 000000000..2ce5c02e4
--- /dev/null
+++ b/plugins/web-ui/test/inbox-avatars.test.ts
@@ -0,0 +1,102 @@
+import assert from "node:assert/strict";
+import { test } from "node:test";
+import { createInboxFixture } from "./inbox-composer-fixture.ts";
+
+test("Slack feed avatars use stable identities and fall back to initials when a photo fails", async () => {
+ const f = await createInboxFixture();
+ try {
+ await f.vite.ssrLoadModule("/src/shell.ts");
+ const { participantsTpl, contextTpl, toInboxItem } = await f.vite.ssrLoadModule("/src/inbox.ts");
+ const { render } = await f.vite.ssrLoadModule("lit");
+ const item = toInboxItem({
+ id: "slack-1",
+ loopId: "inbox",
+ dedupeKey: "D1",
+ source: "slack",
+ state: "held",
+ sourceAt: 1000,
+ updatedAt: 1000,
+ thread: [],
+ sourcePayload: {
+ from: "Alex",
+ snippet: "Waiting message",
+ slack: { channelId: "D1", ts: "1.0", userId: "U1" },
+ participants: [
+ { id: "U1", name: "Alex", avatarUrl: "https://avatars.slack-edge.com/alex.png" },
+ { id: "U2", name: "Alex", avatarUrl: "https://avatars.slack-edge.com/other-alex.png" },
+ { id: "U3", name: "Sam" },
+ ],
+ },
+ });
+ render(participantsTpl(item), f.host);
+ assert.equal(f.host.querySelectorAll(".inbox-avatar").length, 3);
+ assert.equal(f.host.querySelectorAll("img").length, 2);
+ const photo = f.host.querySelector("img")!;
+ assert.equal(photo.getAttribute("referrerpolicy"), "no-referrer");
+ photo.dispatchEvent(new f.dom.window.Event("error"));
+ assert.equal(photo.hidden, true);
+ assert.match(photo.parentElement!.textContent!, /A/);
+ item.participants[0].avatarUrl = "https://avatars.slack-edge.com/updated.png";
+ render(participantsTpl(item), f.host);
+ assert.equal(f.host.querySelector("img")!.hidden, false);
+ assert.equal(f.host.querySelector("img")!.getAttribute("src"), "https://avatars.slack-edge.com/updated.png");
+ render(contextTpl(item), f.host);
+ assert.equal(
+ f.host.querySelector(".inbox-avatar img")!.getAttribute("src"),
+ "https://avatars.slack-edge.com/updated.png",
+ );
+ item.slack.userId = undefined;
+ item.participants[0].name = "Alex Morgan";
+ render(contextTpl(item), f.host);
+ assert.equal(f.host.querySelector(".inbox-context-author")!.textContent, "Alex Morgan");
+ assert.equal(
+ f.host.querySelector(".inbox-avatar img")!.getAttribute("src"),
+ "https://avatars.slack-edge.com/updated.png",
+ );
+ item.participants[0].name = "Alex";
+ item.sourceContextFetched = true;
+ item.context = [
+ { author: "Alex", authorId: "U2", avatarUrl: "https://avatars.slack-edge.com/other-alex.png", text: "Reply" },
+ ];
+ render(contextTpl(item), f.host);
+ assert.equal(
+ f.host.querySelector(".inbox-avatar img")!.getAttribute("src"),
+ "https://avatars.slack-edge.com/other-alex.png",
+ );
+ item.participants[1].name = "Alex Rivera";
+ render(contextTpl(item), f.host);
+ assert.equal(f.host.querySelector(".inbox-context-author")!.textContent, "Alex Rivera");
+ item.participants[1].name = "Alex";
+ item.participants[1].avatarUrl = "https://avatars.slack-edge.com/latest-alex.png";
+ render(contextTpl(item), f.host);
+ assert.equal(
+ f.host.querySelector(".inbox-avatar img")!.getAttribute("src"),
+ "https://avatars.slack-edge.com/latest-alex.png",
+ );
+ item.participants[1].avatarUrl = undefined;
+ render(contextTpl(item), f.host);
+ assert.equal(f.host.querySelectorAll(".inbox-avatar img").length, 0);
+ item.context[0].authorId = "U4";
+ item.context[0].avatarUrl = "javascript:alert(1)";
+ render(contextTpl(item), f.host);
+ assert.equal(f.host.querySelectorAll(".inbox-avatar img").length, 0);
+ item.context[0].authorId = "U2";
+ item.context.push({ author: "Casey", authorId: "U4", text: "Earlier message" });
+ render(participantsTpl(item), f.host);
+ assert.equal(f.host.querySelectorAll(".inbox-avatar").length, 4);
+ assert.match(f.host.querySelector(".inbox-avatars")!.getAttribute("aria-label")!, /Alex, Alex, Sam, Casey/);
+ item.context.push({ author: "Jordan", authorId: "U5", text: "Another message" });
+ render(participantsTpl(item), f.host);
+ assert.equal(f.host.querySelector(".inbox-avatar.more")!.textContent!.trim(), "+2");
+ item.slack = undefined;
+ item.from = "Alex Smith";
+ render(participantsTpl(item), f.host);
+ assert.equal(f.host.querySelector(".inbox-avatar.more")!.textContent!.trim(), "+2");
+ assert.doesNotMatch(f.host.querySelector(".inbox-avatars")!.getAttribute("aria-label")!, /Alex Smith/);
+ item.source = "gmail";
+ render(participantsTpl(item), f.host);
+ assert.equal(f.host.querySelectorAll("img").length, 0);
+ } finally {
+ await f.close();
+ }
+});
diff --git a/src/api/routes/inbox.ts b/src/api/routes/inbox.ts
index e3fff2c67..58657d276 100644
--- a/src/api/routes/inbox.ts
+++ b/src/api/routes/inbox.ts
@@ -69,7 +69,7 @@ async function inbox(ctx: ApiCtx): Promise<void> {
.filter((item) => !isResolved(item) && (item.source ?? item.sourcePayload?.source) === "gmail");
await ctx.deps.inboxSourceRefresh(acting.actorId, mail);
}
- const summaries = (await deps.items.summaries(selectedIds, { includeEmailClassification: true })).filter(
+ const summaries = (await deps.items.summaries(selectedIds, { includeInboxMetadata: true })).filter(
(item) => selectedIds.includes(item.loopId) && item.inboxPreview?.sentChat !== true,
);
const itemId = ctx.url.searchParams.get("itemId");
@@ -141,6 +141,29 @@ async function inbox(ctx: ApiCtx): Promise<void> {
}
const page = feed.slice(0, 40);
const last = page.at(-1);
+ if (ctx.method === "GET" && ctx.deps.inboxSourceRefresh) {
+ const slack = (
+ await Promise.all(
+ page
+ .filter(
+ (item) =>
+ item.source === "slack" &&
+ loopsById.get(item.loopId)?.owner === acting.actorId &&
+ !(
+ typeof item.inboxPreview?.slackAvatarsRefreshAt === "number" &&
+ Date.now() < item.inboxPreview.slackAvatarsRefreshAt
+ ),
+ )
+ .map((item) => deps.items.get(item.id)),
+ )
+ ).filter((item) => item !== null);
+ await ctx.deps.inboxSourceRefresh(acting.actorId, slack, "avatars");
+ for (const refreshed of await Promise.all(slack.map((item) => deps.items.get(item.id)))) {
+ const summary = page.find((entry) => entry.id === refreshed?.id);
+ if (summary && refreshed && refreshed.sourceAt === summary.sourceAt)
+ summary.inboxPreview = { ...summary.inboxPreview, participants: refreshed.sourcePayload?.participants };
+ }
+ }
sendJson(ctx.res, 200, {
selected: await Promise.all(
selected.map(async (loop) => ({
diff --git a/src/api/routes/loop-items.ts b/src/api/routes/loop-items.ts
index ad8965856..8b8870a00 100644
--- a/src/api/routes/loop-items.ts
+++ b/src/api/routes/loop-items.ts
@@ -124,7 +124,7 @@ async function listItems(ctx: ApiCtx): Promise<void> {
const state = ledgerState(item);
counts[state] = (counts[state] ?? 0) + 1;
}
- sendJson(ctx.res, 200, { loop, items: items.map((item) => ledgerItemView(item, loop)), counts });
+ sendJson(ctx.res, 200, { loop, items: items.map((item) => ledgerItemView(item, loop, !!ctx.capability)), counts });
}
async function ingestItems(ctx: ApiCtx): Promise<void> {
@@ -268,7 +268,7 @@ async function getItem(ctx: ApiCtx): Promise<void> {
)
await ctx.deps.inboxSourceRefresh?.(loaded.loop.owner, [loaded.item]);
sendJson(ctx.res, 200, {
- item: ledgerItemView((await loaded.deps.items.get(loaded.item.id)) ?? loaded.item, loaded.loop),
+ item: ledgerItemView((await loaded.deps.items.get(loaded.item.id)) ?? loaded.item, loaded.loop, !!ctx.capability),
outputs: (await loaded.deps.outputs.byItem(loaded.item.id)).filter((output) => output.loopId === loaded.loop.id),
});
}
@@ -307,7 +307,8 @@ async function actOnItem(ctx: ApiCtx): Promise<void> {
const data = proposalFrom(item, args.proposal ?? args);
if (!data) return sendJson(ctx.res, 400, { error: "bad_request", message: "proposal is not valid for this item" });
if (expectedAt !== undefined && item.proposal && item.proposal.at !== expectedAt) return draftChanged();
- if (sameProposalData(item, data)) return sendJson(ctx.res, 200, { item: ledgerItemView(item, loop) });
+ if (sameProposalData(item, data))
+ return sendJson(ctx.res, 200, { item: ledgerItemView(item, loop, !!ctx.capability) });
const next = await deps.items.setProposal(
item.id,
{ data, by: proposalAuthor },
@@ -315,14 +316,14 @@ async function actOnItem(ctx: ApiCtx): Promise<void> {
);
if (!next && expectedAt !== undefined) return draftChanged();
if (!next) return sendJson(ctx.res, 409, { error: "conflict", message: "this item is already actioned" });
- return sendJson(ctx.res, 200, { item: ledgerItemView(next, loop) });
+ return sendJson(ctx.res, 200, { item: ledgerItemView(next, loop, !!ctx.capability) });
}
if (kind === "dismiss") {
const next = await deps.items.recordAction(item.id, { kind, outcome: "dismissed" });
if (!next) return sendJson(ctx.res, 409, { error: "conflict", message: "this item is already actioned" });
if (args.group === true && !ctx.capability) await settleGroup(deps.items, next);
- return sendJson(ctx.res, 200, { item: ledgerItemView(next, loop) });
+ return sendJson(ctx.res, 200, { item: ledgerItemView(next, loop, !!ctx.capability) });
}
if (kind === "prioritize" || kind === "ungroup") {
@@ -336,20 +337,20 @@ async function actOnItem(ctx: ApiCtx): Promise<void> {
? await deps.items.setTriage(item.id, { priority }, "human")
: await removeFromGroup(deps.items, item);
if (!next) return sendJson(ctx.res, 409, { error: "conflict", message: "this item is already actioned" });
- return sendJson(ctx.res, 200, { item: ledgerItemView(next, loop) });
+ return sendJson(ctx.res, 200, { item: ledgerItemView(next, loop, !!ctx.capability) });
}
if (kind === "reply") {
if (!ctx.actor?.p || item.sourcePayload?.sentChat !== true) return sendJson(ctx.res, 403, { error: "forbidden" });
const next = await deps.items.reopen(item.id, { sentReply: true });
if (!next) return sendJson(ctx.res, 409, { error: "conflict", message: "a reply is already being drafted" });
- return sendJson(ctx.res, 200, { item: ledgerItemView(next, loop) });
+ return sendJson(ctx.res, 200, { item: ledgerItemView(next, loop, !!ctx.capability) });
}
if (kind === "reopen") {
const next = await deps.items.reopen(item.id);
if (!next) return sendJson(ctx.res, 409, { error: "conflict", message: "this item is not dismissed" });
- return sendJson(ctx.res, 200, { item: ledgerItemView(next, loop) });
+ return sendJson(ctx.res, 200, { item: ledgerItemView(next, loop, !!ctx.capability) });
}
if (kind === "replied") {
@@ -363,7 +364,7 @@ async function actOnItem(ctx: ApiCtx): Promise<void> {
if (!next) {
return sendJson(ctx.res, 409, { error: "conflict", message: "this item was already actioned from here" });
}
- return sendJson(ctx.res, 200, { item: ledgerItemView(next, loop) });
+ return sendJson(ctx.res, 200, { item: ledgerItemView(next, loop, !!ctx.capability) });
}
if (kind === "send" && item.status !== "ready") {
@@ -415,9 +416,10 @@ async function actOnItem(ctx: ApiCtx): Promise<void> {
return sendJson(ctx.res, statusByReason[result.reason], { error: result.reason, message: result.message });
}
if (result.payloadPatch) item = (await deps.items.annotate(item.id, result.payloadPatch)) ?? item;
- if (result.resolves === false) return sendJson(ctx.res, 200, { item: ledgerItemView(item, loop) });
+ if (result.resolves === false)
+ return sendJson(ctx.res, 200, { item: ledgerItemView(item, loop, !!ctx.capability) });
const next = await deps.items.recordAction(item.id, { kind, outcome: "actioned", result: result.result });
- return sendJson(ctx.res, 200, { item: ledgerItemView(next ?? item, loop) });
+ return sendJson(ctx.res, 200, { item: ledgerItemView(next ?? item, loop, !!ctx.capability) });
} finally {
await deps.items.releaseDecision(item.id, decisionToken);
}
@@ -435,7 +437,7 @@ async function actOnItem(ctx: ApiCtx): Promise<void> {
outcome: "actioned",
...(turn.reply ? { result: turn.reply } : {}),
});
- sendJson(ctx.res, 200, { item: ledgerItemView(next ?? item, loop) });
+ sendJson(ctx.res, 200, { item: ledgerItemView(next ?? item, loop, !!ctx.capability) });
}
const followUpOptionsSchema = z.object({
@@ -487,7 +489,7 @@ async function followUpOnItem(ctx: ApiCtx): Promise<void> {
loaded.actorId,
options,
);
- sendJson(ctx.res, 200, { item: ledgerItemView(next ?? item, loop) });
+ sendJson(ctx.res, 200, { item: ledgerItemView(next ?? item, loop, !!ctx.capability) });
} catch (e) {
sendJson(ctx.res, 502, { error: "followup_failed", message: errMessage(e) });
}
@@ -589,7 +591,7 @@ export async function ensureSentChat(ctx: ApiCtx): Promise<void> {
item = (await deps.items.annotate(id, payload, { summary: text("subject", 300) })) ?? item;
if (item.actionKind === "sent") item = (await deps.items.reopen(id, { sentReply: true })) ?? item;
ctx.res.setHeader("Cache-Control", "no-store");
- sendJson(ctx.res, 200, { item: ledgerItemView(item, loop) });
+ sendJson(ctx.res, 200, { item: ledgerItemView(item, loop, !!ctx.capability) });
}
async function ensureInboxSyncCron(ctx: ApiCtx): Promise<void> {
diff --git a/src/api/routes/loops.ts b/src/api/routes/loops.ts
index bae08f2f7..acc365b2c 100644
--- a/src/api/routes/loops.ts
+++ b/src/api/routes/loops.ts
@@ -12,7 +12,7 @@ import type { ShipGrantStore } from "../../loops/ship-grant-store.ts";
import type { LoopFireService } from "../../loops/loop-fire.ts";
import { collectVitals } from "../../loops/governor.ts";
import { buildShipGrant } from "../../loops/ship-gate.ts";
-import { consolidates, sortLedgerItems } from "../../loops/ledger-view.ts";
+import { agentSourcePayload, consolidates, sortLedgerItems } from "../../loops/ledger-view.ts";
import { settleGroup } from "../../loops/triage.ts";
import type { CronStore } from "../../cron/cron-store.ts";
import { DEFAULT_CRON_TIMEZONE, userScheduleFromBody, validateUserSchedule } from "../../cron/schedule.ts";
@@ -354,7 +354,22 @@ async function getLoop(ctx: ApiCtx): Promise<void> {
]);
return sendJson(ctx.res, 200, {
loop,
- items: sortLedgerItems(items, loop),
+ items: sortLedgerItems(items, loop).map((item) =>
+ ctx.capability
+ ? {
+ ...item,
+ ...(item.sourcePayload ? { sourcePayload: agentSourcePayload(item.sourcePayload, item.source) } : {}),
+ ...(item.inboxPreview
+ ? {
+ inboxPreview: agentSourcePayload(
+ item.inboxPreview,
+ item.source ?? String(item.sourcePayload?.source ?? ""),
+ ),
+ }
+ : {}),
+ }
+ : item,
+ ),
outputs,
grants,
vitals,
diff --git a/src/loops/inbox-source-refresh.ts b/src/loops/inbox-source-refresh.ts
index 71a9e8209..b46da9c5e 100644
--- a/src/loops/inbox-source-refresh.ts
+++ b/src/loops/inbox-source-refresh.ts
@@ -1,5 +1,9 @@
import { LRUCache } from "lru-cache";
-import type { LoopItem } from "../types.ts";
+import { personalScope, type LoopItem } from "../types.ts";
+import type { FeatureFlagStore } from "../feature-flags.ts";
+import type { ErrorLog } from "../admin/error-log.ts";
+import { redactSecrets } from "../harness/redact-secrets.ts";
+import { errMessage } from "../util/errors.ts";
import type { LoopItemLedger } from "./item-ledger.ts";
import { isResolved } from "./ledger-view.ts";
import { isObj, tokenFor, type ConnectorTokenSource } from "./sources/adapter.ts";
@@ -8,12 +12,20 @@ import { normalizeSlackApiUrl } from "../slack/config.ts";
interface RefreshDeps {
items: LoopItemLedger;
tokens: ConnectorTokenSource;
+ featureFlags: Pick<FeatureFlagStore, "enabled">;
+ errors?: ErrorLog;
fetchImpl?: typeof fetch;
slackApiUrl?: string;
now?: () => number;
}
-export type InboxSourceRefresh = (owner: string, items: LoopItem[]) => Promise<void>;
+export type InboxSourceRefresh = (owner: string, items: LoopItem[], mode?: "avatars") => Promise<void>;
+
+interface SlackParticipant {
+ id: string;
+ name: string;
+ avatarUrl?: string;
+}
// Reuse the inbox's existing refresh cycle, not a second provider poller. Cache only
// results/identities, never credentials, and share in-flight reads between tabs.
@@ -22,38 +34,187 @@ export function createInboxSourceRefresh(deps: RefreshDeps): InboxSourceRefresh
const info = new LRUCache<string, Record<string, unknown>>({ max: 2000, ttl: 300_000 });
const limited = new LRUCache<string, boolean>({ max: 2000 });
const running = new Map<string, Promise<void>>();
+ const infoRunning = new Map<string, Promise<Record<string, unknown>>>();
const fetchImpl = deps.fetchImpl ?? fetch;
const now = deps.now ?? Date.now;
const positions = new LRUCache<string, number>({ max: 2000 });
const slackBase = normalizeSlackApiUrl(deps.slackApiUrl ?? "https://slack.com/api");
- async function get(owner: string, source: string, path: string, token: string): Promise<Record<string, unknown>> {
+ function recordFailure(owner: string, subject: string, error: unknown): void {
+ deps.errors?.record({
+ category: "inbox",
+ code: "source_refresh_failed",
+ message: redactSecrets(`${subject}: ${errMessage(error)}`),
+ scopeLabel: personalScope(owner),
+ });
+ }
+
+ async function get(
+ owner: string,
+ source: string,
+ path: string,
+ token: string,
+ deadline = now() + 3000,
+ ): Promise<Record<string, unknown>> {
const method = path.split("?")[0]!;
const key = `${owner}:${source}:${source === "slack" ? method : "read"}`;
if (limited.has(key)) throw new Error("Source rate limited. The next refresh will retry.");
const base = source === "slack" ? slackBase : "https://gmail.googleapis.com/gmail/v1/users/me/";
const res = await fetchImpl(`${base}${path}`, {
headers: { authorization: `Bearer ${token}` },
- signal: AbortSignal.timeout(3000),
+ signal: AbortSignal.timeout(Math.max(1, Math.min(3000, deadline - now()))),
});
if (res.status === 429) {
const retry = Number(res.headers.get("retry-after"));
limited.set(key, true, { ttl: Math.max(60, Number.isFinite(retry) ? retry : 60) * 1000 });
}
- if (!res.ok) throw new Error("Couldn't refresh the source. Your item has not been dismissed.");
+ if (!res.ok)
+ throw new Error("Couldn't refresh the source. Your item has not been dismissed.", {
+ cause: new Error(`${source} ${method}: HTTP ${res.status}`),
+ });
const body: unknown = await res.json();
if (!isObj(body) || body.ok === false)
- throw new Error("Couldn't refresh the source. Your item has not been dismissed.");
+ throw new Error("Couldn't refresh the source. Your item has not been dismissed.", {
+ cause: new Error(
+ `${source} ${method}: ${isObj(body) && typeof body.error === "string" ? body.error : "Invalid response"}`,
+ ),
+ });
return body;
}
- async function slackInfo(owner: string, path: string, token: string): Promise<Record<string, unknown>> {
+ async function slackInfo(
+ owner: string,
+ path: string,
+ token: string,
+ deadline?: number,
+ ): Promise<Record<string, unknown>> {
const key = `${owner}:${path}`;
const cached = info.get(key);
if (cached) return cached;
- const value = await get(owner, "slack", path, token);
- info.set(key, value);
- return value;
+ const pending = infoRunning.get(key);
+ if (pending) return pending;
+ const task = get(owner, "slack", path, token, deadline)
+ .then((value) => {
+ info.set(key, value);
+ return value;
+ })
+ .finally(() => infoRunning.delete(key));
+ infoRunning.set(key, task);
+ return task;
+ }
+
+ function imageUrl(profile: Record<string, unknown>): string | undefined {
+ return [48, 72, 192, 512, 1024, 32, 24, "original", 36, 96, 128, 256]
+ .map((size) => profile[`image_${size}`])
+ .find((value): value is string => typeof value === "string" && value.startsWith("https://"));
+ }
+
+ function savedParticipants(payload: Record<string, unknown>): SlackParticipant[] {
+ return Array.isArray(payload.participants)
+ ? payload.participants.filter(
+ (person): person is SlackParticipant =>
+ isObj(person) && typeof person.id === "string" && typeof person.name === "string",
+ )
+ : [];
+ }
+
+ function messageParticipant(message: Record<string, unknown>): SlackParticipant | undefined {
+ const bot = isObj(message.bot_profile) ? message.bot_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;
+ return {
+ id,
+ name: String(bot.name || message.username || id),
+ ...(avatarUrl ? { avatarUrl } : {}),
+ };
+ }
+
+ async 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(
+ [...new Set(ids)].slice(0, 8).map(async (id): Promise<SlackParticipant> => {
+ const 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 } : {}),
+ };
+ } catch (error) {
+ recordFailure(owner, `Slack profile ${id}`, error);
+ complete = false;
+ return saved;
+ }
+ }),
+ );
+ return { people, refreshAt: now() + (complete ? 86_400_000 : 60_000) };
+ }
+
+ async function refreshAvatars(owner: string, item: LoopItem): Promise<void> {
+ if ((item.source ?? item.sourcePayload?.source) !== "slack") return;
+ const payload = item.sourcePayload ?? {};
+ if (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 } : {}),
+ });
+ }
+ 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,
+ );
+ await deps.items.annotate(
+ item.id,
+ {
+ participants: profiles.people,
+ slackAvatarsRefreshAt: profiles.refreshAt,
+ },
+ { expectedSourceAt: item.sourceAt, expectedSourcePayload: payload },
+ );
}
async function refresh(owner: string, item: LoopItem): Promise<void> {
@@ -102,31 +263,54 @@ export function createInboxSourceRefresh(deps: RefreshDeps): InboxSourceRefresh
.filter((m) => !root || m.ts === root || m.thread_ts === root)
.sort((a, b) => Number(a.ts) - Number(b.ts));
if (root && !messages.some((m) => m.ts === root)) throw new Error("The original Slack message is unavailable.");
- const names = new Map<string, string>();
- for (const user of [
- ...new Set(messages.map((m) => m.user).filter((u): u is string => typeof u === "string")),
- ].slice(0, 8)) {
- try {
- const result = await slackInfo(owner, `users.info?user=${encodeURIComponent(user)}`, token);
- const u = isObj(result.user) ? result.user : {};
- const profile = isObj(u.profile) ? u.profile : {};
- names.set(user, String(profile.display_name || profile.real_name || u.real_name || u.name || user));
- } catch {
- /* User names are cosmetic; message history remains usable. */
- }
+ const waiting = messages.find((message) => message.ts === meta.ts);
+ const saved = savedParticipants(payload);
+ const sender =
+ (waiting && messageParticipant(waiting)) ??
+ (typeof meta.userId === "string" ? { id: meta.userId, name: meta.userId } : saved[0]);
+ const previous = new Map(saved.map((person) => [person.id, person]));
+ for (const message of messages) {
+ const person = messageParticipant(message);
+ if (person)
+ previous.set(person.id, {
+ ...person,
+ ...previous.get(person.id),
+ ...(person.avatarUrl ? { avatarUrl: person.avatarUrl } : {}),
+ });
}
- const context = messages.map((m) => ({
- author: names.get(String(m.user)) ?? String(m.user ?? m.username ?? "Slack"),
- text: typeof m.text === "string" ? m.text : "",
- at: Math.round(Number(m.ts) * 1000),
- ts: m.ts,
- ...(root && m.ts !== root ? { reply: true } : {}),
- images: (Array.isArray(m.files) ? m.files.filter(isObj) : [])
- .filter((f) => typeof f.mimetype === "string" && f.mimetype.startsWith("image/"))
- .map((f) => f.url_private)
- .filter((url): url is string => typeof url === "string" && url.startsWith("https://"))
- .slice(0, 4),
- }));
+ if (sender && (!previous.has(sender.id) || previous.get(sender.id)?.name === sender.id))
+ previous.set(sender.id, { ...sender, ...(typeof payload.from === "string" ? { name: payload.from } : {}) });
+ const profiles = await participants(
+ owner,
+ [
+ ...(sender ? [sender.id] : []),
+ ...messages.toReversed().flatMap((message) => {
+ const person = messageParticipant(message);
+ return person ? [person.id] : [];
+ }),
+ ],
+ token,
+ [...previous.values()],
+ );
+ const people = new Map([...previous.values(), ...profiles.people].map((person) => [person.id, person]));
+ const context = messages.map((m) => {
+ const author = messageParticipant(m);
+ const person = author && people.get(author.id);
+ return {
+ author: person?.name ?? String(m.user ?? m.username ?? "Slack"),
+ ...(person ? { authorId: person.id } : {}),
+ ...(person?.avatarUrl ? { avatarUrl: person.avatarUrl } : {}),
+ text: typeof m.text === "string" ? m.text : "",
+ at: Math.round(Number(m.ts) * 1000),
+ ts: m.ts,
+ ...(root && m.ts !== root ? { reply: true } : {}),
+ images: (Array.isArray(m.files) ? m.files.filter(isObj) : [])
+ .filter((f) => typeof f.mimetype === "string" && f.mimetype.startsWith("image/"))
+ .map((f) => f.url_private)
+ .filter((url): url is string => typeof url === "string" && url.startsWith("https://"))
+ .slice(0, 4),
+ };
+ });
// Nearby channel context is selected by the drafting agent, not an arbitrary
// channel tail. Keep it separate from the authoritative thread snapshot.
const nearby =
@@ -141,7 +325,14 @@ export function createInboxSourceRefresh(deps: RefreshDeps): InboxSourceRefresh
await deps.items.annotate(
item.id,
{
- slack: { ...meta, isDirectMessage: direct, ...(root ? { threadTs: root } : {}) },
+ slack: {
+ ...meta,
+ isDirectMessage: direct,
+ ...(root ? { threadTs: root } : {}),
+ ...(typeof waiting?.user === "string" ? { userId: waiting.user } : {}),
+ },
+ participants: sender ? profiles.people : saved,
+ slackAvatarsRefreshAt: sender ? profiles.refreshAt : 0,
context: [...nearby, ...context],
sourceContextFetched: true,
sourceContextPartial: partial,
@@ -165,15 +356,25 @@ export function createInboxSourceRefresh(deps: RefreshDeps): InboxSourceRefresh
}
}
- async function one(owner: string, item: LoopItem): Promise<void> {
- const key = `${owner}:${item.id}:${item.sourceAt ?? 0}`;
- const pending = running.get(key);
- if (pending) return pending;
+ async function one(owner: string, item: LoopItem, mode?: "avatars"): Promise<void> {
+ const itemKey = `${owner}:${item.id}:${item.sourceAt ?? 0}`;
+ const key = `${itemKey}:${mode ?? "source"}`;
if (checked.has(key)) return;
+ const pending = running.get(itemKey);
+ if (pending) {
+ if (mode === "avatars") return;
+ await pending;
+ const latest = await deps.items.get(item.id);
+ if (latest && latest.sourceAt === item.sourceAt) return one(owner, latest, mode);
+ return;
+ }
const task = (async () => {
try {
- await refresh(owner, item);
+ if (mode === "avatars") await refreshAvatars(owner, item);
+ else await refresh(owner, item);
} catch (e) {
+ recordFailure(owner, `Inbox item ${item.id}`, e);
+ if (mode === "avatars") return;
await deps.items.annotate(
item.id,
{
@@ -183,22 +384,22 @@ export function createInboxSourceRefresh(deps: RefreshDeps): InboxSourceRefresh
);
} finally {
checked.set(key, true);
- running.delete(key);
+ running.delete(itemKey);
}
})();
- running.set(key, task);
+ running.set(itemKey, task);
return task;
}
- return async (owner, items) => {
- // Bound simultaneous Gmail reads. Slack is refreshed only for an opened item;
- // normal Slack reconciliation still comes from events and the existing sync.
- const start = positions.get(owner) ?? 0;
+ return async (owner, items, mode) => {
+ if (!(await deps.featureFlags.enabled("inbox_loops", personalScope(owner)))) return;
+ const positionKey = `${owner}:${mode ?? "source"}`;
+ const start = positions.get(positionKey) ?? 0;
const ordered = items.slice(start).concat(items.slice(0, start));
const deadline = now() + 3000;
let visited = 0;
for (; visited < ordered.length && now() < deadline; visited += 4)
- await Promise.all(ordered.slice(visited, visited + 4).map((item) => one(owner, item)));
+ await Promise.all(ordered.slice(visited, visited + 4).map((item) => one(owner, item, mode)));
// Slow sources must neither block the whole inbox nor starve later cards.
- if (items.length > 1) positions.set(owner, (start + visited) % items.length);
+ if (items.length > 1) positions.set(positionKey, (start + visited) % items.length);
};
}
diff --git a/src/loops/item-ledger.ts b/src/loops/item-ledger.ts
index 3357529b9..6cccdc0d6 100644
--- a/src/loops/item-ledger.ts
+++ b/src/loops/item-ledger.ts
@@ -14,6 +14,7 @@ import { createMemoryMap, type DurableMap } from "../persistence/durable-map.ts"
import { contentPart } from "../triggers/trigger-store.ts";
import { hashId } from "../util/crypto.ts";
import { randomUUID } from "node:crypto";
+import { isDeepStrictEqual } from "node:util";
interface EnqueueItemInput {
loopId: string;
@@ -77,7 +78,7 @@ export interface LoopItemLedger {
annotate(
id: string,
patch: LoopSourcePayload,
- opts?: { summary?: string; expectedSourceAt?: number },
+ opts?: { summary?: string; expectedSourceAt?: number; expectedSourcePayload?: LoopSourcePayload },
): Promise<LoopItem | null>;
appendThread(id: string, messages: Array<Omit<LoopThreadMessage, "id" | "at">>): Promise<LoopItem | null>;
setTriage(id: string, patch: TriagePatch, by: "agent" | "human"): Promise<LoopItem | null>;
@@ -89,7 +90,7 @@ export interface LoopItemLedger {
moveSource(from: string, to: string, source: string): Promise<void>;
summaries(
loopIds: string[],
- options?: { includeEmailClassification?: boolean },
+ options?: { includeInboxMetadata?: boolean },
): Promise<Array<Omit<LoopItem, "proposal" | "agentDrafts" | "thread" | "sourcePayload">>>;
queued(loopId: string, limit?: number): Promise<LoopItem[]>;
claim(id: string, claimedAt?: number, expectedLoopId?: string): Promise<LoopItem | null>;
@@ -302,7 +303,7 @@ export function createLoopItemLedger(
return { item: stored, created: stored.createdAt === candidate.createdAt };
},
async summaries(loopIds, options) {
- if (!options?.includeEmailClassification)
+ if (!options?.includeInboxMetadata)
return backing.select({
where: { field: "loopId", anyOfFold: loopIds },
omit: ["proposal", "agentDrafts", "thread", "sourcePayload"],
@@ -310,13 +311,22 @@ export function createLoopItemLedger(
const items = await backing.select({
where: { field: "loopId", anyOfFold: loopIds },
omit: ["proposal", "agentDrafts", "thread"],
- pickNested: { sourcePayload: ["source", "automated"] },
+ pickNested: { sourcePayload: ["source", "automated", "participants", "slackAvatarsRefreshAt"] },
});
return items.map(({ sourcePayload, ...item }) => {
const source = item.source ?? (typeof sourcePayload?.source === "string" ? sourcePayload.source : undefined);
return {
...item,
...(source !== undefined ? { source } : {}),
+ ...(source === "slack"
+ ? {
+ inboxPreview: {
+ ...item.inboxPreview,
+ participants: sourcePayload?.participants,
+ slackAvatarsRefreshAt: sourcePayload?.slackAvatarsRefreshAt,
+ },
+ }
+ : {}),
...(source === "gmail"
? { inboxPreview: { ...item.inboxPreview, automated: sourcePayload?.automated === true } }
: {}),
@@ -410,7 +420,11 @@ export function createLoopItemLedger(
const after = await update(id, (item) => {
applied = true;
const now = Date.now();
- if (opts?.expectedSourceAt !== undefined && item.sourceAt !== opts?.expectedSourceAt) {
+ if (
+ (opts?.expectedSourceAt !== undefined && item.sourceAt !== opts.expectedSourceAt) ||
+ (opts?.expectedSourcePayload !== undefined &&
+ !isDeepStrictEqual(item.sourcePayload, opts.expectedSourcePayload))
+ ) {
applied = false;
return item;
}
diff --git a/src/loops/ledger-view.ts b/src/loops/ledger-view.ts
index fc6a644fa..7bca432e6 100644
--- a/src/loops/ledger-view.ts
+++ b/src/loops/ledger-view.ts
@@ -76,14 +76,30 @@ export interface LedgerItemView {
updatedAt: number;
}
-export function ledgerItemView(item: LoopItem, loop: Pick<Loop, "triage">): LedgerItemView {
+export function agentSourcePayload(payload: LoopSourcePayload, source?: string): LoopSourcePayload {
+ if ((source ?? payload.source) !== "slack") return payload;
+ const result = { ...payload };
+ delete result.slackAvatarsRefreshAt;
+ for (const key of ["participants", "context"]) {
+ if (Array.isArray(result[key]))
+ result[key] = result[key].map((entry: unknown) => {
+ if (!entry || typeof entry !== "object" || Array.isArray(entry)) return entry;
+ const copy = { ...entry } as Record<string, unknown>;
+ delete copy.avatarUrl;
+ return copy;
+ });
+ }
+ return result;
+}
+
+export function ledgerItemView(item: LoopItem, loop: Pick<Loop, "triage">, forAgent = false): LedgerItemView {
const triage = visibleTriage(loop, item.triage);
return {
id: item.id,
loopId: item.loopId,
dedupeKey: item.sourceKey,
state: ledgerState(item),
- sourcePayload: item.sourcePayload ?? {},
+ sourcePayload: forAgent ? agentSourcePayload(item.sourcePayload ?? {}, item.source) : (item.sourcePayload ?? {}),
thread: item.thread ?? [],
attempts: item.attempts,
outputIds: item.outputIds,
diff --git a/src/loops/loop-fire.ts b/src/loops/loop-fire.ts
index 098561c11..b9caecf1d 100644
--- a/src/loops/loop-fire.ts
+++ b/src/loops/loop-fire.ts
@@ -28,7 +28,7 @@ import { collectVitals, evaluateGovernor, healthWorsened } from "./governor.ts";
import { unresolvedOutput } from "./output-store.ts";
import { decideShip, outputCandidate } from "./ship-gate.ts";
import { evaluateSuccess, type SuccessCheckResult, type SuccessVerdict } from "./success-evaluation.ts";
-import { consolidates, ledgerState, prioritizes } from "./ledger-view.ts";
+import { agentSourcePayload, consolidates, ledgerState, prioritizes } from "./ledger-view.ts";
import {
DEFAULT_CONSOLIDATE_INSTRUCTIONS,
DEFAULT_PRIORITIZE_INSTRUCTIONS,
@@ -111,7 +111,7 @@ function itemContextBlock(item: LoopItem): string {
dedupeKey: item.sourceKey,
state: ledgerState(item),
...(item.source ? { source: item.source } : {}),
- sourcePayload: item.sourcePayload ?? {},
+ sourcePayload: agentSourcePayload(item.sourcePayload ?? {}, item.source),
...(item.proposal ? { proposal: item.proposal.data } : {}),
thread: (item.thread ?? []).slice(-ITEM_THREAD_CONTEXT).map((message) => ({
role: message.role,
@@ -395,7 +395,9 @@ function workPrompt(loop: Loop, item: LoopItem, guidance?: string, similar: Loop
sourceKey: promptText(item.sourceKey),
loopId: loop.id,
itemId: item.id,
- ...(item.sourcePayload ? { sourcePayload: JSON.parse(promptText(JSON.stringify(item.sourcePayload))) } : {}),
+ ...(item.sourcePayload
+ ? { sourcePayload: JSON.parse(promptText(JSON.stringify(agentSourcePayload(item.sourcePayload, item.source)))) }
+ : {}),
...(item.sourceSummary ? { sourceSummary: promptText(item.sourceSummary) } : {}),
...(guidance ? { reviewerNote: promptText(guidance) } : {}),
...(similar.length
diff --git a/src/wiring.ts b/src/wiring.ts
index 62280b4ff..25c100d7e 100644
--- a/src/wiring.ts
+++ b/src/wiring.ts
@@ -3055,7 +3055,9 @@ export function serverDeps(
? {
loopSourceTokens: built.keychain,
inboxSourceRefresh: createInboxSourceRefresh({
+ featureFlags: built.featureFlags,
items: built.loops.items,
+ errors: built.errors,
tokens: built.keychain,
...(config.slack?.apiUrl ? { slackApiUrl: config.slack.apiUrl } : {}),
}),
diff --git a/test/inbox-selection.test.ts b/test/inbox-selection.test.ts
index df05eb201..10ba4e60a 100644
--- a/test/inbox-selection.test.ts
+++ b/test/inbox-selection.test.ts
@@ -214,7 +214,7 @@ test("moving records refuses collisions and a cached worker cannot claim a moved
});
test("disabled rollout cannot create defaults, migrate legacy Inbox, or update selection", async () => {
- const w = world(false);
+ const w = world(false, async () => assert.fail("disabled Inbox must not refresh sources"));
const legacy = await ensureInboxLoop(w.deps.store, "alice");
for (const method of ["GET", "PUT"]) assert.equal((await w.call(method, { loopIds: [] })).status, 403);
assert.equal((await w.deps.store.list()).length, 1);
@@ -658,3 +658,56 @@ test("inbox viewers are exactly the active candidates who can administer the loo
assert.equal((await ask({ loopId: "missing", candidates })).status, 404);
assert.equal((await ask({ loopId: group.id, candidates }, { actorId: "mallory" })).status, 403);
});
+
+test("the visible Slack feed includes fresh and cached avatars without returning message context", async () => {
+ const calls: string[][] = [];
+ const w = world(true, async (owner, items, mode) => {
+ if (mode !== "avatars") return;
+ assert.equal(owner, "alice");
+ calls.push(items.map((item) => item.id));
+ for (const item of items)
+ await w.deps.items.annotate(item.id, {
+ participants: [{ id: "U1", name: "Alex", avatarUrl: "https://avatars.slack-edge.com/alex.png" }],
+ slackAvatarsRefreshAt: Date.now() + 86_400_000,
+ });
+ });
+ const [, slack] = await ensureDefaultInboxLoops(w.deps.store, "alice");
+ await w.deps.items.ingest(
+ Array.from({ length: 45 }, (_, n) => ({
+ loopId: slack!.id,
+ dedupeKey: `slack-${n}`,
+ source: "slack",
+ sourceAt: 1000 + n,
+ sourcePayload: {
+ from: "Alex",
+ slack: { channelId: "D1", ts: `${n}.0`, userId: "U1" },
+ context: [{ author: "Alex", text: "private context" }],
+ },
+ proposal: { by: "agent" as const, data: { body: "draft" } },
+ })),
+ );
+ const feed = await w.call();
+ assert.equal(feed.status, 200);
+ assert.equal(calls.length, 1);
+ assert.equal(calls[0]!.length, 40);
+ assert.equal(feed.data.items.length, 40);
+ assert.deepEqual(new Set(calls[0]), new Set(feed.data.items.map((item: any) => item.id)));
+ assert.equal(feed.data.items[0].sourcePayload.participants[0].avatarUrl, "https://avatars.slack-edge.com/alex.png");
+ assert.equal(feed.data.items[0].sourcePayload.context, undefined);
+ assert.equal(feed.data.items[0].sourcePayload.slack, undefined);
+ await w.call("GET", null, `itemId=${feed.data.items[0].id}`);
+ assert.equal(calls.length, 1);
+ const get = w.deps.items.get.bind(w.deps.items);
+ let fullReads = 0;
+ w.deps.items.get = async (id) => {
+ fullReads++;
+ return get(id);
+ };
+ const cachedFeed = await w.call();
+ assert.equal(
+ cachedFeed.data.items[0].sourcePayload.participants[0].avatarUrl,
+ "https://avatars.slack-edge.com/alex.png",
+ );
+ assert.equal(fullReads, 0);
+ assert.deepEqual(calls.at(-1), []);
+});
diff --git a/test/inbox-source-refresh.test.ts b/test/inbox-source-refresh.test.ts
index 423ec7b7a..3935fe677 100644
--- a/test/inbox-source-refresh.test.ts
+++ b/test/inbox-source-refresh.test.ts
@@ -17,6 +17,7 @@ async function fixture(source = "gmail", meta: Record<string, unknown> = { threa
]);
return { items, item: (await items.byLoop("inbox"))[0]! };
}
+const featureFlags = { enabled: async () => true };
const tokens = { connectorAccessToken: async () => "synthetic-token" };
const json = (body: unknown) => Response.json(body);
@@ -24,6 +25,7 @@ test("Gmail reply sent outside QM closes the card, ignores drafts and recognizes
const { items, item } = await fixture();
let reads = 0;
const refresh = createInboxSourceRefresh({
+ featureFlags,
items,
tokens,
fetchImpl: async (url) => {
@@ -59,7 +61,12 @@ test("an old sent message or a newer inbound message does not close a Gmail item
[{ internalDate: "2000", labelIds: ["DRAFT"] }],
]) {
const { items, item } = await fixture();
- await createInboxSourceRefresh({ items, tokens, fetchImpl: async () => json({ messages }) })("owner", [item]);
+ await createInboxSourceRefresh({
+ featureFlags,
+ items,
+ tokens,
+ fetchImpl: async () => json({ messages }),
+ })("owner", [item]);
assert.equal((await items.get(item.id))!.status, "ready");
}
});
@@ -68,6 +75,7 @@ test("provider failure or missing connection preserves the item with an explicit
for (const connected of [true, false]) {
const { items, item } = await fixture();
await createInboxSourceRefresh({
+ featureFlags,
items,
tokens: { connectorAccessToken: async () => (connected ? "test" : null) },
fetchImpl: async () => new Response("unavailable", { status: 503 }),
@@ -82,6 +90,7 @@ test("provider failure or missing connection preserves the item with an explicit
test("a new inbound message during a provider read wins over the older own reply", async () => {
const { items, item } = await fixture();
await createInboxSourceRefresh({
+ featureFlags,
items,
tokens,
fetchImpl: async () => {
@@ -135,7 +144,12 @@ test("top-level/private-channel mentions fetch just their root and replies, neve
]) {
const { items, item } = await fixture("slack", meta);
const calls: string[] = [];
- await createInboxSourceRefresh({ items, tokens, fetchImpl: slackFetch(calls) })("owner", [item]);
+ await createInboxSourceRefresh({
+ featureFlags,
+ items,
+ tokens,
+ fetchImpl: slackFetch(calls),
+ })("owner", [item]);
const after = (await items.get(item.id))!;
assert.deepEqual(
(after.sourcePayload!.context as Array<{ text: string }>).map((m) => m.text),
@@ -151,19 +165,24 @@ test("top-level/private-channel mentions fetch just their root and replies, neve
test("Slack detects group DMs by conversation metadata, including C-prefixed IDs", async () => {
const { items, item } = await fixture("slack", { channelId: "C_GROUP_DM", ts: "1.0" });
const calls: string[] = [];
- await createInboxSourceRefresh({ items, tokens, fetchImpl: slackFetch(calls, { direct: true, own: true }) })(
- "owner",
- [item],
- );
+ await createInboxSourceRefresh({
+ featureFlags,
+ items,
+ tokens,
+ fetchImpl: slackFetch(calls, { direct: true, own: true }),
+ })("owner", [item]);
assert.ok(calls.some((p) => p.includes("conversations.history")));
assert.equal((await items.get(item.id))!.actionKind, "replied");
});
test("a partial Slack thread is displayed as partial but cannot resolve an item", async () => {
const { items, item } = await fixture("slack", { channelId: "C1", ts: "1.0" });
- await createInboxSourceRefresh({ items, tokens, fetchImpl: slackFetch([], { partial: true, own: true }) })("owner", [
- item,
- ]);
+ await createInboxSourceRefresh({
+ featureFlags,
+ items,
+ tokens,
+ fetchImpl: slackFetch([], { partial: true, own: true }),
+ })("owner", [item]);
const after = (await items.get(item.id))!;
assert.equal(after.status, "ready");
assert.equal(after.sourcePayload!.sourceContextPartial, true);
@@ -173,6 +192,7 @@ test("rate limiting is respected across different Slack items and never triggers
const { items, item } = await fixture("slack", { channelId: "C1", ts: "1.0" });
let reads = 0;
const refresh = createInboxSourceRefresh({
+ featureFlags,
items,
tokens,
fetchImpl: async (url) => {
@@ -192,6 +212,7 @@ test("slow Gmail reads have a total batch budget and later cards are visited on
let clock = 0;
let reads = 0;
const refresh = createInboxSourceRefresh({
+ featureFlags,
items,
tokens,
now: () => clock,
@@ -209,3 +230,629 @@ test("slow Gmail reads have a total batch budget and later cards are visited on
await refresh("owner", cards);
assert.equal(reads, 12);
});
+
+test("Slack avatars are durable, shared across concurrent cards, and refresh without reading conversations", 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 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.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);
+});
+
+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)"]) {
+ 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 } } }),
+ })("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 () => {
+ 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);
+ },
+ });
+ 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.inboxPreview?.participants, undefined);
+});
+
+test("a newer message during an avatar lookup cannot acquire the previous sender's photo", async () => {
+ const { items, item } = await fixture("slack", { channelId: "D1", ts: "1.0", userId: "U1" });
+ await createInboxSourceRefresh({
+ featureFlags,
+ items,
+ tokens,
+ fetchImpl: async () => {
+ await items.ingest([
+ {
+ loopId: "inbox",
+ dedupeKey: "ask",
+ source: "slack",
+ sourceAt: 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);
+});
+
+test("concurrent list and detail refreshes preserve the authoritative Slack thread metadata", async () => {
+ const { items, item } = await fixture("slack", { channelId: "C_GROUP_DM", ts: "1.0", userId: "U1" });
+ const refresh = createInboxSourceRefresh({
+ featureFlags,
+ items,
+ tokens,
+ fetchImpl: slackFetch([], { direct: true }),
+ });
+ await Promise.all([refresh("owner", [item]), refresh("owner", [item], "avatars")]);
+ const after = (await items.get(item.id))!;
+ assert.equal((after.sourcePayload!.slack as { isDirectMessage: boolean }).isDirectMessage, true);
+ assert.equal(after.sourcePayload!.sourceContextFetched, true);
+});
+
+test("partial profile failures keep saved photos and names while saving successful lookups", async () => {
+ const { 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,
+ })("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.equal(after.sourcePayload!.slackAvatarsRefreshAt, 61_000);
+ assert.deepEqual(after.proposal, item.proposal);
+ clock = 62_000;
+ let reads = 0;
+ await createInboxSourceRefresh({
+ featureFlags,
+ items,
+ tokens,
+ now: () => clock,
+ fetchImpl: async (url) => {
+ reads++;
+ return fetchImpl(url);
+ },
+ })("owner", [after], "avatars");
+ assert.equal(reads, 2);
+});
+
+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" };
+ await items.annotate(item.id, { participants: [saved], slackAvatarsRefreshAt: 99_000_000 });
+ const sourceFetch = slackFetch([]);
+ await createInboxSourceRefresh({
+ featureFlags,
+ items,
+ tokens,
+ now: () => 1000,
+ fetchImpl: async (url, init) =>
+ String(url).includes("users.info") ? new Response("unavailable", { status: 503 }) : sourceFetch(url, init),
+ })("owner", [(await items.get(item.id))!]);
+ const after = (await items.get(item.id))!;
+ assert.deepEqual(after.sourcePayload!.participants, [saved]);
+ assert.equal(after.sourcePayload!.slackAvatarsRefreshAt, 61_000);
+ for (const message of after.sourcePayload!.context as Array<Record<string, unknown>>) {
+ assert.equal(message.author, "Alex");
+ assert.equal(message.authorId, "U1");
+ assert.equal(message.avatarUrl, saved.avatarUrl);
+ }
+});
+
+test("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[] = [];
+ await createInboxSourceRefresh({
+ featureFlags,
+ items,
+ tokens,
+ 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) => ({
+ ts: `${i + 1}.0`,
+ thread_ts: "1.0",
+ user: `U${i + 1}`,
+ text: "Message",
+ })),
+ });
+ },
+ })("owner", [item]);
+ assert.deepEqual(lookedUp, ["U1", "U12", "U11", "U10", "U9", "U8", "U7", "U6"]);
+ const after = (await items.get(item.id))!;
+ assert.equal((after.sourcePayload!.participants as Array<{ id: string }>)[0]!.id, "U1");
+ const latest = (after.sourcePayload!.context as Array<{ avatarUrl?: string }>).slice(-6);
+ assert.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;
+ 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");
+ }
+ }
+});
+
+test("a partial source page cannot replace the waiting sender with an unrelated author", async () => {
+ for (const userId of [undefined, "U1"]) {
+ const { items, item } = await fixture("slack", { channelId: "D1", ts: "0.5", ...(userId ? { userId } : {}) });
+ await items.annotate(item.id, {
+ participants: [{ id: "U1", name: "Alex", avatarUrl: "https://avatars.slack-edge.com/alex.png" }],
+ });
+ const sourceFetch = slackFetch([], { direct: true });
+ const fetchImpl: typeof fetch = async (url, init) => {
+ const response = await sourceFetch(url, init);
+ if (!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))!]);
+ 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;
+ let release!: () => void;
+ const started = new Promise<void>((resolve) => {
+ begin = resolve;
+ });
+ const blocked = new Promise<void>((resolve) => {
+ release = resolve;
+ });
+ const sourceFetch = slackFetch([]);
+ const refresh = createInboxSourceRefresh({
+ featureFlags,
+ items,
+ tokens,
+ fetchImpl: async (url, init) => {
+ if (String(url).includes("conversations.info")) {
+ begin();
+ await blocked;
+ }
+ return sourceFetch(url, init);
+ },
+ });
+ const source = refresh("owner", [item]);
+ await started;
+ try {
+ const finished = await Promise.race([
+ refresh("owner", [item], "avatars").then(() => true),
+ new Promise<boolean>((resolve) => setTimeout(() => resolve(false), 100)),
+ ]);
+ assert.equal(finished, true);
+ } finally {
+ release();
+ await source;
+ }
+ assert.equal((await items.get(item.id))!.sourcePayload!.sourceContextFetched, true);
+});
+
+test("a second core's full refresh wins over a stale cosmetic profile refresh", async () => {
+ const { items, item } = await fixture("slack", { channelId: "C1", ts: "1.0", userId: "U1" });
+ let begin!: () => void;
+ let release!: () => void;
+ const started = new Promise<void>((resolve) => {
+ begin = resolve;
+ });
+ const blocked = new Promise<void>((resolve) => {
+ release = resolve;
+ });
+ const avatars = createInboxSourceRefresh({
+ 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" } },
+ });
+ },
+ })("owner", [item], "avatars");
+ await started;
+ const sourceFetch = slackFetch([], { own: true });
+ try {
+ await createInboxSourceRefresh({
+ featureFlags,
+ items,
+ tokens,
+ fetchImpl: async (url, init) => {
+ if (String(url).includes("auth.test")) return json({ ok: true, user_id: "OWNER" });
+ return sourceFetch(url, init);
+ },
+ })("owner", [item]);
+ } finally {
+ release();
+ await avatars;
+ }
+ const after = (await items.get(item.id))!;
+ assert.deepEqual(after.sourcePayload!.participants, [
+ { id: "U1", name: "Alex" },
+ { id: "U2", name: "Taylor" },
+ ]);
+ assert.equal(after.sourcePayload!.sourceContextFetched, true);
+ assert.equal((after.sourcePayload!.context as unknown[]).length, 2);
+});
+
+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({
+ featureFlags,
+ items,
+ tokens,
+ 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]);
+ const after = (await items.get(item.id))!;
+ assert.deepEqual(after.sourcePayload!.participants, []);
+ assert.equal(after.sourcePayload!.slackAvatarsRefreshAt, 0);
+ assert.equal(
+ (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 () => {
+ 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,
+ 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);
+ },
+ })("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.doesNotMatch(JSON.stringify(events), /private-credential/);
+ assert.equal((await items.get(item.id))!.status, "ready");
+ }
+});
+
+test("cosmetic refresh records ledger failures without rejecting the inbox request", async () => {
+ const { createErrorLog } = await import("../src/admin/error-log.ts");
+ const { items, item } = await fixture("slack", { channelId: "D1", ts: "1.0", userId: "U1" });
+ const errors = createErrorLog();
+ await createInboxSourceRefresh({
+ featureFlags,
+ items: {
+ ...items,
+ annotate: async () => {
+ throw new Error("database unavailable");
+ },
+ },
+ tokens,
+ errors,
+ fetchImpl: async () => json({ ok: true, user: { name: "Alex" } }),
+ })("owner", [item], "avatars");
+ const events = await errors.list();
+ assert.equal(events.length, 1);
+ assert.match(events[0]!.message, new RegExp(item.id));
+ assert.match(events[0]!.message, /database unavailable/);
+ assert.equal(events[0]!.scopeLabel, "personal:owner");
+});
+
+test("Inbox source refresh checks the owner rollout before credentials, reads, or writes in either mode", async () => {
+ const { createFeatureFlagStore } = await import("../src/feature-flags.ts");
+ const { createMemoryMap } = await import("../src/persistence/durable-map.ts");
+ const flags = createFeatureFlagStore(createMemoryMap());
+ await flags.setEnabled("inbox_loops", "personal:someone-else", true, "admin");
+ for (const mode of [undefined, "avatars"] as const) {
+ const { items, item } = await fixture("slack", { channelId: "D1", ts: "1.0", userId: "U1" });
+ const before = structuredClone(item);
+ const calls: string[] = [];
+ let credentials = 0;
+ const refresh = createInboxSourceRefresh({
+ items,
+ featureFlags: flags,
+ tokens: {
+ connectorAccessToken: async () => {
+ credentials++;
+ return "synthetic-token";
+ },
+ },
+ fetchImpl: slackFetch(calls),
+ });
+ await refresh("owner", [item], mode);
+ assert.equal(credentials, 0);
+ assert.deepEqual(calls, []);
+ assert.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);
+ const enriched = (await items.get(item.id))!;
+ assert.ok(enriched.sourcePayload?.participants);
+ await flags.setEnabled("inbox_loops", "personal:owner", false, "admin");
+ credentials = 0;
+ calls.length = 0;
+ await refresh("owner", [{ ...enriched, sourceAt: 3000 }], mode);
+ assert.equal(credentials, 0);
+ assert.deepEqual(calls, []);
+ assert.deepEqual(await items.get(item.id), enriched);
+ }
+});
diff --git a/test/loop-fire.test.ts b/test/loop-fire.test.ts
index 14eb20366..1f8641c4b 100644
--- a/test/loop-fire.test.ts
+++ b/test/loop-fire.test.ts
@@ -1070,3 +1070,40 @@ test("a triage dry run regroups every open item with draft instructions and writ
assert.ok(preview.every((entry) => entry.priority === "high" && entry.groupId));
assert.deepEqual(await s.items.byLoop(loop.id), before);
});
+
+test("Slack work and follow-up prompts preserve message images without repeating profile cosmetics", async () => {
+ const s = service((req) => {
+ if (stage(req) === "work") return '```json\n{"proposal":{"body":"Draft reply"},"outputs":[]}\n```';
+ return '```json\n{"outcome":"met","reason":"Ready"}\n```';
+ });
+ const loop = await makeLoop(s.loops, { sources: ["slack"], shipActions: [{ action: "send", gate: "hold" }] });
+ await s.items.ingest([
+ {
+ loopId: loop.id,
+ dedupeKey: "D1",
+ source: "slack",
+ sourcePayload: {
+ participants: [{ id: "U1", name: "Alex", avatarUrl: "https://example.com/avatar.png" }],
+ context: [
+ {
+ authorId: "U1",
+ author: "Alex",
+ text: "Review this image",
+ images: ["https://example.com/task.png"],
+ avatarUrl: "https://example.com/avatar.png",
+ },
+ ],
+ slackAvatarsRefreshAt: 12345,
+ },
+ },
+ ]);
+ await s.fire.fire(loop.id, "push:1", undefined, { enumerate: false });
+ const [item] = await s.items.byLoop(loop.id);
+ await s.fire.followUp(loop, item!, "Please revise", loop.owner);
+ for (const req of s.turns.filter((req) => stage(req) === "work" || req.text?.startsWith("[Loop item chat]"))) {
+ assert.doesNotMatch(req.text ?? "", /avatarUrl|slackAvatarsRefreshAt/);
+ assert.match(req.text ?? "", /task.png/);
+ assert.match(req.text ?? "", /Alex/);
+ }
+ assert.match(JSON.stringify((await s.items.get(item!.id))!.sourcePayload), /avatar.png/);
+});
diff --git a/test/loop-item-routes.test.ts b/test/loop-item-routes.test.ts
index ffeb275af..ea3f38357 100644
--- a/test/loop-item-routes.test.ts
+++ b/test/loop-item-routes.test.ts
@@ -860,6 +860,7 @@ test("inbox list refreshes open Gmail items before returning counts, but not ano
// Exercise the route with the real refresher via the same dependency used by wiring.
const { createInboxSourceRefresh } = await import("../src/loops/inbox-source-refresh.ts");
w.sourceRefresh = createInboxSourceRefresh({
+ featureFlags: { enabled: async () => true },
items: w.loops.items,
tokens: { connectorAccessToken: async () => "synthetic" },
fetchImpl: async (url) => {
@@ -1163,3 +1164,38 @@ test("only a person overrides triage, and archiving a whole group resolves its m
assert.equal(settled.actionKind, "consolidated");
assert.deepEqual(settled.sourcePayload, member.sourcePayload);
});
+
+test("an owner cannot trigger Slack avatar enrichment through item detail when Inbox is disabled", async () => {
+ const { createInboxSourceRefresh } = await import("../src/loops/inbox-source-refresh.ts");
+ const w = world();
+ const loop = await ensureInboxLoop(w.loops.store, "josh");
+ await w.loops.items.ingest([
+ {
+ loopId: loop.id,
+ dedupeKey: "D1",
+ source: "slack",
+ sourceAt: 1000,
+ sourcePayload: { slack: { channelId: "D1", ts: "1.0", userId: "U1" } },
+ },
+ ]);
+ const [item] = await w.loops.items.byLoop(loop.id);
+ const before = structuredClone(item);
+ const enabled = async (flag: string, scope: string) => {
+ assert.equal(flag, "inbox_loops");
+ assert.equal(scope, "personal:josh");
+ return false;
+ };
+ w.sourceRefresh = createInboxSourceRefresh({
+ items: w.loops.items,
+ featureFlags: { enabled },
+ tokens: { connectorAccessToken: async () => assert.fail("disabled Inbox must not read credentials") },
+ fetchImpl: async () => assert.fail("disabled Inbox must not call Slack"),
+ });
+ const result = await call(w, {
+ method: "GET",
+ path: `/v1/loops/${loop.id}/items/${item!.id}?refreshSource=1`,
+ flagEnabled: enabled,
+ });
+ assert.equal(result.status, 200);
+ assert.deepEqual(await w.loops.items.get(item!.id), before);
+});
diff --git a/test/loop-ledger.test.ts b/test/loop-ledger.test.ts
index 00ee57ed5..c93892f23 100644
--- a/test/loop-ledger.test.ts
+++ b/test/loop-ledger.test.ts
@@ -406,7 +406,9 @@ test("email classification projection is opt-in, scoped, and never changes store
assert.ok(query.omit?.includes("proposal"));
assert.ok(query.omit?.includes("thread"));
if (!query.omit?.includes("sourcePayload"))
- assert.deepEqual(query.pickNested, { sourcePayload: ["source", "automated"] });
+ assert.deepEqual(query.pickNested, {
+ sourcePayload: ["source", "automated", "participants", "slackAvatarsRefreshAt"],
+ });
const rows = await originalSelect(query);
for (const row of rows) assert.equal((row as LoopItem).sourcePayload?.privateDetail, undefined);
return rows;
@@ -414,7 +416,7 @@ test("email classification projection is opt-in, scoped, and never changes store
const before = await ledger.summaries([LOOP]);
assert.equal(before.length, 1);
assert.equal(before[0]!.inboxPreview!.automated, undefined);
- const classified = await ledger.summaries([LOOP], { includeEmailClassification: true });
+ const classified = await ledger.summaries([LOOP], { includeInboxMetadata: true });
assert.equal(classified.length, 1);
assert.equal(classified[0]!.inboxPreview!.automated, true);
assert.equal(classified[0]!.inboxPreview!.privateDetail, undefined);
@@ -427,7 +429,7 @@ test("flagged summaries classify payload-only legacy email without changing stor
const ledger = createLoopItemLedger();
await ledger.ingest([entry({ source: undefined, sourcePayload: { source: "gmail", automated: true } })]);
const before = await ledger.summaries([LOOP]);
- const [classified] = await ledger.summaries([LOOP], { includeEmailClassification: true });
+ const [classified] = await ledger.summaries([LOOP], { includeInboxMetadata: true });
assert.equal(classified!.source, "gmail");
assert.equal(classified!.inboxPreview!.automated, true);
assert.deepEqual(await ledger.summaries([LOOP]), before);
@@ -478,3 +480,86 @@ test("ingest batches per-loop locks and writes while resolving legacy IDs and du
assert.ok(await backing.get("legacy"));
assert.equal(await backing.get(original.id), null);
});
+
+test("conditional annotations reject changed source payloads even within the same clock tick", async (t) => {
+ t.mock.method(Date, "now", () => 1000);
+ const ledger = createLoopItemLedger();
+ await ledger.ingest([entry()]);
+ const [item] = await ledger.byLoop(LOOP);
+ const snapshot = structuredClone(item!.sourcePayload!);
+ const first = await ledger.annotate(
+ item!.id,
+ { participants: [{ id: "U1", name: "Alex" }] },
+ { expectedSourcePayload: snapshot },
+ );
+ assert.ok(first);
+ assert.equal(first.updatedAt, item!.updatedAt);
+ const stale = await ledger.annotate(item!.id, { participants: [] }, { expectedSourcePayload: snapshot });
+ assert.equal(stale, null);
+ assert.deepEqual((await ledger.get(item!.id))!.sourcePayload!.participants, [{ id: "U1", name: "Alex" }]);
+ const current = structuredClone(first.sourcePayload!);
+ assert.ok(
+ await ledger.annotate(
+ item!.id,
+ { participants: [{ id: "U2", name: "Taylor" }] },
+ { expectedSourcePayload: current },
+ ),
+ );
+});
+
+test("agent ledger views omit cosmetic Slack data without changing UI data or task images", async () => {
+ const ledger = createLoopItemLedger();
+ const payload = {
+ source: "slack",
+ slackAvatarsRefreshAt: 12345,
+ participants: [{ id: "U1", name: "Alex", avatarUrl: "https://example.com/avatar.png" }],
+ context: [
+ {
+ author: "Alex",
+ authorId: "U1",
+ avatarUrl: "https://example.com/avatar.png",
+ images: ["https://example.com/task.png"],
+ },
+ ],
+ task: { avatarUrl: "keep this task data" },
+ };
+ await ledger.ingest([entry({ source: "slack", sourcePayload: payload })]);
+ const [item] = await ledger.byLoop(LOOP);
+ const agent = ledgerItemView(item!, {}, true);
+ assert.deepEqual(agent.sourcePayload, {
+ source: "slack",
+ participants: [{ id: "U1", name: "Alex" }],
+ context: [{ author: "Alex", authorId: "U1", images: ["https://example.com/task.png"] }],
+ task: { avatarUrl: "keep this task data" },
+ });
+ assert.deepEqual(ledgerItemView(item!, {}).sourcePayload, payload);
+ assert.deepEqual((await ledger.get(item!.id))!.sourcePayload, payload);
+ assert.deepEqual(ledgerItemView({ ...item!, source: "gmail" }, {}, true).sourcePayload, payload);
+});
+
+test("ordinary ledger annotations leave previews unchanged and do not project avatar metadata", async () => {
+ const ledger = createLoopItemLedger();
+ await ledger.ingest([entry()]);
+ const [item] = await ledger.byLoop(LOOP);
+ const before = structuredClone(item!.inboxPreview);
+ const updated = await ledger.annotate(item!.id, {
+ title: "Updated title",
+ participants: [{ id: "U1", name: "Alex", avatarUrl: "https://example.com/avatar.png" }],
+ slackAvatarsRefreshAt: 12345,
+ });
+ assert.equal(updated!.sourcePayload!.title, "Updated title");
+ assert.deepEqual(updated!.inboxPreview, before);
+ const [summary] = await ledger.summaries([LOOP]);
+ assert.deepEqual(summary!.inboxPreview, before);
+ const [inboxSummary] = await ledger.summaries([LOOP], { includeInboxMetadata: true });
+ assert.equal(inboxSummary!.inboxPreview?.participants, undefined);
+ await ledger.ingest([entry({ source: "slack", dedupeKey: "slack", sourcePayload: updated!.sourcePayload })]);
+ const ordinary = (await ledger.summaries([LOOP])).find((item) => item.source === "slack")!;
+ assert.equal(ordinary.inboxPreview?.participants, undefined);
+ const projected = (await ledger.summaries([LOOP], { includeInboxMetadata: true })).find(
+ (item) => item.source === "slack",
+ )!;
+ assert.deepEqual(projected.inboxPreview?.participants, updated!.sourcePayload!.participants);
+ assert.equal(projected.inboxPreview?.slackAvatarsRefreshAt, 12345);
+ assert.equal("sourcePayload" in projected, false);
+});
diff --git a/test/loop-routes.test.ts b/test/loop-routes.test.ts
index 706d530cc..c1b35f477 100644
--- a/test/loop-routes.test.ts
+++ b/test/loop-routes.test.ts
@@ -842,3 +842,26 @@ test("loop icons can be set and reset by their owner, reject invalid input and r
}
assert.equal((await call(deps, "PATCH", `/v1/loops/${loop.id}`, { icon: "shield" }, "mallory")).status, 403);
});
+
+test("agent loop reads omit avatar metadata even when source is only in the payload", async () => {
+ const deps = services();
+ const created = await call(deps, "POST", "/v1/loops", CREATE);
+ const loop = (created.body as { loop: Loop }).loop;
+ const payload = {
+ source: "slack",
+ participants: [{ id: "U1", name: "Alex", avatarUrl: "https://example.com/avatar.png" }],
+ slackAvatarsRefreshAt: 12345,
+ };
+ await deps.items.ingest([{ loopId: loop.id, dedupeKey: "D1", sourcePayload: payload }]);
+ for (const mode of ["source", "capability"] as const) {
+ const response = await call(deps, "GET", `/v1/loops/${loop.id}`, undefined, "josh", mode);
+ assert.equal(response.status, 200);
+ const text = JSON.stringify(response.body);
+ if (mode === "source") assert.match(text, /avatar.png/);
+ else {
+ assert.doesNotMatch(text, /avatarUrl|slackAvatarsRefreshAt/);
+ assert.match(text, /Alex/);
+ }
+ }
+ assert.deepEqual((await deps.items.byLoop(loop.id))[0]!.sourcePayload, payload);
+});