Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions packages/eve/src/channel/routes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ export interface RouteHandlerArgs<TState = undefined> {

export interface SendPayload {
readonly message?: string | UserContent;
readonly [key: string]: unknown;
readonly inputResponses?: readonly InputResponse[];
/**
* Context strings contributed by the channel. eve appends each entry
Expand Down
25 changes: 25 additions & 0 deletions packages/eve/src/channel/send.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,31 @@ describe("createSendFn", () => {
expect(runtime.run).not.toHaveBeenCalled();
});

it("preserves channel-specific fields through delivery", async () => {
const runtime: Runtime = {
cancelTurn: vi.fn(),
deliver: vi.fn().mockResolvedValue({ sessionId: "existing-session-id" }),
resolveSession: vi.fn(),
run: vi.fn(),
getEventStream: vi.fn(),
getStreamTailIndex: vi.fn(),
terminateSession: vi.fn(),
};
const send = createSendFn(runtime, ADAPTER, "test");

await send(
{
inputResponses: [{ optionId: "approve", requestId: "approval-1" }],
pendingApprovalCards: { "approval-1": { messageTs: "123.456" } },
},
{ auth: null, continuationToken: "token" },
);

expect(vi.mocked(runtime.deliver).mock.calls[0]?.[0].payload).toMatchObject({
pendingApprovalCards: { "approval-1": { messageTs: "123.456" } },
});
});

it("forwards context through deliver and run payloads", async () => {
const context = ["thread background"];
const deliverRuntime: Runtime = {
Expand Down
3 changes: 2 additions & 1 deletion packages/eve/src/channel/send.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ export function createSendFn<TState = undefined>(
inputResponses,
context,
outputSchema,
...channelPayload
} = normalizeSendInput(input);
const message = serializeUrlFilePartsInMessage(rawMessage);

Expand All @@ -39,7 +40,7 @@ export function createSendFn<TState = undefined>(
auth,
continuationToken,
requestId: metadata.requestId,
payload: { inputResponses, message, context, outputSchema },
payload: { ...channelPayload, inputResponses, message, context, outputSchema },
};
const { sessionId } = await runtime.deliver(deliverInput);

Expand Down
68 changes: 68 additions & 0 deletions packages/eve/src/public/channels/slack/defaults.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,74 @@ function authRequiredEvent(
};
}

describe("defaultEvents approval lifecycle", () => {
it("sends candidate progress privately", async () => {
const { channel, postEphemeral } = buildChannelStub();
const ctx = sessionContext({
attributes: { user_id: "U777" },
authenticator: "slack-webhook",
principalId: "slack:T1:U777",
principalType: "user",
});

await defaultEvents["approval.candidate"]!(
{
candidateId: "candidate-1",
outcome: "pending",
requestId: "approval-1",
sequence: 1,
stepIndex: 0,
turnId: "turn-1",
},
channel,
ctx,
);

expect(postEphemeral).toHaveBeenCalledWith(
"U777",
"Checking whether you can approve this action…",
);
});

it("updates the shared card only after settlement", async () => {
const { channel, request } = buildChannelStub({
pendingApprovalCards: {
"approval-1": {
actionId: "eve_input:approval-1:button:1",
messageBlocks: [
{
actions: [{ action_id: "eve_input:approval-1:button:1" }],
body: { text: "Approve?", type: "mrkdwn" },
type: "card",
},
],
messageTs: "123.456",
userId: "U777",
},
},
});

await defaultEvents["approval.settled"]!(
{
outcome: "approved",
requestId: "approval-1",
responderPrincipalId: "slack:T1:U777",
sequence: 1,
stepIndex: 0,
turnId: "turn-1",
},
channel,
sessionCtx,
);

expect(request).toHaveBeenCalledWith(
"chat.update",
expect.objectContaining({ channel: "C123", text: "Answered: Approve", ts: "123.456" }),
);
expect(channel.state.pendingApprovalCards).toEqual({});
});
});

describe("defaultEvents authorization.required", () => {
it("posts a public status and delivers the challenge ephemerally to the triggering user", async () => {
const { channel, post, postEphemeral } = buildChannelStub({ triggeringUserId: "U777" });
Expand Down
61 changes: 61 additions & 0 deletions packages/eve/src/public/channels/slack/defaults.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import {
type ConnectionAuthorizationOutcome,
} from "#public/channels/slack/connections.js";
import {
buildAnsweredBlocks,
formatInputRequestFallbackText,
renderInputRequestBlocks,
} from "#public/channels/slack/hitl.js";
Expand All @@ -32,6 +33,21 @@ const log = createLogger("slack.defaults");
const REASONING_TYPING_REFRESH_INTERVAL_MS = 5_000;
const REASONING_TYPING_MIN_PROGRESS_CHARS = 4;

function blockContainsAction(block: unknown, actionId: string): boolean {
if (typeof block !== "object" || block === null) return false;
const candidate = block as { actions?: unknown; elements?: unknown };
return [candidate.actions, candidate.elements].some(
(entries) =>
Array.isArray(entries) &&
entries.some(
(entry) =>
typeof entry === "object" &&
entry !== null &&
(entry as { action_id?: unknown }).action_id === actionId,
),
);
}

/**
* Workspace-scoped projection of the Slack actor that produced
* `message`, derived into a {@link SessionAuthContext}. Used by both
Expand Down Expand Up @@ -146,6 +162,51 @@ function buildInputRequestPosts(
* which user overrides cannot express.
*/
export const defaultEvents: SlackChannelInternalEvents = {
async "approval.candidate"(event, channel, ctx) {
const userId = slackUserIdFromAuthContext(ctx.session.auth.current);
if (userId === undefined) return;
if (event.outcome === "pending") {
await channel.thread.postEphemeral(userId, "Checking whether you can approve this action…");
return;
}
if (event.outcome === "rejected" || event.outcome === "failed") {
await channel.thread.postEphemeral(
userId,
event.safeReason ?? "We couldn’t verify your approval. Please try again.",
);
}
},

async "approval.settled"(event, channel, _ctx) {
const cards = channel.state.pendingApprovalCards ?? {};
const card = cards[event.requestId];
if (card === undefined || channel.state.channelId === null) return;
const answerLabel = event.outcome === "approved" ? "Approve" : "Cancel";
const blocks = card.messageBlocks.flatMap((block) => {
if (!blockContainsAction(block, card.actionId)) return [block];
if (typeof block !== "object" || block === null) return [];
const candidate = block as Record<string, unknown>;
if (candidate.type !== "card") {
return buildAnsweredBlocks({ answerLabel, promptBlocks: [], userId: card.userId });
}
const { actions: _actions, ...withoutActions } = candidate;
return buildAnsweredBlocks({
answerLabel,
promptBlocks: [withoutActions],
userId: card.userId,
});
});
await channel.slack.request("chat.update", {
blocks,
channel: channel.state.channelId,
text: `Answered: ${answerLabel}`,
ts: card.messageTs,
});
const next = { ...cards };
delete next[event.requestId];
channel.state.pendingApprovalCards = next;
},

async "turn.started"(_event, channel, _ctx) {
channel.state.pendingToolCallMessage = null;
channel.state.lastReasoningTypingAtMs = null;
Expand Down
Loading