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
@@ -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]
);