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): keep unsent messages in session composers (#7418)

Wolf Mermelsteine410bc4deade
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 28ba5d6420..76a2efd38b 100644
--- a/apps/web/src/features/agents-view/components/ChatComposer.test.tsx
+++ b/apps/web/src/features/agents-view/components/ChatComposer.test.tsx
@@ -1,3 +1,4 @@
+import { createSessionComposerDraft } from '@app/features/block-agent/primitives/session-composer-draft';
import type { InputAttachmentData } from '@channel/Input/types';
import { isTouchDevice } from '@core/mobile/isTouchDevice';
import { $createQuoteNode, QuoteNode } from '@lexical/rich-text';
@@ -165,6 +166,53 @@ describe('Chat session input', () => {
).toBe(true);
});
+ it('restores an unsent session message after the composer remounts', () => {
+ localStorage.clear();
+ const View = () => {
+ const persisted = createSessionComposerDraft(() => 'session-restore');
+ return (
+ <ChatSessionInput
+ draft={persisted.draft()}
+ onDraftChange={persisted.setDraft}
+ onSend={vi.fn()}
+ />
+ );
+ };
+ const first = render(() => <View />);
+ type('Hold this for the session');
+ first.unmount();
+ editor.text = '';
+ editor.setMarkdown.mockClear();
+ render(() => <View />);
+ expect(editor.setMarkdown).toHaveBeenCalledWith(
+ 'Hold this for the session'
+ );
+ });
+
+ it('drops the saved session message once it is sent', () => {
+ localStorage.clear();
+ const send = vi.fn();
+ const View = () => {
+ const persisted = createSessionComposerDraft(() => 'session-sent');
+ return (
+ <ChatSessionInput
+ draft={persisted.draft()}
+ onDraftChange={persisted.setDraft}
+ onSend={send}
+ />
+ );
+ };
+ const first = render(() => <View />);
+ type('Send and forget');
+ fireEvent.click(screen.getByRole('button', { name: 'Send' }));
+ expect(send).toHaveBeenCalledWith('Send and forget', []);
+ first.unmount();
+ editor.text = '';
+ editor.setMarkdown.mockClear();
+ render(() => <View />);
+ expect(editor.setMarkdown).not.toHaveBeenCalledWith('Send and forget');
+ });
+
it('keeps a draft intact while the session is pending', () => {
const send = vi.fn();
render(() => <ChatSessionInput disabled onSend={send} />);
diff --git a/apps/web/src/features/agents-view/components/ChatComposer.tsx b/apps/web/src/features/agents-view/components/ChatComposer.tsx
index 8e853d5029..e7fc090031 100644
--- a/apps/web/src/features/agents-view/components/ChatComposer.tsx
+++ b/apps/web/src/features/agents-view/components/ChatComposer.tsx
@@ -401,7 +401,13 @@ 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(props.initialInput ?? '');
+ const [owned, setOwned] = createSignal(props.initialInput ?? '');
+ const controlled = () => props.onDraftChange !== undefined;
+ const draft = () => (controlled() ? (props.draft ?? '') : owned());
+ const setDraft = (value: string) => {
+ if (props.onDraftChange) props.onDraftChange(value);
+ else setOwned(value);
+ };
return (
<ChatComposer
draft={draft()}
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 39adcc71e5..6337192c16 100644
--- a/apps/web/src/features/block-agent/component/AgentComposer.test.tsx
+++ b/apps/web/src/features/block-agent/component/AgentComposer.test.tsx
@@ -61,6 +61,7 @@ vi.mock('../context/AgentSessionContext', () => ({
sendNext: mocks.sendNext,
steer: mocks.steer,
turn: () => mocks.turn(),
+ sessionId: () => 'session-1',
registerQuoteInsert: vi.fn(),
}),
}));
@@ -82,6 +83,7 @@ vi.mock('../ui', () => ({
vi.mock('./PermissionRequest', () => ({ PermissionRequest: () => null }));
beforeEach(() => {
+ localStorage.clear();
vi.resetAllMocks();
mocks.turn = () => 'idle';
mocks.session = () => ({ canEdit: false });
diff --git a/apps/web/src/features/block-agent/component/AgentComposer.tsx b/apps/web/src/features/block-agent/component/AgentComposer.tsx
index cfa7260865..c45d6975c2 100644
--- a/apps/web/src/features/block-agent/component/AgentComposer.tsx
+++ b/apps/web/src/features/block-agent/component/AgentComposer.tsx
@@ -9,7 +9,6 @@ import { Button } from '@ui';
import { useOptionalChanges } from '@app/features/changes/context/changes-controller';
import {
- createInputAttachmentTracker,
type InputAttachmentData,
uploadInputAttachments,
} from '@channel/Input';
@@ -18,6 +17,10 @@ import { uploadFile } from '@core/util/upload';
import type { AgentAction } from '@service-agent-harness/generated/schemas';
import { type Component, createSignal, For, Show } from 'solid-js';
import { useAgentSession } from '../context/AgentSessionContext';
+import {
+ createSessionAttachmentTracker,
+ createSessionComposerDraft,
+} from '../primitives/session-composer-draft';
import {
changingConfig,
changingModel,
@@ -69,7 +72,12 @@ export function AgentComposer(props: {
turn,
registerQuoteInsert,
initialInput,
+ sessionId,
} = useAgentSession();
+ const persistedDraft = createSessionComposerDraft(
+ sessionId,
+ () => initialInput
+ );
const changes = useOptionalChanges();
const readOnly = () => session()?.canEdit === false;
@@ -138,7 +146,7 @@ export function AgentComposer(props: {
// the static file service - documents too, not only media - because the
// agent can only reach a file by a URL it can fetch. The chips and the
// upload flow are the channel composer's.
- const attachmentTracker = createInputAttachmentTracker();
+ const attachmentTracker = createSessionAttachmentTracker(sessionId);
const attachFiles = (files: File[]) => {
if (readOnly()) return;
void uploadInputAttachments({
@@ -263,6 +271,8 @@ export function AgentComposer(props: {
</For>
<Input
initialInput={initialInput}
+ draft={persistedDraft.draft()}
+ onDraftChange={persistedDraft.setDraft}
placeholder={
readOnly()
? 'You have view-only access to this agent session'
diff --git a/apps/web/src/features/block-agent/primitives/session-composer-draft.test.ts b/apps/web/src/features/block-agent/primitives/session-composer-draft.test.ts
new file mode 100644
index 0000000000..30905bf550
--- /dev/null
+++ b/apps/web/src/features/block-agent/primitives/session-composer-draft.test.ts
@@ -0,0 +1,181 @@
+/**
+ * @vitest-environment jsdom
+ */
+
+import type { InputAttachmentData } from '@channel/Input/types';
+import { createRoot, createSignal } from 'solid-js';
+import { beforeEach, describe, expect, it } from 'vitest';
+import {
+ agentSessionAttachmentsKey,
+ agentSessionDraftKey,
+ createSessionAttachmentTracker,
+ createSessionComposerDraft,
+} from './session-composer-draft';
+
+const note: InputAttachmentData = {
+ id: 'file-1',
+ name: 'notes.txt',
+ kind: 'document',
+};
+
+function withRoot(run: () => void) {
+ let dispose: () => void = () => {};
+ createRoot((done) => {
+ dispose = done;
+ run();
+ });
+ dispose();
+}
+
+describe('session composer drafts', () => {
+ beforeEach(() => {
+ localStorage.clear();
+ });
+
+ it('restores one session without touching another', () => {
+ withRoot(() => {
+ const first = createSessionComposerDraft(() => 'session-a');
+ const second = createSessionComposerDraft(() => 'session-b');
+ first.setDraft('Ask about the plan');
+ second.setDraft('Ask about the code');
+ });
+
+ withRoot(() => {
+ const first = createSessionComposerDraft(() => 'session-a');
+ const second = createSessionComposerDraft(() => 'session-b');
+ expect(first.draft()).toBe('Ask about the plan');
+ expect(second.draft()).toBe('Ask about the code');
+ first.setDraft('');
+ expect(second.draft()).toBe('Ask about the code');
+ });
+
+ expect(localStorage.getItem(agentSessionDraftKey('session-a'))).toBeNull();
+ withRoot(() => {
+ expect(createSessionComposerDraft(() => 'session-a').draft()).toBe('');
+ expect(createSessionComposerDraft(() => 'session-b').draft()).toBe(
+ 'Ask about the code'
+ );
+ });
+ });
+
+ it('keeps text typed before the session id exists', () => {
+ const [sessionId, setSessionId] = createSignal<string | undefined>();
+ let draft: ReturnType<typeof createSessionComposerDraft> | undefined;
+ let dispose: () => void = () => {};
+ createRoot((done) => {
+ dispose = done;
+ draft = createSessionComposerDraft(sessionId, () => 'Seed');
+ });
+ expect(draft?.draft()).toBe('Seed');
+ draft?.setDraft('Follow up while it starts');
+ setSessionId('session-real');
+ expect(draft?.draft()).toBe('Follow up while it starts');
+ dispose();
+
+ expect(localStorage.getItem(agentSessionDraftKey('session-real'))).toBe(
+ JSON.stringify('Follow up while it starts')
+ );
+ withRoot(() => {
+ expect(createSessionComposerDraft(() => 'session-real').draft()).toBe(
+ 'Follow up while it starts'
+ );
+ });
+ });
+
+ it('removes a cleared editor draft when its markdown contains only whitespace', () => {
+ withRoot(() => {
+ const draft = createSessionComposerDraft(() => 'session-a');
+ const other = createSessionComposerDraft(() => 'session-b');
+ draft.setDraft('Follow up');
+ other.setDraft(' Keep the indentation\n');
+ draft.setDraft('\n \n');
+ });
+
+ expect(localStorage.getItem(agentSessionDraftKey('session-a'))).toBeNull();
+ withRoot(() => {
+ expect(createSessionComposerDraft(() => 'session-a').draft()).toBe('');
+ expect(createSessionComposerDraft(() => 'session-b').draft()).toBe(
+ ' Keep the indentation\n'
+ );
+ });
+ });
+
+ it('ignores a previously saved whitespace-only draft when seeding context', () => {
+ localStorage.setItem(
+ agentSessionDraftKey('session-a'),
+ JSON.stringify('\n \n')
+ );
+ withRoot(() => {
+ const draft = createSessionComposerDraft(
+ () => 'session-a',
+ () => 'Document context'
+ );
+ expect(draft.draft()).toBe('Document context');
+ });
+ });
+
+ it('prefers a saved draft over seeded context', () => {
+ withRoot(() => {
+ createSessionComposerDraft(() => 'session-a').setDraft('Already typed');
+ });
+ withRoot(() => {
+ const draft = createSessionComposerDraft(
+ () => 'session-a',
+ () => 'Document context'
+ );
+ expect(draft.draft()).toBe('Already typed');
+ });
+ });
+
+ it('restores settled attachments and drops uploads that never finished', () => {
+ withRoot(() => {
+ const tracker = createSessionAttachmentTracker(() => 'session-a');
+ tracker.addAttachment(note);
+ tracker.addAttachment({ ...note, id: 'pending-file', pending: true });
+ });
+
+ expect(
+ localStorage.getItem(agentSessionAttachmentsKey('session-a'))
+ ).toContain('notes.txt');
+ expect(
+ localStorage.getItem(agentSessionAttachmentsKey('session-a'))
+ ).not.toContain('pending-file');
+
+ withRoot(() => {
+ const tracker = createSessionAttachmentTracker(() => 'session-a');
+ expect(tracker.attachments().map((file) => file.id)).toEqual(['file-1']);
+ tracker.clearAttachments();
+ });
+
+ expect(
+ localStorage.getItem(agentSessionAttachmentsKey('session-a'))
+ ).toBeNull();
+ withRoot(() => {
+ expect(
+ createSessionAttachmentTracker(() => 'session-a').attachments()
+ ).toEqual([]);
+ });
+ });
+
+ it('moves attachments onto the session id once it exists', () => {
+ const [sessionId, setSessionId] = createSignal<string | undefined>();
+ let tracker: ReturnType<typeof createSessionAttachmentTracker> | undefined;
+ let dispose: () => void = () => {};
+ createRoot((done) => {
+ dispose = done;
+ tracker = createSessionAttachmentTracker(sessionId);
+ });
+ tracker?.addAttachment(note);
+ setSessionId('session-real');
+ expect(tracker?.attachments().map((file) => file.id)).toEqual(['file-1']);
+ dispose();
+
+ withRoot(() => {
+ expect(
+ createSessionAttachmentTracker(() => 'session-real')
+ .attachments()
+ .map((file) => file.id)
+ ).toEqual(['file-1']);
+ });
+ });
+});
diff --git a/apps/web/src/features/block-agent/primitives/session-composer-draft.ts b/apps/web/src/features/block-agent/primitives/session-composer-draft.ts
new file mode 100644
index 0000000000..59f8325b55
--- /dev/null
+++ b/apps/web/src/features/block-agent/primitives/session-composer-draft.ts
@@ -0,0 +1,195 @@
+/**
+ * Unsent text and attachments for one agent session.
+ *
+ * The composer unmounts when the session leaves the screen. These drafts are
+ * keyed by session id, the same way a channel keeps its reply, so coming back
+ * restores what was about to be sent. A session id that arrives after the
+ * composer mounts (the create is still on the wire) takes over the text and
+ * files already in the box.
+ */
+
+import { createInputAttachmentTracker } from '@channel/Input/attachment-tracker';
+import type {
+ InputAttachmentData,
+ InputAttachmentTracker,
+} from '@channel/Input/types';
+import { createPersistenceKey } from '@queries/persistence';
+import {
+ type Accessor,
+ createEffect,
+ createSignal,
+ on,
+ untrack,
+} from 'solid-js';
+
+export function agentSessionDraftKey(sessionId: string) {
+ return createPersistenceKey(`input-value-agent-session:${sessionId}`, 0);
+}
+
+export function agentSessionAttachmentsKey(sessionId: string) {
+ return createPersistenceKey(
+ `attachment-tracker-agent-session:${sessionId}`,
+ 0
+ );
+}
+
+function readJson(key: string | undefined): unknown {
+ if (!key) return undefined;
+ try {
+ const raw = localStorage.getItem(key);
+ if (raw == null) return undefined;
+ return JSON.parse(raw) as unknown;
+ } catch {
+ return undefined;
+ }
+}
+
+function writeJson(key: string | undefined, value: unknown) {
+ if (!key) return;
+ try {
+ if (value === undefined) localStorage.removeItem(key);
+ else localStorage.setItem(key, JSON.stringify(value));
+ } catch {
+ // A full or blocked store leaves the in-memory draft usable.
+ }
+}
+
+function readDraft(sessionId: string | undefined): string | undefined {
+ const parsed = readJson(
+ sessionId ? agentSessionDraftKey(sessionId) : undefined
+ );
+ return typeof parsed === 'string' && parsed.trim().length > 0
+ ? parsed
+ : undefined;
+}
+
+function writeDraft(sessionId: string | undefined, value: string) {
+ writeJson(
+ sessionId ? agentSessionDraftKey(sessionId) : undefined,
+ value.trim().length > 0 ? value : undefined
+ );
+}
+
+function isAttachment(value: unknown): value is InputAttachmentData {
+ return (
+ !!value &&
+ typeof value === 'object' &&
+ typeof (value as InputAttachmentData).id === 'string' &&
+ !(value as InputAttachmentData).pending
+ );
+}
+
+function readAttachments(sessionId: string | undefined): InputAttachmentData[] {
+ const parsed = readJson(
+ sessionId ? agentSessionAttachmentsKey(sessionId) : undefined
+ );
+ return Array.isArray(parsed) ? parsed.filter(isAttachment) : [];
+}
+
+function writeAttachments(
+ sessionId: string | undefined,
+ attachments: InputAttachmentData[]
+) {
+ const settled = attachments.filter((attachment) => !attachment.pending);
+ writeJson(
+ sessionId ? agentSessionAttachmentsKey(sessionId) : undefined,
+ settled.length > 0 ? settled : undefined
+ );
+}
+
+/** Text waiting to be sent into this session. */
+export function createSessionComposerDraft(
+ sessionId: Accessor<string | undefined>,
+ initial?: Accessor<string | undefined>
+) {
+ const startingId = untrack(sessionId);
+ const [text, setText] = createSignal(
+ readDraft(startingId) ?? untrack(() => initial?.()) ?? ''
+ );
+ let currentId = startingId;
+
+ const setDraft = (value: string) => {
+ setText(value);
+ writeDraft(currentId, value);
+ };
+
+ createEffect(
+ on(
+ sessionId,
+ (id) => {
+ if (id === currentId) return;
+ const value = untrack(text);
+ if (currentId) writeDraft(currentId, '');
+ currentId = id;
+ if (!id) return;
+ if (value) {
+ writeDraft(id, value);
+ return;
+ }
+ const stored = readDraft(id);
+ if (stored) setText(stored);
+ },
+ { defer: true }
+ )
+ );
+
+ return { draft: text, setDraft };
+}
+
+/** Files waiting to be sent into this session. Uploads still in flight are not kept. */
+export function createSessionAttachmentTracker(
+ sessionId: Accessor<string | undefined>
+): InputAttachmentTracker {
+ const startingId = untrack(sessionId);
+ const tracker = createInputAttachmentTracker({
+ initialAttachments: readAttachments(startingId),
+ });
+ let currentId = startingId;
+
+ const persist = () => writeAttachments(currentId, tracker.attachments());
+
+ createEffect(
+ on(
+ sessionId,
+ (id) => {
+ if (id === currentId) return;
+ const current = untrack(tracker.attachments);
+ if (currentId) writeAttachments(currentId, []);
+ currentId = id;
+ if (!id) return;
+ if (current.some((attachment) => !attachment.pending)) {
+ writeAttachments(id, current);
+ return;
+ }
+ const stored = readAttachments(id);
+ if (stored.length > 0) tracker.setAttachments(stored);
+ },
+ { defer: true }
+ )
+ );
+
+ return {
+ attachments: tracker.attachments,
+ hasPending: tracker.hasPending,
+ addAttachment: (attachment) => {
+ tracker.addAttachment(attachment);
+ persist();
+ },
+ removeAttachment: (attachmentId) => {
+ tracker.removeAttachment(attachmentId);
+ persist();
+ },
+ setAttachmentPending: (attachmentId, pending) => {
+ tracker.setAttachmentPending(attachmentId, pending);
+ persist();
+ },
+ setAttachments: (attachments) => {
+ tracker.setAttachments(attachments);
+ persist();
+ },
+ clearAttachments: () => {
+ tracker.clearAttachments();
+ persist();
+ },
+ };
+}
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 92162bc7be..b6e9c6aa8e 100644
--- a/apps/web/src/features/block-agent/ui/AgentInput.test.tsx
+++ b/apps/web/src/features/block-agent/ui/AgentInput.test.tsx
@@ -21,7 +21,11 @@ vi.mock('@core/mobile/isTouchDevice', () => ({
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,
}));
@@ -55,6 +59,8 @@ vi.mock(
controls: {
clear: editor.clear,
focus: vi.fn(),
+ getMarkdown: () => editor.text,
+ setMarkdown: editor.setMarkdown,
},
lexical: editor.lexical,
};
@@ -109,7 +115,9 @@ beforeEach(() => {
disconnect() {}
}
);
+ editor.text = '';
editor.clear.mockClear();
+ editor.setMarkdown.mockClear();
editor.enter = undefined;
editor.change = undefined;
vi.mocked(isTouchDevice).mockReturnValue(false);
diff --git a/apps/web/src/features/block-agent/ui/AgentInput.tsx b/apps/web/src/features/block-agent/ui/AgentInput.tsx
index 4140cfca39..b79ce6db48 100644
--- a/apps/web/src/features/block-agent/ui/AgentInput.tsx
+++ b/apps/web/src/features/block-agent/ui/AgentInput.tsx
@@ -30,7 +30,14 @@ import { useTouchOutsideToDismissKeyboard } from '@core/mobile/useTouchOutsideTo
import { handleFileFolderDrop } from '@core/util/upload';
import { $insertReferencedPaste } from '@macro-inc/lexical-core';
import { Button, ComposerSurface, SendButton } from '@ui';
-import { createSignal, type JSX, onCleanup, onMount, Show } from 'solid-js';
+import {
+ createEffect,
+ createSignal,
+ type JSX,
+ onCleanup,
+ onMount,
+ Show,
+} from 'solid-js';
/**
* Id of the agent input's text-area wrapper. Exposed so callers (e.g. the
@@ -45,6 +52,12 @@ export interface AgentInputProps {
placeholder?: string;
/** Context to seed in the composer without sending it. */
initialInput?: string;
+ /**
+ * Controlled composer text. Set with `onDraftChange` when a parent keeps
+ * the unsent message (an agent session draft).
+ */
+ draft?: string;
+ onDraftChange?: (draft: string) => void;
/** The agent is working: the send button becomes a stop square. */
busy?: boolean;
/**
@@ -114,7 +127,13 @@ export interface AgentInputProps {
}
export function AgentInput(props: AgentInputProps) {
- const [markdown, setMarkdown] = createSignal(props.initialInput ?? '');
+ const [owned, setOwned] = createSignal(props.initialInput ?? '');
+ const controlled = () => props.onDraftChange !== undefined;
+ const markdown = () => (controlled() ? (props.draft ?? '') : owned());
+ const setMarkdown = (value: string) => {
+ if (props.onDraftChange) props.onDraftChange(value);
+ else setOwned(value);
+ };
const [isDraggedOver, setIsDraggedOver] = createSignal(false);
let containerRef: HTMLDivElement | undefined;
const [layout, setLayout] = createSignal<HTMLDivElement>();
@@ -167,6 +186,7 @@ export function AgentInput(props: AgentInputProps) {
if (!canSend()) return;
const content = markdown().trim();
const attached = attachments();
+ setMarkdown('');
editor.controls.clear();
props.onSend(content, attached);
};
@@ -238,6 +258,13 @@ export function AgentInput(props: AgentInputProps) {
})
.onChange(setMarkdown);
+ // A parent can restore or clear the draft after the editor has mounted.
+ createEffect(() => {
+ const next = markdown();
+ if (next !== editor.controls.getMarkdown())
+ editor.controls.setMarkdown(next);
+ });
+
const { isCompact, hasMultilineContent } = createComposerLayout(
editor.buildHandle().lexical,
{
@@ -359,7 +386,7 @@ export function AgentInput(props: AgentInputProps) {
>
<ComposerEditor
config={editor}
- initialValue={props.initialInput}
+ initialValue={markdown()}
disabled={props.readOnly}
placeholder={
props.placeholder ??
diff --git a/docs/AGENT_GUIDE/ai-chat.md b/docs/AGENT_GUIDE/ai-chat.md
index ac885484ff..07cb6ab060 100644
--- a/docs/AGENT_GUIDE/ai-chat.md
+++ b/docs/AGENT_GUIDE/ai-chat.md
@@ -394,7 +394,11 @@ the shimmer.
use the same growing, initially single-line input with the model selector on
the right.
Existing sessions retain their agent and kind; use **New conversation** to
- choose another. Stop, queued-message advancement, and quoting remain available.
+ choose another. An unsent message in that session — the text and attached
+ files that finished uploading — stays when you leave for a channel, another
+ session, or Home and come back, including after reload. Sending or clearing
+ the input removes only that session's draft. Stop, queued-message advancement,
+ and quoting remain available.
Archived sessions are read-only: Rename and all message controls are unavailable,
and an **Unarchive** action replaces the composer at the bottom. Archive /
Unarchive is also available from the title dropdown.