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.

fix(web): open new agents from Ask AI actions (#7305)

Eric Hayeseb840ae2810f
diff --git a/apps/web/src/features/agents-view/components/ChatComposer.test.tsx b/apps/web/src/features/agents-view/components/ChatComposer.test.tsx
index 5c61b1095b..94f2801568 100644
--- a/apps/web/src/features/agents-view/components/ChatComposer.test.tsx
+++ b/apps/web/src/features/agents-view/components/ChatComposer.test.tsx
@@ -138,6 +138,15 @@ function type(text: string) {
}
describe('Chat session input', () => {
+ it('seeds the supplied context without sending it', () => {
+ const send = vi.fn();
+ render(() => (
+ <ChatSessionInput initialInput="Document context" onSend={send} />
+ ));
+ expect(editor.setMarkdown).toHaveBeenCalledWith('Document context');
+ expect(send).not.toHaveBeenCalled();
+ });
+
it('shows only the model control and submits a trimmed follow-up', () => {
const send = vi.fn();
render(() => (
diff --git a/apps/web/src/features/agents-view/components/ChatComposer.tsx b/apps/web/src/features/agents-view/components/ChatComposer.tsx
index ff4d785a4b..54ad088648 100644
--- a/apps/web/src/features/agents-view/components/ChatComposer.tsx
+++ b/apps/web/src/features/agents-view/components/ChatComposer.tsx
@@ -349,7 +349,7 @@ export function ChatComposer(props: {
/** Adapt the session's controls to the same input used for a new Chat. */
export function ChatSessionInput(props: AgentInputProps) {
- const [draft, setDraft] = createSignal('');
+ const [draft, setDraft] = createSignal(props.initialInput ?? '');
return (
<ChatComposer
draft={draft()}
diff --git a/apps/web/src/features/block-agent/agent-session-provider.tsx b/apps/web/src/features/block-agent/agent-session-provider.tsx
index 228013f132..31ef68ba43 100644
--- a/apps/web/src/features/block-agent/agent-session-provider.tsx
+++ b/apps/web/src/features/block-agent/agent-session-provider.tsx
@@ -36,9 +36,8 @@ export function AgentSessionProvider(
onSessionId?: (sessionId: string) => void;
}
) {
- const { sessionId, pending, failed, error, pendingPrompt } = resolveSessionId(
- () => props.blockId
- );
+ const { sessionId, pending, failed, error, pendingPrompt, initialInput } =
+ resolveSessionId(() => props.blockId);
createEffect(() => {
const id = sessionId();
@@ -135,6 +134,7 @@ export function AgentSessionProvider(
displayName: idToDisplayName,
sessionId,
pending,
+ initialInput: initialInput(),
startupError: error,
session: live.session,
bot: live.bot,
diff --git a/apps/web/src/features/block-agent/component/AgentComposer.test.tsx b/apps/web/src/features/block-agent/component/AgentComposer.test.tsx
index 07544cc115..c3b7d1da88 100644
--- a/apps/web/src/features/block-agent/component/AgentComposer.test.tsx
+++ b/apps/web/src/features/block-agent/component/AgentComposer.test.tsx
@@ -45,6 +45,7 @@ vi.mock('../context/AgentSessionContext', () => ({
messages: () => [],
metadata: () => undefined,
pending: () => false,
+ initialInput: 'Document context',
queue: {
entries: () => [
{ actionId: 'queued-1', kind: 'prompt', prompt: 'Queued request' },
@@ -81,6 +82,12 @@ beforeEach(() => {
});
afterEach(cleanup);
+it('passes opening context to the composer without issuing it', () => {
+ render(() => <AgentComposer />);
+ expect(mocks.input?.initialInput).toBe('Document context');
+ expect(mocks.issue).not.toHaveBeenCalled();
+});
+
describe('view-only session controls', () => {
it('disables and guards prompt, model, stop, queue, and attachment actions', () => {
render(() => <AgentComposer />);
diff --git a/apps/web/src/features/block-agent/component/AgentComposer.tsx b/apps/web/src/features/block-agent/component/AgentComposer.tsx
index 05c032d51e..cb0a67a555 100644
--- a/apps/web/src/features/block-agent/component/AgentComposer.tsx
+++ b/apps/web/src/features/block-agent/component/AgentComposer.tsx
@@ -65,6 +65,7 @@ export function AgentComposer(props: {
sendNext,
turn,
registerQuoteInsert,
+ initialInput,
} = useAgentSession();
const changes = useOptionalAgentChanges();
const readOnly = () => session()?.canEdit === false;
@@ -224,6 +225,7 @@ export function AgentComposer(props: {
)}
</For>
<Input
+ initialInput={initialInput}
placeholder={
readOnly()
? 'You have view-only access to this agent session'
diff --git a/apps/web/src/features/block-agent/context/AgentSessionContext.tsx b/apps/web/src/features/block-agent/context/AgentSessionContext.tsx
index 5e7f03e47f..e6b0af7343 100644
--- a/apps/web/src/features/block-agent/context/AgentSessionContext.tsx
+++ b/apps/web/src/features/block-agent/context/AgentSessionContext.tsx
@@ -29,6 +29,8 @@ export type AgentSessionState = {
/** The session is still being created — everything else is empty because
* there is nothing to show yet, not because the load failed. */
pending: Accessor<boolean>;
+ /** Unsent context from the action that opened this session. */
+ initialInput?: string;
startupError: Accessor<string | undefined>;
/** Session metadata, absent until the load resolves. */
session: Accessor<AgentSessionResponse | undefined>;
diff --git a/apps/web/src/features/block-agent/context/pending-session.ts b/apps/web/src/features/block-agent/context/pending-session.ts
index 1b0f71a54b..2c5b23d0bf 100644
--- a/apps/web/src/features/block-agent/context/pending-session.ts
+++ b/apps/web/src/features/block-agent/context/pending-session.ts
@@ -44,6 +44,8 @@ export type PendingSession = {
* opens rather than once the create has answered.
*/
prompt: string | undefined;
+ /** Unsent composer context supplied by an Ask AI action. */
+ initialInput?: string;
};
const pending = new Map<string, PendingSession>();
@@ -54,6 +56,8 @@ const pending = new Map<string, PendingSession>();
export type StartPendingSessionOptions = {
/** Persisted managed persona to run; omitted for Macro Coder. */
botId?: string;
+ /** Unsent composer context; never issued as a prompt. */
+ initialInput?: string;
/** First prompt. */
prompt?: string;
/** Uploaded SFS files delivered with the first prompt. */
@@ -90,6 +94,7 @@ export function startPendingSession(
failed: () => error() !== undefined,
error,
prompt: options.prompt?.trim() || undefined,
+ initialInput: options.initialInput,
});
void agentHarnessServiceClient
diff --git a/apps/web/src/features/block-agent/context/resolve-session-id.test.ts b/apps/web/src/features/block-agent/context/resolve-session-id.test.ts
index 68cb7afd6f..9db8b52013 100644
--- a/apps/web/src/features/block-agent/context/resolve-session-id.test.ts
+++ b/apps/web/src/features/block-agent/context/resolve-session-id.test.ts
@@ -130,6 +130,23 @@ describe('a block id that is already a session', () => {
});
describe('an id whose create is in flight', () => {
+ it('keeps initial context as a draft after startup without issuing a prompt', async () => {
+ const placeholder = startPendingSession({
+ initialInput: 'Document context ',
+ });
+ await createRoot(async (dispose) => {
+ const resolved = resolveSessionId(() => placeholder);
+ expect(resolved.initialInput()).toBe('Document context ');
+ expect(resolved.pendingPrompt()).toBeUndefined();
+ create.resolve?.();
+ await flush();
+ expect(resolved.initialInput()).toBe('Document context ');
+ expect(resolved.pending()).toBe(false);
+ expect(create.control).not.toHaveBeenCalled();
+ dispose();
+ });
+ });
+
it('has no session until the create lands, then is that session', async () => {
const placeholder = startPendingSession();
await createRoot(async (dispose) => {
diff --git a/apps/web/src/features/block-agent/context/resolve-session-id.ts b/apps/web/src/features/block-agent/context/resolve-session-id.ts
index 61738ffaad..340faa0c56 100644
--- a/apps/web/src/features/block-agent/context/resolve-session-id.ts
+++ b/apps/web/src/features/block-agent/context/resolve-session-id.ts
@@ -22,6 +22,7 @@ export type ResolvedSessionId = {
/** The first prompt of a create this block started, to show as sent while
* the create is still on the wire. */
pendingPrompt: Accessor<string | undefined>;
+ initialInput: Accessor<string | undefined>;
};
export function resolveSessionId(blockId: Accessor<string>): ResolvedSessionId {
@@ -45,5 +46,6 @@ export function resolveSessionId(blockId: Accessor<string>): ResolvedSessionId {
failed: () => entry()?.failed() ?? false,
error: () => entry()?.error(),
pendingPrompt: () => entry()?.prompt,
+ initialInput: () => entry()?.initialInput,
};
}
diff --git a/apps/web/src/features/block-agent/ui/AgentInput.test.tsx b/apps/web/src/features/block-agent/ui/AgentInput.test.tsx
index 7d77b60c85..774a2aeec1 100644
--- a/apps/web/src/features/block-agent/ui/AgentInput.test.tsx
+++ b/apps/web/src/features/block-agent/ui/AgentInput.test.tsx
@@ -64,8 +64,10 @@ vi.mock(
);
vi.mock('@core/component/LexicalMarkdown/builder/MarkdownShell', () => ({
- MarkdownShell: (props: { disabled?: boolean }) => (
- <div data-testid="agent-input-editor" data-disabled={props.disabled} />
+ MarkdownShell: (props: { disabled?: boolean; initialValue?: string }) => (
+ <div data-testid="agent-input-editor" data-disabled={props.disabled}>
+ {props.initialValue}
+ </div>
),
}));
@@ -120,6 +122,17 @@ beforeEach(() => {
vi.mocked(isTouchDevice).mockReturnValue(false);
});
+it('seeds context without sending it and submits it only on Send', () => {
+ const onSend = vi.fn();
+ render(() => <AgentInput initialInput="Document context" onSend={onSend} />);
+ expect(screen.getByTestId('agent-input-editor').textContent).toBe(
+ 'Document context'
+ );
+ expect(onSend).not.toHaveBeenCalled();
+ fireEvent.click(screen.getByRole('button', { name: 'Send' }));
+ expect(onSend).toHaveBeenCalledWith('Document context', []);
+});
+
describe('on a touch device', () => {
beforeEach(() => {
vi.mocked(isTouchDevice).mockReturnValue(true);
diff --git a/apps/web/src/features/block-agent/ui/AgentInput.tsx b/apps/web/src/features/block-agent/ui/AgentInput.tsx
index af21693b29..2808195e94 100644
--- a/apps/web/src/features/block-agent/ui/AgentInput.tsx
+++ b/apps/web/src/features/block-agent/ui/AgentInput.tsx
@@ -44,6 +44,8 @@ export type QuoteInsert = (text: string) => void;
export interface AgentInputProps {
placeholder?: string;
+ /** Context to seed in the composer without sending it. */
+ initialInput?: string;
/** The agent is working: the send button becomes a stop square. */
busy?: boolean;
/**
@@ -112,7 +114,7 @@ export interface AgentInputProps {
}
export function AgentInput(props: AgentInputProps) {
- const [markdown, setMarkdown] = createSignal('');
+ const [markdown, setMarkdown] = createSignal(props.initialInput ?? '');
const [isDraggedOver, setIsDraggedOver] = createSignal(false);
let containerRef: HTMLDivElement | undefined;
const [layout, setLayout] = createSignal<HTMLDivElement>();
@@ -357,6 +359,7 @@ export function AgentInput(props: AgentInputProps) {
>
<ComposerEditor
config={editor}
+ initialValue={props.initialInput}
disabled={props.readOnly}
placeholder={
props.placeholder ??
diff --git a/apps/web/src/features/block-spreadsheet/README.md b/apps/web/src/features/block-spreadsheet/README.md
index a91a6851a0..e7c9dfe21f 100644
--- a/apps/web/src/features/block-spreadsheet/README.md
+++ b/apps/web/src/features/block-spreadsheet/README.md
@@ -45,8 +45,8 @@ row additions are not duplicated after a lost acknowledgement.
## Ask Macro and spreadsheet tools
-Ask Macro uses the shared chat creation flow and opens an adjacent chat with one
-document mention plus a trailing space. The mention includes the active sheet
+Ask Macro uses the shared agent session flow and opens an adjacent agent with one
+unsent document mention plus a trailing space. The mention includes the active sheet
ID/name and selection snapshot. Local demos save through the existing acknowledged
draft path first. Selection remains local presence, not persisted workbook data.
diff --git a/apps/web/src/features/chat/ChatWithAgentButton.test.ts b/apps/web/src/features/chat/ChatWithAgentButton.test.ts
index 6b64948973..204490493f 100644
--- a/apps/web/src/features/chat/ChatWithAgentButton.test.ts
+++ b/apps/web/src/features/chat/ChatWithAgentButton.test.ts
@@ -1,3 +1,4 @@
+import type { SplitHandle } from '@components/app/split-layout/layoutManager';
import { createHeadlessEditor } from '@lexical/headless';
import {
$convertFromMarkdownString,
@@ -9,47 +10,49 @@ import { $getRoot } from 'lexical';
import { beforeEach, describe, expect, it, vi } from 'vitest';
const mocks = vi.hoisted(() => ({
- createChat: vi.fn(),
+ startPendingSession: vi.fn(),
+ manager: true,
+ failure: vi.fn(),
openWithSplit: vi.fn(),
- storeChatStateImmediate: vi.fn(),
- setPendingSendData: vi.fn(),
}));
vi.mock('@app/signal/splitLayout', () => ({
- globalSplitManager: () => ({ openWithSplit: mocks.openWithSplit }),
+ globalSplitManager: () =>
+ mocks.manager ? { openWithSplit: mocks.openWithSplit } : undefined,
}));
-vi.mock('@core/component/AI/signal/pendingSend', () => ({
- setPendingSendData: mocks.setPendingSendData,
+vi.mock('@app/features/block-agent/context/pending-session', () => ({
+ startPendingSession: mocks.startPendingSession,
}));
vi.mock('@core/component/LexicalMarkdown/plugins/mentions', () => ({
INSERT_DOCUMENT_MENTION_COMMAND: {},
}));
-vi.mock('@core/component/AI/util/storage', () => ({
- storeChatStateImmediate: mocks.storeChatStateImmediate,
-}));
vi.mock('@core/component/Toast/Toast', () => ({
- toast: { failure: vi.fn() },
+ toast: { failure: mocks.failure },
}));
vi.mock('@core/constant/allBlocks', () => ({
fileTypeToBlockName: (fileType: string | null | undefined) =>
fileType ?? 'unknown',
}));
-vi.mock('@core/util/create', () => ({
- createChat: mocks.createChat,
-}));
vi.mock('@ui', () => ({
Button: () => null,
}));
-import { openChatWithAgent } from './ChatWithAgentButton';
+import {
+ openChatWithAgent,
+ openChatWithInput,
+ openChatWithInputReplacingSplit,
+ openChatWithMessage,
+ openChatWithMessageReplacingSplit,
+} from './ChatWithAgentButton';
describe('openChatWithAgent', () => {
beforeEach(() => {
vi.clearAllMocks();
- mocks.createChat.mockResolvedValue({ chatId: 'chat-id' });
+ mocks.startPendingSession.mockReturnValue('session-id');
+ mocks.manager = true;
});
- it('seeds and opens a new chat with a visible mention and attachment', async () => {
+ it('opens an agent session with an unsent visible mention', async () => {
await openChatWithAgent({
type: 'document',
id: 'document-id',
@@ -57,13 +60,13 @@ describe('openChatWithAgent', () => {
fileType: 'md',
});
- expect(mocks.storeChatStateImmediate).toHaveBeenCalledWith('chat-id', {
- input:
+ expect(mocks.startPendingSession).toHaveBeenCalledWith({
+ prompt: undefined,
+ initialInput:
'<m-document-mention>{"documentId":"document-id","documentName":"Project plan","blockName":"md","blockParams":{}}</m-document-mention> ',
- attachments: [{ entity_id: 'document-id', entity_type: 'document' }],
});
expect(mocks.openWithSplit).toHaveBeenCalledWith(
- { type: 'chat', id: 'chat-id' },
+ { type: 'component', id: 'agents-session~agents~session-id' },
{ activate: true, preferNewSplit: true }
);
});
@@ -81,13 +84,13 @@ describe('openChatWithAgent', () => {
},
});
expect(opened).toBe(true);
- expect(mocks.storeChatStateImmediate).toHaveBeenCalledWith('chat-id', {
- input:
+ expect(mocks.startPendingSession).toHaveBeenCalledWith({
+ prompt: undefined,
+ initialInput:
'<m-document-mention>{"documentId":"sheet-id","documentName":"Budget","blockName":"spreadsheet","blockParams":{"sheetId":"sheet-2","sheetName":"Annual budget","range":"B4:E9"}}</m-document-mention> ',
- attachments: [{ entity_id: 'sheet-id', entity_type: 'document' }],
});
- expect(mocks.setPendingSendData).not.toHaveBeenCalled();
- const input: string = mocks.storeChatStateImmediate.mock.calls[0][1].input;
+ const input: string =
+ mocks.startPendingSession.mock.calls[0][0].initialInput;
const editor = createHeadlessEditor({ nodes: SupportedNodeTypes });
editor.update(() => $convertFromMarkdownString(input, ALL_TRANSFORMERS), {
discrete: true,
@@ -101,8 +104,8 @@ describe('openChatWithAgent', () => {
});
});
- it('does not open a split or lose the draft when chat creation fails', async () => {
- mocks.createChat.mockResolvedValueOnce({ error: 'Unavailable' });
+ it('does not start a session when navigation is unavailable', async () => {
+ mocks.manager = false;
expect(
await openChatWithAgent({
type: 'document',
@@ -112,6 +115,64 @@ describe('openChatWithAgent', () => {
})
).toBe(false);
expect(mocks.openWithSplit).not.toHaveBeenCalled();
- expect(mocks.storeChatStateImmediate).not.toHaveBeenCalled();
+ expect(mocks.startPendingSession).not.toHaveBeenCalled();
+ expect(mocks.failure).toHaveBeenCalledWith('Unable to open chat');
+ });
+ it.each([
+ { type: 'email' as const, id: 'email-id', name: 'Subject' },
+ { type: 'project' as const, id: 'project-id', name: 'Launch' },
+ {
+ type: 'channel' as const,
+ id: 'channel-id',
+ name: 'Team',
+ channelType: 'public' as const,
+ },
+ ])('preserves context for $type actions', async (entity) => {
+ await openChatWithAgent(entity);
+ const seed = mocks.startPendingSession.mock.calls[0][0];
+ expect(seed.prompt).toBeUndefined();
+ expect(seed.initialInput).toContain(entity.id);
+ expect(seed.initialInput).toContain(entity.name);
+ if (entity.type === 'channel')
+ expect(seed.initialInput).toContain('"channelType":"public"');
+ });
+
+ it('hands a submitted query to the agent as the first prompt', async () => {
+ await openChatWithMessage('Find my latest invoices');
+ expect(mocks.startPendingSession).toHaveBeenCalledWith({
+ prompt: 'Find my latest invoices',
+ initialInput: undefined,
+ });
+ expect(mocks.openWithSplit).toHaveBeenCalledWith(
+ { type: 'component', id: 'agents-session~agents~session-id' },
+ { activate: true, preferNewSplit: true }
+ );
});
+
+ it('preserves a channel-message draft without sending it', async () => {
+ await openChatWithInput('A message reference\n\n');
+ expect(mocks.startPendingSession).toHaveBeenCalledWith({
+ prompt: undefined,
+ initialInput: 'A message reference\n\n',
+ });
+ });
+
+ it.each(['Find invoices', ''])(
+ 'replaces the search split for query %j',
+ async (query) => {
+ mocks.manager = false;
+ const replace = vi.fn();
+ const split = { replace } as unknown as SplitHandle;
+ if (query) await openChatWithMessageReplacingSplit(query, split);
+ else await openChatWithInputReplacingSplit('', split);
+ expect(mocks.startPendingSession).toHaveBeenCalledWith({
+ prompt: query || undefined,
+ initialInput: query ? undefined : '',
+ });
+ expect(replace).toHaveBeenCalledWith({
+ next: { type: 'component', id: 'agents-session~agents~session-id' },
+ });
+ expect(mocks.openWithSplit).not.toHaveBeenCalled();
+ }
+ );
});
diff --git a/apps/web/src/features/chat/ChatWithAgentButton.tsx b/apps/web/src/features/chat/ChatWithAgentButton.tsx
index b3f222b31e..df2a02a5b6 100644
--- a/apps/web/src/features/chat/ChatWithAgentButton.tsx
+++ b/apps/web/src/features/chat/ChatWithAgentButton.tsx
@@ -1,16 +1,13 @@
+import { agentsRouteId } from '@app/features/agents-view/core/route';
+import { startPendingSession } from '@app/features/block-agent/context/pending-session';
import { globalSplitManager } from '@app/signal/splitLayout';
import type { SplitHandle } from '@components/app/split-layout/layoutManager';
-import { DEFAULT_MODEL } from '@core/component/AI/constant';
-import { setPendingSendData } from '@core/component/AI/signal/pendingSend';
-import type { Attachment } from '@core/component/AI/types';
import {
type ChatAttachmentMention,
chatAttachmentMentionToMarkdown,
} from '@core/component/AI/util/chatAttachmentMention';
-import { storeChatStateImmediate } from '@core/component/AI/util/storage';
import { toast } from '@core/component/Toast/Toast';
import { fileTypeToBlockName } from '@core/constant/allBlocks';
-import { createChat } from '@core/util/create';
import AgentIcon from '@phosphor/sparkle.svg';
import type { ChannelType } from '@service-cognition/generated/schemas/channelType';
import { Button } from '@ui';
@@ -30,12 +27,7 @@ type ChatWithAgentEntity =
| { type: 'project'; id: string; name: string }
| { type: 'channel'; id: string; name: string; channelType: ChannelType };
-function buildSeed(entity: ChatWithAgentEntity): {
- mention: ChatAttachmentMention;
- attachment: Attachment;
-} {
- const attachmentType: Attachment['entity_type'] =
- entity.type === 'email' ? 'email_thread' : entity.type;
+function buildMention(entity: ChatWithAgentEntity): ChatAttachmentMention {
const blockName =
entity.type === 'document'
? fileTypeToBlockName(entity.fileType, true)
@@ -44,28 +36,21 @@ function buildSeed(entity: ChatWithAgentEntity): {
: entity.type;
return {
- mention: {
- documentId: entity.id,
- documentName: entity.name,
- blockName,
- ...(entity.type === 'channel' ? { channelType: entity.channelType } : {}),
- ...(entity.type === 'document' && entity.blockParams
- ? { blockParams: entity.blockParams }
- : {}),
- },
- attachment: {
- entity_id: entity.id,
- entity_type: attachmentType,
- },
+ documentId: entity.id,
+ documentName: entity.name,
+ blockName,
+ ...(entity.type === 'channel' ? { channelType: entity.channelType } : {}),
+ ...(entity.type === 'document' && entity.blockParams
+ ? { blockParams: entity.blockParams }
+ : {}),
};
}
-async function createAndOpenChat(seed: {
+async function createAndOpenAgent(seed: {
input?: string;
- attachments?: Attachment[];
- /** When set, sent immediately when the chat opens instead of seeding the input */
+ /** Sent immediately once the agent session is ready. */
message?: string;
- /** When set, replaces this split's content in place instead of opening a new split. */
+ /** Replaces this split's content instead of opening a new split. */
replaceSplit?: SplitHandle;
}) {
const manager = globalSplitManager();
@@ -73,75 +58,60 @@ async function createAndOpenChat(seed: {
toast.failure('Unable to open chat');
return false;
}
- let result: Awaited<ReturnType<typeof createChat>>;
- try {
- result = await createChat();
- } catch {
- toast.failure('Unable to start chat');
- return false;
- }
- if ('error' in result || !result.chatId) {
- console.warn('createAndOpenChat: createChat failed', result);
- toast.failure('Unable to start chat');
- return false;
- }
- const { message, replaceSplit, ...stored } = seed;
- if (message) {
- setPendingSendData({
- content: message,
- attachments: seed.attachments ?? [],
- model: DEFAULT_MODEL,
- });
- } else {
- storeChatStateImmediate(result.chatId, stored);
- }
- if (replaceSplit) {
- replaceSplit.replace({ next: { type: 'chat', id: result.chatId } });
+ const id = startPendingSession({
+ prompt: seed.message,
+ initialInput: seed.message ? undefined : seed.input,
+ });
+ const next = {
+ type: 'component' as const,
+ id: agentsRouteId({
+ mode: 'chat',
+ conversation: { type: 'agent_session', id },
+ }),
+ };
+ if (seed.replaceSplit) {
+ seed.replaceSplit.replace({ next });
} else {
- manager?.openWithSplit(
- { type: 'chat', id: result.chatId },
- { activate: true, preferNewSplit: true }
- );
+ manager?.openWithSplit(next, { activate: true, preferNewSplit: true });
}
return true;
}
export async function openChatWithAgent(entity: ChatWithAgentEntity) {
- const { mention, attachment } = buildSeed(entity);
- const input = `${chatAttachmentMentionToMarkdown(mention)} `;
- return createAndOpenChat({ input, attachments: [attachment] });
+ const input = `${chatAttachmentMentionToMarkdown(buildMention(entity))} `;
+ return createAndOpenAgent({ input });
}
export async function openChatWithInput(initialInput: string) {
- await createAndOpenChat({ input: initialInput });
+ await createAndOpenAgent({ input: initialInput });
}
/**
- * Replace `splitHandle`'s content with a new chat seeded with `initialInput`
+ * Replace `splitHandle`'s content with a new agent session seeded with `initialInput`
* (not sent). Used by the search view's "Ask AI" button to hand off in place.
*/
export async function openChatWithInputReplacingSplit(
initialInput: string,
splitHandle: SplitHandle
) {
- await createAndOpenChat({ input: initialInput, replaceSplit: splitHandle });
+ await createAndOpenAgent({ input: initialInput, replaceSplit: splitHandle });
}
-/** Open a new chat and immediately send `message` (the chat picks it up via pending send) */
+/** Open a new agent session and send `message` once it is ready. */
export async function openChatWithMessage(message: string) {
- await createAndOpenChat({ message });
+ await createAndOpenAgent({ message });
}
/**
- * Replace `splitHandle`'s content with a new chat and immediately send
+ * Replace `splitHandle`'s content with a new agent session and immediately send
* `message`. Used by the search view's "Ask AI" button to hand off in place.
*/
export async function openChatWithMessageReplacingSplit(
message: string,
splitHandle: SplitHandle
) {
- await createAndOpenChat({ message, replaceSplit: splitHandle });
+ await createAndOpenAgent({ message, replaceSplit: splitHandle });
}
export function ChatWithAgentButton(props: {
diff --git a/apps/web/src/features/command/CommandMenu.tsx b/apps/web/src/features/command/CommandMenu.tsx
index 97250d313c..2ed5ce8d71 100644
--- a/apps/web/src/features/command/CommandMenu.tsx
+++ b/apps/web/src/features/command/CommandMenu.tsx
@@ -372,8 +372,8 @@ export function CommandMenuInner(props: {
}
if (isAskAiItem(item)) {
- // Opens a new chat split and sends the query immediately.
- openChatWithMessage(item.query);
+ // Opens a new agent session and sends the query when ready.
+ void openChatWithMessage(item.query);
CommandState.close();
CommandState.setQuery('');
return;
diff --git a/apps/web/src/features/command/mobile/MobileSearchInput.tsx b/apps/web/src/features/command/mobile/MobileSearchInput.tsx
index b2f72503d8..cb53f4444a 100644
--- a/apps/web/src/features/command/mobile/MobileSearchInput.tsx
+++ b/apps/web/src/features/command/mobile/MobileSearchInput.tsx
@@ -23,7 +23,7 @@ import { openMobileAskAi } from './open-mobile-ask-ai';
function submitAskAi() {
const query = SearchState.query().trim();
if (!query) return;
- openMobileAskAi(query);
+ void openMobileAskAi(query);
SearchState.close();
}
diff --git a/apps/web/src/features/command/mobile/open-mobile-ask-ai.test.ts b/apps/web/src/features/command/mobile/open-mobile-ask-ai.test.ts
index 43d9a5d8c7..3fb82e1182 100644
--- a/apps/web/src/features/command/mobile/open-mobile-ask-ai.test.ts
+++ b/apps/web/src/features/command/mobile/open-mobile-ask-ai.test.ts
@@ -1,73 +1,12 @@
-import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { expect, it, vi } from 'vitest';
-const mocks = vi.hoisted(() => ({
- agentsEnabled: false,
- openChatWithMessage: vi.fn(),
- startPendingSession: vi.fn(() => 'pending-session'),
- openWithSplit: vi.fn(),
- manager: true,
- failure: vi.fn(),
-}));
-
-vi.mock('@app/features/block-agent/context/pending-session', () => ({
- startPendingSession: mocks.startPendingSession,
-}));
vi.mock('@app/features/chat/ChatWithAgentButton', () => ({
- openChatWithMessage: mocks.openChatWithMessage,
-}));
-vi.mock('@app/signal/splitLayout', () => ({
- globalSplitManager: () =>
- mocks.manager ? { openWithSplit: mocks.openWithSplit } : undefined,
-}));
-vi.mock('@core/component/Toast/Toast', () => ({
- toast: { failure: mocks.failure },
-}));
-vi.mock('@core/constant/featureFlags', () => ({
- enableChatV3Agents: { key: 'enable-chat-v3-agents' },
- isFeatureEnabled: () => mocks.agentsEnabled,
+ openChatWithMessage: vi.fn(),
}));
+import { openChatWithMessage } from '@app/features/chat/ChatWithAgentButton';
import { openMobileAskAi } from './open-mobile-ask-ai';
-describe('openMobileAskAi', () => {
- beforeEach(() => {
- vi.clearAllMocks();
- mocks.agentsEnabled = false;
- mocks.manager = true;
- mocks.startPendingSession.mockReturnValue('pending-session');
- });
-
- it('opens the cognition chat when chat v3 agents are off', () => {
- openMobileAskAi('reply to Margot');
-
- expect(mocks.openChatWithMessage).toHaveBeenCalledWith('reply to Margot');
- expect(mocks.startPendingSession).not.toHaveBeenCalled();
- expect(mocks.openWithSplit).not.toHaveBeenCalled();
- });
-
- it('starts an agent session with the query when chat v3 agents are on', () => {
- mocks.agentsEnabled = true;
-
- openMobileAskAi('reply to Margot');
-
- expect(mocks.startPendingSession).toHaveBeenCalledWith({
- prompt: 'reply to Margot',
- });
- expect(mocks.openWithSplit).toHaveBeenCalledWith(
- { type: 'agent', id: 'pending-session' },
- { activate: true, preferNewSplit: true }
- );
- expect(mocks.openChatWithMessage).not.toHaveBeenCalled();
- });
-
- it('reports a failure and skips session creation when no split can open', () => {
- mocks.agentsEnabled = true;
- mocks.manager = false;
-
- openMobileAskAi('reply to Margot');
-
- expect(mocks.failure).toHaveBeenCalledWith('Unable to open chat');
- expect(mocks.startPendingSession).not.toHaveBeenCalled();
- expect(mocks.openChatWithMessage).not.toHaveBeenCalled();
- });
+it('uses the same agent handoff as desktop search and the command menu', () => {
+ expect(openMobileAskAi).toBe(openChatWithMessage);
});
diff --git a/apps/web/src/features/command/mobile/open-mobile-ask-ai.ts b/apps/web/src/features/command/mobile/open-mobile-ask-ai.ts
index 6de2b492ea..2769c41515 100644
--- a/apps/web/src/features/command/mobile/open-mobile-ask-ai.ts
+++ b/apps/web/src/features/command/mobile/open-mobile-ask-ai.ts
@@ -1,31 +1,2 @@
-import { startPendingSession } from '@app/features/block-agent/context/pending-session';
-import { openChatWithMessage } from '@app/features/chat/ChatWithAgentButton';
-import { globalSplitManager } from '@app/signal/splitLayout';
-import { toast } from '@core/component/Toast/Toast';
-import {
- enableChatV3Agents,
- isFeatureEnabled,
-} from '@core/constant/featureFlags';
-
-/**
- * Opens a conversation for a mobile search query and sends it immediately.
- * With chat v3 agents, that is a managed agent session whose first prompt is
- * the query. Otherwise it is the cognition chat.
- */
-export function openMobileAskAi(query: string) {
- if (!isFeatureEnabled(enableChatV3Agents)) {
- void openChatWithMessage(query);
- return;
- }
-
- const manager = globalSplitManager();
- if (!manager) {
- toast.failure('Unable to open chat');
- return;
- }
-
- manager.openWithSplit(
- { type: 'agent', id: startPendingSession({ prompt: query }) },
- { activate: true, preferNewSplit: true }
- );
-}
+// Mobile search shares the agent handoff used by desktop search and the command menu.
+export { openChatWithMessage as openMobileAskAi } from '@app/features/chat/ChatWithAgentButton';
diff --git a/docs/AGENT_GUIDE/ai-chat.md b/docs/AGENT_GUIDE/ai-chat.md
index 5bc0c6cc3b..5029643c77 100644
--- a/docs/AGENT_GUIDE/ai-chat.md
+++ b/docs/AGENT_GUIDE/ai-chat.md
@@ -61,6 +61,20 @@ Refused prompts, provider failures, and hosts without a Google Generative AI key
display a failed tool call; the error tells the agent whether to rephrase, retry,
or stop.
+## Ask AI entry points
+
+**Ask AI** in search (including Tab), the command menu, and mobile search opens
+an agent session. A nonempty search query is sent as the first prompt once the
+session is ready; an empty search opens an empty composer. Desktop search replaces
+its current split, while command-menu and mobile actions open a new split.
+
+**Ask Macro** and **Chat with Agent** on documents, PDFs, spreadsheets, email,
+channels, calls, and projects also open agent sessions. Their entity mention stays
+in the composer as an unsent draft. Spreadsheet mentions retain the current sheet
+and selected range; channel-message actions retain the referenced message.
+Add a question and press Send to submit that context. These actions do not create
+legacy cognition chats, regardless of the Agents workspace feature flag.
+
## Where chats live
The Agents conversation list shows row skeletons after a short delay on first
@@ -314,9 +328,9 @@ The composer has one editable field. Its placeholder appears only while empty;
placeholder updates and disabled-state changes preserve the editor and draft.
The **Ask AI** button beside the mobile search field sends the typed query.
-With `enable-chat-v3-agents` on, it opens an agent session (`/app/agent/<id>`)
-and delivers the query as the first prompt. With the flag off, it opens a
-cognition chat (`/app/chat/<uuid>`) and sends the query.
+It opens an agent session and delivers the query as the first prompt, regardless
+of `enable-chat-v3-agents`. Mobile uses the agent session surface at
+`/app/agent/<id>`; desktop uses the Agents workspace.
Almost every list surface (Home, Agents, Files, Tasks, Customers, Email) has a bottom
composer with placeholder **`Ask AI, @mention anything`**. Click it, `type_text` the message,
@@ -451,10 +465,10 @@ existing UI does not promise a dedicated quota dialog outside development mode.
## Start a doc-scoped chat
-Open a doc → side panel `Actions` → `Ask Macro`. Opens a chat pane with the document already
-attached as context (it appears as a link chip in the composer). New-chat pane shows tips:
-`@mention anything` to attach entities, `Ctrl+Enter` to send in the background (you get
-notified when the AI responds). Legacy Home background sends preserve the submitted tool selection.
+Open a doc → side panel `Actions` → `Ask Macro`. Opens an agent session with the
+document already mentioned as context (a link chip in the composer). The mention
+is an unsent draft: add a question, then Send. Legacy Home background sends
+preserve the submitted tool selection.
## Composer anatomy (a11y)
diff --git a/docs/AGENT_GUIDE/documents.md b/docs/AGENT_GUIDE/documents.md
index 41dfbb9309..31a2169edf 100644
--- a/docs/AGENT_GUIDE/documents.md
+++ b/docs/AGENT_GUIDE/documents.md
@@ -282,7 +282,7 @@ must be saved before persistent comments are available.
## Ask Macro about a spreadsheet
**Ask Macro** sits immediately left of **Share**. Select the relevant cells, then
-click it to open a new chat in a split beside the workbook. The composer starts
+click it to open a new agent session in a split beside the workbook. The composer starts
with the workbook mention followed by one space; nothing sends automatically.
The mention captures the active sheet ID/name and normalized selected range at
click time. Changing the selection later does not change that draft attachment.