Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
import { $createQuoteNode, QuoteNode } from '@lexical/rich-text';
import {
$createParagraphNode,
$createTextNode,
$getRoot,
createEditor,
type LexicalEditor,
} from 'lexical';
/**
* @vitest-environment jsdom
*/
import { preloadAgentFold } from '@core/agent-fold/client';
import { isTouchDevice } from '@core/mobile/isTouchDevice';
import { cleanup, fireEvent, render, screen } from '@solidjs/testing-library';
import { Portal } from 'solid-js/web';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { AGENT_INPUT_TEXT_AREA_ID, AgentInput } from './AgentInput';
vi.mock('@service-connection/websocket', () => ({
ws: { addEventListener: vi.fn(), send: vi.fn() },
state: () => 'closed',
createConnectionBlockWebsocketEffect: vi.fn(),
createConnectionWebsocketEffect: vi.fn(),
}));
vi.mock('@service-storage/websocket', () => ({
storageWS: { reconnectIfDisconnected: vi.fn() },
createWebSocketJob: vi.fn(),
}));
vi.mock('@core/agent-fold/client', () => ({
preloadAgentFold: vi.fn(async () => {}),
}));
vi.mock('@core/mobile/isTouchDevice', () => ({
isTouchDevice: vi.fn(() => false),
}));
const editor = vi.hoisted(() => ({
lexical: undefined as LexicalEditor | undefined,
text: '',
clear: vi.fn(),
setMarkdown: vi.fn((value: string) => {
editor.text = value;
}),
enter: undefined as (() => boolean) | undefined,
change: undefined as ((markdown: string) => void) | undefined,
}));
vi.mock(
'@core/component/LexicalMarkdown/builder/MarkdownConfigBuilder',
() => ({
buildConfig: () => {
editor.lexical = createEditor({ nodes: [QuoteNode] });
const builder = {
buildHandle: () => ({ lexical: editor.lexical }),
namespace: () => builder,
withAppLinkResolver: () => builder,
withMentions: () => builder,
withEmojis: () => builder,
withLinks: () => builder,
withHistory: () => builder,
withCode: () => builder,
withRestoreFocus: () => builder,
withAgentCommands: () => builder,
withFilePaste: () => builder,
onEnter: (callback: () => boolean) => {
editor.enter = callback;
return builder;
},
onFocusLeave: () => builder,
onChange: (callback: (markdown: string) => void) => {
editor.change = callback;
return builder;
},
controls: {
clear: editor.clear,
focus: vi.fn(),
getMarkdown: () => editor.text,
setMarkdown: editor.setMarkdown,
},
lexical: editor.lexical,
};
return builder;
},
})
);
vi.mock('@core/component/LexicalMarkdown/builder/MarkdownShell', () => ({
MarkdownShell: (props: { disabled?: boolean; initialValue?: string }) => (
<div data-testid="agent-input-editor" data-disabled={props.disabled}>
{props.initialValue}
{/* Decorators portal their popups (the paste viewer) out of the editor. */}
<Portal>
<pre data-testid="portaled-text">Pasted text</pre>
</Portal>
</div>
),
}));
// The channel composer's chips and drop zone reach the block registry (and
// through it the chat input's storage module) on import; the composer's own
// send/attach logic is what is under test, so they are stubs that surface
// what this component hands them.
vi.mock('@channel/Input/context', () => ({
InputProvider: (props: { children: unknown }) => props.children,
}));
vi.mock('@channel/Input/Input', () => ({
Input: {
DropZone: (props: { children: unknown }) => props.children,
DropOverlay: () => null,
Attachments: () => null,
AttachFilesAction: () => (
<button type="button" aria-label="Attach files">
attach
</button>
),
},
}));
vi.mock('@core/util/upload', () => ({ handleFileFolderDrop: vi.fn() }));
vi.mock('@icon/system/bold/arrow-up-bold.svg', () => ({
default: () => <span data-testid="send-icon" />,
}));
vi.mock('@icon/system/regular/spinner-gap.svg', () => ({
default: () => <span data-testid="spinner-icon" />,
}));
beforeEach(() => {
vi.mocked(preloadAgentFold).mockClear();
vi.stubGlobal(
'ResizeObserver',
class {
observe() {}
unobserve() {}
disconnect() {}
}
);
editor.text = '';
editor.clear.mockClear();
editor.setMarkdown.mockClear();
editor.enter = undefined;
editor.change = undefined;
vi.mocked(isTouchDevice).mockReturnValue(false);
});
it('preloads on document-chat composer focus without submitting its context', () => {
const send = vi.fn();
render(() => <AgentInput initialInput="Document context" onSend={send} />);
expect(preloadAgentFold).not.toHaveBeenCalled();
fireEvent.focusIn(screen.getByTestId('agent-input-editor'));
expect(preloadAgentFold).toHaveBeenCalledOnce();
expect(send).not.toHaveBeenCalled();
expect(editor.clear).not.toHaveBeenCalled();
});
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);
});
it('leaves Enter to the virtual keyboard and sends only from the button', () => {
const onSend = vi.fn();
render(() => <AgentInput onSend={onSend} />);
editor.change?.('first line');
// Not captured, so the editor inserts a newline instead of sending.
expect(editor.enter?.()).toBe(false);
expect(onSend).not.toHaveBeenCalled();
expect(editor.clear).not.toHaveBeenCalled();
fireEvent.click(screen.getByRole('button', { name: 'Send' }));
expect(onSend).toHaveBeenCalledWith('first line', []);
expect(editor.clear).toHaveBeenCalledOnce();
});
});
describe('while the agent is working', () => {
it('keeps view-only drafts and stop inert', () => {
const onSend = vi.fn();
const onStop = vi.fn();
render(() => <AgentInput readOnly busy onSend={onSend} onStop={onStop} />);
expect(
screen.getByTestId('agent-input-editor').getAttribute('data-disabled')
).toBe('true');
const stop = screen.getByRole('button', {
name: 'Stop',
}) as HTMLButtonElement;
expect(stop.disabled).toBe(true);
fireEvent.click(stop);
editor.enter?.();
editor.change?.('Cannot send this');
editor.enter?.();
expect(onSend).not.toHaveBeenCalled();
expect(onStop).not.toHaveBeenCalled();
});
it('never stops the turn from Enter on an empty draft', () => {
const onSend = vi.fn();
const onStop = vi.fn();
render(() => <AgentInput busy onSend={onSend} onStop={onStop} />);
editor.enter?.();
expect(onStop).not.toHaveBeenCalled();
editor.change?.(' another request ');
editor.enter?.();
expect(onSend).toHaveBeenCalledWith('another request', []);
expect(onStop).not.toHaveBeenCalled();
expect(editor.clear).toHaveBeenCalledOnce();
});
it('sends attached files instead of advancing past them', () => {
const onSend = vi.fn();
const onStop = vi.fn();
const uploaded = {
id: 'file-1',
name: 'screenshot.png',
kind: 'image' as const,
mimeType: 'image/png',
size: 2048,
};
render(() => (
<AgentInput
busy
onSend={onSend}
onStop={onStop}
attachments={[uploaded]}
onAttachFiles={vi.fn()}
/>
));
// Attached files are a draft: both tapping Send and Enter send them.
expect(screen.getByRole('button', { name: 'Send' })).toBeTruthy();
expect(screen.queryByRole('button', { name: 'Stop' })).toBeNull();
editor.enter?.();
expect(onSend).toHaveBeenCalledWith('', [uploaded]);
expect(onStop).not.toHaveBeenCalled();
});
it('keeps Enter inert when there is no queued message or draft', () => {
const onStop = vi.fn();
render(() => <AgentInput busy onSend={vi.fn()} onStop={onStop} />);
expect(screen.getByRole('button', { name: 'Stop' })).toBeTruthy();
editor.enter?.();
expect(onStop).not.toHaveBeenCalled();
});
});
describe('attachments', () => {
const uploaded = {
id: 'file-1',
name: 'screenshot.png',
kind: 'image' as const,
mimeType: 'image/png',
size: 2048,
};
it('sends attached files with no text at all', () => {
const onSend = vi.fn();
render(() => (
<AgentInput
onSend={onSend}
attachments={[uploaded]}
onAttachFiles={vi.fn()}
/>
));
editor.enter?.();
expect(onSend).toHaveBeenCalledWith('', [uploaded]);
});
it('holds the send while a file is still uploading', () => {
const onSend = vi.fn();
render(() => (
<AgentInput
onSend={onSend}
attachments={[{ ...uploaded, pending: true }]}
onAttachFiles={vi.fn()}
/>
));
editor.change?.('look at this');
editor.enter?.();
expect(onSend).not.toHaveBeenCalled();
expect(screen.getByRole('button', { name: 'Send' })).toHaveProperty(
'disabled',
true
);
});
it('measures the composer height above the editor row, so chips are inside it', () => {
// The surface is pinned to the measured element's height. The attachment
// chips render alongside the editor row, so the measured element has to be
// their shared parent — measuring the row alone clips them. The chips come
// from the mocked `@channel/Input` here, so this pins the measurement
// boundary rather than the chip markup.
const { container } = render(() => (
<AgentInput
onSend={vi.fn()}
attachments={[uploaded]}
onAttachFiles={vi.fn()}
/>
));
const measured = container.querySelector('[data-composer-content]');
const editorRow = container.querySelector('[data-composer-compact]');
expect(measured).toBeTruthy();
expect(editorRow).toBeTruthy();
expect(measured).not.toBe(editorRow);
expect(editorRow?.parentElement).toBe(measured);
expect(
measured?.querySelector(`#${AGENT_INPUT_TEXT_AREA_ID}`)
).toBeTruthy();
});
it('offers the paperclip only when files can be attached', () => {
render(() => <AgentInput onSend={vi.fn()} />);
expect(screen.queryByRole('button', { name: 'Attach files' })).toBeNull();
cleanup();
render(() => <AgentInput onSend={vi.fn()} onAttachFiles={vi.fn()} />);
expect(screen.getByRole('button', { name: 'Attach files' })).toBeTruthy();
});
});
it('leaves presses in portaled editor popups to the browser so their text can be selected', () => {
const { container } = render(() => <AgentInput onSend={vi.fn()} />);
const press = (target: Element, type: string) => {
const event = new MouseEvent(type, { bubbles: true, cancelable: true });
target.dispatchEvent(event);
return event.defaultPrevented;
};
const padding = container.querySelector('[data-composer-compact]')!;
const portaled = screen.getByTestId('portaled-text');
expect(container.contains(portaled)).toBe(false);
for (const type of ['pointerdown', 'mousedown']) {
expect(press(padding, type)).toBe(true);
expect(press(portaled, type)).toBe(false);
}
});
it('expands for a short quote and collapses when replaced with a paragraph', () => {
const { container } = render(() => <AgentInput onSend={vi.fn()} />);
const layout = container.querySelector('[data-composer-compact]');
expect(layout?.getAttribute('data-composer-compact')).toBe('true');
editor.lexical!.update(
() => {
$getRoot()
.clear()
.append($createQuoteNode().append($createTextNode('short')));
},
{ discrete: true }
);
expect(layout?.getAttribute('data-composer-compact')).toBe('false');
editor.lexical!.update(
() => {
$getRoot()
.clear()
.append($createParagraphNode().append($createTextNode('short')));
},
{ discrete: true }
);
expect(layout?.getAttribute('data-composer-compact')).toBe('true');
});
it('keeps an attached image and text unsent while the selected model is text-only', () => {
const send = vi.fn();
render(() => (
<AgentInput
onSend={send}
supportsImages={false}
attachments={[{ id: 'image', name: 'test.png', kind: 'image' }]}
/>
));
expect(screen.queryByText(/This model does not support images/)).toBeNull();
editor.enter?.();
expect(send).not.toHaveBeenCalled();
expect(editor.clear).not.toHaveBeenCalled();
});