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): add provider connection prompts and retain the Cursor rollout flag (#6510)

Wolf Mermelstein52f9dda37893
diff --git a/apps/web/src/features/channel/Input/ChannelInput.tsx b/apps/web/src/features/channel/Input/ChannelInput.tsx
index 1f3d5b6b98..bcac2e58df 100644
--- a/apps/web/src/features/channel/Input/ChannelInput.tsx
+++ b/apps/web/src/features/channel/Input/ChannelInput.tsx
@@ -1,4 +1,3 @@
-import { useCodexAgentsAccess } from '@core/codex/flag';
import { ComposerEditor } from '@core/component/LexicalMarkdown/component/ComposerEditor';
import { StaticMarkdown } from '@core/component/LexicalMarkdown/component/core/StaticMarkdown';
import { DragInsertIndicator } from '@core/component/LexicalMarkdown/component/misc/DragInsertIndicator';
@@ -13,6 +12,7 @@ import {
insertDocumentMentionAtDragCoordinates,
updateDragInsertPreviewFromCoordinates,
} from '@core/component/LexicalMarkdown/utils/dragInsertUtils';
+import { isClaudeBotId } from '@core/constant/claudeAgent';
import { isCodexBotId } from '@core/constant/codexAgent';
import { isCursorBotId } from '@core/constant/cursorAgent';
import {
@@ -31,8 +31,6 @@ import {
uploadFile,
} from '@core/util/upload';
import type { EntityData } from '@entity';
-import { useCodexStatusQuery } from '@queries/auth/codex';
-import { useCursorApiKeyStatusQuery } from '@queries/auth/cursor-api-key';
import { CollapsedInput, ComposerSurface } from '@ui';
import { $getRoot } from 'lexical';
import {
@@ -44,6 +42,7 @@ import {
Switch,
} from 'solid-js';
import {
+ claudeMentionUser,
codexMentionUser,
cursorMentionUser,
isMacroAiId,
@@ -259,30 +258,15 @@ export function ChannelInput(props: ChannelInputProps) {
};
const canUseCursor = useCursorAgentsAccess();
- const cursorApiKey = useCursorApiKeyStatusQuery();
- const canUseCodex = useCodexAgentsAccess();
- const codexStatus = useCodexStatusQuery(canUseCodex);
- // Macro AI and Macro Coder (flag-gated) are mentionable in every channel,
- // and any bot added to the channel is mentionable too. All are surfaced
- // through the same `@`-mention typeahead as participants and re-tagged as
- // bot mentions at send time.
+ // Global agents and channel bots share the participant mention typeahead.
+ // Cursor, Macro New, and Macro Coder follow their respective rollout flags.
+ // Mentions are re-tagged as bot mentions at send time.
const mentionUsers: Accessor<IUser[]> = () => {
- const cursorEnabled =
- canUseCursor() && (cursorApiKey.data?.registered ?? false);
- const codexEnabled =
- canUseCodex() &&
- codexStatus.isSuccess &&
- codexStatus.data.connected &&
- !!codexStatus.data.environmentId?.trim();
const base = [
...(props.participants?.() ?? []),
...(props.bots?.() ?? []),
- ].filter(
- (user) =>
- (cursorEnabled || !isCursorBotId(user.id)) &&
- (codexEnabled || !isCodexBotId(user.id))
- );
+ ].filter((user) => canUseCursor() || !isCursorBotId(user.id));
if (
isFeatureEnabled(enableChatV3Agents) &&
!base.some((user) => isMacroCoderId(user.id))
@@ -295,17 +279,17 @@ export function ChannelInput(props: ChannelInputProps) {
) {
base.unshift(macroNewMentionUser());
}
- if (
- cursorEnabled &&
- // Hiding it is not enforcement — a mention can still arrive from a
- // copied message or another client — so the harness refuses these too.
- !base.some((user) => isCursorBotId(user.id))
- ) {
+ // Account setup does not hide bots included in the user's rollout.
+ // Their replies link to Settings → Harness when a connection is needed.
+ if (canUseCursor() && !base.some((user) => isCursorBotId(user.id))) {
base.unshift(cursorMentionUser());
}
- if (codexEnabled && !base.some((user) => isCodexBotId(user.id))) {
+ if (!base.some((user) => isCodexBotId(user.id))) {
base.unshift(codexMentionUser());
}
+ if (!base.some((user) => isClaudeBotId(user.id))) {
+ base.unshift(claudeMentionUser());
+ }
if (!base.some((user) => isMacroAiId(user.id))) {
base.unshift(macroAiMentionUser());
}
diff --git a/apps/web/src/features/channel/Input/tests/input-slots.test.tsx b/apps/web/src/features/channel/Input/tests/input-slots.test.tsx
index c8bd531ef3..30dff3411e 100644
--- a/apps/web/src/features/channel/Input/tests/input-slots.test.tsx
+++ b/apps/web/src/features/channel/Input/tests/input-slots.test.tsx
@@ -2,6 +2,7 @@
* @vitest-environment jsdom
*/
+import type { IUser } from '@core/user/types';
import { render as renderBare, screen } from '@solidjs/testing-library';
import { QueryClient, QueryClientProvider } from '@tanstack/solid-query';
import userEvent from '@testing-library/user-event';
@@ -10,8 +11,10 @@ import { Portal } from 'solid-js/web';
import { beforeEach, describe, expect, it, vi } from 'vitest';
const editorMocks = vi.hoisted(() => ({
+ cursorEnabled: false,
clear: vi.fn(),
focus: vi.fn(),
+ mentionUsers: undefined as (() => IUser[]) | undefined,
emitChange: undefined as ((markdown: string) => void) | undefined,
}));
@@ -46,13 +49,12 @@ vi.mock('@core/util/upload', () => ({
uploadFile: vi.fn(),
}));
-vi.mock('@core/cursor/flag', () => ({
- useCursorAgentsAccess: () => () => true,
-}));
-
vi.mock('@core/codex/flag', () => ({
useCodexAgentsAccess: () => () => false,
}));
+vi.mock('@core/cursor/flag', () => ({
+ useCursorAgentsAccess: () => () => editorMocks.cursorEnabled,
+}));
// Several service clients in StaticMarkdown's import graph build websocket
// connections at module scope, which jsdom cannot do. Stub the builder so
@@ -186,7 +188,10 @@ vi.mock(
};
const builder: any = {
namespace: () => builder,
- withMentions: () => builder,
+ withMentions: (options: { users?: () => IUser[] }) => {
+ editorMocks.mentionUsers = options.users;
+ return builder;
+ },
withEmojis: () => builder,
withActions: () => builder,
withLinks: () => builder,
@@ -238,6 +243,7 @@ vi.mock('../FormatButtons', () => ({
FormatButtons: () => <div data-testid="format-buttons" />,
}));
+import { cursorMentionUser } from '../../macroAi';
import { createInputAttachmentTracker } from '../attachment-tracker';
import { ChannelInput } from '../ChannelInput';
import { DropOverlay } from '../DropOverlay';
@@ -254,12 +260,7 @@ const baseInput: InputData = {
attachments: [],
};
-/**
- * `ChannelInput` reads the stored Cursor API key status to decide whether to
- * offer `@cursor` in the mention typeahead, so it needs a query client even
- * though none of these tests care about that entry. Shadowing `render` keeps
- * every call site below unchanged.
- */
+// Provide query context for the composed input and its decorators.
const testQueryClient = new QueryClient({
defaultOptions: { queries: { retry: false } },
});
@@ -272,9 +273,32 @@ function render(ui: () => JSX.Element) {
describe('Input slots', () => {
beforeEach(() => {
+ editorMocks.cursorEnabled = false;
editorMocks.clear.mockClear();
editorMocks.focus.mockClear();
editorMocks.emitChange = undefined;
+ editorMocks.mentionUsers = undefined;
+ });
+
+ it('offers Cursor within its rollout before account setup', () => {
+ editorMocks.cursorEnabled = true;
+ render(() => <ChannelInput input={baseInput} />);
+ expect(editorMocks.mentionUsers?.().map((user) => user.name)).toEqual(
+ expect.arrayContaining(['Cursor', 'Claude', 'Codex'])
+ );
+ });
+
+ it('hides Cursor outside its rollout, including supplied bot entries', () => {
+ render(() => (
+ <ChannelInput
+ input={baseInput}
+ participants={() => [cursorMentionUser()]}
+ bots={() => [cursorMentionUser()]}
+ />
+ ));
+ const names = editorMocks.mentionUsers?.().map((user) => user.name);
+ expect(names).not.toContain('Cursor');
+ expect(names).toEqual(expect.arrayContaining(['Claude', 'Codex']));
});
it('does not start typing when the editor hydrates an empty composer', async () => {
diff --git a/apps/web/src/features/channel/macroAi.ts b/apps/web/src/features/channel/macroAi.ts
index 44a807bb97..1ab657c206 100644
--- a/apps/web/src/features/channel/macroAi.ts
+++ b/apps/web/src/features/channel/macroAi.ts
@@ -1,3 +1,7 @@
+import {
+ CLAUDE_BOT_NAME,
+ CLAUDE_BOT_PRINCIPAL_ID,
+} from '@core/constant/claudeAgent';
import {
CODEX_BOT_NAME,
CODEX_BOT_PRINCIPAL_ID,
@@ -94,3 +98,12 @@ export function codexMentionUser(): IUser {
email: CODEX_BOT_NAME,
};
}
+
+/** Claude as a bot mention, using the canonical principal identifier. */
+export function claudeMentionUser(): IUser {
+ return {
+ id: CLAUDE_BOT_PRINCIPAL_ID,
+ name: CLAUDE_BOT_NAME,
+ email: CLAUDE_BOT_NAME,
+ };
+}
diff --git a/apps/web/src/features/channel/use-channel-bot-mention-users.test.ts b/apps/web/src/features/channel/use-channel-bot-mention-users.test.ts
index 11775770c6..c0b77d9896 100644
--- a/apps/web/src/features/channel/use-channel-bot-mention-users.test.ts
+++ b/apps/web/src/features/channel/use-channel-bot-mention-users.test.ts
@@ -1,37 +1,31 @@
-const codexAccess = vi.hoisted(() => ({ enabled: true }));
-vi.mock('@core/codex/flag', () => ({
- useCodexAgentsAccess: () => () => codexAccess.enabled,
-}));
-
+import { CURSOR_BOT_ID } from '@core/constant/cursorAgent';
import type { Agent } from '@service-storage/generated/schemas/agent';
import type { Bot } from '@service-storage/generated/schemas/bot';
-import { createRoot } from 'solid-js';
+import { createRoot, createSignal } from 'solid-js';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import {
availableBotMentionUsers,
useChannelBotMentionUsers,
} from './use-channel-bot-mention-users';
-const readiness = vi.hoisted(() => ({
- connected: true,
- environmentId: null as string | null,
+const flags = vi.hoisted(() => ({ cursor: (): boolean => false }));
+vi.mock('@core/constant/featureFlags', () => ({
+ enableCursorAgents: { key: 'enable-cursor-agents' },
}));
-vi.mock('@queries/auth/codex', () => ({
- useCodexStatusQuery: () => ({ isSuccess: true, data: readiness }),
-}));
-vi.mock('@queries/auth/cursor-api-key', () => ({
- useCursorApiKeyStatusQuery: () => ({
- isSuccess: true,
- data: { registered: false },
- }),
+vi.mock('@app/lib/analytics/posthog', () => ({
+ useFeatureFlag: () => () => ({ enabled: flags.cursor() }),
}));
+
vi.mock('@queries/channel/channel-bots', () => ({
useChannelBotsQuery: () => ({ isSuccess: true, data: [] }),
}));
vi.mock('@queries/agents/agents', () => ({
useAgentsQuery: () => ({
isSuccess: true,
- data: [agent('codex-agent', 'Codex', 'all', 'codex-cloud')],
+ data: [
+ agent('codex-agent', 'Codex', 'all', 'codex-cloud'),
+ agent(CURSOR_BOT_ID, 'Cursor', 'all', 'cursor'),
+ ],
}),
}));
@@ -69,48 +63,80 @@ function agent(
describe('availableBotMentionUsers', () => {
beforeEach(() => {
- codexAccess.enabled = true;
+ flags.cursor = () => false;
});
- it('hides connected Codex agents when the rollout is disabled', () => {
- codexAccess.enabled = false;
- readiness.environmentId = 'env-saved';
+
+ it('updates Cursor mention visibility when the rollout changes', () => {
createRoot((dispose) => {
- expect(useChannelBotMentionUsers(() => 'channel-1')()).toEqual([]);
+ const [enabled, setEnabled] = createSignal(false);
+ flags.cursor = enabled;
+ const users = useChannelBotMentionUsers(() => 'channel-1');
+ expect(users().map((user) => user.id)).toEqual(['bot|codex-agent']);
+ setEnabled(true);
+ expect(users().map((user) => user.id)).toEqual([
+ 'bot|codex-agent',
+ `bot|${CURSOR_BOT_ID}`,
+ ]);
+ setEnabled(false);
+ expect(users().map((user) => user.id)).toEqual(['bot|codex-agent']);
dispose();
});
});
- it.each([null, '', ' ', 'env-saved'])(
- 'gates the real mention query on saved environment %s',
- (environmentId) => {
- readiness.environmentId = environmentId;
- createRoot((dispose) => {
- const users = useChannelBotMentionUsers(() => 'channel-1');
- expect(users().map((user) => user.id)).toEqual(
- environmentId === 'env-saved' ? ['bot|codex-agent'] : []
- );
- dispose();
- });
- }
- );
- it('hides installed Codex personas when access is disabled', () => {
- const codex = agent('codex-agent', 'Codex', 'selected', 'codex-cloud');
+
+ it('gates built-in Cursor while preserving custom agents regardless of harness', () => {
+ const global = agent('global-cursor', 'Global Cursor', 'all', 'cursor');
+ const installed = agent(
+ 'installed-cursor',
+ 'Installed Cursor',
+ 'selected',
+ 'cursor'
+ );
+ const codex = agent('codex', 'Codex', 'all', 'codex-cloud');
+ const claude = agent('claude', 'Claude', 'all', 'claude-cloud');
expect(
availableBotMentionUsers(
- [codex.bot, bot('other', 'Other')],
- [codex],
- false,
+ [bot(CURSOR_BOT_ID, 'Cursor'), installed.bot],
+ [global, installed, codex, claude],
false
).map((user) => user.id)
- ).toEqual(['bot|other']);
+ ).toEqual([
+ 'bot|installed-cursor',
+ 'bot|global-cursor',
+ 'bot|codex',
+ 'bot|claude',
+ ]);
+ });
+ it('hides the built-in Cursor bot before agent metadata is available', () => {
expect(
- availableBotMentionUsers([codex.bot], [codex], false, true)
- ).toHaveLength(1);
+ availableBotMentionUsers(
+ [bot(CURSOR_BOT_ID, 'Cursor'), bot('custom', 'Custom agent')],
+ [],
+ false
+ ).map((user) => user.id)
+ ).toEqual(['bot|custom']);
});
- it('only offers Codex agents after connection and environment readiness', () => {
- const codex = agent('codex-agent', 'Codex', 'all', 'codex-cloud');
- expect(availableBotMentionUsers([], [codex], false, false)).toEqual([]);
- expect(availableBotMentionUsers([], [codex], false, true)).toHaveLength(1);
+ it('offers Codex from the mention query without requiring account setup', () => {
+ createRoot((dispose) => {
+ expect(
+ useChannelBotMentionUsers(() => 'channel-1')().map((user) => user.id)
+ ).toEqual(['bot|codex-agent']);
+ dispose();
+ });
});
+ it.each(['cursor', 'codex-cloud', 'claude-cloud'])(
+ 'offers global and installed %s agents before connection',
+ (harness) => {
+ const global = agent('global', 'Global', 'all', harness);
+ const installed = agent('installed', 'Installed', 'selected', harness);
+ expect(
+ availableBotMentionUsers(
+ [installed.bot],
+ [global, installed],
+ true
+ ).map((user) => user.id)
+ ).toEqual(['bot|installed', 'bot|global']);
+ }
+ );
it('adds all-channel agents without adding selected agents from other channels', () => {
expect(
availableBotMentionUsers(
@@ -119,7 +145,7 @@ describe('availableBotMentionUsers', () => {
agent('global', 'Global', 'all'),
agent('selected', 'Selected', 'selected'),
],
- false
+ true
).map((user) => user.id)
).toEqual(['bot|installed', 'bot|global']);
});
@@ -129,7 +155,7 @@ describe('availableBotMentionUsers', () => {
availableBotMentionUsers(
[bot('global', 'Global')],
[agent('global', 'Global', 'all')],
- false
+ true
)
).toHaveLength(1);
});
@@ -146,7 +172,7 @@ describe('availableBotMentionUsers', () => {
bot: bot('global', 'Global', avatarUrl),
},
],
- false
+ true
)
).toEqual([
{
@@ -158,10 +184,9 @@ describe('availableBotMentionUsers', () => {
]);
});
- it('only offers a global Cursor agent when Cursor is connected', () => {
+ it('offers a global Cursor agent before Cursor is connected', () => {
const cursorAgent = agent('cursor-agent', 'Cursor agent', 'all', 'cursor');
- expect(availableBotMentionUsers([], [cursorAgent], false)).toEqual([]);
expect(availableBotMentionUsers([], [cursorAgent], true)).toHaveLength(1);
});
});
diff --git a/apps/web/src/features/channel/use-channel-bot-mention-users.ts b/apps/web/src/features/channel/use-channel-bot-mention-users.ts
index d1f84481b2..5e97284cfd 100644
--- a/apps/web/src/features/channel/use-channel-bot-mention-users.ts
+++ b/apps/web/src/features/channel/use-channel-bot-mention-users.ts
@@ -1,9 +1,7 @@
-import { useCodexAgentsAccess } from '@core/codex/flag';
-import { isCodexBotId } from '@core/constant/codexAgent';
+import { isCursorBotId } from '@core/constant/cursorAgent';
+import { useCursorAgentsAccess } from '@core/cursor/flag';
import type { IUser } from '@core/user/types';
import { useAgentsQuery } from '@queries/agents/agents';
-import { useCodexStatusQuery } from '@queries/auth/codex';
-import { useCursorApiKeyStatusQuery } from '@queries/auth/cursor-api-key';
import { useChannelBotsQuery } from '@queries/channel/channel-bots';
import { queryReadyGate } from '@queries/gate';
import type { Agent } from '@service-storage/generated/schemas/agent';
@@ -19,33 +17,24 @@ function mentionUser(bot: Bot): IUser {
};
}
-/** Build mention entries from installed channel bots and virtual global agents. */
+/**
+ * Build mention entries from installed channel bots and virtual global
+ * agents. Account setup does not hide a mention: the harness answers with
+ * a connection prompt in the thread when setup is needed. The built-in
+ * Cursor entry follows the Cursor rollout flag.
+ */
export function availableBotMentionUsers(
channelBots: readonly Bot[],
agents: readonly Agent[],
- cursorConnected: boolean,
- codexConnected = false
+ cursorEnabled: boolean
): IUser[] {
const globalAgents = agents.filter(
- (agent) =>
- agent.channel_scope === 'all' &&
- agent.bot.has_agent &&
- (agent.harness !== 'cursor' || cursorConnected) &&
- (agent.harness !== 'codex-cloud' || codexConnected)
- );
- const codexBotIds = new Set(
- agents
- .filter((agent) => agent.harness === 'codex-cloud')
- .map((agent) => agent.bot.id)
+ (agent) => agent.channel_scope === 'all' && agent.bot.has_agent
);
const seen = new Set<string>();
return [...channelBots, ...globalAgents.map((agent) => agent.bot)]
- .filter(
- (bot) =>
- codexConnected ||
- (!isCodexBotId(`bot|${bot.id}`) && !codexBotIds.has(bot.id))
- )
+ .filter((bot) => cursorEnabled || !isCursorBotId(bot.id))
.map(mentionUser)
.filter((user) => {
if (seen.has(user.id)) return false;
@@ -66,19 +55,13 @@ export function useChannelBotMentionUsers(
): Accessor<IUser[]> {
const channelBots = useChannelBotsQuery(channelId);
const agents = useAgentsQuery();
- const cursorStatus = useCursorApiKeyStatusQuery();
- const canUseCodex = useCodexAgentsAccess();
- const codexStatus = useCodexStatusQuery(canUseCodex);
+ const canUseCursor = useCursorAgentsAccess();
return createMemo(() =>
availableBotMentionUsers(
queryReadyGate(channelBots) ? channelBots.data : [],
queryReadyGate(agents) ? agents.data : [],
- queryReadyGate(cursorStatus) ? cursorStatus.data.registered : false,
- canUseCodex() &&
- codexStatus.isSuccess &&
- codexStatus.data.connected &&
- !!codexStatus.data.environmentId?.trim()
+ canUseCursor()
)
);
}
diff --git a/apps/web/src/features/settings/Harness.test.tsx b/apps/web/src/features/settings/Harness.test.tsx
index 83c9b4de02..a5d3b68b00 100644
--- a/apps/web/src/features/settings/Harness.test.tsx
+++ b/apps/web/src/features/settings/Harness.test.tsx
@@ -219,23 +219,23 @@ beforeEach(() => {
describe('Harness', () => {
it.each([false, true])(
- 'gates Codex settings on rollout access %s',
+ 'offers Codex settings even when rollout access is %s',
(enabled) => {
codexAccess.enabled = enabled;
render(() => <Harness />);
- expect(screen.queryByTestId('codex-harness') !== null).toBe(enabled);
+ expect(screen.getByTestId('codex-harness')).toBeTruthy();
}
);
- it('does not mount Claude connection or fetch its status when the flag is off', () => {
+ it('offers Claude connection when the rollout flag is off', () => {
claudeFlag.enabled = false;
claudeFlag.source.mockClear();
try {
render(() => <Harness />);
expect(
screen.queryByRole('region', { name: 'Claude Cloud connection' })
- ).toBeNull();
- expect(claudeFlag.source).not.toHaveBeenCalled();
+ ).toBeTruthy();
+ expect(claudeFlag.source).toHaveBeenCalled();
expect(screen.getByRole('heading', { name: 'Cursor' })).toBeTruthy();
} finally {
claudeFlag.enabled = true;
diff --git a/apps/web/src/features/settings/Harness.tsx b/apps/web/src/features/settings/Harness.tsx
index 694cb4ca06..ca3ead0cc8 100644
--- a/apps/web/src/features/settings/Harness.tsx
+++ b/apps/web/src/features/settings/Harness.tsx
@@ -1,9 +1,6 @@
-import { useFeatureFlag } from '@app/lib/analytics/posthog';
-import { useCodexAgentsAccess } from '@core/codex/flag';
import { ModelCatalogPicker } from '@core/component/AI/component/input/ModelCatalogPicker';
import { isLargeModelCatalog } from '@core/component/AI/component/input/modelCatalog';
import { toast } from '@core/component/Toast/Toast';
-import { claudeCloud } from '@core/constant/featureFlags';
import { ThrownResultError } from '@core/util/result';
import CursorIcon from '@icon/wide-cursor-ide.svg';
import ArrowUpRightIcon from '@phosphor/arrow-up-right.svg';
@@ -45,8 +42,6 @@ function lastConnectedText(harness: RegisteredHarness): string {
/** Settings UI for choosing and configuring the available agent harnesses. */
export function Harness() {
- const canUseCodex = useCodexAgentsAccess();
- const claudeCloudFlag = useFeatureFlag(claudeCloud);
const [cursorApiKey, setCursorApiKey] = createSignal('');
const cursorStatus = useCursorApiKeyStatusQuery();
const saveCursorApiKey = useSaveCursorApiKey();
@@ -181,9 +176,7 @@ export function Harness() {
</div>
</section>
- <Show when={claudeCloudFlag().enabled}>
- <ClaudeConnection />
- </Show>
+ <ClaudeConnection />
<section class="flex gap-4 px-6 py-5">
<HarnessIcon>
@@ -370,9 +363,7 @@ export function Harness() {
</div>
</section>
- <Show when={canUseCodex()}>
- <CodexHarness />
- </Show>
+ <CodexHarness />
<section class="flex gap-4 px-6 py-5">
<HarnessIcon>
diff --git a/apps/web/src/lib/core/component/HarnessIcon.tsx b/apps/web/src/lib/core/component/HarnessIcon.tsx
new file mode 100644
index 0000000000..247e604028
--- /dev/null
+++ b/apps/web/src/lib/core/component/HarnessIcon.tsx
@@ -0,0 +1,18 @@
+import ClaudeIcon from '@icon/wide-claude.svg';
+import CodexIcon from '@icon/wide-codex-ide.svg';
+import CursorIcon from '@icon/wide-cursor-ide.svg';
+import PlugsIcon from '@phosphor/plugs.svg';
+import { Dynamic } from 'solid-js/web';
+import { match } from 'ts-pattern';
+
+/** Provider mark for a harness, with a generic connection icon for unknown slugs. */
+export function HarnessIcon(props: { harness: string; class?: string }) {
+ const icon = () =>
+ match(props.harness)
+ .with('cursor', () => CursorIcon)
+ .with('claude-cloud', () => ClaudeIcon)
+ .with('codex-cloud', () => CodexIcon)
+ .otherwise(() => PlugsIcon);
+
+ return <Dynamic component={icon()} class={props.class} aria-hidden="true" />;
+}
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/ConnectApp.test.tsx b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/ConnectApp.test.tsx
new file mode 100644
index 0000000000..5646a449cc
--- /dev/null
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/ConnectApp.test.tsx
@@ -0,0 +1,211 @@
+import { useCursorApiKeyStatusQuery } from '@queries/auth/cursor-api-key';
+import { fireEvent, render, screen } from '@solidjs/testing-library';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+const mocks = vi.hoisted(() => ({
+ openSettings: vi.fn(),
+ requestConnectApp: vi.fn(),
+ pipedreamSlugs: new Set<string>(),
+ cursor: { isSuccess: true, isLoading: false, data: { registered: false } },
+ codex: {
+ isLoading: false,
+ data: { connected: false, environmentId: null as string | null },
+ },
+ claude: { isLoading: false, data: { connected: false } },
+}));
+vi.mock('@core/context/user', () => ({
+ useUserId: () => () => 'macro|[email protected]',
+}));
+vi.mock('@queries/auth/codex', () => ({
+ useCodexStatusQuery: vi.fn(() => mocks.codex),
+}));
+vi.mock('@queries/claude-auth/connection', () => ({
+ useClaudeConnectionStatusQuery: vi.fn(() => mocks.claude),
+}));
+vi.mock('@core/constant/SettingsState', () => ({
+ useSettingsState: () => ({ openSettings: mocks.openSettings }),
+}));
+vi.mock('@core/pipedream/pendingConnect', () => ({
+ requestConnectApp: mocks.requestConnectApp,
+}));
+vi.mock('@core/pipedream/ConnectorIcon', () => ({
+ PipedreamConnectorIcon: () => <span data-pipedream-icon />,
+}));
+vi.mock('@queries/pipedream-connectors', () => ({
+ usePipedreamConnectedSlugs: () => ({
+ ready: () => true,
+ slugs: () => mocks.pipedreamSlugs,
+ }),
+}));
+vi.mock('@queries/auth/cursor-api-key', () => ({
+ useCursorApiKeyStatusQuery: vi.fn(() => mocks.cursor),
+}));
+// Reached through LexicalWrapperContext; the plugin barrel is far heavier
+// than the context object this chip reads its selection from.
+vi.mock('../../plugins', () => ({}));
+
+import { ConnectApp } from './ConnectApp';
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.pipedreamSlugs.clear();
+ mocks.cursor.isLoading = false;
+ mocks.codex.isLoading = false;
+ mocks.codex.data = { connected: false, environmentId: null };
+ mocks.claude.isLoading = false;
+ mocks.claude.data = { connected: false };
+ mocks.cursor.data = { registered: false };
+});
+
+describe('connect-app chip', () => {
+ it('sends a Pipedream chip to Connections with the app queued', () => {
+ render(() => (
+ <ConnectApp
+ appSlug="linear"
+ name="Linear"
+ target="connections"
+ key="node"
+ theme={{}}
+ />
+ ));
+ fireEvent.click(screen.getByRole('button', { name: 'Connect Linear' }));
+ expect(mocks.requestConnectApp).toHaveBeenCalledWith('linear');
+ expect(mocks.openSettings).toHaveBeenCalledWith('Connected');
+ });
+
+ it('sends a harness chip to the Harness page without touching Pipedream', () => {
+ render(() => (
+ <ConnectApp
+ appSlug="cursor"
+ name="Cursor"
+ target="harness"
+ key="node"
+ theme={{}}
+ />
+ ));
+ fireEvent.click(screen.getByRole('button', { name: 'Connect Cursor' }));
+ expect(mocks.openSettings).toHaveBeenCalledWith('Harness');
+ expect(mocks.requestConnectApp).not.toHaveBeenCalled();
+ });
+
+ it('reads as connected once the reader has a Cursor key, and stops navigating', () => {
+ mocks.cursor.data = { registered: true };
+ render(() => (
+ <ConnectApp
+ appSlug="cursor"
+ name="Cursor"
+ target="harness"
+ key="node"
+ theme={{}}
+ />
+ ));
+ const chip = screen.getByRole('button', { name: 'Cursor connected' });
+ fireEvent.click(chip);
+ expect(mocks.openSettings).not.toHaveBeenCalled();
+ });
+
+ it('keeps unknown harnesses connectable without fetching Cursor status', () => {
+ mocks.cursor.data = { registered: true };
+ render(() => (
+ <ConnectApp
+ appSlug="another-harness"
+ name="Another harness"
+ target="harness"
+ key="node"
+ theme={{}}
+ />
+ ));
+
+ const enabled = vi.mocked(useCursorApiKeyStatusQuery).mock.calls[0][0];
+ expect(enabled?.()).toBe(false);
+ fireEvent.click(
+ screen.getByRole('button', { name: 'Connect Another harness' })
+ );
+ expect(mocks.openSettings).toHaveBeenCalledWith('Harness');
+ });
+
+ it('renders a connect action while the harness status is loading', () => {
+ mocks.cursor.isLoading = true;
+ mocks.cursor.data = { registered: true };
+ render(() => (
+ <ConnectApp
+ appSlug="cursor"
+ name="Cursor"
+ target="harness"
+ key="node"
+ theme={{}}
+ />
+ ));
+
+ expect(screen.getByRole('button', { name: 'Connect Cursor' })).toBeTruthy();
+ });
+
+ it.each([
+ ['codex-cloud', 'Codex'],
+ ['claude-cloud', 'Claude'],
+ ])(
+ 'opens Harness settings for an unconnected %s account',
+ (appSlug, name) => {
+ render(() => (
+ <ConnectApp
+ appSlug={appSlug}
+ name={name}
+ target="harness"
+ key="node"
+ theme={{}}
+ />
+ ));
+ fireEvent.click(screen.getByRole('button', { name: `Connect ${name}` }));
+ expect(mocks.openSettings).toHaveBeenCalledWith('Harness');
+ expect(mocks.requestConnectApp).not.toHaveBeenCalled();
+ }
+ );
+
+ it.each([
+ ['codex-cloud', 'Codex'],
+ ['claude-cloud', 'Claude'],
+ ])('recognizes the reader’s connected %s account', (appSlug, name) => {
+ mocks.codex.data = { connected: true, environmentId: 'env-selected' };
+ mocks.claude.data = { connected: true };
+ render(() => (
+ <ConnectApp
+ appSlug={appSlug}
+ name={name}
+ target="harness"
+ key="node"
+ theme={{}}
+ />
+ ));
+ fireEvent.click(screen.getByRole('button', { name: `${name} connected` }));
+ expect(mocks.openSettings).not.toHaveBeenCalled();
+ });
+
+ it('keeps Codex setup available until an environment is selected', () => {
+ mocks.codex.data = { connected: true, environmentId: null };
+ render(() => (
+ <ConnectApp
+ appSlug="codex-cloud"
+ name="Codex"
+ target="harness"
+ key="node"
+ theme={{}}
+ />
+ ));
+ fireEvent.click(screen.getByRole('button', { name: 'Connect Codex' }));
+ expect(mocks.openSettings).toHaveBeenCalledWith('Harness');
+ });
+
+ it('does not let a Cursor key satisfy a Pipedream chip for an app of the same name', () => {
+ mocks.cursor.data = { registered: true };
+ render(() => (
+ <ConnectApp
+ appSlug="cursor"
+ name="Cursor"
+ target="connections"
+ key="node"
+ theme={{}}
+ />
+ ));
+ expect(screen.getByRole('button', { name: 'Connect Cursor' })).toBeTruthy();
+ });
+});
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/ConnectApp.tsx b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/ConnectApp.tsx
index 64327ff31e..cfa996eae9 100644
--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/ConnectApp.tsx
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/ConnectApp.tsx
@@ -1,26 +1,75 @@
+import { HarnessIcon } from '@core/component/HarnessIcon';
import { useSettingsState } from '@core/constant/SettingsState';
+import { useUserId } from '@core/context/user';
import { PipedreamConnectorIcon } from '@core/pipedream/ConnectorIcon';
import { requestConnectApp } from '@core/pipedream/pendingConnect';
import type { ConnectAppDecoratorProps } from '@macro-inc/lexical-core';
import ArrowUpRightIcon from '@phosphor/arrow-up-right.svg';
+import { useHarnessConnectionStatus } from '@queries/harnesses/connections';
import { usePipedreamConnectedSlugs } from '@queries/pipedream-connectors';
-import { cn } from '@ui';
-import { Show, useContext } from 'solid-js';
+import { cn } from '@ui/utils/classname';
+import { type Accessor, type JSX, Show, useContext } from 'solid-js';
+import { match } from 'ts-pattern';
import { LexicalWrapperContext } from '../../context/LexicalWrapperContext';
/**
- * The chip an agent's reply renders when a tool call failed because the
- * reader has not connected an app. Clicking it opens Settings → Integrations
- * with that app queued to connect. Once the reader has connected it, the same
- * chip reads as connected rather than nagging.
+ * The chip a reply renders when the reader has to connect something before
+ * the agent can continue: a Pipedream app or an agent harness account.
+ * Clicking it opens the settings surface
+ * that connects it. Once the reader has connected it, the same chip reads as
+ * connected rather than nagging.
*/
export function ConnectApp(props: ConnectAppDecoratorProps) {
+ return match(props.target)
+ .with('connections', () => <ConnectPipedreamApp {...props} />)
+ .with('harness', () => <ConnectHarness {...props} />)
+ .exhaustive();
+}
+
+function ConnectPipedreamApp(props: ConnectAppDecoratorProps) {
const { openSettings } = useSettingsState();
const connections = usePipedreamConnectedSlugs();
+ return (
+ <ConnectChip
+ {...props}
+ connected={() =>
+ connections.ready() && connections.slugs().has(props.appSlug)
+ }
+ icon={<PipedreamConnectorIcon appSlug={props.appSlug} class="size-3.5" />}
+ onConnect={() => {
+ // The Integrations tab picks this up and starts the Connect flow.
+ requestConnectApp(props.appSlug);
+ openSettings('Connected');
+ }}
+ />
+ );
+}
+
+function ConnectHarness(props: ConnectAppDecoratorProps) {
+ const { openSettings } = useSettingsState();
+ const connected = useHarnessConnectionStatus(
+ () => props.appSlug,
+ useUserId()
+ );
+ return (
+ <ConnectChip
+ {...props}
+ connected={connected}
+ icon={<HarnessIcon harness={props.appSlug} class="size-3.5" />}
+ onConnect={() => openSettings('Harness')}
+ />
+ );
+}
+
+function ConnectChip(
+ props: ConnectAppDecoratorProps & {
+ connected: Accessor<boolean>;
+ icon: JSX.Element;
+ onConnect: () => void;
+ }
+) {
const lexicalWrapper = useContext(LexicalWrapperContext);
const selection = () => lexicalWrapper?.selection;
- const connected = () =>
- connections.ready() && connections.slugs().has(props.appSlug);
const isSelectedAsNode = () => {
const sel = selection();
@@ -29,23 +78,22 @@ export function ConnectApp(props: ConnectAppDecoratorProps) {
};
const handleClick = () => {
- if (connected()) return;
- // The Integrations tab picks this up and starts the Connect flow.
- requestConnectApp(props.appSlug);
- openSettings('Connected');
+ if (props.connected()) return;
+ props.onConnect();
};
return (
<button
type="button"
data-connect-app={props.appSlug}
+ data-connect-target={props.target}
aria-label={
- connected() ? `${props.name} connected` : `Connect ${props.name}`
+ props.connected() ? `${props.name} connected` : `Connect ${props.name}`
}
class={cn(
'pointer-events-auto inline-flex items-center gap-1 rounded-md border px-1.5 py-0.5 align-middle text-xs font-medium',
'cursor-default outline-none transition-colors',
- connected()
+ props.connected()
? 'border-edge-muted text-ink-muted'
: 'border-accent/40 text-accent hover:bg-accent/10 focus-visible:bg-accent/10',
isSelectedAsNode() && 'bg-active'
@@ -55,11 +103,11 @@ export function ConnectApp(props: ConnectAppDecoratorProps) {
onMouseDown={(event) => event.preventDefault()}
onClick={handleClick}
>
- <PipedreamConnectorIcon appSlug={props.appSlug} class="size-3.5" />
- <Show when={connected()} fallback={<>Connect {props.name}</>}>
+ {props.icon}
+ <Show when={props.connected()} fallback={<>Connect {props.name}</>}>
{props.name} connected
</Show>
- <Show when={!connected()}>
+ <Show when={!props.connected()}>
<ArrowUpRightIcon class="size-3 opacity-70" />
</Show>
</button>
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/version.ts b/apps/web/src/lib/core/component/LexicalMarkdown/version.ts
index 74588480c2..97966e48c0 100644
--- a/apps/web/src/lib/core/component/LexicalMarkdown/version.ts
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/version.ts
@@ -21,5 +21,6 @@
* Version 4.0 - Sep 2026. Added AgentSessionMentionNode.
* Version 3.1 - Sep 2026. Added ConnectAppNode (agent "connect this app" chip).
* Version 4.1 - Sep 2026. Expandable session mentions reuse Magic Chip with a null message lock for the latest turn.
+ * Version 4.2 - Sep 2026. ConnectAppNode: optional `target` (connections | harness) so the chip can connect Cursor.
*/
-export const MARKDOWN_VERSION_COUNTER = 4.1;
+export const MARKDOWN_VERSION_COUNTER = 4.2;
diff --git a/apps/web/src/lib/core/constant/claudeAgent.ts b/apps/web/src/lib/core/constant/claudeAgent.ts
new file mode 100644
index 0000000000..d6f556ffca
--- /dev/null
+++ b/apps/web/src/lib/core/constant/claudeAgent.ts
@@ -0,0 +1,8 @@
+/** First-party Claude identity, matching the backend bot_id registry. */
+export const CLAUDE_BOT_ID = '00000000-0000-0000-0000-00000000c1a0';
+export const CLAUDE_BOT_PRINCIPAL_ID = `bot|${CLAUDE_BOT_ID}`;
+export const CLAUDE_BOT_NAME = 'Claude';
+export const CLAUDE_BOT_HANDLE = 'claude';
+export function isClaudeBotId(id: string): boolean {
+ return id === CLAUDE_BOT_ID || id === CLAUDE_BOT_PRINCIPAL_ID;
+}
diff --git a/apps/web/src/lib/core/constant/cursorAgent.test.ts b/apps/web/src/lib/core/constant/cursorAgent.test.ts
deleted file mode 100644
index a119250ff1..0000000000
--- a/apps/web/src/lib/core/constant/cursorAgent.test.ts
+++ /dev/null
@@ -1,16 +0,0 @@
-import { describe, expect, it } from 'vitest';
-import { isMacroStaffEmail } from './cursorAgent';
-
-describe('isMacroStaffEmail', () => {
- it('accepts the Macro domain case-insensitively', () => {
- expect(isMacroStaffEmail('[email protected]')).toBe(true);
- expect(isMacroStaffEmail('[email protected]')).toBe(true);
- });
-
- it('rejects missing and lookalike domains', () => {
- expect(isMacroStaffEmail(undefined)).toBe(false);
- expect(isMacroStaffEmail('[email protected]')).toBe(false);
- expect(isMacroStaffEmail('[email protected]')).toBe(false);
- expect(isMacroStaffEmail('[email protected]@macro.com')).toBe(false);
- });
-});
diff --git a/apps/web/src/lib/core/constant/cursorAgent.ts b/apps/web/src/lib/core/constant/cursorAgent.ts
index 6396cd24c1..24b7e5b597 100644
--- a/apps/web/src/lib/core/constant/cursorAgent.ts
+++ b/apps/web/src/lib/core/constant/cursorAgent.ts
@@ -18,12 +18,6 @@ export const CURSOR_BOT_NAME = 'Cursor';
/** Handle used to find the Cursor bot in the mention typeahead (`@cursor`). */
export const CURSOR_BOT_HANDLE = 'cursor';
-/** Whether an email belongs to a Macro staff account. */
-export function isMacroStaffEmail(email: string | undefined): boolean {
- const parts = email?.toLowerCase().split('@');
- return parts?.length === 2 && parts[1] === 'macro.com';
-}
-
/**
* Whether an id refers to the Cursor bot. Accepts both the bare UUID and the
* `bot|<uuid>` participant/sender form.
diff --git a/apps/web/src/lib/core/constant/featureFlags.ts b/apps/web/src/lib/core/constant/featureFlags.ts
index 70d5ec219f..14db4e367b 100644
--- a/apps/web/src/lib/core/constant/featureFlags.ts
+++ b/apps/web/src/lib/core/constant/featureFlags.ts
@@ -658,18 +658,17 @@ export const enableChatV3Agents = defineFlag({
default: onInDev,
});
-// The `@cursor` mention entry: agent sessions served by Cursor cloud agents
-// on Macro's Cursor account. PostHog-gated per user; the backend additionally
-// restricts these sessions to @macro.com senders. Override with
-// VITE_ENABLE_CURSOR_AGENTS.
+// The built-in @cursor mention, using the mentioning user's own Cursor account.
+// Account setup is checked after the mention; this flag controls discovery.
+// Override with VITE_ENABLE_CURSOR_AGENTS.
export const enableCursorAgents = defineFlag({
key: 'enable-cursor-agents',
env: 'ENABLE_CURSOR_AGENTS',
default: onInDev,
});
-// Codex cloud agent mentions, composer choices, and harness settings also
-// require enableChatV3Agents. Override with VITE_ENABLE_CODEX_AGENTS.
+// Codex composer choices also require enableChatV3Agents.
+// Override with VITE_ENABLE_CODEX_AGENTS.
export const enableCodexAgents = defineFlag({
key: 'enable-codex-agents',
env: 'ENABLE_CODEX_AGENTS',
diff --git a/apps/web/src/lib/core/cursor/flag.ts b/apps/web/src/lib/core/cursor/flag.ts
index 02cd246ef0..d20be21153 100644
--- a/apps/web/src/lib/core/cursor/flag.ts
+++ b/apps/web/src/lib/core/cursor/flag.ts
@@ -1,13 +1,9 @@
import { useFeatureFlag } from '@app/lib/analytics/posthog';
-import { isMacroStaffEmail } from '@core/constant/cursorAgent';
import { enableCursorAgents } from '@core/constant/featureFlags';
-import { useEmail } from '@core/context/user';
import type { Accessor } from 'solid-js';
-/** Whether the current user may see and use Cursor-agent surfaces. */
+/** Whether the built-in Cursor mention is included in this user's rollout. */
export function useCursorAgentsAccess(): Accessor<boolean> {
const flag = useFeatureFlag(enableCursorAgents);
- const email = useEmail();
-
- return () => flag().enabled && isMacroStaffEmail(email());
+ return () => flag().enabled;
}
diff --git a/apps/web/src/lib/queries/auth/cursor-api-key.ts b/apps/web/src/lib/queries/auth/cursor-api-key.ts
index 8b552598e8..9783dac6bb 100644
--- a/apps/web/src/lib/queries/auth/cursor-api-key.ts
+++ b/apps/web/src/lib/queries/auth/cursor-api-key.ts
@@ -26,9 +26,12 @@ const NOT_CONNECTED: CursorApiKeyStatus = {
* enough to render "connected" or "not connected" — which is all the settings
* surface needs.
*/
-export function useCursorApiKeyStatusQuery() {
+export function useCursorApiKeyStatusQuery(
+ enabled: () => boolean = () => true
+) {
return useQuery(() => ({
queryKey: authKeys.cursorApiKeyStatus.queryKey,
+ enabled: enabled(),
queryFn: async () =>
throwOnErr(async () => await authServiceClient.getCursorApiKeyStatus()),
placeholderData: NOT_CONNECTED,
diff --git a/apps/web/src/lib/queries/claude-auth/connection.ts b/apps/web/src/lib/queries/claude-auth/connection.ts
index 9cabb3a28d..74076316a5 100644
--- a/apps/web/src/lib/queries/claude-auth/connection.ts
+++ b/apps/web/src/lib/queries/claude-auth/connection.ts
@@ -4,19 +4,27 @@ import { useQuery, useQueryClient } from '@tanstack/solid-query';
import type { ClaudeConnectionSource } from '../../../features/claude-connection/core/connection';
import { claudeAuthKeys } from './keys';
-/** Only safe status is cached. One-time codes never enter a mutation cache. */
-export function useClaudeConnectionSource(
- owner: () => string | undefined
-): ClaudeConnectionSource {
- const client = useQueryClient();
- const query = useQuery(() => ({
+/** Safe per-owner Claude status, shared by settings and connection prompts. */
+export function useClaudeConnectionStatusQuery(
+ owner: () => string | undefined,
+ enabled: () => boolean = () => true
+) {
+ return useQuery(() => ({
queryKey: claudeAuthKeys.status(owner()).queryKey,
queryFn: ({ signal }) => throwOnErr(() => claudeAuthClient.status(signal)),
- enabled: !!owner(),
+ enabled: !!owner() && enabled(),
staleTime: 0,
gcTime: 0,
retry: false,
}));
+}
+
+/** Only safe status is cached. One-time codes never enter a mutation cache. */
+export function useClaudeConnectionSource(
+ owner: () => string | undefined
+): ClaudeConnectionSource {
+ const client = useQueryClient();
+ const query = useClaudeConnectionStatusQuery(owner);
const refresh = async () => {
await Promise.all([
client.invalidateQueries({ queryKey: claudeAuthKeys._def }),
diff --git a/apps/web/src/lib/queries/harnesses/connections.ts b/apps/web/src/lib/queries/harnesses/connections.ts
new file mode 100644
index 0000000000..6b5798dc82
--- /dev/null
+++ b/apps/web/src/lib/queries/harnesses/connections.ts
@@ -0,0 +1,35 @@
+import type { Accessor } from 'solid-js';
+import { match } from 'ts-pattern';
+import { useCodexStatusQuery } from '../auth/codex';
+import { useCursorApiKeyStatusQuery } from '../auth/cursor-api-key';
+import { useClaudeConnectionStatusQuery } from '../claude-auth/connection';
+import { queryReadyGate } from '../gate';
+
+/** Connection status for a named harness; unsupported providers stay disconnected. */
+export function useHarnessConnectionStatus(
+ harness: Accessor<string>,
+ owner: Accessor<string | undefined>
+): Accessor<boolean> {
+ const cursor = useCursorApiKeyStatusQuery(() => harness() === 'cursor');
+ const codex = useCodexStatusQuery(() => harness() === 'codex-cloud');
+ const claude = useClaudeConnectionStatusQuery(
+ owner,
+ () => harness() === 'claude-cloud'
+ );
+
+ return () =>
+ match(harness())
+ .with('cursor', () => queryReadyGate(cursor) && cursor.data.registered)
+ .with(
+ 'codex-cloud',
+ () =>
+ queryReadyGate(codex) &&
+ codex.data.connected &&
+ !!codex.data.environmentId?.trim()
+ )
+ .with(
+ 'claude-cloud',
+ () => queryReadyGate(claude) && claude.data.connected
+ )
+ .otherwise(() => false);
+}
diff --git a/crates/agent_harness/src/domain/claude.rs b/crates/agent_harness/src/domain/claude.rs
index 39d4844e9f..e0d0086493 100644
--- a/crates/agent_harness/src/domain/claude.rs
+++ b/crates/agent_harness/src/domain/claude.rs
@@ -1,5 +1,6 @@
//! Claude conversation lifecycle through owner-bound provider and session ports.
use crate::domain::error::{HarnessError, Result};
+use crate::domain::model::SessionBlocker;
use agent_session::domain::{
model::{AgentSessionId, ExternalSession},
ports::{AgentSessionRepo, ExternalSessionRepo},
@@ -9,6 +10,7 @@ use claude_cloud_agents::domain::{
ports::{CloudLifecycle, CloudProvider},
service::Session,
};
+use macro_user_id::user_id::MacroUserIdStr;
use std::sync::Arc;
/// Provider identity in the shared external-session store.
@@ -31,6 +33,15 @@ pub struct ClaudeSessions<P, Repo, External> {
impl<P: CloudProvider, Repo: AgentSessionRepo, External: ExternalSessionRepo>
ClaudeSessions<P, Repo, External>
{
+ /// Check the owner's connection before a mention creates any session resources.
+ pub async fn preflight(&self, owner: &MacroUserIdStr<'_>) -> Result<Option<SessionBlocker>> {
+ match self.provider.connect(owner.as_ref()).await {
+ Ok(_) => Ok(None),
+ Err(Error::NotConnected) => Ok(Some(SessionBlocker::ClaudeNotConnected)),
+ Err(error) => Err(cloud_error(error)),
+ }
+ }
+
/// Mint a fresh egress credential on reattach; persist only its hash, as for
/// other external runtimes. The saved agent selection remains authoritative.
pub async fn refresh_egress(
diff --git a/crates/agent_harness/src/domain/claude/test.rs b/crates/agent_harness/src/domain/claude/test.rs
index 39d3080a2e..ccbdb35538 100644
--- a/crates/agent_harness/src/domain/claude/test.rs
+++ b/crates/agent_harness/src/domain/claude/test.rs
@@ -13,6 +13,7 @@ use std::sync::Mutex;
#[derive(Default)]
struct Provider {
+ connection_error: Mutex<Option<Error>>,
calls: Arc<Mutex<Vec<(String, String)>>>,
models: Arc<Mutex<Vec<String>>>,
uncertain: bool,
@@ -31,6 +32,9 @@ struct Client {
impl CloudProvider for Provider {
type Client = Client;
async fn connect(&self, owner: &str) -> claude_cloud_agents::domain::model::Result<Client> {
+ if let Some(error) = self.connection_error.lock().unwrap().take() {
+ return Err(error);
+ }
Ok(Client {
owner: owner.into(),
calls: self.calls.clone(),
@@ -304,3 +308,28 @@ async fn network_setup_failure_never_creates_or_leaves_a_pending_intent() {
assert!(provider.calls.lock().unwrap().is_empty());
assert_eq!(provider.preparations.lock().unwrap().len(), 2);
}
+
+#[tokio::test]
+async fn preflight_only_requests_connection_for_a_missing_account() {
+ let provider = Arc::new(Provider::default());
+ let service = ClaudeSessions::new(
+ provider.clone(),
+ InMemoryAgentSessionRepo::default(),
+ mappings(),
+ "dev-gateway.macro.com".into(),
+ );
+ let owner = MacroUserIdStr::try_from_email("[email protected]").unwrap();
+ *provider.connection_error.lock().unwrap() = Some(Error::NotConnected);
+ assert_eq!(
+ service.preflight(&owner).await.unwrap(),
+ Some(SessionBlocker::ClaudeNotConnected)
+ );
+ assert_eq!(service.preflight(&owner).await.unwrap(), None);
+ *provider.connection_error.lock().unwrap() = Some(Error::Network);
+ assert!(matches!(
+ service.preflight(&owner).await,
+ Err(HarnessError::Container(_))
+ ));
+ assert!(provider.calls.lock().unwrap().is_empty());
+ assert!(provider.preparations.lock().unwrap().is_empty());
+}
diff --git a/crates/agent_harness/src/domain/codex.rs b/crates/agent_harness/src/domain/codex.rs
index 823f37c24b..5ce51239ae 100644
--- a/crates/agent_harness/src/domain/codex.rs
+++ b/crates/agent_harness/src/domain/codex.rs
@@ -1,4 +1,5 @@
//! Per-owner Codex authorization and provider mapping for hosted conversations.
+use crate::domain::{error::HarnessError, model::SessionBlocker};
use agent_session::domain::{
model::{AgentSessionId, ExternalSession},
ports::{AgentSessionRepo, ExternalSessionRepo},
@@ -8,10 +9,25 @@ use codex_cloud_agents::domain::cloud::{
};
use codex_cloud_agents::domain::runtime::{CloudRuntime, CloudTarget, RuntimeIdentity};
use codex_cloud_agents::domain::{Credentials, OAuth};
-use codex_connection::domain::ConnectionService;
+use codex_connection::domain::{ConnectionError, ConnectionService};
use macro_user_id::user_id::MacroUserIdStr;
use std::sync::Arc;
+/// Resolve the owner's account and environment before provisioning a session.
+pub(crate) async fn connection_preflight(
+ connections: &dyn ConnectionService,
+ owner: &MacroUserIdStr<'_>,
+) -> crate::domain::error::Result<Option<SessionBlocker>> {
+ match connections.resolve(owner.as_ref()).await {
+ Ok(connection) if connection.environment_id.is_none() => {
+ Ok(Some(SessionBlocker::CodexEnvironmentNotConfigured))
+ }
+ Ok(_) => Ok(None),
+ Err(ConnectionError::NotConnected) => Ok(Some(SessionBlocker::CodexNotConnected)),
+ Err(error) => Err(HarnessError::Container(error.to_string())),
+ }
+}
+
fn repository_identity(value: &str) -> Result<String, rootcause::Report> {
let parsed = url::Url::parse(value).map_err(|_| {
rootcause::report!(
diff --git a/crates/agent_harness/src/domain/codex/test.rs b/crates/agent_harness/src/domain/codex/test.rs
index dccd8a5303..44a1138e2d 100644
--- a/crates/agent_harness/src/domain/codex/test.rs
+++ b/crates/agent_harness/src/domain/codex/test.rs
@@ -10,10 +10,14 @@ use std::{collections::HashMap, sync::Mutex};
struct Connections(
Mutex<HashMap<String, (String, String)>>,
Mutex<Option<Option<String>>>,
+ Mutex<Option<ConnectionError>>,
);
#[async_trait::async_trait]
impl ConnectionService for Connections {
async fn resolve(&self, owner: &str) -> Result<ResolvedConnection, ConnectionError> {
+ if let Some(error) = self.2.lock().unwrap().take() {
+ return Err(error);
+ }
let rows = self.0.lock().unwrap();
let (connection, account) = rows.get(owner).ok_or(ConnectionError::NotConnected)?;
let environment = self
@@ -328,3 +332,32 @@ async fn pr_publication_passes_the_activated_claim_and_rejects_disconnected_owne
assert!(runtime.report_pull_request(url).await.is_err());
assert_eq!(reporter.0.lock().unwrap().len(), 1);
}
+
+#[tokio::test]
+async fn connection_preflight_distinguishes_missing_account_and_environment() {
+ let connections = Connections::default();
+ let owner = MacroUserIdStr::try_from_email("[email protected]").unwrap();
+ assert_eq!(
+ connection_preflight(&connections, &owner).await.unwrap(),
+ Some(SessionBlocker::CodexNotConnected)
+ );
+ connections.0.lock().unwrap().insert(
+ owner.as_ref().to_owned(),
+ (uuid::Uuid::new_v4().to_string(), "account".into()),
+ );
+ *connections.1.lock().unwrap() = Some(None);
+ assert_eq!(
+ connection_preflight(&connections, &owner).await.unwrap(),
+ Some(SessionBlocker::CodexEnvironmentNotConfigured)
+ );
+ *connections.1.lock().unwrap() = Some(Some("env_selected".into()));
+ assert_eq!(
+ connection_preflight(&connections, &owner).await.unwrap(),
+ None
+ );
+ *connections.2.lock().unwrap() = Some(ConnectionError::Storage);
+ assert!(matches!(
+ connection_preflight(&connections, &owner).await,
+ Err(HarnessError::Container(_))
+ ));
+}
diff --git a/crates/agent_harness/src/domain/model.rs b/crates/agent_harness/src/domain/model.rs
index 093432696f..41d57df40f 100644
--- a/crates/agent_harness/src/domain/model.rs
+++ b/crates/agent_harness/src/domain/model.rs
@@ -85,6 +85,8 @@ impl AgentKind {
Self::Cursor
} else if bot == bot_id::CODEX_BOT_ID {
Self::CodexCloud
+ } else if bot == bot_id::CLAUDE_BOT_ID {
+ Self::ClaudeCloud
} else if bot == bot_id::MACRO_NEW_BOT_ID {
Self::InMemory
} else {
@@ -150,7 +152,7 @@ pub(crate) use agent_egress::domain::model::is_macro_staff;
/// Where a prompt came from, when it came from somewhere the session should
/// answer back into.
-#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
+#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct AnnounceOrigin {
/// Channel or document the prompt was posted in.
pub parent: messages::domain::models::MessageParent,
@@ -321,6 +323,38 @@ pub struct SessionAnnouncement {
pub triggered_by: MacroUserIdStr<'static>,
}
+/// Something the mentioner has to set up before their provider will open a
+/// session for them - the one class of refusal that is theirs to fix, so
+/// it is answered in the thread rather than logged.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
+#[serde(rename_all = "snake_case")]
+pub enum SessionBlocker {
+ /// `@cursor` runs on the mentioner's own Cursor account, and they have
+ /// not registered a key in settings yet.
+ CursorNotConnected,
+ /// The mentioner has not connected their ChatGPT account for Codex.
+ CodexNotConnected,
+ /// Codex is connected, but no cloud environment has been selected.
+ CodexEnvironmentNotConfigured,
+ /// The mentioner has not connected their Claude account.
+ ClaudeNotConnected,
+}
+
+/// A mention that opened no session, and why. Posted back into the mention's
+/// thread as the bot, so the person who asked learns what to do next instead
+/// of watching a chip that never answers.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct DeclinedMention {
+ /// The bot that was mentioned; the reply posts as it.
+ pub bot_id: BotId,
+ /// Where the mention was posted, and so where the reply goes.
+ pub origin: AnnounceOrigin,
+ /// Who mentioned the bot.
+ pub triggered_by: MacroUserIdStr<'static>,
+ /// What stands between them and a session.
+ pub blocker: SessionBlocker,
+}
+
/// The message an announcement became.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct AnnouncedMessage {
diff --git a/crates/agent_harness/src/domain/ports.rs b/crates/agent_harness/src/domain/ports.rs
index 330681e57a..7c0e2739a4 100644
--- a/crates/agent_harness/src/domain/ports.rs
+++ b/crates/agent_harness/src/domain/ports.rs
@@ -14,8 +14,9 @@ use macro_user_id::user_id::MacroUserIdStr;
use super::error::{HarnessError, Result};
use super::model::{
- AgentRuntimeConfig, AnnouncedMessage, CommandOutcome, HarnessCommand, PriorMessage,
- ProvisionedEgress, ReachableRepository, SandboxEgress, SessionAnnouncement, SpawnContainer,
+ AgentKind, AgentRuntimeConfig, AnnouncedMessage, CommandOutcome, DeclinedMention,
+ HarnessCommand, PriorMessage, ProvisionedEgress, ReachableRepository, SandboxEgress,
+ SessionAnnouncement, SessionBlocker, SpawnContainer,
};
use super::notifications::PlannedNotification;
use super::sandbox::SandboxResizeEffect;
@@ -227,6 +228,13 @@ pub trait SessionAnnouncer: Send + Sync + 'static {
&self,
announcement: SessionAnnouncement,
) -> impl Future<Output = Result<AnnouncedMessage>> + Send;
+
+ /// Tell a thread why its mention opened no session.
+ ///
+ /// The other thing the bot can say into a thread: not "here is your
+ /// session" but "here is what you need first". Same channel, same
+ /// sender, no session to point at.
+ fn decline(&self, declined: DeclinedMention) -> impl Future<Output = Result<()>> + Send;
}
/// Where a session finds its bot's live runtime connection.
@@ -311,6 +319,24 @@ pub trait ContainerManager: Send + Sync + 'static {
/// Transport returned by this provider.
type Transport: AgentConnector;
+ /// Whether `owner` is set up for a `kind` session, before anything is
+ /// created for one.
+ ///
+ /// `Ok(None)` is the ordinary answer and the default: most providers
+ /// need nothing from the person mentioning them. A provider that runs
+ /// on the owner's own account answers with what they still have to do,
+ /// so the domain can say so in the thread instead of minting a session
+ /// row whose spawn is doomed. An `Err` is an infrastructure failure -
+ /// the question itself could not be asked.
+ fn preflight(
+ &self,
+ kind: AgentKind,
+ owner: &MacroUserIdStr<'_>,
+ ) -> impl Future<Output = Result<Option<SessionBlocker>>> + Send {
+ let _ = (kind, owner);
+ async { Ok(None) }
+ }
+
/// Boot a new container for a session that has never had one.
fn spawn(
&self,
diff --git a/crates/agent_harness/src/domain/service.rs b/crates/agent_harness/src/domain/service.rs
index 4c39048bd8..3393305979 100644
--- a/crates/agent_harness/src/domain/service.rs
+++ b/crates/agent_harness/src/domain/service.rs
@@ -46,8 +46,9 @@ use tracing::instrument::WithSubscriber as _;
use crate::domain::error::{HarnessError, Result};
use crate::domain::model::{
- AgentKind, AnnounceOrigin, AnnouncePrompt, CommandOutcome, DeliverAction, HarnessCommand,
- HarnessDefaults, OpenSession, SessionAnnouncement, SpawnContainer, is_macro_staff,
+ AgentKind, AnnounceOrigin, AnnouncePrompt, CommandOutcome, DeclinedMention, DeliverAction,
+ HarnessCommand, HarnessDefaults, OpenSession, SessionAnnouncement, SpawnContainer,
+ is_macro_staff,
};
use crate::domain::pending::PendingCommands;
use crate::domain::ports::{
diff --git a/crates/agent_harness/src/domain/service/open.rs b/crates/agent_harness/src/domain/service/open.rs
index 34b7709aa5..ccef47c661 100644
--- a/crates/agent_harness/src/domain/service/open.rs
+++ b/crates/agent_harness/src/domain/service/open.rs
@@ -418,6 +418,37 @@ where
},
)
.await?;
+
+ // Asked before anything exists for the session: a row whose spawn is
+ // bound to fail would be marked disconnected and leave the thread
+ // with a chip that never answers. Declining is the bot's reply
+ // instead - what the mentioner has to connect, where to do it.
+ if let Some(blocker) = self
+ .containers
+ .preflight(runtime.kind, &origin.sender)
+ .await?
+ {
+ tracing::info!(
+ bot_id = %bot_id,
+ sender = %origin.sender,
+ ?blocker,
+ "declining a mention its sender is not set up for"
+ );
+ self.announcer
+ .decline(DeclinedMention {
+ bot_id,
+ origin: AnnounceOrigin {
+ parent: origin.parent,
+ thread_id: origin.thread_id,
+ message_id: origin.message_id,
+ },
+ triggered_by: origin.sender,
+ blocker,
+ })
+ .await?;
+ return Ok(());
+ }
+
let defaults = self.defaults.for_bot(bot_id);
let sandbox_size = self.sessions.user_sandbox_size(&origin.sender).await?;
diff --git a/crates/agent_harness/src/domain/service/test.rs b/crates/agent_harness/src/domain/service/test.rs
index 802a12a993..8a5fbd8d00 100644
--- a/crates/agent_harness/src/domain/service/test.rs
+++ b/crates/agent_harness/src/domain/service/test.rs
@@ -39,9 +39,9 @@ use super::AgentHarnessService;
use super::into_session_error;
use crate::domain::error::HarnessError;
use crate::domain::model::{
- AgentKind, AgentRuntimeConfig, AnnounceOrigin, CommandOutcome, DeliverAction, HarnessCommand,
- HarnessDefaults, MentionOrigin, OpenSession, PriorMessage, SessionDefaults, SessionRepository,
- SpawnContainer,
+ AgentKind, AgentRuntimeConfig, AnnounceOrigin, CommandOutcome, DeclinedMention, DeliverAction,
+ HarnessCommand, HarnessDefaults, MentionOrigin, OpenSession, PriorMessage, SessionBlocker,
+ SessionDefaults, SessionRepository, SpawnContainer,
};
use crate::domain::ports::{
AgentPromptComposer, ContainerManager as _, MessagePromptContext, NoPeers,
@@ -687,6 +687,29 @@ async fn revoked_origin_access_blocks_open_before_anything_is_provisioned() {
assert!(composer.calls().is_empty());
}
+#[tokio::test]
+async fn revoked_origin_access_blocks_the_connect_cursor_reply() {
+ let (service, repo, containers, announcer, _runtimes) = harness_with_edges(
+ PromptContextMock::unauthorized("removed from the channel"),
+ PromptComposerMock::default(),
+ );
+ containers.block_with(SessionBlocker::CursorNotConnected);
+ let mut command = open_command();
+ command.bot_id = bot_id::CURSOR_BOT_ID;
+ command.runtime.kind = AgentKind::Cursor;
+ command.runtime.harness = "cursor".to_owned();
+ let id = AgentSessionId::new();
+
+ let result = service.execute(id, HarnessCommand::Open(command)).await;
+
+ assert!(matches!(result, Err(HarnessError::PromptContext(_))));
+ assert!(repo.get(id).await.is_err());
+ assert_eq!(containers.spawned(), 0);
+ assert!(service.inner.egress.provisioned().is_empty());
+ assert!(announcer.announced().is_empty());
+ assert!(announcer.declined().is_empty());
+}
+
#[tokio::test]
async fn context_failure_still_calls_composer_with_empty_messages_and_delivers() {
let composer = PromptComposerMock::default();
@@ -797,6 +820,91 @@ async fn open_sends_context_but_not_agent_instructions_to_the_agent_prompt() {
);
}
+/// A provider mention from someone missing account setup: the bot answers in
+/// the thread with what to connect, and nothing is created for a session
+/// that could never spawn - no row, no egress token, no chip.
+#[tokio::test]
+async fn a_mention_its_sender_is_not_set_up_for_is_declined_in_the_thread() {
+ for (bot_id, kind, harness_slug, blocker) in [
+ (
+ bot_id::CURSOR_BOT_ID,
+ AgentKind::Cursor,
+ "cursor",
+ SessionBlocker::CursorNotConnected,
+ ),
+ (
+ bot_id::CODEX_BOT_ID,
+ AgentKind::CodexCloud,
+ "codex-cloud",
+ SessionBlocker::CodexNotConnected,
+ ),
+ (
+ bot_id::CODEX_BOT_ID,
+ AgentKind::CodexCloud,
+ "codex-cloud",
+ SessionBlocker::CodexEnvironmentNotConfigured,
+ ),
+ (
+ bot_id::CLAUDE_BOT_ID,
+ AgentKind::ClaudeCloud,
+ "claude-cloud",
+ SessionBlocker::ClaudeNotConnected,
+ ),
+ ] {
+ let (service, repo, containers, announcer, _runtimes) = harness();
+ let id = AgentSessionId::new();
+ containers.block_with(blocker);
+ let mut command = open_command();
+ command.bot_id = bot_id;
+ command.runtime.kind = kind;
+ command.runtime.harness = harness_slug.to_owned();
+ let origin = command.origin.clone();
+
+ let outcome = service
+ .execute(id, HarnessCommand::Open(command))
+ .await
+ .expect("a declined mention is handled, not failed");
+
+ assert_eq!(outcome, CommandOutcome::Completed);
+ assert!(repo.get(id).await.is_err(), "no session row is created");
+ assert_eq!(containers.spawned(), 0);
+ assert!(service.inner.egress.provisioned().is_empty());
+ assert!(announcer.announced().is_empty());
+ assert_eq!(
+ announcer.declined(),
+ [DeclinedMention {
+ bot_id,
+ origin: AnnounceOrigin {
+ parent: origin.parent,
+ thread_id: origin.thread_id,
+ message_id: origin.message_id,
+ },
+ triggered_by: origin.sender,
+ blocker,
+ }]
+ );
+ }
+}
+
+/// The decline is the whole answer, so failing to post it is the open's
+/// failure - the same way a session that cannot be announced is.
+#[tokio::test]
+async fn a_decline_that_cannot_be_posted_fails_the_open() {
+ let (service, repo, containers, announcer, _runtimes) = harness();
+ let id = AgentSessionId::new();
+ containers.block_with(SessionBlocker::CursorNotConnected);
+ announcer.fails("channel unavailable");
+
+ let error = service
+ .execute(id, HarnessCommand::Open(open_command()))
+ .await
+ .expect_err("the decline could not reach the thread");
+
+ assert!(matches!(error, HarnessError::Announce(_)));
+ assert!(repo.get(id).await.is_err(), "still no session row");
+ assert_eq!(containers.spawned(), 0);
+}
+
#[tokio::test]
async fn a_provisioning_failure_marks_the_session_disconnected() {
let (service, repo, containers, _announcer, _runtimes) = harness();
diff --git a/crates/agent_harness/src/outbound/channel_announcer.rs b/crates/agent_harness/src/outbound/channel_announcer.rs
index 3463a17fa3..18ce360f66 100644
--- a/crates/agent_harness/src/outbound/channel_announcer.rs
+++ b/crates/agent_harness/src/outbound/channel_announcer.rs
@@ -7,7 +7,9 @@ use std::sync::Arc;
use entity_access::domain::{models::BotAccessScope, ports::EntityAccessService};
use lexical_client::LexicalClient;
-use lexical_client::parse_markdown::{AgentAnnouncementChip, AgentAnnouncementReplyTarget};
+use lexical_client::parse_markdown::{
+ AgentAnnouncementChip, AgentAnnouncementReplyTarget, AgentConnectionChip, AgentConnectionPrompt,
+};
use messages::domain::{
api::MessageCommands,
models::{MessageAttribution, MessageParent, PostMessage, PostMessageNotificationPolicy},
@@ -15,9 +17,50 @@ use messages::domain::{
};
use crate::domain::error::{HarnessError, Result};
-use crate::domain::model::{AnnouncedMessage, SessionAnnouncement};
+use crate::domain::model::{
+ AnnouncedMessage, DeclinedMention, SessionAnnouncement, SessionBlocker,
+};
use crate::domain::ports::SessionAnnouncer;
+/// 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 {
+ SessionBlocker::CursorNotConnected => (
+ "@cursor",
+ "runs on your own Cursor account, and yours is not connected yet. Add your Cursor API key, then mention me again.",
+ "cursor",
+ "Cursor",
+ ),
+ SessionBlocker::CodexNotConnected => (
+ "@codex",
+ "runs on your own ChatGPT account. Connect Codex and select a cloud environment, then mention me again.",
+ "codex-cloud",
+ "Codex",
+ ),
+ SessionBlocker::CodexEnvironmentNotConfigured => (
+ "@codex",
+ "needs a cloud environment to run. Select an environment in Codex settings, then mention me again.",
+ "codex-cloud",
+ "Codex",
+ ),
+ SessionBlocker::ClaudeNotConnected => (
+ "@claude",
+ "runs on your own Claude account. Connect Claude, then mention me again.",
+ "claude-cloud",
+ "Claude",
+ ),
+ };
+ AgentConnectionPrompt {
+ agent_tag: agent_tag.to_owned(),
+ message: message.to_owned(),
+ chip: AgentConnectionChip {
+ app_slug: app_slug.to_owned(),
+ name: name.to_owned(),
+ target: "harness".to_owned(),
+ },
+ }
+}
+
fn announcement_chip(announcement: &SessionAnnouncement) -> AgentAnnouncementChip {
AgentAnnouncementChip {
agent_session_id: announcement.session_id.to_string(),
@@ -109,4 +152,42 @@ impl<Access: EntityAccessService> SessionAnnouncer for MessageAnnouncer<Access>
message_id: posted.id,
})
}
+
+ async fn decline(&self, declined: DeclinedMention) -> Result<()> {
+ 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(),
+ )
+ .await
+ .map_err(|error| HarnessError::Announce(rootcause::report!(error).into()))?;
+ let content = self
+ .lexical
+ .compose_agent_connection_prompt(&connection_prompt(declined.blocker))
+ .await
+ .map_err(|error| HarnessError::Announce(rootcause::report!(error).into()))?;
+ self.messages
+ .post(
+ access,
+ PostMessage {
+ attribution: MessageAttribution::ActingUser,
+ anchor: None,
+ content,
+ mentions: Vec::new(),
+ thread_id: Some(declined.origin.thread_id),
+ attachments: Vec::new(),
+ nonce: None,
+ // Unlike a session chip, this is the whole answer: the
+ // person who asked should hear it even if they have
+ // already looked away from the thread.
+ notification_policy: PostMessageNotificationPolicy::Default,
+ },
+ )
+ .await
+ .map_err(|error| HarnessError::Announce(rootcause::report!(error).into()))?;
+ Ok(())
+ }
}
diff --git a/crates/agent_harness/src/outbound/channel_announcer/test.rs b/crates/agent_harness/src/outbound/channel_announcer/test.rs
index d74432e6d2..98092413e3 100644
--- a/crates/agent_harness/src/outbound/channel_announcer/test.rs
+++ b/crates/agent_harness/src/outbound/channel_announcer/test.rs
@@ -36,6 +36,31 @@ fn chip_carries_the_announcement_identity() {
);
}
+#[test]
+fn declined_mentions_target_their_harness_settings() {
+ for (blocker, slug, name) in [
+ (SessionBlocker::CursorNotConnected, "cursor", "Cursor"),
+ (SessionBlocker::CodexNotConnected, "codex-cloud", "Codex"),
+ (
+ SessionBlocker::CodexEnvironmentNotConfigured,
+ "codex-cloud",
+ "Codex",
+ ),
+ (SessionBlocker::ClaudeNotConnected, "claude-cloud", "Claude"),
+ ] {
+ let prompt = connection_prompt(blocker);
+ assert_eq!(
+ prompt.chip,
+ AgentConnectionChip {
+ app_slug: slug.to_owned(),
+ name: name.to_owned(),
+ target: "harness".to_owned(),
+ }
+ );
+ assert!(prompt.message.contains("mention me again"));
+ }
+}
+
#[test]
fn reply_target_carries_the_originating_channel_message() {
assert_eq!(
diff --git a/crates/agent_harness/src/outbound/claude.rs b/crates/agent_harness/src/outbound/claude.rs
index c6aa482094..d6e33b3e8e 100644
--- a/crates/agent_harness/src/outbound/claude.rs
+++ b/crates/agent_harness/src/outbound/claude.rs
@@ -2,7 +2,7 @@
use crate::domain::{
claude::ClaudeSessions,
error::{HarnessError, Result},
- model::SpawnContainer,
+ model::{AgentKind, SessionBlocker, SpawnContainer},
model_load::{ClaudeModelProbe, ModelProbeError, RawModelProbe},
ports::{ContainerManager, SandboxEgressProvisioner},
sandbox::SandboxResizeEffect,
@@ -14,6 +14,7 @@ use agent_session::domain::{
ports::{AgentSessionRepo, ExternalSessionRepo},
};
use claude_cloud_agents::domain::{model::Error, ports::CloudProvider, service::Session};
+use macro_user_id::user_id::MacroUserIdStr;
use std::sync::Arc;
/// Adapts the Claude lifecycle service to the same provisioning port as other providers.
@@ -51,6 +52,14 @@ where
{
type Transport = ServerChannel;
+ async fn preflight(
+ &self,
+ _kind: AgentKind,
+ owner: &MacroUserIdStr<'_>,
+ ) -> Result<Option<SessionBlocker>> {
+ self.sessions.preflight(owner).await
+ }
+
async fn spawn(&self, command: SpawnContainer) -> Result<RuntimeAttachment<ServerChannel>> {
let session = self.sessions.attach(command.session_id).await?;
self.tokens
diff --git a/crates/agent_harness/src/outbound/codex.rs b/crates/agent_harness/src/outbound/codex.rs
index cb95ba1234..72e2b53cb5 100644
--- a/crates/agent_harness/src/outbound/codex.rs
+++ b/crates/agent_harness/src/outbound/codex.rs
@@ -1,9 +1,9 @@
//! Hosts per-owner Codex ACP conversations with PostgreSQL ownership fencing.
use super::acp_pipe::PipeTransport;
use crate::domain::{
- codex::{CODEX_PROVIDER, CodexRuntime},
+ codex::{CODEX_PROVIDER, CodexRuntime, connection_preflight},
error::{HarnessError, Result},
- model::SpawnContainer,
+ model::{AgentKind, SessionBlocker, SpawnContainer},
ports::ContainerManager,
sandbox::SandboxResizeEffect,
};
@@ -19,6 +19,7 @@ use codex_cloud_agents::domain::{
runtime::RuntimeIdentity,
};
use codex_connection::domain::ConnectionService;
+use macro_user_id::user_id::MacroUserIdStr;
use std::sync::Arc;
/// Provisions an ACP attachment; cloud execution begins only with a prompt.
@@ -139,6 +140,19 @@ impl<
> ContainerManager for CodexContainerManager<P, S, J>
{
type Transport = PipeTransport;
+ async fn preflight(
+ &self,
+ _kind: AgentKind,
+ owner: &MacroUserIdStr<'_>,
+ ) -> Result<Option<SessionBlocker>> {
+ let connections = self.connections.as_ref().ok_or_else(|| {
+ HarnessError::Container(
+ "Codex connection encryption is not configured on this deployment".into(),
+ )
+ })?;
+ connection_preflight(connections.as_ref(), owner).await
+ }
+
async fn spawn(&self, command: SpawnContainer) -> Result<RuntimeAttachment<PipeTransport>> {
self.attach(command.session_id).await
}
diff --git a/crates/agent_harness/src/outbound/cursor/manager.rs b/crates/agent_harness/src/outbound/cursor/manager.rs
index f9f2c34401..ee703288b8 100644
--- a/crates/agent_harness/src/outbound/cursor/manager.rs
+++ b/crates/agent_harness/src/outbound/cursor/manager.rs
@@ -41,11 +41,12 @@ use super::keys::CursorApiKeys;
use super::pipe::PipeTransport;
use super::repository_chooser::HaikuRepositoryChooser;
use crate::domain::error::{HarnessError, Result};
-use crate::domain::model::SpawnContainer;
+use crate::domain::model::{AgentKind, SessionBlocker, SpawnContainer};
use crate::domain::pending::PendingCommands;
use crate::domain::ports::{ContainerManager, ReachableRepositories};
use crate::domain::sandbox::SandboxResizeEffect;
use agent_session::domain::model::SandboxSize;
+use macro_user_id::user_id::MacroUserIdStr;
#[cfg(test)]
mod test;
@@ -523,14 +524,29 @@ where
{
type Transport = PipeTransport;
+ /// A `@cursor` session runs on its owner's key, so an owner without one
+ /// is told so before any session exists for them. The kind is not
+ /// consulted: the router only asks this manager about Cursor sessions.
+ async fn preflight(
+ &self,
+ _kind: AgentKind,
+ owner: &MacroUserIdStr<'_>,
+ ) -> Result<Option<SessionBlocker>> {
+ match self.keys.resolve(owner).await {
+ Ok(_) => Ok(None),
+ Err(HarnessError::CursorNotConnected) => Ok(Some(SessionBlocker::CursorNotConnected)),
+ Err(error) => Err(error),
+ }
+ }
+
async fn spawn(
&self,
command: SpawnContainer,
) -> Result<agent_session::domain::connection::RuntimeAttachment<PipeTransport>> {
- // The session row is read for its owner alone: spawning is the first
- // moment we can tell whether the person who mentioned @cursor has
- // connected an account, and refusing here is what turns "the bot
- // ignored me" into a sentence they can act on.
+ // The session row is read for its owner alone. The mention path has
+ // already asked [`Self::preflight`] about the owner's key; sessions
+ // opened from the create menu and older rows still reach the refusal
+ // here, so "the bot ignored me" stays a sentence they can act on.
let session = AgentSessionRepo::get(&self.sessions, command.session_id).await?;
let (client, default_model_id) = self.client_for(&session).await?;
// No MCP servers pass through here: they ride the ACP protocol
diff --git a/crates/agent_harness/src/outbound/cursor/manager/test.rs b/crates/agent_harness/src/outbound/cursor/manager/test.rs
index 24171d9009..a22cb472d2 100644
--- a/crates/agent_harness/src/outbound/cursor/manager/test.rs
+++ b/crates/agent_harness/src/outbound/cursor/manager/test.rs
@@ -405,6 +405,14 @@ impl CursorApiKeys for StubKeys {
}
}
+struct UnavailableKeys;
+
+impl CursorApiKeys for UnavailableKeys {
+ async fn resolve(&self, _owner: &MacroUserIdStr<'_>) -> Result<ResolvedCursorConfig> {
+ Err(HarnessError::Container("key decryption failed".to_owned()))
+ }
+}
+
/// A user who reaches no repository through the GitHub App: the chooser
/// short-circuits on an empty listing, so these tests drive the whole spawn
/// path without a model call.
@@ -427,11 +435,11 @@ fn manager(
manager_with_keys(base_url, sessions, StubKeys::connected())
}
-fn manager_with_keys(
+fn manager_with_keys<Keys: CursorApiKeys>(
base_url: String,
sessions: StubSessions,
- keys: StubKeys,
-) -> CursorContainerManager<StubSessions, StubKeys, NoRepositories, NoArtifactStore> {
+ keys: Keys,
+) -> CursorContainerManager<StubSessions, Keys, NoRepositories, NoArtifactStore> {
CursorContainerManager::with_memory_journal(
keys,
base_url,
@@ -854,6 +862,44 @@ async fn teardown_archives_and_forgets() {
);
}
+#[tokio::test]
+async fn preflight_only_requests_a_connection_when_no_key_is_saved() {
+ let owner = MacroUserIdStr::try_from_email("[email protected]").unwrap();
+ for (keys, expected) in [
+ (StubKeys::connected(), None),
+ (StubKeys::absent(), Some(SessionBlocker::CursorNotConnected)),
+ ] {
+ let manager = manager_with_keys(
+ "http://127.0.0.1:1".to_owned(),
+ StubSessions::default(),
+ keys,
+ );
+ assert_eq!(
+ manager.preflight(AgentKind::Cursor, &owner).await.unwrap(),
+ expected
+ );
+ }
+}
+
+#[tokio::test]
+async fn preflight_propagates_key_errors_instead_of_requesting_a_connection() {
+ let manager = manager_with_keys(
+ "http://127.0.0.1:1".to_owned(),
+ StubSessions::default(),
+ UnavailableKeys,
+ );
+ let owner = MacroUserIdStr::try_from_email("[email protected]").unwrap();
+
+ let error = manager
+ .preflight(AgentKind::Cursor, &owner)
+ .await
+ .unwrap_err();
+
+ assert!(
+ matches!(error, HarnessError::Container(message) if message == "key decryption failed")
+ );
+}
+
/// An owner who has not connected Cursor gets a sentence they can act on, not
/// a generic provisioning failure — this is the first run of `@cursor` for
/// everyone, so it is the error most users will ever see.
diff --git a/crates/agent_harness/src/outbound/routing.rs b/crates/agent_harness/src/outbound/routing.rs
index f387a32c2c..ee90cac047 100644
--- a/crates/agent_harness/src/outbound/routing.rs
+++ b/crates/agent_harness/src/outbound/routing.rs
@@ -18,10 +18,11 @@ use agent_session::domain::model::AgentSessionId;
use agent_session::domain::ports::AgentSessionRepo;
use crate::domain::error::{HarnessError, Result};
-use crate::domain::model::{AgentKind, SpawnContainer};
+use crate::domain::model::{AgentKind, SessionBlocker, SpawnContainer};
use crate::domain::ports::ContainerManager;
use crate::domain::sandbox::SandboxResizeEffect;
use agent_session::domain::model::SandboxSize;
+use macro_user_id::user_id::MacroUserIdStr;
#[cfg(test)]
mod test;
@@ -69,6 +70,22 @@ where
type Transport =
RoutedTransport<Sandbox::Transport, Cursor::Transport, Codex::Transport, Claude::Transport>;
+ async fn preflight(
+ &self,
+ kind: AgentKind,
+ owner: &MacroUserIdStr<'_>,
+ ) -> Result<Option<SessionBlocker>> {
+ match kind {
+ AgentKind::CodexCloud => self.codex.preflight(kind, owner).await,
+ AgentKind::ClaudeCloud => self.claude.preflight(kind, owner).await,
+ AgentKind::Cursor => self.cursor.preflight(kind, owner).await,
+ AgentKind::SandboxedCoder | AgentKind::InMemory => {
+ self.sandbox.preflight(kind, owner).await
+ }
+ AgentKind::External => Err(external_is_unroutable()),
+ }
+ }
+
async fn spawn(
&self,
command: SpawnContainer,
diff --git a/crates/agent_harness/src/outbound/routing/test.rs b/crates/agent_harness/src/outbound/routing/test.rs
index 128d6777ff..a20a2b8e62 100644
--- a/crates/agent_harness/src/outbound/routing/test.rs
+++ b/crates/agent_harness/src/outbound/routing/test.rs
@@ -56,6 +56,15 @@ impl TaggedManager {
impl ContainerManager for TaggedManager {
type Transport = TaggedTransport;
+ async fn preflight(
+ &self,
+ _kind: AgentKind,
+ _owner: &MacroUserIdStr<'_>,
+ ) -> Result<Option<SessionBlocker>> {
+ self.record("preflight");
+ Ok(None)
+ }
+
async fn spawn(
&self,
_command: SpawnContainer,
@@ -101,6 +110,11 @@ struct FixedBotSessions(BotId);
const CLAUDE_TEST_BOT: BotId = BotId::TEST_B;
+#[test]
+fn first_party_claude_routes_to_the_claude_provider() {
+ assert_eq!(AgentKind::of(bot_id::CLAUDE_BOT_ID), AgentKind::ClaudeCloud);
+}
+
impl AgentSessionRepo for FixedBotSessions {
async fn create(&self, _params: CreateAgentSessionParams) -> SessionResult<AgentSession> {
unimplemented!("the router never creates sessions")
@@ -271,6 +285,52 @@ async fn the_cursor_bot_routes_to_cursor_and_everything_else_to_the_sandbox() {
assert_eq!(sandbox.calls(), ["sandbox:spawn"]);
}
+/// Preflight has no session row yet, so it routes on the kind the trigger
+/// resolved, like spawn.
+#[tokio::test]
+async fn preflight_routes_by_kind_before_any_session_exists() {
+ let sandbox = TaggedManager::new("sandbox");
+ let cursor = TaggedManager::new("cursor");
+ let codex = TaggedManager::new("codex");
+ let claude = TaggedManager::new("claude");
+ let router = RoutedContainerManager::new(
+ sandbox.clone(),
+ cursor.clone(),
+ codex.clone(),
+ claude.clone(),
+ FixedBotSessions(bot_id::CURSOR_BOT_ID),
+ );
+ let owner = MacroUserIdStr::try_from_email("[email protected]").expect("a valid user id");
+
+ assert_eq!(
+ router.preflight(AgentKind::Cursor, &owner).await.unwrap(),
+ None
+ );
+ assert_eq!(
+ router.preflight(AgentKind::InMemory, &owner).await.unwrap(),
+ None
+ );
+ assert_eq!(
+ router
+ .preflight(AgentKind::CodexCloud, &owner)
+ .await
+ .unwrap(),
+ None
+ );
+ assert_eq!(
+ router
+ .preflight(AgentKind::ClaudeCloud, &owner)
+ .await
+ .unwrap(),
+ None
+ );
+ assert!(router.preflight(AgentKind::External, &owner).await.is_err());
+ assert_eq!(cursor.calls(), ["cursor:preflight"]);
+ assert_eq!(sandbox.calls(), ["sandbox:preflight"]);
+ assert_eq!(codex.calls(), ["codex:preflight"]);
+ assert_eq!(claude.calls(), ["claude:preflight"]);
+}
+
/// Resume and teardown route by the session row's bot — the repo says cursor
/// here, so the sandbox provider must never hear about the session.
#[tokio::test]
diff --git a/crates/agent_harness/src/testing/helpers/announcer.rs b/crates/agent_harness/src/testing/helpers/announcer.rs
index ecc8b95cec..b271cde1cf 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, SessionAnnouncement};
+use crate::domain::model::{AnnouncedMessage, DeclinedMention, SessionAnnouncement};
use crate::domain::ports::SessionAnnouncer;
/// A [`SessionAnnouncer`] that records instead of posting. Cloning shares one
@@ -11,6 +11,7 @@ use crate::domain::ports::SessionAnnouncer;
#[derive(Clone, Default)]
pub struct AnnouncerMock {
announced: Arc<Mutex<Vec<(SessionAnnouncement, AnnouncedMessage)>>>,
+ declined: Arc<Mutex<Vec<DeclinedMention>>>,
/// When set, every announce fails with this message.
failure: Arc<Mutex<Option<String>>>,
}
@@ -42,6 +43,15 @@ impl AnnouncerMock {
.collect()
}
+ /// Every mention declined, in order.
+ #[must_use]
+ pub fn declined(&self) -> Vec<DeclinedMention> {
+ self.declined
+ .lock()
+ .expect("announcer mock declined lock should not be poisoned")
+ .clone()
+ }
+
/// The message each recorded announcement became, in order.
#[must_use]
pub fn announced_messages(&self) -> Vec<AnnouncedMessage> {
@@ -74,4 +84,20 @@ impl SessionAnnouncer for AnnouncerMock {
.push((announcement, message));
Ok(message)
}
+
+ async fn decline(&self, declined: DeclinedMention) -> 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.declined
+ .lock()
+ .expect("announcer mock declined lock should not be poisoned")
+ .push(declined);
+ Ok(())
+ }
}
diff --git a/crates/agent_harness/src/testing/helpers/containers.rs b/crates/agent_harness/src/testing/helpers/containers.rs
index 8d4a9a4c6a..24804c16b3 100644
--- a/crates/agent_harness/src/testing/helpers/containers.rs
+++ b/crates/agent_harness/src/testing/helpers/containers.rs
@@ -15,10 +15,11 @@ use agent_session::domain::model::{AgentSessionId, SandboxSize};
use tokio::sync::mpsc::{UnboundedReceiver, UnboundedSender, unbounded_channel};
use crate::domain::error::{HarnessError, Result};
-use crate::domain::model::SpawnContainer;
+use crate::domain::model::{AgentKind, SessionBlocker, SpawnContainer};
use crate::domain::ports::ContainerManager;
use crate::domain::sandbox::{SandboxResizeEffect, create_only_resize_effect, resize_effect};
use crate::testing::helpers::agent::FakeAgent;
+use macro_user_id::user_id::MacroUserIdStr;
/// A container connection driven by hand.
///
@@ -196,6 +197,7 @@ impl TransportReceiver<ToServerMessage> for ContainerReceiver {
#[derive(Clone, Default)]
pub struct MockContainerManager {
containers: Arc<Mutex<HashMap<AgentSessionId, ContainerMock>>>,
+ blocker: Arc<Mutex<Option<SessionBlocker>>>,
spawn_error: Arc<Mutex<Option<String>>>,
spawn_sizes: Arc<Mutex<Vec<SandboxSize>>>,
resizes: Arc<Mutex<Vec<(AgentSessionId, SandboxSize)>>>,
@@ -229,6 +231,15 @@ impl MockContainerManager {
self.lock().len()
}
+ /// Answer every preflight with `blocker` from now on: the owner is not
+ /// set up for this provider.
+ pub fn block_with(&self, blocker: SessionBlocker) {
+ *self
+ .blocker
+ .lock()
+ .expect("blocker lock should not be poisoned") = Some(blocker);
+ }
+
/// Make the next sandbox spawn fail with `message`.
pub fn fail_next_spawn(&self, message: impl Into<String>) {
*self
@@ -282,6 +293,17 @@ impl MockContainerManager {
impl ContainerManager for MockContainerManager {
type Transport = ContainerMock;
+ async fn preflight(
+ &self,
+ _kind: AgentKind,
+ _owner: &MacroUserIdStr<'_>,
+ ) -> Result<Option<SessionBlocker>> {
+ Ok(*self
+ .blocker
+ .lock()
+ .expect("blocker lock should not be poisoned"))
+ }
+
async fn spawn(
&self,
command: SpawnContainer,
diff --git a/crates/bot_id/src/lib.rs b/crates/bot_id/src/lib.rs
index 3aad6e6592..a4b24cf146 100644
--- a/crates/bot_id/src/lib.rs
+++ b/crates/bot_id/src/lib.rs
@@ -122,6 +122,13 @@ pub const CODEX_HANDLE: &str = "codex";
/// Display name for Codex.
pub const CODEX_NAME: &str = "Codex";
+/// Stable identity for the per-owner Claude cloud agent.
+pub const CLAUDE_BOT_ID: BotId = BotId::new_from_uuid(Uuid::from_u128(0xc1a0));
+/// Mention handle for Claude.
+pub const CLAUDE_HANDLE: &str = "claude";
+/// Display name for Claude.
+pub const CLAUDE_NAME: &str = "Claude";
+
/// Stable handle for the autonomous Macro platform principal.
pub const MACRO_SYSTEM_HANDLE: &str = "macro-system";
@@ -179,6 +186,12 @@ pub const SYSTEM_BOTS: &[SystemBot] = &[
handle: CODEX_HANDLE,
has_agent: true,
},
+ SystemBot {
+ id: CLAUDE_BOT_ID,
+ name: CLAUDE_NAME,
+ handle: CLAUDE_HANDLE,
+ has_agent: true,
+ },
// Posts as itself for autonomous platform operations, but nothing mentions
// it and it opens no sessions.
SystemBot {
diff --git a/crates/bot_id/src/test.rs b/crates/bot_id/src/test.rs
index 0369f925a7..3fc39f872e 100644
--- a/crates/bot_id/src/test.rs
+++ b/crates/bot_id/src/test.rs
@@ -63,6 +63,20 @@ fn rejects_non_bot_storage_string() {
assert!(BotIdStr::parse_from_str("macro|[email protected]").is_err());
}
+#[test]
+fn claude_is_a_global_system_agent_with_a_distinct_identity() {
+ let claude = system_bot(CLAUDE_BOT_ID).unwrap();
+ assert_eq!(claude.handle, "claude");
+ assert_eq!(claude.name, "Claude");
+ assert!(claude.has_agent);
+ assert_eq!(
+ CLAUDE_BOT_ID.to_string(),
+ "00000000-0000-0000-0000-00000000c1a0"
+ );
+ let ids: std::collections::HashSet<_> = SYSTEM_BOTS.iter().map(|bot| bot.id).collect();
+ assert_eq!(ids.len(), SYSTEM_BOTS.len());
+}
+
#[test]
fn rejects_trailing_storage_content() {
let uuid = Uuid::new_v4();
diff --git a/crates/lexical_client/src/parse_markdown.rs b/crates/lexical_client/src/parse_markdown.rs
index 500b8b3a60..370aeca975 100644
--- a/crates/lexical_client/src/parse_markdown.rs
+++ b/crates/lexical_client/src/parse_markdown.rs
@@ -1,3 +1,6 @@
+#[cfg(test)]
+mod test;
+
use super::LexicalClient;
use crate::types::{CognitionResponseData, CognitionV2ResponseData};
use messages::domain::models::MessageParent;
@@ -177,6 +180,36 @@ struct AgentAnnouncementResponse {
markdown: String,
}
+/// Connection chip metadata interpreted by the editor and lexical service.
+#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct AgentConnectionChip {
+ /// Integration or harness slug.
+ pub app_slug: String,
+ /// Display name on the connection chip.
+ pub name: String,
+ /// Settings surface: `connections` or `harness`.
+ pub target: String,
+}
+
+/// Structured explanation and action for a mention that requires account setup.
+#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct AgentConnectionPrompt {
+ /// Bot handle rendered as inline code, such as `@cursor`.
+ pub agent_tag: String,
+ /// Plain text explaining the required setup.
+ pub message: String,
+ /// Connection action rendered by Lexical.
+ pub chip: AgentConnectionChip,
+}
+
+#[derive(serde::Serialize)]
+#[serde(rename_all = "camelCase")]
+struct AgentConnectionPromptRequest<'a> {
+ connection_prompt: &'a AgentConnectionPrompt,
+}
+
/// A channel message included as context for an agent prompt.
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]
pub struct AgentContextMessage<'a> {
@@ -427,6 +460,28 @@ impl LexicalClient {
Ok(data.markdown)
}
+ /// Compose an account setup reply through the lexical service's real nodes.
+ #[tracing::instrument(skip(self, prompt), err)]
+ pub async fn compose_agent_connection_prompt(
+ &self,
+ prompt: &AgentConnectionPrompt,
+ ) -> Result<String> {
+ let url = format!("{}/agent-announcement", self.url);
+ let response = check_response(
+ self.client
+ .post(&url)
+ .json(&AgentConnectionPromptRequest {
+ connection_prompt: prompt,
+ })
+ .send()
+ .await?,
+ )
+ .await?;
+ let data: AgentAnnouncementResponse =
+ response.json().await.context("unexpected response")?;
+ Ok(data.markdown)
+ }
+
/// Sanitizes an agent prompt and optionally composes it with prior-message
/// context via the lexical service, so internal nodes and escaping are
/// handled by Lexical rather than assembled manually by the caller.
diff --git a/crates/lexical_client/src/parse_markdown/test.rs b/crates/lexical_client/src/parse_markdown/test.rs
new file mode 100644
index 0000000000..8994e329f8
--- /dev/null
+++ b/crates/lexical_client/src/parse_markdown/test.rs
@@ -0,0 +1,28 @@
+use super::*;
+
+#[test]
+fn connection_prompt_matches_the_lexical_service_request() {
+ let prompt = AgentConnectionPrompt {
+ agent_tag: "@claude".into(),
+ message: "Connect Claude, then mention me again.".into(),
+ chip: AgentConnectionChip {
+ app_slug: "claude-cloud".into(),
+ name: "Claude".into(),
+ target: "harness".into(),
+ },
+ };
+ let wire = serde_json::to_value(AgentConnectionPromptRequest {
+ connection_prompt: &prompt,
+ })
+ .unwrap();
+ assert_eq!(
+ wire,
+ serde_json::json!({
+ "connectionPrompt": {
+ "agentTag": "@claude",
+ "message": "Connect Claude, then mention me again.",
+ "chip": { "appSlug": "claude-cloud", "name": "Claude", "target": "harness" }
+ }
+ })
+ );
+}
diff --git a/docs/AGENT_GUIDE/channels.md b/docs/AGENT_GUIDE/channels.md
index cfa8d78363..6488851a26 100644
--- a/docs/AGENT_GUIDE/channels.md
+++ b/docs/AGENT_GUIDE/channels.md
@@ -110,7 +110,7 @@ event is created — no invitation goes out from the initial request. It cannot
email at all. The bot's prompt carries the current date and time in the mentioning user's
own time zone (their primary calendar's), so it resolves relative times ("tomorrow at 4",
"EOD") without asking; when no calendar is connected the prompt falls back to UTC and the
-bot asks before scheduling a specific clock time. `@macro-new` / `@coder` / `@cursor` / `@codex` open
+bot asks before scheduling a specific clock time. `@macro-new` / `@coder` / `@cursor` / `@codex` / `@claude` open
an agent session; follow-up
`@` mentions of that bot in the same thread route to it.
A follow-up sent while that session is still working stops the current turn,
@@ -129,9 +129,16 @@ cropped at the chip's height with a fade at its foot; clicking it expands it in
clicking again collapses it. Before anything is there to expand, clicking the area also
opens the session.
-`@codex` requires both `enable-chat-v3-agents` and `enable-codex-agents`.
-It appears when the mentioning user has connected ChatGPT and saved a
-cloud environment in Settings → Harness. New sessions use that environment on
+`@codex` and `@claude` are offered to every user before account setup. The built-in
+`@cursor` entry requires the `enable-cursor-agents` rollout flag (local override:
+`VITE_ENABLE_CURSOR_AGENTS`). Custom agents keep their channel visibility rules
+regardless of which harness they use.
+A mention without a connected account creates no session and replies in the thread
+with a **Connect Cursor**, **Connect Codex**, or **Connect Claude** chip. Each chip
+opens Settings → Harness, where all three connection cards are visible. The same
+chip reads **connected** after setup; mention the bot again to start a session.
+Codex also prompts for a cloud environment when ChatGPT is connected but no
+environment has been saved. New sessions use that environment on
`main`; there is no automatic repository selection. Follow-up mentions continue the same agent session. When
the provider URL arrives, the session header offers **Open in Codex**. Codex
assistant text appears as complete messages while tool activity and thinking
@@ -139,6 +146,13 @@ can continue updating during the turn. Mention
eligibility is covered by component/query tests; the channel interaction requires
a configured backend for end-to-end verification.
+Within the Cursor rollout, `@cursor` is offered whether connected or not. A mention from someone with
+no Cursor API key opens no session: the Cursor bot replies in the thread that
+`@cursor` runs on their own account and is not connected yet, followed by a
+**Connect Cursor** chip. Clicking the chip opens Settings → Harness; once a key
+is saved the same chip reads **Cursor connected** and stops navigating. The
+original mention is not replayed - mention `@cursor` again after connecting.
+
Cursor sessions choose a repository from the mentioning user's linked GitHub App
installations on their first prompt. A session without a repository can still use
Macro and connected MCP tools, but cannot use the Git proxy. For a PR smoke test,
diff --git a/docs/AGENT_GUIDE/surfaces.md b/docs/AGENT_GUIDE/surfaces.md
index 248c6e904a..a3305fad7b 100644
--- a/docs/AGENT_GUIDE/surfaces.md
+++ b/docs/AGENT_GUIDE/surfaces.md
@@ -722,7 +722,8 @@ a retryable error without hiding the other harnesses. Editing preserves a saved
is no longer offered and labels it `saved, unavailable`. A macrod with no responding runtime
can remain loading until the 10-second discovery timeout; use Retry after reconnecting it.
-`Harness` configures Cursor, Codex, and paired macrod runtimes. Cursor's default-model picker uses
+`Harness` shows Cursor, Claude, Codex, and paired macrod runtimes to every user.
+Connection chips in agent replies open this page, including before any account is connected. Cursor's default-model picker uses
the same live model discovery and retains its existing save action.
The Codex row uses the OpenAI logo and the same icon, button, and status styling
diff --git a/docs/CURSOR_AGENT_TRANSPORT.md b/docs/CURSOR_AGENT_TRANSPORT.md
index 3cb1abc1f3..b6504b8fea 100644
--- a/docs/CURSOR_AGENT_TRANSPORT.md
+++ b/docs/CURSOR_AGENT_TRANSPORT.md
@@ -99,23 +99,37 @@ Behaves exactly like Macro Coder: mention it, a session opens, the bot posts the
magic-chip announcement into the thread, the mention text becomes the first
prompt, follow-up mentions in the thread route to the same session.
-Gated on key registration. A user with no Cursor key registered should not see
-`@cursor` in the mention autocomplete, and a mention that somehow arrives anyway
-must fail with a message telling them to register a key — never silently drop.
-
-**How the gate works.** The mention autocomplete reads
-`useChannelBotsQuery` → `GET /channels/{id}/bots`
-(`apps/web/src/lib/queries/channel/channel-bots.ts:31`). That endpoint already
-authenticates the caller, so the filter belongs there: omit `@cursor` from the
-response when the caller has no row in `cursor_api_key`. One `LEFT JOIN` on the
-authenticated user.
-
-No new endpoint, no new frontend query, no client-side join, and no window where
-the autocomplete offers a bot that would fail. The check mirrors
-`is_managed_bot` — a hardcoded `CURSOR_BOT_ID` comparison in the channel-bots
-read. When there is a second credential-gated bot, this becomes a
-`requires_user_credential` column on `bots` and the filter goes declarative; for
-one bot that is premature.
+The `enable-cursor-agents` frontend rollout flag controls the built-in `@cursor`
+mention (local override: `VITE_ENABLE_CURSOR_AGENTS`). Custom agents keep their
+channel visibility rules. Within the rollout,
+mentions are offered before key registration. A mention from someone with no
+key must be answered, never silently dropped or turned into a session that
+cannot spawn. The rollout flag is not a backend authorization boundary.
+
+**How the keyless mention is handled.** Before `open` creates anything, the
+domain asks `ContainerManager::preflight(kind, owner)`. The Cursor manager
+resolves the owner's configuration through `CursorApiKeys::resolve`: a missing
+key yields `SessionBlocker::CursorNotConnected`, while read/decryption failures
+remain errors. A successful preflight decrypts the key, and spawn resolves it
+again. Codex and Claude perform the same account preflight; providers requiring no user connection take the default `Ok(None)`.
+On a blocker the domain calls `SessionAnnouncer::decline` with a
+`DeclinedMention` and returns without a session row, an egress token, or an
+announcement. `MessageAnnouncer::decline` posts as the bot with the sender's
+current write access into the mention's
+thread. The lexical service composes the explanation and connection chip from real Lexical nodes. The Cursor chip payload is
+`{"appSlug":"cursor","name":"Cursor","target":"harness"}`. The frontend's
+`ConnectAppNode` reads `target: "harness"` as "open Settings → Harness, and
+show connected once this reader's own key status says so".
+
+The original design hid `@cursor` until a key existed. That is why nobody
+found it: discovery *is* the feature. Hiding was also never enforcement — a
+mention can arrive from a copied message or another client — so the refusal
+had to live in the harness regardless. The create composer keeps its own
+**Connect Cursor** button for the same reason; it never posts anything.
+
+`CursorContainerManager::spawn` still resolves the key and still fails with
+`HarnessError::CursorNotConnected` when it is gone: sessions opened from the
+create menu, and rows written before the preflight existed, reach it.
Settings needs its own small surface regardless, for the connections tab:
`GET /me/cursor-key` → `{ registered: bool }`, `PUT` to set, `DELETE` to revoke.
@@ -649,14 +663,13 @@ reported as bugs:
without a frame in either direction closes the pipe, reclaiming its tasks
and its poll; the session parks on a clean disconnect and the next prompt
resumes it. A parked session mirrors nothing until then.
-- **A provisioning failure does not reach the thread.** The open path
- announces the session before it spawns, so when spawn fails — most often
- because the mentioning user has not registered a Cursor key — the session
- is marked disconnected and the reason goes to a log. What the user sees is
- a session chip that never answers. `SessionAnnouncer` announces sessions
- and nothing else, so closing this needs a way to post a failure back to
- the originating thread. `HarnessError::CursorNotConnected` already carries
- the sentence to post; it has nowhere to go yet.
+- **A provisioning failure does not reach the thread.** When spawn fails
+ after the session row exists, the session is marked disconnected and the
+ reason goes to a log. The most common cause — the mentioning user has no
+ Cursor key — no longer gets this far: `ContainerManager::preflight` catches
+ it before the row and `SessionAnnouncer::decline` answers in the thread.
+ Other spawn failures (Cursor API down, a key that no longer decrypts) still
+ end in a log rather than a reply.
- **One run at a time per agent.** Cursor returns `409 agent_busy`. Already
matched by the service's sequential-turn rule, so this surfaces as a clean
error rather than a race.
@@ -670,7 +683,8 @@ reported as bugs:
3. **`CursorContainerManager` + routing** — the manager, `RoutedTransport`,
`bot_id` on `SpawnContainer`, `is_managed_bot` as a set, composition root.
4. **Settings + `@cursor` gating** — the connections UI, key validation via
- `GET /v1/me`, mention-autocomplete filtering.
+ `GET /v1/me`, mention-autocomplete filtering (since replaced by the
+ preflight-and-decline reply above).
5. **Sessions page link** — the joined read and the provider logo.
Steps 1 and 2 are independent and can go in parallel.
@@ -694,7 +708,8 @@ Steps 1 and 2 are independent and can go in parallel.
Resolved in review: the external table alone (no `agent_session` column), one
global seeded `@cursor` system bot, channel-bots server-side filtering for the
-mention gate, hardcoded `macro-inc/macro` repo, and omitted model.
+mention gate (later replaced by the in-thread decline, so `@cursor` is offered to
+everyone), hardcoded `macro-inc/macro` repo, and omitted model.
1. **Do we store user keys at all in v1?** **Yes.** Sub-tokens were the
alternative, and they lose the property that makes this feature legible: the
@@ -702,7 +717,7 @@ mention gate, hardcoded `macro-inc/macro` repo, and omitted model.
and their repo access. There is no deployment-wide `CURSOR_API_KEY` — the
manager resolves the session owner's key from `cursor_api_keys` at every
spawn, resume, and teardown, and a user who has not connected Cursor gets
- `HarnessError::CursorNotConnected` in the channel rather than a silent skip.
+ the bot's connect reply in the channel rather than a silent skip.
2. **Lazy or eager agent creation?** **Lazy**, as leaned. `RecordingCursor`
decorates `CursorAgents` and writes the `external_agent_session` row inside
`create_agent`, before it returns — so no prompt can be answered by an agent
diff --git a/packages/lexical-core/nodes/ConnectAppNode.ts b/packages/lexical-core/nodes/ConnectAppNode.ts
index 78f6ca6f85..84137b24b8 100644
--- a/packages/lexical-core/nodes/ConnectAppNode.ts
+++ b/packages/lexical-core/nodes/ConnectAppNode.ts
@@ -13,20 +13,34 @@ import {
import { type DecoratorComponent, getDecorator } from '../decoratorRegistry';
import { $applyIdFromSerialized } from '../plugins/nodeIdPlugin';
-const VERSION = 1;
+const VERSION = 2;
/**
* The tag an agent emits when a tool call failed because the person running
- * the session has not connected an app. Mirrors the egress proxy's
- * `CONNECT_APP_TAG`; the payload shape is `{"appSlug": ..., "name": ...}`.
+ * the session has not connected an app, and the tag the harness posts when
+ * `@cursor` was mentioned by someone without a Cursor key. Mirrors the
+ * backend's `CONNECT_APP_TAG`; the payload shape is
+ * `{"appSlug": ..., "name": ..., "target"?: ...}`.
*/
export const CONNECT_APP_TAG = 'm-connect-app';
+/**
+ * Where the chip sends the reader to connect. Absent in older payloads, which
+ * were all Pipedream apps, so `connections` is the default.
+ */
+export const CONNECT_APP_TARGETS = ['connections', 'harness'] as const;
+
+export type ConnectAppTarget = (typeof CONNECT_APP_TARGETS)[number];
+
+export const DEFAULT_CONNECT_APP_TARGET: ConnectAppTarget = 'connections';
+
export type ConnectAppInfo = {
- /** Pipedream app slug, e.g. `linear`. */
+ /** Pipedream app slug (`linear`) or a harness slug (`cursor`). */
appSlug: string;
/** Display name, e.g. `Linear`. */
name: string;
+ /** Settings surface the chip connects through. */
+ target: ConnectAppTarget;
};
export type SerializedConnectAppNode = Spread<
@@ -44,17 +58,23 @@ export function isConnectAppSlug(value: unknown): value is string {
return typeof value === 'string' && /^[a-z0-9_-]+$/.test(value);
}
+export function isConnectAppTarget(value: unknown): value is ConnectAppTarget {
+ return (CONNECT_APP_TARGETS as readonly unknown[]).includes(value);
+}
+
/**
- * An inline chip offering to connect one Pipedream app. Rendered from a reply
- * the agent wrote after the egress proxy told it the app was not connected
- * for the session owner; clicking it takes the reader to Settings →
- * Connections with that app ready to connect.
+ * An inline chip offering to connect one integration. Rendered from a reply
+ * the agent wrote after the egress proxy told it a Pipedream app was not
+ * connected for the session owner, or from the reply the Cursor bot posts
+ * when its mentioner has no Cursor key; clicking it takes the reader to the
+ * settings surface named by `target` with that integration ready to connect.
*/
export class ConnectAppNode extends DecoratorNode<
DecoratorComponent<ConnectAppDecoratorProps> | undefined
> {
__appSlug: string;
__name: string;
+ __target: ConnectAppTarget;
static getType() {
return 'connect-app';
@@ -69,19 +89,33 @@ export class ConnectAppNode extends DecoratorNode<
}
static clone(node: ConnectAppNode) {
- return new ConnectAppNode(node.__appSlug, node.__name, node.__key);
+ return new ConnectAppNode(
+ node.__appSlug,
+ node.__name,
+ node.__target,
+ node.__key
+ );
}
- constructor(appSlug: string, name: string, key?: NodeKey) {
+ constructor(
+ appSlug: string,
+ name: string,
+ target: ConnectAppTarget = DEFAULT_CONNECT_APP_TARGET,
+ key?: NodeKey
+ ) {
super(key);
this.__appSlug = appSlug;
this.__name = name;
+ this.__target = target;
}
static importJSON(serializedNode: SerializedConnectAppNode) {
const node = $createConnectAppNode(
serializedNode.appSlug,
- serializedNode.name
+ serializedNode.name,
+ isConnectAppTarget(serializedNode.target)
+ ? serializedNode.target
+ : DEFAULT_CONNECT_APP_TARGET
);
$applyIdFromSerialized(node, serializedNode);
return node;
@@ -92,13 +126,18 @@ export class ConnectAppNode extends DecoratorNode<
...super.exportJSON(),
appSlug: this.__appSlug,
name: this.__name,
+ target: this.__target,
type: ConnectAppNode.getType(),
version: VERSION,
};
}
exportComponentProps(): ConnectAppInfo {
- return { appSlug: this.__appSlug, name: this.__name };
+ return {
+ appSlug: this.__appSlug,
+ name: this.__name,
+ target: this.__target,
+ };
}
createDOM(_config: EditorConfig): HTMLElement {
@@ -135,6 +174,10 @@ export class ConnectAppNode extends DecoratorNode<
return this.__name;
}
+ getTarget(): ConnectAppTarget {
+ return this.__target;
+ }
+
decorate(_: LexicalEditor, config: EditorConfig) {
const decorator = getDecorator<ConnectAppDecoratorProps>(ConnectAppNode);
if (decorator) {
@@ -142,6 +185,7 @@ export class ConnectAppNode extends DecoratorNode<
decorator({
appSlug: this.__appSlug,
name: this.__name,
+ target: this.__target,
key: this.getKey(),
theme: config.theme,
});
@@ -151,9 +195,10 @@ export class ConnectAppNode extends DecoratorNode<
export function $createConnectAppNode(
appSlug: string,
- name: string
+ name: string,
+ target: ConnectAppTarget = DEFAULT_CONNECT_APP_TARGET
): ConnectAppNode {
- return $applyNodeReplacement(new ConnectAppNode(appSlug, name));
+ return $applyNodeReplacement(new ConnectAppNode(appSlug, name, target));
}
export function $isConnectAppNode(
diff --git a/packages/lexical-core/tests/agent-connection-prompt.test.ts b/packages/lexical-core/tests/agent-connection-prompt.test.ts
new file mode 100644
index 0000000000..5d2bd8a1e7
--- /dev/null
+++ b/packages/lexical-core/tests/agent-connection-prompt.test.ts
@@ -0,0 +1,36 @@
+import { describe, expect, it } from 'vitest';
+import { composeAgentConnectionPrompt } from '../utils/agent-connection-prompt';
+import { markdownToSerializedEditorStateWithIds } from '../utils/markdown-state';
+
+describe('composeAgentConnectionPrompt', () => {
+ it.each([
+ ['cursor', 'Cursor', '@cursor'],
+ ['codex-cloud', 'Codex', '@codex'],
+ ['claude-cloud', 'Claude', '@claude'],
+ ])(
+ 'round-trips the %s setup reply through real Lexical nodes',
+ (appSlug, name, agentTag) => {
+ const chip = { appSlug, name, target: 'harness' as const };
+ const markdown = composeAgentConnectionPrompt({
+ agentTag,
+ message: 'Connect your account, then mention me again.',
+ chip,
+ });
+ expect(markdown).toBe(
+ `\`${agentTag}\` Connect your account, then mention me again. <m-connect-app>${JSON.stringify(chip)}</m-connect-app>`
+ );
+ const state = markdownToSerializedEditorStateWithIds(markdown);
+ expect(state.root.children[0]).toMatchObject({
+ type: 'paragraph',
+ children: [
+ { type: 'text', text: agentTag, format: 16 },
+ {
+ type: 'text',
+ text: ' Connect your account, then mention me again. ',
+ },
+ { type: 'connect-app', ...chip },
+ ],
+ });
+ }
+ );
+});
diff --git a/packages/lexical-core/tests/connect-app.test.ts b/packages/lexical-core/tests/connect-app.test.ts
index 9fb86d6a53..a3ec13066f 100644
--- a/packages/lexical-core/tests/connect-app.test.ts
+++ b/packages/lexical-core/tests/connect-app.test.ts
@@ -12,6 +12,8 @@ import { markdownToEmbeddingText, markdownToPlainText } from '../utils/parsers';
const TAG =
'<m-connect-app>{"appSlug":"linear","name":"Linear"}</m-connect-app>';
+const HARNESS_TAG =
+ '<m-connect-app>{"appSlug":"cursor","name":"Cursor","target":"harness"}</m-connect-app>';
function editorWith(markdown: string, transformers = ALL_TRANSFORMERS) {
const editor = createEditor({
@@ -54,6 +56,27 @@ describe('connect-app chip', () => {
expect(chip).toBeInstanceOf(ConnectAppNode);
expect(chip?.getAppSlug()).toBe('linear');
expect(chip?.getName()).toBe('Linear');
+ expect(chip?.getTarget()).toBe('connections');
+ });
+
+ it('parses the harness-targeted tag the Cursor bot posts and round-trips it', () => {
+ const editor = editorWith(`Almost: ${HARNESS_TAG}`);
+ const chip = inlineNodes(editor).find($isConnectAppNode);
+ expect(chip?.getAppSlug()).toBe('cursor');
+ expect(chip?.getTarget()).toBe('harness');
+ const exported = editor
+ .getEditorState()
+ .read(() => $convertToMarkdownString(ALL_TRANSFORMERS));
+ expect(exported).toContain(HARNESS_TAG);
+ });
+
+ it('falls back to the unknown-mention chip for a target it does not know', () => {
+ const editor = editorWith(
+ '<m-connect-app>{"appSlug":"cursor","name":"Cursor","target":"desktop"}</m-connect-app>'
+ );
+ const nodes = inlineNodes(editor);
+ expect(nodes.some($isConnectAppNode)).toBe(false);
+ expect(nodes.some($isUnknownMentionNode)).toBe(true);
});
it('renders inside the magic chip, which uses the external transformers', () => {
@@ -90,5 +113,8 @@ describe('connect-app chip', () => {
expect(markdownToEmbeddingText(`Do this: ${TAG}`)).toBe(
'Do this: Connect Linear'
);
+ expect(markdownToPlainText(`Do this: ${HARNESS_TAG}`)).toBe(
+ 'Do this: Connect Cursor'
+ );
});
});
diff --git a/packages/lexical-core/transformers/mentions.ts b/packages/lexical-core/transformers/mentions.ts
index 1de85f0ece..eb81d06f8f 100644
--- a/packages/lexical-core/transformers/mentions.ts
+++ b/packages/lexical-core/transformers/mentions.ts
@@ -11,7 +11,9 @@ import {
import {
CONNECT_APP_TAG,
ConnectAppNode,
+ DEFAULT_CONNECT_APP_TARGET,
isConnectAppSlug,
+ isConnectAppTarget,
} from '../nodes/ConnectAppNode';
import { ContactMentionNode } from '../nodes/ContactMentionNode';
import { DateMentionNode } from '../nodes/DateMentionNode';
@@ -575,9 +577,14 @@ export const I_CONNECT_APP: TextMatchTransformer = {
importRegExp: new RegExp(`<${CONNECT_APP_TAG}>(.*?)</${CONNECT_APP_TAG}>`),
export: (node) => {
if (!(node instanceof ConnectAppNode)) return null;
+ const target = node.getTarget();
const data = JSON.stringify({
appSlug: node.getAppSlug(),
name: node.getName(),
+ // Older payloads carry no target and mean the default; keep emitting
+ // them that way so a chip written before targets existed round-trips
+ // unchanged.
+ ...(target === DEFAULT_CONNECT_APP_TARGET ? {} : { target }),
});
return `<${CONNECT_APP_TAG}>${data}</${CONNECT_APP_TAG}>`;
},
@@ -587,14 +594,19 @@ export const I_CONNECT_APP: TextMatchTransformer = {
if (typeof parsed !== 'object' || parsed === null) {
throw new Error('Invalid connect-app JSON');
}
- const { appSlug, name } = parsed as Record<string, unknown>;
+ const { appSlug, name, target } = parsed as Record<string, unknown>;
// The slug ends up in a URL and is model-authored: only the charset the
// proxy routes on is accepted, anything else falls back to the
// unknown-mention chip rather than being repaired.
if (!isConnectAppSlug(appSlug) || typeof name !== 'string' || !name) {
throw new Error('Invalid connect-app payload');
}
- node.replace(new ConnectAppNode(appSlug, name));
+ const resolvedTarget =
+ target === undefined ? DEFAULT_CONNECT_APP_TARGET : target;
+ if (!isConnectAppTarget(resolvedTarget)) {
+ throw new Error('Invalid connect-app target');
+ }
+ node.replace(new ConnectAppNode(appSlug, name, resolvedTarget));
} catch (e) {
console.error('Error in I_CONNECT_APP replace:', e);
replaceTextWithUnknownMention(node, 'Connect app');
diff --git a/packages/lexical-core/utils/agent-connection-prompt.ts b/packages/lexical-core/utils/agent-connection-prompt.ts
new file mode 100644
index 0000000000..f000e000f4
--- /dev/null
+++ b/packages/lexical-core/utils/agent-connection-prompt.ts
@@ -0,0 +1,44 @@
+import { createHeadlessEditor } from '@lexical/headless';
+import { $convertToMarkdownString } from '@lexical/markdown';
+import { $createParagraphNode, $createTextNode, $getRoot } from 'lexical';
+import { NodeReplacements, SupportedNodeTypes } from '../node-list';
+import {
+ $createConnectAppNode,
+ type ConnectAppInfo,
+} from '../nodes/ConnectAppNode';
+import { ALL_TRANSFORMERS } from '../transformers';
+
+/** A bot's explanation of the account setup required before it can run. */
+export type AgentConnectionPrompt = {
+ agentTag: string;
+ message: string;
+ chip: ConnectAppInfo;
+};
+
+/** Compose connection replies from the same nodes and transformers as the editor. */
+export function composeAgentConnectionPrompt(
+ prompt: AgentConnectionPrompt
+): string {
+ const editor = createHeadlessEditor({
+ nodes: [...SupportedNodeTypes, ...NodeReplacements],
+ });
+ editor.update(
+ () => {
+ $getRoot().append(
+ $createParagraphNode().append(
+ $createTextNode(prompt.agentTag).setFormat('code'),
+ $createTextNode(` ${prompt.message} `),
+ $createConnectAppNode(
+ prompt.chip.appSlug,
+ prompt.chip.name,
+ prompt.chip.target
+ )
+ )
+ );
+ },
+ { discrete: true }
+ );
+ return editor
+ .getEditorState()
+ .read(() => $convertToMarkdownString(ALL_TRANSFORMERS));
+}
diff --git a/services/agent_harness_service/src/main.rs b/services/agent_harness_service/src/main.rs
index 2573afad83..a6c31fd2e2 100644
--- a/services/agent_harness_service/src/main.rs
+++ b/services/agent_harness_service/src/main.rs
@@ -610,6 +610,18 @@ async fn run() -> anyhow::Result<()> {
},
},
));
+ fixed_runtimes.push((
+ bot_id::CLAUDE_BOT_ID,
+ AgentRuntimeConfig {
+ kind: AgentKind::ClaudeCloud,
+ model: claude_cloud_agents::domain::models::Model::default()
+ .id()
+ .to_owned(),
+ harness: "claude-cloud".into(),
+ instructions: String::new(),
+ mcp_servers: AgentMcpServers::OwnerConnections,
+ },
+ ));
let runtime_directory =
PgAgentRuntimeDirectory::new(PgBotsRepo::new(pool.clone()), fixed_runtimes.clone());
// Logged because the failure mode this replaced was silent: a harness that
@@ -768,6 +780,17 @@ async fn run() -> anyhow::Result<()> {
repo_url: None,
},
)
+ .with_bot(
+ bot_id::CLAUDE_BOT_ID,
+ SessionDefaults {
+ bot_id: bot_id::CLAUDE_BOT_ID,
+ model: claude_cloud_agents::domain::models::Model::default()
+ .id()
+ .to_owned(),
+ harness: "claude-cloud".into(),
+ repo_url: None,
+ },
+ )
// Sessions nothing names a bot for (the create menu's) run in-process;
// explicitly selected coding agents keep their configured runtimes.
.with_managed_bot(inmem_bot);
diff --git a/services/lexical-service/src/endpoints/agent-announcement.test.ts b/services/lexical-service/src/endpoints/agent-announcement.test.ts
new file mode 100644
index 0000000000..c2757d2997
--- /dev/null
+++ b/services/lexical-service/src/endpoints/agent-announcement.test.ts
@@ -0,0 +1,61 @@
+import '../polyfills/prism';
+import { describe, expect, it } from 'bun:test';
+import { fromHono } from 'chanfana';
+import { Hono } from 'hono';
+import { AgentAnnouncementEndpoint } from './agent-announcement';
+
+const app = new Hono();
+fromHono(app).post('/agent-announcement', AgentAnnouncementEndpoint);
+const request = (body: unknown) =>
+ app.request('/agent-announcement', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify(body),
+ });
+const connectionPrompt = {
+ agentTag: '@claude',
+ message: 'Connect Claude, then mention me again.',
+ chip: { appSlug: 'claude-cloud', name: 'Claude', target: 'harness' },
+};
+
+describe('agent announcements', () => {
+ it('composes a connection prompt from the client wire format', async () => {
+ const response = await request({ connectionPrompt });
+ expect(response.status).toBe(200);
+ expect(await response.json<{ markdown: string }>()).toEqual({
+ markdown:
+ '`@claude` Connect Claude, then mention me again. <m-connect-app>{"appSlug":"claude-cloud","name":"Claude","target":"harness"}</m-connect-app>',
+ });
+ });
+ it('still accepts existing session announcements', async () => {
+ const chip = {
+ agentSessionId: 'session',
+ promptedMessage: { turn: 0, author: 'user' },
+ status: 'booting',
+ };
+ const response = await request({
+ replyTarget: {
+ parent: { type: 'document', id: 'doc' },
+ targetMessageId: 'message',
+ targetThreadId: 'thread',
+ displayText: 'hello',
+ senderId: 'user',
+ },
+ chip,
+ });
+ expect(response.status).toBe(200);
+ expect(await response.json<{ markdown: string }>()).toEqual({
+ markdown: `<m-magic-chip>${JSON.stringify(chip)}</m-magic-chip>`,
+ });
+ });
+ it('rejects an unknown connection destination', async () => {
+ const response = await request({
+ connectionPrompt: {
+ ...connectionPrompt,
+ chip: { ...connectionPrompt.chip, target: 'unknown' },
+ },
+ });
+ expect(response.status).toBeGreaterThanOrEqual(400);
+ expect(response.status).toBeLessThan(500);
+ });
+});
diff --git a/services/lexical-service/src/endpoints/agent-announcement.ts b/services/lexical-service/src/endpoints/agent-announcement.ts
index 180802ff94..b4f3576949 100644
--- a/services/lexical-service/src/endpoints/agent-announcement.ts
+++ b/services/lexical-service/src/endpoints/agent-announcement.ts
@@ -1,8 +1,10 @@
+import { CONNECT_APP_TARGETS } from '@macro-inc/lexical-core/nodes/ConnectAppNode';
import {
MAGIC_CHIP_AUTHORS,
MAGIC_CHIP_STATUSES,
} from '@macro-inc/lexical-core/nodes/MagicChipNode';
import { composeAgentSessionAnnouncement } from '@macro-inc/lexical-core/utils/agent-announcement';
+import { composeAgentConnectionPrompt } from '@macro-inc/lexical-core/utils/agent-connection-prompt';
import { OpenAPIRoute } from 'chanfana';
import type { Context } from 'hono';
import { z } from 'zod';
@@ -30,7 +32,7 @@ const replyTargetRequest = z
}
);
-const agentAnnouncementRequest = z.object({
+const sessionAnnouncementRequest = z.object({
replyTarget: replyTargetRequest,
chip: z.object({
agentSessionId: z.string(),
@@ -43,6 +45,21 @@ const agentAnnouncementRequest = z.object({
}),
});
+const agentAnnouncementRequest = z.union([
+ sessionAnnouncementRequest,
+ z.object({
+ connectionPrompt: z.object({
+ agentTag: z.string().min(1),
+ message: z.string().min(1),
+ chip: z.object({
+ appSlug: z.string().regex(/^[a-z0-9_-]+$/),
+ name: z.string().min(1),
+ target: z.enum(CONNECT_APP_TARGETS),
+ }),
+ }),
+ }),
+]);
+
const agentAnnouncementResponse = z.object({
markdown: z.string(),
});
@@ -51,7 +68,7 @@ export class AgentAnnouncementEndpoint extends OpenAPIRoute {
schema = {
summary: 'Compose an agent-harness bot response',
description:
- 'Builds an agent-harness announcement from a structured reply target and magic chip.',
+ 'Builds an agent announcement or connection prompt from structured Lexical nodes.',
request: {
body: {
content: {
@@ -75,8 +92,13 @@ export class AgentAnnouncementEndpoint extends OpenAPIRoute {
};
async handle(c: Context) {
+ const { body } = await this.getValidatedData<typeof this.schema>();
try {
- const { body } = await this.getValidatedData<typeof this.schema>();
+ if ('connectionPrompt' in body) {
+ return c.json({
+ markdown: composeAgentConnectionPrompt(body.connectionPrompt),
+ });
+ }
const { parent, channelId, ...target } = body.replyTarget;
// The reply-target node still references channels only; a document
// discussion announces with the chip alone until the node learns
diff --git a/services/lexical-service/tsconfig.json b/services/lexical-service/tsconfig.json
index 4adb7a616d..7a3ae2d715 100644
--- a/services/lexical-service/tsconfig.json
+++ b/services/lexical-service/tsconfig.json
@@ -25,7 +25,7 @@
"moduleResolution": "Bundler",
"module": "es2022",
"noEmit": true,
- "lib": ["es2022", "dom"],
+ "lib": ["es2023", "dom"],
"types": ["./worker-configuration.d.ts", "@types/node", "@types/bun"]
},
"exclude": ["node_modules", "dist", "tests"],