Skip to content

Open-source AI teammates in Slack, Teams, Discord, Telegram and Mattermost. Self-host it, with any agent harness and any model.

7.7 KB
Raw Blame
import { toast } from 'sonner';
import type { AdminSection } from '@renderer/features/admin/admin-sections';
import { isAgentSection } from '@renderer/features/managed-agents/agent-sections';
import { resolveSettingsTab } from '@renderer/features/settings/settings-tabs';
import { findBuddy } from '@renderer/features/switch-buddy/buddy-identity';
import { switchServersStore } from '@renderer/features/switch-servers/switch-servers-store';
import { administersWorkspaceInScope } from '@renderer/features/switch-servers/workspace-admin';
import { workspacesStore } from '@renderer/features/workspaces/workspaces-store';
import { rpc } from '@renderer/lib/ipc';
import { showModal } from '@renderer/lib/modal/modal-provider';
import { appState } from '@renderer/lib/stores/app-state';
import { type ConsoleLink, parseConsoleLink } from '@shared/core/deeplinks/console-links';

/**
 * Open the page a `switchdash://open/…` link points at: from a click in the
 * app's own chat, or handed over by the OS. A link that cannot be followed —
 * malformed, for a server this Console is not connected to, for an agent it
 * cannot show — says so rather than leaving the person where they were with
 * no idea why.
 */
export async function openConsoleLink(raw: string): Promise<void> {
  const parsed = parseConsoleLink(raw);
  if (!parsed.ok) {
    toast.error('Could not open that link', { description: parsed.reason });
    return;
  }
  const { link } = parsed;
  if (link.page === 'settings') {
    appState.navigation.navigate('settings', {
      tab: resolveSettingsTab(link.tab),
    });
    return;
  }
  const serverId = serverFor(link);
  if (serverId === null) return;
  if (switchServersStore.activeServerId !== serverId) await switchServersStore.setActive(serverId);
  await openOnServer(serverId, link);
}

/** The server a link means: the one it names, else the one on screen. */
function serverFor(link: ConsoleLink): string | null {
  if (link.server === null) {
    const active = switchServersStore.activeServerId;
    if (active === null)
      toast.error('Could not open that link', {
        description: 'Connect to a Switch server first.',
      });
    return active;
  }
  const origin = originOf(link.server);
  // An older server's link may name the separate host its dashboard is on.
  const match = switchServersStore.servers.find(
    (server) =>
      origin !== null &&
      [server.url, server.dashboardUrl].some((own) => own !== null && originOf(own) === origin)
  );
  if (!match) {
    toast.error('Could not open that link', {
      description: `It is for ${link.server}, which this Switch Console is not connected to.`,
    });
    return null;
  }
  return match.id;
}

function originOf(address: string): string | null {
  try {
    return new URL(address).origin;
  } catch {
    return null;
  }
}

async function openOnServer(serverId: string, link: ConsoleLink): Promise<void> {
  const navigation = appState.navigation;
  switch (link.page) {
    case 'home':
      navigation.navigate('server', { serverId });
      return;
    case 'server':
      openServerSettings(serverId);
      return;
    case 'agents':
      navigation.navigate('serverAgents', { serverId });
      return;
    case 'agents/new':
      navigation.navigate('serverAgents', { serverId });
      showModal('addAgentModal', { entryPoint: 'link', machine: null });
      return;
    case 'agent':
      await openAgent(serverId, link.id!, link.tab);
      return;
    case 'rooms':
      navigation.navigate('serverRooms', { serverId });
      return;
    case 'room':
      navigation.navigate('room', { roomId: link.id! });
      return;
    case 'chat':
      navigation.navigate('chat', { serverId, roomId: link.id!, agentId: null });
      return;
    case 'buddy':
      await openBuddy(serverId, link.tab);
      return;
    case 'templates':
      navigation.navigate('templates', {
        serverId,
        ...(link.tab ? { kind: link.tab as 'agent' | 'room' | 'group' } : {}),
      });
      return;
    case 'template':
      navigation.navigate('templateDetail', { serverId, templateId: link.id! });
      return;
    case 'messaging-apps/connect':
      // Connecting an app is the workspace admins'; anyone else can only link
      // their own account, which Settings does.
      if (!administersWorkspaceInScope(serverId)) {
        navigation.navigate('settings', { tab: 'messaging-apps' });
        return;
      }
      navigation.navigate('admin', { serverId, section: 'messaging-apps' });
      showModal('connectMessagingAppModal', { serverId, onClosed: () => {} });
      return;
    case 'connections':
      navigation.navigate('connectors', { serverId });
      return;
    case 'invite': {
      const workspaceId = workspacesStore.idOnServerInScope(serverId);
      if (workspaceId === null) {
        toast.error('Could not open that link', {
          description: 'Open a workspace on this server first.',
        });
        return;
      }
      showModal('invitePeopleModal', { workspaceId });
      return;
    }
    case 'admin':
      openAdmin(serverId, link.tab);
      return;
    case 'settings':
      return;
  }
}

/**
 * The Server page exists only for a server this Console runs; for any other
 * the link lands on its home and says why.
 */
function openServerSettings(serverId: string): void {
  const server = switchServersStore.servers.find((listed) => listed.id === serverId);
  if (server?.managed) {
    appState.navigation.navigate('managedServer', { serverId });
    return;
  }
  appState.navigation.navigate('server', { serverId });
  toast.error('This server has no Server page here', {
    description:
      "Someone else runs it, so its start, stop, update and Mattermost settings aren't in this Switch Console.",
  });
}

/**
 * Admin is for the workspace's admins. Whoever runs the server without
 * administering it is looking for its status, and is sent there; anyone else
 * lands on the home and is told why.
 */
function openAdmin(serverId: string, tab: string | null): void {
  if (!administersWorkspaceInScope(serverId)) {
    if (switchServersStore.servers.find((listed) => listed.id === serverId)?.managed) {
      appState.navigation.navigate('managedServer', { serverId });
      return;
    }
    appState.navigation.navigate('server', { serverId });
    toast.error('Admin is for workspace admins', {
      description: 'Ask an admin of this workspace to change these.',
    });
    return;
  }
  appState.navigation.navigate('admin', {
    serverId,
    ...(tab ? { section: tab as AdminSection } : {}),
  });
}

/**
 * switch-buddy's page: its agent page once it exists, on the section the link's tab
 * names, else the page that sets it up, where there are no tabs yet.
 */
async function openBuddy(serverId: string, tab: string | null): Promise<void> {
  const agents = await rpc.managedAgents.list(serverId).catch(() => null);
  const buddy = findBuddy(agents);
  if (buddy === null) {
    appState.navigation.navigate('switchBuddy', { serverId });
    return;
  }
  appState.navigation.navigate('managedAgent', {
    serverId,
    agentId: buddy.agentId,
    name: buddy.name,
    ...(isAgentSection(tab) ? { section: tab } : {}),
  });
}

/** An agent's page is its managed-agent page; one Console does not manage has none here. */
async function openAgent(serverId: string, agentId: string, tab: string | null): Promise<void> {
  const agents = await rpc.managedAgents.list(serverId).catch(() => null);
  const agent = agents?.find((listed) => listed.agentId === agentId) ?? null;
  if (agent === null) {
    toast.error('Could not open that agent', {
      description: "It isn't one of your agents on this server, so it has no page here.",
    });
    return;
  }
  appState.navigation.navigate('managedAgent', {
    serverId,
    agentId,
    name: agent.name,
    ...(isAgentSection(tab) ? { section: tab } : {}),
  });
}