import { useId } from "react"; import { AGENT_ROLES, AGENT_ROLE_LABELS } from "@paperclipai/shared"; import type { MuseInvitationDraft } from "@/lib/muse-invitation-draft"; import { Input } from "../ui/input"; import { Link } from "@/lib/router"; import { ArrowLeft, Bot, Check, Circle, CircleAlert, Loader2 } from "lucide-react"; import { AdapterMark } from "../AdapterMark"; import { AgentSetupPrompt } from "../AgentSetupPrompt"; import { Button } from "../ui/button"; import { DialogDescription, DialogTitle } from "../ui/dialog"; import { cn } from "@/lib/utils"; export type ExternalAgentPreset = "dot" | "grok_bot" | "muse" | "hermes" | "other"; export type DotConnectionState = { phase: "waiting" | "connected" | "subscribed" | "testing" | "finishing" | "ready"; problem?: "event_timeout" | "prompt_unavailable" | "offline" | "agent_unavailable"; }; const presets = [ { id: "dot", name: "Dot", adapter: "openai_dot", description: "Your Dot in ChatGPT" }, { id: "grok_bot", name: "Grok Bot", adapter: "grok_bot", description: "An existing Bot in Grok" }, { id: "muse", name: "Muse — Personal agent", adapter: "muse", description: "Your personal Muse at muse.ai" }, { id: "hermes", name: "Hermes", adapter: "hermes_gateway", description: "An existing Hermes agent" }, { id: "other", name: "Other", adapter: "http", description: "Any agent that can connect to Paperclip" }, ] as const; export function ExternalAgentPresetPicker({ onSelect, dotDisabledReason, grokDisabledReason, museEnabled = false }: { onSelect: (preset: ExternalAgentPreset) => void; dotDisabledReason?: string; grokDisabledReason?: string; museEnabled?: boolean }) { return
{presets.filter(preset => preset.id !== "muse" || museEnabled).map(preset => )}
; } const checks = [ { title: "Connected to Paperclip", description: "Your Dot has connected to this agent." }, { title: "Task updates enabled", description: "Your Dot is subscribed to new assignments and messages." }, { title: "Test event confirmed", description: "Your Dot received our test and replied to Paperclip." }, ]; /** Controlled by server evidence in the invite controller, never by copying a prompt. */ export function DotConnectionChecks({ state }: { state: DotConnectionState }) { const completed = { waiting: 0, connected: 1, subscribed: 2, testing: 2, finishing: 3, ready: 3 }[state.phase]; const message = state.problem === "agent_unavailable" ? "Connection checks passed, but this agent cannot receive tasks. Resolve the agent’s setup blocker in Paperclip." : state.problem === "offline" ? "Connection updates paused. Reconnect to check the latest status." : state.problem === "prompt_unavailable" ? "This setup prompt was replaced in another window. Create a fresh prompt to continue." : state.problem === "event_timeout" ? "Your Dot connected, but hasn’t confirmed the test event. Ask it to check Paperclip, then retry." : state.phase === "finishing" ? "Your Dot confirmed the test event. Paperclip is finishing agent setup." : state.phase === "ready" ? "Your Dot is ready for tasks. Messages can travel both ways." : state.phase === "waiting" ? "Watching for your Dot. Updates will appear here automatically." : state.phase === "connected" ? "Your Dot connected. Waiting for it to enable task updates." : "Waiting for your Dot to confirm a test event. No task will be created."; return
    {checks.map((check, index) => { const done = index < completed; const failed = index === completed && state.problem === "event_timeout"; const active = index === completed && !state.problem; const Icon = done ? Check : failed ? CircleAlert : active ? Loader2 : Circle; return
  1. {check.title}{done ? ": complete" : failed ? ": needs attention" : active ? ": in progress" : ": waiting"}

    {done &&

    {check.description}

    }
  2. ; })}

{message}

; } export type MuseConnectionState = { paired: boolean; receiverDetected: boolean; backgroundReplyVerified: boolean; ready: boolean; finishing?: boolean; testing?: boolean; problem?: "no_recent_response" | "prompt_unavailable" | "offline" | "agent_unavailable" | "disconnected" | "disabled" | "connection_expired"; }; /** Receiver contact is separate from an authenticated, independent worker reply. */ export function MuseConnectionChecks({ state }: { state: MuseConnectionState }) { const milestones = [ { title: "Paired with Paperclip", done: state.paired, description: "Paperclip authorized the scoped Muse agent connection." }, { title: "Receiver detected", done: state.receiverDetected, description: "Paperclip observed a public receiver check. Only an authenticated reply confirms Muse can work." }, { title: "Background reply verified", done: state.backgroundReplyVerified, description: "Muse replied to an independent background test." }, ]; const checksPassed = milestones.every(item => item.done); const message = state.problem === "offline" ? "Connection updates paused. Refresh to check the latest evidence." : state.problem === "disconnected" ? "Disconnected. These are the last observed connection checks. Detector cleanup and worker stop evidence remain separate." : state.problem === "connection_expired" ? "This Muse connection expired. Reconnect Muse with a fresh setup prompt. Previous checks do not restore access." : state.problem === "disabled" ? "Muse is disabled. These are the last observed connection checks; new work cannot start." : state.problem === "prompt_unavailable" ? "This setup prompt was replaced or expired. Create a fresh prompt to continue." : state.problem === "agent_unavailable" ? "Connection checks passed. Resolve this agent’s setup or approval blocker before assigning tasks." : state.problem === "no_recent_response" ? "No recent response. Open Muse to check the current conversation and hostname permission, then test again. Silence does not identify a permission problem." : state.testing ? "Waiting for Muse to reply to the current background test." : checksPassed && state.ready ? "Muse is ready for tasks. All connection checks and agent setup passed." : checksPassed ? "All connection checks passed. Paperclip is finishing agent setup." : !state.paired ? "Watching for Muse to pair. Copy the setup prompt into your current Muse conversation." : !state.receiverDetected ? "Muse is paired. Waiting for the first persisted receiver contact." : "Receiver detected. Waiting for Muse to reply to the background test."; return
    {milestones.map(item =>
  1. {item.done ? : }

    {item.title}{item.done ? ": complete" : ": waiting"}

    {item.done &&

    {item.description}

    }
  2. )}

{message}

; } /** Shared presentation for the invitation flow. The caller owns invitations and watching. */ export function ExternalAgentInviteContent({ preset, prompt, companyName, connection, onSelect, onBack, onClose, onCopied, onRetry, onNewPrompt, dotDisabledReason, grokDisabledReason, busy = false, error, approvalHref, museEnabled = false, museConnection, museDraft, onMuseDraftChange, onMuseContinue, }: { museEnabled?: boolean; museConnection?: MuseConnectionState; museDraft?: MuseInvitationDraft; onMuseDraftChange?: (draft: MuseInvitationDraft) => void; onMuseContinue?: () => void; dotDisabledReason?: string; grokDisabledReason?: string; busy?: boolean; error?: string; approvalHref?: string; preset: ExternalAgentPreset | null; prompt: string; companyName: string; connection: DotConnectionState; onSelect: (preset: ExternalAgentPreset) => void; onBack: () => void; onClose: () => void; onCopied: () => void; onRetry: () => void; onNewPrompt: () => void; }) { const detailsId = useId(); const muse = preset === "muse"; const museDetails = muse && !!museDraft; const museAwaitingInvitation = muse && !museDetails && !museConnection && !approvalHref; const museReady = muse && !!museConnection?.ready && museConnection.paired && museConnection.receiverDetected && museConnection.backgroundReplyVerified && !museConnection.problem && !museConnection.testing; const provider = presets.find(item => item.id === preset); const dot = preset === "dot"; const ready = museReady || (dot && connection.phase === "ready" && !connection.problem); const connecting = dot && connection.phase !== "waiting"; const progressLabel = connection.problem === "agent_unavailable" ? "Agent unavailable" : connection.problem === "offline" ? "Updates paused" : connection.problem === "event_timeout" ? "Needs attention" : connection.phase === "finishing" ? "Finishing setup…" : connection.phase === "connected" ? "Connecting…" : "Confirming connection…"; return <>
{muse && } {provider && }
{!provider ? "Invite an external agent" : muse ? ready ? "Muse is connected" : museDetails || museAwaitingInvitation ? "Invite your Muse" : "Connect your Muse" : dot ? ready ? "Your Dot is connected" : "Connect your Dot" : preset === "hermes" ? "Invite your Hermes agent" : "Invite your agent"} {!provider ? `Bring an agent you already use into ${companyName}.` : muse ? museDetails ? `Give your personal Muse a name and role in ${companyName}.` : museAwaitingInvitation ? "Muse requires an authenticated Paperclip instance with a public HTTPS URL and a company operator account." : ready ? `Muse can receive assignments and work with ${companyName}.` : !prompt && !museConnection?.paired ? "We’re checking whether this instance can prepare Muse setup." : "Paste the setup prompt into your current Muse conversation. Complete Connect Paperclip if Muse asks, then approve this Paperclip hostname. Muse keeps the connection credential in its secure vault. The hostname permission applies to future requests." : ready ? `Your Dot can now receive assignments and work with ${companyName}.` : connection.problem === "agent_unavailable" ? "Your Dot is connected. This agent must be available in Paperclip before it can receive assignments." : connection.phase === "finishing" ? "Your Dot has connected and confirmed task updates. Paperclip is preparing it for assignments." : connecting ? "Your Dot has connected. We’re checking that task updates can travel both ways." : dot ? "Copy the setup prompt and send it to your Dot in ChatGPT. Your Dot will connect itself; we’ll watch for it here." : `Copy the invitation prompt and send it to your ${preset === "hermes" ? "Hermes " : ""}agent. Approve its join request in Paperclip when it’s ready.`}
{error &&

{error}

{!museAwaitingInvitation && }
} {!provider ? <> {dotDisabledReason &&

{dotDisabledReason}

}{grokDisabledReason && grokDisabledReason !== dotDisabledReason &&

{grokDisabledReason}

} : approvalHref ?

An organization admin needs to approve this agent before {muse ? "Muse" : "Dot"} can connect. This page will update after approval.

: museAwaitingInvitation ? busy ?

Loading Muse invitation…

: null : muse && busy && !museDetails && !prompt && !museConnection?.paired ?

Loading Muse setup…

: museDetails ?
{ event.preventDefault(); if (museDraft.name.trim() && !busy) onMuseContinue?.(); }}>
onMuseDraftChange?.({ ...museDraft, name: event.target.value })} />

Muse uses its own approved tools. Provider usage and cost are unavailable to Paperclip.

: muse && museConnection ? <> {museConnection.problem === "no_recent_response" && } {museConnection.problem === "offline" && } {!museConnection.paired && Open Muse}

Receiver contact is persisted in batches and may lag. Setup never creates a task. Provider usage and cost are unavailable.

: busy && !prompt && connection.phase === "waiting" ?

Preparing your invitation…

: dot ? <>
{connection.phase === "waiting" &&

Dot uses your OpenAI account. Provider usage and cost aren’t reported to Paperclip.

}
{connection.problem === "event_timeout" && } {connection.problem === "offline" && } :

The invitation includes everything your agent needs to join {companyName}. You can review its request before granting access.

}
{provider && (approvalHref ? : museDetails ? : ready ? : museAwaitingInvitation ? : muse ? museConnection?.problem === "disconnected" || museConnection?.problem === "connection_expired" ? : museConnection?.problem === "prompt_unavailable" ? : !museConnection?.paired && prompt ? }} description="Send this whole prompt to your current Muse conversation." align="end" className="min-w-0 shrink" onCopied={onCopied} /> : busy ? : : connecting ? : dot && connection.problem === "prompt_unavailable" ? : !prompt || busy ? : )}
; }