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.

8.5 KB
Raw Blame
import { usePending } from '@app/observability/flow';
/** App-facing composition for the agent session and its controllers. */

import { createInteractionController } from '@app/features/agent-interactions/primitives/create-interaction-controller';
import { AgentSession } from '@core/agent-session/AgentSession';
import { toast } from '@core/component/Toast/Toast';
import { isCodexBotId } from '@core/constant/codexAgent';
import { isCursorBotId } from '@core/constant/cursorAgent';
import { useUserId } from '@core/context/user';
import { idToDisplayName } from '@core/user/util';
import { useAgentSessionExternalUrlQuery } from '@queries/agent-session/session';
import { useAgentSessionSubscription } from '@queries/agent-session/subscription';
import { answerAgentSessionToolApproval } from '@queries/agent-session/tool-approvals';
import type {
  FoldedMessage,
  TurnState,
} from '@service-agent-fold/generated/types';
import type { AgentSessionResponse } from '@service-agent-harness/generated/schemas';
import {
  type Accessor,
  createEffect,
  type ParentProps,
  Suspense,
} from 'solid-js';
import { AgentSessionContext } from './context/AgentSessionContext';
import { createAgentSession } from './context/create-agent-session';
import {
  createQueueController,
  type QueueController,
} from './context/create-queue-controller';
import { resolveSessionId } from './context/resolve-session-id';
import { createSteering } from './context/steer';
import { createToolApprovalController } from './primitives/create-tool-approval-controller';
import type { QuoteInsert } from './ui';

export function AgentSessionProvider(
  props: ParentProps & {
    /** The block's id: a session, or a placeholder for one being created. */
    blockId: string;
    /** The real id, once known — the block adopts it into the URL. */
    onSessionId?: (sessionId: string) => void;
  }
) {
  const {
    sessionId,
    pending,
    failed,
    error,
    pendingPrompt,
    initialInput,
    acquired,
  } = resolveSessionId(() => props.blockId);

  usePending('agent.provision', pending);

  createEffect(() => {
    const id = sessionId();
    if (id && id !== props.blockId) props.onSessionId?.(id);
  });

  const userId = useUserId();
  const live = createAgentSession(sessionId, {
    userId,
    provisioning: pending,
    onAcquire: acquired,
  });
  // A block opened by sending a first prompt shows that prompt, and the
  // working line under it, from its very first paint. Nothing else can: the
  // session does not exist until `POST /agent-sessions` answers, and the
  // shared session's own speculation starts only once it does. This stands
  // in until the fold reports anything at all - the speculated bubble
  // arrives under the same key and takes over without a gap.
  const firstPrompt = () => {
    const prompt = pendingPrompt();
    if (!prompt || failed() || live.messages().length > 0) return undefined;
    return prompt;
  };
  const messages = (): FoldedMessage[] => {
    const prompt = firstPrompt();
    if (prompt === undefined) return live.messages();
    return [
      {
        agentSessionId: sessionId() ?? props.blockId,
        key: '0:user',
        turn: 0,
        author: { kind: 'user', userId: userId() ?? null },
        requestId: null,
        parts: [{ kind: 'text', text: prompt }],
        stop: null,
        pending: true,
        segments: [],
        phase: null,
        postedAt: null,
      },
    ];
  };
  const turn = (): TurnState =>
    firstPrompt() !== undefined
      ? 'starting'
      : (live.metadata()?.turn ?? 'idle');
  const served = createQueueController({
    // Public viewers can read the transcript without signing in, while the
    // live action queue requires an authenticated caller.
    sessionId: () => (userId() ? sessionId() : undefined),
    messages: live.messages,
  });
  // A row the user removes may be one a force-send already showed as sent;
  // the fold has to forget it too, or it stays a bubble the log never fills.
  const queue: QueueController = {
    ...served,
    remove: (actionId) => {
      live.retract(actionId);
      return served.remove(actionId);
    },
  };
  const steering = createSteering({
    entries: queue.entries,
    waiting: queue.waiting,
    steer: queue.steer,
    expect: live.expect,
    retract: live.retract,
  });
  const interactions = createInteractionController({
    sessionId,
    pending: () => live.metadata()?.pendingInteractions ?? [],
    canEdit: () => live.session()?.canEdit,
    issue: live.issue,
    onFailure: toast.failure,
  });
  useAgentSessionSubscription(sessionId);
  const toolApprovals = createToolApprovalController({
    sessionId,
    pending: () => live.metadata()?.pendingInteractions ?? [],
    ownerId: () => live.session()?.ownerId,
    userId,
    canEdit: () => live.session()?.canEdit,
    onFailure: toast.failure,
    answer: answerAgentSessionToolApproval,
  });

  // The transcript's "Reply to this" chip hands selected text to the
  // composer through here. A plain variable, not a signal: it is only read
  // at call time, never rendered from.
  let quoteInsert: QuoteInsert | undefined;
  const registerQuoteInsert = (insert: QuoteInsert | undefined) => {
    quoteInsert = insert;
  };
  const quoteSelection: QuoteInsert = (text) => quoteInsert?.(text);

  return (
    <>
      {/* Nested so a pending poll cannot take the block orchestrator's
          <Suspense fallback={<LoadingBlock />}> and blank the transcript.
          The poll component gates on `isSuccess` so it should not suspend;
          this boundary is the backstop if a read of `query.data` ever does. */}
      <Suspense fallback={null}>
        <CloudExternalUrlPoll
          sessionId={sessionId}
          session={live.session}
          applySnapshot={live.applySnapshot}
        />
      </Suspense>
      <AgentSessionContext.Provider
        value={{
          userId,
          displayName: idToDisplayName,
          sessionId,
          pending,
          initialInput: initialInput(),
          startupError: error,
          session: live.session,
          bot: live.bot,
          metadata: live.metadata,
          messages,
          observeRenderedText: (id, turn, element) =>
            id === sessionId()
              ? AgentSession.get(id)?.observeRenderedText(turn, element)
              : undefined,
          // A create that failed leaves the block with nothing to load, which
          // is the same dead end for the reader as a load that failed.
          loadFailed: () => live.loadFailed() || failed(),
          accessDenied: live.accessDenied,
          // Retrying a refusal in earnest gets the same refusal. A refusal of
          // a session this tab just created is not one of those, and never
          // reaches here as denied access: `AgentSession` waits it out, and
          // reports a load that can be tried again if it never clears.
          loadRetryable: () => live.loadFailed() && !live.accessDenied(),
          retryLoad: live.retry,
          turn,
          issue: live.issue,
          selectModel: live.selectModel,
          steer: steering.steer,
          steerFailed: steering.failed,
          interactions,
          toolApprovals,
          queue,
          quoteSelection,
          registerQuoteInsert,
        }}
      >
        {props.children}
      </AgentSessionContext.Provider>
    </>
  );
}

/**
 * Compensating read for a cloud session whose provider URL arrived after
 * the feed's snapshot. Lives in its own Suspense so the rest of the block
 * stays mounted while this query's first fetch is in flight.
 */
function CloudExternalUrlPoll(props: {
  sessionId: Accessor<string | undefined>;
  session: Accessor<AgentSessionResponse | undefined>;
  applySnapshot: (session: AgentSessionResponse) => void;
}) {
  // Only a loaded cloud session whose provider URL is still missing polls;
  // everything else passes `undefined`, which disables the query.
  const query = useAgentSessionExternalUrlQuery(() => {
    const id = props.sessionId();
    const session = props.session();
    if (!id || !session || session.external?.url) return undefined;
    return isCursorBotId(session.botId) || isCodexBotId(session.botId)
      ? id
      : undefined;
  });
  createEffect(() => {
    // `query.data` suspends while pending and throws once it errors
    // (`useFavoritesData`). Gate on success so neither reaches the
    // orchestrator Suspense / an error boundary.
    if (!query.isSuccess) return;
    const snapshot = query.data;
    if (!snapshot?.external?.url) return;
    props.applySnapshot(snapshot);
  });
  return null;
}