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 { ListFilterDropdown } from '@app/components/view-shell';
import { SidePanel } from '@components/app/side-panel';
import { AgentSessionMentionLabel } from '@core/component/LexicalMarkdown/component/decorator/AgentSessionMentionLabel';
import { toast } from '@core/component/Toast/Toast';
import { fireAndForget } from '@core/util/fireAndForget';
import PlusIcon from '@icon/system/regular/plus.svg';
import XIcon from '@icon/system/regular/x.svg';
import { useAgentSessionMentionPreview } from '@queries/agent-session/mentions';
import {
  useAgentSessionPullRequestsQuery,
  useLinkAgentSessionPullRequestMutation,
  usePullRequestAgentSessionsQuery,
  useUnlinkAgentSessionPullRequestMutation,
} from '@queries/agent-session/pull-requests';
import { useQuickAccessAgentSessionsQuery } from '@queries/soup/quick-access-agent-sessions';
import { Button, Dropdown, Tooltip } from '@ui';
import { For, Match, Show, Switch } from 'solid-js';
import { useOpenFromSidePanel } from './open-from-side-panel';

const pullRequestKey = (url: string) =>
  url.replace(/^https:\/\/github\.com\//i, '').toLowerCase();

/** An agent session's name, or why it can't be shown. */
export function useAgentSessionLabel(sessionId: () => string) {
  const preview = useAgentSessionMentionPreview(sessionId, () => true);
  const session = () => {
    const current = preview.isSuccess ? preview.data : undefined;
    return current?.access === 'access' ? current.data : undefined;
  };
  const label = () => {
    const current = preview.isSuccess ? preview.data : undefined;
    if (current?.access === 'no_access') return 'Private agent session';
    if (current?.access === 'does_not_exist') return 'Deleted agent session';
    return session()?.name || 'Agent session';
  };
  return { session, label };
}

function LinkedSessionRow(props: { sessionId: string; url: string }) {
  const open = useOpenFromSidePanel();
  const { session, label } = useAgentSessionLabel(() => props.sessionId);
  const links = useAgentSessionPullRequestsQuery(() => props.sessionId);
  const unlink = useUnlinkAgentSessionPullRequestMutation();
  // The pull request the session's agent opened cannot be unlinked.
  const linkedByPerson = () =>
    links.isSuccess &&
    links.data.some(
      (link) =>
        link.source === 'user' &&
        link.githubKey.toLowerCase() === pullRequestKey(props.url)
    );

  return (
    <div class="flex h-6 min-w-0 items-center gap-2">
      <Tooltip label={label()} class="min-w-0 flex-1">
        <button
          type="button"
          class="w-full min-w-0 truncate text-left disabled:text-ink-placeholder"
          disabled={!session()}
          onClick={(event) =>
            open({ type: 'agent', id: props.sessionId }, event.shiftKey)
          }
        >
          <AgentSessionMentionLabel label={label()} />
        </button>
      </Tooltip>
      <Show when={linkedByPerson()}>
        <Button
          aria-label={`Unlink ${label()}`}
          tooltip={`Unlink ${label()}`}
          variant="ghost"
          size="icon-xs"
          class="ml-auto"
          disabled={unlink.isPending}
          onClick={() =>
            unlink.mutate(
              { sessionId: props.sessionId, url: props.url },
              {
                onError: () =>
                  toast.failure('Couldn’t unlink the agent session.'),
              }
            )
          }
        >
          <XIcon class="size-3 touch:size-6 shrink-0 pointer-events-none" />
        </Button>
      </Show>
    </div>
  );
}

function LinkSessionPicker(props: {
  url: string;
  linkedSessionIds: readonly string[];
}) {
  const sessions = useQuickAccessAgentSessionsQuery();
  const link = useLinkAgentSessionPullRequestMutation();
  const options = () =>
    sessions
      .sessions()
      .filter((session) => !props.linkedSessionIds.includes(session.id))
      .map((session) => ({
        id: session.id,
        label: session.name || 'Agent session',
      }));

  return (
    <ListFilterDropdown
      label="Link agent session"
      customTrigger={
        <Dropdown.Trigger
          aria-label="Link agent session"
          tooltip="Link agent session"
          variant="ghost"
          size="xs"
        >
          <PlusIcon class="size-3 touch:size-6 shrink-0 pointer-events-none" />
          Link session
        </Dropdown.Trigger>
      }
      groups={[
        {
          id: 'session',
          label: 'Agent sessions',
          options: options(),
          searchPlaceholder: 'Search agent sessions',
        },
      ]}
      isSelected={(_group, id) => props.linkedSessionIds.includes(id)}
      onSelectionChange={(_group, sessionId, selected) => {
        if (!selected) return;
        link.mutate(
          { sessionId, url: props.url },
          {
            onError: () => toast.failure('Couldn’t link the agent session.'),
          }
        );
      }}
    />
  );
}

/** Agent sessions linked to a pull request, from either side of the link. */
export function PrAgentSessionsSection(props: {
  url?: string;
  prStatus: 'pending' | 'error' | 'success';
}) {
  const sessions = usePullRequestAgentSessionsQuery(() => props.url);
  const sessionIds = () => (sessions.isSuccess ? sessions.data : []);

  return (
    <SidePanel.Section id="pr-agent-sessions" title="Agent sessions" order={30}>
      <Switch>
        <Match when={props.prStatus === 'error'}>
          <div class="text-ink-placeholder">
            Pull request details couldn’t be loaded
          </div>
        </Match>
        <Match when={!props.url}>
          <div class="text-ink-placeholder" role="status">
            {props.prStatus === 'pending'
              ? 'Loading pull request details…'
              : 'Pull request URL isn’t available'}
          </div>
        </Match>
        <Match when={sessions.isPending}>
          <div class="text-ink-placeholder" role="status">
            Loading agent sessions…
          </div>
        </Match>
        <Match when={sessions.isError}>
          <div class="text-ink-placeholder">
            Agent sessions couldn’t be loaded
          </div>
          <Button
            variant="ghost"
            size="xs"
            onClick={() => fireAndForget(sessions.refetch(), 'pr-side-panel')}
          >
            Retry
          </Button>
        </Match>
        <Match when={sessions.isSuccess && props.url}>
          {(url) => (
            <div class="flex flex-col gap-1 text-xs">
              <Show
                when={sessionIds().length > 0}
                fallback={
                  <div class="text-ink-placeholder">No agent sessions</div>
                }
              >
                <For each={sessionIds()}>
                  {(sessionId) => (
                    <LinkedSessionRow sessionId={sessionId} url={url()} />
                  )}
                </For>
              </Show>
              <div>
                <LinkSessionPicker
                  url={url()}
                  linkedSessionIds={sessionIds()}
                />
              </div>
            </div>
          )}
        </Match>
      </Switch>
    </SidePanel.Section>
  );
}