Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

feat(agents): answer chat agent mentions with one message that starts as a spinner (#6894)

Wolf Mermelsteincb894850c59b
diff --git a/apps/docs/AI/mcp/tools/index.mdx b/apps/docs/AI/mcp/tools/index.mdx
index 91272cd607..6321947826 100644
--- a/apps/docs/AI/mcp/tools/index.mdx
+++ b/apps/docs/AI/mcp/tools/index.mdx
@@ -77,6 +77,7 @@ These pages are generated from Macro's Rust MCP tool registry.
- [SearchTools](/AI/mcp/tools/search-tools)
- [SelfKnowledge](/AI/mcp/tools/self-knowledge)
- [SendChannelMessage](/AI/mcp/tools/send-channel-message)
+- [SendConfirmedEmail](/AI/mcp/tools/send-confirmed-email)
- [SendEmail](/AI/mcp/tools/send-email)
- [SetEntityProperty](/AI/mcp/tools/set-entity-property)
- [SetSenderPolicy](/AI/mcp/tools/set-sender-policy)
diff --git a/apps/docs/AI/mcp/tools/send-confirmed-email.mdx b/apps/docs/AI/mcp/tools/send-confirmed-email.mdx
new file mode 100644
index 0000000000..338a4308a6
--- /dev/null
+++ b/apps/docs/AI/mcp/tools/send-confirmed-email.mdx
@@ -0,0 +1,21 @@
+---
+title: SendConfirmedEmail
+description: "Send an email immediately, with no review card or composer. Only for a prompt that came from a channel or document thread (the context block says so), where there is nothing to review a draft in. The email is always shown before it is sent, even when the user's request already spelled the whole thing out: in one turn write it into the thread - recipients, subject, body - ask whether to send it, and stop there. Call this tool only in a later turn, once the user has replied approving that specific email, quoting that reply verbatim in userConfirmation. Being asked to send an email is a request to draft one, never approval to send it, so a userConfirmation quoting the request that asked you to write the email - rather than the reply approving the one you wrote - is wrong. Never call it in the agent session view or in chat: use SendEmail there, whose review card or composer is the confirmation. Takes the same fields as SendEmail; write the body in Markdown, which is rendered to HTML on send."
+---
+
+# SendConfirmedEmail
+
+Send an email immediately, with no review card or composer. Only for a prompt that came from a channel or document thread (the context block says so), where there is nothing to review a draft in. The email is always shown before it is sent, even when the user's request already spelled the whole thing out: in one turn write it into the thread - recipients, subject, body - ask whether to send it, and stop there. Call this tool only in a later turn, once the user has replied approving that specific email, quoting that reply verbatim in userConfirmation. Being asked to send an email is a request to draft one, never approval to send it, so a userConfirmation quoting the request that asked you to write the email - rather than the reply approving the one you wrote - is wrong. Never call it in the agent session view or in chat: use SendEmail there, whose review card or composer is the confirmation. Takes the same fields as SendEmail; write the body in Markdown, which is rendered to HTML on send.
+
+## Parameters
+
+| Parameter | Type | Required | Description |
+| --- | --- | --- | --- |
+| `subject` | string | Yes | The subject line of the email. |
+| `body` | string | Yes | The body of the email, written as Markdown. A host with a composer (chat) replaces this with the base64url-encoded HTML the composer exported before the tool runs; a host without one (an agent session) leaves the Markdown, and this tool renders it the same way. |
+| `to` | EmailRecipient[] | Yes | The primary recipients (To field). |
+| `cc` | EmailRecipient[] | No | Carbon copy recipients (optional). |
+| `bcc` | EmailRecipient[] | No | Blind carbon copy recipients (optional). |
+| `replyingToId` | string | No | The ID of a message to reply to (optional). When set, the email is sent as a reply within the same thread. |
+| `includeSignature` | boolean | No | Per-message signature override, set by the composer's signature preview — not normally by you. Omit to use the inbox's default policy (always on a new email; on replies/forwards only when the user enabled it). `false` excludes the signature for this one email. |
+| `userConfirmation` | string | Yes | The user's own message approving this specific email, quoted verbatim - for example their "yes, send it" in reply to the email you wrote out for them. It is a reply to your draft, never the earlier request that asked you to write one: if the user has not yet seen this email, there is nothing to quote here and the tool must not be called. Required: do not paraphrase it, and never supply it yourself. |
diff --git a/apps/docs/AI/mcp/tools/send-email.mdx b/apps/docs/AI/mcp/tools/send-email.mdx
index 65dab48c6a..6a3d4a2236 100644
--- a/apps/docs/AI/mcp/tools/send-email.mdx
+++ b/apps/docs/AI/mcp/tools/send-email.mdx
@@ -1,11 +1,11 @@
---
title: SendEmail
-description: "Draft, compose, and send an email. ALWAYS use this tool whenever the user asks you to draft, write, compose, or send an email (or reply to one) — never write the email as plain text in the chat. This tool opens the email draft in the composer for the user to review, edit, and confirm before it is sent, so it is the correct tool even when the user only wants a draft. To reply to an existing message, provide the replying_to_id. Write the body in Markdown — use **bold**, *italics*, lists, links, and other standard Markdown formatting. The draft composer renders the Markdown for the user to review and edit; the composer produces HTML that is sent as the actual email body."
+description: "Draft, compose, and send an email the user confirms in a review card or composer. Use this tool whenever the user asks you to draft, write, compose, or send an email (or reply to one) from the agent session view or from chat — never write the email as plain text there. It opens the draft for the user to review, edit, and confirm before it is sent, so it is the correct tool even when the user only wants a draft. Do NOT use it for a prompt that came from a channel or document thread — the context block names a conversation parent when it did, and there is no surface to review a draft in: write the email out in your reply, ask whether to send it, and use SendConfirmedEmail once the user approves. To reply to an existing message, provide the replying_to_id. Write the body in Markdown — use **bold**, *italics*, lists, links, and other standard Markdown formatting. The draft composer renders the Markdown for the user to review and edit; the composer produces HTML that is sent as the actual email body."
---
# SendEmail
-Draft, compose, and send an email. ALWAYS use this tool whenever the user asks you to draft, write, compose, or send an email (or reply to one) — never write the email as plain text in the chat. This tool opens the email draft in the composer for the user to review, edit, and confirm before it is sent, so it is the correct tool even when the user only wants a draft. To reply to an existing message, provide the replying_to_id. Write the body in Markdown — use **bold**, *italics*, lists, links, and other standard Markdown formatting. The draft composer renders the Markdown for the user to review and edit; the composer produces HTML that is sent as the actual email body.
+Draft, compose, and send an email the user confirms in a review card or composer. Use this tool whenever the user asks you to draft, write, compose, or send an email (or reply to one) from the agent session view or from chat — never write the email as plain text there. It opens the draft for the user to review, edit, and confirm before it is sent, so it is the correct tool even when the user only wants a draft. Do NOT use it for a prompt that came from a channel or document thread — the context block names a conversation parent when it did, and there is no surface to review a draft in: write the email out in your reply, ask whether to send it, and use SendConfirmedEmail once the user approves. To reply to an existing message, provide the replying_to_id. Write the body in Markdown — use **bold**, *italics*, lists, links, and other standard Markdown formatting. The draft composer renders the Markdown for the user to review and edit; the composer produces HTML that is sent as the actual email body.
## Parameters
diff --git a/apps/docs/config/tool-pages.json b/apps/docs/config/tool-pages.json
index 80eced8922..c43e8031c9 100644
--- a/apps/docs/config/tool-pages.json
+++ b/apps/docs/config/tool-pages.json
@@ -68,6 +68,7 @@
"AI/mcp/tools/search-tools",
"AI/mcp/tools/self-knowledge",
"AI/mcp/tools/send-channel-message",
+ "AI/mcp/tools/send-confirmed-email",
"AI/mcp/tools/send-email",
"AI/mcp/tools/set-entity-property",
"AI/mcp/tools/set-sender-policy",
diff --git a/apps/docs/docs.json b/apps/docs/docs.json
index dfdb62a164..7972ffce69 100644
--- a/apps/docs/docs.json
+++ b/apps/docs/docs.json
@@ -139,6 +139,7 @@
"AI/mcp/tools/search-tools",
"AI/mcp/tools/self-knowledge",
"AI/mcp/tools/send-channel-message",
+ "AI/mcp/tools/send-confirmed-email",
"AI/mcp/tools/send-email",
"AI/mcp/tools/set-entity-property",
"AI/mcp/tools/set-sender-policy",
diff --git a/apps/web/src/features/channel/Message/AgentSessionLink.tsx b/apps/web/src/features/channel/Message/AgentSessionLink.tsx
new file mode 100644
index 0000000000..90bede6934
--- /dev/null
+++ b/apps/web/src/features/channel/Message/AgentSessionLink.tsx
@@ -0,0 +1,49 @@
+import { useSplitLayout } from '@components/app/split-layout/layout';
+import ArrowUpRightIcon from '@phosphor/arrow-up-right.svg';
+import { cn } from '@ui';
+import { Show } from 'solid-js';
+import { splitMessageContent } from './agent-session-link';
+import { useMessage } from './context';
+
+type AgentSessionLinkProps = {
+ class?: string;
+};
+
+/**
+ * A quiet "Open Session" chip on the sender line of a message an agent
+ * posted from a session, opening that session in its own split. Rendered
+ * only when the message leads with the harness's session node; see
+ * `agent-session-link`.
+ */
+export function AgentSessionLink(props: AgentSessionLinkProps) {
+ const message = useMessage();
+ const layout = useSplitLayout();
+ const link = () => splitMessageContent(message()).link;
+
+ return (
+ <Show when={link()}>
+ {(link) => (
+ <button
+ type="button"
+ class={cn(
+ 'inline-flex shrink-0 items-center gap-1 rounded-full',
+ 'bg-surface px-2 py-0.5 text-xs leading-none text-ink-muted',
+ 'transition-colors hover:bg-hover hover:text-ink',
+ props.class
+ )}
+ title="Open the agent session this message came from"
+ onClick={(event) => {
+ event.stopPropagation();
+ layout?.openWithSplit(
+ { type: 'agent', id: link().sessionId },
+ { activate: true, preferNewSplit: true }
+ );
+ }}
+ >
+ Open Session
+ <ArrowUpRightIcon class="size-3" aria-hidden="true" />
+ </button>
+ )}
+ </Show>
+ );
+}
diff --git a/apps/web/src/features/channel/Message/ChannelMessage.tsx b/apps/web/src/features/channel/Message/ChannelMessage.tsx
index c43ac00393..469d567646 100644
--- a/apps/web/src/features/channel/Message/ChannelMessage.tsx
+++ b/apps/web/src/features/channel/Message/ChannelMessage.tsx
@@ -125,6 +125,7 @@ function RegularMessageLayout(props: {
<Message.AgentBadge />
<Message.Timestamp class="shrink-0" format="time" />
<Message.EditedIndicator class="shrink-0" />
+ <Message.AgentSessionLink class="ml-auto" />
</div>
<Message.FromPill />
</Message.Slot>
@@ -164,6 +165,9 @@ function GroupedMessageLayout(props: {
messageEditor={props.messageEditor}
class="min-w-0 flex-1"
/>
+ {/* No sender line to sit on: the link takes the top right of the
+ content row instead. */}
+ <Message.AgentSessionLink class="pt-1" />
</div>
</Message.Slot>
<Message.Slot
diff --git a/apps/web/src/features/channel/Message/Content.tsx b/apps/web/src/features/channel/Message/Content.tsx
index ed2d24881f..b6ed834095 100644
--- a/apps/web/src/features/channel/Message/Content.tsx
+++ b/apps/web/src/features/channel/Message/Content.tsx
@@ -4,6 +4,7 @@ import { channelTheme } from '@core/component/LexicalMarkdown/theme';
import { isEmojiOnly } from '@core/util/string';
import { cn } from '@ui';
import { createMemo, createSignal, Show } from 'solid-js';
+import { splitMessageContent } from './agent-session-link';
import { useMessage, useSearchHighlightTermsLookup } from './context';
import { createSearchHighlightOverlay } from './highlightOverlay';
@@ -13,10 +14,12 @@ type ContentProps = {
export function Content(props: ContentProps) {
const message = useMessage();
- const bigEmoji = createMemo(() => isEmojiOnly(message().content));
const termsLookup = useSearchHighlightTermsLookup();
- const content = createMemo(() => message().content);
+ // The body only: an agent message's leading session node is chrome the
+ // sender line renders (`Message.AgentSessionLink`), not part of the text.
+ const content = createMemo(() => splitMessageContent(message()).body);
+ const bigEmoji = createMemo(() => isEmojiOnly(content()));
const terms = createMemo(() => termsLookup?.(message().id));
const [markdownRoot, setMarkdownRoot] = createSignal<HTMLDivElement>();
@@ -24,7 +27,7 @@ export function Content(props: ContentProps) {
createSearchHighlightOverlay({ root: markdownRoot, content, terms });
return (
- <Show when={message().content}>
+ <Show when={content()}>
<div
data-message-content
class={cn(
diff --git a/apps/web/src/features/channel/Message/Message.ts b/apps/web/src/features/channel/Message/Message.ts
index 46481329cb..c693c043cc 100644
--- a/apps/web/src/features/channel/Message/Message.ts
+++ b/apps/web/src/features/channel/Message/Message.ts
@@ -1,5 +1,6 @@
import { ActionMenu } from './ActionMenu';
import { AgentBadge } from './AgentBadge';
+import { AgentSessionLink } from './AgentSessionLink';
import { Attachments } from './Attachments';
import { Content } from './Content';
import { DateDivider } from './DateDivider';
@@ -23,6 +24,7 @@ export const Message = {
Slot,
SenderName: MessageSenderName,
AgentBadge,
+ AgentSessionLink,
FromPill,
SenderIcon,
Timestamp,
diff --git a/apps/web/src/features/channel/Message/agent-session-link.ts b/apps/web/src/features/channel/Message/agent-session-link.ts
new file mode 100644
index 0000000000..9ace4b5cdf
--- /dev/null
+++ b/apps/web/src/features/channel/Message/agent-session-link.ts
@@ -0,0 +1,75 @@
+import type { MessageData } from '@core/messages/types';
+import { isBotSenderId } from '@queries/messages/message-sender';
+
+/**
+ * The session a channel message from an agent came from.
+ *
+ * The agent harness leads every message a chat agent posts into a thread -
+ * the pending spinner and each patch that replaces it - with an
+ * `<m-agent-session-mention>` node naming the session, as its own first
+ * paragraph. It is chrome, not body: the message view lifts it onto the
+ * sender line as a small link and renders what follows as the message.
+ */
+export type AgentSessionLink = {
+ sessionId: string;
+};
+
+/** A message split into the chrome the harness prefixed and its body. */
+export type SplitMessageContent = {
+ link: AgentSessionLink | undefined;
+ body: string;
+};
+
+/**
+ * The exact serialization `I_AGENT_SESSION_MENTION` reads - one JSON object
+ * inside the tag, with no line breaks - anchored to the start, plus the
+ * blank line the harness puts after it.
+ */
+const LEADING_AGENT_SESSION_MENTION =
+ /^<m-agent-session-mention>(.*?)<\/m-agent-session-mention>[ \t]*(?:\r?\n)*/;
+
+function isAgentSessionMentionInfo(value: unknown): value is { id: string } {
+ return (
+ typeof value === 'object' &&
+ value !== null &&
+ 'id' in value &&
+ typeof value.id === 'string' &&
+ value.id.length > 0
+ );
+}
+
+/**
+ * Split a leading agent-session mention off `content`. Content that does
+ * not start with one, or whose node does not parse, is all body.
+ */
+export function splitLeadingAgentSessionLink(
+ content: string
+): SplitMessageContent {
+ const match = LEADING_AGENT_SESSION_MENTION.exec(content);
+ if (!match) return { link: undefined, body: content };
+ let parsed: unknown;
+ try {
+ parsed = JSON.parse(match[1] ?? '');
+ } catch {
+ return { link: undefined, body: content };
+ }
+ if (!isAgentSessionMentionInfo(parsed)) {
+ return { link: undefined, body: content };
+ }
+ return {
+ link: { sessionId: parsed.id },
+ body: content.slice(match[0].length),
+ };
+}
+
+/**
+ * The message as the view renders it. Only an agent's message is split: a
+ * person who opens their own message with a session mention meant it as
+ * part of what they said.
+ */
+export function splitMessageContent(message: MessageData): SplitMessageContent {
+ if (!isBotSenderId(message.sender_id)) {
+ return { link: undefined, body: message.content };
+ }
+ return splitLeadingAgentSessionLink(message.content);
+}
diff --git a/apps/web/src/features/channel/Message/tests/agent-session-link.test.ts b/apps/web/src/features/channel/Message/tests/agent-session-link.test.ts
new file mode 100644
index 0000000000..d1a94ac586
--- /dev/null
+++ b/apps/web/src/features/channel/Message/tests/agent-session-link.test.ts
@@ -0,0 +1,51 @@
+import { describe, expect, it } from 'vitest';
+import { splitLeadingAgentSessionLink } from '../agent-session-link';
+
+const SESSION = '00000000-0000-0000-0000-00000000000a';
+// What the agent harness emits: see `session_link` in
+// crates/agent_harness/src/outbound/channel_announcer.rs.
+const link = `<m-agent-session-mention>{"id":"${SESSION}","label":"Agent session"}</m-agent-session-mention>`;
+
+describe('splitLeadingAgentSessionLink', () => {
+ it('lifts the harness session node off the front and keeps the body', () => {
+ expect(splitLeadingAgentSessionLink(`${link}\n\nHere you go.`)).toEqual({
+ link: { sessionId: SESSION },
+ body: 'Here you go.',
+ });
+ });
+
+ it('lifts it off the pending spinner too', () => {
+ const spinner = '<m-await>{"text":"Thinking…","inline":true}</m-await>';
+ expect(splitLeadingAgentSessionLink(`${link}\n\n${spinner}`)).toEqual({
+ link: { sessionId: SESSION },
+ body: spinner,
+ });
+ });
+
+ it('leaves a session mention that is not leading in the body', () => {
+ const content = `See ${link} for details.`;
+ expect(splitLeadingAgentSessionLink(content)).toEqual({
+ link: undefined,
+ body: content,
+ });
+ });
+
+ it('treats a malformed node as body', () => {
+ for (const content of [
+ '<m-agent-session-mention>not json</m-agent-session-mention>\n\nbody',
+ '<m-agent-session-mention>{"label":"x"}</m-agent-session-mention>\n\nbody',
+ ]) {
+ expect(splitLeadingAgentSessionLink(content)).toEqual({
+ link: undefined,
+ body: content,
+ });
+ }
+ });
+
+ it('returns plain content untouched', () => {
+ expect(splitLeadingAgentSessionLink('hello')).toEqual({
+ link: undefined,
+ body: 'hello',
+ });
+ });
+});
diff --git a/apps/web/src/lib/core/component/AI/component/tool/SendConfirmedEmail.tsx b/apps/web/src/lib/core/component/AI/component/tool/SendConfirmedEmail.tsx
new file mode 100644
index 0000000000..39955c4d82
--- /dev/null
+++ b/apps/web/src/lib/core/component/AI/component/tool/SendConfirmedEmail.tsx
@@ -0,0 +1,75 @@
+import type { NamedTool } from '@service-cognition/generated/tools/tool';
+import { Match, Show, Switch } from 'solid-js';
+import { BaseTool } from './BaseTool';
+import { DraftEmailResponse, SentEmailResponse } from './SendEmail';
+import { createToolRenderer } from './ToolRenderer';
+
+type SendConfirmedEmailResponse = NamedTool<
+ 'SendConfirmedEmail',
+ 'response'
+>['data'];
+
+/**
+ * `SendConfirmedEmail` sends on a confirmation the user already gave in a
+ * conversation thread, so there is no pending composer and no review to
+ * render: the response is the send itself, shown the way `SendEmail` shows
+ * its finished send.
+ */
+function getSentResponse(response: SendConfirmedEmailResponse | undefined) {
+ if (typeof response === 'object' && response !== null && 'sent' in response) {
+ return response.sent;
+ }
+ return null;
+}
+
+function getDraftResponse(response: SendConfirmedEmailResponse | undefined) {
+ if (
+ typeof response === 'object' &&
+ response !== null &&
+ 'convertedToDraft' in response
+ ) {
+ return response.convertedToDraft;
+ }
+ return null;
+}
+
+const handler = createToolRenderer({
+ name: 'SendConfirmedEmail',
+ render: (ctx) => {
+ const response = () => ctx.response?.data;
+ const args = ctx.tool.data;
+ const sentResponse = getSentResponse(response());
+ const draftResponse = getDraftResponse(response());
+
+ return (
+ <Show when={ctx.response}>
+ <Switch>
+ <Match when={sentResponse}>
+ <SentEmailResponse
+ args={args}
+ chatId={ctx.chat_id}
+ messageId={ctx.message_id}
+ renderContext={ctx.renderContext}
+ threadId={sentResponse!.thread_id}
+ toolCallId={ctx.tool.id}
+ />
+ </Match>
+ <Match when={draftResponse}>
+ <DraftEmailResponse
+ args={args}
+ draftId={draftResponse!.draft_id}
+ renderContext={ctx.renderContext}
+ />
+ </Match>
+ <Match when={response() === 'userEdited'}>
+ <BaseTool renderContext={ctx.renderContext} type="response">
+ Email edited by the user
+ </BaseTool>
+ </Match>
+ </Switch>
+ </Show>
+ );
+ },
+});
+
+export const sendConfirmedEmailHandler = handler;
diff --git a/apps/web/src/lib/core/component/AI/component/tool/SendEmail.tsx b/apps/web/src/lib/core/component/AI/component/tool/SendEmail.tsx
index 5ee76f1294..5b10d1e343 100644
--- a/apps/web/src/lib/core/component/AI/component/tool/SendEmail.tsx
+++ b/apps/web/src/lib/core/component/AI/component/tool/SendEmail.tsx
@@ -120,7 +120,7 @@ function DraftPreviewButton(props: {
);
}
-function SentEmailResponse(props: {
+export function SentEmailResponse(props: {
args: SendEmail;
chatId: string;
messageId: string;
@@ -162,7 +162,7 @@ function SentEmailResponse(props: {
);
}
-function DraftEmailResponse(props: {
+export function DraftEmailResponse(props: {
args: SendEmail;
draftId: string;
renderContext: Parameters<typeof BaseTool>[0]['renderContext'];
diff --git a/apps/web/src/lib/core/component/AI/component/tool/handler.tsx b/apps/web/src/lib/core/component/AI/component/tool/handler.tsx
index c36ea7526d..c35ad04aba 100644
--- a/apps/web/src/lib/core/component/AI/component/tool/handler.tsx
+++ b/apps/web/src/lib/core/component/AI/component/tool/handler.tsx
@@ -88,6 +88,7 @@ import { listSkillsHandler, searchSkillsHandler } from './SearchSkills';
import { searchToolsHandler } from './SearchTools';
import { selfKnowledgeHandler } from './SelfKnowledge';
import { sendChannelMessageHandler } from './SendChannelMessage';
+import { sendConfirmedEmailHandler } from './SendConfirmedEmail';
import { sendEmailHandler } from './SendEmail';
import { setSenderPolicyHandler } from './SetSenderPolicy';
import {
@@ -179,6 +180,7 @@ const toolHandlers: ToolHandlerMap<RenderContext> = {
SearchTools: searchToolsHandler,
SelfKnowledge: selfKnowledgeHandler,
SendChannelMessage: sendChannelMessageHandler,
+ SendConfirmedEmail: sendConfirmedEmailHandler,
SendEmail: sendEmailHandler,
SetSenderPolicy: setSenderPolicyHandler,
SetEntityProperty: setEntityPropertyHandler,
diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/tools/schemas.ts b/apps/web/src/lib/service-clients/service-cognition/generated/tools/schemas.ts
index d28c6f05c4..0d4cfe912b 100644
--- a/apps/web/src/lib/service-clients/service-cognition/generated/tools/schemas.ts
+++ b/apps/web/src/lib/service-clients/service-cognition/generated/tools/schemas.ts
@@ -5187,6 +5187,68 @@ export const SendChannelMessageResponse = z.object({
message_id: z.string(),
});
+export const SendConfirmedEmail = z.object({
+ subject: z.string(),
+ body: z.string(),
+ to: z.array(
+ z.object({
+ email: z.string(),
+ name: z.union([z.string(), z.null()]).optional(),
+ })
+ ),
+ cc: z
+ .array(
+ z.object({
+ email: z.string(),
+ name: z.union([z.string(), z.null()]).optional(),
+ })
+ )
+ .optional(),
+ bcc: z
+ .array(
+ z.object({
+ email: z.string(),
+ name: z.union([z.string(), z.null()]).optional(),
+ })
+ )
+ .optional(),
+ replyingToId: z.union([z.string().uuid(), z.null()]).optional(),
+ includeSignature: z.union([z.boolean(), z.null()]).optional(),
+ userConfirmation: z.string(),
+});
+
+export const SendEmailResponse = z.any().superRefine((x, ctx) => {
+ const schemas = [
+ z.literal('userEdited'),
+ z
+ .object({
+ sent: z.object({
+ message_id: z.string().uuid(),
+ thread_id: z.string().uuid(),
+ }),
+ })
+ .strict(),
+ z
+ .object({ convertedToDraft: z.object({ draft_id: z.string().uuid() }) })
+ .strict(),
+ ];
+ const errors = schemas.reduce<z.ZodError[]>(
+ (errors, schema) =>
+ ((result) => (result.error ? [...errors, result.error] : errors))(
+ schema.safeParse(x)
+ ),
+ []
+ );
+ if (schemas.length - errors.length !== 1) {
+ ctx.addIssue({
+ path: ctx.path,
+ code: 'invalid_union',
+ unionErrors: errors,
+ message: 'Invalid input: Should pass single schema',
+ });
+ }
+});
+
export const SendEmail = z.object({
subject: z.string(),
body: z.string(),
diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/tools/tool.ts b/apps/web/src/lib/service-clients/service-cognition/generated/tools/tool.ts
index bb724c3cb8..caa406e66a 100644
--- a/apps/web/src/lib/service-clients/service-cognition/generated/tools/tool.ts
+++ b/apps/web/src/lib/service-clients/service-cognition/generated/tools/tool.ts
@@ -220,6 +220,10 @@ type ToolParserMap = {
call: types.SendChannelMessage;
response: types.SendChannelMessageResponse;
};
+ SendConfirmedEmail: {
+ call: types.SendConfirmedEmail;
+ response: types.SendEmailResponse;
+ };
SendEmail: {
call: types.SendEmail;
response: types.UserToolResponseForSendEmailResponse;
@@ -491,6 +495,10 @@ const toolParserMap = {
call: schemas.SendChannelMessage,
response: schemas.SendChannelMessageResponse,
},
+ SendConfirmedEmail: {
+ call: schemas.SendConfirmedEmail,
+ response: schemas.SendEmailResponse,
+ },
SendEmail: {
call: schemas.SendEmail,
response: schemas.UserToolResponseForSendEmailResponse,
@@ -749,6 +757,10 @@ type ToolDataMap = {
call: types.SendChannelMessage;
response: types.SendChannelMessageResponse;
};
+ SendConfirmedEmail: {
+ call: types.SendConfirmedEmail;
+ response: types.SendEmailResponse;
+ };
SendEmail: {
call: types.SendEmail;
response: types.UserToolResponseForSendEmailResponse;
diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.ts b/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.ts
index e403df0365..f1ba3a6efd 100644
--- a/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.ts
+++ b/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.ts
@@ -1029,15 +1029,6 @@ export type ProjectItemType = 'document' | 'chat' | 'project';
* How search terms are matched against skill names.
*/
export type SearchSkillsMatchType = 'partial' | 'exact';
-/**
- * User tools are pending until a user executes them
- */
-export type UserToolResponseForSendEmailResponse =
- | 'PendingUserExecution'
- | 'Rejected'
- | {
- UserAction: SendEmailResponse;
- };
/**
* Response from the SendEmail tool.
*/
@@ -1060,6 +1051,15 @@ export type SendEmailResponse =
draft_id: string;
};
};
+/**
+ * User tools are pending until a user executes them
+ */
+export type UserToolResponseForSendEmailResponse =
+ | 'PendingUserExecution'
+ | 'Rejected'
+ | {
+ UserAction: SendEmailResponse;
+ };
export type ToolEntityType =
| 'document'
| 'task'
@@ -5775,9 +5775,9 @@ export interface SendChannelMessageResponse {
message_id: string;
}
/**
- * Draft, compose, and send an email. ALWAYS use this tool whenever the user asks you to draft, write, compose, or send an email (or reply to one) — never write the email as plain text in the chat. This tool opens the email draft in the composer for the user to review, edit, and confirm before it is sent, so it is the correct tool even when the user only wants a draft. To reply to an existing message, provide the replying_to_id. Write the body in Markdown — use **bold**, *italics*, lists, links, and other standard Markdown formatting. The draft composer renders the Markdown for the user to review and edit; the composer produces HTML that is sent as the actual email body.
+ * Send an email immediately, with no review card or composer. Only for a prompt that came from a channel or document thread (the context block says so), where there is nothing to review a draft in. The email is always shown before it is sent, even when the user's request already spelled the whole thing out: in one turn write it into the thread - recipients, subject, body - ask whether to send it, and stop there. Call this tool only in a later turn, once the user has replied approving that specific email, quoting that reply verbatim in userConfirmation. Being asked to send an email is a request to draft one, never approval to send it, so a userConfirmation quoting the request that asked you to write the email - rather than the reply approving the one you wrote - is wrong. Never call it in the agent session view or in chat: use SendEmail there, whose review card or composer is the confirmation. Takes the same fields as SendEmail; write the body in Markdown, which is rendered to HTML on send.
*/
-export interface SendEmail {
+export interface SendConfirmedEmail {
/**
* The subject line of the email.
*/
@@ -5813,6 +5813,10 @@ export interface SendEmail {
* excludes the signature for this one email.
*/
includeSignature?: boolean | null;
+ /**
+ * The user's own message approving this specific email, quoted verbatim - for example their "yes, send it" in reply to the email you wrote out for them. It is a reply to your draft, never the earlier request that asked you to write one: if the user has not yet seen this email, there is nothing to quote here and the tool must not be called. Required: do not paraphrase it, and never supply it yourself.
+ */
+ userConfirmation: string;
}
/**
* A recipient for an email.
@@ -5827,6 +5831,46 @@ export interface EmailRecipient {
*/
name?: string | null;
}
+/**
+ * Draft, compose, and send an email the user confirms in a review card or composer. Use this tool whenever the user asks you to draft, write, compose, or send an email (or reply to one) from the agent session view or from chat — never write the email as plain text there. It opens the draft for the user to review, edit, and confirm before it is sent, so it is the correct tool even when the user only wants a draft. Do NOT use it for a prompt that came from a channel or document thread — the context block names a conversation parent when it did, and there is no surface to review a draft in: write the email out in your reply, ask whether to send it, and use SendConfirmedEmail once the user approves. To reply to an existing message, provide the replying_to_id. Write the body in Markdown — use **bold**, *italics*, lists, links, and other standard Markdown formatting. The draft composer renders the Markdown for the user to review and edit; the composer produces HTML that is sent as the actual email body.
+ */
+export interface SendEmail {
+ /**
+ * The subject line of the email.
+ */
+ subject: string;
+ /**
+ * The body of the email, written as Markdown. A host with a composer
+ * (chat) replaces this with the base64url-encoded HTML the composer
+ * exported before the tool runs; a host without one (an agent session)
+ * leaves the Markdown, and this tool renders it the same way.
+ */
+ body: string;
+ /**
+ * The primary recipients (To field).
+ */
+ to: EmailRecipient[];
+ /**
+ * Carbon copy recipients (optional).
+ */
+ cc?: EmailRecipient[];
+ /**
+ * Blind carbon copy recipients (optional).
+ */
+ bcc?: EmailRecipient[];
+ /**
+ * The ID of a message to reply to (optional). When set, the email is
+ * sent as a reply within the same thread.
+ */
+ replyingToId?: string | null;
+ /**
+ * Per-message signature override, set by the composer's signature preview —
+ * not normally by you. Omit to use the inbox's default policy (always on a
+ * new email; on replies/forwards only when the user enabled it). `false`
+ * excludes the signature for this one email.
+ */
+ includeSignature?: boolean | null;
+}
/**
* Set or update a property value on an entity (document, project, etc.). Tasks are targeted as entity_type='document'. Provide the property_definition_id and exactly one value field matching the property's data type.
*
diff --git a/crates/agent_harness/src/domain/model.rs b/crates/agent_harness/src/domain/model.rs
index 7e990551fb..1c8226fd21 100644
--- a/crates/agent_harness/src/domain/model.rs
+++ b/crates/agent_harness/src/domain/model.rs
@@ -2,7 +2,7 @@
use agent_client_protocol::schema::v1::{HttpHeader, McpServer as AcpMcpServer, McpServerHttp};
use agent_egress::domain::model::{McpServerSlug, RepoSlug};
-use agent_fold::domain::model::TurnSignal;
+use agent_fold::domain::model::{StopReason, TurnSignal};
use agent_runtime_protocol::domain::action::{AgentAction, AgentActionId, PromptAttachment};
use agent_session::domain::model::{AgentMcpServers, AgentSessionId, MessageId, SandboxSize};
use agent_session::domain::ports::ControlEvent;
@@ -214,6 +214,18 @@ impl AgentKind {
!matches!(self, Self::External)
}
+ /// Whether this kind's sessions work in a repository.
+ ///
+ /// Decides how a mention is answered in its thread. A coding runtime runs
+ /// for minutes and produces diffs, so its turn is announced as a magic
+ /// chip - a live portal into the session. The in-memory runtime has no
+ /// repository and chats, so its thread gets a pending reply that becomes
+ /// the answer when the turn ends, the way the original Macro bot replied.
+ #[must_use]
+ pub const fn is_coding(self) -> bool {
+ !matches!(self, Self::InMemory)
+ }
+
/// How this kind's sessions answer permission requests without a registered
/// local harness.
///
@@ -512,6 +524,9 @@ pub struct SessionAnnouncement {
pub session_id: AgentSessionId,
/// The bot the session runs for; the announcement posts as it.
pub bot_id: BotId,
+ /// The runtime serving the session, which decides what the announcement
+ /// looks like (see [`AgentKind::is_coding`]).
+ pub kind: AgentKind,
/// Channel or document containing the mention that opened the session.
pub origin_parent: messages::domain::models::MessageParent,
/// Thread where the announcement should be posted.
@@ -561,10 +576,88 @@ pub struct DeclinedMention {
/// The message an announcement became.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct AnnouncedMessage {
- /// The posted message: the magic chip its turn renders into.
+ /// The posted message: a coding agent's magic chip, or a chat agent's
+ /// pending reply.
pub message_id: Uuid,
}
+/// What a turn's reply in the thread that prompted it should say now.
+///
+/// Mostly how the turn ended. Text wins whenever there is any: an agent that
+/// wrote something and was then cancelled or cut off still said it, and the
+/// thread would rather read that than a notice. The rest distinguish the
+/// silences a reader can act on differently - try again, or not.
+///
+/// Two are not ends at all. A turn that asks the user something through an
+/// ACP elicitation is held open until someone answers it in the session
+/// view, and a thread showing a spinner has no way of knowing that; so the
+/// reply says so ([`Self::NeedsInput`]) and returns to pending once the
+/// question is cleared ([`Self::Resumed`]).
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub enum ReplyOutcome {
+ /// The agent answered; its last message, whole.
+ Answered(String),
+ /// The turn ran to its end without saying anything.
+ Empty,
+ /// The turn was cancelled before it finished: a stop, or a follow-up in
+ /// the thread that steered the session onto a new prompt.
+ Cancelled,
+ /// The runtime refused the prompt or died underneath the turn.
+ Failed,
+ /// The turn is waiting on a question only the session view can answer.
+ NeedsInput {
+ /// What the agent is asking, in prose.
+ question: String,
+ },
+ /// The question was answered or withdrawn and the turn is running again.
+ Resumed,
+}
+
+impl ReplyOutcome {
+ /// The outcome of a turn the fold closed with `stop`, whose last text
+ /// part was `last_text`.
+ #[must_use]
+ pub fn of_turn(stop: &StopReason, last_text: Option<String>) -> Self {
+ match last_text.filter(|text| !text.trim().is_empty()) {
+ Some(text) => Self::Answered(text),
+ None => match stop {
+ StopReason::Cancelled => Self::Cancelled,
+ StopReason::Failed { .. } => Self::Failed,
+ StopReason::EndTurn
+ | StopReason::MaxTokens
+ | StopReason::MaxTurnRequests
+ | StopReason::Refusal
+ | StopReason::Other { .. } => Self::Empty,
+ },
+ }
+ }
+}
+
+/// Facts required to replace a turn's pending reply with what it should say.
+///
+/// Modelled on [`SessionAnnouncement`], which posted the message this
+/// resolves: the same bot posts, on the same person's current capability
+/// to the same parent, so a mentioner who has since lost access to the
+/// thread gets nothing patched in their name either.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct ResolvedReply {
+ /// The session whose turn the reply speaks for; what the reply links to.
+ pub session_id: AgentSessionId,
+ /// The bot the session runs for; the patch is made as it.
+ pub bot_id: BotId,
+ /// The runtime serving the session. A coding runtime's chip renders
+ /// the turn itself, so there is nothing to resolve for one.
+ pub kind: AgentKind,
+ /// The pending reply posted when the turn was announced.
+ pub message_id: Uuid,
+ /// Channel or document the mention was posted in.
+ pub origin_parent: messages::domain::models::MessageParent,
+ /// Who prompted the turn.
+ pub triggered_by: MacroUserIdStr<'static>,
+ /// What the reply should say now.
+ pub outcome: ReplyOutcome,
+}
+
/// Values required to provision a new session container.
#[derive(Debug, Clone)]
pub struct SpawnContainer {
diff --git a/crates/agent_harness/src/domain/model/test.rs b/crates/agent_harness/src/domain/model/test.rs
index 63be58e9c3..62c53b0de9 100644
--- a/crates/agent_harness/src/domain/model/test.rs
+++ b/crates/agent_harness/src/domain/model/test.rs
@@ -143,3 +143,67 @@ fn a_session_repository_keeps_the_url_it_was_read_from() {
assert_eq!(SessionRepository::parse(url), None, "accepted {url}");
}
}
+
+/// The in-memory runtime is the one that chats; everything else works in a
+/// repository and is announced as a live chip.
+#[test]
+fn only_the_in_memory_runtime_is_not_a_coder() {
+ assert!(!AgentKind::InMemory.is_coding());
+ for coder in [
+ AgentKind::SandboxedCoder,
+ AgentKind::Cursor,
+ AgentKind::CodexCloud,
+ AgentKind::ClaudeCloud,
+ AgentKind::External,
+ ] {
+ assert!(coder.is_coding(), "{coder:?} has a repository to work in");
+ }
+}
+
+#[test]
+fn a_turn_with_text_answered_however_it_stopped() {
+ for stop in [
+ StopReason::EndTurn,
+ StopReason::Cancelled,
+ StopReason::Failed {
+ message: "boom".to_owned(),
+ notice: None,
+ },
+ ] {
+ assert_eq!(
+ ReplyOutcome::of_turn(&stop, Some("Here you go.".to_owned())),
+ ReplyOutcome::Answered("Here you go.".to_owned()),
+ "{stop:?}"
+ );
+ }
+}
+
+#[test]
+fn a_silent_turn_is_told_by_how_it_stopped() {
+ for (stop, expected) in [
+ (StopReason::EndTurn, ReplyOutcome::Empty),
+ (StopReason::MaxTokens, ReplyOutcome::Empty),
+ (StopReason::Refusal, ReplyOutcome::Empty),
+ (
+ StopReason::Other {
+ reason: "mystery".to_owned(),
+ },
+ ReplyOutcome::Empty,
+ ),
+ (StopReason::Cancelled, ReplyOutcome::Cancelled),
+ (
+ StopReason::Failed {
+ message: "boom".to_owned(),
+ notice: None,
+ },
+ ReplyOutcome::Failed,
+ ),
+ ] {
+ assert_eq!(ReplyOutcome::of_turn(&stop, None), expected, "{stop:?}");
+ assert_eq!(
+ ReplyOutcome::of_turn(&stop, Some(" \n".to_owned())),
+ expected,
+ "blank text is no text: {stop:?}"
+ );
+ }
+}
diff --git a/crates/agent_harness/src/domain/notifications.rs b/crates/agent_harness/src/domain/notifications.rs
index 81e8dd548e..d3b1629ef1 100644
--- a/crates/agent_harness/src/domain/notifications.rs
+++ b/crates/agent_harness/src/domain/notifications.rs
@@ -10,14 +10,25 @@
//!
//! | fact | notification | recipients |
//! | --- | --- | --- |
-//! | `settled` | [`AgentSessionSettledMetadata`] | the session's audience: owner plus everyone who has driven it |
-//! | `waiting_for_input` | [`AgentSessionWaitingForInputMetadata`] | the same audience - anyone with edit access may answer, and these are the people already driving it |
+//! | `settled` | [`AgentSessionSettledMetadata`] | the session's audience: owner plus everyone who has driven it - unless the turn was a chat agent's announced reply, whose patched message already notifies the thread |
+//! | `waiting_for_input` | [`AgentSessionWaitingForInputMetadata`] | the same audience - anyone with edit access may answer, and these are the people already driving it - with the same exception for a chat agent's announced turn, whose reply is patched to say it is waiting |
//! | `mentioned` | [`AgentSessionMentionedMetadata`] | the users the prompt named, who can now open the session |
//!
-//! Everything else is nobody's news. Retracting a notification once it is
-//! stale (the question answered, the next turn started) is deliberately not
-//! done yet: the notification ingress has no producer-facing way to mark
-//! done, and adding one is its own change.
+//! Everything else is nobody's news.
+//!
+//! The session's [`AgentKind`] comes in beside the fact because the fact
+//! does not carry it: a chat agent's announced turn ends by patching its
+//! pending reply into the thread, and the message service notifies on that
+//! patch as if the answer had just been posted, so a `settled` notification
+//! on top would tell the same people the same thing twice. The same reply
+//! is patched when the turn stops to ask a question, so `waiting_for_input`
+//! is suppressed for it likewise. A coding agent's chip notifies nobody,
+//! and a chat turn nobody announced - one driven from the session view -
+//! has no message to speak through, so both keep every notification.
+//!
+//! Retracting a notification once it is stale (the question answered, the
+//! next turn started) is deliberately not done yet: the notification ingress
+//! has no producer-facing way to mark done, and adding one is its own change.
//!
//! # Ids
//!
@@ -48,6 +59,8 @@ use notification::domain::models::apple::PushNotificationData;
use notification::domain::models::request::SendNotificationRequestBuilder;
use notification::domain::models::{Notification, SendNotificationRequest};
+use super::model::AgentKind;
+
/// The namespace agent-session notification ids are derived in. Fixed
/// forever: changing it would orphan every retraction of a notification
/// created before the change.
@@ -116,12 +129,12 @@ impl PlannedNotification {
}
}
-/// The notifications one lifecycle fact warrants.
+/// The notifications one lifecycle fact about a `kind` session warrants.
#[must_use]
-pub fn plan(event: &AgentSessionLifecycleEvent) -> Vec<PlannedNotification> {
+pub fn plan(event: &AgentSessionLifecycleEvent, kind: AgentKind) -> Vec<PlannedNotification> {
match event {
- AgentSessionLifecycleEvent::Settled(settled) => plan_settled(settled),
- AgentSessionLifecycleEvent::WaitingForInput(waiting) => plan_waiting(waiting),
+ AgentSessionLifecycleEvent::Settled(settled) => plan_settled(settled, kind),
+ AgentSessionLifecycleEvent::WaitingForInput(waiting) => plan_waiting(waiting, kind),
AgentSessionLifecycleEvent::Mentioned(mentioned) => plan_mentioned(mentioned),
AgentSessionLifecycleEvent::Opened(_)
| AgentSessionLifecycleEvent::TurnStarted(_)
@@ -133,12 +146,17 @@ pub fn plan(event: &AgentSessionLifecycleEvent) -> Vec<PlannedNotification> {
}
}
-fn plan_settled(settled: &SessionSettledMetadata) -> Vec<PlannedNotification> {
+fn plan_settled(settled: &SessionSettledMetadata, kind: AgentKind) -> Vec<PlannedNotification> {
// "Settled" without the turn's record is a fact nobody can act on: no
// excerpt, no chip, no turn to key the id by.
let Some(turn) = &settled.last_turn else {
return Vec::new();
};
+ // A chat agent's announced turn already told the thread: its pending
+ // reply was patched into the answer, and that patch notifies as a post.
+ if !kind.is_coding() && turn.announcement_message_id.is_some() {
+ return Vec::new();
+ }
let (entity, secondary_entity) = entities(&settled.identity);
vec![PlannedNotification::Settled(Notify {
notification_id: settled_notification_id(settled.identity.session_id.as_uuid(), turn.turn),
@@ -155,7 +173,13 @@ fn plan_settled(settled: &SessionSettledMetadata) -> Vec<PlannedNotification> {
})]
}
-fn plan_waiting(waiting: &WaitingForInputMetadata) -> Vec<PlannedNotification> {
+fn plan_waiting(waiting: &WaitingForInputMetadata, kind: AgentKind) -> Vec<PlannedNotification> {
+ // A chat agent's announced turn tells its thread it is waiting the same
+ // way it tells it the answer: by patching its pending reply, which
+ // notifies as a post.
+ if !kind.is_coding() && waiting.announcement_message_id.is_some() {
+ return Vec::new();
+ }
let (entity, secondary_entity) = entities(&waiting.identity);
vec![PlannedNotification::WaitingForInput(Notify {
notification_id: waiting_notification_id(
diff --git a/crates/agent_harness/src/domain/notifications/test.rs b/crates/agent_harness/src/domain/notifications/test.rs
index c0542cb9f5..db1be7e037 100644
--- a/crates/agent_harness/src/domain/notifications/test.rs
+++ b/crates/agent_harness/src/domain/notifications/test.rs
@@ -59,6 +59,12 @@ fn settled(identity: SessionIdentity, turn: u32) -> AgentSessionLifecycleEvent {
})
}
+/// The plan for a coding agent's session - the shape every fact had before
+/// kinds could differ.
+fn coder(event: &AgentSessionLifecycleEvent) -> Vec<PlannedNotification> {
+ plan(event, AgentKind::SandboxedCoder)
+}
+
fn one_settled(actions: Vec<PlannedNotification>) -> Notify<AgentSessionSettledMetadata> {
match actions.as_slice() {
[PlannedNotification::Settled(notify)] => notify.clone(),
@@ -68,7 +74,7 @@ fn one_settled(actions: Vec<PlannedNotification>) -> Notify<AgentSessionSettledM
#[test]
fn settled_notifies_the_whole_audience_under_the_session() {
- let notify = one_settled(plan(&settled(identity(), 2)));
+ let notify = one_settled(coder(&settled(identity(), 2)));
assert_eq!(
notify.entity,
@@ -93,7 +99,7 @@ fn settled_notifies_the_whole_audience_under_the_session() {
#[test]
fn a_session_with_no_thread_files_the_same_way() {
- let notify = one_settled(plan(&settled(detached_identity(), 0)));
+ let notify = one_settled(coder(&settled(detached_identity(), 0)));
assert_eq!(
notify.entity,
@@ -105,7 +111,7 @@ fn a_session_with_no_thread_files_the_same_way() {
#[test]
fn the_owner_always_hears_settled_even_when_the_audience_is_empty() {
// An event published before the audience field existed.
- let notify = one_settled(plan(&settled(
+ let notify = one_settled(coder(&settled(
SessionIdentity {
audience: Vec::new(),
..identity()
@@ -118,9 +124,9 @@ fn the_owner_always_hears_settled_even_when_the_audience_is_empty() {
#[test]
fn settled_ids_are_stable_per_turn_and_distinct_across_turns() {
- let first = one_settled(plan(&settled(identity(), 1)));
- let again = one_settled(plan(&settled(identity(), 1)));
- let next = one_settled(plan(&settled(identity(), 2)));
+ let first = one_settled(coder(&settled(identity(), 1)));
+ let again = one_settled(coder(&settled(identity(), 1)));
+ let next = one_settled(coder(&settled(identity(), 2)));
assert_eq!(
first.notification_id, again.notification_id,
@@ -133,9 +139,62 @@ fn settled_ids_are_stable_per_turn_and_distinct_across_turns() {
);
}
+/// A chat agent's announced turn already reached the thread as the patched
+/// reply, which the message service notifies on as a post.
+#[test]
+fn a_chat_agents_announced_turn_settles_silently() {
+ let actions = plan(&settled(identity(), 2), AgentKind::InMemory);
+
+ assert!(actions.is_empty(), "{actions:#?}");
+}
+
+/// Only the announced turn is spoken for by its reply: a chat session driven
+/// from the session view posted nothing, so its audience still hears settled.
+#[test]
+fn a_chat_agents_unannounced_turn_still_notifies() {
+ let event = AgentSessionLifecycleEvent::Settled(SessionSettledMetadata {
+ identity: identity(),
+ last_turn: Some(TurnSummary {
+ turn: TurnId(2),
+ action_id: AgentActionId::mint(),
+ actor: Some(user("[email protected]")),
+ announcement_message_id: None,
+ stop_reason: "end_turn".to_owned(),
+ excerpt: Some("Done.".to_owned()),
+ }),
+ });
+
+ let notify = one_settled(plan(&event, AgentKind::InMemory));
+ assert_eq!(
+ notify.recipients,
+ vec![owner(), user("[email protected]"), user("[email protected]")]
+ );
+ assert_eq!(notify.metadata.session.announcement_message_id, None);
+}
+
+/// A coding agent's chip is a pointer, not news, so settled is the only
+/// thing the thread hears - whichever coding runtime it was.
+#[test]
+fn every_coding_kinds_announced_turn_notifies_settled() {
+ for kind in [
+ AgentKind::SandboxedCoder,
+ AgentKind::Cursor,
+ AgentKind::CodexCloud,
+ AgentKind::ClaudeCloud,
+ AgentKind::External,
+ ] {
+ let notify = one_settled(plan(&settled(identity(), 2), kind));
+ assert_eq!(
+ notify.metadata.session.announcement_message_id,
+ Some(Uuid::from_u128(4)),
+ "{kind:?}"
+ );
+ }
+}
+
#[test]
fn settled_without_a_turn_record_notifies_nobody() {
- let actions = plan(&AgentSessionLifecycleEvent::Settled(
+ let actions = coder(&AgentSessionLifecycleEvent::Settled(
SessionSettledMetadata {
identity: identity(),
last_turn: None,
@@ -147,7 +206,7 @@ fn settled_without_a_turn_record_notifies_nobody() {
#[test]
fn waiting_for_input_goes_to_the_audience() {
- let actions = plan(&AgentSessionLifecycleEvent::WaitingForInput(
+ let actions = coder(&AgentSessionLifecycleEvent::WaitingForInput(
WaitingForInputMetadata {
identity: identity(),
turn: TurnId(3),
@@ -172,10 +231,52 @@ fn waiting_for_input_goes_to_the_audience() {
);
}
+fn waiting(announcement_message_id: Option<Uuid>) -> AgentSessionLifecycleEvent {
+ AgentSessionLifecycleEvent::WaitingForInput(WaitingForInputMetadata {
+ identity: identity(),
+ turn: TurnId(3),
+ action_id: AgentActionId::mint(),
+ announcement_message_id,
+ question: "Which approach?".to_owned(),
+ })
+}
+
+/// The pending reply is patched to say the agent is waiting, and that
+/// patch notifies the thread; a notification on top would be the same
+/// news twice.
+#[test]
+fn a_chat_agents_announced_turn_waits_silently() {
+ let actions = plan(&waiting(Some(Uuid::from_u128(4))), AgentKind::InMemory);
+
+ assert!(actions.is_empty(), "{actions:#?}");
+}
+
+/// Only the announced turn has a reply to speak through: a chat session
+/// asking from the session view still notifies its audience, and a coding
+/// agent's chip says nothing about a question.
+#[test]
+fn every_other_waiting_turn_still_notifies() {
+ for (kind, announced) in [
+ (AgentKind::InMemory, None),
+ (AgentKind::SandboxedCoder, Some(Uuid::from_u128(4))),
+ (AgentKind::Cursor, Some(Uuid::from_u128(4))),
+ (AgentKind::External, None),
+ ] {
+ let actions = plan(&waiting(announced), kind);
+ assert!(
+ matches!(
+ actions.as_slice(),
+ [PlannedNotification::WaitingForInput(_)]
+ ),
+ "{kind:?} announced={announced:?}: {actions:#?}"
+ );
+ }
+}
+
#[test]
fn mentioned_notifies_exactly_the_people_named() {
let action_id = AgentActionId::mint();
- let actions = plan(&AgentSessionLifecycleEvent::Mentioned(
+ let actions = coder(&AgentSessionLifecycleEvent::Mentioned(
SessionMentionedMetadata {
identity: identity(),
action_id,
@@ -205,7 +306,7 @@ fn mentioned_notifies_exactly_the_people_named() {
#[test]
fn a_mention_of_nobody_is_nothing() {
- let actions = plan(&AgentSessionLifecycleEvent::Mentioned(
+ let actions = coder(&AgentSessionLifecycleEvent::Mentioned(
SessionMentionedMetadata {
identity: identity(),
action_id: AgentActionId::mint(),
@@ -242,13 +343,13 @@ fn facts_that_are_not_news_to_people_plan_nothing() {
identity: identity(),
}),
] {
- assert!(plan(&event).is_empty(), "{event:?}");
+ assert!(coder(&event).is_empty(), "{event:?}");
}
}
#[test]
fn a_notify_becomes_a_realtime_and_push_request_with_its_own_id() {
- let notify = one_settled(plan(&settled(identity(), 2)));
+ let notify = one_settled(coder(&settled(identity(), 2)));
let expected_id = notify.notification_id;
let request = notify.into_request();
diff --git a/crates/agent_harness/src/domain/pending.rs b/crates/agent_harness/src/domain/pending.rs
index 13bfe08e52..86bd5a0a3c 100644
--- a/crates/agent_harness/src/domain/pending.rs
+++ b/crates/agent_harness/src/domain/pending.rs
@@ -94,6 +94,7 @@ mod test {
action_id: AgentActionId::mint(),
turn: TurnId(7),
actor: None,
+ announce: None,
announcement_message_id: None,
}
}
diff --git a/crates/agent_harness/src/domain/ports.rs b/crates/agent_harness/src/domain/ports.rs
index ff6b02efeb..7adcaaa0d6 100644
--- a/crates/agent_harness/src/domain/ports.rs
+++ b/crates/agent_harness/src/domain/ports.rs
@@ -16,8 +16,8 @@ use macro_user_id::user_id::MacroUserIdStr;
use super::error::{HarnessError, Result};
use super::model::{
AgentKind, AgentRuntimeConfig, AnnouncedMessage, CommandOutcome, ConversationContext,
- DeclinedMention, HarnessCommand, ProvisionedEgress, ReachableRepository, SandboxEgress,
- SessionAnnouncement, SessionBlocker, SpawnContainer,
+ DeclinedMention, HarnessCommand, ProvisionedEgress, ReachableRepository, ResolvedReply,
+ SandboxEgress, SessionAnnouncement, SessionBlocker, SpawnContainer,
};
use super::notifications::PlannedNotification;
use super::sandbox::SandboxResizeEffect;
@@ -254,14 +254,26 @@ impl AgentSessionNotifier for NoopAgentSessionNotifier {
}
}
-/// Posts a pointer to a new agent session into its originating thread.
+/// Speaks for an agent session in the thread that prompted it.
+///
+/// What gets said depends on the session's [`AgentKind`]: a coding agent's
+/// turn is announced as a magic chip that renders the session live, and a
+/// chat agent's as a pending reply that [`Self::resolve`] later turns into
+/// the answer. The domain names the kind and the facts; the adapter owns
+/// what either looks like.
pub trait SessionAnnouncer: Send + Sync + 'static {
- /// Publish one session announcement, returning the message it became.
+ /// Post the message a turn is answered through, returning what it became.
fn announce(
&self,
announcement: SessionAnnouncement,
) -> impl Future<Output = Result<AnnouncedMessage>> + Send;
+ /// Replace a chat agent's pending reply with how its turn ended.
+ ///
+ /// A coding agent's magic chip renders the turn itself, so there is
+ /// nothing to replace and this does nothing for one.
+ fn resolve(&self, resolution: ResolvedReply) -> impl Future<Output = Result<()>> + Send;
+
/// Tell a thread why its mention opened no session.
///
/// The other thing the bot can say into a thread: not "here is your
diff --git a/crates/agent_harness/src/domain/queue.rs b/crates/agent_harness/src/domain/queue.rs
index 04e40d698f..adee30a100 100644
--- a/crates/agent_harness/src/domain/queue.rs
+++ b/crates/agent_harness/src/domain/queue.rs
@@ -76,7 +76,15 @@ pub struct InFlightTurn {
pub turn: TurnId,
/// The user who prompted it, absent when a bot acted on nobody's behalf.
pub actor: Option<MacroUserIdStr<'static>>,
- /// The chip message posted for this turn, when one was.
+ /// Where the prompt came from, when it came from somewhere the session
+ /// answers back into. Kept so the turn's end can speak into the same
+ /// thread the announcement did.
+ pub announce: Option<AnnounceOrigin>,
+ /// The message posted when this turn was announced, when one was. For a
+ /// coding agent that is the chip the turn renders into; for a chat agent
+ /// it is the pending reply the turn's end resolves (see
+ /// [`SessionAnnouncer::resolve`](super::ports::SessionAnnouncer::resolve)).
+ /// Downstream events carry it under this name for both.
pub announcement_message_id: Option<Uuid>,
}
diff --git a/crates/agent_harness/src/domain/service.rs b/crates/agent_harness/src/domain/service.rs
index 7ba54424f9..58134e4b1f 100644
--- a/crates/agent_harness/src/domain/service.rs
+++ b/crates/agent_harness/src/domain/service.rs
@@ -48,8 +48,8 @@ use tracing::instrument::WithSubscriber as _;
use crate::domain::error::{HarnessError, Result};
use crate::domain::model::{
AgentKind, AnnounceOrigin, AnnouncePrompt, CommandOutcome, DeclinedMention, DeliverAction,
- HarnessCommand, HarnessDefaults, OpenSession, SessionAnnouncement, SpawnContainer,
- is_macro_staff,
+ HarnessCommand, HarnessDefaults, OpenSession, ReplyOutcome, ResolvedReply, SessionAnnouncement,
+ SpawnContainer, is_macro_staff,
};
use crate::domain::pending::PendingCommands;
use crate::domain::ports::{
@@ -387,6 +387,7 @@ where
.announce(SessionAnnouncement {
session_id,
bot_id: session.bot_id,
+ kind: AgentKind::for_session(session.bot_id, &session.harness),
origin_parent: prompt.origin.parent,
origin_thread_id: prompt.origin.thread_id,
origin_message_id: prompt.origin.message_id,
diff --git a/crates/agent_harness/src/domain/service/deliver.rs b/crates/agent_harness/src/domain/service/deliver.rs
index d27a374cce..ba9ac278ec 100644
--- a/crates/agent_harness/src/domain/service/deliver.rs
+++ b/crates/agent_harness/src/domain/service/deliver.rs
@@ -231,6 +231,7 @@ where
Ok(Some(SessionAnnouncement {
session_id,
bot_id: session.bot_id,
+ kind: AgentKind::for_session(session.bot_id, &session.harness),
origin_parent: origin.parent,
origin_thread_id: origin.thread_id,
origin_message_id: origin.message_id,
@@ -239,4 +240,64 @@ where
triggered_by: triggered_by.clone(),
}))
}
+
+ /// Tell the thread what an announced turn's reply should say now: how
+ /// the turn ended, or that it is waiting on the user.
+ ///
+ /// Best-effort, like every lifecycle publish: the turn is over or still
+ /// running regardless, and the queue behind it drains whether or not the
+ /// thread hears. The bot and runtime kind are re-read from the row, as
+ /// they were when the turn was announced. A turn nobody announced - no
+ /// origin, no actor, or no message posted - has nothing to resolve.
+ /// Whether the kind's message needs resolving at all is the announcer's
+ /// call.
+ pub(super) async fn resolve_reply(
+ &self,
+ session_id: AgentSessionId,
+ turn: Option<&InFlightTurn>,
+ outcome: ReplyOutcome,
+ ) {
+ let Some(turn) = turn else {
+ return;
+ };
+ let (Some(message_id), Some(origin), Some(triggered_by)) = (
+ turn.announcement_message_id,
+ turn.announce.as_ref(),
+ turn.actor.as_ref(),
+ ) else {
+ return;
+ };
+ let session = match self.sessions.get_session(session_id).await {
+ Ok(session) => session,
+ Err(error) => {
+ tracing::error!(
+ error = ?error,
+ %session_id,
+ %message_id,
+ "leaving a turn's reply unresolved: session row unavailable"
+ );
+ return;
+ }
+ };
+ if let Err(error) = self
+ .announcer
+ .resolve(ResolvedReply {
+ session_id,
+ bot_id: session.bot_id,
+ kind: AgentKind::for_session(session.bot_id, &session.harness),
+ message_id,
+ origin_parent: origin.parent.clone(),
+ triggered_by: triggered_by.clone(),
+ outcome,
+ })
+ .await
+ {
+ tracing::error!(
+ error = ?error,
+ %session_id,
+ %message_id,
+ "failed to resolve a turn's reply in its thread"
+ );
+ }
+ }
}
diff --git a/crates/agent_harness/src/domain/service/lifecycle_events.rs b/crates/agent_harness/src/domain/service/lifecycle_events.rs
index 7615756c17..c18d0484d5 100644
--- a/crates/agent_harness/src/domain/service/lifecycle_events.rs
+++ b/crates/agent_harness/src/domain/service/lifecycle_events.rs
@@ -49,8 +49,23 @@ where
{
/// The identity block for one session, from its row and its bot.
pub(super) async fn identity(&self, session_id: AgentSessionId) -> Result<SessionIdentity> {
+ self.identity_and_kind(session_id)
+ .await
+ .map(|(identity, _)| identity)
+ }
+
+ /// [`Self::identity`], with the runtime kind the same row names - read
+ /// together because the notifications a fact warrants depend on both.
+ pub(super) async fn identity_and_kind(
+ &self,
+ session_id: AgentSessionId,
+ ) -> Result<(SessionIdentity, AgentKind)> {
let session = self.sessions.get_session(session_id).await?;
- self.identity_of(&session).await
+ let identity = self.identity_of(&session).await?;
+ Ok((
+ identity,
+ AgentKind::for_session(session.bot_id, &session.harness),
+ ))
}
/// The identity block for a session whose row is already in hand.
@@ -74,10 +89,10 @@ where
session_id: AgentSessionId,
build: impl FnOnce(SessionIdentity) -> AgentSessionLifecycleEvent,
) {
- match self.identity(session_id).await {
- Ok(identity) => {
+ match self.identity_and_kind(session_id).await {
+ Ok((identity, kind)) => {
let event = build(identity);
- let notifications = plan(&event);
+ let notifications = plan(&event, kind);
self.lifecycle_publisher.publish(event).await;
for notification in notifications {
self.notifier.notify(notification).await;
diff --git a/crates/agent_harness/src/domain/service/open.rs b/crates/agent_harness/src/domain/service/open.rs
index e957e18ed5..990d1b08f5 100644
--- a/crates/agent_harness/src/domain/service/open.rs
+++ b/crates/agent_harness/src/domain/service/open.rs
@@ -124,6 +124,7 @@ where
let announcement = SessionAnnouncement {
session_id: session.id,
bot_id: request.bot_id,
+ kind: AgentKind::for_session(session.bot_id, &session.harness),
origin_parent: thread.parent,
origin_thread_id: thread.thread_id,
origin_message_id: thread.message_id,
diff --git a/crates/agent_harness/src/domain/service/queue.rs b/crates/agent_harness/src/domain/service/queue.rs
index 4f5c19995c..a56f396a09 100644
--- a/crates/agent_harness/src/domain/service/queue.rs
+++ b/crates/agent_harness/src/domain/service/queue.rs
@@ -371,6 +371,18 @@ where
if ended.is_none() {
tracing::info!(%session_id, "turn ended with no in-flight record");
}
+ // The thread hears first, before any fact is published or
+ // the next prompt dispatched: a chat agent's pending reply
+ // is what the person who asked is looking at, and it must
+ // never outlive the turn it stands for. Per turn, not per
+ // settle - a second mention queued behind this one would
+ // otherwise leave the first spinning until both finished.
+ self.resolve_reply(
+ session_id,
+ ended.as_ref(),
+ ReplyOutcome::of_turn(&stop, last_text.clone()),
+ )
+ .await;
if let (Some(turn), Some(fold_action_id)) = (&ended, fold_action_id)
&& turn.action_id != fold_action_id
{
@@ -423,6 +435,10 @@ where
}
HarnessCommand::SessionStopped { reason } => {
let in_flight = self.busy.take(session_id);
+ // No `TurnEnded` follows a death, so this is the turn's last
+ // chance to stop its pending reply spinning.
+ self.resolve_reply(session_id, in_flight.as_ref(), ReplyOutcome::Failed)
+ .await;
self.publish_lifecycle(session_id, |identity| {
AgentSessionLifecycleEvent::Stopped(SessionStoppedMetadata {
identity,
@@ -438,6 +454,22 @@ where
tracing::warn!(%session_id, "elicitation raised with no in-flight record");
return Ok(CommandOutcome::Completed);
};
+ // The question is held for the user and answered only in the
+ // session view (`hold_or_refuse_elicitation`), so a thread
+ // showing a spinner would spin until someone happened to open
+ // the session. Say so where the person who asked is looking.
+ // This is not an in-memory special case: it is the fallback
+ // for any runtime this harness does not control - a user-run
+ // macrod, a third-party agent - that elicits from a channel
+ // turn.
+ self.resolve_reply(
+ session_id,
+ Some(&turn),
+ ReplyOutcome::NeedsInput {
+ question: question.clone(),
+ },
+ )
+ .await;
self.publish_lifecycle(session_id, |identity| {
AgentSessionLifecycleEvent::WaitingForInput(WaitingForInputMetadata {
identity,
@@ -455,6 +487,10 @@ where
tracing::warn!(%session_id, "elicitation cleared with no in-flight record");
return Ok(CommandOutcome::Completed);
};
+ // The turn is running again; the thread goes back to waiting
+ // for its answer.
+ self.resolve_reply(session_id, Some(&turn), ReplyOutcome::Resumed)
+ .await;
self.publish_lifecycle(session_id, |identity| {
AgentSessionLifecycleEvent::InputReceived(InputReceivedMetadata {
identity,
@@ -755,6 +791,7 @@ where
action_id: entry.action_id,
turn: prompted_message_id.turn,
actor: entry.actor,
+ announce: entry.announce,
announcement_message_id: entry.announced,
};
self.busy.mark_turn(session_id, turn.clone());
diff --git a/crates/agent_harness/src/domain/service/test.rs b/crates/agent_harness/src/domain/service/test.rs
index 295027bc1d..4403f4100e 100644
--- a/crates/agent_harness/src/domain/service/test.rs
+++ b/crates/agent_harness/src/domain/service/test.rs
@@ -2,6 +2,7 @@
//! with in-memory persistence, mock containers, a fake agent, and a
//! recording announcer. Only the edges are doubles.
+mod chat_reply;
mod user_cleanup;
use messages::domain::models::MessageParent;
diff --git a/crates/agent_harness/src/domain/service/test/chat_reply.rs b/crates/agent_harness/src/domain/service/test/chat_reply.rs
new file mode 100644
index 0000000000..bbfa454ba4
--- /dev/null
+++ b/crates/agent_harness/src/domain/service/test/chat_reply.rs
@@ -0,0 +1,343 @@
+//! A chat agent's mention is answered in its thread by one message: posted
+//! as a pending reply when the turn is announced, resolved into the answer
+//! when that turn ends. The announcer is a recorder here, so what is checked
+//! is what the domain asked of it and when.
+
+use super::*;
+use crate::domain::model::{ReplyOutcome, ResolvedReply};
+use crate::domain::notifications::PlannedNotification;
+
+/// A mention of a bot whose sessions the in-memory runtime serves.
+fn chat_open_command() -> OpenSession {
+ let mut command = open_command();
+ command.runtime.kind = AgentKind::InMemory;
+ command.runtime.harness = "macro-inmem".to_owned();
+ command
+}
+
+/// Open a chat session and leave its first turn running.
+async fn chat_session_with_a_running_turn(
+ service: &TestHarness,
+ containers: &MockContainerManager,
+ id: AgentSessionId,
+) -> ContainerMock {
+ let open = service.execute(id, HarnessCommand::Open(chat_open_command()));
+ let drive = async {
+ loop {
+ if containers.spawned() == 1 {
+ break;
+ }
+ tokio::task::yield_now().await;
+ }
+ let container = containers
+ .container(session_of(containers))
+ .expect("the spawned container is findable");
+ complete_session_handshake(&container).await;
+ // initialize, session/new, and the opening prompt.
+ container.agent().wait_for_requests(3).await;
+ container
+ };
+ let (opened, container) = tokio::join!(open, drive);
+ opened.expect("the chat session opens");
+ container
+}
+
+/// The agent streams one text part of its answer.
+fn says(agent: &FakeAgent, text: &str) {
+ agent.sends_raw(
+ RawJsonRpcMessage::notification(
+ "session/update".to_owned(),
+ serde_json::json!({
+ "sessionId": "acp-test",
+ "update": {
+ "sessionUpdate": "agent_message_chunk",
+ "content": {"type": "text", "text": text}
+ }
+ }),
+ )
+ .expect("notification params are an object"),
+ );
+}
+
+fn one_resolved(announcer: &AnnouncerMock) -> ResolvedReply {
+ match announcer.resolved().as_slice() {
+ [resolved] => resolved.clone(),
+ other => panic!("expected exactly one resolved reply, got {other:#?}"),
+ }
+}
+
+#[tokio::test]
+async fn a_chat_mention_is_announced_as_a_pending_reply_and_resolved_with_the_answer() {
+ let ((service, _, containers, announcer, _), turns) =
+ harness_with_signals(PromptContextMock::default(), PromptComposerMock::default());
+ let id = AgentSessionId::new();
+ let container = chat_session_with_a_running_turn(&service, &containers, id).await;
+ let agent = container.agent();
+
+ says(&agent, "Hello there.");
+ agent.completes_prompt().await;
+ // Opened, TurnStarted, TurnEnded, Settled: the reply resolves before
+ // the turn's end is published, so once it is, the resolve has happened.
+ turns.lifecycle_published(4).await;
+
+ let announced = announcer.announced();
+ assert_eq!(announced.len(), 1);
+ assert_eq!(announced[0].kind, AgentKind::InMemory);
+ let pending = announcer.announced_messages()[0];
+ let resolved = one_resolved(&announcer);
+ assert_eq!(resolved.kind, AgentKind::InMemory);
+ assert_eq!(resolved.message_id, pending.message_id);
+ // The same bot, into the same parent, for the same person who asked.
+ assert_eq!(resolved.bot_id, announced[0].bot_id);
+ assert_eq!(resolved.origin_parent, announced[0].origin_parent);
+ assert_eq!(resolved.triggered_by, sender());
+ assert_eq!(
+ resolved.outcome,
+ ReplyOutcome::Answered("Hello there.".to_owned())
+ );
+}
+
+/// The patched reply notifies the thread as a post, so `settled` on top
+/// would tell the same people twice.
+#[tokio::test]
+async fn a_chat_turn_settles_without_a_settled_notification() {
+ let ((service, _, containers, _, _), turns) =
+ harness_with_signals(PromptContextMock::default(), PromptComposerMock::default());
+ let id = AgentSessionId::new();
+ let container = chat_session_with_a_running_turn(&service, &containers, id).await;
+
+ says(&container.agent(), "Hello there.");
+ container.agent().completes_prompt().await;
+ turns.lifecycle_published(4).await;
+
+ assert!(
+ matches!(
+ turns.lifecycle().last(),
+ Some(AgentSessionLifecycleEvent::Settled(_))
+ ),
+ "the fact is still published: {:#?}",
+ turns.lifecycle()
+ );
+ assert!(
+ turns.notifier.notified().is_empty(),
+ "nobody is notified twice: {:#?}",
+ turns.notifier.notified()
+ );
+}
+
+#[tokio::test]
+async fn a_silent_chat_turn_resolves_as_empty_rather_than_spinning() {
+ let ((service, _, containers, announcer, _), turns) =
+ harness_with_signals(PromptContextMock::default(), PromptComposerMock::default());
+ let id = AgentSessionId::new();
+ let container = chat_session_with_a_running_turn(&service, &containers, id).await;
+
+ container.agent().completes_prompt().await;
+ turns.lifecycle_published(4).await;
+
+ assert_eq!(one_resolved(&announcer).outcome, ReplyOutcome::Empty);
+}
+
+#[tokio::test]
+async fn a_chat_session_that_dies_mid_turn_resolves_its_reply_as_failed() {
+ let ((service, _, containers, announcer, _), turns) =
+ harness_with_signals(PromptContextMock::default(), PromptComposerMock::default());
+ let id = AgentSessionId::new();
+ let container = chat_session_with_a_running_turn(&service, &containers, id).await;
+
+ container.disconnects();
+ // Opened, TurnStarted, Stopped - and no TurnEnded to resolve on.
+ turns.lifecycle_published(3).await;
+
+ assert!(
+ matches!(
+ turns.lifecycle().last(),
+ Some(AgentSessionLifecycleEvent::Stopped(_))
+ ),
+ "{:#?}",
+ turns.lifecycle()
+ );
+ let resolved = one_resolved(&announcer);
+ assert_eq!(resolved.outcome, ReplyOutcome::Failed);
+ assert_eq!(
+ resolved.message_id,
+ announcer.announced_messages()[0].message_id
+ );
+}
+
+/// Two mentions in quick succession are two messages, each resolved when
+/// its own turn ends - not both when the queue finally drains.
+#[tokio::test]
+async fn each_turns_reply_resolves_when_that_turn_ends() {
+ let ((service, _, containers, announcer, _), turns) =
+ harness_with_signals(PromptContextMock::default(), PromptComposerMock::default());
+ let id = AgentSessionId::new();
+ let container = chat_session_with_a_running_turn(&service, &containers, id).await;
+ let agent = container.agent();
+
+ // A channel follow-up on a running turn steers: it is announced at once
+ // and cancels the turn in progress.
+ let outcome = service
+ .execute(
+ id,
+ HarnessCommand::Deliver(forward_message("actually, this")),
+ )
+ .await
+ .expect("the follow-up is accepted");
+ assert_eq!(outcome, CommandOutcome::Queued);
+ assert_eq!(
+ announcer.announced().len(),
+ 2,
+ "both mentions have a message"
+ );
+ assert!(announcer.resolved().is_empty(), "nothing has ended yet");
+
+ // The first turn ends: only its reply resolves, and the second dispatches.
+ says(&agent, "First answer.");
+ agent.completes_prompt().await;
+ // Opened, TurnStarted, TurnEnded (first), TurnStarted (second).
+ turns.lifecycle_published(4).await;
+ let messages = announcer.announced_messages();
+ let resolved = announcer.resolved();
+ assert_eq!(resolved.len(), 1, "{resolved:#?}");
+ assert_eq!(resolved[0].message_id, messages[0].message_id);
+ assert_eq!(
+ resolved[0].outcome,
+ ReplyOutcome::Answered("First answer.".to_owned())
+ );
+
+ says(&agent, "Second answer.");
+ agent.completes_prompt().await;
+ turns.lifecycle_published(6).await;
+ let resolved = announcer.resolved();
+ assert_eq!(resolved.len(), 2, "{resolved:#?}");
+ assert_eq!(resolved[1].message_id, messages[1].message_id);
+ assert_eq!(resolved[1].triggered_by, staff_sender());
+ assert_eq!(
+ resolved[1].outcome,
+ ReplyOutcome::Answered("Second answer.".to_owned())
+ );
+}
+
+/// The domain does not know a coding kind has nothing to patch - that is the
+/// announcer's call - so it asks for every announced turn, naming the kind,
+/// and the audience still hears `settled` for a coder.
+#[tokio::test]
+async fn a_coding_turn_is_offered_to_the_announcer_as_a_coder_and_still_notifies() {
+ let ((service, _, containers, announcer, _), turns) =
+ harness_with_signals(PromptContextMock::default(), PromptComposerMock::default());
+ let id = AgentSessionId::new();
+ let container = live_sandboxed_coder_session(&service, &containers, id).await;
+ drop(container);
+ turns.lifecycle_published(4).await;
+
+ let resolved = one_resolved(&announcer);
+ assert_eq!(resolved.kind, AgentKind::SandboxedCoder);
+ assert_eq!(
+ resolved.message_id,
+ announcer.announced_messages()[0].message_id
+ );
+ assert!(
+ matches!(
+ turns.notifier.notified().as_slice(),
+ [PlannedNotification::Settled(_)]
+ ),
+ "{:#?}",
+ turns.notifier.notified()
+ );
+}
+
+/// A question the agent asks through ACP is held for the session view; the
+/// thread's spinner has no way of knowing that on its own.
+mod elicitation {
+ use super::*;
+ use agent_client_protocol::schema::v1::{
+ CreateElicitationRequest, ElicitationFormMode, ElicitationSchema, ElicitationSessionScope,
+ RequestId,
+ };
+ use agent_runtime_protocol::domain::action::{ElicitationAnswer, ElicitationRequestId};
+
+ fn ask(agent: &FakeAgent, request_id: i64, question: &str) {
+ let request = CreateElicitationRequest::new(
+ ElicitationFormMode::new(
+ ElicitationSessionScope::new(SessionId::new("acp-test")),
+ ElicitationSchema::new(),
+ ),
+ question,
+ );
+ let (method, params) = request
+ .to_untyped_message()
+ .expect("an elicitation serializes")
+ .into_parts();
+ agent.sends_raw(
+ RawJsonRpcMessage::request(method, params, RequestId::Number(request_id))
+ .expect("elicitation params are an object"),
+ );
+ }
+
+ /// Raised: the reply says it is waiting and what for. Cleared: the reply
+ /// is pending again. Ended: the reply is the answer. One message, three
+ /// patches, and no `waiting_for_input` notification on top of the first -
+ /// the patch already told the thread.
+ #[tokio::test]
+ async fn a_question_is_told_in_the_thread_and_withdrawn_when_answered() {
+ let ((service, _, containers, announcer, _), turns) =
+ harness_with_signals(PromptContextMock::default(), PromptComposerMock::default());
+ let id = AgentSessionId::new();
+ let container = chat_session_with_a_running_turn(&service, &containers, id).await;
+ let agent = container.agent();
+ let pending = announcer.announced_messages()[0].message_id;
+
+ ask(&agent, 7, "Which inbox should I send from?");
+ // Opened, TurnStarted, WaitingForInput.
+ turns.lifecycle_published(3).await;
+ let resolved = announcer.resolved();
+ assert_eq!(resolved.len(), 1, "{resolved:#?}");
+ assert_eq!(resolved[0].message_id, pending);
+ assert_eq!(resolved[0].session_id, id);
+ assert_eq!(
+ resolved[0].outcome,
+ ReplyOutcome::NeedsInput {
+ question: "Which inbox should I send from?".to_owned(),
+ }
+ );
+ assert!(
+ turns.notifier.notified().is_empty(),
+ "the patch is the notification: {:#?}",
+ turns.notifier.notified()
+ );
+
+ service
+ .execute(
+ id,
+ HarnessCommand::Deliver(DeliverAction::control(ControlEvent {
+ action: AgentAction::respond_elicitation(
+ ElicitationRequestId::Number(7),
+ ElicitationAnswer::Decline,
+ ),
+ action_id: None,
+ actor: Some(sender()),
+ })),
+ )
+ .await
+ .expect("the answer is delivered");
+ // InputReceived.
+ turns.lifecycle_published(4).await;
+ let resolved = announcer.resolved();
+ assert_eq!(resolved.len(), 2, "{resolved:#?}");
+ assert_eq!(resolved[1].message_id, pending);
+ assert_eq!(resolved[1].outcome, ReplyOutcome::Resumed);
+
+ says(&agent, "Sent from your primary inbox.");
+ agent.completes_prompt().await;
+ // TurnEnded, Settled.
+ turns.lifecycle_published(6).await;
+ let resolved = announcer.resolved();
+ assert_eq!(resolved.len(), 3, "{resolved:#?}");
+ assert_eq!(resolved[2].message_id, pending);
+ assert_eq!(
+ resolved[2].outcome,
+ ReplyOutcome::Answered("Sent from your primary inbox.".to_owned())
+ );
+ }
+}
diff --git a/crates/agent_harness/src/outbound/channel_announcer.rs b/crates/agent_harness/src/outbound/channel_announcer.rs
index 47f34ba8f1..18705da793 100644
--- a/crates/agent_harness/src/outbound/channel_announcer.rs
+++ b/crates/agent_harness/src/outbound/channel_announcer.rs
@@ -1,27 +1,103 @@
-//! Announce agent responses in their originating message thread through the shared service.
+//! Speak for an agent session in its originating thread through the shared
+//! message service.
+//!
+//! Two shapes, by the session's [`AgentKind`]: a coding agent's turn is a
+//! magic chip, a live portal into the session that renders the turn itself;
+//! a chat agent's turn is a pending reply - the channel markdown's pulsing
+//! await node - that is patched into the answer when the turn ends, the way
+//! the original Macro bot replied, and that says so while the turn waits on
+//! a question only the session view can answer. A chat agent's message
+//! leads with a link to its session in every state. The domain names the
+//! kind, this module chooses the words, and Lexical composes every node:
+//! no node syntax is written here.
#[cfg(test)]
mod test;
use std::sync::Arc;
-use entity_access::domain::{models::BotAccessScope, ports::EntityAccessService};
+use agent_session::domain::model::AgentSessionId;
+use bot_id::BotId;
+use entity_access::domain::{
+ models::{BotAccessScope, EntityAccessReceipt},
+ ports::EntityAccessService,
+};
use lexical_client::LexicalClient;
use lexical_client::parse_markdown::{
- AgentAnnouncementChip, AgentAnnouncementReplyTarget, AgentConnectionChip, AgentConnectionPrompt,
+ AgentAnnouncementChip, AgentAnnouncementReplyTarget, AgentChatReply, AgentChatReplyBody,
+ AgentConnectionChip, AgentConnectionPrompt,
};
+use macro_user_id::user_id::MacroUserIdStr;
use messages::domain::{
api::MessageCommands,
- models::{MessageAttribution, MessageParent, PostMessage, PostMessageNotificationPolicy},
+ models::{
+ MessageAttribution, MessageParent, PatchMessageNotificationPolicy, PostMessage,
+ PostMessageNotificationPolicy,
+ },
+ ports::{MessageError, MessagePatch},
service::MessageWrite,
};
use crate::domain::error::{HarnessError, Result};
use crate::domain::model::{
- AnnouncedMessage, DeclinedMention, SessionAnnouncement, SessionBlocker,
+ AnnouncedMessage, DeclinedMention, ReplyOutcome, ResolvedReply, SessionAnnouncement,
+ SessionBlocker,
};
use crate::domain::ports::SessionAnnouncer;
+const EMPTY_RESPONSE_FALLBACK: &str = "I wasn't able to come up with a response.";
+const CANCELLED_FALLBACK: &str = "I stopped before finishing that.";
+const ERROR_FALLBACK: &str = "Sorry — I ran into an error while responding.";
+/// Introduces the agent's question when a turn stops to ask one. Only the
+/// session view can answer it, and the link ahead of every reply is how the
+/// reader gets there.
+const NEEDS_INPUT_LEAD: &str =
+ "I have a question before I can continue — open the agent session to answer it:";
+
+/// A chat agent's message in one state, for Lexical to compose: the link to
+/// its session, then `body`.
+///
+/// The channel message view lifts a leading session link out of the body
+/// onto the sender line, and every state of the reply carries one: a patch
+/// replaces the content wholesale, and a link only the pending reply had
+/// would vanish with the spinner.
+fn chat_reply(session_id: AgentSessionId, body: AgentChatReplyBody) -> AgentChatReply {
+ AgentChatReply {
+ session_id: session_id.to_string(),
+ body,
+ }
+}
+
+/// What a chat agent's pending reply becomes. Never blank: a turn that said
+/// nothing is told as such rather than left as an empty message. A turn
+/// waiting on its question shows the question, and one resumed after the
+/// answer shows the spinner again.
+fn reply_body(outcome: ReplyOutcome) -> AgentChatReplyBody {
+ let markdown = match outcome {
+ ReplyOutcome::Answered(text) => text,
+ ReplyOutcome::Empty => EMPTY_RESPONSE_FALLBACK.to_owned(),
+ ReplyOutcome::Cancelled => CANCELLED_FALLBACK.to_owned(),
+ ReplyOutcome::Failed => ERROR_FALLBACK.to_owned(),
+ ReplyOutcome::NeedsInput { question } => format!("{NEEDS_INPUT_LEAD}\n\n{question}"),
+ ReplyOutcome::Resumed => return AgentChatReplyBody::Pending,
+ };
+ AgentChatReplyBody::Markdown { markdown }
+}
+
+/// Whether the thread should hear about a patch. The answer, and a question
+/// only a person can unblock, are news the pending reply withheld; the
+/// spinner coming back is not.
+const fn patch_policy(outcome: &ReplyOutcome) -> PatchMessageNotificationPolicy {
+ match outcome {
+ ReplyOutcome::Answered(_)
+ | ReplyOutcome::Empty
+ | ReplyOutcome::Cancelled
+ | ReplyOutcome::Failed
+ | ReplyOutcome::NeedsInput { .. } => PatchMessageNotificationPolicy::NotifyAsPostedMessage,
+ ReplyOutcome::Resumed => PatchMessageNotificationPolicy::Default,
+ }
+}
+
/// Describe the missing setup; Lexical owns the message and chip serialization.
fn connection_prompt(blocker: SessionBlocker) -> AgentConnectionPrompt {
let (agent_tag, message, app_slug, name) = match blocker {
@@ -106,28 +182,53 @@ impl<Access> MessageAnnouncer<Access> {
}
}
+impl<Access: EntityAccessService> MessageAnnouncer<Access> {
+ /// The bot's capability to write into `parent`, minted on the invoking
+ /// user's current one: an author who may no longer write there gets
+ /// nothing posted or patched in their name.
+ async fn bot_write(
+ &self,
+ bot_id: BotId,
+ user: MacroUserIdStr<'static>,
+ parent: &MessageParent,
+ ) -> Result<EntityAccessReceipt<MessageWrite>> {
+ self.access
+ .generate_bot_entity_access_receipt::<MessageWrite>(
+ bot_id,
+ BotAccessScope::user(user),
+ &parent.entity_id(),
+ parent.access_entity_type(),
+ )
+ .await
+ .map_err(|error| HarnessError::Announce(rootcause::report!(error).into()))
+ }
+}
+
impl<Access: EntityAccessService> SessionAnnouncer for MessageAnnouncer<Access> {
async fn announce(&self, announcement: SessionAnnouncement) -> Result<AnnouncedMessage> {
- // Minted on the invoking user's current capability: an author who
- // may no longer write to the parent gets no chip posted for them.
let access = self
- .access
- .generate_bot_entity_access_receipt::<MessageWrite>(
+ .bot_write(
announcement.bot_id,
- BotAccessScope::user(announcement.triggered_by.clone()),
- &announcement.origin_parent.entity_id(),
- announcement.origin_parent.access_entity_type(),
- )
- .await
- .map_err(|error| HarnessError::Announce(rootcause::report!(error).into()))?;
- let content = self
- .lexical
- .compose_agent_announcement(
- &announcement_reply_target(&announcement),
- &announcement_chip(&announcement),
+ announcement.triggered_by.clone(),
+ &announcement.origin_parent,
)
- .await
- .map_err(|error| HarnessError::Announce(rootcause::report!(error).into()))?;
+ .await?;
+ let content = if announcement.kind.is_coding() {
+ self.lexical
+ .compose_agent_announcement(
+ &announcement_reply_target(&announcement),
+ &announcement_chip(&announcement),
+ )
+ .await
+ } else {
+ self.lexical
+ .compose_agent_chat_reply(&chat_reply(
+ announcement.session_id,
+ AgentChatReplyBody::Pending,
+ ))
+ .await
+ }
+ .map_err(|error| HarnessError::Announce(rootcause::report!(error).into()))?;
let posted = self
.messages
.post(
@@ -135,9 +236,11 @@ impl<Access: EntityAccessService> SessionAnnouncer for MessageAnnouncer<Access>
PostMessage {
id: None,
attribution: MessageAttribution::ActingUser,
- // The chip is a pointer, not news: the thread hears
- // about the session when it finishes or asks, through
- // the lifecycle notifications, not when it boots.
+ // Neither shape is news yet. The chip is a pointer: the
+ // thread hears about the session when it finishes or
+ // asks, through the lifecycle notifications. The
+ // pending reply notifies when it is resolved into the
+ // answer, as the answer.
notification_policy: PostMessageNotificationPolicy::Silent,
content,
thread_id: Some(announcement.origin_thread_id),
@@ -154,17 +257,59 @@ impl<Access: EntityAccessService> SessionAnnouncer for MessageAnnouncer<Access>
})
}
- async fn decline(&self, declined: DeclinedMention) -> Result<()> {
+ async fn resolve(&self, resolution: ResolvedReply) -> Result<()> {
+ if resolution.kind.is_coding() {
+ return Ok(());
+ }
let access = self
- .access
- .generate_bot_entity_access_receipt::<MessageWrite>(
- declined.bot_id,
- BotAccessScope::user(declined.triggered_by),
- &declined.origin.parent.entity_id(),
- declined.origin.parent.access_entity_type(),
+ .bot_write(
+ resolution.bot_id,
+ resolution.triggered_by,
+ &resolution.origin_parent,
)
+ .await?;
+ let message_id = resolution.message_id;
+ let notification_policy = patch_policy(&resolution.outcome);
+ let content = self
+ .lexical
+ .compose_agent_chat_reply(&chat_reply(
+ resolution.session_id,
+ reply_body(resolution.outcome),
+ ))
.await
.map_err(|error| HarnessError::Announce(rootcause::report!(error).into()))?;
+ match self
+ .messages
+ .patch(
+ access,
+ message_id,
+ MessagePatch {
+ notification_policy,
+ content: Some(content),
+ ..Default::default()
+ },
+ )
+ .await
+ {
+ Ok(_) => Ok(()),
+ // A participant deleted the pending reply while the agent ran:
+ // they did not want the answer, and there is nowhere to put it.
+ Err(MessageError::NotFound) => {
+ tracing::info!(%message_id, "pending reply was deleted; dropping the answer");
+ Ok(())
+ }
+ Err(error) => Err(HarnessError::Announce(rootcause::report!(error).into())),
+ }
+ }
+
+ async fn decline(&self, declined: DeclinedMention) -> Result<()> {
+ let access = self
+ .bot_write(
+ declined.bot_id,
+ declined.triggered_by,
+ &declined.origin.parent,
+ )
+ .await?;
let content = self
.lexical
.compose_agent_connection_prompt(&connection_prompt(declined.blocker))
diff --git a/crates/agent_harness/src/outbound/channel_announcer/test.rs b/crates/agent_harness/src/outbound/channel_announcer/test.rs
index 98092413e3..5fb766191c 100644
--- a/crates/agent_harness/src/outbound/channel_announcer/test.rs
+++ b/crates/agent_harness/src/outbound/channel_announcer/test.rs
@@ -7,6 +7,7 @@ use bot_id::BotId;
fn announcement() -> SessionAnnouncement {
SessionAnnouncement {
bot_id: BotId::TEST_A,
+ kind: crate::domain::model::AgentKind::SandboxedCoder,
session_id: agent_session::domain::model::AgentSessionId::TEST_A,
origin_parent: MessageParent::Channel(Uuid::from_u128(1)),
origin_thread_id: Uuid::from_u128(2),
@@ -75,3 +76,130 @@ fn reply_target_carries_the_originating_channel_message() {
}
);
}
+
+const SESSION: agent_session::domain::model::AgentSessionId =
+ agent_session::domain::model::AgentSessionId::TEST_A;
+
+/// Everything the reply can say, in every state the domain can ask for.
+fn every_outcome() -> Vec<ReplyOutcome> {
+ vec![
+ ReplyOutcome::Answered("Sure.".to_owned()),
+ ReplyOutcome::Empty,
+ ReplyOutcome::Cancelled,
+ ReplyOutcome::Failed,
+ ReplyOutcome::NeedsInput {
+ question: "Which inbox?".to_owned(),
+ },
+ ReplyOutcome::Resumed,
+ ]
+}
+
+fn markdown(body: AgentChatReplyBody) -> String {
+ match body {
+ AgentChatReplyBody::Markdown { markdown } => markdown,
+ AgentChatReplyBody::Pending => panic!("expected prose, got the spinner"),
+ }
+}
+
+/// A patch replaces the content wholesale, so a link only the pending
+/// reply carried would vanish with the spinner. Every state asks Lexical
+/// for the same session link ahead of its body.
+#[test]
+fn every_reply_names_its_session() {
+ for outcome in every_outcome() {
+ let reply = chat_reply(SESSION, reply_body(outcome.clone()));
+ assert_eq!(reply.session_id, SESSION.to_string(), "{outcome:?}");
+ }
+ assert_eq!(
+ chat_reply(SESSION, AgentChatReplyBody::Pending),
+ AgentChatReply {
+ session_id: "00000000-0000-0000-0000-00000000000a".to_owned(),
+ body: AgentChatReplyBody::Pending,
+ }
+ );
+}
+
+/// The wire shape the lexical service validates: `kind` tags the body.
+#[test]
+fn the_reply_serializes_as_the_endpoint_reads_it() {
+ let pending = serde_json::to_value(chat_reply(SESSION, AgentChatReplyBody::Pending)).unwrap();
+ assert_eq!(
+ pending,
+ serde_json::json!({
+ "sessionId": "00000000-0000-0000-0000-00000000000a",
+ "body": { "kind": "pending" }
+ })
+ );
+ let answered = serde_json::to_value(chat_reply(
+ SESSION,
+ reply_body(ReplyOutcome::Answered("Sure.".to_owned())),
+ ))
+ .unwrap();
+ assert_eq!(
+ answered["body"],
+ serde_json::json!({ "kind": "markdown", "markdown": "Sure." })
+ );
+}
+
+/// The answer goes out as the agent wrote it.
+#[test]
+fn an_answer_is_posted_as_written() {
+ assert_eq!(
+ reply_body(ReplyOutcome::Answered("Sure.\n\n- done".to_owned())),
+ AgentChatReplyBody::Markdown {
+ markdown: "Sure.\n\n- done".to_owned()
+ }
+ );
+}
+
+#[test]
+fn a_resolved_reply_is_never_blank() {
+ for outcome in every_outcome() {
+ if outcome == ReplyOutcome::Resumed {
+ continue;
+ }
+ assert!(
+ !markdown(reply_body(outcome.clone())).trim().is_empty(),
+ "{outcome:?}"
+ );
+ }
+ assert_ne!(
+ reply_body(ReplyOutcome::Failed),
+ reply_body(ReplyOutcome::Empty),
+ "an error and a silence read differently"
+ );
+}
+
+/// The thread cannot answer the question; the reply says where it can be
+/// answered and what it is.
+#[test]
+fn a_waiting_reply_shows_the_question_and_points_at_the_session() {
+ let content = markdown(reply_body(ReplyOutcome::NeedsInput {
+ question: "Which inbox should I send from?".to_owned(),
+ }));
+ assert!(content.contains("Which inbox should I send from?"));
+ assert!(content.contains("open the agent session"), "{content}");
+}
+
+/// Once the question is cleared the turn is running again, and the reply
+/// looks exactly as it did when it was posted.
+#[test]
+fn a_resumed_reply_is_the_pending_reply_again() {
+ assert_eq!(
+ reply_body(ReplyOutcome::Resumed),
+ AgentChatReplyBody::Pending
+ );
+}
+
+/// The answer and a question are news; the spinner coming back is not.
+#[test]
+fn only_the_spinner_returning_is_a_silent_patch() {
+ for outcome in every_outcome() {
+ let expected = if outcome == ReplyOutcome::Resumed {
+ PatchMessageNotificationPolicy::Default
+ } else {
+ PatchMessageNotificationPolicy::NotifyAsPostedMessage
+ };
+ assert_eq!(patch_policy(&outcome), expected, "{outcome:?}");
+ }
+}
diff --git a/crates/agent_harness/src/outbound/notifications/test.rs b/crates/agent_harness/src/outbound/notifications/test.rs
index 524010ec54..ddb3b4537f 100644
--- a/crates/agent_harness/src/outbound/notifications/test.rs
+++ b/crates/agent_harness/src/outbound/notifications/test.rs
@@ -14,6 +14,7 @@ use rootcause::Report;
use serde::Serialize;
use super::IngressAgentSessionNotifier;
+use crate::domain::model::AgentKind;
use crate::domain::notifications::plan;
use crate::domain::ports::AgentSessionNotifier;
@@ -75,7 +76,7 @@ async fn a_planned_notification_becomes_an_ingress_request() {
let ingress = Arc::new(RecordingIngress::default());
let notifier = IngressAgentSessionNotifier::new(Arc::clone(&ingress));
- for notification in plan(&settled()) {
+ for notification in plan(&settled(), AgentKind::SandboxedCoder) {
notifier.notify(notification).await;
}
@@ -101,7 +102,7 @@ async fn an_ingress_failure_is_swallowed() {
});
let notifier = IngressAgentSessionNotifier::new(ingress);
- for notification in plan(&settled()) {
+ for notification in plan(&settled(), AgentKind::SandboxedCoder) {
notifier.notify(notification).await;
}
}
diff --git a/crates/agent_harness/src/testing/helpers/announcer.rs b/crates/agent_harness/src/testing/helpers/announcer.rs
index b271cde1cf..67bb2eceb2 100644
--- a/crates/agent_harness/src/testing/helpers/announcer.rs
+++ b/crates/agent_harness/src/testing/helpers/announcer.rs
@@ -3,7 +3,7 @@
use std::sync::{Arc, Mutex};
use crate::domain::error::{HarnessError, Result};
-use crate::domain::model::{AnnouncedMessage, DeclinedMention, SessionAnnouncement};
+use crate::domain::model::{AnnouncedMessage, DeclinedMention, ResolvedReply, SessionAnnouncement};
use crate::domain::ports::SessionAnnouncer;
/// A [`SessionAnnouncer`] that records instead of posting. Cloning shares one
@@ -12,6 +12,7 @@ use crate::domain::ports::SessionAnnouncer;
pub struct AnnouncerMock {
announced: Arc<Mutex<Vec<(SessionAnnouncement, AnnouncedMessage)>>>,
declined: Arc<Mutex<Vec<DeclinedMention>>>,
+ resolved: Arc<Mutex<Vec<ResolvedReply>>>,
/// When set, every announce fails with this message.
failure: Arc<Mutex<Option<String>>>,
}
@@ -52,6 +53,16 @@ impl AnnouncerMock {
.clone()
}
+ /// Every reply resolved, in order - for a coding kind too, since
+ /// deciding that there is nothing to patch is the real adapter's job.
+ #[must_use]
+ pub fn resolved(&self) -> Vec<ResolvedReply> {
+ self.resolved
+ .lock()
+ .expect("announcer mock resolved lock should not be poisoned")
+ .clone()
+ }
+
/// The message each recorded announcement became, in order.
#[must_use]
pub fn announced_messages(&self) -> Vec<AnnouncedMessage> {
@@ -85,6 +96,22 @@ impl SessionAnnouncer for AnnouncerMock {
Ok(message)
}
+ async fn resolve(&self, resolution: ResolvedReply) -> Result<()> {
+ if let Some(message) = self
+ .failure
+ .lock()
+ .expect("announcer mock failure lock should not be poisoned")
+ .clone()
+ {
+ return Err(HarnessError::Announce(rootcause::report!("{message}")));
+ }
+ self.resolved
+ .lock()
+ .expect("announcer mock resolved lock should not be poisoned")
+ .push(resolution);
+ Ok(())
+ }
+
async fn decline(&self, declined: DeclinedMention) -> Result<()> {
if let Some(message) = self
.failure
diff --git a/crates/email/src/inbound/toolset.rs b/crates/email/src/inbound/toolset.rs
index b7af965d1e..3a463e21f5 100644
--- a/crates/email/src/inbound/toolset.rs
+++ b/crates/email/src/inbound/toolset.rs
@@ -3,6 +3,7 @@
mod get_thread;
mod list_inboxes;
mod list_labels;
+mod send_confirmed_email;
mod send_email;
mod set_sender_policy;
mod update_thread_labels;
@@ -24,6 +25,7 @@ use std::sync::Arc;
pub use get_thread::{GetThread, GetThreadResponse};
pub use list_inboxes::{ListInboxes, ListInboxesResponse, ToolInbox};
pub use list_labels::{ListLabels, ListLabelsResponse, ToolLabel};
+pub use send_confirmed_email::SendConfirmedEmail;
pub use send_email::{SendEmail, SendEmailResponse};
pub use set_sender_policy::{SetSenderPolicy, SetSenderPolicyResponse, ToolSenderPolicy};
pub use update_thread_labels::{UpdateThreadLabels, UpdateThreadLabelsResponse};
@@ -209,19 +211,27 @@ fn decode_composer_html(body: &str) -> Option<String> {
decoded.trim_start().starts_with('<').then_some(decoded)
}
-/// Create the full email toolset including SendEmail.
+/// The full email toolset, for hosts that finish user tools: the deferring
+/// `SendEmail`, which a composer or review card confirms, beside
+/// `SendConfirmedEmail`, which sends on a confirmation the user already
+/// gave in conversation. Both are always registered; the prompt decides
+/// which fits the surface the prompt came from.
pub fn email_toolset<T, G, E>() -> AsyncToolCollection<EmailToolContext<T, G, E>>
where
T: EmailService,
G: GmailTokenProvider,
E: EntityAccessService,
{
- mcp_toolset().add_user_tool::<SendEmail, EmailToolContext<T, G, E>>()
+ mcp_toolset()
+ .add_user_tool::<SendEmail, EmailToolContext<T, G, E>>()
+ .add_tool::<SendConfirmedEmail, EmailToolContext<T, G, E>>()
}
/// Email toolset for hosts without a composer (the MCP server and the
-/// channel-mention bot) — excludes SendEmail, whose draft only the chat
-/// frontend can review and send.
+/// channel-mention bot) — excludes both sending tools: `SendEmail`'s draft
+/// only a composer can review and send, and `SendConfirmedEmail` is for the
+/// in-process agent's conversation turns, not for MCP clients with their
+/// own confirmation policy.
pub fn mcp_toolset<T, G, E>() -> AsyncToolCollection<EmailToolContext<T, G, E>>
where
T: EmailService,
diff --git a/crates/email/src/inbound/toolset/send_confirmed_email.rs b/crates/email/src/inbound/toolset/send_confirmed_email.rs
new file mode 100644
index 0000000000..7c60099d74
--- /dev/null
+++ b/crates/email/src/inbound/toolset/send_confirmed_email.rs
@@ -0,0 +1,90 @@
+//! `SendConfirmedEmail`: [`SendEmail`] without the review, for a host that
+//! has nothing to review in.
+//!
+//! `SendEmail` defers: it returns `PendingUserExecution` and a host finishes
+//! it - the chat composer after the turn, or a review-card elicitation in an
+//! agent-session turn. A prompt read out of a channel or document thread has
+//! neither surface, so the agent asks in prose there, the user answers in the
+//! thread, and this tool sends on that answer. Every host gets both tools;
+//! the prompt, not the toolset, says which to reach for.
+//!
+//! The email is always floated first. Being told to send one is a request to
+//! draft it, not permission to send it, so the agent writes the email into
+//! the thread and stops; only the user's reply to that draft authorizes the
+//! send. An instruction detailed enough to send from is still only a draft
+//! request - the point is that nothing leaves before the user has seen it.
+//!
+//! The gate is `userConfirmation`: the model must quote that approving reply
+//! to call this. That is a cheap first pass, deliberately - it makes the
+//! model produce evidence rather than send silently, and the requirement is
+//! self-documenting in the schema - but nothing here checks the quote against
+//! the thread, so it is not a guarantee. Session-scoped proposal state that
+//! could verify it was considered and deferred.
+
+use ai_toolset::{
+ AsyncTool, RequestContext, ServiceContext, ToolAnnotated, ToolAnnotations, ToolCallError,
+ ToolResult,
+};
+use async_trait::async_trait;
+use entity_access::domain::ports::EntityAccessService;
+use schemars::JsonSchema;
+use serde::Deserialize;
+
+use super::EmailToolContext;
+use super::send_email::{SendEmail, SendEmailResponse};
+use crate::domain::ports::{EmailService, GmailTokenProvider};
+
+/// Send an email the user has already approved in conversation.
+///
+/// The fields are [`SendEmail`]'s, flattened, plus the confirmation; the
+/// sending is [`SendEmail`]'s too. The two tools differ in whether a host
+/// reviews the call, not in what a send is.
+#[derive(Debug, Deserialize, JsonSchema, Clone)]
+#[schemars(
+ title = "SendConfirmedEmail",
+ description = "Send an email immediately, with no review card or composer. Only for a prompt that came from a channel or document thread (the context block says so), where there is nothing to review a draft in. The email is always shown before it is sent, even when the user's request already spelled the whole thing out: in one turn write it into the thread - recipients, subject, body - ask whether to send it, and stop there. Call this tool only in a later turn, once the user has replied approving that specific email, quoting that reply verbatim in userConfirmation. Being asked to send an email is a request to draft one, never approval to send it, so a userConfirmation quoting the request that asked you to write the email - rather than the reply approving the one you wrote - is wrong. Never call it in the agent session view or in chat: use SendEmail there, whose review card or composer is the confirmation. Takes the same fields as SendEmail; write the body in Markdown, which is rendered to HTML on send."
+)]
+#[serde(rename_all = "camelCase")]
+pub struct SendConfirmedEmail {
+ /// The email, exactly as `SendEmail` takes it.
+ #[serde(flatten)]
+ pub email: SendEmail,
+ /// The user's own words approving this send.
+ #[schemars(
+ description = "The user's own message approving this specific email, quoted verbatim - for example their \"yes, send it\" in reply to the email you wrote out for them. It is a reply to your draft, never the earlier request that asked you to write one: if the user has not yet seen this email, there is nothing to quote here and the tool must not be called. Required: do not paraphrase it, and never supply it yourself."
+ )]
+ pub user_confirmation: String,
+}
+
+impl ToolAnnotated for SendConfirmedEmail {
+ const ANNOTATIONS: ToolAnnotations =
+ ToolAnnotations::destructive("Send confirmed email").with_open_world();
+}
+
+#[async_trait]
+impl<T, G, E> AsyncTool<EmailToolContext<T, G, E>> for SendConfirmedEmail
+where
+ T: EmailService,
+ G: GmailTokenProvider,
+ E: EntityAccessService,
+{
+ type Output = SendEmailResponse;
+
+ #[tracing::instrument(skip_all, fields(user_id=?request_context.user_id), err)]
+ async fn call(
+ &self,
+ service_context: ServiceContext<EmailToolContext<T, G, E>>,
+ request_context: RequestContext,
+ ) -> ToolResult<Self::Output> {
+ // The schema makes the field required, so a call gets here with one;
+ // a blank one is the model going through the motions, and is refused
+ // the same way a missing one would be.
+ if self.user_confirmation.trim().is_empty() {
+ return Err(ToolCallError {
+ description: "SendConfirmedEmail requires the user's own message approving this email in userConfirmation. Describe the email in prose, ask whether to send it, and call this tool only after they say yes.".to_owned(),
+ internal_error: anyhow::anyhow!("SendConfirmedEmail called without a confirmation"),
+ });
+ }
+ self.email.call(service_context, request_context).await
+ }
+}
diff --git a/crates/email/src/inbound/toolset/send_email.rs b/crates/email/src/inbound/toolset/send_email.rs
index b2968e967c..e0de1039c4 100644
--- a/crates/email/src/inbound/toolset/send_email.rs
+++ b/crates/email/src/inbound/toolset/send_email.rs
@@ -40,7 +40,7 @@ impl From<EmailRecipient> for ContactInfo {
#[derive(Debug, Deserialize, JsonSchema, Clone)]
#[schemars(
title = "SendEmail",
- description = "Draft, compose, and send an email. ALWAYS use this tool whenever the user asks you to draft, write, compose, or send an email (or reply to one) — never write the email as plain text in the chat. This tool opens the email draft in the composer for the user to review, edit, and confirm before it is sent, so it is the correct tool even when the user only wants a draft. To reply to an existing message, provide the replying_to_id. Write the body in Markdown — use **bold**, *italics*, lists, links, and other standard Markdown formatting. The draft composer renders the Markdown for the user to review and edit; the composer produces HTML that is sent as the actual email body."
+ description = "Draft, compose, and send an email the user confirms in a review card or composer. Use this tool whenever the user asks you to draft, write, compose, or send an email (or reply to one) from the agent session view or from chat — never write the email as plain text there. It opens the draft for the user to review, edit, and confirm before it is sent, so it is the correct tool even when the user only wants a draft. Do NOT use it for a prompt that came from a channel or document thread — the context block names a conversation parent when it did, and there is no surface to review a draft in: write the email out in your reply, ask whether to send it, and use SendConfirmedEmail once the user approves. To reply to an existing message, provide the replying_to_id. Write the body in Markdown — use **bold**, *italics*, lists, links, and other standard Markdown formatting. The draft composer renders the Markdown for the user to review and edit; the composer produces HTML that is sent as the actual email body."
)]
#[serde(rename_all = "camelCase")]
pub struct SendEmail {
@@ -111,8 +111,6 @@ where
service_context: ServiceContext<EmailToolContext<T, G, E>>,
request_context: RequestContext,
) -> ToolResult<Self::Output> {
- println!("CALL SEND EMAIL {:?}", request_context);
-
let acting_user = MacroUserIdStr((*request_context.user_id).clone());
let link = service_context.resolve_link(acting_user.clone()).await?;
diff --git a/crates/email/src/inbound/toolset/test.rs b/crates/email/src/inbound/toolset/test.rs
index 1fce59b6c4..f927ee42c8 100644
--- a/crates/email/src/inbound/toolset/test.rs
+++ b/crates/email/src/inbound/toolset/test.rs
@@ -83,6 +83,44 @@ fn test_send_email_schema_validation() {
);
}
+/// The confirmed variant takes exactly `SendEmail`'s fields plus the
+/// confirmation, and the confirmation is required: the schema is the gate.
+#[test]
+fn send_confirmed_email_is_send_email_plus_a_required_confirmation() {
+ let confirmed = generate_validated_input_schema::<SendConfirmedEmail>().unwrap();
+ let plain = generate_validated_input_schema::<SendEmail>().unwrap();
+ assert_eq!(confirmed.name, "SendConfirmedEmail");
+ assert!(
+ confirmed.description.contains("userConfirmation"),
+ "{}",
+ confirmed.description
+ );
+
+ let confirmed = confirmed.schema.to_value();
+ let plain = plain.schema.to_value();
+ let properties = |schema: &serde_json::Value| {
+ let mut names: Vec<String> = schema["properties"]
+ .as_object()
+ .expect("an object schema")
+ .keys()
+ .cloned()
+ .collect();
+ names.sort();
+ names
+ };
+ let mut expected = properties(&plain);
+ expected.push("userConfirmation".to_owned());
+ expected.sort();
+ assert_eq!(properties(&confirmed), expected);
+ assert!(
+ confirmed["required"]
+ .as_array()
+ .expect("required is an array")
+ .contains(&serde_json::json!("userConfirmation")),
+ "{confirmed:#}"
+ );
+}
+
#[test]
fn test_get_thread_schema_validation() {
let result = generate_validated_input_schema::<GetThread>();
diff --git a/crates/lexical_client/src/parse_markdown.rs b/crates/lexical_client/src/parse_markdown.rs
index 935fceedb2..0c079bf6c9 100644
--- a/crates/lexical_client/src/parse_markdown.rs
+++ b/crates/lexical_client/src/parse_markdown.rs
@@ -210,6 +210,36 @@ struct AgentConnectionPromptRequest<'a> {
connection_prompt: &'a AgentConnectionPrompt,
}
+/// What a chat agent's thread message says below its session link, in the
+/// shape the lexical service `/agent-announcement` endpoint validates.
+#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
+#[serde(tag = "kind", rename_all = "camelCase")]
+pub enum AgentChatReplyBody {
+ /// The spinner while the turn runs.
+ Pending,
+ /// Prose, posted as written: the answer, or what the harness says for a
+ /// turn that answered with nothing or stopped to ask.
+ Markdown {
+ /// The prose, as channel markdown.
+ markdown: String,
+ },
+}
+
+/// A chat agent's thread message in one of its states.
+#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct AgentChatReply {
+ /// Session the message speaks for; linked ahead of the body.
+ pub session_id: String,
+ pub body: AgentChatReplyBody,
+}
+
+#[derive(serde::Serialize)]
+#[serde(rename_all = "camelCase")]
+struct AgentChatReplyRequest<'a> {
+ chat_reply: &'a AgentChatReply,
+}
+
/// A channel message included as context for an agent prompt.
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]
pub struct AgentContextMessage<'a> {
@@ -551,6 +581,24 @@ impl LexicalClient {
Ok(data.markdown)
}
+ /// Compose a chat agent's thread message - its session link over the
+ /// spinner or its prose - through the lexical service's real nodes.
+ #[tracing::instrument(skip(self, reply), err)]
+ pub async fn compose_agent_chat_reply(&self, reply: &AgentChatReply) -> Result<String> {
+ let url = format!("{}/agent-announcement", self.url);
+ let response = check_response(
+ self.client
+ .post(&url)
+ .json(&AgentChatReplyRequest { chat_reply: reply })
+ .send()
+ .await?,
+ )
+ .await?;
+ let data: AgentAnnouncementResponse =
+ response.json().await.context("unexpected response")?;
+ Ok(data.markdown)
+ }
+
/// Sanitizes an agent prompt and optionally composes it with the comment
/// anchor and prior-message context via the lexical service, so internal
/// nodes and escaping are handled by Lexical rather than by the caller.
diff --git a/crates/prompt/src/lib.rs b/crates/prompt/src/lib.rs
index ee6cba437d..ba31cb45a5 100644
--- a/crates/prompt/src/lib.rs
+++ b/crates/prompt/src/lib.rs
@@ -192,6 +192,45 @@ mod tests {
assert!(session.contains("do not ask for confirmation in prose"));
}
+ #[test]
+ fn session_tool_use_prompt_routes_thread_prompts_to_prose_and_the_confirmed_send() {
+ // A prompt read out of a channel or document thread has no review
+ // card anyone is watching: the model asks in the thread, then sends
+ // on the user's reply through SendConfirmedEmail, quoting it.
+ let session = SESSION_TOOL_USE_PROMPT.to_string();
+ assert!(session.contains("channel or document thread"));
+ assert!(session.contains("context block names a conversation parent"));
+ assert!(session.contains("`SendConfirmedEmail`"));
+ assert!(session.contains("quoted verbatim"));
+ assert!(session.contains("`userConfirmation`"));
+ assert!(session.contains("`AskUser`"));
+ assert!(session.contains("`SendConfirmedEmail` is never right here"));
+
+ // The thread rule is to restate what the tool would have done, whole,
+ // so the user can approve it without opening the session - and it
+ // covers every user tool, not just email.
+ assert!(session.contains("written out verbatim"));
+ assert!(session.contains("the whole calendar event"));
+
+ // Which prompt is being answered decides it, not the session.
+ assert!(session.contains("decided per"));
+ }
+
+ #[test]
+ fn chat_prompt_names_the_confirmed_send_only_to_rule_it_out() {
+ // The chat host has the same toolset and a composer, so the direct
+ // tool is visible there and must be steered away from; the direct
+ // prompt's hosts do not register it and say nothing about it.
+ let chat = TOOL_USE_PROMPT.to_string();
+ assert!(chat.contains("`SendConfirmedEmail`"));
+ assert!(chat.contains("never use it here"));
+ assert!(
+ !DIRECT_TOOL_USE_PROMPT
+ .to_string()
+ .contains("SendConfirmedEmail")
+ );
+ }
+
#[test]
fn tool_use_prompt_also_carries_document_content_link_rules() {
// The in-app prompt should keep the same guidance so behavior doesn't
diff --git a/crates/prompt/src/user_tools.rs b/crates/prompt/src/user_tools.rs
index 9ef626da12..e5978d536c 100644
--- a/crates/prompt/src/user_tools.rs
+++ b/crates/prompt/src/user_tools.rs
@@ -7,6 +7,13 @@
//! returns the outcome ([`SESSION_PROMPT`]). Hosts without either surface
//! (the channel-mention bot, MCP) get toolsets where those tools execute
//! directly or are absent, and neither section applies.
+//!
+//! Both hosts also carry `SendConfirmedEmail`, which sends with no review at
+//! all. It exists for the one surface an agent session reads prompts from
+//! that has nothing to review in - a channel or document thread - and the
+//! toolset is the same everywhere, so each section says when it is the right
+//! tool: in the session prompt, when the context block names a thread as the
+//! prompt's origin; in chat, never.
use crate::types::StaticPrompt;
@@ -22,28 +29,54 @@ static INSTRUCTIONS: &str = r##"- User tools are tools that must be executed by
edit, and send — writing the email inline in chat does none of that and is wrong. Drafting and
sending are the same tool: it always creates a draft for the user to confirm before anything is
sent, so use it even when the user only wants a draft.
+
+- `SendConfirmedEmail` sends immediately, with no composer. It is for conversation threads that
+ have no composer, and this chat does, so never use it here: `SendEmail` and its composer are how
+ the user confirms an email in chat.
"##;
static INTENT: &str = "The model treats user tools as composer-confirmed: a PendingUserExecution \
result means the user still has to finish the call, and email drafting or sending always goes \
-through the SendEmail tool rather than inline text in the chat.";
+through the SendEmail tool rather than inline text in the chat - never through SendConfirmedEmail, \
+which is for surfaces without a composer.";
/// The user-tools prompt section for composer-capable chat hosts.
pub static PROMPT: StaticPrompt<'static> = StaticPrompt::borrowed(TITLE, INSTRUCTIONS, INTENT);
-static SESSION_INSTRUCTIONS: &str = r##"- `SendEmail` and `CreateCalendarEvent` are reviewed by the user before they run. Calling one opens a review card in the session, the turn waits while the user edits, confirms or declines, and the tool then returns what happened: the sent email or created event, or "Rejected". Nothing is pending afterwards and there is no chat composer; do not tell the user to confirm anything, and do not ask for confirmation in prose before calling the tool - the review card is the confirmation.
+static SESSION_INSTRUCTIONS: &str = r##"- Before reaching for `SendEmail` or `CreateCalendarEvent`, look at where the newest prompt came
+ from. The context block names a conversation parent when that prompt was posted in a
+ channel or document thread instead of typed in the agent session view. It is decided per
+ prompt, not per session: the same session can be driven from both places, so check the
+ prompt you are answering now.
-- IMPORTANT: When the user asks you to draft, write, compose, or send an email (or reply to one),
- you MUST use the `SendEmail` tool to produce it. NEVER write the email body as plain text in your
- reply. The review card is a real email composer the user can edit before it sends; inline text
- does none of that and is wrong. Drafting and sending are the same tool: the user decides in the
- card whether it goes out.
+- From a thread, nobody is looking at the session. A review card would wait unseen and `AskUser`
+ would ask a question nobody sees, so use neither. State what the tool would have done, in full,
+ in your reply - the whole email with its recipients, subject and body; the whole calendar event
+ with its title, time and guests; whatever it is, written out verbatim so the user can check it
+ without opening anything - then ask whether to go ahead, and end your turn. When the user
+ replies approving it, call `SendConfirmedEmail` with that same email and their approving message
+ quoted verbatim in `userConfirmation`. Never call it without such a reply, and never paraphrase
+ or invent one.
+
+- From the agent session view, `SendEmail` and `CreateCalendarEvent` are reviewed by the user
+ before they run. Calling one opens a review card in the session, the turn waits while the user
+ edits, confirms or declines, and the tool then returns what happened: the sent email or created
+ event, or "Rejected". Nothing is pending afterwards and there is no chat composer; do not tell
+ the user to confirm anything, and do not ask for confirmation in prose before calling the tool -
+ the review card is the confirmation. `SendConfirmedEmail` is never right here.
+
+- IMPORTANT: When the user asks you to draft, write, compose, or send an email (or reply to one)
+ from the session view, you MUST use the `SendEmail` tool to produce it. NEVER write the email
+ body as plain text in your reply. The review card is a real email composer the user can edit
+ before it sends; inline text does none of that and is wrong. Drafting and sending are the same
+ tool: the user decides in the card whether it goes out.
"##;
-static SESSION_INTENT: &str = "The model treats user tools as reviewed in the turn: the call \
-opens a review card, waits for the user, and returns the outcome - so it never describes a \
-pending composer, never asks for confirmation in prose first, and drafts or sends email through \
-SendEmail rather than inline text.";
+static SESSION_INTENT: &str = "The model checks where the newest prompt came from before using a \
+user tool: from a channel or document thread it states the whole email or event verbatim in its \
+reply, asks, and sends only on the user's approving reply through SendConfirmedEmail; from the \
+session view it calls SendEmail or CreateCalendarEvent and lets the review card be the \
+confirmation, never asking for confirmation in prose first.";
/// The user-tools prompt section for an agent session, whose in-process
/// agent finishes user tools in the turn through a review elicitation.
diff --git a/packages/lexical-core/tests/agent-chat-reply.test.ts b/packages/lexical-core/tests/agent-chat-reply.test.ts
new file mode 100644
index 0000000000..2fa2bf271f
--- /dev/null
+++ b/packages/lexical-core/tests/agent-chat-reply.test.ts
@@ -0,0 +1,70 @@
+import { describe, expect, it } from 'vitest';
+import {
+ AGENT_SESSION_LINK_LABEL,
+ composeAgentChatReply,
+ PENDING_REPLY_TEXT,
+} from '../utils/agent-chat-reply';
+import { markdownToSerializedEditorStateWithIds } from '../utils/markdown-state';
+
+const SESSION = '00000000-0000-0000-0000-00000000000a';
+const LINK = `<m-agent-session-mention>{"id":"${SESSION}","label":"${AGENT_SESSION_LINK_LABEL}"}</m-agent-session-mention>`;
+
+/** The mention and what follows it, as the channel view splits them. */
+function splitLeadingLink(markdown: string) {
+ const match =
+ /^(<m-agent-session-mention>.*?<\/m-agent-session-mention>)\n\n([\s\S]*)$/.exec(
+ markdown
+ );
+ if (!match) throw new Error(`no leading link in ${markdown}`);
+ return { link: match[1], body: match[2] };
+}
+
+describe('composeAgentChatReply', () => {
+ it('leads the pending reply with the session link, then the spinner', () => {
+ const markdown = composeAgentChatReply({
+ sessionId: SESSION,
+ body: { kind: 'pending' },
+ });
+ const { link, body } = splitLeadingLink(markdown);
+ expect(link).toBe(LINK);
+ expect(body).toMatch(/^<m-await>.*<\/m-await>$/);
+ const state = markdownToSerializedEditorStateWithIds(markdown);
+ expect(state.root.children).toMatchObject([
+ {
+ type: 'paragraph',
+ children: [{ type: 'agent-session-mention', id: SESSION }],
+ },
+ {
+ type: 'paragraph',
+ children: [{ type: 'await', text: PENDING_REPLY_TEXT, inline: true }],
+ },
+ ]);
+ });
+
+ it('appends prose as written, behind its own paragraph break', () => {
+ const answer = 'Sure.\n\n- one\n- two\n\n`cargo test` passes.';
+ const markdown = composeAgentChatReply({
+ sessionId: SESSION,
+ body: { kind: 'markdown', markdown: answer },
+ });
+ expect(markdown).toBe(`${LINK}\n\n${answer}`);
+ });
+
+ it('escapes a session id that tries to close the tag', () => {
+ const markdown = composeAgentChatReply({
+ sessionId: '</m-agent-session-mention><m-user-mention>x',
+ body: { kind: 'pending' },
+ });
+ expect(markdown.match(/<m-agent-session-mention>/g)).toHaveLength(1);
+ const state = markdownToSerializedEditorStateWithIds(markdown);
+ expect(state.root.children[0]).toMatchObject({
+ type: 'paragraph',
+ children: [
+ {
+ type: 'agent-session-mention',
+ id: '</m-agent-session-mention><m-user-mention>x',
+ },
+ ],
+ });
+ });
+});
diff --git a/packages/lexical-core/tests/agent-context.test.ts b/packages/lexical-core/tests/agent-context.test.ts
index 89729aa237..641903360d 100644
--- a/packages/lexical-core/tests/agent-context.test.ts
+++ b/packages/lexical-core/tests/agent-context.test.ts
@@ -157,11 +157,11 @@ describe('composeAgentContextPrompt', () => {
messages: [{ sender: 'alice', content: 'earlier message' }],
})
).toBe(
- '<m-agent-context>{"version":1,"text":"Conversation parent: {\\"type\\":\\"document\\",\\"id\\":\\"doc-1\\"}\\n\\nPrior message 1:\\nSender: alice\\nContent: earlier message"}</m-agent-context>\n\noriginal request'
+ '<m-agent-context>{"version":1,"text":"Conversation parent: {\\"type\\":\\"document\\",\\"id\\":\\"doc-1\\"}\\nOrigin: this prompt was posted in a document comment thread, not the agent session view. Your reply is posted back into that thread, and it is where the user will answer anything you ask.\\n\\nPrior message 1:\\nSender: alice\\nContent: earlier message"}</m-agent-context>\n\noriginal request'
);
});
- it('names the conversation parent even without history', () => {
+ it('names the conversation parent and its origin even without history', () => {
const composed = composeAgentContextPrompt({
promptMarkdown: 'original',
parent: { type: 'channel', id: 'channel-1' },
@@ -170,8 +170,21 @@ describe('composeAgentContextPrompt', () => {
expect(state.root.children[0]).toMatchObject({
type: 'agent-context',
- text: 'Conversation parent: {"type":"channel","id":"channel-1"}',
+ text:
+ 'Conversation parent: {"type":"channel","id":"channel-1"}\n' +
+ 'Origin: this prompt was posted in a channel thread, not the agent session view. Your reply is posted back into that thread, and it is where the user will answer anything you ask.',
+ });
+ });
+
+ it('says nothing about an origin for a prompt from the session view', () => {
+ // No parent is the session view's signature; an origin line there would
+ // tell the agent its reply lands somewhere it does not.
+ const composed = composeAgentContextPrompt({
+ promptMarkdown: 'original',
+ messages: [{ sender: 'alice', content: 'earlier' }],
});
+ expect(composed).not.toContain('Origin:');
+ expect(composed).not.toContain('Conversation parent');
});
it('names the comment anchor and the text it marked', () => {
@@ -185,7 +198,8 @@ describe('composeAgentContextPrompt', () => {
expect(state.root.children[0]).toMatchObject({
type: 'agent-context',
text:
- 'Conversation parent: {"type":"document","id":"doc-1"}\n\n' +
+ 'Conversation parent: {"type":"document","id":"doc-1"}\n' +
+ 'Origin: this prompt was posted in a document comment thread, not the agent session view. Your reply is posted back into that thread, and it is where the user will answer anything you ask.\n\n' +
'Comment anchor: {"markId":"mark-1","markedText":"the marked phrase"}\n' +
'markedText is what the mark covered when the comment was posted; the document may have changed since.',
});
diff --git a/packages/lexical-core/transformers/transformers.ts b/packages/lexical-core/transformers/transformers.ts
index 55a7b2c9b9..588d2a4bec 100644
--- a/packages/lexical-core/transformers/transformers.ts
+++ b/packages/lexical-core/transformers/transformers.ts
@@ -18,6 +18,7 @@ import type {
import {
$createLineBreakNode,
$createTextNode,
+ $isDecoratorNode,
$isParagraphNode,
type LexicalNode,
LineBreakNode,
@@ -68,7 +69,9 @@ export const PRESERVE_LINES: ConversionOnlyTransformer<ElementTransformer> = {
export: (node) => {
if ($isParagraphNode(node)) {
const content = node.getTextContent();
- if (!content.trim()) {
+ // A decorator with no text content - an await spinner, say - is still
+ // a child worth exporting, not a blank line.
+ if (!content.trim() && !node.getChildren().some($isDecoratorNode)) {
return '\n \n';
}
}
diff --git a/packages/lexical-core/utils/agent-chat-reply.ts b/packages/lexical-core/utils/agent-chat-reply.ts
new file mode 100644
index 0000000000..ececbcd42d
--- /dev/null
+++ b/packages/lexical-core/utils/agent-chat-reply.ts
@@ -0,0 +1,78 @@
+import { createHeadlessEditor } from '@lexical/headless';
+import { $convertToMarkdownString } from '@lexical/markdown';
+import { $createParagraphNode, $getRoot } from 'lexical';
+import { NodeReplacements, SupportedNodeTypes } from '../node-list';
+import { $createAgentSessionMentionNode } from '../nodes/AgentSessionMentionNode';
+import { $createAwaitNode } from '../nodes/AwaitNode';
+import { ALL_TRANSFORMERS } from '../transformers';
+
+/**
+ * What the session link reads as wherever the channel markdown is shown as
+ * text: notification excerpts, search, plain-text previews.
+ */
+export const AGENT_SESSION_LINK_LABEL = 'Agent session';
+
+/** The spinner's caption while a chat agent's turn runs. */
+export const PENDING_REPLY_TEXT = 'Thinking…';
+
+/**
+ * What a chat agent's message says below its session link: the spinner
+ * while the turn runs, or prose - the answer, a fallback the harness wrote
+ * for a turn that said nothing, a question the thread cannot answer.
+ */
+export type AgentChatReplyBody =
+ | { kind: 'pending' }
+ | { kind: 'markdown'; markdown: string };
+
+/** A chat agent's message in its thread, in one of its states. */
+export type AgentChatReply = {
+ sessionId: string;
+ body: AgentChatReplyBody;
+};
+
+/**
+ * Compose a chat agent's thread message: a link to its session as the
+ * agent-session mention node, alone in the first paragraph, then the body.
+ *
+ * The channel message view lifts a leading mention paragraph out of the body
+ * onto the sender line, which is why the link goes first and why every state
+ * of the reply carries it: a patch replaces the content wholesale, and a
+ * link only the pending reply had would vanish with the spinner.
+ *
+ * The nodes are built and serialized headlessly so the markdown is exactly
+ * what the editor's own transformers read back, escaping included. Prose is
+ * appended as written rather than round-tripped through the editor: it is
+ * the agent's answer, and normalizing it is not this function's job.
+ */
+export function composeAgentChatReply(reply: AgentChatReply): string {
+ const editor = createHeadlessEditor({
+ nodes: [...SupportedNodeTypes, ...NodeReplacements],
+ });
+ editor.update(
+ () => {
+ const root = $getRoot();
+ root.append(
+ $createParagraphNode().append(
+ $createAgentSessionMentionNode({
+ id: reply.sessionId,
+ label: AGENT_SESSION_LINK_LABEL,
+ })
+ )
+ );
+ if (reply.body.kind === 'pending') {
+ root.append(
+ $createParagraphNode().append(
+ $createAwaitNode({ text: PENDING_REPLY_TEXT, inline: true })
+ )
+ );
+ }
+ },
+ { discrete: true }
+ );
+ const chrome = editor
+ .getEditorState()
+ .read(() => $convertToMarkdownString(ALL_TRANSFORMERS));
+ return reply.body.kind === 'pending'
+ ? chrome
+ : `${chrome}\n\n${reply.body.markdown}`;
+}
diff --git a/packages/lexical-core/utils/agent-context.ts b/packages/lexical-core/utils/agent-context.ts
index 49f5fccd72..567f4cd3b2 100644
--- a/packages/lexical-core/utils/agent-context.ts
+++ b/packages/lexical-core/utils/agent-context.ts
@@ -90,6 +90,21 @@ function describeAnchor(anchor: AgentContextAnchor): string {
return `${location}\nmarkedText is what the mark covered when the comment was posted; the document may have changed since.`;
}
+/**
+ * Name the conversation a prompt came from, and that it came from there. A
+ * prompt driven from the agent session view carries no parent, so a parent
+ * is also the one signal that the reply is posted back into a thread nobody
+ * is watching the session for - which changes how the agent should ask the
+ * user anything.
+ */
+function describeParent(parent: AgentContextParent): string {
+ const surface =
+ parent.type === 'channel'
+ ? 'a channel thread'
+ : 'a document comment thread';
+ return `Conversation parent: ${JSON.stringify(parent)}\nOrigin: this prompt was posted in ${surface}, not the agent session view. Your reply is posted back into that thread, and it is where the user will answer anything you ask.`;
+}
+
function escapeAgentContextTags(markdown: string): string {
// No user-authored entity may decode into reserved syntax during import.
return markdown
@@ -128,9 +143,7 @@ export function composeAgentContextPrompt(input: AgentContextPrompt): string {
`Prior message ${index + 1}:\nSender: ${message.sender}\nContent: ${message.content}`
)
.join('\n\n');
- const location = input.parent
- ? `Conversation parent: ${JSON.stringify(input.parent)}`
- : '';
+ const location = input.parent ? describeParent(input.parent) : '';
const anchor = input.anchor ? describeAnchor(input.anchor) : '';
const context = $createAgentContextNode({
version: 1,
diff --git a/services/lexical-service/src/endpoints/agent-announcement.test.ts b/services/lexical-service/src/endpoints/agent-announcement.test.ts
index 473a52afd6..5bcf8e889c 100644
--- a/services/lexical-service/src/endpoints/agent-announcement.test.ts
+++ b/services/lexical-service/src/endpoints/agent-announcement.test.ts
@@ -73,6 +73,33 @@ describe('agent announcements', () => {
...replyTarget,
});
});
+ it('composes a chat reply as the session link over its body', async () => {
+ const link =
+ '<m-agent-session-mention>{"id":"session","label":"Agent session"}</m-agent-session-mention>';
+ const pending = await request({
+ chatReply: { sessionId: 'session', body: { kind: 'pending' } },
+ });
+ expect(pending.status).toBe(200);
+ const { markdown: spinner } = await pending.json<{ markdown: string }>();
+ expect(spinner.startsWith(`${link}\n\n<m-await>`)).toBe(true);
+ expect(spinner.endsWith('</m-await>')).toBe(true);
+ const answered = await request({
+ chatReply: {
+ sessionId: 'session',
+ body: { kind: 'markdown', markdown: 'Sure.\n\n- done' },
+ },
+ });
+ expect(await answered.json<{ markdown: string }>()).toEqual({
+ markdown: `${link}\n\nSure.\n\n- done`,
+ });
+ });
+ it('rejects a chat reply body it does not know', async () => {
+ const response = await request({
+ chatReply: { sessionId: 'session', body: { kind: 'spinner' } },
+ });
+ expect(response.status).toBeGreaterThanOrEqual(400);
+ expect(response.status).toBeLessThan(500);
+ });
it('rejects an unknown connection destination', async () => {
const response = await request({
connectionPrompt: {
diff --git a/services/lexical-service/src/endpoints/agent-announcement.ts b/services/lexical-service/src/endpoints/agent-announcement.ts
index 6b1126ff41..40931bb489 100644
--- a/services/lexical-service/src/endpoints/agent-announcement.ts
+++ b/services/lexical-service/src/endpoints/agent-announcement.ts
@@ -5,6 +5,7 @@ import {
} from '@macro-inc/lexical-core/nodes/MagicChipNode';
import type { ReplyTargetParent } from '@macro-inc/lexical-core/nodes/ReplyTargetNode';
import { composeAgentSessionAnnouncement } from '@macro-inc/lexical-core/utils/agent-announcement';
+import { composeAgentChatReply } from '@macro-inc/lexical-core/utils/agent-chat-reply';
import { composeAgentConnectionPrompt } from '@macro-inc/lexical-core/utils/agent-connection-prompt';
import { OpenAPIRoute } from 'chanfana';
import type { Context } from 'hono';
@@ -46,8 +47,24 @@ const sessionAnnouncementRequest = z.object({
}),
});
+/**
+ * A chat agent's thread message in one of its states: the spinner while its
+ * turn runs, or prose the harness patches in - the answer, a fallback for a
+ * turn that said nothing, a question only the session view can answer.
+ */
+const chatReplyRequest = z.object({
+ chatReply: z.object({
+ sessionId: z.string().min(1),
+ body: z.discriminatedUnion('kind', [
+ z.object({ kind: z.literal('pending') }),
+ z.object({ kind: z.literal('markdown'), markdown: z.string() }),
+ ]),
+ }),
+});
+
const agentAnnouncementRequest = z.union([
sessionAnnouncementRequest,
+ chatReplyRequest,
z.object({
connectionPrompt: z.object({
agentTag: z.string().min(1),
@@ -69,7 +86,7 @@ export class AgentAnnouncementEndpoint extends OpenAPIRoute {
schema = {
summary: 'Compose an agent-harness bot response',
description:
- 'Builds an agent announcement or connection prompt from structured Lexical nodes.',
+ 'Builds an agent announcement, a chat agent reply, or a connection prompt from structured Lexical nodes.',
request: {
body: {
content: {
@@ -100,6 +117,19 @@ export class AgentAnnouncementEndpoint extends OpenAPIRoute {
markdown: composeAgentConnectionPrompt(body.connectionPrompt),
});
}
+ if ('chatReply' in body) {
+ const { sessionId, body: replyBody } = body.chatReply;
+ // The schema requires a body, but the discriminated union does not
+ // survive chanfana's OpenAPI round-trip as required, so it arrives
+ // typed as optional. Refuse rather than invent a state: a reply with
+ // no body is a caller bug, and guessing one would post it to a thread.
+ if (!replyBody) {
+ throw new Error('chatReply needs a body');
+ }
+ return c.json({
+ markdown: composeAgentChatReply({ sessionId, body: replyBody }),
+ });
+ }
const { parent, channelId, ...target } = body.replyTarget;
// Callers that predate message parents send only `channelId`; the
// node itself references any parent the reply lives under.