Fix agent routing and E2E create flow

This commit is contained in:
Mohamed Boudra
2026-01-24 20:20:56 +07:00
parent 3e2d403f1b
commit dc4839e2c0
14 changed files with 204 additions and 147 deletions
+6 -2
View File
@@ -135,7 +135,7 @@ async function assertE2EUsesSeededTestDaemon(page: Page): Promise<void> {
} }
export const gotoHome = async (page: Page) => { export const gotoHome = async (page: Page) => {
await page.goto('/agent'); await page.goto('/');
await ensureE2EStorageSeeded(page); await ensureE2EStorageSeeded(page);
await expect(page.getByText('New Agent', { exact: true }).first()).toBeVisible(); await expect(page.getByText('New Agent', { exact: true }).first()).toBeVisible();
await expect(page.getByRole('textbox', { name: 'Message agent...' })).toBeVisible(); await expect(page.getByRole('textbox', { name: 'Message agent...' })).toBeVisible();
@@ -314,7 +314,11 @@ export const createAgent = async (page: Page, message: string) => {
// Expo Router navigations can be "same-document" updates, so avoid waiting for a full `load`. // Expo Router navigations can be "same-document" updates, so avoid waiting for a full `load`.
await page.waitForURL(/\/agent\//, { waitUntil: 'commit' }); await page.waitForURL(/\/agent\//, { waitUntil: 'commit' });
await expect(page.getByText(message, { exact: true })).toBeVisible(); const userBubble = page
.getByRole('button', { name: 'Copy message' })
.filter({ hasText: message })
.first();
await expect(userBubble).toBeVisible();
}; };
export interface AgentConfig { export interface AgentConfig {
+5 -1
View File
@@ -347,8 +347,12 @@ export default function RootLayout() {
> >
<Stack.Screen name="index" /> <Stack.Screen name="index" />
<Stack.Screen name="agents" /> <Stack.Screen name="agents" />
<Stack.Screen name="agent" />
<Stack.Screen name="agent/[id]" options={{ gestureEnabled: false }} /> <Stack.Screen name="agent/[id]" options={{ gestureEnabled: false }} />
<Stack.Screen name="agent/[serverId]/[agentId]" options={{ gestureEnabled: false }} /> <Stack.Screen
name="agent/[serverId]/[agentId]"
options={{ gestureEnabled: false }}
/>
<Stack.Screen name="settings" /> <Stack.Screen name="settings" />
<Stack.Screen name="audio-test" /> <Stack.Screen name="audio-test" />
<Stack.Screen name="pair-scan" /> <Stack.Screen name="pair-scan" />
-109
View File
@@ -1,109 +0,0 @@
import { useEffect, useMemo, useState } from "react";
import { View } from "react-native";
import { useLocalSearchParams } from "expo-router";
import { StyleSheet } from "react-native-unistyles";
import { DraftAgentScreen } from "@/screens/agent/draft-agent-screen";
import { AgentReadyScreen } from "@/screens/agent/agent-ready-screen";
import { LegacyAgentIdScreen } from "@/screens/agent/legacy-agent-id-screen";
import { useSessionStore } from "@/stores/session-store";
type AgentRouteParams = {
route?: string[] | string;
};
function normalizeSegments(raw: AgentRouteParams["route"]): string[] {
if (!raw) return [];
if (Array.isArray(raw)) return raw.filter((s) => typeof s === "string" && s.length > 0);
if (typeof raw === "string") return raw.length > 0 ? [raw] : [];
return [];
}
type RouteKind = "draft" | "legacy" | "ready";
export default function AgentRoute() {
const params = useLocalSearchParams<AgentRouteParams>();
const segments = useMemo(() => normalizeSegments(params.route), [params.route]);
const routeKind: RouteKind =
segments.length === 0 ? "draft" : segments.length === 1 ? "legacy" : "ready";
const legacyAgentId = segments.length === 1 ? segments[0] : "";
const serverId = segments.length >= 2 ? segments[0] : "";
const agentId = segments.length >= 2 ? segments[1] : "";
const agent = useSessionStore((state) =>
serverId && agentId ? state.sessions[serverId]?.agents?.get(agentId) : undefined
);
const isInitializingFromMap = useSessionStore((state) =>
serverId && agentId
? state.sessions[serverId]?.initializingAgents?.get(agentId) ?? false
: false
);
const isInitializing = agentId ? isInitializingFromMap !== false : false;
const isAgentReady = Boolean(agent && !isInitializing);
const [createFlowActive, setCreateFlowActive] = useState(false);
const [shouldMountDraft, setShouldMountDraft] = useState(routeKind === "draft");
useEffect(() => {
if (routeKind === "draft") {
setShouldMountDraft(true);
}
}, [routeKind]);
const ensureAgentIsInitialized = useSessionStore((state) =>
serverId ? state.sessions[serverId]?.methods?.ensureAgentIsInitialized : undefined
);
const isConnected = useSessionStore((state) =>
serverId ? state.sessions[serverId]?.connection.isConnected ?? false : false
);
useEffect(() => {
if (routeKind !== "ready") return;
if (!agentId || !ensureAgentIsInitialized) return;
if (!isConnected) return;
ensureAgentIsInitialized(agentId).catch((error) => {
console.warn("[AgentRoute] Agent initialization failed", {
agentId,
serverId,
error,
});
});
}, [agentId, ensureAgentIsInitialized, isConnected, routeKind, serverId]);
useEffect(() => {
if (routeKind !== "ready") {
return;
}
if (createFlowActive && isAgentReady) {
setCreateFlowActive(false);
}
}, [createFlowActive, isAgentReady, routeKind]);
if (routeKind === "legacy") {
return <LegacyAgentIdScreen agentId={legacyAgentId} />;
}
const shouldShowDraft =
routeKind === "draft" || (routeKind === "ready" && createFlowActive && !isAgentReady);
const shouldShowReady = routeKind === "ready" && (!createFlowActive || isAgentReady);
return (
<View style={styles.container}>
{shouldShowReady ? <AgentReadyScreen serverId={serverId} agentId={agentId} /> : null}
{shouldMountDraft && shouldShowDraft ? (
<DraftAgentScreen
isVisible={shouldShowDraft}
onCreateFlowActiveChange={setCreateFlowActive}
/>
) : null}
</View>
);
}
const styles = StyleSheet.create((theme) => ({
container: {
flex: 1,
backgroundColor: theme.colors.surface0,
},
}));
+8
View File
@@ -0,0 +1,8 @@
import { useLocalSearchParams } from "expo-router";
import { LegacyAgentIdScreen } from "@/screens/agent/legacy-agent-id-screen";
export default function LegacyAgentRoute() {
const { id } = useLocalSearchParams<{ id?: string }>();
return <LegacyAgentIdScreen agentId={typeof id === "string" ? id : ""} />;
}
@@ -0,0 +1,17 @@
import { useLocalSearchParams } from "expo-router";
import { AgentReadyScreen } from "@/screens/agent/agent-ready-screen";
export default function AgentReadyRoute() {
const { serverId, agentId } = useLocalSearchParams<{
serverId?: string;
agentId?: string;
}>();
return (
<AgentReadyScreen
serverId={typeof serverId === "string" ? serverId : ""}
agentId={typeof agentId === "string" ? agentId : ""}
/>
);
}
+6
View File
@@ -0,0 +1,6 @@
import { DraftAgentScreen } from "@/screens/agent/draft-agent-screen";
export default function AgentDraftRoute() {
return <DraftAgentScreen />;
}
+1 -4
View File
@@ -84,10 +84,7 @@ export function AgentList({
onAgentSelect?.(); onAgentSelect?.();
navigate({ navigate(`/agent/${serverId}/${agentId}` as any);
pathname: "/agent/[[...route]]",
params: { route: [serverId, agentId] },
});
}, },
[isActionSheetVisible, pathname, onAgentSelect] [isActionSheetVisible, pathname, onAgentSelect]
); );
@@ -607,7 +607,7 @@ export function GitDiffPane({ serverId, agentId }: GitDiffPaneProps) {
predicate: (query) => predicate: (query) =>
Array.isArray(query.queryKey) && query.queryKey[0] === "paseoWorktreeList", Array.isArray(query.queryKey) && query.queryKey[0] === "paseoWorktreeList",
}); });
router.replace({ pathname: "/agent/[[...route]]" }); router.replace("/agent" as any);
}, },
onError: (err) => { onError: (err) => {
const message = err instanceof Error ? err.message : "Failed to archive worktree"; const message = err instanceof Error ? err.message : "Failed to archive worktree";
+1 -1
View File
@@ -142,7 +142,7 @@ export function HomeFooter() {
<Pressable <Pressable
onPress={() => { onPress={() => {
console.log("[HomeFooter] New Agent button pressed"); console.log("[HomeFooter] New Agent button pressed");
router.push({ pathname: "/agent/[[...route]]" }); router.push("/agent" as any);
}} }}
style={({ pressed }) => [ style={({ pressed }) => [
styles.footerButton, styles.footerButton,
@@ -82,7 +82,7 @@ export function SlidingSidebar({ selectedAgentId }: SlidingSidebarProps) {
}, [closeToAgent]); }, [closeToAgent]);
const handleCreateAgentClean = useCallback(() => { const handleCreateAgentClean = useCallback(() => {
router.push({ pathname: "/agent/[[...route]]" }); router.push("/agent" as any);
}, []); }, []);
// Mobile: close sidebar and navigate // Mobile: close sidebar and navigate
@@ -45,6 +45,8 @@ import { useDaemonConnections } from "@/contexts/daemon-connections-context";
import type { ConnectionStatus } from "@/contexts/daemon-connections-context"; import type { ConnectionStatus } from "@/contexts/daemon-connections-context";
import { formatConnectionStatus } from "@/utils/daemons"; import { formatConnectionStatus } from "@/utils/daemons";
import { useSessionStore } from "@/stores/session-store"; import { useSessionStore } from "@/stores/session-store";
import { useCreateFlowStore } from "@/stores/create-flow-store";
import type { Agent } from "@/contexts/session-context";
import type { StreamItem } from "@/types/stream"; import type { StreamItem } from "@/types/stream";
import { import {
buildAgentNavigationKey, buildAgentNavigationKey,
@@ -118,7 +120,7 @@ export function AgentReadyScreen({
targetMs: 300, targetMs: 300,
}); });
} }
router.replace({ pathname: "/agent/[[...route]]" }); router.replace("/agent" as any);
}, [resolvedAgentId, resolvedServerId, router]); }, [resolvedAgentId, resolvedServerId, router]);
const focusServerId = resolvedServerId; const focusServerId = resolvedServerId;
@@ -300,11 +302,17 @@ function AgentScreenContent({
); );
const streamItems = streamItemsRaw ?? EMPTY_STREAM_ITEMS; const streamItems = streamItemsRaw ?? EMPTY_STREAM_ITEMS;
const pendingCreate = useCreateFlowStore((state) => state.pending);
const clearPendingCreate = useCreateFlowStore((state) => state.clear);
const isPendingCreateForRoute =
Boolean(pendingCreate) &&
pendingCreate?.serverId === serverId &&
pendingCreate?.agentId === resolvedAgentId;
// Select only the specific initializing state // Select only the specific initializing state
const isInitializingFromMap = useSessionStore((state) => const isInitializingFromMap = useSessionStore((state) =>
resolvedAgentId resolvedAgentId
? state.sessions[serverId]?.initializingAgents?.get(resolvedAgentId) ?? ? state.sessions[serverId]?.initializingAgents?.get(resolvedAgentId) ?? false
false
: false : false
); );
@@ -410,9 +418,97 @@ function AgentScreenContent({
}; };
}, [resolvedAgentId, setFocusedAgentId]); }, [resolvedAgentId, setFocusedAgentId]);
const isInitializing = resolvedAgentId const isInitializing = resolvedAgentId ? isInitializingFromMap !== false : false;
? isInitializingFromMap !== false
: false; const optimisticStreamItems = useMemo<StreamItem[]>(() => {
if (!isPendingCreateForRoute || !pendingCreate) {
return EMPTY_STREAM_ITEMS;
}
return [
{
kind: "user_message",
id: pendingCreate.messageId,
text: pendingCreate.text,
timestamp: new Date(pendingCreate.timestamp),
},
];
}, [isPendingCreateForRoute, pendingCreate]);
const mergedStreamItems = useMemo<StreamItem[]>(() => {
if (optimisticStreamItems.length === 0) {
return streamItems;
}
const optimistic = optimisticStreamItems[0];
if (!optimistic) {
return streamItems;
}
const alreadyHasOptimistic = streamItems.some(
(item) => item.kind === "user_message" && item.id === optimistic.id
);
return alreadyHasOptimistic ? streamItems : [...optimisticStreamItems, ...streamItems];
}, [optimisticStreamItems, streamItems]);
const shouldUseOptimisticStream = isPendingCreateForRoute && optimisticStreamItems.length > 0;
const placeholderAgent: Agent | null = useMemo(() => {
if (!shouldUseOptimisticStream || !resolvedAgentId) {
return null;
}
const now = new Date();
return {
serverId,
id: resolvedAgentId,
provider: "claude",
status: "running",
createdAt: now,
updatedAt: now,
lastUserMessageAt: now,
lastActivityAt: now,
capabilities: {
supportsStreaming: true,
supportsSessionPersistence: false,
supportsDynamicModes: false,
supportsMcpServers: false,
supportsReasoningStream: false,
supportsToolInvocations: false,
},
currentModeId: null,
availableModes: [],
pendingPermissions: [],
persistence: null,
runtimeInfo: {
provider: "claude",
sessionId: null,
model: null,
modeId: null,
},
title: "Agent",
cwd: ".",
model: null,
};
}, [resolvedAgentId, serverId, shouldUseOptimisticStream]);
const effectiveAgent = agent ?? placeholderAgent;
useEffect(() => {
if (!isPendingCreateForRoute || !pendingCreate) {
return;
}
const hasUserMessage = streamItems.some(
(item) =>
item.kind === "user_message" &&
(item.id === pendingCreate.messageId || item.text === pendingCreate.text)
);
if (agent && hasUserMessage) {
clearPendingCreate();
}
}, [
agent,
clearPendingCreate,
isPendingCreateForRoute,
pendingCreate,
streamItems,
]);
// Get ensureAgentIsInitialized from methods // Get ensureAgentIsInitialized from methods
const ensureAgentIsInitialized = methods?.ensureAgentIsInitialized; const ensureAgentIsInitialized = methods?.ensureAgentIsInitialized;
@@ -482,7 +578,7 @@ function AgentScreenContent({
refreshAgent({ agentId: resolvedAgentId }); refreshAgent({ agentId: resolvedAgentId });
}, [resolvedAgentId, refreshAgent]); }, [resolvedAgentId, refreshAgent]);
if (!agent) { if (!effectiveAgent) {
return ( return (
<View style={styles.container} testID="agent-not-found"> <View style={styles.container} testID="agent-not-found">
<MenuHeader title="Agent" /> <MenuHeader title="Agent" />
@@ -499,7 +595,7 @@ function AgentScreenContent({
<View style={styles.container}> <View style={styles.container}>
{/* Header */} {/* Header */}
<MenuHeader <MenuHeader
title={agent.title || "Agent"} title={effectiveAgent.title || "Agent"}
rightContent={ rightContent={
<View style={styles.headerRightContent}> <View style={styles.headerRightContent}>
<Pressable onPress={toggleFileExplorer} style={styles.menuButton}> <Pressable onPress={toggleFileExplorer} style={styles.menuButton}>
@@ -542,7 +638,7 @@ function AgentScreenContent({
numberOfLines={2} numberOfLines={2}
ellipsizeMode="middle" ellipsizeMode="middle"
> >
{shortenPath(agent.cwd)} {shortenPath(effectiveAgent.cwd)}
</Text> </Text>
</View> </View>
@@ -625,7 +721,7 @@ function AgentScreenContent({
<ReanimatedAnimated.View <ReanimatedAnimated.View
style={[styles.content, animatedKeyboardStyle]} style={[styles.content, animatedKeyboardStyle]}
> >
{isInitializing ? ( {isInitializing && !shouldUseOptimisticStream ? (
<View style={styles.loadingContainer}> <View style={styles.loadingContainer}>
<ActivityIndicator <ActivityIndicator
size="large" size="large"
@@ -635,10 +731,10 @@ function AgentScreenContent({
</View> </View>
) : ( ) : (
<AgentStreamView <AgentStreamView
agentId={agent.id} agentId={effectiveAgent.id}
serverId={serverId} serverId={serverId}
agent={agent} agent={effectiveAgent}
streamItems={streamItems} streamItems={shouldUseOptimisticStream ? mergedStreamItems : streamItems}
pendingPermissions={pendingPermissions} pendingPermissions={pendingPermissions}
/> />
)} )}
@@ -31,6 +31,7 @@ import { useDaemonConnections } from "@/contexts/daemon-connections-context";
import { useDaemonRegistry } from "@/contexts/daemon-registry-context"; import { useDaemonRegistry } from "@/contexts/daemon-registry-context";
import { formatConnectionStatus } from "@/utils/daemons"; import { formatConnectionStatus } from "@/utils/daemons";
import { useSessionStore } from "@/stores/session-store"; import { useSessionStore } from "@/stores/session-store";
import { useCreateFlowStore } from "@/stores/create-flow-store";
import { MAX_CONTENT_WIDTH } from "@/constants/layout"; import { MAX_CONTENT_WIDTH } from "@/constants/layout";
import { WelcomeScreen } from "@/components/welcome-screen"; import { WelcomeScreen } from "@/components/welcome-screen";
import type { Agent } from "@/contexts/session-context"; import type { Agent } from "@/contexts/session-context";
@@ -197,6 +198,9 @@ export function DraftAgentScreen({
const [worktreeSlug, setWorktreeSlug] = useState(""); const [worktreeSlug, setWorktreeSlug] = useState("");
const [selectedWorktreePath, setSelectedWorktreePath] = useState(""); const [selectedWorktreePath, setSelectedWorktreePath] = useState("");
const addImagesRef = useRef<((images: ImageAttachment[]) => void) | null>(null); const addImagesRef = useRef<((images: ImageAttachment[]) => void) | null>(null);
const setPendingCreateAttempt = useCreateFlowStore((state) => state.setPending);
const updatePendingAgentId = useCreateFlowStore((state) => state.updateAgentId);
const clearPendingCreateAttempt = useCreateFlowStore((state) => state.clear);
type CreateAttempt = { type CreateAttempt = {
messageId: string; messageId: string;
@@ -544,8 +548,7 @@ export function DraftAgentScreen({
selectedServerId ? state.sessions[selectedServerId]?.methods : undefined selectedServerId ? state.sessions[selectedServerId]?.methods : undefined
); );
const promptValue = const promptValue = machine.tag === "draft" ? machine.promptText : "";
machine.tag === "draft" ? machine.promptText : machine.attempt.text;
const formErrorMessage = machine.tag === "draft" ? machine.errorMessage : ""; const formErrorMessage = machine.tag === "draft" ? machine.errorMessage : "";
const isSubmitting = machine.tag === "creating"; const isSubmitting = machine.tag === "creating";
@@ -671,6 +674,13 @@ export function DraftAgentScreen({
text: trimmedPrompt, text: trimmedPrompt,
timestamp: new Date(), timestamp: new Date(),
}; };
setPendingCreateAttempt({
serverId: selectedServerId,
agentId: null,
messageId: attempt.messageId,
text: attempt.text,
timestamp: attempt.timestamp.getTime(),
});
const modeId = const modeId =
modeOptions.length > 0 && selectedMode !== "" ? selectedMode : undefined; modeOptions.length > 0 && selectedMode !== "" ? selectedMode : undefined;
const trimmedModel = selectedModel.trim(); const trimmedModel = selectedModel.trim();
@@ -715,10 +725,8 @@ export function DraftAgentScreen({
const agentId = (result as { id?: string })?.id; const agentId = (result as { id?: string })?.id;
if (agentId && selectedServerId) { if (agentId && selectedServerId) {
router.replace({ updatePendingAgentId(agentId);
pathname: "/agent/[[...route]]", router.replace(`/agent/${selectedServerId}/${agentId}` as any);
params: { route: [selectedServerId, agentId] },
});
return; return;
} }
@@ -727,11 +735,13 @@ export function DraftAgentScreen({
message: "Failed to create agent", message: "Failed to create agent",
}); });
onCreateFlowActiveChange?.(false); onCreateFlowActiveChange?.(false);
clearPendingCreateAttempt();
throw new Error("Failed to create agent"); throw new Error("Failed to create agent");
} catch (error) { } catch (error) {
const message = error instanceof Error ? error.message : "Failed to create agent"; const message = error instanceof Error ? error.message : "Failed to create agent";
dispatch({ type: "CREATE_FAILED", message }); dispatch({ type: "CREATE_FAILED", message });
onCreateFlowActiveChange?.(false); onCreateFlowActiveChange?.(false);
clearPendingCreateAttempt();
throw error; // Re-throw so AgentInputArea knows it failed throw error; // Re-throw so AgentInputArea knows it failed
} }
}, },
@@ -753,6 +763,9 @@ export function DraftAgentScreen({
selectedProvider, selectedProvider,
selectedServerId, selectedServerId,
sessionMethods, sessionMethods,
setPendingCreateAttempt,
updatePendingAgentId,
clearPendingCreateAttempt,
workingDir, workingDir,
isAttachWorktree, isAttachWorktree,
isSubmitting, isSubmitting,
@@ -50,22 +50,16 @@ export function LegacyAgentIdScreen({ agentId }: { agentId: string }) {
return; return;
} }
const match = matches[0]; const match = matches[0];
router.replace({ router.replace(`/agent/${match.serverId}/${match.agent.id}` as any);
pathname: "/agent/[[...route]]",
params: { route: [match.serverId, match.agent.id] },
});
}, [isRedirecting, matches, router]); }, [isRedirecting, matches, router]);
const handleGoDraft = useCallback(() => { const handleGoDraft = useCallback(() => {
router.replace({ pathname: "/agent/[[...route]]" }); router.replace("/agent" as any);
}, [router]); }, [router]);
const handleSelectMatch = useCallback( const handleSelectMatch = useCallback(
(match: AgentMatch) => { (match: AgentMatch) => {
router.replace({ router.replace(`/agent/${match.serverId}/${match.agent.id}` as any);
pathname: "/agent/[[...route]]",
params: { route: [match.serverId, match.agent.id] },
});
}, },
[router] [router]
); );
@@ -0,0 +1,27 @@
import { create } from "zustand";
type PendingCreateAttempt = {
serverId: string;
agentId: string | null;
messageId: string;
text: string;
timestamp: number;
};
type CreateFlowState = {
pending: PendingCreateAttempt | null;
setPending: (pending: PendingCreateAttempt) => void;
updateAgentId: (agentId: string) => void;
clear: () => void;
};
export const useCreateFlowStore = create<CreateFlowState>((set) => ({
pending: null,
setPending: (pending) => set({ pending }),
updateAgentId: (agentId) =>
set((state) =>
state.pending ? { pending: { ...state.pending, agentId } } : state
),
clear: () => set({ pending: null }),
}));