Skip to content

armgit / qm

Public Imported from GitHub
0

Multiplayer agent harness for work.

reach: accept threadTs to reply inside a channel or group thread (#168)

Regan Bellaa5f05f708e9
diff --git a/src/api/agent-api-catalog.ts b/src/api/agent-api-catalog.ts
index 76992bc18..895bbaca0 100644
--- a/src/api/agent-api-catalog.ts
+++ b/src/api/agent-api-catalog.ts
@@ -136,7 +136,7 @@ const FAMILIES: AgentApiFamily[] = [
method: "POST",
path: "/v1/reach",
summary:
- "send a teammate a DM, post to a channel, or post to a group DM RIGHT NOW — `text` plus `recipient`, `channel`, or `participants` (the group DM's other members — the group is opened for you if it doesn't exist yet, so never ask someone to create one), optionally with `files` (workspace-relative paths, attached to the message all-or-nothing). EXTREMELY IMPORTANT: a `channel` post broadcasts to everyone there — pick the narrowest audience that can act; a question or errand for one person goes to their DM (`recipient`), NEVER a public channel, unless the person you're helping explicitly named that channel as the destination or the message genuinely concerns the whole room; or react to a message instead of posting with `react:{ts,emoji}` plus a `channel`/`participants`; or retract one of your own messages with `delete:{ts}` (no target = this conversation, or name a `channel`/`participants` to delete elsewhere) — find a message's `ts` via /v1/surface-context; pass `unfurlLinks:false` to suppress Slack previews (no schedule; for later/recurring use /v1/crons)",
+ "send a teammate a DM, post to a channel, or post to a group DM RIGHT NOW — `text` plus `recipient`, `channel`, or `participants` (the group DM's other members — the group is opened for you if it doesn't exist yet, so never ask someone to create one), optionally with `files` (workspace-relative paths, attached to the message all-or-nothing). EXTREMELY IMPORTANT: a `channel` post broadcasts to everyone there — pick the narrowest audience that can act; a question or errand for one person goes to their DM (`recipient`), NEVER a public channel, unless the person you're helping explicitly named that channel as the destination or the message genuinely concerns the whole room; pass `threadTs` (the parent message's ts) with a `channel`/`participants` post to reply inside that thread instead of top-level; or react to a message instead of posting with `react:{ts,emoji}` plus a `channel`/`participants`; or retract one of your own messages with `delete:{ts}` (no target = this conversation, or name a `channel`/`participants` to delete elsewhere) — find a message's `ts` via /v1/surface-context; pass `unfurlLinks:false` to suppress Slack previews (no schedule; for later/recurring use /v1/crons)",
},
],
},
diff --git a/src/api/app-messaging.ts b/src/api/app-messaging.ts
index b784da4dd..c3d14e4a2 100644
--- a/src/api/app-messaging.ts
+++ b/src/api/app-messaging.ts
@@ -6,7 +6,14 @@ import type { Destination, SurfaceContextRequest, SurfaceContextResult } from ".
import { errMessage } from "../util/errors.ts";
import { createMemoryMap } from "../persistence/durable-map.ts";
import { randomUUID } from "node:crypto";
-import { reachEnqueue, withSlackUnfurlOption, withReact, withDelete, type ReachResolution } from "../reach/reach.ts";
+import {
+ reachEnqueue,
+ withSlackUnfurlOption,
+ withReact,
+ withDelete,
+ withThread,
+ type ReachResolution,
+} from "../reach/reach.ts";
import { isVisible } from "../directory/visibility.ts";
import { answerWebContextRequest } from "./web-context.ts";
import { validateUserSchedule } from "../cron/schedule.ts";
@@ -427,6 +434,17 @@ export function createMessagingMethods(
if (r.channel) extra.channel = r.channel;
if (r.group) extra.group = r.group;
}
+ if (input.threadTs) {
+ if (baseDestination.type !== "slack" && baseDestination.type !== "group") {
+ return {
+ ok: false,
+ status: 400,
+ error: "bad_request",
+ message: "threadTs threads a channel or group DM post — a DM to a person has no threads",
+ };
+ }
+ baseDestination = withThread(baseDestination, input.threadTs);
+ }
const sender = await deps.directory.get(input.senderId).catch(() => null);
const delivery = await reachEnqueue({
deliveries: deps.deliveries,
diff --git a/src/api/app-types.ts b/src/api/app-types.ts
index f2b461ec1..59bdb0c49 100644
--- a/src/api/app-types.ts
+++ b/src/api/app-types.ts
@@ -147,6 +147,7 @@ interface ReachNowInput {
recipient?: string;
channel?: string;
participants?: readonly string[];
+ threadTs?: string;
unfurlLinks?: boolean;
attachments?: OutgoingAttachment[];
react?: { messageTs: string; emoji: string };
diff --git a/src/api/routes/reach.ts b/src/api/routes/reach.ts
index ea5588ef4..d56a740e7 100644
--- a/src/api/routes/reach.ts
+++ b/src/api/routes/reach.ts
@@ -14,6 +14,7 @@ type ReachBody = {
participants?: unknown;
text?: unknown;
message?: unknown;
+ threadTs?: unknown;
unfurlLinks?: unknown;
react?: unknown;
delete?: unknown;
@@ -63,6 +64,29 @@ async function reachNow(ctx: ApiCtx): Promise<void> {
else if (typeof b.message === "string") text = b.message;
const react = parseReact(b.react);
const del = parseDelete(b.delete);
+ let threadTs: string | undefined;
+ if (b.threadTs !== undefined) {
+ if (typeof b.threadTs !== "string" || !/^\d+\.\d+$/.test(b.threadTs.trim())) {
+ return sendJson(res, 400, {
+ error: "bad_request",
+ message:
+ 'threadTs must be the parent message\'s ts string, e.g. "1723497600.123456" — find it via /v1/surface-context',
+ });
+ }
+ threadTs = b.threadTs.trim();
+ if (react || del) {
+ return sendJson(res, 400, {
+ error: "bad_request",
+ message: "threadTs threads a text post — react/delete already name their target message ts",
+ });
+ }
+ if (typeof b.recipient === "string") {
+ return sendJson(res, 400, {
+ error: "bad_request",
+ message: "threadTs applies to a channel or group DM post — a DM to a person has no threads",
+ });
+ }
+ }
const hasNamedTarget =
typeof b.recipient === "string" || typeof b.channel === "string" || Array.isArray(b.participants);
if (react && del) {
@@ -168,6 +192,7 @@ async function reachNow(ctx: ApiCtx): Promise<void> {
senderId: capability.actorId,
senderScope: capability.scopeId,
...(text !== undefined ? { text } : {}),
+ ...(threadTs !== undefined ? { threadTs } : {}),
...(react ? { react } : {}),
...(del ? { delete: del } : {}),
...(typeof b.recipient === "string" ? { recipient: b.recipient } : {}),
diff --git a/src/reach/reach.ts b/src/reach/reach.ts
index 50df10500..49e776caf 100644
--- a/src/reach/reach.ts
+++ b/src/reach/reach.ts
@@ -287,6 +287,10 @@ export function withDelete(destination: Destination, del: { messageTs: string }
return del ? { ...destination, delete: del } : destination;
}
+export function withThread(destination: Destination, threadTs: string | undefined): Destination {
+ return threadTs ? { ...destination, target: `${destination.target}:${threadTs}` } : destination;
+}
+
export function withEdit(destination: Destination, editRef: string | undefined): Destination {
return editRef ? { ...destination, editRef } : destination;
}
diff --git a/test/reach-thread.test.ts b/test/reach-thread.test.ts
new file mode 100644
index 000000000..7dc175058
--- /dev/null
+++ b/test/reach-thread.test.ts
@@ -0,0 +1,85 @@
+import { describe, it, before, after } from "node:test";
+import assert from "node:assert/strict";
+import type { AddressInfo } from "node:net";
+import type { Server } from "node:http";
+import { buildApp, type BuiltApp } from "../src/wiring.ts";
+import { createServer } from "../src/api/server.ts";
+import { scopeId } from "../src/types.ts";
+import { mintCapabilityToken, CAPABILITY_TTL_MS } from "../src/auth/capability-token.ts";
+import { testConfig } from "./support/test-config.ts";
+
+const SECRET = "reach-thread-secret".repeat(3);
+const TS = "1723497600.123456";
+
+describe("POST /v1/reach with threadTs", () => {
+ let server: Server;
+ let base: string;
+ let built: BuiltApp;
+
+ const cap = async (actorId: string) =>
+ await mintCapabilityToken(
+ { actorId, scopeId: scopeId("personal", actorId), exp: Date.now() + CAPABILITY_TTL_MS },
+ SECRET,
+ );
+
+ const post = async (body: unknown, actorId = "U-carol") =>
+ fetch(`${base}/v1/reach`, {
+ method: "POST",
+ headers: { "content-type": "application/json", "x-agent-capability": await cap(actorId) },
+ body: JSON.stringify(body),
+ });
+
+ before(async () => {
+ built = buildApp(testConfig({ signingSecret: SECRET }));
+ await built.app.upsertDirectory([
+ { principalId: "U-carol", displayName: "Carol", type: "internal" },
+ { principalId: "U-alice", displayName: "Alice", type: "internal" },
+ ]);
+ await built.app.upsertChannels([{ channelId: "C-eng", name: "eng" }]);
+ server = createServer(built.app, { signingSecret: SECRET });
+ await new Promise<void>((resolve) => server.listen(0, resolve));
+ base = `http://localhost:${(server.address() as AddressInfo).port}`;
+ });
+
+ after(async () => {
+ await new Promise<void>((resolve) => server.close(() => resolve()));
+ });
+
+ it("threads a channel post: the delivery target carries channel:threadTs", async () => {
+ const res = await post({ channel: "eng", text: "in the thread", threadTs: TS });
+ assert.equal(res.status, 200);
+ const body = (await res.json()) as { deliveryId: string };
+ const d = (await built.app.pendingDeliveries("slack")).find((x) => x.id === body.deliveryId);
+ assert.ok(d, "delivery enqueued for the slack surface");
+ assert.equal(d!.destination.target, `C-eng:${TS}`);
+ });
+
+ it("an unthreaded channel post keeps a bare channel target", async () => {
+ const res = await post({ channel: "eng", text: "top level" });
+ assert.equal(res.status, 200);
+ const body = (await res.json()) as { deliveryId: string };
+ const d = (await built.app.pendingDeliveries("slack")).find((x) => x.id === body.deliveryId);
+ assert.equal(d!.destination.target, "C-eng");
+ });
+
+ it("rejects threadTs on a DM to a person", async () => {
+ const res = await post({ recipient: "Alice", text: "hi", threadTs: TS });
+ assert.equal(res.status, 400);
+ const body = (await res.json()) as { message: string };
+ assert.match(body.message, /has no threads/);
+ });
+
+ it("rejects a malformed threadTs", async () => {
+ const res = await post({ channel: "eng", text: "hi", threadTs: "not-a-ts" });
+ assert.equal(res.status, 400);
+ const body = (await res.json()) as { message: string };
+ assert.match(body.message, /threadTs must be/);
+ });
+
+ it("rejects threadTs combined with react or delete", async () => {
+ const r1 = await post({ channel: "eng", react: { ts: TS, emoji: "eyes" }, threadTs: TS });
+ assert.equal(r1.status, 400);
+ const r2 = await post({ channel: "eng", delete: { ts: TS }, threadTs: TS });
+ assert.equal(r2.status, 400);
+ });
+});