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.

7.0 KB
Raw Blame
import { PersonaAvatar } from '@app/features/agent-dms/components/persona-avatar';
import { InteractionCard } from '@app/features/agent-interactions/components/InteractionCard';
import type { AgentInteraction } from '@app/features/agent-interactions/context/interaction';
import { createInteractionController } from '@app/features/agent-interactions/primitives/create-interaction-controller';
import {
  isWorkingTurn,
  sessionTurn,
  subscribeSessionTurns,
} from '@core/agent-session/session-turn';
import { toast } from '@core/component/Toast/Toast';
import { fireAndForget } from '@core/util/fireAndForget';
import { useAgentSessionQuery } from '@queries/agent-session/session';
import { firstPartyBotName } from '@queries/bots/first-party-bot-name';
import { useBotProfile } from '@queries/bots/profiles';
import { queryReadyGate } from '@queries/gate';
import { getTypingAgents, type TypingAgent } from '@queries/messages/typing';
import type { MessagePart } from '@service-agent-fold/generated/types';
import type { MessageParent } from '@service-storage/messages';
import { Key } from '@solid-primitives/keyed';
import {
  createMemo,
  createSignal,
  For,
  onCleanup,
  Show,
  Suspense,
} from 'solid-js';
import { LiveTail } from './components/live-tail';
import { TypingRow } from './components/typing-row';
import { openReply, openRun, phaseRow } from './core/live-reply';
import { createCodeActivityRows } from './queries/code-activity';
import { createLiveSession } from './queries/live-session';

/** One place of a conversation: the timeline, or one thread. */
type TypingPlace = { parent: MessageParent; threadId: string | null };

/**
 * Agents typing in one place of a conversation - the timeline, or one
 * thread - each as a typing row that says what the agent is doing: the step
 * it is on to a viewer who can read the session, otherwise what its turn is
 * doing. That viewer also gets Stop, and anything the turn is waiting on
 * beneath the row.
 *
 * A list shows it under its newest row, so it mounts again whenever a message
 * arrives; the live session it reads is shared, so it picks up where it was.
 */
export function AgentTyping(props: TypingPlace) {
  // A boundary of its own: rows that suspend must not blank the message.
  return (
    <Suspense>
      <AgentTypingRows parent={props.parent} threadId={props.threadId} />
    </Suspense>
  );
}

function AgentTypingRows(props: TypingPlace) {
  const [turns, setTurns] = createSignal(0);
  onCleanup(subscribeSessionTurns(() => setTurns((count) => count + 1)));
  // Typing lapses whenever its heartbeat does, as when a phone sleeps with
  // the app open. An agent whose turn the fold still has open - working, or
  // waiting on the viewer - keeps its row until the turn ends, and with it
  // whatever the viewer was answering beneath it.
  const agents = createMemo<ReadonlyMap<string, TypingAgent>>((shown) => {
    turns();
    const next = new Map(getTypingAgents(props.parent, props.threadId));
    for (const [botUserId, agent] of shown) {
      const turn = sessionTurn(agent.sessionId);
      if (!next.has(botUserId) && (isWorkingTurn(turn) || turn === 'blocked'))
        next.set(botUserId, agent);
    }
    return next;
  }, new Map());
  return (
    <For each={[...agents().keys()]}>
      {(botUserId) => (
        <Show when={agents().get(botUserId)}>
          {(info) => (
            <AgentTypingEntry
              botUserId={botUserId}
              sessionId={info().sessionId}
              phase={info().phase}
            />
          )}
        </Show>
      )}
    </For>
  );
}

function AgentTypingEntry(props: {
  botUserId: string;
  sessionId: string;
  phase: 'thinking' | 'writing' | 'working' | 'waiting';
}) {
  const botId = () => props.botUserId.replace(/^bot\|/, '');
  const firstParty = () => firstPartyBotName(botId());
  const profile = useBotProfile(() => (firstParty() ? '' : botId()));
  // Empty while the profile loads, rather than a placeholder name that
  // changes a moment later.
  const name = () => {
    const known = firstParty();
    if (known) return known;
    if (queryReadyGate(profile)) return profile.data?.name ?? 'Agent';
    return profile.isError ? 'Agent' : '';
  };
  const avatarUrl = () =>
    queryReadyGate(profile) ? profile.data?.avatarUrl : undefined;

  const live = createLiveSession(() => props.sessionId);
  const sessionQuery = useAgentSessionQuery(() => props.sessionId);
  const canEdit = () =>
    queryReadyGate(sessionQuery) ? sessionQuery.data?.canEdit : undefined;
  const reply = () => (live.loaded() ? openReply(live.messages()) : undefined);
  const run = () => openRun(reply());
  const rows = createCodeActivityRows(
    () => props.sessionId,
    reply,
    () => run()?.index,
    () => run()?.rows ?? [phaseRow(props.phase)]
  );
  // A held tool call is answered from the session, not here: a turn the
  // owner prompts, as every DM turn is, is never held for them.
  const pending = () =>
    (live.metadata()?.pendingInteractions ?? []).filter(
      (request): request is AgentInteraction =>
        request.kind !== 'tool_approval' && request.turn === reply()?.turn
    );
  const interactions = createInteractionController({
    sessionId: () => props.sessionId,
    pending,
    canEdit,
    issue: (action) => live.issue(action),
    onFailure: (message) => toast.failure(message),
  });
  const toolFor = (toolCall: string | null) => {
    const part = reply()?.parts.find(
      (candidate): candidate is Extract<MessagePart, { kind: 'tool_use' }> =>
        candidate.kind === 'tool_use' && candidate.id === toolCall
    );
    return part;
  };
  const [stopping, setStopping] = createSignal(false);
  const stop = async () => {
    setStopping(true);
    try {
      const result = await live.issue({ type: 'stop' });
      if (result?.isErr()) toast.failure('The agent could not be stopped');
    } catch {
      toast.failure('The agent could not be stopped');
    } finally {
      setStopping(false);
    }
  };

  return (
    <TypingRow
      avatar={
        <PersonaAvatar
          botId={botId()}
          name={name()}
          avatarUrl={avatarUrl()}
          size="md"
        />
      }
      rows={rows()}
      onStop={
        canEdit() && reply()
          ? () => fireAndForget(stop(), 'agent-activity')
          : undefined
      }
      stopping={stopping()}
    >
      <Show when={pending().length > 0 || live.failed()}>
        <LiveTail disconnected={live.failed()} onReconnect={live.retry}>
          {/* Each metadata event carries every request anew. Keyed by what
              it asks, a card keeps whatever was typed into it. */}
          <Key
            each={pending()}
            by={(request) =>
              JSON.stringify([request.turn, request.kind, request.requestId])
            }
          >
            {(request) => (
              <InteractionCard
                request={request()}
                controller={interactions}
                tool={toolFor(request().toolCall)}
              />
            )}
          </Key>
        </LiveTail>
      </Show>
    </TypingRow>
  );
}