feat: 支持 acp-link 包进行 acp 通用的 remote-control (#292)

* fix: 修复超时问题

* feat: 添加 acp-link 代码

* refactor: 样式重构完成

* feat: RCS 添加 ACP 后端支持

- 新增 ACP WebSocket handler (agent 注册、EventBus 订阅)
- 新增 relay handler (前端 WS → acp-link 透传 + EventBus inbound 转发)
- 新增 SSE event stream 供外部消费者订阅 channel group 事件
- ACP REST 接口无鉴权 (agents、channel-groups)
- WebSocket 端点保留 token 鉴权
- SPA 路由 /acp/ 指向 acp.html

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* feat: 添加 ACP 专属前端界面

- 新增 /acp/ SPA 页面 (agent 列表 + 实时交互)
- Agent 列表按 channel group 分组,显示在线状态
- 通过 RCS WebSocket relay 与 agent 通信
- Vite multi-page 构建 (index.html + acp.html)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* feat: acp-link 支持 RCS relay 双向通信

- rcs-upstream 新增 messageHandler 转发非控制消息
- server.ts 新增虚拟 WS + relay client state 处理 relay ACP 消息
- newSession/loadSession 补充 mcpServers 参数
- 连接成功后显示 ACP Dashboard URL

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* refactor: 移除 FileExplorer 及文件操作相关代码

- 删除 FileExplorer 组件
- ACPMain 移除 Files tab,仅保留 Chat 和 History
- client.ts 移除 listDir/readFile/onFileChanges 等方法
- types.ts 移除 FileItem/FileContent/FileChange 等类型

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix: 修复类型问题

* feat: RCS 后端统一 ACP/Bridge 注册逻辑

- store: EnvironmentRecord 增加 capabilities 字段、storeFindEnvironmentByMachineName 复用逻辑
- store: 新增 storeGetSessionOwners,支持未绑定 session 自动 claim
- environment: registerEnvironment 支持 ACP 复用已有记录,返回 session_id
- session: resolveOwnedWebSessionId 支持无 owner session 自动绑定
- acp-ws-handler: 新增 handleIdentify 支持 REST+WS 两步注册
- acp routes: /acp/relay 和 /acp/agents 支持 UUID 认证
- event-bus: 增加 error 类型 payload 日志

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* feat: acp-link 改 REST 注册 + WS identify 两步流程

- rcs-upstream: 新增 registerViaRest() 通过 POST /v1/environments/bridge 注册
- rcs-upstream: WS 连接后发送 identify 替代 register,携带 agentId
- rcs-upstream: 入口链接改为 /code/?sid=${sessionId} 实现用户绑定
- server: 修复心跳跳过 relay 虚拟连接的 bug
- server: maxSessions 配置传入 RCS upstream

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* feat: 前端统一 Chat 组件 + ACP 聊天界面重构

- 新增 chat/ 组件: ChatView, ChatInput, MessageBubble, ToolCallGroup, PermissionPanel, SessionSidebar, CommandMenu
- ACPMain: 重构支持完整 ACP 协议交互(session/prompt/permission)
- rcs-chat-adapter: 统一 bridge session SSE 适配器
- ACPClient: 增强 session 管理、permission 流程、streaming 支持
- index.css: 新增 chat 相关样式、动画、布局
- useCommands: 新增快捷命令 hook

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* refactor: 删除 /acp/ 独立页面,ACP 聊天统一到 /code/:sessionId

- 删除 acp.html、acp-main.tsx 入口文件和 pages/acp/ 目录
- SessionDetail: ACP session 在同一页面渲染 ACPSessionDetail 组件
- App.tsx: ?sid= 参数自动调用 apiBind 绑定用户 UUID
- Dashboard: 统一 session 列表导航,ACP 显示紫色标签
- relay-client: 改用 UUID 认证替代 API token
- EnvironmentList: 显示 workerType 标签(ACP Agent / Claude Code)
- index.ts: 移除 /acp/ SPA 路由,vite.config 移除 acp 入口

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* build: 更新构建及测试修复

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
claude-code-best
2026-04-18 17:59:29 +08:00
committed by GitHub
parent 29cc74a170
commit 34154ee3f5
142 changed files with 17847 additions and 5577 deletions

View File

@@ -0,0 +1,86 @@
import { useState, useEffect, useCallback } from "react";
import { Navbar } from "./components/Navbar";
import { Dashboard } from "./pages/Dashboard";
import { SessionDetail } from "./pages/SessionDetail";
import { IdentityPanel } from "./components/IdentityPanel";
import { ThemeProvider } from "./lib/theme";
import { getUuid, setUuid, apiBind } from "./api/client";
export default function App() {
const [currentSessionId, setCurrentSessionId] = useState<string | null>(null);
const [identityOpen, setIdentityOpen] = useState(false);
// Simple hash-based router
const parseRoute = useCallback(() => {
// Ensure UUID exists
getUuid();
const path = window.location.pathname;
// Check for UUID import from QR scan (?uuid=xxx)
const params = new URLSearchParams(window.location.search);
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);
}
// Check for CLI session bind (?sid=xxx) — bind session to current UUID
const sid = params.get("sid");
if (sid) {
const url = new URL(window.location.href);
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);
});
return;
}
// Path-based routing: /code/session_xxx → session detail
const match = path.match(/^\/code\/([^/]+)/);
if (match && match[1]) {
setCurrentSessionId(match[1]);
} else {
setCurrentSessionId(null);
}
}, []);
useEffect(() => {
parseRoute();
window.addEventListener("popstate", parseRoute);
return () => window.removeEventListener("popstate", parseRoute);
}, [parseRoute]);
const navigateToSession = useCallback((sessionId: string) => {
window.history.pushState(null, "", `/code/${sessionId}`);
setCurrentSessionId(sessionId);
}, []);
const navigateToDashboard = useCallback(() => {
window.history.pushState(null, "", "/code/");
setCurrentSessionId(null);
}, []);
return (
<ThemeProvider defaultTheme="light">
<div className="flex h-screen flex-col bg-surface-0 text-text-primary">
<Navbar onIdentityClick={() => setIdentityOpen(true)} />
{currentSessionId ? (
<SessionDetail key={currentSessionId} sessionId={currentSessionId} />
) : (
<div className="flex-1 overflow-y-auto">
<Dashboard onNavigateSession={navigateToSession} />
</div>
)}
<IdentityPanel open={identityOpen} onClose={() => setIdentityOpen(false)} />
</div>
</ThemeProvider>
);
}

View File

@@ -0,0 +1,768 @@
import type {
ACPSettings,
AgentCapabilities,
AgentSessionInfo,
BrowserToolParams,
BrowserToolResult,
ConnectionState,
ContentBlock,
ListSessionsRequest,
ListSessionsResponse,
LoadSessionRequest,
PermissionRequestPayload,
PromptCapabilities,
ProxyMessage,
ProxyResponse,
ResumeSessionRequest,
SessionUpdate,
SessionModelState,
ModelInfo,
AvailableCommand,
} from "./types";
/**
* Error thrown when disconnect() is called while a connection is in progress.
* Callers can use `instanceof` to distinguish this from real connection errors.
*/
export class DisconnectRequestedError extends Error {
constructor() {
super("Disconnect requested");
this.name = "DisconnectRequestedError";
}
}
export type ConnectionStateHandler = (
state: ConnectionState,
error?: string,
) => void;
export type SessionUpdateHandler = (sessionId: string, update: SessionUpdate) => void;
export type SessionCreatedHandler = (sessionId: string) => void;
export type PromptCompleteHandler = (stopReason: string) => void;
export type PermissionRequestHandler = (request: PermissionRequestPayload) => void;
export type BrowserToolCallHandler = (
params: BrowserToolParams,
) => Promise<BrowserToolResult>;
export type ErrorMessageHandler = (message: string) => void;
export type ModelChangedHandler = (modelId: string) => void;
export type ModelStateChangedHandler = (state: SessionModelState | null) => void;
export type AvailableCommandsChangedHandler = (commands: AvailableCommand[]) => void;
// Handler for session loaded/resumed events
export type SessionLoadedHandler = (sessionId: string) => void;
// Handler fired before switching the active session.
// This matches Zed's model more closely: the UI changes active thread first,
// then receives updates for that thread while load/resume is in flight.
export type SessionSwitchingHandler = (sessionId: string) => void;
export class ACPClient {
private ws: WebSocket | null = null;
private settings: ACPSettings;
private connectionState: ConnectionState = "disconnected";
private sessionId: string | null = null;
private pendingSessionTarget: string | null = null;
// Reference: Zed stores full agentCapabilities from initialize response
// Used to check supports_load_session, supports_resume_session, etc.
private _agentCapabilities: AgentCapabilities | null = null;
// Reference: Zed's prompt_capabilities in MessageEditor
// Stores capabilities from agent's initialize response
private _promptCapabilities: PromptCapabilities | null = null;
// Reference: Zed stores model state from NewSessionResponse
private _modelState: SessionModelState | null = null;
private _availableCommands: AvailableCommand[] = [];
private onModelChanged: ModelChangedHandler | null = null;
private onModelStateChanged: ModelStateChangedHandler | null = null;
private onAvailableCommandsChanged: AvailableCommandsChangedHandler | null = null;
private onSessionLoaded: SessionLoadedHandler | null = null;
private onSessionSwitching: SessionSwitchingHandler | null = null;
private onConnectionStateChange: Set<ConnectionStateHandler> = new Set();
private onSessionUpdate: SessionUpdateHandler | null = null;
private onSessionCreated: SessionCreatedHandler | null = null;
private onPromptComplete: PromptCompleteHandler | null = null;
private onPermissionRequest: PermissionRequestHandler | null = null;
private onBrowserToolCall: BrowserToolCallHandler | null = null;
private onErrorMessage: ErrorMessageHandler | null = null;
// Pending session operations
private pendingSessionList: { resolve: (response: ListSessionsResponse) => void; reject: (err: Error) => void; timer: ReturnType<typeof setTimeout> } | null = null;
private pendingSessionLoad: { resolve: (sessionId: string) => void; reject: (err: Error) => void; timer: ReturnType<typeof setTimeout> } | null = null;
private pendingSessionResume: { resolve: (sessionId: string) => void; reject: (err: Error) => void; timer: ReturnType<typeof setTimeout> } | null = null;
private connectResolve: ((value: void) => void) | null = null;
private connectReject: ((error: Error) => void) | null = null;
// Heartbeat state
private heartbeatInterval: ReturnType<typeof setInterval> | null = null;
private heartbeatTimeout: ReturnType<typeof setTimeout> | null = null;
private missedPongs = 0;
private static readonly HEARTBEAT_INTERVAL_MS = 30_000;
private static readonly PONG_TIMEOUT_MS = 10_000;
private static readonly MAX_MISSED_PONGS = 2;
constructor(settings: ACPSettings) {
this.settings = settings;
}
updateSettings(settings: ACPSettings): void {
this.settings = settings;
}
setConnectionStateHandler(handler: ConnectionStateHandler): void {
this.onConnectionStateChange.add(handler);
}
removeConnectionStateHandler(handler: ConnectionStateHandler): void {
this.onConnectionStateChange.delete(handler);
}
setSessionUpdateHandler(handler: SessionUpdateHandler): void {
this.onSessionUpdate = handler;
}
setSessionCreatedHandler(handler: SessionCreatedHandler): void {
this.onSessionCreated = handler;
}
setPromptCompleteHandler(handler: PromptCompleteHandler): void {
this.onPromptComplete = handler;
}
setModelChangedHandler(handler: ModelChangedHandler): void {
this.onModelChanged = handler;
}
/**
* Set handler for model state changes (called when session is created/destroyed).
* This replaces polling - the handler is called immediately with current state,
* and again whenever session is created or disconnected.
*/
setModelStateChangedHandler(handler: ModelStateChangedHandler): void {
this.onModelStateChanged = handler;
// Immediately notify with current state
handler(this._modelState);
}
setAvailableCommandsChangedHandler(handler: AvailableCommandsChangedHandler): void {
this.onAvailableCommandsChanged = handler;
handler(this._availableCommands);
}
setPermissionRequestHandler(handler: PermissionRequestHandler): void {
this.onPermissionRequest = handler;
}
setBrowserToolCallHandler(handler: BrowserToolCallHandler): void {
this.onBrowserToolCall = handler;
}
setErrorMessageHandler(handler: ErrorMessageHandler): void {
this.onErrorMessage = handler;
}
setSessionSwitchingHandler(handler: SessionSwitchingHandler | null): void {
this.onSessionSwitching = handler;
}
private setState(state: ConnectionState, error?: string): void {
this.connectionState = state;
for (const handler of this.onConnectionStateChange) {
handler(state, error);
}
}
getState(): ConnectionState {
return this.connectionState;
}
getSessionId(): string | null {
return this.sessionId;
}
// Reference: Zed's supports_images() in MessageEditor
// Returns true if the agent supports image content in prompts
get supportsImages(): boolean {
return this._promptCapabilities?.image === true;
}
// Reference: Zed's prompt_capabilities in MessageEditor
getPromptCapabilities(): PromptCapabilities | null {
return this._promptCapabilities;
}
/**
* Get the current model state (available models and current model ID).
* Reference: Zed's AgentModelSelector reads from state.available_models
*/
get modelState(): SessionModelState | null {
return this._modelState;
}
/**
* Get the list of available commands from the agent.
*/
get availableCommands(): AvailableCommand[] {
return this._availableCommands;
}
/**
* Check if the agent supports model selection.
* Reference: Zed's model_selector() returns Option<Rc<dyn AgentModelSelector>>
*/
get supportsModelSelection(): boolean {
return this._modelState !== null && this._modelState.availableModels.length > 0;
}
// ============================================================================
// Session Capability Getters
// Reference: Zed's AgentConnection supports_* methods
// ============================================================================
/**
* Get the full agent capabilities.
* Reference: Zed's AcpConnection.agent_capabilities
*/
get agentCapabilities(): AgentCapabilities | null {
return this._agentCapabilities;
}
/**
* Check if the agent supports loading existing sessions.
* Reference: Zed's AcpConnection.supports_load_session()
*/
get supportsLoadSession(): boolean {
return this._agentCapabilities?.loadSession === true;
}
/**
* Check if the agent supports resuming existing sessions.
* Reference: Zed's AcpConnection.supports_resume_session()
*/
get supportsResumeSession(): boolean {
return this._agentCapabilities?.sessionCapabilities?.resume !== undefined
&& this._agentCapabilities?.sessionCapabilities?.resume !== null;
}
/**
* Check if the agent supports listing sessions.
* Reference: Zed checks agent_capabilities.session_capabilities.list
*/
get supportsSessionList(): boolean {
return this._agentCapabilities?.sessionCapabilities?.list !== undefined
&& this._agentCapabilities?.sessionCapabilities?.list !== null;
}
/**
* Check if the agent supports session history (load or resume).
* Reference: Zed's AgentConnection.supports_session_history()
*/
get supportsSessionHistory(): boolean {
return this.supportsLoadSession || this.supportsResumeSession;
}
async connect(): Promise<void> {
// Clean up any existing connection first
if (this.ws) {
const oldWs = this.ws;
this.ws = null;
try { oldWs.close(); } catch { /* ignore */ }
this.stopHeartbeat();
this.connectResolve = null;
this.connectReject = null;
}
this.setState("connecting");
return new Promise((resolve, reject) => {
this.connectResolve = resolve;
this.connectReject = reject;
try {
// Build WebSocket URL with token if provided
let wsUrl = this.settings.proxyUrl;
if (this.settings.token) {
const url = new URL(wsUrl);
url.searchParams.set("token", this.settings.token);
wsUrl = url.toString();
}
const ws = new WebSocket(wsUrl);
this.ws = ws;
ws.onopen = () => {
// Guard against race condition: check if this WebSocket is still current
if (this.ws !== ws) {
console.log("[ACPClient] WebSocket opened but already disconnected/replaced, closing stale socket");
ws.close();
return;
}
console.log("[ACPClient] WebSocket connected, sending connect command");
this.send({ type: "connect" });
};
ws.onmessage = (event) => {
// Ignore messages from stale sockets
if (this.ws !== ws) return;
try {
const response: ProxyResponse = JSON.parse(event.data);
this.handleResponse(response);
} catch (error) {
console.error("[ACPClient] Failed to parse message:", error);
}
};
ws.onerror = () => {
// Ignore errors from stale sockets
if (this.ws !== ws) return;
console.error("[ACPClient] WebSocket error");
this.setState("error", "WebSocket connection error");
this.connectReject?.(new Error("WebSocket connection error"));
this.connectResolve = null;
this.connectReject = null;
};
ws.onclose = (event) => {
// Ignore close events from stale sockets (replaced by a new connection)
if (this.ws !== ws) return;
console.log("[ACPClient] WebSocket closed", event.code, event.reason);
// Check if closed due to auth failure (code 4001) or other error during connect
if (this.connectReject) {
const errorMessage = event.reason || `Connection closed (code: ${event.code})`;
this.setState("error", errorMessage);
this.connectReject(new Error(errorMessage));
this.connectResolve = null;
this.connectReject = null;
} else {
this.setState("disconnected");
}
this.ws = null;
this.sessionId = null;
};
} catch (error) {
this.setState("error", (error as Error).message);
reject(error);
}
});
}
private handleResponse(response: ProxyResponse): void {
console.log("[ACPClient] Received:", response.type);
switch (response.type) {
case "status":
if (response.payload.connected) {
// Reference: Zed stores full agentCapabilities from status message
this._agentCapabilities = response.payload.capabilities ?? null;
this.setState("connected");
this.startHeartbeat();
this.connectResolve?.();
} else {
this.stopHeartbeat();
this.setState("disconnected");
}
this.connectResolve = null;
this.connectReject = null;
break;
case "error":
console.error("[ACPClient] Error:", response.payload);
const errorMsg = response.payload?.message || JSON.stringify(response.payload);
this.pendingSessionTarget = null;
// Reject pending session operations if any (clear their timers)
if (this.pendingSessionList) {
clearTimeout(this.pendingSessionList.timer);
this.pendingSessionList.reject(new Error(errorMsg));
this.pendingSessionList = null;
}
if (this.pendingSessionLoad) {
clearTimeout(this.pendingSessionLoad.timer);
this.pendingSessionLoad.reject(new Error(errorMsg));
this.pendingSessionLoad = null;
}
if (this.pendingSessionResume) {
clearTimeout(this.pendingSessionResume.timer);
this.pendingSessionResume.reject(new Error(errorMsg));
this.pendingSessionResume = null;
}
// If during connect phase, reject the connect promise
if (this.connectReject) {
this.connectReject(new Error(errorMsg));
this.connectResolve = null;
this.connectReject = null;
} else {
// After connected, notify UI about the error
console.error("[ACPClient] Agent error:", errorMsg);
this.onErrorMessage?.(errorMsg);
}
break;
case "session_created":
this.sessionId = response.payload.sessionId;
this.pendingSessionTarget = null;
// Reference: Zed stores promptCapabilities from session/initialize response
this._promptCapabilities = response.payload.promptCapabilities ?? null;
// Reference: Zed stores model state from NewSessionResponse.models
this._modelState = response.payload.models ?? null;
console.log("[ACPClient] Session created, promptCapabilities:", this._promptCapabilities, "models:", this._modelState);
this.onSessionCreated?.(response.payload.sessionId);
// Notify model state subscribers (replaces polling in useModels)
this.onModelStateChanged?.(this._modelState);
break;
// Session history responses - Reference: Zed's AgentSessionList
case "session_list":
console.log("[ACPClient] Session list received:", response.payload.sessions.length, "sessions");
if (this.pendingSessionList) {
clearTimeout(this.pendingSessionList.timer);
this.pendingSessionList.resolve(response.payload);
this.pendingSessionList = null;
}
break;
case "session_loaded":
this.sessionId = response.payload.sessionId;
this.pendingSessionTarget = null;
this._promptCapabilities = response.payload.promptCapabilities ?? null;
this._modelState = response.payload.models ?? null;
console.log("[ACPClient] Session loaded:", response.payload.sessionId);
if (this.pendingSessionLoad) {
clearTimeout(this.pendingSessionLoad.timer);
this.pendingSessionLoad.resolve(response.payload.sessionId);
this.pendingSessionLoad = null;
}
this.onSessionLoaded?.(response.payload.sessionId);
this.onModelStateChanged?.(this._modelState);
break;
case "session_resumed":
this.sessionId = response.payload.sessionId;
this.pendingSessionTarget = null;
this._promptCapabilities = response.payload.promptCapabilities ?? null;
this._modelState = response.payload.models ?? null;
console.log("[ACPClient] Session resumed:", response.payload.sessionId);
if (this.pendingSessionResume) {
clearTimeout(this.pendingSessionResume.timer);
this.pendingSessionResume.resolve(response.payload.sessionId);
this.pendingSessionResume = null;
}
this.onSessionLoaded?.(response.payload.sessionId);
this.onModelStateChanged?.(this._modelState);
break;
case "session_update":
// Intercept available_commands_update for internal state
const updateType = response.payload.update?.sessionUpdate;
console.log("[ACPClient] session_update type:", updateType, "payload:", response.payload);
if (updateType === "available_commands_update") {
this._availableCommands = response.payload.update.availableCommands;
console.log("[ACPClient] Available commands updated:", this._availableCommands.length, "commands");
this.onAvailableCommandsChanged?.(this._availableCommands);
}
this.onSessionUpdate?.(response.payload.sessionId, response.payload.update);
break;
case "prompt_complete":
this.onPromptComplete?.(response.payload.stopReason);
break;
case "permission_request":
console.log("[ACPClient] Permission request:", response.payload);
this.onPermissionRequest?.(response.payload);
break;
case "model_changed":
console.log("[ACPClient] Model changed:", response.payload.modelId);
if (this._modelState) {
this._modelState = {
...this._modelState,
currentModelId: response.payload.modelId,
};
}
this.onModelChanged?.(response.payload.modelId);
break;
case "browser_tool_call":
this.handleBrowserToolCall(response.callId, response.params);
break;
case "pong":
this.missedPongs = 0;
if (this.heartbeatTimeout) {
clearTimeout(this.heartbeatTimeout);
this.heartbeatTimeout = null;
}
break;
}
}
private async handleBrowserToolCall(
callId: string,
params: BrowserToolParams,
): Promise<void> {
console.log("[ACPClient] Browser tool call:", callId, params);
if (!this.onBrowserToolCall) {
console.error("[ACPClient] No browser tool handler registered");
this.send({
type: "browser_tool_result",
callId,
result: { error: "No browser tool handler registered" },
});
return;
}
try {
const result = await this.onBrowserToolCall(params);
this.send({
type: "browser_tool_result",
callId,
result,
});
} catch (error) {
console.error("[ACPClient] Browser tool error:", error);
this.send({
type: "browser_tool_result",
callId,
result: { error: (error as Error).message },
});
}
}
private startHeartbeat(): void {
this.stopHeartbeat();
this.missedPongs = 0;
this.heartbeatInterval = setInterval(() => {
if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
this.stopHeartbeat();
return;
}
this.ws.send(JSON.stringify({ type: "ping" }));
this.heartbeatTimeout = setTimeout(() => {
this.missedPongs++;
if (this.missedPongs >= ACPClient.MAX_MISSED_PONGS) {
console.warn(`[ACPClient] Server unresponsive (${this.missedPongs} missed pongs), closing connection`);
this.stopHeartbeat();
this.ws?.close(4000, "Heartbeat timeout");
}
}, ACPClient.PONG_TIMEOUT_MS);
}, ACPClient.HEARTBEAT_INTERVAL_MS);
}
private stopHeartbeat(): void {
if (this.heartbeatInterval) {
clearInterval(this.heartbeatInterval);
this.heartbeatInterval = null;
}
if (this.heartbeatTimeout) {
clearTimeout(this.heartbeatTimeout);
this.heartbeatTimeout = null;
}
}
private send(message: ProxyMessage): void {
if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
throw new Error("WebSocket not connected");
}
this.ws.send(JSON.stringify(message));
}
async createSession(cwd?: string): Promise<void> {
// Use provided cwd, or fall back to settings.cwd
const sessionCwd = cwd ?? this.settings.cwd;
this.send({ type: "new_session", payload: { cwd: sessionCwd } });
}
// Reference: Zed's MessageEditor.contents() builds Vec<acp::ContentBlock>
// and sends via AcpThread.send()
// Accepts either a string (for backward compatibility) or ContentBlock[]
async sendPrompt(content: string | ContentBlock[]): Promise<void> {
if (!this.sessionId) {
throw new Error("No active session");
}
// Convert string to ContentBlock[] for backward compatibility
const contentBlocks: ContentBlock[] = typeof content === "string"
? [{ type: "text", text: content }]
: content;
this.send({ type: "prompt", payload: { content: contentBlocks } });
}
cancel(): void {
this.send({ type: "cancel" });
}
/**
* Set the model for the current session.
* Reference: Zed's AgentModelSelector.select_model() calls connection.set_session_model()
*/
async setSessionModel(modelId: string): Promise<void> {
if (!this.sessionId) {
throw new Error("No active session");
}
this.send({ type: "set_session_model", payload: { modelId } });
}
respondToPermission(requestId: string, optionId: string | null): void {
const outcome = optionId
? { outcome: "selected" as const, optionId }
: { outcome: "cancelled" as const };
this.send({
type: "permission_response",
payload: { requestId, outcome },
});
}
// ============================================================================
// Session History Methods
// Reference: Zed's AgentSessionList trait and AgentConnection methods
// ============================================================================
/**
* Set handler for session loaded/resumed events.
*/
setSessionLoadedHandler(handler: SessionLoadedHandler): void {
this.onSessionLoaded = handler;
}
/**
* List existing sessions from the agent.
* Reference: Zed's AcpSessionList.list_sessions()
* @throws Error if agent doesn't support session listing
*/
async listSessions(request?: ListSessionsRequest): Promise<ListSessionsResponse> {
if (!this.supportsSessionList) {
throw new Error("Listing sessions is not supported by this agent");
}
return new Promise((resolve, reject) => {
const timer = setTimeout(() => {
if (this.pendingSessionList) {
this.pendingSessionList = null;
reject(new Error("List sessions timed out"));
}
}, 30000);
this.pendingSessionList = { resolve, reject, timer };
try {
this.send({ type: "list_sessions", payload: request });
} catch (err) {
clearTimeout(timer);
this.pendingSessionList = null;
reject(err);
}
});
}
/**
* Load an existing session with history replay.
* Reference: Zed's AcpConnection.load_session()
* @throws Error if agent doesn't support session loading
*/
async loadSession(request: LoadSessionRequest): Promise<string> {
if (!this.supportsLoadSession) {
throw new Error("Loading sessions is not supported by this agent");
}
return new Promise((resolve, reject) => {
this.pendingSessionTarget = request.sessionId;
this.onSessionSwitching?.(request.sessionId);
const timer = setTimeout(() => {
if (this.pendingSessionLoad) {
this.pendingSessionTarget = null;
this.pendingSessionLoad = null;
reject(new Error("Load session timed out"));
}
}, 60000);
this.pendingSessionLoad = { resolve, reject, timer };
try {
this.send({ type: "load_session", payload: request });
} catch (err) {
clearTimeout(timer);
this.pendingSessionTarget = null;
this.pendingSessionLoad = null;
reject(err);
}
});
}
/**
* Resume an existing session without history replay.
* Reference: Zed's AcpConnection.resume_session()
* @throws Error if agent doesn't support session resuming
*/
async resumeSession(request: ResumeSessionRequest): Promise<string> {
if (!this.supportsResumeSession) {
throw new Error("Resuming sessions is not supported by this agent");
}
return new Promise((resolve, reject) => {
this.pendingSessionTarget = request.sessionId;
this.onSessionSwitching?.(request.sessionId);
const timer = setTimeout(() => {
if (this.pendingSessionResume) {
this.pendingSessionTarget = null;
this.pendingSessionResume = null;
reject(new Error("Resume session timed out"));
}
}, 30000);
this.pendingSessionResume = { resolve, reject, timer };
try {
this.send({ type: "resume_session", payload: request });
} catch (err) {
clearTimeout(timer);
this.pendingSessionTarget = null;
this.pendingSessionResume = null;
reject(err);
}
});
}
disconnect(): void {
this.stopHeartbeat();
// Reject any pending connect promise with a distinguishable error
// This ensures the promise settles and callers can catch/ignore it
if (this.connectReject) {
this.connectReject(new DisconnectRequestedError());
}
this.connectResolve = null;
this.connectReject = null;
if (this.ws) {
try {
// Don't send disconnect to acp-link — keep agent process alive for reconnection
// Just close the WebSocket
} catch {
// Ignore send errors during disconnect
}
this.ws.close();
this.ws = null;
}
this.setState("disconnected");
this.sessionId = null;
this.pendingSessionTarget = null;
this._modelState = null;
this._agentCapabilities = null;
this._availableCommands = [];
// Notify model state subscribers that session is gone
this.onModelStateChanged?.(null);
this.onAvailableCommandsChanged?.([]);
// Reject all pending operations before clearing (clear their timers too)
const disconnectError = new Error("Disconnected");
if (this.pendingSessionList) {
clearTimeout(this.pendingSessionList.timer);
this.pendingSessionList.reject(disconnectError);
this.pendingSessionList = null;
}
if (this.pendingSessionLoad) {
clearTimeout(this.pendingSessionLoad.timer);
this.pendingSessionLoad.reject(disconnectError);
this.pendingSessionLoad = null;
}
if (this.pendingSessionResume) {
clearTimeout(this.pendingSessionResume.timer);
this.pendingSessionResume.reject(disconnectError);
this.pendingSessionResume = null;
}
}
}

View File

@@ -0,0 +1,2 @@
export * from "./types";
export * from "./client";

View File

@@ -0,0 +1,24 @@
import { ACPClient } from "./client";
import type { ACPSettings } from "./types";
import { getUuid } 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:";
const uuid = getUuid();
return `${protocol}//${window.location.host}/acp/relay/${agentId}?uuid=${encodeURIComponent(uuid)}`;
}
/**
* Create an ACPClient that connects to an agent through the RCS relay.
* The relay transparently forwards ACP protocol messages between
* the frontend and the target acp-link instance.
*/
export function createRelayClient(agentId: string): ACPClient {
const relayUrl = buildRelayUrl(agentId);
const settings: ACPSettings = { proxyUrl: relayUrl };
return new ACPClient(settings);
}

View File

@@ -0,0 +1,548 @@
// Permission option kinds (from ACP protocol)
export type PermissionOptionKind =
| "allow_once"
| "allow_always"
| "reject_once"
| "reject_always";
// Permission option (from ACP protocol)
export interface PermissionOption {
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[];
toolCall: {
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 };
}
// ============================================================================
// Browser Tool Types
// ============================================================================
// IMPORTANT: These types MUST stay in sync with packages/proxy-server/src/mcp/types.ts
// They define the protocol between proxy-server and browser extension.
// ============================================================================
export interface BrowserToolParams {
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;
}
export interface BrowserTabsResult {
action: "tabs";
tabs: BrowserTabInfo[];
}
export interface BrowserReadResult {
action: "read";
tabId: number;
url: string;
title: string;
dom: string;
viewport: {
width: number;
height: number;
scrollX: number;
scrollY: number;
};
selection: string | null;
}
export interface BrowserExecuteResult {
action: "execute";
tabId: number;
url: string;
result?: unknown;
error?: string;
}
export type BrowserToolResult =
| BrowserTabsResult
| BrowserReadResult
| 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 } }
| { 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 }
// Heartbeat
| { type: "ping" };
// Messages received FROM the proxy server
// Reference: Zed's AgentConnection stores agentCapabilities from initialize response
export interface ProxyStatusMessage {
type: "status";
payload: {
connected: boolean;
agentInfo?: { name?: string; version?: string };
/** Full agent capabilities from initialize response */
capabilities?: AgentCapabilities;
};
}
export interface ProxyErrorMessage {
type: "error";
payload: { message: string };
}
// Reference: Zed's session/initialize response includes promptCapabilities and models
export interface ProxySessionCreatedMessage {
type: "session_created";
payload: {
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";
payload: {
sessionId: string;
update: SessionUpdate;
};
}
export interface ProxyPromptCompleteMessage {
type: "prompt_complete";
payload: { stopReason: string };
}
export interface ProxyPermissionRequestMessage {
type: "permission_request";
payload: PermissionRequestPayload;
}
export interface ProxyBrowserToolCallMessage {
type: "browser_tool_call";
callId: string;
params: BrowserToolParams;
}
export interface ProxyPongMessage {
type: "pong";
}
export interface ProxyModelChangedMessage {
type: "model_changed";
payload: {
modelId: string;
};
}
// ============================================================================
// Session History Response Types
// Reference: Zed's AgentSessionList in acp_thread/src/connection.rs
// ============================================================================
/**
* Response containing list of sessions.
* Reference: Zed's AgentSessionListResponse
*/
export interface ProxySessionListMessage {
type: "session_list";
payload: ListSessionsResponse;
}
/**
* Response when a session is loaded (with history replay).
* Reference: Zed's load_session returns Entity<AcpThread>
*/
export interface ProxySessionLoadedMessage {
type: "session_loaded";
payload: {
sessionId: string;
promptCapabilities?: PromptCapabilities;
models?: SessionModelState | null;
};
}
/**
* Response when a session is resumed (without history replay).
* Reference: Zed's resume_session returns Entity<AcpThread>
*/
export interface ProxySessionResumedMessage {
type: "session_resumed";
payload: {
sessionId: string;
promptCapabilities?: PromptCapabilities;
models?: SessionModelState | null;
};
}
export type ProxyResponse =
| ProxyStatusMessage
| ProxyErrorMessage
| ProxySessionCreatedMessage
| ProxySessionUpdateMessage
| ProxyPromptCompleteMessage
| ProxyPermissionRequestMessage
| ProxyBrowserToolCallMessage
| ProxyModelChangedMessage
| ProxyPongMessage
// Session history responses
| ProxySessionListMessage
| ProxySessionLoadedMessage
| 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;
}
export interface ImageContent {
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;
}
export type ContentBlock = TextContent | ImageContent | ResourceLinkContent | { type: string; text?: string };
// Session update types from ACP
export interface AgentMessageChunkUpdate {
sessionUpdate: "agent_message_chunk";
content: ContentBlock;
}
// Tool call content types from ACP
export interface ToolCallContentBlock {
type: "content";
content: ContentBlock;
}
export interface ToolCallDiffContent {
type: "diff";
path: string;
oldText?: string | null;
newText: string;
}
export interface ToolCallTerminalContent {
type: "terminal";
terminalId: string;
}
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>;
}
export interface ToolCallStatusUpdate {
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;
}
export interface PlanUpdate {
sessionUpdate: "plan";
}
export interface UserMessageChunkUpdate {
sessionUpdate: "user_message_chunk";
content: ContentBlock;
}
// Available command from agent (matches ACP SDK AvailableCommand)
export interface AvailableCommand {
name: string;
description: string;
input?: { hint: string };
}
export interface AvailableCommandsUpdate {
sessionUpdate: "available_commands_update";
availableCommands: AvailableCommand[];
}
export type SessionUpdate =
| AgentMessageChunkUpdate
| ToolCallUpdate
| ToolCallStatusUpdate
| AgentThoughtChunkUpdate
| PlanUpdate
| UserMessageChunkUpdate
| AvailableCommandsUpdate;
// Connection state
export type ConnectionState =
| "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
}
// ============================================================================
// Session Capabilities Types (matches @agentclientprotocol/sdk exactly)
// Reference: Zed's AgentCapabilities in agent_servers/src/acp.rs
// SDK types: @agentclientprotocol/sdk/dist/schema/types.gen.d.ts
// ============================================================================
/**
* MCP capabilities supported by the agent.
* Reference: acp::McpCapabilities
*/
export interface McpCapabilities {
/** Agent supports client-provided MCP servers */
clientServers?: boolean;
/** Reserved for extensibility */
_meta?: Record<string, unknown> | null;
}
/**
* Session list capability configuration.
* Reference: SDK's SessionListCapabilities (note: plural)
* @experimental - This capability is not part of the spec yet
*/
export interface SessionListCapabilities {
/** Reserved for extensibility */
_meta?: Record<string, unknown> | null;
}
/**
* Session resume capability configuration.
* Reference: SDK's SessionResumeCapabilities (note: plural)
* @experimental - This capability is not part of the spec yet
*/
export interface SessionResumeCapabilities {
/** Reserved for extensibility */
_meta?: Record<string, unknown> | null;
}
/**
* Session fork capability configuration.
* Reference: SDK's SessionForkCapabilities
* @experimental - This capability is not part of the spec yet
*/
export interface SessionForkCapabilities {
/** Reserved for extensibility */
_meta?: Record<string, unknown> | null;
}
/**
* Session capabilities supported by the agent.
* Reference: acp::SessionCapabilities
*
* As a baseline, all Agents MUST support session/new, session/prompt,
* session/cancel, and session/update.
* Optionally, they MAY support other session methods by specifying
* additional capabilities.
*/
export interface SessionCapabilities {
/** Reserved for extensibility */
_meta?: Record<string, unknown> | null;
/** @experimental Agent supports forking sessions via session/fork */
fork?: SessionForkCapabilities | null;
/** @experimental Agent supports listing sessions via session/list */
list?: SessionListCapabilities | null;
/** @experimental Agent supports resuming sessions via session/resume */
resume?: SessionResumeCapabilities | null;
}
/**
* Capabilities supported by the agent.
* Advertised during initialization to inform the client about
* available features and content types.
* Reference: acp::AgentCapabilities
*/
export interface AgentCapabilities {
/** Reserved for extensibility */
_meta?: Record<string, unknown> | null;
/** Whether the agent supports session/load */
loadSession?: boolean;
/** MCP capabilities supported by the agent */
mcpCapabilities?: McpCapabilities;
/** Prompt capabilities supported by the agent */
promptCapabilities?: PromptCapabilities;
/** Session capabilities supported by the agent */
sessionCapabilities?: SessionCapabilities;
}
// ============================================================================
// Session List/Load/Resume Types
// Reference: Zed's AgentSessionInfo, AgentSessionList in acp_thread/src/connection.rs
// SDK types: @agentclientprotocol/sdk SessionInfo, ListSessionsResponse
// ============================================================================
/**
* Information about an existing session.
* Returned by session/list and used for load/resume operations.
* Reference: acp::SessionInfo (SDK), Zed's AgentSessionInfo
* Note: SDK's SessionInfo has cwd as REQUIRED, but Zed's AgentSessionInfo has it optional
* We follow SDK here for protocol compatibility
*/
export interface AgentSessionInfo {
/** Reserved for extensibility */
_meta?: Record<string, unknown> | null;
/** Working directory for the session (required per SDK) */
cwd: string;
/** Unique identifier for the session */
sessionId: string;
/** Human-readable title for the session */
title?: string | null;
/** ISO 8601 timestamp when the session was last updated */
updatedAt?: string | null;
}
/**
* Request to list sessions.
* Reference: acp::ListSessionsRequest
*/
export interface ListSessionsRequest {
/** Reserved for extensibility */
_meta?: Record<string, unknown> | null;
/** Filter sessions by working directory */
cwd?: string;
/** Pagination cursor for fetching more results */
cursor?: string;
}
/**
* Response from listing sessions.
* Reference: acp::ListSessionsResponse (SDK)
*/
export interface ListSessionsResponse {
/** Reserved for extensibility */
_meta?: Record<string, unknown> | null;
/** Cursor for fetching the next page of results */
nextCursor?: string | null;
/** Array of session info objects */
sessions: AgentSessionInfo[];
}
/**
* Request to load an existing session.
* Reference: acp::LoadSessionRequest
*/
export interface LoadSessionRequest {
/** Reserved for extensibility */
_meta?: Record<string, unknown> | null;
/** Session ID to load */
sessionId: string;
/** Working directory for the session */
cwd?: string;
}
/**
* Request to resume an existing session without replaying history.
* Reference: acp::ResumeSessionRequest
*/
export interface ResumeSessionRequest {
/** Reserved for extensibility */
_meta?: Record<string, unknown> | null;
/** Session ID to resume */
sessionId: string;
/** Working directory for the session */
cwd?: string;
}
// ============================================================================
// Model Selection Types (matches @agentclientprotocol/sdk)
// Reference: Zed's AgentModelSelector trait in acp_thread/src/connection.rs
// ============================================================================
/**
* Information about a selectable model.
* Matches ACP SDK's ModelInfo type.
*/
export interface ModelInfo {
/** Unique identifier for the model */
modelId: string;
/** Human-readable name of the model */
name: string;
/** Optional description of the model */
description?: string | null;
}
/**
* The set of models and the one currently active.
* Matches ACP SDK's SessionModelState type.
*/
export interface SessionModelState {
/** The set of models that the Agent can use */
availableModels: ModelInfo[];
/** The current model the Agent is using */
currentModelId: string;
}
// Settings
export interface ACPSettings {
proxyUrl: string;
/** Auth token for remote access (passed as ?token=xxx query param) */
token?: string;
/** Working directory for the agent session */
cwd?: string;
}
export const DEFAULT_SETTINGS: ACPSettings = {
proxyUrl: "ws://localhost:9315/ws",
};

View File

@@ -0,0 +1,82 @@
import type { Session, Environment, ControlResponse, SessionEvent } from "../types";
const BASE = "";
function generateUuid(): string {
if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") {
return crypto.randomUUID();
}
return "10000000-1000-4000-8000-100000000000".replace(/[018]/g, (c) =>
(Number(c) ^ (crypto.getRandomValues(new Uint8Array(1))[0] & (15 >> (Number(c) / 4)))).toString(16),
);
}
export function getUuid(): string {
let uuid = localStorage.getItem("rcs_uuid");
if (!uuid) {
uuid = generateUuid();
localStorage.setItem("rcs_uuid", uuid);
}
return uuid;
}
export function setUuid(uuid: string): void {
localStorage.setItem("rcs_uuid", uuid);
}
async function api<T>(method: string, path: string, body?: unknown): Promise<T> {
const headers: Record<string, string> = { "Content-Type": "application/json" };
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();
if (!res.ok) {
const err = data.error || { type: "unknown", message: res.statusText };
throw new Error(err.message || err.type);
}
return data as T;
}
export function apiBind(sessionId: string) {
return api<void>("POST", "/web/bind", { sessionId });
}
export function apiFetchSessions() {
return api<Session[]>("GET", "/web/sessions");
}
export function apiFetchAllSessions() {
return api<Session[]>("GET", "/web/sessions/all");
}
export function apiFetchSession(id: string) {
return api<Session>("GET", `/web/sessions/${id}`);
}
export function apiFetchSessionHistory(id: string) {
return api<{ events: SessionEvent[] }>("GET", `/web/sessions/${id}/history`);
}
export function apiFetchEnvironments() {
return api<Environment[]>("GET", "/web/environments");
}
export function apiSendEvent(sessionId: string, body: Record<string, unknown>) {
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);
}
export function apiInterrupt(sessionId: string) {
return api<void>("POST", `/web/sessions/${sessionId}/interrupt`);
}
export function apiCreateSession(body: { title?: string; environment_id?: string }) {
return api<Session>("POST", "/web/sessions", body);
}

View File

@@ -0,0 +1,41 @@
import { getUuid } from "./client";
import type { SessionEvent } from "../types";
let currentEventSource: EventSource | null = null;
export function connectSSE(
sessionId: string,
onEvent: (event: SessionEvent) => void,
fromSeqNum = 0,
): void {
disconnectSSE();
const uuid = getUuid();
const url = `/web/sessions/${sessionId}/events?uuid=${encodeURIComponent(uuid)}`;
const es = new EventSource(url);
currentEventSource = es;
let lastSeenSeq = fromSeqNum;
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);
} catch {
// ignore parse errors
}
});
es.addEventListener("error", () => {
// EventSource auto-reconnects
});
}
export function disconnectSSE(): void {
if (currentEventSource) {
currentEventSource.close();
currentEventSource = null;
}
}

View File

@@ -0,0 +1,85 @@
import { useState, useRef, useEffect } from "react";
import { cn, isClosedSessionStatus } from "../lib/utils";
interface ControlBarProps {
sessionId: string;
sessionStatus: string | null;
activityMode: string;
onSend: (text: string) => Promise<void>;
onInterrupt: () => Promise<void>;
}
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 handleSend = async () => {
const trimmed = text.trim();
if (!trimmed || closed) return;
setText("");
try {
await onSend(trimmed);
} catch {
setText(trimmed);
}
};
const handleKeyDown = (e: React.KeyboardEvent) => {
if (e.key === "Enter" && !e.shiftKey && !e.nativeEvent?.isComposing) {
e.preventDefault();
handleSend();
}
};
useEffect(() => {
inputRef.current?.focus();
}, [sessionId]);
return (
<div className="border-t border-border bg-surface-1 px-4 py-3">
<div className="mx-auto flex max-w-5xl items-center gap-2">
<input
ref={inputRef}
type="text"
value={text}
onChange={(e) => setText(e.target.value)}
onKeyDown={handleKeyDown}
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"
/>
<button
onClick={working ? onInterrupt : handleSend}
disabled={closed}
className={cn(
"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",
)}
aria-label={working ? "Stop" : "Send"}
title={closed ? "Session is closed" : working ? "Stop" : "Send"}
>
{working ? (
<svg width="18" height="18" viewBox="0 0 18 18" fill="none">
<rect x="3" y="3" width="12" height="12" rx="2" fill="currentColor" />
</svg>
) : (
<svg width="20" height="20" viewBox="0 0 20 20" fill="none">
<path d="M3 10L17 3L10 17L9 11L3 10Z" fill="currentColor" />
</svg>
)}
</button>
</div>
</div>
);
}

View File

@@ -0,0 +1,56 @@
import type { Environment } from "../types";
import { StatusBadge } from "./Navbar";
import { esc, formatTime } from "../lib/utils";
interface EnvironmentListProps {
environments: Environment[];
onSelectEnvironment?: (env: Environment) => void;
}
export function EnvironmentList({ environments, onSelectEnvironment }: EnvironmentListProps) {
if (!environments || environments.length === 0) {
return (
<div className="rounded-xl border border-border bg-surface-1 p-8 text-center text-text-muted">
No active environments
</div>
);
}
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-purple-100 text-purple-700" : "bg-blue-100 text-blue-700";
return (
<div
key={env.id}
onClick={() => onSelectEnvironment?.(env)}
className={`flex items-center justify-between rounded-xl border border-border bg-surface-1 px-4 py-3 transition-colors hover:border-border-light ${onSelectEnvironment ? "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>
</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>
</div>
);
})}
</div>
);
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,218 @@
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";
interface IdentityPanelProps {
open: boolean;
onClose: () => void;
}
export function IdentityPanel({ open, onClose }: IdentityPanelProps) {
const [copied, setCopied] = useState(false);
const [scanning, setScanning] = useState(false);
const canvasRef = useRef<HTMLCanvasElement>(null);
const videoRef = useRef<HTMLVideoElement>(null);
const scannerRef = useRef<QrScanner | null>(null);
const uuid = getUuid();
useEffect(() => {
if (!open || !canvasRef.current) return;
const qrUrl = `${window.location.origin}/code?uuid=${encodeURIComponent(uuid)}`;
QRCode.toCanvas(canvasRef.current, qrUrl, {
width: 200,
margin: 1,
color: { dark: "#f0f0f2", light: "#141416" },
});
}, [open, uuid]);
// Cleanup scanner on close
useEffect(() => {
if (!open && scannerRef.current) {
scannerRef.current.stop();
scannerRef.current.destroy();
scannerRef.current = null;
setScanning(false);
}
}, [open]);
if (!open) return null;
const handleCopy = async () => {
await navigator.clipboard.writeText(uuid);
setCopied(true);
setTimeout(() => setCopied(false), 2000);
};
const startCamera = async () => {
if (!videoRef.current) return;
setScanning(true);
try {
const scanner = new QrScanner(
videoRef.current,
(result) => {
handleScannedData(result.data);
},
{ returnDetailedScanResult: true },
);
scannerRef.current = scanner;
await scanner.start();
} catch (e) {
console.error("Camera error:", e);
setScanning(false);
}
};
const stopCamera = () => {
if (scannerRef.current) {
scannerRef.current.stop();
scannerRef.current.destroy();
scannerRef.current = null;
}
setScanning(false);
};
const handleScannedData = (data: string) => {
try {
// Try ACP format: { url, token }
const parsed = JSON.parse(data);
if (parsed.url && parsed.token) {
// ACP format — extract token as UUID-like identifier
stopCamera();
onClose();
return;
}
} catch {
// Not JSON
}
// Try URL with uuid param
try {
const url = new URL(data);
const importedUuid = url.searchParams.get("uuid");
if (importedUuid) {
setUuid(importedUuid);
stopCamera();
onClose();
return;
}
} catch {
// Not a URL
}
// Raw UUID string
if (data.length >= 32) {
setUuid(data);
stopCamera();
onClose();
return;
}
};
const handleScanUpload = () => {
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 {
const result = await QrScanner.scanImage(file, {
returnDetailedScanResult: true,
});
handleScannedData(result.data);
} catch {
alert("No QR code found in image");
}
};
input.click();
};
return (
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50" onClick={onClose}>
<div
className="w-full max-w-sm rounded-2xl border border-border bg-surface-1 p-6 shadow-2xl"
onClick={(e) => e.stopPropagation()}
>
<div className="mb-4 flex items-center justify-between">
<h3 className="font-display text-lg font-semibold text-text-primary">Identity</h3>
<button
onClick={onClose}
className="rounded-md px-2 py-1 text-text-muted hover:bg-surface-2 hover:text-text-secondary transition-colors"
>
&times;
</button>
</div>
<div className="space-y-6">
{/* UUID */}
<div>
<label className="mb-1 block text-sm text-text-secondary">Your UUID</label>
<div className="flex items-center gap-2">
<code className="flex-1 truncate rounded-lg bg-surface-2 px-3 py-2 font-mono text-xs text-text-primary">
{uuid}
</code>
<button
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"}
</button>
</div>
</div>
{/* QR Code display */}
{!scanning && (
<div>
<label className="mb-2 block text-sm text-text-secondary">Scan on another device</label>
<div className="flex justify-center">
<canvas ref={canvasRef} />
</div>
</div>
)}
{/* Camera scanner */}
{scanning && (
<div>
<label className="mb-2 block text-sm text-text-secondary">Camera scanner</label>
<div className="relative overflow-hidden rounded-lg">
<video ref={videoRef} className="w-full" />
</div>
<button
onClick={stopCamera}
className="mt-2 w-full rounded-lg border border-border px-4 py-2 text-sm text-text-secondary hover:bg-surface-2 transition-colors"
>
Stop scanning
</button>
</div>
)}
{/* Action buttons */}
<div className="flex gap-2">
<button
onClick={scanning ? stopCamera : startCamera}
className={cn(
"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",
)}
>
<svg width="16" height="16" viewBox="0 0 16 16" fill="none">
<path d="M1 1H5V3H3V5H1V1ZM11 1H15V5H13V3H11V1ZM1 11H3V13H5V15H1V11ZM13 11H15V15H11V13H13V11ZM6 6H10V10H6V6Z" fill="currentColor" />
</svg>
{scanning ? "Stop Camera" : "Scan with Camera"}
</button>
<button
onClick={handleScanUpload}
className="flex items-center gap-2 rounded-lg border border-border px-4 py-2 text-sm text-text-secondary hover:bg-surface-2 transition-colors"
>
Upload QR Image
</button>
</div>
</div>
</div>
</div>
);
}

View File

@@ -0,0 +1,52 @@
import { useState, useEffect, useRef } from "react";
const SPINNER_FRAMES = ["·", "✢", "✱", "✶", "✻", "✽"];
const SPINNER_CYCLE = [...SPINNER_FRAMES, ...SPINNER_FRAMES.slice().reverse()];
interface LoadingIndicatorProps {
verb?: string;
stalled?: boolean;
}
export function LoadingIndicator({ verb = "Thinking", stalled = false }: LoadingIndicatorProps) {
const [frame, setFrame] = useState(0);
const [elapsed, setElapsed] = useState(0);
const startTimeRef = useRef(Date.now());
// Spinner animation — 120ms per frame
useEffect(() => {
const id = setInterval(() => {
setFrame((f) => (f + 1) % SPINNER_CYCLE.length);
}, 120);
return () => clearInterval(id);
}, []);
// Timer — 1s updates
useEffect(() => {
startTimeRef.current = Date.now();
const id = setInterval(() => {
setElapsed(Math.floor((Date.now() - startTimeRef.current) / 1000));
}, 1000);
return () => clearInterval(id);
}, []);
return (
<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)" }}
>
{SPINNER_CYCLE[frame]}
</span>
<span
className="glimmer-text text-sm font-medium transition-colors duration-2000"
style={stalled ? undefined : undefined}
>
{verb}
</span>
<span className="ml-auto text-xs font-mono text-text-muted">
{elapsed}s
</span>
</div>
);
}

View File

@@ -0,0 +1,67 @@
import { cn } from "../lib/utils";
interface NavbarProps {
onIdentityClick: () => void;
}
export function Navbar({ onIdentityClick }: NavbarProps) {
return (
<nav className="sticky top-0 z-40 border-b border-border bg-surface-1/80 backdrop-blur-md">
<div className="mx-auto flex h-14 max-w-5xl items-center justify-between px-4">
<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">
<path
d="M10 1L12.2 7.8L19 10L12.2 12.2L10 19L7.8 12.2L1 10L7.8 7.8L10 1Z"
fill="#D97757"
/>
</svg>
Remote Control
</a>
<div className="flex items-center gap-1">
<a
href="/code/"
className="rounded-md px-3 py-1.5 text-sm text-text-secondary hover:bg-surface-2 hover:text-text-primary no-underline transition-colors"
>
Dashboard
</a>
<button
onClick={onIdentityClick}
className="flex items-center gap-1 rounded-md px-3 py-1.5 text-sm text-text-secondary hover:bg-surface-2 hover:text-text-primary transition-colors"
title="Identity & QR"
>
<svg width="16" height="16" viewBox="0 0 16 16" fill="none">
<path
d="M6 8C7.66 8 9 6.66 9 5C9 3.34 7.66 2 6 2C4.34 2 3 3.34 3 5C3 6.66 4.34 8 6 8ZM6 10C3.99 10 0 11.01 0 13V14H12V13C12 11.01 8.01 10 6 10ZM13 8V5H11V8H8V10H11V13H13V10H16V8H13Z"
fill="currentColor"
/>
</svg>
Identity
</button>
</div>
</div>
</nav>
);
}
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",
};
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",
)}
>
{status}
</span>
);
}

View File

@@ -0,0 +1,101 @@
import { useState, useEffect } from "react";
import type { Environment, Session } from "../types";
import { apiCreateSession } from "../api/client";
interface NewSessionDialogProps {
open: boolean;
environments: Environment[];
onClose: () => void;
onCreated: (session: Session) => void;
}
export function NewSessionDialog({ open, environments, onClose, onCreated }: NewSessionDialogProps) {
const [title, setTitle] = useState("");
const [envId, setEnvId] = useState("");
const [error, setError] = useState("");
const [creating, setCreating] = useState(false);
useEffect(() => {
if (open) {
setTitle("");
setEnvId("");
setError("");
}
}, [open]);
if (!open) return null;
const handleCreate = async () => {
setCreating(true);
setError("");
try {
const body: Record<string, string> = {};
if (title.trim()) body.title = title.trim();
if (envId) body.environment_id = envId;
const session = await apiCreateSession(body);
onCreated(session);
} catch (err) {
setError(err instanceof Error ? err.message : "Failed to create session");
} finally {
setCreating(false);
}
};
return (
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50" onClick={onClose}>
<div
className="w-full max-w-md rounded-2xl border border-border bg-surface-1 p-6 shadow-2xl"
onClick={(e) => e.stopPropagation()}
>
<h3 className="mb-4 font-display text-lg font-semibold text-text-primary">New Session</h3>
<div className="space-y-4">
<div>
<label className="mb-1 block text-sm text-text-secondary">Title (optional)</label>
<input
type="text"
value={title}
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"
/>
</div>
<div>
<label className="mb-1 block text-sm text-text-secondary">Environment</label>
<select
value={envId}
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) => (
<option key={env.id} value={env.id}>
{env.machine_name || env.id} ({env.branch || "no branch"})
</option>
))}
</select>
</div>
{error && <div className="text-sm text-status-error">{error}</div>}
<div className="flex justify-end gap-2 pt-2">
<button
onClick={onClose}
className="rounded-lg border border-border px-4 py-2 text-sm text-text-secondary hover:bg-surface-2 transition-colors"
>
Cancel
</button>
<button
onClick={handleCreate}
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"}
</button>
</div>
</div>
</div>
</div>
);
}

View File

@@ -0,0 +1,368 @@
import { useState } from "react";
import type { Question } from "../types";
import { esc, cn, truncate } from "../lib/utils";
// ============================================================
// PermissionPromptView — simple approve/reject for tool use
// ============================================================
export function PermissionPromptView({
requestId,
toolName,
toolInput,
description,
onApprove,
onReject,
}: {
requestId: string;
toolName: string;
toolInput: unknown;
description: string;
onApprove: () => void;
onReject: () => void;
}) {
const inputStr = typeof toolInput === "string" ? toolInput : JSON.stringify(toolInput, null, 2);
return (
<div className="rounded-xl border border-warning-border/30 border-l-3 border-l-warning-border bg-surface-1 p-4">
<div className="mb-2 flex items-center gap-2">
<span className="flex h-5 w-5 items-center justify-center rounded-full bg-warning-border/15 text-warning-text">
<svg width="12" height="12" viewBox="0 0 12 12" fill="none">
<path d="M6 1L11 10H1L6 1Z" fill="currentColor" />
</svg>
</span>
<span className="text-sm font-semibold text-warning-text">Permission Request</span>
</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" && (
<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>
)}
<div className="flex gap-2">
<button
onClick={onApprove}
className="rounded-lg bg-brand px-4 py-2 text-sm font-medium text-white hover:bg-brand-light transition-colors"
>
Approve
</button>
<button
onClick={onReject}
className="rounded-lg bg-status-error/20 px-4 py-2 text-sm font-medium text-status-error hover:bg-status-error/30 transition-colors"
>
Reject
</button>
</div>
</div>
);
}
// ============================================================
// AskUserPanelView — multi-question interactive panel
// ============================================================
export function AskUserPanelView({
questions,
description,
onSubmit,
onSkip,
}: {
requestId: string;
questions: Question[];
description: string;
onSubmit: (answers: Record<string, unknown>) => void;
onSkip: () => void;
}) {
const [answers, setAnswers] = useState<Record<string, unknown>>({});
const [otherTexts, setOtherTexts] = useState<Record<string, string>>({});
const [activeTab, setActiveTab] = useState(0);
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];
setAnswers({ ...answers, [qIdx]: next });
} else {
setAnswers({ ...answers, [qIdx]: oIdx });
}
};
const handleOtherSubmit = (qIdx: number) => {
const text = otherTexts[qIdx]?.trim();
if (!text) return;
setAnswers({ ...answers, [qIdx]: text });
setOtherTexts({ ...otherTexts, [qIdx]: "" });
};
const handleSubmit = () => {
const mapped: Record<string, unknown> = {};
for (const [qIdx, val] of Object.entries(answers)) {
const q = questions[parseInt(qIdx)];
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));
else mapped[qIdx] = val;
}
onSubmit(mapped);
};
// Single question — simple layout
if (questions.length <= 1) {
const q = questions[0] || { question: description, options: [], multiSelect: false };
const multiSelect = q.multiSelect || false;
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")}
</div>
<div className="space-y-2">
{(q.options || []).map((opt, 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",
isSelected
? "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>
{opt.description && <div className="mt-0.5 text-xs text-text-muted">{esc(opt.description)}</div>}
</button>
);
})}
<div className="flex gap-2">
<input
type="text"
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)}
/>
<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>
</div>
</div>
);
}
// Multiple questions — tab layout
const currentQ = questions[activeTab];
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 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",
)}
>
{q.header || `Q${i + 1}`}
</button>
))}
</div>
{currentQ && (
<QuestionTab
question={currentQ}
qIdx={activeTab}
answers={answers}
otherTexts={otherTexts}
onSelect={handleSelect}
onOtherTextChange={(qIdx, text) => setOtherTexts({ ...otherTexts, [qIdx]: text })}
onOtherSubmit={handleOtherSubmit}
/>
)}
<div className="mt-4 flex items-center justify-between">
<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>
</div>
</div>
</div>
);
}
function QuestionTab({
question, qIdx, answers, otherTexts, onSelect, onOtherTextChange, onOtherSubmit,
}: {
question: Question;
qIdx: number;
answers: Record<string, unknown>;
otherTexts: Record<string, string>;
onSelect: (qIdx: number, oIdx: number, multiSelect: boolean) => void;
onOtherTextChange: (qIdx: number, text: string) => void;
onOtherSubmit: (qIdx: number) => void;
}) {
const multiSelect = question.multiSelect || false;
return (
<div>
<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;
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",
isSelected
? "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>
{opt.description && <div className="mt-0.5 text-xs text-text-muted">{esc(opt.description)}</div>}
</button>
);
})}
<div className="flex gap-2">
<input
type="text"
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)}
/>
<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>
);
}
// ============================================================
// PlanPanelView — plan approval with feedback
// ============================================================
export function PlanPanelView({
planContent,
description,
onSubmit,
}: {
requestId: string;
planContent: string;
description: string;
onSubmit: (value: string, feedback?: string) => void;
}) {
const [selected, setSelected] = useState<string | null>(null);
const [feedback, setFeedback] = useState("");
const isEmpty = !planContent || !planContent.trim();
const handleSubmit = () => {
if (!selected) return;
onSubmit(selected, selected === "no" ? feedback : undefined);
};
return (
<div className="rounded-xl border border-brand/30 bg-surface-1 p-4">
<div className="mb-3 flex items-center gap-2">
<span className="flex h-5 w-5 items-center justify-center rounded-full bg-brand/15 text-brand">
<svg width="12" height="12" viewBox="0 0 12 12" fill="none">
<path d="M2 6L5 9L10 3" stroke="currentColor" strokeWidth="1.5" fill="none" />
</svg>
</span>
<span className="text-sm font-semibold text-text-primary">
{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"
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-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" && (
<textarea
value={feedback}
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}
/>
)}
<div className="mt-4">
<button
onClick={handleSubmit}
disabled={!selected}
className="rounded-lg bg-brand px-4 py-2 text-sm font-medium text-white hover:bg-brand-light disabled:opacity-50 transition-colors"
>
Submit
</button>
</div>
</div>
);
}
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",
)}
>
<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>
<span className="font-medium">{label}</span>
</div>
{desc && <div className="mt-0.5 pl-6 text-xs text-text-muted">{desc}</div>}
</button>
);
}
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(/`([^`]+)`/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>");
return html;
}

View File

@@ -0,0 +1,52 @@
import type { Session } from "../types";
import { StatusBadge } from "./Navbar";
import { esc, formatTime } from "../lib/utils";
interface SessionListProps {
sessions: Session[];
onSelect: (sessionId: string) => void;
}
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>
);
}
const sorted = [...sessions].sort((a, b) => (b.updated_at || 0) - (a.updated_at || 0));
return (
<div className="space-y-2">
{sorted.map((session) => (
<div
key={session.id}
onClick={() => onSelect(session.id)}
className="flex cursor-pointer items-center justify-between rounded-xl border border-border bg-surface-1 px-4 py-3 transition-colors hover:border-border-light hover:bg-surface-2"
>
<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-purple-100 px-2 py-0.5 text-xs font-medium text-purple-700">
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>
</div>
</div>
))}
</div>
);
}

View File

@@ -0,0 +1,25 @@
interface TaskPanelProps {
onClose: () => void;
}
export function TaskPanel({ onClose }: TaskPanelProps) {
return (
<div className="fixed inset-0 z-50 flex justify-end bg-black/30" onClick={onClose}>
<div
className="w-80 border-l border-border bg-surface-1 p-4"
onClick={(e) => e.stopPropagation()}
>
<div className="mb-4 flex items-center justify-between">
<h3 className="font-display font-semibold text-text-primary">Tasks</h3>
<button
onClick={onClose}
className="rounded-md px-2 py-1 text-text-muted hover:bg-surface-2 hover:text-text-secondary transition-colors"
>
&times;
</button>
</div>
<div className="text-sm text-text-muted">No active tasks</div>
</div>
</div>
);
}

View File

@@ -0,0 +1,3 @@
export { useModels, type UseModelsResult } from "./useModels";
export { useCommands, type UseCommandsResult } from "./useCommands";
export { useQRScanner, type QRCodeData, type UseQRScannerOptions, type UseQRScannerResult } from "./useQRScanner";

View File

@@ -0,0 +1,12 @@
import { useState, useCallback } from "react";
import { getUuid, setUuid } from "../api/client";
export function useAuth() {
const [uuid] = useState(() => getUuid());
const importUuid = useCallback((newUuid: string) => {
setUuid(newUuid);
}, []);
return { uuid, importUuid };
}

View File

@@ -0,0 +1,39 @@
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[];
/** Whether any commands are available */
hasCommands: boolean;
}
/**
* Hook to manage available commands state.
* Follows the same pattern as useModels — event-driven with immediate callback.
*/
export function useCommands(client: ACPClient): UseCommandsResult {
const [commands, setCommands] = useState<AvailableCommand[]>(
client.availableCommands,
);
useEffect(() => {
const handleCommandsChanged = (newCommands: AvailableCommand[]) => {
setCommands(newCommands);
};
client.setAvailableCommandsChangedHandler(handleCommandsChanged);
return () => {
client.setAvailableCommandsChangedHandler(() => {});
};
}, [client]);
const hasCommands = useMemo(
() => commands.length > 0,
[commands],
);
return { commands, hasCommands };
}

View File

@@ -0,0 +1,103 @@
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;
/** List of available models */
availableModels: ModelInfo[];
/** The currently selected model ID */
currentModelId: string | null;
/** The currently selected model info */
currentModel: ModelInfo | null;
/** Set the model for the current session */
setModel: (modelId: string) => Promise<void>;
/** Whether a model change is in progress */
isLoading: boolean;
}
/**
* Hook to manage model selection state.
* Reference: Zed's AcpModelSelector reads from state.available_models and state.current_model_id
*
* Uses event-driven updates instead of polling:
* - setModelStateChangedHandler: called on session create/disconnect
* - setModelChangedHandler: called when model selection changes
*/
export function useModels(client: ACPClient): UseModelsResult {
const [modelState, setModelState] = useState<SessionModelState | null>(
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);
};
// Handler for when current model changes within a session
const handleModelChanged = (modelId: string) => {
setModelState((prev) => {
if (!prev) return null;
return {
...prev,
currentModelId: modelId,
};
});
setIsLoading(false);
};
// Register handlers - setModelStateChangedHandler immediately calls with current state
client.setModelStateChangedHandler(handleModelStateChanged);
client.setModelChangedHandler(handleModelChanged);
return () => {
// Clear handlers on unmount
client.setModelStateChangedHandler(() => {});
client.setModelChangedHandler(() => {});
};
}, [client]);
const availableModels = useMemo(
() => modelState?.availableModels ?? [],
[modelState]
);
const currentModelId = modelState?.currentModelId ?? null;
const currentModel = useMemo(
() =>
availableModels.find((m) => m.modelId === currentModelId) ?? null,
[availableModels, currentModelId]
);
const setModel = useCallback(
async (modelId: string) => {
if (!modelState) {
throw new Error("Model selection not supported");
}
setIsLoading(true);
try {
await client.setSessionModel(modelId);
// The model_changed event will update the state
} catch (error) {
setIsLoading(false);
throw error;
}
},
[client, modelState]
);
return {
supportsModelSelection: modelState !== null && availableModels.length > 0,
availableModels,
currentModelId,
currentModel,
setModel,
isLoading,
};
}

View File

@@ -0,0 +1,163 @@
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;
}
export interface UseQRScannerOptions {
/** Called when a valid QR code is scanned */
onScan: (data: QRCodeData) => void;
/** Called when an error occurs */
onError?: (error: string) => void;
}
export interface UseQRScannerResult {
/** Whether the scanner is currently active */
isScanning: boolean;
/** Ref to attach to the video element */
videoRef: React.RefObject<HTMLVideoElement | null>;
/** Start scanning */
startScanning: () => void;
/** Stop scanning */
stopScanning: () => void;
/** Scan QR code from a file (e.g., from photo album) */
scanFromFile: (file: File) => Promise<void>;
}
/**
* Hook for QR code scanning functionality.
* Manages QrScanner lifecycle and camera access.
*/
export function useQRScanner({
onScan,
onError,
}: UseQRScannerOptions): UseQRScannerResult {
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);
// Keep refs up to date
useEffect(() => {
onScanRef.current = onScan;
onErrorRef.current = onError;
}, [onScan, onError]);
const startScanning = useCallback(() => {
setIsScanning(true);
}, []);
const stopScanning = useCallback(() => {
if (qrScannerRef.current) {
qrScannerRef.current.stop();
qrScannerRef.current.destroy();
qrScannerRef.current = null;
}
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;
if (data.url && data.token) {
onScanRef.current(data);
} else {
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);
}
}, []);
// Initialize scanner when isScanning becomes true
useEffect(() => {
if (!isScanning || !videoRef.current) return;
let isCancelled = false;
let scanner: QrScanner | null = null;
const initScanner = async () => {
try {
const newScanner = new QrScanner(
videoRef.current!,
(result) => {
try {
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);
}
} catch {
// Not valid JSON, ignore
}
},
{
returnDetailedScanResult: true,
highlightScanRegion: true,
highlightCodeOutline: true,
}
);
if (isCancelled) {
newScanner.destroy();
return;
}
scanner = newScanner;
qrScannerRef.current = newScanner;
await newScanner.start();
if (isCancelled) {
newScanner.stop();
newScanner.destroy();
qrScannerRef.current = null;
}
} catch (e) {
if (!isCancelled) {
onErrorRef.current?.(`Camera error: ${(e as Error).message}`);
setIsScanning(false);
}
}
};
initScanner();
return () => {
isCancelled = true;
if (scanner) {
scanner.stop();
scanner.destroy();
}
if (qrScannerRef.current) {
qrScannerRef.current.stop();
qrScannerRef.current.destroy();
qrScannerRef.current = null;
}
};
}, [isScanning]); // Only depend on isScanning, callbacks are accessed via refs
return {
isScanning,
videoRef,
startScanning,
stopScanning,
scanFromFile,
};
}

View File

@@ -0,0 +1,25 @@
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 stableCallback = useCallback((event: SessionEvent) => {
onEventRef.current(event);
}, []);
useEffect(() => {
if (!sessionId) return;
connectSSE(sessionId, stableCallback);
return () => {
disconnectSSE();
};
}, [sessionId, stableCallback]);
}

View File

@@ -0,0 +1,220 @@
/* Font imports must precede @import "tailwindcss" per CSS spec */
@import url("https://fonts.googleapis.com/css2?family=Lora:ital,wght@0,400;0,500;0,600;0,700;1,400&family=Poppins:wght@300;400;500;600;700&family=JetBrains+Mono:wght@400;500&display=swap");
@import "tailwindcss";
/* ============================================================
Theme — Anthropic-inspired warm design tokens
============================================================ */
@theme {
/* Fonts — Lora (serif body) + Poppins (sans-serif UI) + JetBrains Mono */
--font-sans: "Lora", Georgia, serif;
--font-display: "Poppins", sans-serif;
--font-mono: "JetBrains Mono", monospace;
/* Brand — signature orange */
--color-brand: #D97757;
--color-brand-light: #C96A4D;
--color-brand-subtle: rgba(217, 119, 87, 0.1);
/* Surfaces — warm beige palette (not white) */
--color-surface-0: #ECE9E0;
--color-surface-1: #F5F3EC;
--color-surface-2: #FDFCF8;
--color-surface-3: #E8E6DC;
/* Text — warm dark tones */
--color-text-primary: #141413;
--color-text-secondary: #6B6860;
--color-text-muted: #9C9890;
/* Inverted — for user message bubbles */
--color-bg-inverted: #2D2B27;
--color-text-inverted: #F5F3EC;
/* Warning — warm yellow for permission panels */
--color-warning-bg: #FEF3C7;
--color-warning-border: #F59E0B;
--color-warning-text: #92400E;
/* Status */
--color-status-active: #6B8F47;
--color-status-running: #4A7FB5;
--color-status-idle: #7C3aed;
--color-status-error: #C0453A;
--color-status-warning: #C9943A;
/* Tool card */
--color-tool-card: #F5F3EC;
/* shadcn/ui tokens (oklch — warm hue ~85) */
--color-background: oklch(0.94 0.01 85);
--color-foreground: oklch(0.20 0.01 85);
--color-card: oklch(0.97 0.008 85);
--color-card-foreground: oklch(0.20 0.01 85);
--color-popover: oklch(0.97 0.008 85);
--color-popover-foreground: oklch(0.20 0.01 85);
--color-primary: oklch(0.20 0.01 85);
--color-primary-foreground: oklch(0.96 0.01 85);
--color-secondary: oklch(0.95 0.01 85);
--color-secondary-foreground: oklch(0.20 0.01 85);
--color-muted: oklch(0.93 0.01 85);
--color-muted-foreground: oklch(0.50 0.02 85);
--color-accent: oklch(0.95 0.01 85);
--color-accent-foreground: oklch(0.20 0.01 85);
--color-destructive: oklch(0.577 0.245 27.325);
/* Border / Input / Ring */
--color-border: oklch(0.88 0.015 85);
--color-border-light: #E8E6DC;
--color-input: oklch(0.88 0.015 85);
--color-ring: oklch(0.65 0.08 50);
/* Default utility values */
--default-border-color: var(--color-border);
--default-ring-color: var(--color-ring);
/* Radius */
--radius: 0.625rem;
}
/* ============================================================
Dark mode — warm dark palette
============================================================ */
.dark {
--color-surface-0: #1C1B18;
--color-surface-1: #242320;
--color-surface-2: #2D2B27;
--color-surface-3: #3A3832;
--color-text-primary: #ECE9E0;
--color-text-secondary: #9C9890;
--color-text-muted: #6B6860;
--color-bg-inverted: #F5F3EC;
--color-text-inverted: #2D2B27;
--color-border: #3A3832;
--color-border-light: #2D2B27;
--color-tool-card: #2D2B27;
--color-warning-bg: #45290A;
--color-warning-border: #B47818;
--color-warning-text: #FCD980;
}
/* ============================================================
Base styles — layered so they coexist with Tailwind preflight
============================================================ */
@layer base {
html,
body {
background-color: var(--color-surface-0);
color: var(--color-text-primary);
font-family: var(--font-sans);
-webkit-font-smoothing: antialiased;
}
*,
::before,
::after {
border-color: var(--color-border);
}
}
/* ============================================================
Custom utilities (unlayered so they always win)
============================================================ */
::-webkit-scrollbar {
width: 6px;
}
::-webkit-scrollbar-track {
background: transparent;
}
::-webkit-scrollbar-thumb {
background: var(--color-surface-3);
border-radius: 3px;
}
/* Glimmer sweep — reverse sweep highlight (same visual as TUI) */
.glimmer-text {
background: linear-gradient(
90deg,
var(--color-text-secondary) 0%,
var(--color-text-secondary) 40%,
var(--color-brand) 50%,
var(--color-text-secondary) 60%,
var(--color-text-secondary) 100%
);
background-size: 200% 100%;
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
background-clip: text;
animation: glimmer-sweep 3s ease-in-out infinite;
}
@keyframes glimmer-sweep {
0% {
background-position: 100% 0;
}
100% {
background-position: -100% 0;
}
}
/* ============================================================
Chat UI — Anthropic style overrides
============================================================ */
/* Chat input — warm orange focus ring */
.chat-input-focus:focus-within {
box-shadow: 0 0 0 2px rgba(217, 119, 87, 0.25);
}
/* Markdown content in message bubbles */
.message-content pre {
background-color: var(--color-surface-1);
border-radius: 0.5rem;
padding: 0.75rem;
overflow-x: auto;
font-size: 0.8125rem;
line-height: 1.5;
}
.message-content code {
font-family: var(--font-mono);
font-size: 0.8125rem;
}
.message-content :not(pre) > code {
background-color: var(--color-surface-1);
padding: 0.125rem 0.375rem;
border-radius: 0.25rem;
}
/* ============================================================
Animations — Anthropic entrance effects
============================================================ */
@keyframes fadeUp {
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; }
}
/* Typing indicator dots */
.chat-typing-indicator {
display: inline-flex;
gap: 4px;
align-items: center;
height: 20px;
}
.chat-typing-indicator span {
width: 6px;
height: 6px;
border-radius: 9999px;
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; }

View File

@@ -0,0 +1,472 @@
import type { SetStateAction } from "react";
import {
apiFetchSession,
apiFetchSessionHistory,
apiBind,
apiSendEvent,
apiSendControl,
apiInterrupt,
getUuid,
} from "../api/client";
import type { SessionEvent, EventPayload } from "../types";
import type {
ThreadEntry,
ToolCallData,
ToolCallStatus,
UserMessageEntry,
AssistantMessageEntry,
ToolCallEntry,
UserMessageImage,
PendingPermission,
} from "./types";
// SSE Event Bus — 复用自 rcs-transport.ts仅保留连接管理
type SSEEventHandler = (event: SessionEvent) => void;
class SSEBus {
private listeners: Set<SSEEventHandler> = new Set();
private eventSource: EventSource | null = null;
onEvent(handler: SSEEventHandler): () => void {
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;
es.addEventListener("message", (e: MessageEvent) => {
try {
const data = JSON.parse(e.data) as SessionEvent;
for (const handler of this.listeners) {
handler(data);
}
} catch {
// ignore parse errors
}
});
}
disconnect(): void {
if (this.eventSource) {
this.eventSource.close();
this.eventSource = null;
}
}
}
// 全局 SSE bus 实例
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";
}
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 (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("");
}
}
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;
}
}
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;
constructor(
sessionId: string,
setEntries: React.Dispatch<SetStateAction<ThreadEntry[]>>,
options?: {
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;
}
/** 初始化:绑定会话、加载历史、连接 SSE */
async init(): Promise<void> {
try {
await apiBind(this.sessionId);
} catch {
// may already be bound
}
await this.loadHistory();
this.connectSSE();
}
/** 加载历史事件并转为 ThreadEntry */
async loadHistory(): Promise<void> {
const { events } = await apiFetchSessionHistory(this.sessionId);
if (!events || events.length === 0) return;
const historyEntries: ThreadEntry[] = [];
let currentAssistant: AssistantMessageEntry | null = null;
const flushAssistant = () => {
if (currentAssistant) {
historyEntries.push(currentAssistant);
currentAssistant = null;
}
};
for (const event of events) {
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 (text) {
historyEntries.push({
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[] = [];
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") {
toolParts.push({
type: "tool_call",
toolCall: {
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",
id: event.id || `hist-asst-${historyEntries.length}`,
chunks: text ? [{ type: "message", text }] : [],
};
historyEntries.push(currentAssistant);
// Push tool calls after assistant message
for (const tp of toolParts) {
historyEntries.push(tp);
}
currentAssistant = null; // Tool calls are separate entries
}
} else if (event.type === "tool_use") {
const p = payload as Record<string, unknown>;
const tc: ToolCallEntry = {
type: "tool_call",
toolCall: {
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>;
// Find last tool call and update with output
const idx = findToolCallIndex(historyEntries, (p.tool_call_id as string) || "");
if (idx >= 0) {
const entry = historyEntries[idx] as ToolCallEntry;
historyEntries[idx] = {
type: "tool_call",
toolCall: {
...entry.toolCall,
rawOutput: { output: p.content || p.output || "" },
},
};
}
}
}
flushAssistant();
this.setEntries(historyEntries);
}
/** 连接 SSE 事件流 */
connectSSE(): void {
sseBus.connect(this.sessionId);
this.unsub = sseBus.onEvent((event) => this.handleEvent(event));
}
/** 断开 SSE */
disconnect(): void {
if (this.unsub) {
this.unsub();
this.unsub = null;
}
sseBus.disconnect();
}
/** 处理 SSE 事件 */
handleEvent(event: SessionEvent): void {
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;
switch (type) {
// ---- 助手消息 ----
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") {
return [
...prev.slice(0, -1),
{ ...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 }] },
];
}
// Create new AssistantMessage
if (content && content.trim()) {
const newEntry: AssistantMessageEntry = {
type: "assistant_message",
id: `assistant-${Date.now()}`,
chunks: [{ type: "message", text: content }],
};
return [...prev, newEntry];
}
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");
for (const block of toolBlocks) {
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",
rawInput: (block.input as Record<string, unknown>) || {},
};
this.setEntries((prev) => [...prev, { type: "tool_call", toolCall: toolData }]);
}
}
break;
}
// ---- 工具调用 ----
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",
rawInput: (p.tool_input as Record<string, unknown>) || {},
};
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;
return prev.map((e, i) =>
i === idx
? { type: "tool_call", toolCall: { ...entry.toolCall, status: "complete" as ToolCallStatus, rawOutput: { output: p.content || p.output || "" } } }
: e,
);
});
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) || "";
// Update tool call status
this.setEntries((prev) => {
// Find matching 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") {
return prev.map((e, i) =>
i === realIdx
? { type: "tool_call", toolCall: { ...entry.toolCall, status: "waiting_for_confirmation" as ToolCallStatus, permissionRequest: { requestId, options: [] } } }
: e,
);
}
}
return prev;
});
// Notify parent
this.onPermissionRequest?.({
requestId,
toolName,
toolInput,
description,
});
}
break;
}
// ---- 会话状态 ----
case "session_status": {
if (typeof payload.status === "string") {
this.onStatusChange?.(payload.status);
}
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;
}
}
/** 发送用户消息 */
async sendMessage(text: string, images?: UserMessageImage[]): Promise<void> {
if (!text.trim() && (!images || images.length === 0)) return;
// Add user message to entries
const userEntry: UserMessageEntry = {
type: "user_message",
id: `user-${Date.now()}`,
content: text,
images: images && images.length > 0 ? images : undefined,
};
this.setEntries((prev) => [...prev, userEntry]);
// Send to backend
await apiSendEvent(this.sessionId, {
type: "user",
uuid: crypto.randomUUID(),
content: text,
message: { content: text },
});
}
/** 响应权限请求 */
async respondPermission(requestId: string, approved: boolean, extra?: Record<string, unknown>): Promise<void> {
await apiSendControl(this.sessionId, {
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;
return {
type: "tool_call",
toolCall: {
...entry.toolCall,
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;
return {
type: "tool_call",
toolCall: { ...entry.toolCall, status: "canceled" as ToolCallStatus, permissionRequest: undefined },
};
}),
);
await apiInterrupt(this.sessionId);
}
}

View File

@@ -0,0 +1,335 @@
import type { ChatTransport, UIMessage, UIMessageChunk } from "ai";
import { getUuid } from "../api/client";
import type { SessionEvent, EventPayload } from "../types";
// ============================================================
// SSE Event Bus — shared between SSE listener and transport
// ============================================================
type SSEEventHandler = (event: SessionEvent) => void;
class SSEEventBus {
private listeners: Set<SSEEventHandler> = new Set();
private eventSource: EventSource | null = null;
private _lastSeqNum = 0;
get lastSeqNum() {
return this._lastSeqNum;
}
/** Register a listener for SSE events */
onEvent(handler: SSEEventHandler): () => void {
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;
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;
for (const handler of this.listeners) {
handler(data);
}
} catch {
// ignore parse errors
}
});
}
/** Disconnect the SSE stream */
disconnect(): void {
if (this.eventSource) {
this.eventSource.close();
this.eventSource = null;
}
this._lastSeqNum = 0;
}
}
// Singleton event bus
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;
}
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;
constructor(options: RCSTransportOptions) {
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") {
// Return empty stream if no user message
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")
.map((p: { text: string }) => p.text)
.join("");
if (!text.trim()) {
return new ReadableStream({ start: (c) => c.close() });
}
// POST user message to the RCS backend
const uuid = getUuid();
const response = await fetch(
`/web/sessions/${this.sessionId}/events?uuid=${encodeURIComponent(uuid)}`,
{
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
type: "user",
uuid: crypto.randomUUID(),
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");
}
// 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;
const ensureStarted = () => {
if (!started) {
started = true;
controller.enqueue({ type: "start", messageId: `msg-${Date.now()}` });
}
};
const handler = (event: SessionEvent) => {
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;
switch (type) {
// ---- Assistant text ----
case "assistant": {
const 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 });
}
// 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",
);
for (const block of toolBlocks) {
ensureStarted();
const toolCallId = (block.id as string) || `call-${Date.now()}-${Math.random().toString(16).slice(2, 8)}`;
controller.enqueue({
type: "tool-input-available",
toolCallId,
toolName: (block.name as string) || "tool",
input: block.input || {},
});
}
}
// Finish after assistant message
ensureStarted();
controller.enqueue({ type: "finish", finishReason: "stop" });
controller.close();
cleanup();
break;
}
// ---- Tool use events ----
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)}`;
controller.enqueue({
type: "tool-input-available",
toolCallId,
toolName: (payload as Record<string, unknown>).tool_name as string || "tool",
input: (payload as Record<string, unknown>).tool_input || {},
});
break;
}
// ---- Tool result events ----
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)}`;
const output =
typeof (payload as Record<string, unknown>).output === "string"
? (payload as Record<string, unknown>).output
: (payload as Record<string, unknown>).content || "";
controller.enqueue({
type: "tool-output-available",
toolCallId: resultCallId,
output: output as string,
});
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") {
// Forward to the UI layer for handling
this.onPermissionRequest?.(event);
}
// Don't close the stream — wait for the response
break;
}
// ---- Status events ----
case "status": {
const msg =
(typeof payload.message === "string" ? payload.message : "") ||
payload.content ||
"";
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);
if (
payload.status === "archived" ||
payload.status === "inactive"
) {
ensureStarted();
controller.enqueue({ type: "finish", finishReason: "stop" });
controller.close();
cleanup();
}
}
break;
}
// ---- Errors ----
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;
}
// ---- Interrupt ----
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;
default:
return;
}
};
const cleanup = () => {
if (this.unsub) {
this.unsub();
this.unsub = null;
}
};
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);
}
},
});
}
/** Not supported — RCS doesn't have stream resumption */
reconnectToStream(): Promise<ReadableStream<UIMessageChunk> | null> {
return Promise.resolve(null);
}
/** Clean up listeners */
destroy(): void {
if (this.unsub) {
this.unsub();
this.unsub = null;
}
}
}

View File

@@ -0,0 +1,97 @@
import React, { createContext, useContext, useEffect, useState, useCallback } from "react";
export type Theme = "light" | "dark" | "system";
interface ThemeContextValue {
theme: Theme;
resolvedTheme: "light" | "dark";
setTheme: (theme: Theme) => void;
}
const ThemeContext = createContext<ThemeContextValue | undefined>(undefined);
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 getStoredTheme(): Theme {
if (typeof window === "undefined") return "system";
try {
const stored = localStorage.getItem(STORAGE_KEY);
if (stored === "light" || stored === "dark" || stored === "system") {
return stored;
}
} catch {
// localStorage not available
}
return "system";
}
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);
if (!context) {
throw new Error("useTheme must be used within a ThemeProvider");
}
return context;
}
interface ThemeProviderProps {
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;
});
const setTheme = useCallback((newTheme: Theme) => {
setThemeState(newTheme);
try {
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]);
// Listen for system theme changes
useEffect(() => {
if (theme !== "system") return;
const mediaQuery = window.matchMedia("(prefers-color-scheme: dark)");
const handleChange = (e: MediaQueryListEvent) => {
const newTheme = e.matches ? "dark" : "light";
setResolvedTheme(newTheme);
applyTheme(newTheme);
};
mediaQuery.addEventListener("change", handleChange);
return () => mediaQuery.removeEventListener("change", handleChange);
}, [theme]);
const value: ThemeContextValue = {
theme,
resolvedTheme,
setTheme,
};
return React.createElement(ThemeContext.Provider, { value }, children);
}

View File

@@ -0,0 +1,96 @@
// =============================================================================
// Unified Chat Data Model — shared between ACP and RCS chat interfaces
// =============================================================================
import type { ToolCallContent, PermissionOption } from "../acp/types";
// 工具调用状态
export type ToolCallStatus =
| "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>;
// 权限请求(仅当 status === "waiting_for_confirmation"
permissionRequest?: {
requestId: string;
options: PermissionOption[];
};
// 独立权限请求(无匹配工具调用时创建)
isStandalonePermission?: boolean;
}
// 助手消息块 — 普通消息或思考过程
export type AssistantChunk =
| { type: "message"; text: string }
| { type: "thought"; text: string };
// 用户消息中的图片
export interface UserMessageImage {
mimeType: string;
data: string; // base64 encoded
}
// 用户消息条目
export interface UserMessageEntry {
type: "user_message";
id: string;
content: string;
images?: UserMessageImage[];
}
// 助手消息条目
export interface AssistantMessageEntry {
type: "assistant_message";
id: string;
chunks: AssistantChunk[];
}
// 工具调用条目
export interface ToolCallEntry {
type: "tool_call";
toolCall: ToolCallData;
}
// 统一聊天条目类型
export type ThreadEntry =
| UserMessageEntry
| AssistantMessageEntry
| ToolCallEntry;
// =============================================================================
// Chat 组件 Props 类型
// =============================================================================
// ChatInput 提交消息
export interface ChatInputMessage {
text: string;
images?: UserMessageImage[];
}
// 权限请求条目(用于 PermissionPanel
export interface PendingPermission {
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;
}

View File

@@ -0,0 +1,71 @@
import { type ClassValue, clsx } from "clsx";
import { twMerge } from "tailwind-merge";
export function cn(...inputs: ClassValue[]) {
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;
}
export function formatTime(ts: number | null | undefined): string {
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";
}
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;
}
export function generateMessageUuid(): string {
if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") {
return crypto.randomUUID();
}
return `msg_${Date.now()}_${Math.random().toString(16).slice(2)}`;
}
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");
}
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";
}

View File

@@ -0,0 +1,10 @@
import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import App from "./App";
import "./index.css";
createRoot(document.getElementById("root")!).render(
<StrictMode>
<App />
</StrictMode>,
);

View File

@@ -0,0 +1,82 @@
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;
}
export function Dashboard({ onNavigateSession }: DashboardProps) {
const [sessions, setSessions] = useState<Session[]>([]);
const [environments, setEnvironments] = useState<Environment[]>([]);
const [dialogOpen, setDialogOpen] = useState(false);
const loadDashboard = useCallback(async () => {
try {
const [sess, envs] = await Promise.all([apiFetchAllSessions(), apiFetchEnvironments()]);
setSessions(sess || []);
setEnvironments(envs || []);
} catch (err) {
console.error("Dashboard render error:", err);
}
}, []);
useEffect(() => {
loadDashboard();
const interval = setInterval(loadDashboard, 10000);
return () => clearInterval(interval);
}, [loadDashboard]);
const handleSessionCreated = (session: Session) => {
setDialogOpen(false);
onNavigateSession(session.id);
};
const handleSelectEnvironment = useCallback((env: Environment) => {
if (env.worker_type === "acp") {
// Navigate to ACP agent detail page (same origin, shares UUID auth)
window.history.pushState(null, "", `/acp/agent/${env.id}`);
// Force page reload to load ACP app
window.location.href = `/acp/agent/${env.id}`;
}
// Bridge environments: no direct navigation (sessions are listed below)
}, []);
const handleSelectSession = useCallback((sessionId: string) => {
onNavigateSession(sessionId);
}, [onNavigateSession]);
return (
<div className="mx-auto max-w-5xl px-4 py-8">
{/* Environments */}
<section className="mb-10">
<h2 className="mb-4 font-display text-lg font-semibold text-text-primary">Environments</h2>
<EnvironmentList environments={environments} onSelectEnvironment={handleSelectEnvironment} />
</section>
{/* Sessions */}
<section>
<div className="mb-4 flex items-center justify-between">
<h2 className="font-display text-lg font-semibold text-text-primary">Sessions</h2>
<button
onClick={() => setDialogOpen(true)}
className="rounded-lg bg-brand px-3 py-1.5 text-sm font-medium text-white hover:bg-brand-light transition-colors"
>
+ New Session
</button>
</div>
<SessionList sessions={sessions} onSelect={handleSelectSession} />
</section>
<NewSessionDialog
open={dialogOpen}
environments={environments}
onClose={() => setDialogOpen(false)}
onCreated={handleSessionCreated}
/>
</div>
);
}

View File

@@ -0,0 +1,487 @@
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 { 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";
// ACP chat components
import { ACPClient, DisconnectRequestedError } from "../acp/client";
import { createRelayClient } from "../acp/relay-client";
import { ACPMain } from "../../components/ACPMain";
import { StatusDot } from "../../components/ui/connection-status";
interface SessionDetailProps {
sessionId: string;
}
export function SessionDetail({ sessionId }: SessionDetailProps) {
const [session, setSession] = useState<Session | null>(null);
const [sessionStatus, setSessionStatus] = useState<string | null>(null);
const [error, setError] = useState("");
const [taskPanelOpen, setTaskPanelOpen] = useState(false);
const [showMeta, setShowMeta] = useState(false);
const [entries, setEntries] = useState<ThreadEntry[]>([]);
const [isLoading, setIsLoading] = useState(false);
const [pendingPermissions, setPendingPermissions] = useState<PendingPermission[]>([]);
const adapterRef = useRef<RCSChatAdapter | null>(null);
// Create RCSChatAdapter
const adapter = useMemo(
() =>
new RCSChatAdapter(sessionId, setEntries, {
onStatusChange: (status) => {
setSessionStatus(status);
},
onError: (err) => {
console.error("[RCSChatAdapter] error:", err);
},
onPermissionRequest: (permission) => {
setPendingPermissions((prev) => {
if (prev.some((p) => p.requestId === permission.requestId)) return prev;
return [...prev, permission];
});
},
}),
[sessionId],
);
useEffect(() => {
adapterRef.current = adapter;
return () => {
adapter.disconnect();
};
}, [adapter]);
// Load session data and initialize adapter
useEffect(() => {
let cancelled = false;
async function load() {
setError("");
try {
const sess = await apiFetchSession(sessionId);
if (cancelled) return;
setSession(sess);
setSessionStatus(sess.status);
} catch (err) {
if (cancelled) return;
setError(err instanceof Error ? err.message : "Failed to load session");
return;
}
try {
await adapter.init();
} catch (err) {
console.warn("Failed to init adapter:", err);
}
}
load();
return () => {
cancelled = true;
};
}, [sessionId, adapter]);
const closed = isClosedSessionStatus(sessionStatus);
// Send message via ChatInput
const handleSubmit = useCallback(
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);
}
},
[adapter, closed],
);
// Interrupt
const handleInterrupt = useCallback(async () => {
try {
await adapter.interrupt();
} catch (err) {
console.error("Interrupt failed:", err);
} finally {
setIsLoading(false);
}
}, [adapter]);
// Mark loading done when last assistant message stops streaming
useEffect(() => {
if (entries.length === 0) return;
const last = entries[entries.length - 1];
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;
setIsLoading(false);
}
}, [entries]);
// Permission actions
const handleApprovePermission = useCallback(
async (requestId: string) => {
try {
await adapter.respondPermission(requestId, true);
} catch (err) {
console.error("Failed to approve:", err);
}
setPendingPermissions((prev) => prev.filter((p) => p.requestId !== requestId));
},
[adapter],
);
const handleRejectPermission = useCallback(
async (requestId: string) => {
try {
await adapter.respondPermission(requestId, false);
} catch (err) {
console.error("Failed to reject:", err);
}
setPendingPermissions((prev) => prev.filter((p) => p.requestId !== requestId));
},
[adapter],
);
const handleSubmitAnswers = useCallback(
async (
requestId: string,
answers: Record<string, unknown>,
questions: import("../types").Question[],
) => {
try {
await apiSendControl(sessionId, {
type: "permission_response",
approved: true,
request_id: requestId,
updated_input: { questions, answers },
});
} catch (err) {
console.error("Failed to submit answers:", err);
}
setPendingPermissions((prev) => prev.filter((p) => p.requestId !== requestId));
},
[sessionId],
);
const handleSubmitPlanResponse = useCallback(
async (requestId: string, value: string, feedback?: string) => {
try {
if (value === "no") {
await apiSendControl(sessionId, {
type: "permission_response",
approved: false,
request_id: requestId,
...(feedback ? { message: feedback } : {}),
});
} else {
const modeMap: Record<string, string> = {
"yes-accept-edits": "acceptEdits",
"yes-default": "default",
};
await apiSendControl(sessionId, {
type: "permission_response",
approved: true,
request_id: requestId,
updated_permissions: [
{ type: "setMode", mode: modeMap[value] || "default", destination: "session" },
],
});
}
} catch (err) {
console.error("Failed to submit plan response:", err);
}
setPendingPermissions((prev) => prev.filter((p) => p.requestId !== requestId));
},
[sessionId],
);
if (error) {
return (
<div className="flex flex-1 items-center justify-center">
<div className="text-center">
<p className="text-status-error">{error}</p>
<a href="/code/" className="mt-4 inline-block text-brand hover:underline">
&larr; Back to Dashboard
</a>
</div>
</div>
);
}
if (!session) {
return (
<div className="flex flex-1 items-center justify-center">
<div className="text-text-muted">Loading session...</div>
</div>
);
}
// ACP session — render ACP relay chat
if (session.source === "acp" && session.environment_id) {
return <ACPSessionDetail sessionId={sessionId} agentId={session.environment_id} />;
}
return (
<TooltipProvider>
<div className="flex flex-1 flex-col overflow-hidden">
{/* Session Header */}
<div className="border-b bg-surface-1 px-4 py-3">
<div className="mx-auto max-w-5xl">
<div className="mb-1">
<a
href="/code/"
className="text-sm text-text-muted hover:text-text-secondary transition-colors no-underline"
>
&larr; Dashboard
</a>
</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>
<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>
</div>
</div>
<div className="flex items-center gap-2">
<button
onClick={() => setShowMeta(!showMeta)}
className="flex items-center gap-1 rounded-md px-2 py-1 text-xs text-text-muted hover:bg-surface-2 hover:text-text-secondary transition-colors"
title="Session info"
>
<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="12" r="10"/><path d="M12 16v-4"/><path d="M12 8h.01"/></svg>
</button>
<button
onClick={() => setTaskPanelOpen(!taskPanelOpen)}
className="flex items-center gap-1 rounded-md px-3 py-1.5 text-sm text-text-secondary hover:bg-surface-2 transition-colors"
>
Tasks
</button>
</div>
</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>
{session.environment_id && (
<div><span className="text-text-secondary font-sans font-medium">Environment</span> {session.environment_id}</div>
)}
</div>
)}
</div>
</div>
{/* Chat messages — unified ChatView */}
<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) => (
<PermissionEventView
key={req.requestId}
request={req}
onApprove={() => handleApprovePermission(req.requestId)}
onReject={() => handleRejectPermission(req.requestId)}
onSubmitAnswers={handleSubmitAnswers}
onSubmitPlan={handleSubmitPlanResponse}
/>
))}
</div>
</div>
)}
{/* Unified ChatInput — claude.ai style */}
<ChatInput
onSubmit={handleSubmit}
isLoading={isLoading}
onInterrupt={handleInterrupt}
disabled={closed}
placeholder={closed ? "会话已关闭" : "输入消息..."}
/>
{/* Task Panel */}
{taskPanelOpen && <TaskPanel onClose={() => setTaskPanelOpen(false)} />}
</div>
</TooltipProvider>
);
}
// ============================================================
// Permission Event View — routes to correct UI
// ============================================================
function PermissionEventView({
request,
onApprove,
onReject,
onSubmitAnswers,
onSubmitPlan,
}: {
request: PendingPermission;
onApprove: () => void;
onReject: () => 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 || "";
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)}
onSkip={onReject}
/>
);
}
if (toolName === "ExitPlanMode") {
const planContent = (toolInput.plan as string) || "";
return (
<PlanPanelView
requestId={request.requestId}
planContent={planContent}
description={description}
onSubmit={(value, feedback) => onSubmitPlan(request.requestId, value, feedback)}
/>
);
}
return (
<PermissionPromptView
requestId={request.requestId}
toolName={toolName}
toolInput={toolInput}
description={description}
onApprove={onApprove}
onReject={onReject}
/>
);
}
// ============================================================
// ACP Session Detail — renders ACP relay chat in session page
// ============================================================
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 [error, setError] = useState<string | null>(null);
const clientRef = useRef<ACPClient | null>(null);
useEffect(() => {
const relayClient = createRelayClient(agentId);
relayClient.setConnectionStateHandler((state, err) => {
setConnectionState(state);
setError(err || null);
});
clientRef.current = relayClient;
setClient(relayClient);
relayClient.connect().catch((e) => {
if (e instanceof DisconnectRequestedError) return;
setError((e as Error).message);
setConnectionState("error");
});
return () => {
relayClient.disconnect();
clientRef.current = null;
setClient(null);
setConnectionState("disconnected");
};
}, [agentId]);
return (
<TooltipProvider>
<div className="flex flex-1 flex-col overflow-hidden">
{/* Header */}
<div className="border-b bg-surface-1 px-4 py-3">
<div className="mx-auto max-w-5xl">
<div className="mb-1">
<a href="/code/" className="text-sm text-text-muted hover:text-text-secondary transition-colors no-underline">
&larr; Dashboard
</a>
</div>
<div className="flex items-center gap-3">
<StatusDot state={connectionState} />
<h2 className="font-display text-lg font-semibold text-text-primary">
{agentId}
</h2>
<span className="rounded-full bg-purple-100 px-2 py-0.5 text-xs font-medium text-purple-700">ACP</span>
</div>
</div>
</div>
{error && connectionState === "error" && (
<div className="px-4 py-2 bg-destructive/10 text-destructive text-sm border-b">
{error}
</div>
)}
{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" />
<p className="text-text-muted text-sm">Connecting to agent...</p>
</div>
</div>
)}
{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>
<p className="text-text-muted text-sm">{error}</p>
</div>
</div>
)}
{client && connectionState === "connected" && (
<div className="flex-1 min-h-0">
<ACPMain client={client} />
</div>
)}
</div>
</TooltipProvider>
);
}

View File

@@ -0,0 +1 @@
// Global type declarations

View File

@@ -0,0 +1,99 @@
export interface Environment {
id: string;
machine_name?: string;
directory?: string;
status: string;
branch?: string;
worker_type?: string;
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;
}
export interface SessionEvent {
type: string;
payload?: EventPayload;
direction?: "inbound" | "outbound";
seqNum?: number;
id?: string;
}
export interface EventPayload {
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;
}
export interface ContentBlock {
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;
}
export interface Question {
question: string;
header?: string;
multiSelect?: boolean;
options?: QuestionOption[];
metadata?: Record<string, unknown>;
}
export interface QuestionOption {
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[];
}
export interface PermissionUpdate {
type: string;
mode: string;
destination: string;
}
export type ActivityMode = "working" | "idle" | "standby" | "sleeping";
export interface AutomationActivity {
mode: ActivityMode;
iconVariant: string;
label: string;
endsAt?: number;
}