mirror of
https://github.com/claude-code-best/claude-code.git
synced 2026-06-21 15:55:50 +00:00
style: 完成所有文件的lint
This commit is contained in:
@@ -1,25 +1,21 @@
|
||||
import { useState, useEffect, useLayoutEffect, useCallback, useRef } from "react";
|
||||
import { createPortal } from "react-dom";
|
||||
import { Button } from "./ui/button";
|
||||
import { StatusDot } from "./ui/connection-status";
|
||||
import { ThemeToggle } from "./ui/theme-toggle";
|
||||
import { Label } from "./ui/label";
|
||||
import {
|
||||
InputGroup,
|
||||
InputGroupAddon,
|
||||
InputGroupInput,
|
||||
} from "./ui/input-group";
|
||||
import { ACPClient, DEFAULT_SETTINGS, DisconnectRequestedError } from "../src/acp";
|
||||
import type { ACPSettings, ConnectionState, BrowserToolParams, BrowserToolResult } from "../src/acp";
|
||||
import { ChevronDown, FolderOpen, Globe, Image, KeyRound, ScanLine, X } from "lucide-react";
|
||||
import { useQRScanner, type QRCodeData } from "../src/hooks";
|
||||
import { useState, useEffect, useLayoutEffect, useCallback, useRef } from 'react';
|
||||
import { createPortal } from 'react-dom';
|
||||
import { Button } from './ui/button';
|
||||
import { StatusDot } from './ui/connection-status';
|
||||
import { ThemeToggle } from './ui/theme-toggle';
|
||||
import { Label } from './ui/label';
|
||||
import { InputGroup, InputGroupAddon, InputGroupInput } from './ui/input-group';
|
||||
import { ACPClient, DEFAULT_SETTINGS, DisconnectRequestedError } from '../src/acp';
|
||||
import type { ACPSettings, ConnectionState, BrowserToolParams, BrowserToolResult } from '../src/acp';
|
||||
import { ChevronDown, FolderOpen, Globe, Image, KeyRound, ScanLine, X } from 'lucide-react';
|
||||
import { useQRScanner, type QRCodeData } from '../src/hooks';
|
||||
|
||||
// Get token from the URL fragment so it is not sent in HTTP requests.
|
||||
function getTokenFromUrl(): string | undefined {
|
||||
try {
|
||||
const url = new URL(window.location.href);
|
||||
const hashParams = new URLSearchParams(url.hash.replace(/^#/, ""));
|
||||
return hashParams.get("token") || undefined;
|
||||
const hashParams = new URLSearchParams(url.hash.replace(/^#/, ''));
|
||||
return hashParams.get('token') || undefined;
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
@@ -30,12 +26,12 @@ function getTokenFromUrl(): string | undefined {
|
||||
function inferProxyUrlFromPage(): string | undefined {
|
||||
try {
|
||||
const url = new URL(window.location.href);
|
||||
const hashParams = new URLSearchParams(url.hash.replace(/^#/, ""));
|
||||
const hashParams = new URLSearchParams(url.hash.replace(/^#/, ''));
|
||||
// Only infer if we have a fragment token (indicates user came from server-printed URL)
|
||||
if (!hashParams.has("token")) {
|
||||
if (!hashParams.has('token')) {
|
||||
return undefined;
|
||||
}
|
||||
const protocol = url.protocol === "https:" ? "wss:" : "ws:";
|
||||
const protocol = url.protocol === 'https:' ? 'wss:' : 'ws:';
|
||||
return `${protocol}//${url.host}/ws`;
|
||||
} catch {
|
||||
return undefined;
|
||||
@@ -45,15 +41,15 @@ function inferProxyUrlFromPage(): string | undefined {
|
||||
function scrubTokenFromUrl(): void {
|
||||
try {
|
||||
const url = new URL(window.location.href);
|
||||
const hashParams = new URLSearchParams(url.hash.replace(/^#/, ""));
|
||||
if (!hashParams.has("token")) {
|
||||
const hashParams = new URLSearchParams(url.hash.replace(/^#/, ''));
|
||||
if (!hashParams.has('token')) {
|
||||
return;
|
||||
}
|
||||
|
||||
hashParams.delete("token");
|
||||
hashParams.delete('token');
|
||||
const nextHash = hashParams.toString();
|
||||
url.hash = nextHash ? `#${nextHash}` : "";
|
||||
window.history.replaceState(null, "", url.toString());
|
||||
url.hash = nextHash ? `#${nextHash}` : '';
|
||||
window.history.replaceState(null, '', url.toString());
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
@@ -102,11 +98,11 @@ export function ACPConnect({
|
||||
browserToolHandler,
|
||||
showTokenInput = false,
|
||||
inferFromUrl = false,
|
||||
placeholder = "Proxy server URL",
|
||||
placeholder = 'Proxy server URL',
|
||||
showScanButton = false,
|
||||
}: ACPConnectProps) {
|
||||
const [settings, setSettings] = useState<ACPSettings>(() => getInitialSettings(inferFromUrl));
|
||||
const [connectionState, setConnectionState] = useState<ConnectionState>("disconnected");
|
||||
const [connectionState, setConnectionState] = useState<ConnectionState>('disconnected');
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [isShaking, setIsShaking] = useState(false);
|
||||
const [client, setClient] = useState<ACPClient | null>(null);
|
||||
@@ -122,7 +118,7 @@ export function ACPConnect({
|
||||
// Mark for auto-connect (will be triggered by settings useEffect)
|
||||
pendingAutoConnectRef.current = true;
|
||||
// Update settings - this will trigger auto-connect via useEffect
|
||||
setSettings((prev) => ({
|
||||
setSettings(prev => ({
|
||||
...prev,
|
||||
proxyUrl: data.url,
|
||||
token: data.token,
|
||||
@@ -163,9 +159,9 @@ export function ACPConnect({
|
||||
stopScanning(); // Close the scanner overlay after album scan
|
||||
}
|
||||
// Reset input to allow re-selecting the same file
|
||||
e.target.value = "";
|
||||
e.target.value = '';
|
||||
},
|
||||
[scanFromFile, stopScanning]
|
||||
[scanFromFile, stopScanning],
|
||||
);
|
||||
|
||||
// Open file picker
|
||||
@@ -203,7 +199,7 @@ export function ACPConnect({
|
||||
// Auto-connect after QR scan (when pendingAutoConnectRef is set)
|
||||
if (pendingAutoConnectRef.current) {
|
||||
pendingAutoConnectRef.current = false;
|
||||
client.connect().catch((e) => {
|
||||
client.connect().catch(e => {
|
||||
// Ignore disconnect requested - user cancelled intentionally
|
||||
if (e instanceof DisconnectRequestedError) {
|
||||
return;
|
||||
@@ -219,7 +215,7 @@ export function ACPConnect({
|
||||
|
||||
// Notify parent when client is ready and auto-collapse on connect
|
||||
useEffect(() => {
|
||||
const isConnected = connectionState === "connected";
|
||||
const isConnected = connectionState === 'connected';
|
||||
onClientReady?.(isConnected ? client : null);
|
||||
|
||||
// Auto-collapse when connected for the first time
|
||||
@@ -229,14 +225,14 @@ export function ACPConnect({
|
||||
}
|
||||
|
||||
// Reset auto-collapse flag when disconnected
|
||||
if (connectionState === "disconnected") {
|
||||
if (connectionState === 'disconnected') {
|
||||
hasAutoCollapsedRef.current = false;
|
||||
}
|
||||
}, [connectionState, client, onClientReady, onExpandedChange]);
|
||||
|
||||
const handleConnect = useCallback(async () => {
|
||||
// Prevent duplicate connect calls if already connecting or connected
|
||||
if (!client || connectionState === "connecting" || connectionState === "connected") {
|
||||
if (!client || connectionState === 'connecting' || connectionState === 'connected') {
|
||||
return;
|
||||
}
|
||||
setError(null);
|
||||
@@ -263,7 +259,7 @@ export function ACPConnect({
|
||||
}, [client]);
|
||||
|
||||
const updateSetting = <K extends keyof ACPSettings>(key: K, value: ACPSettings[K]) => {
|
||||
setSettings((prev) => ({ ...prev, [key]: value }));
|
||||
setSettings(prev => ({ ...prev, [key]: value }));
|
||||
};
|
||||
|
||||
// Clear error when starting to scan
|
||||
@@ -272,107 +268,93 @@ export function ACPConnect({
|
||||
startScanning();
|
||||
}, [startScanning]);
|
||||
|
||||
const isConnected = connectionState === "connected";
|
||||
const isConnecting = connectionState === "connecting";
|
||||
const isConnected = connectionState === 'connected';
|
||||
const isConnecting = connectionState === 'connecting';
|
||||
|
||||
const handleInputKeyDown = useCallback((e: React.KeyboardEvent) => {
|
||||
if (e.key === 'Enter' && !isConnected && !isConnecting) {
|
||||
e.preventDefault();
|
||||
handleConnect();
|
||||
}
|
||||
}, [isConnected, isConnecting, handleConnect]);
|
||||
const handleInputKeyDown = useCallback(
|
||||
(e: React.KeyboardEvent) => {
|
||||
if (e.key === 'Enter' && !isConnected && !isConnecting) {
|
||||
e.preventDefault();
|
||||
handleConnect();
|
||||
}
|
||||
},
|
||||
[isConnected, isConnecting, handleConnect],
|
||||
);
|
||||
|
||||
// Format URL for display
|
||||
const displayUrl = settings.proxyUrl.replace(/^wss?:\/\//, "").replace(/\/ws$/, "");
|
||||
const displayUrl = settings.proxyUrl.replace(/^wss?:\/\//, '').replace(/\/ws$/, '');
|
||||
|
||||
// Get status label
|
||||
const statusLabels: Record<ConnectionState, string> = {
|
||||
disconnected: "Disconnected",
|
||||
connecting: "Connecting...",
|
||||
connected: "Connected",
|
||||
error: "Error",
|
||||
disconnected: 'Disconnected',
|
||||
connecting: 'Connecting...',
|
||||
connected: 'Connected',
|
||||
error: 'Error',
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="bg-background/80 backdrop-blur-sm">
|
||||
<div className="max-w-md mx-auto border-b">
|
||||
{/* Status Bar - Always visible */}
|
||||
<button
|
||||
onClick={() => onExpandedChange(!expanded)}
|
||||
className="w-full flex items-center justify-between px-3 py-2 hover:bg-muted/50 transition-colors"
|
||||
>
|
||||
<div className="flex items-center gap-2">
|
||||
<StatusDot state={connectionState} />
|
||||
<span className="text-sm font-medium">{statusLabels[connectionState]}</span>
|
||||
{isConnected && displayUrl && (
|
||||
<span className="text-xs text-muted-foreground">• {displayUrl}</span>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex items-center gap-1">
|
||||
<div onClick={(e) => e.stopPropagation()}>
|
||||
<ThemeToggle />
|
||||
{/* Status Bar - Always visible */}
|
||||
<button
|
||||
onClick={() => onExpandedChange(!expanded)}
|
||||
className="w-full flex items-center justify-between px-3 py-2 hover:bg-muted/50 transition-colors"
|
||||
>
|
||||
<div className="flex items-center gap-2">
|
||||
<StatusDot state={connectionState} />
|
||||
<span className="text-sm font-medium">{statusLabels[connectionState]}</span>
|
||||
{isConnected && displayUrl && <span className="text-xs text-muted-foreground">• {displayUrl}</span>}
|
||||
</div>
|
||||
<ChevronDown
|
||||
className={`w-4 h-4 text-muted-foreground transition-transform duration-200 ${
|
||||
expanded ? "rotate-180" : ""
|
||||
}`}
|
||||
/>
|
||||
</div>
|
||||
</button>
|
||||
<div className="flex items-center gap-1">
|
||||
<div onClick={e => e.stopPropagation()}>
|
||||
<ThemeToggle />
|
||||
</div>
|
||||
<ChevronDown
|
||||
className={`w-4 h-4 text-muted-foreground transition-transform duration-200 ${
|
||||
expanded ? 'rotate-180' : ''
|
||||
}`}
|
||||
/>
|
||||
</div>
|
||||
</button>
|
||||
|
||||
{/* Expandable Settings Panel */}
|
||||
<div
|
||||
className="overflow-hidden transition-all duration-200 ease-out"
|
||||
style={{
|
||||
maxHeight: expanded ? maxHeight : 0,
|
||||
opacity: expanded ? 1 : 0,
|
||||
}}
|
||||
>
|
||||
<div ref={contentRef} className={`px-3 pb-3 pt-1 space-y-3 ${isShaking ? "animate-shake" : ""}`}>
|
||||
{/* Hidden file input for album scanning */}
|
||||
<input
|
||||
ref={fileInputRef}
|
||||
type="file"
|
||||
accept="image/*"
|
||||
onChange={handleFileSelect}
|
||||
className="hidden"
|
||||
/>
|
||||
{/* Expandable Settings Panel */}
|
||||
<div
|
||||
className="overflow-hidden transition-all duration-200 ease-out"
|
||||
style={{
|
||||
maxHeight: expanded ? maxHeight : 0,
|
||||
opacity: expanded ? 1 : 0,
|
||||
}}
|
||||
>
|
||||
<div ref={contentRef} className={`px-3 pb-3 pt-1 space-y-3 ${isShaking ? 'animate-shake' : ''}`}>
|
||||
{/* Hidden file input for album scanning */}
|
||||
<input ref={fileInputRef} type="file" accept="image/*" onChange={handleFileSelect} className="hidden" />
|
||||
|
||||
{/* QR Scanner View - Portal to body to escape backdrop-blur containing block */}
|
||||
{isScanning && createPortal(
|
||||
<div className="fixed inset-0 z-50 bg-black flex flex-col">
|
||||
<video
|
||||
ref={videoRef}
|
||||
className="flex-1 w-full object-cover"
|
||||
/>
|
||||
<Button
|
||||
onClick={stopScanning}
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="absolute top-4 right-4 h-10 w-10 p-0 bg-black/50 hover:bg-black/70 text-white rounded-full"
|
||||
>
|
||||
<X className="h-5 w-5" />
|
||||
</Button>
|
||||
<div className="absolute bottom-16 left-0 right-0 flex flex-col items-center gap-3">
|
||||
<Button
|
||||
onClick={handleSelectFromAlbum}
|
||||
variant="secondary"
|
||||
size="sm"
|
||||
className="h-9 px-4"
|
||||
>
|
||||
<Image className="h-4 w-4 mr-2" />
|
||||
Select from Album
|
||||
</Button>
|
||||
<span className="text-sm text-white/80">
|
||||
or point camera at QR code
|
||||
</span>
|
||||
</div>
|
||||
</div>,
|
||||
document.body
|
||||
)}
|
||||
{/* QR Scanner View - Portal to body to escape backdrop-blur containing block */}
|
||||
{isScanning &&
|
||||
createPortal(
|
||||
<div className="fixed inset-0 z-50 bg-black flex flex-col">
|
||||
<video ref={videoRef} className="flex-1 w-full object-cover" />
|
||||
<Button
|
||||
onClick={stopScanning}
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="absolute top-4 right-4 h-10 w-10 p-0 bg-black/50 hover:bg-black/70 text-white rounded-full"
|
||||
>
|
||||
<X className="h-5 w-5" />
|
||||
</Button>
|
||||
<div className="absolute bottom-16 left-0 right-0 flex flex-col items-center gap-3">
|
||||
<Button onClick={handleSelectFromAlbum} variant="secondary" size="sm" className="h-9 px-4">
|
||||
<Image className="h-4 w-4 mr-2" />
|
||||
Select from Album
|
||||
</Button>
|
||||
<span className="text-sm text-white/80">or point camera at QR code</span>
|
||||
</div>
|
||||
</div>,
|
||||
document.body,
|
||||
)}
|
||||
|
||||
{/* Connection Settings - use invisible (not hidden) to preserve scrollHeight for animation */}
|
||||
<div className={`space-y-3 ${isScanning ? "invisible" : ""}`}>
|
||||
{/* Connection Settings - use invisible (not hidden) to preserve scrollHeight for animation */}
|
||||
<div className={`space-y-3 ${isScanning ? 'invisible' : ''}`}>
|
||||
{/* Server URL */}
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="proxy-url">Server</Label>
|
||||
@@ -396,7 +378,7 @@ export function ACPConnect({
|
||||
<InputGroupInput
|
||||
id="proxy-url"
|
||||
value={settings.proxyUrl}
|
||||
onChange={(e) => updateSetting("proxyUrl", e.target.value)}
|
||||
onChange={e => updateSetting('proxyUrl', e.target.value)}
|
||||
onKeyDown={handleInputKeyDown}
|
||||
placeholder={placeholder}
|
||||
disabled={isConnected || isConnecting}
|
||||
@@ -411,7 +393,7 @@ export function ACPConnect({
|
||||
className="h-9 px-4"
|
||||
type="button"
|
||||
>
|
||||
{isConnecting ? "..." : "Connect"}
|
||||
{isConnecting ? '...' : 'Connect'}
|
||||
</Button>
|
||||
) : (
|
||||
<Button
|
||||
@@ -440,8 +422,8 @@ export function ACPConnect({
|
||||
</InputGroupAddon>
|
||||
<InputGroupInput
|
||||
id="auth-token"
|
||||
value={settings.token || ""}
|
||||
onChange={(e) => updateSetting("token", e.target.value || undefined)}
|
||||
value={settings.token || ''}
|
||||
onChange={e => updateSetting('token', e.target.value || undefined)}
|
||||
onKeyDown={handleInputKeyDown}
|
||||
placeholder="For remote access"
|
||||
disabled={isConnected || isConnecting}
|
||||
@@ -465,8 +447,8 @@ export function ACPConnect({
|
||||
</InputGroupAddon>
|
||||
<InputGroupInput
|
||||
id="working-dir"
|
||||
value={settings.cwd || ""}
|
||||
onChange={(e) => updateSetting("cwd", e.target.value || undefined)}
|
||||
value={settings.cwd || ''}
|
||||
onChange={e => updateSetting('cwd', e.target.value || undefined)}
|
||||
onKeyDown={handleInputKeyDown}
|
||||
placeholder="/path/to/project"
|
||||
disabled={isConnected || isConnecting}
|
||||
@@ -475,17 +457,13 @@ export function ACPConnect({
|
||||
/>
|
||||
</InputGroup>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Error Message */}
|
||||
{error && (
|
||||
<div className="text-xs text-destructive bg-destructive/10 px-2 py-1.5 rounded">
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Error Message */}
|
||||
{error && <div className="text-xs text-destructive bg-destructive/10 px-2 py-1.5 rounded">{error}</div>}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
import { useState, useCallback, useEffect, useMemo } from "react";
|
||||
import type { ACPClient } from "../src/acp/client";
|
||||
import type { AgentSessionInfo } from "../src/acp/types";
|
||||
import { ChatInterface } from "./ChatInterface";
|
||||
import { cn } from "../src/lib/utils";
|
||||
import { MessageSquare, Plus, PanelLeftClose, PanelLeft } from "lucide-react";
|
||||
import { useState, useCallback, useEffect, useMemo } from 'react';
|
||||
import type { ACPClient } from '../src/acp/client';
|
||||
import type { AgentSessionInfo } from '../src/acp/types';
|
||||
import { ChatInterface } from './ChatInterface';
|
||||
import { cn } from '../src/lib/utils';
|
||||
import { MessageSquare, Plus, PanelLeftClose, PanelLeft } from 'lucide-react';
|
||||
|
||||
interface ACPMainProps {
|
||||
client: ACPClient;
|
||||
@@ -18,35 +18,40 @@ export function ACPMain({ client, agentId }: ACPMainProps) {
|
||||
const [sidebarCollapsed, setSidebarCollapsed] = useState(false);
|
||||
|
||||
// Handle session selection
|
||||
const handleSelectSession = useCallback(async (session: AgentSessionInfo) => {
|
||||
try {
|
||||
if (client.supportsLoadSession) {
|
||||
await client.loadSession({ sessionId: session.sessionId, cwd: session.cwd });
|
||||
} else if (client.supportsResumeSession) {
|
||||
await client.resumeSession({ sessionId: session.sessionId, cwd: session.cwd });
|
||||
} else {
|
||||
throw new Error("Loading or resuming sessions is not supported by this agent.");
|
||||
const handleSelectSession = useCallback(
|
||||
async (session: AgentSessionInfo) => {
|
||||
try {
|
||||
if (client.supportsLoadSession) {
|
||||
await client.loadSession({ sessionId: session.sessionId, cwd: session.cwd });
|
||||
} else if (client.supportsResumeSession) {
|
||||
await client.resumeSession({ sessionId: session.sessionId, cwd: session.cwd });
|
||||
} else {
|
||||
throw new Error('Loading or resuming sessions is not supported by this agent.');
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Failed to load/resume session:', error);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Failed to load/resume session:", error);
|
||||
}
|
||||
}, [client]);
|
||||
},
|
||||
[client],
|
||||
);
|
||||
|
||||
return (
|
||||
<div className="flex h-full w-full">
|
||||
{/* 侧边栏 — Anthropic warm sidebar, hidden on mobile */}
|
||||
<div
|
||||
className={cn(
|
||||
"hidden md:flex flex-col border-r border-border/60 bg-surface-1/50 transition-all duration-200 flex-shrink-0",
|
||||
sidebarCollapsed ? "w-12" : "w-64",
|
||||
'hidden md:flex flex-col border-r border-border/60 bg-surface-1/50 transition-all duration-200 flex-shrink-0',
|
||||
sidebarCollapsed ? 'w-12' : 'w-64',
|
||||
)}
|
||||
>
|
||||
{/* 头部 */}
|
||||
<div className="flex items-center justify-between px-3 py-4">
|
||||
{!sidebarCollapsed && (
|
||||
<span className="text-xs font-display font-semibold text-text-muted uppercase tracking-widest px-1">会话</span>
|
||||
<span className="text-xs font-display font-semibold text-text-muted uppercase tracking-widest px-1">
|
||||
会话
|
||||
</span>
|
||||
)}
|
||||
<div className={cn("flex items-center gap-0.5", sidebarCollapsed && "mx-auto")}>
|
||||
<div className={cn('flex items-center gap-0.5', sidebarCollapsed && 'mx-auto')}>
|
||||
{!sidebarCollapsed && (
|
||||
<button
|
||||
type="button"
|
||||
@@ -64,11 +69,7 @@ export function ACPMain({ client, agentId }: ACPMainProps) {
|
||||
onClick={() => setSidebarCollapsed(!sidebarCollapsed)}
|
||||
className="h-7 w-7 flex items-center justify-center rounded-lg text-text-muted hover:text-text-primary hover:bg-surface-2 transition-colors"
|
||||
>
|
||||
{sidebarCollapsed ? (
|
||||
<PanelLeft className="h-4 w-4" />
|
||||
) : (
|
||||
<PanelLeftClose className="h-4 w-4" />
|
||||
)}
|
||||
{sidebarCollapsed ? <PanelLeft className="h-4 w-4" /> : <PanelLeftClose className="h-4 w-4" />}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
@@ -114,21 +115,21 @@ function SidebarSessionList({
|
||||
const response = await client.listSessions();
|
||||
setSessions(response.sessions);
|
||||
} catch (err) {
|
||||
console.warn("[SidebarSessionList] Failed to load:", err);
|
||||
console.warn('[SidebarSessionList] Failed to load:', err);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, [client]);
|
||||
|
||||
useEffect(() => {
|
||||
if (client.getState() === "connected" && client.supportsSessionList) {
|
||||
if (client.getState() === 'connected' && client.supportsSessionList) {
|
||||
loadSessions();
|
||||
}
|
||||
}, [client, loadSessions]);
|
||||
|
||||
useEffect(() => {
|
||||
const handler = (state: string) => {
|
||||
if (state === "connected") {
|
||||
if (state === 'connected') {
|
||||
setTimeout(loadSessions, 200);
|
||||
}
|
||||
};
|
||||
@@ -180,7 +181,7 @@ function SidebarSessionList({
|
||||
{group.label}
|
||||
</span>
|
||||
</div>
|
||||
{group.sessions.map((session) => (
|
||||
{group.sessions.map(session => (
|
||||
<button
|
||||
key={session.sessionId}
|
||||
type="button"
|
||||
@@ -189,16 +190,16 @@ function SidebarSessionList({
|
||||
onSelectSession(session);
|
||||
}}
|
||||
className={cn(
|
||||
"w-full flex items-center gap-2.5 px-4 py-2 text-left transition-colors rounded-none",
|
||||
'w-full flex items-center gap-2.5 px-4 py-2 text-left transition-colors rounded-none',
|
||||
session.sessionId === activeId
|
||||
? "bg-brand/8 text-text-primary"
|
||||
: "text-text-secondary hover:bg-surface-2/60 hover:text-text-primary",
|
||||
? 'bg-brand/8 text-text-primary'
|
||||
: 'text-text-secondary hover:bg-surface-2/60 hover:text-text-primary',
|
||||
)}
|
||||
title={session.title || session.sessionId}
|
||||
>
|
||||
<MessageSquare className="h-3.5 w-3.5 flex-shrink-0 opacity-50" />
|
||||
<span className="text-[13px] font-display truncate leading-snug">
|
||||
{session.title && session.title.trim() ? session.title : "新会话"}
|
||||
{session.title && session.title.trim() ? session.title : '新会话'}
|
||||
</span>
|
||||
</button>
|
||||
))}
|
||||
@@ -223,9 +224,9 @@ function groupByRecency(sessions: AgentSessionInfo[]): SessionGroup[] {
|
||||
const yesterday = new Date(today.getTime() - 86400000);
|
||||
|
||||
const groups: SessionGroup[] = [
|
||||
{ label: "今天", sessions: [] },
|
||||
{ label: "昨天", sessions: [] },
|
||||
{ label: "更早", sessions: [] },
|
||||
{ label: '今天', sessions: [] },
|
||||
{ label: '昨天', sessions: [] },
|
||||
{ label: '更早', sessions: [] },
|
||||
];
|
||||
|
||||
for (const session of sessions) {
|
||||
@@ -239,5 +240,5 @@ function groupByRecency(sessions: AgentSessionInfo[]): SessionGroup[] {
|
||||
}
|
||||
}
|
||||
|
||||
return groups.filter((g) => g.sessions.length > 0);
|
||||
return groups.filter(g => g.sessions.length > 0);
|
||||
}
|
||||
|
||||
@@ -1,30 +1,47 @@
|
||||
import { useState, useEffect, useCallback, useRef } from "react";
|
||||
import imageCompression from "browser-image-compression";
|
||||
import type { ACPClient } from "../src/acp/client";
|
||||
import type { SessionUpdate, PermissionRequestPayload, PermissionOption, ContentBlock, ImageContent } from "../src/acp/types";
|
||||
import type { ThreadEntry, ToolCallStatus, ToolCallData, UserMessageImage, UserMessageEntry, AssistantMessageEntry, ToolCallEntry, ChatInputMessage, PendingPermission, PlanDisplayEntry } from "../src/lib/types";
|
||||
import { ChatView } from "./chat/ChatView";
|
||||
import { ChatInput } from "./chat/ChatInput";
|
||||
import { PermissionPanel } from "./chat/PermissionPanel";
|
||||
import { ModelSelectorPopover } from "./model-selector";
|
||||
import { useCommands } from "../src/hooks/useCommands";
|
||||
import { useState, useEffect, useCallback, useRef } from 'react';
|
||||
import imageCompression from 'browser-image-compression';
|
||||
import type { ACPClient } from '../src/acp/client';
|
||||
import type {
|
||||
SessionUpdate,
|
||||
PermissionRequestPayload,
|
||||
PermissionOption,
|
||||
ContentBlock,
|
||||
ImageContent,
|
||||
} from '../src/acp/types';
|
||||
import type {
|
||||
ThreadEntry,
|
||||
ToolCallStatus,
|
||||
ToolCallData,
|
||||
UserMessageImage,
|
||||
UserMessageEntry,
|
||||
AssistantMessageEntry,
|
||||
ToolCallEntry,
|
||||
ChatInputMessage,
|
||||
PendingPermission,
|
||||
PlanDisplayEntry,
|
||||
} from '../src/lib/types';
|
||||
import { ChatView } from './chat/ChatView';
|
||||
import { ChatInput } from './chat/ChatInput';
|
||||
import { PermissionPanel } from './chat/PermissionPanel';
|
||||
import { ModelSelectorPopover } from './model-selector';
|
||||
import { useCommands } from '../src/hooks/useCommands';
|
||||
|
||||
// Image compression options
|
||||
// Claude API has a 5MB limit, so we target 2MB to be safe
|
||||
const IMAGE_COMPRESSION_OPTIONS = {
|
||||
maxSizeMB: 2, // Max output size in MB
|
||||
maxSizeMB: 2, // Max output size in MB
|
||||
maxWidthOrHeight: 2048, // Max dimension (scales proportionally, no cropping)
|
||||
useWebWorker: true, // Non-blocking compression
|
||||
fileType: "image/jpeg" as const, // Convert to JPEG for better compression
|
||||
useWebWorker: true, // Non-blocking compression
|
||||
fileType: 'image/jpeg' as const, // Convert to JPEG for better compression
|
||||
};
|
||||
|
||||
// Convert data URL to Blob without using fetch()
|
||||
// This is critical for Chrome extensions where fetch(dataUrl) violates CSP
|
||||
function dataUrlToBlob(dataUrl: string): Blob {
|
||||
// Parse the data URL: data:[<mediatype>][;base64],<data>
|
||||
const commaIndex = dataUrl.indexOf(",");
|
||||
const commaIndex = dataUrl.indexOf(',');
|
||||
if (commaIndex === -1) {
|
||||
throw new Error("Invalid data URL: missing comma separator");
|
||||
throw new Error('Invalid data URL: missing comma separator');
|
||||
}
|
||||
|
||||
const header = dataUrl.slice(0, commaIndex);
|
||||
@@ -32,7 +49,7 @@ function dataUrlToBlob(dataUrl: string): Blob {
|
||||
|
||||
// Extract MIME type from header (e.g., "data:image/png;base64")
|
||||
const mimeMatch = header.match(/^data:([^;,]+)/);
|
||||
const mimeType = mimeMatch ? mimeMatch[1] : "application/octet-stream";
|
||||
const mimeType = mimeMatch ? mimeMatch[1] : 'application/octet-stream';
|
||||
|
||||
// Decode base64 to binary
|
||||
const binaryString = atob(base64Data);
|
||||
@@ -44,14 +61,10 @@ function dataUrlToBlob(dataUrl: string): Blob {
|
||||
return new Blob([bytes], { type: mimeType });
|
||||
}
|
||||
|
||||
import { Plus, Shield, ChevronDown, ChevronUp, Check } from "lucide-react";
|
||||
import { Button } from "./ui/button";
|
||||
import {
|
||||
Tooltip,
|
||||
TooltipContent,
|
||||
TooltipTrigger,
|
||||
} from "./ui/tooltip";
|
||||
import { Popover, PopoverContent, PopoverTrigger } from "./ui/popover";
|
||||
import { Plus, Shield, ChevronDown, ChevronUp, Check } from 'lucide-react';
|
||||
import { Button } from './ui/button';
|
||||
import { Tooltip, TooltipContent, TooltipTrigger } from './ui/tooltip';
|
||||
import { Popover, PopoverContent, PopoverTrigger } from './ui/popover';
|
||||
|
||||
// =============================================================================
|
||||
// Type Definitions - imported from shared types module
|
||||
@@ -67,43 +80,29 @@ interface ChatInterfaceProps {
|
||||
// =============================================================================
|
||||
|
||||
const PERMISSION_MODES = [
|
||||
{ value: "default", label: "默认", description: "手动审批权限请求" },
|
||||
{ value: "acceptEdits", label: "自动接受编辑", description: "自动允许文件编辑操作" },
|
||||
{ value: "bypassPermissions", label: "跳过权限", description: "跳过所有权限检查" },
|
||||
{ value: "plan", label: "规划模式", description: "仅规划,不执行工具" },
|
||||
{ value: "dontAsk", label: "不询问", description: "不弹出询问,自动拒绝" },
|
||||
{ value: "auto", label: "自动判断", description: "AI 自动判断是否批准" },
|
||||
{ value: 'default', label: '默认', description: '手动审批权限请求' },
|
||||
{ value: 'acceptEdits', label: '自动接受编辑', description: '自动允许文件编辑操作' },
|
||||
{ value: 'bypassPermissions', label: '跳过权限', description: '跳过所有权限检查' },
|
||||
{ value: 'plan', label: '规划模式', description: '仅规划,不执行工具' },
|
||||
{ value: 'dontAsk', label: '不询问', description: '不弹出询问,自动拒绝' },
|
||||
{ value: 'auto', label: '自动判断', description: 'AI 自动判断是否批准' },
|
||||
] as const;
|
||||
|
||||
function PermissionModeSelector({
|
||||
mode,
|
||||
onModeChange,
|
||||
}: {
|
||||
mode: string;
|
||||
onModeChange: (mode: string) => void;
|
||||
}) {
|
||||
function PermissionModeSelector({ mode, onModeChange }: { mode: string; onModeChange: (mode: string) => void }) {
|
||||
const [open, setOpen] = useState(false);
|
||||
const current = PERMISSION_MODES.find((m) => m.value === mode) ?? PERMISSION_MODES[0];
|
||||
const current = PERMISSION_MODES.find(m => m.value === mode) ?? PERMISSION_MODES[0];
|
||||
|
||||
return (
|
||||
<Popover open={open} onOpenChange={setOpen}>
|
||||
<PopoverTrigger asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="gap-1.5 text-muted-foreground hover:text-foreground h-7 px-2"
|
||||
>
|
||||
<Button variant="ghost" size="sm" className="gap-1.5 text-muted-foreground hover:text-foreground h-7 px-2">
|
||||
<Shield className="h-3 w-3" />
|
||||
<span className="max-w-24 truncate">{current.label}</span>
|
||||
{open ? (
|
||||
<ChevronUp className="h-3 w-3" />
|
||||
) : (
|
||||
<ChevronDown className="h-3 w-3" />
|
||||
)}
|
||||
{open ? <ChevronUp className="h-3 w-3" /> : <ChevronDown className="h-3 w-3" />}
|
||||
</Button>
|
||||
</PopoverTrigger>
|
||||
<PopoverContent className="w-64 p-1" align="start">
|
||||
{PERMISSION_MODES.map((m) => (
|
||||
{PERMISSION_MODES.map(m => (
|
||||
<button
|
||||
key={m.value}
|
||||
type="button"
|
||||
@@ -133,16 +132,16 @@ function PermissionModeSelector({
|
||||
|
||||
// Map ACP status string to our status type
|
||||
function mapToolStatus(status: string): ToolCallStatus {
|
||||
if (status === "completed") return "complete";
|
||||
if (status === "failed") return "error";
|
||||
return "running";
|
||||
if (status === 'completed') return 'complete';
|
||||
if (status === 'failed') return 'error';
|
||||
return 'running';
|
||||
}
|
||||
|
||||
// Find tool call index in entries (search from end, like Zed)
|
||||
function findToolCallIndex(entries: ThreadEntry[], toolCallId: string): number {
|
||||
for (let i = entries.length - 1; i >= 0; i--) {
|
||||
const entry = entries[i];
|
||||
if (entry && entry.type === "tool_call" && entry.toolCall.id === toolCallId) {
|
||||
if (entry && entry.type === 'tool_call' && entry.toolCall.id === toolCallId) {
|
||||
return i;
|
||||
}
|
||||
}
|
||||
@@ -162,7 +161,7 @@ export function ChatInterface({ client, agentId }: ChatInterfaceProps) {
|
||||
const activeSessionIdRef = useRef<string | null>(null);
|
||||
const [errorMessage, setErrorMessage] = useState<string | null>(null);
|
||||
const errorTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
const [permissionMode, setPermissionMode] = useState(() => localStorage.getItem("acp_permission_mode") || "default");
|
||||
const [permissionMode, setPermissionMode] = useState(() => localStorage.getItem('acp_permission_mode') || 'default');
|
||||
// Reference: Zed's supports_images() checks prompt_capabilities.image
|
||||
const [supportsImages, setSupportsImages] = useState(false);
|
||||
const { commands: availableCommands } = useCommands(client);
|
||||
@@ -179,21 +178,26 @@ export function ChatInterface({ client, agentId }: ChatInterfaceProps) {
|
||||
|
||||
const storageKey = agentId ? `acp_last_session_${agentId}` : null;
|
||||
|
||||
const activateSession = useCallback((sessionId: string, options?: { resetEntries?: boolean }) => {
|
||||
const shouldResetEntries = options?.resetEntries ?? true;
|
||||
if (shouldResetEntries) {
|
||||
setEntries([]);
|
||||
setIsLoading(false);
|
||||
}
|
||||
setActiveSessionId(sessionId);
|
||||
setSessionReady(true);
|
||||
setSupportsImages(client.supportsImages);
|
||||
// Persist session ID for restoration on remount
|
||||
if (storageKey) {
|
||||
try { localStorage.setItem(storageKey, sessionId); } catch {}
|
||||
}
|
||||
console.log("[ChatInterface] Active session:", sessionId, "supportsImages:", client.supportsImages);
|
||||
}, [client, storageKey]);
|
||||
const activateSession = useCallback(
|
||||
(sessionId: string, options?: { resetEntries?: boolean }) => {
|
||||
const shouldResetEntries = options?.resetEntries ?? true;
|
||||
if (shouldResetEntries) {
|
||||
setEntries([]);
|
||||
setIsLoading(false);
|
||||
}
|
||||
setActiveSessionId(sessionId);
|
||||
setSessionReady(true);
|
||||
setSupportsImages(client.supportsImages);
|
||||
// Persist session ID for restoration on remount
|
||||
if (storageKey) {
|
||||
try {
|
||||
localStorage.setItem(storageKey, sessionId);
|
||||
} catch {}
|
||||
}
|
||||
console.log('[ChatInterface] Active session:', sessionId, 'supportsImages:', client.supportsImages);
|
||||
},
|
||||
[client, storageKey],
|
||||
);
|
||||
|
||||
// =============================================================================
|
||||
// Permission Request Handler
|
||||
@@ -202,9 +206,9 @@ export function ChatInterface({ client, agentId }: ChatInterfaceProps) {
|
||||
if (activeSessionIdRef.current && request.sessionId !== activeSessionIdRef.current) {
|
||||
return;
|
||||
}
|
||||
console.log("[ChatInterface] Permission request:", request);
|
||||
console.log('[ChatInterface] Permission request:', request);
|
||||
|
||||
setEntries((prev) => {
|
||||
setEntries(prev => {
|
||||
// Find matching tool call (search from end)
|
||||
const toolCallIndex = findToolCallIndex(prev, request.toolCall.toolCallId);
|
||||
|
||||
@@ -212,14 +216,14 @@ export function ChatInterface({ client, agentId }: ChatInterfaceProps) {
|
||||
// Update existing tool call's status
|
||||
return prev.map((entry, index) => {
|
||||
if (index !== toolCallIndex) return entry;
|
||||
if (entry.type !== "tool_call") return entry;
|
||||
if (entry.toolCall.status !== "running") return entry;
|
||||
if (entry.type !== 'tool_call') return entry;
|
||||
if (entry.toolCall.status !== 'running') return entry;
|
||||
|
||||
return {
|
||||
type: "tool_call",
|
||||
type: 'tool_call',
|
||||
toolCall: {
|
||||
...entry.toolCall,
|
||||
status: "waiting_for_confirmation" as const,
|
||||
status: 'waiting_for_confirmation' as const,
|
||||
permissionRequest: {
|
||||
requestId: request.requestId,
|
||||
options: request.options,
|
||||
@@ -229,14 +233,14 @@ export function ChatInterface({ client, agentId }: ChatInterfaceProps) {
|
||||
});
|
||||
} else {
|
||||
// No matching tool call - create standalone permission request as new entry
|
||||
console.log("[ChatInterface] No matching tool call, creating standalone permission request");
|
||||
console.log('[ChatInterface] No matching tool call, creating standalone permission request');
|
||||
|
||||
const permissionToolCall: ToolCallEntry = {
|
||||
type: "tool_call",
|
||||
type: 'tool_call',
|
||||
toolCall: {
|
||||
id: request.toolCall.toolCallId,
|
||||
title: request.toolCall.title || "Permission Request",
|
||||
status: "waiting_for_confirmation",
|
||||
title: request.toolCall.title || 'Permission Request',
|
||||
status: 'waiting_for_confirmation',
|
||||
permissionRequest: {
|
||||
requestId: request.requestId,
|
||||
options: request.options,
|
||||
@@ -259,27 +263,24 @@ export function ChatInterface({ client, agentId }: ChatInterfaceProps) {
|
||||
}
|
||||
|
||||
// Handle agent message chunk
|
||||
if (update.sessionUpdate === "agent_message_chunk") {
|
||||
const text = update.content.type === "text" && update.content.text ? update.content.text : "";
|
||||
if (update.sessionUpdate === 'agent_message_chunk') {
|
||||
const text = update.content.type === 'text' && update.content.text ? update.content.text : '';
|
||||
if (!text) return;
|
||||
|
||||
setEntries((prev) => {
|
||||
setEntries(prev => {
|
||||
const lastEntry = prev[prev.length - 1];
|
||||
|
||||
// If last entry is AssistantMessage, append to it
|
||||
if (lastEntry?.type === "assistant_message") {
|
||||
if (lastEntry?.type === 'assistant_message') {
|
||||
const lastChunk = lastEntry.chunks[lastEntry.chunks.length - 1];
|
||||
|
||||
// If last chunk is same type (message), append text
|
||||
if (lastChunk?.type === "message") {
|
||||
if (lastChunk?.type === 'message') {
|
||||
return [
|
||||
...prev.slice(0, -1),
|
||||
{
|
||||
...lastEntry,
|
||||
chunks: [
|
||||
...lastEntry.chunks.slice(0, -1),
|
||||
{ type: "message", text: lastChunk.text + text },
|
||||
],
|
||||
chunks: [...lastEntry.chunks.slice(0, -1), { type: 'message', text: lastChunk.text + text }],
|
||||
},
|
||||
];
|
||||
}
|
||||
@@ -289,42 +290,39 @@ export function ChatInterface({ client, agentId }: ChatInterfaceProps) {
|
||||
...prev.slice(0, -1),
|
||||
{
|
||||
...lastEntry,
|
||||
chunks: [...lastEntry.chunks, { type: "message", text }],
|
||||
chunks: [...lastEntry.chunks, { type: 'message', text }],
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
// Create new AssistantMessage entry
|
||||
const newEntry: AssistantMessageEntry = {
|
||||
type: "assistant_message",
|
||||
type: 'assistant_message',
|
||||
id: `assistant-${Date.now()}`,
|
||||
chunks: [{ type: "message", text }],
|
||||
chunks: [{ type: 'message', text }],
|
||||
};
|
||||
return [...prev, newEntry];
|
||||
});
|
||||
}
|
||||
// Handle agent thought chunk (NEW - was missing before)
|
||||
else if (update.sessionUpdate === "agent_thought_chunk") {
|
||||
const text = update.content.type === "text" && update.content.text ? update.content.text : "";
|
||||
else if (update.sessionUpdate === 'agent_thought_chunk') {
|
||||
const text = update.content.type === 'text' && update.content.text ? update.content.text : '';
|
||||
if (!text) return;
|
||||
|
||||
setEntries((prev) => {
|
||||
setEntries(prev => {
|
||||
const lastEntry = prev[prev.length - 1];
|
||||
|
||||
// If last entry is AssistantMessage, append to it
|
||||
if (lastEntry?.type === "assistant_message") {
|
||||
if (lastEntry?.type === 'assistant_message') {
|
||||
const lastChunk = lastEntry.chunks[lastEntry.chunks.length - 1];
|
||||
|
||||
// If last chunk is same type (thought), append text
|
||||
if (lastChunk?.type === "thought") {
|
||||
if (lastChunk?.type === 'thought') {
|
||||
return [
|
||||
...prev.slice(0, -1),
|
||||
{
|
||||
...lastEntry,
|
||||
chunks: [
|
||||
...lastEntry.chunks.slice(0, -1),
|
||||
{ type: "thought", text: lastChunk.text + text },
|
||||
],
|
||||
chunks: [...lastEntry.chunks.slice(0, -1), { type: 'thought', text: lastChunk.text + text }],
|
||||
},
|
||||
];
|
||||
}
|
||||
@@ -334,30 +332,30 @@ export function ChatInterface({ client, agentId }: ChatInterfaceProps) {
|
||||
...prev.slice(0, -1),
|
||||
{
|
||||
...lastEntry,
|
||||
chunks: [...lastEntry.chunks, { type: "thought", text }],
|
||||
chunks: [...lastEntry.chunks, { type: 'thought', text }],
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
// Create new AssistantMessage entry with thought
|
||||
const newEntry: AssistantMessageEntry = {
|
||||
type: "assistant_message",
|
||||
type: 'assistant_message',
|
||||
id: `assistant-${Date.now()}`,
|
||||
chunks: [{ type: "thought", text }],
|
||||
chunks: [{ type: 'thought', text }],
|
||||
};
|
||||
return [...prev, newEntry];
|
||||
});
|
||||
}
|
||||
// Handle user message chunk (NEW - was missing before)
|
||||
else if (update.sessionUpdate === "user_message_chunk") {
|
||||
const text = update.content.type === "text" && update.content.text ? update.content.text : "";
|
||||
else if (update.sessionUpdate === 'user_message_chunk') {
|
||||
const text = update.content.type === 'text' && update.content.text ? update.content.text : '';
|
||||
if (!text) return;
|
||||
|
||||
setEntries((prev) => {
|
||||
setEntries(prev => {
|
||||
const lastEntry = prev[prev.length - 1];
|
||||
|
||||
// If last entry is UserMessage, append to it
|
||||
if (lastEntry?.type === "user_message") {
|
||||
if (lastEntry?.type === 'user_message') {
|
||||
return [
|
||||
...prev.slice(0, -1),
|
||||
{
|
||||
@@ -369,7 +367,7 @@ export function ChatInterface({ client, agentId }: ChatInterfaceProps) {
|
||||
|
||||
// Create new UserMessage entry
|
||||
const newEntry: UserMessageEntry = {
|
||||
type: "user_message",
|
||||
type: 'user_message',
|
||||
id: `user-${Date.now()}`,
|
||||
content: text,
|
||||
};
|
||||
@@ -377,7 +375,7 @@ export function ChatInterface({ client, agentId }: ChatInterfaceProps) {
|
||||
});
|
||||
}
|
||||
// Handle tool call (UPSERT - update if exists, create if not)
|
||||
else if (update.sessionUpdate === "tool_call") {
|
||||
else if (update.sessionUpdate === 'tool_call') {
|
||||
const toolCallData: ToolCallData = {
|
||||
id: update.toolCallId,
|
||||
title: update.title,
|
||||
@@ -387,7 +385,7 @@ export function ChatInterface({ client, agentId }: ChatInterfaceProps) {
|
||||
rawOutput: update.rawOutput,
|
||||
};
|
||||
|
||||
setEntries((prev) => {
|
||||
setEntries(prev => {
|
||||
// UPSERT: Check if tool call already exists
|
||||
const existingIndex = findToolCallIndex(prev, update.toolCallId);
|
||||
|
||||
@@ -395,10 +393,10 @@ export function ChatInterface({ client, agentId }: ChatInterfaceProps) {
|
||||
// UPDATE existing tool call
|
||||
return prev.map((entry, index) => {
|
||||
if (index !== existingIndex) return entry;
|
||||
if (entry.type !== "tool_call") return entry;
|
||||
if (entry.type !== 'tool_call') return entry;
|
||||
|
||||
return {
|
||||
type: "tool_call",
|
||||
type: 'tool_call',
|
||||
toolCall: {
|
||||
...entry.toolCall,
|
||||
...toolCallData,
|
||||
@@ -409,27 +407,27 @@ export function ChatInterface({ client, agentId }: ChatInterfaceProps) {
|
||||
|
||||
// CREATE new tool call entry
|
||||
const newEntry: ToolCallEntry = {
|
||||
type: "tool_call",
|
||||
type: 'tool_call',
|
||||
toolCall: toolCallData,
|
||||
};
|
||||
return [...prev, newEntry];
|
||||
});
|
||||
}
|
||||
// Handle tool call update (partial update)
|
||||
else if (update.sessionUpdate === "tool_call_update") {
|
||||
setEntries((prev) => {
|
||||
else if (update.sessionUpdate === 'tool_call_update') {
|
||||
setEntries(prev => {
|
||||
const existingIndex = findToolCallIndex(prev, update.toolCallId);
|
||||
|
||||
if (existingIndex < 0) {
|
||||
// Tool call not found - create a failed tool call entry (like Zed)
|
||||
console.warn(`[ChatInterface] Tool call not found for update: ${update.toolCallId}`);
|
||||
const failedEntry: ToolCallEntry = {
|
||||
type: "tool_call",
|
||||
type: 'tool_call',
|
||||
toolCall: {
|
||||
id: update.toolCallId,
|
||||
title: update.title || "Tool call not found",
|
||||
status: "error",
|
||||
content: [{ type: "content", content: { type: "text", text: "Tool call not found" } }],
|
||||
title: update.title || 'Tool call not found',
|
||||
status: 'error',
|
||||
content: [{ type: 'content', content: { type: 'text', text: 'Tool call not found' } }],
|
||||
},
|
||||
};
|
||||
return [...prev, failedEntry];
|
||||
@@ -437,7 +435,7 @@ export function ChatInterface({ client, agentId }: ChatInterfaceProps) {
|
||||
|
||||
return prev.map((entry, index) => {
|
||||
if (index !== existingIndex) return entry;
|
||||
if (entry.type !== "tool_call") return entry;
|
||||
if (entry.type !== 'tool_call') return entry;
|
||||
|
||||
const newStatus = update.status ? mapToolStatus(update.status) : entry.toolCall.status;
|
||||
const mergedContent = update.content
|
||||
@@ -445,7 +443,7 @@ export function ChatInterface({ client, agentId }: ChatInterfaceProps) {
|
||||
: entry.toolCall.content;
|
||||
|
||||
return {
|
||||
type: "tool_call",
|
||||
type: 'tool_call',
|
||||
toolCall: {
|
||||
...entry.toolCall,
|
||||
status: newStatus,
|
||||
@@ -459,31 +457,24 @@ export function ChatInterface({ client, agentId }: ChatInterfaceProps) {
|
||||
});
|
||||
}
|
||||
// Handle plan update (replace entire plan)
|
||||
else if (update.sessionUpdate === "plan") {
|
||||
setEntries((prev) => {
|
||||
else if (update.sessionUpdate === 'plan') {
|
||||
setEntries(prev => {
|
||||
// Empty entries → remove existing plan
|
||||
if (update.entries.length === 0) {
|
||||
return prev.filter((e) => e.type !== "plan");
|
||||
return prev.filter(e => e.type !== 'plan');
|
||||
}
|
||||
|
||||
// Find last plan entry
|
||||
const lastPlanIndex = prev.reduce(
|
||||
(acc, entry, i) => (entry.type === "plan" ? i : acc),
|
||||
-1,
|
||||
);
|
||||
const lastPlanIndex = prev.reduce((acc, entry, i) => (entry.type === 'plan' ? i : acc), -1);
|
||||
|
||||
if (lastPlanIndex >= 0) {
|
||||
// Update existing plan in place
|
||||
return prev.map((entry, index) =>
|
||||
index === lastPlanIndex
|
||||
? { ...entry, entries: update.entries }
|
||||
: entry,
|
||||
);
|
||||
return prev.map((entry, index) => (index === lastPlanIndex ? { ...entry, entries: update.entries } : entry));
|
||||
}
|
||||
|
||||
// Create new plan entry
|
||||
const newPlanEntry: PlanDisplayEntry = {
|
||||
type: "plan",
|
||||
type: 'plan',
|
||||
id: `plan-${Date.now()}`,
|
||||
entries: update.entries,
|
||||
};
|
||||
@@ -496,18 +487,18 @@ export function ChatInterface({ client, agentId }: ChatInterfaceProps) {
|
||||
// Setup Effect
|
||||
// =============================================================================
|
||||
useEffect(() => {
|
||||
client.setSessionCreatedHandler((sessionId) => {
|
||||
console.log("[ChatInterface] Session created:", sessionId);
|
||||
client.setSessionCreatedHandler(sessionId => {
|
||||
console.log('[ChatInterface] Session created:', sessionId);
|
||||
activateSession(sessionId);
|
||||
});
|
||||
|
||||
client.setSessionLoadedHandler((sessionId) => {
|
||||
console.log("[ChatInterface] Session loaded/resumed:", sessionId);
|
||||
client.setSessionLoadedHandler(sessionId => {
|
||||
console.log('[ChatInterface] Session loaded/resumed:', sessionId);
|
||||
activateSession(sessionId, { resetEntries: false });
|
||||
});
|
||||
|
||||
client.setSessionSwitchingHandler((sessionId) => {
|
||||
console.log("[ChatInterface] Switching to session:", sessionId);
|
||||
client.setSessionSwitchingHandler(sessionId => {
|
||||
console.log('[ChatInterface] Switching to session:', sessionId);
|
||||
setActiveSessionId(sessionId);
|
||||
resetThreadState();
|
||||
});
|
||||
@@ -516,8 +507,8 @@ export function ChatInterface({ client, agentId }: ChatInterfaceProps) {
|
||||
handleSessionUpdate(sessionId, update);
|
||||
});
|
||||
|
||||
client.setPromptCompleteHandler((stopReason) => {
|
||||
console.log("[ChatInterface] Prompt complete:", stopReason);
|
||||
client.setPromptCompleteHandler(stopReason => {
|
||||
console.log('[ChatInterface] Prompt complete:', stopReason);
|
||||
// Always set isLoading=false when prompt completes
|
||||
// This includes stopReason="cancelled" (which is the expected response after client.cancel())
|
||||
// Note: Tool calls are already marked as "canceled" in handleCancel before this fires
|
||||
@@ -526,8 +517,8 @@ export function ChatInterface({ client, agentId }: ChatInterfaceProps) {
|
||||
|
||||
client.setPermissionRequestHandler(handlePermissionRequest);
|
||||
|
||||
client.setErrorMessageHandler((msg) => {
|
||||
console.error("[ChatInterface] Agent error:", msg);
|
||||
client.setErrorMessageHandler(msg => {
|
||||
console.error('[ChatInterface] Agent error:', msg);
|
||||
setErrorMessage(msg);
|
||||
// Clear any existing timer
|
||||
if (errorTimerRef.current) clearTimeout(errorTimerRef.current);
|
||||
@@ -538,7 +529,7 @@ export function ChatInterface({ client, agentId }: ChatInterfaceProps) {
|
||||
// Restore last session or create a new one
|
||||
const lastSessionId = storageKey ? localStorage.getItem(storageKey) : null;
|
||||
if (lastSessionId && (client.supportsLoadSession || client.supportsResumeSession)) {
|
||||
console.log("[ChatInterface] Restoring session:", lastSessionId);
|
||||
console.log('[ChatInterface] Restoring session:', lastSessionId);
|
||||
const restore = async () => {
|
||||
try {
|
||||
if (client.supportsLoadSession) {
|
||||
@@ -547,7 +538,7 @@ export function ChatInterface({ client, agentId }: ChatInterfaceProps) {
|
||||
await client.resumeSession({ sessionId: lastSessionId });
|
||||
}
|
||||
} catch (err) {
|
||||
console.warn("[ChatInterface] Failed to restore session, creating new one:", err);
|
||||
console.warn('[ChatInterface] Failed to restore session, creating new one:', err);
|
||||
client.createSession(undefined, permissionMode);
|
||||
}
|
||||
};
|
||||
@@ -575,7 +566,7 @@ export function ChatInterface({ client, agentId }: ChatInterfaceProps) {
|
||||
// Creates a new session by clearing current state and calling new_session
|
||||
// This is the core of Zed's NewThread action
|
||||
const handleNewSession = useCallback(() => {
|
||||
console.log("[ChatInterface] Creating new session...");
|
||||
console.log('[ChatInterface] Creating new session...');
|
||||
|
||||
// Reference: Zed's set_server_state() calls close_all_sessions() before setting new state
|
||||
// Cancel any ongoing request before creating new session
|
||||
@@ -597,26 +588,25 @@ export function ChatInterface({ client, agentId }: ChatInterfaceProps) {
|
||||
// 2. Send cancel notification to agent
|
||||
// 3. Do NOT set isLoading=false here - wait for prompt_complete with stopReason="cancelled"
|
||||
const handleCancel = () => {
|
||||
console.log("[ChatInterface] Cancel requested");
|
||||
console.log('[ChatInterface] Cancel requested');
|
||||
|
||||
// Like Zed: iterate all entries, mark Pending/WaitingForConfirmation/InProgress tool calls as Canceled
|
||||
setEntries((prev) =>
|
||||
prev.map((entry) => {
|
||||
if (entry.type !== "tool_call") return entry;
|
||||
setEntries(prev =>
|
||||
prev.map(entry => {
|
||||
if (entry.type !== 'tool_call') return entry;
|
||||
|
||||
// Check if status should be canceled (matches Zed's logic)
|
||||
const shouldCancel =
|
||||
entry.toolCall.status === "running" ||
|
||||
entry.toolCall.status === "waiting_for_confirmation";
|
||||
entry.toolCall.status === 'running' || entry.toolCall.status === 'waiting_for_confirmation';
|
||||
|
||||
if (!shouldCancel) return entry;
|
||||
|
||||
console.log("[ChatInterface] Marking tool call as canceled:", entry.toolCall.id);
|
||||
console.log('[ChatInterface] Marking tool call as canceled:', entry.toolCall.id);
|
||||
return {
|
||||
type: "tool_call",
|
||||
type: 'tool_call',
|
||||
toolCall: {
|
||||
...entry.toolCall,
|
||||
status: "canceled" as ToolCallStatus,
|
||||
status: 'canceled' as ToolCallStatus,
|
||||
permissionRequest: undefined, // Clear any pending permission request
|
||||
},
|
||||
};
|
||||
@@ -629,42 +619,45 @@ export function ChatInterface({ client, agentId }: ChatInterfaceProps) {
|
||||
// Wait for prompt_complete with stopReason="cancelled" from the agent
|
||||
};
|
||||
|
||||
const handlePermissionResponse = useCallback((requestId: string, optionId: string | null, optionKind: PermissionOption["kind"] | null) => {
|
||||
console.log("[ChatInterface] Permission response:", { requestId, optionId, optionKind });
|
||||
client.respondToPermission(requestId, optionId);
|
||||
const handlePermissionResponse = useCallback(
|
||||
(requestId: string, optionId: string | null, optionKind: PermissionOption['kind'] | null) => {
|
||||
console.log('[ChatInterface] Permission response:', { requestId, optionId, optionKind });
|
||||
client.respondToPermission(requestId, optionId);
|
||||
|
||||
// Determine new status based on option kind
|
||||
const isRejected = optionKind === "reject_once" || optionKind === "reject_always" || optionId === null;
|
||||
// Determine new status based on option kind
|
||||
const isRejected = optionKind === 'reject_once' || optionKind === 'reject_always' || optionId === null;
|
||||
|
||||
// Update the tool call status in entries
|
||||
setEntries((prev) =>
|
||||
prev.map((entry) => {
|
||||
if (entry.type !== "tool_call") return entry;
|
||||
if (entry.toolCall.permissionRequest?.requestId !== requestId) return entry;
|
||||
// Update the tool call status in entries
|
||||
setEntries(prev =>
|
||||
prev.map(entry => {
|
||||
if (entry.type !== 'tool_call') return entry;
|
||||
if (entry.toolCall.permissionRequest?.requestId !== requestId) return entry;
|
||||
|
||||
// For standalone permission requests, mark as complete immediately when approved
|
||||
// For regular tool calls, mark as running (agent will update to complete later)
|
||||
let newStatus: ToolCallStatus;
|
||||
if (isRejected) {
|
||||
newStatus = "rejected";
|
||||
} else if (entry.toolCall.isStandalonePermission) {
|
||||
newStatus = "complete";
|
||||
} else {
|
||||
newStatus = "running";
|
||||
}
|
||||
// For standalone permission requests, mark as complete immediately when approved
|
||||
// For regular tool calls, mark as running (agent will update to complete later)
|
||||
let newStatus: ToolCallStatus;
|
||||
if (isRejected) {
|
||||
newStatus = 'rejected';
|
||||
} else if (entry.toolCall.isStandalonePermission) {
|
||||
newStatus = 'complete';
|
||||
} else {
|
||||
newStatus = 'running';
|
||||
}
|
||||
|
||||
return {
|
||||
type: "tool_call",
|
||||
toolCall: {
|
||||
...entry.toolCall,
|
||||
status: newStatus,
|
||||
permissionRequest: undefined,
|
||||
isStandalonePermission: undefined,
|
||||
},
|
||||
};
|
||||
}),
|
||||
);
|
||||
}, [client]);
|
||||
return {
|
||||
type: 'tool_call',
|
||||
toolCall: {
|
||||
...entry.toolCall,
|
||||
status: newStatus,
|
||||
permissionRequest: undefined,
|
||||
isStandalonePermission: undefined,
|
||||
},
|
||||
};
|
||||
}),
|
||||
);
|
||||
},
|
||||
[client],
|
||||
);
|
||||
|
||||
// =============================================================================
|
||||
// Render
|
||||
@@ -672,8 +665,11 @@ export function ChatInterface({ client, agentId }: ChatInterfaceProps) {
|
||||
|
||||
// Collect pending permissions from tool call entries
|
||||
const pendingPermissions: PendingPermission[] = entries
|
||||
.filter((e): e is ToolCallEntry => e.type === "tool_call" && e.toolCall.status === "waiting_for_confirmation" && !!e.toolCall.permissionRequest)
|
||||
.map((e) => ({
|
||||
.filter(
|
||||
(e): e is ToolCallEntry =>
|
||||
e.type === 'tool_call' && e.toolCall.status === 'waiting_for_confirmation' && !!e.toolCall.permissionRequest,
|
||||
)
|
||||
.map(e => ({
|
||||
requestId: e.toolCall.permissionRequest!.requestId,
|
||||
toolName: e.toolCall.title,
|
||||
toolInput: e.toolCall.rawInput || {},
|
||||
@@ -682,120 +678,128 @@ export function ChatInterface({ client, agentId }: ChatInterfaceProps) {
|
||||
}));
|
||||
|
||||
// Handle permission respond for unified PermissionPanel
|
||||
const handlePermissionPanelRespond = useCallback((requestId: string, approved: boolean) => {
|
||||
// Find the matching permission request to get the real optionId
|
||||
const perm = pendingPermissions.find((p) => p.requestId === requestId);
|
||||
let optionId: string | null = null;
|
||||
let optionKind: PermissionOption["kind"] | null = null;
|
||||
const handlePermissionPanelRespond = useCallback(
|
||||
(requestId: string, approved: boolean) => {
|
||||
// Find the matching permission request to get the real optionId
|
||||
const perm = pendingPermissions.find(p => p.requestId === requestId);
|
||||
let optionId: string | null = null;
|
||||
let optionKind: PermissionOption['kind'] | null = null;
|
||||
|
||||
if (perm?.options && perm.options.length > 0) {
|
||||
if (approved) {
|
||||
// Pick the first allow option (prefer allow_once, then allow_always)
|
||||
const allowOpt = perm.options.find((o) => o.kind === "allow_once") ?? perm.options.find((o) => o.kind === "allow_always");
|
||||
if (allowOpt) {
|
||||
optionId = allowOpt.optionId;
|
||||
optionKind = allowOpt.kind;
|
||||
}
|
||||
} else {
|
||||
// Pick the first reject option
|
||||
const rejectOpt = perm.options.find((o) => o.kind === "reject_once") ?? perm.options.find((o) => o.kind === "reject_always");
|
||||
if (rejectOpt) {
|
||||
optionId = rejectOpt.optionId;
|
||||
optionKind = rejectOpt.kind;
|
||||
if (perm?.options && perm.options.length > 0) {
|
||||
if (approved) {
|
||||
// Pick the first allow option (prefer allow_once, then allow_always)
|
||||
const allowOpt =
|
||||
perm.options.find(o => o.kind === 'allow_once') ?? perm.options.find(o => o.kind === 'allow_always');
|
||||
if (allowOpt) {
|
||||
optionId = allowOpt.optionId;
|
||||
optionKind = allowOpt.kind;
|
||||
}
|
||||
} else {
|
||||
// Pick the first reject option
|
||||
const rejectOpt =
|
||||
perm.options.find(o => o.kind === 'reject_once') ?? perm.options.find(o => o.kind === 'reject_always');
|
||||
if (rejectOpt) {
|
||||
optionId = rejectOpt.optionId;
|
||||
optionKind = rejectOpt.kind;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Fallback: if no matching option found, use null (cancelled)
|
||||
if (!optionId) {
|
||||
optionKind = approved ? "allow_once" : "reject_once";
|
||||
}
|
||||
// Fallback: if no matching option found, use null (cancelled)
|
||||
if (!optionId) {
|
||||
optionKind = approved ? 'allow_once' : 'reject_once';
|
||||
}
|
||||
|
||||
handlePermissionResponse(requestId, optionId, optionKind);
|
||||
}, [handlePermissionResponse, pendingPermissions]);
|
||||
handlePermissionResponse(requestId, optionId, optionKind);
|
||||
},
|
||||
[handlePermissionResponse, pendingPermissions],
|
||||
);
|
||||
|
||||
// Handle ChatInput submit — convert ChatInputMessage to ContentBlock[]
|
||||
const handleChatInputSubmit = useCallback(async (message: ChatInputMessage) => {
|
||||
const text = message.text.trim();
|
||||
const images = message.images || [];
|
||||
const handleChatInputSubmit = useCallback(
|
||||
async (message: ChatInputMessage) => {
|
||||
const text = message.text.trim();
|
||||
const images = message.images || [];
|
||||
|
||||
if ((!text && images.length === 0) || isLoading || !sessionReady) return;
|
||||
if ((!text && images.length === 0) || isLoading || !sessionReady) return;
|
||||
|
||||
const contentBlocks: ContentBlock[] = [];
|
||||
const contentBlocks: ContentBlock[] = [];
|
||||
|
||||
if (text) {
|
||||
contentBlocks.push({ type: "text", text });
|
||||
}
|
||||
|
||||
// Convert images to ContentBlock
|
||||
const userImages: UserMessageImage[] = [];
|
||||
|
||||
for (const img of images) {
|
||||
try {
|
||||
const dataUrl = `data:${img.mimeType};base64,${img.data}`;
|
||||
let blob: Blob;
|
||||
if (dataUrl.startsWith("data:")) {
|
||||
blob = dataUrlToBlob(dataUrl);
|
||||
} else {
|
||||
const response = await fetch(dataUrl);
|
||||
blob = await response.blob();
|
||||
}
|
||||
|
||||
let finalBlob: Blob = blob;
|
||||
let finalMimeType = img.mimeType;
|
||||
|
||||
if (blob.size > 2 * 1024 * 1024) {
|
||||
const imageFile = new File([blob], "image.jpg", { type: blob.type });
|
||||
finalBlob = await imageCompression(imageFile, IMAGE_COMPRESSION_OPTIONS);
|
||||
finalMimeType = "image/jpeg";
|
||||
}
|
||||
|
||||
const base64Data = await new Promise<string>((resolve, reject) => {
|
||||
const reader = new FileReader();
|
||||
reader.onloadend = () => {
|
||||
const result = reader.result as string;
|
||||
const commaIndex = result.indexOf(",");
|
||||
resolve(commaIndex >= 0 ? result.slice(commaIndex + 1) : result);
|
||||
};
|
||||
reader.onerror = () => reject(new Error("FileReader error: " + reader.error?.message));
|
||||
reader.readAsDataURL(finalBlob);
|
||||
});
|
||||
|
||||
const imageContent: ImageContent = {
|
||||
type: "image",
|
||||
mimeType: finalMimeType,
|
||||
data: base64Data,
|
||||
};
|
||||
contentBlocks.push(imageContent);
|
||||
|
||||
userImages.push({
|
||||
mimeType: finalMimeType,
|
||||
data: base64Data,
|
||||
});
|
||||
} catch (error) {
|
||||
console.error("[ChatInterface] Failed to process image:", error);
|
||||
if (text) {
|
||||
contentBlocks.push({ type: 'text', text });
|
||||
}
|
||||
}
|
||||
|
||||
if (contentBlocks.length === 0) return;
|
||||
// Convert images to ContentBlock
|
||||
const userImages: UserMessageImage[] = [];
|
||||
|
||||
// Add user message entry
|
||||
const userEntry: UserMessageEntry = {
|
||||
type: "user_message",
|
||||
id: `user-${Date.now()}`,
|
||||
content: text,
|
||||
images: userImages.length > 0 ? userImages : undefined,
|
||||
};
|
||||
setEntries((prev) => [...prev, userEntry]);
|
||||
setIsLoading(true);
|
||||
for (const img of images) {
|
||||
try {
|
||||
const dataUrl = `data:${img.mimeType};base64,${img.data}`;
|
||||
let blob: Blob;
|
||||
if (dataUrl.startsWith('data:')) {
|
||||
blob = dataUrlToBlob(dataUrl);
|
||||
} else {
|
||||
const response = await fetch(dataUrl);
|
||||
blob = await response.blob();
|
||||
}
|
||||
|
||||
try {
|
||||
await client.sendPrompt(contentBlocks);
|
||||
} catch (error) {
|
||||
console.error("[ChatInterface] Failed to send prompt:", error);
|
||||
setIsLoading(false);
|
||||
}
|
||||
}, [isLoading, sessionReady, client]);
|
||||
let finalBlob: Blob = blob;
|
||||
let finalMimeType = img.mimeType;
|
||||
|
||||
if (blob.size > 2 * 1024 * 1024) {
|
||||
const imageFile = new File([blob], 'image.jpg', { type: blob.type });
|
||||
finalBlob = await imageCompression(imageFile, IMAGE_COMPRESSION_OPTIONS);
|
||||
finalMimeType = 'image/jpeg';
|
||||
}
|
||||
|
||||
const base64Data = await new Promise<string>((resolve, reject) => {
|
||||
const reader = new FileReader();
|
||||
reader.onloadend = () => {
|
||||
const result = reader.result as string;
|
||||
const commaIndex = result.indexOf(',');
|
||||
resolve(commaIndex >= 0 ? result.slice(commaIndex + 1) : result);
|
||||
};
|
||||
reader.onerror = () => reject(new Error('FileReader error: ' + reader.error?.message));
|
||||
reader.readAsDataURL(finalBlob);
|
||||
});
|
||||
|
||||
const imageContent: ImageContent = {
|
||||
type: 'image',
|
||||
mimeType: finalMimeType,
|
||||
data: base64Data,
|
||||
};
|
||||
contentBlocks.push(imageContent);
|
||||
|
||||
userImages.push({
|
||||
mimeType: finalMimeType,
|
||||
data: base64Data,
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('[ChatInterface] Failed to process image:', error);
|
||||
}
|
||||
}
|
||||
|
||||
if (contentBlocks.length === 0) return;
|
||||
|
||||
// Add user message entry
|
||||
const userEntry: UserMessageEntry = {
|
||||
type: 'user_message',
|
||||
id: `user-${Date.now()}`,
|
||||
content: text,
|
||||
images: userImages.length > 0 ? userImages : undefined,
|
||||
};
|
||||
setEntries(prev => [...prev, userEntry]);
|
||||
setIsLoading(true);
|
||||
|
||||
try {
|
||||
await client.sendPrompt(contentBlocks);
|
||||
} catch (error) {
|
||||
console.error('[ChatInterface] Failed to send prompt:', error);
|
||||
setIsLoading(false);
|
||||
}
|
||||
},
|
||||
[isLoading, sessionReady, client],
|
||||
);
|
||||
|
||||
return (
|
||||
<div className="flex flex-col h-full">
|
||||
@@ -804,17 +808,14 @@ export function ChatInterface({ client, agentId }: ChatInterfaceProps) {
|
||||
entries={entries}
|
||||
isLoading={isLoading && !sessionReady ? false : isLoading}
|
||||
onPermissionRespond={(requestId, optionId, optionKind) => {
|
||||
handlePermissionResponse(requestId, optionId, optionKind as PermissionOption["kind"] | null);
|
||||
handlePermissionResponse(requestId, optionId, optionKind as PermissionOption['kind'] | null);
|
||||
}}
|
||||
emptyTitle={sessionReady ? "开始对话" : undefined}
|
||||
emptyDescription={sessionReady ? "输入消息开始与 ACP agent 聊天" : undefined}
|
||||
emptyTitle={sessionReady ? '开始对话' : undefined}
|
||||
emptyDescription={sessionReady ? '输入消息开始与 ACP agent 聊天' : undefined}
|
||||
/>
|
||||
|
||||
{/* Permission panel — fixed above input */}
|
||||
<PermissionPanel
|
||||
requests={pendingPermissions}
|
||||
onRespond={handlePermissionPanelRespond}
|
||||
/>
|
||||
<PermissionPanel requests={pendingPermissions} onRespond={handlePermissionPanelRespond} />
|
||||
|
||||
{/* Error banner */}
|
||||
{errorMessage && (
|
||||
@@ -826,7 +827,7 @@ export function ChatInterface({ client, agentId }: ChatInterfaceProps) {
|
||||
onClick={() => setErrorMessage(null)}
|
||||
className="ml-2 text-red-500 hover:text-red-700 dark:text-red-400 dark:hover:text-red-200 flex-shrink-0"
|
||||
>
|
||||
{"\u00D7"}
|
||||
{'\u00D7'}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
@@ -836,7 +837,13 @@ export function ChatInterface({ client, agentId }: ChatInterfaceProps) {
|
||||
<div className="flex-shrink-0">
|
||||
<div className="max-w-3xl mx-auto w-full px-4 sm:px-8 pb-1 flex items-center justify-between">
|
||||
<div className="flex items-center gap-1">
|
||||
<PermissionModeSelector mode={permissionMode} onModeChange={(m: string) => { setPermissionMode(m); localStorage.setItem("acp_permission_mode", m); }} />
|
||||
<PermissionModeSelector
|
||||
mode={permissionMode}
|
||||
onModeChange={(m: string) => {
|
||||
setPermissionMode(m);
|
||||
localStorage.setItem('acp_permission_mode', m);
|
||||
}}
|
||||
/>
|
||||
<ModelSelectorPopover client={client} />
|
||||
</div>
|
||||
{entries.length > 0 && (
|
||||
@@ -861,7 +868,7 @@ export function ChatInterface({ client, agentId }: ChatInterfaceProps) {
|
||||
isLoading={isLoading}
|
||||
onInterrupt={handleCancel}
|
||||
disabled={!sessionReady}
|
||||
placeholder={sessionReady ? "给 Claude 发送消息…" : "等待会话..."}
|
||||
placeholder={sessionReady ? '给 Claude 发送消息…' : '等待会话...'}
|
||||
supportsImages={supportsImages}
|
||||
commands={availableCommands.length > 0 ? availableCommands : undefined}
|
||||
/>
|
||||
|
||||
@@ -1,15 +1,15 @@
|
||||
import { cn } from "../src/lib/utils";
|
||||
import { User, Bot, Wrench, Loader2 } from "lucide-react";
|
||||
import { cn } from '../src/lib/utils';
|
||||
import { User, Bot, Wrench, Loader2 } from 'lucide-react';
|
||||
|
||||
export interface ToolCall {
|
||||
id: string;
|
||||
title: string;
|
||||
status: "running" | "complete" | "error";
|
||||
status: 'running' | 'complete' | 'error';
|
||||
}
|
||||
|
||||
export interface ChatMessageData {
|
||||
id: string;
|
||||
role: "user" | "agent";
|
||||
role: 'user' | 'agent';
|
||||
content: string;
|
||||
toolCalls?: ToolCall[];
|
||||
isStreaming?: boolean;
|
||||
@@ -20,36 +20,27 @@ interface ChatMessageProps {
|
||||
}
|
||||
|
||||
export function ChatMessage({ message }: ChatMessageProps) {
|
||||
const isUser = message.role === "user";
|
||||
const isUser = message.role === 'user';
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
"flex gap-3 p-4 rounded-lg",
|
||||
isUser ? "bg-muted/50" : "bg-background"
|
||||
)}
|
||||
>
|
||||
<div className={cn('flex gap-3 p-4 rounded-lg', isUser ? 'bg-muted/50' : 'bg-background')}>
|
||||
<div
|
||||
className={cn(
|
||||
"flex-shrink-0 w-8 h-8 rounded-full flex items-center justify-center",
|
||||
isUser ? "bg-primary text-primary-foreground" : "bg-secondary"
|
||||
'flex-shrink-0 w-8 h-8 rounded-full flex items-center justify-center',
|
||||
isUser ? 'bg-primary text-primary-foreground' : 'bg-secondary',
|
||||
)}
|
||||
>
|
||||
{isUser ? <User className="w-4 h-4" /> : <Bot className="w-4 h-4" />}
|
||||
</div>
|
||||
<div className="flex-1 min-w-0 space-y-2">
|
||||
<div className="text-sm font-medium">
|
||||
{isUser ? "You" : "Agent"}
|
||||
</div>
|
||||
<div className="text-sm font-medium">{isUser ? 'You' : 'Agent'}</div>
|
||||
<div className="text-sm whitespace-pre-wrap break-words">
|
||||
{message.content}
|
||||
{message.isStreaming && (
|
||||
<span className="inline-block w-1.5 h-4 ml-0.5 bg-foreground animate-pulse" />
|
||||
)}
|
||||
{message.isStreaming && <span className="inline-block w-1.5 h-4 ml-0.5 bg-foreground animate-pulse" />}
|
||||
</div>
|
||||
{message.toolCalls && message.toolCalls.length > 0 && (
|
||||
<div className="space-y-1.5 pt-2">
|
||||
{message.toolCalls.map((tool) => (
|
||||
{message.toolCalls.map(tool => (
|
||||
<ToolCallDisplay key={tool.id} toolCall={tool} />
|
||||
))}
|
||||
</div>
|
||||
@@ -67,31 +58,34 @@ function ToolCallDisplay({ toolCall }: ToolCallDisplayProps) {
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
"flex items-center gap-2 text-xs px-2 py-1.5 rounded border",
|
||||
toolCall.status === "running" && "bg-yellow-50 dark:bg-yellow-900/20 border-yellow-200 dark:border-yellow-800",
|
||||
toolCall.status === "complete" && "bg-green-50 dark:bg-green-900/20 border-green-200 dark:border-green-800",
|
||||
toolCall.status === "error" && "bg-red-50 dark:bg-red-900/20 border-red-200 dark:border-red-800"
|
||||
'flex items-center gap-2 text-xs px-2 py-1.5 rounded border',
|
||||
toolCall.status === 'running' && 'bg-yellow-50 dark:bg-yellow-900/20 border-yellow-200 dark:border-yellow-800',
|
||||
toolCall.status === 'complete' && 'bg-green-50 dark:bg-green-900/20 border-green-200 dark:border-green-800',
|
||||
toolCall.status === 'error' && 'bg-red-50 dark:bg-red-900/20 border-red-200 dark:border-red-800',
|
||||
)}
|
||||
>
|
||||
{toolCall.status === "running" ? (
|
||||
{toolCall.status === 'running' ? (
|
||||
<Loader2 className="w-3 h-3 animate-spin text-yellow-600 dark:text-yellow-400" />
|
||||
) : (
|
||||
<Wrench className={cn(
|
||||
"w-3 h-3",
|
||||
toolCall.status === "complete" && "text-green-600 dark:text-green-400",
|
||||
toolCall.status === "error" && "text-red-600 dark:text-red-400"
|
||||
)} />
|
||||
<Wrench
|
||||
className={cn(
|
||||
'w-3 h-3',
|
||||
toolCall.status === 'complete' && 'text-green-600 dark:text-green-400',
|
||||
toolCall.status === 'error' && 'text-red-600 dark:text-red-400',
|
||||
)}
|
||||
/>
|
||||
)}
|
||||
<span className="truncate">{toolCall.title}</span>
|
||||
<span className={cn(
|
||||
"ml-auto text-[10px] uppercase font-medium",
|
||||
toolCall.status === "running" && "text-yellow-600 dark:text-yellow-400",
|
||||
toolCall.status === "complete" && "text-green-600 dark:text-green-400",
|
||||
toolCall.status === "error" && "text-red-600 dark:text-red-400"
|
||||
)}>
|
||||
<span
|
||||
className={cn(
|
||||
'ml-auto text-[10px] uppercase font-medium',
|
||||
toolCall.status === 'running' && 'text-yellow-600 dark:text-yellow-400',
|
||||
toolCall.status === 'complete' && 'text-green-600 dark:text-green-400',
|
||||
toolCall.status === 'error' && 'text-red-600 dark:text-red-400',
|
||||
)}
|
||||
>
|
||||
{toolCall.status}
|
||||
</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,22 +1,22 @@
|
||||
import { useState, useEffect, useCallback, useMemo } from "react";
|
||||
import { Search, Clock, RefreshCw } from "lucide-react";
|
||||
import type { ACPClient } from "../src/acp/client";
|
||||
import type { AgentSessionInfo } from "../src/acp/types";
|
||||
import { Input } from "./ui/input";
|
||||
import { ScrollArea } from "./ui/scroll-area";
|
||||
import { Button } from "./ui/button";
|
||||
import { cn } from "../src/lib/utils";
|
||||
import { useState, useEffect, useCallback, useMemo } from 'react';
|
||||
import { Search, Clock, RefreshCw } from 'lucide-react';
|
||||
import type { ACPClient } from '../src/acp/client';
|
||||
import type { AgentSessionInfo } from '../src/acp/types';
|
||||
import { Input } from './ui/input';
|
||||
import { ScrollArea } from './ui/scroll-area';
|
||||
import { Button } from './ui/button';
|
||||
import { cn } from '../src/lib/utils';
|
||||
|
||||
// Reference: Zed's TimeBucket in thread_history.rs
|
||||
type TimeBucket = "today" | "yesterday" | "thisWeek" | "pastWeek" | "all";
|
||||
type TimeBucket = 'today' | 'yesterday' | 'thisWeek' | 'pastWeek' | 'all';
|
||||
|
||||
// Reference: Zed's Display impl for TimeBucket
|
||||
const BUCKET_LABELS: Record<TimeBucket, string> = {
|
||||
today: "Today",
|
||||
yesterday: "Yesterday",
|
||||
thisWeek: "This Week",
|
||||
pastWeek: "Past Week",
|
||||
all: "All", // Zed uses "All", not "Older"
|
||||
today: 'Today',
|
||||
yesterday: 'Yesterday',
|
||||
thisWeek: 'This Week',
|
||||
pastWeek: 'Past Week',
|
||||
all: 'All', // Zed uses "All", not "Older"
|
||||
};
|
||||
|
||||
// Reference: Zed's TimeBucket::from_dates (line 1028-1051)
|
||||
@@ -29,14 +29,14 @@ function getTimeBucket(date: Date): TimeBucket {
|
||||
|
||||
const entryDate = new Date(date.getFullYear(), date.getMonth(), date.getDate());
|
||||
|
||||
if (entryDate.getTime() === today.getTime()) return "today";
|
||||
if (entryDate.getTime() === yesterday.getTime()) return "yesterday";
|
||||
if (entryDate.getTime() === today.getTime()) return 'today';
|
||||
if (entryDate.getTime() === yesterday.getTime()) return 'yesterday';
|
||||
|
||||
// This week: same ISO week AND year
|
||||
const todayIsoWeek = getISOWeekYear(today);
|
||||
const entryIsoWeek = getISOWeekYear(entryDate);
|
||||
if (todayIsoWeek.year === entryIsoWeek.year && todayIsoWeek.week === entryIsoWeek.week) {
|
||||
return "thisWeek";
|
||||
return 'thisWeek';
|
||||
}
|
||||
|
||||
// Past week: (reference - 7days).iso_week()
|
||||
@@ -44,10 +44,10 @@ function getTimeBucket(date: Date): TimeBucket {
|
||||
lastWeekDate.setDate(lastWeekDate.getDate() - 7);
|
||||
const lastWeekIsoWeek = getISOWeekYear(lastWeekDate);
|
||||
if (lastWeekIsoWeek.year === entryIsoWeek.year && lastWeekIsoWeek.week === entryIsoWeek.week) {
|
||||
return "pastWeek";
|
||||
return 'pastWeek';
|
||||
}
|
||||
|
||||
return "all";
|
||||
return 'all';
|
||||
}
|
||||
|
||||
// Returns ISO week number AND ISO week year (important for year boundaries)
|
||||
@@ -57,13 +57,13 @@ function getISOWeekYear(date: Date): { week: number; year: number } {
|
||||
d.setUTCDate(d.getUTCDate() + 4 - dayNum);
|
||||
const yearStart = new Date(Date.UTC(d.getUTCFullYear(), 0, 1));
|
||||
const week = Math.ceil(((d.getTime() - yearStart.getTime()) / 86400000 + 1) / 7);
|
||||
return { week, year: d.getUTCFullYear() }; // ISO week year, not calendar year
|
||||
return { week, year: d.getUTCFullYear() }; // ISO week year, not calendar year
|
||||
}
|
||||
|
||||
// Reference: Zed's formatted_time in HistoryEntryElement (line 904-921)
|
||||
// Exact format: Xd, Xh ago, Xm ago, Just now, Unknown
|
||||
function formatRelativeTime(date: Date | null): string {
|
||||
if (!date) return "Unknown"; // Zed uses "Unknown" for missing updatedAt
|
||||
if (!date) return 'Unknown'; // Zed uses "Unknown" for missing updatedAt
|
||||
|
||||
const now = new Date();
|
||||
const diffMs = now.getTime() - date.getTime();
|
||||
@@ -74,7 +74,7 @@ function formatRelativeTime(date: Date | null): string {
|
||||
if (diffDays > 0) return `${diffDays}d`;
|
||||
if (diffHours > 0) return `${diffHours}h ago`;
|
||||
if (diffMinutes > 0) return `${diffMinutes}m ago`;
|
||||
return "Just now";
|
||||
return 'Just now';
|
||||
}
|
||||
|
||||
interface ThreadHistoryProps {
|
||||
@@ -90,7 +90,7 @@ interface GroupedSessions {
|
||||
|
||||
export function ThreadHistory({ client, onSelectSession }: ThreadHistoryProps) {
|
||||
const [sessions, setSessions] = useState<AgentSessionInfo[]>([]);
|
||||
const [searchQuery, setSearchQuery] = useState("");
|
||||
const [searchQuery, setSearchQuery] = useState('');
|
||||
// Start with isLoading=true to prevent flash of "no threads" message
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
@@ -103,7 +103,7 @@ export function ThreadHistory({ client, onSelectSession }: ThreadHistoryProps) {
|
||||
|
||||
const loadSessions = useCallback(async () => {
|
||||
if (!client.supportsSessionList) {
|
||||
setError("Session list not supported by this agent");
|
||||
setError('Session list not supported by this agent');
|
||||
setIsLoading(false);
|
||||
return;
|
||||
}
|
||||
@@ -139,7 +139,7 @@ export function ThreadHistory({ client, onSelectSession }: ThreadHistoryProps) {
|
||||
if (searchQuery.trim()) {
|
||||
const query = searchQuery.toLowerCase();
|
||||
filtered = sessions.filter(
|
||||
(s) => s.title?.toLowerCase().includes(query) || s.sessionId.toLowerCase().includes(query)
|
||||
s => s.title?.toLowerCase().includes(query) || s.sessionId.toLowerCase().includes(query),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -148,7 +148,7 @@ export function ThreadHistory({ client, onSelectSession }: ThreadHistoryProps) {
|
||||
const sorted = [...filtered].sort((a, b) => {
|
||||
const dateA = a.updatedAt ? new Date(a.updatedAt).getTime() : 0;
|
||||
const dateB = b.updatedAt ? new Date(b.updatedAt).getTime() : 0;
|
||||
return dateB - dateA; // Descending
|
||||
return dateB - dateA; // Descending
|
||||
});
|
||||
|
||||
// Group by time bucket (preserving sort order within each bucket)
|
||||
@@ -161,10 +161,8 @@ export function ThreadHistory({ client, onSelectSession }: ThreadHistoryProps) {
|
||||
}
|
||||
|
||||
// Return in chronological bucket order
|
||||
const bucketOrder: TimeBucket[] = ["today", "yesterday", "thisWeek", "pastWeek", "all"];
|
||||
return bucketOrder
|
||||
.filter((b) => groups.has(b))
|
||||
.map((bucket) => ({ bucket, sessions: groups.get(bucket)! }));
|
||||
const bucketOrder: TimeBucket[] = ['today', 'yesterday', 'thisWeek', 'pastWeek', 'all'];
|
||||
return bucketOrder.filter(b => groups.has(b)).map(bucket => ({ bucket, sessions: groups.get(bucket)! }));
|
||||
}, [sessions, searchQuery]);
|
||||
|
||||
const handleSelectSession = useCallback(
|
||||
@@ -179,7 +177,7 @@ export function ThreadHistory({ client, onSelectSession }: ThreadHistoryProps) {
|
||||
setLoadingSessionId(null);
|
||||
}
|
||||
},
|
||||
[onSelectSession, loadingSessionId]
|
||||
[onSelectSession, loadingSessionId],
|
||||
);
|
||||
|
||||
if (!supportsHistory) {
|
||||
@@ -191,7 +189,7 @@ export function ThreadHistory({ client, onSelectSession }: ThreadHistoryProps) {
|
||||
);
|
||||
}
|
||||
|
||||
const flatItems = groupedSessions.flatMap((g) => g.sessions);
|
||||
const flatItems = groupedSessions.flatMap(g => g.sessions);
|
||||
|
||||
return (
|
||||
<div className="flex flex-col h-full">
|
||||
@@ -201,25 +199,17 @@ export function ThreadHistory({ client, onSelectSession }: ThreadHistoryProps) {
|
||||
<Input
|
||||
placeholder="Search threads..."
|
||||
value={searchQuery}
|
||||
onChange={(e) => setSearchQuery(e.target.value)}
|
||||
onChange={e => setSearchQuery(e.target.value)}
|
||||
className="h-8 border-0 focus-visible:ring-0 shadow-none"
|
||||
/>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={loadSessions}
|
||||
disabled={isLoading}
|
||||
className="shrink-0"
|
||||
>
|
||||
<RefreshCw className={cn("h-4 w-4", isLoading && "animate-spin")} />
|
||||
<Button variant="ghost" size="sm" onClick={loadSessions} disabled={isLoading} className="shrink-0">
|
||||
<RefreshCw className={cn('h-4 w-4', isLoading && 'animate-spin')} />
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{/* Session list */}
|
||||
<ScrollArea className="flex-1 min-h-0">
|
||||
{error && (
|
||||
<div className="p-4 text-center text-destructive text-sm">{error}</div>
|
||||
)}
|
||||
{error && <div className="p-4 text-center text-destructive text-sm">{error}</div>}
|
||||
|
||||
{!error && isLoading && sessions.length === 0 && (
|
||||
<div className="flex flex-col items-center justify-center h-full p-8 text-center">
|
||||
@@ -230,17 +220,13 @@ export function ThreadHistory({ client, onSelectSession }: ThreadHistoryProps) {
|
||||
|
||||
{!error && !isLoading && sessions.length === 0 && (
|
||||
<div className="flex flex-col items-center justify-center h-full p-8 text-center">
|
||||
<p className="text-muted-foreground text-sm">
|
||||
You don't have any past threads yet.
|
||||
</p>
|
||||
<p className="text-muted-foreground text-sm">You don't have any past threads yet.</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{!error && sessions.length > 0 && groupedSessions.length === 0 && (
|
||||
<div className="flex flex-col items-center justify-center h-full p-8 text-center">
|
||||
<p className="text-muted-foreground text-sm">
|
||||
No threads match your search.
|
||||
</p>
|
||||
<p className="text-muted-foreground text-sm">No threads match your search.</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
@@ -249,14 +235,12 @@ export function ThreadHistory({ client, onSelectSession }: ThreadHistoryProps) {
|
||||
{groupedSessions.map((group, groupIndex) => (
|
||||
<div key={group.bucket}>
|
||||
{/* Bucket separator - Reference: Zed's BucketSeparator */}
|
||||
<div className={cn("px-2 pb-1", groupIndex > 0 && "pt-3")}>
|
||||
<span className="text-xs text-muted-foreground font-medium">
|
||||
{BUCKET_LABELS[group.bucket]}
|
||||
</span>
|
||||
<div className={cn('px-2 pb-1', groupIndex > 0 && 'pt-3')}>
|
||||
<span className="text-xs text-muted-foreground font-medium">{BUCKET_LABELS[group.bucket]}</span>
|
||||
</div>
|
||||
|
||||
{/* Session entries */}
|
||||
{group.sessions.map((session) => {
|
||||
{group.sessions.map(session => {
|
||||
const globalIdx = flatItems.indexOf(session);
|
||||
const isSelected = globalIdx === selectedIndex;
|
||||
const isLoadingThis = loadingSessionId === session.sessionId;
|
||||
@@ -273,23 +257,19 @@ export function ThreadHistory({ client, onSelectSession }: ThreadHistoryProps) {
|
||||
}}
|
||||
className={cn(
|
||||
// min-w-0 is required for truncate to work in flex containers
|
||||
"w-full min-w-0 flex items-center gap-2 px-3 py-2 rounded-md text-left transition-colors",
|
||||
"hover:bg-accent",
|
||||
isSelected && "bg-accent",
|
||||
isAnyLoading && !isLoadingThis && "opacity-50 cursor-not-allowed",
|
||||
isLoadingThis && "bg-accent"
|
||||
'w-full min-w-0 flex items-center gap-2 px-3 py-2 rounded-md text-left transition-colors',
|
||||
'hover:bg-accent',
|
||||
isSelected && 'bg-accent',
|
||||
isAnyLoading && !isLoadingThis && 'opacity-50 cursor-not-allowed',
|
||||
isLoadingThis && 'bg-accent',
|
||||
)}
|
||||
>
|
||||
{/* min-w-0 + truncate ensures long titles are clipped with ellipsis */}
|
||||
<span className="text-sm truncate flex-1 min-w-0">
|
||||
{session.title && session.title.trim() ? session.title : "New Thread"}
|
||||
{session.title && session.title.trim() ? session.title : 'New Thread'}
|
||||
</span>
|
||||
<span className="text-xs text-muted-foreground shrink-0 whitespace-nowrap">
|
||||
{isLoadingThis ? (
|
||||
<RefreshCw className="h-3 w-3 animate-spin" />
|
||||
) : (
|
||||
formatRelativeTime(date)
|
||||
)}
|
||||
{isLoadingThis ? <RefreshCw className="h-3 w-3 animate-spin" /> : formatRelativeTime(date)}
|
||||
</span>
|
||||
</button>
|
||||
);
|
||||
@@ -301,4 +281,3 @@ export function ThreadHistory({ client, onSelectSession }: ThreadHistoryProps) {
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,15 +1,9 @@
|
||||
"use client";
|
||||
'use client';
|
||||
|
||||
import { Button } from "../ui/button";
|
||||
import { cn } from "../../src/lib/utils";
|
||||
import { CheckIcon, CopyIcon } from "lucide-react";
|
||||
import {
|
||||
type ComponentProps,
|
||||
createContext,
|
||||
type HTMLAttributes,
|
||||
useContext,
|
||||
useState,
|
||||
} from "react";
|
||||
import { Button } from '../ui/button';
|
||||
import { cn } from '../../src/lib/utils';
|
||||
import { CheckIcon, CopyIcon } from 'lucide-react';
|
||||
import { type ComponentProps, createContext, type HTMLAttributes, useContext, useState } from 'react';
|
||||
|
||||
type CodeBlockProps = HTMLAttributes<HTMLDivElement> & {
|
||||
code: string;
|
||||
@@ -22,7 +16,7 @@ type CodeBlockContextType = {
|
||||
};
|
||||
|
||||
const CodeBlockContext = createContext<CodeBlockContextType>({
|
||||
code: "",
|
||||
code: '',
|
||||
});
|
||||
|
||||
export const CodeBlock = ({
|
||||
@@ -33,14 +27,14 @@ export const CodeBlock = ({
|
||||
children,
|
||||
...props
|
||||
}: CodeBlockProps) => {
|
||||
const lines = code.split("\n");
|
||||
const lines = code.split('\n');
|
||||
|
||||
return (
|
||||
<CodeBlockContext.Provider value={{ code }}>
|
||||
<div
|
||||
className={cn(
|
||||
"group relative w-full overflow-hidden rounded-md border bg-background text-foreground",
|
||||
className
|
||||
'group relative w-full overflow-hidden rounded-md border bg-background text-foreground',
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
@@ -57,7 +51,7 @@ export const CodeBlock = ({
|
||||
)}
|
||||
<td className="p-0">
|
||||
<pre className="m-0 p-0 text-sm whitespace-pre font-mono">
|
||||
<code className="text-sm">{line || "\u00A0"}</code>
|
||||
<code className="text-sm">{line || '\u00A0'}</code>
|
||||
</pre>
|
||||
</td>
|
||||
</tr>
|
||||
@@ -65,11 +59,7 @@ export const CodeBlock = ({
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
{children && (
|
||||
<div className="absolute top-2 right-2 flex items-center gap-2">
|
||||
{children}
|
||||
</div>
|
||||
)}
|
||||
{children && <div className="absolute top-2 right-2 flex items-center gap-2">{children}</div>}
|
||||
</div>
|
||||
</div>
|
||||
</CodeBlockContext.Provider>
|
||||
@@ -94,8 +84,8 @@ export const CodeBlockCopyButton = ({
|
||||
const { code } = useContext(CodeBlockContext);
|
||||
|
||||
const copyToClipboard = async () => {
|
||||
if (typeof window === "undefined" || !navigator?.clipboard?.writeText) {
|
||||
onError?.(new Error("Clipboard API not available"));
|
||||
if (typeof window === 'undefined' || !navigator?.clipboard?.writeText) {
|
||||
onError?.(new Error('Clipboard API not available'));
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -112,13 +102,7 @@ export const CodeBlockCopyButton = ({
|
||||
const Icon = isCopied ? CheckIcon : CopyIcon;
|
||||
|
||||
return (
|
||||
<Button
|
||||
className={cn("shrink-0", className)}
|
||||
onClick={copyToClipboard}
|
||||
size="icon"
|
||||
variant="ghost"
|
||||
{...props}
|
||||
>
|
||||
<Button className={cn('shrink-0', className)} onClick={copyToClipboard} size="icon" variant="ghost" {...props}>
|
||||
{children ?? <Icon size={14} />}
|
||||
</Button>
|
||||
);
|
||||
|
||||
@@ -1,17 +1,17 @@
|
||||
"use client";
|
||||
'use client';
|
||||
|
||||
import { Button } from "../ui/button";
|
||||
import { cn } from "../../src/lib/utils";
|
||||
import { ArrowDownIcon, UserIcon } from "lucide-react";
|
||||
import type { ComponentProps } from "react";
|
||||
import { useCallback } from "react";
|
||||
import { StickToBottom, useStickToBottomContext } from "use-stick-to-bottom";
|
||||
import { Button } from '../ui/button';
|
||||
import { cn } from '../../src/lib/utils';
|
||||
import { ArrowDownIcon, UserIcon } from 'lucide-react';
|
||||
import type { ComponentProps } from 'react';
|
||||
import { useCallback } from 'react';
|
||||
import { StickToBottom, useStickToBottomContext } from 'use-stick-to-bottom';
|
||||
|
||||
export type ConversationProps = ComponentProps<typeof StickToBottom>;
|
||||
|
||||
export const Conversation = ({ className, ...props }: ConversationProps) => (
|
||||
<StickToBottom
|
||||
className={cn("relative flex-1 overflow-y-hidden overflow-x-hidden", className)}
|
||||
className={cn('relative flex-1 overflow-y-hidden overflow-x-hidden', className)}
|
||||
initial="smooth"
|
||||
resize="smooth"
|
||||
role="log"
|
||||
@@ -19,21 +19,16 @@ export const Conversation = ({ className, ...props }: ConversationProps) => (
|
||||
/>
|
||||
);
|
||||
|
||||
export type ConversationContentProps = ComponentProps<
|
||||
typeof StickToBottom.Content
|
||||
>;
|
||||
export type ConversationContentProps = ComponentProps<typeof StickToBottom.Content>;
|
||||
|
||||
export const ConversationContent = ({
|
||||
className,
|
||||
...props
|
||||
}: ConversationContentProps) => (
|
||||
export const ConversationContent = ({ className, ...props }: ConversationContentProps) => (
|
||||
<StickToBottom.Content
|
||||
className={cn("mx-auto flex max-w-3xl flex-col gap-2 px-4 py-8 sm:px-8 sm:py-12 min-w-0", className)}
|
||||
className={cn('mx-auto flex max-w-3xl flex-col gap-2 px-4 py-8 sm:px-8 sm:py-12 min-w-0', className)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
|
||||
export type ConversationEmptyStateProps = ComponentProps<"div"> & {
|
||||
export type ConversationEmptyStateProps = ComponentProps<'div'> & {
|
||||
title?: string;
|
||||
description?: string;
|
||||
icon?: React.ReactNode;
|
||||
@@ -41,17 +36,14 @@ export type ConversationEmptyStateProps = ComponentProps<"div"> & {
|
||||
|
||||
export const ConversationEmptyState = ({
|
||||
className,
|
||||
title = "No messages yet",
|
||||
description = "Start a conversation to see messages here",
|
||||
title = 'No messages yet',
|
||||
description = 'Start a conversation to see messages here',
|
||||
icon,
|
||||
children,
|
||||
...props
|
||||
}: ConversationEmptyStateProps) => (
|
||||
<div
|
||||
className={cn(
|
||||
"flex size-full flex-col items-center justify-center gap-4 p-8 text-center",
|
||||
className
|
||||
)}
|
||||
className={cn('flex size-full flex-col items-center justify-center gap-4 p-8 text-center', className)}
|
||||
{...props}
|
||||
>
|
||||
{children ?? (
|
||||
@@ -59,9 +51,7 @@ export const ConversationEmptyState = ({
|
||||
{icon && <div className="text-text-muted">{icon}</div>}
|
||||
<div className="space-y-2">
|
||||
<h3 className="font-semibold text-base font-display text-text-primary">{title}</h3>
|
||||
{description && (
|
||||
<p className="text-text-muted text-sm leading-relaxed max-w-xs">{description}</p>
|
||||
)}
|
||||
{description && <p className="text-text-muted text-sm leading-relaxed max-w-xs">{description}</p>}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
@@ -76,10 +66,7 @@ export type ConversationScrollButtonProps = ComponentProps<typeof Button>;
|
||||
* When used standalone, it handles its own visibility based on isAtBottom.
|
||||
* When used in ConversationScrollButtons, the container manages visibility.
|
||||
*/
|
||||
export const ConversationScrollButton = ({
|
||||
className,
|
||||
...props
|
||||
}: ConversationScrollButtonProps) => {
|
||||
export const ConversationScrollButton = ({ className, ...props }: ConversationScrollButtonProps) => {
|
||||
const { scrollToBottom } = useStickToBottomContext();
|
||||
|
||||
const handleScrollToBottom = useCallback(() => {
|
||||
@@ -88,10 +75,7 @@ export const ConversationScrollButton = ({
|
||||
|
||||
return (
|
||||
<Button
|
||||
className={cn(
|
||||
"rounded-full",
|
||||
className
|
||||
)}
|
||||
className={cn('rounded-full', className)}
|
||||
onClick={handleScrollToBottom}
|
||||
size="icon"
|
||||
type="button"
|
||||
@@ -108,7 +92,7 @@ export const ConversationScrollButton = ({
|
||||
* Data attribute used to mark the last user message element.
|
||||
* ChatInterface adds this attribute to the last user message for scroll targeting.
|
||||
*/
|
||||
export const LAST_USER_MESSAGE_ATTR = "data-last-user-message";
|
||||
export const LAST_USER_MESSAGE_ATTR = 'data-last-user-message';
|
||||
|
||||
export type ConversationScrollToLastUserMessageButtonProps = ComponentProps<typeof Button>;
|
||||
|
||||
@@ -124,16 +108,13 @@ export const ConversationScrollToLastUserMessageButton = ({
|
||||
// Find the last user message element by data attribute
|
||||
const lastUserMessage = document.querySelector(`[${LAST_USER_MESSAGE_ATTR}="true"]`);
|
||||
if (lastUserMessage) {
|
||||
lastUserMessage.scrollIntoView({ behavior: "smooth", block: "start" });
|
||||
lastUserMessage.scrollIntoView({ behavior: 'smooth', block: 'start' });
|
||||
}
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<Button
|
||||
className={cn(
|
||||
"rounded-full",
|
||||
className
|
||||
)}
|
||||
className={cn('rounded-full', className)}
|
||||
onClick={handleScrollToLastUserMessage}
|
||||
size="icon"
|
||||
type="button"
|
||||
@@ -146,7 +127,7 @@ export const ConversationScrollToLastUserMessageButton = ({
|
||||
);
|
||||
};
|
||||
|
||||
export type ConversationScrollButtonsProps = ComponentProps<"div"> & {
|
||||
export type ConversationScrollButtonsProps = ComponentProps<'div'> & {
|
||||
/** Whether there are user messages to scroll to */
|
||||
hasUserMessages?: boolean;
|
||||
};
|
||||
@@ -166,16 +147,9 @@ export const ConversationScrollButtons = ({
|
||||
if (isAtBottom) return null;
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
"absolute bottom-4 left-1/2 -translate-x-1/2 flex gap-2",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<div className={cn('absolute bottom-4 left-1/2 -translate-x-1/2 flex gap-2', className)} {...props}>
|
||||
{hasUserMessages && <ConversationScrollToLastUserMessageButton />}
|
||||
<ConversationScrollButton />
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
|
||||
@@ -1,9 +1,8 @@
|
||||
export * from "./code-block";
|
||||
export * from "./conversation";
|
||||
export * from "./message";
|
||||
export * from "./permission-request";
|
||||
export * from "./prompt-input";
|
||||
export * from "./reasoning";
|
||||
export * from "./shimmer";
|
||||
export * from "./tool";
|
||||
|
||||
export * from './code-block'
|
||||
export * from './conversation'
|
||||
export * from './message'
|
||||
export * from './permission-request'
|
||||
export * from './prompt-input'
|
||||
export * from './reasoning'
|
||||
export * from './shimmer'
|
||||
export * from './tool'
|
||||
|
||||
@@ -1,39 +1,26 @@
|
||||
"use client";
|
||||
'use client';
|
||||
|
||||
import { Button } from "../ui/button";
|
||||
import {
|
||||
ButtonGroup,
|
||||
ButtonGroupText,
|
||||
} from "../ui/button-group";
|
||||
import {
|
||||
Tooltip,
|
||||
TooltipContent,
|
||||
TooltipProvider,
|
||||
TooltipTrigger,
|
||||
} from "../ui/tooltip";
|
||||
import { cn } from "../../src/lib/utils";
|
||||
import type { FileUIPart, UIMessage } from "ai";
|
||||
import {
|
||||
ChevronLeftIcon,
|
||||
ChevronRightIcon,
|
||||
PaperclipIcon,
|
||||
XIcon,
|
||||
} from "lucide-react";
|
||||
import type { ComponentProps, HTMLAttributes, ReactElement } from "react";
|
||||
import { createContext, lazy, memo, Suspense, useContext, useEffect, useState } from "react";
|
||||
import { Button } from '../ui/button';
|
||||
import { ButtonGroup, ButtonGroupText } from '../ui/button-group';
|
||||
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '../ui/tooltip';
|
||||
import { cn } from '../../src/lib/utils';
|
||||
import type { FileUIPart, UIMessage } from 'ai';
|
||||
import { ChevronLeftIcon, ChevronRightIcon, PaperclipIcon, XIcon } from 'lucide-react';
|
||||
import type { ComponentProps, HTMLAttributes, ReactElement } from 'react';
|
||||
import { createContext, lazy, memo, Suspense, useContext, useEffect, useState } from 'react';
|
||||
|
||||
const LazyStreamdown = lazy(() => import("streamdown").then((m) => ({ default: m.Streamdown })));
|
||||
const LazyStreamdown = lazy(() => import('streamdown').then(m => ({ default: m.Streamdown })));
|
||||
|
||||
export type MessageProps = HTMLAttributes<HTMLDivElement> & {
|
||||
from: UIMessage["role"];
|
||||
from: UIMessage['role'];
|
||||
};
|
||||
|
||||
export const Message = ({ className, from, ...props }: MessageProps) => (
|
||||
<div
|
||||
className={cn(
|
||||
"group flex w-full max-w-[85%] min-w-0 flex-col gap-2",
|
||||
from === "user" ? "is-user ml-auto justify-end" : "is-assistant",
|
||||
className
|
||||
'group flex w-full max-w-[85%] min-w-0 flex-col gap-2',
|
||||
from === 'user' ? 'is-user ml-auto justify-end' : 'is-assistant',
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
@@ -41,33 +28,25 @@ export const Message = ({ className, from, ...props }: MessageProps) => (
|
||||
|
||||
export type MessageContentProps = HTMLAttributes<HTMLDivElement>;
|
||||
|
||||
export const MessageContent = ({
|
||||
children,
|
||||
className,
|
||||
...props
|
||||
}: MessageContentProps) => (
|
||||
export const MessageContent = ({ children, className, ...props }: MessageContentProps) => (
|
||||
<div
|
||||
className={cn(
|
||||
"is-user:dark flex w-fit max-w-full flex-col gap-2 overflow-hidden text-sm break-words",
|
||||
"group-[.is-user]:ml-auto group-[.is-user]:rounded-lg group-[.is-user]:bg-secondary group-[.is-user]:px-4 group-[.is-user]:py-3 group-[.is-user]:text-foreground",
|
||||
"group-[.is-assistant]:text-foreground",
|
||||
className
|
||||
'is-user:dark flex w-fit max-w-full flex-col gap-2 overflow-hidden text-sm break-words',
|
||||
'group-[.is-user]:ml-auto group-[.is-user]:rounded-lg group-[.is-user]:bg-secondary group-[.is-user]:px-4 group-[.is-user]:py-3 group-[.is-user]:text-foreground',
|
||||
'group-[.is-assistant]:text-foreground',
|
||||
className,
|
||||
)}
|
||||
style={{ overflowWrap: "anywhere" }}
|
||||
style={{ overflowWrap: 'anywhere' }}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
</div>
|
||||
);
|
||||
|
||||
export type MessageActionsProps = ComponentProps<"div">;
|
||||
export type MessageActionsProps = ComponentProps<'div'>;
|
||||
|
||||
export const MessageActions = ({
|
||||
className,
|
||||
children,
|
||||
...props
|
||||
}: MessageActionsProps) => (
|
||||
<div className={cn("flex items-center gap-1", className)} {...props}>
|
||||
export const MessageActions = ({ className, children, ...props }: MessageActionsProps) => (
|
||||
<div className={cn('flex items-center gap-1', className)} {...props}>
|
||||
{children}
|
||||
</div>
|
||||
);
|
||||
@@ -81,8 +60,8 @@ export const MessageAction = ({
|
||||
tooltip,
|
||||
children,
|
||||
label,
|
||||
variant = "ghost",
|
||||
size = "icon-sm",
|
||||
variant = 'ghost',
|
||||
size = 'icon-sm',
|
||||
...props
|
||||
}: MessageActionProps) => {
|
||||
const button = (
|
||||
@@ -117,17 +96,13 @@ type MessageBranchContextType = {
|
||||
setBranches: (branches: ReactElement[]) => void;
|
||||
};
|
||||
|
||||
const MessageBranchContext = createContext<MessageBranchContextType | null>(
|
||||
null
|
||||
);
|
||||
const MessageBranchContext = createContext<MessageBranchContextType | null>(null);
|
||||
|
||||
const useMessageBranch = () => {
|
||||
const context = useContext(MessageBranchContext);
|
||||
|
||||
if (!context) {
|
||||
throw new Error(
|
||||
"MessageBranch components must be used within MessageBranch"
|
||||
);
|
||||
throw new Error('MessageBranch components must be used within MessageBranch');
|
||||
}
|
||||
|
||||
return context;
|
||||
@@ -138,12 +113,7 @@ export type MessageBranchProps = HTMLAttributes<HTMLDivElement> & {
|
||||
onBranchChange?: (branchIndex: number) => void;
|
||||
};
|
||||
|
||||
export const MessageBranch = ({
|
||||
defaultBranch = 0,
|
||||
onBranchChange,
|
||||
className,
|
||||
...props
|
||||
}: MessageBranchProps) => {
|
||||
export const MessageBranch = ({ defaultBranch = 0, onBranchChange, className, ...props }: MessageBranchProps) => {
|
||||
const [currentBranch, setCurrentBranch] = useState(defaultBranch);
|
||||
const [branches, setBranches] = useState<ReactElement[]>([]);
|
||||
|
||||
@@ -153,14 +123,12 @@ export const MessageBranch = ({
|
||||
};
|
||||
|
||||
const goToPrevious = () => {
|
||||
const newBranch =
|
||||
currentBranch > 0 ? currentBranch - 1 : branches.length - 1;
|
||||
const newBranch = currentBranch > 0 ? currentBranch - 1 : branches.length - 1;
|
||||
handleBranchChange(newBranch);
|
||||
};
|
||||
|
||||
const goToNext = () => {
|
||||
const newBranch =
|
||||
currentBranch < branches.length - 1 ? currentBranch + 1 : 0;
|
||||
const newBranch = currentBranch < branches.length - 1 ? currentBranch + 1 : 0;
|
||||
handleBranchChange(newBranch);
|
||||
};
|
||||
|
||||
@@ -175,20 +143,14 @@ export const MessageBranch = ({
|
||||
|
||||
return (
|
||||
<MessageBranchContext.Provider value={contextValue}>
|
||||
<div
|
||||
className={cn("grid w-full gap-2 [&>div]:pb-0", className)}
|
||||
{...props}
|
||||
/>
|
||||
<div className={cn('grid w-full gap-2 [&>div]:pb-0', className)} {...props} />
|
||||
</MessageBranchContext.Provider>
|
||||
);
|
||||
};
|
||||
|
||||
export type MessageBranchContentProps = HTMLAttributes<HTMLDivElement>;
|
||||
|
||||
export const MessageBranchContent = ({
|
||||
children,
|
||||
...props
|
||||
}: MessageBranchContentProps) => {
|
||||
export const MessageBranchContent = ({ children, ...props }: MessageBranchContentProps) => {
|
||||
const { currentBranch, setBranches, branches } = useMessageBranch();
|
||||
const childrenArray = Array.isArray(children) ? children : [children];
|
||||
|
||||
@@ -201,10 +163,7 @@ export const MessageBranchContent = ({
|
||||
|
||||
return childrenArray.map((branch, index) => (
|
||||
<div
|
||||
className={cn(
|
||||
"grid gap-2 overflow-hidden [&>div]:pb-0",
|
||||
index === currentBranch ? "block" : "hidden"
|
||||
)}
|
||||
className={cn('grid gap-2 overflow-hidden [&>div]:pb-0', index === currentBranch ? 'block' : 'hidden')}
|
||||
key={branch.key}
|
||||
{...props}
|
||||
>
|
||||
@@ -214,14 +173,10 @@ export const MessageBranchContent = ({
|
||||
};
|
||||
|
||||
export type MessageBranchSelectorProps = HTMLAttributes<HTMLDivElement> & {
|
||||
from: UIMessage["role"];
|
||||
from: UIMessage['role'];
|
||||
};
|
||||
|
||||
export const MessageBranchSelector = ({
|
||||
className,
|
||||
from,
|
||||
...props
|
||||
}: MessageBranchSelectorProps) => {
|
||||
export const MessageBranchSelector = ({ className, from, ...props }: MessageBranchSelectorProps) => {
|
||||
const { totalBranches } = useMessageBranch();
|
||||
|
||||
// Don't render if there's only one branch
|
||||
@@ -240,10 +195,7 @@ export const MessageBranchSelector = ({
|
||||
|
||||
export type MessageBranchPreviousProps = ComponentProps<typeof Button>;
|
||||
|
||||
export const MessageBranchPrevious = ({
|
||||
children,
|
||||
...props
|
||||
}: MessageBranchPreviousProps) => {
|
||||
export const MessageBranchPrevious = ({ children, ...props }: MessageBranchPreviousProps) => {
|
||||
const { goToPrevious, totalBranches } = useMessageBranch();
|
||||
|
||||
return (
|
||||
@@ -263,11 +215,7 @@ export const MessageBranchPrevious = ({
|
||||
|
||||
export type MessageBranchNextProps = ComponentProps<typeof Button>;
|
||||
|
||||
export const MessageBranchNext = ({
|
||||
children,
|
||||
className,
|
||||
...props
|
||||
}: MessageBranchNextProps) => {
|
||||
export const MessageBranchNext = ({ children, className, ...props }: MessageBranchNextProps) => {
|
||||
const { goToNext, totalBranches } = useMessageBranch();
|
||||
|
||||
return (
|
||||
@@ -287,18 +235,12 @@ export const MessageBranchNext = ({
|
||||
|
||||
export type MessageBranchPageProps = HTMLAttributes<HTMLSpanElement>;
|
||||
|
||||
export const MessageBranchPage = ({
|
||||
className,
|
||||
...props
|
||||
}: MessageBranchPageProps) => {
|
||||
export const MessageBranchPage = ({ className, ...props }: MessageBranchPageProps) => {
|
||||
const { currentBranch, totalBranches } = useMessageBranch();
|
||||
|
||||
return (
|
||||
<ButtonGroupText
|
||||
className={cn(
|
||||
"border-none bg-transparent text-muted-foreground shadow-none",
|
||||
className
|
||||
)}
|
||||
className={cn('border-none bg-transparent text-muted-foreground shadow-none', className)}
|
||||
{...props}
|
||||
>
|
||||
{currentBranch + 1} of {totalBranches}
|
||||
@@ -309,22 +251,16 @@ export const MessageBranchPage = ({
|
||||
export type MessageResponseProps = {
|
||||
children?: string;
|
||||
className?: string;
|
||||
mode?: "static" | "streaming";
|
||||
mode?: 'static' | 'streaming';
|
||||
};
|
||||
|
||||
export const MessageResponse = memo(
|
||||
({ className, children, ...props }: MessageResponseProps) => (
|
||||
<Suspense
|
||||
fallback={
|
||||
<div className={cn("whitespace-pre-wrap break-words", className)}>
|
||||
{children}
|
||||
</div>
|
||||
}
|
||||
>
|
||||
<Suspense fallback={<div className={cn('whitespace-pre-wrap break-words', className)}>{children}</div>}>
|
||||
<LazyStreamdown
|
||||
className={cn(
|
||||
"size-full break-words [overflow-wrap:anywhere] [&>*:first-child]:mt-0 [&>*:last-child]:mb-0",
|
||||
className
|
||||
'size-full break-words [overflow-wrap:anywhere] [&>*:first-child]:mt-0 [&>*:last-child]:mb-0',
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
@@ -332,10 +268,10 @@ export const MessageResponse = memo(
|
||||
</LazyStreamdown>
|
||||
</Suspense>
|
||||
),
|
||||
(prevProps, nextProps) => prevProps.children === nextProps.children
|
||||
(prevProps, nextProps) => prevProps.children === nextProps.children,
|
||||
);
|
||||
|
||||
MessageResponse.displayName = "MessageResponse";
|
||||
MessageResponse.displayName = 'MessageResponse';
|
||||
|
||||
export type MessageAttachmentProps = HTMLAttributes<HTMLDivElement> & {
|
||||
data: FileUIPart;
|
||||
@@ -343,30 +279,18 @@ export type MessageAttachmentProps = HTMLAttributes<HTMLDivElement> & {
|
||||
onRemove?: () => void;
|
||||
};
|
||||
|
||||
export function MessageAttachment({
|
||||
data,
|
||||
className,
|
||||
onRemove,
|
||||
...props
|
||||
}: MessageAttachmentProps) {
|
||||
const filename = data.filename || "";
|
||||
const mediaType =
|
||||
data.mediaType?.startsWith("image/") && data.url ? "image" : "file";
|
||||
const isImage = mediaType === "image";
|
||||
const attachmentLabel = filename || (isImage ? "Image" : "Attachment");
|
||||
export function MessageAttachment({ data, className, onRemove, ...props }: MessageAttachmentProps) {
|
||||
const filename = data.filename || '';
|
||||
const mediaType = data.mediaType?.startsWith('image/') && data.url ? 'image' : 'file';
|
||||
const isImage = mediaType === 'image';
|
||||
const attachmentLabel = filename || (isImage ? 'Image' : 'Attachment');
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
"group relative size-24 overflow-hidden rounded-lg",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<div className={cn('group relative size-24 overflow-hidden rounded-lg', className)} {...props}>
|
||||
{isImage ? (
|
||||
<>
|
||||
<img
|
||||
alt={filename || "attachment"}
|
||||
alt={filename || 'attachment'}
|
||||
className="size-full object-cover"
|
||||
height={100}
|
||||
src={data.url}
|
||||
@@ -376,7 +300,7 @@ export function MessageAttachment({
|
||||
<Button
|
||||
aria-label="Remove attachment"
|
||||
className="absolute top-2 right-2 size-6 rounded-full bg-background/80 p-0 opacity-0 backdrop-blur-sm transition-opacity hover:bg-background group-hover:opacity-100 [&>svg]:size-3"
|
||||
onClick={(e) => {
|
||||
onClick={e => {
|
||||
e.stopPropagation();
|
||||
onRemove();
|
||||
}}
|
||||
@@ -404,7 +328,7 @@ export function MessageAttachment({
|
||||
<Button
|
||||
aria-label="Remove attachment"
|
||||
className="size-6 shrink-0 rounded-full p-0 opacity-0 transition-opacity hover:bg-accent group-hover:opacity-100 [&>svg]:size-3"
|
||||
onClick={(e) => {
|
||||
onClick={e => {
|
||||
e.stopPropagation();
|
||||
onRemove();
|
||||
}}
|
||||
@@ -421,45 +345,24 @@ export function MessageAttachment({
|
||||
);
|
||||
}
|
||||
|
||||
export type MessageAttachmentsProps = ComponentProps<"div">;
|
||||
export type MessageAttachmentsProps = ComponentProps<'div'>;
|
||||
|
||||
export function MessageAttachments({
|
||||
children,
|
||||
className,
|
||||
...props
|
||||
}: MessageAttachmentsProps) {
|
||||
export function MessageAttachments({ children, className, ...props }: MessageAttachmentsProps) {
|
||||
if (!children) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
"ml-auto flex w-fit flex-wrap items-start gap-2",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<div className={cn('ml-auto flex w-fit flex-wrap items-start gap-2', className)} {...props}>
|
||||
{children}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export type MessageToolbarProps = ComponentProps<"div">;
|
||||
export type MessageToolbarProps = ComponentProps<'div'>;
|
||||
|
||||
export const MessageToolbar = ({
|
||||
className,
|
||||
children,
|
||||
...props
|
||||
}: MessageToolbarProps) => (
|
||||
<div
|
||||
className={cn(
|
||||
"mt-4 flex w-full items-center justify-between gap-4",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
export const MessageToolbar = ({ className, children, ...props }: MessageToolbarProps) => (
|
||||
<div className={cn('mt-4 flex w-full items-center justify-between gap-4', className)} {...props}>
|
||||
{children}
|
||||
</div>
|
||||
);
|
||||
|
||||
|
||||
@@ -1,32 +1,32 @@
|
||||
"use client";
|
||||
'use client';
|
||||
|
||||
import { cn } from "../../src/lib/utils";
|
||||
import { Button } from "../ui/button";
|
||||
import { ShieldAlertIcon, CheckIcon, XIcon } from "lucide-react";
|
||||
import type { PermissionOption } from "../../src/acp/types";
|
||||
import { cn } from '../../src/lib/utils';
|
||||
import { Button } from '../ui/button';
|
||||
import { ShieldAlertIcon, CheckIcon, XIcon } from 'lucide-react';
|
||||
import type { PermissionOption } from '../../src/acp/types';
|
||||
|
||||
// Get button variant based on option kind
|
||||
function getButtonVariant(kind: PermissionOption["kind"]): "default" | "destructive" | "outline" | "secondary" {
|
||||
function getButtonVariant(kind: PermissionOption['kind']): 'default' | 'destructive' | 'outline' | 'secondary' {
|
||||
switch (kind) {
|
||||
case "allow_once":
|
||||
case "allow_always":
|
||||
return "default";
|
||||
case "reject_once":
|
||||
case "reject_always":
|
||||
return "destructive";
|
||||
case 'allow_once':
|
||||
case 'allow_always':
|
||||
return 'default';
|
||||
case 'reject_once':
|
||||
case 'reject_always':
|
||||
return 'destructive';
|
||||
default:
|
||||
return "outline";
|
||||
return 'outline';
|
||||
}
|
||||
}
|
||||
|
||||
// Get button icon based on option kind
|
||||
function getButtonIcon(kind: PermissionOption["kind"]) {
|
||||
function getButtonIcon(kind: PermissionOption['kind']) {
|
||||
switch (kind) {
|
||||
case "allow_once":
|
||||
case "allow_always":
|
||||
case 'allow_once':
|
||||
case 'allow_always':
|
||||
return <CheckIcon className="size-4" />;
|
||||
case "reject_once":
|
||||
case "reject_always":
|
||||
case 'reject_once':
|
||||
case 'reject_always':
|
||||
return <XIcon className="size-4" />;
|
||||
default:
|
||||
return null;
|
||||
@@ -37,7 +37,7 @@ function getButtonIcon(kind: PermissionOption["kind"]) {
|
||||
export interface ToolPermissionButtonsProps {
|
||||
requestId: string;
|
||||
options: PermissionOption[];
|
||||
onRespond: (requestId: string, optionId: string | null, optionKind: PermissionOption["kind"] | null) => void;
|
||||
onRespond: (requestId: string, optionId: string | null, optionKind: PermissionOption['kind'] | null) => void;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
@@ -47,15 +47,13 @@ export function ToolPermissionButtons({ requestId, options, onRespond, className
|
||||
};
|
||||
|
||||
return (
|
||||
<div className={cn("p-3 border-t border-warning-border/30 bg-warning-bg/50", className)}>
|
||||
<div className={cn('p-3 border-t border-warning-border/30 bg-warning-bg/50', className)}>
|
||||
<div className="flex items-center gap-2 mb-2">
|
||||
<ShieldAlertIcon className="size-4 text-warning-text" />
|
||||
<span className="text-xs font-medium text-warning-text">
|
||||
Permission Required
|
||||
</span>
|
||||
<span className="text-xs font-medium text-warning-text">Permission Required</span>
|
||||
</div>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{options.map((option) => (
|
||||
{options.map(option => (
|
||||
<Button
|
||||
key={option.optionId}
|
||||
variant={getButtonVariant(option.kind)}
|
||||
@@ -71,4 +69,3 @@ export function ToolPermissionButtons({ requestId, options, onRespond, className
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,16 +1,12 @@
|
||||
"use client";
|
||||
'use client';
|
||||
|
||||
import { useControllableState } from "@radix-ui/react-use-controllable-state";
|
||||
import {
|
||||
Collapsible,
|
||||
CollapsibleContent,
|
||||
CollapsibleTrigger,
|
||||
} from "../ui/collapsible";
|
||||
import { cn } from "../../src/lib/utils";
|
||||
import { BrainIcon, ChevronDownIcon } from "lucide-react";
|
||||
import type { ComponentProps, ReactNode } from "react";
|
||||
import { createContext, memo, useCallback, useContext, useEffect, useState } from "react";
|
||||
import { Shimmer } from "./shimmer";
|
||||
import { useControllableState } from '@radix-ui/react-use-controllable-state';
|
||||
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from '../ui/collapsible';
|
||||
import { cn } from '../../src/lib/utils';
|
||||
import { BrainIcon, ChevronDownIcon } from 'lucide-react';
|
||||
import type { ComponentProps, ReactNode } from 'react';
|
||||
import { createContext, memo, useCallback, useContext, useEffect, useState } from 'react';
|
||||
import { Shimmer } from './shimmer';
|
||||
|
||||
interface ReasoningContextValue {
|
||||
isStreaming: boolean;
|
||||
@@ -24,7 +20,7 @@ const ReasoningContext = createContext<ReasoningContextValue | null>(null);
|
||||
export const useReasoning = () => {
|
||||
const context = useContext(ReasoningContext);
|
||||
if (!context) {
|
||||
throw new Error("Reasoning components must be used within Reasoning");
|
||||
throw new Error('Reasoning components must be used within Reasoning');
|
||||
}
|
||||
return context;
|
||||
};
|
||||
@@ -78,8 +74,8 @@ export const Reasoning = memo(
|
||||
|
||||
// Auto-open when streaming starts, auto-close when streaming ends (once only)
|
||||
// Respect prefers-reduced-motion: skip animation auto-close
|
||||
const prefersReducedMotion = typeof window !== "undefined"
|
||||
&& window.matchMedia("(prefers-reduced-motion: reduce)").matches;
|
||||
const prefersReducedMotion =
|
||||
typeof window !== 'undefined' && window.matchMedia('(prefers-reduced-motion: reduce)').matches;
|
||||
|
||||
useEffect(() => {
|
||||
if (!prefersReducedMotion && defaultOpen && !isStreaming && isOpen && !hasAutoClosed) {
|
||||
@@ -97,11 +93,9 @@ export const Reasoning = memo(
|
||||
};
|
||||
|
||||
return (
|
||||
<ReasoningContext.Provider
|
||||
value={{ isStreaming, isOpen: isOpen ?? false, setIsOpen, duration }}
|
||||
>
|
||||
<ReasoningContext.Provider value={{ isStreaming, isOpen: isOpen ?? false, setIsOpen, duration }}>
|
||||
<Collapsible
|
||||
className={cn("not-prose mb-4", className)}
|
||||
className={cn('not-prose mb-4', className)}
|
||||
onOpenChange={handleOpenChange}
|
||||
open={isOpen}
|
||||
{...props}
|
||||
@@ -110,12 +104,10 @@ export const Reasoning = memo(
|
||||
</Collapsible>
|
||||
</ReasoningContext.Provider>
|
||||
);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
export type ReasoningTriggerProps = ComponentProps<
|
||||
typeof CollapsibleTrigger
|
||||
> & {
|
||||
export type ReasoningTriggerProps = ComponentProps<typeof CollapsibleTrigger> & {
|
||||
getThinkingMessage?: (isStreaming: boolean, duration?: number) => ReactNode;
|
||||
};
|
||||
|
||||
@@ -130,19 +122,14 @@ const defaultGetThinkingMessage = (isStreaming: boolean, duration?: number) => {
|
||||
};
|
||||
|
||||
export const ReasoningTrigger = memo(
|
||||
({
|
||||
className,
|
||||
children,
|
||||
getThinkingMessage = defaultGetThinkingMessage,
|
||||
...props
|
||||
}: ReasoningTriggerProps) => {
|
||||
({ className, children, getThinkingMessage = defaultGetThinkingMessage, ...props }: ReasoningTriggerProps) => {
|
||||
const { isStreaming, isOpen, duration } = useReasoning();
|
||||
|
||||
return (
|
||||
<CollapsibleTrigger
|
||||
className={cn(
|
||||
"flex w-full items-center gap-2 text-muted-foreground text-sm transition-colors hover:text-foreground",
|
||||
className
|
||||
'flex w-full items-center gap-2 text-muted-foreground text-sm transition-colors hover:text-foreground',
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
@@ -150,41 +137,31 @@ export const ReasoningTrigger = memo(
|
||||
<>
|
||||
<BrainIcon className="size-4" />
|
||||
{getThinkingMessage(isStreaming, duration)}
|
||||
<ChevronDownIcon
|
||||
className={cn(
|
||||
"size-4 transition-transform",
|
||||
isOpen ? "rotate-180" : "rotate-0"
|
||||
)}
|
||||
/>
|
||||
<ChevronDownIcon className={cn('size-4 transition-transform', isOpen ? 'rotate-180' : 'rotate-0')} />
|
||||
</>
|
||||
)}
|
||||
</CollapsibleTrigger>
|
||||
);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
export type ReasoningContentProps = ComponentProps<
|
||||
typeof CollapsibleContent
|
||||
> & {
|
||||
export type ReasoningContentProps = ComponentProps<typeof CollapsibleContent> & {
|
||||
children: ReactNode;
|
||||
};
|
||||
|
||||
export const ReasoningContent = memo(
|
||||
({ className, children, ...props }: ReasoningContentProps) => (
|
||||
<CollapsibleContent
|
||||
className={cn(
|
||||
"mt-4 text-sm",
|
||||
"data-[state=closed]:fade-out-0 data-[state=closed]:slide-out-to-top-2 data-[state=open]:slide-in-from-top-2 text-muted-foreground outline-none data-[state=closed]:animate-out data-[state=open]:animate-in",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
</CollapsibleContent>
|
||||
)
|
||||
);
|
||||
|
||||
Reasoning.displayName = "Reasoning";
|
||||
ReasoningTrigger.displayName = "ReasoningTrigger";
|
||||
ReasoningContent.displayName = "ReasoningContent";
|
||||
export const ReasoningContent = memo(({ className, children, ...props }: ReasoningContentProps) => (
|
||||
<CollapsibleContent
|
||||
className={cn(
|
||||
'mt-4 text-sm',
|
||||
'data-[state=closed]:fade-out-0 data-[state=closed]:slide-out-to-top-2 data-[state=open]:slide-in-from-top-2 text-muted-foreground outline-none data-[state=closed]:animate-out data-[state=open]:animate-in',
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
</CollapsibleContent>
|
||||
));
|
||||
|
||||
Reasoning.displayName = 'Reasoning';
|
||||
ReasoningTrigger.displayName = 'ReasoningTrigger';
|
||||
ReasoningContent.displayName = 'ReasoningContent';
|
||||
|
||||
@@ -1,12 +1,8 @@
|
||||
"use client";
|
||||
'use client';
|
||||
|
||||
import { cn } from "../../src/lib/utils";
|
||||
import { motion } from "motion/react";
|
||||
import {
|
||||
type ElementType,
|
||||
type JSX,
|
||||
memo,
|
||||
} from "react";
|
||||
import { cn } from '../../src/lib/utils';
|
||||
import { motion } from 'motion/react';
|
||||
import { type ElementType, type JSX, memo } from 'react';
|
||||
|
||||
export interface TextShimmerProps {
|
||||
children: string;
|
||||
@@ -16,27 +12,17 @@ export interface TextShimmerProps {
|
||||
spread?: number;
|
||||
}
|
||||
|
||||
const ShimmerComponent = ({
|
||||
children,
|
||||
as: Component = "p",
|
||||
className,
|
||||
duration = 2,
|
||||
}: TextShimmerProps) => {
|
||||
const MotionComponent = motion.create(
|
||||
Component as keyof JSX.IntrinsicElements
|
||||
);
|
||||
const ShimmerComponent = ({ children, as: Component = 'p', className, duration = 2 }: TextShimmerProps) => {
|
||||
const MotionComponent = motion.create(Component as keyof JSX.IntrinsicElements);
|
||||
|
||||
return (
|
||||
<MotionComponent
|
||||
animate={{ opacity: [0.5, 1, 0.5] }}
|
||||
className={cn(
|
||||
"relative inline-block text-muted-foreground",
|
||||
className
|
||||
)}
|
||||
className={cn('relative inline-block text-muted-foreground', className)}
|
||||
transition={{
|
||||
repeat: Number.POSITIVE_INFINITY,
|
||||
duration,
|
||||
ease: "easeInOut",
|
||||
ease: 'easeInOut',
|
||||
}}
|
||||
>
|
||||
{children}
|
||||
|
||||
@@ -1,67 +1,56 @@
|
||||
"use client";
|
||||
'use client';
|
||||
|
||||
import { Badge } from "../ui/badge";
|
||||
import {
|
||||
Collapsible,
|
||||
CollapsibleContent,
|
||||
CollapsibleTrigger,
|
||||
} from "../ui/collapsible";
|
||||
import { cn } from "../../src/lib/utils";
|
||||
import type { ToolUIPart } from "ai";
|
||||
import {
|
||||
CheckCircleIcon,
|
||||
ChevronDownIcon,
|
||||
CircleIcon,
|
||||
ClockIcon,
|
||||
WrenchIcon,
|
||||
XCircleIcon,
|
||||
} from "lucide-react";
|
||||
import type { ComponentProps, ReactNode } from "react";
|
||||
import { isValidElement } from "react";
|
||||
import { CodeBlock } from "./code-block";
|
||||
import { Badge } from '../ui/badge';
|
||||
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from '../ui/collapsible';
|
||||
import { cn } from '../../src/lib/utils';
|
||||
import type { ToolUIPart } from 'ai';
|
||||
import { CheckCircleIcon, ChevronDownIcon, CircleIcon, ClockIcon, WrenchIcon, XCircleIcon } from 'lucide-react';
|
||||
import type { ComponentProps, ReactNode } from 'react';
|
||||
import { isValidElement } from 'react';
|
||||
import { CodeBlock } from './code-block';
|
||||
|
||||
export type ToolProps = ComponentProps<typeof Collapsible>;
|
||||
|
||||
export const Tool = ({ className, ...props }: ToolProps) => (
|
||||
<Collapsible
|
||||
className={cn("not-prose mb-4 w-full max-w-full overflow-hidden rounded-md border", className)}
|
||||
className={cn('not-prose mb-4 w-full max-w-full overflow-hidden rounded-md border', className)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
|
||||
// Extended state type to include our custom states
|
||||
export type ExtendedToolState = ToolUIPart["state"] | "waiting-for-confirmation" | "rejected";
|
||||
export type ExtendedToolState = ToolUIPart['state'] | 'waiting-for-confirmation' | 'rejected';
|
||||
|
||||
export type ToolHeaderProps = {
|
||||
title?: string;
|
||||
type: ToolUIPart["type"];
|
||||
type: ToolUIPart['type'];
|
||||
state: ExtendedToolState;
|
||||
className?: string;
|
||||
};
|
||||
|
||||
const getStatusBadge = (status: ExtendedToolState) => {
|
||||
const labels: Record<ExtendedToolState, string> = {
|
||||
"input-streaming": "Pending",
|
||||
"input-available": "Running",
|
||||
"approval-requested": "Awaiting Approval",
|
||||
"approval-responded": "Responded",
|
||||
"output-available": "Completed",
|
||||
"output-error": "Error",
|
||||
"output-denied": "Denied",
|
||||
"waiting-for-confirmation": "Awaiting Approval",
|
||||
"rejected": "Rejected",
|
||||
'input-streaming': 'Pending',
|
||||
'input-available': 'Running',
|
||||
'approval-requested': 'Awaiting Approval',
|
||||
'approval-responded': 'Responded',
|
||||
'output-available': 'Completed',
|
||||
'output-error': 'Error',
|
||||
'output-denied': 'Denied',
|
||||
'waiting-for-confirmation': 'Awaiting Approval',
|
||||
rejected: 'Rejected',
|
||||
};
|
||||
|
||||
const icons: Record<ExtendedToolState, ReactNode> = {
|
||||
"input-streaming": <CircleIcon className="size-4" />,
|
||||
"input-available": <ClockIcon className="size-4 animate-pulse" />,
|
||||
"approval-requested": <ClockIcon className="size-4 text-yellow-600" />,
|
||||
"approval-responded": <CheckCircleIcon className="size-4 text-blue-600" />,
|
||||
"output-available": <CheckCircleIcon className="size-4 text-green-600" />,
|
||||
"output-error": <XCircleIcon className="size-4 text-red-600" />,
|
||||
"output-denied": <XCircleIcon className="size-4 text-orange-600" />,
|
||||
"waiting-for-confirmation": <ClockIcon className="size-4 text-yellow-600" />,
|
||||
"rejected": <XCircleIcon className="size-4 text-orange-600" />,
|
||||
'input-streaming': <CircleIcon className="size-4" />,
|
||||
'input-available': <ClockIcon className="size-4 animate-pulse" />,
|
||||
'approval-requested': <ClockIcon className="size-4 text-yellow-600" />,
|
||||
'approval-responded': <CheckCircleIcon className="size-4 text-blue-600" />,
|
||||
'output-available': <CheckCircleIcon className="size-4 text-green-600" />,
|
||||
'output-error': <XCircleIcon className="size-4 text-red-600" />,
|
||||
'output-denied': <XCircleIcon className="size-4 text-orange-600" />,
|
||||
'waiting-for-confirmation': <ClockIcon className="size-4 text-yellow-600" />,
|
||||
rejected: <XCircleIcon className="size-4 text-orange-600" />,
|
||||
};
|
||||
|
||||
return (
|
||||
@@ -72,25 +61,11 @@ const getStatusBadge = (status: ExtendedToolState) => {
|
||||
);
|
||||
};
|
||||
|
||||
export const ToolHeader = ({
|
||||
className,
|
||||
title,
|
||||
type,
|
||||
state,
|
||||
...props
|
||||
}: ToolHeaderProps) => (
|
||||
<CollapsibleTrigger
|
||||
className={cn(
|
||||
"flex w-full items-center justify-between gap-4 p-3",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
export const ToolHeader = ({ className, title, type, state, ...props }: ToolHeaderProps) => (
|
||||
<CollapsibleTrigger className={cn('flex w-full items-center justify-between gap-4 p-3', className)} {...props}>
|
||||
<div className="flex min-w-0 items-center gap-2">
|
||||
<WrenchIcon className="size-4 shrink-0 text-muted-foreground" />
|
||||
<span className="truncate font-medium text-sm">
|
||||
{title ?? type.split("-").slice(1).join("-")}
|
||||
</span>
|
||||
<span className="truncate font-medium text-sm">{title ?? type.split('-').slice(1).join('-')}</span>
|
||||
{getStatusBadge(state)}
|
||||
</div>
|
||||
<ChevronDownIcon className="size-4 shrink-0 text-muted-foreground transition-transform group-data-[state=open]:rotate-180" />
|
||||
@@ -102,64 +77,53 @@ export type ToolContentProps = ComponentProps<typeof CollapsibleContent>;
|
||||
export const ToolContent = ({ className, ...props }: ToolContentProps) => (
|
||||
<CollapsibleContent
|
||||
className={cn(
|
||||
"data-[state=closed]:fade-out-0 data-[state=closed]:slide-out-to-top-2 data-[state=open]:slide-in-from-top-2 text-popover-foreground outline-none data-[state=closed]:animate-out data-[state=open]:animate-in",
|
||||
className
|
||||
'data-[state=closed]:fade-out-0 data-[state=closed]:slide-out-to-top-2 data-[state=open]:slide-in-from-top-2 text-popover-foreground outline-none data-[state=closed]:animate-out data-[state=open]:animate-in',
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
|
||||
export type ToolInputProps = ComponentProps<"div"> & {
|
||||
input: ToolUIPart["input"];
|
||||
export type ToolInputProps = ComponentProps<'div'> & {
|
||||
input: ToolUIPart['input'];
|
||||
};
|
||||
|
||||
export const ToolInput = ({ className, input, ...props }: ToolInputProps) => (
|
||||
<div className={cn("space-y-2 overflow-hidden p-4 max-w-full", className)} {...props}>
|
||||
<h4 className="font-medium text-muted-foreground text-xs uppercase tracking-wide">
|
||||
Parameters
|
||||
</h4>
|
||||
<div className={cn('space-y-2 overflow-hidden p-4 max-w-full', className)} {...props}>
|
||||
<h4 className="font-medium text-muted-foreground text-xs uppercase tracking-wide">Parameters</h4>
|
||||
<div className="rounded-md bg-muted/50 overflow-hidden">
|
||||
<CodeBlock code={JSON.stringify(input, null, 2)} language="json" />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
export type ToolOutputProps = ComponentProps<"div"> & {
|
||||
output: ToolUIPart["output"];
|
||||
errorText: ToolUIPart["errorText"];
|
||||
export type ToolOutputProps = ComponentProps<'div'> & {
|
||||
output: ToolUIPart['output'];
|
||||
errorText: ToolUIPart['errorText'];
|
||||
};
|
||||
|
||||
export const ToolOutput = ({
|
||||
className,
|
||||
output,
|
||||
errorText,
|
||||
...props
|
||||
}: ToolOutputProps) => {
|
||||
export const ToolOutput = ({ className, output, errorText, ...props }: ToolOutputProps) => {
|
||||
if (!(output || errorText)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
let Output = <div>{output as ReactNode}</div>;
|
||||
|
||||
if (typeof output === "object" && !isValidElement(output)) {
|
||||
Output = (
|
||||
<CodeBlock code={JSON.stringify(output, null, 2)} language="json" />
|
||||
);
|
||||
} else if (typeof output === "string") {
|
||||
if (typeof output === 'object' && !isValidElement(output)) {
|
||||
Output = <CodeBlock code={JSON.stringify(output, null, 2)} language="json" />;
|
||||
} else if (typeof output === 'string') {
|
||||
Output = <CodeBlock code={output} language="json" />;
|
||||
}
|
||||
|
||||
return (
|
||||
<div className={cn("space-y-2 p-4 max-w-full overflow-hidden", className)} {...props}>
|
||||
<div className={cn('space-y-2 p-4 max-w-full overflow-hidden', className)} {...props}>
|
||||
<h4 className="font-medium text-muted-foreground text-xs uppercase tracking-wide">
|
||||
{errorText ? "Error" : "Result"}
|
||||
{errorText ? 'Error' : 'Result'}
|
||||
</h4>
|
||||
<div
|
||||
className={cn(
|
||||
"overflow-hidden rounded-md text-xs [&_table]:w-full",
|
||||
errorText
|
||||
? "bg-destructive/10 text-destructive"
|
||||
: "bg-muted/50 text-foreground"
|
||||
'overflow-hidden rounded-md text-xs [&_table]:w-full',
|
||||
errorText ? 'bg-destructive/10 text-destructive' : 'bg-muted/50 text-foreground',
|
||||
)}
|
||||
>
|
||||
{errorText && <div className="p-2">{errorText}</div>}
|
||||
@@ -168,4 +132,3 @@ export const ToolOutput = ({
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
|
||||
@@ -1,17 +1,17 @@
|
||||
import { useState, useRef, useCallback, type KeyboardEvent, type ClipboardEvent } from "react";
|
||||
import { cn } from "../../src/lib/utils";
|
||||
import { Send, Square, Paperclip, Slash } from "lucide-react";
|
||||
import type { ChatInputMessage, UserMessageImage } from "../../src/lib/types";
|
||||
import type { AvailableCommand } from "../../src/acp/types";
|
||||
import { CommandMenu } from "./CommandMenu";
|
||||
import imageCompression from "browser-image-compression";
|
||||
import { useState, useRef, useCallback, type KeyboardEvent, type ClipboardEvent } from 'react';
|
||||
import { cn } from '../../src/lib/utils';
|
||||
import { Send, Square, Paperclip, Slash } from 'lucide-react';
|
||||
import type { ChatInputMessage, UserMessageImage } from '../../src/lib/types';
|
||||
import type { AvailableCommand } from '../../src/acp/types';
|
||||
import { CommandMenu } from './CommandMenu';
|
||||
import imageCompression from 'browser-image-compression';
|
||||
|
||||
// 图片压缩配置
|
||||
const IMAGE_COMPRESSION_OPTIONS = {
|
||||
maxSizeMB: 2,
|
||||
maxWidthOrHeight: 2048,
|
||||
useWebWorker: true,
|
||||
fileType: "image/jpeg" as const,
|
||||
fileType: 'image/jpeg' as const,
|
||||
};
|
||||
|
||||
// =============================================================================
|
||||
@@ -36,15 +36,15 @@ export function ChatInput({
|
||||
isLoading = false,
|
||||
onInterrupt,
|
||||
disabled = false,
|
||||
placeholder = "给 Claude 发送消息…",
|
||||
placeholder = '给 Claude 发送消息…',
|
||||
supportsImages = false,
|
||||
commands,
|
||||
className,
|
||||
}: ChatInputProps) {
|
||||
const [text, setText] = useState("");
|
||||
const [text, setText] = useState('');
|
||||
const [images, setImages] = useState<UserMessageImage[]>([]);
|
||||
const [showCommandMenu, setShowCommandMenu] = useState(false);
|
||||
const [commandFilter, setCommandFilter] = useState("");
|
||||
const [commandFilter, setCommandFilter] = useState('');
|
||||
const textareaRef = useRef<HTMLTextAreaElement>(null);
|
||||
const fileInputRef = useRef<HTMLInputElement>(null);
|
||||
|
||||
@@ -53,37 +53,37 @@ export function ChatInput({
|
||||
if ((!trimmed && images.length === 0) || disabled) return;
|
||||
|
||||
onSubmit({ text: trimmed, images: images.length > 0 ? images : undefined });
|
||||
setText("");
|
||||
setText('');
|
||||
setImages([]);
|
||||
setShowCommandMenu(false);
|
||||
setCommandFilter("");
|
||||
setCommandFilter('');
|
||||
// 重置 textarea 高度
|
||||
if (textareaRef.current) {
|
||||
textareaRef.current.style.height = "auto";
|
||||
textareaRef.current.style.height = 'auto';
|
||||
}
|
||||
}, [text, images, disabled, onSubmit]);
|
||||
|
||||
const handleKeyDown = useCallback(
|
||||
(e: KeyboardEvent<HTMLTextAreaElement>) => {
|
||||
if (showCommandMenu) {
|
||||
if (e.key === "Escape") {
|
||||
if (e.key === 'Escape') {
|
||||
e.preventDefault();
|
||||
setShowCommandMenu(false);
|
||||
return;
|
||||
}
|
||||
// Arrow keys and Enter are handled by CommandMenu via document-level listener
|
||||
// Don't submit or move cursor when menu is open
|
||||
if (e.key === "ArrowUp" || e.key === "ArrowDown" || e.key === "Enter") {
|
||||
if (e.key === 'ArrowUp' || e.key === 'ArrowDown' || e.key === 'Enter') {
|
||||
e.preventDefault();
|
||||
return;
|
||||
}
|
||||
if (e.key === "Tab") {
|
||||
if (e.key === 'Tab') {
|
||||
e.preventDefault();
|
||||
setShowCommandMenu(false);
|
||||
return;
|
||||
}
|
||||
}
|
||||
if (e.key === "Enter" && !e.shiftKey && !e.nativeEvent.isComposing) {
|
||||
if (e.key === 'Enter' && !e.shiftKey && !e.nativeEvent.isComposing) {
|
||||
e.preventDefault();
|
||||
if (isLoading) {
|
||||
onInterrupt?.();
|
||||
@@ -95,35 +95,41 @@ export function ChatInput({
|
||||
[handleSubmit, isLoading, onInterrupt, showCommandMenu],
|
||||
);
|
||||
|
||||
const handleInput = useCallback((e: React.ChangeEvent<HTMLTextAreaElement>) => {
|
||||
const value = e.target.value;
|
||||
setText(value);
|
||||
const handleInput = useCallback(
|
||||
(e: React.ChangeEvent<HTMLTextAreaElement>) => {
|
||||
const value = e.target.value;
|
||||
setText(value);
|
||||
|
||||
// 检测 slash 命令模式:仅在输入开头输入 / 时触发
|
||||
if (value.startsWith("/") && commands && commands.length > 0) {
|
||||
setShowCommandMenu(true);
|
||||
setCommandFilter(value.slice(1).split(/\s/)[0] || "");
|
||||
} else if (showCommandMenu) {
|
||||
setShowCommandMenu(false);
|
||||
setCommandFilter("");
|
||||
}
|
||||
// 检测 slash 命令模式:仅在输入开头输入 / 时触发
|
||||
if (value.startsWith('/') && commands && commands.length > 0) {
|
||||
setShowCommandMenu(true);
|
||||
setCommandFilter(value.slice(1).split(/\s/)[0] || '');
|
||||
} else if (showCommandMenu) {
|
||||
setShowCommandMenu(false);
|
||||
setCommandFilter('');
|
||||
}
|
||||
|
||||
// 自动调整高度
|
||||
const el = e.target;
|
||||
el.style.height = "auto";
|
||||
el.style.height = Math.min(el.scrollHeight, 200) + "px";
|
||||
}, [commands, showCommandMenu]);
|
||||
// 自动调整高度
|
||||
const el = e.target;
|
||||
el.style.height = 'auto';
|
||||
el.style.height = Math.min(el.scrollHeight, 200) + 'px';
|
||||
},
|
||||
[commands, showCommandMenu],
|
||||
);
|
||||
|
||||
// 粘贴图片
|
||||
const handlePaste = useCallback(async (e: ClipboardEvent) => {
|
||||
if (!supportsImages) return;
|
||||
const files = Array.from(e.clipboardData.files).filter((f) => f.type.startsWith("image/"));
|
||||
if (files.length === 0) return;
|
||||
const handlePaste = useCallback(
|
||||
async (e: ClipboardEvent) => {
|
||||
if (!supportsImages) return;
|
||||
const files = Array.from(e.clipboardData.files).filter(f => f.type.startsWith('image/'));
|
||||
if (files.length === 0) return;
|
||||
|
||||
e.preventDefault();
|
||||
const newImages = await processImageFiles(files);
|
||||
setImages((prev) => [...prev, ...newImages]);
|
||||
}, [supportsImages]);
|
||||
e.preventDefault();
|
||||
const newImages = await processImageFiles(files);
|
||||
setImages(prev => [...prev, ...newImages]);
|
||||
},
|
||||
[supportsImages],
|
||||
);
|
||||
|
||||
// 选择文件
|
||||
const handleFileSelect = useCallback(async () => {
|
||||
@@ -132,32 +138,32 @@ export function ChatInput({
|
||||
if (!files || files.length === 0) return;
|
||||
|
||||
const newImages = await processImageFiles(Array.from(files));
|
||||
setImages((prev) => [...prev, ...newImages]);
|
||||
setImages(prev => [...prev, ...newImages]);
|
||||
// 清空 input 以便重复选择
|
||||
fileInputRef.current.value = "";
|
||||
fileInputRef.current.value = '';
|
||||
}, []);
|
||||
|
||||
const removeImage = useCallback((index: number) => {
|
||||
setImages((prev) => prev.filter((_, i) => i !== index));
|
||||
setImages(prev => prev.filter((_, i) => i !== index));
|
||||
}, []);
|
||||
|
||||
const handleCommandSelect = useCallback((command: AvailableCommand) => {
|
||||
setText(`/${command.name} `);
|
||||
setShowCommandMenu(false);
|
||||
setCommandFilter("");
|
||||
setCommandFilter('');
|
||||
textareaRef.current?.focus();
|
||||
}, []);
|
||||
|
||||
const toggleCommandMenu = useCallback(() => {
|
||||
if (showCommandMenu) {
|
||||
setShowCommandMenu(false);
|
||||
setCommandFilter("");
|
||||
setCommandFilter('');
|
||||
} else {
|
||||
if (!text.startsWith("/")) {
|
||||
setText("/" + text);
|
||||
if (!text.startsWith('/')) {
|
||||
setText('/' + text);
|
||||
}
|
||||
setShowCommandMenu(true);
|
||||
setCommandFilter(text.startsWith("/") ? text.slice(1).split(/\s/)[0] || "" : "");
|
||||
setCommandFilter(text.startsWith('/') ? text.slice(1).split(/\s/)[0] || '' : '');
|
||||
textareaRef.current?.focus();
|
||||
}
|
||||
}, [showCommandMenu, text]);
|
||||
@@ -165,7 +171,7 @@ export function ChatInput({
|
||||
const canSend = (text.trim() || images.length > 0) && !disabled;
|
||||
|
||||
return (
|
||||
<div className={cn("w-full max-w-3xl mx-auto px-4 sm:px-8 pb-4 pt-2", className)}>
|
||||
<div className={cn('w-full max-w-3xl mx-auto px-4 sm:px-8 pb-4 pt-2', className)}>
|
||||
<div className="relative">
|
||||
{/* Slash command menu — floating above input */}
|
||||
{showCommandMenu && commands && commands.length > 0 && (
|
||||
@@ -175,127 +181,124 @@ export function ChatInput({
|
||||
onSelect={handleCommandSelect}
|
||||
onClose={() => {
|
||||
setShowCommandMenu(false);
|
||||
setCommandFilter("");
|
||||
setCommandFilter('');
|
||||
}}
|
||||
className="absolute bottom-full left-0 right-0 mb-1 z-50"
|
||||
/>
|
||||
)}
|
||||
<div className={cn(
|
||||
"rounded-xl border border-border bg-surface-2 overflow-hidden",
|
||||
"focus-within:border-brand/50 focus-within:shadow-[0_0_0_3px_rgba(217,119,87,0.15)] transition-all",
|
||||
)}>
|
||||
{/* 图片预览 */}
|
||||
{images.length > 0 && (
|
||||
<div className="flex flex-wrap gap-2 px-3 pt-3">
|
||||
{images.map((img, i) => (
|
||||
<div key={i} className="relative group">
|
||||
<img
|
||||
src={`data:${img.mimeType};base64,${img.data}`}
|
||||
alt={`Attached image ${i + 1}`}
|
||||
className="h-14 w-14 object-cover rounded-lg border border-border"
|
||||
/>
|
||||
<div
|
||||
className={cn(
|
||||
'rounded-xl border border-border bg-surface-2 overflow-hidden',
|
||||
'focus-within:border-brand/50 focus-within:shadow-[0_0_0_3px_rgba(217,119,87,0.15)] transition-all',
|
||||
)}
|
||||
>
|
||||
{/* 图片预览 */}
|
||||
{images.length > 0 && (
|
||||
<div className="flex flex-wrap gap-2 px-3 pt-3">
|
||||
{images.map((img, i) => (
|
||||
<div key={i} className="relative group">
|
||||
<img
|
||||
src={`data:${img.mimeType};base64,${img.data}`}
|
||||
alt={`Attached image ${i + 1}`}
|
||||
className="h-14 w-14 object-cover rounded-lg border border-border"
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => removeImage(i)}
|
||||
className="absolute -top-1.5 -right-1.5 min-h-[32px] min-w-[32px] h-5 w-5 rounded-full bg-surface-2 border border-border flex items-center justify-center text-text-muted hover:text-text-primary text-xs opacity-0 group-hover:opacity-100 transition-opacity"
|
||||
aria-label={`Remove image ${i + 1}`}
|
||||
>
|
||||
{'\u00D7'}
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* 输入区域 — Anthropic 单行紧凑布局 */}
|
||||
<div className="flex items-end gap-2 px-3 py-2.5">
|
||||
{/* 左侧附件按钮 */}
|
||||
{supportsImages && (
|
||||
<>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => removeImage(i)}
|
||||
className="absolute -top-1.5 -right-1.5 min-h-[32px] min-w-[32px] h-5 w-5 rounded-full bg-surface-2 border border-border flex items-center justify-center text-text-muted hover:text-text-primary text-xs opacity-0 group-hover:opacity-100 transition-opacity"
|
||||
aria-label={`Remove image ${i + 1}`}
|
||||
onClick={() => fileInputRef.current?.click()}
|
||||
className="flex-shrink-0 h-8 w-8 flex items-center justify-center rounded-lg text-text-muted hover:text-text-secondary hover:bg-surface-1/50 transition-colors"
|
||||
disabled={disabled}
|
||||
>
|
||||
{"\u00D7"}
|
||||
<Paperclip className="h-4 w-4" />
|
||||
<span className="sr-only">Attach file</span>
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
<input
|
||||
ref={fileInputRef}
|
||||
type="file"
|
||||
accept="image/*"
|
||||
multiple
|
||||
className="hidden"
|
||||
onChange={handleFileSelect}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
|
||||
{/* 输入区域 — Anthropic 单行紧凑布局 */}
|
||||
<div className="flex items-end gap-2 px-3 py-2.5">
|
||||
{/* 左侧附件按钮 */}
|
||||
{supportsImages && (
|
||||
<>
|
||||
{/* Slash 命令按钮 */}
|
||||
{commands && commands.length > 0 && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => fileInputRef.current?.click()}
|
||||
className="flex-shrink-0 h-8 w-8 flex items-center justify-center rounded-lg text-text-muted hover:text-text-secondary hover:bg-surface-1/50 transition-colors"
|
||||
onClick={toggleCommandMenu}
|
||||
className={cn(
|
||||
'flex-shrink-0 h-8 w-8 flex items-center justify-center rounded-lg transition-colors',
|
||||
showCommandMenu
|
||||
? 'bg-brand/15 text-brand'
|
||||
: 'text-text-muted hover:text-text-secondary hover:bg-surface-1/50',
|
||||
)}
|
||||
disabled={disabled}
|
||||
title="命令列表"
|
||||
>
|
||||
<Paperclip className="h-4 w-4" />
|
||||
<span className="sr-only">Attach file</span>
|
||||
<Slash className="h-4 w-4" />
|
||||
</button>
|
||||
<input
|
||||
ref={fileInputRef}
|
||||
type="file"
|
||||
accept="image/*"
|
||||
multiple
|
||||
className="hidden"
|
||||
onChange={handleFileSelect}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
)}
|
||||
|
||||
{/* Slash 命令按钮 */}
|
||||
{commands && commands.length > 0 && (
|
||||
{/* Textarea — Poppins font */}
|
||||
<textarea
|
||||
ref={textareaRef}
|
||||
value={text}
|
||||
onChange={handleInput}
|
||||
onKeyDown={handleKeyDown}
|
||||
onPaste={handlePaste}
|
||||
placeholder={placeholder}
|
||||
disabled={disabled}
|
||||
rows={1}
|
||||
className={cn(
|
||||
'flex-1 resize-none border-none bg-transparent outline-none',
|
||||
'text-sm text-text-primary placeholder:text-text-muted font-display',
|
||||
'max-h-[200px] min-h-[24px] leading-normal',
|
||||
)}
|
||||
/>
|
||||
|
||||
{/* 右侧发送/取消按钮 */}
|
||||
<button
|
||||
type="button"
|
||||
onClick={toggleCommandMenu}
|
||||
onClick={isLoading ? onInterrupt : handleSubmit}
|
||||
disabled={!isLoading && !canSend}
|
||||
className={cn(
|
||||
"flex-shrink-0 h-8 w-8 flex items-center justify-center rounded-lg transition-colors",
|
||||
showCommandMenu
|
||||
? "bg-brand/15 text-brand"
|
||||
: "text-text-muted hover:text-text-secondary hover:bg-surface-1/50",
|
||||
'flex-shrink-0 h-8 w-8 flex items-center justify-center rounded-lg transition-all',
|
||||
isLoading
|
||||
? 'bg-text-primary text-surface-2 hover:bg-text-secondary'
|
||||
: canSend
|
||||
? 'bg-brand text-white hover:bg-brand-light hover:scale-[1.05] active:scale-[0.97]'
|
||||
: 'bg-surface-1 text-text-muted',
|
||||
)}
|
||||
disabled={disabled}
|
||||
title="命令列表"
|
||||
>
|
||||
<Slash className="h-4 w-4" />
|
||||
{isLoading ? <Square className="h-3.5 w-3.5" fill="currentColor" /> : <Send className="h-4 w-4" />}
|
||||
</button>
|
||||
)}
|
||||
|
||||
{/* Textarea — Poppins font */}
|
||||
<textarea
|
||||
ref={textareaRef}
|
||||
value={text}
|
||||
onChange={handleInput}
|
||||
onKeyDown={handleKeyDown}
|
||||
onPaste={handlePaste}
|
||||
placeholder={placeholder}
|
||||
disabled={disabled}
|
||||
rows={1}
|
||||
className={cn(
|
||||
"flex-1 resize-none border-none bg-transparent outline-none",
|
||||
"text-sm text-text-primary placeholder:text-text-muted font-display",
|
||||
"max-h-[200px] min-h-[24px] leading-normal",
|
||||
)}
|
||||
/>
|
||||
|
||||
{/* 右侧发送/取消按钮 */}
|
||||
<button
|
||||
type="button"
|
||||
onClick={isLoading ? onInterrupt : handleSubmit}
|
||||
disabled={!isLoading && !canSend}
|
||||
className={cn(
|
||||
"flex-shrink-0 h-8 w-8 flex items-center justify-center rounded-lg transition-all",
|
||||
isLoading
|
||||
? "bg-text-primary text-surface-2 hover:bg-text-secondary"
|
||||
: canSend
|
||||
? "bg-brand text-white hover:bg-brand-light hover:scale-[1.05] active:scale-[0.97]"
|
||||
: "bg-surface-1 text-text-muted",
|
||||
)}
|
||||
>
|
||||
{isLoading ? (
|
||||
<Square className="h-3.5 w-3.5" fill="currentColor" />
|
||||
) : (
|
||||
<Send className="h-4 w-4" />
|
||||
)}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>{/* end relative */}
|
||||
{/* end relative */}
|
||||
|
||||
{/* 提示文本 */}
|
||||
<div className="text-center mt-1.5">
|
||||
<span className="text-[11px] text-text-muted font-display">
|
||||
Enter 发送,Shift+Enter 换行
|
||||
</span>
|
||||
<span className="text-[11px] text-text-muted font-display">Enter 发送,Shift+Enter 换行</span>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
@@ -316,23 +319,23 @@ async function processImageFiles(files: File[]): Promise<UserMessageImage[]> {
|
||||
if (file.size > 2 * 1024 * 1024) {
|
||||
const compressed = await imageCompression(file, IMAGE_COMPRESSION_OPTIONS);
|
||||
blob = compressed;
|
||||
mimeType = "image/jpeg";
|
||||
mimeType = 'image/jpeg';
|
||||
}
|
||||
|
||||
const base64 = await new Promise<string>((resolve, reject) => {
|
||||
const reader = new FileReader();
|
||||
reader.onloadend = () => {
|
||||
const result = reader.result as string;
|
||||
const commaIdx = result.indexOf(",");
|
||||
const commaIdx = result.indexOf(',');
|
||||
resolve(commaIdx >= 0 ? result.slice(commaIdx + 1) : result);
|
||||
};
|
||||
reader.onerror = () => reject(new Error("FileReader error"));
|
||||
reader.onerror = () => reject(new Error('FileReader error'));
|
||||
reader.readAsDataURL(blob);
|
||||
});
|
||||
|
||||
results.push({ mimeType, data: base64 });
|
||||
} catch (err) {
|
||||
console.error("Failed to process image:", err);
|
||||
console.error('Failed to process image:', err);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,9 +1,14 @@
|
||||
import type { ThreadEntry, ToolCallEntry, PlanDisplayEntry } from "../../src/lib/types";
|
||||
import { cn } from "../../src/lib/utils";
|
||||
import { UserBubble, AssistantBubble } from "./MessageBubble";
|
||||
import { ToolCallGroup } from "./ToolCallGroup";
|
||||
import { PlanDisplay } from "./PlanView";
|
||||
import { Conversation, ConversationContent, ConversationEmptyState, ConversationScrollButtons } from "../ai-elements/conversation";
|
||||
import type { ThreadEntry, ToolCallEntry, PlanDisplayEntry } from '../../src/lib/types';
|
||||
import { cn } from '../../src/lib/utils';
|
||||
import { UserBubble, AssistantBubble } from './MessageBubble';
|
||||
import { ToolCallGroup } from './ToolCallGroup';
|
||||
import { PlanDisplay } from './PlanView';
|
||||
import {
|
||||
Conversation,
|
||||
ConversationContent,
|
||||
ConversationEmptyState,
|
||||
ConversationScrollButtons,
|
||||
} from '../ai-elements/conversation';
|
||||
|
||||
// =============================================================================
|
||||
// 统一聊天视图 — Anthropic 编辑式排版
|
||||
@@ -22,28 +27,25 @@ export function ChatView({
|
||||
entries,
|
||||
isLoading = false,
|
||||
onPermissionRespond,
|
||||
emptyTitle = "开始对话",
|
||||
emptyDescription = "输入消息开始聊天",
|
||||
emptyTitle = '开始对话',
|
||||
emptyDescription = '输入消息开始聊天',
|
||||
}: ChatViewProps) {
|
||||
// 将相邻的 ToolCallEntry 合并为一组
|
||||
const grouped = groupToolCalls(entries);
|
||||
const hasMessages = entries.length > 0;
|
||||
|
||||
// 检查是否正在加载(最后一个条目是用户消息)
|
||||
const showThinking = isLoading && entries.length > 0 && entries[entries.length - 1]?.type === "user_message";
|
||||
const showThinking = isLoading && entries.length > 0 && entries[entries.length - 1]?.type === 'user_message';
|
||||
|
||||
return (
|
||||
<Conversation className="flex-1">
|
||||
<ConversationContent>
|
||||
{!hasMessages ? (
|
||||
<ConversationEmptyState
|
||||
title={emptyTitle}
|
||||
description={emptyDescription}
|
||||
/>
|
||||
<ConversationEmptyState title={emptyTitle} description={emptyDescription} />
|
||||
) : (
|
||||
<>
|
||||
{grouped.map((item, i) => {
|
||||
if (item.type === "single") {
|
||||
if (item.type === 'single') {
|
||||
return (
|
||||
<div key={`entry-${i}`} className={cn(entrySpacing(entries, i))}>
|
||||
<EntryRenderer entry={item.entry} isLoading={isLoading} onPermissionRespond={onPermissionRespond} />
|
||||
@@ -63,19 +65,25 @@ export function ChatView({
|
||||
<div className="flex gap-4 items-start">
|
||||
<div className="w-8 h-8 rounded-lg bg-brand/8 flex items-center justify-center flex-shrink-0">
|
||||
<svg width="20" height="20" viewBox="0 0 24 24" aria-hidden="true">
|
||||
<path d="M4.709 15.955l4.72-2.647.08-.23-.08-.128H9.2l-.79-.048-2.698-.073-2.339-.097-2.266-.122-.571-.121L0 11.784l.055-.352.48-.321.686.06 1.52.103 2.278.158 1.652.097 2.449.255h.389l.055-.157-.134-.098-.103-.097-2.358-1.596-2.552-1.688-1.336-.972-.724-.491-.364-.462-.158-1.008.656-.722.881.06.225.061.893.686 1.908 1.476 2.491 1.833.365.304.145-.103.019-.073-.164-.274-1.355-2.446-1.446-2.49-.644-1.032-.17-.619a2.97 2.97 0 01-.104-.729L6.283.134 6.696 0l.996.134.42.364.62 1.414 1.002 2.229 1.555 3.03.456.898.243.832.091.255h.158V9.01l.128-1.706.237-2.095.23-2.695.08-.76.376-.91.747-.492.584.28.48.685-.067.444-.286 1.851-.559 2.903-.364 1.942h.212l.243-.242.985-1.306 1.652-2.064.73-.82.85-.904.547-.431h1.033l.76 1.129-.34 1.166-1.064 1.347-.881 1.142-1.264 1.7-.79 1.36.073.11.188-.02 2.856-.606 1.543-.28 1.841-.315.833.388.091.395-.328.807-1.969.486-2.309.462-3.439.813-.042.03.049.061 1.549.146.662.036h1.622l3.02.225.79.522.474.638-.079.485-1.215.62-1.64-.389-3.829-.91-1.312-.329h-.182v.11l1.093 1.068 2.006 1.81 2.509 2.33.127.578-.322.455-.34-.049-2.205-1.657-.851-.747-1.926-1.62h-.128v.17l.444.649 2.345 3.521.122 1.08-.17.353-.608.213-.668-.122-1.374-1.925-1.415-2.167-1.143-1.943-.14.08-.674 7.254-.316.37-.729.28-.607-.461-.322-.747.322-1.476.389-1.924.315-1.53.286-1.9.17-.632-.012-.042-.14.018-1.434 1.967-2.18 2.945-1.726 1.845-.414.164-.717-.37.067-.662.401-.589 2.388-3.036 1.44-1.882.93-1.086-.006-.158h-.055L4.132 18.56l-1.13.146-.487-.456.061-.746.231-.243 1.908-1.312-.006.006z" fill="var(--color-brand)" fillRule="nonzero" />
|
||||
<path
|
||||
d="M4.709 15.955l4.72-2.647.08-.23-.08-.128H9.2l-.79-.048-2.698-.073-2.339-.097-2.266-.122-.571-.121L0 11.784l.055-.352.48-.321.686.06 1.52.103 2.278.158 1.652.097 2.449.255h.389l.055-.157-.134-.098-.103-.097-2.358-1.596-2.552-1.688-1.336-.972-.724-.491-.364-.462-.158-1.008.656-.722.881.06.225.061.893.686 1.908 1.476 2.491 1.833.365.304.145-.103.019-.073-.164-.274-1.355-2.446-1.446-2.49-.644-1.032-.17-.619a2.97 2.97 0 01-.104-.729L6.283.134 6.696 0l.996.134.42.364.62 1.414 1.002 2.229 1.555 3.03.456.898.243.832.091.255h.158V9.01l.128-1.706.237-2.095.23-2.695.08-.76.376-.91.747-.492.584.28.48.685-.067.444-.286 1.851-.559 2.903-.364 1.942h.212l.243-.242.985-1.306 1.652-2.064.73-.82.85-.904.547-.431h1.033l.76 1.129-.34 1.166-1.064 1.347-.881 1.142-1.264 1.7-.79 1.36.073.11.188-.02 2.856-.606 1.543-.28 1.841-.315.833.388.091.395-.328.807-1.969.486-2.309.462-3.439.813-.042.03.049.061 1.549.146.662.036h1.622l3.02.225.79.522.474.638-.079.485-1.215.62-1.64-.389-3.829-.91-1.312-.329h-.182v.11l1.093 1.068 2.006 1.81 2.509 2.33.127.578-.322.455-.34-.049-2.205-1.657-.851-.747-1.926-1.62h-.128v.17l.444.649 2.345 3.521.122 1.08-.17.353-.608.213-.668-.122-1.374-1.925-1.415-2.167-1.143-1.943-.14.08-.674 7.254-.316.37-.729.28-.607-.461-.322-.747.322-1.476.389-1.924.315-1.53.286-1.9.17-.632-.012-.042-.14.018-1.434 1.967-2.18 2.945-1.726 1.845-.414.164-.717-.37.067-.662.401-.589 2.388-3.036 1.44-1.882.93-1.086-.006-.158h-.055L4.132 18.56l-1.13.146-.487-.456.061-.746.231-.243 1.908-1.312-.006.006z"
|
||||
fill="var(--color-brand)"
|
||||
fillRule="nonzero"
|
||||
/>
|
||||
</svg>
|
||||
</div>
|
||||
<div className="flex items-center gap-1 pt-2">
|
||||
<span className="chat-typing-indicator" aria-hidden="true">
|
||||
<span></span><span></span><span></span>
|
||||
<span></span>
|
||||
<span></span>
|
||||
<span></span>
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
<ConversationScrollButtons hasUserMessages={entries.some((e) => e.type === "user_message")} />
|
||||
<ConversationScrollButtons hasUserMessages={entries.some(e => e.type === 'user_message')} />
|
||||
</ConversationContent>
|
||||
</Conversation>
|
||||
);
|
||||
@@ -88,22 +96,22 @@ export function ChatView({
|
||||
function entrySpacing(entries: ThreadEntry[], index: number): string {
|
||||
const entry = entries[index];
|
||||
// 用户消息前后大留白 — Claude.ai 式宽松间距
|
||||
if (entry?.type === "user_message") {
|
||||
return "pt-10 pb-3";
|
||||
if (entry?.type === 'user_message') {
|
||||
return 'pt-10 pb-3';
|
||||
}
|
||||
// 助手消息 — 工具调用紧贴,否则多留白
|
||||
if (entry?.type === "assistant_message") {
|
||||
if (entry?.type === 'assistant_message') {
|
||||
const next = entries[index + 1];
|
||||
if (next?.type === "tool_call") {
|
||||
return "pt-3 pb-1";
|
||||
if (next?.type === 'tool_call') {
|
||||
return 'pt-3 pb-1';
|
||||
}
|
||||
return "pt-3 pb-8";
|
||||
return 'pt-3 pb-8';
|
||||
}
|
||||
// Plan 条目
|
||||
if (entry?.type === "plan") {
|
||||
return "pt-3 pb-3";
|
||||
if (entry?.type === 'plan') {
|
||||
return 'pt-3 pb-3';
|
||||
}
|
||||
return "py-2";
|
||||
return 'py-2';
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
@@ -120,18 +128,13 @@ function EntryRenderer({
|
||||
onPermissionRespond?: (requestId: string, optionId: string | null, optionKind: string | null) => void;
|
||||
}) {
|
||||
switch (entry.type) {
|
||||
case "user_message":
|
||||
case 'user_message':
|
||||
return <UserBubble entry={entry} />;
|
||||
case "assistant_message":
|
||||
case 'assistant_message':
|
||||
return <AssistantBubble entry={entry} isStreaming={isLoading} />;
|
||||
case "tool_call":
|
||||
return (
|
||||
<ToolCallGroup
|
||||
entries={[entry as ToolCallEntry]}
|
||||
onPermissionRespond={onPermissionRespond}
|
||||
/>
|
||||
);
|
||||
case "plan":
|
||||
case 'tool_call':
|
||||
return <ToolCallGroup entries={[entry as ToolCallEntry]} onPermissionRespond={onPermissionRespond} />;
|
||||
case 'plan':
|
||||
return <PlanDisplay entry={entry as PlanDisplayEntry} />;
|
||||
default:
|
||||
return null;
|
||||
@@ -142,9 +145,7 @@ function EntryRenderer({
|
||||
// 工具调用分组逻辑
|
||||
// =============================================================================
|
||||
|
||||
type GroupedItem =
|
||||
| { type: "single"; entry: ThreadEntry }
|
||||
| { type: "tool_group"; entries: ToolCallEntry[] };
|
||||
type GroupedItem = { type: 'single'; entry: ThreadEntry } | { type: 'tool_group'; entries: ToolCallEntry[] };
|
||||
|
||||
function groupToolCalls(entries: ThreadEntry[]): GroupedItem[] {
|
||||
const result: GroupedItem[] = [];
|
||||
@@ -152,19 +153,19 @@ function groupToolCalls(entries: ThreadEntry[]): GroupedItem[] {
|
||||
|
||||
const flushToolGroup = () => {
|
||||
if (currentToolGroup.length === 1) {
|
||||
result.push({ type: "single", entry: currentToolGroup[0] });
|
||||
result.push({ type: 'single', entry: currentToolGroup[0] });
|
||||
} else if (currentToolGroup.length > 1) {
|
||||
result.push({ type: "tool_group", entries: currentToolGroup });
|
||||
result.push({ type: 'tool_group', entries: currentToolGroup });
|
||||
}
|
||||
currentToolGroup = [];
|
||||
};
|
||||
|
||||
for (const entry of entries) {
|
||||
if (entry.type === "tool_call") {
|
||||
if (entry.type === 'tool_call') {
|
||||
currentToolGroup.push(entry);
|
||||
} else {
|
||||
flushToolGroup();
|
||||
result.push({ type: "single", entry });
|
||||
result.push({ type: 'single', entry });
|
||||
}
|
||||
}
|
||||
flushToolGroup();
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { useMemo, useRef, useEffect, useState } from "react";
|
||||
import { cn } from "../../src/lib/utils";
|
||||
import type { AvailableCommand } from "../../src/acp/types";
|
||||
import { useMemo, useRef, useEffect, useState } from 'react';
|
||||
import { cn } from '../../src/lib/utils';
|
||||
import type { AvailableCommand } from '../../src/acp/types';
|
||||
|
||||
// =============================================================================
|
||||
// Slash command picker — floating above ChatInput
|
||||
@@ -23,22 +23,14 @@ function prefixMatch(query: string, text: string): boolean {
|
||||
return text.toLowerCase().startsWith(query.toLowerCase());
|
||||
}
|
||||
|
||||
export function CommandMenu({
|
||||
commands,
|
||||
filter,
|
||||
onSelect,
|
||||
onClose,
|
||||
className,
|
||||
}: CommandMenuProps) {
|
||||
export function CommandMenu({ commands, filter, onSelect, onClose, className }: CommandMenuProps) {
|
||||
const containerRef = useRef<HTMLDivElement>(null);
|
||||
const [activeIndex, setActiveIndex] = useState(0);
|
||||
|
||||
// Filter commands by current input
|
||||
const filtered = useMemo(() => {
|
||||
if (!filter) return commands;
|
||||
return commands.filter(
|
||||
(cmd) => prefixMatch(filter, cmd.name),
|
||||
);
|
||||
return commands.filter(cmd => prefixMatch(filter, cmd.name));
|
||||
}, [commands, filter]);
|
||||
|
||||
// Reset active index when filter changes
|
||||
@@ -53,8 +45,8 @@ export function CommandMenu({
|
||||
onClose();
|
||||
}
|
||||
};
|
||||
document.addEventListener("mousedown", handleClick);
|
||||
return () => document.removeEventListener("mousedown", handleClick);
|
||||
document.addEventListener('mousedown', handleClick);
|
||||
return () => document.removeEventListener('mousedown', handleClick);
|
||||
}, [onClose]);
|
||||
|
||||
// Handle keyboard navigation (ArrowUp/ArrowDown/Enter) via document-level listener
|
||||
@@ -62,21 +54,21 @@ export function CommandMenu({
|
||||
const handleKeyDown = (e: KeyboardEvent) => {
|
||||
if (filtered.length === 0) return;
|
||||
|
||||
if (e.key === "ArrowDown") {
|
||||
if (e.key === 'ArrowDown') {
|
||||
e.preventDefault();
|
||||
setActiveIndex((prev) => (prev + 1) % filtered.length);
|
||||
} else if (e.key === "ArrowUp") {
|
||||
setActiveIndex(prev => (prev + 1) % filtered.length);
|
||||
} else if (e.key === 'ArrowUp') {
|
||||
e.preventDefault();
|
||||
setActiveIndex((prev) => (prev - 1 + filtered.length) % filtered.length);
|
||||
} else if (e.key === "Enter" && !e.shiftKey) {
|
||||
setActiveIndex(prev => (prev - 1 + filtered.length) % filtered.length);
|
||||
} else if (e.key === 'Enter' && !e.shiftKey) {
|
||||
e.preventDefault();
|
||||
const cmd = filtered[activeIndex];
|
||||
if (cmd) onSelect(cmd);
|
||||
}
|
||||
};
|
||||
|
||||
document.addEventListener("keydown", handleKeyDown, true); // capture phase
|
||||
return () => document.removeEventListener("keydown", handleKeyDown, true);
|
||||
document.addEventListener('keydown', handleKeyDown, true); // capture phase
|
||||
return () => document.removeEventListener('keydown', handleKeyDown, true);
|
||||
}, [filtered, activeIndex, onSelect]);
|
||||
|
||||
// Scroll active item into view
|
||||
@@ -84,22 +76,14 @@ export function CommandMenu({
|
||||
const container = containerRef.current;
|
||||
if (!container) return;
|
||||
const active = container.querySelector("[data-active='true']");
|
||||
active?.scrollIntoView({ block: "nearest" });
|
||||
active?.scrollIntoView({ block: 'nearest' });
|
||||
}, [activeIndex]);
|
||||
|
||||
return (
|
||||
<div
|
||||
ref={containerRef}
|
||||
className={cn(
|
||||
"rounded-xl border border-border bg-surface-2 shadow-lg",
|
||||
className,
|
||||
)}
|
||||
>
|
||||
<div ref={containerRef} className={cn('rounded-xl border border-border bg-surface-2 shadow-lg', className)}>
|
||||
<div className="max-h-[320px] overflow-y-auto py-1">
|
||||
{filtered.length === 0 ? (
|
||||
<div className="text-xs text-text-muted font-display py-3 text-center">
|
||||
没有匹配的命令
|
||||
</div>
|
||||
<div className="text-xs text-text-muted font-display py-3 text-center">没有匹配的命令</div>
|
||||
) : (
|
||||
filtered.map((cmd, index) => (
|
||||
<button
|
||||
@@ -109,25 +93,15 @@ export function CommandMenu({
|
||||
onClick={() => onSelect(cmd)}
|
||||
onMouseEnter={() => setActiveIndex(index)}
|
||||
className={cn(
|
||||
"flex w-full items-center gap-2 px-3 py-2 cursor-pointer rounded-lg mx-1 text-left",
|
||||
"transition-colors",
|
||||
index === activeIndex
|
||||
? "bg-brand/10 text-text-primary"
|
||||
: "text-text-secondary hover:bg-surface-1/50",
|
||||
'flex w-full items-center gap-2 px-3 py-2 cursor-pointer rounded-lg mx-1 text-left',
|
||||
'transition-colors',
|
||||
index === activeIndex ? 'bg-brand/10 text-text-primary' : 'text-text-secondary hover:bg-surface-1/50',
|
||||
)}
|
||||
style={{ width: "calc(100% - 8px)" }}
|
||||
style={{ width: 'calc(100% - 8px)' }}
|
||||
>
|
||||
<span className="text-sm font-display font-medium text-brand">
|
||||
/{cmd.name}
|
||||
</span>
|
||||
<span className="text-xs text-text-muted truncate flex-1">
|
||||
{cmd.description}
|
||||
</span>
|
||||
{cmd.input?.hint && (
|
||||
<span className="text-[10px] text-text-muted italic">
|
||||
{cmd.input.hint}
|
||||
</span>
|
||||
)}
|
||||
<span className="text-sm font-display font-medium text-brand">/{cmd.name}</span>
|
||||
<span className="text-xs text-text-muted truncate flex-1">{cmd.description}</span>
|
||||
{cmd.input?.hint && <span className="text-[10px] text-text-muted italic">{cmd.input.hint}</span>}
|
||||
</button>
|
||||
))
|
||||
)}
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
import { useState, useRef, useEffect, useCallback } from "react";
|
||||
import type { UserMessageEntry, AssistantMessageEntry, UserMessageImage } from "../../src/lib/types";
|
||||
import { cn, esc } from "../../src/lib/utils";
|
||||
import { MessageResponse } from "../ai-elements/message";
|
||||
import { Reasoning, ReasoningTrigger, ReasoningContent } from "../ai-elements/reasoning";
|
||||
import { ChevronDown } from "lucide-react";
|
||||
import { useState, useRef, useEffect, useCallback } from 'react';
|
||||
import type { UserMessageEntry, AssistantMessageEntry, UserMessageImage } from '../../src/lib/types';
|
||||
import { cn, esc } from '../../src/lib/utils';
|
||||
import { MessageResponse } from '../ai-elements/message';
|
||||
import { Reasoning, ReasoningTrigger, ReasoningContent } from '../ai-elements/reasoning';
|
||||
import { ChevronDown } from 'lucide-react';
|
||||
|
||||
// 用户消息折叠最大高度(px)
|
||||
const COLLAPSED_MAX_HEIGHT = 200;
|
||||
@@ -48,7 +48,7 @@ export function UserBubble({ entry }: UserBubbleProps) {
|
||||
<div
|
||||
ref={contentRef}
|
||||
className={cn(
|
||||
"px-5 py-3 text-sm text-white whitespace-pre-wrap font-display leading-relaxed",
|
||||
'px-5 py-3 text-sm text-white whitespace-pre-wrap font-display leading-relaxed',
|
||||
!expanded && overflowing && `max-h-[${COLLAPSED_MAX_HEIGHT}px]`,
|
||||
)}
|
||||
style={!expanded && overflowing ? { maxHeight: `${COLLAPSED_MAX_HEIGHT}px` } : undefined}
|
||||
@@ -90,7 +90,11 @@ export function AssistantBubble({ entry, isStreaming }: AssistantBubbleProps) {
|
||||
{/* Orange triangle avatar */}
|
||||
<div className="w-8 h-8 rounded-lg bg-brand/8 flex items-center justify-center flex-shrink-0 mt-0.5">
|
||||
<svg width="20" height="20" viewBox="0 0 24 24" aria-hidden="true">
|
||||
<path d="M4.709 15.955l4.72-2.647.08-.23-.08-.128H9.2l-.79-.048-2.698-.073-2.339-.097-2.266-.122-.571-.121L0 11.784l.055-.352.48-.321.686.06 1.52.103 2.278.158 1.652.097 2.449.255h.389l.055-.157-.134-.098-.103-.097-2.358-1.596-2.552-1.688-1.336-.972-.724-.491-.364-.462-.158-1.008.656-.722.881.06.225.061.893.686 1.908 1.476 2.491 1.833.365.304.145-.103.019-.073-.164-.274-1.355-2.446-1.446-2.49-.644-1.032-.17-.619a2.97 2.97 0 01-.104-.729L6.283.134 6.696 0l.996.134.42.364.62 1.414 1.002 2.229 1.555 3.03.456.898.243.832.091.255h.158V9.01l.128-1.706.237-2.095.23-2.695.08-.76.376-.91.747-.492.584.28.48.685-.067.444-.286 1.851-.559 2.903-.364 1.942h.212l.243-.242.985-1.306 1.652-2.064.73-.82.85-.904.547-.431h1.033l.76 1.129-.34 1.166-1.064 1.347-.881 1.142-1.264 1.7-.79 1.36.073.11.188-.02 2.856-.606 1.543-.28 1.841-.315.833.388.091.395-.328.807-1.969.486-2.309.462-3.439.813-.042.03.049.061 1.549.146.662.036h1.622l3.02.225.79.522.474.638-.079.485-1.215.62-1.64-.389-3.829-.91-1.312-.329h-.182v.11l1.093 1.068 2.006 1.81 2.509 2.33.127.578-.322.455-.34-.049-2.205-1.657-.851-.747-1.926-1.62h-.128v.17l.444.649 2.345 3.521.122 1.08-.17.353-.608.213-.668-.122-1.374-1.925-1.415-2.167-1.143-1.943-.14.08-.674 7.254-.316.37-.729.28-.607-.461-.322-.747.322-1.476.389-1.924.315-1.53.286-1.9.17-.632-.012-.042-.14.018-1.434 1.967-2.18 2.945-1.726 1.845-.414.164-.717-.37.067-.662.401-.589 2.388-3.036 1.44-1.882.93-1.086-.006-.158h-.055L4.132 18.56l-1.13.146-.487-.456.061-.746.231-.243 1.908-1.312-.006.006z" fill="var(--color-brand)" fillRule="nonzero" />
|
||||
<path
|
||||
d="M4.709 15.955l4.72-2.647.08-.23-.08-.128H9.2l-.79-.048-2.698-.073-2.339-.097-2.266-.122-.571-.121L0 11.784l.055-.352.48-.321.686.06 1.52.103 2.278.158 1.652.097 2.449.255h.389l.055-.157-.134-.098-.103-.097-2.358-1.596-2.552-1.688-1.336-.972-.724-.491-.364-.462-.158-1.008.656-.722.881.06.225.061.893.686 1.908 1.476 2.491 1.833.365.304.145-.103.019-.073-.164-.274-1.355-2.446-1.446-2.49-.644-1.032-.17-.619a2.97 2.97 0 01-.104-.729L6.283.134 6.696 0l.996.134.42.364.62 1.414 1.002 2.229 1.555 3.03.456.898.243.832.091.255h.158V9.01l.128-1.706.237-2.095.23-2.695.08-.76.376-.91.747-.492.584.28.48.685-.067.444-.286 1.851-.559 2.903-.364 1.942h.212l.243-.242.985-1.306 1.652-2.064.73-.82.85-.904.547-.431h1.033l.76 1.129-.34 1.166-1.064 1.347-.881 1.142-1.264 1.7-.79 1.36.073.11.188-.02 2.856-.606 1.543-.28 1.841-.315.833.388.091.395-.328.807-1.969.486-2.309.462-3.439.813-.042.03.049.061 1.549.146.662.036h1.622l3.02.225.79.522.474.638-.079.485-1.215.62-1.64-.389-3.829-.91-1.312-.329h-.182v.11l1.093 1.068 2.006 1.81 2.509 2.33.127.578-.322.455-.34-.049-2.205-1.657-.851-.747-1.926-1.62h-.128v.17l.444.649 2.345 3.521.122 1.08-.17.353-.608.213-.668-.122-1.374-1.925-1.415-2.167-1.143-1.943-.14.08-.674 7.254-.316.37-.729.28-.607-.461-.322-.747.322-1.476.389-1.924.315-1.53.286-1.9.17-.632-.012-.042-.14.018-1.434 1.967-2.18 2.945-1.726 1.845-.414.164-.717-.37.067-.662.401-.589 2.388-3.036 1.44-1.882.93-1.086-.006-.158h-.055L4.132 18.56l-1.13.146-.487-.456.061-.746.231-.243 1.908-1.312-.006.006z"
|
||||
fill="var(--color-brand)"
|
||||
fillRule="nonzero"
|
||||
/>
|
||||
</svg>
|
||||
</div>
|
||||
{/* 内容 — 无卡片背景,直接排版 */}
|
||||
@@ -98,16 +102,14 @@ export function AssistantBubble({ entry, isStreaming }: AssistantBubbleProps) {
|
||||
{/* Sender label */}
|
||||
<span className="text-sm font-semibold text-text-primary font-display">Claude</span>
|
||||
{entry.chunks.map((chunk, i) => {
|
||||
if (chunk.type === "thought") {
|
||||
if (chunk.type === 'thought') {
|
||||
const isLastChunk = i === entry.chunks.length - 1;
|
||||
const isThoughtStreaming = isStreaming && isLastChunk;
|
||||
return (
|
||||
<Reasoning key={i} isStreaming={isThoughtStreaming}>
|
||||
<ReasoningTrigger />
|
||||
<ReasoningContent>
|
||||
<div className="text-sm text-text-secondary leading-relaxed">
|
||||
{chunk.text}
|
||||
</div>
|
||||
<div className="text-sm text-text-secondary leading-relaxed">{chunk.text}</div>
|
||||
</ReasoningContent>
|
||||
</Reasoning>
|
||||
);
|
||||
@@ -135,17 +137,13 @@ function ImageThumbnail({ image }: { image: UserMessageImage }) {
|
||||
type="button"
|
||||
className="rounded-lg overflow-hidden border border-border hover:border-brand/40 transition-colors cursor-pointer"
|
||||
onClick={() => {
|
||||
const w = window.open("");
|
||||
const w = window.open('');
|
||||
if (w) {
|
||||
w.document.write(`<img src="${dataUrl}" style="max-width:100%;max-height:100%" />`);
|
||||
}
|
||||
}}
|
||||
>
|
||||
<img
|
||||
src={dataUrl}
|
||||
alt="Uploaded image"
|
||||
className="h-20 w-20 object-cover"
|
||||
/>
|
||||
<img src={dataUrl} alt="Uploaded image" className="h-20 w-20 object-cover" />
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import type { PendingPermission } from "../../src/lib/types";
|
||||
import { cn } from "../../src/lib/utils";
|
||||
import { ShieldAlert, Check, X } from "lucide-react";
|
||||
import type { PendingPermission } from '../../src/lib/types';
|
||||
import { cn } from '../../src/lib/utils';
|
||||
import { ShieldAlert, Check, X } from 'lucide-react';
|
||||
|
||||
// =============================================================================
|
||||
// 权限请求面板 — 固定在输入框上方(Anthropic warm token style)
|
||||
@@ -16,14 +16,10 @@ export function PermissionPanel({ requests, onRespond, className }: PermissionPa
|
||||
if (requests.length === 0) return null;
|
||||
|
||||
return (
|
||||
<div className={cn("w-full max-w-3xl mx-auto px-4", className)}>
|
||||
<div className={cn('w-full max-w-3xl mx-auto px-4', className)}>
|
||||
<div className="space-y-2">
|
||||
{requests.map((req) => (
|
||||
<PermissionCard
|
||||
key={req.requestId}
|
||||
request={req}
|
||||
onRespond={onRespond}
|
||||
/>
|
||||
{requests.map(req => (
|
||||
<PermissionCard key={req.requestId} request={req} onRespond={onRespond} />
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
@@ -44,13 +40,9 @@ function PermissionCard({ request, onRespond }: PermissionCardProps) {
|
||||
<div className="flex items-center gap-3 rounded-xl border border-warning-border/30 bg-warning-bg/50 px-4 py-3">
|
||||
<ShieldAlert className="h-5 w-5 text-warning-text flex-shrink-0" />
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="text-sm font-medium text-warning-text">
|
||||
{request.toolName}
|
||||
</div>
|
||||
<div className="text-sm font-medium text-warning-text">{request.toolName}</div>
|
||||
{request.description && (
|
||||
<div className="text-xs text-warning-text/80 mt-0.5 truncate">
|
||||
{request.description}
|
||||
</div>
|
||||
<div className="text-xs text-warning-text/80 mt-0.5 truncate">{request.description}</div>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex items-center gap-2 flex-shrink-0">
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import { useState } from "react";
|
||||
import type { PlanDisplayEntry } from "../../src/lib/types";
|
||||
import type { PlanEntry, PlanEntryPriority, PlanEntryStatus } from "../../src/acp/types";
|
||||
import { cn } from "../../src/lib/utils";
|
||||
import { CheckCircle2, Loader2, Circle } from "lucide-react";
|
||||
import { useState } from 'react';
|
||||
import type { PlanDisplayEntry } from '../../src/lib/types';
|
||||
import type { PlanEntry, PlanEntryPriority, PlanEntryStatus } from '../../src/acp/types';
|
||||
import { cn } from '../../src/lib/utils';
|
||||
import { CheckCircle2, Loader2, Circle } from 'lucide-react';
|
||||
|
||||
// =============================================================================
|
||||
// Plan 展示组件 — 执行计划可视化
|
||||
@@ -18,7 +18,7 @@ export function PlanDisplay({ entry }: PlanDisplayProps) {
|
||||
|
||||
if (entries.length === 0) return null;
|
||||
|
||||
const completed = entries.filter((e) => e.status === "completed").length;
|
||||
const completed = entries.filter(e => e.status === 'completed').length;
|
||||
const total = entries.length;
|
||||
const percentage = total > 0 ? Math.round((completed / total) * 100) : 0;
|
||||
|
||||
@@ -36,14 +36,12 @@ export function PlanDisplay({ entry }: PlanDisplayProps) {
|
||||
height="12"
|
||||
viewBox="0 0 12 12"
|
||||
fill="none"
|
||||
className={cn("transition-transform text-text-muted flex-shrink-0", collapsed && "rotate-90")}
|
||||
className={cn('transition-transform text-text-muted flex-shrink-0', collapsed && 'rotate-90')}
|
||||
>
|
||||
<path d="M4 2L8 6L4 10" stroke="currentColor" strokeWidth="1.5" fill="none" />
|
||||
</svg>
|
||||
|
||||
<span className="text-xs font-display font-medium text-text-secondary">
|
||||
执行计划
|
||||
</span>
|
||||
<span className="text-xs font-display font-medium text-text-secondary">执行计划</span>
|
||||
|
||||
<span className="text-[10px] text-text-muted font-mono">
|
||||
{completed}/{total}
|
||||
@@ -57,17 +55,14 @@ export function PlanDisplay({ entry }: PlanDisplayProps) {
|
||||
/>
|
||||
</div>
|
||||
|
||||
<span className="text-[10px] text-text-muted font-mono">
|
||||
{percentage}%
|
||||
</span>
|
||||
<span className="text-[10px] text-text-muted font-mono">{percentage}%</span>
|
||||
</button>
|
||||
|
||||
{/* Entry list */}
|
||||
{!collapsed && (
|
||||
<div className={cn(
|
||||
"border-t border-border px-3 py-1.5 space-y-0.5",
|
||||
total > 5 && "max-h-64 overflow-y-auto",
|
||||
)}>
|
||||
<div
|
||||
className={cn('border-t border-border px-3 py-1.5 space-y-0.5', total > 5 && 'max-h-64 overflow-y-auto')}
|
||||
>
|
||||
{entries.map((planEntry, i) => (
|
||||
<PlanEntryRow key={i} entry={planEntry} />
|
||||
))}
|
||||
@@ -88,11 +83,13 @@ function PlanEntryRow({ entry }: { entry: PlanEntry }) {
|
||||
<span className="flex-shrink-0 mt-0.5">
|
||||
<StatusIcon status={entry.status} />
|
||||
</span>
|
||||
<span className={cn(
|
||||
"text-xs leading-relaxed flex-1",
|
||||
entry.status === "completed" ? "text-text-muted line-through" : "text-text-secondary",
|
||||
entry.status === "in_progress" && "text-text-primary font-medium",
|
||||
)}>
|
||||
<span
|
||||
className={cn(
|
||||
'text-xs leading-relaxed flex-1',
|
||||
entry.status === 'completed' ? 'text-text-muted line-through' : 'text-text-secondary',
|
||||
entry.status === 'in_progress' && 'text-text-primary font-medium',
|
||||
)}
|
||||
>
|
||||
{entry.content}
|
||||
</span>
|
||||
<PriorityBadge priority={entry.priority} />
|
||||
@@ -106,11 +103,11 @@ function PlanEntryRow({ entry }: { entry: PlanEntry }) {
|
||||
|
||||
function StatusIcon({ status }: { status: PlanEntryStatus }) {
|
||||
switch (status) {
|
||||
case "completed":
|
||||
case 'completed':
|
||||
return <CheckCircle2 className="h-3.5 w-3.5 text-status-active" />;
|
||||
case "in_progress":
|
||||
return <Loader2 className="h-3.5 w-3.5 text-brand animate-spin" style={{ animationDuration: "2s" }} />;
|
||||
case "pending":
|
||||
case 'in_progress':
|
||||
return <Loader2 className="h-3.5 w-3.5 text-brand animate-spin" style={{ animationDuration: '2s' }} />;
|
||||
case 'pending':
|
||||
return <Circle className="h-3.5 w-3.5 text-text-muted" />;
|
||||
}
|
||||
}
|
||||
@@ -121,22 +118,21 @@ function StatusIcon({ status }: { status: PlanEntryStatus }) {
|
||||
|
||||
function PriorityBadge({ priority }: { priority: PlanEntryPriority }) {
|
||||
const styles: Record<PlanEntryPriority, string> = {
|
||||
high: "bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-300",
|
||||
medium: "bg-brand/10 text-brand dark:bg-brand/20",
|
||||
low: "bg-surface-1 text-text-muted",
|
||||
high: 'bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-300',
|
||||
medium: 'bg-brand/10 text-brand dark:bg-brand/20',
|
||||
low: 'bg-surface-1 text-text-muted',
|
||||
};
|
||||
|
||||
const labels: Record<PlanEntryPriority, string> = {
|
||||
high: "高",
|
||||
medium: "中",
|
||||
low: "低",
|
||||
high: '高',
|
||||
medium: '中',
|
||||
low: '低',
|
||||
};
|
||||
|
||||
return (
|
||||
<span className={cn(
|
||||
"text-[9px] font-display rounded-full px-1.5 py-0.5 flex-shrink-0 leading-none",
|
||||
styles[priority],
|
||||
)}>
|
||||
<span
|
||||
className={cn('text-[9px] font-display rounded-full px-1.5 py-0.5 flex-shrink-0 leading-none', styles[priority])}
|
||||
>
|
||||
{labels[priority]}
|
||||
</span>
|
||||
);
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { cn } from "../../src/lib/utils";
|
||||
import { Plus, MessageSquare, ChevronLeft, ChevronRight } from "lucide-react";
|
||||
import { useState } from "react";
|
||||
import type { SessionListItem } from "../../src/lib/types";
|
||||
import { cn } from '../../src/lib/utils';
|
||||
import { Plus, MessageSquare, ChevronLeft, ChevronRight } from 'lucide-react';
|
||||
import { useState } from 'react';
|
||||
import type { SessionListItem } from '../../src/lib/types';
|
||||
|
||||
// =============================================================================
|
||||
// 会话侧边栏 — Anthropic 分段式:今天/昨天/更早 + 橙色活跃态
|
||||
@@ -15,13 +15,7 @@ interface SessionSidebarProps {
|
||||
className?: string;
|
||||
}
|
||||
|
||||
export function SessionSidebar({
|
||||
sessions,
|
||||
activeId,
|
||||
onSelect,
|
||||
onNew,
|
||||
className,
|
||||
}: SessionSidebarProps) {
|
||||
export function SessionSidebar({ sessions, activeId, onSelect, onNew, className }: SessionSidebarProps) {
|
||||
const [collapsed, setCollapsed] = useState(false);
|
||||
|
||||
// 按日期分组
|
||||
@@ -30,8 +24,8 @@ export function SessionSidebar({
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
"hidden md:flex flex-col border-r border-border bg-surface-1 transition-all duration-200",
|
||||
collapsed ? "w-12" : "w-64",
|
||||
'hidden md:flex flex-col border-r border-border bg-surface-1 transition-all duration-200',
|
||||
collapsed ? 'w-12' : 'w-64',
|
||||
className,
|
||||
)}
|
||||
>
|
||||
@@ -55,11 +49,7 @@ export function SessionSidebar({
|
||||
onClick={() => setCollapsed(!collapsed)}
|
||||
className="h-7 w-7 flex items-center justify-center rounded-lg text-text-muted hover:text-text-primary hover:bg-surface-2 transition-colors"
|
||||
>
|
||||
{collapsed ? (
|
||||
<ChevronRight className="h-4 w-4" />
|
||||
) : (
|
||||
<ChevronLeft className="h-4 w-4" />
|
||||
)}
|
||||
{collapsed ? <ChevronRight className="h-4 w-4" /> : <ChevronLeft className="h-4 w-4" />}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
@@ -67,30 +57,28 @@ export function SessionSidebar({
|
||||
{/* 会话列表 — 分段 */}
|
||||
{!collapsed && (
|
||||
<nav className="flex-1 overflow-y-auto py-2" aria-label="历史会话">
|
||||
{groups.map((group) => (
|
||||
{groups.map(group => (
|
||||
<div key={group.label}>
|
||||
<div className="px-3 py-1.5">
|
||||
<span className="text-[10px] font-display font-medium uppercase tracking-widest text-text-muted">
|
||||
{group.label}
|
||||
</span>
|
||||
</div>
|
||||
{group.sessions.map((session) => (
|
||||
{group.sessions.map(session => (
|
||||
<button
|
||||
key={session.id}
|
||||
type="button"
|
||||
onClick={() => onSelect?.(session.id)}
|
||||
className={cn(
|
||||
"w-full flex items-center gap-2 px-3 py-2 text-left transition-colors",
|
||||
'w-full flex items-center gap-2 px-3 py-2 text-left transition-colors',
|
||||
session.id === activeId
|
||||
? "bg-brand/10 text-text-primary"
|
||||
: "text-text-secondary hover:bg-surface-1/50 hover:text-text-primary",
|
||||
? 'bg-brand/10 text-text-primary'
|
||||
: 'text-text-secondary hover:bg-surface-1/50 hover:text-text-primary',
|
||||
)}
|
||||
title={session.title || session.id}
|
||||
>
|
||||
<MessageSquare className="h-3.5 w-3.5 shrink-0 text-text-muted" />
|
||||
<span className="text-sm font-display truncate">
|
||||
{session.title || session.id.slice(0, 8)}
|
||||
</span>
|
||||
<span className="text-sm font-display truncate">{session.title || session.id.slice(0, 8)}</span>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
@@ -121,9 +109,9 @@ function groupByRecency(sessions: SessionListItem[]): SessionGroup[] {
|
||||
const yesterday = new Date(today.getTime() - 86400000);
|
||||
|
||||
const groups: SessionGroup[] = [
|
||||
{ label: "今天", sessions: [] },
|
||||
{ label: "昨天", sessions: [] },
|
||||
{ label: "更早", sessions: [] },
|
||||
{ label: '今天', sessions: [] },
|
||||
{ label: '昨天', sessions: [] },
|
||||
{ label: '更早', sessions: [] },
|
||||
];
|
||||
|
||||
for (const session of sessions) {
|
||||
@@ -137,5 +125,5 @@ function groupByRecency(sessions: SessionListItem[]): SessionGroup[] {
|
||||
}
|
||||
}
|
||||
|
||||
return groups.filter((g) => g.sessions.length > 0);
|
||||
return groups.filter(g => g.sessions.length > 0);
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { useState } from "react";
|
||||
import type { ToolCallEntry, ToolCallData } from "../../src/lib/types";
|
||||
import { cn } from "../../src/lib/utils";
|
||||
import { ToolPermissionButtons } from "../ai-elements/permission-request";
|
||||
import { useState } from 'react';
|
||||
import type { ToolCallEntry, ToolCallData } from '../../src/lib/types';
|
||||
import { cn } from '../../src/lib/utils';
|
||||
import { ToolPermissionButtons } from '../ai-elements/permission-request';
|
||||
|
||||
// =============================================================================
|
||||
// 工具调用折叠组 — Anthropic: subtle card, left-border accent, compact layout
|
||||
@@ -21,11 +21,7 @@ export function ToolCallGroup({ entries, onPermissionRespond }: ToolCallGroupPro
|
||||
if (entries.length === 1) {
|
||||
return (
|
||||
<div className="pl-10">
|
||||
<SingleToolCard
|
||||
tool={entries[0].toolCall}
|
||||
compact
|
||||
onPermissionRespond={onPermissionRespond}
|
||||
/>
|
||||
<SingleToolCard tool={entries[0].toolCall} compact onPermissionRespond={onPermissionRespond} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -47,7 +43,7 @@ export function ToolCallGroup({ entries, onPermissionRespond }: ToolCallGroupPro
|
||||
height="12"
|
||||
viewBox="0 0 12 12"
|
||||
fill="none"
|
||||
className={cn("transition-transform text-text-muted", expanded && "rotate-90")}
|
||||
className={cn('transition-transform text-text-muted', expanded && 'rotate-90')}
|
||||
>
|
||||
<path d="M4 2L8 6L4 10" stroke="currentColor" strokeWidth="1.5" fill="none" />
|
||||
</svg>
|
||||
@@ -87,27 +83,28 @@ function SingleToolCard({ tool, compact, onPermissionRespond }: SingleToolCardPr
|
||||
|
||||
const statusIcon = (() => {
|
||||
switch (tool.status) {
|
||||
case "running":
|
||||
case 'running':
|
||||
return <span className="text-status-running text-[10px]">▶</span>;
|
||||
case "complete":
|
||||
case 'complete':
|
||||
return <span className="text-status-active text-[10px]">✓</span>;
|
||||
case "error":
|
||||
case 'error':
|
||||
return <span className="text-status-error text-[10px]">✕</span>;
|
||||
case "waiting_for_confirmation":
|
||||
case 'waiting_for_confirmation':
|
||||
return <span className="text-brand text-[10px]">⍻</span>;
|
||||
case "canceled":
|
||||
case 'canceled':
|
||||
return <span className="text-text-muted text-[10px]">—</span>;
|
||||
case "rejected":
|
||||
case 'rejected':
|
||||
return <span className="text-status-error text-[10px]">✕</span>;
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
})();
|
||||
|
||||
const hasOutput = tool.status !== "running" && tool.status !== "waiting_for_confirmation" && (tool.rawOutput || tool.content);
|
||||
const hasOutput =
|
||||
tool.status !== 'running' && tool.status !== 'waiting_for_confirmation' && (tool.rawOutput || tool.content);
|
||||
|
||||
return (
|
||||
<div className={cn("px-3 py-2", compact && "py-1.5")}>
|
||||
<div className={cn('px-3 py-2', compact && 'py-1.5')}>
|
||||
{/* 标题行 — 单行紧凑 */}
|
||||
<button
|
||||
type="button"
|
||||
@@ -118,13 +115,11 @@ function SingleToolCard({ tool, compact, onPermissionRespond }: SingleToolCardPr
|
||||
<span className="text-xs font-display font-medium text-text-secondary group-hover:text-text-primary transition-colors truncate">
|
||||
{tool.title}
|
||||
</span>
|
||||
{tool.status === "running" && (
|
||||
<span className="text-[10px] text-status-running animate-pulse">running</span>
|
||||
)}
|
||||
{tool.status === 'running' && <span className="text-[10px] text-status-running animate-pulse">running</span>}
|
||||
</button>
|
||||
|
||||
{/* 权限请求按钮 */}
|
||||
{tool.status === "waiting_for_confirmation" && tool.permissionRequest && (
|
||||
{tool.status === 'waiting_for_confirmation' && tool.permissionRequest && (
|
||||
<div className="mt-1.5 ml-4">
|
||||
<ToolPermissionButtons
|
||||
requestId={tool.permissionRequest.requestId}
|
||||
@@ -146,10 +141,12 @@ function SingleToolCard({ tool, compact, onPermissionRespond }: SingleToolCardPr
|
||||
)}
|
||||
{hasOutput && (
|
||||
<div>
|
||||
<pre className={cn(
|
||||
"text-[11px] rounded-md p-2 overflow-x-auto font-mono max-h-36",
|
||||
tool.status === "error" ? "bg-status-error/10 text-status-error" : "bg-surface-1 text-text-secondary",
|
||||
)}>
|
||||
<pre
|
||||
className={cn(
|
||||
'text-[11px] rounded-md p-2 overflow-x-auto font-mono max-h-36',
|
||||
tool.status === 'error' ? 'bg-status-error/10 text-status-error' : 'bg-surface-1 text-text-secondary',
|
||||
)}
|
||||
>
|
||||
{formatOutput(tool)}
|
||||
</pre>
|
||||
</div>
|
||||
@@ -179,7 +176,7 @@ function buildSummary(entries: ToolCallEntry[]): string {
|
||||
|
||||
if (parts.length === 0) return `${entries.length} 个工具调用`;
|
||||
if (parts.length === 1) return parts[0];
|
||||
return `${entries.length} 个工具: ${parts.join("、")}`;
|
||||
return `${entries.length} 个工具: ${parts.join('、')}`;
|
||||
}
|
||||
|
||||
/** 简化工具名称 */
|
||||
@@ -192,17 +189,17 @@ function simplifyToolName(title: string): string {
|
||||
function formatOutput(tool: ToolCallData): string {
|
||||
if (tool.content && tool.content.length > 0) {
|
||||
const texts = tool.content
|
||||
.filter((c): c is Extract<typeof c, { type: "content" }> => c.type === "content")
|
||||
.filter((c) => c.content.type === "text" && "text" in c.content)
|
||||
.map((c) => (c.content as { text: string }).text);
|
||||
if (texts.length > 0) return truncate(texts.join("\n"), 2000);
|
||||
.filter((c): c is Extract<typeof c, { type: 'content' }> => c.type === 'content')
|
||||
.filter(c => c.content.type === 'text' && 'text' in c.content)
|
||||
.map(c => (c.content as { text: string }).text);
|
||||
if (texts.length > 0) return truncate(texts.join('\n'), 2000);
|
||||
}
|
||||
if (tool.rawOutput && Object.keys(tool.rawOutput).length > 0) {
|
||||
return truncate(JSON.stringify(tool.rawOutput, null, 2), 2000);
|
||||
}
|
||||
return "";
|
||||
return '';
|
||||
}
|
||||
|
||||
function truncate(str: string, max: number): string {
|
||||
return str.length > max ? str.slice(0, max) + "..." : str;
|
||||
return str.length > max ? str.slice(0, max) + '...' : str;
|
||||
}
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
export { ChatView } from "./ChatView";
|
||||
export { UserBubble, AssistantBubble } from "./MessageBubble";
|
||||
export { ToolCallGroup } from "./ToolCallGroup";
|
||||
export { PlanDisplay } from "./PlanView";
|
||||
export { ChatInput } from "./ChatInput";
|
||||
export { PermissionPanel } from "./PermissionPanel";
|
||||
export { SessionSidebar } from "./SessionSidebar";
|
||||
export { CommandMenu } from "./CommandMenu";
|
||||
export { ChatView } from './ChatView'
|
||||
export { UserBubble, AssistantBubble } from './MessageBubble'
|
||||
export { ToolCallGroup } from './ToolCallGroup'
|
||||
export { PlanDisplay } from './PlanView'
|
||||
export { ChatInput } from './ChatInput'
|
||||
export { PermissionPanel } from './PermissionPanel'
|
||||
export { SessionSidebar } from './SessionSidebar'
|
||||
export { CommandMenu } from './CommandMenu'
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
export * from "./ACPConnect";
|
||||
export * from "./ACPMain";
|
||||
export * from "./ChatInterface";
|
||||
export * from "./ChatMessage";
|
||||
export * from "./ThreadHistory";
|
||||
export * from "./model-selector";
|
||||
export * from './ACPConnect'
|
||||
export * from './ACPMain'
|
||||
export * from './ChatInterface'
|
||||
export * from './ChatMessage'
|
||||
export * from './ThreadHistory'
|
||||
export * from './model-selector'
|
||||
|
||||
@@ -1,15 +1,8 @@
|
||||
import { useState, useMemo } from "react";
|
||||
import { Check } from "lucide-react";
|
||||
import {
|
||||
Command,
|
||||
CommandInput,
|
||||
CommandList,
|
||||
CommandEmpty,
|
||||
CommandGroup,
|
||||
CommandItem,
|
||||
} from "../ui/command";
|
||||
import type { ModelInfo } from "../../src/acp/types";
|
||||
import { cn } from "../../src/lib/utils";
|
||||
import { useState, useMemo } from 'react';
|
||||
import { Check } from 'lucide-react';
|
||||
import { Command, CommandInput, CommandList, CommandEmpty, CommandGroup, CommandItem } from '../ui/command';
|
||||
import type { ModelInfo } from '../../src/acp/types';
|
||||
import { cn } from '../../src/lib/utils';
|
||||
|
||||
interface ModelSelectorPickerProps {
|
||||
models: ModelInfo[];
|
||||
@@ -51,33 +44,24 @@ export function ModelSelectorPicker({
|
||||
showSearch = true,
|
||||
isMobile = false,
|
||||
}: ModelSelectorPickerProps) {
|
||||
const [search, setSearch] = useState("");
|
||||
const [search, setSearch] = useState('');
|
||||
// On mobile, don't auto-select first item (no keyboard navigation needed)
|
||||
// Use a non-existent value to prevent any item from being selected
|
||||
const [selectedValue, setSelectedValue] = useState(isMobile ? "__none__" : undefined);
|
||||
const [selectedValue, setSelectedValue] = useState(isMobile ? '__none__' : undefined);
|
||||
|
||||
// Filter models using fuzzy search
|
||||
const filteredModels = useMemo(() => {
|
||||
if (!search) return models;
|
||||
return models.filter((model) =>
|
||||
fuzzyMatch(search, model.name) ||
|
||||
fuzzyMatch(search, model.modelId)
|
||||
);
|
||||
return models.filter(model => fuzzyMatch(search, model.name) || fuzzyMatch(search, model.modelId));
|
||||
}, [models, search]);
|
||||
|
||||
return (
|
||||
<Command shouldFilter={false} value={selectedValue} onValueChange={setSelectedValue}>
|
||||
{showSearch && (
|
||||
<CommandInput
|
||||
placeholder="Select a model…"
|
||||
value={search}
|
||||
onValueChange={setSearch}
|
||||
/>
|
||||
)}
|
||||
{showSearch && <CommandInput placeholder="Select a model…" value={search} onValueChange={setSearch} />}
|
||||
<CommandList>
|
||||
<CommandEmpty>No models found.</CommandEmpty>
|
||||
<CommandGroup>
|
||||
{filteredModels.map((model) => (
|
||||
{filteredModels.map(model => (
|
||||
<CommandItem
|
||||
key={model.modelId}
|
||||
value={model.modelId}
|
||||
@@ -87,16 +71,11 @@ export function ModelSelectorPicker({
|
||||
<div className="flex flex-col gap-0.5 min-w-0">
|
||||
<span className="truncate font-medium">{model.name}</span>
|
||||
{model.description && (
|
||||
<span className="text-xs text-muted-foreground truncate">
|
||||
{model.description}
|
||||
</span>
|
||||
<span className="text-xs text-muted-foreground truncate">{model.description}</span>
|
||||
)}
|
||||
</div>
|
||||
<Check
|
||||
className={cn(
|
||||
"h-4 w-4 shrink-0",
|
||||
currentModelId === model.modelId ? "opacity-100" : "opacity-0"
|
||||
)}
|
||||
className={cn('h-4 w-4 shrink-0', currentModelId === model.modelId ? 'opacity-100' : 'opacity-0')}
|
||||
/>
|
||||
</CommandItem>
|
||||
))}
|
||||
@@ -105,4 +84,3 @@ export function ModelSelectorPicker({
|
||||
</Command>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
import { useState } from "react";
|
||||
import { ChevronDown, ChevronUp, Loader2 } from "lucide-react";
|
||||
import { Button } from "../ui/button";
|
||||
import { Popover, PopoverContent, PopoverTrigger } from "../ui/popover";
|
||||
import { ModelSelectorPicker } from "./ModelSelectorPicker";
|
||||
import type { ACPClient } from "../../src/acp/client";
|
||||
import type { ModelInfo } from "../../src/acp/types";
|
||||
import { useModels } from "../../src/hooks/useModels";
|
||||
import { useState } from 'react';
|
||||
import { ChevronDown, ChevronUp, Loader2 } from 'lucide-react';
|
||||
import { Button } from '../ui/button';
|
||||
import { Popover, PopoverContent, PopoverTrigger } from '../ui/popover';
|
||||
import { ModelSelectorPicker } from './ModelSelectorPicker';
|
||||
import type { ACPClient } from '../../src/acp/client';
|
||||
import type { ModelInfo } from '../../src/acp/types';
|
||||
import { useModels } from '../../src/hooks/useModels';
|
||||
|
||||
interface ModelSelectorPopoverProps {
|
||||
/** ACPClient instance for model state management */
|
||||
@@ -18,25 +18,15 @@ interface ModelSelectorPopoverProps {
|
||||
* Model selector popover component.
|
||||
* Reference: Zed's AcpModelSelectorPopover that shows current model and allows switching.
|
||||
*/
|
||||
export function ModelSelectorPopover({
|
||||
client,
|
||||
onModelSelect,
|
||||
}: ModelSelectorPopoverProps) {
|
||||
export function ModelSelectorPopover({ client, onModelSelect }: ModelSelectorPopoverProps) {
|
||||
const [open, setOpen] = useState(false);
|
||||
const {
|
||||
supportsModelSelection,
|
||||
availableModels,
|
||||
currentModel,
|
||||
setModel,
|
||||
isLoading,
|
||||
} = useModels(client);
|
||||
const { supportsModelSelection, availableModels, currentModel, setModel, isLoading } = useModels(client);
|
||||
|
||||
// Always show the button — disable dropdown when no models available
|
||||
const hasModels = supportsModelSelection && availableModels.length > 0;
|
||||
|
||||
// Check if we're on a mobile device (touch-only)
|
||||
const isMobile = typeof window !== "undefined" &&
|
||||
window.matchMedia("(hover: none) and (pointer: coarse)").matches;
|
||||
const isMobile = typeof window !== 'undefined' && window.matchMedia('(hover: none) and (pointer: coarse)').matches;
|
||||
|
||||
const handleSelect = async (model: ModelInfo) => {
|
||||
try {
|
||||
@@ -44,7 +34,7 @@ export function ModelSelectorPopover({
|
||||
onModelSelect?.(model.modelId);
|
||||
setOpen(false);
|
||||
} catch (error) {
|
||||
console.error("[ModelSelector] Failed to set model:", error);
|
||||
console.error('[ModelSelector] Failed to set model:', error);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -57,17 +47,9 @@ export function ModelSelectorPopover({
|
||||
className="gap-1.5 text-muted-foreground hover:text-foreground h-7 px-2"
|
||||
disabled={!hasModels || isLoading}
|
||||
>
|
||||
{isLoading ? (
|
||||
<Loader2 className="h-3 w-3 animate-spin" />
|
||||
) : null}
|
||||
<span className="max-w-32 truncate">
|
||||
{currentModel?.name ?? "Select Model"}
|
||||
</span>
|
||||
{open ? (
|
||||
<ChevronUp className="h-3 w-3" />
|
||||
) : (
|
||||
<ChevronDown className="h-3 w-3" />
|
||||
)}
|
||||
{isLoading ? <Loader2 className="h-3 w-3 animate-spin" /> : null}
|
||||
<span className="max-w-32 truncate">{currentModel?.name ?? 'Select Model'}</span>
|
||||
{open ? <ChevronUp className="h-3 w-3" /> : <ChevronDown className="h-3 w-3" />}
|
||||
</Button>
|
||||
</PopoverTrigger>
|
||||
<PopoverContent className="w-72 p-0" align="end">
|
||||
@@ -82,4 +64,3 @@ export function ModelSelectorPopover({
|
||||
</Popover>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,3 +1,2 @@
|
||||
export { ModelSelectorPopover } from "./ModelSelectorPopover";
|
||||
export { ModelSelectorPicker } from "./ModelSelectorPicker";
|
||||
|
||||
export { ModelSelectorPopover } from './ModelSelectorPopover'
|
||||
export { ModelSelectorPicker } from './ModelSelectorPicker'
|
||||
|
||||
@@ -1,47 +1,36 @@
|
||||
import * as React from "react"
|
||||
import { Slot } from "@radix-ui/react-slot"
|
||||
import { cva, type VariantProps } from "class-variance-authority"
|
||||
import * as React from 'react';
|
||||
import { Slot } from '@radix-ui/react-slot';
|
||||
import { cva, type VariantProps } from 'class-variance-authority';
|
||||
|
||||
import { cn } from "../../src/lib/utils"
|
||||
import { cn } from '../../src/lib/utils';
|
||||
|
||||
const badgeVariants = cva(
|
||||
"inline-flex items-center justify-center rounded-full border px-2 py-0.5 text-xs font-medium w-fit whitespace-nowrap shrink-0 [&>svg]:size-3 gap-1 [&>svg]:pointer-events-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive transition-[color,box-shadow] overflow-hidden",
|
||||
'inline-flex items-center justify-center rounded-full border px-2 py-0.5 text-xs font-medium w-fit whitespace-nowrap shrink-0 [&>svg]:size-3 gap-1 [&>svg]:pointer-events-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive transition-[color,box-shadow] overflow-hidden',
|
||||
{
|
||||
variants: {
|
||||
variant: {
|
||||
default:
|
||||
"border-transparent bg-primary text-primary-foreground [a&]:hover:bg-primary/90",
|
||||
secondary:
|
||||
"border-transparent bg-secondary text-secondary-foreground [a&]:hover:bg-secondary/90",
|
||||
default: 'border-transparent bg-primary text-primary-foreground [a&]:hover:bg-primary/90',
|
||||
secondary: 'border-transparent bg-secondary text-secondary-foreground [a&]:hover:bg-secondary/90',
|
||||
destructive:
|
||||
"border-transparent bg-destructive text-white [a&]:hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",
|
||||
outline:
|
||||
"text-foreground [a&]:hover:bg-accent [a&]:hover:text-accent-foreground",
|
||||
'border-transparent bg-destructive text-white [a&]:hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60',
|
||||
outline: 'text-foreground [a&]:hover:bg-accent [a&]:hover:text-accent-foreground',
|
||||
},
|
||||
},
|
||||
defaultVariants: {
|
||||
variant: "default",
|
||||
variant: 'default',
|
||||
},
|
||||
}
|
||||
)
|
||||
},
|
||||
);
|
||||
|
||||
function Badge({
|
||||
className,
|
||||
variant,
|
||||
asChild = false,
|
||||
...props
|
||||
}: React.ComponentProps<"span"> &
|
||||
VariantProps<typeof badgeVariants> & { asChild?: boolean }) {
|
||||
const Comp = asChild ? Slot : "span"
|
||||
}: React.ComponentProps<'span'> & VariantProps<typeof badgeVariants> & { asChild?: boolean }) {
|
||||
const Comp = asChild ? Slot : 'span';
|
||||
|
||||
return (
|
||||
<Comp
|
||||
data-slot="badge"
|
||||
className={cn(badgeVariants({ variant }), className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
return <Comp data-slot="badge" className={cn(badgeVariants({ variant }), className)} {...props} />;
|
||||
}
|
||||
|
||||
export { Badge, badgeVariants }
|
||||
|
||||
export { Badge, badgeVariants };
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import { Slot } from "@radix-ui/react-slot"
|
||||
import { cva, type VariantProps } from "class-variance-authority"
|
||||
import { Slot } from '@radix-ui/react-slot';
|
||||
import { cva, type VariantProps } from 'class-variance-authority';
|
||||
|
||||
import { cn } from "../../src/lib/utils"
|
||||
import { Separator } from "./separator"
|
||||
import { cn } from '../../src/lib/utils';
|
||||
import { Separator } from './separator';
|
||||
|
||||
const buttonGroupVariants = cva(
|
||||
"flex w-fit items-stretch [&>*]:focus-visible:z-10 [&>*]:focus-visible:relative [&>[data-slot=select-trigger]:not([class*='w-'])]:w-fit [&>input]:flex-1 has-[select[aria-hidden=true]:last-child]:[&>[data-slot=select-trigger]:last-of-type]:rounded-r-md has-[>[data-slot=button-group]]:gap-2",
|
||||
@@ -10,22 +10,22 @@ const buttonGroupVariants = cva(
|
||||
variants: {
|
||||
orientation: {
|
||||
horizontal:
|
||||
"[&>*:not(:first-child)]:rounded-l-none [&>*:not(:first-child)]:border-l-0 [&>*:not(:last-child)]:rounded-r-none",
|
||||
'[&>*:not(:first-child)]:rounded-l-none [&>*:not(:first-child)]:border-l-0 [&>*:not(:last-child)]:rounded-r-none',
|
||||
vertical:
|
||||
"flex-col [&>*:not(:first-child)]:rounded-t-none [&>*:not(:first-child)]:border-t-0 [&>*:not(:last-child)]:rounded-b-none",
|
||||
'flex-col [&>*:not(:first-child)]:rounded-t-none [&>*:not(:first-child)]:border-t-0 [&>*:not(:last-child)]:rounded-b-none',
|
||||
},
|
||||
},
|
||||
defaultVariants: {
|
||||
orientation: "horizontal",
|
||||
orientation: 'horizontal',
|
||||
},
|
||||
}
|
||||
)
|
||||
},
|
||||
);
|
||||
|
||||
function ButtonGroup({
|
||||
className,
|
||||
orientation,
|
||||
...props
|
||||
}: React.ComponentProps<"div"> & VariantProps<typeof buttonGroupVariants>) {
|
||||
}: React.ComponentProps<'div'> & VariantProps<typeof buttonGroupVariants>) {
|
||||
return (
|
||||
<div
|
||||
role="group"
|
||||
@@ -34,51 +34,42 @@ function ButtonGroup({
|
||||
className={cn(buttonGroupVariants({ orientation }), className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function ButtonGroupText({
|
||||
className,
|
||||
asChild = false,
|
||||
...props
|
||||
}: React.ComponentProps<"div"> & {
|
||||
asChild?: boolean
|
||||
}: React.ComponentProps<'div'> & {
|
||||
asChild?: boolean;
|
||||
}) {
|
||||
const Comp = asChild ? Slot : "div"
|
||||
const Comp = asChild ? Slot : 'div';
|
||||
|
||||
return (
|
||||
<Comp
|
||||
className={cn(
|
||||
"bg-muted flex items-center gap-2 rounded-md border px-4 text-sm font-medium shadow-xs [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4",
|
||||
className
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function ButtonGroupSeparator({
|
||||
className,
|
||||
orientation = "vertical",
|
||||
orientation = 'vertical',
|
||||
...props
|
||||
}: React.ComponentProps<typeof Separator>) {
|
||||
return (
|
||||
<Separator
|
||||
data-slot="button-group-separator"
|
||||
orientation={orientation}
|
||||
className={cn(
|
||||
"bg-input relative !m-0 self-stretch data-[orientation=vertical]:h-auto",
|
||||
className
|
||||
)}
|
||||
className={cn('bg-input relative !m-0 self-stretch data-[orientation=vertical]:h-auto', className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export {
|
||||
ButtonGroup,
|
||||
ButtonGroupSeparator,
|
||||
ButtonGroupText,
|
||||
buttonGroupVariants,
|
||||
);
|
||||
}
|
||||
|
||||
export { ButtonGroup, ButtonGroupSeparator, ButtonGroupText, buttonGroupVariants };
|
||||
|
||||
@@ -1,40 +1,38 @@
|
||||
import * as React from "react"
|
||||
import { Slot } from "@radix-ui/react-slot"
|
||||
import { cva, type VariantProps } from "class-variance-authority"
|
||||
import * as React from 'react';
|
||||
import { Slot } from '@radix-ui/react-slot';
|
||||
import { cva, type VariantProps } from 'class-variance-authority';
|
||||
|
||||
import { cn } from "../../src/lib/utils"
|
||||
import { cn } from '../../src/lib/utils';
|
||||
|
||||
const buttonVariants = cva(
|
||||
"inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-all disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 shrink-0 [&_svg]:shrink-0 outline-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",
|
||||
{
|
||||
variants: {
|
||||
variant: {
|
||||
default: "bg-primary text-primary-foreground hover:bg-primary/90",
|
||||
default: 'bg-primary text-primary-foreground hover:bg-primary/90',
|
||||
destructive:
|
||||
"bg-destructive text-white hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",
|
||||
'bg-destructive text-white hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60',
|
||||
outline:
|
||||
"border bg-background shadow-xs hover:bg-accent hover:text-accent-foreground dark:bg-input/30 dark:border-input dark:hover:bg-input/50",
|
||||
secondary:
|
||||
"bg-secondary text-secondary-foreground hover:bg-secondary/80",
|
||||
ghost:
|
||||
"hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50",
|
||||
link: "text-primary underline-offset-4 hover:underline",
|
||||
'border bg-background shadow-xs hover:bg-accent hover:text-accent-foreground dark:bg-input/30 dark:border-input dark:hover:bg-input/50',
|
||||
secondary: 'bg-secondary text-secondary-foreground hover:bg-secondary/80',
|
||||
ghost: 'hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50',
|
||||
link: 'text-primary underline-offset-4 hover:underline',
|
||||
},
|
||||
size: {
|
||||
default: "h-9 px-4 py-2 has-[>svg]:px-3",
|
||||
sm: "h-8 rounded-md gap-1.5 px-3 has-[>svg]:px-2.5",
|
||||
lg: "h-10 rounded-md px-6 has-[>svg]:px-4",
|
||||
icon: "size-9",
|
||||
"icon-sm": "size-8",
|
||||
"icon-lg": "size-10",
|
||||
default: 'h-9 px-4 py-2 has-[>svg]:px-3',
|
||||
sm: 'h-8 rounded-md gap-1.5 px-3 has-[>svg]:px-2.5',
|
||||
lg: 'h-10 rounded-md px-6 has-[>svg]:px-4',
|
||||
icon: 'size-9',
|
||||
'icon-sm': 'size-8',
|
||||
'icon-lg': 'size-10',
|
||||
},
|
||||
},
|
||||
defaultVariants: {
|
||||
variant: "default",
|
||||
size: "default",
|
||||
variant: 'default',
|
||||
size: 'default',
|
||||
},
|
||||
}
|
||||
)
|
||||
},
|
||||
);
|
||||
|
||||
function Button({
|
||||
className,
|
||||
@@ -42,20 +40,13 @@ function Button({
|
||||
size,
|
||||
asChild = false,
|
||||
...props
|
||||
}: React.ComponentProps<"button"> &
|
||||
}: React.ComponentProps<'button'> &
|
||||
VariantProps<typeof buttonVariants> & {
|
||||
asChild?: boolean
|
||||
asChild?: boolean;
|
||||
}) {
|
||||
const Comp = asChild ? Slot : "button"
|
||||
const Comp = asChild ? Slot : 'button';
|
||||
|
||||
return (
|
||||
<Comp
|
||||
data-slot="button"
|
||||
className={cn(buttonVariants({ variant, size, className }))}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
return <Comp data-slot="button" className={cn(buttonVariants({ variant, size, className }))} {...props} />;
|
||||
}
|
||||
|
||||
export { Button, buttonVariants }
|
||||
|
||||
export { Button, buttonVariants };
|
||||
|
||||
@@ -1,93 +1,56 @@
|
||||
import * as React from "react"
|
||||
import * as React from 'react';
|
||||
|
||||
import { cn } from "../../src/lib/utils"
|
||||
import { cn } from '../../src/lib/utils';
|
||||
|
||||
function Card({ className, ...props }: React.ComponentProps<"div">) {
|
||||
function Card({ className, ...props }: React.ComponentProps<'div'>) {
|
||||
return (
|
||||
<div
|
||||
data-slot="card"
|
||||
className={cn(
|
||||
"bg-card text-card-foreground flex flex-col gap-6 rounded-xl border py-6 shadow-sm",
|
||||
className
|
||||
)}
|
||||
className={cn('bg-card text-card-foreground flex flex-col gap-6 rounded-xl border py-6 shadow-sm', className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function CardHeader({ className, ...props }: React.ComponentProps<"div">) {
|
||||
function CardHeader({ className, ...props }: React.ComponentProps<'div'>) {
|
||||
return (
|
||||
<div
|
||||
data-slot="card-header"
|
||||
className={cn(
|
||||
"@container/card-header grid auto-rows-min grid-rows-[auto_auto] items-start gap-2 px-6 has-data-[slot=card-action]:grid-cols-[1fr_auto] [.border-b]:pb-6",
|
||||
className
|
||||
'@container/card-header grid auto-rows-min grid-rows-[auto_auto] items-start gap-2 px-6 has-data-[slot=card-action]:grid-cols-[1fr_auto] [.border-b]:pb-6',
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function CardTitle({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="card-title"
|
||||
className={cn("leading-none font-semibold", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
function CardTitle({ className, ...props }: React.ComponentProps<'div'>) {
|
||||
return <div data-slot="card-title" className={cn('leading-none font-semibold', className)} {...props} />;
|
||||
}
|
||||
|
||||
function CardDescription({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="card-description"
|
||||
className={cn("text-muted-foreground text-sm", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
function CardDescription({ className, ...props }: React.ComponentProps<'div'>) {
|
||||
return <div data-slot="card-description" className={cn('text-muted-foreground text-sm', className)} {...props} />;
|
||||
}
|
||||
|
||||
function CardAction({ className, ...props }: React.ComponentProps<"div">) {
|
||||
function CardAction({ className, ...props }: React.ComponentProps<'div'>) {
|
||||
return (
|
||||
<div
|
||||
data-slot="card-action"
|
||||
className={cn(
|
||||
"col-start-2 row-span-2 row-start-1 self-start justify-self-end",
|
||||
className
|
||||
)}
|
||||
className={cn('col-start-2 row-span-2 row-start-1 self-start justify-self-end', className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function CardContent({ className, ...props }: React.ComponentProps<"div">) {
|
||||
function CardContent({ className, ...props }: React.ComponentProps<'div'>) {
|
||||
return <div data-slot="card-content" className={cn('px-6', className)} {...props} />;
|
||||
}
|
||||
|
||||
function CardFooter({ className, ...props }: React.ComponentProps<'div'>) {
|
||||
return (
|
||||
<div
|
||||
data-slot="card-content"
|
||||
className={cn("px-6", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function CardFooter({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="card-footer"
|
||||
className={cn("flex items-center px-6 [.border-t]:pt-6", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export {
|
||||
Card,
|
||||
CardHeader,
|
||||
CardFooter,
|
||||
CardTitle,
|
||||
CardAction,
|
||||
CardDescription,
|
||||
CardContent,
|
||||
<div data-slot="card-footer" className={cn('flex items-center px-6 [.border-t]:pt-6', className)} {...props} />
|
||||
);
|
||||
}
|
||||
|
||||
export { Card, CardHeader, CardFooter, CardTitle, CardAction, CardDescription, CardContent };
|
||||
|
||||
@@ -1,34 +1,17 @@
|
||||
"use client"
|
||||
'use client';
|
||||
|
||||
import * as CollapsiblePrimitive from "@radix-ui/react-collapsible"
|
||||
import * as CollapsiblePrimitive from '@radix-ui/react-collapsible';
|
||||
|
||||
function Collapsible({
|
||||
...props
|
||||
}: React.ComponentProps<typeof CollapsiblePrimitive.Root>) {
|
||||
return <CollapsiblePrimitive.Root data-slot="collapsible" {...props} />
|
||||
function Collapsible({ ...props }: React.ComponentProps<typeof CollapsiblePrimitive.Root>) {
|
||||
return <CollapsiblePrimitive.Root data-slot="collapsible" {...props} />;
|
||||
}
|
||||
|
||||
function CollapsibleTrigger({
|
||||
...props
|
||||
}: React.ComponentProps<typeof CollapsiblePrimitive.CollapsibleTrigger>) {
|
||||
return (
|
||||
<CollapsiblePrimitive.CollapsibleTrigger
|
||||
data-slot="collapsible-trigger"
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
function CollapsibleTrigger({ ...props }: React.ComponentProps<typeof CollapsiblePrimitive.CollapsibleTrigger>) {
|
||||
return <CollapsiblePrimitive.CollapsibleTrigger data-slot="collapsible-trigger" {...props} />;
|
||||
}
|
||||
|
||||
function CollapsibleContent({
|
||||
...props
|
||||
}: React.ComponentProps<typeof CollapsiblePrimitive.CollapsibleContent>) {
|
||||
return (
|
||||
<CollapsiblePrimitive.CollapsibleContent
|
||||
data-slot="collapsible-content"
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
function CollapsibleContent({ ...props }: React.ComponentProps<typeof CollapsiblePrimitive.CollapsibleContent>) {
|
||||
return <CollapsiblePrimitive.CollapsibleContent data-slot="collapsible-content" {...props} />;
|
||||
}
|
||||
|
||||
export { Collapsible, CollapsibleTrigger, CollapsibleContent }
|
||||
|
||||
export { Collapsible, CollapsibleTrigger, CollapsibleContent };
|
||||
|
||||
@@ -1,44 +1,35 @@
|
||||
import * as React from "react"
|
||||
import { Command as CommandPrimitive } from "cmdk"
|
||||
import { SearchIcon } from "lucide-react"
|
||||
import * as React from 'react';
|
||||
import { Command as CommandPrimitive } from 'cmdk';
|
||||
import { SearchIcon } from 'lucide-react';
|
||||
|
||||
import { cn } from "../../src/lib/utils"
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "./dialog"
|
||||
import { cn } from '../../src/lib/utils';
|
||||
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from './dialog';
|
||||
|
||||
function Command({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof CommandPrimitive>) {
|
||||
function Command({ className, ...props }: React.ComponentProps<typeof CommandPrimitive>) {
|
||||
return (
|
||||
<CommandPrimitive
|
||||
data-slot="command"
|
||||
className={cn(
|
||||
"bg-popover text-popover-foreground flex h-full w-full flex-col overflow-hidden rounded-md",
|
||||
className
|
||||
'bg-popover text-popover-foreground flex h-full w-full flex-col overflow-hidden rounded-md',
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function CommandDialog({
|
||||
title = "Command Palette",
|
||||
description = "Search for a command to run...",
|
||||
title = 'Command Palette',
|
||||
description = 'Search for a command to run...',
|
||||
children,
|
||||
className,
|
||||
showCloseButton = true,
|
||||
...props
|
||||
}: React.ComponentProps<typeof Dialog> & {
|
||||
title?: string
|
||||
description?: string
|
||||
className?: string
|
||||
showCloseButton?: boolean
|
||||
title?: string;
|
||||
description?: string;
|
||||
className?: string;
|
||||
showCloseButton?: boolean;
|
||||
}) {
|
||||
return (
|
||||
<Dialog {...props}>
|
||||
@@ -46,127 +37,89 @@ function CommandDialog({
|
||||
<DialogTitle>{title}</DialogTitle>
|
||||
<DialogDescription>{description}</DialogDescription>
|
||||
</DialogHeader>
|
||||
<DialogContent
|
||||
className={cn("overflow-hidden p-0", className)}
|
||||
showCloseButton={showCloseButton}
|
||||
>
|
||||
<DialogContent className={cn('overflow-hidden p-0', className)} showCloseButton={showCloseButton}>
|
||||
<Command className="[&_[cmdk-group-heading]]:text-muted-foreground **:data-[slot=command-input-wrapper]:h-12 [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group]]:px-2 [&_[cmdk-group]:not([hidden])_~[cmdk-group]]:pt-0 [&_[cmdk-input-wrapper]_svg]:h-5 [&_[cmdk-input-wrapper]_svg]:w-5 [&_[cmdk-input]]:h-12 [&_[cmdk-item]]:px-2 [&_[cmdk-item]]:py-3 [&_[cmdk-item]_svg]:h-5 [&_[cmdk-item]_svg]:w-5">
|
||||
{children}
|
||||
</Command>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function CommandInput({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof CommandPrimitive.Input>) {
|
||||
function CommandInput({ className, ...props }: React.ComponentProps<typeof CommandPrimitive.Input>) {
|
||||
return (
|
||||
<div
|
||||
data-slot="command-input-wrapper"
|
||||
className="flex h-9 items-center gap-2 border-b px-3"
|
||||
>
|
||||
<div data-slot="command-input-wrapper" className="flex h-9 items-center gap-2 border-b px-3">
|
||||
<SearchIcon className="size-4 shrink-0 opacity-50" />
|
||||
<CommandPrimitive.Input
|
||||
data-slot="command-input"
|
||||
className={cn(
|
||||
"placeholder:text-muted-foreground flex h-10 w-full rounded-md bg-transparent py-3 text-sm outline-hidden disabled:cursor-not-allowed disabled:opacity-50",
|
||||
className
|
||||
'placeholder:text-muted-foreground flex h-10 w-full rounded-md bg-transparent py-3 text-sm outline-hidden disabled:cursor-not-allowed disabled:opacity-50',
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function CommandList({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof CommandPrimitive.List>) {
|
||||
function CommandList({ className, ...props }: React.ComponentProps<typeof CommandPrimitive.List>) {
|
||||
return (
|
||||
<CommandPrimitive.List
|
||||
data-slot="command-list"
|
||||
className={cn(
|
||||
"max-h-[300px] scroll-py-1 overflow-x-hidden overflow-y-auto",
|
||||
className
|
||||
)}
|
||||
className={cn('max-h-[300px] scroll-py-1 overflow-x-hidden overflow-y-auto', className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function CommandEmpty({
|
||||
...props
|
||||
}: React.ComponentProps<typeof CommandPrimitive.Empty>) {
|
||||
return (
|
||||
<CommandPrimitive.Empty
|
||||
data-slot="command-empty"
|
||||
className="py-6 text-center text-sm"
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
function CommandEmpty({ ...props }: React.ComponentProps<typeof CommandPrimitive.Empty>) {
|
||||
return <CommandPrimitive.Empty data-slot="command-empty" className="py-6 text-center text-sm" {...props} />;
|
||||
}
|
||||
|
||||
function CommandGroup({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof CommandPrimitive.Group>) {
|
||||
function CommandGroup({ className, ...props }: React.ComponentProps<typeof CommandPrimitive.Group>) {
|
||||
return (
|
||||
<CommandPrimitive.Group
|
||||
data-slot="command-group"
|
||||
className={cn(
|
||||
"text-foreground [&_[cmdk-group-heading]]:text-muted-foreground overflow-hidden p-1 [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:py-1.5 [&_[cmdk-group-heading]]:text-xs [&_[cmdk-group-heading]]:font-medium",
|
||||
className
|
||||
'text-foreground [&_[cmdk-group-heading]]:text-muted-foreground overflow-hidden p-1 [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:py-1.5 [&_[cmdk-group-heading]]:text-xs [&_[cmdk-group-heading]]:font-medium',
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function CommandSeparator({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof CommandPrimitive.Separator>) {
|
||||
function CommandSeparator({ className, ...props }: React.ComponentProps<typeof CommandPrimitive.Separator>) {
|
||||
return (
|
||||
<CommandPrimitive.Separator
|
||||
data-slot="command-separator"
|
||||
className={cn("bg-border -mx-1 h-px", className)}
|
||||
className={cn('bg-border -mx-1 h-px', className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function CommandItem({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof CommandPrimitive.Item>) {
|
||||
function CommandItem({ className, ...props }: React.ComponentProps<typeof CommandPrimitive.Item>) {
|
||||
return (
|
||||
<CommandPrimitive.Item
|
||||
data-slot="command-item"
|
||||
className={cn(
|
||||
"data-[selected=true]:bg-accent data-[selected=true]:text-accent-foreground [&_svg:not([class*='text-'])]:text-muted-foreground relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[disabled=true]:pointer-events-none data-[disabled=true]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||
className
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function CommandShortcut({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<"span">) {
|
||||
function CommandShortcut({ className, ...props }: React.ComponentProps<'span'>) {
|
||||
return (
|
||||
<span
|
||||
data-slot="command-shortcut"
|
||||
className={cn(
|
||||
"text-muted-foreground ml-auto text-xs tracking-widest",
|
||||
className
|
||||
)}
|
||||
className={cn('text-muted-foreground ml-auto text-xs tracking-widest', className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
export {
|
||||
@@ -179,5 +132,4 @@ export {
|
||||
CommandItem,
|
||||
CommandShortcut,
|
||||
CommandSeparator,
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
@@ -1,20 +1,20 @@
|
||||
import type { ConnectionState } from "../../src/acp/types";
|
||||
import { cn } from "../../src/lib/utils";
|
||||
import type { ConnectionState } from '../../src/acp/types';
|
||||
import { cn } from '../../src/lib/utils';
|
||||
|
||||
// Shared styles for connection state dots
|
||||
const connectionDotStyles: Record<ConnectionState, string> = {
|
||||
disconnected: "bg-gray-400",
|
||||
connecting: "bg-yellow-400 animate-pulse",
|
||||
connected: "bg-green-500 shadow-[0_0_8px_rgba(34,197,94,0.6)]",
|
||||
error: "bg-red-500 shadow-[0_0_8px_rgba(239,68,68,0.6)]",
|
||||
disconnected: 'bg-gray-400',
|
||||
connecting: 'bg-yellow-400 animate-pulse',
|
||||
connected: 'bg-green-500 shadow-[0_0_8px_rgba(34,197,94,0.6)]',
|
||||
error: 'bg-red-500 shadow-[0_0_8px_rgba(239,68,68,0.6)]',
|
||||
};
|
||||
|
||||
// Shared labels for connection states
|
||||
const connectionStateLabels: Record<ConnectionState, string> = {
|
||||
disconnected: "Disconnected",
|
||||
connecting: "Connecting...",
|
||||
connected: "Connected",
|
||||
error: "Error",
|
||||
disconnected: 'Disconnected',
|
||||
connecting: 'Connecting...',
|
||||
connected: 'Connected',
|
||||
error: 'Error',
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -28,33 +28,17 @@ export function getConnectionStateLabel(state: ConnectionState): string {
|
||||
* A small dot indicator for connection state
|
||||
* Used in status bars and headers
|
||||
*/
|
||||
export function StatusDot({
|
||||
state,
|
||||
className,
|
||||
}: {
|
||||
state: ConnectionState;
|
||||
className?: string;
|
||||
}) {
|
||||
return (
|
||||
<span
|
||||
className={cn("w-2 h-2 rounded-full", connectionDotStyles[state], className)}
|
||||
/>
|
||||
);
|
||||
export function StatusDot({ state, className }: { state: ConnectionState; className?: string }) {
|
||||
return <span className={cn('w-2 h-2 rounded-full', connectionDotStyles[state], className)} />;
|
||||
}
|
||||
|
||||
/**
|
||||
* A status indicator with dot and label
|
||||
* Used in cards and detailed views
|
||||
*/
|
||||
export function StatusIndicator({
|
||||
state,
|
||||
className,
|
||||
}: {
|
||||
state: ConnectionState;
|
||||
className?: string;
|
||||
}) {
|
||||
export function StatusIndicator({ state, className }: { state: ConnectionState; className?: string }) {
|
||||
return (
|
||||
<span className={cn("flex items-center gap-2 text-sm font-normal", className)}>
|
||||
<span className={cn('flex items-center gap-2 text-sm font-normal', className)}>
|
||||
<StatusDot state={state} />
|
||||
{state}
|
||||
</span>
|
||||
@@ -74,17 +58,12 @@ export function ConnectionStatusBar({
|
||||
className?: string;
|
||||
}) {
|
||||
return (
|
||||
<div className={cn("flex items-center gap-2", className)}>
|
||||
<div className={cn('flex items-center gap-2', className)}>
|
||||
<StatusDot state={state} />
|
||||
<span className="text-sm font-medium">
|
||||
{getConnectionStateLabel(state)}
|
||||
</span>
|
||||
{state === "connected" && displayUrl && (
|
||||
<span className="text-xs text-muted-foreground truncate max-w-[150px]">
|
||||
{displayUrl}
|
||||
</span>
|
||||
<span className="text-sm font-medium">{getConnectionStateLabel(state)}</span>
|
||||
{state === 'connected' && displayUrl && (
|
||||
<span className="text-xs text-muted-foreground truncate max-w-[150px]">{displayUrl}</span>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,49 +1,38 @@
|
||||
"use client"
|
||||
'use client';
|
||||
|
||||
import * as React from "react"
|
||||
import * as DialogPrimitive from "@radix-ui/react-dialog"
|
||||
import { XIcon } from "lucide-react"
|
||||
import * as React from 'react';
|
||||
import * as DialogPrimitive from '@radix-ui/react-dialog';
|
||||
import { XIcon } from 'lucide-react';
|
||||
|
||||
import { cn } from "../../src/lib/utils"
|
||||
import { cn } from '../../src/lib/utils';
|
||||
|
||||
function Dialog({
|
||||
...props
|
||||
}: React.ComponentProps<typeof DialogPrimitive.Root>) {
|
||||
return <DialogPrimitive.Root data-slot="dialog" {...props} />
|
||||
function Dialog({ ...props }: React.ComponentProps<typeof DialogPrimitive.Root>) {
|
||||
return <DialogPrimitive.Root data-slot="dialog" {...props} />;
|
||||
}
|
||||
|
||||
function DialogTrigger({
|
||||
...props
|
||||
}: React.ComponentProps<typeof DialogPrimitive.Trigger>) {
|
||||
return <DialogPrimitive.Trigger data-slot="dialog-trigger" {...props} />
|
||||
function DialogTrigger({ ...props }: React.ComponentProps<typeof DialogPrimitive.Trigger>) {
|
||||
return <DialogPrimitive.Trigger data-slot="dialog-trigger" {...props} />;
|
||||
}
|
||||
|
||||
function DialogPortal({
|
||||
...props
|
||||
}: React.ComponentProps<typeof DialogPrimitive.Portal>) {
|
||||
return <DialogPrimitive.Portal data-slot="dialog-portal" {...props} />
|
||||
function DialogPortal({ ...props }: React.ComponentProps<typeof DialogPrimitive.Portal>) {
|
||||
return <DialogPrimitive.Portal data-slot="dialog-portal" {...props} />;
|
||||
}
|
||||
|
||||
function DialogClose({
|
||||
...props
|
||||
}: React.ComponentProps<typeof DialogPrimitive.Close>) {
|
||||
return <DialogPrimitive.Close data-slot="dialog-close" {...props} />
|
||||
function DialogClose({ ...props }: React.ComponentProps<typeof DialogPrimitive.Close>) {
|
||||
return <DialogPrimitive.Close data-slot="dialog-close" {...props} />;
|
||||
}
|
||||
|
||||
function DialogOverlay({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DialogPrimitive.Overlay>) {
|
||||
function DialogOverlay({ className, ...props }: React.ComponentProps<typeof DialogPrimitive.Overlay>) {
|
||||
return (
|
||||
<DialogPrimitive.Overlay
|
||||
data-slot="dialog-overlay"
|
||||
className={cn(
|
||||
"data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50",
|
||||
className
|
||||
'data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50',
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function DialogContent({
|
||||
@@ -52,7 +41,7 @@ function DialogContent({
|
||||
showCloseButton = true,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DialogPrimitive.Content> & {
|
||||
showCloseButton?: boolean
|
||||
showCloseButton?: boolean;
|
||||
}) {
|
||||
return (
|
||||
<DialogPortal data-slot="dialog-portal">
|
||||
@@ -60,8 +49,8 @@ function DialogContent({
|
||||
<DialogPrimitive.Content
|
||||
data-slot="dialog-content"
|
||||
className={cn(
|
||||
"bg-background data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border p-6 shadow-lg duration-200 sm:max-w-lg",
|
||||
className
|
||||
'bg-background data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border p-6 shadow-lg duration-200 sm:max-w-lg',
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
@@ -77,56 +66,47 @@ function DialogContent({
|
||||
)}
|
||||
</DialogPrimitive.Content>
|
||||
</DialogPortal>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function DialogHeader({ className, ...props }: React.ComponentProps<"div">) {
|
||||
function DialogHeader({ className, ...props }: React.ComponentProps<'div'>) {
|
||||
return (
|
||||
<div
|
||||
data-slot="dialog-header"
|
||||
className={cn("flex flex-col gap-2 text-center sm:text-left", className)}
|
||||
className={cn('flex flex-col gap-2 text-center sm:text-left', className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function DialogFooter({ className, ...props }: React.ComponentProps<"div">) {
|
||||
function DialogFooter({ className, ...props }: React.ComponentProps<'div'>) {
|
||||
return (
|
||||
<div
|
||||
data-slot="dialog-footer"
|
||||
className={cn(
|
||||
"flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",
|
||||
className
|
||||
)}
|
||||
className={cn('flex flex-col-reverse gap-2 sm:flex-row sm:justify-end', className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function DialogTitle({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DialogPrimitive.Title>) {
|
||||
function DialogTitle({ className, ...props }: React.ComponentProps<typeof DialogPrimitive.Title>) {
|
||||
return (
|
||||
<DialogPrimitive.Title
|
||||
data-slot="dialog-title"
|
||||
className={cn("text-lg leading-none font-semibold", className)}
|
||||
className={cn('text-lg leading-none font-semibold', className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function DialogDescription({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DialogPrimitive.Description>) {
|
||||
function DialogDescription({ className, ...props }: React.ComponentProps<typeof DialogPrimitive.Description>) {
|
||||
return (
|
||||
<DialogPrimitive.Description
|
||||
data-slot="dialog-description"
|
||||
className={cn("text-muted-foreground text-sm", className)}
|
||||
className={cn('text-muted-foreground text-sm', className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
export {
|
||||
@@ -140,5 +120,4 @@ export {
|
||||
DialogPortal,
|
||||
DialogTitle,
|
||||
DialogTrigger,
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
@@ -1,32 +1,19 @@
|
||||
import * as React from "react"
|
||||
import * as DropdownMenuPrimitive from "@radix-ui/react-dropdown-menu"
|
||||
import { CheckIcon, ChevronRightIcon, CircleIcon } from "lucide-react"
|
||||
import * as React from 'react';
|
||||
import * as DropdownMenuPrimitive from '@radix-ui/react-dropdown-menu';
|
||||
import { CheckIcon, ChevronRightIcon, CircleIcon } from 'lucide-react';
|
||||
|
||||
import { cn } from "../../src/lib/utils"
|
||||
import { cn } from '../../src/lib/utils';
|
||||
|
||||
function DropdownMenu({
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.Root>) {
|
||||
return <DropdownMenuPrimitive.Root data-slot="dropdown-menu" {...props} />
|
||||
function DropdownMenu({ ...props }: React.ComponentProps<typeof DropdownMenuPrimitive.Root>) {
|
||||
return <DropdownMenuPrimitive.Root data-slot="dropdown-menu" {...props} />;
|
||||
}
|
||||
|
||||
function DropdownMenuPortal({
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.Portal>) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.Portal data-slot="dropdown-menu-portal" {...props} />
|
||||
)
|
||||
function DropdownMenuPortal({ ...props }: React.ComponentProps<typeof DropdownMenuPrimitive.Portal>) {
|
||||
return <DropdownMenuPrimitive.Portal data-slot="dropdown-menu-portal" {...props} />;
|
||||
}
|
||||
|
||||
function DropdownMenuTrigger({
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.Trigger>) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.Trigger
|
||||
data-slot="dropdown-menu-trigger"
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
function DropdownMenuTrigger({ ...props }: React.ComponentProps<typeof DropdownMenuPrimitive.Trigger>) {
|
||||
return <DropdownMenuPrimitive.Trigger data-slot="dropdown-menu-trigger" {...props} />;
|
||||
}
|
||||
|
||||
function DropdownMenuContent({
|
||||
@@ -40,31 +27,27 @@ function DropdownMenuContent({
|
||||
data-slot="dropdown-menu-content"
|
||||
sideOffset={sideOffset}
|
||||
className={cn(
|
||||
"bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 max-h-(--radix-dropdown-menu-content-available-height) min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border p-1 shadow-md",
|
||||
className
|
||||
'bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 max-h-(--radix-dropdown-menu-content-available-height) min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border p-1 shadow-md',
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
</DropdownMenuPrimitive.Portal>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function DropdownMenuGroup({
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.Group>) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.Group data-slot="dropdown-menu-group" {...props} />
|
||||
)
|
||||
function DropdownMenuGroup({ ...props }: React.ComponentProps<typeof DropdownMenuPrimitive.Group>) {
|
||||
return <DropdownMenuPrimitive.Group data-slot="dropdown-menu-group" {...props} />;
|
||||
}
|
||||
|
||||
function DropdownMenuItem({
|
||||
className,
|
||||
inset,
|
||||
variant = "default",
|
||||
variant = 'default',
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.Item> & {
|
||||
inset?: boolean
|
||||
variant?: "default" | "destructive"
|
||||
inset?: boolean;
|
||||
variant?: 'default' | 'destructive';
|
||||
}) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.Item
|
||||
@@ -73,11 +56,11 @@ function DropdownMenuItem({
|
||||
data-variant={variant}
|
||||
className={cn(
|
||||
"focus:bg-accent focus:text-accent-foreground data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 dark:data-[variant=destructive]:focus:bg-destructive/20 data-[variant=destructive]:focus:text-destructive data-[variant=destructive]:*:[svg]:!text-destructive [&_svg:not([class*='text-'])]:text-muted-foreground relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[inset]:pl-8 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||
className
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function DropdownMenuCheckboxItem({
|
||||
@@ -91,7 +74,7 @@ function DropdownMenuCheckboxItem({
|
||||
data-slot="dropdown-menu-checkbox-item"
|
||||
className={cn(
|
||||
"focus:bg-accent focus:text-accent-foreground relative flex cursor-default items-center gap-2 rounded-sm py-1.5 pr-2 pl-8 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||
className
|
||||
className,
|
||||
)}
|
||||
checked={checked}
|
||||
{...props}
|
||||
@@ -103,18 +86,11 @@ function DropdownMenuCheckboxItem({
|
||||
</span>
|
||||
{children}
|
||||
</DropdownMenuPrimitive.CheckboxItem>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function DropdownMenuRadioGroup({
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.RadioGroup>) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.RadioGroup
|
||||
data-slot="dropdown-menu-radio-group"
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
function DropdownMenuRadioGroup({ ...props }: React.ComponentProps<typeof DropdownMenuPrimitive.RadioGroup>) {
|
||||
return <DropdownMenuPrimitive.RadioGroup data-slot="dropdown-menu-radio-group" {...props} />;
|
||||
}
|
||||
|
||||
function DropdownMenuRadioItem({
|
||||
@@ -127,7 +103,7 @@ function DropdownMenuRadioItem({
|
||||
data-slot="dropdown-menu-radio-item"
|
||||
className={cn(
|
||||
"focus:bg-accent focus:text-accent-foreground relative flex cursor-default items-center gap-2 rounded-sm py-1.5 pr-2 pl-8 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||
className
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
@@ -138,7 +114,7 @@ function DropdownMenuRadioItem({
|
||||
</span>
|
||||
{children}
|
||||
</DropdownMenuPrimitive.RadioItem>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function DropdownMenuLabel({
|
||||
@@ -146,54 +122,40 @@ function DropdownMenuLabel({
|
||||
inset,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.Label> & {
|
||||
inset?: boolean
|
||||
inset?: boolean;
|
||||
}) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.Label
|
||||
data-slot="dropdown-menu-label"
|
||||
data-inset={inset}
|
||||
className={cn(
|
||||
"px-2 py-1.5 text-sm font-medium data-[inset]:pl-8",
|
||||
className
|
||||
)}
|
||||
className={cn('px-2 py-1.5 text-sm font-medium data-[inset]:pl-8', className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function DropdownMenuSeparator({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.Separator>) {
|
||||
function DropdownMenuSeparator({ className, ...props }: React.ComponentProps<typeof DropdownMenuPrimitive.Separator>) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.Separator
|
||||
data-slot="dropdown-menu-separator"
|
||||
className={cn("bg-border -mx-1 my-1 h-px", className)}
|
||||
className={cn('bg-border -mx-1 my-1 h-px', className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function DropdownMenuShortcut({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<"span">) {
|
||||
function DropdownMenuShortcut({ className, ...props }: React.ComponentProps<'span'>) {
|
||||
return (
|
||||
<span
|
||||
data-slot="dropdown-menu-shortcut"
|
||||
className={cn(
|
||||
"text-muted-foreground ml-auto text-xs tracking-widest",
|
||||
className
|
||||
)}
|
||||
className={cn('text-muted-foreground ml-auto text-xs tracking-widest', className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function DropdownMenuSub({
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.Sub>) {
|
||||
return <DropdownMenuPrimitive.Sub data-slot="dropdown-menu-sub" {...props} />
|
||||
function DropdownMenuSub({ ...props }: React.ComponentProps<typeof DropdownMenuPrimitive.Sub>) {
|
||||
return <DropdownMenuPrimitive.Sub data-slot="dropdown-menu-sub" {...props} />;
|
||||
}
|
||||
|
||||
function DropdownMenuSubTrigger({
|
||||
@@ -202,7 +164,7 @@ function DropdownMenuSubTrigger({
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.SubTrigger> & {
|
||||
inset?: boolean
|
||||
inset?: boolean;
|
||||
}) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.SubTrigger
|
||||
@@ -210,14 +172,14 @@ function DropdownMenuSubTrigger({
|
||||
data-inset={inset}
|
||||
className={cn(
|
||||
"focus:bg-accent focus:text-accent-foreground data-[state=open]:bg-accent data-[state=open]:text-accent-foreground [&_svg:not([class*='text-'])]:text-muted-foreground flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[inset]:pl-8 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||
className
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
<ChevronRightIcon className="ml-auto size-4" />
|
||||
</DropdownMenuPrimitive.SubTrigger>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function DropdownMenuSubContent({
|
||||
@@ -228,12 +190,12 @@ function DropdownMenuSubContent({
|
||||
<DropdownMenuPrimitive.SubContent
|
||||
data-slot="dropdown-menu-sub-content"
|
||||
className={cn(
|
||||
"bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-hidden rounded-md border p-1 shadow-lg",
|
||||
className
|
||||
'bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-hidden rounded-md border p-1 shadow-lg',
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
export {
|
||||
@@ -252,5 +214,4 @@ export {
|
||||
DropdownMenuSub,
|
||||
DropdownMenuSubTrigger,
|
||||
DropdownMenuSubContent,
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
@@ -1,27 +1,21 @@
|
||||
"use client"
|
||||
'use client';
|
||||
|
||||
import * as React from "react"
|
||||
import * as HoverCardPrimitive from "@radix-ui/react-hover-card"
|
||||
import * as React from 'react';
|
||||
import * as HoverCardPrimitive from '@radix-ui/react-hover-card';
|
||||
|
||||
import { cn } from "../../src/lib/utils"
|
||||
import { cn } from '../../src/lib/utils';
|
||||
|
||||
function HoverCard({
|
||||
...props
|
||||
}: React.ComponentProps<typeof HoverCardPrimitive.Root>) {
|
||||
return <HoverCardPrimitive.Root data-slot="hover-card" {...props} />
|
||||
function HoverCard({ ...props }: React.ComponentProps<typeof HoverCardPrimitive.Root>) {
|
||||
return <HoverCardPrimitive.Root data-slot="hover-card" {...props} />;
|
||||
}
|
||||
|
||||
function HoverCardTrigger({
|
||||
...props
|
||||
}: React.ComponentProps<typeof HoverCardPrimitive.Trigger>) {
|
||||
return (
|
||||
<HoverCardPrimitive.Trigger data-slot="hover-card-trigger" {...props} />
|
||||
)
|
||||
function HoverCardTrigger({ ...props }: React.ComponentProps<typeof HoverCardPrimitive.Trigger>) {
|
||||
return <HoverCardPrimitive.Trigger data-slot="hover-card-trigger" {...props} />;
|
||||
}
|
||||
|
||||
function HoverCardContent({
|
||||
className,
|
||||
align = "center",
|
||||
align = 'center',
|
||||
sideOffset = 4,
|
||||
...props
|
||||
}: React.ComponentProps<typeof HoverCardPrimitive.Content>) {
|
||||
@@ -32,14 +26,13 @@ function HoverCardContent({
|
||||
align={align}
|
||||
sideOffset={sideOffset}
|
||||
className={cn(
|
||||
"bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 w-64 origin-(--radix-hover-card-content-transform-origin) rounded-md border p-4 shadow-md outline-hidden",
|
||||
className
|
||||
'bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 w-64 origin-(--radix-hover-card-content-transform-origin) rounded-md border p-4 shadow-md outline-hidden',
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
</HoverCardPrimitive.Portal>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
export { HoverCard, HoverCardTrigger, HoverCardContent }
|
||||
|
||||
export { HoverCard, HoverCardTrigger, HoverCardContent };
|
||||
|
||||
@@ -1,22 +1,22 @@
|
||||
export * from "./badge"
|
||||
export * from "./connection-status"
|
||||
export * from "./button-group"
|
||||
export * from "./button"
|
||||
export * from "./card"
|
||||
export * from "./collapsible"
|
||||
export * from "./command"
|
||||
export * from "./dialog"
|
||||
export * from "./dropdown-menu"
|
||||
export * from "./hover-card"
|
||||
export * from "./input-group"
|
||||
export * from "./input"
|
||||
export * from "./label"
|
||||
export * from "./resizable"
|
||||
export * from "./scroll-area"
|
||||
export * from "./select"
|
||||
export * from "./separator"
|
||||
export * from "./tabs"
|
||||
export * from "./textarea"
|
||||
export * from "./theme-toggle"
|
||||
export * from "./tooltip"
|
||||
export * from "./popover"
|
||||
export * from './badge'
|
||||
export * from './connection-status'
|
||||
export * from './button-group'
|
||||
export * from './button'
|
||||
export * from './card'
|
||||
export * from './collapsible'
|
||||
export * from './command'
|
||||
export * from './dialog'
|
||||
export * from './dropdown-menu'
|
||||
export * from './hover-card'
|
||||
export * from './input-group'
|
||||
export * from './input'
|
||||
export * from './label'
|
||||
export * from './resizable'
|
||||
export * from './scroll-area'
|
||||
export * from './select'
|
||||
export * from './separator'
|
||||
export * from './tabs'
|
||||
export * from './textarea'
|
||||
export * from './theme-toggle'
|
||||
export * from './tooltip'
|
||||
export * from './popover'
|
||||
|
||||
@@ -1,39 +1,39 @@
|
||||
"use client"
|
||||
'use client';
|
||||
|
||||
import * as React from "react"
|
||||
import { cva, type VariantProps } from "class-variance-authority"
|
||||
import * as React from 'react';
|
||||
import { cva, type VariantProps } from 'class-variance-authority';
|
||||
|
||||
import { cn } from "../../src/lib/utils"
|
||||
import { Button } from "./button"
|
||||
import { Input } from "./input"
|
||||
import { Textarea } from "./textarea"
|
||||
import { cn } from '../../src/lib/utils';
|
||||
import { Button } from './button';
|
||||
import { Input } from './input';
|
||||
import { Textarea } from './textarea';
|
||||
|
||||
function InputGroup({ className, ...props }: React.ComponentProps<"div">) {
|
||||
function InputGroup({ className, ...props }: React.ComponentProps<'div'>) {
|
||||
return (
|
||||
<div
|
||||
data-slot="input-group"
|
||||
role="group"
|
||||
className={cn(
|
||||
"group/input-group border-input dark:bg-input/30 relative flex w-full items-center rounded-md border shadow-xs transition-[color,box-shadow] outline-none",
|
||||
"h-9 min-w-0 has-[>textarea]:h-auto",
|
||||
'group/input-group border-input dark:bg-input/30 relative flex w-full items-center rounded-md border shadow-xs transition-[color,box-shadow] outline-none',
|
||||
'h-9 min-w-0 has-[>textarea]:h-auto',
|
||||
|
||||
// Variants based on alignment.
|
||||
"has-[>[data-align=inline-start]]:[&>input]:pl-2",
|
||||
"has-[>[data-align=inline-end]]:[&>input]:pr-2",
|
||||
"has-[>[data-align=block-start]]:h-auto has-[>[data-align=block-start]]:flex-col has-[>[data-align=block-start]]:[&>input]:pb-3",
|
||||
"has-[>[data-align=block-end]]:h-auto has-[>[data-align=block-end]]:flex-col has-[>[data-align=block-end]]:[&>input]:pt-3",
|
||||
'has-[>[data-align=inline-start]]:[&>input]:pl-2',
|
||||
'has-[>[data-align=inline-end]]:[&>input]:pr-2',
|
||||
'has-[>[data-align=block-start]]:h-auto has-[>[data-align=block-start]]:flex-col has-[>[data-align=block-start]]:[&>input]:pb-3',
|
||||
'has-[>[data-align=block-end]]:h-auto has-[>[data-align=block-end]]:flex-col has-[>[data-align=block-end]]:[&>input]:pt-3',
|
||||
|
||||
// Focus state.
|
||||
"has-[[data-slot=input-group-control]:focus-visible]:border-ring has-[[data-slot=input-group-control]:focus-visible]:ring-ring/50 has-[[data-slot=input-group-control]:focus-visible]:ring-[3px]",
|
||||
'has-[[data-slot=input-group-control]:focus-visible]:border-ring has-[[data-slot=input-group-control]:focus-visible]:ring-ring/50 has-[[data-slot=input-group-control]:focus-visible]:ring-[3px]',
|
||||
|
||||
// Error state.
|
||||
"has-[[data-slot][aria-invalid=true]]:ring-destructive/20 has-[[data-slot][aria-invalid=true]]:border-destructive dark:has-[[data-slot][aria-invalid=true]]:ring-destructive/40",
|
||||
'has-[[data-slot][aria-invalid=true]]:ring-destructive/20 has-[[data-slot][aria-invalid=true]]:border-destructive dark:has-[[data-slot][aria-invalid=true]]:ring-destructive/40',
|
||||
|
||||
className
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
const inputGroupAddonVariants = cva(
|
||||
@@ -41,70 +41,62 @@ const inputGroupAddonVariants = cva(
|
||||
{
|
||||
variants: {
|
||||
align: {
|
||||
"inline-start":
|
||||
"order-first pl-3 has-[>button]:ml-[-0.45rem] has-[>kbd]:ml-[-0.35rem]",
|
||||
"inline-end":
|
||||
"order-last pr-3 has-[>button]:mr-[-0.45rem] has-[>kbd]:mr-[-0.35rem]",
|
||||
"block-start":
|
||||
"order-first w-full justify-start px-3 pt-3 [.border-b]:pb-3 group-has-[>input]/input-group:pt-2.5",
|
||||
"block-end":
|
||||
"order-last w-full justify-start px-3 pb-3 [.border-t]:pt-3 group-has-[>input]/input-group:pb-2.5",
|
||||
'inline-start': 'order-first pl-3 has-[>button]:ml-[-0.45rem] has-[>kbd]:ml-[-0.35rem]',
|
||||
'inline-end': 'order-last pr-3 has-[>button]:mr-[-0.45rem] has-[>kbd]:mr-[-0.35rem]',
|
||||
'block-start':
|
||||
'order-first w-full justify-start px-3 pt-3 [.border-b]:pb-3 group-has-[>input]/input-group:pt-2.5',
|
||||
'block-end': 'order-last w-full justify-start px-3 pb-3 [.border-t]:pt-3 group-has-[>input]/input-group:pb-2.5',
|
||||
},
|
||||
},
|
||||
defaultVariants: {
|
||||
align: "inline-start",
|
||||
align: 'inline-start',
|
||||
},
|
||||
}
|
||||
)
|
||||
},
|
||||
);
|
||||
|
||||
function InputGroupAddon({
|
||||
className,
|
||||
align = "inline-start",
|
||||
align = 'inline-start',
|
||||
...props
|
||||
}: React.ComponentProps<"div"> & VariantProps<typeof inputGroupAddonVariants>) {
|
||||
}: React.ComponentProps<'div'> & VariantProps<typeof inputGroupAddonVariants>) {
|
||||
return (
|
||||
<div
|
||||
role="group"
|
||||
data-slot="input-group-addon"
|
||||
data-align={align}
|
||||
className={cn(inputGroupAddonVariants({ align }), className)}
|
||||
onClick={(e) => {
|
||||
if ((e.target as HTMLElement).closest("button")) {
|
||||
return
|
||||
onClick={e => {
|
||||
if ((e.target as HTMLElement).closest('button')) {
|
||||
return;
|
||||
}
|
||||
e.currentTarget.parentElement?.querySelector("input")?.focus()
|
||||
e.currentTarget.parentElement?.querySelector('input')?.focus();
|
||||
}}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
const inputGroupButtonVariants = cva(
|
||||
"text-sm shadow-none flex gap-2 items-center",
|
||||
{
|
||||
variants: {
|
||||
size: {
|
||||
xs: "h-6 gap-1 px-2 rounded-[calc(var(--radius)-5px)] [&>svg:not([class*='size-'])]:size-3.5 has-[>svg]:px-2",
|
||||
sm: "h-8 px-2.5 gap-1.5 rounded-md has-[>svg]:px-2.5",
|
||||
"icon-xs":
|
||||
"size-6 rounded-[calc(var(--radius)-5px)] p-0 has-[>svg]:p-0",
|
||||
"icon-sm": "size-8 p-0 has-[>svg]:p-0",
|
||||
},
|
||||
const inputGroupButtonVariants = cva('text-sm shadow-none flex gap-2 items-center', {
|
||||
variants: {
|
||||
size: {
|
||||
xs: "h-6 gap-1 px-2 rounded-[calc(var(--radius)-5px)] [&>svg:not([class*='size-'])]:size-3.5 has-[>svg]:px-2",
|
||||
sm: 'h-8 px-2.5 gap-1.5 rounded-md has-[>svg]:px-2.5',
|
||||
'icon-xs': 'size-6 rounded-[calc(var(--radius)-5px)] p-0 has-[>svg]:p-0',
|
||||
'icon-sm': 'size-8 p-0 has-[>svg]:p-0',
|
||||
},
|
||||
defaultVariants: {
|
||||
size: "xs",
|
||||
},
|
||||
}
|
||||
)
|
||||
},
|
||||
defaultVariants: {
|
||||
size: 'xs',
|
||||
},
|
||||
});
|
||||
|
||||
function InputGroupButton({
|
||||
className,
|
||||
type = "button",
|
||||
variant = "ghost",
|
||||
size = "xs",
|
||||
type = 'button',
|
||||
variant = 'ghost',
|
||||
size = 'xs',
|
||||
...props
|
||||
}: Omit<React.ComponentProps<typeof Button>, "size"> &
|
||||
VariantProps<typeof inputGroupButtonVariants>) {
|
||||
}: Omit<React.ComponentProps<typeof Button>, 'size'> & VariantProps<typeof inputGroupButtonVariants>) {
|
||||
return (
|
||||
<Button
|
||||
type={type}
|
||||
@@ -113,59 +105,45 @@ function InputGroupButton({
|
||||
className={cn(inputGroupButtonVariants({ size }), className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function InputGroupText({ className, ...props }: React.ComponentProps<"span">) {
|
||||
function InputGroupText({ className, ...props }: React.ComponentProps<'span'>) {
|
||||
return (
|
||||
<span
|
||||
className={cn(
|
||||
"text-muted-foreground flex items-center gap-2 text-sm [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4",
|
||||
className
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function InputGroupInput({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<"input">) {
|
||||
function InputGroupInput({ className, ...props }: React.ComponentProps<'input'>) {
|
||||
return (
|
||||
<Input
|
||||
data-slot="input-group-control"
|
||||
className={cn(
|
||||
"flex-1 rounded-none border-0 bg-transparent shadow-none focus-visible:ring-0 dark:bg-transparent",
|
||||
className
|
||||
'flex-1 rounded-none border-0 bg-transparent shadow-none focus-visible:ring-0 dark:bg-transparent',
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function InputGroupTextarea({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<"textarea">) {
|
||||
function InputGroupTextarea({ className, ...props }: React.ComponentProps<'textarea'>) {
|
||||
return (
|
||||
<Textarea
|
||||
data-slot="input-group-control"
|
||||
className={cn(
|
||||
"flex-1 resize-none rounded-none border-0 bg-transparent py-3 shadow-none focus-visible:ring-0 dark:bg-transparent",
|
||||
className
|
||||
'flex-1 resize-none rounded-none border-0 bg-transparent py-3 shadow-none focus-visible:ring-0 dark:bg-transparent',
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export {
|
||||
InputGroup,
|
||||
InputGroupAddon,
|
||||
InputGroupButton,
|
||||
InputGroupText,
|
||||
InputGroupInput,
|
||||
InputGroupTextarea,
|
||||
);
|
||||
}
|
||||
|
||||
export { InputGroup, InputGroupAddon, InputGroupButton, InputGroupText, InputGroupInput, InputGroupTextarea };
|
||||
|
||||
@@ -1,22 +1,21 @@
|
||||
import * as React from "react"
|
||||
import * as React from 'react';
|
||||
|
||||
import { cn } from "../../src/lib/utils"
|
||||
import { cn } from '../../src/lib/utils';
|
||||
|
||||
function Input({ className, type, ...props }: React.ComponentProps<"input">) {
|
||||
function Input({ className, type, ...props }: React.ComponentProps<'input'>) {
|
||||
return (
|
||||
<input
|
||||
type={type}
|
||||
data-slot="input"
|
||||
className={cn(
|
||||
"file:text-foreground placeholder:text-muted-foreground selection:bg-primary selection:text-primary-foreground dark:bg-input/30 border-input h-9 w-full min-w-0 rounded-md border bg-transparent px-3 py-1 text-base shadow-xs transition-[color,box-shadow] outline-none file:inline-flex file:h-7 file:border-0 file:bg-transparent file:text-sm file:font-medium disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",
|
||||
"focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px]",
|
||||
"aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",
|
||||
className
|
||||
'file:text-foreground placeholder:text-muted-foreground selection:bg-primary selection:text-primary-foreground dark:bg-input/30 border-input h-9 w-full min-w-0 rounded-md border bg-transparent px-3 py-1 text-base shadow-xs transition-[color,box-shadow] outline-none file:inline-flex file:h-7 file:border-0 file:bg-transparent file:text-sm file:font-medium disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 md:text-sm',
|
||||
'focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px]',
|
||||
'aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive',
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
export { Input }
|
||||
|
||||
export { Input };
|
||||
|
||||
@@ -1,16 +1,16 @@
|
||||
"use client";
|
||||
'use client';
|
||||
|
||||
import * as LabelPrimitive from "@radix-ui/react-label";
|
||||
import * as React from "react";
|
||||
import * as LabelPrimitive from '@radix-ui/react-label';
|
||||
import * as React from 'react';
|
||||
|
||||
import { cn } from "../../src/lib/utils";
|
||||
import { cn } from '../../src/lib/utils';
|
||||
|
||||
function Label({ className, ...props }: React.ComponentProps<typeof LabelPrimitive.Root>) {
|
||||
return (
|
||||
<LabelPrimitive.Root
|
||||
data-slot="label"
|
||||
className={cn(
|
||||
"flex items-center gap-2 text-sm leading-none font-medium select-none group-data-[disabled=true]:pointer-events-none group-data-[disabled=true]:opacity-50 peer-disabled:cursor-not-allowed peer-disabled:opacity-50",
|
||||
'flex items-center gap-2 text-sm leading-none font-medium select-none group-data-[disabled=true]:pointer-events-none group-data-[disabled=true]:opacity-50 peer-disabled:cursor-not-allowed peer-disabled:opacity-50',
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
@@ -19,4 +19,3 @@ function Label({ className, ...props }: React.ComponentProps<typeof LabelPrimiti
|
||||
}
|
||||
|
||||
export { Label };
|
||||
|
||||
|
||||
@@ -1,23 +1,19 @@
|
||||
import * as React from "react"
|
||||
import * as PopoverPrimitive from "@radix-ui/react-popover"
|
||||
import * as React from 'react';
|
||||
import * as PopoverPrimitive from '@radix-ui/react-popover';
|
||||
|
||||
import { cn } from "../../src/lib/utils"
|
||||
import { cn } from '../../src/lib/utils';
|
||||
|
||||
function Popover({
|
||||
...props
|
||||
}: React.ComponentProps<typeof PopoverPrimitive.Root>) {
|
||||
return <PopoverPrimitive.Root data-slot="popover" {...props} />
|
||||
function Popover({ ...props }: React.ComponentProps<typeof PopoverPrimitive.Root>) {
|
||||
return <PopoverPrimitive.Root data-slot="popover" {...props} />;
|
||||
}
|
||||
|
||||
function PopoverTrigger({
|
||||
...props
|
||||
}: React.ComponentProps<typeof PopoverPrimitive.Trigger>) {
|
||||
return <PopoverPrimitive.Trigger data-slot="popover-trigger" {...props} />
|
||||
function PopoverTrigger({ ...props }: React.ComponentProps<typeof PopoverPrimitive.Trigger>) {
|
||||
return <PopoverPrimitive.Trigger data-slot="popover-trigger" {...props} />;
|
||||
}
|
||||
|
||||
function PopoverContent({
|
||||
className,
|
||||
align = "center",
|
||||
align = 'center',
|
||||
sideOffset = 4,
|
||||
...props
|
||||
}: React.ComponentProps<typeof PopoverPrimitive.Content>) {
|
||||
@@ -28,20 +24,17 @@ function PopoverContent({
|
||||
align={align}
|
||||
sideOffset={sideOffset}
|
||||
className={cn(
|
||||
"bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 w-72 rounded-md border p-4 shadow-md outline-none",
|
||||
className
|
||||
'bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 w-72 rounded-md border p-4 shadow-md outline-none',
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
</PopoverPrimitive.Portal>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function PopoverAnchor({
|
||||
...props
|
||||
}: React.ComponentProps<typeof PopoverPrimitive.Anchor>) {
|
||||
return <PopoverPrimitive.Anchor data-slot="popover-anchor" {...props} />
|
||||
function PopoverAnchor({ ...props }: React.ComponentProps<typeof PopoverPrimitive.Anchor>) {
|
||||
return <PopoverPrimitive.Anchor data-slot="popover-anchor" {...props} />;
|
||||
}
|
||||
|
||||
export { Popover, PopoverTrigger, PopoverContent, PopoverAnchor }
|
||||
|
||||
export { Popover, PopoverTrigger, PopoverContent, PopoverAnchor };
|
||||
|
||||
@@ -1,28 +1,22 @@
|
||||
"use client"
|
||||
'use client';
|
||||
|
||||
import { GripVerticalIcon } from "lucide-react"
|
||||
import * as ResizablePrimitive from "react-resizable-panels"
|
||||
import { GripVerticalIcon } from 'lucide-react';
|
||||
import * as ResizablePrimitive from 'react-resizable-panels';
|
||||
|
||||
import { cn } from "../../src/lib/utils"
|
||||
import { cn } from '../../src/lib/utils';
|
||||
|
||||
function ResizablePanelGroup({
|
||||
className,
|
||||
...props
|
||||
}: ResizablePrimitive.GroupProps) {
|
||||
function ResizablePanelGroup({ className, ...props }: ResizablePrimitive.GroupProps) {
|
||||
return (
|
||||
<ResizablePrimitive.Group
|
||||
data-slot="resizable-panel-group"
|
||||
className={cn(
|
||||
"flex h-full w-full aria-[orientation=vertical]:flex-col",
|
||||
className
|
||||
)}
|
||||
className={cn('flex h-full w-full aria-[orientation=vertical]:flex-col', className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function ResizablePanel({ ...props }: ResizablePrimitive.PanelProps) {
|
||||
return <ResizablePrimitive.Panel data-slot="resizable-panel" {...props} />
|
||||
return <ResizablePrimitive.Panel data-slot="resizable-panel" {...props} />;
|
||||
}
|
||||
|
||||
function ResizableHandle({
|
||||
@@ -30,14 +24,14 @@ function ResizableHandle({
|
||||
className,
|
||||
...props
|
||||
}: ResizablePrimitive.SeparatorProps & {
|
||||
withHandle?: boolean
|
||||
withHandle?: boolean;
|
||||
}) {
|
||||
return (
|
||||
<ResizablePrimitive.Separator
|
||||
data-slot="resizable-handle"
|
||||
className={cn(
|
||||
"bg-border focus-visible:ring-ring relative flex w-px items-center justify-center after:absolute after:inset-y-0 after:left-1/2 after:w-1 after:-translate-x-1/2 focus-visible:ring-1 focus-visible:ring-offset-1 focus-visible:outline-hidden aria-[orientation=horizontal]:h-px aria-[orientation=horizontal]:w-full aria-[orientation=horizontal]:after:left-0 aria-[orientation=horizontal]:after:h-1 aria-[orientation=horizontal]:after:w-full aria-[orientation=horizontal]:after:translate-x-0 aria-[orientation=horizontal]:after:-translate-y-1/2 [&[aria-orientation=horizontal]>div]:rotate-90",
|
||||
className
|
||||
'bg-border focus-visible:ring-ring relative flex w-px items-center justify-center after:absolute after:inset-y-0 after:left-1/2 after:w-1 after:-translate-x-1/2 focus-visible:ring-1 focus-visible:ring-offset-1 focus-visible:outline-hidden aria-[orientation=horizontal]:h-px aria-[orientation=horizontal]:w-full aria-[orientation=horizontal]:after:left-0 aria-[orientation=horizontal]:after:h-1 aria-[orientation=horizontal]:after:w-full aria-[orientation=horizontal]:after:translate-x-0 aria-[orientation=horizontal]:after:-translate-y-1/2 [&[aria-orientation=horizontal]>div]:rotate-90',
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
@@ -47,7 +41,7 @@ function ResizableHandle({
|
||||
</div>
|
||||
)}
|
||||
</ResizablePrimitive.Separator>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
export { ResizableHandle, ResizablePanel, ResizablePanelGroup }
|
||||
export { ResizableHandle, ResizablePanel, ResizablePanelGroup };
|
||||
|
||||
@@ -1,19 +1,11 @@
|
||||
import * as React from "react"
|
||||
import * as ScrollAreaPrimitive from "@radix-ui/react-scroll-area"
|
||||
import * as React from 'react';
|
||||
import * as ScrollAreaPrimitive from '@radix-ui/react-scroll-area';
|
||||
|
||||
import { cn } from "../../src/lib/utils"
|
||||
import { cn } from '../../src/lib/utils';
|
||||
|
||||
function ScrollArea({
|
||||
className,
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<typeof ScrollAreaPrimitive.Root>) {
|
||||
function ScrollArea({ className, children, ...props }: React.ComponentProps<typeof ScrollAreaPrimitive.Root>) {
|
||||
return (
|
||||
<ScrollAreaPrimitive.Root
|
||||
data-slot="scroll-area"
|
||||
className={cn("relative", className)}
|
||||
{...props}
|
||||
>
|
||||
<ScrollAreaPrimitive.Root data-slot="scroll-area" className={cn('relative', className)} {...props}>
|
||||
{/*
|
||||
Workaround for Radix ScrollArea bug #926:
|
||||
The Viewport's inner div uses display:table which breaks text-overflow:ellipsis.
|
||||
@@ -29,12 +21,12 @@ function ScrollArea({
|
||||
<ScrollBar />
|
||||
<ScrollAreaPrimitive.Corner />
|
||||
</ScrollAreaPrimitive.Root>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function ScrollBar({
|
||||
className,
|
||||
orientation = "vertical",
|
||||
orientation = 'vertical',
|
||||
...props
|
||||
}: React.ComponentProps<typeof ScrollAreaPrimitive.ScrollAreaScrollbar>) {
|
||||
return (
|
||||
@@ -42,12 +34,10 @@ function ScrollBar({
|
||||
data-slot="scroll-area-scrollbar"
|
||||
orientation={orientation}
|
||||
className={cn(
|
||||
"flex touch-none p-px transition-colors select-none",
|
||||
orientation === "vertical" &&
|
||||
"h-full w-2.5 border-l border-l-transparent",
|
||||
orientation === "horizontal" &&
|
||||
"h-2.5 flex-col border-t border-t-transparent",
|
||||
className
|
||||
'flex touch-none p-px transition-colors select-none',
|
||||
orientation === 'vertical' && 'h-full w-2.5 border-l border-l-transparent',
|
||||
orientation === 'horizontal' && 'h-2.5 flex-col border-t border-t-transparent',
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
@@ -56,8 +46,7 @@ function ScrollBar({
|
||||
className="bg-border relative flex-1 rounded-full"
|
||||
/>
|
||||
</ScrollAreaPrimitive.ScrollAreaScrollbar>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
export { ScrollArea, ScrollBar }
|
||||
|
||||
export { ScrollArea, ScrollBar };
|
||||
|
||||
@@ -1,36 +1,30 @@
|
||||
"use client"
|
||||
'use client';
|
||||
|
||||
import * as React from "react"
|
||||
import * as SelectPrimitive from "@radix-ui/react-select"
|
||||
import { CheckIcon, ChevronDownIcon, ChevronUpIcon } from "lucide-react"
|
||||
import * as React from 'react';
|
||||
import * as SelectPrimitive from '@radix-ui/react-select';
|
||||
import { CheckIcon, ChevronDownIcon, ChevronUpIcon } from 'lucide-react';
|
||||
|
||||
import { cn } from "../../src/lib/utils"
|
||||
import { cn } from '../../src/lib/utils';
|
||||
|
||||
function Select({
|
||||
...props
|
||||
}: React.ComponentProps<typeof SelectPrimitive.Root>) {
|
||||
return <SelectPrimitive.Root data-slot="select" {...props} />
|
||||
function Select({ ...props }: React.ComponentProps<typeof SelectPrimitive.Root>) {
|
||||
return <SelectPrimitive.Root data-slot="select" {...props} />;
|
||||
}
|
||||
|
||||
function SelectGroup({
|
||||
...props
|
||||
}: React.ComponentProps<typeof SelectPrimitive.Group>) {
|
||||
return <SelectPrimitive.Group data-slot="select-group" {...props} />
|
||||
function SelectGroup({ ...props }: React.ComponentProps<typeof SelectPrimitive.Group>) {
|
||||
return <SelectPrimitive.Group data-slot="select-group" {...props} />;
|
||||
}
|
||||
|
||||
function SelectValue({
|
||||
...props
|
||||
}: React.ComponentProps<typeof SelectPrimitive.Value>) {
|
||||
return <SelectPrimitive.Value data-slot="select-value" {...props} />
|
||||
function SelectValue({ ...props }: React.ComponentProps<typeof SelectPrimitive.Value>) {
|
||||
return <SelectPrimitive.Value data-slot="select-value" {...props} />;
|
||||
}
|
||||
|
||||
function SelectTrigger({
|
||||
className,
|
||||
size = "default",
|
||||
size = 'default',
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<typeof SelectPrimitive.Trigger> & {
|
||||
size?: "sm" | "default"
|
||||
size?: 'sm' | 'default';
|
||||
}) {
|
||||
return (
|
||||
<SelectPrimitive.Trigger
|
||||
@@ -38,7 +32,7 @@ function SelectTrigger({
|
||||
data-size={size}
|
||||
className={cn(
|
||||
"border-input data-[placeholder]:text-muted-foreground [&_svg:not([class*='text-'])]:text-muted-foreground focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive dark:bg-input/30 dark:hover:bg-input/50 flex w-fit items-center justify-between gap-2 rounded-md border bg-transparent px-3 py-2 text-sm whitespace-nowrap shadow-xs transition-[color,box-shadow] outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50 data-[size=default]:h-9 data-[size=sm]:h-8 *:data-[slot=select-value]:line-clamp-1 *:data-[slot=select-value]:flex *:data-[slot=select-value]:items-center *:data-[slot=select-value]:gap-2 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||
className
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
@@ -47,14 +41,14 @@ function SelectTrigger({
|
||||
<ChevronDownIcon className="size-4 opacity-50" />
|
||||
</SelectPrimitive.Icon>
|
||||
</SelectPrimitive.Trigger>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function SelectContent({
|
||||
className,
|
||||
children,
|
||||
position = "popper",
|
||||
align = "center",
|
||||
position = 'popper',
|
||||
align = 'center',
|
||||
...props
|
||||
}: React.ComponentProps<typeof SelectPrimitive.Content>) {
|
||||
return (
|
||||
@@ -62,10 +56,10 @@ function SelectContent({
|
||||
<SelectPrimitive.Content
|
||||
data-slot="select-content"
|
||||
className={cn(
|
||||
"bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 relative z-50 max-h-(--radix-select-content-available-height) min-w-[8rem] origin-(--radix-select-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border shadow-md",
|
||||
position === "popper" &&
|
||||
"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",
|
||||
className
|
||||
'bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 relative z-50 max-h-(--radix-select-content-available-height) min-w-[8rem] origin-(--radix-select-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border shadow-md',
|
||||
position === 'popper' &&
|
||||
'data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1',
|
||||
className,
|
||||
)}
|
||||
position={position}
|
||||
align={align}
|
||||
@@ -74,9 +68,9 @@ function SelectContent({
|
||||
<SelectScrollUpButton />
|
||||
<SelectPrimitive.Viewport
|
||||
className={cn(
|
||||
"p-1",
|
||||
position === "popper" &&
|
||||
"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)] scroll-my-1"
|
||||
'p-1',
|
||||
position === 'popper' &&
|
||||
'h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)] scroll-my-1',
|
||||
)}
|
||||
>
|
||||
{children}
|
||||
@@ -84,33 +78,26 @@ function SelectContent({
|
||||
<SelectScrollDownButton />
|
||||
</SelectPrimitive.Content>
|
||||
</SelectPrimitive.Portal>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function SelectLabel({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof SelectPrimitive.Label>) {
|
||||
function SelectLabel({ className, ...props }: React.ComponentProps<typeof SelectPrimitive.Label>) {
|
||||
return (
|
||||
<SelectPrimitive.Label
|
||||
data-slot="select-label"
|
||||
className={cn("text-muted-foreground px-2 py-1.5 text-xs", className)}
|
||||
className={cn('text-muted-foreground px-2 py-1.5 text-xs', className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function SelectItem({
|
||||
className,
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<typeof SelectPrimitive.Item>) {
|
||||
function SelectItem({ className, children, ...props }: React.ComponentProps<typeof SelectPrimitive.Item>) {
|
||||
return (
|
||||
<SelectPrimitive.Item
|
||||
data-slot="select-item"
|
||||
className={cn(
|
||||
"focus:bg-accent focus:text-accent-foreground [&_svg:not([class*='text-'])]:text-muted-foreground relative flex w-full cursor-default items-center gap-2 rounded-sm py-1.5 pr-8 pl-2 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 *:[span]:last:flex *:[span]:last:items-center *:[span]:last:gap-2",
|
||||
className
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
@@ -121,38 +108,29 @@ function SelectItem({
|
||||
</span>
|
||||
<SelectPrimitive.ItemText>{children}</SelectPrimitive.ItemText>
|
||||
</SelectPrimitive.Item>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function SelectSeparator({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof SelectPrimitive.Separator>) {
|
||||
function SelectSeparator({ className, ...props }: React.ComponentProps<typeof SelectPrimitive.Separator>) {
|
||||
return (
|
||||
<SelectPrimitive.Separator
|
||||
data-slot="select-separator"
|
||||
className={cn("bg-border pointer-events-none -mx-1 my-1 h-px", className)}
|
||||
className={cn('bg-border pointer-events-none -mx-1 my-1 h-px', className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function SelectScrollUpButton({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof SelectPrimitive.ScrollUpButton>) {
|
||||
function SelectScrollUpButton({ className, ...props }: React.ComponentProps<typeof SelectPrimitive.ScrollUpButton>) {
|
||||
return (
|
||||
<SelectPrimitive.ScrollUpButton
|
||||
data-slot="select-scroll-up-button"
|
||||
className={cn(
|
||||
"flex cursor-default items-center justify-center py-1",
|
||||
className
|
||||
)}
|
||||
className={cn('flex cursor-default items-center justify-center py-1', className)}
|
||||
{...props}
|
||||
>
|
||||
<ChevronUpIcon className="size-4" />
|
||||
</SelectPrimitive.ScrollUpButton>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function SelectScrollDownButton({
|
||||
@@ -162,15 +140,12 @@ function SelectScrollDownButton({
|
||||
return (
|
||||
<SelectPrimitive.ScrollDownButton
|
||||
data-slot="select-scroll-down-button"
|
||||
className={cn(
|
||||
"flex cursor-default items-center justify-center py-1",
|
||||
className
|
||||
)}
|
||||
className={cn('flex cursor-default items-center justify-center py-1', className)}
|
||||
{...props}
|
||||
>
|
||||
<ChevronDownIcon className="size-4" />
|
||||
</SelectPrimitive.ScrollDownButton>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
export {
|
||||
@@ -184,5 +159,4 @@ export {
|
||||
SelectSeparator,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
import * as React from "react"
|
||||
import * as SeparatorPrimitive from "@radix-ui/react-separator"
|
||||
import * as React from 'react';
|
||||
import * as SeparatorPrimitive from '@radix-ui/react-separator';
|
||||
|
||||
import { cn } from "../../src/lib/utils"
|
||||
import { cn } from '../../src/lib/utils';
|
||||
|
||||
function Separator({
|
||||
className,
|
||||
orientation = "horizontal",
|
||||
orientation = 'horizontal',
|
||||
decorative = true,
|
||||
...props
|
||||
}: React.ComponentProps<typeof SeparatorPrimitive.Root>) {
|
||||
@@ -15,13 +15,12 @@ function Separator({
|
||||
decorative={decorative}
|
||||
orientation={orientation}
|
||||
className={cn(
|
||||
"bg-border shrink-0 data-[orientation=horizontal]:h-px data-[orientation=horizontal]:w-full data-[orientation=vertical]:h-full data-[orientation=vertical]:w-px",
|
||||
className
|
||||
'bg-border shrink-0 data-[orientation=horizontal]:h-px data-[orientation=horizontal]:w-full data-[orientation=vertical]:h-full data-[orientation=vertical]:w-px',
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
export { Separator }
|
||||
|
||||
export { Separator };
|
||||
|
||||
@@ -1,49 +1,41 @@
|
||||
import * as React from "react"
|
||||
import { cva, type VariantProps } from "class-variance-authority"
|
||||
import { Tabs as TabsPrimitive } from "radix-ui"
|
||||
import * as React from 'react';
|
||||
import { cva, type VariantProps } from 'class-variance-authority';
|
||||
import { Tabs as TabsPrimitive } from 'radix-ui';
|
||||
|
||||
import { cn } from "../../src/lib/utils"
|
||||
import { cn } from '../../src/lib/utils';
|
||||
|
||||
function Tabs({
|
||||
className,
|
||||
orientation = "horizontal",
|
||||
...props
|
||||
}: React.ComponentProps<typeof TabsPrimitive.Root>) {
|
||||
function Tabs({ className, orientation = 'horizontal', ...props }: React.ComponentProps<typeof TabsPrimitive.Root>) {
|
||||
return (
|
||||
<TabsPrimitive.Root
|
||||
data-slot="tabs"
|
||||
data-orientation={orientation}
|
||||
orientation={orientation}
|
||||
className={cn(
|
||||
"group/tabs flex gap-2 data-[orientation=horizontal]:flex-col",
|
||||
className
|
||||
)}
|
||||
className={cn('group/tabs flex gap-2 data-[orientation=horizontal]:flex-col', className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
const tabsListVariants = cva(
|
||||
"rounded-lg p-[3px] group-data-[orientation=horizontal]/tabs:h-9 data-[variant=line]:rounded-none group/tabs-list text-muted-foreground inline-flex w-fit items-center justify-center group-data-[orientation=vertical]/tabs:h-fit group-data-[orientation=vertical]/tabs:flex-col",
|
||||
'rounded-lg p-[3px] group-data-[orientation=horizontal]/tabs:h-9 data-[variant=line]:rounded-none group/tabs-list text-muted-foreground inline-flex w-fit items-center justify-center group-data-[orientation=vertical]/tabs:h-fit group-data-[orientation=vertical]/tabs:flex-col',
|
||||
{
|
||||
variants: {
|
||||
variant: {
|
||||
default: "bg-muted",
|
||||
line: "gap-1 bg-transparent",
|
||||
default: 'bg-muted',
|
||||
line: 'gap-1 bg-transparent',
|
||||
},
|
||||
},
|
||||
defaultVariants: {
|
||||
variant: "default",
|
||||
variant: 'default',
|
||||
},
|
||||
}
|
||||
)
|
||||
},
|
||||
);
|
||||
|
||||
function TabsList({
|
||||
className,
|
||||
variant = "default",
|
||||
variant = 'default',
|
||||
...props
|
||||
}: React.ComponentProps<typeof TabsPrimitive.List> &
|
||||
VariantProps<typeof tabsListVariants>) {
|
||||
}: React.ComponentProps<typeof TabsPrimitive.List> & VariantProps<typeof tabsListVariants>) {
|
||||
return (
|
||||
<TabsPrimitive.List
|
||||
data-slot="tabs-list"
|
||||
@@ -51,26 +43,23 @@ function TabsList({
|
||||
className={cn(tabsListVariants({ variant }), className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function TabsTrigger({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof TabsPrimitive.Trigger>) {
|
||||
function TabsTrigger({ className, ...props }: React.ComponentProps<typeof TabsPrimitive.Trigger>) {
|
||||
return (
|
||||
<TabsPrimitive.Trigger
|
||||
data-slot="tabs-trigger"
|
||||
className={cn(
|
||||
"focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:outline-ring text-foreground/60 hover:text-foreground dark:text-muted-foreground dark:hover:text-foreground relative inline-flex h-[calc(100%-1px)] flex-1 items-center justify-center gap-1.5 rounded-md border border-transparent px-2 py-1 text-sm font-medium whitespace-nowrap transition-all group-data-[orientation=vertical]/tabs:w-full group-data-[orientation=vertical]/tabs:justify-start focus-visible:ring-[3px] focus-visible:outline-1 disabled:pointer-events-none disabled:opacity-50 group-data-[variant=default]/tabs-list:data-[state=active]:shadow-sm group-data-[variant=line]/tabs-list:data-[state=active]:shadow-none [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||
"group-data-[variant=line]/tabs-list:bg-transparent group-data-[variant=line]/tabs-list:data-[state=active]:bg-transparent dark:group-data-[variant=line]/tabs-list:data-[state=active]:border-transparent dark:group-data-[variant=line]/tabs-list:data-[state=active]:bg-transparent",
|
||||
"data-[state=active]:bg-background dark:data-[state=active]:text-foreground dark:data-[state=active]:border-input dark:data-[state=active]:bg-input/30 data-[state=active]:text-foreground",
|
||||
"after:bg-foreground after:absolute after:opacity-0 after:transition-opacity group-data-[orientation=horizontal]/tabs:after:inset-x-0 group-data-[orientation=horizontal]/tabs:after:bottom-[-5px] group-data-[orientation=horizontal]/tabs:after:h-0.5 group-data-[orientation=vertical]/tabs:after:inset-y-0 group-data-[orientation=vertical]/tabs:after:-right-1 group-data-[orientation=vertical]/tabs:after:w-0.5 group-data-[variant=line]/tabs-list:data-[state=active]:after:opacity-100",
|
||||
className
|
||||
'group-data-[variant=line]/tabs-list:bg-transparent group-data-[variant=line]/tabs-list:data-[state=active]:bg-transparent dark:group-data-[variant=line]/tabs-list:data-[state=active]:border-transparent dark:group-data-[variant=line]/tabs-list:data-[state=active]:bg-transparent',
|
||||
'data-[state=active]:bg-background dark:data-[state=active]:text-foreground dark:data-[state=active]:border-input dark:data-[state=active]:bg-input/30 data-[state=active]:text-foreground',
|
||||
'after:bg-foreground after:absolute after:opacity-0 after:transition-opacity group-data-[orientation=horizontal]/tabs:after:inset-x-0 group-data-[orientation=horizontal]/tabs:after:bottom-[-5px] group-data-[orientation=horizontal]/tabs:after:h-0.5 group-data-[orientation=vertical]/tabs:after:inset-y-0 group-data-[orientation=vertical]/tabs:after:-right-1 group-data-[orientation=vertical]/tabs:after:w-0.5 group-data-[variant=line]/tabs-list:data-[state=active]:after:opacity-100',
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function TabsContent({
|
||||
@@ -85,14 +74,14 @@ function TabsContent({
|
||||
data-slot="tabs-content"
|
||||
forceMount={forceMount}
|
||||
className={cn(
|
||||
"flex-1 outline-none",
|
||||
'flex-1 outline-none',
|
||||
// When forceMount is used, hide inactive tabs
|
||||
forceMount && "data-[state=inactive]:hidden",
|
||||
className
|
||||
forceMount && 'data-[state=inactive]:hidden',
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
export { Tabs, TabsList, TabsTrigger, TabsContent, tabsListVariants }
|
||||
export { Tabs, TabsList, TabsTrigger, TabsContent, tabsListVariants };
|
||||
|
||||
@@ -1,19 +1,18 @@
|
||||
import * as React from "react"
|
||||
import * as React from 'react';
|
||||
|
||||
import { cn } from "../../src/lib/utils"
|
||||
import { cn } from '../../src/lib/utils';
|
||||
|
||||
function Textarea({ className, ...props }: React.ComponentProps<"textarea">) {
|
||||
function Textarea({ className, ...props }: React.ComponentProps<'textarea'>) {
|
||||
return (
|
||||
<textarea
|
||||
data-slot="textarea"
|
||||
className={cn(
|
||||
"border-input placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive dark:bg-input/30 flex field-sizing-content min-h-16 w-full rounded-md border bg-transparent px-3 py-2 text-base shadow-xs transition-[color,box-shadow] outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",
|
||||
className
|
||||
'border-input placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive dark:bg-input/30 flex field-sizing-content min-h-16 w-full rounded-md border bg-transparent px-3 py-2 text-base shadow-xs transition-[color,box-shadow] outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50 md:text-sm',
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
export { Textarea }
|
||||
|
||||
export { Textarea };
|
||||
|
||||
@@ -1,17 +1,12 @@
|
||||
import { Moon, Sun, Monitor } from "lucide-react";
|
||||
import { useTheme, type Theme } from "../../src/lib/theme";
|
||||
import { Button } from "./button";
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuTrigger,
|
||||
} from "./dropdown-menu";
|
||||
import { Moon, Sun, Monitor } from 'lucide-react';
|
||||
import { useTheme, type Theme } from '../../src/lib/theme';
|
||||
import { Button } from './button';
|
||||
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from './dropdown-menu';
|
||||
|
||||
const themeOptions: { value: Theme; label: string; icon: React.ReactNode }[] = [
|
||||
{ value: "light", label: "Light", icon: <Sun className="h-4 w-4" /> },
|
||||
{ value: "dark", label: "Dark", icon: <Moon className="h-4 w-4" /> },
|
||||
{ value: "system", label: "System", icon: <Monitor className="h-4 w-4" /> },
|
||||
{ value: 'light', label: 'Light', icon: <Sun className="h-4 w-4" /> },
|
||||
{ value: 'dark', label: 'Dark', icon: <Moon className="h-4 w-4" /> },
|
||||
{ value: 'system', label: 'System', icon: <Monitor className="h-4 w-4" /> },
|
||||
];
|
||||
|
||||
export function ThemeToggle() {
|
||||
@@ -21,20 +16,16 @@ export function ThemeToggle() {
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button variant="ghost" size="icon" className="h-8 w-8">
|
||||
{resolvedTheme === "dark" ? (
|
||||
<Moon className="h-4 w-4" />
|
||||
) : (
|
||||
<Sun className="h-4 w-4" />
|
||||
)}
|
||||
{resolvedTheme === 'dark' ? <Moon className="h-4 w-4" /> : <Sun className="h-4 w-4" />}
|
||||
<span className="sr-only">Toggle theme</span>
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
{themeOptions.map((option) => (
|
||||
{themeOptions.map(option => (
|
||||
<DropdownMenuItem
|
||||
key={option.value}
|
||||
onClick={() => setTheme(option.value)}
|
||||
className={theme === option.value ? "bg-accent" : ""}
|
||||
className={theme === option.value ? 'bg-accent' : ''}
|
||||
>
|
||||
{option.icon}
|
||||
<span className="ml-2">{option.label}</span>
|
||||
@@ -44,4 +35,3 @@ export function ThemeToggle() {
|
||||
</DropdownMenu>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,35 +1,22 @@
|
||||
import * as React from "react"
|
||||
import * as TooltipPrimitive from "@radix-ui/react-tooltip"
|
||||
import * as React from 'react';
|
||||
import * as TooltipPrimitive from '@radix-ui/react-tooltip';
|
||||
|
||||
import { cn } from "../../src/lib/utils"
|
||||
import { cn } from '../../src/lib/utils';
|
||||
|
||||
function TooltipProvider({
|
||||
delayDuration = 0,
|
||||
...props
|
||||
}: React.ComponentProps<typeof TooltipPrimitive.Provider>) {
|
||||
return (
|
||||
<TooltipPrimitive.Provider
|
||||
data-slot="tooltip-provider"
|
||||
delayDuration={delayDuration}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
function TooltipProvider({ delayDuration = 0, ...props }: React.ComponentProps<typeof TooltipPrimitive.Provider>) {
|
||||
return <TooltipPrimitive.Provider data-slot="tooltip-provider" delayDuration={delayDuration} {...props} />;
|
||||
}
|
||||
|
||||
function Tooltip({
|
||||
...props
|
||||
}: React.ComponentProps<typeof TooltipPrimitive.Root>) {
|
||||
function Tooltip({ ...props }: React.ComponentProps<typeof TooltipPrimitive.Root>) {
|
||||
return (
|
||||
<TooltipProvider>
|
||||
<TooltipPrimitive.Root data-slot="tooltip" {...props} />
|
||||
</TooltipProvider>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function TooltipTrigger({
|
||||
...props
|
||||
}: React.ComponentProps<typeof TooltipPrimitive.Trigger>) {
|
||||
return <TooltipPrimitive.Trigger data-slot="tooltip-trigger" {...props} />
|
||||
function TooltipTrigger({ ...props }: React.ComponentProps<typeof TooltipPrimitive.Trigger>) {
|
||||
return <TooltipPrimitive.Trigger data-slot="tooltip-trigger" {...props} />;
|
||||
}
|
||||
|
||||
function TooltipContent({
|
||||
@@ -44,8 +31,8 @@ function TooltipContent({
|
||||
data-slot="tooltip-content"
|
||||
sideOffset={sideOffset}
|
||||
className={cn(
|
||||
"bg-foreground text-background animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 w-fit origin-(--radix-tooltip-content-transform-origin) rounded-md px-3 py-1.5 text-xs text-balance",
|
||||
className
|
||||
'bg-foreground text-background animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 w-fit origin-(--radix-tooltip-content-transform-origin) rounded-md px-3 py-1.5 text-xs text-balance',
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
@@ -53,8 +40,7 @@ function TooltipContent({
|
||||
<TooltipPrimitive.Arrow className="bg-foreground fill-foreground z-50 size-2.5 translate-y-[calc(-50%_-_2px)] rotate-45 rounded-[2px]" />
|
||||
</TooltipPrimitive.Content>
|
||||
</TooltipPrimitive.Portal>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
export { Tooltip, TooltipTrigger, TooltipContent, TooltipProvider }
|
||||
|
||||
export { Tooltip, TooltipTrigger, TooltipContent, TooltipProvider };
|
||||
|
||||
@@ -1,30 +1,34 @@
|
||||
import { useState, useEffect, useCallback, lazy, Suspense } from "react";
|
||||
import { Navbar } from "./components/Navbar";
|
||||
import { IdentityPanel } from "./components/IdentityPanel";
|
||||
import { TokenManagerDialog } from "./components/TokenManagerDialog";
|
||||
import { ThemeProvider } from "./lib/theme";
|
||||
import { getUuid, setUuid, apiBind, setActiveApiToken } from "./api/client";
|
||||
import { ACPDirectView } from "./components/ACPDirectView";
|
||||
import { useTokens } from "./hooks/useTokens";
|
||||
import { useState, useEffect, useCallback, lazy, Suspense } from 'react';
|
||||
import { Navbar } from './components/Navbar';
|
||||
import { IdentityPanel } from './components/IdentityPanel';
|
||||
import { TokenManagerDialog } from './components/TokenManagerDialog';
|
||||
import { ThemeProvider } from './lib/theme';
|
||||
import { getUuid, setUuid, apiBind, setActiveApiToken } from './api/client';
|
||||
import { ACPDirectView } from './components/ACPDirectView';
|
||||
import { useTokens } from './hooks/useTokens';
|
||||
|
||||
const Dashboard = lazy(() => import("./pages/Dashboard").then((m) => ({ default: m.Dashboard })));
|
||||
const SessionDetail = lazy(() => import("./pages/SessionDetail").then((m) => ({ default: m.SessionDetail })));
|
||||
const Dashboard = lazy(() => import('./pages/Dashboard').then(m => ({ default: m.Dashboard })));
|
||||
const SessionDetail = lazy(() => import('./pages/SessionDetail').then(m => ({ default: m.SessionDetail })));
|
||||
|
||||
export default function App() {
|
||||
const [currentSessionId, setCurrentSessionId] = useState<string | null>(null);
|
||||
const [identityOpen, setIdentityOpen] = useState(false);
|
||||
const [tokenDialogOpen, setTokenDialogOpen] = useState(false);
|
||||
const [acpDirect, setAcpDirect] = useState<{ url: string; token: string } | null>(null);
|
||||
const { tokens, activeTokenId, activeLabel, activeTokenValue, setActiveTokenId, addToken, removeToken, updateToken } = useTokens();
|
||||
const { tokens, activeTokenId, activeLabel, activeTokenValue, setActiveTokenId, addToken, removeToken, updateToken } =
|
||||
useTokens();
|
||||
|
||||
// Sync active token to API client
|
||||
useEffect(() => {
|
||||
setActiveApiToken(activeTokenValue);
|
||||
}, [activeTokenValue]);
|
||||
|
||||
const handleSetActiveToken = useCallback((id: string) => {
|
||||
setActiveTokenId(id);
|
||||
}, [setActiveTokenId]);
|
||||
const handleSetActiveToken = useCallback(
|
||||
(id: string) => {
|
||||
setActiveTokenId(id);
|
||||
},
|
||||
[setActiveTokenId],
|
||||
);
|
||||
|
||||
// Simple hash-based router
|
||||
const parseRoute = useCallback(() => {
|
||||
@@ -35,46 +39,46 @@ export default function App() {
|
||||
|
||||
// Check for UUID import from QR scan (?uuid=xxx)
|
||||
const params = new URLSearchParams(window.location.search);
|
||||
const importUuid = params.get("uuid");
|
||||
const importUuid = params.get('uuid');
|
||||
if (importUuid) {
|
||||
setUuid(importUuid);
|
||||
const url = new URL(window.location.href);
|
||||
url.searchParams.delete("uuid");
|
||||
window.history.replaceState(null, "", url);
|
||||
url.searchParams.delete('uuid');
|
||||
window.history.replaceState(null, '', url);
|
||||
}
|
||||
|
||||
// Check for ACP direct connection (?acp=1)
|
||||
const acpParam = params.get("acp");
|
||||
if (acpParam === "1") {
|
||||
const stored = sessionStorage.getItem("acp_connection");
|
||||
const acpParam = params.get('acp');
|
||||
if (acpParam === '1') {
|
||||
const stored = sessionStorage.getItem('acp_connection');
|
||||
if (stored) {
|
||||
try {
|
||||
const acpData = JSON.parse(stored);
|
||||
if (acpData.url && acpData.token) {
|
||||
setAcpDirect({ url: acpData.url, token: acpData.token });
|
||||
sessionStorage.removeItem("acp_connection");
|
||||
sessionStorage.removeItem('acp_connection');
|
||||
// Clean URL
|
||||
const url = new URL(window.location.href);
|
||||
url.searchParams.delete("acp");
|
||||
window.history.replaceState(null, "", url);
|
||||
url.searchParams.delete('acp');
|
||||
window.history.replaceState(null, '', url);
|
||||
return;
|
||||
}
|
||||
} catch {
|
||||
sessionStorage.removeItem("acp_connection");
|
||||
sessionStorage.removeItem('acp_connection');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Check for CLI session bind (?sid=xxx) — bind session to current UUID
|
||||
const sid = params.get("sid");
|
||||
const sid = params.get('sid');
|
||||
if (sid) {
|
||||
const url = new URL(window.location.href);
|
||||
url.searchParams.delete("sid");
|
||||
window.history.replaceState(null, "", `/code/${sid}`);
|
||||
url.searchParams.delete('sid');
|
||||
window.history.replaceState(null, '', `/code/${sid}`);
|
||||
setCurrentSessionId(sid);
|
||||
// Bind this session to the current user's UUID for ownership
|
||||
apiBind(sid).catch((err: unknown) => {
|
||||
console.warn("Failed to bind session:", err);
|
||||
console.warn('Failed to bind session:', err);
|
||||
});
|
||||
return;
|
||||
}
|
||||
@@ -90,17 +94,17 @@ export default function App() {
|
||||
|
||||
useEffect(() => {
|
||||
parseRoute();
|
||||
window.addEventListener("popstate", parseRoute);
|
||||
return () => window.removeEventListener("popstate", parseRoute);
|
||||
window.addEventListener('popstate', parseRoute);
|
||||
return () => window.removeEventListener('popstate', parseRoute);
|
||||
}, [parseRoute]);
|
||||
|
||||
const navigateToSession = useCallback((sessionId: string) => {
|
||||
window.history.pushState(null, "", `/code/${sessionId}`);
|
||||
window.history.pushState(null, '', `/code/${sessionId}`);
|
||||
setCurrentSessionId(sessionId);
|
||||
}, []);
|
||||
|
||||
const navigateToDashboard = useCallback(() => {
|
||||
window.history.pushState(null, "", "/code/");
|
||||
window.history.pushState(null, '', '/code/');
|
||||
setCurrentSessionId(null);
|
||||
setAcpDirect(null);
|
||||
}, []);
|
||||
@@ -112,8 +116,8 @@ export default function App() {
|
||||
onIdentityClick={() => setIdentityOpen(true)}
|
||||
onTokenClick={() => setTokenDialogOpen(true)}
|
||||
activeTokenLabel={currentSessionId ? undefined : activeLabel}
|
||||
sessionTitle={currentSessionId || (acpDirect ? "ACP" : undefined)}
|
||||
onBack={(currentSessionId || acpDirect) ? navigateToDashboard : undefined}
|
||||
sessionTitle={currentSessionId || (acpDirect ? 'ACP' : undefined)}
|
||||
onBack={currentSessionId || acpDirect ? navigateToDashboard : undefined}
|
||||
/>
|
||||
|
||||
<Suspense fallback={<div className="flex flex-1 items-center justify-center text-text-muted">Loading...</div>}>
|
||||
|
||||
@@ -1,172 +1,192 @@
|
||||
import { describe, test, expect, mock, beforeEach } from "bun:test";
|
||||
import { describe, test, expect, mock, beforeEach } from 'bun:test'
|
||||
|
||||
// In-memory localStorage mock
|
||||
let store: Record<string, string> = {};
|
||||
let store: Record<string, string> = {}
|
||||
|
||||
beforeEach(() => {
|
||||
store = {};
|
||||
(globalThis as any).localStorage = {
|
||||
store = {}
|
||||
;(globalThis as any).localStorage = {
|
||||
getItem: (k: string) => store[k] ?? null,
|
||||
setItem: (k: string, v: string) => { store[k] = v; },
|
||||
removeItem: (k: string) => { delete store[k]; },
|
||||
clear: () => { store = {}; },
|
||||
get length() { return Object.keys(store).length; },
|
||||
setItem: (k: string, v: string) => {
|
||||
store[k] = v
|
||||
},
|
||||
removeItem: (k: string) => {
|
||||
delete store[k]
|
||||
},
|
||||
clear: () => {
|
||||
store = {}
|
||||
},
|
||||
get length() {
|
||||
return Object.keys(store).length
|
||||
},
|
||||
key: () => null,
|
||||
};
|
||||
});
|
||||
}
|
||||
})
|
||||
|
||||
// Mock fetch
|
||||
const fetchMock = {
|
||||
lastUrl: "",
|
||||
lastUrl: '',
|
||||
lastOpts: {} as RequestInit,
|
||||
response: { ok: true, status: 200, statusText: "OK" },
|
||||
response: { ok: true, status: 200, statusText: 'OK' },
|
||||
responseData: {} as any,
|
||||
};
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
fetchMock.lastUrl = "";
|
||||
fetchMock.lastOpts = {};
|
||||
fetchMock.response = { ok: true, status: 200, statusText: "OK" };
|
||||
fetchMock.responseData = {};
|
||||
client.setActiveApiToken(null);
|
||||
});
|
||||
fetchMock.lastUrl = ''
|
||||
fetchMock.lastOpts = {}
|
||||
fetchMock.response = { ok: true, status: 200, statusText: 'OK' }
|
||||
fetchMock.responseData = {}
|
||||
client.setActiveApiToken(null)
|
||||
})
|
||||
|
||||
(globalThis as any).fetch = async (url: string, opts: RequestInit) => {
|
||||
fetchMock.lastUrl = url;
|
||||
fetchMock.lastOpts = opts;
|
||||
;(globalThis as any).fetch = async (url: string, opts: RequestInit) => {
|
||||
fetchMock.lastUrl = url
|
||||
fetchMock.lastOpts = opts
|
||||
return {
|
||||
ok: fetchMock.response.ok,
|
||||
status: fetchMock.response.status,
|
||||
statusText: fetchMock.response.statusText,
|
||||
json: async () => fetchMock.responseData,
|
||||
} as Response;
|
||||
};
|
||||
} as Response
|
||||
}
|
||||
|
||||
const { getUuid, setUuid } = await import("../api/client");
|
||||
const { getUuid, setUuid } = await import('../api/client')
|
||||
|
||||
// Import api* functions - they depend on getUuid and fetch
|
||||
const client = await import("../api/client");
|
||||
const relayClient = await import("../acp/relay-client");
|
||||
const client = await import('../api/client')
|
||||
const relayClient = await import('../acp/relay-client')
|
||||
|
||||
// =============================================================================
|
||||
// getUuid()
|
||||
// =============================================================================
|
||||
|
||||
describe("getUuid", () => {
|
||||
test("returns existing UUID from localStorage", () => {
|
||||
store["rcs_uuid"] = "existing-uuid";
|
||||
expect(getUuid()).toBe("existing-uuid");
|
||||
});
|
||||
describe('getUuid', () => {
|
||||
test('returns existing UUID from localStorage', () => {
|
||||
store['rcs_uuid'] = 'existing-uuid'
|
||||
expect(getUuid()).toBe('existing-uuid')
|
||||
})
|
||||
|
||||
test("generates and stores new UUID when none exists", () => {
|
||||
const uuid = getUuid();
|
||||
test('generates and stores new UUID when none exists', () => {
|
||||
const uuid = getUuid()
|
||||
expect(uuid).toMatch(
|
||||
/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,
|
||||
);
|
||||
expect(store["rcs_uuid"]).toBe(uuid);
|
||||
});
|
||||
)
|
||||
expect(store['rcs_uuid']).toBe(uuid)
|
||||
})
|
||||
|
||||
test("returns same UUID on subsequent calls", () => {
|
||||
const a = getUuid();
|
||||
const b = getUuid();
|
||||
expect(a).toBe(b);
|
||||
});
|
||||
});
|
||||
test('returns same UUID on subsequent calls', () => {
|
||||
const a = getUuid()
|
||||
const b = getUuid()
|
||||
expect(a).toBe(b)
|
||||
})
|
||||
})
|
||||
|
||||
// =============================================================================
|
||||
// setUuid()
|
||||
// =============================================================================
|
||||
|
||||
describe("setUuid", () => {
|
||||
test("writes UUID to localStorage", () => {
|
||||
setUuid("custom-uuid-999");
|
||||
expect(store["rcs_uuid"]).toBe("custom-uuid-999");
|
||||
});
|
||||
describe('setUuid', () => {
|
||||
test('writes UUID to localStorage', () => {
|
||||
setUuid('custom-uuid-999')
|
||||
expect(store['rcs_uuid']).toBe('custom-uuid-999')
|
||||
})
|
||||
|
||||
test("getUuid returns the set UUID", () => {
|
||||
setUuid("my-uuid");
|
||||
expect(getUuid()).toBe("my-uuid");
|
||||
});
|
||||
});
|
||||
test('getUuid returns the set UUID', () => {
|
||||
setUuid('my-uuid')
|
||||
expect(getUuid()).toBe('my-uuid')
|
||||
})
|
||||
})
|
||||
|
||||
// =============================================================================
|
||||
// api() — tested via apiFetchSession (GET) and apiBind (POST)
|
||||
// =============================================================================
|
||||
|
||||
describe("api functions", () => {
|
||||
test("GET request appends uuid to URL", async () => {
|
||||
store["rcs_uuid"] = "test-uuid";
|
||||
fetchMock.responseData = [];
|
||||
await client.apiFetchSessions();
|
||||
expect(fetchMock.lastUrl).toContain("uuid=test-uuid");
|
||||
expect(fetchMock.lastOpts.method).toBe("GET");
|
||||
});
|
||||
describe('api functions', () => {
|
||||
test('GET request appends uuid to URL', async () => {
|
||||
store['rcs_uuid'] = 'test-uuid'
|
||||
fetchMock.responseData = []
|
||||
await client.apiFetchSessions()
|
||||
expect(fetchMock.lastUrl).toContain('uuid=test-uuid')
|
||||
expect(fetchMock.lastOpts.method).toBe('GET')
|
||||
})
|
||||
|
||||
test("GET request uses ? for URL without existing query params", async () => {
|
||||
store["rcs_uuid"] = "test-uuid";
|
||||
fetchMock.responseData = [];
|
||||
await client.apiFetchSessions();
|
||||
expect(fetchMock.lastUrl).toContain("?uuid=");
|
||||
});
|
||||
test('GET request uses ? for URL without existing query params', async () => {
|
||||
store['rcs_uuid'] = 'test-uuid'
|
||||
fetchMock.responseData = []
|
||||
await client.apiFetchSessions()
|
||||
expect(fetchMock.lastUrl).toContain('?uuid=')
|
||||
})
|
||||
|
||||
test("GET request uses & for URL with existing query params", async () => {
|
||||
store["rcs_uuid"] = "test-uuid";
|
||||
fetchMock.responseData = [];
|
||||
await client.apiFetchAllSessions();
|
||||
test('GET request uses & for URL with existing query params', async () => {
|
||||
store['rcs_uuid'] = 'test-uuid'
|
||||
fetchMock.responseData = []
|
||||
await client.apiFetchAllSessions()
|
||||
// apiFetchAllSessions calls GET /web/sessions/all
|
||||
expect(fetchMock.lastUrl).toContain("?uuid=");
|
||||
});
|
||||
expect(fetchMock.lastUrl).toContain('?uuid=')
|
||||
})
|
||||
|
||||
test("POST request includes JSON body", async () => {
|
||||
store["rcs_uuid"] = "test-uuid";
|
||||
fetchMock.responseData = {};
|
||||
await client.apiBind("sess-1");
|
||||
expect(fetchMock.lastOpts.method).toBe("POST");
|
||||
expect(fetchMock.lastOpts.body).toBe(JSON.stringify({ sessionId: "sess-1" }));
|
||||
expect(fetchMock.lastOpts.headers).toEqual({ "Content-Type": "application/json" });
|
||||
});
|
||||
|
||||
test("active API token is sent only in Authorization header", async () => {
|
||||
store["rcs_uuid"] = "browser-uuid";
|
||||
fetchMock.responseData = [];
|
||||
client.setActiveApiToken("secret-token");
|
||||
|
||||
await client.apiFetchSessions();
|
||||
|
||||
expect(fetchMock.lastUrl).toContain("uuid=browser-uuid");
|
||||
expect(fetchMock.lastUrl).not.toContain("secret-token");
|
||||
test('POST request includes JSON body', async () => {
|
||||
store['rcs_uuid'] = 'test-uuid'
|
||||
fetchMock.responseData = {}
|
||||
await client.apiBind('sess-1')
|
||||
expect(fetchMock.lastOpts.method).toBe('POST')
|
||||
expect(fetchMock.lastOpts.body).toBe(
|
||||
JSON.stringify({ sessionId: 'sess-1' }),
|
||||
)
|
||||
expect(fetchMock.lastOpts.headers).toEqual({
|
||||
"Content-Type": "application/json",
|
||||
Authorization: "Bearer secret-token",
|
||||
});
|
||||
});
|
||||
'Content-Type': 'application/json',
|
||||
})
|
||||
})
|
||||
|
||||
test("throws error on non-ok response", async () => {
|
||||
store["rcs_uuid"] = "test-uuid";
|
||||
fetchMock.response = { ok: false, status: 401, statusText: "Unauthorized" };
|
||||
fetchMock.responseData = { error: { type: "auth", message: "Invalid UUID" } };
|
||||
await expect(client.apiFetchSessions()).rejects.toThrow("Invalid UUID");
|
||||
});
|
||||
test('active API token is sent only in Authorization header', async () => {
|
||||
store['rcs_uuid'] = 'browser-uuid'
|
||||
fetchMock.responseData = []
|
||||
client.setActiveApiToken('secret-token')
|
||||
|
||||
test("throws with statusText when error message is missing", async () => {
|
||||
store["rcs_uuid"] = "test-uuid";
|
||||
fetchMock.response = { ok: false, status: 500, statusText: "Internal Server Error" };
|
||||
fetchMock.responseData = {};
|
||||
await expect(client.apiFetchSessions()).rejects.toThrow("Internal Server Error");
|
||||
});
|
||||
});
|
||||
await client.apiFetchSessions()
|
||||
|
||||
describe("ACP relay client", () => {
|
||||
test("builds relay URLs without UUID or token query params", () => {
|
||||
(globalThis as any).window = {
|
||||
expect(fetchMock.lastUrl).toContain('uuid=browser-uuid')
|
||||
expect(fetchMock.lastUrl).not.toContain('secret-token')
|
||||
expect(fetchMock.lastOpts.headers).toEqual({
|
||||
'Content-Type': 'application/json',
|
||||
Authorization: 'Bearer secret-token',
|
||||
})
|
||||
})
|
||||
|
||||
test('throws error on non-ok response', async () => {
|
||||
store['rcs_uuid'] = 'test-uuid'
|
||||
fetchMock.response = { ok: false, status: 401, statusText: 'Unauthorized' }
|
||||
fetchMock.responseData = {
|
||||
error: { type: 'auth', message: 'Invalid UUID' },
|
||||
}
|
||||
await expect(client.apiFetchSessions()).rejects.toThrow('Invalid UUID')
|
||||
})
|
||||
|
||||
test('throws with statusText when error message is missing', async () => {
|
||||
store['rcs_uuid'] = 'test-uuid'
|
||||
fetchMock.response = {
|
||||
ok: false,
|
||||
status: 500,
|
||||
statusText: 'Internal Server Error',
|
||||
}
|
||||
fetchMock.responseData = {}
|
||||
await expect(client.apiFetchSessions()).rejects.toThrow(
|
||||
'Internal Server Error',
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
describe('ACP relay client', () => {
|
||||
test('builds relay URLs without UUID or token query params', () => {
|
||||
;(globalThis as any).window = {
|
||||
location: {
|
||||
protocol: "https:",
|
||||
host: "rcs.example.test",
|
||||
protocol: 'https:',
|
||||
host: 'rcs.example.test',
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
expect(relayClient.buildRelayUrl("agent_123")).toBe(
|
||||
"wss://rcs.example.test/acp/relay/agent_123",
|
||||
);
|
||||
});
|
||||
});
|
||||
expect(relayClient.buildRelayUrl('agent_123')).toBe(
|
||||
'wss://rcs.example.test/acp/relay/agent_123',
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { afterEach, describe, test, expect } from "bun:test";
|
||||
import { afterEach, describe, test, expect } from 'bun:test'
|
||||
|
||||
const {
|
||||
formatTime,
|
||||
@@ -8,273 +8,284 @@ const {
|
||||
generateMessageUuid,
|
||||
extractEventText,
|
||||
isConversationClearedStatus,
|
||||
} = await import("../lib/utils");
|
||||
} = await import('../lib/utils')
|
||||
|
||||
type UuidCrypto = {
|
||||
randomUUID?: () => string;
|
||||
getRandomValues?: (array: Uint8Array) => Uint8Array;
|
||||
};
|
||||
randomUUID?: () => string
|
||||
getRandomValues?: (array: Uint8Array) => Uint8Array
|
||||
}
|
||||
|
||||
const originalCryptoDescriptor = Object.getOwnPropertyDescriptor(globalThis, "crypto");
|
||||
const originalCryptoDescriptor = Object.getOwnPropertyDescriptor(
|
||||
globalThis,
|
||||
'crypto',
|
||||
)
|
||||
|
||||
function setCryptoForTest(value: UuidCrypto): void {
|
||||
Object.defineProperty(globalThis, "crypto", {
|
||||
Object.defineProperty(globalThis, 'crypto', {
|
||||
configurable: true,
|
||||
writable: true,
|
||||
value,
|
||||
});
|
||||
})
|
||||
}
|
||||
|
||||
function restoreCryptoForTest(): void {
|
||||
if (originalCryptoDescriptor) {
|
||||
Object.defineProperty(globalThis, "crypto", originalCryptoDescriptor);
|
||||
Object.defineProperty(globalThis, 'crypto', originalCryptoDescriptor)
|
||||
} else {
|
||||
Reflect.deleteProperty(globalThis, "crypto");
|
||||
Reflect.deleteProperty(globalThis, 'crypto')
|
||||
}
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
restoreCryptoForTest();
|
||||
});
|
||||
restoreCryptoForTest()
|
||||
})
|
||||
|
||||
// =============================================================================
|
||||
// formatTime()
|
||||
// =============================================================================
|
||||
|
||||
describe("formatTime", () => {
|
||||
test("returns empty string for null", () => {
|
||||
expect(formatTime(null)).toBe("");
|
||||
});
|
||||
describe('formatTime', () => {
|
||||
test('returns empty string for null', () => {
|
||||
expect(formatTime(null)).toBe('')
|
||||
})
|
||||
|
||||
test("returns empty string for undefined", () => {
|
||||
expect(formatTime(undefined)).toBe("");
|
||||
});
|
||||
test('returns empty string for undefined', () => {
|
||||
expect(formatTime(undefined)).toBe('')
|
||||
})
|
||||
|
||||
test("returns empty string for 0", () => {
|
||||
expect(formatTime(0)).toBe("");
|
||||
});
|
||||
test('returns empty string for 0', () => {
|
||||
expect(formatTime(0)).toBe('')
|
||||
})
|
||||
|
||||
test("formats valid unix timestamp", () => {
|
||||
const result = formatTime(1700000000);
|
||||
expect(result).toContain("2023");
|
||||
});
|
||||
});
|
||||
test('formats valid unix timestamp', () => {
|
||||
const result = formatTime(1700000000)
|
||||
expect(result).toContain('2023')
|
||||
})
|
||||
})
|
||||
|
||||
// =============================================================================
|
||||
// statusClass()
|
||||
// =============================================================================
|
||||
|
||||
describe("statusClass", () => {
|
||||
test("maps known statuses correctly", () => {
|
||||
expect(statusClass("active")).toBe("active");
|
||||
expect(statusClass("running")).toBe("running");
|
||||
expect(statusClass("idle")).toBe("idle");
|
||||
expect(statusClass("inactive")).toBe("inactive");
|
||||
expect(statusClass("requires_action")).toBe("requires_action");
|
||||
expect(statusClass("archived")).toBe("archived");
|
||||
expect(statusClass("error")).toBe("error");
|
||||
});
|
||||
describe('statusClass', () => {
|
||||
test('maps known statuses correctly', () => {
|
||||
expect(statusClass('active')).toBe('active')
|
||||
expect(statusClass('running')).toBe('running')
|
||||
expect(statusClass('idle')).toBe('idle')
|
||||
expect(statusClass('inactive')).toBe('inactive')
|
||||
expect(statusClass('requires_action')).toBe('requires_action')
|
||||
expect(statusClass('archived')).toBe('archived')
|
||||
expect(statusClass('error')).toBe('error')
|
||||
})
|
||||
|
||||
test("returns default for unknown status", () => {
|
||||
expect(statusClass("unknown")).toBe("default");
|
||||
});
|
||||
test('returns default for unknown status', () => {
|
||||
expect(statusClass('unknown')).toBe('default')
|
||||
})
|
||||
|
||||
test("returns default for null", () => {
|
||||
expect(statusClass(null)).toBe("default");
|
||||
});
|
||||
test('returns default for null', () => {
|
||||
expect(statusClass(null)).toBe('default')
|
||||
})
|
||||
|
||||
test("returns default for undefined", () => {
|
||||
expect(statusClass(undefined)).toBe("default");
|
||||
});
|
||||
test('returns default for undefined', () => {
|
||||
expect(statusClass(undefined)).toBe('default')
|
||||
})
|
||||
|
||||
test("returns default for empty string", () => {
|
||||
expect(statusClass("")).toBe("default");
|
||||
});
|
||||
});
|
||||
test('returns default for empty string', () => {
|
||||
expect(statusClass('')).toBe('default')
|
||||
})
|
||||
})
|
||||
|
||||
// =============================================================================
|
||||
// isClosedSessionStatus()
|
||||
// =============================================================================
|
||||
|
||||
describe("isClosedSessionStatus", () => {
|
||||
test("returns true for archived", () => {
|
||||
expect(isClosedSessionStatus("archived")).toBe(true);
|
||||
});
|
||||
describe('isClosedSessionStatus', () => {
|
||||
test('returns true for archived', () => {
|
||||
expect(isClosedSessionStatus('archived')).toBe(true)
|
||||
})
|
||||
|
||||
test("returns true for inactive", () => {
|
||||
expect(isClosedSessionStatus("inactive")).toBe(true);
|
||||
});
|
||||
test('returns true for inactive', () => {
|
||||
expect(isClosedSessionStatus('inactive')).toBe(true)
|
||||
})
|
||||
|
||||
test("returns false for active", () => {
|
||||
expect(isClosedSessionStatus("active")).toBe(false);
|
||||
});
|
||||
test('returns false for active', () => {
|
||||
expect(isClosedSessionStatus('active')).toBe(false)
|
||||
})
|
||||
|
||||
test("returns false for null", () => {
|
||||
expect(isClosedSessionStatus(null)).toBe(false);
|
||||
});
|
||||
test('returns false for null', () => {
|
||||
expect(isClosedSessionStatus(null)).toBe(false)
|
||||
})
|
||||
|
||||
test("returns false for undefined", () => {
|
||||
expect(isClosedSessionStatus(undefined)).toBe(false);
|
||||
});
|
||||
});
|
||||
test('returns false for undefined', () => {
|
||||
expect(isClosedSessionStatus(undefined)).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
// =============================================================================
|
||||
// truncate()
|
||||
// =============================================================================
|
||||
|
||||
describe("truncate", () => {
|
||||
test("returns empty string for null", () => {
|
||||
expect(truncate(null, 10)).toBe("");
|
||||
});
|
||||
describe('truncate', () => {
|
||||
test('returns empty string for null', () => {
|
||||
expect(truncate(null, 10)).toBe('')
|
||||
})
|
||||
|
||||
test("returns empty string for undefined", () => {
|
||||
expect(truncate(undefined, 10)).toBe("");
|
||||
});
|
||||
test('returns empty string for undefined', () => {
|
||||
expect(truncate(undefined, 10)).toBe('')
|
||||
})
|
||||
|
||||
test("returns original string when shorter than max", () => {
|
||||
expect(truncate("hello", 10)).toBe("hello");
|
||||
});
|
||||
test('returns original string when shorter than max', () => {
|
||||
expect(truncate('hello', 10)).toBe('hello')
|
||||
})
|
||||
|
||||
test("returns original string when exactly max length", () => {
|
||||
expect(truncate("12345", 5)).toBe("12345");
|
||||
});
|
||||
test('returns original string when exactly max length', () => {
|
||||
expect(truncate('12345', 5)).toBe('12345')
|
||||
})
|
||||
|
||||
test("truncates and appends ... when longer than max", () => {
|
||||
expect(truncate("hello world", 5)).toBe("hello...");
|
||||
});
|
||||
});
|
||||
test('truncates and appends ... when longer than max', () => {
|
||||
expect(truncate('hello world', 5)).toBe('hello...')
|
||||
})
|
||||
})
|
||||
|
||||
// =============================================================================
|
||||
// generateMessageUuid()
|
||||
// =============================================================================
|
||||
|
||||
describe("generateMessageUuid", () => {
|
||||
test("returns an RFC 4122 v4 UUID", () => {
|
||||
const uuid = generateMessageUuid();
|
||||
expect(typeof uuid).toBe("string");
|
||||
describe('generateMessageUuid', () => {
|
||||
test('returns an RFC 4122 v4 UUID', () => {
|
||||
const uuid = generateMessageUuid()
|
||||
expect(typeof uuid).toBe('string')
|
||||
expect(uuid).toMatch(
|
||||
/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,
|
||||
);
|
||||
});
|
||||
)
|
||||
})
|
||||
|
||||
test("uses crypto.randomUUID when available", () => {
|
||||
test('uses crypto.randomUUID when available', () => {
|
||||
setCryptoForTest({
|
||||
randomUUID: () => "11111111-1111-4111-8111-111111111111",
|
||||
randomUUID: () => '11111111-1111-4111-8111-111111111111',
|
||||
getRandomValues: () => {
|
||||
throw new Error("getRandomValues should not be called");
|
||||
throw new Error('getRandomValues should not be called')
|
||||
},
|
||||
});
|
||||
})
|
||||
|
||||
expect(generateMessageUuid()).toBe("11111111-1111-4111-8111-111111111111");
|
||||
});
|
||||
expect(generateMessageUuid()).toBe('11111111-1111-4111-8111-111111111111')
|
||||
})
|
||||
|
||||
test("uses crypto.getRandomValues when randomUUID is unavailable", () => {
|
||||
test('uses crypto.getRandomValues when randomUUID is unavailable', () => {
|
||||
setCryptoForTest({
|
||||
getRandomValues: (array) => {
|
||||
getRandomValues: array => {
|
||||
for (let i = 0; i < array.length; i++) {
|
||||
array[i] = i;
|
||||
array[i] = i
|
||||
}
|
||||
return array;
|
||||
return array
|
||||
},
|
||||
});
|
||||
})
|
||||
|
||||
expect(generateMessageUuid()).toBe("00010203-0405-4607-8809-0a0b0c0d0e0f");
|
||||
});
|
||||
expect(generateMessageUuid()).toBe('00010203-0405-4607-8809-0a0b0c0d0e0f')
|
||||
})
|
||||
|
||||
test("throws when no secure random source is available", () => {
|
||||
setCryptoForTest({});
|
||||
test('throws when no secure random source is available', () => {
|
||||
setCryptoForTest({})
|
||||
|
||||
expect(() => generateMessageUuid()).toThrow("crypto.getRandomValues is required");
|
||||
});
|
||||
});
|
||||
expect(() => generateMessageUuid()).toThrow(
|
||||
'crypto.getRandomValues is required',
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
// =============================================================================
|
||||
// extractEventText()
|
||||
// =============================================================================
|
||||
|
||||
describe("extractEventText", () => {
|
||||
test("returns empty string for null", () => {
|
||||
expect(extractEventText(null)).toBe("");
|
||||
});
|
||||
describe('extractEventText', () => {
|
||||
test('returns empty string for null', () => {
|
||||
expect(extractEventText(null)).toBe('')
|
||||
})
|
||||
|
||||
test("returns empty string for undefined", () => {
|
||||
expect(extractEventText(undefined)).toBe("");
|
||||
});
|
||||
test('returns empty string for undefined', () => {
|
||||
expect(extractEventText(undefined)).toBe('')
|
||||
})
|
||||
|
||||
test("returns empty string for non-object", () => {
|
||||
expect(extractEventText("string" as any)).toBe("");
|
||||
});
|
||||
test('returns empty string for non-object', () => {
|
||||
expect(extractEventText('string' as any)).toBe('')
|
||||
})
|
||||
|
||||
test("extracts payload.content string", () => {
|
||||
expect(extractEventText({ content: "hello" })).toBe("hello");
|
||||
});
|
||||
test('extracts payload.content string', () => {
|
||||
expect(extractEventText({ content: 'hello' })).toBe('hello')
|
||||
})
|
||||
|
||||
test("extracts from message.content text blocks array", () => {
|
||||
test('extracts from message.content text blocks array', () => {
|
||||
const payload = {
|
||||
message: {
|
||||
content: [
|
||||
{ type: "text", text: "line 1" },
|
||||
{ type: "text", text: "line 2" },
|
||||
{ type: 'text', text: 'line 1' },
|
||||
{ type: 'text', text: 'line 2' },
|
||||
],
|
||||
},
|
||||
};
|
||||
expect(extractEventText(payload)).toBe("line 1\nline 2");
|
||||
});
|
||||
}
|
||||
expect(extractEventText(payload)).toBe('line 1\nline 2')
|
||||
})
|
||||
|
||||
test("ignores non-text blocks", () => {
|
||||
test('ignores non-text blocks', () => {
|
||||
const payload = {
|
||||
message: {
|
||||
content: [
|
||||
{ type: "image", data: "base64..." },
|
||||
{ type: "text", text: "only text" },
|
||||
{ type: 'image', data: 'base64...' },
|
||||
{ type: 'text', text: 'only text' },
|
||||
],
|
||||
},
|
||||
};
|
||||
expect(extractEventText(payload)).toBe("only text");
|
||||
});
|
||||
}
|
||||
expect(extractEventText(payload)).toBe('only text')
|
||||
})
|
||||
|
||||
test("returns empty string when message.content has no text blocks", () => {
|
||||
test('returns empty string when message.content has no text blocks', () => {
|
||||
const payload = {
|
||||
message: { content: [{ type: "image", data: "base64" }] },
|
||||
};
|
||||
expect(extractEventText(payload)).toBe("");
|
||||
});
|
||||
message: { content: [{ type: 'image', data: 'base64' }] },
|
||||
}
|
||||
expect(extractEventText(payload)).toBe('')
|
||||
})
|
||||
|
||||
test("returns empty string for empty object", () => {
|
||||
expect(extractEventText({})).toBe("");
|
||||
});
|
||||
});
|
||||
test('returns empty string for empty object', () => {
|
||||
expect(extractEventText({})).toBe('')
|
||||
})
|
||||
})
|
||||
|
||||
// =============================================================================
|
||||
// isConversationClearedStatus()
|
||||
// =============================================================================
|
||||
|
||||
describe("isConversationClearedStatus", () => {
|
||||
test("returns true when payload.status is conversation_cleared", () => {
|
||||
expect(isConversationClearedStatus({ status: "conversation_cleared" })).toBe(true);
|
||||
});
|
||||
describe('isConversationClearedStatus', () => {
|
||||
test('returns true when payload.status is conversation_cleared', () => {
|
||||
expect(
|
||||
isConversationClearedStatus({ status: 'conversation_cleared' }),
|
||||
).toBe(true)
|
||||
})
|
||||
|
||||
test("returns true when payload.raw.status is conversation_cleared", () => {
|
||||
expect(isConversationClearedStatus({ raw: { status: "conversation_cleared" } })).toBe(true);
|
||||
});
|
||||
test('returns true when payload.raw.status is conversation_cleared', () => {
|
||||
expect(
|
||||
isConversationClearedStatus({ raw: { status: 'conversation_cleared' } }),
|
||||
).toBe(true)
|
||||
})
|
||||
|
||||
test("returns false for null", () => {
|
||||
expect(isConversationClearedStatus(null)).toBe(false);
|
||||
});
|
||||
test('returns false for null', () => {
|
||||
expect(isConversationClearedStatus(null)).toBe(false)
|
||||
})
|
||||
|
||||
test("returns false for undefined", () => {
|
||||
expect(isConversationClearedStatus(undefined)).toBe(false);
|
||||
});
|
||||
test('returns false for undefined', () => {
|
||||
expect(isConversationClearedStatus(undefined)).toBe(false)
|
||||
})
|
||||
|
||||
test("returns false for other status", () => {
|
||||
expect(isConversationClearedStatus({ status: "active" })).toBe(false);
|
||||
});
|
||||
test('returns false for other status', () => {
|
||||
expect(isConversationClearedStatus({ status: 'active' })).toBe(false)
|
||||
})
|
||||
|
||||
test("returns false when raw has different status", () => {
|
||||
expect(isConversationClearedStatus({ raw: { status: "running" } })).toBe(false);
|
||||
});
|
||||
test('returns false when raw has different status', () => {
|
||||
expect(isConversationClearedStatus({ raw: { status: 'running' } })).toBe(
|
||||
false,
|
||||
)
|
||||
})
|
||||
|
||||
test("returns false for empty object", () => {
|
||||
expect(isConversationClearedStatus({})).toBe(false);
|
||||
});
|
||||
});
|
||||
test('returns false for empty object', () => {
|
||||
expect(isConversationClearedStatus({})).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,2 +1,2 @@
|
||||
export * from "./types";
|
||||
export * from "./client";
|
||||
export * from './types'
|
||||
export * from './client'
|
||||
|
||||
@@ -1,14 +1,14 @@
|
||||
import { ACPClient } from "./client";
|
||||
import type { ACPSettings } from "./types";
|
||||
import { getActiveApiToken } from "../api/client";
|
||||
import { ACPClient } from './client'
|
||||
import type { ACPSettings } from './types'
|
||||
import { getActiveApiToken } from '../api/client'
|
||||
|
||||
/**
|
||||
* Build the RCS relay WebSocket URL for a given agent.
|
||||
* Uses UUID auth (same as /code/ pages).
|
||||
*/
|
||||
export function buildRelayUrl(agentId: string): string {
|
||||
const protocol = window.location.protocol === "https:" ? "wss:" : "ws:";
|
||||
return `${protocol}//${window.location.host}/acp/relay/${agentId}`;
|
||||
const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:'
|
||||
return `${protocol}//${window.location.host}/acp/relay/${agentId}`
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -17,10 +17,10 @@ export function buildRelayUrl(agentId: string): string {
|
||||
* the frontend and the target acp-link instance.
|
||||
*/
|
||||
export function createRelayClient(agentId: string): ACPClient {
|
||||
const relayUrl = buildRelayUrl(agentId);
|
||||
const token = getActiveApiToken();
|
||||
const relayUrl = buildRelayUrl(agentId)
|
||||
const token = getActiveApiToken()
|
||||
const settings: ACPSettings = token
|
||||
? { proxyUrl: relayUrl, token }
|
||||
: { proxyUrl: relayUrl };
|
||||
return new ACPClient(settings);
|
||||
: { proxyUrl: relayUrl }
|
||||
return new ACPClient(settings)
|
||||
}
|
||||
|
||||
@@ -1,33 +1,33 @@
|
||||
// Permission option kinds (from ACP protocol)
|
||||
export type PermissionOptionKind =
|
||||
| "allow_once"
|
||||
| "allow_always"
|
||||
| "reject_once"
|
||||
| "reject_always";
|
||||
| 'allow_once'
|
||||
| 'allow_always'
|
||||
| 'reject_once'
|
||||
| 'reject_always'
|
||||
|
||||
// Permission option (from ACP protocol)
|
||||
export interface PermissionOption {
|
||||
optionId: string;
|
||||
name: string;
|
||||
kind: PermissionOptionKind;
|
||||
optionId: string
|
||||
name: string
|
||||
kind: PermissionOptionKind
|
||||
}
|
||||
|
||||
// Permission request payload (sent from server to client)
|
||||
export interface PermissionRequestPayload {
|
||||
requestId: string; // Unique ID for this request (generated by server)
|
||||
sessionId: string;
|
||||
options: PermissionOption[];
|
||||
requestId: string // Unique ID for this request (generated by server)
|
||||
sessionId: string
|
||||
options: PermissionOption[]
|
||||
toolCall: {
|
||||
toolCallId: string; // Tool call ID to match with existing tool calls
|
||||
title?: string;
|
||||
content?: ToolCallContent[];
|
||||
};
|
||||
toolCallId: string // Tool call ID to match with existing tool calls
|
||||
title?: string
|
||||
content?: ToolCallContent[]
|
||||
}
|
||||
}
|
||||
|
||||
// Permission response (sent from client to server)
|
||||
export interface PermissionResponsePayload {
|
||||
requestId: string;
|
||||
outcome: { outcome: "cancelled" } | { outcome: "selected"; optionId: string };
|
||||
requestId: string
|
||||
outcome: { outcome: 'cancelled' } | { outcome: 'selected'; optionId: string }
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
@@ -38,129 +38,133 @@ export interface PermissionResponsePayload {
|
||||
// ============================================================================
|
||||
|
||||
export interface BrowserToolParams {
|
||||
action: "tabs" | "read" | "execute";
|
||||
tabId?: number; // Required for read/execute
|
||||
script?: string; // Required for execute
|
||||
action: 'tabs' | 'read' | 'execute'
|
||||
tabId?: number // Required for read/execute
|
||||
script?: string // Required for execute
|
||||
}
|
||||
|
||||
export interface BrowserTabInfo {
|
||||
id: number;
|
||||
url: string;
|
||||
title: string;
|
||||
active: boolean;
|
||||
id: number
|
||||
url: string
|
||||
title: string
|
||||
active: boolean
|
||||
}
|
||||
|
||||
export interface BrowserTabsResult {
|
||||
action: "tabs";
|
||||
tabs: BrowserTabInfo[];
|
||||
action: 'tabs'
|
||||
tabs: BrowserTabInfo[]
|
||||
}
|
||||
|
||||
export interface BrowserReadResult {
|
||||
action: "read";
|
||||
tabId: number;
|
||||
url: string;
|
||||
title: string;
|
||||
dom: string;
|
||||
action: 'read'
|
||||
tabId: number
|
||||
url: string
|
||||
title: string
|
||||
dom: string
|
||||
viewport: {
|
||||
width: number;
|
||||
height: number;
|
||||
scrollX: number;
|
||||
scrollY: number;
|
||||
};
|
||||
selection: string | null;
|
||||
width: number
|
||||
height: number
|
||||
scrollX: number
|
||||
scrollY: number
|
||||
}
|
||||
selection: string | null
|
||||
}
|
||||
|
||||
export interface BrowserExecuteResult {
|
||||
action: "execute";
|
||||
tabId: number;
|
||||
url: string;
|
||||
result?: unknown;
|
||||
error?: string;
|
||||
action: 'execute'
|
||||
tabId: number
|
||||
url: string
|
||||
result?: unknown
|
||||
error?: string
|
||||
}
|
||||
|
||||
export type BrowserToolResult =
|
||||
| BrowserTabsResult
|
||||
| BrowserReadResult
|
||||
| BrowserExecuteResult;
|
||||
| BrowserExecuteResult
|
||||
|
||||
// Messages sent TO the proxy server
|
||||
// Reference: Zed's MessageEditor.contents() builds Vec<acp::ContentBlock>
|
||||
export type ProxyMessage =
|
||||
| { type: "connect" }
|
||||
| { type: "disconnect" }
|
||||
| { type: "new_session"; payload?: { cwd?: string; permissionMode?: string } }
|
||||
| { type: "prompt"; payload: { content: ContentBlock[] } } // Changed from { text: string } to match Zed
|
||||
| { type: "cancel" }
|
||||
| { type: "permission_response"; payload: PermissionResponsePayload }
|
||||
| { type: "browser_tool_result"; callId: string; result: BrowserToolResult | { error: string } }
|
||||
| { type: "set_session_model"; payload: { modelId: string } }
|
||||
| { type: 'connect' }
|
||||
| { type: 'disconnect' }
|
||||
| { type: 'new_session'; payload?: { cwd?: string; permissionMode?: string } }
|
||||
| { type: 'prompt'; payload: { content: ContentBlock[] } } // Changed from { text: string } to match Zed
|
||||
| { type: 'cancel' }
|
||||
| { type: 'permission_response'; payload: PermissionResponsePayload }
|
||||
| {
|
||||
type: 'browser_tool_result'
|
||||
callId: string
|
||||
result: BrowserToolResult | { error: string }
|
||||
}
|
||||
| { type: 'set_session_model'; payload: { modelId: string } }
|
||||
// Session history operations - Reference: Zed's AgentSessionList trait
|
||||
| { type: "list_sessions"; payload?: ListSessionsRequest }
|
||||
| { type: "load_session"; payload: LoadSessionRequest }
|
||||
| { type: "resume_session"; payload: ResumeSessionRequest }
|
||||
| { type: 'list_sessions'; payload?: ListSessionsRequest }
|
||||
| { type: 'load_session'; payload: LoadSessionRequest }
|
||||
| { type: 'resume_session'; payload: ResumeSessionRequest }
|
||||
// Heartbeat
|
||||
| { type: "ping" };
|
||||
| { type: 'ping' }
|
||||
|
||||
// Messages received FROM the proxy server
|
||||
// Reference: Zed's AgentConnection stores agentCapabilities from initialize response
|
||||
export interface ProxyStatusMessage {
|
||||
type: "status";
|
||||
type: 'status'
|
||||
payload: {
|
||||
connected: boolean;
|
||||
agentInfo?: { name?: string; version?: string };
|
||||
connected: boolean
|
||||
agentInfo?: { name?: string; version?: string }
|
||||
/** Full agent capabilities from initialize response */
|
||||
capabilities?: AgentCapabilities;
|
||||
};
|
||||
capabilities?: AgentCapabilities
|
||||
}
|
||||
}
|
||||
|
||||
export interface ProxyErrorMessage {
|
||||
type: "error";
|
||||
payload: { message: string };
|
||||
type: 'error'
|
||||
payload: { message: string }
|
||||
}
|
||||
|
||||
// Reference: Zed's session/initialize response includes promptCapabilities and models
|
||||
export interface ProxySessionCreatedMessage {
|
||||
type: "session_created";
|
||||
type: 'session_created'
|
||||
payload: {
|
||||
sessionId: string;
|
||||
promptCapabilities?: PromptCapabilities; // From agent's initialize response
|
||||
models?: SessionModelState | null; // Model state if agent supports model selection
|
||||
};
|
||||
sessionId: string
|
||||
promptCapabilities?: PromptCapabilities // From agent's initialize response
|
||||
models?: SessionModelState | null // Model state if agent supports model selection
|
||||
}
|
||||
}
|
||||
|
||||
export interface ProxySessionUpdateMessage {
|
||||
type: "session_update";
|
||||
type: 'session_update'
|
||||
payload: {
|
||||
sessionId: string;
|
||||
update: SessionUpdate;
|
||||
};
|
||||
sessionId: string
|
||||
update: SessionUpdate
|
||||
}
|
||||
}
|
||||
|
||||
export interface ProxyPromptCompleteMessage {
|
||||
type: "prompt_complete";
|
||||
payload: { stopReason: string };
|
||||
type: 'prompt_complete'
|
||||
payload: { stopReason: string }
|
||||
}
|
||||
|
||||
export interface ProxyPermissionRequestMessage {
|
||||
type: "permission_request";
|
||||
payload: PermissionRequestPayload;
|
||||
type: 'permission_request'
|
||||
payload: PermissionRequestPayload
|
||||
}
|
||||
|
||||
export interface ProxyBrowserToolCallMessage {
|
||||
type: "browser_tool_call";
|
||||
callId: string;
|
||||
params: BrowserToolParams;
|
||||
type: 'browser_tool_call'
|
||||
callId: string
|
||||
params: BrowserToolParams
|
||||
}
|
||||
|
||||
export interface ProxyPongMessage {
|
||||
type: "pong";
|
||||
type: 'pong'
|
||||
}
|
||||
|
||||
export interface ProxyModelChangedMessage {
|
||||
type: "model_changed";
|
||||
type: 'model_changed'
|
||||
payload: {
|
||||
modelId: string;
|
||||
};
|
||||
modelId: string
|
||||
}
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
@@ -173,8 +177,8 @@ export interface ProxyModelChangedMessage {
|
||||
* Reference: Zed's AgentSessionListResponse
|
||||
*/
|
||||
export interface ProxySessionListMessage {
|
||||
type: "session_list";
|
||||
payload: ListSessionsResponse;
|
||||
type: 'session_list'
|
||||
payload: ListSessionsResponse
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -182,12 +186,12 @@ export interface ProxySessionListMessage {
|
||||
* Reference: Zed's load_session returns Entity<AcpThread>
|
||||
*/
|
||||
export interface ProxySessionLoadedMessage {
|
||||
type: "session_loaded";
|
||||
type: 'session_loaded'
|
||||
payload: {
|
||||
sessionId: string;
|
||||
promptCapabilities?: PromptCapabilities;
|
||||
models?: SessionModelState | null;
|
||||
};
|
||||
sessionId: string
|
||||
promptCapabilities?: PromptCapabilities
|
||||
models?: SessionModelState | null
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -195,12 +199,12 @@ export interface ProxySessionLoadedMessage {
|
||||
* Reference: Zed's resume_session returns Entity<AcpThread>
|
||||
*/
|
||||
export interface ProxySessionResumedMessage {
|
||||
type: "session_resumed";
|
||||
type: 'session_resumed'
|
||||
payload: {
|
||||
sessionId: string;
|
||||
promptCapabilities?: PromptCapabilities;
|
||||
models?: SessionModelState | null;
|
||||
};
|
||||
sessionId: string
|
||||
promptCapabilities?: PromptCapabilities
|
||||
models?: SessionModelState | null
|
||||
}
|
||||
}
|
||||
|
||||
export type ProxyResponse =
|
||||
@@ -216,116 +220,123 @@ export type ProxyResponse =
|
||||
// Session history responses
|
||||
| ProxySessionListMessage
|
||||
| ProxySessionLoadedMessage
|
||||
| ProxySessionResumedMessage;
|
||||
| ProxySessionResumedMessage
|
||||
|
||||
// Content block types (matches @agentclientprotocol/sdk ContentBlock)
|
||||
// Reference: Zed's acp::ContentBlock in agent-client-protocol crate
|
||||
export interface TextContent {
|
||||
type: "text";
|
||||
text: string;
|
||||
type: 'text'
|
||||
text: string
|
||||
}
|
||||
|
||||
export interface ImageContent {
|
||||
type: "image";
|
||||
mimeType: string;
|
||||
data: string; // base64 encoded image data
|
||||
uri?: string; // optional URI for the image source
|
||||
type: 'image'
|
||||
mimeType: string
|
||||
data: string // base64 encoded image data
|
||||
uri?: string // optional URI for the image source
|
||||
}
|
||||
|
||||
export interface ResourceLinkContent {
|
||||
type: "resource_link";
|
||||
uri: string;
|
||||
name: string;
|
||||
title?: string;
|
||||
description?: string;
|
||||
mimeType?: string;
|
||||
size?: number;
|
||||
type: 'resource_link'
|
||||
uri: string
|
||||
name: string
|
||||
title?: string
|
||||
description?: string
|
||||
mimeType?: string
|
||||
size?: number
|
||||
}
|
||||
|
||||
export type ContentBlock = TextContent | ImageContent | ResourceLinkContent | { type: string; text?: string };
|
||||
export type ContentBlock =
|
||||
| TextContent
|
||||
| ImageContent
|
||||
| ResourceLinkContent
|
||||
| { type: string; text?: string }
|
||||
|
||||
// Session update types from ACP
|
||||
export interface AgentMessageChunkUpdate {
|
||||
sessionUpdate: "agent_message_chunk";
|
||||
content: ContentBlock;
|
||||
sessionUpdate: 'agent_message_chunk'
|
||||
content: ContentBlock
|
||||
}
|
||||
|
||||
// Tool call content types from ACP
|
||||
export interface ToolCallContentBlock {
|
||||
type: "content";
|
||||
content: ContentBlock;
|
||||
type: 'content'
|
||||
content: ContentBlock
|
||||
}
|
||||
|
||||
export interface ToolCallDiffContent {
|
||||
type: "diff";
|
||||
path: string;
|
||||
oldText?: string | null;
|
||||
newText: string;
|
||||
type: 'diff'
|
||||
path: string
|
||||
oldText?: string | null
|
||||
newText: string
|
||||
}
|
||||
|
||||
export interface ToolCallTerminalContent {
|
||||
type: "terminal";
|
||||
terminalId: string;
|
||||
type: 'terminal'
|
||||
terminalId: string
|
||||
}
|
||||
|
||||
export type ToolCallContent = ToolCallContentBlock | ToolCallDiffContent | ToolCallTerminalContent;
|
||||
export type ToolCallContent =
|
||||
| ToolCallContentBlock
|
||||
| ToolCallDiffContent
|
||||
| ToolCallTerminalContent
|
||||
|
||||
export interface ToolCallUpdate {
|
||||
sessionUpdate: "tool_call";
|
||||
toolCallId: string;
|
||||
title: string;
|
||||
status: string;
|
||||
content?: ToolCallContent[];
|
||||
rawInput?: Record<string, unknown>;
|
||||
rawOutput?: Record<string, unknown>;
|
||||
sessionUpdate: 'tool_call'
|
||||
toolCallId: string
|
||||
title: string
|
||||
status: string
|
||||
content?: ToolCallContent[]
|
||||
rawInput?: Record<string, unknown>
|
||||
rawOutput?: Record<string, unknown>
|
||||
}
|
||||
|
||||
export interface ToolCallStatusUpdate {
|
||||
sessionUpdate: "tool_call_update";
|
||||
toolCallId: string;
|
||||
status?: string;
|
||||
title?: string;
|
||||
content?: ToolCallContent[];
|
||||
rawInput?: Record<string, unknown>;
|
||||
rawOutput?: Record<string, unknown>;
|
||||
sessionUpdate: 'tool_call_update'
|
||||
toolCallId: string
|
||||
status?: string
|
||||
title?: string
|
||||
content?: ToolCallContent[]
|
||||
rawInput?: Record<string, unknown>
|
||||
rawOutput?: Record<string, unknown>
|
||||
}
|
||||
|
||||
export interface AgentThoughtChunkUpdate {
|
||||
sessionUpdate: "agent_thought_chunk";
|
||||
content: ContentBlock;
|
||||
sessionUpdate: 'agent_thought_chunk'
|
||||
content: ContentBlock
|
||||
}
|
||||
|
||||
export type PlanEntryPriority = "high" | "medium" | "low";
|
||||
export type PlanEntryStatus = "pending" | "in_progress" | "completed";
|
||||
export type PlanEntryPriority = 'high' | 'medium' | 'low'
|
||||
export type PlanEntryStatus = 'pending' | 'in_progress' | 'completed'
|
||||
|
||||
export interface PlanEntry {
|
||||
_meta?: Record<string, unknown> | null;
|
||||
content: string;
|
||||
priority: PlanEntryPriority;
|
||||
status: PlanEntryStatus;
|
||||
_meta?: Record<string, unknown> | null
|
||||
content: string
|
||||
priority: PlanEntryPriority
|
||||
status: PlanEntryStatus
|
||||
}
|
||||
|
||||
export interface PlanUpdate {
|
||||
sessionUpdate: "plan";
|
||||
_meta?: Record<string, unknown> | null;
|
||||
entries: PlanEntry[];
|
||||
sessionUpdate: 'plan'
|
||||
_meta?: Record<string, unknown> | null
|
||||
entries: PlanEntry[]
|
||||
}
|
||||
|
||||
export interface UserMessageChunkUpdate {
|
||||
sessionUpdate: "user_message_chunk";
|
||||
content: ContentBlock;
|
||||
sessionUpdate: 'user_message_chunk'
|
||||
content: ContentBlock
|
||||
}
|
||||
|
||||
// Available command from agent (matches ACP SDK AvailableCommand)
|
||||
export interface AvailableCommand {
|
||||
name: string;
|
||||
description: string;
|
||||
input?: { hint: string };
|
||||
name: string
|
||||
description: string
|
||||
input?: { hint: string }
|
||||
}
|
||||
|
||||
export interface AvailableCommandsUpdate {
|
||||
sessionUpdate: "available_commands_update";
|
||||
availableCommands: AvailableCommand[];
|
||||
sessionUpdate: 'available_commands_update'
|
||||
availableCommands: AvailableCommand[]
|
||||
}
|
||||
|
||||
export type SessionUpdate =
|
||||
@@ -335,22 +346,22 @@ export type SessionUpdate =
|
||||
| AgentThoughtChunkUpdate
|
||||
| PlanUpdate
|
||||
| UserMessageChunkUpdate
|
||||
| AvailableCommandsUpdate;
|
||||
| AvailableCommandsUpdate
|
||||
|
||||
// Connection state
|
||||
export type ConnectionState =
|
||||
| "disconnected"
|
||||
| "connecting"
|
||||
| "connected"
|
||||
| "error";
|
||||
| 'disconnected'
|
||||
| 'connecting'
|
||||
| 'connected'
|
||||
| 'error'
|
||||
|
||||
// PromptCapabilities from ACP protocol
|
||||
// Reference: Zed's acp::PromptCapabilities in agent-client-protocol crate
|
||||
// Used to check what content types the agent supports
|
||||
export interface PromptCapabilities {
|
||||
audio?: boolean; // Agent supports audio content
|
||||
embeddedContext?: boolean; // Agent supports embedded context in prompts
|
||||
image?: boolean; // Agent supports image content
|
||||
audio?: boolean // Agent supports audio content
|
||||
embeddedContext?: boolean // Agent supports embedded context in prompts
|
||||
image?: boolean // Agent supports image content
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
@@ -365,9 +376,9 @@ export interface PromptCapabilities {
|
||||
*/
|
||||
export interface McpCapabilities {
|
||||
/** Agent supports client-provided MCP servers */
|
||||
clientServers?: boolean;
|
||||
clientServers?: boolean
|
||||
/** Reserved for extensibility */
|
||||
_meta?: Record<string, unknown> | null;
|
||||
_meta?: Record<string, unknown> | null
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -377,7 +388,7 @@ export interface McpCapabilities {
|
||||
*/
|
||||
export interface SessionListCapabilities {
|
||||
/** Reserved for extensibility */
|
||||
_meta?: Record<string, unknown> | null;
|
||||
_meta?: Record<string, unknown> | null
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -387,7 +398,7 @@ export interface SessionListCapabilities {
|
||||
*/
|
||||
export interface SessionResumeCapabilities {
|
||||
/** Reserved for extensibility */
|
||||
_meta?: Record<string, unknown> | null;
|
||||
_meta?: Record<string, unknown> | null
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -397,7 +408,7 @@ export interface SessionResumeCapabilities {
|
||||
*/
|
||||
export interface SessionForkCapabilities {
|
||||
/** Reserved for extensibility */
|
||||
_meta?: Record<string, unknown> | null;
|
||||
_meta?: Record<string, unknown> | null
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -411,13 +422,13 @@ export interface SessionForkCapabilities {
|
||||
*/
|
||||
export interface SessionCapabilities {
|
||||
/** Reserved for extensibility */
|
||||
_meta?: Record<string, unknown> | null;
|
||||
_meta?: Record<string, unknown> | null
|
||||
/** @experimental Agent supports forking sessions via session/fork */
|
||||
fork?: SessionForkCapabilities | null;
|
||||
fork?: SessionForkCapabilities | null
|
||||
/** @experimental Agent supports listing sessions via session/list */
|
||||
list?: SessionListCapabilities | null;
|
||||
list?: SessionListCapabilities | null
|
||||
/** @experimental Agent supports resuming sessions via session/resume */
|
||||
resume?: SessionResumeCapabilities | null;
|
||||
resume?: SessionResumeCapabilities | null
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -428,15 +439,15 @@ export interface SessionCapabilities {
|
||||
*/
|
||||
export interface AgentCapabilities {
|
||||
/** Reserved for extensibility */
|
||||
_meta?: Record<string, unknown> | null;
|
||||
_meta?: Record<string, unknown> | null
|
||||
/** Whether the agent supports session/load */
|
||||
loadSession?: boolean;
|
||||
loadSession?: boolean
|
||||
/** MCP capabilities supported by the agent */
|
||||
mcpCapabilities?: McpCapabilities;
|
||||
mcpCapabilities?: McpCapabilities
|
||||
/** Prompt capabilities supported by the agent */
|
||||
promptCapabilities?: PromptCapabilities;
|
||||
promptCapabilities?: PromptCapabilities
|
||||
/** Session capabilities supported by the agent */
|
||||
sessionCapabilities?: SessionCapabilities;
|
||||
sessionCapabilities?: SessionCapabilities
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
@@ -454,15 +465,15 @@ export interface AgentCapabilities {
|
||||
*/
|
||||
export interface AgentSessionInfo {
|
||||
/** Reserved for extensibility */
|
||||
_meta?: Record<string, unknown> | null;
|
||||
_meta?: Record<string, unknown> | null
|
||||
/** Working directory for the session (required per SDK) */
|
||||
cwd: string;
|
||||
cwd: string
|
||||
/** Unique identifier for the session */
|
||||
sessionId: string;
|
||||
sessionId: string
|
||||
/** Human-readable title for the session */
|
||||
title?: string | null;
|
||||
title?: string | null
|
||||
/** ISO 8601 timestamp when the session was last updated */
|
||||
updatedAt?: string | null;
|
||||
updatedAt?: string | null
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -471,11 +482,11 @@ export interface AgentSessionInfo {
|
||||
*/
|
||||
export interface ListSessionsRequest {
|
||||
/** Reserved for extensibility */
|
||||
_meta?: Record<string, unknown> | null;
|
||||
_meta?: Record<string, unknown> | null
|
||||
/** Filter sessions by working directory */
|
||||
cwd?: string;
|
||||
cwd?: string
|
||||
/** Pagination cursor for fetching more results */
|
||||
cursor?: string;
|
||||
cursor?: string
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -484,11 +495,11 @@ export interface ListSessionsRequest {
|
||||
*/
|
||||
export interface ListSessionsResponse {
|
||||
/** Reserved for extensibility */
|
||||
_meta?: Record<string, unknown> | null;
|
||||
_meta?: Record<string, unknown> | null
|
||||
/** Cursor for fetching the next page of results */
|
||||
nextCursor?: string | null;
|
||||
nextCursor?: string | null
|
||||
/** Array of session info objects */
|
||||
sessions: AgentSessionInfo[];
|
||||
sessions: AgentSessionInfo[]
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -497,11 +508,11 @@ export interface ListSessionsResponse {
|
||||
*/
|
||||
export interface LoadSessionRequest {
|
||||
/** Reserved for extensibility */
|
||||
_meta?: Record<string, unknown> | null;
|
||||
_meta?: Record<string, unknown> | null
|
||||
/** Session ID to load */
|
||||
sessionId: string;
|
||||
sessionId: string
|
||||
/** Working directory for the session */
|
||||
cwd?: string;
|
||||
cwd?: string
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -510,11 +521,11 @@ export interface LoadSessionRequest {
|
||||
*/
|
||||
export interface ResumeSessionRequest {
|
||||
/** Reserved for extensibility */
|
||||
_meta?: Record<string, unknown> | null;
|
||||
_meta?: Record<string, unknown> | null
|
||||
/** Session ID to resume */
|
||||
sessionId: string;
|
||||
sessionId: string
|
||||
/** Working directory for the session */
|
||||
cwd?: string;
|
||||
cwd?: string
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
@@ -528,11 +539,11 @@ export interface ResumeSessionRequest {
|
||||
*/
|
||||
export interface ModelInfo {
|
||||
/** Unique identifier for the model */
|
||||
modelId: string;
|
||||
modelId: string
|
||||
/** Human-readable name of the model */
|
||||
name: string;
|
||||
name: string
|
||||
/** Optional description of the model */
|
||||
description?: string | null;
|
||||
description?: string | null
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -541,20 +552,20 @@ export interface ModelInfo {
|
||||
*/
|
||||
export interface SessionModelState {
|
||||
/** The set of models that the Agent can use */
|
||||
availableModels: ModelInfo[];
|
||||
availableModels: ModelInfo[]
|
||||
/** The current model the Agent is using */
|
||||
currentModelId: string;
|
||||
currentModelId: string
|
||||
}
|
||||
|
||||
// Settings
|
||||
export interface ACPSettings {
|
||||
proxyUrl: string;
|
||||
proxyUrl: string
|
||||
/** Auth token for remote access (sent via WebSocket subprotocol) */
|
||||
token?: string;
|
||||
token?: string
|
||||
/** Working directory for the agent session */
|
||||
cwd?: string;
|
||||
cwd?: string
|
||||
}
|
||||
|
||||
export const DEFAULT_SETTINGS: ACPSettings = {
|
||||
proxyUrl: "ws://localhost:9315/ws",
|
||||
};
|
||||
proxyUrl: 'ws://localhost:9315/ws',
|
||||
}
|
||||
|
||||
@@ -1,90 +1,102 @@
|
||||
import type { Session, Environment, ControlResponse, SessionEvent } from "../types";
|
||||
import { generateMessageUuid } from "../lib/utils";
|
||||
import type {
|
||||
Session,
|
||||
Environment,
|
||||
ControlResponse,
|
||||
SessionEvent,
|
||||
} from '../types'
|
||||
import { generateMessageUuid } from '../lib/utils'
|
||||
|
||||
const BASE = "";
|
||||
const BASE = ''
|
||||
|
||||
export function getUuid(): string {
|
||||
let uuid = localStorage.getItem("rcs_uuid");
|
||||
let uuid = localStorage.getItem('rcs_uuid')
|
||||
if (!uuid) {
|
||||
uuid = generateMessageUuid();
|
||||
localStorage.setItem("rcs_uuid", uuid);
|
||||
uuid = generateMessageUuid()
|
||||
localStorage.setItem('rcs_uuid', uuid)
|
||||
}
|
||||
return uuid;
|
||||
return uuid
|
||||
}
|
||||
|
||||
export function setUuid(uuid: string): void {
|
||||
localStorage.setItem("rcs_uuid", uuid);
|
||||
localStorage.setItem('rcs_uuid', uuid)
|
||||
}
|
||||
|
||||
/** Active API token for Authorization header (set by useTokens) */
|
||||
let _activeToken: string | null = null;
|
||||
let _activeToken: string | null = null
|
||||
|
||||
export function setActiveApiToken(token: string | null): void {
|
||||
_activeToken = token;
|
||||
_activeToken = token
|
||||
}
|
||||
|
||||
export function getActiveApiToken(): string | null {
|
||||
return _activeToken;
|
||||
return _activeToken
|
||||
}
|
||||
|
||||
async function api<T>(method: string, path: string, body?: unknown): Promise<T> {
|
||||
const headers: Record<string, string> = { "Content-Type": "application/json" };
|
||||
async function api<T>(
|
||||
method: string,
|
||||
path: string,
|
||||
body?: unknown,
|
||||
): Promise<T> {
|
||||
const headers: Record<string, string> = { 'Content-Type': 'application/json' }
|
||||
|
||||
if (_activeToken) {
|
||||
headers["Authorization"] = `Bearer ${_activeToken}`;
|
||||
headers['Authorization'] = `Bearer ${_activeToken}`
|
||||
}
|
||||
|
||||
const uuid = getUuid();
|
||||
const sep = path.includes("?") ? "&" : "?";
|
||||
const url = `${BASE}${path}${sep}uuid=${encodeURIComponent(uuid)}`;
|
||||
const opts: RequestInit = { method, headers };
|
||||
if (body !== undefined) opts.body = JSON.stringify(body);
|
||||
const uuid = getUuid()
|
||||
const sep = path.includes('?') ? '&' : '?'
|
||||
const url = `${BASE}${path}${sep}uuid=${encodeURIComponent(uuid)}`
|
||||
const opts: RequestInit = { method, headers }
|
||||
if (body !== undefined) opts.body = JSON.stringify(body)
|
||||
|
||||
const res = await fetch(url, opts);
|
||||
const data = await res.json();
|
||||
const res = await fetch(url, opts)
|
||||
const data = await res.json()
|
||||
if (!res.ok) {
|
||||
const err = data.error || { type: "unknown", message: res.statusText };
|
||||
throw new Error(err.message || err.type);
|
||||
const err = data.error || { type: 'unknown', message: res.statusText }
|
||||
throw new Error(err.message || err.type)
|
||||
}
|
||||
return data as T;
|
||||
return data as T
|
||||
}
|
||||
|
||||
export function apiBind(sessionId: string) {
|
||||
return api<void>("POST", "/web/bind", { sessionId });
|
||||
return api<void>('POST', '/web/bind', { sessionId })
|
||||
}
|
||||
|
||||
export function apiFetchSessions() {
|
||||
return api<Session[]>("GET", "/web/sessions");
|
||||
return api<Session[]>('GET', '/web/sessions')
|
||||
}
|
||||
|
||||
export function apiFetchAllSessions() {
|
||||
return api<Session[]>("GET", "/web/sessions/all");
|
||||
return api<Session[]>('GET', '/web/sessions/all')
|
||||
}
|
||||
|
||||
export function apiFetchSession(id: string) {
|
||||
return api<Session>("GET", `/web/sessions/${id}`);
|
||||
return api<Session>('GET', `/web/sessions/${id}`)
|
||||
}
|
||||
|
||||
export function apiFetchSessionHistory(id: string) {
|
||||
return api<{ events: SessionEvent[] }>("GET", `/web/sessions/${id}/history`);
|
||||
return api<{ events: SessionEvent[] }>('GET', `/web/sessions/${id}/history`)
|
||||
}
|
||||
|
||||
export function apiFetchEnvironments() {
|
||||
return api<Environment[]>("GET", "/web/environments");
|
||||
return api<Environment[]>('GET', '/web/environments')
|
||||
}
|
||||
|
||||
export function apiSendEvent(sessionId: string, body: Record<string, unknown>) {
|
||||
return api<void>("POST", `/web/sessions/${sessionId}/events`, body);
|
||||
return api<void>('POST', `/web/sessions/${sessionId}/events`, body)
|
||||
}
|
||||
|
||||
export function apiSendControl(sessionId: string, body: ControlResponse) {
|
||||
return api<void>("POST", `/web/sessions/${sessionId}/control`, body);
|
||||
return api<void>('POST', `/web/sessions/${sessionId}/control`, body)
|
||||
}
|
||||
|
||||
export function apiInterrupt(sessionId: string) {
|
||||
return api<void>("POST", `/web/sessions/${sessionId}/interrupt`);
|
||||
return api<void>('POST', `/web/sessions/${sessionId}/interrupt`)
|
||||
}
|
||||
|
||||
export function apiCreateSession(body: { title?: string; environment_id?: string }) {
|
||||
return api<Session>("POST", "/web/sessions", body);
|
||||
export function apiCreateSession(body: {
|
||||
title?: string
|
||||
environment_id?: string
|
||||
}) {
|
||||
return api<Session>('POST', '/web/sessions', body)
|
||||
}
|
||||
|
||||
@@ -1,41 +1,41 @@
|
||||
import { getUuid } from "./client";
|
||||
import type { SessionEvent } from "../types";
|
||||
import { getUuid } from './client'
|
||||
import type { SessionEvent } from '../types'
|
||||
|
||||
let currentEventSource: EventSource | null = null;
|
||||
let currentEventSource: EventSource | null = null
|
||||
|
||||
export function connectSSE(
|
||||
sessionId: string,
|
||||
onEvent: (event: SessionEvent) => void,
|
||||
fromSeqNum = 0,
|
||||
): void {
|
||||
disconnectSSE();
|
||||
disconnectSSE()
|
||||
|
||||
const uuid = getUuid();
|
||||
const url = `/web/sessions/${sessionId}/events?uuid=${encodeURIComponent(uuid)}`;
|
||||
const es = new EventSource(url);
|
||||
currentEventSource = es;
|
||||
const uuid = getUuid()
|
||||
const url = `/web/sessions/${sessionId}/events?uuid=${encodeURIComponent(uuid)}`
|
||||
const es = new EventSource(url)
|
||||
currentEventSource = es
|
||||
|
||||
let lastSeenSeq = fromSeqNum;
|
||||
let lastSeenSeq = fromSeqNum
|
||||
|
||||
es.addEventListener("message", (e: MessageEvent) => {
|
||||
es.addEventListener('message', (e: MessageEvent) => {
|
||||
try {
|
||||
const data = JSON.parse(e.data) as SessionEvent;
|
||||
if (data.seqNum !== undefined && data.seqNum <= lastSeenSeq) return;
|
||||
if (data.seqNum !== undefined) lastSeenSeq = data.seqNum;
|
||||
onEvent(data);
|
||||
const data = JSON.parse(e.data) as SessionEvent
|
||||
if (data.seqNum !== undefined && data.seqNum <= lastSeenSeq) return
|
||||
if (data.seqNum !== undefined) lastSeenSeq = data.seqNum
|
||||
onEvent(data)
|
||||
} catch {
|
||||
// ignore parse errors
|
||||
}
|
||||
});
|
||||
})
|
||||
|
||||
es.addEventListener("error", () => {
|
||||
es.addEventListener('error', () => {
|
||||
// EventSource auto-reconnects
|
||||
});
|
||||
})
|
||||
}
|
||||
|
||||
export function disconnectSSE(): void {
|
||||
if (currentEventSource) {
|
||||
currentEventSource.close();
|
||||
currentEventSource = null;
|
||||
currentEventSource.close()
|
||||
currentEventSource = null
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { useState, useEffect, useRef } from "react";
|
||||
import { ACPClient, DisconnectRequestedError } from "../acp/client";
|
||||
import type { ConnectionState } from "../acp/types";
|
||||
import { ACPMain } from "../../components/ACPMain";
|
||||
import { useState, useEffect, useRef } from 'react';
|
||||
import { ACPClient, DisconnectRequestedError } from '../acp/client';
|
||||
import type { ConnectionState } from '../acp/types';
|
||||
import { ACPMain } from '../../components/ACPMain';
|
||||
|
||||
interface ACPDirectViewProps {
|
||||
url: string;
|
||||
@@ -11,7 +11,7 @@ interface ACPDirectViewProps {
|
||||
|
||||
export function ACPDirectView({ url, token, onBack }: ACPDirectViewProps) {
|
||||
const [client, setClient] = useState<ACPClient | null>(null);
|
||||
const [connectionState, setConnectionState] = useState<ConnectionState>("disconnected");
|
||||
const [connectionState, setConnectionState] = useState<ConnectionState>('disconnected');
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const clientRef = useRef<ACPClient | null>(null);
|
||||
|
||||
@@ -26,35 +26,32 @@ export function ACPDirectView({ url, token, onBack }: ACPDirectViewProps) {
|
||||
clientRef.current = acpClient;
|
||||
setClient(acpClient);
|
||||
|
||||
acpClient.connect().catch((e) => {
|
||||
acpClient.connect().catch(e => {
|
||||
if (e instanceof DisconnectRequestedError) return;
|
||||
setError((e as Error).message);
|
||||
setConnectionState("error");
|
||||
setConnectionState('error');
|
||||
});
|
||||
|
||||
return () => {
|
||||
acpClient.disconnect();
|
||||
clientRef.current = null;
|
||||
setClient(null);
|
||||
setConnectionState("disconnected");
|
||||
setConnectionState('disconnected');
|
||||
};
|
||||
}, [url, token]);
|
||||
|
||||
return (
|
||||
<div className="flex flex-1 flex-col overflow-hidden">
|
||||
{error && connectionState === "error" && (
|
||||
{error && connectionState === 'error' && (
|
||||
<div className="px-4 py-2 bg-status-error/10 text-status-error text-sm border-b">
|
||||
{error}
|
||||
<button
|
||||
onClick={onBack}
|
||||
className="ml-3 underline hover:no-underline"
|
||||
>
|
||||
<button onClick={onBack} className="ml-3 underline hover:no-underline">
|
||||
Back to Dashboard
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{connectionState === "connecting" && (
|
||||
{connectionState === 'connecting' && (
|
||||
<div className="flex-1 flex items-center justify-center">
|
||||
<div className="text-center">
|
||||
<div className="animate-spin h-8 w-8 border-2 border-brand border-t-transparent rounded-full mx-auto mb-3" />
|
||||
@@ -63,7 +60,7 @@ export function ACPDirectView({ url, token, onBack }: ACPDirectViewProps) {
|
||||
</div>
|
||||
)}
|
||||
|
||||
{connectionState === "error" && !client && (
|
||||
{connectionState === 'error' && !client && (
|
||||
<div className="flex-1 flex items-center justify-center">
|
||||
<div className="text-center">
|
||||
<p className="font-medium mb-1">Connection Failed</p>
|
||||
@@ -78,9 +75,7 @@ export function ACPDirectView({ url, token, onBack }: ACPDirectViewProps) {
|
||||
</div>
|
||||
)}
|
||||
|
||||
{client && connectionState === "connected" && (
|
||||
<ACPMain client={client} />
|
||||
)}
|
||||
{client && connectionState === 'connected' && <ACPMain client={client} />}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { useState, useRef, useEffect } from "react";
|
||||
import { cn, isClosedSessionStatus } from "../lib/utils";
|
||||
import { Square, SendHorizonal } from "lucide-react";
|
||||
import { useState, useRef, useEffect } from 'react';
|
||||
import { cn, isClosedSessionStatus } from '../lib/utils';
|
||||
import { Square, SendHorizonal } from 'lucide-react';
|
||||
|
||||
interface ControlBarProps {
|
||||
sessionId: string;
|
||||
@@ -10,22 +10,16 @@ interface ControlBarProps {
|
||||
onInterrupt: () => Promise<void>;
|
||||
}
|
||||
|
||||
export function ControlBar({
|
||||
sessionId,
|
||||
sessionStatus,
|
||||
activityMode,
|
||||
onSend,
|
||||
onInterrupt,
|
||||
}: ControlBarProps) {
|
||||
const [text, setText] = useState("");
|
||||
export function ControlBar({ sessionId, sessionStatus, activityMode, onSend, onInterrupt }: ControlBarProps) {
|
||||
const [text, setText] = useState('');
|
||||
const inputRef = useRef<HTMLInputElement>(null);
|
||||
const closed = isClosedSessionStatus(sessionStatus);
|
||||
const working = activityMode === "working";
|
||||
const working = activityMode === 'working';
|
||||
|
||||
const handleSend = async () => {
|
||||
const trimmed = text.trim();
|
||||
if (!trimmed || closed) return;
|
||||
setText("");
|
||||
setText('');
|
||||
try {
|
||||
await onSend(trimmed);
|
||||
} catch {
|
||||
@@ -34,7 +28,7 @@ export function ControlBar({
|
||||
};
|
||||
|
||||
const handleKeyDown = (e: React.KeyboardEvent) => {
|
||||
if (e.key === "Enter" && !e.shiftKey && !e.nativeEvent?.isComposing) {
|
||||
if (e.key === 'Enter' && !e.shiftKey && !e.nativeEvent?.isComposing) {
|
||||
e.preventDefault();
|
||||
handleSend();
|
||||
}
|
||||
@@ -51,9 +45,9 @@ export function ControlBar({
|
||||
ref={inputRef}
|
||||
type="text"
|
||||
value={text}
|
||||
onChange={(e) => setText(e.target.value)}
|
||||
onChange={e => setText(e.target.value)}
|
||||
onKeyDown={handleKeyDown}
|
||||
placeholder={closed ? "Session is closed" : "Type a message..."}
|
||||
placeholder={closed ? 'Session is closed' : 'Type a message...'}
|
||||
disabled={closed}
|
||||
className="flex-1 rounded-lg border border-border bg-surface-2 px-4 py-2.5 text-sm text-text-primary placeholder:text-text-muted focus:border-brand focus:outline-none focus:ring-1 focus:ring-brand/20 disabled:opacity-50 transition-colors"
|
||||
/>
|
||||
@@ -61,14 +55,14 @@ export function ControlBar({
|
||||
onClick={working ? onInterrupt : handleSend}
|
||||
disabled={closed}
|
||||
className={cn(
|
||||
"flex h-10 w-10 items-center justify-center rounded-lg transition-colors",
|
||||
'flex h-10 w-10 items-center justify-center rounded-lg transition-colors',
|
||||
working
|
||||
? "bg-status-error/20 text-status-error hover:bg-status-error/30"
|
||||
: "bg-brand text-white hover:bg-brand-light",
|
||||
closed && "opacity-50 cursor-not-allowed",
|
||||
? 'bg-status-error/20 text-status-error hover:bg-status-error/30'
|
||||
: 'bg-brand text-white hover:bg-brand-light',
|
||||
closed && 'opacity-50 cursor-not-allowed',
|
||||
)}
|
||||
aria-label={working ? "Stop" : "Send"}
|
||||
title={closed ? "Session is closed" : working ? "Stop" : "Send"}
|
||||
aria-label={working ? 'Stop' : 'Send'}
|
||||
title={closed ? 'Session is closed' : working ? 'Stop' : 'Send'}
|
||||
>
|
||||
{working ? (
|
||||
<Square className="h-4.5 w-4.5 fill-current" />
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import type { Environment } from "../types";
|
||||
import { StatusBadge } from "./Navbar";
|
||||
import { esc, formatTime } from "../lib/utils";
|
||||
import type { Environment } from '../types';
|
||||
import { StatusBadge } from './Navbar';
|
||||
import { esc, formatTime } from '../lib/utils';
|
||||
|
||||
interface EnvironmentListProps {
|
||||
environments: Environment[];
|
||||
@@ -18,10 +18,10 @@ export function EnvironmentList({ environments, onSelectEnvironment }: Environme
|
||||
|
||||
return (
|
||||
<div className="space-y-2">
|
||||
{environments.map((env) => {
|
||||
const isAcp = env.worker_type === "acp";
|
||||
const typeLabel = isAcp ? "ACP Agent" : "Claude Code";
|
||||
const typeColor = isAcp ? "bg-brand/15 text-brand" : "bg-status-running/15 text-status-running";
|
||||
{environments.map(env => {
|
||||
const isAcp = env.worker_type === 'acp';
|
||||
const typeLabel = isAcp ? 'ACP Agent' : 'Claude Code';
|
||||
const typeColor = isAcp ? 'bg-brand/15 text-brand' : 'bg-status-running/15 text-status-running';
|
||||
|
||||
return (
|
||||
<button
|
||||
@@ -29,26 +29,20 @@ export function EnvironmentList({ environments, onSelectEnvironment }: Environme
|
||||
type="button"
|
||||
onClick={() => onSelectEnvironment?.(env)}
|
||||
disabled={isAcp}
|
||||
className={`flex w-full items-center justify-between rounded-xl border border-border bg-surface-1 px-4 py-3 text-left transition-colors ${isAcp ? "cursor-default opacity-80" : "hover:border-border-light cursor-pointer"}`}
|
||||
className={`flex w-full items-center justify-between rounded-xl border border-border bg-surface-1 px-4 py-3 text-left transition-colors ${isAcp ? 'cursor-default opacity-80' : 'hover:border-border-light cursor-pointer'}`}
|
||||
>
|
||||
<div className="flex items-center gap-3">
|
||||
<div>
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="font-medium text-text-primary">
|
||||
{env.machine_name || env.id}
|
||||
</span>
|
||||
<span className={`rounded-full px-2 py-0.5 text-xs font-medium ${typeColor}`}>
|
||||
{typeLabel}
|
||||
</span>
|
||||
<span className="font-medium text-text-primary">{env.machine_name || env.id}</span>
|
||||
<span className={`rounded-full px-2 py-0.5 text-xs font-medium ${typeColor}`}>{typeLabel}</span>
|
||||
</div>
|
||||
<div className="text-sm text-text-muted">{env.directory || ""}</div>
|
||||
<div className="text-sm text-text-muted">{env.directory || ''}</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="text-right">
|
||||
<StatusBadge status={env.status} />
|
||||
<div className="mt-1 text-xs text-text-muted">
|
||||
{env.branch || ""}
|
||||
</div>
|
||||
<div className="mt-1 text-xs text-text-muted">{env.branch || ''}</div>
|
||||
</div>
|
||||
</button>
|
||||
);
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { useState, useEffect, useRef } from "react";
|
||||
import type { SessionEvent, EventPayload } from "../types";
|
||||
import { esc, truncate, cn, extractEventText, isConversationClearedStatus } from "../lib/utils";
|
||||
import { useState, useEffect, useRef } from 'react';
|
||||
import type { SessionEvent, EventPayload } from '../types';
|
||||
import { esc, truncate, cn, extractEventText, isConversationClearedStatus } from '../lib/utils';
|
||||
|
||||
// ============================================================
|
||||
// Tool Trace State
|
||||
@@ -8,9 +8,9 @@ import { esc, truncate, cn, extractEventText, isConversationClearedStatus } from
|
||||
|
||||
interface TraceHost {
|
||||
id: string;
|
||||
kind: "assistant" | "orphan";
|
||||
kind: 'assistant' | 'orphan';
|
||||
assistantContent: string;
|
||||
entryKinds: ("use" | "result")[];
|
||||
entryKinds: ('use' | 'result')[];
|
||||
}
|
||||
|
||||
interface ToolTraceState {
|
||||
@@ -26,7 +26,7 @@ function createTraceState(): ToolTraceState {
|
||||
function addAssistantHost(state: ToolTraceState, content: string): { state: ToolTraceState; host: TraceHost } {
|
||||
const host: TraceHost = {
|
||||
id: `trace-${state.nextHostId}`,
|
||||
kind: "assistant",
|
||||
kind: 'assistant',
|
||||
assistantContent: content,
|
||||
entryKinds: [],
|
||||
};
|
||||
@@ -45,26 +45,29 @@ function clearActiveHost(state: ToolTraceState): ToolTraceState {
|
||||
return { ...state, activeHostId: null };
|
||||
}
|
||||
|
||||
function addTraceEntry(state: ToolTraceState, entryKind: "use" | "result"): {
|
||||
function addTraceEntry(
|
||||
state: ToolTraceState,
|
||||
entryKind: 'use' | 'result',
|
||||
): {
|
||||
state: ToolTraceState;
|
||||
host: TraceHost;
|
||||
createdHost: TraceHost | null;
|
||||
} {
|
||||
let host = state.hosts.find((h) => h.id === state.activeHostId);
|
||||
let host = state.hosts.find(h => h.id === state.activeHostId);
|
||||
let createdHost: TraceHost | null = null;
|
||||
|
||||
if (!host) {
|
||||
createdHost = {
|
||||
id: `trace-${state.nextHostId}`,
|
||||
kind: "orphan",
|
||||
assistantContent: "",
|
||||
kind: 'orphan',
|
||||
assistantContent: '',
|
||||
entryKinds: [],
|
||||
};
|
||||
host = createdHost;
|
||||
}
|
||||
|
||||
const updatedHost = { ...host, entryKinds: [...host.entryKinds, entryKind] };
|
||||
const newHosts = state.hosts.map((h) => (h.id === updatedHost.id ? updatedHost : h));
|
||||
const newHosts = state.hosts.map(h => (h.id === updatedHost.id ? updatedHost : h));
|
||||
if (createdHost) newHosts.push(createdHost);
|
||||
|
||||
return {
|
||||
@@ -83,12 +86,12 @@ function addTraceEntry(state: ToolTraceState, entryKind: "use" | "result"): {
|
||||
// ============================================================
|
||||
|
||||
interface UserMessage {
|
||||
kind: "user";
|
||||
kind: 'user';
|
||||
content: string;
|
||||
}
|
||||
|
||||
interface AssistantMessage {
|
||||
kind: "assistant";
|
||||
kind: 'assistant';
|
||||
content: string;
|
||||
traceEntries: TraceEntry[];
|
||||
traceExpanded: boolean;
|
||||
@@ -96,7 +99,7 @@ interface AssistantMessage {
|
||||
}
|
||||
|
||||
interface TraceEntry {
|
||||
entryKind: "use" | "result";
|
||||
entryKind: 'use' | 'result';
|
||||
toolName?: string;
|
||||
toolInput?: unknown;
|
||||
content?: string;
|
||||
@@ -105,12 +108,12 @@ interface TraceEntry {
|
||||
}
|
||||
|
||||
interface SystemMessage {
|
||||
kind: "system";
|
||||
kind: 'system';
|
||||
content: string;
|
||||
}
|
||||
|
||||
interface PermissionMessage {
|
||||
kind: "permission";
|
||||
kind: 'permission';
|
||||
requestId: string;
|
||||
toolName: string;
|
||||
toolInput: unknown;
|
||||
@@ -118,21 +121,21 @@ interface PermissionMessage {
|
||||
}
|
||||
|
||||
interface AskUserMessage {
|
||||
kind: "ask_user";
|
||||
kind: 'ask_user';
|
||||
requestId: string;
|
||||
questions: import("../types").Question[];
|
||||
questions: import('../types').Question[];
|
||||
description: string;
|
||||
}
|
||||
|
||||
interface PlanMessage {
|
||||
kind: "plan";
|
||||
kind: 'plan';
|
||||
requestId: string;
|
||||
planContent: string;
|
||||
description: string;
|
||||
}
|
||||
|
||||
interface LoadingMessage {
|
||||
kind: "loading";
|
||||
kind: 'loading';
|
||||
verb: string;
|
||||
startTime: number;
|
||||
}
|
||||
@@ -150,15 +153,40 @@ type DisplayMessage =
|
||||
// Spinner
|
||||
// ============================================================
|
||||
|
||||
const SPINNER_FRAMES = ["·", "✢", "✱", "✶", "✻", "✽"];
|
||||
const SPINNER_FRAMES = ['·', '✢', '✱', '✶', '✻', '✽'];
|
||||
const SPINNER_CYCLE = [...SPINNER_FRAMES, ...SPINNER_FRAMES.slice().reverse()];
|
||||
|
||||
const SPINNER_VERBS = [
|
||||
"Accomplishing", "Baking", "Calculating", "Clauding", "Cogitating", "Computing",
|
||||
"Considering", "Contemplating", "Cooking", "Crafting", "Creating", "Crunching",
|
||||
"Deliberating", "Doing", "Effecting", "Generating", "Hatching", "Ideating",
|
||||
"Imagining", "Inferring", "Manifesting", "Mulling", "Pondering", "Processing",
|
||||
"Ruminating", "Simmering", "Synthesizing", "Thinking", "Tinkering", "Working",
|
||||
'Accomplishing',
|
||||
'Baking',
|
||||
'Calculating',
|
||||
'Clauding',
|
||||
'Cogitating',
|
||||
'Computing',
|
||||
'Considering',
|
||||
'Contemplating',
|
||||
'Cooking',
|
||||
'Crafting',
|
||||
'Creating',
|
||||
'Crunching',
|
||||
'Deliberating',
|
||||
'Doing',
|
||||
'Effecting',
|
||||
'Generating',
|
||||
'Hatching',
|
||||
'Ideating',
|
||||
'Imagining',
|
||||
'Inferring',
|
||||
'Manifesting',
|
||||
'Mulling',
|
||||
'Pondering',
|
||||
'Processing',
|
||||
'Ruminating',
|
||||
'Simmering',
|
||||
'Synthesizing',
|
||||
'Thinking',
|
||||
'Tinkering',
|
||||
'Working',
|
||||
];
|
||||
|
||||
// ============================================================
|
||||
@@ -169,7 +197,11 @@ interface EventStreamProps {
|
||||
messages: DisplayMessage[];
|
||||
onApprovePermission: (requestId: string) => void;
|
||||
onRejectPermission: (requestId: string) => void;
|
||||
onSubmitAnswers: (requestId: string, answers: Record<string, unknown>, questions: import("../types").Question[]) => void;
|
||||
onSubmitAnswers: (
|
||||
requestId: string,
|
||||
answers: Record<string, unknown>,
|
||||
questions: import('../types').Question[],
|
||||
) => void;
|
||||
onSubmitPlanResponse: (requestId: string, value: string, feedback?: string) => void;
|
||||
}
|
||||
|
||||
@@ -192,28 +224,42 @@ export function EventStream({
|
||||
<div ref={scrollRef} className="flex-1 overflow-y-auto px-4 py-4">
|
||||
<div className="mx-auto max-w-5xl space-y-3">
|
||||
{messages.map((msg, i) => (
|
||||
<MessageRow key={i} message={msg} {...{ onApprovePermission, onRejectPermission, onSubmitAnswers, onSubmitPlanResponse }} />
|
||||
<MessageRow
|
||||
key={i}
|
||||
message={msg}
|
||||
{...{ onApprovePermission, onRejectPermission, onSubmitAnswers, onSubmitPlanResponse }}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function MessageRow({ message, onApprovePermission, onRejectPermission, onSubmitAnswers, onSubmitPlanResponse }: {
|
||||
function MessageRow({
|
||||
message,
|
||||
onApprovePermission,
|
||||
onRejectPermission,
|
||||
onSubmitAnswers,
|
||||
onSubmitPlanResponse,
|
||||
}: {
|
||||
message: DisplayMessage;
|
||||
onApprovePermission: (requestId: string) => void;
|
||||
onRejectPermission: (requestId: string) => void;
|
||||
onSubmitAnswers: (requestId: string, answers: Record<string, unknown>, questions: import("../types").Question[]) => void;
|
||||
onSubmitAnswers: (
|
||||
requestId: string,
|
||||
answers: Record<string, unknown>,
|
||||
questions: import('../types').Question[],
|
||||
) => void;
|
||||
onSubmitPlanResponse: (requestId: string, value: string, feedback?: string) => void;
|
||||
}) {
|
||||
switch (message.kind) {
|
||||
case "user":
|
||||
case 'user':
|
||||
return <UserBubble content={message.content} />;
|
||||
case "assistant":
|
||||
case 'assistant':
|
||||
return <AssistantBubble content={message.content} traceEntries={message.traceEntries} />;
|
||||
case "system":
|
||||
case 'system':
|
||||
return <SystemBubble content={message.content} />;
|
||||
case "permission":
|
||||
case 'permission':
|
||||
return (
|
||||
<PermissionPrompt
|
||||
{...message}
|
||||
@@ -221,22 +267,22 @@ function MessageRow({ message, onApprovePermission, onRejectPermission, onSubmit
|
||||
onReject={() => onRejectPermission(message.requestId)}
|
||||
/>
|
||||
);
|
||||
case "ask_user":
|
||||
case 'ask_user':
|
||||
return (
|
||||
<AskUserPanel
|
||||
{...message}
|
||||
onSubmit={(answers) => onSubmitAnswers(message.requestId, answers, message.questions)}
|
||||
onSubmit={answers => onSubmitAnswers(message.requestId, answers, message.questions)}
|
||||
onSkip={() => onRejectPermission(message.requestId)}
|
||||
/>
|
||||
);
|
||||
case "plan":
|
||||
case 'plan':
|
||||
return (
|
||||
<PlanPanel
|
||||
{...message}
|
||||
onSubmit={(value, feedback) => onSubmitPlanResponse(message.requestId, value, feedback)}
|
||||
/>
|
||||
);
|
||||
case "loading":
|
||||
case 'loading':
|
||||
return <LoadingIndicator verb={message.verb} />;
|
||||
default:
|
||||
return null;
|
||||
@@ -266,7 +312,7 @@ function formatAssistantContent(content: string): string {
|
||||
// Inline code
|
||||
html = html.replace(/`([^`]+)`/g, '<code class="rounded bg-tool-card px-1.5 py-0.5 font-mono text-xs">$1</code>');
|
||||
// Bold
|
||||
html = html.replace(/\*\*([^*]+)\*\*/g, "<strong>$1</strong>");
|
||||
html = html.replace(/\*\*([^*]+)\*\*/g, '<strong>$1</strong>');
|
||||
return html;
|
||||
}
|
||||
|
||||
@@ -279,6 +325,7 @@ function AssistantBubble({ content, traceEntries }: { content: string; traceEntr
|
||||
{content && (
|
||||
<div
|
||||
className="rounded-2xl rounded-bl-md bg-surface-2 px-4 py-2.5 text-sm text-text-primary"
|
||||
// biome-ignore lint/security/noDangerouslySetInnerHtml: content is sanitized by formatAssistantContent
|
||||
dangerouslySetInnerHTML={{ __html: formatAssistantContent(content) }}
|
||||
/>
|
||||
)}
|
||||
@@ -288,8 +335,10 @@ function AssistantBubble({ content, traceEntries }: { content: string; traceEntr
|
||||
onClick={() => setExpanded(!expanded)}
|
||||
className="flex items-center gap-1.5 text-xs text-text-muted hover:text-text-secondary transition-colors"
|
||||
>
|
||||
<span className={cn("transition-transform", expanded && "rotate-90")}>›</span>
|
||||
<span>{traceEntries.length} tool {traceEntries.length === 1 ? "call" : "calls"}</span>
|
||||
<span className={cn('transition-transform', expanded && 'rotate-90')}>›</span>
|
||||
<span>
|
||||
{traceEntries.length} tool {traceEntries.length === 1 ? 'call' : 'calls'}
|
||||
</span>
|
||||
</button>
|
||||
{expanded && (
|
||||
<div className="mt-1 space-y-1 pl-2">
|
||||
@@ -308,8 +357,8 @@ function AssistantBubble({ content, traceEntries }: { content: string; traceEntr
|
||||
function ToolCard({ entry }: { entry: TraceEntry }) {
|
||||
const [expanded, setExpanded] = useState(false);
|
||||
|
||||
if (entry.entryKind === "use") {
|
||||
const inputStr = typeof entry.toolInput === "string" ? entry.toolInput : JSON.stringify(entry.toolInput, null, 2);
|
||||
if (entry.entryKind === 'use') {
|
||||
const inputStr = typeof entry.toolInput === 'string' ? entry.toolInput : JSON.stringify(entry.toolInput, null, 2);
|
||||
return (
|
||||
<div
|
||||
className="cursor-pointer rounded-lg border border-border bg-tool-card"
|
||||
@@ -317,7 +366,7 @@ function ToolCard({ entry }: { entry: TraceEntry }) {
|
||||
>
|
||||
<div className="flex items-center gap-2 px-3 py-2 text-xs">
|
||||
<span className="text-brand">▶</span>
|
||||
<span className="font-medium text-text-primary">{entry.toolName || "tool"}</span>
|
||||
<span className="font-medium text-text-primary">{entry.toolName || 'tool'}</span>
|
||||
</div>
|
||||
{expanded && (
|
||||
<pre className="border-t border-border px-3 py-2 text-xs text-text-secondary overflow-x-auto">
|
||||
@@ -328,22 +377,18 @@ function ToolCard({ entry }: { entry: TraceEntry }) {
|
||||
);
|
||||
}
|
||||
|
||||
const contentStr = typeof entry.output === "string" ? entry.output : JSON.stringify(entry.output, null, 2);
|
||||
const contentStr = typeof entry.output === 'string' ? entry.output : JSON.stringify(entry.output, null, 2);
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
"cursor-pointer rounded-lg border bg-tool-card",
|
||||
entry.isError ? "border-status-error/30" : "border-border",
|
||||
'cursor-pointer rounded-lg border bg-tool-card',
|
||||
entry.isError ? 'border-status-error/30' : 'border-border',
|
||||
)}
|
||||
onClick={() => setExpanded(!expanded)}
|
||||
>
|
||||
<div className="flex items-center gap-2 px-3 py-2 text-xs">
|
||||
<span className={entry.isError ? "text-status-error" : "text-status-active"}>
|
||||
{entry.isError ? "✕" : "✓"}
|
||||
</span>
|
||||
<span className="font-medium text-text-primary">
|
||||
{entry.isError ? "Error" : "Result"}
|
||||
</span>
|
||||
<span className={entry.isError ? 'text-status-error' : 'text-status-active'}>{entry.isError ? '✕' : '✓'}</span>
|
||||
<span className="font-medium text-text-primary">{entry.isError ? 'Error' : 'Result'}</span>
|
||||
</div>
|
||||
{expanded && (
|
||||
<pre className="border-t border-border px-3 py-2 text-xs text-text-secondary overflow-x-auto">
|
||||
@@ -357,9 +402,7 @@ function ToolCard({ entry }: { entry: TraceEntry }) {
|
||||
function SystemBubble({ content }: { content: string }) {
|
||||
return (
|
||||
<div className="flex justify-center">
|
||||
<div className="rounded-full bg-surface-2 px-4 py-1.5 text-xs text-text-muted">
|
||||
{esc(content)}
|
||||
</div>
|
||||
<div className="rounded-full bg-surface-2 px-4 py-1.5 text-xs text-text-muted">{esc(content)}</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -379,14 +422,14 @@ function PermissionPrompt({
|
||||
onApprove: () => void;
|
||||
onReject: () => void;
|
||||
}) {
|
||||
const inputStr = typeof toolInput === "string" ? toolInput : JSON.stringify(toolInput, null, 2);
|
||||
const inputStr = typeof toolInput === 'string' ? toolInput : JSON.stringify(toolInput, null, 2);
|
||||
|
||||
return (
|
||||
<div className="rounded-xl border border-status-warning/30 bg-surface-1 p-4">
|
||||
<div className="mb-2 text-sm font-semibold text-status-warning">Permission Request</div>
|
||||
{description && <div className="mb-2 text-sm text-text-secondary">{esc(description)}</div>}
|
||||
<div className="mb-2 font-mono text-xs font-bold text-text-primary">{esc(toolName)}</div>
|
||||
{toolName !== "AskUserQuestion" && (
|
||||
{toolName !== 'AskUserQuestion' && (
|
||||
<pre className="mb-3 max-h-40 overflow-auto rounded-lg bg-tool-card p-2 text-xs text-text-secondary">
|
||||
{truncate(inputStr, 500)}
|
||||
</pre>
|
||||
@@ -416,7 +459,7 @@ function AskUserPanel({
|
||||
onSkip,
|
||||
}: {
|
||||
requestId: string;
|
||||
questions: import("../types").Question[];
|
||||
questions: import('../types').Question[];
|
||||
description: string;
|
||||
onSubmit: (answers: Record<string, unknown>) => void;
|
||||
onSkip: () => void;
|
||||
@@ -427,7 +470,7 @@ function AskUserPanel({
|
||||
const handleSelect = (qIdx: number, oIdx: number, multiSelect: boolean) => {
|
||||
if (multiSelect) {
|
||||
const current = (answers[qIdx] as number[]) || [];
|
||||
const next = current.includes(oIdx) ? current.filter((i) => i !== oIdx) : [...current, oIdx];
|
||||
const next = current.includes(oIdx) ? current.filter(i => i !== oIdx) : [...current, oIdx];
|
||||
setAnswers({ ...answers, [qIdx]: next });
|
||||
} else {
|
||||
setAnswers({ ...answers, [qIdx]: oIdx });
|
||||
@@ -438,7 +481,7 @@ function AskUserPanel({
|
||||
const text = otherTexts[qIdx]?.trim();
|
||||
if (!text) return;
|
||||
setAnswers({ ...answers, [qIdx]: text });
|
||||
setOtherTexts({ ...otherTexts, [qIdx]: "" });
|
||||
setOtherTexts({ ...otherTexts, [qIdx]: '' });
|
||||
};
|
||||
|
||||
const handleSubmit = () => {
|
||||
@@ -446,10 +489,10 @@ function AskUserPanel({
|
||||
for (const [qIdx, val] of Object.entries(answers)) {
|
||||
const q = questions[parseInt(qIdx, 10)];
|
||||
if (!q) continue;
|
||||
if (typeof val === "number") {
|
||||
if (typeof val === 'number') {
|
||||
mapped[qIdx] = q.options?.[val]?.label || String(val);
|
||||
} else if (Array.isArray(val)) {
|
||||
mapped[qIdx] = val.map((i) => q.options?.[i]?.label || String(i));
|
||||
mapped[qIdx] = val.map(i => q.options?.[i]?.label || String(i));
|
||||
} else {
|
||||
mapped[qIdx] = val;
|
||||
}
|
||||
@@ -465,22 +508,20 @@ function AskUserPanel({
|
||||
return (
|
||||
<div className="rounded-xl border border-brand/30 bg-surface-1 p-4">
|
||||
<div className="mb-3 text-sm font-semibold text-text-primary">
|
||||
{esc(description || q.question || "Question")}
|
||||
{esc(description || q.question || 'Question')}
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
{(q.options || []).map((opt, j) => {
|
||||
const isSelected = multiSelect
|
||||
? ((answers[0] as number[]) || []).includes(j)
|
||||
: selectedIdx === j;
|
||||
const isSelected = multiSelect ? ((answers[0] as number[]) || []).includes(j) : selectedIdx === j;
|
||||
return (
|
||||
<button
|
||||
key={j}
|
||||
onClick={() => handleSelect(0, j, multiSelect)}
|
||||
className={cn(
|
||||
"w-full rounded-lg border px-4 py-2.5 text-left text-sm transition-colors",
|
||||
'w-full rounded-lg border px-4 py-2.5 text-left text-sm transition-colors',
|
||||
isSelected
|
||||
? "border-brand bg-brand/10 text-text-primary"
|
||||
: "border-border bg-surface-2 text-text-secondary hover:border-border-light",
|
||||
? 'border-brand bg-brand/10 text-text-primary'
|
||||
: 'border-border bg-surface-2 text-text-secondary hover:border-border-light',
|
||||
)}
|
||||
>
|
||||
<div className="font-medium">{esc(opt.label)}</div>
|
||||
@@ -491,11 +532,11 @@ function AskUserPanel({
|
||||
<div className="flex gap-2">
|
||||
<input
|
||||
type="text"
|
||||
value={otherTexts[0] || ""}
|
||||
onChange={(e) => setOtherTexts({ ...otherTexts, [0]: e.target.value })}
|
||||
value={otherTexts[0] || ''}
|
||||
onChange={e => setOtherTexts({ ...otherTexts, [0]: e.target.value })}
|
||||
placeholder="Other..."
|
||||
className="flex-1 rounded-lg border border-border bg-surface-2 px-3 py-2 text-sm text-text-primary placeholder:text-text-muted focus:border-brand focus:outline-none"
|
||||
onKeyDown={(e) => e.key === "Enter" && handleOtherSubmit(0)}
|
||||
onKeyDown={e => e.key === 'Enter' && handleOtherSubmit(0)}
|
||||
/>
|
||||
<button
|
||||
onClick={() => handleOtherSubmit(0)}
|
||||
@@ -528,17 +569,15 @@ function AskUserPanel({
|
||||
|
||||
return (
|
||||
<div className="rounded-xl border border-brand/30 bg-surface-1 p-4">
|
||||
<div className="mb-3 text-sm font-semibold text-text-primary">{esc(description || "Questions")}</div>
|
||||
<div className="mb-3 text-sm font-semibold text-text-primary">{esc(description || 'Questions')}</div>
|
||||
<div className="mb-3 flex gap-1 overflow-x-auto">
|
||||
{questions.map((q, i) => (
|
||||
<button
|
||||
key={i}
|
||||
onClick={() => setActiveTab(i)}
|
||||
className={cn(
|
||||
"rounded-md px-3 py-1.5 text-xs whitespace-nowrap transition-colors",
|
||||
activeTab === i
|
||||
? "bg-brand/20 text-brand"
|
||||
: "text-text-muted hover:bg-surface-2",
|
||||
'rounded-md px-3 py-1.5 text-xs whitespace-nowrap transition-colors',
|
||||
activeTab === i ? 'bg-brand/20 text-brand' : 'text-text-muted hover:bg-surface-2',
|
||||
)}
|
||||
>
|
||||
{q.header || `Q${i + 1}`}
|
||||
@@ -557,7 +596,9 @@ function AskUserPanel({
|
||||
/>
|
||||
)}
|
||||
<div className="mt-4 flex items-center justify-between">
|
||||
<span className="text-xs text-text-muted">{activeTab + 1} / {questions.length}</span>
|
||||
<span className="text-xs text-text-muted">
|
||||
{activeTab + 1} / {questions.length}
|
||||
</span>
|
||||
<div className="flex gap-2">
|
||||
<button
|
||||
onClick={handleSubmit}
|
||||
@@ -586,7 +627,7 @@ function QuestionTab({
|
||||
onOtherTextChange,
|
||||
onOtherSubmit,
|
||||
}: {
|
||||
question: import("../types").Question;
|
||||
question: import('../types').Question;
|
||||
qIdx: number;
|
||||
answers: Record<string, unknown>;
|
||||
otherTexts: Record<string, string>;
|
||||
@@ -601,18 +642,16 @@ function QuestionTab({
|
||||
<div className="mb-2 text-sm text-text-secondary">{esc(question.question)}</div>
|
||||
<div className="space-y-2">
|
||||
{(question.options || []).map((opt, j) => {
|
||||
const isSelected = multiSelect
|
||||
? ((answers[qIdx] as number[]) || []).includes(j)
|
||||
: answers[qIdx] === j;
|
||||
const isSelected = multiSelect ? ((answers[qIdx] as number[]) || []).includes(j) : answers[qIdx] === j;
|
||||
return (
|
||||
<button
|
||||
key={j}
|
||||
onClick={() => onSelect(qIdx, j, multiSelect)}
|
||||
className={cn(
|
||||
"w-full rounded-lg border px-4 py-2.5 text-left text-sm transition-colors",
|
||||
'w-full rounded-lg border px-4 py-2.5 text-left text-sm transition-colors',
|
||||
isSelected
|
||||
? "border-brand bg-brand/10 text-text-primary"
|
||||
: "border-border bg-surface-2 text-text-secondary hover:border-border-light",
|
||||
? 'border-brand bg-brand/10 text-text-primary'
|
||||
: 'border-border bg-surface-2 text-text-secondary hover:border-border-light',
|
||||
)}
|
||||
>
|
||||
<div className="font-medium">{esc(opt.label)}</div>
|
||||
@@ -623,11 +662,11 @@ function QuestionTab({
|
||||
<div className="flex gap-2">
|
||||
<input
|
||||
type="text"
|
||||
value={otherTexts[qIdx] || ""}
|
||||
onChange={(e) => onOtherTextChange(qIdx, e.target.value)}
|
||||
value={otherTexts[qIdx] || ''}
|
||||
onChange={e => onOtherTextChange(qIdx, e.target.value)}
|
||||
placeholder="Other..."
|
||||
className="flex-1 rounded-lg border border-border bg-surface-2 px-3 py-2 text-sm text-text-primary placeholder:text-text-muted focus:border-brand focus:outline-none"
|
||||
onKeyDown={(e) => e.key === "Enter" && onOtherSubmit(qIdx)}
|
||||
onKeyDown={e => e.key === 'Enter' && onOtherSubmit(qIdx)}
|
||||
/>
|
||||
<button
|
||||
onClick={() => onOtherSubmit(qIdx)}
|
||||
@@ -652,58 +691,59 @@ function PlanPanel({
|
||||
onSubmit: (value: string, feedback?: string) => void;
|
||||
}) {
|
||||
const [selected, setSelected] = useState<string | null>(null);
|
||||
const [feedback, setFeedback] = useState("");
|
||||
const [feedback, setFeedback] = useState('');
|
||||
const isEmpty = !planContent || !planContent.trim();
|
||||
|
||||
const handleSubmit = () => {
|
||||
if (!selected) return;
|
||||
onSubmit(selected, selected === "no" ? feedback : undefined);
|
||||
onSubmit(selected, selected === 'no' ? feedback : undefined);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="rounded-xl border border-brand/30 bg-surface-1 p-4">
|
||||
<div className="mb-3 text-sm font-semibold text-text-primary">
|
||||
{isEmpty ? "Exit plan mode?" : "Ready to code?"}
|
||||
{isEmpty ? 'Exit plan mode?' : 'Ready to code?'}
|
||||
</div>
|
||||
{!isEmpty && (
|
||||
<div
|
||||
className="mb-4 max-h-64 overflow-auto rounded-lg bg-tool-card p-4 text-sm text-text-secondary prose prose-invert"
|
||||
// biome-ignore lint/security/noDangerouslySetInnerHtml: content is sanitized by formatPlanContent
|
||||
dangerouslySetInnerHTML={{ __html: formatPlanContent(planContent) }}
|
||||
/>
|
||||
)}
|
||||
<div className="space-y-2">
|
||||
{isEmpty ? (
|
||||
<>
|
||||
<PlanOption selected={selected === "yes-default"} onClick={() => setSelected("yes-default")} label="Yes" />
|
||||
<PlanOption selected={selected === "no"} onClick={() => setSelected("no")} label="No" />
|
||||
<PlanOption selected={selected === 'yes-default'} onClick={() => setSelected('yes-default')} label="Yes" />
|
||||
<PlanOption selected={selected === 'no'} onClick={() => setSelected('no')} label="No" />
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<PlanOption
|
||||
selected={selected === "yes-accept-edits"}
|
||||
onClick={() => setSelected("yes-accept-edits")}
|
||||
selected={selected === 'yes-accept-edits'}
|
||||
onClick={() => setSelected('yes-accept-edits')}
|
||||
label="Yes, auto-accept edits"
|
||||
desc="Approve plan and auto-accept file edits"
|
||||
/>
|
||||
<PlanOption
|
||||
selected={selected === "yes-default"}
|
||||
onClick={() => setSelected("yes-default")}
|
||||
selected={selected === 'yes-default'}
|
||||
onClick={() => setSelected('yes-default')}
|
||||
label="Yes, manually approve edits"
|
||||
desc="Approve plan but confirm each edit"
|
||||
/>
|
||||
<PlanOption
|
||||
selected={selected === "no"}
|
||||
onClick={() => setSelected("no")}
|
||||
selected={selected === 'no'}
|
||||
onClick={() => setSelected('no')}
|
||||
label="No, keep planning"
|
||||
desc="Provide feedback to refine the plan"
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
{selected === "no" && (
|
||||
{selected === 'no' && (
|
||||
<textarea
|
||||
value={feedback}
|
||||
onChange={(e) => setFeedback(e.target.value)}
|
||||
onChange={e => setFeedback(e.target.value)}
|
||||
placeholder="Tell Claude what to change..."
|
||||
className="mt-3 w-full rounded-lg border border-border bg-surface-2 px-3 py-2 text-sm text-text-primary placeholder:text-text-muted focus:border-brand focus:outline-none"
|
||||
rows={3}
|
||||
@@ -737,10 +777,10 @@ function PlanOption({
|
||||
<button
|
||||
onClick={onClick}
|
||||
className={cn(
|
||||
"w-full rounded-lg border px-4 py-2.5 text-left text-sm transition-colors",
|
||||
'w-full rounded-lg border px-4 py-2.5 text-left text-sm transition-colors',
|
||||
selected
|
||||
? "border-brand bg-brand/10 text-text-primary"
|
||||
: "border-border bg-surface-2 text-text-secondary hover:border-border-light",
|
||||
? 'border-brand bg-brand/10 text-text-primary'
|
||||
: 'border-border bg-surface-2 text-text-secondary hover:border-border-light',
|
||||
)}
|
||||
>
|
||||
<div className="font-medium">{label}</div>
|
||||
@@ -758,7 +798,7 @@ function formatPlanContent(content: string): string {
|
||||
// Inline code
|
||||
html = html.replace(/`([^`]+)`/g, '<code class="rounded bg-tool-card px-1.5 py-0.5 font-mono text-xs">$1</code>');
|
||||
// Bold
|
||||
html = html.replace(/\*\*([^*]+)\*\*/g, "<strong>$1</strong>");
|
||||
html = html.replace(/\*\*([^*]+)\*\*/g, '<strong>$1</strong>');
|
||||
return html;
|
||||
}
|
||||
|
||||
@@ -767,8 +807,8 @@ function LoadingIndicator({ verb }: { verb: string }) {
|
||||
const [elapsed, setElapsed] = useState(0);
|
||||
|
||||
useEffect(() => {
|
||||
const spinInterval = setInterval(() => setFrame((f) => (f + 1) % SPINNER_CYCLE.length), 120);
|
||||
const timerInterval = setInterval(() => setElapsed((e) => e + 1), 1000);
|
||||
const spinInterval = setInterval(() => setFrame(f => (f + 1) % SPINNER_CYCLE.length), 120);
|
||||
const timerInterval = setInterval(() => setElapsed(e => e + 1), 1000);
|
||||
return () => {
|
||||
clearInterval(spinInterval);
|
||||
clearInterval(timerInterval);
|
||||
@@ -788,7 +828,17 @@ function LoadingIndicator({ verb }: { verb: string }) {
|
||||
// Event Processing Hook
|
||||
// ============================================================
|
||||
|
||||
export { type DisplayMessage, type TraceEntry, type UserMessage, type AssistantMessage, type SystemMessage, type PermissionMessage, type AskUserMessage, type PlanMessage, type LoadingMessage };
|
||||
export type {
|
||||
DisplayMessage,
|
||||
TraceEntry,
|
||||
UserMessage,
|
||||
AssistantMessage,
|
||||
SystemMessage,
|
||||
PermissionMessage,
|
||||
AskUserMessage,
|
||||
PlanMessage,
|
||||
LoadingMessage,
|
||||
};
|
||||
|
||||
export function useEventProcessor() {
|
||||
const [messages, setMessages] = useState<DisplayMessage[]>([]);
|
||||
@@ -802,19 +852,19 @@ export function useEventProcessor() {
|
||||
};
|
||||
|
||||
const removeLoading = () => {
|
||||
setMessages((prev) => prev.filter((m) => m.kind !== "loading"));
|
||||
setMessages(prev => prev.filter(m => m.kind !== 'loading'));
|
||||
};
|
||||
|
||||
const showLoading = () => {
|
||||
removeLoading();
|
||||
const verb = SPINNER_VERBS[Math.floor(Math.random() * SPINNER_VERBS.length)];
|
||||
setMessages((prev) => [...prev, { kind: "loading", verb, startTime: Date.now() }]);
|
||||
setMessages(prev => [...prev, { kind: 'loading', verb, startTime: Date.now() }]);
|
||||
};
|
||||
|
||||
const processEvent = (event: SessionEvent, replay = false) => {
|
||||
const type = event.type;
|
||||
const payload = event.payload || ({} as EventPayload);
|
||||
const direction = event.direction || "inbound";
|
||||
const direction = event.direction || 'inbound';
|
||||
|
||||
// Skip bridge init noise
|
||||
const serialized = JSON.stringify(event);
|
||||
@@ -826,14 +876,14 @@ export function useEventProcessor() {
|
||||
}
|
||||
|
||||
switch (type) {
|
||||
case "user": {
|
||||
const toolResultBlocks = getEmbeddedToolBlocks(payload, "tool_result");
|
||||
case 'user': {
|
||||
const toolResultBlocks = getEmbeddedToolBlocks(payload, 'tool_result');
|
||||
if (toolResultBlocks.length > 0) {
|
||||
// Process tool results
|
||||
for (const block of toolResultBlocks) {
|
||||
addToolTraceEntry("result", {
|
||||
content: block.content as string || "",
|
||||
output: block.content as string || "",
|
||||
addToolTraceEntry('result', {
|
||||
content: (block.content as string) || '',
|
||||
output: (block.content as string) || '',
|
||||
is_error: !!block.is_error,
|
||||
});
|
||||
}
|
||||
@@ -847,25 +897,25 @@ export function useEventProcessor() {
|
||||
traceStateRef.current = clearActiveHost(traceStateRef.current);
|
||||
const text = extractEventText(payload as Record<string, unknown>);
|
||||
if (text) {
|
||||
setMessages((prev) => [...prev, { kind: "user", content: text }]);
|
||||
setMessages(prev => [...prev, { kind: 'user', content: text }]);
|
||||
if (!replay) showLoading();
|
||||
}
|
||||
break;
|
||||
}
|
||||
case "partial_assistant":
|
||||
case 'partial_assistant':
|
||||
return;
|
||||
case "assistant": {
|
||||
case 'assistant': {
|
||||
removeLoading();
|
||||
const text = extractEventText(payload as Record<string, unknown>);
|
||||
const toolUseBlocks = getEmbeddedToolBlocks(payload, "tool_use");
|
||||
const toolUseBlocks = getEmbeddedToolBlocks(payload, 'tool_use');
|
||||
|
||||
if (text && text.trim()) {
|
||||
const result = addAssistantHost(traceStateRef.current, text);
|
||||
traceStateRef.current = result.state;
|
||||
setMessages((prev) => [
|
||||
setMessages(prev => [
|
||||
...prev,
|
||||
{
|
||||
kind: "assistant",
|
||||
kind: 'assistant',
|
||||
content: text,
|
||||
traceEntries: [],
|
||||
traceExpanded: false,
|
||||
@@ -875,169 +925,172 @@ export function useEventProcessor() {
|
||||
}
|
||||
|
||||
for (const block of toolUseBlocks) {
|
||||
addToolTraceEntry("use", {
|
||||
tool_name: (block.name as string) || "tool",
|
||||
addToolTraceEntry('use', {
|
||||
tool_name: (block.name as string) || 'tool',
|
||||
tool_input: block.input,
|
||||
});
|
||||
}
|
||||
break;
|
||||
}
|
||||
case "task_state":
|
||||
case "automation_state":
|
||||
case 'task_state':
|
||||
case 'automation_state':
|
||||
return;
|
||||
case "result":
|
||||
case "result_success":
|
||||
case 'result':
|
||||
case 'result_success':
|
||||
removeLoading();
|
||||
return;
|
||||
case "tool_use":
|
||||
addToolTraceEntry("use", payload as Record<string, unknown> as { tool_name: string; tool_input: unknown });
|
||||
case 'tool_use':
|
||||
addToolTraceEntry('use', payload as Record<string, unknown> as { tool_name: string; tool_input: unknown });
|
||||
break;
|
||||
case "tool_result":
|
||||
addToolTraceEntry("result", payload as Record<string, unknown> as { content: string; output: string; is_error: boolean });
|
||||
case 'tool_result':
|
||||
addToolTraceEntry(
|
||||
'result',
|
||||
payload as Record<string, unknown> as { content: string; output: string; is_error: boolean },
|
||||
);
|
||||
break;
|
||||
case "control_request":
|
||||
case "permission_request": {
|
||||
case 'control_request':
|
||||
case 'permission_request': {
|
||||
const req = payload.request;
|
||||
if (req && req.subtype === "can_use_tool") {
|
||||
const toolName = req.tool_name || "unknown";
|
||||
if (req && req.subtype === 'can_use_tool') {
|
||||
const toolName = req.tool_name || 'unknown';
|
||||
const toolInput = req.input || req.tool_input || {};
|
||||
if (toolName === "AskUserQuestion") {
|
||||
setMessages((prev) => [
|
||||
if (toolName === 'AskUserQuestion') {
|
||||
setMessages(prev => [
|
||||
...prev,
|
||||
{
|
||||
kind: "ask_user",
|
||||
requestId: payload.request_id || event.id || "",
|
||||
questions: (toolInput as Record<string, unknown>).questions as import("../types").Question[] || [],
|
||||
description: req.description || "",
|
||||
kind: 'ask_user',
|
||||
requestId: payload.request_id || event.id || '',
|
||||
questions: ((toolInput as Record<string, unknown>).questions as import('../types').Question[]) || [],
|
||||
description: req.description || '',
|
||||
},
|
||||
]);
|
||||
} else if (toolName === "ExitPlanMode") {
|
||||
setMessages((prev) => [
|
||||
} else if (toolName === 'ExitPlanMode') {
|
||||
setMessages(prev => [
|
||||
...prev,
|
||||
{
|
||||
kind: "plan",
|
||||
requestId: payload.request_id || event.id || "",
|
||||
planContent: ((toolInput as Record<string, unknown>).plan as string) || "",
|
||||
description: req.description || "",
|
||||
kind: 'plan',
|
||||
requestId: payload.request_id || event.id || '',
|
||||
planContent: ((toolInput as Record<string, unknown>).plan as string) || '',
|
||||
description: req.description || '',
|
||||
},
|
||||
]);
|
||||
} else {
|
||||
setMessages((prev) => [
|
||||
setMessages(prev => [
|
||||
...prev,
|
||||
{
|
||||
kind: "permission",
|
||||
requestId: payload.request_id || event.id || "",
|
||||
kind: 'permission',
|
||||
requestId: payload.request_id || event.id || '',
|
||||
toolName,
|
||||
toolInput,
|
||||
description: req.description || "",
|
||||
description: req.description || '',
|
||||
},
|
||||
]);
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
case "control_response":
|
||||
case "permission_response":
|
||||
case 'control_response':
|
||||
case 'permission_response':
|
||||
return;
|
||||
case "status": {
|
||||
case 'status': {
|
||||
if (isConversationClearedStatus(payload as Record<string, unknown>)) {
|
||||
reset();
|
||||
return;
|
||||
}
|
||||
const rawMsg = payload.message;
|
||||
const msg = (typeof rawMsg === "string" ? rawMsg : "") || payload.content || "";
|
||||
const msg = (typeof rawMsg === 'string' ? rawMsg : '') || payload.content || '';
|
||||
if (/connecting|waiting|initializing|Remote Control/i.test(msg)) return;
|
||||
if (!msg.trim()) return;
|
||||
setMessages((prev) => [...prev, { kind: "system", content: msg }]);
|
||||
setMessages(prev => [...prev, { kind: 'system', content: msg }]);
|
||||
break;
|
||||
}
|
||||
case "error":
|
||||
case 'error':
|
||||
removeLoading();
|
||||
setMessages((prev) => [
|
||||
setMessages(prev => [
|
||||
...prev,
|
||||
{ kind: "system", content: `Error: ${(typeof payload.message === "string" ? payload.message : "") || payload.content || "Unknown error"}` },
|
||||
{
|
||||
kind: 'system',
|
||||
content: `Error: ${(typeof payload.message === 'string' ? payload.message : '') || payload.content || 'Unknown error'}`,
|
||||
},
|
||||
]);
|
||||
break;
|
||||
case "session_status":
|
||||
if (payload.status === "archived" || payload.status === "inactive") {
|
||||
case 'session_status':
|
||||
if (payload.status === 'archived' || payload.status === 'inactive') {
|
||||
removeLoading();
|
||||
setMessages((prev) => [...prev, { kind: "system", content: `Session ${payload.status}` }]);
|
||||
setMessages(prev => [...prev, { kind: 'system', content: `Session ${payload.status}` }]);
|
||||
}
|
||||
break;
|
||||
case "interrupt":
|
||||
case 'interrupt':
|
||||
removeLoading();
|
||||
setMessages((prev) => [...prev, { kind: "system", content: "Session interrupted" }]);
|
||||
setMessages(prev => [...prev, { kind: 'system', content: 'Session interrupted' }]);
|
||||
break;
|
||||
case "system":
|
||||
case 'system':
|
||||
return;
|
||||
default: {
|
||||
const raw = JSON.stringify(payload);
|
||||
if (/Remote Control connecting/i.test(raw)) return;
|
||||
setMessages((prev) => [...prev, { kind: "system", content: `${type}: ${truncate(raw, 200)}` }]);
|
||||
setMessages(prev => [...prev, { kind: 'system', content: `${type}: ${truncate(raw, 200)}` }]);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
function processReplayEvent(type: string, payload: EventPayload, direction: string, event: SessionEvent) {
|
||||
switch (type) {
|
||||
case "user": {
|
||||
case 'user': {
|
||||
const text = extractEventText(payload as Record<string, unknown>);
|
||||
if (text) {
|
||||
traceStateRef.current = clearActiveHost(traceStateRef.current);
|
||||
setMessages((prev) => [...prev, { kind: "user", content: text }]);
|
||||
setMessages(prev => [...prev, { kind: 'user', content: text }]);
|
||||
}
|
||||
break;
|
||||
}
|
||||
case "assistant": {
|
||||
case 'assistant': {
|
||||
const text = extractEventText(payload as Record<string, unknown>);
|
||||
if (text && text.trim()) {
|
||||
const result = addAssistantHost(traceStateRef.current, text);
|
||||
traceStateRef.current = result.state;
|
||||
setMessages((prev) => [
|
||||
setMessages(prev => [
|
||||
...prev,
|
||||
{ kind: "assistant", content: text, traceEntries: [], traceExpanded: false, traceId: result.host.id },
|
||||
{ kind: 'assistant', content: text, traceEntries: [], traceExpanded: false, traceId: result.host.id },
|
||||
]);
|
||||
}
|
||||
break;
|
||||
}
|
||||
case "error":
|
||||
setMessages((prev) => [...prev, { kind: "system", content: `Error: ${payload.message || "Unknown error"}` }]);
|
||||
case 'error':
|
||||
setMessages(prev => [...prev, { kind: 'system', content: `Error: ${payload.message || 'Unknown error'}` }]);
|
||||
break;
|
||||
case "session_status":
|
||||
if (payload.status === "archived" || payload.status === "inactive") {
|
||||
setMessages((prev) => [...prev, { kind: "system", content: `Session ${payload.status}` }]);
|
||||
case 'session_status':
|
||||
if (payload.status === 'archived' || payload.status === 'inactive') {
|
||||
setMessages(prev => [...prev, { kind: 'system', content: `Session ${payload.status}` }]);
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
function addToolTraceEntry(entryKind: "use" | "result", payload: Record<string, unknown>) {
|
||||
function addToolTraceEntry(entryKind: 'use' | 'result', payload: Record<string, unknown>) {
|
||||
const result = addTraceEntry(traceStateRef.current, entryKind);
|
||||
traceStateRef.current = result.state;
|
||||
|
||||
const entry: TraceEntry = entryKind === "use"
|
||||
? {
|
||||
entryKind: "use",
|
||||
toolName: (payload.tool_name as string) || (payload.name as string) || "tool",
|
||||
toolInput: payload.tool_input || payload.input,
|
||||
}
|
||||
: {
|
||||
entryKind: "result",
|
||||
content: (payload.content as string) || "",
|
||||
output: (payload.output as string) || (payload.content as string) || "",
|
||||
isError: !!payload.is_error,
|
||||
};
|
||||
const entry: TraceEntry =
|
||||
entryKind === 'use'
|
||||
? {
|
||||
entryKind: 'use',
|
||||
toolName: (payload.tool_name as string) || (payload.name as string) || 'tool',
|
||||
toolInput: payload.tool_input || payload.input,
|
||||
}
|
||||
: {
|
||||
entryKind: 'result',
|
||||
content: (payload.content as string) || '',
|
||||
output: (payload.output as string) || (payload.content as string) || '',
|
||||
isError: !!payload.is_error,
|
||||
};
|
||||
|
||||
// Add entry to the last assistant message
|
||||
setMessages((prev) => {
|
||||
setMessages(prev => {
|
||||
for (let i = prev.length - 1; i >= 0; i--) {
|
||||
if (prev[i].kind === "assistant") {
|
||||
if (prev[i].kind === 'assistant') {
|
||||
const msg = prev[i] as AssistantMessage;
|
||||
return [
|
||||
...prev.slice(0, i),
|
||||
{ ...msg, traceEntries: [...msg.traceEntries, entry] },
|
||||
...prev.slice(i + 1),
|
||||
];
|
||||
return [...prev.slice(0, i), { ...msg, traceEntries: [...msg.traceEntries, entry] }, ...prev.slice(i + 1)];
|
||||
}
|
||||
}
|
||||
return prev;
|
||||
@@ -1045,20 +1098,20 @@ export function useEventProcessor() {
|
||||
}
|
||||
|
||||
function getUserUuid(payload: EventPayload): string | null {
|
||||
if (!payload || typeof payload !== "object") return null;
|
||||
if (typeof payload.uuid === "string" && payload.uuid) return payload.uuid;
|
||||
if (payload.raw && typeof payload.raw === "object" && typeof payload.raw.uuid === "string" && payload.raw.uuid) {
|
||||
if (!payload || typeof payload !== 'object') return null;
|
||||
if (typeof payload.uuid === 'string' && payload.uuid) return payload.uuid;
|
||||
if (payload.raw && typeof payload.raw === 'object' && typeof payload.raw.uuid === 'string' && payload.raw.uuid) {
|
||||
return payload.raw.uuid;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function getEmbeddedToolBlocks(payload: EventPayload, blockType: string): import("../types").ContentBlock[] {
|
||||
if (!payload || typeof payload !== "object") return [];
|
||||
function getEmbeddedToolBlocks(payload: EventPayload, blockType: string): import('../types').ContentBlock[] {
|
||||
if (!payload || typeof payload !== 'object') return [];
|
||||
const msg = payload.message as Record<string, unknown> | undefined;
|
||||
if (!msg || typeof msg !== "object" || !Array.isArray(msg.content)) return [];
|
||||
return (msg.content as import("../types").ContentBlock[]).filter(
|
||||
(b) => b && typeof b === "object" && b.type === blockType,
|
||||
if (!msg || typeof msg !== 'object' || !Array.isArray(msg.content)) return [];
|
||||
return (msg.content as import('../types').ContentBlock[]).filter(
|
||||
b => b && typeof b === 'object' && b.type === blockType,
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,16 +1,11 @@
|
||||
import { useState, useRef, useEffect } from "react";
|
||||
import QRCode from "qrcode";
|
||||
import QrScanner from "qr-scanner";
|
||||
import { getUuid, setUuid } from "../api/client";
|
||||
import { cn } from "../lib/utils";
|
||||
import { Scan } from "lucide-react";
|
||||
import { useTheme } from "../lib/theme";
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "../../components/ui/dialog";
|
||||
import { useState, useRef, useEffect } from 'react';
|
||||
import QRCode from 'qrcode';
|
||||
import QrScanner from 'qr-scanner';
|
||||
import { getUuid, setUuid } from '../api/client';
|
||||
import { cn } from '../lib/utils';
|
||||
import { Scan } from 'lucide-react';
|
||||
import { useTheme } from '../lib/theme';
|
||||
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '../../components/ui/dialog';
|
||||
|
||||
interface IdentityPanelProps {
|
||||
open: boolean;
|
||||
@@ -26,9 +21,8 @@ export function IdentityPanel({ open, onClose }: IdentityPanelProps) {
|
||||
const uuid = getUuid();
|
||||
const { resolvedTheme } = useTheme();
|
||||
|
||||
const qrColors = resolvedTheme === "dark"
|
||||
? { dark: "#ECE9E0", light: "#1C1B18" }
|
||||
: { dark: "#141413", light: "#FDFCF8" };
|
||||
const qrColors =
|
||||
resolvedTheme === 'dark' ? { dark: '#ECE9E0', light: '#1C1B18' } : { dark: '#141413', light: '#FDFCF8' };
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
@@ -41,7 +35,7 @@ export function IdentityPanel({ open, onClose }: IdentityPanelProps) {
|
||||
margin: 1,
|
||||
color: qrColors,
|
||||
}).catch((err: unknown) => {
|
||||
console.error("QR generation failed:", err);
|
||||
console.error('QR generation failed:', err);
|
||||
});
|
||||
});
|
||||
return () => cancelAnimationFrame(rafId);
|
||||
@@ -71,7 +65,7 @@ export function IdentityPanel({ open, onClose }: IdentityPanelProps) {
|
||||
try {
|
||||
const scanner = new QrScanner(
|
||||
videoRef.current,
|
||||
(result) => {
|
||||
result => {
|
||||
handleScannedData(result.data);
|
||||
},
|
||||
{ returnDetailedScanResult: true },
|
||||
@@ -79,7 +73,7 @@ export function IdentityPanel({ open, onClose }: IdentityPanelProps) {
|
||||
scannerRef.current = scanner;
|
||||
await scanner.start();
|
||||
} catch (e) {
|
||||
console.error("Camera error:", e);
|
||||
console.error('Camera error:', e);
|
||||
setScanning(false);
|
||||
}
|
||||
};
|
||||
@@ -101,8 +95,8 @@ export function IdentityPanel({ open, onClose }: IdentityPanelProps) {
|
||||
// Store ACP connection data and navigate to ACP direct connect view
|
||||
stopCamera();
|
||||
onClose();
|
||||
sessionStorage.setItem("acp_connection", JSON.stringify({ url: parsed.url, token: parsed.token }));
|
||||
window.location.href = "/code/?acp=1";
|
||||
sessionStorage.setItem('acp_connection', JSON.stringify({ url: parsed.url, token: parsed.token }));
|
||||
window.location.href = '/code/?acp=1';
|
||||
return;
|
||||
}
|
||||
} catch {
|
||||
@@ -112,7 +106,7 @@ export function IdentityPanel({ open, onClose }: IdentityPanelProps) {
|
||||
// Try URL with uuid param
|
||||
try {
|
||||
const url = new URL(data);
|
||||
const importedUuid = url.searchParams.get("uuid");
|
||||
const importedUuid = url.searchParams.get('uuid');
|
||||
if (importedUuid) {
|
||||
setUuid(importedUuid);
|
||||
stopCamera();
|
||||
@@ -133,10 +127,10 @@ export function IdentityPanel({ open, onClose }: IdentityPanelProps) {
|
||||
};
|
||||
|
||||
const handleScanUpload = () => {
|
||||
const input = document.createElement("input");
|
||||
input.type = "file";
|
||||
input.accept = "image/*";
|
||||
input.onchange = async (e) => {
|
||||
const input = document.createElement('input');
|
||||
input.type = 'file';
|
||||
input.accept = 'image/*';
|
||||
input.onchange = async e => {
|
||||
const file = (e.target as HTMLInputElement).files?.[0];
|
||||
if (!file) return;
|
||||
try {
|
||||
@@ -145,14 +139,19 @@ export function IdentityPanel({ open, onClose }: IdentityPanelProps) {
|
||||
});
|
||||
handleScannedData(result.data);
|
||||
} catch {
|
||||
alert("No QR code found in image");
|
||||
alert('No QR code found in image');
|
||||
}
|
||||
};
|
||||
input.click();
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={(o) => { if (!o) onClose(); }}>
|
||||
<Dialog
|
||||
open={open}
|
||||
onOpenChange={o => {
|
||||
if (!o) onClose();
|
||||
}}
|
||||
>
|
||||
<DialogContent className="max-w-sm rounded-2xl border-border bg-surface-1 p-6 shadow-2xl">
|
||||
<DialogHeader>
|
||||
<DialogTitle className="font-display text-lg font-semibold text-text-primary">Identity</DialogTitle>
|
||||
@@ -170,7 +169,7 @@ export function IdentityPanel({ open, onClose }: IdentityPanelProps) {
|
||||
onClick={handleCopy}
|
||||
className="rounded-lg border border-border px-3 py-2 text-sm text-text-secondary hover:bg-surface-2 transition-colors"
|
||||
>
|
||||
{copied ? "Copied!" : "Copy"}
|
||||
{copied ? 'Copied!' : 'Copy'}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
@@ -206,14 +205,14 @@ export function IdentityPanel({ open, onClose }: IdentityPanelProps) {
|
||||
<button
|
||||
onClick={scanning ? stopCamera : startCamera}
|
||||
className={cn(
|
||||
"flex items-center gap-2 rounded-lg border px-4 py-2 text-sm transition-colors",
|
||||
'flex items-center gap-2 rounded-lg border px-4 py-2 text-sm transition-colors',
|
||||
scanning
|
||||
? "border-status-error/30 text-status-error hover:bg-status-error/10"
|
||||
: "border-border text-text-secondary hover:bg-surface-2",
|
||||
? 'border-status-error/30 text-status-error hover:bg-status-error/10'
|
||||
: 'border-border text-text-secondary hover:bg-surface-2',
|
||||
)}
|
||||
>
|
||||
<Scan className="h-4 w-4" />
|
||||
{scanning ? "Stop Camera" : "Scan with Camera"}
|
||||
{scanning ? 'Stop Camera' : 'Scan with Camera'}
|
||||
</button>
|
||||
<button
|
||||
onClick={handleScanUpload}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { useState, useEffect, useRef } from "react";
|
||||
import { useState, useEffect, useRef } from 'react';
|
||||
|
||||
const SPINNER_FRAMES = ["·", "✢", "✱", "✶", "✻", "✽"];
|
||||
const SPINNER_FRAMES = ['·', '✢', '✱', '✶', '✻', '✽'];
|
||||
const SPINNER_CYCLE = [...SPINNER_FRAMES, ...SPINNER_FRAMES.slice().reverse()];
|
||||
|
||||
interface LoadingIndicatorProps {
|
||||
@@ -8,7 +8,7 @@ interface LoadingIndicatorProps {
|
||||
stalled?: boolean;
|
||||
}
|
||||
|
||||
export function LoadingIndicator({ verb = "Thinking", stalled = false }: LoadingIndicatorProps) {
|
||||
export function LoadingIndicator({ verb = 'Thinking', stalled = false }: LoadingIndicatorProps) {
|
||||
const [frame, setFrame] = useState(0);
|
||||
const [elapsed, setElapsed] = useState(0);
|
||||
const startTimeRef = useRef(Date.now());
|
||||
@@ -16,7 +16,7 @@ export function LoadingIndicator({ verb = "Thinking", stalled = false }: Loading
|
||||
// Spinner animation — 120ms per frame
|
||||
useEffect(() => {
|
||||
const id = setInterval(() => {
|
||||
setFrame((f) => (f + 1) % SPINNER_CYCLE.length);
|
||||
setFrame(f => (f + 1) % SPINNER_CYCLE.length);
|
||||
}, 120);
|
||||
return () => clearInterval(id);
|
||||
}, []);
|
||||
@@ -34,7 +34,7 @@ export function LoadingIndicator({ verb = "Thinking", stalled = false }: Loading
|
||||
<div className="flex items-center gap-2.5 py-2">
|
||||
<span
|
||||
className="text-xl leading-none min-w-[1.2em] transition-colors duration-2000"
|
||||
style={{ color: stalled ? "var(--color-status-error)" : "var(--color-brand)" }}
|
||||
style={{ color: stalled ? 'var(--color-status-error)' : 'var(--color-brand)' }}
|
||||
>
|
||||
{SPINNER_CYCLE[frame]}
|
||||
</span>
|
||||
@@ -44,9 +44,7 @@ export function LoadingIndicator({ verb = "Thinking", stalled = false }: Loading
|
||||
>
|
||||
{verb}…
|
||||
</span>
|
||||
<span className="ml-auto text-xs font-mono text-text-muted">
|
||||
{elapsed}s
|
||||
</span>
|
||||
<span className="ml-auto text-xs font-mono text-text-muted">{elapsed}s</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { cn } from "../lib/utils";
|
||||
import { ThemeToggle } from "../../components/ui/theme-toggle";
|
||||
import { ChevronLeft, LayoutGrid, UserPlus, KeyRound } from "lucide-react";
|
||||
import { cn } from '../lib/utils';
|
||||
import { ThemeToggle } from '../../components/ui/theme-toggle';
|
||||
import { ChevronLeft, LayoutGrid, UserPlus, KeyRound } from 'lucide-react';
|
||||
|
||||
interface NavbarProps {
|
||||
onIdentityClick: () => void;
|
||||
@@ -27,16 +27,18 @@ export function Navbar({ onIdentityClick, onTokenClick, activeTokenLabel, sessio
|
||||
</button>
|
||||
<span className="text-text-muted/40">/</span>
|
||||
<span className="text-sm font-display font-medium text-text-primary truncate">{sessionTitle}</span>
|
||||
<span className="rounded-full bg-brand/15 px-2 py-0.5 text-[10px] font-medium text-brand flex-shrink-0">ACP</span>
|
||||
<span className="rounded-full bg-brand/15 px-2 py-0.5 text-[10px] font-medium text-brand flex-shrink-0">
|
||||
ACP
|
||||
</span>
|
||||
</div>
|
||||
) : (
|
||||
/* Dashboard 页面 — 品牌 */
|
||||
<a href="/code/" className="flex items-center gap-2 font-display text-lg font-semibold text-text-primary no-underline">
|
||||
<a
|
||||
href="/code/"
|
||||
className="flex items-center gap-2 font-display text-lg font-semibold text-text-primary no-underline"
|
||||
>
|
||||
<svg width="20" height="20" viewBox="0 0 20 20" fill="none" aria-hidden="true" className="flex-shrink-0">
|
||||
<path
|
||||
d="M10 1L12.2 7.8L19 10L12.2 12.2L10 19L7.8 12.2L1 10L7.8 7.8L10 1Z"
|
||||
fill="var(--color-brand)"
|
||||
/>
|
||||
<path d="M10 1L12.2 7.8L19 10L12.2 12.2L10 19L7.8 12.2L1 10L7.8 7.8L10 1Z" fill="var(--color-brand)" />
|
||||
</svg>
|
||||
<span className="hidden sm:inline">Remote Control</span>
|
||||
</a>
|
||||
@@ -56,15 +58,15 @@ export function Navbar({ onIdentityClick, onTokenClick, activeTokenLabel, sessio
|
||||
<button
|
||||
onClick={onTokenClick}
|
||||
className={cn(
|
||||
"flex items-center gap-1 rounded-md px-2 sm:px-3 py-1.5 text-sm transition-colors",
|
||||
'flex items-center gap-1 rounded-md px-2 sm:px-3 py-1.5 text-sm transition-colors',
|
||||
activeTokenLabel
|
||||
? "bg-brand/10 text-brand hover:bg-brand/20"
|
||||
: "text-text-secondary hover:bg-surface-2 hover:text-text-primary"
|
||||
? 'bg-brand/10 text-brand hover:bg-brand/20'
|
||||
: 'text-text-secondary hover:bg-surface-2 hover:text-text-primary',
|
||||
)}
|
||||
title="Token Manager"
|
||||
>
|
||||
<KeyRound className="h-4 w-4" />
|
||||
<span className="hidden sm:inline max-w-24 truncate">{activeTokenLabel || "No Token"}</span>
|
||||
<span className="hidden sm:inline max-w-24 truncate">{activeTokenLabel || 'No Token'}</span>
|
||||
</button>
|
||||
<button
|
||||
onClick={onIdentityClick}
|
||||
@@ -82,20 +84,20 @@ export function Navbar({ onIdentityClick, onTokenClick, activeTokenLabel, sessio
|
||||
|
||||
export function StatusBadge({ status }: { status: string }) {
|
||||
const colorMap: Record<string, string> = {
|
||||
active: "bg-status-active/20 text-status-active",
|
||||
running: "bg-status-running/20 text-status-running",
|
||||
idle: "bg-status-idle/20 text-status-idle",
|
||||
inactive: "bg-text-muted/20 text-text-muted",
|
||||
requires_action: "bg-status-warning/20 text-status-warning",
|
||||
archived: "bg-text-muted/20 text-text-muted",
|
||||
error: "bg-status-error/20 text-status-error",
|
||||
active: 'bg-status-active/20 text-status-active',
|
||||
running: 'bg-status-running/20 text-status-running',
|
||||
idle: 'bg-status-idle/20 text-status-idle',
|
||||
inactive: 'bg-text-muted/20 text-text-muted',
|
||||
requires_action: 'bg-status-warning/20 text-status-warning',
|
||||
archived: 'bg-text-muted/20 text-text-muted',
|
||||
error: 'bg-status-error/20 text-status-error',
|
||||
};
|
||||
|
||||
return (
|
||||
<span
|
||||
className={cn(
|
||||
"inline-flex items-center rounded-full px-2 py-0.5 text-xs font-medium",
|
||||
colorMap[status] || "bg-surface-3 text-text-secondary",
|
||||
'inline-flex items-center rounded-full px-2 py-0.5 text-xs font-medium',
|
||||
colorMap[status] || 'bg-surface-3 text-text-secondary',
|
||||
)}
|
||||
>
|
||||
{status}
|
||||
|
||||
@@ -1,13 +1,7 @@
|
||||
import { useState, useEffect } from "react";
|
||||
import type { Environment, Session } from "../types";
|
||||
import { apiCreateSession } from "../api/client";
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogFooter,
|
||||
} from "../../components/ui/dialog";
|
||||
import { useState, useEffect } from 'react';
|
||||
import type { Environment, Session } from '../types';
|
||||
import { apiCreateSession } from '../api/client';
|
||||
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from '../../components/ui/dialog';
|
||||
|
||||
interface NewSessionDialogProps {
|
||||
open: boolean;
|
||||
@@ -17,22 +11,22 @@ interface NewSessionDialogProps {
|
||||
}
|
||||
|
||||
export function NewSessionDialog({ open, environments, onClose, onCreated }: NewSessionDialogProps) {
|
||||
const [title, setTitle] = useState("");
|
||||
const [envId, setEnvId] = useState("");
|
||||
const [error, setError] = useState("");
|
||||
const [title, setTitle] = useState('');
|
||||
const [envId, setEnvId] = useState('');
|
||||
const [error, setError] = useState('');
|
||||
const [creating, setCreating] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (open) {
|
||||
setTitle("");
|
||||
setEnvId("");
|
||||
setError("");
|
||||
setTitle('');
|
||||
setEnvId('');
|
||||
setError('');
|
||||
}
|
||||
}, [open]);
|
||||
|
||||
const handleCreate = async () => {
|
||||
setCreating(true);
|
||||
setError("");
|
||||
setError('');
|
||||
try {
|
||||
const body: Record<string, string> = {};
|
||||
if (title.trim()) body.title = title.trim();
|
||||
@@ -40,14 +34,19 @@ export function NewSessionDialog({ open, environments, onClose, onCreated }: New
|
||||
const session = await apiCreateSession(body);
|
||||
onCreated(session);
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : "Failed to create session");
|
||||
setError(err instanceof Error ? err.message : 'Failed to create session');
|
||||
} finally {
|
||||
setCreating(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={(o) => { if (!o) onClose(); }}>
|
||||
<Dialog
|
||||
open={open}
|
||||
onOpenChange={o => {
|
||||
if (!o) onClose();
|
||||
}}
|
||||
>
|
||||
<DialogContent className="max-w-md rounded-2xl border-border bg-surface-1 p-6 shadow-2xl">
|
||||
<DialogHeader>
|
||||
<DialogTitle className="font-display text-lg font-semibold text-text-primary">New Session</DialogTitle>
|
||||
@@ -59,7 +58,7 @@ export function NewSessionDialog({ open, environments, onClose, onCreated }: New
|
||||
<input
|
||||
type="text"
|
||||
value={title}
|
||||
onChange={(e) => setTitle(e.target.value)}
|
||||
onChange={e => setTitle(e.target.value)}
|
||||
placeholder="My session"
|
||||
className="w-full rounded-lg border border-border bg-surface-2 px-3 py-2 text-sm text-text-primary placeholder:text-text-muted focus:border-brand focus:outline-none"
|
||||
/>
|
||||
@@ -69,13 +68,13 @@ export function NewSessionDialog({ open, environments, onClose, onCreated }: New
|
||||
<label className="mb-1 block text-sm text-text-secondary">Environment</label>
|
||||
<select
|
||||
value={envId}
|
||||
onChange={(e) => setEnvId(e.target.value)}
|
||||
onChange={e => setEnvId(e.target.value)}
|
||||
className="w-full rounded-lg border border-border bg-surface-2 px-3 py-2 text-sm text-text-primary focus:border-brand focus:outline-none"
|
||||
>
|
||||
<option value="">-- None --</option>
|
||||
{environments.map((env) => (
|
||||
{environments.map(env => (
|
||||
<option key={env.id} value={env.id}>
|
||||
{env.machine_name || env.id} ({env.branch || "no branch"})
|
||||
{env.machine_name || env.id} ({env.branch || 'no branch'})
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
@@ -96,7 +95,7 @@ export function NewSessionDialog({ open, environments, onClose, onCreated }: New
|
||||
disabled={creating}
|
||||
className="rounded-lg bg-brand px-4 py-2 text-sm font-medium text-white hover:bg-brand-light disabled:opacity-50 transition-colors"
|
||||
>
|
||||
{creating ? "Creating..." : "Create"}
|
||||
{creating ? 'Creating...' : 'Create'}
|
||||
</button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { useState } from "react";
|
||||
import type { Question } from "../types";
|
||||
import { esc, cn, truncate } from "../lib/utils";
|
||||
import { TriangleAlert, Check } from "lucide-react";
|
||||
import { useState } from 'react';
|
||||
import type { Question } from '../types';
|
||||
import { esc, cn, truncate } from '../lib/utils';
|
||||
import { TriangleAlert, Check } from 'lucide-react';
|
||||
|
||||
// ============================================================
|
||||
// PermissionPromptView — simple approve/reject for tool use
|
||||
@@ -22,7 +22,7 @@ export function PermissionPromptView({
|
||||
onApprove: () => void;
|
||||
onReject: () => void;
|
||||
}) {
|
||||
const inputStr = typeof toolInput === "string" ? toolInput : JSON.stringify(toolInput, null, 2);
|
||||
const inputStr = typeof toolInput === 'string' ? toolInput : JSON.stringify(toolInput, null, 2);
|
||||
|
||||
return (
|
||||
<div className="rounded-xl border border-warning-border/30 bg-surface-1 p-4">
|
||||
@@ -34,7 +34,7 @@ export function PermissionPromptView({
|
||||
</div>
|
||||
{description && <div className="mb-2 text-sm text-text-secondary">{esc(description)}</div>}
|
||||
<div className="mb-2 font-mono text-xs font-bold text-text-primary">{esc(toolName)}</div>
|
||||
{toolName !== "AskUserQuestion" && (
|
||||
{toolName !== 'AskUserQuestion' && (
|
||||
<pre className="mb-3 max-h-40 overflow-auto rounded-lg bg-surface-1 p-2 text-xs text-text-secondary font-mono">
|
||||
{truncate(inputStr, 500)}
|
||||
</pre>
|
||||
@@ -80,7 +80,7 @@ export function AskUserPanelView({
|
||||
const handleSelect = (qIdx: number, oIdx: number, multiSelect: boolean) => {
|
||||
if (multiSelect) {
|
||||
const current = (answers[qIdx] as number[]) || [];
|
||||
const next = current.includes(oIdx) ? current.filter((i) => i !== oIdx) : [...current, oIdx];
|
||||
const next = current.includes(oIdx) ? current.filter(i => i !== oIdx) : [...current, oIdx];
|
||||
setAnswers({ ...answers, [qIdx]: next });
|
||||
} else {
|
||||
setAnswers({ ...answers, [qIdx]: oIdx });
|
||||
@@ -91,7 +91,7 @@ export function AskUserPanelView({
|
||||
const text = otherTexts[qIdx]?.trim();
|
||||
if (!text) return;
|
||||
setAnswers({ ...answers, [qIdx]: text });
|
||||
setOtherTexts({ ...otherTexts, [qIdx]: "" });
|
||||
setOtherTexts({ ...otherTexts, [qIdx]: '' });
|
||||
};
|
||||
|
||||
const handleSubmit = () => {
|
||||
@@ -99,8 +99,8 @@ export function AskUserPanelView({
|
||||
for (const [qIdx, val] of Object.entries(answers)) {
|
||||
const q = questions[parseInt(qIdx, 10)];
|
||||
if (!q) continue;
|
||||
if (typeof val === "number") mapped[qIdx] = q.options?.[val]?.label || String(val);
|
||||
else if (Array.isArray(val)) mapped[qIdx] = val.map((i) => q.options?.[i]?.label || String(i));
|
||||
if (typeof val === 'number') mapped[qIdx] = q.options?.[val]?.label || String(val);
|
||||
else if (Array.isArray(val)) mapped[qIdx] = val.map(i => q.options?.[i]?.label || String(i));
|
||||
else mapped[qIdx] = val;
|
||||
}
|
||||
onSubmit(mapped);
|
||||
@@ -114,22 +114,20 @@ export function AskUserPanelView({
|
||||
return (
|
||||
<div className="rounded-xl border border-brand/30 bg-surface-1 p-4">
|
||||
<div className="mb-3 text-sm font-semibold text-text-primary">
|
||||
{esc(description || q.question || "Question")}
|
||||
{esc(description || q.question || 'Question')}
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
{(q.options || []).map((opt, j) => {
|
||||
const isSelected = multiSelect
|
||||
? ((answers[0] as number[]) || []).includes(j)
|
||||
: answers[0] === j;
|
||||
const isSelected = multiSelect ? ((answers[0] as number[]) || []).includes(j) : answers[0] === j;
|
||||
return (
|
||||
<button
|
||||
key={j}
|
||||
onClick={() => handleSelect(0, j, multiSelect)}
|
||||
className={cn(
|
||||
"w-full rounded-lg border px-4 py-2.5 text-left text-sm transition-colors",
|
||||
'w-full rounded-lg border px-4 py-2.5 text-left text-sm transition-colors',
|
||||
isSelected
|
||||
? "border-brand bg-brand/10 text-text-primary"
|
||||
: "border-border bg-surface-2 text-text-secondary hover:border-border-light",
|
||||
? 'border-brand bg-brand/10 text-text-primary'
|
||||
: 'border-border bg-surface-2 text-text-secondary hover:border-border-light',
|
||||
)}
|
||||
>
|
||||
<div className="font-medium">{esc(opt.label)}</div>
|
||||
@@ -140,20 +138,33 @@ export function AskUserPanelView({
|
||||
<div className="flex gap-2">
|
||||
<input
|
||||
type="text"
|
||||
value={otherTexts[0] || ""}
|
||||
onChange={(e) => setOtherTexts({ ...otherTexts, [0]: e.target.value })}
|
||||
value={otherTexts[0] || ''}
|
||||
onChange={e => setOtherTexts({ ...otherTexts, [0]: e.target.value })}
|
||||
placeholder="Other..."
|
||||
className="flex-1 rounded-lg border border-border bg-surface-2 px-3 py-2 text-sm text-text-primary placeholder:text-text-muted focus:border-brand focus:outline-none"
|
||||
onKeyDown={(e) => e.key === "Enter" && handleOtherSubmit(0)}
|
||||
onKeyDown={e => e.key === 'Enter' && handleOtherSubmit(0)}
|
||||
/>
|
||||
<button onClick={() => handleOtherSubmit(0)} className="rounded-lg border border-border px-3 py-2 text-sm text-text-secondary hover:bg-surface-2 transition-colors">
|
||||
<button
|
||||
onClick={() => handleOtherSubmit(0)}
|
||||
className="rounded-lg border border-border px-3 py-2 text-sm text-text-secondary hover:bg-surface-2 transition-colors"
|
||||
>
|
||||
Send
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<div className="mt-4 flex gap-2">
|
||||
<button onClick={handleSubmit} className="rounded-lg bg-brand px-4 py-2 text-sm font-medium text-white hover:bg-brand-light transition-colors">Submit</button>
|
||||
<button onClick={onSkip} className="rounded-lg border border-border px-4 py-2 text-sm text-text-secondary hover:bg-surface-2 transition-colors">Skip</button>
|
||||
<button
|
||||
onClick={handleSubmit}
|
||||
className="rounded-lg bg-brand px-4 py-2 text-sm font-medium text-white hover:bg-brand-light transition-colors"
|
||||
>
|
||||
Submit
|
||||
</button>
|
||||
<button
|
||||
onClick={onSkip}
|
||||
className="rounded-lg border border-border px-4 py-2 text-sm text-text-secondary hover:bg-surface-2 transition-colors"
|
||||
>
|
||||
Skip
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
@@ -164,15 +175,15 @@ export function AskUserPanelView({
|
||||
|
||||
return (
|
||||
<div className="rounded-xl border border-brand/30 bg-surface-1 p-4">
|
||||
<div className="mb-3 text-sm font-semibold text-text-primary">{esc(description || "Questions")}</div>
|
||||
<div className="mb-3 text-sm font-semibold text-text-primary">{esc(description || 'Questions')}</div>
|
||||
<div className="mb-3 flex gap-1 overflow-x-auto">
|
||||
{questions.map((q, i) => (
|
||||
<button
|
||||
key={i}
|
||||
onClick={() => setActiveTab(i)}
|
||||
className={cn(
|
||||
"rounded-md px-3 py-1.5 text-xs whitespace-nowrap transition-colors",
|
||||
activeTab === i ? "bg-brand/20 text-brand" : "text-text-muted hover:bg-surface-2",
|
||||
'rounded-md px-3 py-1.5 text-xs whitespace-nowrap transition-colors',
|
||||
activeTab === i ? 'bg-brand/20 text-brand' : 'text-text-muted hover:bg-surface-2',
|
||||
)}
|
||||
>
|
||||
{q.header || `Q${i + 1}`}
|
||||
@@ -193,10 +204,22 @@ export function AskUserPanelView({
|
||||
)}
|
||||
|
||||
<div className="mt-4 flex items-center justify-between">
|
||||
<span className="text-xs text-text-muted">{activeTab + 1} / {questions.length}</span>
|
||||
<span className="text-xs text-text-muted">
|
||||
{activeTab + 1} / {questions.length}
|
||||
</span>
|
||||
<div className="flex gap-2">
|
||||
<button onClick={handleSubmit} className="rounded-lg bg-brand px-4 py-2 text-sm font-medium text-white hover:bg-brand-light transition-colors">Submit All</button>
|
||||
<button onClick={onSkip} className="rounded-lg border border-border px-4 py-2 text-sm text-text-secondary hover:bg-surface-2 transition-colors">Skip</button>
|
||||
<button
|
||||
onClick={handleSubmit}
|
||||
className="rounded-lg bg-brand px-4 py-2 text-sm font-medium text-white hover:bg-brand-light transition-colors"
|
||||
>
|
||||
Submit All
|
||||
</button>
|
||||
<button
|
||||
onClick={onSkip}
|
||||
className="rounded-lg border border-border px-4 py-2 text-sm text-text-secondary hover:bg-surface-2 transition-colors"
|
||||
>
|
||||
Skip
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -204,7 +227,13 @@ export function AskUserPanelView({
|
||||
}
|
||||
|
||||
function QuestionTab({
|
||||
question, qIdx, answers, otherTexts, onSelect, onOtherTextChange, onOtherSubmit,
|
||||
question,
|
||||
qIdx,
|
||||
answers,
|
||||
otherTexts,
|
||||
onSelect,
|
||||
onOtherTextChange,
|
||||
onOtherSubmit,
|
||||
}: {
|
||||
question: Question;
|
||||
qIdx: number;
|
||||
@@ -221,18 +250,16 @@ function QuestionTab({
|
||||
<div className="mb-2 text-sm text-text-secondary">{esc(question.question)}</div>
|
||||
<div className="space-y-2">
|
||||
{(question.options || []).map((opt, j) => {
|
||||
const isSelected = multiSelect
|
||||
? ((answers[qIdx] as number[]) || []).includes(j)
|
||||
: answers[qIdx] === j;
|
||||
const isSelected = multiSelect ? ((answers[qIdx] as number[]) || []).includes(j) : answers[qIdx] === j;
|
||||
return (
|
||||
<button
|
||||
key={j}
|
||||
onClick={() => onSelect(qIdx, j, multiSelect)}
|
||||
className={cn(
|
||||
"w-full rounded-lg border px-4 py-2.5 text-left text-sm transition-colors",
|
||||
'w-full rounded-lg border px-4 py-2.5 text-left text-sm transition-colors',
|
||||
isSelected
|
||||
? "border-brand bg-brand/10 text-text-primary"
|
||||
: "border-border bg-surface-2 text-text-secondary hover:border-border-light",
|
||||
? 'border-brand bg-brand/10 text-text-primary'
|
||||
: 'border-border bg-surface-2 text-text-secondary hover:border-border-light',
|
||||
)}
|
||||
>
|
||||
<div className="font-medium">{esc(opt.label)}</div>
|
||||
@@ -243,13 +270,18 @@ function QuestionTab({
|
||||
<div className="flex gap-2">
|
||||
<input
|
||||
type="text"
|
||||
value={otherTexts[qIdx] || ""}
|
||||
onChange={(e) => onOtherTextChange(qIdx, e.target.value)}
|
||||
value={otherTexts[qIdx] || ''}
|
||||
onChange={e => onOtherTextChange(qIdx, e.target.value)}
|
||||
placeholder="Other..."
|
||||
className="flex-1 rounded-lg border border-border bg-surface-2 px-3 py-2 text-sm text-text-primary placeholder:text-text-muted focus:border-brand focus:outline-none"
|
||||
onKeyDown={(e) => e.key === "Enter" && onOtherSubmit(qIdx)}
|
||||
onKeyDown={e => e.key === 'Enter' && onOtherSubmit(qIdx)}
|
||||
/>
|
||||
<button onClick={() => onOtherSubmit(qIdx)} className="rounded-lg border border-border px-3 py-2 text-sm text-text-secondary hover:bg-surface-2 transition-colors">Send</button>
|
||||
<button
|
||||
onClick={() => onOtherSubmit(qIdx)}
|
||||
className="rounded-lg border border-border px-3 py-2 text-sm text-text-secondary hover:bg-surface-2 transition-colors"
|
||||
>
|
||||
Send
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -271,12 +303,12 @@ export function PlanPanelView({
|
||||
onSubmit: (value: string, feedback?: string) => void;
|
||||
}) {
|
||||
const [selected, setSelected] = useState<string | null>(null);
|
||||
const [feedback, setFeedback] = useState("");
|
||||
const [feedback, setFeedback] = useState('');
|
||||
const isEmpty = !planContent || !planContent.trim();
|
||||
|
||||
const handleSubmit = () => {
|
||||
if (!selected) return;
|
||||
onSubmit(selected, selected === "no" ? feedback : undefined);
|
||||
onSubmit(selected, selected === 'no' ? feedback : undefined);
|
||||
};
|
||||
|
||||
return (
|
||||
@@ -286,33 +318,49 @@ export function PlanPanelView({
|
||||
<Check className="h-3 w-3" strokeWidth={2.5} />
|
||||
</span>
|
||||
<span className="text-sm font-semibold text-text-primary">
|
||||
{isEmpty ? "Exit plan mode?" : "Ready to code?"}
|
||||
{isEmpty ? 'Exit plan mode?' : 'Ready to code?'}
|
||||
</span>
|
||||
</div>
|
||||
{!isEmpty && (
|
||||
<div
|
||||
className="mb-4 max-h-64 overflow-auto rounded-lg bg-tool-card p-4 text-sm text-text-secondary"
|
||||
// biome-ignore lint/security/noDangerouslySetInnerHtml: content is sanitized by formatPlanContent
|
||||
dangerouslySetInnerHTML={{ __html: formatPlanContent(planContent) }}
|
||||
/>
|
||||
)}
|
||||
<div className="space-y-2">
|
||||
{isEmpty ? (
|
||||
<>
|
||||
<PlanOption selected={selected === "yes-default"} onClick={() => setSelected("yes-default")} label="Yes" />
|
||||
<PlanOption selected={selected === "no"} onClick={() => setSelected("no")} label="No" />
|
||||
<PlanOption selected={selected === 'yes-default'} onClick={() => setSelected('yes-default')} label="Yes" />
|
||||
<PlanOption selected={selected === 'no'} onClick={() => setSelected('no')} label="No" />
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<PlanOption selected={selected === "yes-accept-edits"} onClick={() => setSelected("yes-accept-edits")} label="Yes, auto-accept edits" desc="Approve plan and auto-accept file edits" />
|
||||
<PlanOption selected={selected === "yes-default"} onClick={() => setSelected("yes-default")} label="Yes, manually approve edits" desc="Approve plan but confirm each edit" />
|
||||
<PlanOption selected={selected === "no"} onClick={() => setSelected("no")} label="No, keep planning" desc="Provide feedback to refine the plan" />
|
||||
<PlanOption
|
||||
selected={selected === 'yes-accept-edits'}
|
||||
onClick={() => setSelected('yes-accept-edits')}
|
||||
label="Yes, auto-accept edits"
|
||||
desc="Approve plan and auto-accept file edits"
|
||||
/>
|
||||
<PlanOption
|
||||
selected={selected === 'yes-default'}
|
||||
onClick={() => setSelected('yes-default')}
|
||||
label="Yes, manually approve edits"
|
||||
desc="Approve plan but confirm each edit"
|
||||
/>
|
||||
<PlanOption
|
||||
selected={selected === 'no'}
|
||||
onClick={() => setSelected('no')}
|
||||
label="No, keep planning"
|
||||
desc="Provide feedback to refine the plan"
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
{selected === "no" && (
|
||||
{selected === 'no' && (
|
||||
<textarea
|
||||
value={feedback}
|
||||
onChange={(e) => setFeedback(e.target.value)}
|
||||
onChange={e => setFeedback(e.target.value)}
|
||||
placeholder="Tell Claude what to change..."
|
||||
className="mt-3 w-full rounded-lg border border-border bg-surface-2 px-3 py-2 text-sm text-text-primary placeholder:text-text-muted focus:border-brand focus:outline-none"
|
||||
rows={3}
|
||||
@@ -331,21 +379,35 @@ export function PlanPanelView({
|
||||
);
|
||||
}
|
||||
|
||||
function PlanOption({ selected, onClick, label, desc }: { selected: boolean; onClick: () => void; label: string; desc?: string }) {
|
||||
function PlanOption({
|
||||
selected,
|
||||
onClick,
|
||||
label,
|
||||
desc,
|
||||
}: {
|
||||
selected: boolean;
|
||||
onClick: () => void;
|
||||
label: string;
|
||||
desc?: string;
|
||||
}) {
|
||||
return (
|
||||
<button
|
||||
onClick={onClick}
|
||||
className={cn(
|
||||
"w-full rounded-lg border px-4 py-2.5 text-left text-sm transition-colors",
|
||||
selected ? "border-brand bg-brand/10 text-text-primary" : "border-border bg-surface-2 text-text-secondary hover:border-border-light",
|
||||
'w-full rounded-lg border px-4 py-2.5 text-left text-sm transition-colors',
|
||||
selected
|
||||
? 'border-brand bg-brand/10 text-text-primary'
|
||||
: 'border-border bg-surface-2 text-text-secondary hover:border-border-light',
|
||||
)}
|
||||
>
|
||||
<div className="flex items-center gap-2">
|
||||
<span className={cn(
|
||||
"flex h-4 w-4 items-center justify-center rounded-full border text-[10px] transition-colors",
|
||||
selected ? "border-brand bg-brand text-white" : "border-border",
|
||||
)}>
|
||||
{selected && "\u2713"}
|
||||
<span
|
||||
className={cn(
|
||||
'flex h-4 w-4 items-center justify-center rounded-full border text-[10px] transition-colors',
|
||||
selected ? 'border-brand bg-brand text-white' : 'border-border',
|
||||
)}
|
||||
>
|
||||
{selected && '\u2713'}
|
||||
</span>
|
||||
<span className="font-medium">{label}</span>
|
||||
</div>
|
||||
@@ -356,10 +418,12 @@ function PlanOption({ selected, onClick, label, desc }: { selected: boolean; onC
|
||||
|
||||
function formatPlanContent(content: string): string {
|
||||
let html = esc(content);
|
||||
html = html.replace(/```(\w*)\n?([\s\S]*?)```/g, (_, _l, code) =>
|
||||
`<pre class="my-2 overflow-x-auto rounded-lg bg-tool-card p-3 font-mono text-xs">${code.trim()}</pre>`
|
||||
html = html.replace(
|
||||
/```(\w*)\n?([\s\S]*?)```/g,
|
||||
(_, _l, code) =>
|
||||
`<pre class="my-2 overflow-x-auto rounded-lg bg-tool-card p-3 font-mono text-xs">${code.trim()}</pre>`,
|
||||
);
|
||||
html = html.replace(/`([^`]+)`/g, '<code class="rounded bg-tool-card px-1.5 py-0.5 font-mono text-xs">$1</code>');
|
||||
html = html.replace(/\*\*([^*]+)\*\*/g, "<strong>$1</strong>");
|
||||
html = html.replace(/\*\*([^*]+)\*\*/g, '<strong>$1</strong>');
|
||||
return html;
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import type { Session } from "../types";
|
||||
import { StatusBadge } from "./Navbar";
|
||||
import { esc, formatTime } from "../lib/utils";
|
||||
import type { Session } from '../types';
|
||||
import { StatusBadge } from './Navbar';
|
||||
import { esc, formatTime } from '../lib/utils';
|
||||
|
||||
interface SessionListProps {
|
||||
sessions: Session[];
|
||||
@@ -10,9 +10,7 @@ interface SessionListProps {
|
||||
export function SessionList({ sessions, onSelect }: SessionListProps) {
|
||||
if (!sessions || sessions.length === 0) {
|
||||
return (
|
||||
<div className="rounded-xl border border-border bg-surface-1 p-8 text-center text-text-muted">
|
||||
No sessions
|
||||
</div>
|
||||
<div className="rounded-xl border border-border bg-surface-1 p-8 text-center text-text-muted">No sessions</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -20,7 +18,7 @@ export function SessionList({ sessions, onSelect }: SessionListProps) {
|
||||
|
||||
return (
|
||||
<div className="space-y-2">
|
||||
{sorted.map((session) => (
|
||||
{sorted.map(session => (
|
||||
<button
|
||||
key={session.id}
|
||||
type="button"
|
||||
@@ -29,22 +27,16 @@ export function SessionList({ sessions, onSelect }: SessionListProps) {
|
||||
>
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="truncate font-medium text-text-primary">
|
||||
{session.title || session.id}
|
||||
</span>
|
||||
{session.source === "acp" && (
|
||||
<span className="rounded-full bg-brand/15 px-2 py-0.5 text-xs font-medium text-brand">
|
||||
ACP
|
||||
</span>
|
||||
<span className="truncate font-medium text-text-primary">{session.title || session.id}</span>
|
||||
{session.source === 'acp' && (
|
||||
<span className="rounded-full bg-brand/15 px-2 py-0.5 text-xs font-medium text-brand">ACP</span>
|
||||
)}
|
||||
</div>
|
||||
<div className="truncate text-xs text-text-muted">{session.id}</div>
|
||||
</div>
|
||||
<div className="flex items-center gap-3">
|
||||
<StatusBadge status={session.status} />
|
||||
<span className="text-xs text-text-muted">
|
||||
{formatTime(session.created_at || session.updated_at)}
|
||||
</span>
|
||||
<span className="text-xs text-text-muted">{formatTime(session.created_at || session.updated_at)}</span>
|
||||
</div>
|
||||
</button>
|
||||
))}
|
||||
|
||||
@@ -1,9 +1,4 @@
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "../../components/ui/dialog";
|
||||
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '../../components/ui/dialog';
|
||||
|
||||
interface TaskPanelProps {
|
||||
onClose: () => void;
|
||||
@@ -11,7 +6,12 @@ interface TaskPanelProps {
|
||||
|
||||
export function TaskPanel({ onClose }: TaskPanelProps) {
|
||||
return (
|
||||
<Dialog open={true} onOpenChange={(o) => { if (!o) onClose(); }}>
|
||||
<Dialog
|
||||
open={true}
|
||||
onOpenChange={o => {
|
||||
if (!o) onClose();
|
||||
}}
|
||||
>
|
||||
<DialogContent
|
||||
showCloseButton={false}
|
||||
className="fixed inset-y-0 right-0 top-auto left-auto translate-x-0 translate-y-0 w-full sm:w-80 h-full max-w-none max-h-none rounded-none border-l border-border bg-surface-1 p-4 sm:max-w-sm"
|
||||
|
||||
@@ -1,13 +1,7 @@
|
||||
import { useState } from "react";
|
||||
import type { TokenEntry } from "../hooks/useTokens";
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogDescription,
|
||||
} from "../../components/ui/dialog";
|
||||
import { Check, Copy, Eye, EyeOff, Pencil, Plus, Trash2, X } from "lucide-react";
|
||||
import { useState } from 'react';
|
||||
import type { TokenEntry } from '../hooks/useTokens';
|
||||
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription } from '../../components/ui/dialog';
|
||||
import { Check, Copy, Eye, EyeOff, Pencil, Plus, Trash2, X } from 'lucide-react';
|
||||
|
||||
interface TokenManagerDialogProps {
|
||||
open: boolean;
|
||||
@@ -30,11 +24,11 @@ export function TokenManagerDialog({
|
||||
onRemove,
|
||||
onUpdate,
|
||||
}: TokenManagerDialogProps) {
|
||||
const [newToken, setNewToken] = useState("");
|
||||
const [newLabel, setNewLabel] = useState("");
|
||||
const [addError, setAddError] = useState("");
|
||||
const [newToken, setNewToken] = useState('');
|
||||
const [newLabel, setNewLabel] = useState('');
|
||||
const [addError, setAddError] = useState('');
|
||||
const [editingId, setEditingId] = useState<string | null>(null);
|
||||
const [editLabel, setEditLabel] = useState("");
|
||||
const [editLabel, setEditLabel] = useState('');
|
||||
const [visibleTokenId, setVisibleTokenId] = useState<string | null>(null);
|
||||
const [copiedId, setCopiedId] = useState<string | null>(null);
|
||||
|
||||
@@ -51,9 +45,9 @@ export function TokenManagerDialog({
|
||||
setAddError(error);
|
||||
return;
|
||||
}
|
||||
setNewToken("");
|
||||
setNewLabel("");
|
||||
setAddError("");
|
||||
setNewToken('');
|
||||
setNewLabel('');
|
||||
setAddError('');
|
||||
};
|
||||
|
||||
const handleStartEdit = (entry: TokenEntry) => {
|
||||
@@ -62,7 +56,7 @@ export function TokenManagerDialog({
|
||||
};
|
||||
|
||||
const handleSaveEdit = (id: string) => {
|
||||
onUpdate(id, editLabel.trim() || "Unnamed");
|
||||
onUpdate(id, editLabel.trim() || 'Unnamed');
|
||||
setEditingId(null);
|
||||
};
|
||||
|
||||
@@ -72,12 +66,15 @@ export function TokenManagerDialog({
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={(o) => { if (!o) onClose(); }}>
|
||||
<Dialog
|
||||
open={open}
|
||||
onOpenChange={o => {
|
||||
if (!o) onClose();
|
||||
}}
|
||||
>
|
||||
<DialogContent className="max-w-md rounded-2xl border-border bg-surface-1 p-6 shadow-2xl">
|
||||
<DialogHeader>
|
||||
<DialogTitle className="font-display text-lg font-semibold text-text-primary">
|
||||
Token Manager
|
||||
</DialogTitle>
|
||||
<DialogTitle className="font-display text-lg font-semibold text-text-primary">Token Manager</DialogTitle>
|
||||
<DialogDescription className="text-sm text-text-muted">
|
||||
Manage API tokens for RCS authentication.
|
||||
</DialogDescription>
|
||||
@@ -85,16 +82,16 @@ export function TokenManagerDialog({
|
||||
|
||||
{/* Token list */}
|
||||
<div className="space-y-1 max-h-64 overflow-y-auto">
|
||||
{tokens.map((entry) => (
|
||||
{tokens.map(entry => (
|
||||
<div key={entry.id} className="group flex items-center gap-1">
|
||||
{editingId === entry.id ? (
|
||||
<div className="flex flex-1 items-center gap-2 rounded-lg bg-surface-2 px-3 py-1.5">
|
||||
<input
|
||||
value={editLabel}
|
||||
onChange={(e) => setEditLabel(e.target.value)}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === "Enter") handleSaveEdit(entry.id);
|
||||
if (e.key === "Escape") setEditingId(null);
|
||||
onChange={e => setEditLabel(e.target.value)}
|
||||
onKeyDown={e => {
|
||||
if (e.key === 'Enter') handleSaveEdit(entry.id);
|
||||
if (e.key === 'Escape') setEditingId(null);
|
||||
}}
|
||||
className="flex-1 rounded border border-border bg-surface-1 px-2 py-1 text-sm text-text-primary focus:border-brand focus:outline-none"
|
||||
autoFocus
|
||||
@@ -117,17 +114,13 @@ export function TokenManagerDialog({
|
||||
<button
|
||||
onClick={() => handleSwitch(entry.id)}
|
||||
className={`flex flex-1 items-center justify-between rounded-lg px-3 py-2 text-sm transition-colors ${
|
||||
activeTokenId === entry.id
|
||||
? "bg-brand/10 text-brand"
|
||||
: "text-text-secondary hover:bg-surface-2"
|
||||
activeTokenId === entry.id ? 'bg-brand/10 text-brand' : 'text-text-secondary hover:bg-surface-2'
|
||||
}`}
|
||||
>
|
||||
<div className="flex flex-col items-start min-w-0">
|
||||
<span className="font-medium truncate w-full">{entry.label}</span>
|
||||
<span className="text-xs text-text-muted font-mono">
|
||||
{visibleTokenId === entry.id
|
||||
? entry.token
|
||||
: `${entry.token.slice(0, 6)}${"\u2022".repeat(6)}`}
|
||||
{visibleTokenId === entry.id ? entry.token : `${entry.token.slice(0, 6)}${'\u2022'.repeat(6)}`}
|
||||
</span>
|
||||
</div>
|
||||
{activeTokenId === entry.id && <Check className="h-4 w-4 flex-shrink-0" />}
|
||||
@@ -144,7 +137,11 @@ export function TokenManagerDialog({
|
||||
className="rounded p-1 text-text-muted opacity-0 group-hover:opacity-100 hover:text-text-primary transition-all"
|
||||
title="Copy token"
|
||||
>
|
||||
{copiedId === entry.id ? <Check className="h-3.5 w-3.5 text-status-active" /> : <Copy className="h-3.5 w-3.5" />}
|
||||
{copiedId === entry.id ? (
|
||||
<Check className="h-3.5 w-3.5 text-status-active" />
|
||||
) : (
|
||||
<Copy className="h-3.5 w-3.5" />
|
||||
)}
|
||||
</button>
|
||||
<button
|
||||
onClick={() => handleStartEdit(entry)}
|
||||
@@ -166,9 +163,7 @@ export function TokenManagerDialog({
|
||||
))}
|
||||
|
||||
{tokens.length === 0 && (
|
||||
<div className="py-4 text-center text-sm text-text-muted">
|
||||
No tokens saved yet. Add one below.
|
||||
</div>
|
||||
<div className="py-4 text-center text-sm text-text-muted">No tokens saved yet. Add one below.</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
@@ -179,25 +174,25 @@ export function TokenManagerDialog({
|
||||
<input
|
||||
type="text"
|
||||
value={newToken}
|
||||
onChange={(e) => {
|
||||
onChange={e => {
|
||||
setNewToken(e.target.value);
|
||||
setAddError("");
|
||||
setAddError('');
|
||||
}}
|
||||
placeholder="API Token"
|
||||
className="w-full rounded-lg border border-border bg-surface-2 px-3 py-2 text-sm text-text-primary placeholder:text-text-muted focus:border-brand focus:outline-none font-mono"
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === "Enter") handleAdd();
|
||||
onKeyDown={e => {
|
||||
if (e.key === 'Enter') handleAdd();
|
||||
}}
|
||||
/>
|
||||
<div className="flex gap-2">
|
||||
<input
|
||||
type="text"
|
||||
value={newLabel}
|
||||
onChange={(e) => setNewLabel(e.target.value)}
|
||||
onChange={e => setNewLabel(e.target.value)}
|
||||
placeholder="Label (optional)"
|
||||
className="flex-1 rounded-lg border border-border bg-surface-2 px-3 py-2 text-sm text-text-primary placeholder:text-text-muted focus:border-brand focus:outline-none"
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === "Enter") handleAdd();
|
||||
onKeyDown={e => {
|
||||
if (e.key === 'Enter') handleAdd();
|
||||
}}
|
||||
/>
|
||||
<button
|
||||
|
||||
@@ -1,3 +1,8 @@
|
||||
export { useModels, type UseModelsResult } from "./useModels";
|
||||
export { useCommands, type UseCommandsResult } from "./useCommands";
|
||||
export { useQRScanner, type QRCodeData, type UseQRScannerOptions, type UseQRScannerResult } from "./useQRScanner";
|
||||
export { useModels, type UseModelsResult } from './useModels'
|
||||
export { useCommands, type UseCommandsResult } from './useCommands'
|
||||
export {
|
||||
useQRScanner,
|
||||
type QRCodeData,
|
||||
type UseQRScannerOptions,
|
||||
type UseQRScannerResult,
|
||||
} from './useQRScanner'
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
import { useState, useCallback } from "react";
|
||||
import { getUuid, setUuid } from "../api/client";
|
||||
import { useState, useCallback } from 'react'
|
||||
import { getUuid, setUuid } from '../api/client'
|
||||
|
||||
export function useAuth() {
|
||||
const [uuid] = useState(() => getUuid());
|
||||
const [uuid] = useState(() => getUuid())
|
||||
|
||||
const importUuid = useCallback((newUuid: string) => {
|
||||
setUuid(newUuid);
|
||||
}, []);
|
||||
setUuid(newUuid)
|
||||
}, [])
|
||||
|
||||
return { uuid, importUuid };
|
||||
return { uuid, importUuid }
|
||||
}
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
import { useState, useEffect, useMemo } from "react";
|
||||
import type { ACPClient } from "../acp/client";
|
||||
import type { AvailableCommand } from "../acp/types";
|
||||
import { useState, useEffect, useMemo } from 'react'
|
||||
import type { ACPClient } from '../acp/client'
|
||||
import type { AvailableCommand } from '../acp/types'
|
||||
|
||||
export interface UseCommandsResult {
|
||||
/** List of available slash commands from the agent */
|
||||
commands: AvailableCommand[];
|
||||
commands: AvailableCommand[]
|
||||
/** Whether any commands are available */
|
||||
hasCommands: boolean;
|
||||
hasCommands: boolean
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -16,24 +16,21 @@ export interface UseCommandsResult {
|
||||
export function useCommands(client: ACPClient): UseCommandsResult {
|
||||
const [commands, setCommands] = useState<AvailableCommand[]>(
|
||||
client.availableCommands,
|
||||
);
|
||||
)
|
||||
|
||||
useEffect(() => {
|
||||
const handleCommandsChanged = (newCommands: AvailableCommand[]) => {
|
||||
setCommands(newCommands);
|
||||
};
|
||||
setCommands(newCommands)
|
||||
}
|
||||
|
||||
client.setAvailableCommandsChangedHandler(handleCommandsChanged);
|
||||
client.setAvailableCommandsChangedHandler(handleCommandsChanged)
|
||||
|
||||
return () => {
|
||||
client.setAvailableCommandsChangedHandler(() => {});
|
||||
};
|
||||
}, [client]);
|
||||
client.setAvailableCommandsChangedHandler(() => {})
|
||||
}
|
||||
}, [client])
|
||||
|
||||
const hasCommands = useMemo(
|
||||
() => commands.length > 0,
|
||||
[commands],
|
||||
);
|
||||
const hasCommands = useMemo(() => commands.length > 0, [commands])
|
||||
|
||||
return { commands, hasCommands };
|
||||
return { commands, hasCommands }
|
||||
}
|
||||
|
||||
@@ -1,20 +1,20 @@
|
||||
import { useState, useEffect, useMemo, useCallback } from "react";
|
||||
import type { ACPClient } from "../acp/client";
|
||||
import type { ModelInfo, SessionModelState } from "../acp/types";
|
||||
import { useState, useEffect, useMemo, useCallback } from 'react'
|
||||
import type { ACPClient } from '../acp/client'
|
||||
import type { ModelInfo, SessionModelState } from '../acp/types'
|
||||
|
||||
export interface UseModelsResult {
|
||||
/** Whether model selection is supported by the current agent */
|
||||
supportsModelSelection: boolean;
|
||||
supportsModelSelection: boolean
|
||||
/** List of available models */
|
||||
availableModels: ModelInfo[];
|
||||
availableModels: ModelInfo[]
|
||||
/** The currently selected model ID */
|
||||
currentModelId: string | null;
|
||||
currentModelId: string | null
|
||||
/** The currently selected model info */
|
||||
currentModel: ModelInfo | null;
|
||||
currentModel: ModelInfo | null
|
||||
/** Set the model for the current session */
|
||||
setModel: (modelId: string) => Promise<void>;
|
||||
setModel: (modelId: string) => Promise<void>
|
||||
/** Whether a model change is in progress */
|
||||
isLoading: boolean;
|
||||
isLoading: boolean
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -27,78 +27,81 @@ export interface UseModelsResult {
|
||||
*/
|
||||
export function useModels(client: ACPClient): UseModelsResult {
|
||||
const [modelState, setModelState] = useState<SessionModelState | null>(
|
||||
client.modelState
|
||||
);
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
client.modelState,
|
||||
)
|
||||
const [isLoading, setIsLoading] = useState(false)
|
||||
|
||||
// Subscribe to model state changes (session created/destroyed)
|
||||
// This replaces the previous 500ms polling approach
|
||||
useEffect(() => {
|
||||
// Handler for when model state changes (session created or disconnected)
|
||||
const handleModelStateChanged = (state: SessionModelState | null) => {
|
||||
setModelState(state);
|
||||
setModelState(state)
|
||||
// Auto-restore previously selected model when a new session is created
|
||||
if (state && state.availableModels.length > 0) {
|
||||
const saved = localStorage.getItem("acp_model_id");
|
||||
if (saved && saved !== state.currentModelId && state.availableModels.some((m) => m.modelId === saved)) {
|
||||
client.setSessionModel(saved).catch(() => {});
|
||||
const saved = localStorage.getItem('acp_model_id')
|
||||
if (
|
||||
saved &&
|
||||
saved !== state.currentModelId &&
|
||||
state.availableModels.some(m => m.modelId === saved)
|
||||
) {
|
||||
client.setSessionModel(saved).catch(() => {})
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
// Handler for when current model changes within a session
|
||||
const handleModelChanged = (modelId: string) => {
|
||||
setModelState((prev) => {
|
||||
if (!prev) return null;
|
||||
setModelState(prev => {
|
||||
if (!prev) return null
|
||||
return {
|
||||
...prev,
|
||||
currentModelId: modelId,
|
||||
};
|
||||
});
|
||||
setIsLoading(false);
|
||||
};
|
||||
}
|
||||
})
|
||||
setIsLoading(false)
|
||||
}
|
||||
|
||||
// Register handlers - setModelStateChangedHandler immediately calls with current state
|
||||
client.setModelStateChangedHandler(handleModelStateChanged);
|
||||
client.setModelChangedHandler(handleModelChanged);
|
||||
client.setModelStateChangedHandler(handleModelStateChanged)
|
||||
client.setModelChangedHandler(handleModelChanged)
|
||||
|
||||
return () => {
|
||||
// Clear handlers on unmount
|
||||
client.setModelStateChangedHandler(() => {});
|
||||
client.setModelChangedHandler(() => {});
|
||||
};
|
||||
}, [client]);
|
||||
client.setModelStateChangedHandler(() => {})
|
||||
client.setModelChangedHandler(() => {})
|
||||
}
|
||||
}, [client])
|
||||
|
||||
const availableModels = useMemo(
|
||||
() => modelState?.availableModels ?? [],
|
||||
[modelState]
|
||||
);
|
||||
[modelState],
|
||||
)
|
||||
|
||||
const currentModelId = modelState?.currentModelId ?? null;
|
||||
const currentModelId = modelState?.currentModelId ?? null
|
||||
|
||||
const currentModel = useMemo(
|
||||
() =>
|
||||
availableModels.find((m) => m.modelId === currentModelId) ?? null,
|
||||
[availableModels, currentModelId]
|
||||
);
|
||||
() => availableModels.find(m => m.modelId === currentModelId) ?? null,
|
||||
[availableModels, currentModelId],
|
||||
)
|
||||
|
||||
const setModel = useCallback(
|
||||
async (modelId: string) => {
|
||||
if (!modelState) {
|
||||
throw new Error("Model selection not supported");
|
||||
throw new Error('Model selection not supported')
|
||||
}
|
||||
setIsLoading(true);
|
||||
setIsLoading(true)
|
||||
try {
|
||||
await client.setSessionModel(modelId);
|
||||
localStorage.setItem("acp_model_id", modelId);
|
||||
await client.setSessionModel(modelId)
|
||||
localStorage.setItem('acp_model_id', modelId)
|
||||
// The model_changed event will update the state
|
||||
} catch (error) {
|
||||
setIsLoading(false);
|
||||
throw error;
|
||||
setIsLoading(false)
|
||||
throw error
|
||||
}
|
||||
},
|
||||
[client, modelState]
|
||||
);
|
||||
[client, modelState],
|
||||
)
|
||||
|
||||
return {
|
||||
supportsModelSelection: modelState !== null && availableModels.length > 0,
|
||||
@@ -107,5 +110,5 @@ export function useModels(client: ACPClient): UseModelsResult {
|
||||
currentModel,
|
||||
setModel,
|
||||
isLoading,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,30 +1,30 @@
|
||||
import { useState, useEffect, useRef, useCallback } from "react";
|
||||
import QrScanner from "qr-scanner";
|
||||
import { useState, useEffect, useRef, useCallback } from 'react'
|
||||
import QrScanner from 'qr-scanner'
|
||||
|
||||
/** QR code data format for scanning */
|
||||
export interface QRCodeData {
|
||||
url: string;
|
||||
token: string;
|
||||
url: string
|
||||
token: string
|
||||
}
|
||||
|
||||
export interface UseQRScannerOptions {
|
||||
/** Called when a valid QR code is scanned */
|
||||
onScan: (data: QRCodeData) => void;
|
||||
onScan: (data: QRCodeData) => void
|
||||
/** Called when an error occurs */
|
||||
onError?: (error: string) => void;
|
||||
onError?: (error: string) => void
|
||||
}
|
||||
|
||||
export interface UseQRScannerResult {
|
||||
/** Whether the scanner is currently active */
|
||||
isScanning: boolean;
|
||||
isScanning: boolean
|
||||
/** Ref to attach to the video element */
|
||||
videoRef: React.RefObject<HTMLVideoElement | null>;
|
||||
videoRef: React.RefObject<HTMLVideoElement | null>
|
||||
/** Start scanning */
|
||||
startScanning: () => void;
|
||||
startScanning: () => void
|
||||
/** Stop scanning */
|
||||
stopScanning: () => void;
|
||||
stopScanning: () => void
|
||||
/** Scan QR code from a file (e.g., from photo album) */
|
||||
scanFromFile: (file: File) => Promise<void>;
|
||||
scanFromFile: (file: File) => Promise<void>
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -35,74 +35,74 @@ export function useQRScanner({
|
||||
onScan,
|
||||
onError,
|
||||
}: UseQRScannerOptions): UseQRScannerResult {
|
||||
const [isScanning, setIsScanning] = useState(false);
|
||||
const videoRef = useRef<HTMLVideoElement | null>(null);
|
||||
const qrScannerRef = useRef<QrScanner | null>(null);
|
||||
const [isScanning, setIsScanning] = useState(false)
|
||||
const videoRef = useRef<HTMLVideoElement | null>(null)
|
||||
const qrScannerRef = useRef<QrScanner | null>(null)
|
||||
|
||||
// Store callbacks in refs to avoid re-creating scanner when callbacks change
|
||||
// This allows callers to pass inline functions without causing re-renders
|
||||
const onScanRef = useRef(onScan);
|
||||
const onErrorRef = useRef(onError);
|
||||
const onScanRef = useRef(onScan)
|
||||
const onErrorRef = useRef(onError)
|
||||
|
||||
// Keep refs up to date
|
||||
useEffect(() => {
|
||||
onScanRef.current = onScan;
|
||||
onErrorRef.current = onError;
|
||||
}, [onScan, onError]);
|
||||
onScanRef.current = onScan
|
||||
onErrorRef.current = onError
|
||||
}, [onScan, onError])
|
||||
|
||||
const startScanning = useCallback(() => {
|
||||
setIsScanning(true);
|
||||
}, []);
|
||||
setIsScanning(true)
|
||||
}, [])
|
||||
|
||||
const stopScanning = useCallback(() => {
|
||||
if (qrScannerRef.current) {
|
||||
qrScannerRef.current.stop();
|
||||
qrScannerRef.current.destroy();
|
||||
qrScannerRef.current = null;
|
||||
qrScannerRef.current.stop()
|
||||
qrScannerRef.current.destroy()
|
||||
qrScannerRef.current = null
|
||||
}
|
||||
setIsScanning(false);
|
||||
}, []);
|
||||
setIsScanning(false)
|
||||
}, [])
|
||||
|
||||
// Scan QR code from a file (photo album)
|
||||
const scanFromFile = useCallback(async (file: File) => {
|
||||
try {
|
||||
const result = await QrScanner.scanImage(file, {
|
||||
returnDetailedScanResult: true,
|
||||
});
|
||||
})
|
||||
|
||||
const data = JSON.parse(result.data) as QRCodeData;
|
||||
const data = JSON.parse(result.data) as QRCodeData
|
||||
if (data.url && data.token) {
|
||||
onScanRef.current(data);
|
||||
onScanRef.current(data)
|
||||
} else {
|
||||
onErrorRef.current?.("Invalid QR code: missing url or token");
|
||||
onErrorRef.current?.('Invalid QR code: missing url or token')
|
||||
}
|
||||
} catch (e) {
|
||||
const message = e instanceof Error ? e.message : "No QR code found";
|
||||
onErrorRef.current?.(message);
|
||||
const message = e instanceof Error ? e.message : 'No QR code found'
|
||||
onErrorRef.current?.(message)
|
||||
}
|
||||
}, []);
|
||||
}, [])
|
||||
|
||||
// Initialize scanner when isScanning becomes true
|
||||
useEffect(() => {
|
||||
if (!isScanning || !videoRef.current) return;
|
||||
if (!isScanning || !videoRef.current) return
|
||||
|
||||
let isCancelled = false;
|
||||
let scanner: QrScanner | null = null;
|
||||
let isCancelled = false
|
||||
let scanner: QrScanner | null = null
|
||||
|
||||
const initScanner = async () => {
|
||||
try {
|
||||
const newScanner = new QrScanner(
|
||||
videoRef.current!,
|
||||
(result) => {
|
||||
result => {
|
||||
try {
|
||||
const data = JSON.parse(result.data) as QRCodeData;
|
||||
const data = JSON.parse(result.data) as QRCodeData
|
||||
if (data.url && data.token) {
|
||||
// Stop scanning and notify
|
||||
newScanner.stop();
|
||||
newScanner.destroy();
|
||||
qrScannerRef.current = null;
|
||||
setIsScanning(false);
|
||||
onScanRef.current(data);
|
||||
newScanner.stop()
|
||||
newScanner.destroy()
|
||||
qrScannerRef.current = null
|
||||
setIsScanning(false)
|
||||
onScanRef.current(data)
|
||||
}
|
||||
} catch {
|
||||
// Not valid JSON, ignore
|
||||
@@ -112,46 +112,46 @@ export function useQRScanner({
|
||||
returnDetailedScanResult: true,
|
||||
highlightScanRegion: true,
|
||||
highlightCodeOutline: true,
|
||||
}
|
||||
);
|
||||
},
|
||||
)
|
||||
|
||||
if (isCancelled) {
|
||||
newScanner.destroy();
|
||||
return;
|
||||
newScanner.destroy()
|
||||
return
|
||||
}
|
||||
|
||||
scanner = newScanner;
|
||||
qrScannerRef.current = newScanner;
|
||||
await newScanner.start();
|
||||
scanner = newScanner
|
||||
qrScannerRef.current = newScanner
|
||||
await newScanner.start()
|
||||
|
||||
if (isCancelled) {
|
||||
newScanner.stop();
|
||||
newScanner.destroy();
|
||||
qrScannerRef.current = null;
|
||||
newScanner.stop()
|
||||
newScanner.destroy()
|
||||
qrScannerRef.current = null
|
||||
}
|
||||
} catch (e) {
|
||||
if (!isCancelled) {
|
||||
onErrorRef.current?.(`Camera error: ${(e as Error).message}`);
|
||||
setIsScanning(false);
|
||||
onErrorRef.current?.(`Camera error: ${(e as Error).message}`)
|
||||
setIsScanning(false)
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
initScanner();
|
||||
initScanner()
|
||||
|
||||
return () => {
|
||||
isCancelled = true;
|
||||
isCancelled = true
|
||||
if (scanner) {
|
||||
scanner.stop();
|
||||
scanner.destroy();
|
||||
scanner.stop()
|
||||
scanner.destroy()
|
||||
}
|
||||
if (qrScannerRef.current) {
|
||||
qrScannerRef.current.stop();
|
||||
qrScannerRef.current.destroy();
|
||||
qrScannerRef.current = null;
|
||||
qrScannerRef.current.stop()
|
||||
qrScannerRef.current.destroy()
|
||||
qrScannerRef.current = null
|
||||
}
|
||||
};
|
||||
}, [isScanning]); // Only depend on isScanning, callbacks are accessed via refs
|
||||
}
|
||||
}, [isScanning]) // Only depend on isScanning, callbacks are accessed via refs
|
||||
|
||||
return {
|
||||
isScanning,
|
||||
@@ -159,5 +159,5 @@ export function useQRScanner({
|
||||
startScanning,
|
||||
stopScanning,
|
||||
scanFromFile,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,25 +1,25 @@
|
||||
import { useEffect, useRef, useCallback } from "react";
|
||||
import { connectSSE, disconnectSSE } from "../api/sse";
|
||||
import type { SessionEvent } from "../types";
|
||||
import { useEffect, useRef, useCallback } from 'react'
|
||||
import { connectSSE, disconnectSSE } from '../api/sse'
|
||||
import type { SessionEvent } from '../types'
|
||||
|
||||
export function useSSE(
|
||||
sessionId: string | null,
|
||||
onEvent: (event: SessionEvent) => void,
|
||||
) {
|
||||
const onEventRef = useRef(onEvent);
|
||||
onEventRef.current = onEvent;
|
||||
const onEventRef = useRef(onEvent)
|
||||
onEventRef.current = onEvent
|
||||
|
||||
const stableCallback = useCallback((event: SessionEvent) => {
|
||||
onEventRef.current(event);
|
||||
}, []);
|
||||
onEventRef.current(event)
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
if (!sessionId) return;
|
||||
if (!sessionId) return
|
||||
|
||||
connectSSE(sessionId, stableCallback);
|
||||
connectSSE(sessionId, stableCallback)
|
||||
|
||||
return () => {
|
||||
disconnectSSE();
|
||||
};
|
||||
}, [sessionId, stableCallback]);
|
||||
disconnectSSE()
|
||||
}
|
||||
}, [sessionId, stableCallback])
|
||||
}
|
||||
|
||||
@@ -1,110 +1,126 @@
|
||||
import { useState, useCallback } from "react";
|
||||
import { useState, useCallback } from 'react'
|
||||
|
||||
export interface TokenEntry {
|
||||
id: string;
|
||||
token: string;
|
||||
label: string;
|
||||
id: string
|
||||
token: string
|
||||
label: string
|
||||
}
|
||||
|
||||
const TOKENS_KEY = "rcs_tokens";
|
||||
const ACTIVE_TOKEN_KEY = "rcs_uuid";
|
||||
const DEFAULT_ID = "__default__";
|
||||
const TOKENS_KEY = 'rcs_tokens'
|
||||
const ACTIVE_TOKEN_KEY = 'rcs_uuid'
|
||||
const DEFAULT_ID = '__default__'
|
||||
|
||||
function generateId(): string {
|
||||
return `tk_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 8)}`;
|
||||
return `tk_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 8)}`
|
||||
}
|
||||
|
||||
/** Ensure the existing rcs_uuid is present as the default token entry */
|
||||
function ensureDefault(tokens: TokenEntry[]): TokenEntry[] {
|
||||
if (tokens.some((t) => t.id === DEFAULT_ID)) return tokens;
|
||||
let uuid: string | null = null;
|
||||
if (tokens.some(t => t.id === DEFAULT_ID)) return tokens
|
||||
let uuid: string | null = null
|
||||
try {
|
||||
uuid = localStorage.getItem("rcs_uuid");
|
||||
uuid = localStorage.getItem('rcs_uuid')
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
if (!uuid) return tokens;
|
||||
return [{ id: DEFAULT_ID, token: uuid, label: "Default" }, ...tokens];
|
||||
if (!uuid) return tokens
|
||||
return [{ id: DEFAULT_ID, token: uuid, label: 'Default' }, ...tokens]
|
||||
}
|
||||
|
||||
function loadTokens(): TokenEntry[] {
|
||||
let tokens: TokenEntry[] = [];
|
||||
let tokens: TokenEntry[] = []
|
||||
try {
|
||||
const raw = localStorage.getItem(TOKENS_KEY);
|
||||
const raw = localStorage.getItem(TOKENS_KEY)
|
||||
if (raw) {
|
||||
const parsed = JSON.parse(raw);
|
||||
if (Array.isArray(parsed)) tokens = parsed;
|
||||
const parsed = JSON.parse(raw)
|
||||
if (Array.isArray(parsed)) tokens = parsed
|
||||
}
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
return ensureDefault(tokens);
|
||||
return ensureDefault(tokens)
|
||||
}
|
||||
|
||||
function loadActiveTokenId(tokens: TokenEntry[]): string {
|
||||
// Try saved active token
|
||||
try {
|
||||
const saved = localStorage.getItem(ACTIVE_TOKEN_KEY);
|
||||
if (saved && tokens.some((t) => t.id === saved)) return saved;
|
||||
const saved = localStorage.getItem(ACTIVE_TOKEN_KEY)
|
||||
if (saved && tokens.some(t => t.id === saved)) return saved
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
// Fall back to default (rcs_uuid) entry
|
||||
const defaultEntry = tokens.find((t) => t.id === DEFAULT_ID);
|
||||
if (defaultEntry) return defaultEntry.id;
|
||||
const defaultEntry = tokens.find(t => t.id === DEFAULT_ID)
|
||||
if (defaultEntry) return defaultEntry.id
|
||||
// Fall back to first entry
|
||||
return tokens[0]?.id ?? DEFAULT_ID;
|
||||
return tokens[0]?.id ?? DEFAULT_ID
|
||||
}
|
||||
|
||||
export function useTokens() {
|
||||
const [tokens, setTokens] = useState<TokenEntry[]>(loadTokens);
|
||||
const [activeTokenId, setActiveTokenIdState] = useState<string>(() => loadActiveTokenId(loadTokens()));
|
||||
const [tokens, setTokens] = useState<TokenEntry[]>(loadTokens)
|
||||
const [activeTokenId, setActiveTokenIdState] = useState<string>(() =>
|
||||
loadActiveTokenId(loadTokens()),
|
||||
)
|
||||
|
||||
const persistTokens = useCallback((next: TokenEntry[]) => {
|
||||
setTokens(next);
|
||||
setTokens(next)
|
||||
try {
|
||||
localStorage.setItem(TOKENS_KEY, JSON.stringify(next));
|
||||
localStorage.setItem(TOKENS_KEY, JSON.stringify(next))
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
}, []);
|
||||
}, [])
|
||||
|
||||
const setActiveTokenId = useCallback((id: string) => {
|
||||
setActiveTokenIdState(id);
|
||||
setActiveTokenIdState(id)
|
||||
try {
|
||||
localStorage.setItem(ACTIVE_TOKEN_KEY, id);
|
||||
location.reload(); // Reload to ensure api client picks up new token from localStorage
|
||||
localStorage.setItem(ACTIVE_TOKEN_KEY, id)
|
||||
location.reload() // Reload to ensure api client picks up new token from localStorage
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
}, []);
|
||||
}, [])
|
||||
|
||||
const addToken = useCallback((token: string, label: string): string | null => {
|
||||
const trimmed = token.trim();
|
||||
if (!trimmed) return "Token is required";
|
||||
const entry: TokenEntry = { id: generateId(), token: trimmed, label: label.trim() || trimmed.slice(0, 8) };
|
||||
const next = [...tokens, entry];
|
||||
persistTokens(next);
|
||||
return null;
|
||||
}, [tokens, persistTokens]);
|
||||
const addToken = useCallback(
|
||||
(token: string, label: string): string | null => {
|
||||
const trimmed = token.trim()
|
||||
if (!trimmed) return 'Token is required'
|
||||
const entry: TokenEntry = {
|
||||
id: generateId(),
|
||||
token: trimmed,
|
||||
label: label.trim() || trimmed.slice(0, 8),
|
||||
}
|
||||
const next = [...tokens, entry]
|
||||
persistTokens(next)
|
||||
return null
|
||||
},
|
||||
[tokens, persistTokens],
|
||||
)
|
||||
|
||||
const removeToken = useCallback((id: string) => {
|
||||
if (id === DEFAULT_ID) return; // Cannot remove default
|
||||
const next = tokens.filter((t) => t.id !== id);
|
||||
persistTokens(next);
|
||||
if (activeTokenId === id) {
|
||||
setActiveTokenId(DEFAULT_ID);
|
||||
}
|
||||
}, [tokens, persistTokens, activeTokenId, setActiveTokenId]);
|
||||
const removeToken = useCallback(
|
||||
(id: string) => {
|
||||
if (id === DEFAULT_ID) return // Cannot remove default
|
||||
const next = tokens.filter(t => t.id !== id)
|
||||
persistTokens(next)
|
||||
if (activeTokenId === id) {
|
||||
setActiveTokenId(DEFAULT_ID)
|
||||
}
|
||||
},
|
||||
[tokens, persistTokens, activeTokenId, setActiveTokenId],
|
||||
)
|
||||
|
||||
const updateToken = useCallback((id: string, label: string) => {
|
||||
const next = tokens.map((t) => t.id === id ? { ...t, label } : t);
|
||||
persistTokens(next);
|
||||
}, [tokens, persistTokens]);
|
||||
const updateToken = useCallback(
|
||||
(id: string, label: string) => {
|
||||
const next = tokens.map(t => (t.id === id ? { ...t, label } : t))
|
||||
persistTokens(next)
|
||||
},
|
||||
[tokens, persistTokens],
|
||||
)
|
||||
|
||||
const activeToken = tokens.find((t) => t.id === activeTokenId) ?? tokens[0] ?? null;
|
||||
const activeLabel = activeToken?.label ?? "Default";
|
||||
const activeTokenValue = activeToken?.token ?? null;
|
||||
const activeToken =
|
||||
tokens.find(t => t.id === activeTokenId) ?? tokens[0] ?? null
|
||||
const activeLabel = activeToken?.label ?? 'Default'
|
||||
const activeTokenValue = activeToken?.token ?? null
|
||||
|
||||
return {
|
||||
tokens,
|
||||
@@ -116,5 +132,5 @@ export function useTokens() {
|
||||
addToken,
|
||||
removeToken,
|
||||
updateToken,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,8 +3,6 @@
|
||||
|
||||
@import "tailwindcss";
|
||||
|
||||
|
||||
|
||||
/* ============================================================
|
||||
Theme — Refined stone palette (warm gray, not beige)
|
||||
Hue shifted from 85 (yellow-cream) to 65 (warm stone)
|
||||
@@ -17,43 +15,43 @@
|
||||
--font-mono: "JetBrains Mono", monospace;
|
||||
|
||||
/* Brand — signature orange (unchanged) */
|
||||
--color-brand: #C96442;
|
||||
--color-brand-light: #B55838;
|
||||
--color-brand: #c96442;
|
||||
--color-brand-light: #b55838;
|
||||
--color-brand-subtle: oklch(0.65 0.12 30 / 0.08);
|
||||
|
||||
/* Surfaces — warm stone gray (not yellow-beige) */
|
||||
--color-surface-0: #EFEEE9;
|
||||
--color-surface-1: #F6F5F2;
|
||||
--color-surface-2: #FBFAF8;
|
||||
--color-surface-3: #DFDDD8;
|
||||
--color-surface-0: #efeee9;
|
||||
--color-surface-1: #f6f5f2;
|
||||
--color-surface-2: #fbfaf8;
|
||||
--color-surface-3: #dfddd8;
|
||||
|
||||
/* Text — warm near-black tones */
|
||||
--color-text-primary: #1A1917;
|
||||
--color-text-secondary: #5E5A54;
|
||||
--color-text-primary: #1a1917;
|
||||
--color-text-secondary: #5e5a54;
|
||||
--color-text-muted: #969088;
|
||||
|
||||
/* Inverted — for user message bubbles */
|
||||
--color-bg-inverted: #2C2A27;
|
||||
--color-text-inverted: #F6F5F2;
|
||||
--color-bg-inverted: #2c2a27;
|
||||
--color-text-inverted: #f6f5f2;
|
||||
|
||||
/* User bubble — brand-tinted surface */
|
||||
--color-user-bubble: #C96442;
|
||||
--color-user-bubble-border: #B55838;
|
||||
--color-user-bubble: #c96442;
|
||||
--color-user-bubble-border: #b55838;
|
||||
|
||||
/* Warning — refined amber (less construction-zone) */
|
||||
--color-warning-bg: oklch(0.96 0.02 85);
|
||||
--color-warning-border: oklch(0.75 0.14 75);
|
||||
--color-warning-text: oklch(0.40 0.08 60);
|
||||
--color-warning-text: oklch(0.4 0.08 60);
|
||||
|
||||
/* Status */
|
||||
--color-status-active: #5D8A3C;
|
||||
--color-status-running: #3D72A8;
|
||||
--color-status-idle: #7C3aed;
|
||||
--color-status-error: #B83B31;
|
||||
--color-status-warning: #B88630;
|
||||
--color-status-active: #5d8a3c;
|
||||
--color-status-running: #3d72a8;
|
||||
--color-status-idle: #7c3aed;
|
||||
--color-status-error: #b83b31;
|
||||
--color-status-warning: #b88630;
|
||||
|
||||
/* Tool card */
|
||||
--color-tool-card: #F6F5F2;
|
||||
--color-tool-card: #f6f5f2;
|
||||
|
||||
/* shadcn/ui tokens (oklch — warm stone hue ~65) */
|
||||
--color-background: oklch(0.955 0.006 65);
|
||||
@@ -74,9 +72,9 @@
|
||||
|
||||
/* Border / Input / Ring */
|
||||
--color-border: oklch(0.905 0.008 65);
|
||||
--color-border-light: #DFDDD8;
|
||||
--color-border-light: #dfddd8;
|
||||
--color-input: oklch(0.905 0.008 65);
|
||||
--color-ring: oklch(0.65 0.10 40);
|
||||
--color-ring: oklch(0.65 0.1 40);
|
||||
|
||||
/* Default utility values */
|
||||
--default-border-color: var(--color-border);
|
||||
@@ -90,20 +88,20 @@
|
||||
Dark mode — warm stone dark palette
|
||||
============================================================ */
|
||||
.dark {
|
||||
--color-surface-0: #1A1917;
|
||||
--color-surface-0: #1a1917;
|
||||
--color-surface-1: #222120;
|
||||
--color-surface-2: #2C2A28;
|
||||
--color-surface-3: #3A3835;
|
||||
--color-text-primary: #EFEEE9;
|
||||
--color-surface-2: #2c2a28;
|
||||
--color-surface-3: #3a3835;
|
||||
--color-text-primary: #efeee9;
|
||||
--color-text-secondary: #969088;
|
||||
--color-text-muted: #5E5A54;
|
||||
--color-bg-inverted: #F6F5F2;
|
||||
--color-text-inverted: #2C2A28;
|
||||
--color-user-bubble: #C96442;
|
||||
--color-user-bubble-border: #B55838;
|
||||
--color-border: #3A3835;
|
||||
--color-border-light: #2C2A28;
|
||||
--color-tool-card: #2C2A28;
|
||||
--color-text-muted: #5e5a54;
|
||||
--color-bg-inverted: #f6f5f2;
|
||||
--color-text-inverted: #2c2a28;
|
||||
--color-user-bubble: #c96442;
|
||||
--color-user-bubble-border: #b55838;
|
||||
--color-border: #3a3835;
|
||||
--color-border-light: #2c2a28;
|
||||
--color-tool-card: #2c2a28;
|
||||
--color-warning-bg: oklch(0.22 0.03 75);
|
||||
--color-warning-border: oklch(0.62 0.12 75);
|
||||
--color-warning-text: oklch(0.82 0.08 85);
|
||||
@@ -149,8 +147,13 @@
|
||||
}
|
||||
|
||||
@keyframes glimmer-pulse {
|
||||
0%, 100% { opacity: 0.5; }
|
||||
50% { opacity: 1; }
|
||||
0%,
|
||||
100% {
|
||||
opacity: 0.5;
|
||||
}
|
||||
50% {
|
||||
opacity: 1;
|
||||
}
|
||||
}
|
||||
|
||||
/* ============================================================
|
||||
@@ -159,7 +162,7 @@
|
||||
|
||||
/* Chat input — warm orange focus ring */
|
||||
.chat-input-focus:focus-within {
|
||||
box-shadow: 0 0 0 2px oklch(0.65 0.12 30 / 0.20);
|
||||
box-shadow: 0 0 0 2px oklch(0.65 0.12 30 / 0.2);
|
||||
}
|
||||
|
||||
/* Markdown content in message bubbles */
|
||||
@@ -190,9 +193,9 @@
|
||||
*,
|
||||
::before,
|
||||
::after {
|
||||
animation-duration: 0.01ms !important;
|
||||
animation-iteration-count: 1 !important;
|
||||
transition-duration: 0.01ms !important;
|
||||
animation-duration: 0.01ms;
|
||||
animation-iteration-count: 1;
|
||||
transition-duration: 0.01ms;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -200,13 +203,27 @@
|
||||
Animations — Anthropic entrance effects
|
||||
============================================================ */
|
||||
@keyframes fadeUp {
|
||||
from { opacity: 0; transform: translateY(24px); }
|
||||
to { opacity: 1; transform: translateY(0); }
|
||||
from {
|
||||
opacity: 0;
|
||||
transform: translateY(24px);
|
||||
}
|
||||
to {
|
||||
opacity: 1;
|
||||
transform: translateY(0);
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes typing-bounce {
|
||||
0%, 60%, 100% { transform: translateY(0); opacity: 0.5; }
|
||||
30% { transform: translateY(-5px); opacity: 1; }
|
||||
0%,
|
||||
60%,
|
||||
100% {
|
||||
transform: translateY(0);
|
||||
opacity: 0.5;
|
||||
}
|
||||
30% {
|
||||
transform: translateY(-5px);
|
||||
opacity: 1;
|
||||
}
|
||||
}
|
||||
|
||||
/* Typing indicator dots */
|
||||
@@ -223,5 +240,9 @@
|
||||
background: var(--color-brand);
|
||||
animation: typing-bounce 1.2s ease-in-out infinite;
|
||||
}
|
||||
.chat-typing-indicator span:nth-child(2) { animation-delay: 0.2s; }
|
||||
.chat-typing-indicator span:nth-child(3) { animation-delay: 0.4s; }
|
||||
.chat-typing-indicator span:nth-child(2) {
|
||||
animation-delay: 0.2s;
|
||||
}
|
||||
.chat-typing-indicator span:nth-child(3) {
|
||||
animation-delay: 0.4s;
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { SetStateAction } from "react";
|
||||
import type { SetStateAction } from 'react'
|
||||
import {
|
||||
apiFetchSession,
|
||||
apiFetchSessionHistory,
|
||||
@@ -7,9 +7,9 @@ import {
|
||||
apiSendControl,
|
||||
apiInterrupt,
|
||||
getUuid,
|
||||
} from "../api/client";
|
||||
import { generateMessageUuid } from "./utils";
|
||||
import type { SessionEvent, EventPayload } from "../types";
|
||||
} from '../api/client'
|
||||
import { generateMessageUuid } from './utils'
|
||||
import type { SessionEvent, EventPayload } from '../types'
|
||||
import type {
|
||||
ThreadEntry,
|
||||
ToolCallData,
|
||||
@@ -19,352 +19,405 @@ import type {
|
||||
ToolCallEntry,
|
||||
UserMessageImage,
|
||||
PendingPermission,
|
||||
} from "./types";
|
||||
} from './types'
|
||||
|
||||
// SSE Event Bus — 复用自 rcs-transport.ts,仅保留连接管理
|
||||
type SSEEventHandler = (event: SessionEvent) => void;
|
||||
type SSEEventHandler = (event: SessionEvent) => void
|
||||
|
||||
class SSEBus {
|
||||
private listeners: Set<SSEEventHandler> = new Set();
|
||||
private eventSource: EventSource | null = null;
|
||||
private listeners: Set<SSEEventHandler> = new Set()
|
||||
private eventSource: EventSource | null = null
|
||||
|
||||
onEvent(handler: SSEEventHandler): () => void {
|
||||
this.listeners.add(handler);
|
||||
return () => this.listeners.delete(handler);
|
||||
this.listeners.add(handler)
|
||||
return () => this.listeners.delete(handler)
|
||||
}
|
||||
|
||||
connect(sessionId: string): void {
|
||||
this.disconnect();
|
||||
const uuid = getUuid();
|
||||
const url = `/web/sessions/${sessionId}/events?uuid=${encodeURIComponent(uuid)}`;
|
||||
const es = new EventSource(url);
|
||||
this.eventSource = es;
|
||||
this.disconnect()
|
||||
const uuid = getUuid()
|
||||
const url = `/web/sessions/${sessionId}/events?uuid=${encodeURIComponent(uuid)}`
|
||||
const es = new EventSource(url)
|
||||
this.eventSource = es
|
||||
|
||||
es.addEventListener("message", (e: MessageEvent) => {
|
||||
es.addEventListener('message', (e: MessageEvent) => {
|
||||
try {
|
||||
const data = JSON.parse(e.data) as SessionEvent;
|
||||
const data = JSON.parse(e.data) as SessionEvent
|
||||
for (const handler of this.listeners) {
|
||||
handler(data);
|
||||
handler(data)
|
||||
}
|
||||
} catch {
|
||||
// ignore parse errors
|
||||
}
|
||||
});
|
||||
})
|
||||
}
|
||||
|
||||
disconnect(): void {
|
||||
if (this.eventSource) {
|
||||
this.eventSource.close();
|
||||
this.eventSource = null;
|
||||
this.eventSource.close()
|
||||
this.eventSource = null
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 全局 SSE bus 实例
|
||||
export const sseBus = new SSEBus();
|
||||
export const sseBus = new SSEBus()
|
||||
|
||||
// =============================================================================
|
||||
// RCS Chat Adapter — 将 SSE 事件转为 ThreadEntry
|
||||
// =============================================================================
|
||||
|
||||
function mapToolStatus(status: string): ToolCallStatus {
|
||||
if (status === "completed") return "complete";
|
||||
if (status === "failed") return "error";
|
||||
return "running";
|
||||
if (status === 'completed') return 'complete'
|
||||
if (status === 'failed') return 'error'
|
||||
return 'running'
|
||||
}
|
||||
|
||||
function extractEventText(payload: EventPayload): string {
|
||||
if (typeof payload.content === "string") return payload.content;
|
||||
if (payload.message && typeof payload.message === "object") {
|
||||
const msg = payload.message as Record<string, unknown>;
|
||||
if (typeof msg.content === "string") return msg.content;
|
||||
if (typeof payload.content === 'string') return payload.content
|
||||
if (payload.message && typeof payload.message === 'object') {
|
||||
const msg = payload.message as Record<string, unknown>
|
||||
if (typeof msg.content === 'string') return msg.content
|
||||
if (Array.isArray(msg.content)) {
|
||||
return (msg.content as Array<Record<string, unknown>>)
|
||||
.filter((b) => b.type === "text" && typeof b.text === "string")
|
||||
.map((b) => b.text as string)
|
||||
.join("");
|
||||
.filter(b => b.type === 'text' && typeof b.text === 'string')
|
||||
.map(b => b.text as string)
|
||||
.join('')
|
||||
}
|
||||
}
|
||||
return "";
|
||||
return ''
|
||||
}
|
||||
|
||||
function findToolCallIndex(entries: ThreadEntry[], toolCallId: string): number {
|
||||
for (let i = entries.length - 1; i >= 0; i--) {
|
||||
const entry = entries[i];
|
||||
if (entry && entry.type === "tool_call" && entry.toolCall.id === toolCallId) {
|
||||
return i;
|
||||
const entry = entries[i]
|
||||
if (
|
||||
entry &&
|
||||
entry.type === 'tool_call' &&
|
||||
entry.toolCall.id === toolCallId
|
||||
) {
|
||||
return i
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
return -1
|
||||
}
|
||||
|
||||
export class RCSChatAdapter {
|
||||
private sessionId: string;
|
||||
private setEntries: React.Dispatch<SetStateAction<ThreadEntry[]>>;
|
||||
private unsub: (() => void) | null = null;
|
||||
private onStatusChange?: (status: string) => void;
|
||||
private onError?: (error: string) => void;
|
||||
private onPermissionRequest?: (permission: PendingPermission) => void;
|
||||
private sessionId: string
|
||||
private setEntries: React.Dispatch<SetStateAction<ThreadEntry[]>>
|
||||
private unsub: (() => void) | null = null
|
||||
private onStatusChange?: (status: string) => void
|
||||
private onError?: (error: string) => void
|
||||
private onPermissionRequest?: (permission: PendingPermission) => void
|
||||
|
||||
constructor(
|
||||
sessionId: string,
|
||||
setEntries: React.Dispatch<SetStateAction<ThreadEntry[]>>,
|
||||
options?: {
|
||||
onStatusChange?: (status: string) => void;
|
||||
onError?: (error: string) => void;
|
||||
onPermissionRequest?: (permission: PendingPermission) => void;
|
||||
onStatusChange?: (status: string) => void
|
||||
onError?: (error: string) => void
|
||||
onPermissionRequest?: (permission: PendingPermission) => void
|
||||
},
|
||||
) {
|
||||
this.sessionId = sessionId;
|
||||
this.setEntries = setEntries;
|
||||
this.onStatusChange = options?.onStatusChange;
|
||||
this.onError = options?.onError;
|
||||
this.onPermissionRequest = options?.onPermissionRequest;
|
||||
this.sessionId = sessionId
|
||||
this.setEntries = setEntries
|
||||
this.onStatusChange = options?.onStatusChange
|
||||
this.onError = options?.onError
|
||||
this.onPermissionRequest = options?.onPermissionRequest
|
||||
}
|
||||
|
||||
/** 初始化:绑定会话、加载历史、连接 SSE */
|
||||
async init(): Promise<void> {
|
||||
try {
|
||||
await apiBind(this.sessionId);
|
||||
await apiBind(this.sessionId)
|
||||
} catch {
|
||||
// may already be bound
|
||||
}
|
||||
|
||||
await this.loadHistory();
|
||||
this.connectSSE();
|
||||
await this.loadHistory()
|
||||
this.connectSSE()
|
||||
}
|
||||
|
||||
/** 加载历史事件并转为 ThreadEntry */
|
||||
async loadHistory(): Promise<void> {
|
||||
const { events } = await apiFetchSessionHistory(this.sessionId);
|
||||
if (!events || events.length === 0) return;
|
||||
const { events } = await apiFetchSessionHistory(this.sessionId)
|
||||
if (!events || events.length === 0) return
|
||||
|
||||
const historyEntries: ThreadEntry[] = [];
|
||||
let currentAssistant: AssistantMessageEntry | null = null;
|
||||
const historyEntries: ThreadEntry[] = []
|
||||
let currentAssistant: AssistantMessageEntry | null = null
|
||||
|
||||
const flushAssistant = () => {
|
||||
if (currentAssistant) {
|
||||
historyEntries.push(currentAssistant);
|
||||
currentAssistant = null;
|
||||
historyEntries.push(currentAssistant)
|
||||
currentAssistant = null
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
for (const event of events) {
|
||||
const payload = event.payload || ({} as EventPayload);
|
||||
const payload = event.payload || ({} as EventPayload)
|
||||
|
||||
if (event.type === "user") {
|
||||
if (event.direction === "outbound") continue; // skip echoed user messages
|
||||
flushAssistant();
|
||||
const text = extractEventText(payload);
|
||||
if (event.type === 'user') {
|
||||
if (event.direction === 'outbound') continue // skip echoed user messages
|
||||
flushAssistant()
|
||||
const text = extractEventText(payload)
|
||||
if (text) {
|
||||
historyEntries.push({
|
||||
type: "user_message",
|
||||
type: 'user_message',
|
||||
id: event.id || `hist-user-${historyEntries.length}`,
|
||||
content: text,
|
||||
});
|
||||
})
|
||||
}
|
||||
} else if (event.type === "assistant") {
|
||||
flushAssistant();
|
||||
const text = extractEventText(payload);
|
||||
const toolParts: ThreadEntry[] = [];
|
||||
} else if (event.type === 'assistant') {
|
||||
flushAssistant()
|
||||
const text = extractEventText(payload)
|
||||
const toolParts: ThreadEntry[] = []
|
||||
|
||||
const msg = payload.message as Record<string, unknown> | undefined;
|
||||
if (msg && typeof msg === "object" && Array.isArray(msg.content)) {
|
||||
const msg = payload.message as Record<string, unknown> | undefined
|
||||
if (msg && typeof msg === 'object' && Array.isArray(msg.content)) {
|
||||
for (const block of msg.content as Array<Record<string, unknown>>) {
|
||||
if (block.type === "tool_use") {
|
||||
if (block.type === 'tool_use') {
|
||||
toolParts.push({
|
||||
type: "tool_call",
|
||||
type: 'tool_call',
|
||||
toolCall: {
|
||||
id: (block.id as string) || `hist-tool-${historyEntries.length}`,
|
||||
title: (block.name as string) || "tool",
|
||||
status: "complete",
|
||||
id:
|
||||
(block.id as string) ||
|
||||
`hist-tool-${historyEntries.length}`,
|
||||
title: (block.name as string) || 'tool',
|
||||
status: 'complete',
|
||||
rawInput: (block.input as Record<string, unknown>) || {},
|
||||
},
|
||||
});
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (text || toolParts.length > 0) {
|
||||
currentAssistant = {
|
||||
type: "assistant_message",
|
||||
type: 'assistant_message',
|
||||
id: event.id || `hist-asst-${historyEntries.length}`,
|
||||
chunks: text ? [{ type: "message", text }] : [],
|
||||
};
|
||||
historyEntries.push(currentAssistant);
|
||||
chunks: text ? [{ type: 'message', text }] : [],
|
||||
}
|
||||
historyEntries.push(currentAssistant)
|
||||
// Push tool calls after assistant message
|
||||
for (const tp of toolParts) {
|
||||
historyEntries.push(tp);
|
||||
historyEntries.push(tp)
|
||||
}
|
||||
currentAssistant = null; // Tool calls are separate entries
|
||||
currentAssistant = null // Tool calls are separate entries
|
||||
}
|
||||
} else if (event.type === "tool_use") {
|
||||
const p = payload as Record<string, unknown>;
|
||||
} else if (event.type === 'tool_use') {
|
||||
const p = payload as Record<string, unknown>
|
||||
const tc: ToolCallEntry = {
|
||||
type: "tool_call",
|
||||
type: 'tool_call',
|
||||
toolCall: {
|
||||
id: (p.tool_call_id as string) || `hist-tool-${historyEntries.length}`,
|
||||
title: (p.tool_name as string) || "tool",
|
||||
status: "complete",
|
||||
id:
|
||||
(p.tool_call_id as string) ||
|
||||
`hist-tool-${historyEntries.length}`,
|
||||
title: (p.tool_name as string) || 'tool',
|
||||
status: 'complete',
|
||||
rawInput: (p.tool_input as Record<string, unknown>) || {},
|
||||
},
|
||||
};
|
||||
historyEntries.push(tc);
|
||||
} else if (event.type === "tool_result") {
|
||||
const p = payload as Record<string, unknown>;
|
||||
}
|
||||
historyEntries.push(tc)
|
||||
} else if (event.type === 'tool_result') {
|
||||
const p = payload as Record<string, unknown>
|
||||
// Find last tool call and update with output
|
||||
const idx = findToolCallIndex(historyEntries, (p.tool_call_id as string) || "");
|
||||
const idx = findToolCallIndex(
|
||||
historyEntries,
|
||||
(p.tool_call_id as string) || '',
|
||||
)
|
||||
if (idx >= 0) {
|
||||
const entry = historyEntries[idx] as ToolCallEntry;
|
||||
const entry = historyEntries[idx] as ToolCallEntry
|
||||
historyEntries[idx] = {
|
||||
type: "tool_call",
|
||||
type: 'tool_call',
|
||||
toolCall: {
|
||||
...entry.toolCall,
|
||||
rawOutput: { output: p.content || p.output || "" },
|
||||
rawOutput: { output: p.content || p.output || '' },
|
||||
},
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
flushAssistant();
|
||||
this.setEntries(historyEntries);
|
||||
flushAssistant()
|
||||
this.setEntries(historyEntries)
|
||||
}
|
||||
|
||||
/** 连接 SSE 事件流 */
|
||||
connectSSE(): void {
|
||||
sseBus.connect(this.sessionId);
|
||||
this.unsub = sseBus.onEvent((event) => this.handleEvent(event));
|
||||
sseBus.connect(this.sessionId)
|
||||
this.unsub = sseBus.onEvent(event => this.handleEvent(event))
|
||||
}
|
||||
|
||||
/** 断开 SSE */
|
||||
disconnect(): void {
|
||||
if (this.unsub) {
|
||||
this.unsub();
|
||||
this.unsub = null;
|
||||
this.unsub()
|
||||
this.unsub = null
|
||||
}
|
||||
sseBus.disconnect();
|
||||
sseBus.disconnect()
|
||||
}
|
||||
|
||||
/** 处理 SSE 事件 */
|
||||
handleEvent(event: SessionEvent): void {
|
||||
const type = event.type;
|
||||
const payload = event.payload || ({} as EventPayload);
|
||||
const type = event.type
|
||||
const payload = event.payload || ({} as EventPayload)
|
||||
|
||||
// Skip bridge init noise
|
||||
const serialized = JSON.stringify(event);
|
||||
if (/Remote Control connecting/i.test(serialized)) return;
|
||||
const serialized = JSON.stringify(event)
|
||||
if (/Remote Control connecting/i.test(serialized)) return
|
||||
|
||||
switch (type) {
|
||||
// ---- 助手消息 ----
|
||||
case "assistant": {
|
||||
const content = typeof payload.content === "string" ? payload.content : "";
|
||||
this.setEntries((prev) => {
|
||||
const lastEntry = prev[prev.length - 1];
|
||||
case 'assistant': {
|
||||
const content =
|
||||
typeof payload.content === 'string' ? payload.content : ''
|
||||
this.setEntries(prev => {
|
||||
const lastEntry = prev[prev.length - 1]
|
||||
|
||||
// If last entry is AssistantMessage, append to it
|
||||
if (lastEntry?.type === "assistant_message") {
|
||||
const lastChunk = lastEntry.chunks[lastEntry.chunks.length - 1];
|
||||
if (lastChunk?.type === "message") {
|
||||
if (lastEntry?.type === 'assistant_message') {
|
||||
const lastChunk = lastEntry.chunks[lastEntry.chunks.length - 1]
|
||||
if (lastChunk?.type === 'message') {
|
||||
return [
|
||||
...prev.slice(0, -1),
|
||||
{ ...lastEntry, chunks: [...lastEntry.chunks.slice(0, -1), { type: "message", text: lastChunk.text + content }] },
|
||||
];
|
||||
{
|
||||
...lastEntry,
|
||||
chunks: [
|
||||
...lastEntry.chunks.slice(0, -1),
|
||||
{ type: 'message', text: lastChunk.text + content },
|
||||
],
|
||||
},
|
||||
]
|
||||
}
|
||||
return [
|
||||
...prev.slice(0, -1),
|
||||
{ ...lastEntry, chunks: [...lastEntry.chunks, { type: "message", text: content }] },
|
||||
];
|
||||
{
|
||||
...lastEntry,
|
||||
chunks: [
|
||||
...lastEntry.chunks,
|
||||
{ type: 'message', text: content },
|
||||
],
|
||||
},
|
||||
]
|
||||
}
|
||||
|
||||
// Create new AssistantMessage
|
||||
if (content && content.trim()) {
|
||||
const newEntry: AssistantMessageEntry = {
|
||||
type: "assistant_message",
|
||||
type: 'assistant_message',
|
||||
id: `assistant-${Date.now()}`,
|
||||
chunks: [{ type: "message", text: content }],
|
||||
};
|
||||
return [...prev, newEntry];
|
||||
chunks: [{ type: 'message', text: content }],
|
||||
}
|
||||
return [...prev, newEntry]
|
||||
}
|
||||
return prev;
|
||||
});
|
||||
return prev
|
||||
})
|
||||
|
||||
// Check for embedded tool_use blocks
|
||||
const msg = payload.message as Record<string, unknown> | undefined;
|
||||
if (msg && typeof msg === "object" && Array.isArray(msg.content)) {
|
||||
const toolBlocks = (msg.content as Array<Record<string, unknown>>).filter((b) => b.type === "tool_use");
|
||||
const msg = payload.message as Record<string, unknown> | undefined
|
||||
if (msg && typeof msg === 'object' && Array.isArray(msg.content)) {
|
||||
const toolBlocks = (
|
||||
msg.content as Array<Record<string, unknown>>
|
||||
).filter(b => b.type === 'tool_use')
|
||||
for (const block of toolBlocks) {
|
||||
const toolCallId = (block.id as string) || `call-${Date.now()}-${Math.random().toString(16).slice(2, 8)}`;
|
||||
const toolCallId =
|
||||
(block.id as string) ||
|
||||
`call-${Date.now()}-${Math.random().toString(16).slice(2, 8)}`
|
||||
const toolData: ToolCallData = {
|
||||
id: toolCallId,
|
||||
title: (block.name as string) || "tool",
|
||||
status: "running",
|
||||
title: (block.name as string) || 'tool',
|
||||
status: 'running',
|
||||
rawInput: (block.input as Record<string, unknown>) || {},
|
||||
};
|
||||
this.setEntries((prev) => [...prev, { type: "tool_call", toolCall: toolData }]);
|
||||
}
|
||||
this.setEntries(prev => [
|
||||
...prev,
|
||||
{ type: 'tool_call', toolCall: toolData },
|
||||
])
|
||||
}
|
||||
}
|
||||
break;
|
||||
break
|
||||
}
|
||||
|
||||
// ---- 工具调用 ----
|
||||
case "tool_use": {
|
||||
const p = payload as Record<string, unknown>;
|
||||
const toolCallId = (p.tool_call_id as string) || `call-${Date.now()}`;
|
||||
case 'tool_use': {
|
||||
const p = payload as Record<string, unknown>
|
||||
const toolCallId = (p.tool_call_id as string) || `call-${Date.now()}`
|
||||
const toolData: ToolCallData = {
|
||||
id: toolCallId,
|
||||
title: (p.tool_name as string) || "tool",
|
||||
status: "running",
|
||||
title: (p.tool_name as string) || 'tool',
|
||||
status: 'running',
|
||||
rawInput: (p.tool_input as Record<string, unknown>) || {},
|
||||
};
|
||||
this.setEntries((prev) => [...prev, { type: "tool_call", toolCall: toolData }]);
|
||||
break;
|
||||
}
|
||||
this.setEntries(prev => [
|
||||
...prev,
|
||||
{ type: 'tool_call', toolCall: toolData },
|
||||
])
|
||||
break
|
||||
}
|
||||
|
||||
// ---- 工具结果 ----
|
||||
case "tool_result": {
|
||||
const p = payload as Record<string, unknown>;
|
||||
const callId = (p.tool_call_id as string) || "";
|
||||
this.setEntries((prev) => {
|
||||
const idx = findToolCallIndex(prev, callId);
|
||||
if (idx < 0) return prev;
|
||||
const entry = prev[idx] as ToolCallEntry;
|
||||
case 'tool_result': {
|
||||
const p = payload as Record<string, unknown>
|
||||
const callId = (p.tool_call_id as string) || ''
|
||||
this.setEntries(prev => {
|
||||
const idx = findToolCallIndex(prev, callId)
|
||||
if (idx < 0) return prev
|
||||
const entry = prev[idx] as ToolCallEntry
|
||||
return prev.map((e, i) =>
|
||||
i === idx
|
||||
? { type: "tool_call", toolCall: { ...entry.toolCall, status: "complete" as ToolCallStatus, rawOutput: { output: p.content || p.output || "" } } }
|
||||
? {
|
||||
type: 'tool_call',
|
||||
toolCall: {
|
||||
...entry.toolCall,
|
||||
status: 'complete' as ToolCallStatus,
|
||||
rawOutput: { output: p.content || p.output || '' },
|
||||
},
|
||||
}
|
||||
: e,
|
||||
);
|
||||
});
|
||||
break;
|
||||
)
|
||||
})
|
||||
break
|
||||
}
|
||||
|
||||
// ---- 权限请求 ----
|
||||
case "control_request":
|
||||
case "permission_request": {
|
||||
const req = payload.request as Record<string, unknown> | undefined;
|
||||
if (req && req.subtype === "can_use_tool") {
|
||||
const requestId = payload.request_id || "";
|
||||
const toolName = (req.tool_name as string) || "unknown";
|
||||
const toolInput = (req.input || req.tool_input || {}) as Record<string, unknown>;
|
||||
const description = (req.description as string) || "";
|
||||
case 'control_request':
|
||||
case 'permission_request': {
|
||||
const req = payload.request as Record<string, unknown> | undefined
|
||||
if (req && req.subtype === 'can_use_tool') {
|
||||
const requestId = payload.request_id || ''
|
||||
const toolName = (req.tool_name as string) || 'unknown'
|
||||
const toolInput = (req.input || req.tool_input || {}) as Record<
|
||||
string,
|
||||
unknown
|
||||
>
|
||||
const description = (req.description as string) || ''
|
||||
|
||||
// Update tool call status
|
||||
this.setEntries((prev) => {
|
||||
this.setEntries(prev => {
|
||||
// Find matching tool call
|
||||
const idx = [...prev].reverse().findIndex((e) => e.type === "tool_call");
|
||||
const idx = [...prev]
|
||||
.reverse()
|
||||
.findIndex(e => e.type === 'tool_call')
|
||||
if (idx >= 0) {
|
||||
const realIdx = prev.length - 1 - idx;
|
||||
const entry = prev[realIdx] as ToolCallEntry;
|
||||
if (entry.toolCall.status === "running") {
|
||||
const realIdx = prev.length - 1 - idx
|
||||
const entry = prev[realIdx] as ToolCallEntry
|
||||
if (entry.toolCall.status === 'running') {
|
||||
return prev.map((e, i) =>
|
||||
i === realIdx
|
||||
? { type: "tool_call", toolCall: { ...entry.toolCall, status: "waiting_for_confirmation" as ToolCallStatus, permissionRequest: { requestId, options: [] } } }
|
||||
? {
|
||||
type: 'tool_call',
|
||||
toolCall: {
|
||||
...entry.toolCall,
|
||||
status: 'waiting_for_confirmation' as ToolCallStatus,
|
||||
permissionRequest: { requestId, options: [] },
|
||||
},
|
||||
}
|
||||
: e,
|
||||
);
|
||||
)
|
||||
}
|
||||
}
|
||||
return prev;
|
||||
});
|
||||
return prev
|
||||
})
|
||||
|
||||
// Notify parent
|
||||
this.onPermissionRequest?.({
|
||||
@@ -372,102 +425,117 @@ export class RCSChatAdapter {
|
||||
toolName,
|
||||
toolInput,
|
||||
description,
|
||||
});
|
||||
})
|
||||
}
|
||||
break;
|
||||
break
|
||||
}
|
||||
|
||||
// ---- 会话状态 ----
|
||||
case "session_status": {
|
||||
if (typeof payload.status === "string") {
|
||||
this.onStatusChange?.(payload.status);
|
||||
case 'session_status': {
|
||||
if (typeof payload.status === 'string') {
|
||||
this.onStatusChange?.(payload.status)
|
||||
}
|
||||
break;
|
||||
break
|
||||
}
|
||||
|
||||
// ---- 错误 ----
|
||||
case "error": {
|
||||
const errorMsg = String(payload.message || payload.content || "Unknown error");
|
||||
this.onError?.(errorMsg);
|
||||
break;
|
||||
case 'error': {
|
||||
const errorMsg = String(
|
||||
payload.message || payload.content || 'Unknown error',
|
||||
)
|
||||
this.onError?.(errorMsg)
|
||||
break
|
||||
}
|
||||
|
||||
// ---- 忽略的事件类型 ----
|
||||
case "partial_assistant":
|
||||
case "result":
|
||||
case "result_success":
|
||||
case "control_response":
|
||||
case "permission_response":
|
||||
case "system":
|
||||
case "task_state":
|
||||
case "automation_state":
|
||||
case "status":
|
||||
break;
|
||||
case 'partial_assistant':
|
||||
case 'result':
|
||||
case 'result_success':
|
||||
case 'control_response':
|
||||
case 'permission_response':
|
||||
case 'system':
|
||||
case 'task_state':
|
||||
case 'automation_state':
|
||||
case 'status':
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
/** 发送用户消息 */
|
||||
async sendMessage(text: string, images?: UserMessageImage[]): Promise<void> {
|
||||
if (!text.trim() && (!images || images.length === 0)) return;
|
||||
if (!text.trim() && (!images || images.length === 0)) return
|
||||
|
||||
// Add user message to entries
|
||||
const userEntry: UserMessageEntry = {
|
||||
type: "user_message",
|
||||
type: 'user_message',
|
||||
id: `user-${Date.now()}`,
|
||||
content: text,
|
||||
images: images && images.length > 0 ? images : undefined,
|
||||
};
|
||||
this.setEntries((prev) => [...prev, userEntry]);
|
||||
}
|
||||
this.setEntries(prev => [...prev, userEntry])
|
||||
|
||||
// Send to backend
|
||||
await apiSendEvent(this.sessionId, {
|
||||
type: "user",
|
||||
type: 'user',
|
||||
uuid: generateMessageUuid(),
|
||||
content: text,
|
||||
message: { content: text },
|
||||
});
|
||||
})
|
||||
}
|
||||
|
||||
/** 响应权限请求 */
|
||||
async respondPermission(requestId: string, approved: boolean, extra?: Record<string, unknown>): Promise<void> {
|
||||
async respondPermission(
|
||||
requestId: string,
|
||||
approved: boolean,
|
||||
extra?: Record<string, unknown>,
|
||||
): Promise<void> {
|
||||
await apiSendControl(this.sessionId, {
|
||||
type: "permission_response",
|
||||
type: 'permission_response',
|
||||
approved,
|
||||
request_id: requestId,
|
||||
...extra,
|
||||
});
|
||||
})
|
||||
|
||||
// Update tool call status
|
||||
this.setEntries((prev) =>
|
||||
prev.map((entry) => {
|
||||
if (entry.type !== "tool_call") return entry;
|
||||
if (entry.toolCall.permissionRequest?.requestId !== requestId) return entry;
|
||||
this.setEntries(prev =>
|
||||
prev.map(entry => {
|
||||
if (entry.type !== 'tool_call') return entry
|
||||
if (entry.toolCall.permissionRequest?.requestId !== requestId)
|
||||
return entry
|
||||
return {
|
||||
type: "tool_call",
|
||||
type: 'tool_call',
|
||||
toolCall: {
|
||||
...entry.toolCall,
|
||||
status: approved ? "running" : ("rejected" as ToolCallStatus),
|
||||
status: approved ? 'running' : ('rejected' as ToolCallStatus),
|
||||
permissionRequest: undefined,
|
||||
},
|
||||
};
|
||||
}
|
||||
}),
|
||||
);
|
||||
)
|
||||
}
|
||||
|
||||
/** 中断当前操作 */
|
||||
async interrupt(): Promise<void> {
|
||||
// Mark running tools as canceled
|
||||
this.setEntries((prev) =>
|
||||
prev.map((entry) => {
|
||||
if (entry.type !== "tool_call") return entry;
|
||||
if (entry.toolCall.status !== "running" && entry.toolCall.status !== "waiting_for_confirmation") return entry;
|
||||
this.setEntries(prev =>
|
||||
prev.map(entry => {
|
||||
if (entry.type !== 'tool_call') return entry
|
||||
if (
|
||||
entry.toolCall.status !== 'running' &&
|
||||
entry.toolCall.status !== 'waiting_for_confirmation'
|
||||
)
|
||||
return entry
|
||||
return {
|
||||
type: "tool_call",
|
||||
toolCall: { ...entry.toolCall, status: "canceled" as ToolCallStatus, permissionRequest: undefined },
|
||||
};
|
||||
type: 'tool_call',
|
||||
toolCall: {
|
||||
...entry.toolCall,
|
||||
status: 'canceled' as ToolCallStatus,
|
||||
permissionRequest: undefined,
|
||||
},
|
||||
}
|
||||
}),
|
||||
);
|
||||
)
|
||||
|
||||
await apiInterrupt(this.sessionId);
|
||||
await apiInterrupt(this.sessionId)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,336 +1,363 @@
|
||||
import type { ChatTransport, UIMessage, UIMessageChunk } from "ai";
|
||||
import { getUuid } from "../api/client";
|
||||
import { generateMessageUuid } from "./utils";
|
||||
import type { SessionEvent, EventPayload } from "../types";
|
||||
import type { ChatTransport, UIMessage, UIMessageChunk } from 'ai'
|
||||
import { getUuid } from '../api/client'
|
||||
import { generateMessageUuid } from './utils'
|
||||
import type { SessionEvent, EventPayload } from '../types'
|
||||
|
||||
// ============================================================
|
||||
// SSE Event Bus — shared between SSE listener and transport
|
||||
// ============================================================
|
||||
|
||||
type SSEEventHandler = (event: SessionEvent) => void;
|
||||
type SSEEventHandler = (event: SessionEvent) => void
|
||||
|
||||
class SSEEventBus {
|
||||
private listeners: Set<SSEEventHandler> = new Set();
|
||||
private eventSource: EventSource | null = null;
|
||||
private _lastSeqNum = 0;
|
||||
private listeners: Set<SSEEventHandler> = new Set()
|
||||
private eventSource: EventSource | null = null
|
||||
private _lastSeqNum = 0
|
||||
|
||||
get lastSeqNum() {
|
||||
return this._lastSeqNum;
|
||||
return this._lastSeqNum
|
||||
}
|
||||
|
||||
/** Register a listener for SSE events */
|
||||
onEvent(handler: SSEEventHandler): () => void {
|
||||
this.listeners.add(handler);
|
||||
return () => this.listeners.delete(handler);
|
||||
this.listeners.add(handler)
|
||||
return () => this.listeners.delete(handler)
|
||||
}
|
||||
|
||||
/** Connect to the SSE stream for a session */
|
||||
connect(sessionId: string): void {
|
||||
this.disconnect();
|
||||
const uuid = getUuid();
|
||||
const url = `/web/sessions/${sessionId}/events?uuid=${encodeURIComponent(uuid)}`;
|
||||
const es = new EventSource(url);
|
||||
this.eventSource = es;
|
||||
this.disconnect()
|
||||
const uuid = getUuid()
|
||||
const url = `/web/sessions/${sessionId}/events?uuid=${encodeURIComponent(uuid)}`
|
||||
const es = new EventSource(url)
|
||||
this.eventSource = es
|
||||
|
||||
es.addEventListener("message", (e: MessageEvent) => {
|
||||
es.addEventListener('message', (e: MessageEvent) => {
|
||||
try {
|
||||
const data = JSON.parse(e.data) as SessionEvent;
|
||||
if (data.seqNum !== undefined && data.seqNum <= this._lastSeqNum) return;
|
||||
if (data.seqNum !== undefined) this._lastSeqNum = data.seqNum;
|
||||
const data = JSON.parse(e.data) as SessionEvent
|
||||
if (data.seqNum !== undefined && data.seqNum <= this._lastSeqNum) return
|
||||
if (data.seqNum !== undefined) this._lastSeqNum = data.seqNum
|
||||
for (const handler of this.listeners) {
|
||||
handler(data);
|
||||
handler(data)
|
||||
}
|
||||
} catch {
|
||||
// ignore parse errors
|
||||
}
|
||||
});
|
||||
})
|
||||
}
|
||||
|
||||
/** Disconnect the SSE stream */
|
||||
disconnect(): void {
|
||||
if (this.eventSource) {
|
||||
this.eventSource.close();
|
||||
this.eventSource = null;
|
||||
this.eventSource.close()
|
||||
this.eventSource = null
|
||||
}
|
||||
this._lastSeqNum = 0;
|
||||
this._lastSeqNum = 0
|
||||
}
|
||||
}
|
||||
|
||||
// Singleton event bus
|
||||
export const sseBus = new SSEEventBus();
|
||||
export const sseBus = new SSEEventBus()
|
||||
|
||||
// ============================================================
|
||||
// RCS ChatTransport — bridges RCS SSE to AI SDK UIMessageChunk
|
||||
// ============================================================
|
||||
|
||||
interface RCSTransportOptions {
|
||||
sessionId: string;
|
||||
onPermissionRequest?: (event: SessionEvent) => void;
|
||||
onSessionStatus?: (status: string) => void;
|
||||
onError?: (error: string) => void;
|
||||
sessionId: string
|
||||
onPermissionRequest?: (event: SessionEvent) => void
|
||||
onSessionStatus?: (status: string) => void
|
||||
onError?: (error: string) => void
|
||||
}
|
||||
|
||||
export class RCSTransport implements ChatTransport<UIMessage> {
|
||||
private sessionId: string;
|
||||
private onPermissionRequest?: (event: SessionEvent) => void;
|
||||
private onSessionStatus?: (status: string) => void;
|
||||
private onError?: (error: string) => void;
|
||||
private unsub: (() => void) | null = null;
|
||||
private sessionId: string
|
||||
private onPermissionRequest?: (event: SessionEvent) => void
|
||||
private onSessionStatus?: (status: string) => void
|
||||
private onError?: (error: string) => void
|
||||
private unsub: (() => void) | null = null
|
||||
|
||||
constructor(options: RCSTransportOptions) {
|
||||
this.sessionId = options.sessionId;
|
||||
this.onPermissionRequest = options.onPermissionRequest;
|
||||
this.onSessionStatus = options.onSessionStatus;
|
||||
this.onError = options.onError;
|
||||
this.sessionId = options.sessionId
|
||||
this.onPermissionRequest = options.onPermissionRequest
|
||||
this.onSessionStatus = options.onSessionStatus
|
||||
this.onError = options.onError
|
||||
}
|
||||
|
||||
async sendMessages({
|
||||
messages,
|
||||
abortSignal,
|
||||
}: Parameters<ChatTransport<UIMessage>["sendMessages"]>[0]): Promise<ReadableStream<UIMessageChunk>> {
|
||||
const lastMessage = messages[messages.length - 1];
|
||||
if (!lastMessage || lastMessage.role !== "user") {
|
||||
}: Parameters<ChatTransport<UIMessage>['sendMessages']>[0]): Promise<
|
||||
ReadableStream<UIMessageChunk>
|
||||
> {
|
||||
const lastMessage = messages[messages.length - 1]
|
||||
if (!lastMessage || lastMessage.role !== 'user') {
|
||||
// Return empty stream if no user message
|
||||
return new ReadableStream({ start: (c) => c.close() });
|
||||
return new ReadableStream({ start: c => c.close() })
|
||||
}
|
||||
|
||||
// Extract text from the user message parts
|
||||
const text = lastMessage.parts
|
||||
.filter((p: UIMessage["parts"][number]): p is Extract<typeof p, { type: "text" }> => p.type === "text")
|
||||
.filter(
|
||||
(
|
||||
p: UIMessage['parts'][number],
|
||||
): p is Extract<typeof p, { type: 'text' }> => p.type === 'text',
|
||||
)
|
||||
.map((p: { text: string }) => p.text)
|
||||
.join("");
|
||||
.join('')
|
||||
|
||||
if (!text.trim()) {
|
||||
return new ReadableStream({ start: (c) => c.close() });
|
||||
return new ReadableStream({ start: c => c.close() })
|
||||
}
|
||||
|
||||
// POST user message to the RCS backend
|
||||
const uuid = getUuid();
|
||||
const uuid = getUuid()
|
||||
const response = await fetch(
|
||||
`/web/sessions/${this.sessionId}/events?uuid=${encodeURIComponent(uuid)}`,
|
||||
{
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
type: "user",
|
||||
type: 'user',
|
||||
uuid: generateMessageUuid(),
|
||||
content: text,
|
||||
message: { content: text },
|
||||
}),
|
||||
signal: abortSignal,
|
||||
},
|
||||
);
|
||||
)
|
||||
|
||||
if (!response.ok) {
|
||||
const data = await response.json().catch(() => ({ error: { message: response.statusText } }));
|
||||
throw new Error(data.error?.message || "Failed to send message");
|
||||
const data = await response
|
||||
.json()
|
||||
.catch(() => ({ error: { message: response.statusText } }))
|
||||
throw new Error(data.error?.message || 'Failed to send message')
|
||||
}
|
||||
|
||||
// Create a ReadableStream from the SSE event bus
|
||||
// Collects events until the assistant turn is complete
|
||||
return new ReadableStream<UIMessageChunk>({
|
||||
start: (controller) => {
|
||||
let textId = `text-${Date.now()}`;
|
||||
let started = false;
|
||||
start: controller => {
|
||||
let textId = `text-${Date.now()}`
|
||||
let started = false
|
||||
|
||||
const ensureStarted = () => {
|
||||
if (!started) {
|
||||
started = true;
|
||||
controller.enqueue({ type: "start", messageId: `msg-${Date.now()}` });
|
||||
started = true
|
||||
controller.enqueue({
|
||||
type: 'start',
|
||||
messageId: `msg-${Date.now()}`,
|
||||
})
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
const handler = (event: SessionEvent) => {
|
||||
const type = event.type;
|
||||
const payload = event.payload || ({} as EventPayload);
|
||||
const type = event.type
|
||||
const payload = event.payload || ({} as EventPayload)
|
||||
|
||||
// Skip bridge init noise
|
||||
const serialized = JSON.stringify(event);
|
||||
if (/Remote Control connecting/i.test(serialized)) return;
|
||||
const serialized = JSON.stringify(event)
|
||||
if (/Remote Control connecting/i.test(serialized)) return
|
||||
|
||||
switch (type) {
|
||||
// ---- Assistant text ----
|
||||
case "assistant": {
|
||||
case 'assistant': {
|
||||
const content =
|
||||
typeof payload.content === "string"
|
||||
? payload.content
|
||||
: "";
|
||||
typeof payload.content === 'string' ? payload.content : ''
|
||||
if (content && content.trim()) {
|
||||
ensureStarted();
|
||||
controller.enqueue({ type: "text-start", id: textId });
|
||||
controller.enqueue({ type: "text-delta", id: textId, delta: content });
|
||||
controller.enqueue({ type: "text-end", id: textId });
|
||||
ensureStarted()
|
||||
controller.enqueue({ type: 'text-start', id: textId })
|
||||
controller.enqueue({
|
||||
type: 'text-delta',
|
||||
id: textId,
|
||||
delta: content,
|
||||
})
|
||||
controller.enqueue({ type: 'text-end', id: textId })
|
||||
}
|
||||
|
||||
// Check for embedded tool_use blocks
|
||||
const msg = payload.message as Record<string, unknown> | undefined;
|
||||
if (msg && typeof msg === "object" && Array.isArray(msg.content)) {
|
||||
const toolBlocks = (msg.content as Array<Record<string, unknown>>).filter(
|
||||
(b) => b.type === "tool_use",
|
||||
);
|
||||
const msg = payload.message as Record<string, unknown> | undefined
|
||||
if (
|
||||
msg &&
|
||||
typeof msg === 'object' &&
|
||||
Array.isArray(msg.content)
|
||||
) {
|
||||
const toolBlocks = (
|
||||
msg.content as Array<Record<string, unknown>>
|
||||
).filter(b => b.type === 'tool_use')
|
||||
for (const block of toolBlocks) {
|
||||
ensureStarted();
|
||||
const toolCallId = (block.id as string) || `call-${Date.now()}-${Math.random().toString(16).slice(2, 8)}`;
|
||||
ensureStarted()
|
||||
const toolCallId =
|
||||
(block.id as string) ||
|
||||
`call-${Date.now()}-${Math.random().toString(16).slice(2, 8)}`
|
||||
controller.enqueue({
|
||||
type: "tool-input-available",
|
||||
type: 'tool-input-available',
|
||||
toolCallId,
|
||||
toolName: (block.name as string) || "tool",
|
||||
toolName: (block.name as string) || 'tool',
|
||||
input: block.input || {},
|
||||
});
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Finish after assistant message
|
||||
ensureStarted();
|
||||
controller.enqueue({ type: "finish", finishReason: "stop" });
|
||||
controller.close();
|
||||
cleanup();
|
||||
break;
|
||||
ensureStarted()
|
||||
controller.enqueue({ type: 'finish', finishReason: 'stop' })
|
||||
controller.close()
|
||||
cleanup()
|
||||
break
|
||||
}
|
||||
|
||||
// ---- Tool use events ----
|
||||
case "tool_use": {
|
||||
ensureStarted();
|
||||
case 'tool_use': {
|
||||
ensureStarted()
|
||||
const toolCallId =
|
||||
(payload as Record<string, unknown>).tool_call_id as string ||
|
||||
`call-${Date.now()}-${Math.random().toString(16).slice(2, 8)}`;
|
||||
((payload as Record<string, unknown>).tool_call_id as string) ||
|
||||
`call-${Date.now()}-${Math.random().toString(16).slice(2, 8)}`
|
||||
controller.enqueue({
|
||||
type: "tool-input-available",
|
||||
type: 'tool-input-available',
|
||||
toolCallId,
|
||||
toolName: (payload as Record<string, unknown>).tool_name as string || "tool",
|
||||
toolName:
|
||||
((payload as Record<string, unknown>).tool_name as string) ||
|
||||
'tool',
|
||||
input: (payload as Record<string, unknown>).tool_input || {},
|
||||
});
|
||||
break;
|
||||
})
|
||||
break
|
||||
}
|
||||
|
||||
// ---- Tool result events ----
|
||||
case "tool_result": {
|
||||
ensureStarted();
|
||||
case 'tool_result': {
|
||||
ensureStarted()
|
||||
const resultCallId =
|
||||
(payload as Record<string, unknown>).tool_call_id as string ||
|
||||
`call-${Date.now()}-${Math.random().toString(16).slice(2, 8)}`;
|
||||
((payload as Record<string, unknown>).tool_call_id as string) ||
|
||||
`call-${Date.now()}-${Math.random().toString(16).slice(2, 8)}`
|
||||
const output =
|
||||
typeof (payload as Record<string, unknown>).output === "string"
|
||||
typeof (payload as Record<string, unknown>).output === 'string'
|
||||
? (payload as Record<string, unknown>).output
|
||||
: (payload as Record<string, unknown>).content || "";
|
||||
: (payload as Record<string, unknown>).content || ''
|
||||
controller.enqueue({
|
||||
type: "tool-output-available",
|
||||
type: 'tool-output-available',
|
||||
toolCallId: resultCallId,
|
||||
output: output as string,
|
||||
});
|
||||
break;
|
||||
})
|
||||
break
|
||||
}
|
||||
|
||||
// ---- Permission / control requests ----
|
||||
case "control_request":
|
||||
case "permission_request": {
|
||||
const req = payload.request as Record<string, unknown> | undefined;
|
||||
if (req && req.subtype === "can_use_tool") {
|
||||
case 'control_request':
|
||||
case 'permission_request': {
|
||||
const req = payload.request as Record<string, unknown> | undefined
|
||||
if (req && req.subtype === 'can_use_tool') {
|
||||
// Forward to the UI layer for handling
|
||||
this.onPermissionRequest?.(event);
|
||||
this.onPermissionRequest?.(event)
|
||||
}
|
||||
// Don't close the stream — wait for the response
|
||||
break;
|
||||
break
|
||||
}
|
||||
|
||||
// ---- Status events ----
|
||||
case "status": {
|
||||
case 'status': {
|
||||
const msg =
|
||||
(typeof payload.message === "string" ? payload.message : "") ||
|
||||
(typeof payload.message === 'string' ? payload.message : '') ||
|
||||
payload.content ||
|
||||
"";
|
||||
if (/connecting|waiting|initializing|Remote Control/i.test(msg)) return;
|
||||
break;
|
||||
''
|
||||
if (/connecting|waiting|initializing|Remote Control/i.test(msg))
|
||||
return
|
||||
break
|
||||
}
|
||||
|
||||
// ---- Session status ----
|
||||
case "session_status": {
|
||||
if (typeof payload.status === "string") {
|
||||
this.onSessionStatus?.(payload.status);
|
||||
case 'session_status': {
|
||||
if (typeof payload.status === 'string') {
|
||||
this.onSessionStatus?.(payload.status)
|
||||
if (
|
||||
payload.status === "archived" ||
|
||||
payload.status === "inactive"
|
||||
payload.status === 'archived' ||
|
||||
payload.status === 'inactive'
|
||||
) {
|
||||
ensureStarted();
|
||||
controller.enqueue({ type: "finish", finishReason: "stop" });
|
||||
controller.close();
|
||||
cleanup();
|
||||
ensureStarted()
|
||||
controller.enqueue({ type: 'finish', finishReason: 'stop' })
|
||||
controller.close()
|
||||
cleanup()
|
||||
}
|
||||
}
|
||||
break;
|
||||
break
|
||||
}
|
||||
|
||||
// ---- Errors ----
|
||||
case "error": {
|
||||
ensureStarted();
|
||||
case 'error': {
|
||||
ensureStarted()
|
||||
controller.enqueue({
|
||||
type: "error",
|
||||
errorText: String(payload.message || payload.content || "Unknown error"),
|
||||
});
|
||||
controller.enqueue({ type: "finish", finishReason: "error" });
|
||||
controller.close();
|
||||
cleanup();
|
||||
break;
|
||||
type: 'error',
|
||||
errorText: String(
|
||||
payload.message || payload.content || 'Unknown error',
|
||||
),
|
||||
})
|
||||
controller.enqueue({ type: 'finish', finishReason: 'error' })
|
||||
controller.close()
|
||||
cleanup()
|
||||
break
|
||||
}
|
||||
|
||||
// ---- Interrupt ----
|
||||
case "interrupt": {
|
||||
ensureStarted();
|
||||
controller.enqueue({ type: "abort", reason: "Session interrupted" });
|
||||
controller.close();
|
||||
cleanup();
|
||||
break;
|
||||
case 'interrupt': {
|
||||
ensureStarted()
|
||||
controller.enqueue({
|
||||
type: 'abort',
|
||||
reason: 'Session interrupted',
|
||||
})
|
||||
controller.close()
|
||||
cleanup()
|
||||
break
|
||||
}
|
||||
|
||||
// ---- Skip noise ----
|
||||
case "partial_assistant":
|
||||
case "result":
|
||||
case "result_success":
|
||||
case "control_response":
|
||||
case "permission_response":
|
||||
case "system":
|
||||
case "task_state":
|
||||
case "automation_state":
|
||||
return;
|
||||
case 'partial_assistant':
|
||||
case 'result':
|
||||
case 'result_success':
|
||||
case 'control_response':
|
||||
case 'permission_response':
|
||||
case 'system':
|
||||
case 'task_state':
|
||||
case 'automation_state':
|
||||
return
|
||||
|
||||
default:
|
||||
return;
|
||||
return
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
const cleanup = () => {
|
||||
if (this.unsub) {
|
||||
this.unsub();
|
||||
this.unsub = null;
|
||||
this.unsub()
|
||||
this.unsub = null
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
this.unsub = sseBus.onEvent(handler);
|
||||
this.unsub = sseBus.onEvent(handler)
|
||||
|
||||
// Handle abort
|
||||
if (abortSignal) {
|
||||
const onAbort = () => {
|
||||
controller.enqueue({ type: "abort", reason: "Aborted" });
|
||||
controller.close();
|
||||
cleanup();
|
||||
abortSignal.removeEventListener("abort", onAbort);
|
||||
};
|
||||
abortSignal.addEventListener("abort", onAbort);
|
||||
controller.enqueue({ type: 'abort', reason: 'Aborted' })
|
||||
controller.close()
|
||||
cleanup()
|
||||
abortSignal.removeEventListener('abort', onAbort)
|
||||
}
|
||||
abortSignal.addEventListener('abort', onAbort)
|
||||
}
|
||||
},
|
||||
});
|
||||
})
|
||||
}
|
||||
|
||||
/** Not supported — RCS doesn't have stream resumption */
|
||||
reconnectToStream(): Promise<ReadableStream<UIMessageChunk> | null> {
|
||||
return Promise.resolve(null);
|
||||
return Promise.resolve(null)
|
||||
}
|
||||
|
||||
/** Clean up listeners */
|
||||
destroy(): void {
|
||||
if (this.unsub) {
|
||||
this.unsub();
|
||||
this.unsub = null;
|
||||
this.unsub()
|
||||
this.unsub = null
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,97 +1,110 @@
|
||||
import React, { createContext, useContext, useEffect, useState, useCallback } from "react";
|
||||
import React, {
|
||||
createContext,
|
||||
useContext,
|
||||
useEffect,
|
||||
useState,
|
||||
useCallback,
|
||||
} from 'react'
|
||||
|
||||
export type Theme = "light" | "dark" | "system";
|
||||
export type Theme = 'light' | 'dark' | 'system'
|
||||
|
||||
interface ThemeContextValue {
|
||||
theme: Theme;
|
||||
resolvedTheme: "light" | "dark";
|
||||
setTheme: (theme: Theme) => void;
|
||||
theme: Theme
|
||||
resolvedTheme: 'light' | 'dark'
|
||||
setTheme: (theme: Theme) => void
|
||||
}
|
||||
|
||||
const ThemeContext = createContext<ThemeContextValue | undefined>(undefined);
|
||||
const ThemeContext = createContext<ThemeContextValue | undefined>(undefined)
|
||||
|
||||
const STORAGE_KEY = "theme";
|
||||
const STORAGE_KEY = 'theme'
|
||||
|
||||
function getSystemTheme(): "light" | "dark" {
|
||||
if (typeof window === "undefined") return "light";
|
||||
return window.matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light";
|
||||
function getSystemTheme(): 'light' | 'dark' {
|
||||
if (typeof window === 'undefined') return 'light'
|
||||
return window.matchMedia('(prefers-color-scheme: dark)').matches
|
||||
? 'dark'
|
||||
: 'light'
|
||||
}
|
||||
|
||||
function getStoredTheme(): Theme {
|
||||
if (typeof window === "undefined") return "system";
|
||||
if (typeof window === 'undefined') return 'system'
|
||||
try {
|
||||
const stored = localStorage.getItem(STORAGE_KEY);
|
||||
if (stored === "light" || stored === "dark" || stored === "system") {
|
||||
return stored;
|
||||
const stored = localStorage.getItem(STORAGE_KEY)
|
||||
if (stored === 'light' || stored === 'dark' || stored === 'system') {
|
||||
return stored
|
||||
}
|
||||
} catch {
|
||||
// localStorage not available
|
||||
}
|
||||
return "system";
|
||||
return 'system'
|
||||
}
|
||||
|
||||
function applyTheme(theme: "light" | "dark") {
|
||||
const root = document.documentElement;
|
||||
root.classList.remove("light", "dark");
|
||||
root.classList.add(theme);
|
||||
function applyTheme(theme: 'light' | 'dark') {
|
||||
const root = document.documentElement
|
||||
root.classList.remove('light', 'dark')
|
||||
root.classList.add(theme)
|
||||
}
|
||||
|
||||
export function useTheme() {
|
||||
const context = useContext(ThemeContext);
|
||||
const context = useContext(ThemeContext)
|
||||
if (!context) {
|
||||
throw new Error("useTheme must be used within a ThemeProvider");
|
||||
throw new Error('useTheme must be used within a ThemeProvider')
|
||||
}
|
||||
return context;
|
||||
return context
|
||||
}
|
||||
|
||||
interface ThemeProviderProps {
|
||||
children: React.ReactNode;
|
||||
defaultTheme?: Theme;
|
||||
children: React.ReactNode
|
||||
defaultTheme?: Theme
|
||||
}
|
||||
|
||||
export function ThemeProvider({ children, defaultTheme = "system" }: ThemeProviderProps) {
|
||||
const [theme, setThemeState] = useState<Theme>(() => getStoredTheme() || defaultTheme);
|
||||
const [resolvedTheme, setResolvedTheme] = useState<"light" | "dark">(() => {
|
||||
const stored = getStoredTheme() || defaultTheme;
|
||||
return stored === "system" ? getSystemTheme() : stored;
|
||||
});
|
||||
export function ThemeProvider({
|
||||
children,
|
||||
defaultTheme = 'system',
|
||||
}: ThemeProviderProps) {
|
||||
const [theme, setThemeState] = useState<Theme>(
|
||||
() => getStoredTheme() || defaultTheme,
|
||||
)
|
||||
const [resolvedTheme, setResolvedTheme] = useState<'light' | 'dark'>(() => {
|
||||
const stored = getStoredTheme() || defaultTheme
|
||||
return stored === 'system' ? getSystemTheme() : stored
|
||||
})
|
||||
|
||||
const setTheme = useCallback((newTheme: Theme) => {
|
||||
setThemeState(newTheme);
|
||||
setThemeState(newTheme)
|
||||
try {
|
||||
localStorage.setItem(STORAGE_KEY, newTheme);
|
||||
localStorage.setItem(STORAGE_KEY, newTheme)
|
||||
} catch {
|
||||
// localStorage not available
|
||||
}
|
||||
}, []);
|
||||
}, [])
|
||||
|
||||
// Apply theme on mount and when theme changes
|
||||
useEffect(() => {
|
||||
const resolved = theme === "system" ? getSystemTheme() : theme;
|
||||
setResolvedTheme(resolved);
|
||||
applyTheme(resolved);
|
||||
}, [theme]);
|
||||
const resolved = theme === 'system' ? getSystemTheme() : theme
|
||||
setResolvedTheme(resolved)
|
||||
applyTheme(resolved)
|
||||
}, [theme])
|
||||
|
||||
// Listen for system theme changes
|
||||
useEffect(() => {
|
||||
if (theme !== "system") return;
|
||||
if (theme !== 'system') return
|
||||
|
||||
const mediaQuery = window.matchMedia("(prefers-color-scheme: dark)");
|
||||
const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)')
|
||||
const handleChange = (e: MediaQueryListEvent) => {
|
||||
const newTheme = e.matches ? "dark" : "light";
|
||||
setResolvedTheme(newTheme);
|
||||
applyTheme(newTheme);
|
||||
};
|
||||
const newTheme = e.matches ? 'dark' : 'light'
|
||||
setResolvedTheme(newTheme)
|
||||
applyTheme(newTheme)
|
||||
}
|
||||
|
||||
mediaQuery.addEventListener("change", handleChange);
|
||||
return () => mediaQuery.removeEventListener("change", handleChange);
|
||||
}, [theme]);
|
||||
mediaQuery.addEventListener('change', handleChange)
|
||||
return () => mediaQuery.removeEventListener('change', handleChange)
|
||||
}, [theme])
|
||||
|
||||
const value: ThemeContextValue = {
|
||||
theme,
|
||||
resolvedTheme,
|
||||
setTheme,
|
||||
};
|
||||
}
|
||||
|
||||
return React.createElement(ThemeContext.Provider, { value }, children);
|
||||
return React.createElement(ThemeContext.Provider, { value }, children)
|
||||
}
|
||||
|
||||
@@ -2,71 +2,71 @@
|
||||
// Unified Chat Data Model — shared between ACP and RCS chat interfaces
|
||||
// =============================================================================
|
||||
|
||||
import type { ToolCallContent, PermissionOption, PlanEntry } from "../acp/types";
|
||||
import type { ToolCallContent, PermissionOption, PlanEntry } from '../acp/types'
|
||||
|
||||
// 工具调用状态
|
||||
export type ToolCallStatus =
|
||||
| "running"
|
||||
| "complete"
|
||||
| "error"
|
||||
| "waiting_for_confirmation"
|
||||
| "rejected"
|
||||
| "canceled";
|
||||
| 'running'
|
||||
| 'complete'
|
||||
| 'error'
|
||||
| 'waiting_for_confirmation'
|
||||
| 'rejected'
|
||||
| 'canceled'
|
||||
|
||||
// 工具调用数据
|
||||
export interface ToolCallData {
|
||||
id: string;
|
||||
title: string;
|
||||
status: ToolCallStatus;
|
||||
content?: ToolCallContent[];
|
||||
rawInput?: Record<string, unknown>;
|
||||
rawOutput?: Record<string, unknown>;
|
||||
id: string
|
||||
title: string
|
||||
status: ToolCallStatus
|
||||
content?: ToolCallContent[]
|
||||
rawInput?: Record<string, unknown>
|
||||
rawOutput?: Record<string, unknown>
|
||||
// 权限请求(仅当 status === "waiting_for_confirmation")
|
||||
permissionRequest?: {
|
||||
requestId: string;
|
||||
options: PermissionOption[];
|
||||
};
|
||||
requestId: string
|
||||
options: PermissionOption[]
|
||||
}
|
||||
// 独立权限请求(无匹配工具调用时创建)
|
||||
isStandalonePermission?: boolean;
|
||||
isStandalonePermission?: boolean
|
||||
}
|
||||
|
||||
// 助手消息块 — 普通消息或思考过程
|
||||
export type AssistantChunk =
|
||||
| { type: "message"; text: string }
|
||||
| { type: "thought"; text: string };
|
||||
| { type: 'message'; text: string }
|
||||
| { type: 'thought'; text: string }
|
||||
|
||||
// 用户消息中的图片
|
||||
export interface UserMessageImage {
|
||||
mimeType: string;
|
||||
data: string; // base64 encoded
|
||||
mimeType: string
|
||||
data: string // base64 encoded
|
||||
}
|
||||
|
||||
// 用户消息条目
|
||||
export interface UserMessageEntry {
|
||||
type: "user_message";
|
||||
id: string;
|
||||
content: string;
|
||||
images?: UserMessageImage[];
|
||||
type: 'user_message'
|
||||
id: string
|
||||
content: string
|
||||
images?: UserMessageImage[]
|
||||
}
|
||||
|
||||
// 助手消息条目
|
||||
export interface AssistantMessageEntry {
|
||||
type: "assistant_message";
|
||||
id: string;
|
||||
chunks: AssistantChunk[];
|
||||
type: 'assistant_message'
|
||||
id: string
|
||||
chunks: AssistantChunk[]
|
||||
}
|
||||
|
||||
// 工具调用条目
|
||||
export interface ToolCallEntry {
|
||||
type: "tool_call";
|
||||
toolCall: ToolCallData;
|
||||
type: 'tool_call'
|
||||
toolCall: ToolCallData
|
||||
}
|
||||
|
||||
// Plan 展示条目(Agent 执行计划)
|
||||
export interface PlanDisplayEntry {
|
||||
type: "plan";
|
||||
id: string;
|
||||
entries: PlanEntry[];
|
||||
type: 'plan'
|
||||
id: string
|
||||
entries: PlanEntry[]
|
||||
}
|
||||
|
||||
// 统一聊天条目类型
|
||||
@@ -74,7 +74,7 @@ export type ThreadEntry =
|
||||
| UserMessageEntry
|
||||
| AssistantMessageEntry
|
||||
| ToolCallEntry
|
||||
| PlanDisplayEntry;
|
||||
| PlanDisplayEntry
|
||||
|
||||
// =============================================================================
|
||||
// Chat 组件 Props 类型
|
||||
@@ -82,23 +82,23 @@ export type ThreadEntry =
|
||||
|
||||
// ChatInput 提交消息
|
||||
export interface ChatInputMessage {
|
||||
text: string;
|
||||
images?: UserMessageImage[];
|
||||
text: string
|
||||
images?: UserMessageImage[]
|
||||
}
|
||||
|
||||
// 权限请求条目(用于 PermissionPanel)
|
||||
export interface PendingPermission {
|
||||
requestId: string;
|
||||
toolName: string;
|
||||
toolInput: Record<string, unknown>;
|
||||
description?: string;
|
||||
options?: PermissionOption[];
|
||||
requestId: string
|
||||
toolName: string
|
||||
toolInput: Record<string, unknown>
|
||||
description?: string
|
||||
options?: PermissionOption[]
|
||||
}
|
||||
|
||||
// 会话列表条目(用于 SessionSidebar)
|
||||
export interface SessionListItem {
|
||||
id: string;
|
||||
title?: string | null;
|
||||
updatedAt?: string | null;
|
||||
isActive?: boolean;
|
||||
id: string
|
||||
title?: string | null
|
||||
updatedAt?: string | null
|
||||
isActive?: boolean
|
||||
}
|
||||
|
||||
@@ -1,91 +1,102 @@
|
||||
import { type ClassValue, clsx } from "clsx";
|
||||
import { twMerge } from "tailwind-merge";
|
||||
import { type ClassValue, clsx } from 'clsx'
|
||||
import { twMerge } from 'tailwind-merge'
|
||||
|
||||
export function cn(...inputs: ClassValue[]) {
|
||||
return twMerge(clsx(inputs));
|
||||
return twMerge(clsx(inputs))
|
||||
}
|
||||
|
||||
export function esc(str: string | null | undefined): string {
|
||||
if (!str) return "";
|
||||
const value = String(str);
|
||||
const div = document.createElement("div");
|
||||
div.textContent = value;
|
||||
return div.innerHTML;
|
||||
if (!str) return ''
|
||||
const value = String(str)
|
||||
const div = document.createElement('div')
|
||||
div.textContent = value
|
||||
return div.innerHTML
|
||||
}
|
||||
|
||||
export function formatTime(ts: number | null | undefined): string {
|
||||
if (!ts) return "";
|
||||
return new Date(ts * 1000).toLocaleString();
|
||||
if (!ts) return ''
|
||||
return new Date(ts * 1000).toLocaleString()
|
||||
}
|
||||
|
||||
export function statusClass(status: string | null | undefined): string {
|
||||
const map: Record<string, string> = {
|
||||
active: "active",
|
||||
running: "running",
|
||||
idle: "idle",
|
||||
inactive: "inactive",
|
||||
requires_action: "requires_action",
|
||||
archived: "archived",
|
||||
error: "error",
|
||||
};
|
||||
return map[status || ""] || "default";
|
||||
active: 'active',
|
||||
running: 'running',
|
||||
idle: 'idle',
|
||||
inactive: 'inactive',
|
||||
requires_action: 'requires_action',
|
||||
archived: 'archived',
|
||||
error: 'error',
|
||||
}
|
||||
return map[status || ''] || 'default'
|
||||
}
|
||||
|
||||
export function isClosedSessionStatus(status: string | null | undefined): boolean {
|
||||
return status === "archived" || status === "inactive";
|
||||
export function isClosedSessionStatus(
|
||||
status: string | null | undefined,
|
||||
): boolean {
|
||||
return status === 'archived' || status === 'inactive'
|
||||
}
|
||||
|
||||
export function truncate(str: string | null | undefined, max: number): string {
|
||||
if (!str) return "";
|
||||
const s = String(str);
|
||||
return s.length > max ? s.slice(0, max) + "..." : s;
|
||||
if (!str) return ''
|
||||
const s = String(str)
|
||||
return s.length > max ? s.slice(0, max) + '...' : s
|
||||
}
|
||||
|
||||
function formatUuidV4(bytes: Uint8Array): string {
|
||||
bytes[6] = (bytes[6] & 0x0f) | 0x40;
|
||||
bytes[8] = (bytes[8] & 0x3f) | 0x80;
|
||||
bytes[6] = (bytes[6] & 0x0f) | 0x40
|
||||
bytes[8] = (bytes[8] & 0x3f) | 0x80
|
||||
|
||||
const hex = Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0"));
|
||||
const hex = Array.from(bytes, byte => byte.toString(16).padStart(2, '0'))
|
||||
return [
|
||||
hex.slice(0, 4).join(""),
|
||||
hex.slice(4, 6).join(""),
|
||||
hex.slice(6, 8).join(""),
|
||||
hex.slice(8, 10).join(""),
|
||||
hex.slice(10, 16).join(""),
|
||||
].join("-");
|
||||
hex.slice(0, 4).join(''),
|
||||
hex.slice(4, 6).join(''),
|
||||
hex.slice(6, 8).join(''),
|
||||
hex.slice(8, 10).join(''),
|
||||
hex.slice(10, 16).join(''),
|
||||
].join('-')
|
||||
}
|
||||
|
||||
export function generateMessageUuid(): string {
|
||||
const cryptoApi = globalThis.crypto;
|
||||
if (cryptoApi && typeof cryptoApi.randomUUID === "function") {
|
||||
return cryptoApi.randomUUID();
|
||||
const cryptoApi = globalThis.crypto
|
||||
if (cryptoApi && typeof cryptoApi.randomUUID === 'function') {
|
||||
return cryptoApi.randomUUID()
|
||||
}
|
||||
if (!cryptoApi || typeof cryptoApi.getRandomValues !== "function") {
|
||||
throw new Error("crypto.getRandomValues is required to generate message UUIDs");
|
||||
if (!cryptoApi || typeof cryptoApi.getRandomValues !== 'function') {
|
||||
throw new Error(
|
||||
'crypto.getRandomValues is required to generate message UUIDs',
|
||||
)
|
||||
}
|
||||
const bytes = new Uint8Array(16);
|
||||
cryptoApi.getRandomValues(bytes);
|
||||
return formatUuidV4(bytes);
|
||||
const bytes = new Uint8Array(16)
|
||||
cryptoApi.getRandomValues(bytes)
|
||||
return formatUuidV4(bytes)
|
||||
}
|
||||
|
||||
export function extractEventText(payload: Record<string, unknown> | null | undefined): string {
|
||||
if (!payload || typeof payload !== "object") return "";
|
||||
if (typeof payload.content === "string") return payload.content;
|
||||
const msg = payload.message as Record<string, unknown> | undefined;
|
||||
if (msg && typeof msg === "object" && Array.isArray(msg.content)) {
|
||||
export function extractEventText(
|
||||
payload: Record<string, unknown> | null | undefined,
|
||||
): string {
|
||||
if (!payload || typeof payload !== 'object') return ''
|
||||
if (typeof payload.content === 'string') return payload.content
|
||||
const msg = payload.message as Record<string, unknown> | undefined
|
||||
if (msg && typeof msg === 'object' && Array.isArray(msg.content)) {
|
||||
const texts = msg.content
|
||||
.filter((b: Record<string, unknown>) => b && b.type === "text" && typeof b.text === "string")
|
||||
.map((b: Record<string, unknown>) => b.text as string);
|
||||
if (texts.length > 0) return texts.join("\n");
|
||||
.filter(
|
||||
(b: Record<string, unknown>) =>
|
||||
b && b.type === 'text' && typeof b.text === 'string',
|
||||
)
|
||||
.map((b: Record<string, unknown>) => b.text as string)
|
||||
if (texts.length > 0) return texts.join('\n')
|
||||
}
|
||||
return "";
|
||||
return ''
|
||||
}
|
||||
|
||||
export function isConversationClearedStatus(
|
||||
payload: Record<string, unknown> | null | undefined,
|
||||
): boolean {
|
||||
if (!payload || typeof payload !== "object") return false;
|
||||
if (payload.status === "conversation_cleared") return true;
|
||||
const raw = payload.raw as Record<string, unknown> | undefined;
|
||||
return !!raw && typeof raw === "object" && raw.status === "conversation_cleared";
|
||||
if (!payload || typeof payload !== 'object') return false
|
||||
if (payload.status === 'conversation_cleared') return true
|
||||
const raw = payload.raw as Record<string, unknown> | undefined
|
||||
return (
|
||||
!!raw && typeof raw === 'object' && raw.status === 'conversation_cleared'
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
import { StrictMode } from "react";
|
||||
import { createRoot } from "react-dom/client";
|
||||
import App from "./App";
|
||||
import "./index.css";
|
||||
import { StrictMode } from 'react';
|
||||
import { createRoot } from 'react-dom/client';
|
||||
import App from './App';
|
||||
import './index.css';
|
||||
|
||||
createRoot(document.getElementById("root")!).render(
|
||||
createRoot(document.getElementById('root')!).render(
|
||||
<StrictMode>
|
||||
<App />
|
||||
</StrictMode>,
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
import { useState, useEffect, useCallback } from "react";
|
||||
import { apiFetchAllSessions, apiFetchEnvironments } from "../api/client";
|
||||
import type { Session, Environment } from "../types";
|
||||
import { EnvironmentList } from "../components/EnvironmentList";
|
||||
import { SessionList } from "../components/SessionList";
|
||||
import { NewSessionDialog } from "../components/NewSessionDialog";
|
||||
import { useState, useEffect, useCallback } from 'react';
|
||||
import { apiFetchAllSessions, apiFetchEnvironments } from '../api/client';
|
||||
import type { Session, Environment } from '../types';
|
||||
import { EnvironmentList } from '../components/EnvironmentList';
|
||||
import { SessionList } from '../components/SessionList';
|
||||
import { NewSessionDialog } from '../components/NewSessionDialog';
|
||||
|
||||
interface DashboardProps {
|
||||
onNavigateSession: (sessionId: string) => void;
|
||||
@@ -20,7 +20,7 @@ export function Dashboard({ onNavigateSession }: DashboardProps) {
|
||||
setSessions(sess || []);
|
||||
setEnvironments(envs || []);
|
||||
} catch (err) {
|
||||
console.error("Dashboard render error:", err);
|
||||
console.error('Dashboard render error:', err);
|
||||
}
|
||||
}, []);
|
||||
|
||||
@@ -40,9 +40,12 @@ export function Dashboard({ onNavigateSession }: DashboardProps) {
|
||||
// Bridge environments: no direct navigation (sessions are listed below)
|
||||
}, []);
|
||||
|
||||
const handleSelectSession = useCallback((sessionId: string) => {
|
||||
onNavigateSession(sessionId);
|
||||
}, [onNavigateSession]);
|
||||
const handleSelectSession = useCallback(
|
||||
(sessionId: string) => {
|
||||
onNavigateSession(sessionId);
|
||||
},
|
||||
[onNavigateSession],
|
||||
);
|
||||
|
||||
return (
|
||||
<div className="mx-auto max-w-5xl px-4 py-8">
|
||||
|
||||
@@ -1,31 +1,23 @@
|
||||
import { useState, useEffect, useCallback, useMemo, useRef } from "react";
|
||||
import {
|
||||
apiFetchSession,
|
||||
apiSendControl,
|
||||
apiInterrupt,
|
||||
} from "../api/client";
|
||||
import type { Session, SessionEvent } from "../types";
|
||||
import { isClosedSessionStatus, formatTime, cn } from "../lib/utils";
|
||||
import { Info } from "lucide-react";
|
||||
import { RCSChatAdapter } from "../lib/rcs-chat-adapter";
|
||||
import type { ThreadEntry, PendingPermission } from "../lib/types";
|
||||
import { StatusBadge } from "../components/Navbar";
|
||||
import { TaskPanel } from "../components/TaskPanel";
|
||||
import {
|
||||
PermissionPromptView,
|
||||
AskUserPanelView,
|
||||
PlanPanelView,
|
||||
} from "../components/PermissionViews";
|
||||
import { useState, useEffect, useCallback, useMemo, useRef } from 'react';
|
||||
import { apiFetchSession, apiSendControl, apiInterrupt } from '../api/client';
|
||||
import type { Session, SessionEvent } from '../types';
|
||||
import { isClosedSessionStatus, formatTime, cn } from '../lib/utils';
|
||||
import { Info } from 'lucide-react';
|
||||
import { RCSChatAdapter } from '../lib/rcs-chat-adapter';
|
||||
import type { ThreadEntry, PendingPermission } from '../lib/types';
|
||||
import { StatusBadge } from '../components/Navbar';
|
||||
import { TaskPanel } from '../components/TaskPanel';
|
||||
import { PermissionPromptView, AskUserPanelView, PlanPanelView } from '../components/PermissionViews';
|
||||
|
||||
// Unified chat components
|
||||
import { ChatView } from "../../components/chat/ChatView";
|
||||
import { ChatInput } from "../../components/chat/ChatInput";
|
||||
import { TooltipProvider } from "../../components/ui/tooltip";
|
||||
import { ChatView } from '../../components/chat/ChatView';
|
||||
import { ChatInput } from '../../components/chat/ChatInput';
|
||||
import { TooltipProvider } from '../../components/ui/tooltip';
|
||||
|
||||
// ACP chat components
|
||||
import { ACPClient, DisconnectRequestedError } from "../acp/client";
|
||||
import { createRelayClient } from "../acp/relay-client";
|
||||
import { ACPMain } from "../../components/ACPMain";
|
||||
import { ACPClient, DisconnectRequestedError } from '../acp/client';
|
||||
import { createRelayClient } from '../acp/relay-client';
|
||||
import { ACPMain } from '../../components/ACPMain';
|
||||
|
||||
interface SessionDetailProps {
|
||||
sessionId: string;
|
||||
@@ -34,7 +26,7 @@ interface SessionDetailProps {
|
||||
export function SessionDetail({ sessionId }: SessionDetailProps) {
|
||||
const [session, setSession] = useState<Session | null>(null);
|
||||
const [sessionStatus, setSessionStatus] = useState<string | null>(null);
|
||||
const [error, setError] = useState("");
|
||||
const [error, setError] = useState('');
|
||||
const [taskPanelOpen, setTaskPanelOpen] = useState(false);
|
||||
const [showMeta, setShowMeta] = useState(false);
|
||||
const [entries, setEntries] = useState<ThreadEntry[]>([]);
|
||||
@@ -46,15 +38,15 @@ export function SessionDetail({ sessionId }: SessionDetailProps) {
|
||||
const adapter = useMemo(
|
||||
() =>
|
||||
new RCSChatAdapter(sessionId, setEntries, {
|
||||
onStatusChange: (status) => {
|
||||
onStatusChange: status => {
|
||||
setSessionStatus(status);
|
||||
},
|
||||
onError: (err) => {
|
||||
console.error("[RCSChatAdapter] error:", err);
|
||||
onError: err => {
|
||||
console.error('[RCSChatAdapter] error:', err);
|
||||
},
|
||||
onPermissionRequest: (permission) => {
|
||||
setPendingPermissions((prev) => {
|
||||
if (prev.some((p) => p.requestId === permission.requestId)) return prev;
|
||||
onPermissionRequest: permission => {
|
||||
setPendingPermissions(prev => {
|
||||
if (prev.some(p => p.requestId === permission.requestId)) return prev;
|
||||
return [...prev, permission];
|
||||
});
|
||||
},
|
||||
@@ -74,7 +66,7 @@ export function SessionDetail({ sessionId }: SessionDetailProps) {
|
||||
let cancelled = false;
|
||||
|
||||
async function load() {
|
||||
setError("");
|
||||
setError('');
|
||||
|
||||
try {
|
||||
const sess = await apiFetchSession(sessionId);
|
||||
@@ -83,14 +75,14 @@ export function SessionDetail({ sessionId }: SessionDetailProps) {
|
||||
setSessionStatus(sess.status);
|
||||
} catch (err) {
|
||||
if (cancelled) return;
|
||||
setError(err instanceof Error ? err.message : "Failed to load session");
|
||||
setError(err instanceof Error ? err.message : 'Failed to load session');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
await adapter.init();
|
||||
} catch (err) {
|
||||
console.warn("Failed to init adapter:", err);
|
||||
console.warn('Failed to init adapter:', err);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -104,14 +96,14 @@ export function SessionDetail({ sessionId }: SessionDetailProps) {
|
||||
|
||||
// Send message via ChatInput
|
||||
const handleSubmit = useCallback(
|
||||
async (message: import("../../src/lib/types").ChatInputMessage) => {
|
||||
async (message: import('../../src/lib/types').ChatInputMessage) => {
|
||||
const text = message.text.trim();
|
||||
if (!text || closed) return;
|
||||
setIsLoading(true);
|
||||
try {
|
||||
await adapter.sendMessage(text, message.images);
|
||||
} catch (err) {
|
||||
console.error("Send failed:", err);
|
||||
console.error('Send failed:', err);
|
||||
}
|
||||
},
|
||||
[adapter, closed],
|
||||
@@ -122,7 +114,7 @@ export function SessionDetail({ sessionId }: SessionDetailProps) {
|
||||
try {
|
||||
await adapter.interrupt();
|
||||
} catch (err) {
|
||||
console.error("Interrupt failed:", err);
|
||||
console.error('Interrupt failed:', err);
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
@@ -132,9 +124,9 @@ export function SessionDetail({ sessionId }: SessionDetailProps) {
|
||||
useEffect(() => {
|
||||
if (entries.length === 0) return;
|
||||
const last = entries[entries.length - 1];
|
||||
if (last?.type === "assistant_message" || last?.type === "tool_call") {
|
||||
if (last?.type === 'assistant_message' || last?.type === 'tool_call') {
|
||||
// If the last entry is no longer a streaming tool, consider loading done
|
||||
if (last.type === "tool_call" && last.toolCall.status === "running") return;
|
||||
if (last.type === 'tool_call' && last.toolCall.status === 'running') return;
|
||||
setIsLoading(false);
|
||||
}
|
||||
}, [entries]);
|
||||
@@ -145,9 +137,9 @@ export function SessionDetail({ sessionId }: SessionDetailProps) {
|
||||
try {
|
||||
await adapter.respondPermission(requestId, true);
|
||||
} catch (err) {
|
||||
console.error("Failed to approve:", err);
|
||||
console.error('Failed to approve:', err);
|
||||
}
|
||||
setPendingPermissions((prev) => prev.filter((p) => p.requestId !== requestId));
|
||||
setPendingPermissions(prev => prev.filter(p => p.requestId !== requestId));
|
||||
},
|
||||
[adapter],
|
||||
);
|
||||
@@ -157,30 +149,26 @@ export function SessionDetail({ sessionId }: SessionDetailProps) {
|
||||
try {
|
||||
await adapter.respondPermission(requestId, false);
|
||||
} catch (err) {
|
||||
console.error("Failed to reject:", err);
|
||||
console.error('Failed to reject:', err);
|
||||
}
|
||||
setPendingPermissions((prev) => prev.filter((p) => p.requestId !== requestId));
|
||||
setPendingPermissions(prev => prev.filter(p => p.requestId !== requestId));
|
||||
},
|
||||
[adapter],
|
||||
);
|
||||
|
||||
const handleSubmitAnswers = useCallback(
|
||||
async (
|
||||
requestId: string,
|
||||
answers: Record<string, unknown>,
|
||||
questions: import("../types").Question[],
|
||||
) => {
|
||||
async (requestId: string, answers: Record<string, unknown>, questions: import('../types').Question[]) => {
|
||||
try {
|
||||
await apiSendControl(sessionId, {
|
||||
type: "permission_response",
|
||||
type: 'permission_response',
|
||||
approved: true,
|
||||
request_id: requestId,
|
||||
updated_input: { questions, answers },
|
||||
});
|
||||
} catch (err) {
|
||||
console.error("Failed to submit answers:", err);
|
||||
console.error('Failed to submit answers:', err);
|
||||
}
|
||||
setPendingPermissions((prev) => prev.filter((p) => p.requestId !== requestId));
|
||||
setPendingPermissions(prev => prev.filter(p => p.requestId !== requestId));
|
||||
},
|
||||
[sessionId],
|
||||
);
|
||||
@@ -188,31 +176,29 @@ export function SessionDetail({ sessionId }: SessionDetailProps) {
|
||||
const handleSubmitPlanResponse = useCallback(
|
||||
async (requestId: string, value: string, feedback?: string) => {
|
||||
try {
|
||||
if (value === "no") {
|
||||
if (value === 'no') {
|
||||
await apiSendControl(sessionId, {
|
||||
type: "permission_response",
|
||||
type: 'permission_response',
|
||||
approved: false,
|
||||
request_id: requestId,
|
||||
...(feedback ? { message: feedback } : {}),
|
||||
});
|
||||
} else {
|
||||
const modeMap: Record<string, string> = {
|
||||
"yes-accept-edits": "acceptEdits",
|
||||
"yes-default": "default",
|
||||
'yes-accept-edits': 'acceptEdits',
|
||||
'yes-default': 'default',
|
||||
};
|
||||
await apiSendControl(sessionId, {
|
||||
type: "permission_response",
|
||||
type: 'permission_response',
|
||||
approved: true,
|
||||
request_id: requestId,
|
||||
updated_permissions: [
|
||||
{ type: "setMode", mode: modeMap[value] || "default", destination: "session" },
|
||||
],
|
||||
updated_permissions: [{ type: 'setMode', mode: modeMap[value] || 'default', destination: 'session' }],
|
||||
});
|
||||
}
|
||||
} catch (err) {
|
||||
console.error("Failed to submit plan response:", err);
|
||||
console.error('Failed to submit plan response:', err);
|
||||
}
|
||||
setPendingPermissions((prev) => prev.filter((p) => p.requestId !== requestId));
|
||||
setPendingPermissions(prev => prev.filter(p => p.requestId !== requestId));
|
||||
},
|
||||
[sessionId],
|
||||
);
|
||||
@@ -239,7 +225,7 @@ export function SessionDetail({ sessionId }: SessionDetailProps) {
|
||||
}
|
||||
|
||||
// ACP session — render ACP relay chat
|
||||
if (session.source === "acp" && session.environment_id) {
|
||||
if (session.source === 'acp' && session.environment_id) {
|
||||
return <ACPSessionDetail sessionId={sessionId} agentId={session.environment_id} />;
|
||||
}
|
||||
|
||||
@@ -260,14 +246,10 @@ export function SessionDetail({ sessionId }: SessionDetailProps) {
|
||||
</div>
|
||||
<div className="flex items-start justify-between">
|
||||
<div className="min-w-0">
|
||||
<h2 className="font-display text-lg font-semibold text-text-primary">
|
||||
{session.title || session.id}
|
||||
</h2>
|
||||
<h2 className="font-display text-lg font-semibold text-text-primary">{session.title || session.id}</h2>
|
||||
<div className="mt-1 flex flex-wrap items-center gap-2">
|
||||
{sessionStatus && <StatusBadge status={sessionStatus} />}
|
||||
<span className="text-xs text-text-muted">
|
||||
{formatTime(session.created_at)}
|
||||
</span>
|
||||
<span className="text-xs text-text-muted">{formatTime(session.created_at)}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
@@ -288,9 +270,14 @@ export function SessionDetail({ sessionId }: SessionDetailProps) {
|
||||
</div>
|
||||
{showMeta && (
|
||||
<div className="mt-2 rounded-md bg-surface-2 px-3 py-2 text-xs text-text-muted space-y-1 font-mono">
|
||||
<div><span className="text-text-secondary font-sans font-medium">Session</span> {session.id}</div>
|
||||
<div>
|
||||
<span className="text-text-secondary font-sans font-medium">Session</span> {session.id}
|
||||
</div>
|
||||
{session.environment_id && (
|
||||
<div><span className="text-text-secondary font-sans font-medium">Environment</span> {session.environment_id}</div>
|
||||
<div>
|
||||
<span className="text-text-secondary font-sans font-medium">Environment</span>{' '}
|
||||
{session.environment_id}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
@@ -298,18 +285,13 @@ export function SessionDetail({ sessionId }: SessionDetailProps) {
|
||||
</div>
|
||||
|
||||
{/* Chat messages — unified ChatView */}
|
||||
<ChatView
|
||||
entries={entries}
|
||||
isLoading={isLoading}
|
||||
emptyTitle="开始对话"
|
||||
emptyDescription="输入消息开始聊天"
|
||||
/>
|
||||
<ChatView entries={entries} isLoading={isLoading} emptyTitle="开始对话" emptyDescription="输入消息开始聊天" />
|
||||
|
||||
{/* Unified Permission Panel — above input */}
|
||||
{pendingPermissions.length > 0 && (
|
||||
<div className="border-t bg-surface-1 px-4 py-3">
|
||||
<div className="mx-auto max-w-3xl space-y-3">
|
||||
{pendingPermissions.map((req) => (
|
||||
{pendingPermissions.map(req => (
|
||||
<PermissionEventView
|
||||
key={req.requestId}
|
||||
request={req}
|
||||
@@ -329,7 +311,7 @@ export function SessionDetail({ sessionId }: SessionDetailProps) {
|
||||
isLoading={isLoading}
|
||||
onInterrupt={handleInterrupt}
|
||||
disabled={closed}
|
||||
placeholder={closed ? "会话已关闭" : "输入消息..."}
|
||||
placeholder={closed ? '会话已关闭' : '输入消息...'}
|
||||
/>
|
||||
|
||||
{/* Task Panel */}
|
||||
@@ -353,28 +335,32 @@ function PermissionEventView({
|
||||
request: PendingPermission;
|
||||
onApprove: () => void;
|
||||
onReject: () => void;
|
||||
onSubmitAnswers: (requestId: string, answers: Record<string, unknown>, questions: import("../types").Question[]) => void;
|
||||
onSubmitAnswers: (
|
||||
requestId: string,
|
||||
answers: Record<string, unknown>,
|
||||
questions: import('../types').Question[],
|
||||
) => void;
|
||||
onSubmitPlan: (requestId: string, value: string, feedback?: string) => void;
|
||||
}) {
|
||||
const toolName = request.toolName;
|
||||
const toolInput = request.toolInput;
|
||||
const description = request.description || "";
|
||||
const description = request.description || '';
|
||||
|
||||
if (toolName === "AskUserQuestion") {
|
||||
const questions = (toolInput.questions as import("../types").Question[]) || [];
|
||||
if (toolName === 'AskUserQuestion') {
|
||||
const questions = (toolInput.questions as import('../types').Question[]) || [];
|
||||
return (
|
||||
<AskUserPanelView
|
||||
requestId={request.requestId}
|
||||
questions={questions}
|
||||
description={description}
|
||||
onSubmit={(answers) => onSubmitAnswers(request.requestId, answers, questions)}
|
||||
onSubmit={answers => onSubmitAnswers(request.requestId, answers, questions)}
|
||||
onSkip={onReject}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
if (toolName === "ExitPlanMode") {
|
||||
const planContent = (toolInput.plan as string) || "";
|
||||
if (toolName === 'ExitPlanMode') {
|
||||
const planContent = (toolInput.plan as string) || '';
|
||||
return (
|
||||
<PlanPanelView
|
||||
requestId={request.requestId}
|
||||
@@ -403,7 +389,9 @@ function PermissionEventView({
|
||||
|
||||
function ACPSessionDetail({ sessionId, agentId }: { sessionId: string; agentId: string }) {
|
||||
const [client, setClient] = useState<ACPClient | null>(null);
|
||||
const [connectionState, setConnectionState] = useState<"disconnected" | "connecting" | "connected" | "error">("disconnected");
|
||||
const [connectionState, setConnectionState] = useState<'disconnected' | 'connecting' | 'connected' | 'error'>(
|
||||
'disconnected',
|
||||
);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const clientRef = useRef<ACPClient | null>(null);
|
||||
|
||||
@@ -418,30 +406,28 @@ function ACPSessionDetail({ sessionId, agentId }: { sessionId: string; agentId:
|
||||
clientRef.current = relayClient;
|
||||
setClient(relayClient);
|
||||
|
||||
relayClient.connect().catch((e) => {
|
||||
relayClient.connect().catch(e => {
|
||||
if (e instanceof DisconnectRequestedError) return;
|
||||
setError((e as Error).message);
|
||||
setConnectionState("error");
|
||||
setConnectionState('error');
|
||||
});
|
||||
|
||||
return () => {
|
||||
relayClient.disconnect();
|
||||
clientRef.current = null;
|
||||
setClient(null);
|
||||
setConnectionState("disconnected");
|
||||
setConnectionState('disconnected');
|
||||
};
|
||||
}, [agentId]);
|
||||
|
||||
return (
|
||||
<TooltipProvider>
|
||||
<div className="flex flex-1 flex-col overflow-hidden">
|
||||
{error && connectionState === "error" && (
|
||||
<div className="px-4 py-2 bg-destructive/10 text-destructive text-sm border-b">
|
||||
{error}
|
||||
</div>
|
||||
{error && connectionState === 'error' && (
|
||||
<div className="px-4 py-2 bg-destructive/10 text-destructive text-sm border-b">{error}</div>
|
||||
)}
|
||||
|
||||
{connectionState === "connecting" && (
|
||||
{connectionState === 'connecting' && (
|
||||
<div className="flex-1 flex items-center justify-center">
|
||||
<div className="text-center">
|
||||
<div className="animate-spin h-8 w-8 border-2 border-brand border-t-transparent rounded-full mx-auto mb-3" />
|
||||
@@ -450,7 +436,7 @@ function ACPSessionDetail({ sessionId, agentId }: { sessionId: string; agentId:
|
||||
</div>
|
||||
)}
|
||||
|
||||
{connectionState === "error" && !client && (
|
||||
{connectionState === 'error' && !client && (
|
||||
<div className="flex-1 flex items-center justify-center">
|
||||
<div className="text-center">
|
||||
<p className="font-medium mb-1">Connection Failed</p>
|
||||
@@ -459,7 +445,7 @@ function ACPSessionDetail({ sessionId, agentId }: { sessionId: string; agentId:
|
||||
</div>
|
||||
)}
|
||||
|
||||
{client && connectionState === "connected" && (
|
||||
{client && connectionState === 'connected' && (
|
||||
<div className="flex-1 min-h-0">
|
||||
<ACPMain client={client} agentId={agentId} />
|
||||
</div>
|
||||
|
||||
@@ -1,100 +1,100 @@
|
||||
export interface Environment {
|
||||
id: string;
|
||||
machine_name?: string;
|
||||
directory?: string;
|
||||
status: string;
|
||||
branch?: string;
|
||||
worker_type?: string;
|
||||
channel_group_id?: string | null;
|
||||
capabilities?: Record<string, unknown> | null;
|
||||
id: string
|
||||
machine_name?: string
|
||||
directory?: string
|
||||
status: string
|
||||
branch?: string
|
||||
worker_type?: string
|
||||
channel_group_id?: string | null
|
||||
capabilities?: Record<string, unknown> | null
|
||||
}
|
||||
|
||||
export interface Session {
|
||||
id: string;
|
||||
title?: string;
|
||||
status: string;
|
||||
environment_id?: string;
|
||||
source?: string;
|
||||
created_at?: number;
|
||||
updated_at?: number;
|
||||
automation_state?: unknown;
|
||||
id: string
|
||||
title?: string
|
||||
status: string
|
||||
environment_id?: string
|
||||
source?: string
|
||||
created_at?: number
|
||||
updated_at?: number
|
||||
automation_state?: unknown
|
||||
}
|
||||
|
||||
export interface SessionEvent {
|
||||
type: string;
|
||||
payload?: EventPayload;
|
||||
direction?: "inbound" | "outbound";
|
||||
seqNum?: number;
|
||||
id?: string;
|
||||
type: string
|
||||
payload?: EventPayload
|
||||
direction?: 'inbound' | 'outbound'
|
||||
seqNum?: number
|
||||
id?: string
|
||||
}
|
||||
|
||||
export interface EventPayload {
|
||||
content?: string;
|
||||
message?: unknown;
|
||||
status?: string;
|
||||
uuid?: string;
|
||||
content?: string
|
||||
message?: unknown
|
||||
status?: string
|
||||
uuid?: string
|
||||
raw?: {
|
||||
uuid?: string;
|
||||
status?: string;
|
||||
};
|
||||
request_id?: string;
|
||||
request?: PermissionRequest;
|
||||
tool_name?: string;
|
||||
tool_input?: unknown;
|
||||
input?: unknown;
|
||||
description?: string;
|
||||
uuid?: string
|
||||
status?: string
|
||||
}
|
||||
request_id?: string
|
||||
request?: PermissionRequest
|
||||
tool_name?: string
|
||||
tool_input?: unknown
|
||||
input?: unknown
|
||||
description?: string
|
||||
}
|
||||
|
||||
export interface ContentBlock {
|
||||
type: string;
|
||||
text?: string;
|
||||
name?: string;
|
||||
input?: unknown;
|
||||
content?: unknown;
|
||||
is_error?: boolean;
|
||||
type: string
|
||||
text?: string
|
||||
name?: string
|
||||
input?: unknown
|
||||
content?: unknown
|
||||
is_error?: boolean
|
||||
}
|
||||
|
||||
export interface PermissionRequest {
|
||||
subtype?: string;
|
||||
tool_name?: string;
|
||||
input?: unknown;
|
||||
tool_input?: unknown;
|
||||
description?: string;
|
||||
subtype?: string
|
||||
tool_name?: string
|
||||
input?: unknown
|
||||
tool_input?: unknown
|
||||
description?: string
|
||||
}
|
||||
|
||||
export interface Question {
|
||||
question: string;
|
||||
header?: string;
|
||||
multiSelect?: boolean;
|
||||
options?: QuestionOption[];
|
||||
metadata?: Record<string, unknown>;
|
||||
question: string
|
||||
header?: string
|
||||
multiSelect?: boolean
|
||||
options?: QuestionOption[]
|
||||
metadata?: Record<string, unknown>
|
||||
}
|
||||
|
||||
export interface QuestionOption {
|
||||
label: string;
|
||||
description?: string;
|
||||
label: string
|
||||
description?: string
|
||||
}
|
||||
|
||||
export interface ControlResponse {
|
||||
type: "permission_response";
|
||||
approved: boolean;
|
||||
request_id: string;
|
||||
message?: string;
|
||||
updated_input?: Record<string, unknown>;
|
||||
updated_permissions?: PermissionUpdate[];
|
||||
type: 'permission_response'
|
||||
approved: boolean
|
||||
request_id: string
|
||||
message?: string
|
||||
updated_input?: Record<string, unknown>
|
||||
updated_permissions?: PermissionUpdate[]
|
||||
}
|
||||
|
||||
export interface PermissionUpdate {
|
||||
type: string;
|
||||
mode: string;
|
||||
destination: string;
|
||||
type: string
|
||||
mode: string
|
||||
destination: string
|
||||
}
|
||||
|
||||
export type ActivityMode = "working" | "idle" | "standby" | "sleeping";
|
||||
export type ActivityMode = 'working' | 'idle' | 'standby' | 'sleeping'
|
||||
|
||||
export interface AutomationActivity {
|
||||
mode: ActivityMode;
|
||||
iconVariant: string;
|
||||
label: string;
|
||||
endsAt?: number;
|
||||
mode: ActivityMode
|
||||
iconVariant: string
|
||||
label: string
|
||||
endsAt?: number
|
||||
}
|
||||
|
||||
@@ -1,41 +1,56 @@
|
||||
import { defineConfig } from "vite";
|
||||
import react from "@vitejs/plugin-react";
|
||||
import tailwindcss from "@tailwindcss/vite";
|
||||
import path from "path";
|
||||
import { defineConfig } from 'vite'
|
||||
import react from '@vitejs/plugin-react'
|
||||
import tailwindcss from '@tailwindcss/vite'
|
||||
import path from 'path'
|
||||
|
||||
export default defineConfig({
|
||||
plugins: [react(), tailwindcss()],
|
||||
base: "/code/",
|
||||
base: '/code/',
|
||||
resolve: {
|
||||
alias: {
|
||||
"@/src": path.resolve(__dirname, "src"),
|
||||
"@/components": path.resolve(__dirname, "components"),
|
||||
'@/src': path.resolve(__dirname, 'src'),
|
||||
'@/components': path.resolve(__dirname, 'components'),
|
||||
},
|
||||
},
|
||||
build: {
|
||||
outDir: "dist",
|
||||
outDir: 'dist',
|
||||
emptyOutDir: true,
|
||||
chunkSizeWarningLimit: 10000,
|
||||
rollupOptions: {
|
||||
input: {
|
||||
main: path.resolve(__dirname, "index.html"),
|
||||
main: path.resolve(__dirname, 'index.html'),
|
||||
},
|
||||
output: {
|
||||
manualChunks(id) {
|
||||
if (id.includes("node_modules/shiki") || id.includes("node_modules/@shikijs")) {
|
||||
return "shiki";
|
||||
if (
|
||||
id.includes('node_modules/shiki') ||
|
||||
id.includes('node_modules/@shikijs')
|
||||
) {
|
||||
return 'shiki'
|
||||
}
|
||||
if (id.includes("node_modules/motion") || id.includes("node_modules/framer-motion")) {
|
||||
return "motion";
|
||||
if (
|
||||
id.includes('node_modules/motion') ||
|
||||
id.includes('node_modules/framer-motion')
|
||||
) {
|
||||
return 'motion'
|
||||
}
|
||||
if (id.includes("node_modules/react") || id.includes("node_modules/react-dom")) {
|
||||
return "vendor";
|
||||
if (
|
||||
id.includes('node_modules/react') ||
|
||||
id.includes('node_modules/react-dom')
|
||||
) {
|
||||
return 'vendor'
|
||||
}
|
||||
if (id.includes("node_modules/ai/") || id.includes("node_modules/@ai-sdk/")) {
|
||||
return "ai-sdk";
|
||||
if (
|
||||
id.includes('node_modules/ai/') ||
|
||||
id.includes('node_modules/@ai-sdk/')
|
||||
) {
|
||||
return 'ai-sdk'
|
||||
}
|
||||
if (id.includes("node_modules/qrcode") || id.includes("node_modules/jsqr")) {
|
||||
return "qr";
|
||||
if (
|
||||
id.includes('node_modules/qrcode') ||
|
||||
id.includes('node_modules/jsqr')
|
||||
) {
|
||||
return 'qr'
|
||||
}
|
||||
},
|
||||
},
|
||||
@@ -43,10 +58,10 @@ export default defineConfig({
|
||||
},
|
||||
server: {
|
||||
proxy: {
|
||||
"/web": "http://localhost:3000",
|
||||
"/v1": "http://localhost:3000",
|
||||
"/v2": "http://localhost:3000",
|
||||
"/acp": "http://localhost:3000",
|
||||
'/web': 'http://localhost:3000',
|
||||
'/v1': 'http://localhost:3000',
|
||||
'/v2': 'http://localhost:3000',
|
||||
'/acp': 'http://localhost:3000',
|
||||
},
|
||||
},
|
||||
});
|
||||
})
|
||||
|
||||
Reference in New Issue
Block a user