Skip to content

armgit / qm

Public Imported from GitHub
0

Multiplayer agent harness for work.

Read current Slack reactions through the context API (#2556)

Joshua France1c0b71e69b78
diff --git a/src/api/agent-api-catalog.ts b/src/api/agent-api-catalog.ts
index 213fefacd..1f523b1ee 100644
--- a/src/api/agent-api-catalog.ts
+++ b/src/api/agent-api-catalog.ts
@@ -482,7 +482,7 @@ const FAMILIES: AgentApiFamily[] = [
method: "POST",
path: "/v1/surface-context",
summary:
- "fetch recent messages from a channel/DM YOU can see (count/before/match) — a private channel only if you're a member; directory-resolved, never a raw address",
+ "fetch recent messages from a channel/DM YOU can see (count/before/match) — a private channel only if you're a member; live:true reads Slack directly for current reaction counts (reactions:[] means none), with no mirror fallback on failure; omitted uses configured history; directory-resolved, never a raw address",
},
{
method: "POST",
diff --git a/src/api/routes/context.ts b/src/api/routes/context.ts
index cdc791f15..2372ec65a 100644
--- a/src/api/routes/context.ts
+++ b/src/api/routes/context.ts
@@ -94,6 +94,7 @@ async function createSurfaceContextRequest(ctx: ApiCtx): Promise<void> {
...(await rateLimitRecipient(ctx)),
...(before ? { before } : {}),
...(match ? { match } : {}),
+ ...(b.live === true ? { live: true } : {}),
};
const request = await app.createContextRequest(resolved.source, query);
return awaitFulfillment(ctx, request.id, query.channelName);
diff --git a/src/slack/conversation.ts b/src/slack/conversation.ts
index b63aeac29..b93904f9c 100644
--- a/src/slack/conversation.ts
+++ b/src/slack/conversation.ts
@@ -11,6 +11,7 @@ export interface ContextWireMessage {
text: string;
threadTs?: string;
files?: string[];
+ reactions?: ReactionTally[];
}
const MAX_CONTEXT_MESSAGE_CHARS = 600;
@@ -39,6 +40,7 @@ export function buildContextWindow(
text: clipMessage(resolveMentions(m.text ?? "", opts.nameById), MAX_CONTEXT_MESSAGE_CHARS),
...(m.parentTs ? { threadTs: m.parentTs } : {}),
...(m.files?.length ? { files: m.files } : {}),
+ ...(m.reactions ? { reactions: m.reactions } : {}),
};
});
const droppedMatches = matched.length > kept.length;
diff --git a/src/slack/history.ts b/src/slack/history.ts
index d3cdf75c0..b5f39a030 100644
--- a/src/slack/history.ts
+++ b/src/slack/history.ts
@@ -25,6 +25,7 @@ export type SlackHistoryReader = (
threadTs?: string,
before?: string,
expandThreads?: boolean,
+ live?: boolean,
) => Promise<SlackHistoryPage>;
const MIRROR_CONTEXT_NOTE =
@@ -215,7 +216,13 @@ export function createSlackHistoryReader(deps: {
const backfilled = new Set<string>();
let shadowPending = false;
- return async (client, channel, threadTs, before, expandThreads) => {
+ return async (client, channel, threadTs, before, expandThreads, live) => {
+ if (live) {
+ const page = await liveHistory(client, channel, threadTs, before, expandThreads);
+ if (threadTs && page.hasMore)
+ throw new Error("Live Slack thread exceeds the history limit; its replies could not be read completely.");
+ return page;
+ }
if (deps.source !== "mirror") {
const live = await liveHistory(client, channel, threadTs, before, expandThreads);
if (deps.source === "shadow" && !shadowPending) {
diff --git a/src/slack/surface-context.ts b/src/slack/surface-context.ts
index 3dcd459d8..4064412b9 100644
--- a/src/slack/surface-context.ts
+++ b/src/slack/surface-context.ts
@@ -80,8 +80,10 @@ export function createSurfaceContextFulfiller(deps: {
channel: string,
threadTs: string | undefined,
before: string | undefined,
+ live: boolean,
): Promise<{ raw: SlackHistoryMessage[]; hasMore: boolean; note?: string }> {
- if (deps.readHistory) return deps.readHistory(client, channel, threadTs, before);
+ if (deps.readHistory) return deps.readHistory(client, channel, threadTs, before, false, live);
+ if (live) throw new Error("Live Slack history is unavailable.");
const page = before ? { latest: before, inclusive: false } : {};
if (threadTs) {
const { messages, hasMore } = parseMessageList(
@@ -251,9 +253,9 @@ export function createSurfaceContextFulfiller(deps: {
);
const before = typeof q.before === "string" && q.before ? q.before : undefined;
const outcomes = await Promise.allSettled([
- fetchContextHistory(client, channel, undefined, before),
+ fetchContextHistory(client, channel, undefined, before, q.live === true),
threadTs
- ? fetchContextHistory(client, channel, threadTs, before)
+ ? fetchContextHistory(client, channel, threadTs, before, q.live === true)
: Promise.resolve<{ raw: SlackHistoryMessage[]; hasMore: boolean }>({ raw: [], hasMore: false }),
]);
const byTs = new Map<string, SlackHistoryMessage>();
@@ -274,10 +276,16 @@ export function createSurfaceContextFulfiller(deps: {
}
const raw = [...byTs.values()];
const failure = outcomes.find((outcome) => outcome.status === "rejected");
+ if (q.live === true && failure?.status === "rejected") throw failure.reason;
+ if (q.live === true && threadTs && outcomes[0]?.status === "fulfilled" && outcomes[0].value.hasMore)
+ throw new Error("Live Slack thread context includes truncated channel history; read the channel separately.");
if (!raw.length && failure?.status === "rejected") throw failure.reason;
const note = [...notes].join(" ");
const nameById = new Map<string, string>();
const shaped = await serializer.shapeRecentMessages(client, raw, "", nameById);
+ if (q.live === true && hasMore && !shaped.length)
+ throw new Error("Live Slack history contains only filtered messages; an earlier page could not be located.");
+ if (q.live === true) for (const message of shaped) message.reactions ??= [];
await post({
...buildContextWindow(shaped, {
count,
diff --git a/src/types.ts b/src/types.ts
index 405c4fb6d..431925f47 100644
--- a/src/types.ts
+++ b/src/types.ts
@@ -528,6 +528,7 @@ export interface SurfaceContextQuery {
viewer?: string;
before?: string;
match?: string;
+ live?: boolean;
searchAll?: string;
viewerToken?: string;
file?: { ts: string; threadTs?: string; name?: string };
diff --git a/test/slack-conversation.test.ts b/test/slack-conversation.test.ts
index 56ae1f23a..b25bce2d0 100644
--- a/test/slack-conversation.test.ts
+++ b/test/slack-conversation.test.ts
@@ -98,6 +98,23 @@ test("buildContextWindow labels self messages, resolves mentions, threads, files
assert.ok(self.text.length <= 601 && self.text.endsWith("…"), "long text is clipped");
});
+test("buildContextWindow preserves reaction counts without inventing missing reaction data", () => {
+ const w = buildContextWindow(
+ [
+ ctxMsg("1700000001.000100", "agent", "completed", {
+ isSelf: true,
+ reactions: [{ name: "white_check_mark", count: 2 }],
+ }),
+ ctxMsg("1700000002.000100", "Alice", "waiting", { reactions: [] }),
+ ctxMsg("1700000003.000100", "Bob", "search result"),
+ ],
+ { count: 10 },
+ );
+ assert.deepEqual(w.messages[0]!.reactions, [{ name: "white_check_mark", count: 2 }]);
+ assert.deepEqual(w.messages[1]!.reactions, []);
+ assert.equal(Object.hasOwn(w.messages[2]!, "reactions"), false);
+});
+
test("recentWindow keeps the contiguous recent window — a NON-latest message in it is not dropped", () => {
const candidates = [
{ ts: "1700000000.000001", name: "Carol", text: "Yeah it's pretty nice", authorId: "U_CAROL" },
diff --git a/test/slack-mirror-context.test.ts b/test/slack-mirror-context.test.ts
index c7bc5d040..a40e6d948 100644
--- a/test/slack-mirror-context.test.ts
+++ b/test/slack-mirror-context.test.ts
@@ -428,7 +428,7 @@ test("automatic context keeps the thread parent and recent exchange but excludes
);
});
-for (const source of ["live", "mirror"] as const) {
+for (const source of ["live", "mirror", "explicit-live"] as const) {
test(`own status cards are excluded from ${source} history and backfill`, async () => {
const f = fixture();
const messages = [
@@ -437,15 +437,123 @@ for (const source of ["live", "mirror"] as const) {
{ user: "UBOT", ts: "3", text: "ordinary answer" },
{ user: "UOTHER", ts: "4", text: "other bot task", blocks: [{ type: "task_card", task_id: "qm_status:other" }] },
];
- const read = createSlackHistoryReader({ core: f.core, ids, source });
+ const read = createSlackHistoryReader({
+ core: f.core,
+ ids,
+ source: source === "explicit-live" ? "mirror" : source,
+ });
const client = { conversations: { history: async () => ({ messages }), replies: async () => ({ messages }) } };
- const result = await read(client, "C1", "1");
+ const result = await read(client, "C1", "1", undefined, false, source === "explicit-live");
assert.deepEqual(
result.raw.map((m) => m.ts),
["1", "3", "4"],
);
assert.ok(!(await f.cache.readMessages("C1", { limit: 100 })).some((m) => m.ts === "2"));
- const expanded = await read(client, "C1", undefined, undefined, true);
+ const expanded = await read(client, "C1", undefined, undefined, true, source === "explicit-live");
assert.ok(!expanded.raw.some((m) => m.ts === "2"));
});
}
+
+test("explicit live context verifies reactions and never substitutes mirrored data on failure", async () => {
+ const { createSurfaceContextFulfiller } = await import("../src/slack/surface-context.ts");
+ const { core, client } = fixture();
+ const calls: unknown[] = [];
+ const historyClient = {
+ conversations: {
+ history: async (args: unknown) => {
+ calls.push(args);
+ return {
+ messages: [
+ { ts: "2.5", user: "UBOT", text: "Working", blocks: [{ type: "task_card", task_id: "qm_status:test" }] },
+ {
+ ts: "2.0",
+ text: "complete",
+ user: "U1",
+ reactions: [{ name: "white_check_mark", count: 2, users: ["U2"] }],
+ },
+ { ts: "1.0", text: "waiting", user: "U1" },
+ ],
+ has_more: true,
+ };
+ },
+ replies: async () => ({ messages: [{ ts: "1.0", text: "waiting", user: "U1" }] }),
+ },
+ };
+ const readHistory = createSlackHistoryReader({ core, ids, source: "mirror", historyClient });
+ let outcome: any;
+ const fulfiller = createSurfaceContextFulfiller({
+ core: {
+ fulfillContextRequest: async (_id, result) => {
+ outcome = result;
+ },
+ } as SlackCoreClient,
+ directory,
+ serializer: createConversationSerializer({
+ ids,
+ directory,
+ readHistory,
+ externalParticipantsEnabled: async () => false,
+ }),
+ botToken: "test",
+ clientOptions: {},
+ historyClient,
+ readHistory,
+ });
+ const request = {
+ id: "live",
+ query: { conversationTarget: "C1", count: 2, before: "3.0", live: true },
+ } as import("../src/api/slack-core-client.ts").SurfaceContextRequest;
+ await fulfiller.fulfillSurfaceContext(client, request);
+ assert.equal(outcome.error, undefined);
+ assert.deepEqual(
+ outcome.result.messages.map((m: any) => m.reactions),
+ [[], [{ name: "white_check_mark", count: 2 }]],
+ );
+ assert.deepEqual(calls, [{ channel: "C1", limit: 200, latest: "3.0", inclusive: false }]);
+ assert.equal(outcome.result.hasMore, true);
+ assert.equal(outcome.result.nextBefore, "1.0");
+ request.query.conversationTarget = "C1:1.0";
+ await fulfiller.fulfillSurfaceContext(client, request);
+ assert.match(outcome.error, /truncated channel history/);
+ assert.equal(outcome.result, undefined);
+ historyClient.conversations.replies = async () => {
+ throw new Error("missing_scope");
+ };
+ await fulfiller.fulfillSurfaceContext(client, request);
+ assert.match(outcome.error, /missing_scope/);
+ assert.equal(outcome.result, undefined);
+ historyClient.conversations.replies = async () => ({ messages: [{ ts: "1.0", text: "waiting", user: "U1" }] });
+ request.query.conversationTarget = "C1";
+ historyClient.conversations.history = async () => {
+ throw new Error("live source unavailable");
+ };
+ await fulfiller.fulfillSurfaceContext(client, request);
+ assert.match(outcome.error, /live source unavailable/);
+ assert.equal(outcome.result, undefined);
+ request.query.conversationTarget = "C1:1.0";
+ await fulfiller.fulfillSurfaceContext(client, request);
+ assert.match(outcome.error, /live source unavailable/);
+ assert.equal(outcome.result, undefined);
+ request.query.conversationTarget = "C1";
+ historyClient.conversations.history = async () => ({
+ messages: [{ ts: "2.0", subtype: "channel_join", text: "joined", user: "U1" }],
+ has_more: true,
+ });
+ await fulfiller.fulfillSurfaceContext(client, request);
+ assert.match(outcome.error, /only filtered messages/);
+ assert.equal(outcome.result, undefined);
+});
+
+test("explicit live reads reject truncated threads instead of returning an unusable backward cursor", async () => {
+ const f = fixture();
+ const read = createSlackHistoryReader({ core: f.core, ids, source: "mirror", managed: true });
+ const client = {
+ conversations: {
+ replies: async ({ limit }: { limit: number }) => ({
+ messages: Array.from({ length: limit }, (_, i) => ({ ts: `${i + 1}.0`, text: `reply ${i}` })),
+ has_more: true,
+ }),
+ },
+ };
+ await assert.rejects(read(client, "C1", "1.0", undefined, false, true), /thread exceeds the history limit/);
+});
diff --git a/test/surface-context.test.ts b/test/surface-context.test.ts
index 0b2bd3879..bc34fe8e0 100644
--- a/test/surface-context.test.ts
+++ b/test/surface-context.test.ts
@@ -128,6 +128,14 @@ describe("surface-context pulls", async () => {
assert.deepEqual((pending as any).requests, []);
});
+ it("passes an explicit live read through the authorized context route", async () => {
+ const asking = post("/v1/surface-context", { live: true }, { "x-agent-capability": await cap() });
+ const query = await fulfillNext(() => ({ messages: [] }));
+ assert.equal(query.live, true);
+ assert.equal(query.conversationTarget, "C9:1700.0001");
+ assert.equal((await asking).status, 200);
+ });
+
it("only live capabilities supply the original requester target, ignoring body overrides", async () => {
for (const path of ["/v1/surface-context", "/v1/surface-file"]) {
for (const liveActor of [true, false]) {