Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
feat(web): add ChatPage with DevicePairing and ChatView
Naiyuan Qing7cb9788bed2f
diff --git a/apps/web/app/app-header.tsx b/apps/web/app/header.tsxsimilarity index 62%rename from apps/web/app/app-header.tsxrename to apps/web/app/header.tsxindex 5dd8fbcad2..dee519d6fd 100644--- a/apps/web/app/app-header.tsx+++ b/apps/web/app/header.tsx@@ -1,13 +1,10 @@"use client";-import { Button } from "@multica/ui/components/ui/button";import { ThemeToggle } from "./theme-toggle";-export function AppHeader({ children }: { children: React.ReactNode }) {+export function Header() {return (- <>- <header>- <div className="flex items-center justify-between px-4 py-2 max-w-4xl mx-auto">+ <header className="container flex justify-between items-center p-2"><div className="flex items-center gap-2.5"><img src="/logo.svg" alt="Multica" className="size-6 rounded-md" /><span className="text-sm tracking-wide font-[family-name:var(--font-brand)]">@@ -17,9 +14,6 @@ export function AppHeader({ children }: { children: React.ReactNode }) {<div className="flex items-center gap-1"><ThemeToggle /></div>- </div></header>- {children}- </>);}diff --git a/apps/web/app/layout.tsx b/apps/web/app/layout.tsxindex 6317127e20..60c1655a43 100644--- a/apps/web/app/layout.tsx+++ b/apps/web/app/layout.tsx@@ -2,7 +2,6 @@ import type { Metadata } from "next";import { Geist, Geist_Mono, Inter, Playfair_Display } from "next/font/google";import "@multica/ui/globals.css";import { ThemeProvider } from "@multica/ui/components/theme-provider";-import { AppHeader } from "./app-header";import { Toaster } from "@multica/ui/components/ui/sonner";import { ServiceWorkerRegister } from "./sw-register";@@ -53,9 +52,7 @@ export default function RootLayout({enableSystemdisableTransitionOnChange>- <AppHeader>- <div className="flex-1 overflow-hidden">{children}</div>- </AppHeader>+ <div className="h-dvh overflow-hidden">{children}</div></ThemeProvider><Toaster /><ServiceWorkerRegister />diff --git a/apps/web/app/page.tsx b/apps/web/app/page.tsxindex 74c6c4a782..50d9c19344 100644--- a/apps/web/app/page.tsx+++ b/apps/web/app/page.tsx@@ -1,5 +1,5 @@-import { Chat } from "@multica/ui/components/chat";+import ChatPage from "@/components/pages/chat-page";export default function Page() {- return <Chat />;+ return <ChatPage />;}diff --git a/apps/web/components/device-pairing.tsx b/apps/web/components/device-pairing.tsxnew file mode 100644index 0000000000..278665ed25--- /dev/null+++ b/apps/web/components/device-pairing.tsx@@ -0,0 +1,299 @@+"use client";++import { useState, useCallback, useRef, useEffect } from "react";+import { Button } from "@multica/ui/components/ui/button";+import { Textarea } from "@multica/ui/components/ui/textarea";+import { Loading } from "@multica/ui/components/ui/loading";+import { useIsMobile } from "@multica/ui/hooks/use-mobile";+import { HugeiconsIcon } from "@hugeicons/react";+import {+ Camera01Icon,+ TextIcon,+ CheckmarkCircle02Icon,+ Alert02Icon,+} from "@hugeicons/core-free-icons";+import { QrScannerView } from "@multica/ui/components/qr-scanner-view";+import { parseConnectionCode } from "@multica/store";+import type { ConnectionIdentity } from "@/hooks/use-gateway-connection";++export interface DevicePairingProps {+ connectionState: string;+ lastError: string | null;+ onConnect: (identity: ConnectionIdentity, token: string) => void;+ onCancel: () => void;+}++type Mode = "scan" | "paste";+type PasteState = "idle" | "success" | "error";++/** Shown while connecting to Gateway or waiting for Owner approval */+function ConnectionStatus({+ connectionState,+ fullscreen,+ onCancel,+}: {+ connectionState: string;+ fullscreen?: boolean;+ onCancel: () => void;+}) {+ const isVerifying = connectionState === "verifying";++ const wrapper = fullscreen+ ? "fixed inset-0 z-50 bg-background flex flex-col items-center justify-center gap-5 px-6"+ : "flex flex-col items-center justify-center h-full gap-5 px-4";++ return (+ <div className={wrapper}>+ <Loading className="text-muted-foreground text-sm" />+ <div className="text-center space-y-1.5">+ <p className="text-base font-medium">+ {isVerifying ? "Waiting for approval" : "Connecting..."}+ </p>+ <p className="text-xs text-muted-foreground max-w-[260px]">+ {isVerifying+ ? "The device owner needs to approve this connection on their computer"+ : "Establishing connection to the agent"}+ </p>+ </div>+ <Button+ variant="ghost"+ size="sm"+ className="text-xs text-muted-foreground"+ onClick={onCancel}+ >+ Cancel+ </Button>+ </div>+ );+}++/** Shown when Owner rejects the connection, auto-dismisses after 2s */+function RejectedStatus({+ fullscreen,+ onDismiss,+}: {+ fullscreen?: boolean;+ onDismiss: () => void;+}) {+ useEffect(() => {+ const timer = setTimeout(onDismiss, 2000);+ return () => clearTimeout(timer);+ }, [onDismiss]);++ const wrapper = fullscreen+ ? "fixed inset-0 z-50 bg-background flex flex-col items-center justify-center gap-5 px-6"+ : "flex flex-col items-center justify-center h-full gap-5 px-4";++ return (+ <div className={wrapper}>+ <HugeiconsIcon+ icon={Alert02Icon}+ className="size-14 text-destructive animate-in zoom-in duration-300"+ />+ <div className="text-center space-y-1.5">+ <p className="text-base font-medium">Connection rejected</p>+ <p className="text-xs text-muted-foreground max-w-[260px]">+ The device owner declined this connection+ </p>+ </div>+ </div>+ );+}++export function DevicePairing({+ connectionState,+ lastError,+ onConnect,+ onCancel,+}: DevicePairingProps) {+ const [mode, setMode] = useState<Mode>("scan");+ const [codeInput, setCodeInput] = useState("");+ const [pasteState, setPasteState] = useState<PasteState>("idle");+ const [pasteError, setPasteError] = useState<string | null>(null);+ const [showRejected, setShowRejected] = useState(false);+ const isMobile = useIsMobile();+ const validatingRef = useRef(false);++ // Detect verify rejection+ useEffect(() => {+ if (lastError && connectionState === "disconnected") {+ setShowRejected(true);+ }+ }, [lastError, connectionState]);++ const handleDismissRejected = useCallback(() => {+ setShowRejected(false);+ }, []);++ const tryConnect = useCallback(+ (raw: string) => {+ const trimmed = raw.trim();+ if (!trimmed || validatingRef.current) return;+ validatingRef.current = true;+ try {+ const info = parseConnectionCode(trimmed);+ setPasteState("success");+ navigator.vibrate?.(50);+ setTimeout(() => {+ onConnect(+ { gateway: info.gateway, hubId: info.hubId, agentId: info.agentId },+ info.token,+ );+ }, 600);+ } catch (e) {+ setPasteState("error");+ setPasteError((e as Error).message || "Invalid code");+ navigator.vibrate?.([30, 50, 30]);+ setTimeout(() => {+ setPasteState("idle");+ setPasteError(null);+ setCodeInput("");+ }, 2000);+ } finally {+ validatingRef.current = false;+ }+ },+ [onConnect],+ );++ const handlePaste = useCallback(+ (e: React.ClipboardEvent) => {+ const text = e.clipboardData.getData("text");+ if (!text.trim()) return;+ setTimeout(() => tryConnect(text), 50);+ },+ [tryConnect],+ );++ const handleScanResult = useCallback(+ async (data: string) => {+ const info = parseConnectionCode(data);+ onConnect(+ { gateway: info.gateway, hubId: info.hubId, agentId: info.agentId },+ info.token,+ );+ },+ [onConnect],+ );++ const isInProgress =+ connectionState === "connecting" ||+ connectionState === "connected" ||+ connectionState === "verifying";++ if (showRejected) {+ return (+ <RejectedStatus fullscreen={isMobile} onDismiss={handleDismissRejected} />+ );+ }++ if (isInProgress) {+ return (+ <ConnectionStatus+ connectionState={connectionState}+ fullscreen={isMobile}+ onCancel={onCancel}+ />+ );+ }++ // Mobile: scanner only+ if (isMobile) {+ return (+ <div className="flex flex-col items-center justify-center h-full gap-4 px-4">+ <div className="text-center space-y-1">+ <p className="text-base font-medium">Scan to connect</p>+ <p className="text-xs text-muted-foreground">+ Scan a Multica QR code to connect to your agent+ </p>+ </div>+ <QrScannerView onResult={handleScanResult} fullscreen />+ </div>+ );+ }++ // Desktop: tab toggle (scan / paste)+ return (+ <div className="flex flex-col items-center justify-center h-full gap-4 px-4 mb-28">+ <div className="text-center space-y-1">+ <p className="text-base font-medium">+ {mode === "scan" ? "Scan to connect" : "Paste to connect"}+ </p>+ <p className="text-xs text-muted-foreground">+ {mode === "scan"+ ? "Scan a Multica QR code to connect to your agent"+ : "Paste a Multica connection code to connect to your agent"}+ </p>+ </div>++ {/* Mode toggle */}+ <div className="flex gap-1 bg-muted rounded-lg p-1">+ <Button+ variant={mode === "scan" ? "default" : "ghost"}+ size="sm"+ className="text-xs gap-1.5 h-7 px-3"+ onClick={() => setMode("scan")}+ >+ <HugeiconsIcon icon={Camera01Icon} className="size-3.5" />+ Scan+ </Button>+ <Button+ variant={mode === "paste" ? "default" : "ghost"}+ size="sm"+ className="text-xs gap-1.5 h-7 px-3"+ onClick={() => setMode("paste")}+ >+ <HugeiconsIcon icon={TextIcon} className="size-3.5" />+ Paste+ </Button>+ </div>++ {/* Content */}+ <div className="w-full max-w-[320px]">+ {mode === "scan" ? (+ <QrScannerView onResult={handleScanResult} />+ ) : (+ <div className="aspect-square rounded-xl bg-muted flex flex-col items-center justify-center p-4">+ {pasteState === "idle" && (+ <Textarea+ value={codeInput}+ onChange={(e) => setCodeInput(e.target.value)}+ onPaste={handlePaste}+ autoFocus={true}+ placeholder="Paste connection code here..."+ className="text-xs font-mono flex-1 resize-none bg-transparent! border-0 focus-visible:ring-0 shadow-none"+ onKeyDown={(e) => {+ if (e.key === "Enter" && (e.metaKey || e.ctrlKey)) {+ e.preventDefault();+ tryConnect(codeInput);+ }+ }}+ />+ )}++ {pasteState === "success" && (+ <HugeiconsIcon+ icon={CheckmarkCircle02Icon}+ className="size-14 text-(--tool-success) animate-in zoom-in duration-300"+ />+ )}++ {pasteState === "error" && (+ <div className="flex flex-col items-center justify-center gap-2">+ <HugeiconsIcon+ icon={Alert02Icon}+ className="size-12 text-(--tool-error)"+ />+ {pasteError && (+ <p className="text-xs text-destructive bg-destructive/10 px-3 py-1.5 rounded-full">+ {pasteError}+ </p>+ )}+ </div>+ )}+ </div>+ )}+ </div>+ </div>+ );+}diff --git a/apps/web/components/pages/chat-page.tsx b/apps/web/components/pages/chat-page.tsxnew file mode 100644index 0000000000..23166da174--- /dev/null+++ b/apps/web/components/pages/chat-page.tsx@@ -0,0 +1,136 @@+"use client";++import { useRef } from "react";+import { Header } from "@/app/header";+import { Button } from "@multica/ui/components/ui/button";+import { Loading } from "@multica/ui/components/ui/loading";+import { ChatInput } from "@multica/ui/components/chat-input";+import { MessageList } from "@multica/ui/components/message-list";+import { useScrollFade } from "@multica/ui/hooks/use-scroll-fade";+import { useAutoScroll } from "@multica/ui/hooks/use-auto-scroll";+import { useGatewayConnection } from "@/hooks/use-gateway-connection";+import { useChat } from "@/hooks/use-chat";+import { ExecApprovalItem } from "@multica/ui/components/exec-approval-item";+import { DevicePairing } from "@/components/device-pairing";++const ChatPage = () => {+ const { pageState, connectionState, identity, error, client, pairingKey, connect, disconnect } =+ useGatewayConnection();++ return (+ <div className="h-full flex flex-col bg-background">+ <Header />+ <div className="flex-1 overflow-hidden min-h-0 flex flex-col">+ {pageState === "loading" && (+ <div className="flex-1 flex items-center justify-center gap-2 text-muted-foreground text-sm">+ <Loading />+ Loading...+ </div>+ )}++ {(pageState === "not-connected" || pageState === "connecting") && (+ <DevicePairing+ key={pairingKey}+ connectionState={connectionState}+ lastError={error}+ onConnect={connect}+ onCancel={disconnect}+ />+ )}++ {pageState === "connected" && client && identity && (+ <ChatView+ client={client}+ hubId={identity.hubId}+ agentId={identity.agentId}+ onDisconnect={disconnect}+ />+ )}+ </div>+ </div>+ );+};++function ChatView({+ client,+ hubId,+ agentId,+ onDisconnect,+}: {+ client: NonNullable<ReturnType<typeof useGatewayConnection>["client"]>;+ hubId: string;+ agentId: string;+ onDisconnect: () => void;+}) {+ const { messages, streamingIds, isLoading, error, pendingApprovals, sendMessage, resolveApproval } = useChat({ client, hubId, agentId });++ const mainRef = useRef<HTMLElement>(null);+ const fadeStyle = useScrollFade(mainRef);+ useAutoScroll(mainRef);++ return (+ <div className="flex-1 flex flex-col min-h-0">+ <div className="container flex items-center justify-end p-2">+ <button+ onClick={onDisconnect}+ className="text-xs text-muted-foreground hover:text-foreground"+ >+ Disconnect+ </button>+ </div>++ <main ref={mainRef} className="flex-1 overflow-y-auto min-h-0" style={fadeStyle}>+ {messages.length === 0 && pendingApprovals.length === 0 ? (+ <div className="flex items-center justify-center h-full text-muted-foreground text-sm">+ Your Agent is ready+ </div>+ ) : (+ <>+ <MessageList messages={messages} streamingIds={streamingIds} />+ {pendingApprovals.length > 0 && (+ <div className="relative px-4 max-w-4xl mx-auto">+ {pendingApprovals.map((approval) => (+ <ExecApprovalItem+ key={approval.approvalId}+ command={approval.command}+ cwd={approval.cwd}+ riskLevel={approval.riskLevel}+ riskReasons={approval.riskReasons}+ expiresAtMs={approval.expiresAtMs}+ onDecision={(decision) => resolveApproval(approval.approvalId, decision)}+ />+ ))}+ </div>+ )}+ </>+ )}+ </main>++ {error && (+ <div className="container px-4" role="alert" aria-live="polite">+ <div className="rounded-lg bg-destructive/5 border border-destructive/15 text-xs px-3 py-2 flex items-center justify-between gap-3">+ <span className="text-foreground leading-snug">{error.message}</span>+ <Button+ variant="destructive"+ size="sm"+ onClick={onDisconnect}+ className="shrink-0 text-xs h-7 px-2.5"+ >+ Disconnect+ </Button>+ </div>+ </div>+ )}++ <footer className="container p-2 pt-1">+ <ChatInput+ onSubmit={sendMessage}+ disabled={isLoading || !!error}+ placeholder={error ? "Connection error" : "Ask your Agent..."}+ />+ </footer>+ </div>+ );+}++export default ChatPage;