Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
"use client";
import {
useCallback,
useEffect,
useRef,
useState,
type ReactNode,
} from "react";
import { AnimatePresence, motion } from "motion/react";
import { useReducedMotion } from "@multica/core/appearance";
import { Check, ChevronRight, Terminal } from "@multica/ui/icons";
import { CopyCheckIcon } from "@multica/ui/components/common/copy-check-icon";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import { useAuthStore } from "@multica/core/auth";
import { useWorkspaceId } from "@multica/core/hooks";
import { runtimeKeys, runtimeListOptions } from "@multica/core/runtimes/queries";
import { useDaemonSetupCommands } from "@multica/core/runtimes";
import { useWSEvent, useWSReconnect } from "@multica/core/realtime";
import { paths, useWorkspaceSlug } from "@multica/core/paths";
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from "@multica/ui/components/ui/dialog";
import { Button } from "@multica/ui/components/ui/button";
import { TooltipHint } from "@multica/ui/components/common/tooltip-hint";
import { CODE_LIGATURE_CLASS } from "@multica/ui/lib/code-style";
import { copyText } from "@multica/ui/lib/clipboard";
import {
UI_EASE_OUT,
UI_MOTION_DURATION,
} from "@multica/ui/lib/motion";
import { cn } from "@multica/ui/lib/utils";
import { CliInstallCommand } from "../../common/cli-install-command";
import { DaemonSetupNotice } from "../../common/daemon-setup-notice";
import { useNavigation } from "../../navigation";
import { useT } from "../../i18n";
type Step = "instructions" | "success";
export function ConnectRemoteDialog({ onClose }: { onClose: () => void }) {
const wsId = useWorkspaceId();
const currentUserId = useAuthStore((state) => state.user?.id);
return (
<WorkspaceConnectDialog
key={`${wsId}:${currentUserId ?? ""}`}
wsId={wsId}
currentUserId={currentUserId}
onClose={onClose}
/>
);
}
function WorkspaceConnectDialog({ wsId, currentUserId, onClose }: {
wsId: string;
currentUserId: string | undefined;
onClose: () => void;
}) {
const [step, setStep] = useState<Step>("instructions");
const slug = useWorkspaceSlug();
const qc = useQueryClient();
const navigation = useNavigation();
const shouldReduceMotion = useReducedMotion();
const newRuntimeIdRef = useRef<string | null>(null);
const initialDaemonIds = useRef<Set<string> | null>(null);
const pendingInitialRefresh = useRef(false);
const { data: runtimes, isSuccess, isFetchedAfterMount, isFetching } = useQuery({
...runtimeListOptions(wsId, "me", slug ?? undefined),
enabled: !!currentUserId && step === "instructions",
refetchOnMount: "always",
});
// Registration, configuration updates and offline sweeps share this event.
// Only the refreshed runtime list can confirm a newly connected computer.
const handleDaemonRegister = useCallback(() => {
if (step !== "instructions") return;
// Invalidating an uncached in-flight query only joins its stale snapshot.
if (!initialDaemonIds.current && qc.isFetching({ queryKey: runtimeKeys.listMine(wsId), exact: true })) {
pendingInitialRefresh.current = true;
return;
}
return qc.invalidateQueries({ queryKey: runtimeKeys.all(wsId) });
}, [step, qc, wsId]);
useWSEvent("daemon:register", handleDaemonRegister);
useWSReconnect(handleDaemonRegister);
useEffect(() => {
if (
step !== "instructions" ||
!currentUserId ||
!isSuccess ||
!isFetchedAfterMount ||
isFetching ||
!runtimes
) return;
// A fresh initial response avoids treating an old, uncached machine as new.
const knownDaemonIds = initialDaemonIds.current;
if (!knownDaemonIds) {
initialDaemonIds.current = new Set(
runtimes.flatMap((runtime) => runtime.daemon_id ? [runtime.daemon_id] : []),
);
return;
}
const runtime = runtimes.find((runtime) =>
runtime.workspace_id === wsId &&
runtime.owner_id === currentUserId &&
runtime.runtime_mode === "local" &&
runtime.status === "online" &&
runtime.daemon_id &&
!knownDaemonIds.has(runtime.daemon_id) &&
runtime.metadata.pending_custom_runtime !== true &&
runtime.metadata.runtime_profile_registration_error !== true,
);
if (!runtime) return;
newRuntimeIdRef.current = runtime.id;
setStep("success");
}, [step, currentUserId, isSuccess, isFetchedAfterMount, isFetching, runtimes, wsId]);
useEffect(() => {
if (step !== "instructions" || isFetching || !pendingInitialRefresh.current) return;
// Establish the initial baseline above before fetching queued notifications.
pendingInitialRefresh.current = false;
void qc.invalidateQueries({ queryKey: runtimeKeys.all(wsId) });
}, [step, isFetching, qc, wsId]);
const handleGoToAgents = () => {
onClose();
if (slug) {
navigation.push(paths.workspace(slug).agents());
}
};
const handleGoToRuntime = () => {
onClose();
if (slug && newRuntimeIdRef.current) {
navigation.push(
paths.workspace(slug).runtimeDetail(newRuntimeIdRef.current),
);
}
};
return (
<Dialog open onOpenChange={(v) => !v && onClose()}>
<DialogContent className="flex max-h-[85%] flex-col gap-0 p-0 sm:max-w-lg">
<AnimatePresence mode="wait" initial={false}>
<motion.div
key={step}
className="flex min-h-0 flex-1 flex-col"
initial={{
opacity: 0,
transform: shouldReduceMotion
? "translateY(0)"
: "translateY(8px)",
}}
animate={{
opacity: 1,
transform: "translateY(0)",
transition: {
duration: shouldReduceMotion
? UI_MOTION_DURATION.fast
: UI_MOTION_DURATION.standard,
ease: UI_EASE_OUT,
},
}}
exit={{
opacity: 0,
transform: shouldReduceMotion
? "translateY(0)"
: "translateY(-8px)",
transition: {
duration: shouldReduceMotion
? UI_MOTION_DURATION.fast
: UI_MOTION_DURATION.micro,
ease: UI_EASE_OUT,
},
}}
>
{step === "instructions" ? (
<InstructionsStep onClose={onClose} />
) : (
<SuccessStep
onGoToAgents={handleGoToAgents}
onGoToRuntime={
newRuntimeIdRef.current ? handleGoToRuntime : undefined
}
/>
)}
</motion.div>
</AnimatePresence>
</DialogContent>
</Dialog>
);
}
// Copy button + code row — mirrors onboarding/CliInstallInstructions
function CopyButton({ text, ariaLabel }: { text: string; ariaLabel: string }) {
const [copied, setCopied] = useState(false);
useEffect(() => {
if (!copied) return;
const t = setTimeout(() => setCopied(false), 2000);
return () => clearTimeout(t);
}, [copied]);
const handleCopy = () => {
void copyText(text).then((ok) => {
if (ok) setCopied(true);
});
};
return (
<TooltipHint label={ariaLabel}>
<button
type="button"
onClick={handleCopy}
aria-label={ariaLabel}
className="shrink-0 rounded-xs p-1 text-muted-foreground transition-colors hover:bg-accent hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
>
<CopyCheckIcon copied={copied} />
</button>
</TooltipHint>
);
}
function CommandRow({ cmd, copyAria }: { cmd: string; copyAria: string }) {
return (
<div className="flex items-start gap-2 rounded-lg bg-muted px-3 py-2.5 font-mono text-body">
<Terminal
className="mt-0.5 h-3.5 w-3.5 shrink-0 text-muted-foreground"
aria-hidden
/>
<code
className={cn(
"min-w-0 flex-1 break-all whitespace-pre-wrap tabular-nums",
CODE_LIGATURE_CLASS,
)}
>
{cmd}
</code>
<CopyButton text={cmd} ariaLabel={copyAria} />
</div>
);
}
function CommandStep({
n,
label,
children,
}: {
n: number;
label: string;
children: ReactNode;
}) {
return (
<div>
<p className="mb-1.5 text-caption font-medium text-foreground">
{n}. {label}
</p>
{children}
</div>
);
}
// Step 1: Instructions
function InstructionsStep({ onClose }: { onClose: () => void }) {
const { t } = useT("runtimes");
const commands = useDaemonSetupCommands();
return (
<>
<DialogHeader className="px-6 pt-6 pb-2">
<DialogTitle className="text-title-sm text-balance">
{t(($) => $.connect.title)}
</DialogTitle>
<DialogDescription className="text-caption text-balance">
{t(($) => $.connect.description)}
</DialogDescription>
</DialogHeader>
<div className="min-h-0 flex-1 overflow-y-auto px-6 py-4">
<div className="space-y-4">
{/* Step 1 owns the platform switch: the install command differs by
OS, so the user picks instead of us guessing. Step 2's
`multica setup` is platform-independent. */}
<CommandStep n={1} label={t(($) => $.connect.step1_label)}>
<CliInstallCommand
labels={{
group: t(($) => $.connect.platform_group),
macosLinux: t(($) => $.connect.platform_macos_linux),
windows: t(($) => $.connect.platform_windows),
}}
>
{(cmd) => (
<CommandRow
cmd={cmd}
copyAria={t(($) => $.connect.copy_aria)}
/>
)}
</CliInstallCommand>
</CommandStep>
<div>
<CommandStep n={2} label={t(($) => $.connect.step2_label)}>
{commands.status === "ready" ? (
<CommandRow
cmd={commands.setupCmd}
copyAria={t(($) => $.connect.copy_aria)}
/>
) : (
<DaemonSetupNotice status={commands.status} />
)}
</CommandStep>
{commands.status === "ready" && (
<p className="mt-1.5 text-micro leading-[1.55] text-muted-foreground">
{t(($) => $.connect.step2_hint)}
</p>
)}
</div>
{commands.status === "ready" && (
<>
<LiveListening />
<TroubleshootingDetails tokenCmd={commands.tokenCmd} />
</>
)}
</div>
</div>
<DialogFooter className="m-0 rounded-b-xl border-t bg-muted/30 px-6 py-3">
<Button variant="outline" size="sm" onClick={onClose}>
{t(($) => $.connect.cancel)}
</Button>
</DialogFooter>
</>
);
}
function TroubleshootingDetails({ tokenCmd }: { tokenCmd: string }) {
const { t } = useT("runtimes");
return (
<details className="group rounded-lg border border-dashed">
<summary className="flex cursor-pointer list-none items-center gap-1.5 px-3 py-2 text-caption font-medium text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring">
<ChevronRight
className="h-3 w-3 transition-transform group-open:rotate-90"
aria-hidden
/>
{t(($) => $.connect.troubleshooting)}
</summary>
<div className="space-y-2 border-t px-3 pt-2.5 pb-3 text-micro leading-[1.55] text-muted-foreground">
<p>{t(($) => $.connect.trouble_intro)}</p>
<CommandStep n={2} label={t(($) => $.connect.step2_label)}>
<CommandRow
cmd={tokenCmd}
copyAria={t(($) => $.connect.copy_aria)}
/>
</CommandStep>
<p>
{t(($) => $.connect.trouble_token_hint_prefix)}
<span className="font-medium text-foreground">
{t(($) => $.connect.trouble_token_hint_destination)}
</span>
{t(($) => $.connect.trouble_token_hint_suffix)}
</p>
<ul className="space-y-1">
<li className="flex items-center gap-1.5">
<span>{t(($) => $.connect.trouble_check_status)}</span>
{/* CLI command — literal shell string, not i18n content. */}
<code
className={cn(
"rounded-xs bg-muted px-1.5 py-0.5 font-mono text-micro text-foreground",
CODE_LIGATURE_CLASS,
)}
>
{"multica daemon status"}
</code>
</li>
<li className="flex items-center gap-1.5">
<span>{t(($) => $.connect.trouble_view_logs)}</span>
{/* CLI command — literal shell string, not i18n content. */}
<code
className={cn(
"rounded-xs bg-muted px-1.5 py-0.5 font-mono text-micro text-foreground",
CODE_LIGATURE_CLASS,
)}
>
{"multica daemon logs -f"}
</code>
</li>
</ul>
</div>
</details>
);
}
// Live-listening indicator
function LiveListening() {
const { t } = useT("runtimes");
return (
<div
className="flex items-center gap-2.5 rounded-lg border bg-muted/40 px-3 py-2.5 text-caption"
role="status"
aria-live="polite"
>
<span className="relative inline-flex shrink-0" aria-hidden>
<span className="absolute inline-flex h-2 w-2 animate-ping rounded-full bg-success opacity-60 motion-reduce:hidden" />
<span className="relative inline-flex h-2 w-2 rounded-full bg-success" />
</span>
<span className="font-medium text-foreground">
{t(($) => $.connect.live_listening)}
</span>
</div>
);
}
// Step 2: Success
function SuccessStep({
onGoToAgents,
onGoToRuntime,
}: {
onGoToAgents: () => void;
onGoToRuntime?: () => void;
}) {
const { t } = useT("runtimes");
return (
<>
<DialogHeader className="px-6 pt-6 pb-2">
<DialogTitle className="text-title-sm text-balance">
{t(($) => $.connect.success_title)}
</DialogTitle>
<DialogDescription className="text-caption text-balance">
{t(($) => $.connect.success_description)}
</DialogDescription>
</DialogHeader>
<div className="flex flex-col items-center gap-3 px-6 py-8">
<div
className="flex h-12 w-12 items-center justify-center rounded-full bg-success/10"
aria-hidden
>
<Check className="h-6 w-6 text-success" />
</div>
</div>
<DialogFooter className="m-0 rounded-b-xl border-t bg-muted/30 px-6 py-3">
{onGoToRuntime && (
<Button variant="ghost" size="sm" onClick={onGoToRuntime}>
{t(($) => $.connect.view_runtime)}
</Button>
)}
<Button size="sm" onClick={onGoToAgents}>
{t(($) => $.connect.create_agent)}
<ChevronRight className="h-3.5 w-3.5" aria-hidden />
</Button>
</DialogFooter>
</>
);
}