The Open Framework for Building Agents
fix(eve): retire inactive prompts the same way on every button channel (#4840)
roboeve[bot]0d45099ffb76
diff --git a/.changeset/quiet-inactive-approval-press.md b/.changeset/quiet-inactive-approval-press.mdnew file mode 100644index 000000000..9b8b1789e--- /dev/null+++ b/.changeset/quiet-inactive-approval-press.md@@ -0,0 +1,5 @@+---+"eve": patch+---++Pressing a human-in-the-loop button whose session is no longer active, for example after its run was cancelled outside eve, now retires the prompt the same way on Slack, Teams, Telegram, Discord, and Chat SDK: its buttons are replaced with `No longer active`, as a resolved prompt reads, and the person who pressed is told to send a new message: privately on Slack, Discord, Chat SDK and Telegram, and on Teams by the retired card itself, or the reply to an invoke. Before, the press was only logged (or, on Chat SDK, thrown) and the prompt stayed live.diff --git a/docs/channels/slack.mdx b/docs/channels/slack.mdxindex 471ea6c22..5d3d5392c 100644--- a/docs/channels/slack.mdx+++ b/docs/channels/slack.mdx@@ -645,6 +645,8 @@ The callback receives the `InputRequest` and current `SessionContext`, so it canWhen a tool approval resolves, eve retires the messages it posted for it. The card loses its buttons and shows the answer and who gave it, the separate tool-input post is deleted, and a direct-message request's `Waiting on approval` note in the thread changes to the outcome. This also happens when the approval ends without a click, for example when the person replies in the thread instead, in which case the card reads `No longer needed`.+A click on any request whose session is no longer active, for example because its run was cancelled outside eve, can never be answered. eve removes the card's buttons, marks it `No longer active`, and tells the person who clicked, in an ephemeral message, to send a new message.+A renderer's `input.requested` handler can extend delivery and then hand the requests on to eve with `next()`. For example, an application can add non-sensitive context to the Slack thread before eve renders the actionable controls. The configured `approvalChannel` still sends sensitive reviews to a DM and keeps ordinary requests in the thread:```ts title="agent/channels/slack.ts"diff --git a/docs/channels/teams.mdx b/docs/channels/teams.mdxindex 5aef35892..585fb6536 100644--- a/docs/channels/teams.mdx+++ b/docs/channels/teams.mdx@@ -85,7 +85,7 @@ A human-in-the-loop (HITL) `input.requested` event renders as an Adaptive Card.By default, submissions use the Teams identity of the user who clicked the card. If you customize `onMessage` for an allowlist, configure the same policy in `onInputResponse`; eve otherwise rejects HITL submissions rather than bypassing the message gate.-When a tool approval settles, eve replaces its Adaptive Card with the outcome and responder name. A response rejected by an approval policy leaves the shared card unchanged.+When a tool approval settles, eve replaces its Adaptive Card with the outcome and responder name. A response rejected by an approval policy leaves the shared card unchanged. A submission to a card whose session is no longer active, for example because its run was cancelled outside eve, replaces the card with its prompt and `No longer active`, and the invoke response tells the person who submitted to send a new message.### Connection sign-insdiff --git a/docs/channels/telegram.mdx b/docs/channels/telegram.mdxindex d4de56c95..358ea7656 100644--- a/docs/channels/telegram.mdx+++ b/docs/channels/telegram.mdx@@ -49,7 +49,7 @@ The default `message.completed` handler sends plain text via `sendMessage`. It p### Human-in-the-loop (HITL)-Human-in-the-loop (HITL) turns option requests into inline-keyboard buttons and freeform requests into `ForceReply`. Telegram caps `callback_data` at 64 bytes, so eve keeps compact callback ids in channel state instead. It acknowledges its own callbacks with `answerCallbackQuery`; anything it doesn't recognize goes to `onCallbackQuery`.+Human-in-the-loop (HITL) turns option requests into inline-keyboard buttons and freeform requests into `ForceReply`. Telegram caps `callback_data` at 64 bytes, so eve keeps compact callback ids in channel state instead. It acknowledges its own callbacks with `answerCallbackQuery`; anything it doesn't recognize goes to `onCallbackQuery`. A press on a prompt whose session is no longer active replaces the keyboard with `No longer active`, and the acknowledgement tells the person to send a new message.A text reply to a bot message is sent as a normal message, with the replied-to message id in `state.replyToBotMessageId`. When that id matches a pending `ForceReply` prompt, the channel's `deliver` hook turns the reply into the answer. Otherwise the reply reaches the agent as a message, and starts a new session when none owns the thread.diff --git a/packages/eve/src/channel/channel-address.ts b/packages/eve/src/channel/channel-address.tsindex 78296f45e..bac99bff1 100644--- a/packages/eve/src/channel/channel-address.ts+++ b/packages/eve/src/channel/channel-address.ts@@ -8,6 +8,7 @@ import {import type { SendPayload } from "#channel/routes.js";import { normalizeSendInput, serializeFilePartsInMessage } from "#channel/send-input.js";import { createSession, sessionCallbackToTurnCaller, type Session } from "#channel/session.js";+import { SessionNotActiveError } from "#channel/session-not-active-error.js";import type {CancelTurnResult,ClearSessionResult,@@ -41,6 +42,7 @@ export type ChannelAddressDeliveryOptions<TState = undefined> = [TState] extends* Only {@link send} may create a session: when the address is unowned, or in* place of a stranded session that another eve version built. Sends to a session whose* owner is only unavailable throw `SessionStrandedError` and deliver nothing.+ * Responses to an address no session holds throw `SessionNotActiveError`.*/interface ChannelAddress<TState = undefined> {readonly continuationToken: string;@@ -140,9 +142,7 @@ export function createChannelAddress<TState = undefined>(input: {});if (result.status === "accepted") return toSession(result.sessionId);if (payload.inputResponses && payload.inputResponses.length > 0) {- throw new Error(- "Cannot deliver inputResponses — the target session was not found via continuation token.",- );+ throw new SessionNotActiveError();}return toSession((await input.runtime.createSession(runInput)).sessionId);},diff --git a/packages/eve/src/channel/inactive-prompt.ts b/packages/eve/src/channel/inactive-prompt.tsnew file mode 100644index 000000000..ea4d666bb--- /dev/null+++ b/packages/eve/src/channel/inactive-prompt.ts@@ -0,0 +1,66 @@+import { isUnanswerableResponseError } from "#channel/session-not-active-error.js";+import type { Logger } from "#internal/logging.js";++/** What a channel tells the person whose answer can never be taken. */+export const INACTIVE_REQUEST_NOTICE =+ "This request is no longer active. Send a new message to start again.";++/** The label a retired prompt shows in place of its choices. */+export const INACTIVE_PROMPT_LABEL = "No longer active";++/** How one channel retires a prompt that a press found no session for. */+export interface InactivePromptRetirement {+ /**+ * Edits the pressed prompt the way the channel shows a resolved one: its+ * prompt kept, its choices replaced by `label`.+ */+ readonly retirePrompt: (label: string) => Promise<void>;+}++/** What became of a person's answer to a prompt. */+export type PromptResponse =+ /** A session took the answer. */+ | { readonly outcome: "delivered" }+ /**+ * Delivery failed in a way a retry may fix; the prompt is left as it was.+ * `error` is what delivery threw, for a caller whose platform expects it.+ */+ | { readonly outcome: "failed"; readonly error: unknown }+ /**+ * No session can ever take it. `retirement` is the prompt's edit, already+ * started; it logs its own failure and never rejects.+ */+ | { readonly outcome: "inactive"; readonly retirement: Promise<void> };++/**+ * Delivers a person's answer to a prompt and reports what became of it.+ *+ * When no session can ever take the answer, such as after the session's run+ * was cancelled outside eve, nothing will withdraw the prompt either, so its+ * retirement starts here, labeled `No longer active`. The caller tells the+ * presser in whatever way its platform allows, without waiting on the edit,+ * and keeps its request alive until `retirement` settles. Any other failure+ * is only logged and leaves the prompt as it was, since a retry may succeed.+ */+export async function respondOrRetireInactivePrompt(+ respond: () => Promise<unknown>,+ retirement: InactivePromptRetirement,+ log: Logger,+): Promise<PromptResponse> {+ try {+ await respond();+ return { outcome: "delivered" };+ } catch (error) {+ if (!isUnanswerableResponseError(error)) {+ log.error("input response delivery failed", { error });+ return { outcome: "failed", error };+ }+ log.warn("input response reached no active session", { error });+ }+ return {+ outcome: "inactive",+ retirement: retirement+ .retirePrompt(INACTIVE_PROMPT_LABEL)+ .catch((error: unknown) => log.error("inactive prompt edit failed", { error })),+ };+}diff --git a/packages/eve/src/channel/session-not-active-error.ts b/packages/eve/src/channel/session-not-active-error.tsnew file mode 100644index 000000000..933bb0115--- /dev/null+++ b/packages/eve/src/channel/session-not-active-error.ts@@ -0,0 +1,34 @@+import { SessionStrandedError } from "#channel/session-stranded-error.js";++/**+ * Thrown by `respond()` when no session holds the address it answers, such as+ * after the session's run was cancelled outside eve, so the requests being+ * answered no longer exist. Nothing is delivered. Narrow with+ * {@link SessionNotActiveError.is}.+ */+export class SessionNotActiveError extends Error {+ constructor() {+ super(+ "Cannot deliver inputResponses — the target session was not found via continuation token.",+ );+ this.name = "SessionNotActiveError";+ }++ /** Narrows not-active-session errors across bundle boundaries, where `instanceof` can miss. */+ static is(error: unknown): error is SessionNotActiveError {+ return (+ error instanceof SessionNotActiveError ||+ (typeof error === "object" &&+ error !== null &&+ Reflect.get(error, "name") === "SessionNotActiveError")+ );+ }+}++/**+ * Whether a failed `respond()` can never succeed: no session holds the+ * requests, or the session holding them is stranded and can run no code.+ */+export function isUnanswerableResponseError(error: unknown): boolean {+ return SessionNotActiveError.is(error) || SessionStrandedError.is(error);+}diff --git a/packages/eve/src/internal/nitro/routes/channel-dispatch-inactive-press.test.ts b/packages/eve/src/internal/nitro/routes/channel-dispatch-inactive-press.test.tsnew file mode 100644index 000000000..f13b69ec6--- /dev/null+++ b/packages/eve/src/internal/nitro/routes/channel-dispatch-inactive-press.test.ts@@ -0,0 +1,216 @@+import { createHmac } from "node:crypto";+import { afterEach, expect, describe, it, vi } from "vitest";++import { type CompiledChannel, isCompiledChannel } from "#channel/compiled-channel.js";+import type { Runtime } from "#channel/types.js";+import { dispatchChannelRequest } from "#internal/nitro/routes/channel-dispatch.js";+import { resolveNitroChannelRuntimeBundle } from "#internal/nitro/routes/runtime-stack.js";+import { slackChannel } from "#public/channels/slack/index.js";+import { HITL_ACTION_PREFIX } from "#public/channels/slack/hitl.js";+import { teamsChannel } from "#public/channels/teams/index.js";+import type { ResolvedChannelDefinition } from "#runtime/types.js";+import type { H3Event } from "nitro";++vi.mock("#internal/nitro/routes/runtime-stack.js", () => ({+ resolveNitroChannelRuntimeBundle: vi.fn(),+}));++vi.mock("#internal/workflow/runtime.js", () => ({+ getWorld: async () => ({ getDeploymentId: async () => "dpl_test" }),+}));++const mockedResolveNitroChannelRuntimeBundle = vi.mocked(resolveNitroChannelRuntimeBundle);++function asCompiled(channel: unknown): CompiledChannel {+ if (!isCompiledChannel(channel)) throw new Error("Expected compiled channel.");+ return channel;+}++function createDeferred<T>() {+ let resolve!: (value: T | PromiseLike<T>) => void;+ const promise = new Promise<T>((resolvePromise) => {+ resolve = resolvePromise;+ });+ return { promise, resolve };+}++/**+ * A runtime whose sessions have all ended, as after a run cancelled outside+ * eve. Like a real one, it answers after the webhook has been acknowledged.+ */+function runtimeWithNoActiveSession(acknowledged: Promise<void>): Runtime {+ return {+ createSession: vi.fn(),+ dispatchContinuation: vi.fn(async () => {+ await acknowledged;+ return { status: "session_not_active" };+ }) as Runtime["dispatchContinuation"],+ dispatchSession: vi.fn(),+ getEventStream: vi.fn().mockResolvedValue(new ReadableStream()),+ getStreamTailIndex: vi.fn().mockResolvedValue(-1),+ resolveContinuation: vi.fn(),+ };+}++describe("an inactive press through the production dispatcher", () => {+ /** A card edit that starts, then waits until the test lets it finish. */+ function heldEdit() {+ const started = createDeferred<void>();+ const release = createDeferred<void>();+ return {+ async hold(): Promise<void> {+ started.resolve();+ await release.promise;+ },+ release: () => release.resolve(),+ started: started.promise,+ };+ }++ /**+ * Serves `request` with `channel`'s real route against a runtime that has no+ * active session, and returns the one task handed to the platform. It is+ * wrapped, since awaiting a returned promise would wait for the task itself.+ */+ async function dispatchInactivePress(+ channel: CompiledChannel,+ request: Request,+ ): Promise<{ readonly task: Promise<unknown> }> {+ const acknowledged = createDeferred<void>();+ const definition = channel as CompiledChannel & {+ routes: readonly { readonly handler: ResolvedChannelDefinition["handler"] }[];+ };+ mockedResolveNitroChannelRuntimeBundle.mockResolvedValue({+ agentName: "test-agent",+ channels: [+ {+ adapter: channel.adapter,+ definition: channel,+ fetch: async () => new Response("ok"),+ handler: definition.routes[0]!.handler,+ logicalPath: "agent/channels/press.ts",+ method: "POST",+ name: "press",+ sourceId: "channel-press",+ sourceKind: "module",+ urlPath: "/press",+ } satisfies ResolvedChannelDefinition,+ ],+ runtime: runtimeWithNoActiveSession(acknowledged.promise),+ });+ const waitUntil = vi.fn<(task: Promise<unknown>) => void>();+ Object.assign(request, { ip: "127.0.0.1" });+ const handOff: (task: Promise<unknown>) => void = waitUntil;+ const event = { context: { params: {} }, req: request, waitUntil: handOff } as H3Event;+ await dispatchChannelRequest(event, "POST /press", {} as never);+ acknowledged.resolve();+ expect(waitUntil).toHaveBeenCalledTimes(1);+ return { task: waitUntil.mock.calls[0]![0] };+ }++ async function expectHeldUntilRelease(+ task: Promise<unknown>,+ edit: ReturnType<typeof heldEdit>,+ ): Promise<void> {+ let settled = false;+ void task.then(() => {+ settled = true;+ });+ await edit.started;+ await new Promise((resolve) => setTimeout(resolve, 0));+ expect(settled, "the request let go before the card's edit finished").toBe(false);+ edit.release();+ await task;+ expect(settled).toBe(true);+ }++ afterEach(() => {+ vi.unstubAllGlobals();+ });++ it("keeps a Teams button press's request alive until its card is retired", async () => {+ const edit = heldEdit();+ const channel = asCompiled(+ teamsChannel({+ api: {+ fetch: async (input: string | URL | Request, init?: RequestInit) => {+ if (new Request(input, init).method === "PUT") await edit.hold();+ return new Response(JSON.stringify({ id: "card" }));+ },+ },+ credentials: { tokenProvider: () => "test-token", webhookVerifier: () => true },+ }),+ );+ // An Action.Submit button posts a message activity carrying its data.+ const request = new Request("https://eve.test/press", {+ body: JSON.stringify({+ channelData: { tenant: { id: "TENANT" } },+ conversation: { conversationType: "personal", id: "CONV" },+ from: { id: "USER", name: "Ada" },+ id: "PRESS",+ recipient: { id: "BOT", name: "eve Bot" },+ replyToId: "CARD",+ serviceUrl: "https://smba.example.test/teams",+ type: "message",+ value: {+ eve_input: { optionId: "approve", prompt: "Deploy?", requestId: "REQ" },+ },+ }),+ headers: { "content-type": "application/json" },+ method: "POST",+ });++ const { task } = await dispatchInactivePress(channel, request);+ await expectHeldUntilRelease(task, edit);+ });++ it("keeps a Slack button press's request alive until its card is retired", async () => {+ const edit = heldEdit();+ vi.stubGlobal("fetch", async (input: string | URL | Request, init?: RequestInit) => {+ if (new Request(input, init).url.endsWith("/chat.update")) await edit.hold();+ return Response.json({ ok: true, ts: "1700000000.000010" });+ });+ const signingSecret = "test-signing-secret";+ const channel = asCompiled(+ slackChannel({+ credentials: { botToken: "xoxb-test", signingSecret },+ }),+ );+ const body = new URLSearchParams({+ payload: JSON.stringify({+ actions: [+ {+ action_id: `${HITL_ACTION_PREFIX}tool-approval:approval_abc123:button:0`,+ text: { text: "Approve", type: "plain_text" },+ value: "approve",+ },+ ],+ channel: { id: "C01" },+ message: {+ blocks: [{ text: { text: "Approve?", type: "mrkdwn" }, type: "section" }],+ thread_ts: "1700000000.000001",+ ts: "1700000000.000010",+ },+ team: { id: "T01" },+ type: "block_actions",+ user: { id: "U_APPROVER", name: "ada", team_id: "T01", username: "ada" },+ }),+ }).toString();+ const timestamp = Math.floor(Date.now() / 1000);+ const signature = `v0=${createHmac("sha256", signingSecret)+ .update(`v0:${timestamp}:${body}`)+ .digest("hex")}`;+ const request = new Request("https://eve.test/press", {+ body,+ headers: {+ "content-type": "application/x-www-form-urlencoded",+ "x-slack-request-timestamp": String(timestamp),+ "x-slack-signature": signature,+ },+ method: "POST",+ });++ const { task } = await dispatchInactivePress(channel, request);+ await expectHeldUntilRelease(task, edit);+ });+});diff --git a/packages/eve/src/internal/testing/channel-conformance/MATRIX.md b/packages/eve/src/internal/testing/channel-conformance/MATRIX.mdindex fa6de976e..81b94e2fd 100644--- a/packages/eve/src/internal/testing/channel-conformance/MATRIX.md+++ b/packages/eve/src/internal/testing/channel-conformance/MATRIX.md@@ -67,6 +67,15 @@ pnpm --filter eve exec vitest run --config vitest.unit.config.ts channel-conform| pressing Approve names who approved on the approval | —<sup>[12](#note-12)</sup> | —<sup>[13](#note-13)</sup> | ❌<sup>[14](#note-14)</sup> | | —<sup>[1](#note-1)</sup> | ❌<sup>[14](#note-14)</sup> | | —<sup>[1](#note-1)</sup> | | ✅ | | ✅ | | ❌<sup>[14](#note-14)</sup> | | —<sup>[1](#note-1)</sup> | —<sup>[1](#note-1)</sup> | —<sup>[1](#note-1)</sup> | —<sup>[1](#note-1)</sup> || approving by text names who approved on the approval | —<sup>[6](#note-6)</sup> | —<sup>[13](#note-13)</sup> | ❌<sup>[14](#note-14)</sup> | ❌<sup>[14](#note-14)</sup> | —<sup>[1](#note-1)</sup> | —<sup>[2](#note-2)</sup> | —<sup>[2](#note-2)</sup> | —<sup>[1](#note-1)</sup> | —<sup>[1](#note-1)</sup> | ✅ | ✅ | ❌<sup>[14](#note-14)</sup> | ❌<sup>[14](#note-14)</sup> | ❌<sup>[14](#note-14)</sup> | ❌<sup>[14](#note-14)</sup> | —<sup>[1](#note-1)</sup> | —<sup>[1](#note-1)</sup> | —<sup>[1](#note-1)</sup> | —<sup>[1](#note-1)</sup> |+## Inactive prompts++| Rule | `tui` | `web chat` | `chat-sdk` | `chat-sdk-dm` | `chat-sdk-text` | `discord` | `discord-dm` | `linq` | `linq-dm` | `slack` | `slack-dm` | `teams` | `teams-dm` | `telegram` | `telegram-dm` | `github` | `linear` | `photon` | `twilio` |+| --- | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: |+| pressing Approve after the session's run ended outside eve runs nothing and clears the approval's buttons | ✅ | ✅ | ✅ | | —<sup>[1](#note-1)</sup> | ✅ | | —<sup>[1](#note-1)</sup> | | ✅ | | ✅ | | ✅ | | —<sup>[1](#note-1)</sup> | —<sup>[1](#note-1)</sup> | —<sup>[1](#note-1)</sup> | —<sup>[1](#note-1)</sup> |+| pressing an option after the session's run ended outside eve clears the question's buttons | ✅ | ✅ | ✅ | | —<sup>[1](#note-1)</sup> | ✅ | | —<sup>[1](#note-1)</sup> | | ✅ | | ✅ | | ✅ | | —<sup>[1](#note-1)</sup> | —<sup>[1](#note-1)</sup> | —<sup>[1](#note-1)</sup> | —<sup>[1](#note-1)</sup> |+| pressing an option after the session's run ended outside eve tells the person it is no longer active | ✅ | ✅ | ✅ | | —<sup>[1](#note-1)</sup> | ✅ | | —<sup>[1](#note-1)</sup> | | ✅ | | ✅ | | ✅ | | —<sup>[1](#note-1)</sup> | —<sup>[1](#note-1)</sup> | —<sup>[1](#note-1)</sup> | —<sup>[1](#note-1)</sup> |+| a question pressed after the session's run ended outside eve keeps its prompt and says it is no longer active | ✅ | ✅ | ❌<sup>[15](#note-15)</sup> | | —<sup>[1](#note-1)</sup> | ✅ | | —<sup>[1](#note-1)</sup> | | ✅ | | ✅ | | ✅ | | —<sup>[1](#note-1)</sup> | —<sup>[1](#note-1)</sup> | —<sup>[1](#note-1)</sup> | —<sup>[1](#note-1)</sup> |+## Budget prompts| Rule | `tui` | `web chat` | `chat-sdk` | `chat-sdk-dm` | `chat-sdk-text` | `discord` | `discord-dm` | `linq` | `linq-dm` | `slack` | `slack-dm` | `teams` | `teams-dm` | `telegram` | `telegram-dm` | `github` | `linear` | `photon` | `twilio` |@@ -82,15 +91,15 @@ pnpm --filter eve exec vitest run --config vitest.unit.config.ts channel-conform| Rule | `tui` | `web chat` | `chat-sdk` | `chat-sdk-dm` | `chat-sdk-text` | `discord` | `discord-dm` | `linq` | `linq-dm` | `slack` | `slack-dm` | `teams` | `teams-dm` | `telegram` | `telegram-dm` | `github` | `linear` | `photon` | `twilio` || --- | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: |-| a sign-in names the service and shows its sign-in link | ✅ | ✅ | ✅ | ✅ | ✅ | ❌<sup>[15](#note-15)</sup> | ❌<sup>[15](#note-15)</sup> | ❌<sup>[16](#note-16)</sup> | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | —<sup>[17](#note-17)</sup> | ✅ | ✅ | ✅ |-| a sign-in shows its confirmation code | ✅ | ✅ | ✅ | ✅ | ✅ | ❌<sup>[15](#note-15)</sup> | ❌<sup>[15](#note-15)</sup> | ❌<sup>[16](#note-16)</sup> | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | —<sup>[17](#note-17)</sup> | ✅ | ✅ | ✅ |-| only the person signing in sees the sign-in link and code | —<sup>[18](#note-18)</sup> | —<sup>[18](#note-18)</sup> | ✅ | —<sup>[18](#note-18)</sup> | —<sup>[18](#note-18)</sup> | ✅ | —<sup>[18](#note-18)</sup> | ✅ | —<sup>[18](#note-18)</sup> | ✅ | —<sup>[18](#note-18)</sup> | ✅ | —<sup>[18](#note-18)</sup> | ✅ | —<sup>[18](#note-18)</sup> | ✅ | ❌<sup>[19](#note-19)</sup> | —<sup>[18](#note-18)</sup> | —<sup>[18](#note-18)</sup> |-| someone else pressing a sign-in isn't shown its link or code | —<sup>[9](#note-9)</sup> | —<sup>[9](#note-9)</sup> | —<sup>[20](#note-20)</sup> | —<sup>[9](#note-9)</sup> | —<sup>[10](#note-10)</sup> | —<sup>[21](#note-21)</sup> | —<sup>[9](#note-9)</sup> | —<sup>[10](#note-10)</sup> | —<sup>[10](#note-10)</sup> | —<sup>[20](#note-20)</sup> | —<sup>[9](#note-9)</sup> | ✅ | —<sup>[9](#note-9)</sup> | ✅ | —<sup>[9](#note-9)</sup> | —<sup>[1](#note-1)</sup> | —<sup>[1](#note-1)</sup> | —<sup>[10](#note-10)</sup> | —<sup>[10](#note-10)</sup> |-| a sign-in without a link shows its instructions | ✅ | ✅ | ✅ | ✅ | ✅ | ❌<sup>[15](#note-15)</sup> | ❌<sup>[15](#note-15)</sup> | ❌<sup>[16](#note-16)</sup> | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ❌<sup>[15](#note-15)</sup> | ✅ | ✅ | ✅ |+| a sign-in names the service and shows its sign-in link | ✅ | ✅ | ✅ | ✅ | ✅ | ❌<sup>[16](#note-16)</sup> | ❌<sup>[16](#note-16)</sup> | ❌<sup>[17](#note-17)</sup> | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | —<sup>[18](#note-18)</sup> | ✅ | ✅ | ✅ |+| a sign-in shows its confirmation code | ✅ | ✅ | ✅ | ✅ | ✅ | ❌<sup>[16](#note-16)</sup> | ❌<sup>[16](#note-16)</sup> | ❌<sup>[17](#note-17)</sup> | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | —<sup>[18](#note-18)</sup> | ✅ | ✅ | ✅ |+| only the person signing in sees the sign-in link and code | —<sup>[19](#note-19)</sup> | —<sup>[19](#note-19)</sup> | ✅ | —<sup>[19](#note-19)</sup> | —<sup>[19](#note-19)</sup> | ✅ | —<sup>[19](#note-19)</sup> | ✅ | —<sup>[19](#note-19)</sup> | ✅ | —<sup>[19](#note-19)</sup> | ✅ | —<sup>[19](#note-19)</sup> | ✅ | —<sup>[19](#note-19)</sup> | ✅ | ❌<sup>[20](#note-20)</sup> | —<sup>[19](#note-19)</sup> | —<sup>[19](#note-19)</sup> |+| someone else pressing a sign-in isn't shown its link or code | —<sup>[9](#note-9)</sup> | —<sup>[9](#note-9)</sup> | —<sup>[21](#note-21)</sup> | —<sup>[9](#note-9)</sup> | —<sup>[10](#note-10)</sup> | —<sup>[22](#note-22)</sup> | —<sup>[9](#note-9)</sup> | —<sup>[10](#note-10)</sup> | —<sup>[10](#note-10)</sup> | —<sup>[21](#note-21)</sup> | —<sup>[9](#note-9)</sup> | ✅ | —<sup>[9](#note-9)</sup> | ✅ | —<sup>[9](#note-9)</sup> | —<sup>[1](#note-1)</sup> | —<sup>[1](#note-1)</sup> | —<sup>[10](#note-10)</sup> | —<sup>[10](#note-10)</sup> |+| a sign-in without a link shows its instructions | ✅ | ✅ | ✅ | ✅ | ✅ | ❌<sup>[16](#note-16)</sup> | ❌<sup>[16](#note-16)</sup> | ❌<sup>[17](#note-17)</sup> | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ❌<sup>[16](#note-16)</sup> | ✅ | ✅ | ✅ || after signing in, the agent carries on with the request | ✅ | ✅ | ✅ | | ✅ | ✅ | | ✅ | | ✅ | | ✅ | | ✅ | | ✅ | ✅ | ✅ | ✅ |-| completing a sign-in tells the person it succeeded | ✅ | ✅ | ✅ | ✅ | ✅ | ❌<sup>[15](#note-15)</sup> | ❌<sup>[15](#note-15)</sup> | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ❌<sup>[15](#note-15)</sup> | ✅ | ✅ | ✅ |+| completing a sign-in tells the person it succeeded | ✅ | ✅ | ✅ | ✅ | ✅ | ❌<sup>[16](#note-16)</sup> | ❌<sup>[16](#note-16)</sup> | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ❌<sup>[16](#note-16)</sup> | ✅ | ✅ | ✅ || message after ignored sign-in gets an answer, signing in late doesn't run | ✅ | ✅ | ✅ | ✅ | ✅ | —<sup>[2](#note-2)</sup> | —<sup>[2](#note-2)</sup> | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |-| message after ignored sign-in tells user it was cancelled | ✅ | ✅ | ✅ | ✅ | ✅ | —<sup>[2](#note-2)</sup> | —<sup>[2](#note-2)</sup> | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ❌<sup>[15](#note-15)</sup> | ✅ | ✅ | ✅ |+| message after ignored sign-in tells user it was cancelled | ✅ | ✅ | ✅ | ✅ | ✅ | —<sup>[2](#note-2)</sup> | —<sup>[2](#note-2)</sup> | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ❌<sup>[16](#note-16)</sup> | ✅ | ✅ | ✅ |## Tool callers@@ -103,10 +112,10 @@ pnpm --filter eve exec vitest run --config vitest.unit.config.ts channel-conform| Rule | `tui` | `web chat` | `chat-sdk` | `chat-sdk-dm` | `chat-sdk-text` | `discord` | `discord-dm` | `linq` | `linq-dm` | `slack` | `slack-dm` | `teams` | `teams-dm` | `telegram` | `telegram-dm` | `github` | `linear` | `photon` | `twilio` || --- | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: |-| an image a person sends reaches the agent with its bytes and type | —<sup>[22](#note-22)</sup> | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | —<sup>[22](#note-22)</sup> | ✅ | ✅ | ✅ |-| a PDF a person sends reaches the agent with its bytes and type | —<sup>[22](#note-22)</sup> | ✅ | ✅ | | ✅ | ✅ | | ✅ | | ✅ | | ✅ | | ✅ | | —<sup>[22](#note-22)</sup> | ✅ | ✅ | ✅ |-| a file that can't be downloaded reaches the agent as a note, not a link, and the next message still works | —<sup>[22](#note-22)</sup> | —<sup>[23](#note-23)</sup> | ✅ | | ✅ | ✅ | | ✅ | | ✅ | | ✅ | | ✅ | | —<sup>[22](#note-22)</sup> | ✅ | ✅ | ✅ |-| a file sent earlier in the conversation is still there on a later message | —<sup>[22](#note-22)</sup> | ✅ | ✅ | | ✅ | —<sup>[24](#note-24)</sup> | | ✅ | | ✅ | | ✅ | | ✅ | | —<sup>[22](#note-22)</sup> | ✅ | ✅ | ✅ |+| an image a person sends reaches the agent with its bytes and type | —<sup>[23](#note-23)</sup> | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | —<sup>[23](#note-23)</sup> | ✅ | ✅ | ✅ |+| a PDF a person sends reaches the agent with its bytes and type | —<sup>[23](#note-23)</sup> | ✅ | ✅ | | ✅ | ✅ | | ✅ | | ✅ | | ✅ | | ✅ | | —<sup>[23](#note-23)</sup> | ✅ | ✅ | ✅ |+| a file that can't be downloaded reaches the agent as a note, not a link, and the next message still works | —<sup>[23](#note-23)</sup> | —<sup>[24](#note-24)</sup> | ✅ | | ✅ | ✅ | | ✅ | | ✅ | | ✅ | | ✅ | | —<sup>[23](#note-23)</sup> | ✅ | ✅ | ✅ |+| a file sent earlier in the conversation is still there on a later message | —<sup>[23](#note-23)</sup> | ✅ | ✅ | | ✅ | —<sup>[25](#note-25)</sup> | | ✅ | | ✅ | | ✅ | | ✅ | | —<sup>[23](#note-23)</sup> | ✅ | ✅ | ✅ |## Notes@@ -124,13 +133,14 @@ pnpm --filter eve exec vitest run --config vitest.unit.config.ts channel-conform12. <a id="note-12"></a>one person answers at their own terminal; there's nobody else to tell13. <a id="note-13"></a>one person answers in their own browser tab; there's nobody else to tell14. <a id="note-14"></a>a resolved prompt doesn't say who answered; input.resolved carries no responder-15. <a id="note-15"></a>the channel has no default sign-in renderer-16. <a id="note-16"></a>Linq's openDM needs the person's phone handle, but a message names its sender by an opaque handle id, so the bot can only say to continue in a direct message-17. <a id="note-17"></a>the rule applies only where the conversation is shared or private, and this one is public-18. <a id="note-18"></a>the rule applies only where the conversation is public or shared, and this one is private-19. <a id="note-19"></a>the code is in the elicitation body the whole issue sees; who sees the auth signal's link is unverified-20. <a id="note-20"></a>the sign-in goes privately to the person signing in, so the thread shows nothing to press-21. <a id="note-21"></a>the channel shows no sign-in, so there's nothing to press-22. <a id="note-22"></a>the platform has no files a person can send-23. <a id="note-23"></a>the browser sends a file's bytes with the message, so there is no download to fail-24. <a id="note-24"></a>each slash command starts its own session, so no later message shares one with the file+15. <a id="note-15"></a>a press carries only the card's message id, and the session that knew its prompt is gone, so the retired card shows only how it ended+16. <a id="note-16"></a>the channel has no default sign-in renderer+17. <a id="note-17"></a>Linq's openDM needs the person's phone handle, but a message names its sender by an opaque handle id, so the bot can only say to continue in a direct message+18. <a id="note-18"></a>the rule applies only where the conversation is shared or private, and this one is public+19. <a id="note-19"></a>the rule applies only where the conversation is public or shared, and this one is private+20. <a id="note-20"></a>the code is in the elicitation body the whole issue sees; who sees the auth signal's link is unverified+21. <a id="note-21"></a>the sign-in goes privately to the person signing in, so the thread shows nothing to press+22. <a id="note-22"></a>the channel shows no sign-in, so there's nothing to press+23. <a id="note-23"></a>the platform has no files a person can send+24. <a id="note-24"></a>the browser sends a file's bytes with the message, so there is no download to fail+25. <a id="note-25"></a>each slash command starts its own session, so no later message shares one with the filediff --git a/packages/eve/src/internal/testing/channel-conformance/conformance.ts b/packages/eve/src/internal/testing/channel-conformance/conformance.tsindex 7a223bf35..3a4d4d936 100644--- a/packages/eve/src/internal/testing/channel-conformance/conformance.ts+++ b/packages/eve/src/internal/testing/channel-conformance/conformance.ts@@ -145,6 +145,12 @@ const CHAT_SDK_BROKEN = {"questionPress","questionText",]),+ "a question pressed after the session's run ended outside eve keeps its prompt and says it is no longer active":+ {+ reason:+ "a press carries only the card's message id, and the session that knew its prompt is gone, so the retired card shows only how it ended",+ symptom: /the inactive prompt reads .* to contain/u,+ },};const DISCORD_BROKEN = {diff --git a/packages/eve/src/internal/testing/channel-conformance/contract.ts b/packages/eve/src/internal/testing/channel-conformance/contract.tsindex e1bef9b9c..03df2448a 100644--- a/packages/eve/src/internal/testing/channel-conformance/contract.ts+++ b/packages/eve/src/internal/testing/channel-conformance/contract.ts@@ -757,6 +757,67 @@ const answeredPromptRules = [},] as const satisfies readonly ContractRule[];+/**+ * A run cancelled outside eve, such as by an operator in the workflow world,+ * never withdraws its pending prompts, so their buttons stay pressable. A press+ * can then reach no session (#4835).+ */+async function pressAfterRunEnded(+ conversation: ChannelConversation,+ kind: "approval" | "question",+) {+ const options =+ kind === "approval" ? await askToDeploy(conversation) : await askWhichDay(conversation);+ await conversation.cancelRunsInWorld();+ await conversation.press(option(options, kind === "approval" ? APPROVE_LABELS : "Saturday"));+}++const NO_LONGER_ACTIVE = /no longer active/iu;++const inactivePromptRules = [+ {+ rule: "pressing Approve after the session's run ended outside eve runs nothing and clears the approval's buttons",+ source: "#4835",+ requires: ["buttons"],+ async run(conversation) {+ await pressAfterRunEnded(conversation, "approval");+ expect(conversation.runsOf(GATED_TOOL), `${GATED_TOOL} ran with no session`).toBe(0);+ await expectButtonsCleared(conversation, APPROVAL_PROMPT);+ },+ },+ {+ rule: "pressing an option after the session's run ended outside eve clears the question's buttons",+ source: "#4835",+ requires: ["buttons"],+ async run(conversation) {+ await pressAfterRunEnded(conversation, "question");+ await expectButtonsCleared(conversation, PROMPT);+ },+ },+ {+ rule: "pressing an option after the session's run ended outside eve tells the person it is no longer active",+ source: "#4835",+ requires: ["buttons"],+ async run(conversation) {+ await pressAfterRunEnded(conversation, "question");+ await conversation.waitForShown(NO_LONGER_ACTIVE);+ },+ },+ {+ rule: "a question pressed after the session's run ended outside eve keeps its prompt and says it is no longer active",+ source: "#4835",+ requires: ["buttons"],+ async run(conversation) {+ await pressAfterRunEnded(conversation, "question");+ await conversation.waitForShown(NO_LONGER_ACTIVE);+ const { text } = await conversation.shownPrompt(PROMPT);+ const message = `the inactive prompt reads ${JSON.stringify(text)}`;+ expect(text, message).toContain(PROMPT);+ expect(text, message).toMatch(NO_LONGER_ACTIVE);+ },+ },+] as const satisfies readonly ContractRule[];+const budgetRules = [{rule: "running out of budget opens budget prompt",@@ -1128,6 +1189,7 @@ export const channelContractSections = [{ title: "Tool approvals", rules: approvalRules },{ title: "Approval permissions", rules: approvalPermissionRules },{ title: "Answered prompts", rules: answeredPromptRules },+ { title: "Inactive prompts", rules: inactivePromptRules },{ title: "Budget prompts", rules: budgetRules },{ title: "Sign-ins", rules: signInRules },{ title: "Tool callers", rules: callerRules },diff --git a/packages/eve/src/internal/testing/channel-conformance/discord-driver.ts b/packages/eve/src/internal/testing/channel-conformance/discord-driver.tsindex 838c1ea92..22b7494c6 100644--- a/packages/eve/src/internal/testing/channel-conformance/discord-driver.ts+++ b/packages/eve/src/internal/testing/channel-conformance/discord-driver.ts@@ -16,6 +16,8 @@ import {let nextChannel = 0;const PERSON = { id: "U_CONFORMANCE", username: "alice" } as const;const PEOPLE = { alice: PERSON, bob: { id: "U_BOB", username: "bob" } } as const;+/** Discord's message flag (1 << 6) for a message only its recipient sees. */+const EPHEMERAL_FLAG = 64;/** A message component eve renders for a choice: a button (type 2) or a select menu (type 3). */interface DiscordComponent {@@ -28,6 +30,8 @@ interface DiscordComponent {interface PressHandle {readonly customId: string;readonly messageId: string;+ /** The pressed message's text, which Discord sends with every component press. */+ readonly content?: string;/** Set for a select menu option; a button press carries no value. */readonly value?: string;}@@ -197,6 +201,8 @@ export function discordDriver(surface: Exclude<Surface, "public"> = "shared"): Creturn {id: (call.response as { readonly id: string }).id,links: linkTargets((call.body as { readonly components?: unknown }).components),+ onlyPerson:+ (((call.body as { readonly flags?: number }).flags ?? 0) & EPHEMERAL_FLAG) !== 0,options: choicesOf(call),text: (call.body as { readonly content?: string }).content ?? "",};@@ -217,7 +223,7 @@ export function discordDriver(surface: Exclude<Surface, "public"> = "shared"): C: { component_type: 3, custom_id: handle.customId, values: [handle.value] },id,...where(PEOPLE[person]),- message: { id: handle.messageId },+ message: { content: handle.content, id: handle.messageId },token: `tok-${id}`,type: 3,version: 1,@@ -234,22 +240,31 @@ export function discordDriver(surface: Exclude<Surface, "public"> = "shared"): Cfunction choicesOf(call: PlatformCall): RenderedOption[] {const body = call.body as {readonly components?: readonly { readonly components?: readonly DiscordComponent[] }[];+ readonly content?: string;};const messageId = (call.response as { readonly id: string }).id;return (body.components ?? []).flatMap((row) =>- (row.components ?? []).flatMap((component) => visibleChoices(component, messageId)),+ (row.components ?? []).flatMap((component) =>+ visibleChoices(component, messageId, body.content),+ ),);}-function visibleChoices(component: DiscordComponent, messageId: string): RenderedOption[] {+function visibleChoices(+ component: DiscordComponent,+ messageId: string,+ content: string | undefined,+): RenderedOption[] {if (component.custom_id === undefined) return [];const customId = component.custom_id;if (component.type === 2 && component.label !== undefined) {- return [{ handle: { customId, messageId } satisfies PressHandle, label: component.label }];+ return [+ { handle: { content, customId, messageId } satisfies PressHandle, label: component.label },+ ];}if (component.type === 3) {return (component.options ?? []).map((option) => ({- handle: { customId, messageId, value: option.value } satisfies PressHandle,+ handle: { content, customId, messageId, value: option.value } satisfies PressHandle,label: option.label,}));}diff --git a/packages/eve/src/internal/testing/channel-conformance/teams-driver.ts b/packages/eve/src/internal/testing/channel-conformance/teams-driver.tsindex 202d0cf52..b67aaf98a 100644--- a/packages/eve/src/internal/testing/channel-conformance/teams-driver.ts+++ b/packages/eve/src/internal/testing/channel-conformance/teams-driver.ts@@ -50,6 +50,8 @@ interface PressHandle {/** The card's activity, which Teams names as `replyToId` on the press. */readonly activityId: string;readonly data: Record<string, unknown>;+ /** Whether the button is an `Action.Execute`, which Teams sends as an invoke. */+ readonly execute: boolean;/** The chosen ChoiceSet value; unset when each option is its own Submit action. */readonly value?: string;}@@ -201,14 +203,25 @@ export function teamsDriver(surface: Exclude<Surface, "public"> = "shared"): Cha},personShownAs: [PERSON.name],press: (option: RenderedOption, person: Person) => {- const { activityId: cardActivityId, data, value } = option.handle as PressHandle;+ const { activityId: cardActivityId, data, execute, value } = option.handle as PressHandle;+ const submitted = value === undefined ? data : { ...data, eve_option: value };+ if (execute) {+ return activity({+ from: PEOPLE[person],+ id: `INVOKE-${activityId + 1}`,+ name: "adaptiveCard/action",+ replyToId: cardActivityId,+ type: "invoke",+ value: { action: { data: submitted } },+ });+ }+ // An Action.Submit button in a conversation posts a message activity whose value is the+ // action's data merged with the card's inputs; only Action.Execute sends an invoke.return activity({from: PEOPLE[person],- id: `INVOKE-${activityId + 1}`,- name: "adaptiveCard/action",replyToId: cardActivityId,- type: "invoke",- value: { action: { data: value === undefined ? data : { ...data, eve_option: value } } },+ type: "message",+ value: submitted,});},postedText(call) {@@ -248,15 +261,21 @@ function cardOptions(call: PlatformCall): RenderedOption[] {);// A select renders one ChoiceSet and a single Submit; other choices are one Submit each.if (choiceSet?.choices !== undefined) {- const data = submits[0]?.data;- if (data === undefined) return [];+ const submit = submits[0];+ if (submit?.data === undefined) return [];+ const { data } = submit;+ const execute = submit.type === "Action.Execute";return choiceSet.choices.map((choice) => ({- handle: { activityId, data, value: choice.value } satisfies PressHandle,+ handle: { activityId, data, execute, value: choice.value } satisfies PressHandle,label: choice.title,}));}return submits.map((action) => ({- handle: { activityId, data: action.data! } satisfies PressHandle,+ handle: {+ activityId,+ data: action.data!,+ execute: action.type === "Action.Execute",+ } satisfies PressHandle,label: action.title ?? "",}));}diff --git a/packages/eve/src/internal/testing/channel-conformance/telegram-driver.ts b/packages/eve/src/internal/testing/channel-conformance/telegram-driver.tsindex 5aac1623e..0dd72bac0 100644--- a/packages/eve/src/internal/testing/channel-conformance/telegram-driver.ts+++ b/packages/eve/src/internal/testing/channel-conformance/telegram-driver.ts@@ -79,6 +79,10 @@ export function telegramDriver(surface: Exclude<Surface, "public"> = "shared"):let messageId = 0;/** The bot's latest message, which a person in a group replies to so the bot hears them. */let lastBotMessage: number | undefined;+ /** Each bot message's text as last written, by message id. */+ const texts = new Map<number, string>();+ /** The text a keyboard-only edit leaves in place, which its body doesn't carry. */+ const keptText = new WeakMap<PlatformCall, string>();/*** A group's default policy hears only mentions and replies to the bot, and a@@ -151,11 +155,16 @@ export function telegramDriver(surface: Exclude<Surface, "public"> = "shared"):}messageId += 1;if (method === "sendMessage") lastBotMessage = messageId;- return {+ const call: PlatformCall = {body: text === "" ? {} : JSON.parse(text),method,response: { ok: true, result: { chat: CHAT, date: 0, message_id: messageId } },};+ // Editing only the keyboard leaves the message's text as it was.+ const id = messageIdOf(call);+ if (method === "editMessageReplyMarkup") keptText.set(call, texts.get(id) ?? "");+ else if (MESSAGE_WRITES.has(method)) texts.set(id, (call.body as MessageBody).text ?? "");+ return call;}return {@@ -211,7 +220,7 @@ export function telegramDriver(surface: Exclude<Surface, "public"> = "shared"):onlyPerson: (call.body as MessageBody).ephemeral_message_parameters !== undefined,// Telegram drops a message's inline keyboard when an edit omits `reply_markup`.options: inlineOptions(call),- text: (call.body as MessageBody).text ?? "",+ text: keptText.get(call) ?? (call.body as MessageBody).text ?? "",};},personShownAs: [PERSON.first_name],@@ -227,7 +236,7 @@ export function telegramDriver(surface: Exclude<Surface, "public"> = "shared"):data,from: PEOPLE[person],id: `callback-${updateId}`,- message: { chat: CHAT, date: 0, message_id: messageId },+ message: { chat: CHAT, date: 0, message_id: messageId, text: texts.get(messageId) },},});},diff --git a/packages/eve/src/public/channels/chat-sdk/chatSdkChannel.test.ts b/packages/eve/src/public/channels/chat-sdk/chatSdkChannel.test.tsindex 18cb1abab..b6eda6281 100644--- a/packages/eve/src/public/channels/chat-sdk/chatSdkChannel.test.ts+++ b/packages/eve/src/public/channels/chat-sdk/chatSdkChannel.test.ts@@ -4,7 +4,9 @@ import type { Message as ExternalMessage, Thread as ExternalThread } from "chat"import { buildAdapterContext } from "#channel/adapter-context.js";import { callAdapterEventHandler, type ChannelAdapter } from "#channel/adapter.js";import { isCompiledChannel, type CompiledChannel } from "#channel/compiled-channel.js";+import { INACTIVE_REQUEST_NOTICE } from "#channel/inactive-prompt.js";import { isHttpRouteDefinition } from "#channel/routes.js";+import { SessionNotActiveError } from "#channel/session-not-active-error.js";import { ContextContainer, contextStorage } from "#context/container.js";import { sessionView } from "#harness/session-machine/commit.js";import { enterSessionProjection, recordPublishedEvent } from "#harness/session-machine/current.js";@@ -112,6 +114,7 @@ async function firePost(channel: unknown,path: string,body: Record<string, unknown>,+ sendError?: Error,): Promise<{cancel: ReturnType<typeof vi.fn>;response: Response;@@ -124,6 +127,7 @@ async function firePost(throw new Error(`Expected POST ${path}.`);}const send = vi.fn().mockResolvedValue({ id: "session-1" });+ if (sendError) send.mockRejectedValue(sendError);const cancel = vi.fn().mockResolvedValue({ sessionId: "session-1", status: "accepted" });const waitUntil = vi.fn();const channelContext = mockChannelContext<ChatSdkChannelState>(send);@@ -355,6 +359,87 @@ describe("chatSdkChannel", () => {);});+ describe("pressing a button no session can take", () => {+ const press = { actionId: "eve_input:request-1:approve", kind: "action", value: "approve" };++ async function pressWith(adapter: TestAdapter & Adapter, error: Error) {+ const ephemerals: Array<{ message: AdapterPostableMessage; userId: string }> = [];+ adapter.postEphemeral = async (threadId, userId, posted) => {+ ephemerals.push({ message: posted, userId });+ return { id: "e1", raw: {}, threadId, usedFallback: false };+ };+ const bridge = chatSdkChannel({+ adapters: { test: adapter },+ concurrency: "concurrent",+ logger: "warn",+ state: memoryState(),+ userName: "bot",+ });+ const { response } = await firePost(bridge.channel, "/eve/v1/test", press, error);+ expect(response.status).toBe(200);+ return ephemerals;+ }++ it("retires the pressed card and tells only the presser", async () => {+ const adapter = testAdapter();++ const ephemerals = await pressWith(adapter, new SessionNotActiveError());++ expect(adapter.edited).toMatchObject([+ {+ message: {+ card: { type: "card", children: [{ type: "text", content: "No longer active" }] },+ fallbackText: "No longer active",+ },+ messageId: "message-1",+ threadId: THREAD_ID,+ },+ ]);+ expect(ephemerals).toEqual([+ { message: { markdown: INACTIVE_REQUEST_NOTICE }, userId: author().userId },+ ]);+ });++ it("still tells the presser when the adapter can't edit", async () => {+ const adapter = testAdapter();+ adapter.editError = new NotImplementedError("editMessage");++ const ephemerals = await pressWith(adapter, new SessionNotActiveError());++ expect(adapter.edited).toEqual([]);+ expect(ephemerals).toHaveLength(1);+ });++ it.each([+ ["authorization", { resolveInputAuth: () => Promise.reject(new Error("auth down")) }],+ ["delivery", {}, new Error("network down")],+ ] as const)(+ "lets Chat SDK see a failed %s and leaves the card live",+ async (_, config, sendError?: Error) => {+ const adapter = testAdapter();+ adapter.postEphemeral = vi.fn();+ const bridge = chatSdkChannel({+ adapters: { test: adapter },+ concurrency: "concurrent",+ logger: "warn",+ state: memoryState(),+ userName: "bot",+ ...config,+ });+ const later = vi.fn();+ bridge.bot.onAction(later);++ await expect(firePost(bridge.channel, "/eve/v1/test", press, sendError)).rejects.toThrow(+ sendError?.message ?? "auth down",+ );++ expect(later).not.toHaveBeenCalled();+ expect(adapter.edited).toEqual([]);+ expect(adapter.postEphemeral).not.toHaveBeenCalled();+ },+ );+ });+it("fails loudly when bridge.send is called outside a Chat SDK webhook", async () => {const bridge = chatSdkChannel({adapters: { test: testAdapter() },diff --git a/packages/eve/src/public/channels/chat-sdk/chatSdkChannel.ts b/packages/eve/src/public/channels/chat-sdk/chatSdkChannel.tsindex f23d88bd3..5684f3005 100644--- a/packages/eve/src/public/channels/chat-sdk/chatSdkChannel.ts+++ b/packages/eve/src/public/channels/chat-sdk/chatSdkChannel.ts@@ -7,6 +7,10 @@ import type {ChannelSendOptions,} from "#channel/channel-operations.js";import { defaultDeliverResult } from "#channel/adapter.js";+import {+ INACTIVE_REQUEST_NOTICE,+ respondOrRetireInactivePrompt,+} from "#channel/inactive-prompt.js";import type { SessionHandle } from "#channel/session.js";import type { DeliverPayload, SessionAuthContext, TurnPolicy } from "#channel/types.js";import { ContextContainer, contextStorage } from "#context/container.js";@@ -34,7 +38,11 @@ import type {import { Chat, Message, ThreadImpl } from "#compiled/chat/index.js";import { defaultAuthorizationEvents } from "#public/channels/chat-sdk/authorization.js";import { parseChatSdkFileRef } from "#public/channels/chat-sdk/attachment-refs.js";-import { decodeInputAction, renderInputRequests } from "#public/channels/chat-sdk/input-actions.js";+import {+ decodeInputAction,+ renderInputRequests,+ renderRetiredInputRequest,+} from "#public/channels/chat-sdk/input-actions.js";import { DEFAULT_UPLOAD_POLICY } from "#public/channels/upload-policy.js";import { isNotImplemented } from "#public/channels/chat-sdk/notImplemented.js";import {@@ -293,15 +301,30 @@ export function chatSdkChannel<TAdapters extends ChatSdkAdapters>(bot.onAction(async (event: ActionEvent) => {const response = decodeInputAction(event.actionId, inputActionPrefix, event.value);if (!response) return;- if (!event.thread) {+ const { thread } = event;+ if (!thread) {throw new Error("chatSdkChannel input actions require a thread on the Chat SDK action event.",);}- await bridgeRespond(bot, [response], {- auth: config.resolveInputAuth ? await config.resolveInputAuth(event) : null,- thread: event.thread.toJSON(),- });+ const auth = config.resolveInputAuth ? await config.resolveInputAuth(event) : null;+ const answer = await respondOrRetireInactivePrompt(+ () => bridgeRespond(bot, [response], { auth, thread: thread.toJSON() }),+ {+ retirePrompt: (label) => retireInputCard(thread, event.messageId, label),+ },+ log,+ );+ // Chat SDK stops its action handlers at a throw, as it did before inactive+ // presses were told apart from other failures.+ if (answer.outcome === "failed") throw answer.error;+ if (answer.outcome === "delivered") return;+ await Promise.all([+ answer.retirement,+ thread+ .postEphemeral(event.user, { markdown: INACTIVE_REQUEST_NOTICE }, { fallbackToDM: true })+ .catch((error: unknown) => log.error("inactive prompt notice failed", { error })),+ ]);});const channel = defineChannel<@@ -556,6 +579,23 @@ async function editMessage(thread: Thread, messageId: string, markdown: string):await thread.adapter.editMessage(thread.id, messageId, { markdown });}+/**+ * Replaces a pressed request card with only `label`. The session that held the+ * request is gone and a press carries no prompt text, so the prompt can't be+ * kept; what matters is that the buttons stop being offered.+ */+async function retireInputCard(+ thread: Pick<Thread, "adapter" | "id">,+ messageId: string,+ label: string,+): Promise<void> {+ try {+ await thread.adapter.editMessage(thread.id, messageId, renderRetiredInputRequest(label));+ } catch (error) {+ if (!isNotImplemented(error)) throw error;+ }+}+/*** Finalizes a completed assistant message. When a streamed anchor exists, edits* it in place so it shows the complete text instead of the last throttleddiff --git a/packages/eve/src/public/channels/chat-sdk/input-actions.ts b/packages/eve/src/public/channels/chat-sdk/input-actions.tsindex 545ccc610..732db53b8 100644--- a/packages/eve/src/public/channels/chat-sdk/input-actions.ts+++ b/packages/eve/src/public/channels/chat-sdk/input-actions.ts@@ -42,6 +42,11 @@ export function renderInputRequests(};}+/** Renders a request card whose prompt is unknown as only how it ended. */+export function renderRetiredInputRequest(label: string) {+ return { card: Card({ children: [CardText(label)] }), fallbackText: label };+}+// The SDK's card fallback drops buttons, so the options are numbered instead.function renderInputRequestText(request: InputRequest): string {const options = request.options ?? [];diff --git a/packages/eve/src/public/channels/discord/defaults.ts b/packages/eve/src/public/channels/discord/defaults.tsindex 635ffa150..a2ec201b0 100644--- a/packages/eve/src/public/channels/discord/defaults.ts+++ b/packages/eve/src/public/channels/discord/defaults.ts@@ -15,6 +15,8 @@ import type {DiscordChannelEvents,DiscordCommandResult,DiscordContext,+ DiscordHandle,+ DiscordHitlPrompt,} from "#public/channels/discord/discordChannel.js";const log = createLogger("discord.defaults");@@ -59,6 +61,26 @@ export function defaultOnCommand(return { auth: defaultDiscordAuth(interaction) };}+/**+ * Edits a posted prompt the way a resolved one reads: its prompt kept, its+ * choices replaced by `label`. Throws when Discord refuses the edit.+ */+export async function editDiscordResolvedPrompt(+ discord: Pick<DiscordHandle, "channelId" | "request">,+ prompt: Pick<DiscordHitlPrompt, "content" | "messageId">,+ label: string,+): Promise<void> {+ const content = `${prompt.content}\n\n${label}`.slice(0, DISCORD_MESSAGE_CONTENT_MAX_LENGTH);+ const response = await discord.request(+ `/channels/${encodeURIComponent(discord.channelId)}/messages/${encodeURIComponent(prompt.messageId)}`,+ { components: [], content },+ { botAuth: true, method: "PATCH" },+ );+ if (!response.ok) {+ throw new Error(`Discord prompt edit failed with HTTP ${response.status}.`);+ }+}+/** Built-in Discord event handlers for typing, replies, HITL, and terminal errors. */export const defaultEvents: DiscordChannelEvents = {async "turn.started"(_event, channel, _ctx) {@@ -101,19 +123,8 @@ export const defaultEvents: DiscordChannelEvents = {const { [resolution.requestId]: _, ...rest } = channel.state.hitlPrompts ?? {};channel.state.hitlPrompts = rest;const label = resolvedPromptLabel(resolution, prompt.options);- const content = `${prompt.content}\n\n${label}`.slice(0, DISCORD_MESSAGE_CONTENT_MAX_LENGTH);try {- const response = await channel.discord.request(- `/channels/${encodeURIComponent(channel.discord.channelId)}/messages/${encodeURIComponent(prompt.messageId)}`,- { components: [], content },- { botAuth: true, method: "PATCH" },- );- if (!response.ok) {- log.warn("Discord answered prompt edit failed", {- requestId: resolution.requestId,- status: response.status,- });- }+ await editDiscordResolvedPrompt(channel.discord, prompt, label);} catch (error) {log.warn("Discord answered prompt edit failed", { error, requestId: resolution.requestId });}diff --git a/packages/eve/src/public/channels/discord/discordChannel.test.ts b/packages/eve/src/public/channels/discord/discordChannel.test.tsindex 0366657af..8b91ed7ee 100644--- a/packages/eve/src/public/channels/discord/discordChannel.test.ts+++ b/packages/eve/src/public/channels/discord/discordChannel.test.ts@@ -1,11 +1,13 @@import { generateKeyPairSync, sign, type KeyObject } from "node:crypto";-import { afterEach, describe, expect, it, vi } from "vitest";+import { afterEach, describe, expect, it, type Mock, vi } from "vitest";import { buildAdapterContext } from "#channel/adapter-context.js";import { callAdapterEventHandler, type ChannelAdapter } from "#channel/adapter.js";import { isCompiledChannel, type CompiledChannel } from "#channel/compiled-channel.js";+import { INACTIVE_REQUEST_NOTICE } from "#channel/inactive-prompt.js";import { isHttpRouteDefinition } from "#channel/routes.js";+import { SessionNotActiveError } from "#channel/session-not-active-error.js";import { ContextContainer, contextStorage } from "#context/container.js";import { SessionKey } from "#context/keys.js";import { mockChannelContext } from "#internal/testing/mocks/mock-channel-operations.js";@@ -131,9 +133,10 @@ function signedRequest(input: {async function firePost(channel: unknown,request: Request,+ send: Mock<(...args: any[]) => any> = vi.fn().mockResolvedValue({ id: "s1" }),): Promise<{response: Response;- send: ReturnType<typeof vi.fn>;+ send: Mock<(...args: any[]) => any>;waitUntil: ReturnType<typeof vi.fn>;}> {const compiled = asCompiled(channel);@@ -141,7 +144,6 @@ async function firePost(if (!post || !isHttpRouteDefinition(post)) {throw new Error("Expected discord channel to define a POST route.");}- const send = vi.fn().mockResolvedValue({ id: "s1" });const waitUntil = vi.fn();const response = await post.handler(request, {@@ -303,7 +305,7 @@ describe("discordChannel() inbound route", () => {})[0] as { components: Array<{ custom_id: string }> }).components[0]!.custom_id;/** A press of Approve in guild G01, as Discord sends it: the presser on `member`. */- const press = (userId: string) =>+ const press = (userId: string, content: string | null = "Approve?") =>signedRequest({body: JSON.stringify({application_id: "APP1",@@ -312,7 +314,7 @@ describe("discordChannel() inbound route", () => {guild_id: "G01",id: `I-${userId}`,member: { user: { id: userId, username: userId } },- message: { id: "M01" },+ message: { content, id: "M01" },token: "tok2",type: 3,version: 1,@@ -372,6 +374,74 @@ describe("discordChannel() inbound route", () => {expect(send).not.toHaveBeenCalled();expect(logs.records).toContainEqual(expect.objectContaining(log));});++ describe("when no session takes the press", () => {+ const notActive = () => vi.fn().mockRejectedValue(new SessionNotActiveError());+ const discordApi = (config: Parameters<typeof discordChannel>[0] = {}) => {+ const fetchMock = vi.fn(async (_url: unknown, _init?: RequestInit) =>+ Response.json({ channel_id: "C01", id: "M02" }),+ );+ return {+ channel: discordChannel({+ api: { fetch: fetchMock as typeof fetch },+ credentials: { applicationId: "APP1", botToken: "bot-token", publicKey: publicKeyHex },+ ...config,+ }),+ calls: () =>+ fetchMock.mock.calls.map(([url, init]) => ({+ body: JSON.parse(String(init?.body)) as unknown,+ method: init?.method,+ url: String(url),+ })),+ };+ };+ const prompt = {+ body: { components: [], content: "Approve?\n\nNo longer active" },+ method: "PATCH",+ url: "https://discord.com/api/v10/channels/C01/messages/M01",+ };+ const notice = {+ body: { allowed_mentions: { parse: [] }, content: INACTIVE_REQUEST_NOTICE, flags: 64 },+ method: "POST",+ url: "https://discord.com/api/v10/webhooks/APP1/tok2",+ };++ it("retires the pressed prompt and tells only the presser", async () => {+ captureLogRecords();+ const { channel, calls } = discordApi();++ await firePost(channel, press("U01"), notActive());++ expect(calls()).toEqual([prompt, notice]);+ });++ it("only tells the presser when the press carries no prompt to keep", async () => {+ captureLogRecords();+ const { channel, calls } = discordApi();++ await firePost(channel, press("U01", null), notActive());++ expect(calls()).toEqual([notice]);+ });++ it("leaves the prompt alone when delivery fails for another reason", async () => {+ captureLogRecords();+ const { channel, calls } = discordApi();++ await firePost(channel, press("U01"), vi.fn().mockRejectedValue(new Error("boom")));++ expect(calls()).toEqual([]);+ });++ it("leaves the prompt alone when onInputResponse drops the press", async () => {+ captureLogRecords();+ const { channel, calls } = discordApi({ onInputResponse: () => null });++ await firePost(channel, press("U01"), notActive());++ expect(calls()).toEqual([]);+ });+ });});it("opens and resolves freeform HITL modals", async () => {diff --git a/packages/eve/src/public/channels/discord/discordChannel.ts b/packages/eve/src/public/channels/discord/discordChannel.tsindex 1a7e6626a..c61004202 100644--- a/packages/eve/src/public/channels/discord/discordChannel.ts+++ b/packages/eve/src/public/channels/discord/discordChannel.ts@@ -1,5 +1,9 @@import type { DiscordInstrumentationMetadata } from "#public/channels/discord/index.js";import type { ChannelFrom } from "#channel/channel-operations.js";+import {+ INACTIVE_REQUEST_NOTICE,+ respondOrRetireInactivePrompt,+} from "#channel/inactive-prompt.js";import type { SessionHandle } from "#channel/session.js";import type { SessionAuthContext, TurnPolicy } from "#channel/types.js";import type { SessionContext } from "#public/definitions/callback-context.js";@@ -25,6 +29,7 @@ import {defaultDiscordAuth,defaultEvents,defaultOnCommand,+ editDiscordResolvedPrompt,} from "#public/channels/discord/defaults.js";import {deriveComponentInputResponses,@@ -34,6 +39,7 @@ import {} from "#public/channels/discord/hitl.js";import {commandInteractionMessage,+ DISCORD_EPHEMERAL_MESSAGE_FLAG,DISCORD_INTERACTION_RESPONSE_TYPE,DISCORD_INTERACTION_TYPE,formatDiscordContextBlock,@@ -708,12 +714,13 @@ async function dispatchInputResponses(input: {hasMessageAnchor: input.conversationId !== input.interaction.id,initialResponseSent: true,});+ const discord = buildDiscordHandle({ config: input.config, state });let result: DiscordInputResponseResult;try {result = await input.onInputResponse({defaultAuth: defaultDiscordAuth(input.interaction),- discord: buildDiscordHandle({ config: input.config, state }),+ discord,},input.interaction,);@@ -722,14 +729,38 @@ async function dispatchInputResponses(input: {return;}if (result === null) return;+ const { auth } = result;+ const source = input.from(+ discordContinuationToken(input.interaction.channelId, input.conversationId),+ );+ const response = await respondOrRetireInactivePrompt(+ () => source.respond(input.inputResponses, { auth }),+ {+ // The session's record of the prompt is gone, so its text comes from the+ // pressed message. A modal submitted outside a message has neither, and+ // editing without the prompt would erase it.+ retirePrompt: async (label) => {+ const messageId = input.interaction.messageId;+ const content = readMessageContent(input.interaction.raw);+ if (messageId === undefined || content === undefined) return;+ await editDiscordResolvedPrompt(discord, { content, messageId }, label);+ },+ },+ log,+ );+ if (response.outcome !== "inactive") return;+ await Promise.all([response.retirement, sendInactiveNotice(discord)]);+}++/** Tells only the presser that the prompt they answered is no longer active. */+async function sendInactiveNotice(discord: DiscordHandle): Promise<void> {try {- await input- .from(discordContinuationToken(input.interaction.channelId, input.conversationId))- .respond(input.inputResponses, {- auth: result.auth,- });+ await discord.followup({+ content: INACTIVE_REQUEST_NOTICE,+ flags: DISCORD_EPHEMERAL_MESSAGE_FLAG,+ });} catch (error) {- log.error("interaction response delivery failed", { error });+ log.error("inactive prompt notice failed", { error });}}diff --git a/packages/eve/src/public/channels/inactive-session-press.integration.test.ts b/packages/eve/src/public/channels/inactive-session-press.integration.test.tsdeleted file mode 100644index 0018deb98..000000000--- a/packages/eve/src/public/channels/inactive-session-press.integration.test.ts+++ /dev/null@@ -1,32 +0,0 @@-import { expect, it } from "vitest";--import {- deployPrompt,- GATED_TOOL,- withChannelConversation,-} from "#internal/testing/channel-conformance/harness.js";-import { slackDriver } from "#internal/testing/channel-conformance/slack-driver.js";-import { teamsDriver } from "#internal/testing/channel-conformance/teams-driver.js";-import { telegramDriver } from "#internal/testing/channel-conformance/telegram-driver.js";--// #4835: an operator cancels a session's run through the workflow world, so-// eve never withdraws its pending approval. A later press reaches no session.-for (const driver of [slackDriver(), teamsDriver(), telegramDriver()]) {- it.fails(- `${driver.name}: pressing Approve after the session's run was cancelled outside eve clears the approval's buttons and says it is no longer active`,- () =>- withChannelConversation(driver, async (conversation) => {- const prompt = deployPrompt("v2.4");- await conversation.say(`Use ${GATED_TOOL} to ship release "v2.4".`);- const options = await conversation.waitForQuestion(prompt);- await conversation.cancelRunsInWorld();-- await conversation.press(options.find(({ label }) => label === "Approve")!);-- expect(conversation.runsOf(GATED_TOOL)).toBe(0);- expect((await conversation.shownPrompt(prompt)).options).toEqual([]);- await conversation.waitForShown(/no longer active/);- }),- 60_000,- );-}diff --git a/packages/eve/src/public/channels/slack/approval-cards.ts b/packages/eve/src/public/channels/slack/approval-cards.tsindex 0743d38ca..9fdffa041 100644--- a/packages/eve/src/public/channels/slack/approval-cards.ts+++ b/packages/eve/src/public/channels/slack/approval-cards.ts@@ -14,7 +14,10 @@ import {renderInputRequestPostParts,type SlackInputRequestPostPart,} from "#public/channels/slack/hitl.js";-import { answeredBlocksFromActionBlock } from "#public/channels/slack/interaction-cards.js";+import {+ answeredBlocksFromActionBlock,+ type SettledCard,+} from "#public/channels/slack/interaction-cards.js";import {SLACK_MAX_BLOCKS_PER_MESSAGE,truncateMessageText,@@ -135,7 +138,7 @@ function recordApprovalCards(async function settleApprovalCard(channel: SlackEventContext,requestId: string,- answer: { readonly announcement: string; readonly label: string; readonly userId?: string },+ answer: SettledCard & { readonly announcement: string },): Promise<void> {const cards = channel.state.pendingApprovalCards ?? {};const card = cards[requestId];@@ -154,7 +157,7 @@ async function settleApprovalCard(answeredBlocksFromActionBlock({answerLabel: answer.label,block,- userId: answer.userId ?? "",+ userId: answer.userId,}) ?? buildAnsweredBlocks({ answerLabel: answer.label, promptBlocks: [] }));});@@ -166,7 +169,7 @@ async function settleApprovalCard(await settleRequest(channel, "chat.update", requestId, {blocks,channel: messageChannelId,- text: `Answered: ${answer.label}`,+ text: answer.text,ts: card.messageTs,});@@ -289,9 +292,11 @@ export const approvalEvents: Pick<const approved = event.outcome === "approved";const userId = slackUserIdForPrincipal(channel.state, event.responderPrincipalId);const by = userId === undefined ? "" : ` by <@${userId}>`;+ const label = approved ? "Approve" : "Cancel";await settleApprovalCard(channel, event.requestId, {announcement: `${approved ? "Approved" : "Cancelled"}${by}.`,- label: approved ? "Approve" : "Cancel",+ label,+ text: `Answered: ${label}`,userId,});},@@ -308,12 +313,13 @@ export const approvalEvents: Pick<: resolution.outcome === "denied"? "Cancel": "No longer needed";+ const withdrawn = label === "No longer needed";await settleApprovalCard(channel, resolution.requestId, {- announcement:- label === "No longer needed"- ? "This approval is no longer needed."- : `${label === "Approve" ? "Approved" : "Cancelled"}.`,+ announcement: withdrawn+ ? "This approval is no longer needed."+ : `${label === "Approve" ? "Approved" : "Cancelled"}.`,label,+ text: withdrawn ? label : `Answered: ${label}`,});}},diff --git a/packages/eve/src/public/channels/slack/defaults.test.ts b/packages/eve/src/public/channels/slack/defaults.test.tsindex 86bf924a3..bee45f197 100644--- a/packages/eve/src/public/channels/slack/defaults.test.ts+++ b/packages/eve/src/public/channels/slack/defaults.test.ts@@ -342,7 +342,7 @@ describe("defaultInputRequestedHandler private input requests", () => {"chat.update",expect.objectContaining({channel: "C123",- text: "Answered: No longer needed",+ text: "No longer needed",ts: "card-ts",}),);@@ -352,6 +352,38 @@ describe("defaultInputRequestedHandler private input requests", () => {expect.objectContaining({ level: "error", message: "failed to retire approval message" }),);});++ it("announces an approval answered by an unmapped responder as answered, crediting nobody", async () => {+ const { channel, post, request } = buildChannelStub();+ post+ .mockResolvedValueOnce({ id: "details-ts", raw: { ok: true } })+ .mockResolvedValueOnce({ id: "card-ts", raw: { ok: true } });++ await defaultInputRequestedHandler()(+ { requests: [approvalRequest()], sequence: 1, stepIndex: 0, turnId: "turn-1" },+ channel,+ sessionCtx,+ );+ await defaultEvents["approval.settled"]!(+ {+ outcome: "approved",+ requestId: "approval-1",+ responderPrincipalId: "custom:unmapped",+ sequence: 2,+ stepIndex: 0,+ turnId: "turn-1",+ },+ channel,+ sessionCtx,+ );++ const update = request.mock.calls.find(([method]) => method === "chat.update")?.[1] as {+ blocks?: unknown[];+ text?: string;+ };+ expect(update.text).toBe("Answered: Approve");+ expect(JSON.stringify(update.blocks)).not.toContain("<@");+ });});describe("defaultEvents approval lifecycle", () => {diff --git a/packages/eve/src/public/channels/slack/interaction-cards.ts b/packages/eve/src/public/channels/slack/interaction-cards.tsindex 11946efdb..b5bf6ff1b 100644--- a/packages/eve/src/public/channels/slack/interaction-cards.ts+++ b/packages/eve/src/public/channels/slack/interaction-cards.ts@@ -9,11 +9,21 @@ import type {ParsedBlockActionsPayload,} from "#public/channels/slack/interactions.js";-function buildAnsweredHitlMessageBlocks(input: {+/**+ * What a settled card shows in place of its controls: the line that replaces+ * them, the notification text of the update, such as `Answered: Saturday` or+ * `No longer active`, and who answered when the card credits someone.+ */+export interface SettledCard {+ readonly label: string;+ readonly text: string;+ readonly userId?: string;+}++function buildSettledHitlMessageBlocks(input: {readonly actionId: string;- readonly answerLabel: string;+ readonly card: SettledCard;readonly messageBlocks: readonly unknown[];- readonly userId: string;}): unknown[] {const actionBlockIndex = input.messageBlocks.findIndex((block) =>blockContainsActionId(block, input.actionId),@@ -21,22 +31,22 @@ function buildAnsweredHitlMessageBlocks(input: {if (actionBlockIndex === -1) {return buildAnsweredBlocks({promptBlocks: findPromptBlocks(input.messageBlocks),- answerLabel: input.answerLabel,- userId: input.userId,+ answerLabel: input.card.label,+ userId: input.card.userId,});}const actionBlock = input.messageBlocks[actionBlockIndex];const answeredBlocks =answeredBlocksFromActionBlock({- answerLabel: input.answerLabel,+ answerLabel: input.card.label,block: actionBlock,- userId: input.userId,+ userId: input.card.userId,}) ??buildAnsweredBlocks({promptBlocks: promptBlocksFromActionBlock(actionBlock),- answerLabel: input.answerLabel,- userId: input.userId,+ answerLabel: input.card.label,+ userId: input.card.userId,});return [...input.messageBlocks.slice(0, actionBlockIndex),@@ -75,7 +85,7 @@ function actionsContainActionId(actions: unknown, actionId: string): boolean {export function answeredBlocksFromActionBlock(input: {readonly answerLabel: string;readonly block: unknown;- readonly userId: string;+ readonly userId?: string;}): unknown[] | undefined {if (!isObjectRecord(input.block) || input.block.type !== "card") return undefined;@@ -96,9 +106,9 @@ const ANSWERED_CARD_SUBTEXT_SUFFIX = "*";function formatAnsweredCardSubtext(input: {readonly answerLabel: string;- readonly userId: string;+ readonly userId?: string;}): string {- const attribution = input.userId.length > 0 ? ` by <@${input.userId}>` : "";+ const attribution = input.userId === undefined ? "" : ` by <@${input.userId}>`;const labelBudget =SLACK_CARD_SUBTEXT_MAX_LENGTH -ANSWERED_CARD_SUBTEXT_PREFIX.length -@@ -132,25 +142,37 @@ function isObjectRecord(value: unknown): value is Record<string, unknown> {return typeof value === "object" && value !== null;}+/** Settles a pressed HITL card as answered by the presser with the choice they pressed. */export async function updateAnsweredHitlCard(interaction: ParsedBlockActionsPayload,deps: InteractionHandlerDeps,): Promise<void> {const hitlAction = interaction.actions.find((action) => isHitlAction(action.actionId));- if (!hitlAction?.messageTs) return;-- const answerLabel = hitlAction.label ?? hitlAction.selectedOptionValue ?? hitlAction.value;- if (!answerLabel) return;-- const blocks = buildAnsweredHitlMessageBlocks({- actionId: hitlAction.actionId,- answerLabel,- messageBlocks: interaction.messageBlocks,+ const label = hitlAction?.label ?? hitlAction?.selectedOptionValue ?? hitlAction?.value;+ if (!hitlAction || !label) return;+ await settleHitlCard(interaction, deps, {+ label,+ text: `Answered: ${label}`,userId: hitlAction.user.id,});- await updateAnsweredCard({- answerLabel,- blocks,+}++/** Replaces a pressed HITL card's controls with `card`. */+export async function settleHitlCard(+ interaction: ParsedBlockActionsPayload,+ deps: InteractionHandlerDeps,+ card: SettledCard,+): Promise<void> {+ const hitlAction = interaction.actions.find((action) => isHitlAction(action.actionId));+ if (!hitlAction?.messageTs) return;++ await updateSettledCard({+ blocks: buildSettledHitlMessageBlocks({+ actionId: hitlAction.actionId,+ card,+ messageBlocks: interaction.messageBlocks,+ }),+ card,channelId: interaction.channelId,deps,installationTeamId: interaction.installationTeamId,@@ -158,27 +180,27 @@ export async function updateAnsweredHitlCard(});}-export async function updateAnsweredFreeformCard(input: {+/** Replaces a freeform card's controls with `card`. */+export async function settleFreeformCard(input: {+ readonly card: SettledCard;readonly channelId: string;- readonly messageTs: string;- readonly answerLabel: string;- readonly userId?: string;- readonly installationTeamId?: string;readonly deps: InteractionHandlerDeps;+ readonly installationTeamId?: string;+ readonly messageTs: string;}): Promise<void> {- await updateAnsweredCard({+ await updateSettledCard({...input,blocks: buildAnsweredBlocks({promptBlocks: [],- answerLabel: input.answerLabel,- userId: input.userId,+ answerLabel: input.card.label,+ userId: input.card.userId,}),});}-async function updateAnsweredCard(input: {- readonly answerLabel: string;+async function updateSettledCard(input: {readonly blocks: unknown[];+ readonly card: SettledCard;readonly channelId: string;readonly deps: InteractionHandlerDeps;readonly installationTeamId?: string;@@ -193,7 +215,7 @@ async function updateAnsweredCard(input: {channel: input.channelId,ts: input.messageTs,blocks: input.blocks,- text: `Answered: ${input.answerLabel}`,+ text: input.card.text,},});}diff --git a/packages/eve/src/public/channels/slack/interactions.ts b/packages/eve/src/public/channels/slack/interactions.tsindex 47f1efacb..f4560987f 100644--- a/packages/eve/src/public/channels/slack/interactions.ts+++ b/packages/eve/src/public/channels/slack/interactions.ts@@ -37,7 +37,8 @@ import {} from "#public/channels/slack/hitl.js";import { readSlackTextObject } from "#public/channels/slack/inbound-content.js";import {- updateAnsweredFreeformCard,+ settleFreeformCard,+ settleHitlCard,updateAnsweredHitlCard,} from "#public/channels/slack/interaction-cards.js";import { authorizeInputResponse } from "#public/channels/slack/input-response.js";@@ -52,6 +53,10 @@ import type {SlackShortcutContext,} from "#public/channels/slack/slackChannel.js";import type { ChannelFrom, ChannelResolveSession } from "#channel/channel-operations.js";+import {+ INACTIVE_REQUEST_NOTICE,+ respondOrRetireInactivePrompt,+} from "#channel/inactive-prompt.js";import {bindSlackSessionOperations,withSlackResponder,@@ -496,17 +501,34 @@ async function dispatchBlockInputResponses(input: {});if (result === null) return;- try {- await input.ctx- .from(slackContinuationToken(channelId, threadTs))- .respond(input.submission.inputResponses, {- auth: result.auth,- state: withSlackResponder(undefined, input.submission.user.id),- });- } catch (error) {- log.error("HITL interaction delivery failed", { error });- return;+ const response = await respondOrRetireInactivePrompt(+ () =>+ input.ctx+ .from(slackContinuationToken(channelId, threadTs))+ .respond(input.submission.inputResponses, {+ auth: result.auth,+ state: withSlackResponder(undefined, input.submission.user.id),+ }),+ {+ retirePrompt: (label) =>+ settleHitlCard(input.interaction, input.deps, { label, text: label }),+ },+ log,+ );+ if (response.outcome === "inactive") {+ await Promise.all([+ response.retirement,+ postEphemeralNotice({+ channelId: input.interaction.channelId,+ deps: input.deps,+ installationTeamId: input.interaction.installationTeamId,+ teamId: input.interaction.teamId,+ threadTs: input.interaction.threadTs,+ userId: input.submission.user.id,+ }),+ ]);}+ if (response.outcome !== "delivered") return;if (input.submission.actions.some((action) => decodeHitlResponse(action)?.kind === "tool-approval")@@ -521,6 +543,30 @@ async function dispatchBlockInputResponses(input: {}}+/** Tells only `userId` that the card they answered is no longer active. */+async function postEphemeralNotice(input: {+ readonly channelId: string;+ readonly deps: InteractionHandlerDeps;+ readonly installationTeamId: string | undefined;+ readonly teamId: string | undefined;+ readonly threadTs: string;+ readonly userId: string;+}): Promise<void> {+ const { thread } = buildSlackBinding({+ api: input.deps.api,+ botToken: input.deps.config.credentials?.botToken,+ channelId: input.channelId,+ installationTeamId: input.installationTeamId,+ teamId: input.teamId,+ threadTs: input.threadTs,+ });+ try {+ await thread.postEphemeral(input.userId, INACTIVE_REQUEST_NOTICE);+ } catch (error) {+ log.error("inactive prompt notice failed", { error });+ }+}+async function openFreeformModal(input: {readonly payload: Record<string, unknown>;readonly interaction: ParsedBlockActionsPayload;@@ -655,7 +701,9 @@ async function handleViewSubmission(}async function dispatchViewInputResponse(input: {- readonly ctx: { from: ChannelFrom<SlackChannelState> };+ readonly ctx: {+ from: ChannelFrom<SlackChannelState>;+ };readonly deps: InteractionHandlerDeps;readonly installationTeamId: string | undefined;readonly metadata: HitlFreeformModalMetadata;@@ -673,26 +721,52 @@ async function dispatchViewInputResponse(input: {});if (result === null) return;- try {- await input.ctx- .from(input.metadata.continuationToken)- .respond(input.submission.inputResponses, {+ const cardChannelId = input.metadata.messageChannelId ?? input.metadata.channelId;+ const response = await respondOrRetireInactivePrompt(+ () =>+ input.ctx.from(input.metadata.continuationToken).respond(input.submission.inputResponses, {auth: result.auth,state: withSlackResponder(undefined, input.submission.user.id),- });- } catch (error) {- log.error("freeform answer delivery failed", { error });- return;+ }),+ {+ retirePrompt: (label) =>+ settleFreeformCard({+ card: { label, text: label },+ channelId: cardChannelId,+ deps: input.deps,+ installationTeamId: input.installationTeamId,+ messageTs: input.metadata.messageTs,+ }),+ },+ log,+ );+ if (response.outcome === "inactive") {+ await Promise.all([+ response.retirement,+ postEphemeralNotice({+ channelId: cardChannelId,+ deps: input.deps,+ installationTeamId: input.installationTeamId,+ teamId: input.teamId ?? undefined,+ // A card routed to another conversation only records the thread it answers.+ threadTs: cardChannelId === input.metadata.channelId ? input.metadata.threadTs : "",+ userId: input.submission.user.id,+ }),+ ]);}+ if (response.outcome !== "delivered") return;try {- await updateAnsweredFreeformCard({- channelId: input.metadata.messageChannelId ?? input.metadata.channelId,- messageTs: input.metadata.messageTs,- answerLabel: input.text,- userId: input.submission.user.id,- installationTeamId: input.installationTeamId,+ await settleFreeformCard({+ card: {+ label: input.text,+ text: `Answered: ${input.text}`,+ userId: input.submission.user.id,+ },+ channelId: cardChannelId,deps: input.deps,+ installationTeamId: input.installationTeamId,+ messageTs: input.metadata.messageTs,});} catch (error) {log.error("freeform answered-card update failed", { error });diff --git a/packages/eve/src/public/channels/slack/slackChannel.test.ts b/packages/eve/src/public/channels/slack/slackChannel.test.tsindex 848abc533..e550ab21a 100644--- a/packages/eve/src/public/channels/slack/slackChannel.test.ts+++ b/packages/eve/src/public/channels/slack/slackChannel.test.ts@@ -10,6 +10,7 @@ import {type CompiledChannel,} from "#channel/compiled-channel.js";import type { ChannelFrom, ChannelSource } from "#channel/channel-operations.js";+import { SessionStrandedError } from "#channel/session-stranded-error.js";import type { SessionAuthContext } from "#channel/types.js";import { isHttpRouteDefinition } from "#channel/routes.js";import { ContextContainer, contextStorage } from "#context/container.js";@@ -5035,10 +5036,32 @@ describe("slackChannel() HITL interaction pipeline", () => {expect(send).toHaveBeenCalledTimes(1);expect(slackOperations(fetchMock)).toEqual([]);expect(logs.records).toContainEqual(- expect.objectContaining({ level: "error", message: "HITL interaction delivery failed" }),+ expect.objectContaining({ level: "error", message: "input response delivery failed" }),);});+ it("retires a HITL card and tells the presser when its session is stranded", async () => {+ const send = vi.fn().mockRejectedValue(new SessionStrandedError({}));+ const channel = slackChannel({ credentials: { botToken: "xoxb-test" } });++ await firePost(channel, buildHitlButtonRequest(), { send });++ expect(slackOperations(fetchMock)).toEqual(["chat.update", "chat.postEphemeral"]);+ const update = parseSlackRequestBody(slackCalls(fetchMock, "chat.update")[0]?.[1]);+ expect(update).toMatchObject({ text: "No longer active", ts: "1700000000.000010" });+ // Nobody's answer was taken, so the retired card credits nobody.+ const shown = JSON.stringify(update.blocks);+ expect(shown).toContain("No longer active");+ expect(shown).not.toContain("U_APPROVER");+ expect(+ parseSlackRequestBody(slackCalls(fetchMock, "chat.postEphemeral")[0]?.[1]),+ ).toMatchObject({+ markdown_text: "This request is no longer active. Send a new message to start again.",+ thread_ts: "1700000000.000001",+ user: "U_APPROVER",+ });+ });+it("waits for approval settlement before updating a tool-approval card", async () => {const channel = slackChannel({ credentials: { botToken: "xoxb-test" } });diff --git a/packages/eve/src/public/channels/teams/hitl.test.ts b/packages/eve/src/public/channels/teams/hitl.test.tsindex 5b3cf9bb7..6356eebdb 100644--- a/packages/eve/src/public/channels/teams/hitl.test.ts+++ b/packages/eve/src/public/channels/teams/hitl.test.ts@@ -47,6 +47,28 @@ describe("Teams HITL helpers", () => {});});+ it("carries the prompt each button submits as the card shows it", () => {+ const prompt = "x".repeat(20_000);+ const body = renderInputRequestMessage({+ ...request(),+ kind: "question",+ options: ["a", "b", "c", "d", "e", "f"].map((id) => ({ id, label: id })),+ prompt,+ requestId: "REQ",+ });+ const card = body.attachments?.[0]?.content as {+ actions?: Array<{ data?: Record<string, Record<string, unknown>> }>;+ body?: Array<{ text?: string }>;+ };+ const shown = card.body?.[0]?.text;++ expect(shown?.length).toBeLessThan(prompt.length);+ expect(card.actions).toHaveLength(6);+ for (const action of card.actions ?? []) {+ expect(action.data?.[TEAMS_HITL_DATA_KEY]?.[TEAMS_HITL_PROMPT_KEY]).toBe(shown);+ }+ });+it("decodes message and invoke submission values", () => {const message = parseTeamsActivity(activityWithValue({diff --git a/packages/eve/src/public/channels/teams/hitl.ts b/packages/eve/src/public/channels/teams/hitl.tsindex bbb3fd12c..c250bb6c4 100644--- a/packages/eve/src/public/channels/teams/hitl.ts+++ b/packages/eve/src/public/channels/teams/hitl.ts@@ -107,19 +107,43 @@ export function renderAnsweredInputRequestMessage(input: {readonly prompt: string;}): TeamsMessageBody {const text = input.label ? `Answered: ${input.label}` : "Answered";- const result: TeamsMessageBody = {+ const result = renderSettledInputRequestMessage(input.prompt, { color: "good", text });+ if (input.includeText !== false) return { ...result, text };+ return result;+}++/**+ * Renders the card that replaces a prompt no session can answer anymore: its+ * prompt, then `label`, as the session would have resolved it.+ */+export function renderInactiveInputRequestMessage(+ prompt: string | undefined,+ label: string,+): TeamsMessageBody {+ return renderSettledInputRequestMessage(prompt, { text: label });+}++/** A card without its choices: `status` under the prompt, when the prompt is known. */+function renderSettledInputRequestMessage(+ prompt: string | undefined,+ status: { readonly color?: string; readonly text: string },+): TeamsMessageBody {+ const promptBlocks =+ prompt === undefined+ ? []+ : [+ {+ text: truncate(prompt, TEAMS_ADAPTIVE_CARD_TEXT_MAX_LENGTH),+ type: "TextBlock",+ wrap: true,+ },+ ];+ return {attachments: [{content: parseJsonObject({$schema: "http://adaptivecards.io/schemas/adaptive-card.json",- body: [- {- text: truncate(input.prompt, TEAMS_ADAPTIVE_CARD_TEXT_MAX_LENGTH),- type: "TextBlock",- wrap: true,- },- { color: "good", text, type: "TextBlock", wrap: true },- ],+ body: [...promptBlocks, { ...status, type: "TextBlock", wrap: true }],type: "AdaptiveCard",version: "1.5",}),@@ -127,8 +151,6 @@ export function renderAnsweredInputRequestMessage(input: {},],};- if (input.includeText !== false) return { ...result, text };- return result;}/** Returns true when a Teams activity carries an eve HITL submit payload. */@@ -145,6 +167,11 @@ export function isTeamsToolApprovalResponseActivity(activity: TeamsActivity): bo/** Reads the original prompt from a tool-approval submit activity. */export function readTeamsToolApprovalPrompt(activity: TeamsActivity): string | undefined {+ return isTeamsToolApprovalResponseActivity(activity) ? readTeamsInputPrompt(activity) : undefined;+}++/** Reads the prompt a submit activity answers, which every eve card carries in its submit data. */+export function readTeamsInputPrompt(activity: TeamsActivity): string | undefined {const value = readActivityValue(activity);const payload = value && readHitlPayload(value);const prompt = payload?.[TEAMS_HITL_PROMPT_KEY];@@ -247,11 +274,13 @@ function renderActions(replyToActivityId: string | undefined,): readonly Record<string, unknown>[] {const payload = (optionId?: string): Record<string, unknown> => {- const value: Record<string, unknown> = { requestId: request.requestId };- if (request.kind === "tool-approval") {- value[TEAMS_HITL_REQUEST_KIND_KEY] = "tool-approval";- value[TEAMS_HITL_PROMPT_KEY] = request.prompt;- }+ // The prompt the card shows rides along so a card can be retired without+ // the session that posted it, such as when that session is gone.+ const value: Record<string, unknown> = {+ requestId: request.requestId,+ [TEAMS_HITL_PROMPT_KEY]: truncate(request.prompt, TEAMS_ADAPTIVE_CARD_TEXT_MAX_LENGTH),+ };+ if (request.kind === "tool-approval") value[TEAMS_HITL_REQUEST_KIND_KEY] = "tool-approval";if (replyToActivityId !== undefined) value.replyToActivityId = replyToActivityId;if (optionId !== undefined) value.optionId = optionId;return value;diff --git a/packages/eve/src/public/channels/teams/teamsChannel.test.ts b/packages/eve/src/public/channels/teams/teamsChannel.test.tsindex 9c8276bd7..96ff8d596 100644--- a/packages/eve/src/public/channels/teams/teamsChannel.test.ts+++ b/packages/eve/src/public/channels/teams/teamsChannel.test.ts@@ -5,7 +5,9 @@ import { buildAdapterContext } from "#channel/adapter-context.js";import { isCompiledChannel, type CompiledChannel } from "#channel/compiled-channel.js";import { ContextContainer, contextStorage } from "#context/container.js";import { SessionKey } from "#context/keys.js";+import { INACTIVE_REQUEST_NOTICE } from "#channel/inactive-prompt.js";import { isHttpRouteDefinition } from "#channel/routes.js";+import { SessionNotActiveError } from "#channel/session-not-active-error.js";import {mockChannelContext,type ObservedChannelDelivery,@@ -310,6 +312,134 @@ describe("teamsChannel", () => {);});+ it("answers an inactive press without waiting for its card to clear", async () => {+ let releaseUpdate!: () => void;+ const updateHeld = new Promise<void>((resolve) => {+ releaseUpdate = resolve;+ });+ const updates: string[] = [];+ const fetchMock = vi.fn(async (url: string | URL | Request, init?: RequestInit) => {+ if (init?.method === "PUT") {+ updates.push(String(url));+ await updateHeld;+ }+ return new Response(JSON.stringify({ id: "updated-card" }));+ });+ const channel = asCompiled<TeamsChannelState>(+ teamsChannel({+ api: { fetch: fetchMock },+ credentials: { tokenProvider: () => "test-token", webhookVerifier: () => true },+ }),+ );+ const post = channel.routes.find((route) => route.method === "POST");+ if (!post || !isHttpRouteDefinition(post)) throw new Error("Expected a POST route.");+ const send = vi.fn().mockRejectedValue(new SessionNotActiveError());+ const waitUntil = vi.fn();++ const response = await post.handler(+ new Request("https://eve.test/eve/v1/teams", {+ body: JSON.stringify({+ ...baseActivity({ conversationType: "channel" }),+ replyToId: "approval-card",+ name: "adaptiveCard/action",+ type: "invoke",+ value: {+ action: {+ data: {+ eve_input: {+ kind: "tool-approval",+ prompt: "Approve deployment?",+ optionId: "approve",+ replyToActivityId: "THREAD_ROOT",+ requestId: "REQ",+ },+ },+ },+ },+ }),+ headers: { "content-type": "application/json" },+ method: "POST",+ }),+ {+ ...mockAgentRouteArgs(),+ from: mockChannelContext<TeamsChannelState>(send).from,+ resolveSession: vi.fn().mockResolvedValue(undefined) as never,+ attachSession: vi.fn() as any,+ params: {},+ to: vi.fn(),+ requestIp: null,+ waitUntil,+ },+ );++ expect(await response.json()).toMatchObject({ value: INACTIVE_REQUEST_NOTICE });+ expect(updates).toEqual([+ "https://smba.example.test/teams/v3/conversations/CONV/activities/approval-card",+ ]);+ expect(waitUntil).toHaveBeenCalledTimes(1);+ releaseUpdate();+ await Promise.all(waitUntil.mock.calls.map(([task]) => task as Promise<unknown>));+ });++ it("retires a question card that predates prompts in its data when pressed inactive", async () => {+ const updates: { url: string; body: unknown }[] = [];+ const fetchMock = vi.fn(async (input: string | URL | Request, init?: RequestInit) => {+ const request = new Request(input, init);+ if (request.method === "PUT") updates.push({ body: await request.json(), url: request.url });+ return new Response(JSON.stringify({ id: "updated-card" }));+ });+ const channel = asCompiled<TeamsChannelState>(+ teamsChannel({+ api: { fetch: fetchMock },+ credentials: { tokenProvider: () => "test-token", webhookVerifier: () => true },+ }),+ );+ const post = channel.routes.find((route) => route.method === "POST");+ if (!post || !isHttpRouteDefinition(post)) throw new Error("Expected a POST route.");+ const send = vi.fn().mockRejectedValue(new SessionNotActiveError());+ const waitUntil = vi.fn();++ // A question card rendered before this change carries only the request and option.+ await post.handler(+ new Request("https://eve.test/eve/v1/teams", {+ body: JSON.stringify({+ ...baseActivity({ conversationType: "channel" }),+ replyToId: "question-card",+ type: "message",+ value: {+ eve_input: {+ optionId: "saturday",+ replyToActivityId: "THREAD_ROOT",+ requestId: "REQ",+ },+ },+ }),+ headers: { "content-type": "application/json" },+ method: "POST",+ }),+ {+ ...mockAgentRouteArgs(),+ from: mockChannelContext<TeamsChannelState>(send).from,+ resolveSession: vi.fn().mockResolvedValue(undefined) as never,+ attachSession: vi.fn() as any,+ params: {},+ to: vi.fn(),+ requestIp: null,+ waitUntil,+ },+ );+ await Promise.all(waitUntil.mock.calls.map(([task]) => task as Promise<unknown>));++ expect(updates.map(({ url }) => url)).toEqual([+ "https://smba.example.test/teams/v3/conversations/CONV/activities/question-card",+ ]);+ const [update] = updates;+ const card = (update!.body as { attachments: { content: Record<string, unknown> }[] })+ .attachments[0]?.content;+ expect(card?.actions).toBeUndefined();+ expect(card?.body).toEqual([expect.objectContaining({ text: "No longer active" })]);+ });+it("updates a posted approval card after a durable cancel settlement", async () => {const fetchMock = vi.fn()diff --git a/packages/eve/src/public/channels/teams/teamsChannel.ts b/packages/eve/src/public/channels/teams/teamsChannel.tsindex 25197f40a..e9c489967 100644--- a/packages/eve/src/public/channels/teams/teamsChannel.ts+++ b/packages/eve/src/public/channels/teams/teamsChannel.ts@@ -1,6 +1,11 @@import { defaultDeliverResult } from "#channel/adapter.js";import type { TeamsInstrumentationMetadata } from "#public/channels/teams/index.js";import type { ChannelFrom, ChannelResolveSession } from "#channel/channel-operations.js";+import {+ INACTIVE_REQUEST_NOTICE,+ respondOrRetireInactivePrompt,+ type PromptResponse,+} from "#channel/inactive-prompt.js";import type { SessionHandle } from "#channel/session.js";import type { SessionAuthContext, TurnPolicy } from "#channel/types.js";import type { SessionContext } from "#public/definitions/callback-context.js";@@ -51,6 +56,8 @@ import {isTeamsToolApprovalResponseActivity,readTeamsInputReplyToActivityId,readTeamsToolApprovalPrompt,+ readTeamsInputPrompt,+ renderInactiveInputRequestMessage,teamsInvokeResponse,} from "#public/channels/teams/hitl.js";import {@@ -368,7 +375,10 @@ export function teamsChannel(config: TeamsChannelConfig = {}): TeamsChannel {if (activity.type === "message") {waitUntil(isTeamsInputResponseActivity(activity)- ? dispatchInputResponses({ activity, config, from, onInputResponse })+ ? // The retired card is the notice here: a message has no private reply.+ dispatchInputResponses({ activity, config, from, onInputResponse }).then(+ (answer) => (answer?.outcome === "inactive" ? answer.retirement : undefined),+ ): dispatchMessage({activity,config,@@ -690,15 +700,17 @@ async function handleInvoke(input: {if (reveal !== null) return Response.json(await revealAuthorization({ ...input, reveal }));if (isTeamsInputResponseActivity(input.activity)) {- input.waitUntil(- dispatchInputResponses({- activity: input.activity,- config: input.config,- onInputResponse: input.onInputResponse,- from: input.from,- }),- );- return Response.json(teamsInvokeResponse());+ // Answered after delivery, so the presser learns when no session took it.+ const answer = await dispatchInputResponses({+ activity: input.activity,+ config: input.config,+ onInputResponse: input.onInputResponse,+ from: input.from,+ });+ if (answer?.outcome !== "inactive") return Response.json(teamsInvokeResponse());+ // The reply doesn't wait for the card's edit, which the request still keeps.+ input.waitUntil(answer.retirement);+ return Response.json(teamsInvokeResponse({ message: INACTIVE_REQUEST_NOTICE }));}if (input.config.onInvoke === undefined) return teamsOk();@@ -739,14 +751,19 @@ async function revealAuthorization(input: {});}+/**+ * Delivers a card submission and reports what became of it. When no session+ * can take it, the card's retirement has started and the caller keeps the+ * request alive until it settles.+ */async function dispatchInputResponses(input: {readonly activity: TeamsInvokeActivity | TeamsMessageActivity;readonly from: ChannelFrom<TeamsChannelState>;readonly config: TeamsChannelConfig;readonly onInputResponse: NonNullable<TeamsChannelConfig["onInputResponse"]>;-}): Promise<void> {+}): Promise<PromptResponse | undefined> {const inputResponses = deriveTeamsInputResponses(input.activity as TeamsActivity);- if (inputResponses.length === 0) return;+ if (inputResponses.length === 0) return undefined;const state = stateFromActivity(input.activity);const ctx = buildTeamsBinding({ config: input.config, state });let result: TeamsInputResponseResult;@@ -754,25 +771,31 @@ async function dispatchInputResponses(input: {result = await input.onInputResponse(ctx, input.activity);} catch (error) {log.error("Teams input response authorization failed", { error });- return;- }- if (result === null) return;- try {- await input- .from(- cardContinuationToken(- input.activity,- state,- readTeamsInputReplyToActivityId(input.activity),- ),- )- .respond(inputResponses, {- auth: result.auth,- state: approvalResponseStatePatch(input.activity, result.auth),- });- } catch (error) {- log.error("Teams input response delivery failed", { error });+ return undefined;}+ if (result === null) return undefined;+ const auth = result.auth;+ const activity = input.activity;+ return respondOrRetireInactivePrompt(+ () =>+ input+ .from(cardContinuationToken(activity, state, readTeamsInputReplyToActivityId(activity)))+ .respond(inputResponses, {+ auth,+ state: approvalResponseStatePatch(activity, auth),+ }),+ {+ async retirePrompt(label) {+ if (activity.replyToId === undefined) return;+ // A card posted before prompts rode in its data still loses its buttons.+ await ctx.thread.update(+ activity.replyToId,+ renderInactiveInputRequestMessage(readTeamsInputPrompt(activity), label),+ );+ },+ },+ log,+ );}function stateFromActivity(diff --git a/packages/eve/src/public/channels/telegram/hitl.ts b/packages/eve/src/public/channels/telegram/hitl.tsindex a0586919d..6f8412e93 100644--- a/packages/eve/src/public/channels/telegram/hitl.ts+++ b/packages/eve/src/public/channels/telegram/hitl.ts@@ -139,11 +139,15 @@ export function takeTelegramResolvedPrompt(if (prompt === undefined) return undefined;const { [resolution.requestId]: _, ...rest } = state.hitlPrompts ?? {};state.hitlPrompts = rest;- const label = truncate(- resolvedPromptLabel(resolution, prompt.options),- TELEGRAM_RESOLVED_LABEL_MAX_LENGTH,- );- return { messageId: prompt.messageId, text: `${prompt.text}\n\n${label}` };+ return {+ messageId: prompt.messageId,+ text: telegramResolvedPromptText(prompt.text, resolvedPromptLabel(resolution, prompt.options)),+ };+}++/** A resolved prompt's text: the prompt it asked, then `label`, how it ended. */+export function telegramResolvedPromptText(promptText: string, label: string): string {+ return `${promptText}\n\n${truncate(label, TELEGRAM_RESOLVED_LABEL_MAX_LENGTH)}`;}/**diff --git a/packages/eve/src/public/channels/telegram/inbound.ts b/packages/eve/src/public/channels/telegram/inbound.tsindex 3c4ed06e8..f3c5087c1 100644--- a/packages/eve/src/public/channels/telegram/inbound.ts+++ b/packages/eve/src/public/channels/telegram/inbound.ts@@ -49,6 +49,8 @@ export interface TelegramMessageReference {readonly from?: TelegramUser;readonly messageId: string;readonly messageThreadId?: number;+ /** The message's text, which Telegram includes on a callback query's message. */+ readonly text?: string;}/**@@ -188,6 +190,7 @@ function parseMessageReference(value: unknown): TelegramMessageReference | undefmessageId,messageThreadId:typeof value.message_thread_id === "number" ? value.message_thread_id : undefined,+ text: typeof value.text === "string" ? value.text : undefined,};}diff --git a/packages/eve/src/public/channels/telegram/telegramChannel.test.ts b/packages/eve/src/public/channels/telegram/telegramChannel.test.tsindex 1d1e3e177..49b8bced3 100644--- a/packages/eve/src/public/channels/telegram/telegramChannel.test.ts+++ b/packages/eve/src/public/channels/telegram/telegramChannel.test.ts@@ -1,4 +1,4 @@-import { afterEach, describe, expect, it, vi } from "vitest";+import { afterEach, describe, expect, it, vi, type Mock } from "vitest";import { buildAdapterContext } from "#channel/adapter-context.js";import { callAdapterEventHandler, type ChannelAdapter } from "#channel/adapter.js";@@ -15,6 +15,8 @@ import {} from "#public/channels/telegram/index.js";import { isTelegramBotMentioned } from "#public/channels/telegram/defaults.js";import { captureLogRecords } from "#internal/testing/log-records.js";+import { SessionNotActiveError } from "#channel/session-not-active-error.js";+import { INACTIVE_REQUEST_NOTICE } from "#channel/inactive-prompt.js";import { mockAgentRouteArgs } from "#internal/testing/mocks/mock-route-args.js";const SECRET = "telegram-secret";@@ -80,7 +82,10 @@ function fakeTelegramFetch(): typeof fetch {async function firePost(channel: unknown,body: unknown,- options: { readonly resolveSession?: () => Promise<any> } = {},+ options: {+ readonly resolveSession?: () => Promise<any>;+ readonly send?: Mock<(...args: any[]) => Promise<unknown>>;+ } = {},): Promise<{readonly response: Response;readonly send: ReturnType<typeof vi.fn>;@@ -91,7 +96,7 @@ async function firePost(if (!post || !isHttpRouteDefinition(post)) {throw new Error("Expected telegram channel to define a POST route.");}- const send = vi.fn().mockResolvedValue({ id: "s1" });+ const send = options.send ?? vi.fn().mockResolvedValue({ id: "s1" });const waitUntil = vi.fn();const response = await post.handler(signedRequest(JSON.stringify(body)), {@@ -321,6 +326,47 @@ describe("telegramChannel() inbound route", () => {);});+ it("tells the presser a prompt is inactive without waiting for its buttons to clear", async () => {+ let releaseEdit!: () => void;+ const editHeld = new Promise<void>((resolve) => {+ releaseEdit = resolve;+ });+ const methods: string[] = [];+ const fetchMock = vi.fn(async (url: string | URL | Request, _init?: RequestInit) => {+ const method = String(url).split("/").pop()!;+ methods.push(method);+ if (method === "editMessageText") await editHeld;+ return new Response(JSON.stringify({ ok: true, result: true }));+ });+ const channel = telegramChannel({+ api: { fetch: fetchMock },+ credentials: { botToken: "bot-token", webhookSecretToken: SECRET },+ });++ const posted = firePost(+ channel,+ {+ callback_query: {+ id: "cb-inactive",+ from: { id: "U1", is_bot: false },+ data: "eve:0",+ message: { message_id: 55, chat: { id: 42, type: "private" }, text: "Deploy?" },+ },+ },+ { send: vi.fn().mockRejectedValue(new SessionNotActiveError()) },+ );+ await vi.waitFor(() => expect(methods).toEqual(["editMessageText", "answerCallbackQuery"]));+ releaseEdit();+ await posted;++ const ack = fetchMock.mock.calls.find(([url]) => String(url).endsWith("/answerCallbackQuery"));+ expect(JSON.parse(String((ack![1] as RequestInit).body))).toEqual({+ callback_query_id: "cb-inactive",+ text: INACTIVE_REQUEST_NOTICE,+ });+ expect(methods).toEqual(["editMessageText", "answerCallbackQuery"]);+ });+it("sends a reply to a bot prompt as a message carrying the replied-to id", async () => {const channel = telegramChannel({api: { fetch: fakeTelegramFetch() },diff --git a/packages/eve/src/public/channels/telegram/telegramChannel.ts b/packages/eve/src/public/channels/telegram/telegramChannel.tsindex 956d6f6fc..7b3332bfb 100644--- a/packages/eve/src/public/channels/telegram/telegramChannel.ts+++ b/packages/eve/src/public/channels/telegram/telegramChannel.ts@@ -1,6 +1,10 @@import type { TelegramInstrumentationMetadata } from "#public/channels/telegram/index.js";import { defaultDeliverResult, type ChannelAdapterContext } from "#channel/adapter.js";import type { ChannelFrom, ChannelResolveSession } from "#channel/channel-operations.js";+import {+ INACTIVE_REQUEST_NOTICE,+ respondOrRetireInactivePrompt,+} from "#channel/inactive-prompt.js";import type { SessionHandle } from "#channel/session.js";import type { DeliverPayload, SessionAuthContext, TurnPolicy } from "#channel/types.js";import type { SessionContext } from "#public/definitions/callback-context.js";@@ -42,6 +46,7 @@ import {resolveTelegramInputResponses,telegramCallbackInputResponse,telegramReplyInputResponses,+ telegramResolvedPromptText,type TelegramHitlState,} from "#public/channels/telegram/hitl.js";import {@@ -50,6 +55,7 @@ import {type TelegramCallbackQuery,type TelegramChatType,type TelegramMessage,+ type TelegramMessageReference,} from "#public/channels/telegram/inbound.js";import {mergeUploadPolicy,@@ -622,26 +628,35 @@ async function dispatchCallbackQuery(input: {}if (input.query.data?.startsWith(TELEGRAM_HITL_CALLBACK_PREFIX) === true) {+ // Telegram takes one answer per callback, so it waits for delivery: a press+ // no session can take is answered with the inactive notice instead.+ // The prompt's edit starts before the answer and finishes after it.+ const message = input.query.message;+ const data = input.query.data;+ const answer =+ message && state.chatId+ ? await respondOrRetireInactivePrompt(+ // The presser acts as themselves, so a press that starts a turn lets+ // their next message steer it.+ () =>+ input+ .from(telegramContinuationTokenFromState(state))+ .respond([telegramCallbackInputResponse(data)], {+ auth: defaultTelegramAuth({ ...message, from: input.query.from }),+ }),+ { retirePrompt: (label) => retireInactivePrompt(telegram, message, label) },+ log,+ )+ : undefined;try {await telegram.telegram.answerCallbackQuery({callbackQueryId: input.query.id,- text: "Answer received.",+ text: answer?.outcome === "inactive" ? INACTIVE_REQUEST_NOTICE : "Answer received.",});} catch (error) {log.warn("Telegram callback-query acknowledgement failed", { error });}-- if (!input.query.message || !state.chatId) return;- try {- const source = input.from(telegramContinuationTokenFromState(state));- // The presser acts as themselves, so a press that starts a turn lets- // their next message steer it.- await source.respond([telegramCallbackInputResponse(input.query.data)], {- auth: defaultTelegramAuth({ ...input.query.message, from: input.query.from }),- });- } catch (error) {- log.error("callback query delivery failed", { error });- }+ if (answer?.outcome === "inactive") await answer.retirement;return;}@@ -664,6 +679,28 @@ async function dispatchCallbackQuery(input: {}}+/**+ * Edits a prompt no session holds the way `input.resolved` edits a resolved+ * one. The session's record of the prompt is gone, so its text comes from the+ * pressed message.+ */+async function retireInactivePrompt(+ telegram: TelegramContext,+ message: TelegramMessageReference,+ label: string,+): Promise<void> {+ const replyMarkup = { inline_keyboard: [] };+ if (message.text === undefined) {+ await telegram.telegram.editMessageReplyMarkup({ messageId: message.messageId, replyMarkup });+ return;+ }+ await telegram.telegram.editMessageText({+ messageId: message.messageId,+ replyMarkup,+ text: telegramResolvedPromptText(message.text, label),+ });+}+function attachTelegramDeliver(channel: TelegramChannel): void {if (!isCompiledChannel(channel)) return;const adapter = channel.adapter;