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) => {
await page.goto('/agent');
await page.goto('/');
await ensureE2EStorageSeeded(page);
await expect(page.getByText('New Agent', { exact: true }).first()).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`.
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 {
+5 -1
View File
@@ -347,8 +347,12 @@ export default function RootLayout() {
>
<Stack.Screen name="index" />
<Stack.Screen name="agents" />
<Stack.Screen name="agent" />
<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="audio-test" />
<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?.();
navigate({
pathname: "/agent/[[...route]]",
params: { route: [serverId, agentId] },
});
navigate(`/agent/${serverId}/${agentId}` as any);
},
[isActionSheetVisible, pathname, onAgentSelect]
);
@@ -607,7 +607,7 @@ export function GitDiffPane({ serverId, agentId }: GitDiffPaneProps) {
predicate: (query) =>
Array.isArray(query.queryKey) && query.queryKey[0] === "paseoWorktreeList",
});
router.replace({ pathname: "/agent/[[...route]]" });
router.replace("/agent" as any);
},
onError: (err) => {
const message = err instanceof Error ? err.message : "Failed to archive worktree";
+1 -1
View File
@@ -142,7 +142,7 @@ export function HomeFooter() {
<Pressable
onPress={() => {
console.log("[HomeFooter] New Agent button pressed");
router.push({ pathname: "/agent/[[...route]]" });
router.push("/agent" as any);
}}
style={({ pressed }) => [
styles.footerButton,
@@ -82,7 +82,7 @@ export function SlidingSidebar({ selectedAgentId }: SlidingSidebarProps) {
}, [closeToAgent]);
const handleCreateAgentClean = useCallback(() => {
router.push({ pathname: "/agent/[[...route]]" });
router.push("/agent" as any);
}, []);
// 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 { formatConnectionStatus } from "@/utils/daemons";
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 {
buildAgentNavigationKey,
@@ -118,7 +120,7 @@ export function AgentReadyScreen({
targetMs: 300,
});
}
router.replace({ pathname: "/agent/[[...route]]" });
router.replace("/agent" as any);
}, [resolvedAgentId, resolvedServerId, router]);
const focusServerId = resolvedServerId;
@@ -300,11 +302,17 @@ function AgentScreenContent({
);
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
const isInitializingFromMap = useSessionStore((state) =>
resolvedAgentId
? state.sessions[serverId]?.initializingAgents?.get(resolvedAgentId) ??
false
? state.sessions[serverId]?.initializingAgents?.get(resolvedAgentId) ?? false
: false
);
@@ -410,9 +418,97 @@ function AgentScreenContent({
};
}, [resolvedAgentId, setFocusedAgentId]);
const isInitializing = resolvedAgentId
? isInitializingFromMap !== false
: false;
const isInitializing = resolvedAgentId ? 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
const ensureAgentIsInitialized = methods?.ensureAgentIsInitialized;
@@ -482,7 +578,7 @@ function AgentScreenContent({
refreshAgent({ agentId: resolvedAgentId });
}, [resolvedAgentId, refreshAgent]);
if (!agent) {
if (!effectiveAgent) {
return (
<View style={styles.container} testID="agent-not-found">
<MenuHeader title="Agent" />
@@ -499,7 +595,7 @@ function AgentScreenContent({
<View style={styles.container}>
{/* Header */}
<MenuHeader
title={agent.title || "Agent"}
title={effectiveAgent.title || "Agent"}
rightContent={
<View style={styles.headerRightContent}>
<Pressable onPress={toggleFileExplorer} style={styles.menuButton}>
@@ -542,7 +638,7 @@ function AgentScreenContent({
numberOfLines={2}
ellipsizeMode="middle"
>
{shortenPath(agent.cwd)}
{shortenPath(effectiveAgent.cwd)}
</Text>
</View>
@@ -625,7 +721,7 @@ function AgentScreenContent({
<ReanimatedAnimated.View
style={[styles.content, animatedKeyboardStyle]}
>
{isInitializing ? (
{isInitializing && !shouldUseOptimisticStream ? (
<View style={styles.loadingContainer}>
<ActivityIndicator
size="large"
@@ -635,10 +731,10 @@ function AgentScreenContent({
</View>
) : (
<AgentStreamView
agentId={agent.id}
agentId={effectiveAgent.id}
serverId={serverId}
agent={agent}
streamItems={streamItems}
agent={effectiveAgent}
streamItems={shouldUseOptimisticStream ? mergedStreamItems : streamItems}
pendingPermissions={pendingPermissions}
/>
)}
@@ -31,6 +31,7 @@ import { useDaemonConnections } from "@/contexts/daemon-connections-context";
import { useDaemonRegistry } from "@/contexts/daemon-registry-context";
import { formatConnectionStatus } from "@/utils/daemons";
import { useSessionStore } from "@/stores/session-store";
import { useCreateFlowStore } from "@/stores/create-flow-store";
import { MAX_CONTENT_WIDTH } from "@/constants/layout";
import { WelcomeScreen } from "@/components/welcome-screen";
import type { Agent } from "@/contexts/session-context";
@@ -197,6 +198,9 @@ export function DraftAgentScreen({
const [worktreeSlug, setWorktreeSlug] = useState("");
const [selectedWorktreePath, setSelectedWorktreePath] = useState("");
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 = {
messageId: string;
@@ -544,8 +548,7 @@ export function DraftAgentScreen({
selectedServerId ? state.sessions[selectedServerId]?.methods : undefined
);
const promptValue =
machine.tag === "draft" ? machine.promptText : machine.attempt.text;
const promptValue = machine.tag === "draft" ? machine.promptText : "";
const formErrorMessage = machine.tag === "draft" ? machine.errorMessage : "";
const isSubmitting = machine.tag === "creating";
@@ -671,6 +674,13 @@ export function DraftAgentScreen({
text: trimmedPrompt,
timestamp: new Date(),
};
setPendingCreateAttempt({
serverId: selectedServerId,
agentId: null,
messageId: attempt.messageId,
text: attempt.text,
timestamp: attempt.timestamp.getTime(),
});
const modeId =
modeOptions.length > 0 && selectedMode !== "" ? selectedMode : undefined;
const trimmedModel = selectedModel.trim();
@@ -715,10 +725,8 @@ export function DraftAgentScreen({
const agentId = (result as { id?: string })?.id;
if (agentId && selectedServerId) {
router.replace({
pathname: "/agent/[[...route]]",
params: { route: [selectedServerId, agentId] },
});
updatePendingAgentId(agentId);
router.replace(`/agent/${selectedServerId}/${agentId}` as any);
return;
}
@@ -727,11 +735,13 @@ export function DraftAgentScreen({
message: "Failed to create agent",
});
onCreateFlowActiveChange?.(false);
clearPendingCreateAttempt();
throw new Error("Failed to create agent");
} catch (error) {
const message = error instanceof Error ? error.message : "Failed to create agent";
dispatch({ type: "CREATE_FAILED", message });
onCreateFlowActiveChange?.(false);
clearPendingCreateAttempt();
throw error; // Re-throw so AgentInputArea knows it failed
}
},
@@ -753,6 +763,9 @@ export function DraftAgentScreen({
selectedProvider,
selectedServerId,
sessionMethods,
setPendingCreateAttempt,
updatePendingAgentId,
clearPendingCreateAttempt,
workingDir,
isAttachWorktree,
isSubmitting,
@@ -50,22 +50,16 @@ export function LegacyAgentIdScreen({ agentId }: { agentId: string }) {
return;
}
const match = matches[0];
router.replace({
pathname: "/agent/[[...route]]",
params: { route: [match.serverId, match.agent.id] },
});
router.replace(`/agent/${match.serverId}/${match.agent.id}` as any);
}, [isRedirecting, matches, router]);
const handleGoDraft = useCallback(() => {
router.replace({ pathname: "/agent/[[...route]]" });
router.replace("/agent" as any);
}, [router]);
const handleSelectMatch = useCallback(
(match: AgentMatch) => {
router.replace({
pathname: "/agent/[[...route]]",
params: { route: [match.serverId, match.agent.id] },
});
router.replace(`/agent/${match.serverId}/${match.agent.id}` as any);
},
[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 }),
}));