feat: add opencode provider and refactor stream model to head/tail architecture

This commit is contained in:
Mohamed Boudra
2026-01-11 16:00:25 +07:00
parent 7fe10f9b4a
commit ebabcc09e5
42 changed files with 4416 additions and 2926 deletions
@@ -308,10 +308,10 @@ function AgentScreenContent({
return children;
}, [allAgents, resolvedAgentId]);
// Select only the specific stream state - use stable empty array to avoid infinite loop
// Select only the specific stream tail - use stable empty array to avoid infinite loop
const streamItemsRaw = useSessionStore((state) =>
resolvedAgentId
? state.sessions[serverId]?.agentStreamState?.get(resolvedAgentId)
? state.sessions[serverId]?.agentStreamTail?.get(resolvedAgentId)
: undefined
);
const streamItems = streamItemsRaw ?? EMPTY_STREAM_ITEMS;
+18 -199
View File
@@ -10,13 +10,14 @@ import {
} from "react-native";
import { useLocalSearchParams, useRouter } from "expo-router";
import { StyleSheet, useUnistyles } from "react-native-unistyles";
import { ChevronRight, Monitor } from "lucide-react-native";
import { Monitor } from "lucide-react-native";
import { MenuHeader } from "@/components/headers/menu-header";
import { AgentInputArea } from "@/components/agent-input-area";
import {
DropdownSheet,
GitOptionsSection,
WorkingDirectoryDropdown,
AgentConfigRow,
} from "@/components/agent-form/agent-form-dropdowns";
import { FileDropZone } from "@/components/file-drop-zone";
import { useDaemonRequest } from "@/hooks/use-daemon-request";
@@ -75,14 +76,6 @@ type DraftAgentParams = {
workingDir?: string;
};
type ConfigRowProps = {
label: string;
value: string;
meta?: string;
onPress: () => void;
disabled?: boolean;
};
export default function HomeScreen() {
const { theme } = useUnistyles();
const router = useRouter();
@@ -160,9 +153,7 @@ export default function HomeScreen() {
? formatConnectionStatus(hostEntry.status)
: undefined;
const [openDropdown, setOpenDropdown] = useState<
"host" | "provider" | "mode" | "model" | "agent" | null
>(null);
const [openDropdown, setOpenDropdown] = useState<"host" | null>(null);
const [errorMessage, setErrorMessage] = useState("");
const [isLoading, setIsLoading] = useState(false);
const [promptText, setPromptText] = useState("");
@@ -178,12 +169,9 @@ export default function HomeScreen() {
const handleAddImagesCallback = useCallback((addImages: (images: ImageAttachment[]) => void) => {
addImagesRef.current = addImages;
}, []);
const openDropdownSheet = useCallback(
(key: "host" | "provider" | "mode" | "model" | "agent") => {
setOpenDropdown(key);
},
[]
);
const openDropdownSheet = useCallback((key: "host") => {
setOpenDropdown(key);
}, []);
const closeDropdown = useCallback(() => {
setOpenDropdown(null);
}, []);
@@ -414,25 +402,6 @@ export default function HomeScreen() {
}
}, [isNonGitDirectory, useWorktree]);
const renderConfigRow = useCallback(
({ label, value, meta, onPress, disabled }: ConfigRowProps) => (
<Pressable
style={[styles.configRow, disabled && styles.configRowDisabled]}
onPress={onPress}
disabled={disabled}
>
<View style={styles.configTextGroup}>
<Text style={styles.configLabel}>{label}</Text>
<Text style={styles.configValue} numberOfLines={1}>
{value}
</Text>
{meta ? <Text style={styles.configMeta}>{meta}</Text> : null}
</View>
<ChevronRight size={18} color={theme.colors.mutedForeground} />
</Pressable>
),
[theme.colors.mutedForeground]
);
const pendingRequestIdRef = useRef<string | null>(null);
const sessionMethods = useSessionStore((state) =>
selectedServerId ? state.sessions[selectedServerId]?.methods : undefined
@@ -581,16 +550,6 @@ export default function HomeScreen() {
};
}, [router, selectedServerId, sessionWs]);
const selectedProviderLabel =
providerDefinitions.find((provider) => provider.id === selectedProvider)?.label ??
selectedProvider;
const selectedModeLabel =
modeOptions.length > 0
? modeOptions.find((mode) => mode.id === selectedMode)?.label ??
modeOptions[0]?.label ??
"Default"
: "Automatic";
return (
<FileDropZone onFilesDropped={handleFilesDropped}>
<View style={styles.container}>
@@ -630,11 +589,18 @@ export default function HomeScreen() {
</Text>
</View>
)}
{renderConfigRow({
label: "Agent",
value: `${selectedProviderLabel} · ${selectedModel || "auto"} · ${selectedModeLabel}`,
onPress: () => openDropdownSheet("agent"),
})}
<AgentConfigRow
providerDefinitions={providerDefinitions}
selectedProvider={selectedProvider}
onSelectProvider={setProviderFromUser}
modeOptions={modeOptions}
selectedMode={selectedMode}
onSelectMode={setModeFromUser}
models={availableModels}
selectedModel={selectedModel}
isModelLoading={isModelLoading}
onSelectModel={setModelFromUser}
/>
{trimmedWorkingDir.length > 0 && !isNonGitDirectory ? (
<GitOptionsSection
useWorktree={useWorktree}
@@ -690,111 +656,6 @@ export default function HomeScreen() {
)}
</DropdownSheet>
<DropdownSheet
title="Agent"
visible={openDropdown === "agent"}
onClose={closeDropdown}
>
<View style={styles.agentSheetSection}>
<Text style={styles.agentSheetSectionLabel}>Provider</Text>
<View style={styles.dropdownSheetList}>
{providerDefinitions.map((definition) => {
const isSelected = definition.id === selectedProvider;
return (
<Pressable
key={definition.id}
style={[
styles.dropdownSheetOption,
isSelected && styles.dropdownSheetOptionSelected,
]}
onPress={() => {
setProviderFromUser(definition.id);
}}
>
<Text style={styles.dropdownSheetOptionLabel}>
{definition.label}
</Text>
{definition.description ? (
<Text style={styles.dropdownSheetOptionDescription}>
{definition.description}
</Text>
) : null}
</Pressable>
);
})}
</View>
</View>
<View style={styles.agentSheetSection}>
<Text style={styles.agentSheetSectionLabel}>Model</Text>
<View style={styles.dropdownSheetList}>
<Pressable
style={[
styles.dropdownSheetOption,
!selectedModel && styles.dropdownSheetOptionSelected,
]}
onPress={() => setModelFromUser("")}
>
<Text style={styles.dropdownSheetOptionLabel}>
Automatic (provider default)
</Text>
</Pressable>
{availableModels.map((model) => {
const isSelected = model.id === selectedModel;
return (
<Pressable
key={model.id}
style={[
styles.dropdownSheetOption,
isSelected && styles.dropdownSheetOptionSelected,
]}
onPress={() => setModelFromUser(model.id)}
>
<Text style={styles.dropdownSheetOptionLabel}>
{model.label}
</Text>
{model.description ? (
<Text style={styles.dropdownSheetOptionDescription}>
{model.description}
</Text>
) : null}
</Pressable>
);
})}
</View>
</View>
{modeOptions.length > 0 ? (
<View style={styles.agentSheetSection}>
<Text style={styles.agentSheetSectionLabel}>Mode</Text>
<View style={styles.dropdownSheetList}>
{modeOptions.map((mode) => {
const isSelected = mode.id === selectedMode;
return (
<Pressable
key={mode.id}
style={[
styles.dropdownSheetOption,
isSelected && styles.dropdownSheetOptionSelected,
]}
onPress={() => setModeFromUser(mode.id)}
>
<Text style={styles.dropdownSheetOptionLabel}>
{mode.label}
</Text>
{mode.description ? (
<Text style={styles.dropdownSheetOptionDescription}>
{mode.description}
</Text>
) : null}
</Pressable>
);
})}
</View>
</View>
) : null}
</DropdownSheet>
{errorMessage ? (
<View style={styles.errorContainer}>
<Text style={styles.errorText}>{errorMessage}</Text>
@@ -855,39 +716,6 @@ const styles = StyleSheet.create((theme) => ({
alignSelf: "center",
width: "100%",
},
configRow: {
flexDirection: "row",
alignItems: "center",
justifyContent: "space-between",
paddingHorizontal: theme.spacing[3],
paddingVertical: theme.spacing[3],
borderRadius: theme.borderRadius.lg,
borderWidth: 1,
borderColor: theme.colors.border,
backgroundColor: theme.colors.card,
},
configRowDisabled: {
opacity: theme.opacity[50],
},
configTextGroup: {
flex: 1,
gap: theme.spacing[1],
marginRight: theme.spacing[2],
},
configLabel: {
fontSize: theme.fontSize.xs,
textTransform: "uppercase",
letterSpacing: 0.6,
color: theme.colors.mutedForeground,
},
configValue: {
fontSize: theme.fontSize.base,
color: theme.colors.foreground,
},
configMeta: {
fontSize: theme.fontSize.xs,
color: theme.colors.mutedForeground,
},
dropdownHelper: {
fontSize: theme.fontSize.sm,
color: theme.colors.mutedForeground,
@@ -963,15 +791,6 @@ const styles = StyleSheet.create((theme) => ({
hostStatusDotOnline: {
backgroundColor: theme.colors.palette.green[500],
},
agentSheetSection: {
marginBottom: theme.spacing[4],
},
agentSheetSectionLabel: {
fontSize: theme.fontSize.sm,
fontWeight: theme.fontWeight.semibold,
color: theme.colors.foreground,
marginBottom: theme.spacing[2],
},
loadingOverlay: {
position: "absolute",
top: 0,
@@ -301,6 +301,308 @@ export function AdaptiveSelect({
);
}
interface ComboSelectOption {
id: string;
label: string;
description?: string;
}
interface ComboSelectProps {
label: string;
title: string;
value: string;
options: ComboSelectOption[];
placeholder?: string;
disabled?: boolean;
allowCustomValue?: boolean;
isLoading?: boolean;
onSelect: (id: string) => void;
}
export function ComboSelect({
label,
title,
value,
options,
placeholder,
disabled,
allowCustomValue = false,
isLoading,
onSelect,
}: ComboSelectProps): ReactElement {
const [isOpen, setIsOpen] = useState(false);
const anchorRef = useRef<View>(null);
const inputRef = useRef<TextInput | null>(null);
const [searchQuery, setSearchQuery] = useState("");
const selectedOption = options.find((opt) => opt.id === value);
const displayValue = selectedOption?.label ?? (value || "");
const handleOpen = useCallback(() => setIsOpen(true), []);
const handleClose = useCallback(() => {
setIsOpen(false);
setSearchQuery("");
}, []);
useEffect(() => {
if (isOpen) {
setSearchQuery("");
inputRef.current?.focus();
}
}, [isOpen]);
const normalizedSearch = searchQuery.trim().toLowerCase();
const filteredOptions = useMemo(() => {
if (!normalizedSearch) {
return options;
}
return options.filter(
(opt) =>
opt.label.toLowerCase().includes(normalizedSearch) ||
opt.id.toLowerCase().includes(normalizedSearch) ||
opt.description?.toLowerCase().includes(normalizedSearch)
);
}, [options, normalizedSearch]);
const hasMatches = filteredOptions.length > 0;
const sanitizedSearchValue = searchQuery.trim();
const showCustomOption =
allowCustomValue &&
sanitizedSearchValue.length > 0 &&
!options.some(
(opt) =>
opt.id.toLowerCase() === sanitizedSearchValue.toLowerCase() ||
opt.label.toLowerCase() === sanitizedSearchValue.toLowerCase()
);
const handleSelect = useCallback(
(id: string) => {
onSelect(id);
handleClose();
},
[handleClose, onSelect]
);
return (
<>
<CompactSelectField
label={label}
value={displayValue}
placeholder={placeholder}
onPress={handleOpen}
disabled={disabled}
isLoading={isLoading}
controlRef={anchorRef}
/>
<AdaptiveSelect
title={title}
visible={isOpen}
onClose={handleClose}
anchorRef={anchorRef}
>
<TextInput
ref={inputRef}
style={styles.dropdownSearchInput}
placeholder={`Search ${label.toLowerCase()}...`}
placeholderTextColor={defaultTheme.colors.mutedForeground}
value={searchQuery}
onChangeText={setSearchQuery}
autoCapitalize="none"
autoCorrect={false}
/>
{showCustomOption ? (
<View style={styles.dropdownSheetList}>
<Pressable
style={styles.dropdownSheetOption}
onPress={() => handleSelect(sanitizedSearchValue)}
>
<Text style={styles.dropdownSheetOptionLabel} numberOfLines={1}>
{`Use "${sanitizedSearchValue}"`}
</Text>
</Pressable>
</View>
) : null}
{hasMatches ? (
<View style={styles.dropdownSheetList}>
{filteredOptions.map((opt) => {
const isSelected = opt.id === value;
return (
<Pressable
key={opt.id}
style={[
styles.dropdownSheetOption,
isSelected && styles.dropdownSheetOptionSelected,
]}
onPress={() => handleSelect(opt.id)}
>
<Text style={styles.dropdownSheetOptionLabel}>{opt.label}</Text>
{opt.description ? (
<Text style={styles.dropdownSheetOptionDescription}>
{opt.description}
</Text>
) : null}
</Pressable>
);
})}
</View>
) : !showCustomOption ? (
<Text style={styles.helperText}>No options match your search.</Text>
) : null}
{isLoading ? (
<View style={styles.dropdownSheetLoading}>
<ActivityIndicator size="small" color={defaultTheme.colors.foreground} />
</View>
) : null}
</AdaptiveSelect>
</>
);
}
interface CompactSelectFieldProps {
label: string;
value: string;
placeholder?: string;
onPress: () => void;
disabled?: boolean;
isLoading?: boolean;
controlRef?: React.RefObject<View | null>;
}
function CompactSelectField({
label,
value,
placeholder,
onPress,
disabled,
isLoading,
controlRef,
}: CompactSelectFieldProps): ReactElement {
return (
<Pressable
ref={controlRef}
onPress={onPress}
disabled={disabled}
style={[styles.compactSelectControl, disabled && styles.compactSelectControlDisabled]}
>
<Text style={styles.compactSelectLabel}>{label}</Text>
{isLoading ? (
<ActivityIndicator size="small" color={defaultTheme.colors.mutedForeground} />
) : (
<Text
style={value ? styles.compactSelectValue : styles.compactSelectPlaceholder}
numberOfLines={1}
>
{value || placeholder || "Select..."}
</Text>
)}
</Pressable>
);
}
interface AgentConfigRowProps {
providerDefinitions: AgentProviderDefinition[];
selectedProvider: AgentProvider;
onSelectProvider: (provider: AgentProvider) => void;
modeOptions: AgentMode[];
selectedMode: string;
onSelectMode: (modeId: string) => void;
models: AgentModelDefinition[];
selectedModel: string;
isModelLoading: boolean;
onSelectModel: (modelId: string) => void;
disabled?: boolean;
}
export function AgentConfigRow({
providerDefinitions,
selectedProvider,
onSelectProvider,
modeOptions,
selectedMode,
onSelectMode,
models,
selectedModel,
isModelLoading,
onSelectModel,
disabled,
}: AgentConfigRowProps): ReactElement {
const providerOptions: ComboSelectOption[] = useMemo(
() =>
providerDefinitions.map((def) => ({
id: def.id,
label: def.label,
description: def.description,
})),
[providerDefinitions]
);
const modeSelectOptions: ComboSelectOption[] = useMemo(() => {
if (modeOptions.length === 0) {
return [{ id: "", label: "Default", description: "Provider default mode" }];
}
return modeOptions.map((mode) => ({
id: mode.id,
label: mode.label,
description: mode.description,
}));
}, [modeOptions]);
const modelSelectOptions: ComboSelectOption[] = useMemo(() => {
const opts: ComboSelectOption[] = [
{ id: "", label: "Auto", description: "Provider default model" },
];
for (const model of models) {
opts.push({
id: model.id,
label: model.label,
description: model.description,
});
}
return opts;
}, [models]);
const effectiveSelectedMode = selectedMode || (modeOptions.length > 0 ? modeOptions[0]?.id : "");
return (
<View style={styles.agentConfigRow}>
<View style={styles.agentConfigColumn}>
<ComboSelect
label="PROVIDER"
title="Select Provider"
value={selectedProvider}
options={providerOptions}
placeholder="Select..."
disabled={disabled}
onSelect={onSelectProvider}
/>
</View>
<View style={styles.agentConfigColumn}>
<ComboSelect
label="MODEL"
title="Select Model"
value={selectedModel}
options={modelSelectOptions}
placeholder="Auto"
disabled={disabled}
isLoading={isModelLoading}
onSelect={onSelectModel}
/>
</View>
<View style={styles.agentConfigColumn}>
<ComboSelect
label="MODE"
title="Select Mode"
value={effectiveSelectedMode}
options={modeSelectOptions}
placeholder="Default"
disabled={disabled || modeOptions.length === 0}
onSelect={onSelectMode}
/>
</View>
</View>
);
}
interface AssistantDropdownProps {
providerDefinitions: AgentProviderDefinition[];
selectedProvider: AgentProvider;
@@ -1184,4 +1486,38 @@ const styles = StyleSheet.create((theme) => ({
desktopDropdownScrollContent: {
padding: theme.spacing[2],
},
agentConfigRow: {
flexDirection: "row",
gap: theme.spacing[2],
},
agentConfigColumn: {
flex: 1,
},
compactSelectControl: {
backgroundColor: theme.colors.background,
borderWidth: theme.borderWidth[1],
borderColor: theme.colors.border,
borderRadius: theme.borderRadius.lg,
paddingVertical: theme.spacing[2],
paddingHorizontal: theme.spacing[3],
gap: theme.spacing[1],
},
compactSelectControlDisabled: {
opacity: theme.opacity[50],
},
compactSelectLabel: {
color: theme.colors.mutedForeground,
fontSize: theme.fontSize.xs,
fontWeight: theme.fontWeight.medium,
textTransform: "uppercase",
letterSpacing: 0.5,
},
compactSelectValue: {
color: theme.colors.foreground,
fontSize: theme.fontSize.sm,
},
compactSelectPlaceholder: {
color: theme.colors.mutedForeground,
fontSize: theme.fontSize.sm,
},
}));
+209 -56
View File
@@ -16,7 +16,17 @@ import Markdown from "react-native-markdown-display";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { StyleSheet, useUnistyles } from "react-native-unistyles";
import { Fonts } from "@/constants/theme";
import Animated, { FadeIn, FadeOut, cancelAnimation, useAnimatedStyle, useSharedValue, withDelay, withRepeat, withSequence, withTiming } from "react-native-reanimated";
import Animated, {
FadeIn,
FadeOut,
cancelAnimation,
useAnimatedStyle,
useSharedValue,
withDelay,
withRepeat,
withSequence,
withTiming,
} from "react-native-reanimated";
import { ChevronDown } from "lucide-react-native";
import { useExplorerSidebarStore } from "@/stores/explorer-sidebar-store";
import {
@@ -72,19 +82,22 @@ export function AgentStreamView({
const isProgrammaticScrollRef = useRef(false);
const isNearBottomRef = useRef(true);
const isUserScrollingRef = useRef(false);
const { open: openExplorer, setActiveTab: setExplorerTab } = useExplorerSidebarStore();
const { open: openExplorer, setActiveTab: setExplorerTab } =
useExplorerSidebarStore();
// Get serverId (fallback to agent's serverId if not provided)
const resolvedServerId = serverId ?? agent.serverId ?? "";
// Get ws for connection status
const ws = useSessionStore((state) => state.sessions[resolvedServerId]?.ws);
const streamingBuffer = useSessionStore((state) =>
state.sessions[resolvedServerId]?.agentStreamingBuffer?.get(agentId)
const streamHead = useSessionStore((state) =>
state.sessions[resolvedServerId]?.agentStreamHead?.get(agentId)
);
// Get methods for file operations
const methods = useSessionStore((state) => state.sessions[resolvedServerId]?.methods);
const methods = useSessionStore(
(state) => state.sessions[resolvedServerId]?.methods
);
const requestDirectoryListing = methods?.requestDirectoryListing;
const requestFilePreview = methods?.requestFilePreview;
@@ -109,8 +122,12 @@ export function AgentStreamView({
// Keep entry/exit animations off on Android due to RN dispatchDraw crashes
// tracked in react-native-reanimated#8422.
const shouldDisableEntryExitAnimations = Platform.OS === "android";
const scrollIndicatorFadeIn = shouldDisableEntryExitAnimations ? undefined : FadeIn.duration(200);
const scrollIndicatorFadeOut = shouldDisableEntryExitAnimations ? undefined : FadeOut.duration(200);
const scrollIndicatorFadeIn = shouldDisableEntryExitAnimations
? undefined
: FadeIn.duration(200);
const scrollIndicatorFadeOut = shouldDisableEntryExitAnimations
? undefined
: FadeOut.duration(200);
useEffect(() => {
hasScrolledInitially.current = false;
@@ -265,7 +282,10 @@ export function AgentStreamView({
break;
case "thought":
content = <AgentThoughtMessage message={item.text} status={item.status} />;
console.log("[AgentStreamView] renderStreamItem", { item });
content = (
<AgentThoughtMessage message={item.text} status={item.status} />
);
break;
case "tool_call": {
@@ -343,9 +363,9 @@ export function AgentStreamView({
const listHeaderComponent = useMemo(() => {
const hasPermissions = pendingPermissionItems.length > 0;
const hasStreaming = !!streamingBuffer;
const hasHeadItems = streamHead && streamHead.length > 0;
if (!hasPermissions && !showWorkingIndicator && !hasStreaming) {
if (!hasPermissions && !showWorkingIndicator && !hasHeadItems) {
return null;
}
@@ -355,7 +375,11 @@ export function AgentStreamView({
{hasPermissions ? (
<View style={stylesheet.permissionsContainer}>
{pendingPermissionItems.map((permission) => (
<PermissionRequestCard key={permission.key} permission={permission} ws={wsOrInert} />
<PermissionRequestCard
key={permission.key}
permission={permission}
ws={wsOrInert}
/>
))}
</View>
) : null}
@@ -366,19 +390,32 @@ export function AgentStreamView({
</View>
) : null}
{hasStreaming ? (
<View style={stylesheet.streamItemWrapper}>
<AssistantMessage
message={streamingBuffer.text}
timestamp={streamingBuffer.timestamp.getTime()}
onInlinePathPress={handleInlinePathPress}
/>
</View>
) : null}
{hasHeadItems
? [...streamHead].reverse().map((item) => {
const rendered = renderStreamItem({
item,
index: 0,
separators: {
highlight: () => {},
unhighlight: () => {},
updateProps: () => {},
},
});
return rendered ? (
<View key={item.id}>{rendered}</View>
) : null;
})
: null}
</View>
</View>
);
}, [pendingPermissionItems, showWorkingIndicator, wsOrInert, streamingBuffer, handleInlinePathPress]);
}, [
pendingPermissionItems,
showWorkingIndicator,
wsOrInert,
streamHead,
renderStreamItem,
]);
const flatListData = useMemo(() => {
return [...streamItems].reverse();
@@ -457,9 +494,7 @@ export function AgentStreamView({
function normalizeInlinePath(
rawPath: string,
cwd?: string
):
| { directory: string; file?: string }
| null {
): { directory: string; file?: string } | null {
if (!rawPath) {
return null;
}
@@ -506,7 +541,10 @@ function normalizePathInput(value: string | undefined): string | null {
return null;
}
const trimmed = value.trim().replace(/^['"`]/, "").replace(/['"`]$/, "");
const trimmed = value
.trim()
.replace(/^['"`]/, "")
.replace(/['"`]$/, "");
if (!trimmed) {
return null;
}
@@ -516,7 +554,11 @@ function normalizePathInput(value: string | undefined): string | null {
function resolvePathAgainstCwd(pathValue: string, cwd?: string): string | null {
const normalizedCwd = normalizePathInput(cwd);
if (!normalizedCwd || !isAbsolutePath(pathValue) || !isAbsolutePath(normalizedCwd)) {
if (
!normalizedCwd ||
!isAbsolutePath(pathValue) ||
!isAbsolutePath(normalizedCwd)
) {
return null;
}
@@ -616,7 +658,9 @@ function PermissionRequestCard({
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;
const inputPreview = request.input
? JSON.stringify(request.input, null, 2)
: null;
const planMarkdown = useMemo(() => {
if (!request) {
@@ -651,10 +695,7 @@ function PermissionRequestCard({
[request]
);
const markdownStyles = useMemo(
() => createMarkdownStyles(theme),
[theme]
);
const markdownStyles = useMemo(() => createMarkdownStyles(theme), [theme]);
const markdownRules = useMemo(() => {
return {
@@ -676,7 +717,11 @@ function PermissionRequestCard({
styles: any,
inheritedStyles: any = {}
) => (
<Text key={node.key} style={[inheritedStyles, styles.textgroup]} selectable>
<Text
key={node.key}
style={[inheritedStyles, styles.textgroup]}
selectable
>
{children}
</Text>
),
@@ -687,7 +732,11 @@ function PermissionRequestCard({
styles: any,
inheritedStyles: any = {}
) => (
<Text key={node.key} style={[inheritedStyles, styles.code_block]} selectable>
<Text
key={node.key}
style={[inheritedStyles, styles.code_block]}
selectable
>
{node.content}
</Text>
),
@@ -709,7 +758,11 @@ function PermissionRequestCard({
styles: any,
inheritedStyles: any = {}
) => (
<Text key={node.key} style={[inheritedStyles, styles.code_inline]} selectable>
<Text
key={node.key}
style={[inheritedStyles, styles.code_inline]}
selectable
>
{node.content}
</Text>
),
@@ -752,7 +805,10 @@ function PermissionRequestCard({
return (
<View key={node.key} style={[styles.list_item, { flexShrink: 0 }]}>
<Text style={iconStyle}>{bullet}</Text>
<Text style={[contentStyle, { flex: 1, flexShrink: 1, minWidth: 0 }]} selectable>
<Text
style={[contentStyle, { flex: 1, flexShrink: 1, minWidth: 0 }]}
selectable
>
{children}
</Text>
</View>
@@ -799,7 +855,10 @@ function PermissionRequestCard({
response,
})
.catch((error) => {
console.error("[PermissionRequestCard] Failed to respond to permission:", error);
console.error(
"[PermissionRequestCard] Failed to respond to permission:",
error
);
});
},
[permission.agentId, permission.request.id, permissionResponse]
@@ -815,19 +874,33 @@ function PermissionRequestCard({
},
]}
>
<Text style={[permissionStyles.title, { color: theme.colors.foreground }]}>
<Text
style={[permissionStyles.title, { color: theme.colors.foreground }]}
>
{title}
</Text>
{description ? (
<Text style={[permissionStyles.description, { color: theme.colors.mutedForeground }]}>
<Text
style={[
permissionStyles.description,
{ color: theme.colors.mutedForeground },
]}
>
{description}
</Text>
) : null}
{planMarkdown ? (
<View style={permissionStyles.section}>
<Text style={[permissionStyles.sectionTitle, { color: theme.colors.mutedForeground }]}>Proposed Plan</Text>
<Text
style={[
permissionStyles.sectionTitle,
{ color: theme.colors.mutedForeground },
]}
>
Proposed Plan
</Text>
<View
style={[
permissionStyles.contentCard,
@@ -837,26 +910,59 @@ function PermissionRequestCard({
},
]}
>
<Markdown style={markdownStyles} rules={markdownRules}>{planMarkdown}</Markdown>
<Markdown style={markdownStyles} rules={markdownRules}>
{planMarkdown}
</Markdown>
</View>
</View>
) : null}
{commandDetails ? (
<View style={permissionStyles.section}>
<Text style={[permissionStyles.sectionTitle, { color: theme.colors.mutedForeground }]}>Command</Text>
<Text
style={[
permissionStyles.sectionTitle,
{ color: theme.colors.mutedForeground },
]}
>
Command
</Text>
{commandDetails.command ? (
<View style={permissionStyles.metadataRow}>
<Text style={[permissionStyles.metadataLabel, { color: theme.colors.mutedForeground }]}>Command</Text>
<Text style={[permissionStyles.metadataValue, { color: theme.colors.foreground }]}>
<Text
style={[
permissionStyles.metadataLabel,
{ color: theme.colors.mutedForeground },
]}
>
Command
</Text>
<Text
style={[
permissionStyles.metadataValue,
{ color: theme.colors.foreground },
]}
>
{commandDetails.command}
</Text>
</View>
) : null}
{commandDetails.cwd ? (
<View style={permissionStyles.metadataRow}>
<Text style={[permissionStyles.metadataLabel, { color: theme.colors.mutedForeground }]}>Directory</Text>
<Text style={[permissionStyles.metadataValue, { color: theme.colors.foreground }]}>
<Text
style={[
permissionStyles.metadataLabel,
{ color: theme.colors.mutedForeground },
]}
>
Directory
</Text>
<Text
style={[
permissionStyles.metadataValue,
{ color: theme.colors.foreground },
]}
>
{commandDetails.cwd}
</Text>
</View>
@@ -866,9 +972,19 @@ function PermissionRequestCard({
{editEntries.length > 0 ? (
<View style={permissionStyles.section}>
<Text style={[permissionStyles.sectionTitle, { color: theme.colors.mutedForeground }]}>Proposed Changes</Text>
<Text
style={[
permissionStyles.sectionTitle,
{ color: theme.colors.mutedForeground },
]}
>
Proposed Changes
</Text>
{editEntries.map((entry, index) => (
<View key={`${entry.filePath ?? "change"}-${index}`} style={permissionStyles.diffSection}>
<View
key={`${entry.filePath ?? "change"}-${index}`}
style={permissionStyles.diffSection}
>
{entry.filePath ? (
<View
style={[
@@ -879,7 +995,12 @@ function PermissionRequestCard({
},
]}
>
<Text style={[permissionStyles.fileBadgeText, { color: theme.colors.foreground }]}>
<Text
style={[
permissionStyles.fileBadgeText,
{ color: theme.colors.foreground },
]}
>
{entry.filePath}
</Text>
</View>
@@ -902,7 +1023,14 @@ function PermissionRequestCard({
{readEntries.length > 0 ? (
<View style={permissionStyles.section}>
<Text style={[permissionStyles.sectionTitle, { color: theme.colors.mutedForeground }]}>File Content</Text>
<Text
style={[
permissionStyles.sectionTitle,
{ color: theme.colors.mutedForeground },
]}
>
File Content
</Text>
{readEntries.map((entry, index) => (
<View
key={`${entry.filePath ?? "content"}-${index}`}
@@ -918,13 +1046,21 @@ function PermissionRequestCard({
<Text
style={[
permissionStyles.metadataLabel,
{ color: theme.colors.mutedForeground, marginBottom: theme.spacing[1] },
{
color: theme.colors.mutedForeground,
marginBottom: theme.spacing[1],
},
]}
>
{entry.filePath}
</Text>
) : null}
<Text style={[permissionStyles.rawContentText, { color: theme.colors.foreground }]}>
<Text
style={[
permissionStyles.rawContentText,
{ color: theme.colors.foreground },
]}
>
{entry.content}
</Text>
</View>
@@ -934,7 +1070,14 @@ function PermissionRequestCard({
{inputPreview ? (
<View style={permissionStyles.section}>
<Text style={[permissionStyles.sectionTitle, { color: theme.colors.mutedForeground }]}>Raw Request</Text>
<Text
style={[
permissionStyles.sectionTitle,
{ color: theme.colors.mutedForeground },
]}
>
Raw Request
</Text>
<View
style={[
permissionStyles.contentCard,
@@ -944,7 +1087,12 @@ function PermissionRequestCard({
},
]}
>
<Text style={[permissionStyles.rawContentText, { color: theme.colors.foreground }]}>
<Text
style={[
permissionStyles.rawContentText,
{ color: theme.colors.foreground },
]}
>
{inputPreview}
</Text>
</View>
@@ -970,7 +1118,10 @@ function PermissionRequestCard({
disabled={isResponding}
>
{isResponding ? (
<ActivityIndicator size="small" color={theme.colors.primaryForeground} />
<ActivityIndicator
size="small"
color={theme.colors.primaryForeground}
/>
) : (
<Text
style={[
@@ -996,7 +1147,10 @@ function PermissionRequestCard({
disabled={isResponding}
>
{isResponding ? (
<ActivityIndicator size="small" color={theme.colors.primaryForeground} />
<ActivityIndicator
size="small"
color={theme.colors.primaryForeground}
/>
) : (
<Text
style={[
@@ -1013,7 +1167,6 @@ function PermissionRequestCard({
);
}
const stylesheet = StyleSheet.create((theme) => ({
container: {
flex: 1,
File diff suppressed because it is too large Load Diff
+52 -34
View File
@@ -4,9 +4,10 @@ import {
Text,
ActivityIndicator,
Pressable,
RefreshControl,
FlatList,
type NativeSyntheticEvent,
type NativeScrollEvent,
type ListRenderItem,
} from "react-native";
import { ScrollView, type ScrollView as ScrollViewType } from "react-native-gesture-handler";
import { StyleSheet, useUnistyles } from "react-native-unistyles";
@@ -258,6 +259,18 @@ export function GitDiffPane({ serverId, agentId }: GitDiffPaneProps) {
state.sessions[serverId]?.agents?.has(agentId) ?? false
);
const renderFileSection: ListRenderItem<ParsedDiffFile> = useCallback(
({ item, index }) => (
<DiffFileSection file={item} testID={`diff-file-${index}`} />
),
[]
);
const keyExtractor = useCallback(
(item: ParsedDiffFile, index: number) => `${item.path}-${index}`,
[]
);
if (!agentExists) {
return (
<View style={styles.errorContainer}>
@@ -269,40 +282,45 @@ export function GitDiffPane({ serverId, agentId }: GitDiffPaneProps) {
const hasChanges = files.length > 0;
const errorMessage = isError && error instanceof Error ? error.message : null;
return (
<ScrollView
style={styles.scrollView}
testID="git-diff-scroll"
refreshControl={
<RefreshControl
refreshing={isManualRefresh && isFetching}
onRefresh={handleRefresh}
tintColor={theme.colors.mutedForeground}
colors={[theme.colors.primary]}
/>
}
>
<View style={styles.contentContainer} testID="git-diff-content">
{isLoading ? (
<View style={styles.loadingContainer}>
<ActivityIndicator size="large" />
<Text style={styles.loadingText}>Loading changes...</Text>
</View>
) : isError ? (
<View style={styles.errorContainer}>
<Text style={styles.errorText}>{errorMessage ?? "Failed to load changes"}</Text>
</View>
) : !hasChanges ? (
<View style={styles.emptyContainer}>
<Text style={styles.emptyText}>No changes</Text>
</View>
) : (
files.map((file, fileIndex) => (
<DiffFileSection key={fileIndex} file={file} testID={`diff-file-${fileIndex}`} />
))
)}
if (isLoading) {
return (
<View style={styles.loadingContainer}>
<ActivityIndicator size="large" />
<Text style={styles.loadingText}>Loading changes...</Text>
</View>
</ScrollView>
);
}
if (isError) {
return (
<View style={styles.errorContainer}>
<Text style={styles.errorText}>{errorMessage ?? "Failed to load changes"}</Text>
</View>
);
}
if (!hasChanges) {
return (
<View style={styles.emptyContainer}>
<Text style={styles.emptyText}>No changes</Text>
</View>
);
}
return (
<FlatList
data={files}
renderItem={renderFileSection}
keyExtractor={keyExtractor}
style={styles.scrollView}
contentContainerStyle={styles.contentContainer}
testID="git-diff-scroll"
onRefresh={handleRefresh}
refreshing={isManualRefresh && isFetching}
initialNumToRender={3}
maxToRenderPerBatch={3}
windowSize={5}
/>
);
}
+125 -40
View File
@@ -22,16 +22,26 @@ import {
Search,
Brain,
} from "lucide-react-native";
import { StyleSheet, useUnistyles, UnistylesRuntime } from "react-native-unistyles";
import {
StyleSheet,
useUnistyles,
UnistylesRuntime,
} from "react-native-unistyles";
import { baseColors, theme } from "@/styles/theme";
import { createMarkdownStyles, createCompactMarkdownStyles } from "@/styles/markdown-styles";
import {
createMarkdownStyles,
createCompactMarkdownStyles,
} from "@/styles/markdown-styles";
import { Colors, Fonts } from "@/constants/theme";
import * as Clipboard from "expo-clipboard";
import type { TodoEntry, ThoughtStatus } from "@/types/stream";
import { extractPrincipalParam } from "@/utils/tool-call-parsers";
import { resolveToolCallPreview } from "./tool-call-preview";
import { useToolCallSheet } from "./tool-call-sheet";
import { ToolCallDetailsContent, useToolCallDetails } from "./tool-call-details";
import {
ToolCallDetailsContent,
useToolCallDetails,
} from "./tool-call-details";
interface UserMessageProps {
message: string;
@@ -259,13 +269,17 @@ function isLikelyPathToken(value: string): boolean {
return false;
}
const looksLikeDir = value.endsWith("/") || value.startsWith("./") || value.startsWith("../");
const looksLikeDir =
value.endsWith("/") || value.startsWith("./") || value.startsWith("../");
return hasExtension || looksLikeDir || value.includes("/");
}
function normalizeInlinePathValue(value: string): string | null {
const trimmed = value.trim().replace(/^['"`]/, "").replace(/['"`]$/, "");
const trimmed = value
.trim()
.replace(/^['"`]/, "")
.replace(/['"`]$/, "");
if (!trimmed) {
return null;
}
@@ -290,7 +304,9 @@ function parseInlinePathToken(
return null;
}
const lineStart = parseInt(rangeOnlyMatch[1], 10);
const lineEnd = rangeOnlyMatch[2] ? parseInt(rangeOnlyMatch[2], 10) : undefined;
const lineEnd = rangeOnlyMatch[2]
? parseInt(rangeOnlyMatch[2], 10)
: undefined;
return {
raw: rawValue,
path: basePath,
@@ -335,10 +351,7 @@ export const AssistantMessage = memo(function AssistantMessage({
const { theme } = useUnistyles();
const lastPathRef = useRef<string | null>(null);
const markdownStyles = useMemo(
() => createMarkdownStyles(theme),
[theme]
);
const markdownStyles = useMemo(() => createMarkdownStyles(theme), [theme]);
const markdownRules = useMemo(() => {
return {
@@ -360,7 +373,11 @@ export const AssistantMessage = memo(function AssistantMessage({
styles: any,
inheritedStyles: any = {}
) => (
<Text key={node.key} style={[inheritedStyles, styles.textgroup]} selectable>
<Text
key={node.key}
style={[inheritedStyles, styles.textgroup]}
selectable
>
{children}
</Text>
),
@@ -371,7 +388,11 @@ export const AssistantMessage = memo(function AssistantMessage({
styles: any,
inheritedStyles: any = {}
) => (
<Text key={node.key} style={[inheritedStyles, styles.code_block]} selectable>
<Text
key={node.key}
style={[inheritedStyles, styles.code_block]}
selectable
>
{node.content}
</Text>
),
@@ -402,7 +423,10 @@ export const AssistantMessage = memo(function AssistantMessage({
return (
<Text
key={node.key}
style={[inheritedStyles, assistantMessageStylesheet.markdownCodeInline]}
style={[
inheritedStyles,
assistantMessageStylesheet.markdownCodeInline,
]}
selectable
>
{content}
@@ -415,7 +439,10 @@ export const AssistantMessage = memo(function AssistantMessage({
key={node.key}
onPress={() => parsed && onInlinePathPress?.(parsed)}
selectable={false}
style={[assistantMessageStylesheet.pathChip, assistantMessageStylesheet.pathChipText]}
style={[
assistantMessageStylesheet.pathChip,
assistantMessageStylesheet.pathChipText,
]}
>
{content}
</Text>
@@ -460,7 +487,9 @@ export const AssistantMessage = memo(function AssistantMessage({
return (
<View key={node.key} style={styles.list_item}>
<Text style={iconStyle}>{bullet}</Text>
<View style={[contentStyle, { flex: 1, flexShrink: 1, minWidth: 0 }]}>
<View
style={[contentStyle, { flex: 1, flexShrink: 1, minWidth: 0 }]}
>
{children}
</View>
</View>
@@ -781,7 +810,10 @@ export const TodoListCard = memo(function TodoListCard({
[items]
);
const timestampLabel = useMemo(() => formatPlanTimestamp(timestamp), [timestamp]);
const timestampLabel = useMemo(
() => formatPlanTimestamp(timestamp),
[timestamp]
);
const iconColor = theme.colors.background;
@@ -791,10 +823,14 @@ export const TodoListCard = memo(function TodoListCard({
<View style={todoListCardStylesheet.header}>
<View style={todoListCardStylesheet.headerMeta}>
<Text style={todoListCardStylesheet.title}>Plan</Text>
<Text style={todoListCardStylesheet.timestamp}>{timestampLabel}</Text>
<Text style={todoListCardStylesheet.timestamp}>
{timestampLabel}
</Text>
</View>
<View style={todoListCardStylesheet.providerBadge}>
<Text style={todoListCardStylesheet.providerText}>{providerLabel}</Text>
<Text style={todoListCardStylesheet.providerText}>
{providerLabel}
</Text>
</View>
</View>
<Text style={todoListCardStylesheet.progressText}>
@@ -809,7 +845,10 @@ export const TodoListCard = memo(function TodoListCard({
</Text>
) : (
items.map((item, idx) => (
<View key={`${item.text}-${idx}`} style={todoListCardStylesheet.itemRow}>
<View
key={`${item.text}-${idx}`}
style={todoListCardStylesheet.itemRow}
>
<View
style={[
todoListCardStylesheet.checkbox,
@@ -889,10 +928,14 @@ const ExpandableBadge = memo(function ExpandableBadge({
};
}, [isLoading, spinAnim]);
const spin = spinAnim.interpolate({
inputRange: [0, 1],
outputRange: ["0deg", "360deg"],
});
const spin = useMemo(
() =>
spinAnim.interpolate({
inputRange: [0, 1],
outputRange: ["0deg", "360deg"],
}),
[spinAnim]
);
const IconComponent = icon;
const iconColor = isError
@@ -921,7 +964,9 @@ const ExpandableBadge = memo(function ExpandableBadge({
accessibilityState={hasDetails ? { expanded: isExpanded } : undefined}
style={({ pressed }) => [
expandableBadgeStylesheet.pressable,
pressed && hasDetails ? expandableBadgeStylesheet.pressablePressed : null,
pressed && hasDetails
? expandableBadgeStylesheet.pressablePressed
: null,
]}
>
<View style={expandableBadgeStylesheet.headerRow}>
@@ -930,7 +975,10 @@ const ExpandableBadge = memo(function ExpandableBadge({
{label}
</Text>
{secondaryLabel ? (
<Text style={expandableBadgeStylesheet.secondaryLabel} numberOfLines={1}>
<Text
style={expandableBadgeStylesheet.secondaryLabel}
numberOfLines={1}
>
{secondaryLabel}
</Text>
) : (
@@ -948,7 +996,9 @@ const ExpandableBadge = memo(function ExpandableBadge({
) : null}
</View>
{detailContent ? (
<View style={expandableBadgeStylesheet.detailWrapper}>{detailContent}</View>
<View style={expandableBadgeStylesheet.detailWrapper}>
{detailContent}
</View>
) : null}
</Pressable>
</View>
@@ -963,7 +1013,10 @@ const agentThoughtStylesheet = StyleSheet.create((theme) => ({
},
}));
export const AgentThoughtMessage = memo(function AgentThoughtMessage({ message, status = "ready" }: AgentThoughtMessageProps) {
export const AgentThoughtMessage = memo(function AgentThoughtMessage({
message,
status = "ready",
}: AgentThoughtMessageProps) {
const { theme } = useUnistyles();
const [isExpanded, setIsExpanded] = useState(false);
const markdownContent = useMemo(() => message?.trim() ?? "", [message]);
@@ -996,7 +1049,11 @@ export const AgentThoughtMessage = memo(function AgentThoughtMessage({ message,
styles: any,
inheritedStyles: any = {}
) => (
<Text key={node.key} style={[inheritedStyles, styles.textgroup]} selectable>
<Text
key={node.key}
style={[inheritedStyles, styles.textgroup]}
selectable
>
{children}
</Text>
),
@@ -1007,7 +1064,11 @@ export const AgentThoughtMessage = memo(function AgentThoughtMessage({ message,
styles: any,
inheritedStyles: any = {}
) => (
<Text key={node.key} style={[inheritedStyles, styles.code_block]} selectable>
<Text
key={node.key}
style={[inheritedStyles, styles.code_block]}
selectable
>
{node.content}
</Text>
),
@@ -1029,7 +1090,11 @@ export const AgentThoughtMessage = memo(function AgentThoughtMessage({ message,
styles: any,
inheritedStyles: any = {}
) => (
<Text key={node.key} style={[inheritedStyles, styles.code_inline]} selectable>
<Text
key={node.key}
style={[inheritedStyles, styles.code_inline]}
selectable
>
{node.content}
</Text>
),
@@ -1072,7 +1137,9 @@ export const AgentThoughtMessage = memo(function AgentThoughtMessage({ message,
return (
<View key={node.key} style={styles.list_item}>
<Text style={iconStyle}>{bullet}</Text>
<View style={[contentStyle, { flex: 1, flexShrink: 1, minWidth: 0 }]}>
<View
style={[contentStyle, { flex: 1, flexShrink: 1, minWidth: 0 }]}
>
{children}
</View>
</View>
@@ -1083,7 +1150,11 @@ export const AgentThoughtMessage = memo(function AgentThoughtMessage({ message,
const renderDetails = useCallback(() => {
if (!markdownContent) {
return <Text style={agentThoughtStylesheet.emptyText}>No captured thinking</Text>;
return (
<Text style={agentThoughtStylesheet.emptyText}>
No captured thinking
</Text>
);
}
return (
<Markdown style={markdownStyles} rules={markdownRules}>
@@ -1124,14 +1195,16 @@ const toolKindIcons: Record<string, any> = {
// Derive tool kind from tool name for icon selection
function getToolKindFromName(toolName: string): string {
const lower = toolName.toLowerCase();
if (lower === "read" || lower === "read_file" || lower.startsWith("read")) return "read";
if (lower === "edit" || lower === "write" || lower === "apply_patch") return "edit";
if (lower === "read" || lower === "read_file" || lower.startsWith("read"))
return "read";
if (lower === "edit" || lower === "write" || lower === "apply_patch")
return "edit";
if (lower === "bash" || lower === "shell") return "execute";
if (lower === "grep" || lower === "glob" || lower === "web_search") return "search";
if (lower === "grep" || lower === "glob" || lower === "web_search")
return "search";
return "tool";
}
export const ToolCall = memo(function ToolCall({
toolName,
args,
@@ -1145,7 +1218,8 @@ export const ToolCall = memo(function ToolCall({
// Check if we're on mobile (use bottom sheet) or desktop (inline expand)
const isMobile =
UnistylesRuntime.breakpoint === "xs" || UnistylesRuntime.breakpoint === "sm";
UnistylesRuntime.breakpoint === "xs" ||
UnistylesRuntime.breakpoint === "sm";
const kind = getToolKindFromName(toolName);
const IconComponent = toolKindIcons[kind] || Wrench;
@@ -1157,7 +1231,8 @@ export const ToolCall = memo(function ToolCall({
);
// Check if there's any content to display
const hasDetails = args !== undefined || result !== undefined || error !== undefined;
const hasDetails =
args !== undefined || result !== undefined || error !== undefined;
// Parse tool call details for inline rendering
const { display, errorText } = useToolCallDetails({ args, result, error });
@@ -1184,7 +1259,11 @@ export const ToolCall = memo(function ToolCall({
if (isMobile) return null;
return (
<View style={toolCallInlineStyles.detailsContainer}>
<ToolCallDetailsContent display={display} errorText={errorText} maxHeight={400} />
<ToolCallDetailsContent
display={display}
errorText={errorText}
maxHeight={400}
/>
</View>
);
}, [isMobile, display, errorText]);
@@ -1196,7 +1275,13 @@ export const ToolCall = memo(function ToolCall({
icon={IconComponent}
isExpanded={!isMobile && isExpanded}
onToggle={hasDetails ? handleToggle : undefined}
renderDetails={hasDetails && !isMobile ? renderDetails : (hasDetails ? () => null : undefined)}
renderDetails={
hasDetails && !isMobile
? renderDetails
: hasDetails
? () => null
: undefined
}
isLoading={status === "executing"}
isError={status === "failed"}
/>
File diff suppressed because it is too large Load Diff
@@ -131,6 +131,8 @@ export function useAgentFormState(
setSelectedProvider(provider);
userEditedPreferencesRef.current.model = true;
setSelectedModel("");
userEditedPreferencesRef.current.mode = true;
setSelectedMode("");
}, []);
const setModeFromUser = useCallback((modeId: string) => {
+26 -33
View File
@@ -212,9 +212,9 @@ export interface SessionState {
messages: MessageEntry[];
currentAssistantMessage: string;
// Stream state
agentStreamState: Map<string, StreamItem[]>;
agentStreamingBuffer: Map<string, { id: string; text: string; timestamp: Date }>;
// Stream state (head/tail model)
agentStreamTail: Map<string, StreamItem[]>;
agentStreamHead: Map<string, StreamItem[]>;
// Initializing agents
initializingAgents: Map<string, boolean>;
@@ -270,17 +270,10 @@ interface SessionStoreActions {
setMessages: (serverId: string, messages: MessageEntry[] | ((prev: MessageEntry[]) => MessageEntry[])) => void;
setCurrentAssistantMessage: (serverId: string, message: string | ((prev: string) => string)) => void;
// Stream state
setAgentStreamState: (serverId: string, state: Map<string, StreamItem[]> | ((prev: Map<string, StreamItem[]>) => Map<string, StreamItem[]>)) => void;
setAgentStreamingBuffer: (
serverId: string,
state:
| Map<string, { id: string; text: string; timestamp: Date }>
| ((
prev: Map<string, { id: string; text: string; timestamp: Date }>
) => Map<string, { id: string; text: string; timestamp: Date }>)
) => void;
clearAgentStreamingBuffer: (serverId: string, agentId: string) => void;
// Stream state (head/tail model)
setAgentStreamTail: (serverId: string, state: Map<string, StreamItem[]> | ((prev: Map<string, StreamItem[]>) => Map<string, StreamItem[]>)) => void;
setAgentStreamHead: (serverId: string, state: Map<string, StreamItem[]> | ((prev: Map<string, StreamItem[]>) => Map<string, StreamItem[]>)) => void;
clearAgentStreamHead: (serverId: string, agentId: string) => void;
// Initializing agents
setInitializingAgents: (serverId: string, state: Map<string, boolean> | ((prev: Map<string, boolean>) => Map<string, boolean>)) => void;
@@ -362,8 +355,8 @@ function createInitialSessionState(serverId: string, ws: UseWebSocketReturn, aud
focusedAgentId: null,
messages: [],
currentAssistantMessage: "",
agentStreamState: new Map(),
agentStreamingBuffer: new Map(),
agentStreamTail: new Map(),
agentStreamHead: new Map(),
initializingAgents: new Map(),
agents: new Map(),
pendingPermissions: new Map(),
@@ -524,66 +517,66 @@ export const useSessionStore = create<SessionStore>()(
});
},
// Stream state
setAgentStreamState: (serverId, state) => {
// Stream state (head/tail model)
setAgentStreamTail: (serverId, state) => {
set((prev) => {
const session = prev.sessions[serverId];
if (!session) {
return prev;
}
const nextState = typeof state === "function" ? state(session.agentStreamState) : state;
if (session.agentStreamState === nextState) {
const nextState = typeof state === "function" ? state(session.agentStreamTail) : state;
if (session.agentStreamTail === nextState) {
return prev;
}
logSessionStoreUpdate("setAgentStreamState", serverId, { agentCount: nextState.size });
logSessionStoreUpdate("setAgentStreamTail", serverId, { agentCount: nextState.size });
return {
...prev,
sessions: {
...prev.sessions,
[serverId]: { ...session, agentStreamState: nextState },
[serverId]: { ...session, agentStreamTail: nextState },
},
};
});
},
setAgentStreamingBuffer: (serverId, state) => {
setAgentStreamHead: (serverId, state) => {
set((prev) => {
const session = prev.sessions[serverId];
if (!session) {
return prev;
}
const nextState = typeof state === "function" ? state(session.agentStreamingBuffer) : state;
if (session.agentStreamingBuffer === nextState) {
const nextState = typeof state === "function" ? state(session.agentStreamHead) : state;
if (session.agentStreamHead === nextState) {
return prev;
}
logSessionStoreUpdate("setAgentStreamingBuffer", serverId, { agentCount: nextState.size });
logSessionStoreUpdate("setAgentStreamHead", serverId, { agentCount: nextState.size });
return {
...prev,
sessions: {
...prev.sessions,
[serverId]: { ...session, agentStreamingBuffer: nextState },
[serverId]: { ...session, agentStreamHead: nextState },
},
};
});
},
clearAgentStreamingBuffer: (serverId, agentId) => {
clearAgentStreamHead: (serverId, agentId) => {
set((prev) => {
const session = prev.sessions[serverId];
if (!session) {
return prev;
}
if (!session.agentStreamingBuffer.has(agentId)) {
if (!session.agentStreamHead.has(agentId)) {
return prev;
}
const nextBuffer = new Map(session.agentStreamingBuffer);
nextBuffer.delete(agentId);
logSessionStoreUpdate("clearAgentStreamingBuffer", serverId, { agentId });
const nextHead = new Map(session.agentStreamHead);
nextHead.delete(agentId);
logSessionStoreUpdate("clearAgentStreamHead", serverId, { agentId });
return {
...prev,
sessions: {
...prev.sessions,
[serverId]: { ...session, agentStreamingBuffer: nextBuffer },
[serverId]: { ...session, agentStreamHead: nextHead },
},
};
});
+112 -2
View File
@@ -1,7 +1,11 @@
import { describe, expect, it } from "vitest";
import type { AgentStreamEventPayload } from "@server/server/messages";
import type { StreamItem } from "@/types/stream";
import { applyStreamEventWithBuffer, type StreamingBufferEntry } from "@/types/stream";
import type { StreamItem, ThoughtItem } from "@/types/stream";
import {
applyStreamEvent,
applyStreamEventWithBuffer,
type StreamingBufferEntry,
} from "@/types/stream";
const baseTimestamp = new Date(0);
@@ -40,6 +44,15 @@ const permissionEvent = (): AgentStreamEventPayload => ({
},
});
const reasoningChunk = (text: string): AgentStreamEventPayload => ({
type: "timeline",
provider: "claude",
item: {
type: "reasoning",
text,
},
});
describe("applyStreamEventWithBuffer", () => {
it("buffers assistant chunks without changing stream", () => {
const stream: StreamItem[] = [];
@@ -154,3 +167,100 @@ describe("applyStreamEventWithBuffer", () => {
expect(result.buffer).toBe(null);
});
});
describe("applyStreamEvent (head/tail model)", () => {
it("buffers reasoning chunks in head", () => {
const result = applyStreamEvent({
tail: [],
head: [],
event: reasoningChunk("Let me think..."),
timestamp: baseTimestamp,
});
expect(result.tail).toHaveLength(0);
expect(result.head).toHaveLength(1);
expect(result.head[0].kind).toBe("thought");
expect((result.head[0] as ThoughtItem).text).toBe("Let me think...");
expect((result.head[0] as ThoughtItem).status).toBe("loading");
});
it("accumulates reasoning chunks in head", () => {
let result = applyStreamEvent({
tail: [],
head: [],
event: reasoningChunk("Let me "),
timestamp: baseTimestamp,
});
result = applyStreamEvent({
tail: result.tail,
head: result.head,
event: reasoningChunk("think..."),
timestamp: baseTimestamp,
});
expect(result.tail).toHaveLength(0);
expect(result.head).toHaveLength(1);
expect((result.head[0] as ThoughtItem).text).toBe("Let me think...");
});
it("flushes reasoning to tail when tool call arrives", () => {
let result = applyStreamEvent({
tail: [],
head: [],
event: reasoningChunk("Thinking..."),
timestamp: baseTimestamp,
});
result = applyStreamEvent({
tail: result.tail,
head: result.head,
event: toolCallEvent(),
timestamp: baseTimestamp,
});
expect(result.head).toHaveLength(0);
expect(result.tail).toHaveLength(2);
expect(result.tail[0].kind).toBe("thought");
expect((result.tail[0] as ThoughtItem).status).toBe("ready");
expect(result.tail[1].kind).toBe("tool_call");
});
it("flushes head on turn completion", () => {
let result = applyStreamEvent({
tail: [],
head: [],
event: assistantChunk("Hello"),
timestamp: baseTimestamp,
});
result = applyStreamEvent({
tail: result.tail,
head: result.head,
event: completionEvent(),
timestamp: baseTimestamp,
});
expect(result.head).toHaveLength(0);
expect(result.tail).toHaveLength(1);
expect(result.tail[0].kind).toBe("assistant_message");
});
it("flushes reasoning when assistant message starts", () => {
let result = applyStreamEvent({
tail: [],
head: [],
event: reasoningChunk("Thinking..."),
timestamp: baseTimestamp,
});
result = applyStreamEvent({
tail: result.tail,
head: result.head,
event: assistantChunk("Here's my answer"),
timestamp: baseTimestamp,
});
expect(result.tail).toHaveLength(1);
expect(result.tail[0].kind).toBe("thought");
expect((result.tail[0] as ThoughtItem).status).toBe("ready");
expect(result.head).toHaveLength(1);
expect(result.head[0].kind).toBe("assistant_message");
});
});
+277 -105
View File
@@ -29,7 +29,11 @@ export function generateMessageId(): string {
return `msg_${Date.now()}_${Math.random().toString(36).substring(2, 11)}`;
}
function createTimelineId(prefix: string, text: string, timestamp: Date): string {
function createTimelineId(
prefix: string,
text: string,
timestamp: Date
): string {
return `${prefix}_${timestamp.getTime()}_${simpleHash(text)}`;
}
@@ -132,7 +136,9 @@ export type AgentToolCallItem = ToolCallItem & {
payload: { source: "agent"; data: AgentToolCallData };
};
export function isAgentToolCallItem(item: StreamItem): item is AgentToolCallItem {
export function isAgentToolCallItem(
item: StreamItem
): item is AgentToolCallItem {
return item.kind === "tool_call" && item.payload.source === "agent";
}
@@ -210,7 +216,11 @@ function appendUserMessage(
return [...state, nextItem];
}
function appendAssistantMessage(state: StreamItem[], text: string, timestamp: Date): StreamItem[] {
function appendAssistantMessage(
state: StreamItem[],
text: string,
timestamp: Date
): StreamItem[] {
const { chunk, hasContent } = normalizeChunk(text);
if (!chunk) {
return state;
@@ -240,7 +250,11 @@ function appendAssistantMessage(state: StreamItem[], text: string, timestamp: Da
return [...state, item];
}
function appendThought(state: StreamItem[], text: string, timestamp: Date): StreamItem[] {
function appendThought(
state: StreamItem[],
text: string,
timestamp: Date
): StreamItem[] {
const { chunk, hasContent } = normalizeChunk(text);
if (!chunk) {
return state;
@@ -298,9 +312,7 @@ function mergeToolCallRaw(existingRaw: unknown, nextRaw: unknown): unknown {
return [existingRaw, nextRaw];
}
function computeParsedToolPayload(
result: unknown
): {
function computeParsedToolPayload(result: unknown): {
parsedEdits?: EditEntry[];
parsedReads?: ReadEntry[];
parsedCommand?: CommandDetails | null;
@@ -335,14 +347,16 @@ function findExistingAgentToolCallIndex(
(entry) =>
entry.kind === "tool_call" &&
entry.payload.source === "agent" &&
normalizeComparableString(entry.payload.data.callId) === normalizedCallId
normalizeComparableString(entry.payload.data.callId) ===
normalizedCallId
);
if (existingIndex >= 0) {
return existingIndex;
}
}
const fallbackCandidates: Array<{ index: number; item: AgentToolCallItem }> = [];
const fallbackCandidates: Array<{ index: number; item: AgentToolCallItem }> =
[];
const metadataMatches: Array<{ index: number; item: AgentToolCallItem }> = [];
for (let i = 0; i < state.length; i += 1) {
const entry = state[i];
@@ -351,8 +365,7 @@ function findExistingAgentToolCallIndex(
}
const payload = entry.payload.data;
const providerMatches =
payload.provider === data.provider &&
payload.name === data.name;
payload.provider === data.provider && payload.name === data.name;
if (providerMatches) {
metadataMatches.push({ index: i, item: entry as AgentToolCallItem });
}
@@ -397,7 +410,11 @@ function appendAgentToolCall(
callId: callId ?? data.callId,
};
const existingIndex = findExistingAgentToolCallIndex(state, callId ?? null, payloadData);
const existingIndex = findExistingAgentToolCallIndex(
state,
callId ?? null,
payloadData
);
if (existingIndex >= 0) {
const next = [...state];
@@ -429,7 +446,8 @@ function appendAgentToolCall(
callId: payloadData.callId ?? existing.payload.data.callId,
parsedEdits: parsed.parsedEdits ?? existing.payload.data.parsedEdits,
parsedReads: parsed.parsedReads ?? existing.payload.data.parsedReads,
parsedCommand: parsed.parsedCommand ?? existing.payload.data.parsedCommand,
parsedCommand:
parsed.parsedCommand ?? existing.payload.data.parsedCommand,
},
},
};
@@ -469,7 +487,8 @@ function isPermissionToolCall(raw: unknown): boolean {
return candidate.name === "permission_request";
}
const FAILED_STATUS_PATTERN = /fail|error|deny|reject|cancel|abort|exception|refus/;
const FAILED_STATUS_PATTERN =
/fail|error|deny|reject|cancel|abort|exception|refus/;
const COMPLETED_STATUS_PATTERN =
/complete|success|granted|applied|done|resolved|finish|succeed|ok/;
@@ -552,8 +571,8 @@ function inferStatusFromRaw(raw: unknown): "completed" | "failed" | null {
typeof record.exitCode === "number"
? record.exitCode
: typeof record.exit_code === "number"
? record.exit_code
: null;
? record.exit_code
: null;
if (exitCode !== null) {
return exitCode === 0 ? "completed" : "failed";
}
@@ -657,7 +676,10 @@ function extractToolCallId(raw: unknown, depth = 0): string | null {
return null;
}
function appendActivityLog(state: StreamItem[], entry: ActivityLogItem): StreamItem[] {
function appendActivityLog(
state: StreamItem[],
entry: ActivityLogItem
): StreamItem[] {
const index = state.findIndex((existing) => existing.id === entry.id);
if (index >= 0) {
const next = [...state];
@@ -679,7 +701,11 @@ function appendTodoList(
}));
const lastItem = state[state.length - 1];
if (lastItem && lastItem.kind === "todo_list" && lastItem.provider === provider) {
if (
lastItem &&
lastItem.kind === "todo_list" &&
lastItem.provider === provider
) {
const next = [...state];
const updated: TodoListItem = {
...lastItem,
@@ -722,7 +748,12 @@ export function reduceStreamUpdate(
let nextState = state;
switch (item.type) {
case "user_message":
nextState = appendUserMessage(state, item.text, timestamp, item.messageId);
nextState = appendUserMessage(
state,
item.text,
timestamp,
item.messageId
);
break;
case "assistant_message":
nextState = appendAssistantMessage(state, item.text, timestamp);
@@ -790,18 +821,30 @@ export function reduceStreamUpdate(
export function hydrateStreamState(
events: Array<{ event: AgentStreamEventPayload; timestamp: Date }>
): StreamItem[] {
const hydrated = events.reduce<StreamItem[]>((state, { event, timestamp }) => {
return reduceStreamUpdate(state, event, timestamp);
}, []);
const hydrated = events.reduce<StreamItem[]>(
(state, { event, timestamp }) => {
return reduceStreamUpdate(state, event, timestamp);
},
[]
);
return finalizeActiveThoughts(hydrated);
}
export type StreamingBufferEntry = {
id: string;
text: string;
timestamp: Date;
};
/**
* Streamable item kinds - items that can be incrementally streamed
* and should be buffered in the head before committing to tail.
*/
type StreamableKind = "assistant_message" | "thought";
const STREAMABLE_KINDS = new Set<StreamItem["kind"]>([
"assistant_message",
"thought",
]);
function isStreamableKind(kind: StreamItem["kind"]): kind is StreamableKind {
return STREAMABLE_KINDS.has(kind);
}
const STREAM_COMPLETION_EVENTS = new Set<AgentStreamEventPayload["type"]>([
"turn_completed",
@@ -809,24 +852,190 @@ const STREAM_COMPLETION_EVENTS = new Set<AgentStreamEventPayload["type"]>([
"turn_canceled",
]);
function appendCompletedAssistantMessage(
state: StreamItem[],
buffer: StreamingBufferEntry
/**
* Determine what kind of StreamItem an event would produce
*/
function getEventItemKind(
event: AgentStreamEventPayload
): StreamItem["kind"] | null {
if (event.type !== "timeline") {
return null;
}
switch (event.item.type) {
case "user_message":
return "user_message";
case "assistant_message":
return "assistant_message";
case "reasoning":
return "thought";
case "tool_call":
return "tool_call";
case "todo":
return "todo_list";
case "error":
return "activity_log";
default:
return null;
}
}
/**
* Finalize head items before flushing to tail.
* Marks thoughts as "ready" since they're no longer being streamed.
*/
function finalizeHeadItems(head: StreamItem[]): StreamItem[] {
return head.map((item) => {
if (item.kind === "thought" && item.status !== "ready") {
return { ...item, status: "ready" as ThoughtStatus };
}
return item;
});
}
/**
* Flush head items to tail, avoiding duplicates.
*/
function flushHeadToTail(
tail: StreamItem[],
head: StreamItem[]
): StreamItem[] {
if (state.some((item) => item.id === buffer.id)) {
return state;
if (head.length === 0) {
return tail;
}
const entry: AssistantMessageItem = {
kind: "assistant_message",
id: buffer.id,
text: buffer.text,
timestamp: buffer.timestamp,
const finalized = finalizeHeadItems(head);
const tailIds = new Set(tail.map((item) => item.id));
const newItems = finalized.filter((item) => !tailIds.has(item.id));
if (newItems.length === 0) {
return tail;
}
return [...tail, ...newItems];
}
/**
* Determine if the head should be flushed based on incoming event kind.
* Flush when a different kind arrives or when the incoming kind is not streamable.
*/
function shouldFlushHead(
head: StreamItem[],
incomingKind: StreamItem["kind"] | null
): boolean {
if (head.length === 0) {
return false;
}
// Non-timeline events don't trigger flush (except completion events handled separately)
if (incomingKind === null) {
return false;
}
const lastHeadItem = head[head.length - 1];
// If incoming is not streamable, flush current head
if (!isStreamableKind(incomingKind)) {
return true;
}
// If incoming kind is different from current head kind, flush
if (lastHeadItem.kind !== incomingKind) {
return true;
}
return false;
}
export interface ApplyStreamEventResult {
tail: StreamItem[];
head: StreamItem[];
changedTail: boolean;
changedHead: boolean;
}
/**
* Apply a stream event using head/tail model.
*
* - Tail: committed history (rarely changes during streaming)
* - Head: active streaming items (frequently updated)
*
* Both use the same reduceStreamUpdate function. The difference is:
* - Streamable items (assistant_message, thought) go to head
* - Non-streamable items flush head to tail first, then go to tail
* - Turn completion events flush head to tail
*/
export function applyStreamEvent(params: {
tail: StreamItem[];
head: StreamItem[];
event: AgentStreamEventPayload;
timestamp: Date;
}): ApplyStreamEventResult {
const { tail, head, event, timestamp } = params;
let nextTail = tail;
let nextHead = head;
let changedTail = false;
let changedHead = false;
const flushHead = () => {
if (nextHead.length === 0) {
return;
}
const flushed = flushHeadToTail(nextTail, nextHead);
if (flushed !== nextTail) {
nextTail = flushed;
changedTail = true;
}
nextHead = [];
changedHead = true;
};
return [...state, entry];
// Handle turn completion events - flush everything
if (STREAM_COMPLETION_EVENTS.has(event.type)) {
flushHead();
// Also finalize any remaining thoughts in tail
const finalized = finalizeActiveThoughts(nextTail);
if (finalized !== nextTail) {
nextTail = finalized;
changedTail = true;
}
return { tail: nextTail, head: nextHead, changedTail, changedHead };
}
const incomingKind = getEventItemKind(event);
// Check if we need to flush head before processing this event
if (shouldFlushHead(nextHead, incomingKind)) {
flushHead();
}
// For streamable kinds, apply to head
if (incomingKind !== null && isStreamableKind(incomingKind)) {
const reduced = reduceStreamUpdate(nextHead, event, timestamp);
if (reduced !== nextHead) {
nextHead = reduced;
changedHead = true;
}
return { tail: nextTail, head: nextHead, changedTail, changedHead };
}
// For non-streamable kinds or non-timeline events, apply to tail
const reduced = reduceStreamUpdate(nextTail, event, timestamp);
if (reduced !== nextTail) {
nextTail = reduced;
changedTail = true;
}
return { tail: nextTail, head: nextHead, changedTail, changedHead };
}
// Legacy export for backwards compatibility during migration
// TODO: Remove after all consumers are updated
export type StreamingBufferEntry = {
id: string;
text: string;
timestamp: Date;
};
export function applyStreamEventWithBuffer(params: {
state: StreamItem[];
buffer: StreamingBufferEntry | null;
@@ -838,73 +1047,36 @@ export function applyStreamEventWithBuffer(params: {
changedStream: boolean;
changedBuffer: boolean;
} {
const { state, buffer, event, timestamp } = params;
let nextStream = state;
let nextBuffer = buffer;
let changedStream = false;
let changedBuffer = false;
// Convert legacy buffer to head
const head: StreamItem[] = params.buffer
? [
{
kind: "assistant_message" as const,
id: params.buffer.id,
text: params.buffer.text,
timestamp: params.buffer.timestamp,
},
]
: [];
const commitBuffer = () => {
if (!nextBuffer) {
return;
}
const next = appendCompletedAssistantMessage(nextStream, nextBuffer);
if (next !== nextStream) {
nextStream = next;
changedStream = true;
}
nextBuffer = null;
changedBuffer = true;
const result = applyStreamEvent({
tail: params.state,
head,
event: params.event,
timestamp: params.timestamp,
});
// Convert head back to legacy buffer format
const lastHead = result.head[result.head.length - 1];
const newBuffer: StreamingBufferEntry | null =
lastHead && lastHead.kind === "assistant_message"
? { id: lastHead.id, text: lastHead.text, timestamp: lastHead.timestamp }
: null;
return {
stream: result.tail,
buffer: newBuffer,
changedStream: result.changedTail,
changedBuffer: result.changedHead,
};
if (event.type === "timeline") {
if (event.item.type === "assistant_message") {
const { chunk, hasContent } = normalizeChunk(event.item.text);
if (!chunk) {
return { stream: nextStream, buffer: nextBuffer, changedStream, changedBuffer };
}
if (!hasContent && !nextBuffer) {
return { stream: nextStream, buffer: nextBuffer, changedStream, changedBuffer };
}
if (nextBuffer) {
const updatedText = `${nextBuffer.text}${chunk}`;
if (updatedText !== nextBuffer.text) {
nextBuffer = { ...nextBuffer, text: updatedText };
changedBuffer = true;
}
} else {
const idSeed = chunk.trim() || chunk;
nextBuffer = {
id: createUniqueTimelineId(nextStream, "assistant", idSeed, timestamp),
text: chunk,
timestamp,
};
changedBuffer = true;
}
return { stream: nextStream, buffer: nextBuffer, changedStream, changedBuffer };
}
if (nextBuffer) {
commitBuffer();
}
const reduced = reduceStreamUpdate(nextStream, event, timestamp);
if (reduced !== nextStream) {
nextStream = reduced;
changedStream = true;
}
return { stream: nextStream, buffer: nextBuffer, changedStream, changedBuffer };
}
if (STREAM_COMPLETION_EVENTS.has(event.type)) {
commitBuffer();
return { stream: nextStream, buffer: nextBuffer, changedStream, changedBuffer };
}
const reduced = reduceStreamUpdate(nextStream, event, timestamp);
if (reduced !== nextStream) {
nextStream = reduced;
changedStream = true;
}
return { stream: nextStream, buffer: nextBuffer, changedStream, changedBuffer };
}