Multiplayer agent harness for work.
Preserve Slack bot identity and file presentation metadata (#1251)
Regan Bell5944c5c12625
diff --git a/src/api/routes/surface-cache.ts b/src/api/routes/surface-cache.tsindex 1233f1ecb..74dd001e1 100644--- a/src/api/routes/surface-cache.ts+++ b/src/api/routes/surface-cache.ts@@ -19,6 +19,8 @@ export function toEvent(raw: unknown): IngestEvent | null {.map((f) => ({fileId: f.fileId as string,...(typeof f.name === "string" ? { name: f.name } : {}),+ ...(typeof f.title === "string" ? { title: f.title } : {}),+ ...(typeof f.size === "number" && Number.isSafeInteger(f.size) && f.size >= 0 ? { size: f.size } : {}),...(typeof f.mimetype === "string" ? { mimetype: f.mimetype } : {}),})): undefined;@@ -31,6 +33,7 @@ export function toEvent(raw: unknown): IngestEvent | null {...(raw.sub === null || (typeof raw.sub === "string" && raw.sub) ? { sub: raw.sub } : {}),...(typeof raw.subtype === "string" ? { subtype: raw.subtype } : {}),...(typeof raw.broadcast === "boolean" ? { broadcast: raw.broadcast } : {}),+ ...(typeof raw.botId === "string" ? { botId: raw.botId } : {}),...(typeof raw.authorId === "string" ? { authorId: raw.authorId } : {}),...(typeof raw.authorName === "string" ? { authorName: raw.authorName } : {}),...(typeof raw.text === "string" ? { text: raw.text } : {}),diff --git a/src/slack/events.ts b/src/slack/events.tsindex db26ed9db..dd825a2dc 100644--- a/src/slack/events.ts+++ b/src/slack/events.ts@@ -149,6 +149,8 @@ export function registerSlackEvents(...(identity.actor ? { actor: identity.actor } : {}),rawText: content.text,subtype: e.subtype ?? "",+ ...(e.bot_id ? { botId: e.bot_id } : {}),+ ...(e.bot_profile?.name || e.username ? { authorName: String(e.bot_profile?.name || e.username) } : {}),files: content.files,threadTs: e.thread_ts,ts: e.ts,@@ -275,6 +277,7 @@ export function registerSlackEvents(channel: m.channel,userId: identity.userId,...(identity.actor ? { actor: identity.actor } : {}),+ ...(m.bot_id ? { botId: m.bot_id } : {}),...(m.bot_profile?.name || m.username ? { authorName: String(m.bot_profile?.name || m.username) } : {}),rawText: content.text,subtype: m.subtype ?? "",@@ -321,6 +324,7 @@ export function registerSlackEvents(channel: m.channel,userId: identity.userId,...(identity.actor ? { actor: identity.actor } : {}),+ ...(m.bot_id ? { botId: m.bot_id } : {}),...(m.bot_profile?.name || m.username ? { authorName: String(m.bot_profile?.name || m.username) } : {}),rawText: content.text,subtype: m.subtype ?? "",diff --git a/src/slack/history.ts b/src/slack/history.tsindex 48d20043f..691baf3a3 100644--- a/src/slack/history.ts+++ b/src/slack/history.ts@@ -214,9 +214,17 @@ export function createSlackHistoryReader(deps: {...(m.sub ? { thread_ts: m.sub } : {}),...(m.self || m.authorId ? { user: m.self ? deps.ids.botUserId : m.authorId } : {}),...(m.authorName ? { username: m.authorName } : {}),- ...(m.bot ? { bot_id: m.self ? deps.ids.ownBotId : "mirrored-bot" } : {}),+ ...(m.bot ? { bot_id: m.botId ?? (m.self ? deps.ids.ownBotId : "mirrored-bot") } : {}),...(m.files?.length- ? { files: m.files.map((f) => ({ id: f.fileId, name: f.name, mimetype: f.mimetype })) }+ ? {+ files: m.files.map((f) => ({+ id: f.fileId,+ name: f.name,+ title: f.title,+ size: f.size,+ mimetype: f.mimetype,+ })),+ }: {}),}));if (mirrored.length && (!threadTs || rows.some((m) => m.ts === threadTs) || before)) {diff --git a/src/slack/mirror.ts b/src/slack/mirror.tsindex 10f1d5eb3..4b4600a6e 100644--- a/src/slack/mirror.ts+++ b/src/slack/mirror.ts@@ -47,6 +47,7 @@ export function slackMessageToIngestEvent(...(m.thread_ts !== undefined || !opts.partial? { sub: m.thread_ts && m.thread_ts !== m.ts ? String(m.thread_ts) : null }: {}),+ ...(m.bot_id ? { botId: String(m.bot_id) } : {}),...(m.user ? { authorId: String(m.user) } : {}),...(m.bot_profile?.name || m.username ? { authorName: String(m.bot_profile?.name || m.username) } : {}),text: opts.text ?? decodeSlackEntities(raw),@@ -55,7 +56,13 @@ export function slackMessageToIngestEvent(: {}),files: content.files.filter((file) => file.id)- .map((file) => ({ fileId: file.id!, name: file.name, mimetype: file.mimetype })),+ .map((file) => ({+ fileId: file.id!,+ name: file.name,+ ...(file.title !== undefined ? { title: file.title } : {}),+ ...(file.size !== undefined ? { size: file.size } : {}),+ mimetype: file.mimetype,+ })),...(Object.keys(opts.mentions ?? {}).length ? { mentions: opts.mentions } : {}),...(m.bot_id || m.bot_profile ? { bot: true } : {}),...(mentionsBot(raw, ids.botUserId) ? { mentionsSelf: true } : {}),diff --git a/src/slack/turn-handler.ts b/src/slack/turn-handler.tsindex 00fa1afba..57db56064 100644--- a/src/slack/turn-handler.ts+++ b/src/slack/turn-handler.ts@@ -83,6 +83,7 @@ interface Incoming {userId: string | undefined;actor?: ActorAssertion;authorName?: string;+ botId?: string;rawText: string;subtype?: string;files: SlackFile[];@@ -412,6 +413,9 @@ export function createTurnHandler(deps: {subtype: inc.subtype,files: inc.files,user: inc.userId,+ bot_id: inc.botId,+ username: inc.authorName,+ ...(inc.botAuthored ? { bot_profile: { name: inc.authorName } } : {}),thread_ts: inc.threadTs,channel_type: channelType(inc.kind, conversationKind),},diff --git a/src/surface-cache/surface-cache.ts b/src/surface-cache/surface-cache.tsindex 196df9434..307cdf324 100644--- a/src/surface-cache/surface-cache.ts+++ b/src/surface-cache/surface-cache.ts@@ -123,6 +123,14 @@ export function createPostgresSurfaceCache(id: "surface-cache/store/0005",statements: [`ALTER TABLE channel_messages ADD COLUMN IF NOT EXISTS subtype TEXT`],},+ {+ id: "surface-cache/store/0006",+ statements: [+ `ALTER TABLE channel_messages ADD COLUMN IF NOT EXISTS bot_id TEXT`,+ `ALTER TABLE channel_files ADD COLUMN IF NOT EXISTS title TEXT`,+ `ALTER TABLE channel_files ADD COLUMN IF NOT EXISTS size BIGINT`,+ ],+ },]);const liveFallback = opts.liveFallback;@@ -134,6 +142,7 @@ export function createPostgresSurfaceCache(...(r.sub != null ? { sub: r.sub as string } : {}),...(r.subtype != null ? { subtype: r.subtype as string } : {}),...(r.broadcast ? { broadcast: true } : {}),+ ...(r.bot_id != null ? { botId: r.bot_id as string } : {}),...(r.author_id != null ? { authorId: r.author_id as string } : {}),...(r.author_name != null ? { authorName: r.author_name as string } : {}),text: (r.text as string) ?? "",@@ -163,12 +172,13 @@ export function createPostgresSurfaceCache(const e = normalizeEvent(event);if (!e.container || !e.ts) continue;const res = await client.query(- `INSERT INTO channel_messages(org_id, container, ts, sub, author_id, author_name, text, mentions, self, bot, mentions_self, edited_at, deleted, handled, created_at, deleted_at, broadcast, subtype)- VALUES ($1,$2,$3,$4,$5,$6,$7,$8::jsonb,$9,$10,$11,$12,$13,$14,$15,$16,COALESCE($18::boolean, FALSE),$19)+ `INSERT INTO channel_messages(org_id, container, ts, sub, author_id, author_name, text, mentions, self, bot, mentions_self, edited_at, deleted, handled, created_at, deleted_at, broadcast, subtype, bot_id)+ VALUES ($1,$2,$3,$4,$5,$6,$7,$8::jsonb,$9,$10,$11,$12,$13,$14,$15,$16,COALESCE($18::boolean, FALSE),$19,$20)ON CONFLICT (org_id, container, ts) DO UPDATE SETsub = CASE WHEN EXCLUDED.deleted OR channel_messages.deleted OR COALESCE(EXCLUDED.edited_at, 0) < COALESCE(channel_messages.edited_at, 0) OR NOT $17 THEN channel_messages.sub ELSE EXCLUDED.sub END,subtype = CASE WHEN EXCLUDED.deleted OR channel_messages.deleted OR COALESCE(EXCLUDED.edited_at, 0) < COALESCE(channel_messages.edited_at, 0) THEN channel_messages.subtype ELSE COALESCE(EXCLUDED.subtype, channel_messages.subtype) END,broadcast = CASE WHEN EXCLUDED.deleted OR channel_messages.deleted OR COALESCE(EXCLUDED.edited_at, 0) < COALESCE(channel_messages.edited_at, 0) OR $18::boolean IS NULL THEN channel_messages.broadcast ELSE EXCLUDED.broadcast END,+ bot_id = CASE WHEN EXCLUDED.deleted OR channel_messages.deleted OR COALESCE(EXCLUDED.edited_at, 0) < COALESCE(channel_messages.edited_at, 0) THEN channel_messages.bot_id ELSE COALESCE(EXCLUDED.bot_id, channel_messages.bot_id) END,author_id = CASE WHEN EXCLUDED.deleted OR channel_messages.deleted OR COALESCE(EXCLUDED.edited_at, 0) < COALESCE(channel_messages.edited_at, 0) THEN channel_messages.author_id ELSE COALESCE(EXCLUDED.author_id, channel_messages.author_id) END,author_name = CASE WHEN EXCLUDED.deleted OR channel_messages.deleted OR COALESCE(EXCLUDED.edited_at, 0) < COALESCE(channel_messages.edited_at, 0) THEN channel_messages.author_name ELSE COALESCE(EXCLUDED.author_name, channel_messages.author_name) END,text = CASE WHEN EXCLUDED.deleted OR channel_messages.deleted OR COALESCE(EXCLUDED.edited_at, 0) < COALESCE(channel_messages.edited_at, 0) THEN channel_messages.text ELSE EXCLUDED.text END,@@ -204,6 +214,7 @@ export function createPostgresSurfaceCache(e.sub !== undefined,e.broadcast ?? null,e.subtype ?? null,+ e.botId ?? null,],);upserted += res.rowCount ?? 0;@@ -216,10 +227,20 @@ export function createPostgresSurfaceCache(for (const f of e.files) {if (!f.fileId) continue;await client.query(- `INSERT INTO channel_files(org_id, container, ts, file_id, name, mimetype, created_at)- VALUES ($1,$2,$3,$4,$5,$6,$7)- ON CONFLICT (org_id, container, ts, file_id) DO UPDATE SET name = EXCLUDED.name, mimetype = EXCLUDED.mimetype`,- [orgId, e.container, e.ts, f.fileId, f.name ?? null, f.mimetype ?? null, e.createdAt ?? now],+ `INSERT INTO channel_files(org_id, container, ts, file_id, name, mimetype, created_at, title, size)+ VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9)+ ON CONFLICT (org_id, container, ts, file_id) DO UPDATE SET name = EXCLUDED.name, mimetype = EXCLUDED.mimetype, title = EXCLUDED.title, size = EXCLUDED.size`,+ [+ orgId,+ e.container,+ e.ts,+ f.fileId,+ f.name ?? null,+ f.mimetype ?? null,+ e.createdAt ?? now,+ f.title ?? null,+ f.size ?? null,+ ],);}}@@ -288,7 +309,7 @@ export function createPostgresSurfaceCache(if (!opts.includeDeleted) conds.push("deleted = FALSE");args.push(limit);const rows = await q(- `SELECT channel_messages.*, (SELECT COUNT(*) FROM channel_messages replies WHERE replies.org_id = channel_messages.org_id AND replies.container = channel_messages.container AND replies.sub = channel_messages.ts AND replies.ts <> channel_messages.ts AND replies.deleted = FALSE) AS reply_count, (SELECT json_agg(json_build_object('fileId', f.file_id, 'name', f.name, 'mimetype', f.mimetype)) FROM channel_files f WHERE f.org_id = channel_messages.org_id AND f.container = channel_messages.container AND f.ts = channel_messages.ts) AS files FROM channel_messages WHERE ${conds.join(" AND ")} ORDER BY ts ${opts.oldestFirst ? "ASC" : "DESC"} LIMIT $${args.length}`,+ `SELECT channel_messages.*, (SELECT COUNT(*) FROM channel_messages replies WHERE replies.org_id = channel_messages.org_id AND replies.container = channel_messages.container AND replies.sub = channel_messages.ts AND replies.ts <> channel_messages.ts AND replies.deleted = FALSE) AS reply_count, (SELECT json_agg(json_build_object('fileId', f.file_id, 'name', f.name, 'mimetype', f.mimetype, 'title', f.title, 'size', f.size)) FROM channel_files f WHERE f.org_id = channel_messages.org_id AND f.container = channel_messages.container AND f.ts = channel_messages.ts) AS files FROM channel_messages WHERE ${conds.join(" AND ")} ORDER BY ts ${opts.oldestFirst ? "ASC" : "DESC"} LIMIT $${args.length}`,args,);const hit = rows.map(rowToMessage);@@ -466,6 +487,7 @@ export function createMemorySurfaceCache(opts: { liveFallback?: LiveFallback } =: {}),...((e.subtype ?? existing?.subtype) !== undefined ? { subtype: e.subtype ?? existing?.subtype } : {}),...((e.broadcast ?? existing?.broadcast) ? { broadcast: true } : {}),+ ...((e.botId ?? existing?.botId) ? { botId: e.botId ?? existing?.botId } : {}),...((e.authorId ?? existing?.authorId) ? { authorId: (e.authorId ?? existing?.authorId) as string } : {}),...((e.authorName ?? existing?.authorName)? { authorName: (e.authorName ?? existing?.authorName) as string }@@ -552,7 +574,15 @@ export function createMemorySurfaceCache(opts: { liveFallback?: LiveFallback } =(reply) => reply.sub === m.ts && reply.ts !== m.ts && !reply.deleted,).length,...(attached.length- ? { files: attached.map(({ fileId, name, mimetype }) => ({ fileId, name, mimetype })) }+ ? {+ files: attached.map(({ fileId, name, title, size, mimetype }) => ({+ fileId,+ name,+ ...(title !== undefined ? { title } : {}),+ ...(size !== undefined ? { size } : {}),+ mimetype,+ })),+ }: {}),};});diff --git a/src/surface-cache/types.ts b/src/surface-cache/types.tsindex 6234b2076..6707ef994 100644--- a/src/surface-cache/types.ts+++ b/src/surface-cache/types.ts@@ -5,10 +5,11 @@ export interface CachedMessage {broadcast?: boolean;subtype?: string;authorId?: string;+ botId?: string;authorName?: string;text: string;replyCount?: number;- files?: Array<{ fileId: string; name?: string; mimetype?: string }>;+ files?: Array<{ fileId: string; name?: string; title?: string; size?: number; mimetype?: string }>;mentions?: Record<string, string>;self?: boolean;bot?: boolean;@@ -25,6 +26,8 @@ export interface CachedFile {ts: string;fileId: string;name?: string;+ title?: string;+ size?: number;mimetype?: string;createdAt: number;}@@ -53,6 +56,7 @@ export interface IngestEvent {broadcast?: boolean;subtype?: string;authorId?: string;+ botId?: string;authorName?: string;text?: string;mentions?: Record<string, string>;@@ -63,7 +67,7 @@ export interface IngestEvent {deleted?: boolean;handled?: boolean;createdAt?: number;- files?: Array<{ fileId: string; name?: string; mimetype?: string }>;+ files?: Array<{ fileId: string; name?: string; title?: string; size?: number; mimetype?: string }>;members?: string[];containerName?: string;kind?: "channel" | "dm" | "group";diff --git a/test/slack-mirror-fidelity.test.ts b/test/slack-mirror-fidelity.test.tsindex 4b58908af..e32417855 100644--- a/test/slack-mirror-fidelity.test.ts+++ b/test/slack-mirror-fidelity.test.ts@@ -198,3 +198,93 @@ test("event mirroring preserves mention IDs for current-context rendering", asynconst context = buildContextWindow(shaped[1]!, { count: 20, nameById: new Map([["U1", "New name"]]) });assert.equal(context.messages[0]!.text, "Hi @New name and <@U2> & welcome");});++for (const postgres of [false, true]) {+ test(+ `bot and attachment presentation metadata roundtrip (${postgres ? "postgres" : "memory"})`,+ {+ skip: postgres && !process.env.DATABASE_URL,+ },+ async () => {+ const cache = postgres ? createPostgresSurfaceCache(process.env.DATABASE_URL!) : createMemorySurfaceCache();+ const container = `presentation-${Date.now()}-${postgres}`;+ const raw = {+ channel: container,+ ts: "1000",+ bot_id: "BOTHER",+ text: "Report",+ files: [{ id: "FLARGE", title: "Large report", size: 1_000_000_001, mimetype: "application/pdf" }],+ };+ const event = toEvent(slackMessageToIngestEvent(raw, ids))!;+ try {+ await cache.ingest([event]);+ await cache.ingest([{ container, ts: "1000", text: "Report", editedAt: 20 }]);+ await cache.ingest([+ {+ container,+ ts: "1000",+ text: "stale",+ editedAt: 10,+ botId: "BWRONG",+ files: [{ fileId: "FWRONG" }],+ handled: true,+ },+ ]);+ const stored = (await cache.readMessages(container))[0]!;+ assert.equal(stored.botId, "BOTHER");+ assert.equal(stored.files![0]!.title, "Large report");+ assert.equal(stored.files![0]!.size, 1_000_000_001);+ const core = { readSurfaceMessages: cache.readMessages } as SlackCoreClient;+ const client = {+ conversations: { replies: async () => ({ messages: [raw] }) },+ bots: {+ info: async ({ bot }: { bot: string }) => {+ assert.equal(bot, "BOTHER");+ return { bot: { name: "Report bot" } };+ },+ },+ };+ const views = [];+ for (const source of ["live", "mirror"] as const) {+ const serializer = createConversationSerializer({+ ids,+ directory,+ externalParticipantsEnabled: async () => true,+ readHistory: createSlackHistoryReader({ core, ids, source }),+ });+ const result = await serializer.serializeSlackConversation(+ client,+ {+ kind: "channel",+ channel: container,+ threadTs: "1000",+ ts: "1001",+ rawText: "question",+ userId: "U1",+ files: [],+ },+ { audience: [] },+ );+ views.push(result.view);+ }+ assert.deepEqual(views[1]!.messages, views[0]!.messages);+ assert.equal(views[1]!.messages[0]!.authorId, "BOTHER");+ assert.equal(views[1]!.messages[0]!.name, "Report bot");+ assert.deepEqual(views[1]!.files, views[0]!.files);+ assert.deepEqual(views[1]!.omittedFiles, [{ name: "Large report", reason: "too-big" }]);+ await cache.ingest([{ container, ts: "1000", deleted: true }]);+ await cache.ingest([{ ...event, botId: "BWRONG", editedAt: 30 }]);+ assert.equal((await cache.readMessages(container, { includeDeleted: true }))[0]!.botId, "BOTHER");+ } finally {+ await cache.close();+ }+ },+ );+}++test("HTTP ingestion rejects invalid file sizes", () => {+ for (const size of [-1, Infinity, NaN, 0.5, Number.MAX_SAFE_INTEGER + 1, "10"]) {+ assert.equal(toEvent({ container: "C", ts: "1", files: [{ fileId: "F", size }] })!.files![0]!.size, undefined);+ }+ assert.equal(toEvent({ container: "C", ts: "1", files: [{ fileId: "F", size: 0 }] })!.files![0]!.size, 0);+});diff --git a/test/slack-mirror-ingestion.test.ts b/test/slack-mirror-ingestion.test.tsindex f6b2ca3f3..d1e789187 100644--- a/test/slack-mirror-ingestion.test.ts+++ b/test/slack-mirror-ingestion.test.ts@@ -758,3 +758,24 @@ test("untyped edit channel lookup failure withholds acknowledgement for retry",assert.equal(acks, 0);assert.equal(f.events.length, 0);});++test("mention, DM and thread dispatch preserve bot identity and presentation name", async () => {+ for (const path of ["mention", "dm", "thread"]) {+ const f = fixture({ external: true, stake: async () => true });+ await f.fire({+ type: path === "mention" ? "app_mention" : "message",+ channel: path === "dm" ? "D1" : "C1",+ channel_type: path === "dm" ? "im" : "channel",+ ts: "2",+ ...(path === "thread" ? { thread_ts: "1" } : {}),+ user: "U1",+ bot_id: "BOTHER",+ bot_profile: { name: "Report bot" },+ text: path === "mention" ? "<@UBOT> report" : "report",+ });+ assert.equal(f.dispatches.length, 1, path);+ assert.equal(f.dispatches[0][1].botId, "BOTHER", path);+ assert.equal(f.dispatches[0][1].authorName, "Report bot", path);+ assert.equal(f.dispatches[0][1].botAuthored, true, path);+ }+});