Skip to content

armgit / qm

Public Imported from GitHub
0

Multiplayer agent harness for work.

Default shared Slack history reads to 15 messages (#1263)

Regan Bell32590bdc6f01
diff --git a/src/core/orchestrator/surface-tools.ts b/src/core/orchestrator/surface-tools.ts
index 84b63c3b9..e32f60224 100644
--- a/src/core/orchestrator/surface-tools.ts
+++ b/src/core/orchestrator/surface-tools.ts
@@ -35,7 +35,6 @@ import { adminSessionUrl } from "../../util/admin-links.ts";
import { headLooksLikeText, replaceThreadSegment, type TurnPostKeys } from "./turn-helpers.ts";
import type { OrchestratorDeps, OrchestratorInput } from "./types.ts";
-const SURFACE_READ_DEFAULT = 100;
const SURFACE_READ_MAX = 200;
const SURFACE_SEARCH_DEFAULT = 10;
const SURFACE_SEARCH_MAX = 40;
@@ -295,12 +294,11 @@ export function createSurfaceToolDeps(ctx: SurfaceToolsContext): SurfaceToolDeps
readThread: async (opts?: { limit?: number }) => {
if (!deps.surfaceContext) return { ok: false, message: "the surface can't be read from this turn" };
if (!currentDestination.target) return { ok: false, message: "this conversation has no thread to read" };
- const count = Math.max(1, Math.min(SURFACE_READ_MAX, opts?.limit ?? SURFACE_READ_DEFAULT));
const result = await deps.surfaceContext.pull(input.surface ?? "unknown", {
conversationTarget: currentDestination.target,
viewer: actor.id,
...rateLimitRecipient,
- count,
+ ...(opts?.limit !== undefined ? { count: Math.max(1, Math.min(SURFACE_READ_MAX, opts.limit)) } : {}),
});
if (!result) return { ok: false, message: "the surface didn't answer in time" };
if (result.note && !result.messages?.length) return { ok: false, message: result.note };
diff --git a/src/slack/history-rate-limit.ts b/src/slack/history-rate-limit.ts
index 4f518dd91..087d29c28 100644
--- a/src/slack/history-rate-limit.ts
+++ b/src/slack/history-rate-limit.ts
@@ -1,3 +1,5 @@
+export const SHARED_SLACK_HISTORY_LIMIT = 15;
+
export function slackHistoryRateLimitMessage(
error: unknown,
opts: { setupUrl?: string; managed?: boolean; format?: "slack" } = {},
diff --git a/src/slack/history.ts b/src/slack/history.ts
index d68526aff..6de83aceb 100644
--- a/src/slack/history.ts
+++ b/src/slack/history.ts
@@ -2,7 +2,7 @@ import { slackMessageToIngestEvent } from "./mirror.ts";
import { messageWithForwardedContent } from "./forwards.ts";
import type { SlackContextSource } from "./config.ts";
import { decodeSlackEntities } from "./lib.ts";
-import { slackHistoryRateLimitMessage } from "./history-rate-limit.ts";
+import { SHARED_SLACK_HISTORY_LIMIT, slackHistoryRateLimitMessage } from "./history-rate-limit.ts";
import type { SlackCoreClient } from "../api/slack-core-client.ts";
import type { CachedMessage } from "../surface-cache/types.ts";
import type { BotIdentity } from "./directory.ts";
@@ -37,6 +37,7 @@ export function createSlackHistoryReader(deps: {
setupUrl?: string;
historyClient?: { conversations: { history(args: any): Promise<unknown>; replies(args: any): Promise<unknown> } };
}): SlackHistoryReader {
+ const limit = deps.managed ? SHARED_SLACK_HISTORY_LIMIT : 200;
async function liveHistory(
client: any,
channel: string,
@@ -45,7 +46,7 @@ export function createSlackHistoryReader(deps: {
expandThreads = false,
): Promise<SlackHistoryPage> {
const historyClient = deps.historyClient ?? client;
- const paging = { channel, limit: 200, ...(before ? { latest: before, inclusive: false } : {}) };
+ const paging = { channel, limit, ...(before ? { latest: before, inclusive: false } : {}) };
const page = parseMessageList(
threadTs
? await historyClient.conversations.replies({ ...paging, ts: threadTs })
@@ -58,7 +59,7 @@ export function createSlackHistoryReader(deps: {
parents.map(async (m) => {
try {
return {
- page: parseMessageList(await historyClient.conversations.replies({ channel, ts: m.ts, limit: 200 })),
+ page: parseMessageList(await historyClient.conversations.replies({ channel, ts: m.ts, limit })),
failed: false,
};
} catch {
@@ -83,23 +84,24 @@ export function createSlackHistoryReader(deps: {
threadTs?: string,
before?: string,
expandThreads = false,
+ pageLimit = 200,
): Promise<{ rows: CachedMessage[]; hasMore: boolean; truncatedExpansions?: number }> {
const read = deps.core.readSurfaceMessages!;
- const options = { limit: 201, noFallback: true, ...(before ? { before } : {}) };
+ const options = { limit: pageLimit + 1, noFallback: true, ...(before ? { before } : {}) };
if (threadTs) {
const [parents, replies] = await Promise.all([
read(channel, { at: threadTs, noFallback: true, ...(before ? { before } : {}) }),
read(channel, { ...options, sub: threadTs, oldestFirst: true }),
]);
const rows = [...parents, ...replies];
- return { rows: rows.slice(0, 200), hasMore: rows.length > 200 };
+ return { rows: rows.slice(0, pageLimit), hasMore: rows.length > pageLimit };
}
const rootPage = await read(channel, { ...options, channelHistory: true });
- const roots = rootPage.slice(-200);
- const hasMore = rootPage.length > 200;
+ const roots = rootPage.slice(-pageLimit);
+ const hasMore = rootPage.length > pageLimit;
if (!expandThreads) return { rows: roots, hasMore };
const parents = roots.filter((m) => (m.replyCount ?? 0) > 0).slice(-5);
- const expanded = await Promise.all(parents.map((m) => mirrorHistory(channel, m.ts)));
+ const expanded = await Promise.all(parents.map((m) => mirrorHistory(channel, m.ts, undefined, false, pageLimit)));
return {
rows: [...new Map([...roots, ...expanded.flatMap((page) => page.rows)].map((m) => [m.ts, m])).values()],
hasMore,
@@ -116,7 +118,7 @@ export function createSlackHistoryReader(deps: {
): Promise<void> {
if (!deps.core.readSurfaceMessages) return;
try {
- const mirrorPage = await mirrorHistory(channel, threadTs, before, expandThreads);
+ const mirrorPage = await mirrorHistory(channel, threadTs, before, expandThreads, limit);
const rows = mirrorPage.rows;
const timestamps = new Set(rows.map((m) => m.ts));
const liveTimestamps = new Set(live.raw.flatMap((m) => (m.ts ? [m.ts] : [])));
@@ -253,7 +255,7 @@ export function createSlackHistoryReader(deps: {
}
}
try {
- const paging = { channel, limit: 200, ...(before ? { latest: before, inclusive: false } : {}) };
+ const paging = { channel, limit, ...(before ? { latest: before, inclusive: false } : {}) };
const page = parseMessageList(
threadTs
? await historyClient.conversations.replies({ ...paging, ts: threadTs })
diff --git a/src/slack/index.ts b/src/slack/index.ts
index f3af3eec8..16f9d82ca 100644
--- a/src/slack/index.ts
+++ b/src/slack/index.ts
@@ -211,7 +211,7 @@ export async function startSlackPlugin(
});
const mirror = createMirror({ core, ids, directory, externalParticipantsEnabled });
const historyRateLimitOptions = {
- managed: Boolean(cfg.sharedServiceUrl?.trim()),
+ managed: Boolean(cfg.installationId && cfg.sharedServiceUrl?.trim()),
...(cfg.webUiPublicUrl ? { setupUrl: `${cfg.webUiPublicUrl.replace(/\/$/, "")}/admin/?setup=slack` } : {}),
};
const rateLimitNotice = createSlackRateLimitNotice({
diff --git a/src/slack/surface-context.ts b/src/slack/surface-context.ts
index 081c27fe5..11b70652b 100644
--- a/src/slack/surface-context.ts
+++ b/src/slack/surface-context.ts
@@ -1,5 +1,5 @@
import type { SlackRateLimitNotice } from "./rate-limit-notice.ts";
-import { slackHistoryRateLimitMessage } from "./history-rate-limit.ts";
+import { SHARED_SLACK_HISTORY_LIMIT, slackHistoryRateLimitMessage } from "./history-rate-limit.ts";
import type { SlackHistoryReader } from "./history.ts";
import { swallow, swallowAs } from "../util/errors.ts";
import { WebClient } from "@slack/web-api";
@@ -39,6 +39,8 @@ export function createSurfaceContextFulfiller(deps: {
}): { fulfillSurfaceContext(client: any, r: SurfaceContextRequest): Promise<void> } {
const { core, directory, serializer, botToken, trustedFileHost, userToken, clientOptions } = deps;
+ const managed = deps.historyRateLimitOptions?.managed === true;
+
async function fulfillLiveSearch(
query: string,
count: number,
@@ -83,12 +85,21 @@ export function createSurfaceContextFulfiller(deps: {
const page = before ? { latest: before, inclusive: false } : {};
if (threadTs) {
const { messages, hasMore } = parseMessageList(
- await client.conversations.replies({ channel, ts: threadTs, limit: RECENT_THREAD_LIMIT, ...page }),
+ await client.conversations.replies({
+ channel,
+ ts: threadTs,
+ limit: managed ? SHARED_SLACK_HISTORY_LIMIT : RECENT_THREAD_LIMIT,
+ ...page,
+ }),
);
return { raw: messages, hasMore };
}
const { messages, hasMore } = parseMessageList(
- await client.conversations.history({ channel, limit: RECENT_HISTORY_LIMIT, ...page }),
+ await client.conversations.history({
+ channel,
+ limit: managed ? SHARED_SLACK_HISTORY_LIMIT : RECENT_HISTORY_LIMIT,
+ ...page,
+ }),
);
return { raw: messages.slice().reverse(), hasMore };
}
@@ -231,7 +242,10 @@ export function createSurfaceContextFulfiller(deps: {
if (q.file && typeof q.file.ts === "string" && q.file.ts) {
return await post(await fetchSurfaceFile(client, channel, threadTs, q.file));
}
- const count = Math.max(1, Math.min(RECENT_THREAD_LIMIT, Number(q.count) || 100));
+ const count = Math.max(
+ 1,
+ Math.min(RECENT_THREAD_LIMIT, Number(q.count) || (managed ? SHARED_SLACK_HISTORY_LIMIT : 100)),
+ );
const before = typeof q.before === "string" && q.before ? q.before : undefined;
const outcomes = await Promise.allSettled([
fetchContextHistory(client, channel, undefined, before),
diff --git a/src/types.ts b/src/types.ts
index cee88a14b..eb35e38d8 100644
--- a/src/types.ts
+++ b/src/types.ts
@@ -461,7 +461,7 @@ export interface SurfaceContextQuery {
conversationTarget?: string;
channelId?: string;
channelName?: string;
- count: number;
+ count?: number;
viewer?: string;
before?: string;
match?: string;
diff --git a/src/wiring.ts b/src/wiring.ts
index 830fc82e9..09dbc5652 100644
--- a/src/wiring.ts
+++ b/src/wiring.ts
@@ -1735,7 +1735,10 @@ export function buildApp(
}> | null> => {
const puller = orchestratorDeps.surfaceContext;
if (!puller) return null;
- const result = await puller.pull("slack", { conversationTarget: container, count: opts?.limit ?? 100 });
+ const result = await puller.pull("slack", {
+ conversationTarget: container,
+ ...(opts?.limit !== undefined ? { count: opts.limit } : {}),
+ });
if (!result) return null;
return (result.messages as Array<Record<string, unknown>>).map((m) => ({
container,
diff --git a/test/slack-history-rate-limit.test.ts b/test/slack-history-rate-limit.test.ts
index 44d60ad17..e2bdb953b 100644
--- a/test/slack-history-rate-limit.test.ts
+++ b/test/slack-history-rate-limit.test.ts
@@ -69,3 +69,99 @@ test("Slack history 429 returns immediately instead of sleeping inside the SDK",
await new Promise<void>((resolve) => server.close(() => resolve()));
}
});
+
+for (const source of ["live", "shadow", "mirror"] as const) {
+ for (const managed of [false, true]) {
+ test(`${source} history uses the ${managed ? "shared" : "workspace-owned"} app page size`, async () => {
+ const { createSlackHistoryReader } = await import("../src/slack/history.ts");
+ const calls: Array<{ method: string; args: any }> = [];
+ const client = {
+ conversations: Object.fromEntries(
+ ["history", "replies"].map((method) => [
+ method,
+ async (args: any) => {
+ calls.push({ method, args });
+ return { messages: [{ ts: "1.0", text: "parent", reply_count: 1 }], has_more: true };
+ },
+ ]),
+ ),
+ };
+ const reader = createSlackHistoryReader({
+ core: {} as import("../src/api/slack-core-client.ts").SlackCoreClient,
+ ids: { botUserId: "UBOT", ownBotId: "BBOT" } as import("../src/slack/directory.ts").BotIdentity,
+ source,
+ managed,
+ });
+ const channel = await reader(client, "C1", undefined, "10.0", true);
+ const thread = await reader(client, "C1", "1.0");
+ assert.equal(calls.length, source === "mirror" ? 2 : 3);
+ assert.ok(calls.some((call) => call.method === "history"));
+ assert.ok(calls.some((call) => call.method === "replies"));
+ assert.ok(calls.every((call) => call.args.limit === (managed ? 15 : 200)));
+ assert.equal(calls[0]!.args.latest, "10.0");
+ assert.equal(calls[0]!.args.inclusive, false);
+ for (const page of [channel, thread]) {
+ assert.equal(page.hasMore, true);
+ assert.equal(
+ page.note,
+ source === "mirror" ? "Slack history is truncated; older messages may be absent." : undefined,
+ );
+ }
+ });
+ }
+}
+
+for (const managed of [false, true]) {
+ test(`surface history defaults for ${managed ? "shared" : "workspace-owned"} apps`, async () => {
+ const { createSurfaceContextFulfiller } = await import("../src/slack/surface-context.ts");
+ let outcome: any;
+ const calls: any[] = [];
+ const client = {
+ conversations: Object.fromEntries(
+ ["history", "replies"].map((method) => [
+ method,
+ async (args: any) => {
+ calls.push(args);
+ return {
+ messages: Array.from({ length: Math.min(args.limit, 15) }, (_, i) => ({
+ ts: String((method === "history" ? 100 : 200) + i),
+ text: `message ${i}`,
+ user: "U1",
+ })),
+ has_more: true,
+ };
+ },
+ ]),
+ ),
+ };
+ const fulfiller = createSurfaceContextFulfiller({
+ core: {
+ fulfillContextRequest: async (_id: string, result: unknown) => {
+ outcome = result;
+ },
+ } as unknown as import("../src/api/slack-core-client.ts").SlackCoreClient,
+ directory: {} as import("../src/slack/directory.ts").Directory,
+ serializer: {
+ shapeRecentMessages: async (_client: unknown, raw: any[]) => raw.map((m) => ({ ...m, name: "Alice" })),
+ } as unknown as import("../src/slack/conversation-view.ts").ConversationSerializer,
+ botToken: "test",
+ clientOptions: {},
+ historyRateLimitOptions: { managed },
+ });
+ const query = { conversationTarget: "C1:1.0" };
+ await fulfiller.fulfillSurfaceContext(client, {
+ id: "test",
+ query,
+ } as import("../src/api/slack-core-client.ts").SurfaceContextRequest);
+ assert.equal(outcome.result.messages.length, managed ? 15 : 30);
+ assert.equal(outcome.result.hasMore, true);
+ assert.ok(outcome.result.nextBefore);
+ assert.ok(calls.every((args) => args.limit === (managed ? 15 : 200)));
+ assert.equal(outcome.result.note, undefined);
+ await fulfiller.fulfillSurfaceContext(client, {
+ id: "test",
+ query: { ...query, count: 5 },
+ } as import("../src/api/slack-core-client.ts").SurfaceContextRequest);
+ assert.equal(outcome.result.messages.length, 5);
+ });
+}
diff --git a/test/slack-mirror-context.test.ts b/test/slack-mirror-context.test.ts
index fc6a52135..4a9b10025 100644
--- a/test/slack-mirror-context.test.ts
+++ b/test/slack-mirror-context.test.ts
@@ -295,3 +295,30 @@ test("deleted messages do not consume context page slots or reappear through fal
["1.0"],
);
});
+
+test("shared-app shadow compares equal pages while mirror reads retain stored history", async (t) => {
+ const { cache, core, readHistory, client } = fixture();
+ const messages = Array.from({ length: 30 }, (_, i) => ({
+ ts: `${1000 + i}.000000`,
+ text: `message ${i}`,
+ user: "U1",
+ }));
+ await cache.ingest(messages.map((m) => ({ container: "C1", ts: m.ts, text: m.text, authorId: m.user })));
+ assert.equal((await readHistory(client, "C1")).raw.length, 30);
+ let resolveReport!: (value: any) => void;
+ const report = new Promise<any>((resolve) => {
+ resolveReport = resolve;
+ });
+ t.mock.method(console, "info", (value: string) => resolveReport(JSON.parse(value)));
+ const shadow = createSlackHistoryReader({ core, ids, source: "shadow", managed: true });
+ const liveClient = {
+ conversations: {
+ history: async () => ({ messages: messages.slice(-15).reverse(), has_more: true }),
+ },
+ };
+ assert.equal((await shadow(liveClient, "C1")).raw.length, 15);
+ const comparison = await report;
+ assert.equal(comparison.matchingMessages, 15);
+ assert.equal(comparison.mirrorMessagesOutsideLiveWindow, 0);
+ assert.equal(comparison.mirrorHasMore, true);
+});
diff --git a/test/surface-read-tools.test.ts b/test/surface-read-tools.test.ts
index 868e113cb..f9fdd1819 100644
--- a/test/surface-read-tools.test.ts
+++ b/test/surface-read-tools.test.ts
@@ -61,6 +61,32 @@ async function subToolResult(built: any, root: string, tool: string, deadlineMs
throw new Error(`no assistant reply for ${tool}`);
}
+test("read_thread leaves an omitted limit to the surface provider", async () => {
+ const built = freshApp();
+ built.runtime.start();
+ let running = true;
+ const queries: any[] = [];
+ const loop = (async () => {
+ while (running) {
+ for (const request of await built.app.pendingContextRequests("slack")) {
+ queries.push(request.query);
+ await built.app.fulfillContextRequest(request.id, { result: { messages: [] } });
+ }
+ await sleep(20);
+ }
+ })();
+ try {
+ await built.app.turn(mention("!read_thread", "C10", "1000.1"));
+ assert.match(await subToolResult(built, "C10:1000.1", "read_thread"), /read 0 message/);
+ assert.equal(queries.length, 1);
+ assert.equal(queries[0].count, undefined);
+ } finally {
+ running = false;
+ await loop;
+ await built.runtime.stop();
+ }
+});
+
test("whats_new returns POINTERS (counts of new-here + other active threads), never message prose", async () => {
const built = freshApp();
built.runtime.start();