Multiplayer agent harness for work.
Reply to Slack conversations from the web UI (#2383)
Regan Bell45806535cbe3
diff --git a/plugins/web-ui/server/index.ts b/plugins/web-ui/server/index.tsindex c7d501f13..ab0e97a05 100644--- a/plugins/web-ui/server/index.ts+++ b/plugins/web-ui/server/index.ts@@ -1298,6 +1298,15 @@ const apiRoutes: readonly WebRoute[] = [c.res.end();},},+ ...["reply-status", "reply"].map((action) => ({+ method: "POST",+ path: `/api/composio/slack/${action}`,+ handle: async (c: WebCtx) => {+ const body = await readJson(c.req, c.res, false);+ if (!body) return;+ return relayCore(c.res, "POST", `/v1/composio/slack/${action}`, JSON.stringify(body));+ },+ })),{ method: "GET", path: "/api/composio/slack", handle: (c) => relayCore(c.res, "GET", "/v1/composio/slack") },{method: "POST",@@ -2181,7 +2190,17 @@ const apiRoutes: readonly WebRoute[] = [const { res, user } = c;const provider = c.params.provider!;const callback = `${PUBLIC_URL}/v1/connectors/oauth/${encodeURIComponent(provider)}/callback`;- const params = new URLSearchParams({ principalId: user, redirectUri: callback, returnTo: "/keychain" });+ const body = await readJson<{ returnTo?: unknown }>(c.req, res);+ if (!body) return;+ const returnTo =+ typeof body?.returnTo === "string" &&+ body.returnTo.startsWith("/") &&+ !body.returnTo.startsWith("//") &&+ !body.returnTo.includes("\\") &&+ new URL(body.returnTo, PUBLIC_URL).origin === new URL(PUBLIC_URL).origin+ ? body.returnTo+ : "/keychain";+ const params = new URLSearchParams({ principalId: user, redirectUri: callback, returnTo });const corePath = `/v1/connectors/oauth/${encodeURIComponent(provider)}/start?${params.toString()}`;return relayCore(res, "GET", corePath);},diff --git a/plugins/web-ui/src/chat.ts b/plugins/web-ui/src/chat.tsindex 137cecf2d..ba821948b 100644--- a/plugins/web-ui/src/chat.ts+++ b/plugins/web-ui/src/chat.ts@@ -1,3 +1,5 @@+import "./slack-reply";+import type { SlackReply } from "./slack-reply";import { assistantSidebar, assistantMessage } from "./assistant-sidebar";import { formatMessageTime } from "./message-time.ts";import { messageEntrySeqs, highlightMessage } from "./message-link.ts";@@ -1160,6 +1162,14 @@ export function createChatSurface(resetBackgroundPanel();const host = document.createElement("div");host.className = "custom-chat readonly-chat";+ const priorReply = sameSession ? container.querySelector<SlackReply>("qm-slack-reply") : null;+ const slackReply =+ surfaceOf(s) === "slack" ? (priorReply ?? (document.createElement("qm-slack-reply") as SlackReply)) : null;+ if (slackReply) {+ slackReply.sessionId = s.id;+ slackReply.user = appState.me?.user ?? "";+ if (!priorReply) slackReply.addEventListener("slack-sent", () => onDelivery(s.threadRef));+ }let approvals: PendingApproval[] = [];const draw = () => {approvals = unresolvedApprovals(approvals);@@ -1168,12 +1178,12 @@ export function createChatSurface(render(html`<div class="custom-chat-shell">- ${chatHeader(groupDmTitle(s), surfaceOf(s), true)}+ ${chatHeader(groupDmTitle(s), surfaceOf(s), surfaceOf(s) !== "slack")}<div class="readonly-banner">${surfaceOf(s) === "slack"- ? html`This conversation lives in Slack. Replies happen- there.${+ ? html`Replies are sent to this Slack conversation as+ you.${sessionSlackUrl(s)? html` <aclass="readonly-banner-link"@@ -1250,6 +1260,7 @@ export function createChatSurface(${ctx.composer.state.error ? html`<div class="composer-error inline">${ctx.composer.state.error}</div>` : nothing}</div></section>+ ${slackReply ?? nothing}</div>`,host,diff --git a/plugins/web-ui/src/composer-input.ts b/plugins/web-ui/src/composer-input.tsnew file mode 100644index 000000000..ae6c4c21d--- /dev/null+++ b/plugins/web-ui/src/composer-input.ts@@ -0,0 +1,42 @@+import { emojiCompletion } from "./emoji-completion";+import { html, nothing, type TemplateResult } from "lit";+import { live } from "lit/directives/live.js";++export function composerInput(options: {+ value: string;+ placeholder: string;+ disabled: boolean;+ label?: string;+ maxLength?: number;+ onInput: (event: InputEvent) => void;+ onKeydown: (event: KeyboardEvent) => void;+ onPaste?: (event: ClipboardEvent) => void;+}): TemplateResult {+ return html`<textarea+ class="composer-input"+ ${emojiCompletion(options.value)}+ dir="auto"+ rows="1"+ aria-label=${options.label ?? nothing}+ maxlength=${options.maxLength ?? nothing}+ placeholder=${options.placeholder}+ ?disabled=${options.disabled}+ .value=${live(options.value)}+ @input=${options.onInput}+ @keydown=${options.onKeydown}+ @paste=${options.onPaste ?? nothing}+ ></textarea>`;+}++export function resizeComposerInput(input: HTMLTextAreaElement, minHeight = 48): void {+ const wrap = input.closest<HTMLElement>(".composer-wrap");+ const wrapHeight = wrap?.style.height ?? "";+ if (wrap) wrap.style.height = `${wrap.getBoundingClientRect().height}px`;+ input.style.height = "auto";+ const cap = parseFloat(getComputedStyle(input).maxHeight) || 180;+ const content = input.scrollHeight;+ input.style.height = `${Math.min(cap, Math.max(minHeight, content))}px`;+ if (wrap) wrap.style.height = wrapHeight;+ input.style.overflowY = content > cap ? "auto" : "hidden";+ if (content <= cap) input.scrollTop = 0;+}diff --git a/plugins/web-ui/src/composer.ts b/plugins/web-ui/src/composer.tsindex 35d37d83f..477145a13 100644--- a/plugins/web-ui/src/composer.ts+++ b/plugins/web-ui/src/composer.ts@@ -1,4 +1,5 @@import { emojiCompletion } from "./emoji-completion";+import { composerInput, resizeComposerInput } from "./composer-input";import { reportHandledError } from "./browser-errors.ts";import { appEditSlug } from "./app-edit";import { runtimeConfigKey, loadRuntimeConfig, saveRuntimeConfig, subscribeRuntimeConfig } from "./runtime-config-store";@@ -671,20 +672,14 @@ export function createComposerSurface(ctx: ConvCtx, options: ComposerOptions = {${blockingPauses.length? nothing- : html`- <textarea- class="composer-input"- dir="auto"- ${emojiCompletion(composerState.draft)}- rows="1"- placeholder=${placeholder}- ?disabled=${inputBlocked}- .value=${live(composerState.draft)}- @input=${(e: InputEvent) => onDraftInput(e, agent)}- @keydown=${(e: KeyboardEvent) => onComposerKeydown(e, agent)}- @paste=${(e: ClipboardEvent) => void onComposerPaste(e, agent)}- ></textarea>- `+ : composerInput({+ value: composerState.draft,+ placeholder,+ disabled: inputBlocked,+ onInput: (e) => onDraftInput(e, agent),+ onKeydown: (e) => onComposerKeydown(e, agent),+ onPaste: (e) => void onComposerPaste(e, agent),+ })}<div class="composer-toolbar"><div class="composer-left">@@ -2024,20 +2019,7 @@ export function createComposerSurface(ctx: ConvCtx, options: ComposerOptions = {}if (ta.value === autosizedValue) return;autosizedValue = ta.value;- const wrap = ta.closest<HTMLElement>(".composer-wrap");- const wrapHeight = wrap?.style.height ?? "";- if (wrap) wrap.style.height = `${wrap.getBoundingClientRect().height}px`;- ta.style.height = "auto";- const cap = parseFloat(getComputedStyle(ta).maxHeight) || 180;- const content = ta.scrollHeight;- ta.style.height = `${Math.min(cap, Math.max(ctx.pane ? 0 : 48, content))}px`;- if (wrap) wrap.style.height = wrapHeight;- if (content > cap) {- ta.style.overflowY = "auto";- } else {- ta.style.overflowY = "hidden";- ta.scrollTop = 0;- }+ resizeComposerInput(ta, ctx.pane ? 0 : 48);});}diff --git a/plugins/web-ui/src/sessions.ts b/plugins/web-ui/src/sessions.tsindex 62b5473fe..f8971ee27 100644--- a/plugins/web-ui/src/sessions.ts+++ b/plugins/web-ui/src/sessions.ts@@ -801,7 +801,7 @@ function isActiveRow(s: CoreSession): boolean {}function chatPageRow(s: CoreSession): TemplateResult {- const readOnly = !s.canContinue;+ const readOnly = surfaceOf(s) !== "slack" && !s.canContinue;const color = displaySessionColor(s.color);return html`<div class="list-row chat-row ${color ? "colored" : ""}" style=${color ? `--session-color:${color}` : nothing}>@@ -978,7 +978,7 @@ function sessionRow(s: CoreSession, projectChild = false): TemplateResult {const untitledProjectChild = projectChild && !s.title?.trim();let title = sessionTitle(s);if (untitledProjectChild) title = surfaceOf(s) === "web" ? "Web chat" : "New chat";- const readOnly = !s.canContinue;+ const readOnly = surfaceOf(s) !== "slack" && !s.canContinue;const surface = surfaceOf(s);const context = projectChild ? null : rowContext(s);const working = sessionWorking(s);diff --git a/plugins/web-ui/src/slack-account.ts b/plugins/web-ui/src/slack-account.tsindex 7b28900af..8153393b7 100644--- a/plugins/web-ui/src/slack-account.ts+++ b/plugins/web-ui/src/slack-account.ts@@ -23,16 +23,19 @@ export function captureSlackReturn(url: string): void {export class SlackAccount extends LitElement {static properties = {user: {},+ reply: { type: Boolean },busy: { state: true },error: { state: true },connected: { state: true },label: { state: true },};user = "";+ reply = false;private busy = false;private error = "";private connected = false;private label = "";+ private nativeOAuth = false;private attempt: SlackAttempt | null = null;protected createRenderRoot(): HTMLElement {@@ -96,6 +99,7 @@ export class SlackAccount extends LitElement {});if (!response.ok) return;const result = await response.json();+ this.nativeOAuth = result.nativeOAuth === true;this.connected = result.connected === true;this.label = [result.user, result.workspace].filter(Boolean).join(" · ");} catch {@@ -109,6 +113,27 @@ export class SlackAccount extends LitElement {this.error = "";try {if (await openDesktopBrowser(withBase("/settings"))) return;+ await this.status();+ if (this.nativeOAuth) {+ const response = await fetch(withBase("/api/connectors/slack/start"), {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ returnTo: `${location.pathname}${location.search}` }),+ signal: AbortSignal.timeout(30_000),+ });+ const result = await response.json();+ if (!response.ok) throw Error(result.message ?? "Could not start Slack authorization.");+ const url = new URL(result.authorizeUrl);+ if (+ url.origin !== "https://slack.com" ||+ url.pathname !== "/oauth/v2/authorize" ||+ url.username ||+ url.password+ )+ throw Error("Could not verify the Slack authorization link.");+ location.assign(url.href);+ return;+ }const state = crypto.randomUUID();const response = await fetch(withBase("/api/composio/slack/authorize"), {method: "POST",@@ -153,6 +178,7 @@ export class SlackAccount extends LitElement {this.connected = true;this.label = [result.user, result.workspace].filter(Boolean).join(" · ");this.clearAttempt();+ this.dispatchEvent(new CustomEvent("slack-linked", { bubbles: true }));} catch (error) {this.error = error instanceof Error ? error.message : "Could not verify your Slack account.";} finally {@@ -163,7 +189,7 @@ export class SlackAccount extends LitElement {protected render() {return html`<section class="slack-account" aria-label="Your Slack account">${- this.connected+ this.connected && !this.reply? html`<div class="slack-connected" role="status">${icon(Check, 14)}<span>Your Slack account is linked${this.label ? ` · ${this.label}` : ""}</span></div>`@@ -175,7 +201,9 @@ export class SlackAccount extends LitElement {</div><span><strong>${this.busy ? "Linking Slack…" : "Link your Slack account"}</strong- ><small>Let QM search Slack and take action on your behalf.</small></span+ ><small+ >${this.reply ? "Send replies here as yourself in Slack." : "Let QM search Slack and take action on your behalf."}</small+ ></span>${icon(ArrowUpRight, 16)}</button>`diff --git a/plugins/web-ui/src/slack-reply.css b/plugins/web-ui/src/slack-reply.cssnew file mode 100644index 000000000..0d03bc7b5--- /dev/null+++ b/plugins/web-ui/src/slack-reply.css@@ -0,0 +1,14 @@+qm-slack-reply {+ display: block;+ flex: none;+}+.slack-reply-box {+ width: min(var(--content-w), 100%);+ box-sizing: border-box;+ margin: 0 auto;+ padding: 12px var(--composer-inset) 20px;+}+.slack-reply-box .welcome-slack {+ max-width: none;+ margin-bottom: 0;+}diff --git a/plugins/web-ui/src/slack-reply.ts b/plugins/web-ui/src/slack-reply.tsnew file mode 100644index 000000000..aae9c2f53--- /dev/null+++ b/plugins/web-ui/src/slack-reply.ts@@ -0,0 +1,159 @@+import { composerInput, resizeComposerInput } from "./composer-input";+import { ArrowUp } from "lucide";+import { icon } from "./icons";+import { tip } from "./tooltip";+import { LitElement, html, nothing } from "lit";+import { withBase } from "./core-bridge";+import "./slack-account";+import "./slack-reply.css";++export class SlackReply extends LitElement {+ static properties = {+ sessionId: {},+ user: {},+ connected: { state: true },+ linkAvailable: { state: true },+ loading: { state: true },+ sending: { state: true },+ error: { state: true },+ text: { state: true },+ label: { state: true },+ };+ sessionId = "";+ user = "";+ private connected = false;+ private linkAvailable = false;+ private loading = true;+ private sending = false;+ private error = "";+ private text = "";+ private label = "";+ private inputObserver: ResizeObserver | null = null;+ private observedInput: HTMLTextAreaElement | null = null;++ protected createRenderRoot(): HTMLElement {+ return this;+ }+ connectedCallback(): void {+ super.connectedCallback();+ window.addEventListener("focus", this.refresh);+ this.requestUpdate();+ }+ disconnectedCallback(): void {+ super.disconnectedCallback();+ window.removeEventListener("focus", this.refresh);+ this.inputObserver?.disconnect();+ this.inputObserver = null;+ this.observedInput = null;+ }+ protected updated(): void {+ const input = this.querySelector<HTMLTextAreaElement>(".composer-input");+ if (input !== this.observedInput) {+ this.inputObserver?.disconnect();+ this.inputObserver = null;+ this.observedInput = input;+ }+ if (!input) return;+ resizeComposerInput(input);+ if (!this.inputObserver && typeof ResizeObserver !== "undefined") {+ let width = input.clientWidth;+ this.inputObserver = new ResizeObserver(() => {+ if (width === input.clientWidth) return;+ width = input.clientWidth;+ resizeComposerInput(input);+ });+ this.inputObserver.observe(input);+ }+ }+ protected firstUpdated(): void {+ void this.refresh();+ }+ private refresh = async (): Promise<void> => {+ try {+ const response = await this.request("reply-status");+ const result = await response.json();+ this.connected = response.ok && result.connected === true;+ this.linkAvailable = response.ok;+ this.label = result.user ?? "yourself";+ this.error = response.ok ? "" : (result.message ?? "Could not check your Slack connection.");+ if (!response.ok && result.error === "composio_unavailable")+ this.error = "Slack linking isn’t configured for your account on this deployment.";+ } catch {+ this.connected = false;+ this.linkAvailable = false;+ this.error = "Could not check your Slack connection.";+ } finally {+ this.loading = false;+ }+ };+ private request(action: string, message?: { text: string; clientMessageId: string }): Promise<Response> {+ return fetch(withBase(`/api/composio/slack/${action}`), {+ method: "POST",+ headers: { "content-type": "application/json" },+ body: JSON.stringify({ sessionId: this.sessionId, ...message }),+ signal: AbortSignal.timeout(60_000),+ });+ }+ private async send(event: Event): Promise<void> {+ event.preventDefault();+ if (!this.connected || this.sending || !this.text.trim()) return;+ this.sending = true;+ this.error = "";+ try {+ const response = await this.request("reply", { text: this.text, clientMessageId: crypto.randomUUID() });+ const result = await response.json();+ if (!response.ok || !result.sent) {+ if (result.connected === false) this.connected = false;+ this.error = result.message ?? "Could not send your Slack message.";+ return;+ }+ this.text = "";+ this.dispatchEvent(new CustomEvent("slack-sent", { bubbles: true }));+ } catch {+ this.error = "The send outcome is unknown. Check Slack before trying again.";+ } finally {+ this.sending = false;+ }+ }+ protected render() {+ if (this.loading)+ return html`<div class="slack-reply-box"><p role="status">Checking your Slack connection…</p></div>`;+ if (this.connected)+ return html`<form class="composer-wrap" @submit=${(e: Event) => void this.send(e)}>+ ${composerInput({+ value: this.text,+ placeholder: `Reply in Slack as ${this.label}`,+ label: `Reply in Slack as ${this.label}`,+ disabled: this.sending,+ maxLength: 4000,+ onInput: (e) => {+ this.text = (e.target as HTMLTextAreaElement).value;+ },+ onKeydown: (e) => {+ if (e.isComposing || e.keyCode === 229 || e.key !== "Enter" || e.shiftKey) return;+ void this.send(e);+ },+ })}+ <div class="composer-toolbar">+ <div class="composer-left"></div>+ <div class="composer-right">+ <button+ class="send-btn"+ type="submit"+ aria-label="Send to Slack"+ ${tip("Send to Slack")}+ ?disabled=${this.sending || !this.text.trim()}+ >+ ${icon(ArrowUp, 16)}+ </button>+ </div>+ </div>+ ${this.error ? html`<div class="composer-error" role="alert">${this.error}</div>` : nothing}+ </form>`;+ return html`<div class="slack-reply-box">+ ${this.linkAvailable ? html`<qm-slack-account .user=${this.user} .reply=${true} @slack-linked=${this.refresh}></qm-slack-account>` : nothing}+ ${this.error ? html`<p class="slack-account-error" role="alert">${this.error} <button class="btn" @click=${this.refresh}>Check connection</button></p>` : nothing}+ </div>`;+ }+}+if (!customElements.get("qm-slack-reply")) customElements.define("qm-slack-reply", SlackReply);diff --git a/plugins/web-ui/test/browser-env.ts b/plugins/web-ui/test/browser-env.tsindex 24e818b2e..9fee89d81 100644--- a/plugins/web-ui/test/browser-env.ts+++ b/plugins/web-ui/test/browser-env.ts@@ -38,6 +38,7 @@ export async function browserEnv(sessionStorage: dom.window.sessionStorage,navigator: dom.window.navigator,HTMLElement: dom.window.HTMLElement,+ HTMLAnchorElement: dom.window.HTMLAnchorElement,Element: dom.window.Element,Node: dom.window.Node,Event: dom.window.Event,diff --git a/plugins/web-ui/test/deep-link-boot-fixture.ts b/plugins/web-ui/test/deep-link-boot-fixture.tsindex 93fb6d098..ec17cdb88 100644--- a/plugins/web-ui/test/deep-link-boot-fixture.ts+++ b/plugins/web-ui/test/deep-link-boot-fixture.ts@@ -26,6 +26,7 @@ export interface Harness {}interface HarnessOptions {+ api?: (path: string, init?: RequestInit) => Response | undefined;path: string;session?: CoreSession;messageLink?: boolean;@@ -63,8 +64,8 @@ export async function harness(opts: HarnessOptions): Promise<Harness> {const env = await browserEnv({dom: { url: `http://localhost${opts.path}` },html: '<!doctype html><div id="app"></div>',- fetch: (input) => {- const answer = respond(input);+ fetch: (input, init) => {+ const answer = respond(input, init);inFlight.add(answer);void answer.finally(() => inFlight.delete(answer)).catch(() => {});return answer;@@ -125,9 +126,11 @@ export async function harness(opts: HarnessOptions): Promise<Harness> {const sessionsHeld = new Promise<void>((resolve) => (releaseSessions = resolve));const transcriptHeld = new Promise<void>((resolve) => (releaseTranscript = resolve));let failuresLeft = opts.transcriptFailures ?? (opts.transcriptStatus ? Number.POSITIVE_INFINITY : 0);- const respond = async (input: RequestInfo | URL): Promise<Response> => {+ const respond = async (input: RequestInfo | URL, init?: RequestInit): Promise<Response> => {const path = String(input);requests.push(path);+ const custom = opts.api?.(path, init);+ if (custom) return custom;if (path === "/me")return Response.json({user: "tester",diff --git a/plugins/web-ui/test/sidebar-surface-default.test.ts b/plugins/web-ui/test/sidebar-surface-default.test.tsindex cefaeec23..dcf504f8d 100644--- a/plugins/web-ui/test/sidebar-surface-default.test.ts+++ b/plugins/web-ui/test/sidebar-surface-default.test.ts@@ -93,7 +93,7 @@ for (const stored of [null, "1", "0", "unavailable"] as const) {assert.deepEqual(rowIds(), ["web", "slack", "group"]);assert.ok(slackRow()?.querySelector(".slack-logo"));assert.equal(slackRow()?.querySelector(".ro-lock"), null);- assert.match(slackRow()?.querySelector(".session")?.getAttribute("aria-label") ?? "", /read-only/);+ assert.doesNotMatch(slackRow()?.querySelector(".session")?.getAttribute("aria-label") ?? "", /read-only/);if (stored !== "unavailable") assert.equal(localStorage.getItem("web-ui:web-only"), "0");} finally {await env.close();diff --git a/plugins/web-ui/test/slack-authorize-native.test.ts b/plugins/web-ui/test/slack-authorize-native.test.tsnew file mode 100644index 000000000..7db631fdc--- /dev/null+++ b/plugins/web-ui/test/slack-authorize-native.test.ts@@ -0,0 +1,37 @@+import assert from "node:assert/strict";+import test from "node:test";+import { harness } from "./deep-link-boot-fixture.ts";++test("Slack account linking selects native OAuth and preserves the conversation return path", async () => {+ const h = await harness({ path: "/settings" });+ const previousFetch = globalThis.fetch;+ const starts: string[] = [];+ let composioStarts = 0;+ globalThis.fetch = async (input, init) => {+ if (String(input) === "/api/composio/slack")+ return Response.json({ connected: false, nativeOAuth: true, workspaceInstalled: true });+ if (String(input) === "/api/connectors/slack/start") {+ starts.push(JSON.parse(String(init?.body)).returnTo);+ return Response.json({ authorizeUrl: "https://untrusted.test/oauth/v2/authorize" });+ }+ if (String(input) === "/api/composio/slack/authorize") composioStarts++;+ return previousFetch(input, init);+ };+ try {+ h.releaseSessions();+ await h.boot();+ const card = document.querySelector("qm-slack-account")!;+ history.replaceState(null, "", "/s/sess-deep?layout=single");+ (card.querySelector("button") as HTMLButtonElement).click();+ for (let i = 0; i < 100 && !card.textContent?.includes("Could not verify"); i++)+ await new Promise((resolve) => setTimeout(resolve, 5));+ assert.deepEqual(starts, ["/s/sess-deep?layout=single"]);+ assert.equal(composioStarts, 0);+ assert.match(card.textContent ?? "", /Could not verify the Slack authorization link/);+ assert.equal(location.pathname, "/s/sess-deep");+ } finally {+ globalThis.fetch = previousFetch;+ document.querySelector("#app")?.replaceChildren();+ await h.close();+ }+});diff --git a/plugins/web-ui/test/slack-reply-send.test.ts b/plugins/web-ui/test/slack-reply-send.test.tsnew file mode 100644index 000000000..b6963c307--- /dev/null+++ b/plugins/web-ui/test/slack-reply-send.test.ts@@ -0,0 +1,76 @@+import assert from "node:assert/strict";+import test from "node:test";+import { harness } from "./deep-link-boot-fixture.ts";++const session = {+ id: "slack-chat",+ threadRef: "ch:C123:123.456",+ surface: "slack",+ scopeId: "channel:C123",+ type: "channel" as const,+ createdAt: Date.now(),+ title: "Slack discussion",+};+async function until(check: () => boolean) {+ for (let i = 0; i < 100 && !check(); i++) await new Promise((resolve) => setTimeout(resolve, 10));+ assert.ok(check());+}++test("Slack composer posts to the Slack endpoint and retains text after a rejected send", async () => {+ const messages: unknown[] = [];+ let succeed = false;+ const h = await harness({+ path: "/",+ api: (path, init) => {+ if (path.endsWith("/slack/reply-status")) return Response.json({ connected: true, user: "Alice" });+ if (path.endsWith("/slack/reply")) {+ messages.push(JSON.parse(String(init?.body)));+ return succeed+ ? Response.json({ sent: true })+ : Response.json({ message: "Slack denied this message." }, { status: 403 });+ }+ return undefined;+ },+ });+ const originalCustomEvent = globalThis.CustomEvent;+ globalThis.CustomEvent = window.CustomEvent;+ try {+ h.releaseSessions();+ await h.boot();+ h.releaseTranscript();+ await h.openSession(session);+ await until(() => !!document.querySelector("qm-slack-reply textarea"));+ const widget = document.querySelector("qm-slack-reply")!;+ widget.addEventListener("slack-sent", (e) => e.stopPropagation());+ const field = widget.querySelector("textarea")!;+ field.value = "Hello Slack";+ field.dispatchEvent(new window.Event("input", { bubbles: true }));+ await h.openSession(session);+ assert.equal(document.querySelector("qm-slack-reply"), widget);+ assert.equal(field.value, "Hello Slack");+ field.dispatchEvent(new window.KeyboardEvent("keydown", { key: "Enter", shiftKey: true, cancelable: true }));+ field.dispatchEvent(new window.KeyboardEvent("keydown", { key: "Enter", isComposing: true, cancelable: true }));+ assert.equal(messages.length, 0);+ field.dispatchEvent(new window.KeyboardEvent("keydown", { key: "Enter", cancelable: true }));+ await until(() => !!widget.querySelector('[role="alert"]'));+ assert.equal(field.value, "Hello Slack");+ assert.equal(messages.length, 1);+ assert.deepEqual(Object.keys(messages[0] as object).sort(), ["clientMessageId", "sessionId", "text"]);+ const transcriptReads = () => h.requests.filter((path) => path.startsWith("/api/sessions/slack-chat")).length;+ const beforeSend = transcriptReads();+ succeed = true;+ widget.querySelector("form")!.dispatchEvent(new window.Event("submit", { cancelable: true }));+ await until(() => field.value === "");+ await until(() => transcriptReads() > beforeSend);+ assert.doesNotMatch(widget.textContent!, /Sending to Slack|Sent to Slack/);+ assert.equal(widget.querySelector('[role="alert"]'), null);+ assert.equal(messages.length, 2);+ assert.equal(+ h.requests.some((path) => path === "/api/turn"),+ false,+ );+ } finally {+ globalThis.CustomEvent = originalCustomEvent;+ await h.close();+ }+});diff --git a/plugins/web-ui/test/slack-reply-unavailable.test.ts b/plugins/web-ui/test/slack-reply-unavailable.test.tsnew file mode 100644index 000000000..28a6ae850--- /dev/null+++ b/plugins/web-ui/test/slack-reply-unavailable.test.ts@@ -0,0 +1,46 @@+import assert from "node:assert/strict";+import test from "node:test";+import { harness } from "./deep-link-boot-fixture.ts";++const session = {+ id: "slack-chat",+ threadRef: "ch:C123:123.456",+ surface: "slack",+ scopeId: "channel:C123",+ type: "channel" as const,+ createdAt: Date.now(),+ title: "Slack discussion",+};+async function until(check: () => boolean) {+ for (let i = 0; i < 100 && !check(); i++) await new Promise((resolve) => setTimeout(resolve, 10));+ assert.ok(check());+}++test("unavailable Slack linking shows one explanation and recovers when configured", async () => {+ let configured = false;+ const h = await harness({+ path: "/",+ api: (path) => {+ if (!path.endsWith("/slack/reply-status")) return undefined;+ if (configured) return Response.json({ connected: false });+ return Response.json({ error: "composio_unavailable", message: "App connections unavailable" }, { status: 403 });+ },+ });+ try {+ h.releaseSessions();+ await h.boot();+ h.releaseTranscript();+ await h.openSession(session);+ await until(() => !!document.querySelector("qm-slack-reply [role=alert]"));+ const reply = document.querySelector("qm-slack-reply")!;+ assert.equal(reply.querySelector("qm-slack-account"), null);+ assert.equal(reply.querySelectorAll("[role=alert]").length, 1);+ assert.match(reply.textContent!, /Slack linking isn’t configured/);+ configured = true;+ (reply.querySelector("button") as HTMLButtonElement).click();+ await until(() => !!reply.querySelector(".welcome-slack"));+ assert.equal(reply.querySelector("[role=alert]"), null);+ } finally {+ await h.close();+ }+});diff --git a/plugins/web-ui/test/slack-reply.test.ts b/plugins/web-ui/test/slack-reply.test.tsnew file mode 100644index 000000000..bfdd5d45d--- /dev/null+++ b/plugins/web-ui/test/slack-reply.test.ts@@ -0,0 +1,45 @@+import assert from "node:assert/strict";+import test from "node:test";+import { harness } from "./deep-link-boot-fixture.ts";++const session = {+ id: "slack-chat",+ threadRef: "ch:C123:123.456",+ surface: "slack",+ scopeId: "channel:C123",+ type: "channel" as const,+ createdAt: Date.now(),+ title: "Slack discussion",+};+async function until(check: () => boolean) {+ for (let i = 0; i < 100 && !check(); i++) await new Promise((resolve) => setTimeout(resolve, 10));+ assert.ok(check());+}++test("Slack chats show a compact account link until the viewer can reply", async () => {+ let linked = false;+ const h = await harness({+ path: "/",+ api: (path) =>+ path.endsWith("/slack/reply-status") ? Response.json({ connected: linked, user: "Alice" }) : undefined,+ });+ try {+ h.releaseSessions();+ await h.boot();+ h.releaseTranscript();+ await h.openSession(session);+ await until(() => !!document.querySelector("qm-slack-reply .welcome-slack"));+ assert.equal(document.querySelector("qm-slack-reply textarea"), null);+ assert.match(document.querySelector("qm-slack-reply")!.textContent!, /Send replies here as yourself/);+ linked = true;+ window.dispatchEvent(new window.Event("focus"));+ await until(() => !!document.querySelector("qm-slack-reply textarea"));+ assert.match(+ document.querySelector("qm-slack-reply .composer-input")!.getAttribute("placeholder")!,+ /Reply in Slack as Alice/,+ );+ assert.equal(document.querySelector(".chat-subtitle")!.textContent, "slack");+ } finally {+ await h.close();+ }+});diff --git a/src/api/deps.ts b/src/api/deps.tsindex ba19e78cb..499019f69 100644--- a/src/api/deps.ts+++ b/src/api/deps.ts@@ -1,3 +1,4 @@+import type { SlackWebClientFactory } from "../slack/web-client.ts";import type { TeamStore } from "../teams/teams.ts";import type { DecisionStore } from "../decisions/store.ts";import type { ExternalSlackPolicies } from "../resolution/external-slack.ts";@@ -107,6 +108,7 @@ export interface ServerDeps {managedSlack?: ManagedSlack;slackInstallation?: SlackInstallationStore;slackInstallationFetch?: typeof fetch;+ slackWebClient?: SlackWebClientFactory;slackInstallationSocketAppId?: SlackSocketAppIdReader;slackEnvironmentState?: "absent" | "configured" | "partial";slackEventsPort?: number;diff --git a/src/api/routes/composio.ts b/src/api/routes/composio.tsindex ef1d6cdc5..43155059d 100644--- a/src/api/routes/composio.ts+++ b/src/api/routes/composio.ts@@ -1,3 +1,6 @@+import { hasSlackAccount } from "./slack-composio.ts";+import { slackReply } from "./slack-reply.ts";+import { nativeSlackConfigured, nativeSlackConnection } from "./slack-native.ts";import { isBackendCredential } from "../../credentials/keychain.ts";import { livePersonCapability } from "../artifact-share.ts";import { mintSignedPayload, verifySignedPayload } from "../../auth/signed-token.ts";@@ -21,7 +24,7 @@ export function composioUserId(org: string, principal: string): string {.digest("hex")}`;}-function composioUserIds(principal: string): string[] {+export function composioUserIds(principal: string): string[] {return [...new Set(personIds(principal).map((id) => composioUserId(orgId(), id)))];}@@ -48,7 +51,7 @@ async function activeRun(ctx: ApiCtx): Promise<boolean> {return true;}-async function credential(ctx: ApiCtx): Promise<{ key: string; principal: string } | null> {+export async function credential(ctx: ApiCtx): Promise<{ key: string; principal: string } | null> {if (!(await activeRun(ctx))) return null;const principal = ctx.capability?.actorId ?? ctx.actor?.p;if (!principal) {@@ -145,7 +148,7 @@ function executeFailureCause(error: unknown, timedOut: boolean): string {const EXECUTE_TIMEOUT_MS = 90_000;-async function request(+export async function request(ctx: ApiCtx,key: string,path: string,@@ -520,10 +523,33 @@ export interface SlackAccountLink {}async function slackStatus(ctx: ApiCtx): Promise<void> {- const access = await credential(ctx);- if (!access) return;+ ctx.res.setHeader("Cache-Control", "no-store");const installation = await ctx.deps.slackInstallation?.get();const workspaceInstalled = Boolean(installation?.botToken || ctx.deps.slackEnvBotToken);+ let nativeOAuth = false;+ if (ctx.actor && !ctx.actor.imp && !ctx.capability) {+ try {+ if (!(await activePrincipal(ctx.deps, ctx.actor.p))) return sendJson(ctx.res, 403, { error: "forbidden" });+ const native = await nativeSlackConnection(ctx);+ if (native)+ return sendJson(ctx.res, 200, {+ connected: true,+ user: native.user,+ workspace: native.workspace,+ nativeOAuth: true,+ workspaceInstalled,+ });+ nativeOAuth = await nativeSlackConfigured(ctx);+ if (nativeOAuth && !(await hasSlackAccount(ctx)))+ return sendJson(ctx.res, 200, { connected: false, nativeOAuth, workspaceInstalled });+ } catch (error) {+ reportFailure("Slack connection status", error);+ return sendJson(ctx.res, 502, { error: "slack_unavailable" });+ }+ }+ const access = await credential(ctx);+ if (!access) return;+ctx.res.setHeader("Cache-Control", "no-store");let failed = false;for (const id of personIds(access.principal)) {@@ -551,7 +577,7 @@ async function slackStatus(ctx: ApiCtx): Promise<void> {}return failed? sendJson(ctx.res, 502, { error: "status_unavailable" })- : sendJson(ctx.res, 200, { connected: false, workspaceInstalled });+ : sendJson(ctx.res, 200, { connected: false, workspaceInstalled, nativeOAuth });}async function completeSlack(ctx: ApiCtx): Promise<void> {@@ -726,6 +752,8 @@ export const composioRoutes: ReadonlyArray<Route<ApiCtx>> = [{ method: "GET", path: "/v1/composio/tools", auth: "either", handle: tools },{ method: "POST", path: "/v1/composio/execute", auth: "either", handle: execute },{ method: "POST", path: "/v1/composio/complete-auth", auth: "source", handle: completeAuth },+ { method: "POST", path: "/v1/composio/slack/reply-status", auth: "source", handle: (ctx) => slackReply(ctx, false) },+ { method: "POST", path: "/v1/composio/slack/reply", auth: "source", handle: (ctx) => slackReply(ctx, true) },{ method: "GET", path: "/v1/composio/slack", auth: "source", handle: slackStatus },{ method: "POST", path: "/v1/composio/slack/authorize", auth: "source", handle: (ctx) => authorize(ctx, true) },{ method: "POST", path: "/v1/composio/slack/complete", auth: "source", handle: completeSlack },diff --git a/src/api/routes/slack-composio.ts b/src/api/routes/slack-composio.tsnew file mode 100644index 000000000..e153506c4--- /dev/null+++ b/src/api/routes/slack-composio.ts@@ -0,0 +1,70 @@+import { createExactSecretValueMasker } from "../../security/secret-masking.ts";+import { redactSecrets } from "../../harness/redact-secrets.ts";+import { errMessage } from "../../util/errors.ts";+import { personIds, samePerson } from "../../directory/person.ts";+import { composioUserIds, credential, request as composioRequest } from "./composio.ts";+import type { ApiCtx } from "./route.ts";++export async function hasSlackAccount(ctx: ApiCtx): Promise<boolean> {+ for (const id of personIds(ctx.actor!.p)) {+ const record = await ctx.deps.slackAccounts?.get(id);+ if (record && samePerson(record.memberId, ctx.actor!.p)) return true;+ }+ return false;+}++export async function composioSlackConnection(ctx: ApiCtx) {+ const access = await credential(ctx);+ if (!access) return undefined;+ const request: typeof composioRequest = async (...args) => {+ try {+ return await composioRequest(...args);+ } catch (error) {+ const sanitized = new Error(createExactSecretValueMasker([access.key])(redactSecrets(errMessage(error))));+ throw sanitized;+ }+ };+ for (const id of personIds(access.principal)) {+ const record = await ctx.deps.slackAccounts?.get(id);+ if (!record || !samePerson(record.memberId, access.principal)) continue;+ const account = await request(ctx, access.key, `/connected_accounts/${encodeURIComponent(record.accountId)}`);+ if (+ account.id !== record.accountId ||+ !composioUserIds(access.principal).includes(String(account.user_id)) ||+ (account.toolkit as { slug?: string } | undefined)?.slug !== "slack" ||+ account.status !== "ACTIVE" ||+ account.is_disabled === true+ )+ continue;+ const proxy = async (method: string, payload?: Record<string, unknown>) => {+ const result = await request(ctx, access.key, "/tools/execute/proxy", {+ connected_account_id: record.accountId,+ endpoint: `https://slack.com/api/${method}`,+ method: method === "chat.postMessage" ? "POST" : "GET",+ ...(method === "chat.postMessage"+ ? { body: payload, parameters: [{ name: "Content-Type", value: "application/json", in: "header" }] }+ : {+ parameters: Object.entries(payload ?? {}).map(([name, value]) => ({+ name,+ value: String(value),+ in: "query",+ })),+ }),+ });+ return result.data as+ { ok?: boolean; bot_id?: string; user_id?: string; team_id?: string; ts?: string; error?: string } | undefined;+ };+ const identity = await proxy("auth.test");+ const installation = await ctx.deps.slackInstallation?.get();+ if (+ !identity?.ok ||+ identity.bot_id ||+ identity.user_id !== record.userId ||+ identity.team_id !== record.teamId ||+ (installation?.teamId && identity.team_id !== installation.teamId)+ )+ continue;+ return { call: proxy, user: record.user, workspace: record.workspace };+ }+ return null;+}diff --git a/src/api/routes/slack-native.ts b/src/api/routes/slack-native.tsnew file mode 100644index 000000000..d091fa127--- /dev/null+++ b/src/api/routes/slack-native.ts@@ -0,0 +1,56 @@+import { createExactSecretValueMasker } from "../../security/secret-masking.ts";+import { redactSecrets } from "../../harness/redact-secrets.ts";+import { errMessage } from "../../util/errors.ts";+import { ErrorCode, type WebAPIPlatformError, type AuthTestResponse } from "@slack/web-api";+import { slackWebClient } from "../../slack/web-client.ts";+import { personIds, samePerson } from "../../directory/person.ts";+import { resolverFor } from "./connectors.ts";+import type { ApiCtx } from "./route.ts";++export async function nativeSlackConfigured(ctx: ApiCtx): Promise<boolean> {+ try {+ await resolverFor(ctx.deps)("slack", {});+ return Boolean(ctx.deps.connectorTokens);+ } catch {+ return false;+ }+}++export async function nativeSlackConnection(ctx: ApiCtx) {+ const principal = ctx.actor!.p;+ for (const id of personIds(principal)) {+ for (const accountType of ["default", "personal", "company"]) {+ const auth = await ctx.deps.connectorTokens?.connectorDerivedAuth("slack.com", id, accountType);+ if (!auth) continue;+ const call = async (method: string, payload?: Record<string, unknown>, token = auth.accessToken) => {+ const client = slackWebClient(token, ctx.deps.slackWebClient);+ try {+ return (await client.apiCall(method, payload)) as AuthTestResponse & { ts?: string };+ } catch (error) {+ if (error instanceof Error && "code" in error && error.code === ErrorCode.PlatformError)+ return (error as WebAPIPlatformError).data as AuthTestResponse & { ts?: string };+ const sanitized = new Error(createExactSecretValueMasker([token])(redactSecrets(errMessage(error))));+ throw sanitized;+ }+ };+ const identity = await call("auth.test");+ if (!identity.ok || identity.bot_id || !identity.user_id || !identity.team_id) continue;+ const members = (await ctx.deps.directory?.list()) ?? [];+ const member = members.find(+ (m) =>+ (m.slackId === identity.user_id || m.principalId === identity.user_id) &&+ samePerson(m.principalId, principal),+ );+ if (!member || member.type !== "internal") continue;+ const installation = await ctx.deps.slackInstallation?.get();+ let teamId = installation?.teamId;+ if (!teamId && ctx.deps.slackEnvBotToken) {+ const bot = await call("auth.test", undefined, ctx.deps.slackEnvBotToken);+ if (bot.ok) teamId = bot.team_id;+ }+ if (!teamId || teamId !== identity.team_id) continue;+ return { call, user: identity.user ?? member.displayName, workspace: identity.team };+ }+ }+ return null;+}diff --git a/src/api/routes/slack-reply.ts b/src/api/routes/slack-reply.tsnew file mode 100644index 000000000..94e95f7f2--- /dev/null+++ b/src/api/routes/slack-reply.ts@@ -0,0 +1,130 @@+import { nativeSlackConfigured, nativeSlackConnection } from "./slack-native.ts";+import { composioSlackConnection, hasSlackAccount } from "./slack-composio.ts";+import { parseSlackThreadRef } from "../../slack/message-gating.ts";+import { sendJson } from "../http.ts";+import { reportFailure } from "../../util/errors.ts";+import { activePrincipal } from "./shared.ts";+import type { ApiCtx } from "./route.ts";++export async function slackReply(ctx: ApiCtx, send: boolean): Promise<void> {+ if (!ctx.actor || ctx.actor.imp || ctx.capability)+ return sendJson(ctx.res, 403, { error: "browser_identity_required" });+ ctx.res.setHeader("Cache-Control", "no-store");+ if (!(await activePrincipal(ctx.deps, ctx.actor.p))) return sendJson(ctx.res, 403, { error: "forbidden" });+ const body = ctx.body as { sessionId?: unknown; text?: unknown; clientMessageId?: unknown } | null;+ if (typeof body?.sessionId !== "string") return sendJson(ctx.res, 400, { error: "invalid_session" });+ const source = await ctx.app.getSessionForViewer(body.sessionId, ctx.actor.p);+ if (!source) return sendJson(ctx.res, 404, { error: "not_found" });+ const target = parseSlackThreadRef(source.session.threadRef);+ if (!target || !/^[CDG][A-Z0-9]+$/.test(target.container) || (target.root && !/^\d+\.\d+$/.test(target.root)))+ return sendJson(ctx.res, 400, { error: "not_slack" });+ if (+ send &&+ (typeof body.text !== "string" ||+ !body.text.trim() ||+ body.text.length > 4000 ||+ typeof body.clientMessageId !== "string" ||+ !/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(body.clientMessageId))+ )+ return sendJson(ctx.res, 400, { error: "invalid_message" });+ if (send && !ctx.deps.deliveries)+ return sendJson(ctx.res, 503, {+ error: "slack_unavailable",+ message: "Slack replies are temporarily unavailable.",+ });+ let slackConfirmed = false;+ const recordReply = async (ts: unknown, name: string) => {+ slackConfirmed = true;+ if (typeof ts !== "string" || !/^\d+\.\d+$/.test(ts)) throw new Error("Slack response missing timestamp");+ await ctx.deps.deliveries!.enqueue({+ destination: {+ type: "web",+ target: source.session.threadRef,+ audienceScopeId: source.session.scopeId,+ webTranscript: { kind: "slack_reply", sessionId: body.sessionId as string, ts, name },+ },+ text: body.text as string,+ idempotencyKey: `slack-reply:${body.sessionId}:${target.container}:${ts}`,+ });+ return sendJson(ctx.res, 200, { sent: true, ts });+ };+ let attemptedSend = false;+ const replyVia = async (connection: {+ user?: string;+ workspace?: string;+ call: (+ method: string,+ payload?: Record<string, unknown>,+ ) => Promise<{ ok?: boolean; ts?: string; error?: string } | undefined>;+ }) => {+ const conversation = await connection.call("conversations.info", { channel: target.container });+ if (!conversation?.ok) {+ reportFailure(+ "slack reply: conversation access",+ new Error(conversation?.error ?? "Slack rejected conversation access"),+ `session=${body.sessionId}`,+ );+ return sendJson(ctx.res, 403, {+ error: "slack_access_denied",+ message: "Your Slack account cannot access this conversation. Check its Slack permissions.",+ });+ }+ if (!send)+ return sendJson(ctx.res, 200, { connected: true, user: connection.user, workspace: connection.workspace });+ attemptedSend = true;+ const result = await connection.call("chat.postMessage", {+ channel: target.container,+ ...(target.root ? { thread_ts: target.root } : {}),+ text: body.text,+ client_msg_id: body.clientMessageId,+ as_user: true,+ unfurl_links: false,+ unfurl_media: false,+ });+ if (!result?.ok) {+ reportFailure(+ "slack reply: send",+ new Error(result?.error ?? "Slack rejected message send"),+ `session=${body.sessionId}`,+ );+ return sendJson(ctx.res, 403, {+ error: "slack_send_failed",+ message:+ "Slack could not send your message. Check your account’s conversation access and permission to send messages.",+ });+ }+ return recordReply(result.ts, connection.user ?? ctx.actor!.p);+ };+ try {+ const native = await nativeSlackConnection(ctx);+ if (native) return await replyVia(native);+ const hasComposioLink = await hasSlackAccount(ctx);+ if (!hasComposioLink && (await nativeSlackConfigured(ctx)))+ return sendJson(ctx.res, send ? 409 : 200, {+ connected: false,+ error: "slack_link_required",+ message: "Link your personal Slack account to reply.",+ });+ const connection = await composioSlackConnection(ctx);+ if (connection === undefined) return;+ if (connection) return await replyVia(connection);+ return sendJson(ctx.res, send ? 409 : 200, {+ connected: false,+ error: "slack_link_required",+ message: "Link your personal Slack account to reply.",+ });+ } catch (error) {+ reportFailure("slack reply", error, `session=${body.sessionId}`);+ if (slackConfirmed)+ return sendJson(ctx.res, 502, {+ error: "transcript_unavailable",+ message: "Slack sent your message, but its transcript update could not be saved. Do not resend it.",+ });+ return sendJson(ctx.res, 502, {+ error: "slack_unavailable",+ message: attemptedSend+ ? "The send outcome is unknown. Check Slack before trying again."+ : "Could not verify your Slack connection. Please try again.",+ });+ }+}diff --git a/src/delivery/delivery-store.ts b/src/delivery/delivery-store.tsindex a81afbe74..5eaf641f7 100644--- a/src/delivery/delivery-store.ts+++ b/src/delivery/delivery-store.ts@@ -68,7 +68,13 @@ export function createDeliveryStore(opts?: { maxAgeMs?: number }): DeliveryStoreconst expireOveraged = (now: number): void => {for (const d of deliveries.values()) {- if (d.deliveredAt !== null || d.shadow || d.expiredAt !== undefined) continue;+ if (+ d.deliveredAt !== null ||+ d.shadow ||+ d.expiredAt !== undefined ||+ d.destination.webTranscript?.kind === "slack_reply"+ )+ continue;if ((claimedUntil.get(d.id) ?? 0) > now) continue;if (now - d.createdAt < maxAgeMs) continue;d.expiredAt = now;diff --git a/src/delivery/postgres-delivery-store.ts b/src/delivery/postgres-delivery-store.tsindex 9cf52c8f5..6fdfb980d 100644--- a/src/delivery/postgres-delivery-store.ts+++ b/src/delivery/postgres-delivery-store.ts@@ -101,6 +101,7 @@ export function createPostgresDeliveryStore(connectionString: string, opts?: { mWHERE id IN (SELECT id FROM deliveriesWHERE delivered_at IS NULL AND expired_at IS NULL AND NOT shadow+ AND destination->'webTranscript'->>'kind' IS DISTINCT FROM 'slack_reply'AND created_at <= ${NOW_MS_SQL} - $1AND (claim_expires_at IS NULLOR claim_expires_at <= ${NOW_MS_SQL})diff --git a/src/delivery/web-transcript-delivery.ts b/src/delivery/web-transcript-delivery.tsindex 1d2b5cc5f..a36af3b29 100644--- a/src/delivery/web-transcript-delivery.ts+++ b/src/delivery/web-transcript-delivery.ts@@ -9,7 +9,7 @@ const WRITE_GIVEUP_MS = 10 * 60_000;type WebTranscriptSessions = Pick<SessionStore,- "append" | "getByThread" | "acquireLease" | "releaseLease" | "getEntries"+ "append" | "hasDeliveryEntry" | "get" | "getByThread" | "acquireLease" | "releaseLease" | "getEntries">;export function turnRecordedFailure(@@ -42,34 +42,50 @@ export function withWebTranscriptDeliveries(store: DeliveryStore, sessions: WebTif (recorded.size >= RECORDED_CACHE_CAP) recorded.clear();recorded.add(key);};- const overdue = (d: Delivery): boolean => Date.now() - d.createdAt > WRITE_GIVEUP_MS;+ const overdue = (d: Delivery): boolean =>+ d.destination.webTranscript?.kind !== "slack_reply" && Date.now() - d.createdAt > WRITE_GIVEUP_MS;const appendTranscriptEntry = async (d: Delivery, session: { id: string; scopeId: ScopeId }): Promise<boolean> => {const { lease } = await sessions.acquireLease(session.id, "backfill");if (!lease) return false;try {const tail = await sessions.getEntries(session.id, { limit: DEDUPE_SCAN_LIMIT });- if (tail.some((entry) => entryDeliveryKey(entry) === d.idempotencyKey)) return true;const note = d.destination.webTranscript;+ const reply = note?.kind === "slack_reply" ? note : undefined;+ if (await sessions.hasDeliveryEntry(session.id, d.idempotencyKey, reply?.ts)) return true;const failure = note?.kind === "turn_failure" ? note : undefined;if (failure && turnRecordedFailure(tail, failure)) return true;const scopeLabel = session.scopeId;const ownReply = d.provenance?.sourceThreadRef === d.destination.target;const via = d.provenance?.trigger && !ownReply ? d.provenance.trigger : undefined;- const entry = failure- ? {- type: "system" as const,- payload: {- kind: "turn_failure",- message: d.text,- deliveryKey: d.idempotencyKey,- ...(failure.runId ? { runId: failure.runId } : {}),- },- }- : {- type: "assistant" as const,- payload: { text: d.text, deliveryKey: d.idempotencyKey, ...(via ? { via } : {}) },- };+ let entry: Pick<SessionEntry, "type" | "payload">;+ if (reply) {+ entry = {+ type: "user",+ payload: {+ text: d.text,+ name: reply.name,+ ts: reply.ts,+ slackReplyReceipt: true,+ deliveryKey: d.idempotencyKey,+ },+ };+ } else if (failure) {+ entry = {+ type: "system",+ payload: {+ kind: "turn_failure",+ message: d.text,+ deliveryKey: d.idempotencyKey,+ ...(failure.runId ? { runId: failure.runId } : {}),+ },+ };+ } else {+ entry = {+ type: "assistant",+ payload: { text: d.text, deliveryKey: d.idempotencyKey, ...(via ? { via } : {}) },+ };+ }await sessions.append(lease, { ...entry, scopeLabel });return true;} finally {@@ -86,7 +102,11 @@ export function withWebTranscriptDeliveries(store: DeliveryStore, sessions: WebTremember(d.idempotencyKey);return true;}- const session = await sessions.getByThread(d.destination.target);+ const note = d.destination.webTranscript;+ const session =+ note?.kind === "slack_reply"+ ? await sessions.get(note.sessionId)+ : await sessions.getByThread(d.destination.target);if (!session) {console.error(`[delivery] web delivery ${d.idempotencyKey} targets ${d.destination.target}, which has no session — delivering as a nudge only`,@@ -130,6 +150,17 @@ export function withWebTranscriptDeliveries(store: DeliveryStore, sessions: WebTreturn {...store,+ async enqueue(input) {+ const delivery = await store.enqueue(input);+ if (delivery.destination.webTranscript?.kind === "slack_reply") {+ try {+ await recordedForDelivery(delivery);+ } catch (error) {+ swallow("slack reply transcript write (will retry)", error);+ }+ }+ return delivery;+ },async pending(type) {const rows = await store.pending(type);return type === "web" ? drained(rows) : rows;diff --git a/src/harness/context-compaction.ts b/src/harness/context-compaction.tsindex d26613e34..b48e873a7 100644--- a/src/harness/context-compaction.ts+++ b/src/harness/context-compaction.ts@@ -51,6 +51,7 @@ function modelReplayable(entries: SessionEntry[]): SessionEntry[] {(e) =>((e.type !== "thinking" && e.type !== "text") || isObj((e.payload as { step?: unknown } | null)?.step)) &&e.type !== "soul" &&+ (e.payload as { slackReplyReceipt?: unknown } | null)?.slackReplyReceipt !== true &&(e.payload as { kind?: unknown } | null)?.kind !== "turn_failure",);}diff --git a/src/sessions/memory-session-store.ts b/src/sessions/memory-session-store.tsindex abf0860d7..3cffb9157 100644--- a/src/sessions/memory-session-store.ts+++ b/src/sessions/memory-session-store.ts@@ -1,3 +1,4 @@+import { transcriptEntries } from "./transcript-source.ts";import { randomUUID } from "node:crypto";import type { Session, SessionEntry, ScopeId } from "../types.ts";import type { GoalRecord } from "../harness/goal.ts";@@ -295,8 +296,19 @@ export function createMemorySessionStore(opts: StoreOptions = {}): SessionStore});},+ async hasDeliveryEntry(sessionId, deliveryKey, slackTs) {+ return (entries.get(sessionId) ?? []).some((entry) => {+ const payload = entry.payload as { deliveryKey?: string; ts?: string } | null;+ return (+ payload?.deliveryKey === deliveryKey ||+ (slackTs !== undefined && entry.type === "user" && payload?.ts === slackTs)+ );+ });+ },+async getEntries(sessionId, opts?: GetEntriesOptions) {- const log = entries.get(sessionId) ?? [];+ const all = entries.get(sessionId) ?? [];+ const log = opts?.transcript ? transcriptEntries(all) : all;const since = opts?.sinceSeq ?? 0;const filtered = log.filter((e) => e.seq >= since && (opts?.beforeSeq === undefined || e.seq < opts.beforeSeq));return opts?.limit !== undefined ? filtered.slice(-opts.limit) : filtered;@@ -305,8 +317,8 @@ export function createMemorySessionStore(opts: StoreOptions = {}): SessionStoreasync countEntriesBefore(sessionId, beforeSeq, principalId) {const win = principalId === undefined ? undefined : windows.get(sessionId)?.get(principalId);if (principalId !== undefined && !win) return 0;- return (entries.get(sessionId) ?? []).filter(- (e) => e.seq < beforeSeq && e.type !== "soul" && (!win || entryWithinTenure(e, win)),+ return transcriptEntries((entries.get(sessionId) ?? []).filter((e) => !win || entryWithinTenure(e, win))).filter(+ (e) => e.seq < beforeSeq,).length;},@@ -514,11 +526,9 @@ export function createMemorySessionStore(opts: StoreOptions = {}): SessionStoreasync visibleEntries(sessionId, principalId, opts?: GetEntriesOptions) {const win = windows.get(sessionId)?.get(principalId);if (!win) return [];- const visible = (entries.get(sessionId) ?? []).filter(- (e) =>- entryWithinTenure(e, win) &&- e.seq >= (opts?.sinceSeq ?? 0) &&- (opts?.beforeSeq === undefined || e.seq < opts.beforeSeq),+ const all = (entries.get(sessionId) ?? []).filter((e) => entryWithinTenure(e, win));+ const visible = (opts?.transcript ? transcriptEntries(all) : all).filter(+ (e) => e.seq >= (opts?.sinceSeq ?? 0) && (opts?.beforeSeq === undefined || e.seq < opts.beforeSeq),);return opts?.limit !== undefined ? visible.slice(-opts.limit) : visible;},diff --git a/src/sessions/postgres-session-store.ts b/src/sessions/postgres-session-store.tsindex 6e0b9a340..69c578547 100644--- a/src/sessions/postgres-session-store.ts+++ b/src/sessions/postgres-session-store.ts@@ -236,6 +236,18 @@ export function createPostgresSessionStore(connectionString: string, opts: StoreparticipantWindowBounds(entry, participant).map((bounds) => `(${bounds.join(" OR ")})`).join(" AND ");+ function transcriptEntryPredicate(alias: string, participant?: string): string {+ return `${alias}.type <> 'soul' AND (+ ${alias}.payload::jsonb -> 'slackReplyReceipt' IS DISTINCT FROM 'true'::jsonb+ OR NOT EXISTS (+ SELECT 1 FROM session_entries received+ WHERE received.session_id = ${alias}.session_id AND received.type = 'user'+ AND received.payload::jsonb ->> 'ts' = ${alias}.payload::jsonb ->> 'ts'+ AND received.payload::jsonb -> 'slackReplyReceipt' IS DISTINCT FROM 'true'::jsonb+ ${participant ? `AND ${withinParticipantWindow("received", participant)}` : ""}+ )+ )`;+ }const [fromBounds, toBounds] = participantWindowBounds("x", "p");const participantPresenceSql = fromBounds.flatMap((from) =>@@ -1175,13 +1187,13 @@ export function createPostgresSessionStore(connectionString: string, opts: Storeconst rows =principalId === undefined? await q(- "SELECT count(*)::int AS n FROM session_entries WHERE session_id = $1 AND seq < $2 AND type <> 'soul'",+ `SELECT count(*)::int AS n FROM session_entries e WHERE session_id = $1 AND seq < $2 AND ${transcriptEntryPredicate("e")}`,[sessionId, beforeSeq],): await q(`SELECT count(*)::int AS n FROM session_entries eJOIN participants p ON p.session_id = e.session_id AND p.principal_id = $3- WHERE e.session_id = $1 AND e.seq < $2 AND e.type <> 'soul' AND ${withinParticipantWindow("e", "p")}`,+ WHERE e.session_id = $1 AND e.seq < $2 AND ${transcriptEntryPredicate("e", "p")} AND ${withinParticipantWindow("e", "p")}`,[sessionId, beforeSeq, principalId],);return Number(rows[0]?.n ?? 0);@@ -1236,9 +1248,20 @@ export function createPostgresSessionStore(connectionString: string, opts: Store});},+ async hasDeliveryEntry(sessionId, deliveryKey, slackTs) {+ const rows = await q(+ `SELECT 1 FROM session_entries WHERE session_id = $1+ AND (payload::jsonb ->> 'deliveryKey' = $2+ OR (type = 'user' AND payload::jsonb ->> 'ts' = $3)) LIMIT 1`,+ [sessionId, deliveryKey, slackTs ?? null],+ );+ return rows.length > 0;+ },+async getEntries(sessionId, opts?: GetEntriesOptions): Promise<SessionEntry[]> {const params: unknown[] = [sessionId, opts?.sinceSeq ?? 0];- let sql = "SELECT * FROM session_entries WHERE session_id = $1 AND seq >= $2";+ let sql = "SELECT e.* FROM session_entries e WHERE session_id = $1 AND seq >= $2";+ if (opts?.transcript) sql += ` AND ${transcriptEntryPredicate("e")}`;if (opts?.beforeSeq !== undefined) {params.push(opts.beforeSeq);sql += ` AND seq < $${params.length}`;@@ -1566,6 +1589,7 @@ export function createPostgresSessionStore(connectionString: string, opts: StoreJOIN participants p ON p.session_id = e.session_id AND p.principal_id = $2WHERE e.session_id = $1 AND e.seq >= $3AND ${withinParticipantWindow("e", "p")}`;+ if (opts?.transcript) sql += ` AND ${transcriptEntryPredicate("e", "p")}`;if (opts?.beforeSeq !== undefined) {params.push(opts.beforeSeq);sql += ` AND e.seq < $${params.length}`;diff --git a/src/sessions/session-store.ts b/src/sessions/session-store.tsindex d6c48fc5f..ebba25198 100644--- a/src/sessions/session-store.ts+++ b/src/sessions/session-store.ts@@ -146,6 +146,7 @@ export interface SessionPin extends NewSessionPin {export const isWebThread = (threadRef: string): boolean => threadRef.startsWith("web:");export interface GetEntriesOptions {+ transcript?: boolean;sinceSeq?: number;beforeSeq?: number;limit?: number;@@ -584,6 +585,7 @@ export interface SessionStore {append(lease: Lease, entry: NewEntry): Promise<SessionEntry>;appendMany(lease: Lease, entries: readonly NewEntry[]): Promise<SessionEntry[]>;getEntries(sessionId: string, opts?: GetEntriesOptions): Promise<SessionEntry[]>;+ hasDeliveryEntry(sessionId: string, deliveryKey: string, slackTs?: string): Promise<boolean>;countEntriesBefore(sessionId: string, beforeSeq: number, principalId?: string): Promise<number>;getContextWindow(sessionId: string): Promise<ContextWindow>;getEntry(sessionId: string, seq: number): Promise<SessionEntry | undefined>;diff --git a/src/sessions/transcript-source.ts b/src/sessions/transcript-source.tsindex 49592f8c8..eb2a8f17f 100644--- a/src/sessions/transcript-source.ts+++ b/src/sessions/transcript-source.ts@@ -13,7 +13,18 @@ export interface TranscriptSource {forViewer(sessionId: string, principalId: string, opts?: GetEntriesOptions): Promise<TranscriptRead>;}-const transcriptEntries = (entries: SessionEntry[]): SessionEntry[] => entries.filter((e) => e.type !== "soul");+export function transcriptEntries(entries: readonly SessionEntry[]): SessionEntry[] {+ const received = new Set(+ entries.flatMap((entry) => {+ const payload = entry.payload as { ts?: string; slackReplyReceipt?: boolean } | null;+ return entry.type === "user" && payload?.ts && !payload.slackReplyReceipt ? [payload.ts] : [];+ }),+ );+ return entries.filter((entry) => {+ const payload = entry.payload as { ts?: string; slackReplyReceipt?: boolean } | null;+ return entry.type !== "soul" && !(payload?.slackReplyReceipt && payload.ts && received.has(payload.ts));+ });+}const emptyWindowStart = (opts?: GetEntriesOptions): number =>Math.min(opts?.sinceSeq ?? Infinity, opts?.beforeSeq ?? Infinity, Number.MAX_SAFE_INTEGER);@@ -26,8 +37,8 @@ export function createTranscriptSource(sessions: TranscriptStore): TranscriptSou): Promise<TranscriptRead> => {const entries = transcriptEntries(principalId === undefined- ? await sessions.getEntries(sessionId, opts)- : await sessions.visibleEntries(sessionId, principalId, opts),+ ? await sessions.getEntries(sessionId, { ...opts, transcript: true })+ : await sessions.visibleEntries(sessionId, principalId, { ...opts, transcript: true }),);const windowed = opts?.sinceSeq !== undefined || (opts?.limit !== undefined && entries.length >= opts.limit);const earlier = windoweddiff --git a/src/slack/web-client.ts b/src/slack/web-client.tsnew file mode 100644index 000000000..cefbd9a07--- /dev/null+++ b/src/slack/web-client.ts@@ -0,0 +1,16 @@+import { WebClient, type WebClientOptions } from "@slack/web-api";++export type SlackWebClientFactory = (token: string, options: WebClientOptions) => Pick<WebClient, "apiCall">;++export function slackWebClient(+ token: string,+ factory: SlackWebClientFactory = (token, options) => new WebClient(token, options),+ timeout = 20_000,+) {+ return factory(token, {+ retryConfig: { retries: 0 },+ rejectRateLimitedCalls: true,+ attachOriginalToWebAPIRequestError: false,+ timeout,+ });+}diff --git a/src/types.ts b/src/types.tsindex dcca1c0b1..40f7db19c 100644--- a/src/types.ts+++ b/src/types.ts@@ -230,7 +230,10 @@ export interface Destination {pin?: { messageTs: string; remove?: boolean };identity?: string;debugFooter?: string;- webTranscript?: { kind: "reply" } | { kind: "turn_failure"; notBefore: number; runId?: string };+ webTranscript?:+ | { kind: "reply" }+ | { kind: "slack_reply"; sessionId: string; ts: string; name: string }+ | { kind: "turn_failure"; notBefore: number; runId?: string };}export interface CandidateDestination extends Destination {diff --git a/test/composio-route.test.ts b/test/composio-route.test.tsindex f131854e6..4eabaaeca 100644--- a/test/composio-route.test.ts+++ b/test/composio-route.test.ts@@ -1,3 +1,4 @@+import { createDeliveryStore } from "../src/delivery/delivery-store.ts";import type { CapabilityClaims } from "../src/auth/capability-token.ts";import { test } from "node:test";import assert from "node:assert/strict";@@ -20,10 +21,12 @@ function fixture() {key: deriveConnectorKey("composio-test"),});const acl = createAclStore();+ const app = { getSessionForViewer: async (_id: string, _viewer: string): Promise<unknown> => null };const calls: Array<{ url: string; init?: RequestInit }> = [];const replies: unknown[] = [];const deps: Partial<ServerDeps> = {keychain,+ deliveries: createDeliveryStore(),serviceCreds: keychain,acl,composioReturns: createMemoryMap(),@@ -45,7 +48,13 @@ function fixture() {return Response.json(result);}) as typeof fetch,};- async function invoke(path: string, body?: unknown, actor: string | null = "alice", capability?: CapabilityClaims) {+ async function invoke(+ path: string,+ body?: unknown,+ actor: string | null = "alice",+ capability?: CapabilityClaims,+ impersonating = false,+ ) {let status = 0;let text = "";const url = new URL(path, "http://localhost");@@ -61,11 +70,12 @@ function fixture() {} as unknown as ServerResponse;const ctx = {deps,+ app,res,url,body,capability,- actor: actor ? { p: actor, exp: Date.now() + 60_000 } : null,+ actor: actor ? { p: actor, exp: Date.now() + 60_000, ...(impersonating ? { imp: "admin" } : {}) } : null,} as ApiCtx;const route = composioRoutes.find((r) => "path" in r && r.path === url.pathname)!;await route.handle(ctx);@@ -94,7 +104,7 @@ function fixture() {grantedBy: "admin",});}- return { invoke, own, shared, calls, replies, deps };+ return { invoke, own, shared, calls, replies, deps, app };}test("Composio requires a verified actor and never uses another person's key", async () => {@@ -862,3 +872,276 @@ test("authorization failures keep a redacted upstream cause for operators", asynassert.match(report, /req_123/);assert.doesNotMatch(report, /private-key|sk-other/);});++async function slackReplyFixture() {+ const f = fixture();+ await f.own();+ f.app.getSessionForViewer = async (id, viewer) =>+ id === "session" && viewer === "alice" ? { session: { threadRef: "ch:C123:123.456" } } : null;+ f.deps.slackAccounts = createMemoryMap();+ await f.deps.slackAccounts.put("alice", {+ principalId: "alice",+ memberId: "alice",+ accountId: "ca_alice",+ userId: "U123",+ teamId: "T123",+ user: "Alice",+ workspace: "Test",+ });+ const account = {+ id: "ca_alice",+ user_id: composioUserId(orgId(), "alice"),+ toolkit: { slug: "slack" },+ status: "ACTIVE",+ };+ const identity = { data: { ok: true, user_id: "U123", team_id: "T123" } };+ const message = { sessionId: "session", text: "Hello", clientMessageId: "01234567-0123-4123-8123-012345678901" };+ return { ...f, account, identity, message };+}++test("Slack replies use only the viewer's verified user connection and server-side thread destination", async () => {+ const f = await slackReplyFixture();+ f.replies.push(f.account, f.identity, { data: { ok: true } }, { data: { ok: true, ts: "123.789" } });+ const result = await f.invoke("/v1/composio/slack/reply", {+ ...f.message,+ channel: "CATTACK",+ accountId: "ca_other",+ });+ assert.equal(result.status, 200);+ assert.equal(result.data.sent, true);+ const receipts = await f.deps.deliveries!.pending("web");+ assert.equal(receipts.length, 1);+ assert.equal(receipts[0]!.text, "Hello");+ assert.deepEqual(receipts[0]!.destination.webTranscript, {+ kind: "slack_reply",+ sessionId: "session",+ ts: "123.789",+ name: "Alice",+ });+ const request = JSON.parse(String(f.calls.at(-1)!.init!.body));+ assert.equal(request.connected_account_id, "ca_alice");+ assert.equal(request.endpoint, "https://slack.com/api/chat.postMessage");+ assert.deepEqual(request.body, {+ channel: "C123",+ thread_ts: "123.456",+ text: "Hello",+ client_msg_id: f.message.clientMessageId,+ as_user: true,+ unfurl_links: false,+ unfurl_media: false,+ });+});++test("Slack reply status verifies personal access without posting", async () => {+ const f = await slackReplyFixture();+ f.replies.push(f.account, f.identity, { data: { ok: true } });+ assert.equal((await f.invoke("/v1/composio/slack/reply-status", f.message)).data.connected, true);+ assert.equal(f.calls.length, 3);+});++test("Slack replies cannot target hidden sessions or accept blank messages", async () => {+ const f = await slackReplyFixture();+ assert.equal((await f.invoke("/v1/composio/slack/reply", { ...f.message, sessionId: "hidden" })).status, 404);+ assert.equal((await f.invoke("/v1/composio/slack/reply", { ...f.message, text: " " })).status, 400);+ assert.equal((await f.invoke("/v1/composio/slack/reply", f.message, null)).status, 403);+ assert.equal(f.calls.length, 0);+});++test("Slack replies require a linked user account and never fall back to the bot token", async () => {+ const f = await slackReplyFixture();+ await f.deps.slackAccounts!.delete("alice");+ f.deps.slackEnvBotToken = "must-not-use";+ assert.equal((await f.invoke("/v1/composio/slack/reply-status", f.message)).data.connected, false);+ assert.equal((await f.invoke("/v1/composio/slack/reply", f.message)).status, 409);+ assert.equal(f.calls.length, 0);+});++for (const [label, accountPatch, identityPatch] of [+ ["another owner", { user_id: "other" }, {}],+ ["revoked connection", { status: "REVOKED" }, {}],+ ["bot token", {}, { bot_id: "B123" }],+ ["another user", {}, { user_id: "UOTHER" }],+ ["another workspace", {}, { team_id: "TOTHER" }],+] as const)+ test(`Slack replies reject ${label}`, async () => {+ const f = await slackReplyFixture();+ f.replies.push({ ...f.account, ...accountPatch }, { data: { ...f.identity.data, ...identityPatch } });+ assert.equal((await f.invoke("/v1/composio/slack/reply", f.message)).status, 409);+ assert.ok(f.calls.length <= 2);+ });++test("Slack replies preserve an uncertain send result without retrying", async () => {+ const f = await slackReplyFixture();+ f.replies.push(f.account, f.identity, { data: { ok: true } }, new Error("timeout"));+ const result = await f.invoke("/v1/composio/slack/reply", f.message);+ assert.equal(result.status, 502);+ assert.match(result.data.message, /outcome is unknown/);+ assert.equal(f.calls.length, 4);+});++test("Slack replies stop when the personal account cannot access the conversation", async () => {+ const f = await slackReplyFixture();+ f.replies.push(f.account, f.identity, { data: { ok: false, error: "channel_not_found" } });+ assert.equal((await f.invoke("/v1/composio/slack/reply", f.message)).status, 403);+ assert.equal(f.calls.length, 3);+});++test("Slack replies reject impersonation and agent capabilities", async () => {+ const f = await slackReplyFixture();+ assert.equal((await f.invoke("/v1/composio/slack/reply", f.message, "alice", undefined, true)).status, 403);+ assert.equal((await f.invoke("/v1/composio/slack/reply", f.message, "alice", {} as CapabilityClaims)).status, 403);+ assert.equal(f.calls.length, 0);+});++test("Slack replies preserve unthreaded DMs and report Slack permission failures", async () => {+ const f = await slackReplyFixture();+ f.app.getSessionForViewer = async () => ({ session: { threadRef: "dm:D123" } });+ f.replies.push(f.account, f.identity, { data: { ok: true } }, { data: { ok: false, error: "missing_scope" } });+ assert.equal((await f.invoke("/v1/composio/slack/reply", f.message)).status, 403);+ const request = JSON.parse(String(f.calls.at(-1)!.init!.body));+ assert.equal(request.body.channel, "D123");+ assert.equal("thread_ts" in request.body, false);+});++async function nativeSlackFixture(linked = true) {+ const f = await slackReplyFixture();+ const { createDirectoryStore } = await import("../src/directory/directory-store.ts");+ f.deps.slackAccounts = createMemoryMap();+ f.deps.connectorTokens = f.deps.keychain;+ f.deps.oauthEnv = { SLACK_OAUTH_CLIENT_ID: "native-client", SLACK_OAUTH_CLIENT_SECRET: "native-secret" };+ f.deps.directory = createDirectoryStore();+ await f.deps.directory.replace([{ principalId: "alice", slackId: "U123", displayName: "Alice", type: "internal" }]);+ f.deps.slackEnvBotToken = "workspace-bot";+ if (linked) await f.deps.connectorTokens!.setConnectorToken("slack.com", "alice", { accessToken: "alice-user" });+ const nativeCalls: Array<{ method: string; token: string; payload?: object }> = [];+ const nativeReplies: unknown[] = [];+ f.deps.slackWebClient = (token, options) => {+ assert.equal(options.retryConfig?.retries, 0);+ assert.equal(options.rejectRateLimitedCalls, true);+ return {+ async apiCall(method, payload) {+ nativeCalls.push({ method, token, payload });+ if (token === "workspace-bot") return { ok: true, team_id: "T123" };+ const value = nativeReplies.shift();+ if (value instanceof Error) throw value;+ if ((value as { ok?: boolean })?.ok === false)+ throw Object.assign(new Error("Slack API error"), { code: "slack_webapi_platform_error", data: value });+ return value as { ok: boolean };+ },+ };+ };+ const nativeIdentity = { ok: true, user_id: "U123", team_id: "T123", user: "Alice", team: "Test" };+ return { ...f, nativeCalls, nativeReplies, nativeIdentity };+}++test("native Slack replies use the authenticated user's token and server destination without Composio", async () => {+ const f = await nativeSlackFixture();+ f.nativeReplies.push(f.nativeIdentity, { ok: true }, { ok: true, ts: "123.789" });+ const result = await f.invoke("/v1/composio/slack/reply", { ...f.message, channel: "COTHER" });+ assert.equal(result.data.sent, true);+ const receipts = await f.deps.deliveries!.pending("web");+ assert.equal(receipts.length, 1);+ assert.equal(receipts[0]!.text, "Hello");+ assert.deepEqual(receipts[0]!.destination.webTranscript, {+ kind: "slack_reply",+ sessionId: "session",+ ts: "123.789",+ name: "Alice",+ });+ assert.equal(f.calls.length, 0);+ const sent = f.nativeCalls.at(-1)!;+ assert.equal(sent.method, "chat.postMessage");+ assert.equal(sent.token, "alice-user");+ assert.deepEqual(sent.payload, {+ channel: "C123",+ thread_ts: "123.456",+ text: "Hello",+ client_msg_id: f.message.clientMessageId,+ as_user: true,+ unfurl_links: false,+ unfurl_media: false,+ });+});++test("native Slack rejects bot, wrong person, and wrong workspace tokens", async () => {+ for (const invalid of [{ bot_id: "B123" }, { user_id: "UOTHER" }, { team_id: "TOTHER" }]) {+ const f = await nativeSlackFixture();+ f.nativeReplies.push({ ...f.nativeIdentity, ...invalid });+ const result = await f.invoke("/v1/composio/slack/reply", f.message);+ assert.equal(result.status, 409);+ assert.equal(+ f.nativeCalls.some((c) => c.method === "chat.postMessage"),+ false,+ );+ }+});++test("native Slack connection status and linking work without a Composio credential", async () => {+ const f = await nativeSlackFixture(false);+ f.deps.keychain = undefined;+ f.deps.serviceCreds = undefined;+ assert.deepEqual((await f.invoke("/v1/composio/slack")).data, {+ connected: false,+ nativeOAuth: true,+ workspaceInstalled: true,+ });+ assert.equal((await f.invoke("/v1/composio/slack/reply-status", { sessionId: "session" })).data.connected, false);+ await f.deps.connectorTokens!.setConnectorToken("slack.com", "alice", { accessToken: "alice-user" });+ f.nativeReplies.push(f.nativeIdentity);+ assert.equal((await f.invoke("/v1/composio/slack")).data.connected, true);+});++test("configured native OAuth preserves an existing Composio connection", async () => {+ const f = await nativeSlackFixture(false);+ await f.deps.slackAccounts!.put("alice", {+ principalId: "alice",+ memberId: "alice",+ accountId: "ca_alice",+ userId: "U123",+ teamId: "T123",+ user: "Alice",+ workspace: "Test",+ });+ f.replies.push(f.account);+ assert.equal((await f.invoke("/v1/composio/slack")).data.connected, true);+ f.replies.push(f.account, f.identity, { data: { ok: true } }, { data: { ok: true, ts: "123.789" } });+ assert.equal((await f.invoke("/v1/composio/slack/reply", f.message)).data.sent, true);+ assert.equal(f.nativeCalls.length, 0);+});++test("native Slack access denial and uncertain sends never fall through to another transport", async () => {+ for (const sending of [false, true]) {+ const f = await nativeSlackFixture();+ f.nativeReplies.push(f.nativeIdentity, { ok: sending });+ if (sending) f.nativeReplies.push(new Error("timeout"));+ const result = await f.invoke("/v1/composio/slack/reply", f.message);+ assert.equal(result.status, sending ? 502 : 403);+ if (sending) assert.match(result.data.message, /outcome is unknown/);+ assert.equal(f.calls.length, 0);+ }+});++test("a confirmed Slack send is distinguished from a failed transcript write", async () => {+ const f = await slackReplyFixture();+ f.deps.deliveries!.enqueue = async () => {+ throw new Error("database unavailable");+ };+ f.replies.push(f.account, f.identity, { data: { ok: true } }, { data: { ok: true, ts: "123.789" } });+ const result = await f.invoke("/v1/composio/slack/reply", f.message);+ assert.equal(result.status, 502);+ assert.equal(result.data.error, "transcript_unavailable");+ assert.match(result.data.message, /Slack sent your message.*Do not resend/);+});++test("Slack reply failures redact both provider credentials from diagnostics", async (t) => {+ const logged: string[] = [];+ t.mock.method(console, "error", (...args: unknown[]) => logged.push(args.map(String).join(" ")));+ const composio = await slackReplyFixture();+ composio.replies.push(new Response("provider rejected private-key", { status: 502 }));+ assert.equal((await composio.invoke("/v1/composio/slack/reply", composio.message)).status, 502);+ const native = await nativeSlackFixture();+ native.nativeReplies.push(new Error("provider rejected alice-user"));+ assert.equal((await native.invoke("/v1/composio/slack/reply", native.message)).status, 502);+ assert.match(logged.join("\n"), /provider rejected/);+ assert.doesNotMatch(logged.join("\n"), /private-key|alice-user/);+});diff --git a/test/slack-receipt-transcript.test.ts b/test/slack-receipt-transcript.test.tsnew file mode 100644index 000000000..664667216--- /dev/null+++ b/test/slack-receipt-transcript.test.ts@@ -0,0 +1,142 @@+import { test } from "node:test";+import assert from "node:assert/strict";+import { randomUUID } from "node:crypto";+import { createMemorySessionStore } from "../src/sessions/memory-session-store.ts";+import { createPostgresSessionStore } from "../src/sessions/postgres-session-store.ts";+import { createTranscriptSource } from "../src/sessions/transcript-source.ts";+import { createDeliveryStore } from "../src/delivery/delivery-store.ts";+import { createPostgresDeliveryStore } from "../src/delivery/postgres-delivery-store.ts";+import { withWebTranscriptDeliveries } from "../src/delivery/web-transcript-delivery.ts";+import { forModelContext, forSearchView } from "../src/harness/context-compaction.ts";+import { scopeId } from "../src/types.ts";+import { sleep } from "../src/util/async.ts";+import type { SessionStore } from "../src/sessions/session-store.ts";++const scope = scopeId("personal", "alice");+const databaseUrl = process.env.DATABASE_URL;++for (const backend of ["memory", "postgres"] as const) {+ test(+ `${backend}: Slack receipts render once across pages and stay out of model context`,+ {+ skip: backend === "postgres" && !databaseUrl ? "requires DATABASE_URL" : false,+ },+ async () => {+ const sessions: SessionStore =+ backend === "memory" ? createMemorySessionStore() : createPostgresSessionStore(databaseUrl!);+ const session = await sessions.getOrCreateByThread(`dm:${randomUUID()}`, "dm", scope, undefined, "slack");+ await sessions.addParticipant(session.id, "alice");+ const { lease } = await sessions.acquireLease(session.id, "turn");+ assert.ok(lease);+ const receipt = await sessions.append(lease, {+ type: "user",+ scopeLabel: scope,+ payload: { text: "Receipt text", ts: "100.123", slackReplyReceipt: true, deliveryKey: "sent-1" },+ });+ const middle = await sessions.append(lease, {+ type: "assistant",+ scopeLabel: scope,+ payload: { text: "Intervening reply" },+ });+ const source = createTranscriptSource(sessions);+ assert.deepEqual(+ (await source.forViewer(session.id, "alice")).entries.map((e) => e.seq),+ [receipt.seq, middle.seq],+ );+ assert.deepEqual(+ forModelContext(await sessions.getEntries(session.id)).map((e) => e.seq),+ [middle.seq],+ );+ assert.deepEqual(+ forSearchView(await sessions.getEntries(session.id)).map((e) => e.seq),+ [middle.seq],+ );+ await sessions.removeParticipant(session.id, "alice");+ await sessions.addParticipant(session.id, "bob");+ const event = await sessions.append(lease, {+ type: "user",+ scopeLabel: scope,+ payload: { text: "Receipt text", ts: "100.123" },+ });+ await sessions.releaseLease(lease);+ const page = await source.forRender(session.id, { limit: 1 });+ assert.deepEqual(+ page.entries.map((e) => e.seq),+ [event.seq],+ );+ assert.equal(page.earlier, 1);+ const previous = await source.forRender(session.id, { limit: 1, beforeSeq: event.seq });+ assert.deepEqual(+ previous.entries.map((e) => e.seq),+ [middle.seq],+ );+ assert.equal(previous.earlier, 0);+ assert.deepEqual(+ (await source.forViewer(session.id, "alice")).entries.map((e) => e.seq),+ [receipt.seq, middle.seq],+ );+ assert.deepEqual(+ forModelContext(await sessions.getEntries(session.id)).map((e) => e.seq),+ [middle.seq, event.seq],+ );+ assert.deepEqual(+ (await source.forViewer(session.id, "bob")).entries.map((e) => e.seq),+ [event.seq],+ );+ },+ );++ test(+ `${backend}: receipt retries remain pending and deduplicate beyond the transcript tail`,+ {+ skip: backend === "postgres" && !databaseUrl ? "requires DATABASE_URL" : false,+ },+ async () => {+ const sessions: SessionStore =+ backend === "memory" ? createMemorySessionStore() : createPostgresSessionStore(databaseUrl!);+ const inner =+ backend === "memory"+ ? createDeliveryStore({ maxAgeMs: 1 })+ : createPostgresDeliveryStore(databaseUrl!, { maxAgeMs: 1 });+ const thread = `dm:${randomUUID()}`;+ const session = await sessions.getOrCreateByThread(thread, "dm", scope, undefined, "slack");+ const { lease } = await sessions.acquireLease(session.id, "turn");+ assert.ok(lease);+ const deliveries = withWebTranscriptDeliveries(inner, sessions);+ const row = await deliveries.enqueue({+ destination: {+ type: "web",+ target: thread,+ audienceScopeId: scope,+ webTranscript: { kind: "slack_reply", sessionId: session.id, ts: "200.123", name: "Alice" },+ },+ text: "Durable receipt",+ idempotencyKey: `receipt:${randomUUID()}`,+ });+ row.createdAt = Date.now() - 7 * 60 * 60_000;+ await sleep(10);+ assert.deepEqual(await deliveries.claimPending("web", 1), []);+ assert.equal((await inner.get(row.id))?.expiredAt, undefined);+ assert.equal((await sessions.getEntries(session.id)).length, 0);+ await sessions.releaseLease(lease);+ await sleep(10);+ assert.equal((await deliveries.claimPending("web", 1)).length, 1);+ const next = await sessions.acquireLease(session.id, "turn");+ assert.ok(next.lease);+ await sessions.appendMany(+ next.lease,+ Array.from({ length: 210 }, (_, i) => ({+ type: "assistant" as const,+ scopeLabel: scope,+ payload: { text: `Reply ${i}` },+ })),+ );+ await sessions.releaseLease(next.lease);+ const restarted = withWebTranscriptDeliveries(inner, sessions);+ await restarted.pending("web");+ const entries = (await createTranscriptSource(sessions).forRender(session.id)).entries;+ assert.equal(entries.filter((e) => (e.payload as { slackReplyReceipt?: boolean }).slackReplyReceipt).length, 1);+ await inner.ack(row.id, Date.now());+ },+ );+}diff --git a/test/slack-web-client.test.ts b/test/slack-web-client.test.tsnew file mode 100644index 000000000..9c0f1853a--- /dev/null+++ b/test/slack-web-client.test.ts@@ -0,0 +1,30 @@+import { test } from "node:test";+import assert from "node:assert/strict";+import { createServer } from "node:http";+import type { AddressInfo } from "node:net";+import { WebClient } from "@slack/web-api";+import { slackWebClient } from "../src/slack/web-client.ts";+import { errDetail } from "../plugins/chassis/src/errors.ts";++test("Slack transport errors retain diagnostic evidence without credentials or automatic resends", async (t) => {+ const token = "synthetic-slack-transport-token";+ let attempts = 0;+ const server = createServer((req) => {+ attempts++;+ assert.equal(req.headers.authorization, `Bearer ${token}`);+ req.socket.destroy();+ });+ await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));+ t.after(() => new Promise<void>((resolve) => server.close(() => resolve())));+ const base = `http://127.0.0.1:${(server.address() as AddressInfo).port}/`;+ const client = slackWebClient(token, (secret, options) => new WebClient(secret, { ...options, slackApiUrl: base }));+ await assert.rejects(client.apiCall("chat.postMessage", { channel: "C123", text: "Test" }), (error: unknown) => {+ assert.ok(error instanceof Error);+ assert.match(errDetail(error), /socket hang up|ECONNRESET/);+ assert.ok(!errDetail(error).includes(token));+ assert.ok(!JSON.stringify(error).includes(token));+ assert.equal((error as Error & { code: string }).code, "slack_webapi_request_error");+ return true;+ });+ assert.equal(attempts, 1);+});diff --git a/test/web-transcript-delivery.test.ts b/test/web-transcript-delivery.test.tsindex 630196cf0..d72ad5260 100644--- a/test/web-transcript-delivery.test.ts+++ b/test/web-transcript-delivery.test.ts@@ -111,12 +111,12 @@ test("a failed transcript write converges on retry: one entry", async () => {let failNextAppend = true;const flaky = {...sessions,- appendMany: async (...args: Parameters<SessionStore["appendMany"]>) => {+ append: async (...args: Parameters<SessionStore["append"]>) => {if (failNextAppend) {failNextAppend = false;throw new Error("transient append failure");}- return sessions.appendMany(...args);+ return sessions.append(...args);},};const inner = createDeliveryStore();@@ -399,3 +399,53 @@ test("a recovered reply the turn never recorded is written into the transcript,assert.equal(entries[0]!.type, "assistant");assert.deepEqual(entries[0]!.payload, { text: "recovered reply", deliveryKey: drained[0]!.idempotencyKey });});++test("Slack send receipts survive a restart, retry a busy session, and collapse against the Slack event", async () => {+ const { sessions, inner, deliveries } = wired();+ const session = await webSession(sessions, "dm:D123");+ const { lease } = await sessions.acquireLease(session.id, "turn");+ assert.ok(lease);+ const input = {+ destination: {+ ...webDestination("dm:D123"),+ webTranscript: { kind: "slack_reply" as const, sessionId: session.id, ts: "123.789", name: "Alice" },+ },+ text: "Sent as Alice",+ idempotencyKey: "slack-reply:session:D123:123.789",+ };+ await deliveries.enqueue(input);+ assert.equal((await sessions.getEntries(session.id)).length, 0);+ assert.equal((await inner.pending("web")).length, 1);+ await sessions.releaseLease(lease);+ const restarted = withWebTranscriptDeliveries(inner, sessions);+ assert.equal((await restarted.pending("web")).length, 1);+ await restarted.enqueue(input);+ const entries = (await createTranscriptSource(sessions).forRender(session.id)).entries;+ assert.equal(entries.length, 1);+ assert.equal(entries[0]!.type, "user");+ assert.equal((entries[0]!.payload as { text: string }).text, input.text);+ const eventLease = await sessions.acquireLease(session.id, "turn");+ assert.ok(eventLease.lease);+ await sessions.append(eventLease.lease, {+ type: "user",+ scopeLabel: SCOPE,+ payload: { text: input.text, name: "Alice", ts: "123.789" },+ });+ await sessions.releaseLease(eventLease.lease);+ const visible = (await createTranscriptSource(sessions).forRender(session.id)).entries;+ assert.equal(visible.length, 1);+ assert.equal((visible[0]!.payload as { slackReplyReceipt?: boolean }).slackReplyReceipt, undefined);+});++test("Slack send receipts are recorded immediately without a listener and skip an already recorded event", async () => {+ const { sessions, deliveries } = wired();+ const session = await webSession(sessions, "dm:D123");+ const destination: Destination = {+ ...webDestination("dm:D123"),+ webTranscript: { kind: "slack_reply", sessionId: session.id, ts: "123.789", name: "Alice" },+ };+ await deliveries.enqueue({ destination, text: "Hello", idempotencyKey: "send-1" });+ assert.equal((await sessions.getEntries(session.id)).length, 1);+ await deliveries.enqueue({ destination, text: "Hello", idempotencyKey: "send-2" });+ assert.equal((await sessions.getEntries(session.id)).length, 1);+});