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.

12.9 KB
Raw Blame
import { openMacroMcpSetupModal } from '@app/features/integrations/mcp-setup/MacroMcpSetupModal';
import type { CustomFileOperation } from '@components/app/split-layout/components/SplitFileMenu';
import type { SplitFileMenuAction } from '@components/app/split-layout/context';
import { editorStateAsMarkdown } from '@core/component/LexicalMarkdown/utils';
import { toast } from '@core/component/Toast/Toast';
import { macroIdToEmail, tryMacroId } from '@core/user';
import { copyBranchNameToClipboard } from '@core/util/branchName';
import { fireAndForget } from '@core/util/fireAndForget';
import CaretDown from '@icon/system/regular/caret-down.svg';
import CopyIcon from '@icon/system/regular/copy.svg';
import GitBranch from '@icon/system/regular/git-branch.svg';
import PlugIcon from '@icon/system/regular/plug.svg';
import TerminalWindowIcon from '@icon/system/regular/terminal-window.svg';
import ClaudeIcon from '@icon/wide-claude.svg';
import CodexIcon from '@icon/wide-codex-ide.svg';
import CursorIcon from '@icon/wide-cursor-ide.svg';
import ZedIcon from '@icon/wide-zed-ide.svg';
import { fetchDocumentThreads } from '@queries/messages/document-messages';
import { storageServiceClient } from '@service-storage/client';
import type { MessageThread } from '@service-storage/messages';
import { createCallback } from '@solid-primitives/rootless';
import { makePersisted } from '@solid-primitives/storage';
import { ButtonGroup, CopyButton, Dropdown } from '@ui';
import { type Component, createSignal, For, type JSX, Show } from 'solid-js';
import { Dynamic } from 'solid-js/web';
import { useMarkdownDocument } from '../context/markdown-document-context';
import { useMarkdownName } from './MarkdownNameProvider';

const LAST_USED_KEY = 'dispatch-agent-last-used';

type PromptComment = {
  author: string;
  createdAt?: string | null;
  text: string;
};
type PromptThread = { threadId: string | number; comments: PromptComment[] };

function messagePromptThreads(threads: MessageThread[]): PromptThread[] {
  return threads.map((thread) => ({
    threadId: thread.state.root_id,
    comments: [thread.root, ...thread.replies]
      .filter((message) => message.content && !message.deleted_at)
      .map((message) => ({
        author: message.imported_author?.name?.trim() || message.sender_id,
        createdAt: message.created_at,
        text: message.content,
      })),
  }));
}

/** Copy/export needs full discussions, not the timeline's bounded reply previews. */
async function fetchMessagePromptThreads(
  documentId: string
): Promise<PromptThread[]> {
  const threads = await fetchDocumentThreads({
    type: 'document',
    id: documentId,
  });
  threads.reverse();
  return messagePromptThreads(threads);
}

function promptThreadLines(threads: PromptThread[]): string[] {
  const lines: string[] = [];
  for (const thread of threads) {
    lines.push(`<comment-thread thread-id="${thread.threadId}">`);
    for (const comment of thread.comments) {
      const macroId = tryMacroId(comment.author);
      const author = macroId ? macroIdToEmail(macroId) : comment.author;
      const createdAt = comment.createdAt
        ? ` created-at="${comment.createdAt}"`
        : '';
      lines.push(
        `<comment author="${author}"${createdAt}>${comment.text}</comment>`
      );
    }
    lines.push('</comment-thread>');
  }
  return lines;
}

async function fetchBranchName(documentId: string) {
  const result = await storageServiceClient.getDocumentBranchName({
    documentId,
  });
  if (!result.isOk()) {
    throw new Error('Failed to fetch branch name');
  }
  return result.value;
}

/**
 * Plain documents carry no branch (the branch endpoint rejects non-tasks), so
 * the prompt frames them as context to read.
 */
async function generateDocumentPrompt(
  documentId: string,
  documentName: string,
  content: string,
  threads: PromptThread[]
): Promise<string> {
  const result = await storageServiceClient.getDocumentShortId({ documentId });
  if (!result.isOk()) {
    throw new Error('Failed to fetch short id');
  }
  const shortId = result.value;

  const lines: string[] = [];

  lines.push(`Read the Macro document ${documentName}:`);
  lines.push('');
  lines.push(`<document identifier="${shortId}">`);
  lines.push(`<title>${documentName}</title>`);
  lines.push('</document>');

  if (content) {
    lines.push('');
    lines.push('<document-content>');
    lines.push(content);
    lines.push('</document-content>');
  }

  if (threads.length > 0) {
    lines.push('');
    lines.push(...promptThreadLines(threads));
  }

  lines.push('');
  lines.push(
    'If you have the Macro MCP server enabled, use it to gather additional context about this document.'
  );

  return lines.join('\n');
}

async function generateTaskPrompt(
  documentId: string,
  documentName: string,
  content: string,
  threads: PromptThread[]
): Promise<string> {
  const { shortId, branchName } = await fetchBranchName(documentId);

  const lines: string[] = [];

  lines.push(`Work on Macro task ${documentName}:`);
  lines.push('');
  lines.push(`<task identifier="${shortId}">`);
  lines.push(`<title>${documentName}</title>`);
  lines.push(`<branch>${branchName}</branch>`);
  lines.push('</task>');

  if (content) {
    lines.push('');
    lines.push('<task-content>');
    lines.push(content);
    lines.push('</task-content>');
  }

  if (threads.length > 0) {
    lines.push('');
    lines.push(...promptThreadLines(threads));
  }

  lines.push('');
  lines.push(`Please use the branch "${branchName}" for your work.`);
  lines.push('');
  lines.push(
    'If you have the Macro MCP server enabled, use it to gather additional context about this task.'
  );
  lines.push('');
  lines.push(
    'When committing and titling pull requests, please follow the Conventional Commits spec (e.g. `feat: ...`, `fix: ...`, `chore: ...`) so the history stays consistent.'
  );
  lines.push('');
  lines.push(
    'Keep the pull request description concise, succinct, and useful. No need for test cases or verification steps — just describe exactly what the PR solves and how, and include a link back to the original session if applicable.'
  );

  return lines.join('\n');
}

type AgentAction = {
  key: string;
  name: string;
  icon: Component<JSX.SvgSVGAttributes<SVGSVGElement>>;
  buttonIcon?: Component<JSX.SvgSVGAttributes<SVGSVGElement>>;
  execute: (prompt: string) => unknown;
};

const COPY_ACTION: AgentAction = {
  key: 'copy',
  name: 'Copy as prompt',
  icon: CopyIcon,
  buttonIcon: TerminalWindowIcon,
  execute: async (prompt) => {
    await navigator.clipboard.writeText(prompt);
  },
};

const PLATFORM_ACTIONS: AgentAction[] = [
  {
    key: 'claude-code',
    name: 'Claude Code Web',
    icon: ClaudeIcon,
    execute: (prompt) =>
      window.open(
        `https://claude.ai/code?q=${encodeURIComponent(prompt)}`,
        '_blank'
      ),
  },
  {
    key: 'codex-desktop',
    name: 'Codex Desktop',
    icon: CodexIcon,
    execute: (prompt) =>
      window.open(`codex://new?prompt=${encodeURIComponent(prompt)}`, '_blank'),
  },
  {
    key: 'cursor',
    name: 'Cursor',
    icon: CursorIcon,
    execute: (prompt) =>
      window.open(
        `cursor://anysphere.cursor-deeplink/prompt?text=${encodeURIComponent(prompt)}`,
        '_blank'
      ),
  },
  {
    key: 'zed',
    name: 'Zed',
    icon: ZedIcon,
    execute: (prompt) =>
      window.open(`zed://agent?prompt=${encodeURIComponent(prompt)}`, '_blank'),
  },
];

const ALL_ACTIONS = [COPY_ACTION, ...PLATFORM_ACTIONS];

const [lastUsedKey, setLastUsedKey] = makePersisted(
  createSignal(COPY_ACTION.key),
  { name: LAST_USED_KEY }
);

export function useDispatchAgentAction() {
  const { documentId, kind, state } = useMarkdownDocument();
  const blockId = documentId();
  const { displayName: name } = useMarkdownName();
  const isTask = () => kind() === 'task';

  const lastUsed = () =>
    ALL_ACTIONS.find((a) => a.key === lastUsedKey()) ?? COPY_ACTION;

  const buildPrompt = createCallback(async () => {
    const docName = name() ?? '';
    const editor = state.editor.md.editor;
    const content = editor ? editorStateAsMarkdown(editor, 'external') : '';
    const threads = await fetchMessagePromptThreads(blockId);
    const generate = isTask() ? generateTaskPrompt : generateDocumentPrompt;
    return generate(blockId, docName, content, threads);
  });

  const executeAction = async (
    action: AgentAction,
    options: { silent?: boolean } = {}
  ) => {
    try {
      const prompt = await buildPrompt();
      await action.execute(prompt);
      if (action.key === 'copy' && !options.silent) {
        toast.success('Prompt copied to clipboard');
      }
      setLastUsedKey(action.key);
      return true;
    } catch (e) {
      console.error('Failed to generate prompt', e);
      toast.failure('Failed to generate prompt');
      return false;
    }
  };

  return {
    blockId,
    isTask,
    lastUsed,
    executeAction,
    executeLastUsed: () => executeAction(lastUsed(), { silent: true }),
  };
}

export function useDispatchAgentSplitFileActions(): {
  copyAsPrompt: CustomFileOperation;
  all: SplitFileMenuAction[];
} {
  const { executeAction } = useDispatchAgentAction();

  const copyAsPrompt: CustomFileOperation = {
    label: COPY_ACTION.name,
    icon: COPY_ACTION.icon,
    action: () => {
      fireAndForget(executeAction(COPY_ACTION), 'dispatch-agent');
    },
  };

  return {
    copyAsPrompt,
    all: [
      copyAsPrompt,
      ...PLATFORM_ACTIONS.map((action) => ({
        label: action.name,
        icon: action.icon,
        action: () => {
          fireAndForget(executeAction(action), 'dispatch-agent');
        },
      })),
      {
        label: 'MCP setup instructions',
        icon: PlugIcon,
        action: openMacroMcpSetupModal,
      },
    ],
  };
}

export function DispatchAgentButton(
  props: { showPrimaryLabel?: boolean } = {}
) {
  const [open, setOpen] = createSignal(false);
  const { blockId, isTask, lastUsed, executeAction, executeLastUsed } =
    useDispatchAgentAction();

  return (
    <Dropdown open={open()} onOpenChange={setOpen}>
      <ButtonGroup
        finish="raised"
        variant="secondary"
        size={props.showPrimaryLabel ? 'sm' : 'icon-sm'}
        class="border-0"
      >
        <Dynamic
          component={
            lastUsed().key === 'copy' ? CopyButton : ButtonGroup.Button
          }
          {...(lastUsed().key === 'copy' ? { as: ButtonGroup.Button } : {})}
          onClick={executeLastUsed}
          tooltip={lastUsed().name}
          class="@max-[600px]/split-header:w-7 @max-[600px]/split-header:p-0"
        >
          <Dynamic
            component={lastUsed().buttonIcon ?? lastUsed().icon}
            class="size-3.5!"
          />
          <Show when={props.showPrimaryLabel}>
            <span class="max-w-36 truncate @max-[600px]/split-header:hidden">
              {lastUsed().name}
            </span>
          </Show>
        </Dynamic>
        <ButtonGroup.Divider />
        <Dropdown.Trigger
          as={ButtonGroup.Button}
          aria-label="Agent options"
          tooltip="Agent options"
          variant="secondary"
          size="icon-sm"
        >
          <CaretDown class="size-3.5!" />
        </Dropdown.Trigger>
      </ButtonGroup>
      <Dropdown.Content>
        <Dropdown.Group>
          <Dropdown.Item
            onSelect={() => {
              fireAndForget(executeAction(COPY_ACTION), 'dispatch-agent');
              setOpen(false);
            }}
          >
            <Dynamic component={COPY_ACTION.icon} class="size-4 shrink-0" />
            <span class="flex-1 truncate">{COPY_ACTION.name}</span>
          </Dropdown.Item>
          <Show when={isTask()}>
            <Dropdown.Item
              onSelect={() => {
                fireAndForget(
                  copyBranchNameToClipboard(blockId),
                  'dispatch-agent'
                );
                setOpen(false);
              }}
            >
              <GitBranch class="size-4 shrink-0" />
              <span class="flex-1 truncate">Copy branch name</span>
            </Dropdown.Item>
          </Show>
          <Dropdown.Item
            onSelect={() => {
              openMacroMcpSetupModal();
              setOpen(false);
            }}
          >
            <PlugIcon class="size-4 shrink-0" />
            <span class="flex-1 truncate">MCP setup instructions</span>
          </Dropdown.Item>
        </Dropdown.Group>
        <Dropdown.Group>
          <Dropdown.GroupLabel>Open in</Dropdown.GroupLabel>
          <For each={PLATFORM_ACTIONS}>
            {(action) => (
              <Dropdown.Item
                onSelect={() => {
                  fireAndForget(executeAction(action), 'dispatch-agent');
                  setOpen(false);
                }}
              >
                <Dynamic component={action.icon} class="size-4 shrink-0" />
                <span class="flex-1 truncate">{action.name}</span>
              </Dropdown.Item>
            )}
          </For>
        </Dropdown.Group>
      </Dropdown.Content>
    </Dropdown>
  );
}