refactor(agent): consolidate agent system into unified AgentManager with provider-based architecture

Replace separate ACP and agent-types modules with unified AgentManager using provider pattern. Migrate Claude and Codex implementations to provider-specific clients. Streamline session-agent integration, remove old ACP notification types, and introduce agent timeline events. Delete obsolete documentation and test files. Add AgentRegistry for persistence and agent-stream-based communication pattern.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
Mohamed Boudra
2025-11-15 02:06:09 +01:00
co-authored by Claude
parent 90b0094aae
commit 8cf808b14d
55 changed files with 2770 additions and 7042 deletions
+2 -2
View File
@@ -231,8 +231,8 @@ export default function AgentScreen() {
agent={agent}
streamItems={streamItems}
pendingPermissions={agentPermissions}
onPermissionResponse={(requestId, optionId) =>
respondToPermission(requestId, id!, agent.sessionId || "", [optionId])
onPermissionResponse={(agentId, requestId, response) =>
respondToPermission(agentId, requestId, response)
}
/>
)}
+1 -1
View File
@@ -176,7 +176,7 @@ export default function FileExplorerScreen() {
return (
<View style={styles.container}>
<BackHeader title={selectedEntryPath ?? currentPath || "."} />
<BackHeader title={selectedEntryPath ?? (currentPath || ".")} />
<View style={styles.content}>
{shouldShowPreview ? (
@@ -1,15 +1,9 @@
import { View, Text, Pressable, ScrollView } from 'react-native';
import { StyleSheet } from 'react-native-unistyles';
import type { AgentStatus } from '@server/server/acp/types';
import { View, Text, Pressable, ScrollView } from "react-native";
import { StyleSheet } from "react-native-unistyles";
import type { Agent } from "@/contexts/session-context";
export interface ActiveProcessesProps {
agents: Array<{
id: string;
status: AgentStatus;
type: 'claude';
currentModeId?: string;
availableModes?: Array<{ id: string; name: string; description?: string | null }>;
}>;
agents: Agent[];
commands: Array<{
id: string;
name: string;
@@ -18,46 +12,44 @@ export interface ActiveProcessesProps {
isDead: boolean;
exitCode: number | null;
}>;
viewMode: 'orchestrator' | 'agent';
viewMode: "orchestrator" | "agent";
activeAgentId: string | null;
onSelectAgent: (id: string) => void;
onSelectOrchestrator: () => void;
}
function getAgentStatusColor(status: AgentStatus): string {
function getAgentStatusColor(status: Agent["status"]): string {
switch (status) {
case 'initializing':
return '#f59e0b'; // orange
case 'ready':
return '#3b82f6'; // blue
case 'processing':
return '#fbbf24'; // yellow
case 'completed':
return '#22c55e'; // green
case 'failed':
return '#ef4444'; // red
case 'killed':
return '#9ca3af'; // gray
case "initializing":
return "#f59e0b";
case "idle":
return "#22c55e";
case "running":
return "#3b82f6";
case "error":
return "#ef4444";
case "closed":
return "#9ca3af";
default:
return '#9ca3af';
return "#9ca3af";
}
}
function getModeName(modeId?: string, availableModes?: Array<{ id: string; name: string }>): string {
if (!modeId) return 'unknown';
function getModeName(modeId?: string, availableModes?: Agent["availableModes"]): string {
if (!modeId) return "unknown";
const mode = availableModes?.find((m) => m.id === modeId);
return mode?.name || modeId;
return mode?.label || modeId;
}
function getModeColor(modeId?: string): string {
if (!modeId) return '#9ca3af'; // gray
if (!modeId) return "#9ca3af"; // gray
// Color based on common mode types
if (modeId.includes('ask')) return '#f59e0b'; // orange - asks permission
if (modeId.includes('code')) return '#22c55e'; // green - writes code
if (modeId.includes('architect') || modeId.includes('plan')) return '#3b82f6'; // blue - plans
if (modeId.includes("ask")) return "#f59e0b"; // orange - asks permission
if (modeId.includes("code")) return "#22c55e"; // green - writes code
if (modeId.includes("architect") || modeId.includes("plan")) return "#3b82f6"; // blue - plans
return '#9ca3af'; // gray - unknown
return "#9ca3af"; // gray - unknown
}
const styles = StyleSheet.create((theme) => ({
+3 -41
View File
@@ -2,51 +2,13 @@ import { View, Text, Pressable, ScrollView } from "react-native";
import { router } from "expo-router";
import { StyleSheet, useUnistyles } from "react-native-unistyles";
import type { Agent } from "@/contexts/session-context";
import type { AgentStatus } from "@server/server/acp/types";
import { formatTimeAgo } from "@/utils/time";
import { getAgentStatusColor, getAgentStatusLabel } from "@/utils/agent-status";
interface AgentListProps {
agents: Map<string, Agent>;
}
function getStatusColor(status: AgentStatus): string {
switch (status) {
case "initializing":
return "#FFA500";
case "ready":
return "#2563EB";
case "processing":
return "#FACC15";
case "completed":
return "#10B981";
case "failed":
return "#EF4444";
case "killed":
return "#6B7280";
default:
return "#6B7280";
}
}
function getStatusLabel(status: AgentStatus): string {
switch (status) {
case "initializing":
return "Initializing";
case "ready":
return "Ready";
case "processing":
return "Processing";
case "completed":
return "Completed";
case "failed":
return "Failed";
case "killed":
return "Killed";
default:
return "Unknown";
}
}
export function AgentList({ agents }: AgentListProps) {
const { theme } = useUnistyles();
@@ -62,8 +24,8 @@ export function AgentList({ agents }: AgentListProps) {
return (
<ScrollView style={styles.container} showsVerticalScrollIndicator={false}>
{agentArray.map((agent) => {
const statusColor = getStatusColor(agent.status);
const statusLabel = getStatusLabel(agent.status);
const statusColor = getAgentStatusColor(agent.status);
const statusLabel = getAgentStatusLabel(agent.status);
const timeAgo = formatTimeAgo(agent.lastActivityAt);
return (
+4 -48
View File
@@ -13,14 +13,8 @@ import Animated, {
Easing,
type SharedValue,
} from "react-native-reanimated";
import type { AgentStatus } from "@server/server/acp/types";
interface Agent {
id: string;
status: AgentStatus;
title?: string;
cwd: string;
}
import type { Agent } from "@/contexts/session-context";
import { getAgentStatusColor, getAgentStatusLabel } from "@/utils/agent-status";
interface AgentSidebarProps {
isOpen: boolean;
@@ -32,44 +26,6 @@ interface AgentSidebarProps {
edgeSwipeTranslateX?: SharedValue<number> | null;
}
function getStatusColor(status: AgentStatus): string {
switch (status) {
case "initializing":
return "#FFA500";
case "ready":
return "#2563EB";
case "processing":
return "#FACC15";
case "completed":
return "#10B981";
case "failed":
return "#EF4444";
case "killed":
return "#6B7280";
default:
return "#6B7280";
}
}
function getStatusLabel(status: AgentStatus): string {
switch (status) {
case "initializing":
return "Initializing";
case "ready":
return "Ready";
case "processing":
return "Processing";
case "completed":
return "Completed";
case "failed":
return "Failed";
case "killed":
return "Killed";
default:
return "Unknown";
}
}
export function AgentSidebar({
isOpen,
agents,
@@ -221,8 +177,8 @@ export function AgentSidebar({
<ScrollView style={styles.agentList} showsVerticalScrollIndicator={false}>
{agents.map((agent) => {
const isActive = agent.id === activeAgentId;
const statusColor = getStatusColor(agent.status);
const statusLabel = getStatusLabel(agent.status);
const statusColor = getAgentStatusColor(agent.status);
const statusLabel = getAgentStatusLabel(agent.status);
return (
<Pressable
@@ -2,6 +2,7 @@ import { View, Text, Pressable } from "react-native";
import { StyleSheet, useUnistyles } from "react-native-unistyles";
import { ChevronDown } from "lucide-react-native";
import { useSession } from "@/contexts/session-context";
import type { Agent } from "@/contexts/session-context";
import { useState } from "react";
import { ModeSelectorModal } from "./mode-selector-modal";
@@ -24,35 +25,18 @@ export function AgentStatusBar({ agentId }: AgentStatusBarProps) {
setAgentMode(agentId, modeId);
}
function getStatusLabel(status: string): string {
function getStatusColor(status: Agent["status"]): string {
switch (status) {
case "ready":
return "Ready";
case "processing":
return "Working";
case "completed":
return "Completed";
case "failed":
return "Failed";
case "killed":
return "Stopped";
default:
return status;
}
}
function getStatusColor(status: string): string {
switch (status) {
case "ready":
return theme.colors.palette.green[500];
case "processing":
return theme.colors.palette.blue[500];
case "completed":
return theme.colors.palette.gray[500];
case "failed":
return theme.colors.palette.red[500];
case "killed":
case "initializing":
return theme.colors.palette.orange[500];
case "idle":
return theme.colors.palette.green[500];
case "running":
return theme.colors.palette.blue[500];
case "error":
return theme.colors.palette.red[500];
case "closed":
return theme.colors.palette.gray[500];
default:
return theme.colors.mutedForeground;
}
@@ -70,7 +54,7 @@ export function AgentStatusBar({ agentId }: AgentStatusBarProps) {
]}
>
<Text style={styles.modeBadgeText}>
{agent.availableModes?.find((m) => m.id === agent.currentModeId)?.name ||
{agent.availableModes?.find((m) => m.id === agent.currentModeId)?.label ||
agent.currentModeId ||
"default"}
</Text>
+71 -118
View File
@@ -26,6 +26,7 @@ import {
import { ToolCallBottomSheet } from "./tool-call-bottom-sheet";
import type { StreamItem } from "@/types/stream";
import type { SelectedToolCall, PendingPermission } from "@/types/shared";
import type { AgentPermissionResponse } from "@server/server/agent/agent-sdk-types";
import type { Agent } from "@/contexts/session-context";
import { useSession } from "@/contexts/session-context";
@@ -34,7 +35,7 @@ export interface AgentStreamViewProps {
agent: Agent;
streamItems: StreamItem[];
pendingPermissions: Map<string, PendingPermission>;
onPermissionResponse: (requestId: string, optionId: string) => void;
onPermissionResponse: (agentId: string, requestId: string, response: AgentPermissionResponse) => void;
}
export function AgentStreamView({
@@ -232,30 +233,18 @@ export function AgentStreamView({
case "tool_call": {
const { payload } = item;
// Extract data based on source
if (payload.source === "acp") {
if (payload.source === "agent") {
const data = payload.data;
// Map ACP status to display status
const toolStatus =
data.status === "pending" || data.status === "in_progress"
? ("executing" as const)
: data.status === "completed"
? ("completed" as const)
: ("failed" as const);
return (
<ToolCall
toolName={data.title ?? "Unknown Tool"}
kind={data.kind}
args={data.rawInput}
result={data.rawOutput}
status={toolStatus}
toolName={`${data.server}/${data.tool}`}
args={data.raw}
status={data.status as "executing" | "completed" | "failed"}
onOpenDetails={() => handleOpenToolCallDetails({ payload })}
/>
);
}
// Orchestrator tool call
const data = payload.data;
return (
<ToolCall
@@ -268,9 +257,16 @@ export function AgentStreamView({
);
}
case "plan":
case "activity_log":
case "artifact":
return (
<ActivityLog
type={item.activityType}
message={item.message}
timestamp={item.timestamp.getTime()}
metadata={item.metadata}
/>
);
default:
return null;
}
@@ -318,7 +314,7 @@ export function AgentStreamView({
<View style={stylesheet.permissionsContainer}>
{pendingPermissionItems.map((permission) => (
<PermissionRequestCard
key={permission.requestId}
key={permission.request.id}
permission={permission}
onResponse={onPermissionResponse}
/>
@@ -411,75 +407,17 @@ function PermissionRequestCard({
permission,
onResponse,
}: {
permission: {
requestId: string;
toolCall: any;
options: Array<{
kind: string;
name: string;
optionId: string;
}>;
};
onResponse: (requestId: string, optionId: string) => void;
permission: PendingPermission;
onResponse: (agentId: string, requestId: string, response: AgentPermissionResponse) => void;
}) {
const { theme } = useUnistyles();
// Determine permission type and content based on toolCall
const getPermissionInfo = () => {
const rawInput = permission.toolCall?.rawInput || {};
const toolCallId = permission.toolCall?.toolCallId || "";
console.log("[PermissionCard] Tool call details:", {
toolCallId,
rawInputKeys: Object.keys(rawInput),
rawInput,
});
// Check if this is a plan (ExitPlanMode)
if (rawInput.plan) {
return {
title: "Plan Ready for Review",
content: rawInput.plan,
type: "plan" as const,
};
}
// Check if this is a file operation (Write, Edit, etc.)
if (rawInput.file_path) {
const operation = toolCallId.includes("Write") ? "Create" : "Edit";
const fileContent = rawInput.content || rawInput.new_string || "";
const preview =
fileContent.length > 500
? fileContent.slice(0, 500) + "\n\n... (truncated)"
: fileContent;
return {
title: `${operation} File Permission`,
content: `File: ${rawInput.file_path}\n\n${preview || "(empty file)"}`,
type: "file" as const,
};
}
// Check if this is a command (Bash)
if (rawInput.command) {
return {
title: "Run Command Permission",
content: `Command: ${rawInput.command}\n\nDescription: ${
rawInput.description || "No description"
}`,
type: "command" as const,
};
}
// Fallback - show whatever is in rawInput
return {
title: "Permission Required",
content: JSON.stringify(rawInput, null, 2),
type: "unknown" as const,
};
};
const permissionInfo = getPermissionInfo();
const { request } = permission;
const title = request.title ?? request.name ?? "Permission Required";
const description = request.description ?? "";
const inputPreview = request.input
? JSON.stringify(request.input, null, 2)
: null;
return (
<View
@@ -491,26 +429,25 @@ function PermissionRequestCard({
},
]}
>
<Text
style={[permissionStyles.title, { color: theme.colors.foreground }]}
>
{permissionInfo.title}
<Text style={[permissionStyles.title, { color: theme.colors.foreground }]}>
{title}
</Text>
{permissionInfo.content && (
{description ? (
<Text style={[permissionStyles.planText, { color: theme.colors.mutedForeground }]}>
{description}
</Text>
) : null}
{inputPreview && (
<View
style={[
permissionStyles.planContainer,
{ backgroundColor: theme.colors.background },
]}
>
<Text
style={[
permissionStyles.planText,
{ color: theme.colors.foreground },
]}
>
{permissionInfo.content}
<Text style={[permissionStyles.planText, { color: theme.colors.foreground }]}>
{inputPreview}
</Text>
</View>
)}
@@ -525,29 +462,45 @@ function PermissionRequestCard({
</Text>
<View style={permissionStyles.optionsContainer}>
{permission.options.map((option) => (
<Pressable
key={option.optionId}
<Pressable
style={[
permissionStyles.optionButton,
{ backgroundColor: theme.colors.primary },
]}
onPress={() =>
onResponse(permission.agentId, request.id, { behavior: "allow" })
}
>
<Text
style={[
permissionStyles.optionButton,
{
backgroundColor: option.kind.includes("reject")
? theme.colors.destructive
: theme.colors.primary,
},
permissionStyles.optionText,
{ color: theme.colors.primaryForeground },
]}
onPress={() => onResponse(permission.requestId, option.optionId)}
>
<Text
style={[
permissionStyles.optionText,
{ color: theme.colors.primaryForeground },
]}
>
{option.name}
</Text>
</Pressable>
))}
Allow
</Text>
</Pressable>
<Pressable
style={[
permissionStyles.optionButton,
{ backgroundColor: theme.colors.destructive },
]}
onPress={() =>
onResponse(permission.agentId, request.id, {
behavior: "deny",
message: "Denied by user",
})
}
>
<Text
style={[
permissionStyles.optionText,
{ color: theme.colors.primaryForeground },
]}
>
Deny
</Text>
</Pressable>
</View>
</View>
);
@@ -1,4 +1,5 @@
import { useState, useRef, useEffect, useMemo, useCallback } from "react";
import type { ReactElement } from "react";
import {
View,
Text,
@@ -28,30 +29,24 @@ import { useSession } from "@/contexts/session-context";
import { useRouter } from "expo-router";
import { generateMessageId } from "@/types/stream";
import {
listAgentTypeDefinitions,
type AgentType,
type AgentTypeDefinition,
type AgentModeDefinition,
} from "@server/server/acp/agent-types";
AGENT_PROVIDER_DEFINITIONS,
type AgentProviderDefinition,
} from "@server/server/agent/provider-manifest";
import type { AgentProvider, AgentMode, AgentSessionConfig } from "@server/server/agent/agent-sdk-types";
interface CreateAgentModalProps {
isVisible: boolean;
onClose: () => void;
}
const agentTypeDefinitions = listAgentTypeDefinitions();
const providerDefinitions = AGENT_PROVIDER_DEFINITIONS;
const providerDefinitionMap = new Map<AgentProvider, AgentProviderDefinition>(
providerDefinitions.map((definition) => [definition.id, definition])
);
const agentTypeDefinitionMap: Record<AgentType, AgentTypeDefinition> =
{} as Record<AgentType, AgentTypeDefinition>;
for (const definition of agentTypeDefinitions) {
agentTypeDefinitionMap[definition.id] = definition;
}
const fallbackDefinition = agentTypeDefinitionMap.claude ?? agentTypeDefinitions[0];
const DEFAULT_AGENT_TYPE: AgentType = fallbackDefinition
? fallbackDefinition.id
: "claude";
const DEFAULT_MODE_FOR_DEFAULT_AGENT = fallbackDefinition?.defaultModeId ?? "";
const fallbackDefinition = providerDefinitions[0];
const DEFAULT_PROVIDER: AgentProvider = fallbackDefinition?.id ?? "claude";
const DEFAULT_MODE_FOR_DEFAULT_PROVIDER = fallbackDefinition?.defaultModeId ?? "";
const BACKDROP_OPACITY = 0.55;
export function CreateAgentModal({
@@ -71,10 +66,10 @@ export function CreateAgentModal({
const [isMounted, setIsMounted] = useState(isVisible);
const [workingDir, setWorkingDir] = useState("");
const [selectedAgentType, setSelectedAgentType] = useState<AgentType>(
DEFAULT_AGENT_TYPE
const [selectedProvider, setSelectedProvider] = useState<AgentProvider>(
DEFAULT_PROVIDER
);
const [selectedMode, setSelectedMode] = useState(DEFAULT_MODE_FOR_DEFAULT_AGENT);
const [selectedMode, setSelectedMode] = useState(DEFAULT_MODE_FOR_DEFAULT_PROVIDER);
const [worktreeName, setWorktreeName] = useState("");
const [errorMessage, setErrorMessage] = useState("");
const [isLoading, setIsLoading] = useState(false);
@@ -82,8 +77,8 @@ export function CreateAgentModal({
const pendingNavigationAgentIdRef = useRef<string | null>(null);
const agentDefinition = agentTypeDefinitionMap[selectedAgentType];
const modeOptions = agentDefinition?.availableModes ?? [];
const agentDefinition = providerDefinitionMap.get(selectedProvider);
const modeOptions = agentDefinition?.modes ?? [];
useEffect(() => {
if (!agentDefinition) {
@@ -109,8 +104,8 @@ export function CreateAgentModal({
const resetFormState = useCallback(() => {
setWorkingDir("");
setWorktreeName("");
setSelectedAgentType(DEFAULT_AGENT_TYPE);
setSelectedMode(DEFAULT_MODE_FOR_DEFAULT_AGENT);
setSelectedProvider(DEFAULT_PROVIDER);
setSelectedMode(DEFAULT_MODE_FOR_DEFAULT_PROVIDER);
setErrorMessage("");
setIsLoading(false);
setPendingRequestId(null);
@@ -293,14 +288,17 @@ export function CreateAgentModal({
setPendingRequestId(requestId);
setErrorMessage("");
const modeId =
modeOptions.length > 0 && selectedMode !== "" ? selectedMode : undefined;
const modeId = modeOptions.length > 0 && selectedMode !== "" ? selectedMode : undefined;
const config: AgentSessionConfig = {
provider: selectedProvider,
cwd: trimmedPath,
...(modeId ? { modeId } : {}),
};
try {
createAgent({
cwd: trimmedPath,
agentType: selectedAgentType,
initialMode: modeId,
config,
worktreeName: worktree || undefined,
requestId,
});
@@ -314,8 +312,8 @@ export function CreateAgentModal({
workingDir,
worktreeName,
selectedMode,
selectedAgentType,
modeOptions,
selectedProvider,
isLoading,
validateWorktreeName,
addRecentPath,
@@ -327,20 +325,22 @@ export function CreateAgentModal({
return;
}
const unsubscribe = ws.on("agent_created", (message) => {
if (message.type !== "agent_created") {
const unsubscribe = ws.on("status", (message) => {
if (message.type !== "status") {
return;
}
const { agentId, requestId } = message.payload;
if (requestId === pendingRequestId) {
console.log("[CreateAgentModal] Agent created:", agentId);
setIsLoading(false);
setPendingRequestId(null);
pendingNavigationAgentIdRef.current = agentId;
handleClose();
const payload = message.payload as { status: string; agentId?: string; requestId?: string };
if (payload.status !== "agent_created") {
return;
}
if (payload.requestId !== pendingRequestId || !payload.agentId) {
return;
}
console.log("[CreateAgentModal] Agent created:", payload.agentId);
setIsLoading(false);
setPendingRequestId(null);
pendingNavigationAgentIdRef.current = payload.agentId;
handleClose();
});
return () => {
@@ -427,11 +427,11 @@ export function CreateAgentModal({
]}
>
<AssistantSelector
agentTypeDefinitions={agentTypeDefinitions}
providerDefinitions={providerDefinitions}
disabled={isLoading}
isStacked={isCompactLayout}
selectedAgentType={selectedAgentType}
onSelect={setSelectedAgentType}
selectedProvider={selectedProvider}
onSelect={setSelectedProvider}
/>
<ModeSelector
disabled={isLoading}
@@ -496,12 +496,12 @@ interface ModalHeaderProps {
onClose: () => void;
}
function ModalHeader({ paddingTop, paddingLeft, paddingRight, onClose }: ModalHeaderProps): JSX.Element {
function ModalHeader({ paddingTop, paddingLeft, paddingRight, onClose }: ModalHeaderProps): ReactElement {
return (
<View style={[styles.header, { paddingTop, paddingLeft, paddingRight }]}>
<Text style={styles.headerTitle}>Create New Agent</Text>
<Pressable onPress={onClose} style={styles.closeButton} hitSlop={8}>
<X size={20} style={styles.closeIcon} />
<X size={20} color={defaultTheme.colors.mutedForeground} />
</Pressable>
</View>
);
@@ -521,7 +521,7 @@ function WorkingDirectorySection({
errorMessage,
recentPaths,
onChangeWorkingDir,
}: WorkingDirectorySectionProps): JSX.Element {
}: WorkingDirectorySectionProps): ReactElement {
return (
<View style={styles.formSection}>
<Text style={styles.label}>Working Directory</Text>
@@ -557,26 +557,26 @@ function WorkingDirectorySection({
}
interface AssistantSelectorProps {
agentTypeDefinitions: AgentTypeDefinition[];
selectedAgentType: AgentType;
providerDefinitions: AgentProviderDefinition[];
selectedProvider: AgentProvider;
disabled: boolean;
isStacked: boolean;
onSelect: (agentType: AgentType) => void;
onSelect: (provider: AgentProvider) => void;
}
function AssistantSelector({
agentTypeDefinitions,
selectedAgentType,
providerDefinitions,
selectedProvider,
disabled,
isStacked,
onSelect,
}: AssistantSelectorProps): JSX.Element {
}: AssistantSelectorProps): ReactElement {
return (
<View style={[styles.selectorColumn, isStacked && styles.selectorColumnFull]}>
<Text style={styles.label}>Assistant</Text>
<View style={styles.optionGroup}>
{agentTypeDefinitions.map((definition) => {
const isSelected = selectedAgentType === definition.id;
{providerDefinitions.map((definition) => {
const isSelected = selectedProvider === definition.id;
return (
<Pressable
key={definition.id}
@@ -608,7 +608,7 @@ function AssistantSelector({
}
interface ModeSelectorProps {
modeOptions: AgentModeDefinition[];
modeOptions: AgentMode[];
selectedMode: string;
disabled: boolean;
isStacked: boolean;
@@ -621,7 +621,7 @@ function ModeSelector({
disabled,
isStacked,
onSelect,
}: ModeSelectorProps): JSX.Element {
}: ModeSelectorProps): ReactElement {
return (
<View style={[styles.selectorColumn, isStacked && styles.selectorColumnFull]}>
<Text style={styles.label}>Permissions</Text>
@@ -652,7 +652,7 @@ function ModeSelector({
{isSelected ? <View style={styles.radioInner} /> : null}
</View>
<View style={styles.modeTextContainer}>
<Text style={styles.optionLabel}>{mode.name}</Text>
<Text style={styles.optionLabel}>{mode.label}</Text>
{mode.description ? <Text style={styles.modeDescription}>{mode.description}</Text> : null}
</View>
</View>
@@ -671,7 +671,7 @@ interface WorktreeSectionProps {
onChange: (value: string) => void;
}
function WorktreeSection({ value, isLoading, onChange }: WorktreeSectionProps): JSX.Element {
function WorktreeSection({ value, isLoading, onChange }: WorktreeSectionProps): ReactElement {
return (
<View style={styles.formSection}>
<Text style={styles.label}>Worktree Name (Optional)</Text>
@@ -742,9 +742,6 @@ const styles = StyleSheet.create((theme) => ({
alignItems: "center",
justifyContent: "center",
},
closeIcon: {
color: theme.colors.mutedForeground,
},
scroll: {
flex: 1,
},
@@ -46,7 +46,7 @@ export function ModeSelectorModal({
isActive && styles.modeNameActive,
]}
>
{mode.name}
{mode.label}
</Text>
{mode.description && (
<Text
@@ -209,34 +209,23 @@ export function ToolCallBottomSheet({
const { payload } = selectedToolCall;
if (payload.source === "acp") {
const data = payload.data;
const content = data.content
?.flatMap((item) => {
if (item.type === "content" && item.content.type === "text") {
return [item.content.text];
}
return [];
})
.join("\n");
return {
toolName: data.kind ?? "Unknown Tool",
args: data.rawInput,
result: content,
error: undefined, // ACP doesn't have a separate error field
};
} else {
// Orchestrator tool call
if (payload.source === "agent") {
const data = payload.data;
return {
toolName: data.toolName,
args: data.arguments,
result: data.result,
error: data.error,
toolName: `${data.server}/${data.tool}`,
args: data.raw,
result: undefined,
error: undefined,
};
}
const data = payload.data;
return {
toolName: data.toolName,
args: data.arguments,
result: data.result,
error: data.error,
};
}, [selectedToolCall]);
const editEntries = useMemo(() => {
+179 -226
View File
@@ -1,16 +1,28 @@
import { createContext, useContext, useState, useRef, ReactNode, useCallback, useEffect } from "react";
import { useWebSocket, type UseWebSocketReturn } from "@/hooks/use-websocket";
import { useAudioPlayer } from "@/hooks/use-audio-player";
import { reduceStreamUpdate, generateMessageId, type StreamItem } from "@/types/stream";
import { reduceStreamUpdate, generateMessageId, hydrateStreamState, type StreamItem } from "@/types/stream";
import type { PendingPermission } from "@/types/shared";
import type {
ActivityLogPayload,
AgentSnapshotPayload,
AgentStreamEventPayload,
SessionInboundMessage,
WSInboundMessage,
} from "@server/server/messages";
import type { AgentStatus, AgentUpdate, AgentNotification } from "@server/server/acp/types";
import type { AgentType } from "@server/server/acp/agent-types";
import { parseSessionUpdate } from "@/types/agent-activity";
import type {
AgentLifecycleStatus,
} from "@server/server/agent/agent-manager";
import type {
AgentPermissionResponse,
AgentSessionConfig,
AgentProvider,
AgentPermissionRequest,
AgentMode,
AgentCapabilityFlags,
AgentUsage,
AgentPersistenceHandle,
} from "@server/server/agent/agent-sdk-types";
import { ScrollView } from "react-native";
import * as FileSystem from 'expo-file-system';
@@ -56,18 +68,19 @@ export type MessageEntry =
export interface Agent {
id: string;
status: AgentStatus;
provider: AgentProvider;
status: AgentLifecycleStatus;
createdAt: Date;
updatedAt: Date;
lastActivityAt: Date;
type: AgentType;
sessionId: string | null;
error: string | null;
capabilities: AgentCapabilityFlags;
currentModeId: string | null;
availableModes: Array<{
id: string;
name: string;
description?: string | null;
}> | null;
availableModes: AgentMode[];
pendingPermissions: AgentPermissionRequest[];
persistence: AgentPersistenceHandle | null;
lastUsage?: AgentUsage;
lastError?: string | null;
title: string | null;
cwd: string;
}
@@ -131,6 +144,29 @@ const createExplorerState = (): AgentFileExplorerState => ({
currentPath: ".",
});
function normalizeAgentSnapshot(snapshot: AgentSnapshotPayload): Agent {
const createdAt = new Date(snapshot.createdAt);
const updatedAt = new Date(snapshot.updatedAt);
return {
id: snapshot.id,
provider: snapshot.provider,
status: snapshot.status as AgentLifecycleStatus,
createdAt,
updatedAt,
lastActivityAt: updatedAt,
sessionId: snapshot.sessionId,
capabilities: snapshot.capabilities,
currentModeId: snapshot.currentModeId,
availableModes: snapshot.availableModes ?? [],
pendingPermissions: snapshot.pendingPermissions ?? [],
persistence: snapshot.persistence ?? null,
lastUsage: snapshot.lastUsage,
lastError: snapshot.lastError ?? null,
title: snapshot.title ?? null,
cwd: snapshot.cwd,
};
}
interface SessionContextValue {
// WebSocket
@@ -158,8 +194,6 @@ interface SessionContextValue {
setAgents: (agents: Map<string, Agent> | ((prev: Map<string, Agent>) => Map<string, Agent>)) => void;
commands: Map<string, Command>;
setCommands: (commands: Map<string, Command> | ((prev: Map<string, Command>) => Map<string, Command>)) => void;
agentUpdates: Map<string, AgentUpdate[]>;
setAgentUpdates: (updates: Map<string, AgentUpdate[]> | ((prev: Map<string, AgentUpdate[]>) => Map<string, AgentUpdate[]>)) => void;
// Permissions
pendingPermissions: Map<string, PendingPermission>;
@@ -178,15 +212,9 @@ interface SessionContextValue {
initializeAgent: (params: { agentId: string; requestId?: string }) => void;
sendAgentMessage: (agentId: string, message: string, imageUris?: string[]) => Promise<void>;
sendAgentAudio: (agentId: string, audioBlob: Blob, requestId?: string) => Promise<void>;
createAgent: (options: {
cwd: string;
agentType: AgentType;
initialMode?: string;
worktreeName?: string;
requestId?: string;
}) => void;
createAgent: (options: { config: AgentSessionConfig; worktreeName?: string; requestId?: string }) => void;
setAgentMode: (agentId: string, modeId: string) => void;
respondToPermission: (requestId: string, agentId: string, sessionId: string, selectedOptionIds: string[]) => void;
respondToPermission: (agentId: string, requestId: string, response: AgentPermissionResponse) => void;
}
const SessionContext = createContext<SessionContextValue | null>(null);
@@ -224,7 +252,6 @@ export function SessionProvider({ children, serverUrl }: SessionProviderProps) {
const [agents, setAgents] = useState<Map<string, Agent>>(new Map());
const [commands, setCommands] = useState<Map<string, Command>>(new Map());
const [agentUpdates, setAgentUpdates] = useState<Map<string, AgentUpdate[]>>(new Map());
const [pendingPermissions, setPendingPermissions] = useState<Map<string, PendingPermission>>(new Map());
const [gitDiffs, setGitDiffs] = useState<Map<string, string>>(new Map());
const [fileExplorer, setFileExplorer] = useState<Map<string, AgentFileExplorerState>>(new Map());
@@ -250,212 +277,151 @@ export function SessionProvider({ children, serverUrl }: SessionProviderProps) {
console.log("[Session] Session state:", agentsList.length, "agents,", commandsList.length, "commands");
setAgents(
new Map(
agentsList.map((agentInfo) => {
const createdAt = new Date(agentInfo.createdAt);
const lastActivityAt = agentInfo.lastActivityAt
? new Date(agentInfo.lastActivityAt)
: createdAt;
return [
agentInfo.id,
{
id: agentInfo.id,
status: agentInfo.status as AgentStatus,
type: agentInfo.type,
createdAt,
lastActivityAt,
title: agentInfo.title ?? null,
cwd: agentInfo.cwd,
sessionId: agentInfo.sessionId ?? null,
error: agentInfo.error ?? null,
currentModeId: agentInfo.currentModeId ?? null,
availableModes: agentInfo.availableModes ?? null,
} satisfies Agent,
];
})
)
);
const nextAgents = new Map<string, Agent>();
const nextPermissions = new Map<string, PendingPermission>();
for (const snapshot of agentsList) {
const agent = normalizeAgentSnapshot(snapshot);
nextAgents.set(agent.id, agent);
for (const request of agent.pendingPermissions) {
nextPermissions.set(request.id, { agentId: agent.id, request });
}
}
setAgents(nextAgents);
setPendingPermissions(nextPermissions);
setCommands(new Map(commandsList.map((c) => [c.id, c as Command])));
setAgentStreamState(new Map());
setAgentUpdates(new Map());
setAgentStreamState(() => {
const next = new Map<string, StreamItem[]>();
for (const snapshot of agentsList) {
next.set(snapshot.id, []);
}
return next;
});
setInitializingAgents(new Map());
});
// Agent created
const unsubAgentCreated = ws.on("agent_created", (message) => {
if (message.type !== "agent_created") return;
const { agentId, status, type, currentModeId, availableModes, title, cwd } = message.payload;
const unsubAgentState = ws.on("agent_state", (message) => {
if (message.type !== "agent_state") return;
const snapshot = message.payload;
const agent = normalizeAgentSnapshot(snapshot);
console.log("[Session] Agent created:", agentId);
const now = new Date();
const agent: Agent = {
id: agentId,
status: status as AgentStatus,
type,
createdAt: now,
lastActivityAt: now,
title: title ?? null,
cwd,
sessionId: null,
error: null,
currentModeId: currentModeId ?? null,
availableModes: availableModes ?? null,
};
setAgents((prev) => new Map(prev).set(agentId, agent));
setAgentStreamState((prev) => new Map(prev).set(agentId, []));
});
// Agent initialized - receive full history on demand
const unsubAgentInitialized = ws.on("agent_initialized", (message) => {
if (message.type !== "agent_initialized") return;
const { agentId, info, updates } = message.payload;
console.log(
"[Session] Agent initialized:",
agentId,
"updates:",
updates.length
);
console.log("[Session] Agent state update:", agent.id, agent.status);
setAgents((prev) => {
const next = new Map(prev);
const createdAt = new Date(info.createdAt);
const lastActivityAt = info.lastActivityAt
? new Date(info.lastActivityAt)
: createdAt;
const existing = next.get(agentId);
const normalizedAgent: Agent = {
id: info.id,
status: info.status as AgentStatus,
type: info.type,
createdAt,
lastActivityAt,
title: info.title ?? null,
cwd: info.cwd,
sessionId: info.sessionId ?? null,
error: info.error ?? null,
currentModeId: info.currentModeId ?? null,
availableModes: info.availableModes ?? null,
};
next.set(
agentId,
existing
? {
...existing,
...normalizedAgent,
}
: normalizedAgent
);
next.set(agent.id, agent);
return next;
});
const normalizedUpdates: AgentUpdate[] = updates.map((update) => ({
agentId: update.agentId,
timestamp: new Date(update.timestamp),
notification: update.notification,
}));
setPendingPermissions((prev) => {
const next = new Map(prev);
for (const [key, pending] of Array.from(next.entries())) {
if (pending.agentId === agent.id) {
next.delete(key);
}
}
for (const request of agent.pendingPermissions) {
next.set(request.id, { agentId: agent.id, request });
}
return next;
});
});
setAgentUpdates((prev) => new Map(prev).set(agentId, normalizedUpdates));
const unsubAgentStream = ws.on("agent_stream", (message) => {
if (message.type !== "agent_stream") return;
const { agentId, event, timestamp } = message.payload;
const parsedTimestamp = new Date(timestamp);
setAgentStreamState((prev) => {
const reconstructedStream = normalizedUpdates.reduce<StreamItem[]>(
(acc, update) => reduceStreamUpdate(acc, update.notification, update.timestamp),
[]
const currentStream = prev.get(agentId) || [];
const newStream = reduceStreamUpdate(
currentStream,
event as AgentStreamEventPayload,
parsedTimestamp
);
return new Map(prev).set(agentId, reconstructedStream);
const next = new Map(prev);
next.set(agentId, newStream);
return next;
});
setAgents((prev) => {
const existing = prev.get(agentId);
if (!existing) {
return prev;
}
const next = new Map(prev);
next.set(agentId, {
...existing,
lastActivityAt: parsedTimestamp,
updatedAt: parsedTimestamp,
});
return next;
});
});
const unsubAgentStreamSnapshot = ws.on("agent_stream_snapshot", (message) => {
if (message.type !== "agent_stream_snapshot") return;
const { agentId, events } = message.payload;
const hydrated = hydrateStreamState(
events.map(({ event, timestamp }) => ({
event: event as AgentStreamEventPayload,
timestamp: new Date(timestamp),
}))
);
setAgentStreamState((prev) => {
const next = new Map(prev);
next.set(agentId, hydrated);
return next;
});
setInitializingAgents((prev) => {
if (!prev.has(agentId)) {
return prev;
}
const next = new Map(prev);
next.set(agentId, false);
return next;
});
});
// Agent status update (mode changes, title changes, etc.)
const unsubAgentStatus = ws.on("agent_status", (message) => {
if (message.type !== "agent_status") return;
const { agentId, info } = message.payload;
console.log("[Session] Agent status update:", agentId, "mode:", info.currentModeId);
setAgents((prev) => {
const existingAgent = prev.get(agentId);
if (!existingAgent) return prev;
const lastActivityAt = info.lastActivityAt
? new Date(info.lastActivityAt)
: existingAgent.lastActivityAt;
const updatedAgent: Agent = {
...existingAgent,
status: info.status as AgentStatus,
sessionId: info.sessionId ?? null,
error: info.error ?? null,
currentModeId: info.currentModeId ?? null,
availableModes: info.availableModes ?? null,
title: info.title ?? null,
cwd: info.cwd,
lastActivityAt,
};
return new Map(prev).set(agentId, updatedAgent);
});
});
// Agent update
const unsubAgentUpdate = ws.on("agent_update", (message) => {
if (message.type !== "agent_update") return;
const { agentId, notification, timestamp: rawTimestamp } = message.payload;
const timestamp = new Date(rawTimestamp);
const update: AgentUpdate = {
agentId,
timestamp,
notification,
};
setAgentUpdates((prev) => {
const agentHistory = prev.get(agentId) || [];
return new Map(prev).set(agentId, [...agentHistory, update]);
});
// Update stream state using reducer
setAgentStreamState((prev) => {
const currentStream = prev.get(agentId) || [];
const newStream = reduceStreamUpdate(currentStream, notification, timestamp);
return new Map(prev).set(agentId, newStream);
});
const unsubStatus = ws.on("status", (message) => {
if (message.type !== "status") return;
const status = message.payload.status;
if (status === "agent_initialized" && "agentId" in message.payload) {
const agentId = (message.payload as any).agentId as string | undefined;
if (agentId) {
setInitializingAgents((prev) => {
const next = new Map(prev);
next.set(agentId, false);
return next;
});
}
}
});
// Permission request
const unsubPermissionRequest = ws.on("agent_permission_request", (message) => {
if (message.type !== "agent_permission_request") return;
const { agentId, requestId, sessionId, toolCall, options } = message.payload;
const { agentId, request } = message.payload;
console.log("[Session] Permission request:", requestId, "for agent:", agentId);
console.log("[Session] Permission request:", request.id, "for agent:", agentId);
setPendingPermissions((prev) => new Map(prev).set(requestId, {
agentId,
requestId,
sessionId,
toolCall,
options,
}));
setPendingPermissions((prev) => {
const next = new Map(prev);
next.set(request.id, { agentId, request });
return next;
});
});
// Permission resolved - remove from pending
const unsubPermissionResolved = ws.on("agent_permission_resolved", (message) => {
if (message.type !== "agent_permission_resolved") return;
const { requestId, agentId, optionId } = message.payload;
const { requestId, agentId } = message.payload;
console.log("[Session] Permission resolved:", requestId, "for agent:", agentId, "with option:", optionId);
console.log("[Session] Permission resolved:", requestId, "for agent:", agentId);
setPendingPermissions((prev) => {
const next = new Map(prev);
@@ -724,10 +690,10 @@ export function SessionProvider({ children, serverUrl }: SessionProviderProps) {
return () => {
unsubSessionState();
unsubAgentCreated();
unsubAgentInitialized();
unsubAgentStatus();
unsubAgentUpdate();
unsubAgentState();
unsubAgentStream();
unsubAgentStreamSnapshot();
unsubStatus();
unsubPermissionRequest();
unsubPermissionResolved();
unsubAudioOutput();
@@ -746,6 +712,12 @@ export function SessionProvider({ children, serverUrl }: SessionProviderProps) {
return next;
});
setAgentStreamState((prev) => {
const next = new Map(prev);
next.set(agentId, []);
return next;
});
const msg: WSInboundMessage = {
type: "session",
message: {
@@ -764,25 +736,14 @@ export function SessionProvider({ children, serverUrl }: SessionProviderProps) {
// Optimistically add user message to stream
setAgentStreamState((prev) => {
const currentStream = prev.get(agentId) || [];
// Create AgentNotification structure that matches server format
const notification: AgentNotification = {
type: 'session',
notification: {
sessionId: '',
update: {
sessionUpdate: "user_message_chunk",
content: { type: 'text', text: message },
messageId,
},
},
const nextItem: StreamItem = {
kind: "user_message",
id: messageId,
text: message,
timestamp: new Date(),
};
// Use reduceStreamUpdate to properly create the StreamItem
const newStream = reduceStreamUpdate(currentStream, notification, new Date());
const updated = new Map(prev);
updated.set(agentId, newStream);
updated.set(agentId, [...currentStream, nextItem]);
return updated;
});
@@ -858,12 +819,14 @@ export function SessionProvider({ children, serverUrl }: SessionProviderProps) {
}
}, [ws]);
const createAgent = useCallback((options: { cwd: string; agentType: AgentType; initialMode?: string; worktreeName?: string; requestId?: string }) => {
const createAgent = useCallback(({ config, worktreeName, requestId }: { config: AgentSessionConfig; worktreeName?: string; requestId?: string }) => {
const msg: WSInboundMessage = {
type: "session",
message: {
type: "create_agent_request",
...options,
config,
...(worktreeName ? { worktreeName } : {}),
...(requestId ? { requestId } : {}),
},
};
ws.send(msg);
@@ -881,25 +844,17 @@ export function SessionProvider({ children, serverUrl }: SessionProviderProps) {
ws.send(msg);
}, [ws]);
const respondToPermission = useCallback((
requestId: string,
agentId: string,
sessionId: string,
selectedOptionIds: string[]
) => {
const respondToPermission = useCallback((agentId: string, requestId: string, response: AgentPermissionResponse) => {
const msg: WSInboundMessage = {
type: "session",
message: {
type: "agent_permission_response",
agentId,
requestId,
optionId: selectedOptionIds[0],
response,
},
};
ws.send(msg);
// Don't remove from pending here - wait for server confirmation via agent_permission_resolved
// This ensures UI stays in sync whether permission is accepted via UI or MCP
}, [ws]);
const setVoiceDetectionFlags = useCallback((isDetecting: boolean, isSpeaking: boolean) => {
@@ -978,8 +933,6 @@ export function SessionProvider({ children, serverUrl }: SessionProviderProps) {
setAgents,
commands,
setCommands,
agentUpdates,
setAgentUpdates,
pendingPermissions,
setPendingPermissions,
gitDiffs,
+1 -83
View File
@@ -1,6 +1,4 @@
import type { SessionNotification } from '@agentclientprotocol/sdk';
/**
/**
* Discriminated union types for session updates
*/
export type SessionUpdate =
@@ -119,86 +117,6 @@ export interface MergedToolCall {
endTimestamp: Date;
}
/**
* Parse SessionNotification into typed SessionUpdate
*/
export function parseSessionUpdate(notification: SessionNotification): SessionUpdate | null {
const update = (notification as any).update;
if (!update || !update.sessionUpdate) {
return null;
}
const kind = update.sessionUpdate;
switch (kind) {
case 'user_message_chunk':
return {
kind: 'user_message_chunk',
content: update.content,
};
case 'agent_message_chunk':
return {
kind: 'agent_message_chunk',
content: update.content,
};
case 'agent_thought_chunk':
return {
kind: 'agent_thought_chunk',
content: update.content,
};
case 'tool_call':
return {
kind: 'tool_call',
toolCallId: update.toolCallId,
title: update.title,
status: update.status,
toolKind: update.kind,
rawInput: update.rawInput,
rawOutput: update.rawOutput,
content: update.content,
locations: update.locations,
};
case 'tool_call_update':
return {
kind: 'tool_call_update',
toolCallId: update.toolCallId,
title: update.title,
status: update.status,
toolKind: update.kind,
rawInput: update.rawInput,
rawOutput: update.rawOutput,
content: update.content,
locations: update.locations,
};
case 'plan':
return {
kind: 'plan',
entries: update.entries,
};
case 'available_commands_update':
return {
kind: 'available_commands_update',
availableCommands: update.availableCommands,
};
case 'current_mode_update':
return {
kind: 'current_mode_update',
currentModeId: update.currentModeId,
};
default:
return null;
}
}
/**
* Group consecutive text chunks into messages and merge tool calls by ID
*/
+3 -6
View File
@@ -1,5 +1,5 @@
import type { RequestPermissionRequest } from '@agentclientprotocol/sdk';
import type { ToolCallPayload } from './stream';
import type { AgentPermissionRequest } from "@server/server/agent/agent-sdk-types";
import type { ToolCallPayload } from "./stream";
/**
* Generic tool call selection for bottom sheet
@@ -15,10 +15,7 @@ export interface SelectedToolCall {
*/
export interface PendingPermission {
agentId: string;
requestId: string;
sessionId: string;
toolCall: RequestPermissionRequest['toolCall'];
options: RequestPermissionRequest['options'];
request: AgentPermissionRequest;
}
// Agent info interface is provided by SessionContext's Agent type
+287 -350
View File
@@ -1,16 +1,15 @@
import type { AgentNotification } from '@server/server/acp/types';
import type { SessionNotification } from '@agentclientprotocol/sdk';
import type { AgentProvider } from "@server/server/agent/agent-sdk-types";
import type { AgentStreamEventPayload } from "@server/server/messages";
/**
* Simple hash function for deterministic ID generation
* Uses a basic string hash algorithm for consistency across runs
*/
function simpleHash(str: string): string {
let hash = 0;
for (let i = 0; i < str.length; i++) {
for (let i = 0; i < str.length; i += 1) {
const char = str.charCodeAt(i);
hash = ((hash << 5) - hash) + char;
hash = hash & hash; // Convert to 32bit integer
hash = (hash << 5) - hash + char;
hash |= 0; // Convert to 32bit integer
}
return Math.abs(hash).toString(36);
}
@@ -22,414 +21,352 @@ export function generateMessageId(): string {
return `msg_${Date.now()}_${Math.random().toString(36).substring(2, 11)}`;
}
/**
* Derive deterministic ID for user message based on timestamp and content
* If messageId is provided from server, use that instead
*/
function deriveUserMessageId(text: string, timestamp: Date, messageId?: string): string {
if (messageId) {
return messageId;
}
return `user_${timestamp.getTime()}_${simpleHash(text)}`;
function createTimelineId(prefix: string, text: string, timestamp: Date): string {
return `${prefix}_${timestamp.getTime()}_${simpleHash(text)}`;
}
/**
* Derive deterministic ID for assistant message
* Now uses stable messageId from server if available
*/
function deriveAssistantMessageId(messageId: string | undefined, timestamp: Date): string {
if (messageId) {
return `assistant_${messageId}`;
}
// Fallback for messages without messageId (shouldn't happen with enriched updates)
return `assistant_${timestamp.getTime()}`;
}
/**
* Derive deterministic ID for thought
* Now uses stable messageId from server if available
*/
function deriveThoughtId(messageId: string | undefined, timestamp: Date): string {
if (messageId) {
return `thought_${messageId}`;
}
// Fallback for thoughts without messageId (shouldn't happen with enriched updates)
return `thought_${timestamp.getTime()}`;
}
/**
* Unified stream item types for both orchestrator and agent views
*/
export type StreamItem =
| UserMessageItem
| AssistantMessageItem
| ThoughtItem
| ToolCallItem
| PlanItem
| ActivityLogItem
| ArtifactItem;
| ActivityLogItem;
export interface UserMessageItem {
kind: 'user_message';
kind: "user_message";
id: string;
text: string;
timestamp: Date;
}
export interface AssistantMessageItem {
kind: 'assistant_message';
kind: "assistant_message";
id: string;
text: string;
timestamp: Date;
}
export interface ThoughtItem {
kind: 'thought';
kind: "thought";
id: string;
text: string;
timestamp: Date;
}
// Extract the actual ACP tool_call type from SDK
type ACPToolCall = Extract<SessionNotification['update'], { sessionUpdate: 'tool_call' }>;
// Orchestrator tool call data (from activity_log messages)
interface OrchestratorToolCallData {
toolCallId: string;
toolName: string;
arguments: unknown;
result?: unknown;
error?: unknown;
status: 'executing' | 'completed' | 'failed';
status: "executing" | "completed" | "failed";
}
// Tagged union for tool call sources
export interface AgentToolCallData {
provider: AgentProvider;
server: string;
tool: string;
status: string;
raw?: unknown;
}
export type ToolCallPayload =
| { source: 'acp'; data: ACPToolCall }
| { source: 'orchestrator'; data: OrchestratorToolCallData };
| { source: "agent"; data: AgentToolCallData }
| { source: "orchestrator"; data: OrchestratorToolCallData };
// Simplified ToolCallItem with payload
export interface ToolCallItem {
kind: 'tool_call';
kind: "tool_call";
id: string;
timestamp: Date;
payload: ToolCallPayload;
}
export interface PlanItem {
kind: 'plan';
id: string;
entries: Array<{
content: string;
status: 'pending' | 'in_progress' | 'completed';
priority: 'high' | 'medium' | 'low';
}>;
timestamp: Date;
}
type ActivityLogType = "system" | "info" | "success" | "error";
export interface ActivityLogItem {
kind: 'activity_log';
kind: "activity_log";
id: string;
activityType: 'system' | 'transcript' | 'assistant' | 'tool_call' | 'tool_result' | 'error';
timestamp: Date;
activityType: ActivityLogType;
message: string;
metadata?: Record<string, unknown>;
timestamp: Date;
}
export interface ArtifactItem {
kind: 'artifact';
id: string;
artifactId: string;
artifactType: 'markdown' | 'diff' | 'image' | 'code';
title: string;
timestamp: Date;
}
type FileChangeEntry = { path: string; kind: string };
type TodoEntry = { text: string; completed: boolean };
// Extract ACP types for tool calls
type ACPToolCallUpdate = Extract<SessionNotification['update'], { sessionUpdate: 'tool_call_update' }>;
/**
* Parsed notification types (internal representation before converting to StreamItem)
*/
type ParsedNotification =
| { kind: 'user_message_chunk'; text: string; messageId?: string }
| { kind: 'agent_message_chunk'; text: string; messageId?: string }
| { kind: 'agent_thought_chunk'; text: string; messageId?: string }
| { kind: 'tool_call'; data: ACPToolCall }
| { kind: 'tool_call_update'; data: ACPToolCallUpdate }
| { kind: 'plan'; entries: Array<{ content: string; status: string; priority: string }> }
| { kind: 'current_mode_update'; currentModeId: string }
| { kind: 'available_commands_update'; availableCommands: Array<{ name: string; description: string }> }
| null;
/**
* Parse AgentNotification into typed ParsedNotification
* Only processes session notifications, ignoring permission and status notifications
*/
function parseNotification(notification: AgentNotification): ParsedNotification {
// Only process session notifications (discriminated union)
if (notification.type !== 'session') {
return null;
}
const update = notification.notification.update;
if (!update || !update.sessionUpdate) {
return null;
}
const kind = update.sessionUpdate;
switch (kind) {
case 'user_message_chunk': {
const content = update.content;
const text = content && content.type === 'text' ? content.text : '';
const messageId = 'messageId' in update ? update.messageId : undefined;
return {
kind: 'user_message_chunk',
text,
messageId,
};
}
case 'agent_message_chunk': {
const content = update.content;
const text = content && content.type === 'text' ? content.text : '';
const messageId = 'messageId' in update ? update.messageId : undefined;
return {
kind: 'agent_message_chunk',
text,
messageId,
};
}
case 'agent_thought_chunk': {
const content = update.content;
const text = content && content.type === 'text' ? content.text : '';
const messageId = 'messageId' in update ? update.messageId : undefined;
return {
kind: 'agent_thought_chunk',
text,
messageId,
};
}
case 'tool_call': {
return {
kind: 'tool_call' as const,
data: update as ACPToolCall,
};
}
case 'tool_call_update': {
return {
kind: 'tool_call_update' as const,
data: update as ACPToolCallUpdate,
};
}
case 'plan':
return {
kind: 'plan',
entries: update.entries,
};
case 'current_mode_update':
return {
kind: 'current_mode_update',
currentModeId: update.currentModeId,
};
case 'available_commands_update':
return {
kind: 'available_commands_update',
availableCommands: update.availableCommands,
};
default:
return null;
}
}
/**
* Core reducer function that processes stream updates one at a time
*
* This function handles:
* - Message chunks (accumulates text into single message)
* - Tool call updates (finds and merges with existing)
* - New items (appends to stream)
*
* Can be used for:
* - Hydration: updates.reduce(reduceStreamUpdate, [])
* - Real-time: setState(prev => reduceStreamUpdate(prev, update))
*/
export function reduceStreamUpdate(
state: StreamItem[],
notification: AgentNotification,
timestamp: Date
): StreamItem[] {
const parsed = parseNotification(notification);
if (!parsed) {
function appendAssistantMessage(state: StreamItem[], text: string, timestamp: Date): StreamItem[] {
const trimmed = text.trim();
if (!trimmed) {
return state;
}
// User message chunks - always create new message (they're complete from server)
if (parsed.kind === 'user_message_chunk') {
const id = deriveUserMessageId(parsed.text, timestamp, parsed.messageId);
// Idempotency check - if this exact message already exists, don't add it again
if (state.some(item => item.id === id)) {
return state;
}
return [...state, {
kind: 'user_message',
id,
text: parsed.text,
const last = state[state.length - 1];
if (last && last.kind === "assistant_message") {
const updated: AssistantMessageItem = {
...last,
text: `${last.text}${trimmed}`,
timestamp,
}];
}
// Agent message chunks - accumulate into message with matching ID or create new
if (parsed.kind === 'agent_message_chunk') {
const id = deriveAssistantMessageId(parsed.messageId, timestamp);
// Find existing message with this ID
const existingIndex = state.findIndex(
item => item.kind === 'assistant_message' && item.id === id
);
if (existingIndex >= 0) {
// Append to existing message
const existing = state[existingIndex] as AssistantMessageItem;
return state.map((item, idx) =>
idx === existingIndex
? { ...existing, text: existing.text + parsed.text }
: item
);
}
// Create new message with stable ID
return [...state, {
kind: 'assistant_message',
id,
text: parsed.text,
timestamp,
}];
}
// Thought chunks - accumulate into thought with matching ID or create new
if (parsed.kind === 'agent_thought_chunk') {
const id = deriveThoughtId(parsed.messageId, timestamp);
// Find existing thought with this ID
const existingIndex = state.findIndex(
item => item.kind === 'thought' && item.id === id
);
if (existingIndex >= 0) {
// Append to existing thought
const existing = state[existingIndex] as ThoughtItem;
return state.map((item, idx) =>
idx === existingIndex
? { ...existing, text: existing.text + parsed.text }
: item
);
}
// Create new thought with stable ID
return [...state, {
kind: 'thought',
id,
text: parsed.text,
timestamp,
}];
}
// Tool call updates - find existing and merge
if (parsed.kind === 'tool_call_update') {
return state.map(item => {
if (item.kind === 'tool_call' &&
item.payload.source === 'acp' &&
item.payload.data.toolCallId === parsed.data.toolCallId) {
// Merge the update data with existing ACP data
const updatedData = { ...item.payload.data };
// Apply non-null updates from parsed.data
Object.entries(parsed.data).forEach(([key, value]) => {
if (value !== undefined && value !== null) {
(updatedData as any)[key] = value;
}
});
return {
...item,
payload: { source: 'acp' as const, data: updatedData },
timestamp,
};
}
return item;
});
}
// New tool call - check if exists first (server may send multiple notifications for same tool)
if (parsed.kind === 'tool_call') {
const existingIndex = state.findIndex(
item => item.kind === 'tool_call' &&
item.payload.source === 'acp' &&
item.payload.data.toolCallId === parsed.data.toolCallId
);
if (existingIndex >= 0) {
// Update existing tool call
return state.map((item, idx) => {
if (idx === existingIndex && item.kind === 'tool_call') {
return {
...item,
payload: { source: 'acp' as const, data: parsed.data },
timestamp,
};
}
return item;
});
}
// Create new tool call
const newToolCall: ToolCallItem = {
kind: 'tool_call',
id: parsed.data.toolCallId,
timestamp,
payload: { source: 'acp', data: parsed.data },
};
return [...state, newToolCall];
return [...state.slice(0, -1), updated];
}
// Plan - replace existing or create new (uses constant ID since only one plan exists)
if (parsed.kind === 'plan') {
const withoutPlan = state.filter(item => item.kind !== 'plan');
return [...withoutPlan, {
kind: 'plan',
id: 'plan_latest',
entries: parsed.entries as any,
const item: AssistantMessageItem = {
kind: "assistant_message",
id: createTimelineId("assistant", trimmed, timestamp),
text: trimmed,
timestamp,
};
return [...state, item];
}
function appendThought(state: StreamItem[], text: string, timestamp: Date): StreamItem[] {
const trimmed = text.trim();
if (!trimmed) {
return state;
}
const last = state[state.length - 1];
if (last && last.kind === "thought") {
const updated: ThoughtItem = {
...last,
text: `${last.text}${trimmed}`,
timestamp,
}];
};
return [...state.slice(0, -1), updated];
}
// Mode updates and other types don't create stream items
// They're handled separately in state management
return state;
const item: ThoughtItem = {
kind: "thought",
id: createTimelineId("thought", trimmed, timestamp),
text: trimmed,
timestamp,
};
return [...state, item];
}
function appendAgentToolCall(
state: StreamItem[],
data: AgentToolCallData,
timestamp: Date
): StreamItem[] {
const status = data.status;
const id = createTimelineId(
"tool",
`${data.provider}:${data.server}:${data.tool}:${status}`,
timestamp
);
const normalizedStatus: "executing" | "completed" | "failed" =
status === "completed"
? "completed"
: status === "failed"
? "failed"
: "executing";
const item: ToolCallItem = {
kind: "tool_call",
id,
timestamp,
payload: {
source: "agent",
data: { ...data, status: normalizedStatus },
},
};
// Replace existing entry with same ID if present
const index = state.findIndex((entry) => entry.id === id);
if (index >= 0) {
const next = [...state];
next[index] = item;
return next;
}
return [...state, item];
}
function appendActivityLog(state: StreamItem[], entry: ActivityLogItem): StreamItem[] {
const index = state.findIndex((existing) => existing.id === entry.id);
if (index >= 0) {
const next = [...state];
next[index] = entry;
return next;
}
return [...state, entry];
}
function toHumanLabel(value?: string): string {
if (!value) {
return "";
}
return value
.replace(/[_-]+/g, " ")
.split(" ")
.filter(Boolean)
.map((word) => word.charAt(0).toUpperCase() + word.slice(1))
.join(" ");
}
function describeCommandStatus(status?: string): ActivityLogType {
if (!status) {
return "info";
}
const normalized = status.toLowerCase();
if (
normalized.includes("fail") ||
normalized.includes("error") ||
normalized.includes("deny") ||
normalized.includes("reject")
) {
return "error";
}
if (
normalized.includes("success") ||
normalized.includes("complete") ||
normalized.includes("granted") ||
normalized.includes("applied")
) {
return "success";
}
return "info";
}
function formatCommandMessage(command: string, status?: string): string {
const label = status ? toHumanLabel(status) : null;
const header = label ? `Command (${label})` : "Command";
return `${header}\n${command}`;
}
function formatFileChangeMessage(files: FileChangeEntry[]): string {
if (!files.length) {
return "File changes";
}
const header = files.length === 1 ? "File change" : `${files.length} file changes`;
const entries = files.map((file) => {
const kindLabel = file.kind ? toHumanLabel(file.kind) : "";
return `• ${kindLabel ? `[${kindLabel}] ` : ""}${file.path}`;
});
return [header, ...entries].join("\n");
}
function formatWebSearchMessage(query: string): string {
return `Web search\n"${query.trim()}"`;
}
function formatTodoMessage(items: TodoEntry[]): string {
if (!items.length) {
return "Todo list";
}
const header = "Todo list";
const entries = items.map((item) => `• [${item.completed ? "x" : " "}] ${item.text}`);
return [header, ...entries].join("\n");
}
function formatErrorMessage(message: string): string {
return `Agent error\n${message}`;
}
/**
* Hydrate stream state from batch of notifications
* Reduce a single AgentManager stream event into the UI timeline
*/
export function reduceStreamUpdate(
state: StreamItem[],
event: AgentStreamEventPayload,
timestamp: Date
): StreamItem[] {
switch (event.type) {
case "timeline": {
const item = event.item;
switch (item.type) {
case "assistant_message":
return appendAssistantMessage(state, item.text, timestamp);
case "reasoning":
return appendThought(state, item.text, timestamp);
case "mcp_tool":
return appendAgentToolCall(
state,
{
provider: event.provider,
server: item.server,
tool: item.tool,
status: item.status,
raw: item.raw,
},
timestamp
);
case "command": {
const activity: ActivityLogItem = {
kind: "activity_log",
id: createTimelineId("command", `${item.command}:${item.status ?? ""}`, timestamp),
timestamp,
activityType: describeCommandStatus(item.status),
message: formatCommandMessage(item.command, item.status),
metadata: item.raw ? { raw: item.raw } : undefined,
};
return appendActivityLog(state, activity);
}
case "file_change": {
const files = (item.files ?? []) as FileChangeEntry[];
const activity: ActivityLogItem = {
kind: "activity_log",
id: createTimelineId("file_change", JSON.stringify(files), timestamp),
timestamp,
activityType: "info",
message: formatFileChangeMessage(files),
metadata: files.length ? { files } : undefined,
};
return appendActivityLog(state, activity);
}
case "web_search": {
const activity: ActivityLogItem = {
kind: "activity_log",
id: createTimelineId("web_search", item.query ?? "", timestamp),
timestamp,
activityType: "info",
message: formatWebSearchMessage(item.query ?? ""),
metadata: item.raw ? { raw: item.raw } : { query: item.query },
};
return appendActivityLog(state, activity);
}
case "todo": {
const items = (item.items ?? []) as TodoEntry[];
const activity: ActivityLogItem = {
kind: "activity_log",
id: createTimelineId("todo", JSON.stringify(items), timestamp),
timestamp,
activityType: "system",
message: formatTodoMessage(items),
metadata: items.length ? { items } : undefined,
};
return appendActivityLog(state, activity);
}
case "error": {
const activity: ActivityLogItem = {
kind: "activity_log",
id: createTimelineId("error", item.message ?? "", timestamp),
timestamp,
activityType: "error",
message: formatErrorMessage(item.message ?? "Unknown error"),
metadata: item.raw ? { raw: item.raw } : undefined,
};
return appendActivityLog(state, activity);
}
default:
return state;
}
}
default:
return state;
}
}
/**
* Hydrate stream state from a batch of AgentManager stream events
*/
export function hydrateStreamState(
notifications: Array<{ timestamp: Date; notification: AgentNotification }>
events: Array<{ event: AgentStreamEventPayload; timestamp: Date }>
): StreamItem[] {
return notifications.reduce(
(state, { notification, timestamp }) => reduceStreamUpdate(state, notification, timestamp),
[] as StreamItem[]
);
return events.reduce<StreamItem[]>((state, { event, timestamp }) => {
return reduceStreamUpdate(state, event, timestamp);
}, []);
}
+27
View File
@@ -0,0 +1,27 @@
import type { Agent } from "@/contexts/session-context";
type AgentStatus = Agent["status"];
const STATUS_COLOR_MAP: Record<AgentStatus, string> = {
initializing: "#f59e0b",
idle: "#22c55e",
running: "#3b82f6",
error: "#ef4444",
closed: "#6b7280",
};
const STATUS_LABEL_MAP: Record<AgentStatus, string> = {
initializing: "Initializing",
idle: "Idle",
running: "Running",
error: "Error",
closed: "Closed",
};
export function getAgentStatusColor(status: AgentStatus): string {
return STATUS_COLOR_MAP[status] ?? "#9ca3af";
}
export function getAgentStatusLabel(status: AgentStatus): string {
return STATUS_LABEL_MAP[status] ?? "Unknown";
}