feat(runtime): add local codex daemon pairing

This commit is contained in:
Jiayuan Zhang 2026-03-24 12:03:14 +08:00
parent c6960d39b9
commit cdfa63af15
36 changed files with 2579 additions and 309 deletions

View file

@ -6,6 +6,7 @@ import userEvent from "@testing-library/user-event";
vi.mock("next/navigation", () => ({
useRouter: () => ({ push: vi.fn() }),
usePathname: () => "/login",
useSearchParams: () => new URLSearchParams(),
}));
// Mock auth-context
@ -68,7 +69,7 @@ describe("LoginPage", () => {
await user.click(screen.getByRole("button", { name: "Sign in" }));
await waitFor(() => {
expect(mockLogin).toHaveBeenCalledWith("test@multica.ai", "Test User");
expect(mockLogin).toHaveBeenCalledWith("test@multica.ai", "Test User", undefined);
});
});
@ -81,7 +82,7 @@ describe("LoginPage", () => {
await user.click(screen.getByRole("button", { name: "Sign in" }));
await waitFor(() => {
expect(mockLogin).toHaveBeenCalledWith("test@multica.ai", undefined);
expect(mockLogin).toHaveBeenCalledWith("test@multica.ai", undefined, undefined);
});
});

View file

@ -1,10 +1,12 @@
"use client";
import { useState } from "react";
import { useSearchParams } from "next/navigation";
import { useAuth } from "../../../lib/auth-context";
export default function LoginPage() {
const { login, isLoading } = useAuth();
const searchParams = useSearchParams();
const [email, setEmail] = useState("");
const [name, setName] = useState("");
const [error, setError] = useState("");
@ -19,7 +21,7 @@ export default function LoginPage() {
setError("");
setSubmitting(true);
try {
await login(email, name || undefined);
await login(email, name || undefined, searchParams.get("next") || undefined);
} catch (err) {
setError("Login failed. Make sure the server is running.");
setSubmitting(false);

View file

@ -72,50 +72,8 @@ function generateId(): string {
return `${Date.now()}-${Math.random().toString(36).slice(2, 9)}`;
}
// ---------------------------------------------------------------------------
// Mock Runtime Devices (will be replaced with real daemon registration API)
// ---------------------------------------------------------------------------
const MOCK_RUNTIME_DEVICES: RuntimeDevice[] = [
{
id: "runtime-cloud",
name: "Multica Agent",
runtime_mode: "cloud",
status: "online",
device_info: "Cloud",
},
{
id: "runtime-macbook",
name: "Jiayuan's MacBook Pro",
runtime_mode: "local",
status: "online",
device_info: "macOS 15.4 · Claude Code v1.2",
},
{
id: "runtime-linux",
name: "Dev Server (gpu-01)",
runtime_mode: "local",
status: "online",
device_info: "Ubuntu 24.04 · Codex v0.8",
},
{
id: "runtime-ci",
name: "CI Runner",
runtime_mode: "local",
status: "offline",
device_info: "Linux · GitHub Actions",
},
];
function getRuntimeDevice(agent: Agent): RuntimeDevice | undefined {
const runtimeId = agent.runtime_config?.runtime_id as string | undefined;
if (runtimeId) {
return MOCK_RUNTIME_DEVICES.find((d) => d.id === runtimeId);
}
if (agent.runtime_mode === "cloud") {
return MOCK_RUNTIME_DEVICES.find((d) => d.runtime_mode === "cloud");
}
return undefined;
function getRuntimeDevice(agent: Agent, runtimes: RuntimeDevice[]): RuntimeDevice | undefined {
return runtimes.find((runtime) => runtime.id === agent.runtime_id);
}
// ---------------------------------------------------------------------------
@ -123,32 +81,36 @@ function getRuntimeDevice(agent: Agent): RuntimeDevice | undefined {
// ---------------------------------------------------------------------------
function CreateAgentDialog({
runtimes,
onClose,
onCreate,
}: {
runtimes: RuntimeDevice[];
onClose: () => void;
onCreate: (data: CreateAgentRequest) => Promise<void>;
}) {
const [name, setName] = useState("");
const [description, setDescription] = useState("");
const [selectedRuntimeId, setSelectedRuntimeId] = useState(MOCK_RUNTIME_DEVICES[0]!.id);
const [selectedRuntimeId, setSelectedRuntimeId] = useState(runtimes[0]?.id ?? "");
const [creating, setCreating] = useState(false);
const [runtimeOpen, setRuntimeOpen] = useState(false);
const selectedRuntime = MOCK_RUNTIME_DEVICES.find((d) => d.id === selectedRuntimeId)!;
useEffect(() => {
if (!selectedRuntimeId && runtimes[0]) {
setSelectedRuntimeId(runtimes[0].id);
}
}, [runtimes, selectedRuntimeId]);
const selectedRuntime = runtimes.find((d) => d.id === selectedRuntimeId) ?? null;
const handleSubmit = async () => {
if (!name.trim()) return;
if (!name.trim() || !selectedRuntime) return;
setCreating(true);
try {
await onCreate({
name: name.trim(),
description: description.trim(),
runtime_mode: selectedRuntime.runtime_mode,
runtime_config: {
runtime_id: selectedRuntime.id,
runtime_name: selectedRuntime.name,
},
runtime_id: selectedRuntime.id,
triggers: [{ id: generateId(), type: "on_assign", enabled: true, config: {} }],
});
onClose();
@ -205,23 +167,28 @@ function CreateAgentDialog({
<button
type="button"
onClick={() => setRuntimeOpen(!runtimeOpen)}
disabled={runtimes.length === 0}
className="flex w-full items-center gap-3 rounded-md border bg-background px-3 py-2.5 text-left text-sm transition-colors hover:bg-accent/50 focus:outline-none focus:ring-2 focus:ring-ring"
>
{selectedRuntime.runtime_mode === "cloud" ? (
{selectedRuntime?.runtime_mode === "cloud" ? (
<Cloud className="h-4 w-4 shrink-0 text-muted-foreground" />
) : (
<Monitor className="h-4 w-4 shrink-0 text-muted-foreground" />
)}
<div className="min-w-0 flex-1">
<div className="flex items-center gap-2">
<span className="truncate font-medium">{selectedRuntime.name}</span>
{selectedRuntime.runtime_mode === "cloud" && (
<span className="truncate font-medium">
{selectedRuntime?.name ?? "No runtime available"}
</span>
{selectedRuntime?.runtime_mode === "cloud" && (
<span className="shrink-0 rounded bg-blue-500/10 px-1.5 py-0.5 text-[10px] font-medium text-blue-600">
Cloud
</span>
)}
</div>
<div className="text-xs text-muted-foreground">{selectedRuntime.device_info}</div>
<div className="text-xs text-muted-foreground">
{selectedRuntime?.device_info ?? "Register a runtime before creating an agent"}
</div>
</div>
<ChevronDown className={`h-4 w-4 shrink-0 text-muted-foreground transition-transform ${runtimeOpen ? "rotate-180" : ""}`} />
</button>
@ -230,7 +197,7 @@ function CreateAgentDialog({
<>
<div className="fixed inset-0 z-40" onClick={() => setRuntimeOpen(false)} />
<div className="absolute left-0 right-0 top-full z-50 mt-1 max-h-60 overflow-y-auto rounded-lg border bg-popover p-1 shadow-md">
{MOCK_RUNTIME_DEVICES.map((device) => (
{runtimes.map((device) => (
<button
key={device.id}
onClick={() => {
@ -280,7 +247,7 @@ function CreateAgentDialog({
</button>
<button
onClick={handleSubmit}
disabled={creating || !name.trim()}
disabled={creating || !name.trim() || !selectedRuntime}
className="rounded-md bg-primary px-3 py-1.5 text-sm font-medium text-primary-foreground hover:bg-primary/90 disabled:opacity-50"
>
{creating ? "Creating..." : "Create"}
@ -899,15 +866,17 @@ const detailTabs: { id: DetailTab; label: string; icon: typeof FileText }[] = [
function AgentDetail({
agent,
runtimes,
onUpdate,
onDelete,
}: {
agent: Agent;
runtimes: RuntimeDevice[];
onUpdate: (id: string, data: Partial<Agent>) => Promise<void>;
onDelete: (id: string) => Promise<void>;
}) {
const st = statusConfig[agent.status];
const runtimeDevice = getRuntimeDevice(agent);
const runtimeDevice = getRuntimeDevice(agent, runtimes);
const [activeTab, setActiveTab] = useState<DetailTab>("skills");
const [showMenu, setShowMenu] = useState(false);
const [confirmDelete, setConfirmDelete] = useState(false);
@ -1055,9 +1024,21 @@ function AgentDetail({
// ---------------------------------------------------------------------------
export default function AgentsPage() {
const { agents, refreshAgents, isLoading } = useAuth();
const { agents, refreshAgents, workspace, isLoading } = useAuth();
const [selectedId, setSelectedId] = useState<string>("");
const [showCreate, setShowCreate] = useState(false);
const [runtimes, setRuntimes] = useState<RuntimeDevice[]>([]);
useEffect(() => {
if (!workspace) {
setRuntimes([]);
return;
}
api
.listRuntimes({ workspace_id: workspace.id })
.then(setRuntimes)
.catch(() => setRuntimes([]));
}, [workspace]);
// Select first agent on initial load
useEffect(() => {
@ -1147,6 +1128,7 @@ export default function AgentsPage() {
{selected ? (
<AgentDetail
agent={selected}
runtimes={runtimes}
onUpdate={handleUpdate}
onDelete={handleDelete}
/>
@ -1167,6 +1149,7 @@ export default function AgentsPage() {
{showCreate && (
<CreateAgentDialog
runtimes={runtimes}
onClose={() => setShowCreate(false)}
onCreate={handleCreate}
/>

View file

@ -260,7 +260,7 @@ export default function SettingsPage() {
Name
</label>
<input
type="text"
type="search"
value={profileName}
onChange={(e) => setProfileName(e.target.value)}
className="mt-1 w-full rounded-md border bg-background px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-ring"
@ -291,7 +291,7 @@ export default function SettingsPage() {
className="flex items-center gap-1.5 rounded-md bg-primary px-3 py-1.5 text-xs font-medium text-primary-foreground hover:bg-primary/90 disabled:opacity-50"
>
<Save className="h-3 w-3" />
{profileSaving ? "Saving..." : "Save"}
{profileSaving ? "Updating..." : "Update Profile"}
</button>
</div>
</div>

View file

@ -0,0 +1,155 @@
"use client";
import Link from "next/link";
import { useEffect, useMemo, useState } from "react";
import { useSearchParams } from "next/navigation";
import type { DaemonPairingSession } from "@multica/types";
import { api } from "../../../lib/api";
import { useAuth } from "../../../lib/auth-context";
function formatExpiresAt(value: string) {
return new Date(value).toLocaleString("en-US", {
month: "short",
day: "numeric",
hour: "numeric",
minute: "2-digit",
});
}
export default function LocalDaemonPairPage() {
const searchParams = useSearchParams();
const token = searchParams.get("token") ?? "";
const { user, workspaces, workspace, isLoading } = useAuth();
const [session, setSession] = useState<DaemonPairingSession | null>(null);
const [selectedWorkspaceId, setSelectedWorkspaceId] = useState("");
const [loading, setLoading] = useState(true);
const [submitting, setSubmitting] = useState(false);
const [error, setError] = useState("");
const nextLoginURL = useMemo(() => {
const next = `/pair/local?token=${encodeURIComponent(token)}`;
return `/login?next=${encodeURIComponent(next)}`;
}, [token]);
useEffect(() => {
if (!token) {
setError("Missing pairing token.");
setLoading(false);
return;
}
setLoading(true);
api.getDaemonPairingSession(token)
.then((value) => {
setSession(value);
setSelectedWorkspaceId(value.workspace_id || workspace?.id || workspaces[0]?.id || "");
})
.catch((err) => setError(err instanceof Error ? err.message : "Failed to load pairing session."))
.finally(() => setLoading(false));
}, [token, workspace?.id, workspaces]);
const approve = async () => {
if (!token || !selectedWorkspaceId) return;
setSubmitting(true);
setError("");
try {
const approved = await api.approveDaemonPairingSession(token, {
workspace_id: selectedWorkspaceId,
});
setSession(approved);
} catch (err) {
setError(err instanceof Error ? err.message : "Failed to approve pairing session.");
} finally {
setSubmitting(false);
}
};
return (
<div className="flex min-h-screen items-center justify-center bg-canvas px-6 py-12">
<div className="w-full max-w-xl rounded-2xl border bg-background p-8 shadow-sm">
<div>
<h1 className="text-2xl font-semibold">Connect Local Codex Runtime</h1>
<p className="mt-2 text-sm text-muted-foreground">
Approve this pairing request to register your local Codex runtime with a workspace.
</p>
</div>
{loading || isLoading ? (
<div className="mt-8 text-sm text-muted-foreground">Loading pairing session...</div>
) : error ? (
<div className="mt-8 rounded-lg border border-red-200 bg-red-50 px-4 py-3 text-sm text-red-700">
{error}
</div>
) : session ? (
<>
<div className="mt-6 rounded-xl border bg-muted/30 p-4">
<div className="text-sm font-medium">{session.runtime_name}</div>
<div className="mt-1 text-sm text-muted-foreground">
{session.device_name}
{session.runtime_version ? ` · ${session.runtime_version}` : ""}
</div>
<div className="mt-1 text-xs uppercase tracking-wide text-muted-foreground">
{session.runtime_type}
</div>
<div className="mt-3 text-xs text-muted-foreground">
Expires {formatExpiresAt(session.expires_at)}
</div>
</div>
{!user ? (
<div className="mt-6 space-y-3">
<p className="text-sm text-muted-foreground">
Sign in first, then choose which workspace should own this local runtime.
</p>
<Link
href={nextLoginURL}
className="inline-flex rounded-md bg-primary px-4 py-2 text-sm font-medium text-primary-foreground hover:bg-primary/90"
>
Sign in to continue
</Link>
</div>
) : session.status === "approved" || session.status === "claimed" ? (
<div className="mt-6 rounded-xl border border-emerald-200 bg-emerald-50 px-4 py-3 text-sm text-emerald-800">
This runtime is linked to a workspace. Return to the daemon window to finish setup.
</div>
) : session.status === "expired" ? (
<div className="mt-6 rounded-xl border border-amber-200 bg-amber-50 px-4 py-3 text-sm text-amber-800">
This pairing link expired. Restart the daemon to generate a new link.
</div>
) : workspaces.length === 0 ? (
<div className="mt-6 rounded-xl border px-4 py-3 text-sm text-muted-foreground">
You do not have a workspace yet. Create one first, then reopen this pairing link.
</div>
) : (
<div className="mt-6 space-y-4">
<div>
<label className="mb-2 block text-sm font-medium">Workspace</label>
<select
value={selectedWorkspaceId}
onChange={(e) => setSelectedWorkspaceId(e.target.value)}
className="w-full rounded-md border bg-background px-3 py-2 text-sm"
>
{workspaces.map((item) => (
<option key={item.id} value={item.id}>
{item.name}
</option>
))}
</select>
</div>
<button
type="button"
onClick={approve}
disabled={submitting || !selectedWorkspaceId}
className="inline-flex rounded-md bg-primary px-4 py-2 text-sm font-medium text-primary-foreground hover:bg-primary/90 disabled:opacity-50"
>
{submitting ? "Registering..." : "Register runtime"}
</button>
</div>
)}
</>
) : null}
</div>
</div>
);
}

View file

@ -76,6 +76,7 @@ const mockAgents: Agent[] = [
{
id: "agent-1",
workspace_id: "ws-1",
runtime_id: "runtime-1",
name: "Claude",
description: "",
avatar_url: null,

View file

@ -19,7 +19,7 @@ interface AuthContextValue {
members: MemberWithUser[];
agents: Agent[];
isLoading: boolean;
login: (email: string, name?: string) => Promise<void>;
login: (email: string, name?: string, redirectTo?: string) => Promise<void>;
logout: () => void;
switchWorkspace: (workspaceId: string) => Promise<void>;
createWorkspace: (data: { name: string; slug: string; description?: string }) => Promise<Workspace>;
@ -121,7 +121,7 @@ export function AuthProvider({ children }: { children: ReactNode }) {
})();
}, [hydrateWorkspace]);
const login = useCallback(async (email: string, name?: string) => {
const login = useCallback(async (email: string, name?: string, redirectTo?: string) => {
const { token, user: u } = await api.login(email, name);
api.setToken(token);
localStorage.setItem("multica_token", token);
@ -130,7 +130,7 @@ export function AuthProvider({ children }: { children: ReactNode }) {
const wsList = await api.listWorkspaces();
await hydrateWorkspace(wsList);
router.push("/issues");
router.push(redirectTo || "/issues");
}, [hydrateWorkspace, router]);
const logout = useCallback(() => {

View file

@ -43,6 +43,7 @@ export const mockAgents: Agent[] = [
{
id: "agent-1",
workspace_id: "ws-1",
runtime_id: "runtime-1",
name: "Claude Agent",
description: "",
avatar_url: null,