1589 lines
51 KiB
TypeScript
1589 lines
51 KiB
TypeScript
import * as Haptics from "expo-haptics";
|
|
import { KeyboardAwareLegendList } from "@legendapp/list/keyboard";
|
|
import { type LegendListRef } from "@legendapp/list/react-native";
|
|
import type { EnvironmentId, MessageId, ThreadId, TurnId } from "@t3tools/contracts";
|
|
import { CHAT_LIST_ANCHOR_OFFSET, resolveChatListAnchoredEndSpace } from "@t3tools/shared/chatList";
|
|
import { SymbolView } from "expo-symbols";
|
|
import { useAppNavigation } from "../../navigation/native-stack-header";
|
|
import {
|
|
memo,
|
|
useCallback,
|
|
useEffect,
|
|
useMemo,
|
|
useRef,
|
|
useState,
|
|
type ReactNode,
|
|
type RefObject,
|
|
} from "react";
|
|
import {
|
|
Markdown,
|
|
type CustomRenderers,
|
|
type NodeStyleOverrides,
|
|
type PartialMarkdownTheme,
|
|
} from "react-native-nitro-markdown";
|
|
import {
|
|
ActivityIndicator,
|
|
Image,
|
|
Linking,
|
|
Platform,
|
|
type LayoutChangeEvent,
|
|
type NativeScrollEvent,
|
|
type NativeSyntheticEvent,
|
|
Pressable,
|
|
ScrollView,
|
|
StyleSheet,
|
|
Text as NativeText,
|
|
type ColorValue,
|
|
useColorScheme,
|
|
useWindowDimensions,
|
|
View,
|
|
} from "react-native";
|
|
import { TouchableOpacity } from "react-native-gesture-handler";
|
|
import { ScrollViewMarker } from "react-native-screens";
|
|
import ImageViewing from "react-native-image-viewing";
|
|
import { useSafeAreaInsets } from "react-native-safe-area-context";
|
|
import { type SharedValue } from "react-native-reanimated";
|
|
import { useThemeColor } from "../../lib/useThemeColor";
|
|
import { copyTextWithHaptic } from "../../lib/copyTextWithHaptic";
|
|
import {
|
|
hasNativeSelectableMarkdownText,
|
|
SelectableMarkdownText,
|
|
type NativeMarkdownTextStyle,
|
|
type SelectableMarkdownSkill,
|
|
} from "../../native/SelectableMarkdownText";
|
|
|
|
import { AppText as Text } from "../../components/AppText";
|
|
import { CopyTextButton } from "../../components/CopyTextButton";
|
|
import {
|
|
parseReviewCommentMessageSegments,
|
|
type ReviewInlineComment,
|
|
} from "../review/reviewCommentSelection";
|
|
import { resolveNativeReviewDiffView } from "../diffs/nativeReviewDiffSurface";
|
|
import {
|
|
buildNativeReviewDiffData,
|
|
createNativeReviewDiffTheme,
|
|
NATIVE_REVIEW_DIFF_CONTENT_WIDTH,
|
|
NATIVE_REVIEW_DIFF_ROW_HEIGHT,
|
|
NATIVE_REVIEW_DIFF_STYLE,
|
|
} from "../review/nativeReviewDiffAdapter";
|
|
import { buildReviewParsedDiff } from "../review/reviewModel";
|
|
import { cn } from "../../lib/cn";
|
|
import { deriveCenteredContentHorizontalPadding, type LayoutVariant } from "../../lib/layout";
|
|
import { nativeHeaderScrollEdgeEffects } from "../../lib/native-scroll-edge-effect";
|
|
import { buildThreadFilesNavigation } from "../../lib/routes";
|
|
import { MOBILE_CODE_SURFACE, MOBILE_TYPOGRAPHY } from "../../lib/typography";
|
|
import { markdownFileIconSource } from "@t3tools/mobile-markdown-text/file-icons";
|
|
import { resolveMarkdownLinkPresentation } from "@t3tools/mobile-markdown-text/links";
|
|
import {
|
|
deriveThreadFeedPresentation,
|
|
type ThreadFeedEntry,
|
|
type ThreadFeedLatestTurn,
|
|
} from "../../lib/threadActivity";
|
|
import type { ThreadContentPresentation } from "./threadContentPresentation";
|
|
import { ThreadWorkGroupToggle, ThreadWorkLog } from "./thread-work-log";
|
|
import { useAssetUrl } from "../../state/assets";
|
|
import { resolveWorkspaceRelativeFilePath } from "../files/filePath";
|
|
|
|
const MESSAGE_TIME_FORMATTER = new Intl.DateTimeFormat(undefined, {
|
|
hour: "numeric",
|
|
minute: "2-digit",
|
|
});
|
|
const HEADER_SCROLL_EDGE_EFFECTS = nativeHeaderScrollEdgeEffects(Platform.OS, Platform.Version);
|
|
|
|
function formatMessageTime(input: string): string {
|
|
const timestamp = Date.parse(input);
|
|
if (Number.isNaN(timestamp)) {
|
|
return "";
|
|
}
|
|
return MESSAGE_TIME_FORMATTER.format(timestamp);
|
|
}
|
|
|
|
export interface ThreadFeedProps {
|
|
readonly environmentId: EnvironmentId;
|
|
readonly threadId: ThreadId;
|
|
readonly workspaceRoot?: string | null;
|
|
readonly feed: ReadonlyArray<ThreadFeedEntry>;
|
|
readonly contentPresentation: ThreadContentPresentation;
|
|
readonly agentLabel: string;
|
|
readonly latestTurn: ThreadFeedLatestTurn | null;
|
|
readonly listRef: RefObject<LegendListRef | null>;
|
|
readonly freeze: SharedValue<boolean>;
|
|
readonly anchorMessageId: MessageId | null;
|
|
readonly contentInsetEndAdjustment: SharedValue<number>;
|
|
readonly contentTopInset?: number;
|
|
readonly contentBottomInset?: number;
|
|
readonly contentMaxWidth?: number;
|
|
readonly layoutVariant?: LayoutVariant;
|
|
readonly usesAutomaticContentInsets?: boolean;
|
|
readonly onHeaderMaterialVisibilityChange?: (visible: boolean) => void;
|
|
readonly skills?: ReadonlyArray<SelectableMarkdownSkill>;
|
|
}
|
|
|
|
function MessageAttachmentImage(props: {
|
|
readonly environmentId: EnvironmentId;
|
|
readonly attachmentId: string;
|
|
readonly className: string;
|
|
readonly onPressImage: (uri: string, headers?: Record<string, string>) => void;
|
|
}) {
|
|
const uri = useAssetUrl(props.environmentId, {
|
|
_tag: "attachment",
|
|
attachmentId: props.attachmentId,
|
|
});
|
|
|
|
if (uri === null) {
|
|
return (
|
|
<View className={`${props.className} items-center justify-center`}>
|
|
<ActivityIndicator />
|
|
</View>
|
|
);
|
|
}
|
|
|
|
return (
|
|
<TouchableOpacity activeOpacity={0.7} onPress={() => props.onPressImage(uri)}>
|
|
<Image source={{ uri }} className={props.className} resizeMode="cover" />
|
|
</TouchableOpacity>
|
|
);
|
|
}
|
|
|
|
const MARKDOWN_COLORS = {
|
|
light: {
|
|
body: "#111111",
|
|
strong: "#000000",
|
|
link: "#2563eb",
|
|
blockquoteBorder: "rgba(0, 0, 0, 0.08)",
|
|
blockquoteBackground: "rgba(0, 0, 0, 0.02)",
|
|
codeBackground: "rgba(0, 0, 0, 0.04)",
|
|
codeText: "#262626",
|
|
inlineCodeText: "#5f6368",
|
|
horizontalRule: "rgba(0, 0, 0, 0.08)",
|
|
userBody: "#ffffff",
|
|
userCodeBackground: "rgba(255, 255, 255, 0.22)",
|
|
userCodeText: "#ffffff",
|
|
userInlineCodeText: "rgba(255, 255, 255, 0.82)",
|
|
userFenceBackground: "rgba(0, 0, 0, 0.16)",
|
|
userFenceText: "#ffffff",
|
|
},
|
|
dark: {
|
|
body: "#e5e5e5",
|
|
strong: "#f5f5f5",
|
|
link: "#60a5fa",
|
|
blockquoteBorder: "rgba(255, 255, 255, 0.1)",
|
|
blockquoteBackground: "rgba(255, 255, 255, 0.03)",
|
|
codeBackground: "rgba(255, 255, 255, 0.06)",
|
|
codeText: "#e5e5e5",
|
|
inlineCodeText: "#b8bcc2",
|
|
horizontalRule: "rgba(255, 255, 255, 0.08)",
|
|
userBody: "#ffffff",
|
|
userCodeBackground: "rgba(255, 255, 255, 0.18)",
|
|
userCodeText: "#ffffff",
|
|
userInlineCodeText: "rgba(255, 255, 255, 0.82)",
|
|
userFenceBackground: "rgba(0, 0, 0, 0.28)",
|
|
userFenceText: "#ffffff",
|
|
},
|
|
} as const;
|
|
|
|
interface MarkdownStyleSets {
|
|
readonly user: MarkdownStyleSet;
|
|
readonly assistant: MarkdownStyleSet;
|
|
}
|
|
|
|
interface MarkdownStyleSet {
|
|
readonly theme: PartialMarkdownTheme;
|
|
readonly styles: NodeStyleOverrides;
|
|
readonly renderers: CustomRenderers;
|
|
readonly nativeTextStyle: NativeMarkdownTextStyle;
|
|
}
|
|
|
|
interface ReviewCommentColors {
|
|
readonly background: ColorValue;
|
|
readonly border: ColorValue;
|
|
readonly mutedBackground: ColorValue;
|
|
readonly text: ColorValue;
|
|
readonly mutedText: ColorValue;
|
|
readonly codeBackground: ColorValue;
|
|
}
|
|
|
|
const failedMarkdownFaviconHosts = new Set<string>();
|
|
const markdownLinkStyles = StyleSheet.create({
|
|
inlineIcon: {
|
|
width: 14,
|
|
height: 14,
|
|
marginHorizontal: 3,
|
|
transform: [{ translateY: 2 }],
|
|
},
|
|
favicon: {
|
|
borderRadius: 3,
|
|
},
|
|
file: {
|
|
fontFamily: "DMSans_700Bold",
|
|
fontWeight: "700",
|
|
},
|
|
});
|
|
|
|
const MarkdownExternalLink = memo(function MarkdownExternalLink(props: {
|
|
readonly children: ReactNode;
|
|
readonly color: string;
|
|
readonly host: string;
|
|
readonly href: string;
|
|
}) {
|
|
const [failed, setFailed] = useState(() => failedMarkdownFaviconHosts.has(props.host));
|
|
|
|
return (
|
|
<NativeText
|
|
onPress={() => {
|
|
void Linking.openURL(props.href);
|
|
}}
|
|
style={{
|
|
color: props.color,
|
|
fontFamily: "DMSans_400Regular",
|
|
textDecorationLine: "none",
|
|
}}
|
|
>
|
|
{!failed ? (
|
|
<Image
|
|
source={{
|
|
uri: `https://www.google.com/s2/favicons?domain=${encodeURIComponent(props.host)}&sz=32`,
|
|
}}
|
|
style={[markdownLinkStyles.inlineIcon, markdownLinkStyles.favicon]}
|
|
onError={() => {
|
|
failedMarkdownFaviconHosts.add(props.host);
|
|
setFailed(true);
|
|
}}
|
|
/>
|
|
) : (
|
|
<NativeText style={{ color: props.color }}>{" ◉ "}</NativeText>
|
|
)}
|
|
{props.children}
|
|
</NativeText>
|
|
);
|
|
});
|
|
|
|
function useReviewCommentColors(): ReviewCommentColors {
|
|
const colorScheme = useColorScheme();
|
|
const isDark = colorScheme === "dark";
|
|
const background = isDark ? "#151515" : "#ffffff";
|
|
const border = isDark ? "#2a2a2a" : "#d7d7d7";
|
|
const mutedBackground = isDark ? "#242424" : "#f2f2f2";
|
|
const text = isDark ? "#f3f3f3" : "#111111";
|
|
const mutedText = isDark ? "#8f8f8f" : "#666666";
|
|
const codeBackground = isDark ? "#0f0f0f" : "#ffffff";
|
|
|
|
return useMemo(
|
|
() => ({
|
|
background,
|
|
border,
|
|
mutedBackground,
|
|
text,
|
|
mutedText,
|
|
codeBackground,
|
|
}),
|
|
[background, border, codeBackground, mutedBackground, mutedText, text],
|
|
);
|
|
}
|
|
|
|
function useMarkdownStyles(onLinkPress: (href: string) => void): MarkdownStyleSets {
|
|
const colorScheme = useColorScheme();
|
|
const colors = MARKDOWN_COLORS[colorScheme === "dark" ? "dark" : "light"];
|
|
const inlineSkillForeground = String(useThemeColor("--color-inline-skill-foreground"));
|
|
|
|
return useMemo(() => {
|
|
const markdownBodyColor = colors.body;
|
|
const markdownStrongColor = colors.strong;
|
|
const markdownLinkColor = colors.link;
|
|
const markdownBlockquoteBg = colors.blockquoteBackground;
|
|
const markdownBlockquoteBorder = colors.blockquoteBorder;
|
|
const markdownCodeBg = colors.codeBackground;
|
|
const markdownCodeText = colors.codeText;
|
|
const markdownInlineCodeText = colors.inlineCodeText;
|
|
const markdownHrColor = colors.horizontalRule;
|
|
const markdownUserBodyColor = colors.userBody;
|
|
const markdownUserCodeBg = colors.userCodeBackground;
|
|
const markdownUserCodeText = colors.userCodeText;
|
|
const markdownUserInlineCodeText = colors.userInlineCodeText;
|
|
const markdownUserFenceBg = colors.userFenceBackground;
|
|
const markdownUserFenceText = colors.userFenceText;
|
|
|
|
const baseTheme: PartialMarkdownTheme = {
|
|
colors: {
|
|
text: markdownBodyColor,
|
|
heading: markdownStrongColor,
|
|
link: markdownLinkColor,
|
|
blockquote: markdownBlockquoteBorder,
|
|
border: markdownHrColor,
|
|
surfaceLight: markdownBlockquoteBg,
|
|
accent: markdownLinkColor,
|
|
tableBorder: markdownHrColor,
|
|
tableHeader: markdownBlockquoteBg,
|
|
tableHeaderText: markdownStrongColor,
|
|
tableRowOdd: "transparent",
|
|
tableRowEven: "transparent",
|
|
},
|
|
spacing: {
|
|
xs: 4,
|
|
s: 4,
|
|
m: 8,
|
|
l: 8,
|
|
xl: 16,
|
|
},
|
|
fontSizes: {
|
|
s: 13,
|
|
m: 15,
|
|
h1: 20,
|
|
h2: 18,
|
|
h3: 16,
|
|
h4: 14,
|
|
h5: 14,
|
|
h6: 14,
|
|
},
|
|
fontFamilies: {
|
|
regular: "DMSans_400Regular",
|
|
heading: "DMSans_700Bold",
|
|
mono: "ui-monospace",
|
|
},
|
|
headingWeight: "700",
|
|
borderRadius: {
|
|
s: 4,
|
|
m: 8,
|
|
l: 12,
|
|
},
|
|
showCodeLanguage: false,
|
|
};
|
|
|
|
const baseStyles: NodeStyleOverrides = {
|
|
document: { flexShrink: 1 },
|
|
paragraph: { marginTop: 0, marginBottom: 10 },
|
|
list: { marginTop: 4, marginBottom: 8 },
|
|
list_item: { marginTop: 0, marginBottom: 4 },
|
|
task_list_item: { marginTop: 0, marginBottom: 4 },
|
|
text: { lineHeight: 22 },
|
|
bold: {
|
|
fontWeight: "700",
|
|
color: markdownStrongColor,
|
|
fontFamily: "DMSans_700Bold",
|
|
},
|
|
italic: { fontStyle: "italic" },
|
|
link: {
|
|
color: markdownLinkColor,
|
|
textDecorationLine: "underline" as const,
|
|
},
|
|
blockquote: {
|
|
borderLeftWidth: 2,
|
|
borderLeftColor: markdownBlockquoteBorder,
|
|
paddingLeft: 11,
|
|
paddingVertical: 2,
|
|
marginLeft: 0,
|
|
marginVertical: 10,
|
|
},
|
|
heading: {
|
|
fontFamily: "DMSans_700Bold",
|
|
color: markdownStrongColor,
|
|
marginTop: 18,
|
|
marginBottom: 8,
|
|
},
|
|
horizontal_rule: {
|
|
backgroundColor: markdownHrColor,
|
|
height: 1,
|
|
marginVertical: 12,
|
|
},
|
|
};
|
|
|
|
const createMarkdownRenderers = (
|
|
inlineTextColor: string,
|
|
inlineCodeTextColor: string,
|
|
blockBackgroundColor: string,
|
|
blockTextColor: string,
|
|
preserveSoftBreaks: boolean,
|
|
): CustomRenderers => ({
|
|
link: ({ children, href = "" }) => {
|
|
const presentation = resolveMarkdownLinkPresentation(href);
|
|
if (presentation.kind === "file") {
|
|
return (
|
|
<NativeText
|
|
onPress={() => onLinkPress(href)}
|
|
style={[markdownLinkStyles.file, { color: inlineTextColor }]}
|
|
>
|
|
<Image
|
|
source={markdownFileIconSource(presentation.icon)}
|
|
style={markdownLinkStyles.inlineIcon}
|
|
/>
|
|
{presentation.label}
|
|
</NativeText>
|
|
);
|
|
}
|
|
if (presentation.kind === "external") {
|
|
return (
|
|
<MarkdownExternalLink
|
|
href={presentation.href}
|
|
host={presentation.host}
|
|
color={markdownLinkColor}
|
|
>
|
|
{children}
|
|
</MarkdownExternalLink>
|
|
);
|
|
}
|
|
const linkHref = presentation.href;
|
|
return (
|
|
<NativeText
|
|
onPress={
|
|
linkHref
|
|
? () => {
|
|
void Linking.openURL(linkHref);
|
|
}
|
|
: undefined
|
|
}
|
|
style={{
|
|
color: markdownLinkColor,
|
|
textDecorationLine: "underline",
|
|
}}
|
|
>
|
|
{children}
|
|
</NativeText>
|
|
);
|
|
},
|
|
list: ({ node, Renderer, ordered = false, start = 1 }) => (
|
|
<View style={{ marginTop: 2, marginBottom: 8 }}>
|
|
{node.children?.map((child, index) => {
|
|
const childKey = `${child.type}:${child.beg ?? "unknown"}:${child.end ?? "unknown"}`;
|
|
if (child.type === "task_list_item") {
|
|
return (
|
|
<Renderer key={childKey} node={child} depth={1} inListItem parentIsText={false} />
|
|
);
|
|
}
|
|
return (
|
|
<View
|
|
key={childKey}
|
|
style={{
|
|
flexDirection: "row",
|
|
alignItems: "flex-start",
|
|
marginBottom: 3,
|
|
}}
|
|
>
|
|
<NativeText
|
|
style={{
|
|
width: ordered ? 22 : 12,
|
|
marginRight: 5,
|
|
color: inlineTextColor,
|
|
fontFamily: "DMSans_400Regular",
|
|
...MOBILE_TYPOGRAPHY.body,
|
|
textAlign: ordered ? "right" : "center",
|
|
}}
|
|
>
|
|
{ordered ? `${start + index}.` : "•"}
|
|
</NativeText>
|
|
<View style={{ flex: 1, minWidth: 0 }}>
|
|
<Renderer node={child} depth={1} inListItem parentIsText={false} />
|
|
</View>
|
|
</View>
|
|
);
|
|
})}
|
|
</View>
|
|
),
|
|
code_inline: ({ content }) => {
|
|
const value = content ?? "";
|
|
return (
|
|
<NativeText
|
|
style={{
|
|
color: inlineCodeTextColor,
|
|
fontFamily: "ui-monospace",
|
|
fontSize: MOBILE_TYPOGRAPHY.label.fontSize,
|
|
lineHeight: 22,
|
|
}}
|
|
>
|
|
{value}
|
|
</NativeText>
|
|
);
|
|
},
|
|
...(preserveSoftBreaks
|
|
? {
|
|
soft_break: () => <NativeText>{"\n"}</NativeText>,
|
|
}
|
|
: {}),
|
|
code_block: ({ content, language }) => (
|
|
<View
|
|
style={{
|
|
backgroundColor: blockBackgroundColor,
|
|
borderRadius: 10,
|
|
borderWidth: 1,
|
|
borderColor: markdownHrColor,
|
|
marginVertical: 12,
|
|
overflow: "hidden",
|
|
}}
|
|
>
|
|
{language ? (
|
|
<View
|
|
style={{
|
|
borderBottomWidth: 1,
|
|
borderBottomColor: markdownHrColor,
|
|
paddingHorizontal: 14,
|
|
paddingVertical: 8,
|
|
}}
|
|
>
|
|
<NativeText
|
|
style={{
|
|
color: markdownBodyColor,
|
|
fontFamily: "ui-monospace",
|
|
fontSize: MOBILE_TYPOGRAPHY.label.fontSize,
|
|
opacity: 0.7,
|
|
textTransform: "uppercase",
|
|
}}
|
|
>
|
|
{language}
|
|
</NativeText>
|
|
</View>
|
|
) : null}
|
|
<ScrollView
|
|
horizontal
|
|
showsHorizontalScrollIndicator={false}
|
|
bounces={false}
|
|
contentContainerStyle={{ paddingHorizontal: 14, paddingVertical: 12 }}
|
|
>
|
|
<NativeText
|
|
selectable
|
|
style={{
|
|
color: blockTextColor,
|
|
fontFamily: "ui-monospace",
|
|
fontSize: MOBILE_TYPOGRAPHY.label.fontSize,
|
|
lineHeight: 18,
|
|
}}
|
|
>
|
|
{content}
|
|
</NativeText>
|
|
</ScrollView>
|
|
</View>
|
|
),
|
|
});
|
|
|
|
const userTheme: PartialMarkdownTheme = {
|
|
...baseTheme,
|
|
colors: {
|
|
...baseTheme.colors,
|
|
text: markdownUserBodyColor,
|
|
heading: markdownUserBodyColor,
|
|
link: markdownUserBodyColor,
|
|
code: markdownUserCodeText,
|
|
codeBackground: markdownUserCodeBg,
|
|
border: markdownUserFenceBg,
|
|
},
|
|
};
|
|
const userStyles: NodeStyleOverrides = {
|
|
...baseStyles,
|
|
paragraph: { marginTop: 0, marginBottom: 0 },
|
|
bold: {
|
|
fontWeight: "700",
|
|
color: markdownUserBodyColor,
|
|
fontFamily: "DMSans_700Bold",
|
|
},
|
|
heading: {
|
|
...baseStyles.heading,
|
|
color: markdownUserBodyColor,
|
|
marginTop: 8,
|
|
marginBottom: 4,
|
|
},
|
|
link: {
|
|
color: markdownUserBodyColor,
|
|
textDecorationLine: "underline" as const,
|
|
},
|
|
};
|
|
|
|
const assistantTheme: PartialMarkdownTheme = {
|
|
...baseTheme,
|
|
colors: {
|
|
...baseTheme.colors,
|
|
code: markdownCodeText,
|
|
codeBackground: markdownCodeBg,
|
|
border: markdownCodeBg,
|
|
},
|
|
};
|
|
const assistantStyles: NodeStyleOverrides = {
|
|
...baseStyles,
|
|
};
|
|
|
|
return {
|
|
user: {
|
|
theme: userTheme,
|
|
styles: userStyles,
|
|
renderers: createMarkdownRenderers(
|
|
markdownUserCodeText,
|
|
markdownUserInlineCodeText,
|
|
markdownUserFenceBg,
|
|
markdownUserFenceText,
|
|
true,
|
|
),
|
|
nativeTextStyle: {
|
|
color: markdownUserBodyColor,
|
|
strongColor: markdownUserBodyColor,
|
|
mutedColor: markdownUserBodyColor,
|
|
linkColor: markdownUserBodyColor,
|
|
inlineCodeColor: markdownUserInlineCodeText,
|
|
codeColor: markdownUserCodeText,
|
|
codeBackgroundColor: markdownUserCodeBg,
|
|
codeBlockBackgroundColor: markdownUserFenceBg,
|
|
fileTextColor: "#ffffff",
|
|
skillTextColor: "#f0abfc",
|
|
quoteMarkerColor: markdownUserBodyColor,
|
|
dividerColor: markdownUserBodyColor,
|
|
...MOBILE_TYPOGRAPHY.body,
|
|
fontFamily: "DMSans_400Regular",
|
|
headingFontFamily: "DMSans_700Bold",
|
|
boldFontFamily: "DMSans_700Bold",
|
|
},
|
|
},
|
|
assistant: {
|
|
theme: assistantTheme,
|
|
styles: assistantStyles,
|
|
renderers: createMarkdownRenderers(
|
|
markdownCodeText,
|
|
markdownInlineCodeText,
|
|
markdownCodeBg,
|
|
markdownCodeText,
|
|
false,
|
|
),
|
|
nativeTextStyle: {
|
|
color: markdownBodyColor,
|
|
strongColor: markdownStrongColor,
|
|
mutedColor: markdownBodyColor,
|
|
linkColor: markdownLinkColor,
|
|
inlineCodeColor: markdownInlineCodeText,
|
|
codeColor: markdownCodeText,
|
|
codeBackgroundColor: markdownCodeBg,
|
|
codeBlockBackgroundColor: markdownCodeBg,
|
|
fileTextColor: markdownCodeText,
|
|
skillTextColor: inlineSkillForeground,
|
|
quoteMarkerColor: markdownBlockquoteBorder,
|
|
dividerColor: markdownHrColor,
|
|
...MOBILE_TYPOGRAPHY.body,
|
|
fontFamily: "DMSans_400Regular",
|
|
headingFontFamily: "DMSans_700Bold",
|
|
boldFontFamily: "DMSans_700Bold",
|
|
},
|
|
},
|
|
};
|
|
}, [colors, inlineSkillForeground, onLinkPress]);
|
|
}
|
|
|
|
function renderFeedEntry(
|
|
info: { item: ThreadFeedEntry; index: number },
|
|
props: Pick<ThreadFeedProps, "environmentId" | "skills"> & {
|
|
readonly copiedRowId: string | null;
|
|
readonly expandedWorkRows: Record<string, boolean>;
|
|
readonly terminalAssistantMessageIds: ReadonlySet<string>;
|
|
readonly unsettledTurnId: TurnId | null;
|
|
readonly onCopyWorkRow: (rowId: string, value: string) => void;
|
|
readonly onToggleWorkGroup: (groupId: string) => void;
|
|
readonly onToggleWorkRow: (rowId: string) => void;
|
|
readonly onToggleTurnFold: (turnId: TurnId) => void;
|
|
readonly onPressImage: (uri: string, headers?: Record<string, string>) => void;
|
|
readonly onMarkdownLinkPress: (href: string) => void;
|
|
readonly iconSubtleColor: string | import("react-native").ColorValue;
|
|
readonly userBubbleColor: string | import("react-native").ColorValue;
|
|
readonly markdownStyles: MarkdownStyleSets;
|
|
readonly reviewCommentColors: ReviewCommentColors;
|
|
readonly reviewCommentBubbleWidth: number;
|
|
readonly userBubbleMaxWidth: number;
|
|
},
|
|
) {
|
|
const entry = info.item;
|
|
const { markdownStyles, iconSubtleColor, userBubbleColor } = props;
|
|
|
|
if (entry.type === "turn-fold") {
|
|
return (
|
|
<Pressable
|
|
accessibilityRole="button"
|
|
accessibilityState={{ expanded: entry.expanded }}
|
|
onPress={() => props.onToggleTurnFold(entry.turnId)}
|
|
hitSlop={4}
|
|
className="mb-3 min-h-11 flex-row items-center gap-2 border-b border-neutral-200/80 px-2 dark:border-white/[0.08]"
|
|
>
|
|
<Text className="font-t3-medium text-sm tabular-nums text-foreground-muted">
|
|
{entry.label}
|
|
</Text>
|
|
<SymbolView
|
|
name={entry.expanded ? "chevron.down" : "chevron.right"}
|
|
size={15}
|
|
tintColor={iconSubtleColor}
|
|
type="monochrome"
|
|
/>
|
|
</Pressable>
|
|
);
|
|
}
|
|
|
|
if (entry.type === "work-toggle") {
|
|
return (
|
|
<ThreadWorkGroupToggle
|
|
expanded={entry.expanded}
|
|
hiddenCount={entry.hiddenCount}
|
|
iconSubtleColor={iconSubtleColor}
|
|
onlyToolActivities={entry.onlyToolActivities}
|
|
onToggle={() => props.onToggleWorkGroup(entry.groupId)}
|
|
/>
|
|
);
|
|
}
|
|
|
|
if (entry.type === "message") {
|
|
const { message } = entry;
|
|
const isUser = message.role === "user";
|
|
const styles = isUser ? markdownStyles.user : markdownStyles.assistant;
|
|
const timestampLabel = formatMessageTime(isUser ? message.createdAt : message.updatedAt);
|
|
const attachments = message.attachments ?? [];
|
|
const hasReviewCommentContext = message.text.includes("<review_comment");
|
|
const assistantTurnStillInProgress =
|
|
message.role === "assistant" &&
|
|
props.unsettledTurnId !== null &&
|
|
message.turnId === props.unsettledTurnId;
|
|
const showAssistantMeta =
|
|
message.role === "assistant" &&
|
|
props.terminalAssistantMessageIds.has(message.id) &&
|
|
!assistantTurnStillInProgress &&
|
|
!message.streaming;
|
|
|
|
if (isUser) {
|
|
return (
|
|
<View className="mb-5 items-end">
|
|
<View
|
|
className="min-w-0 gap-2 rounded-[20px] px-3.5 py-2.5"
|
|
style={{
|
|
backgroundColor: userBubbleColor,
|
|
maxWidth: props.userBubbleMaxWidth,
|
|
...(hasReviewCommentContext ? { width: props.reviewCommentBubbleWidth } : null),
|
|
}}
|
|
>
|
|
{message.text.trim().length > 0 ? (
|
|
<UserMessageContent
|
|
text={message.text}
|
|
markdownStyles={styles}
|
|
reviewCommentColors={props.reviewCommentColors}
|
|
skills={props.skills}
|
|
onLinkPress={props.onMarkdownLinkPress}
|
|
/>
|
|
) : null}
|
|
{attachments.map((attachment) => {
|
|
return (
|
|
<MessageAttachmentImage
|
|
key={attachment.id}
|
|
environmentId={props.environmentId}
|
|
attachmentId={attachment.id}
|
|
className="aspect-[1.3] w-full rounded-[14px] bg-white/15"
|
|
onPressImage={props.onPressImage}
|
|
/>
|
|
);
|
|
})}
|
|
</View>
|
|
<View className="mt-1 flex-row items-center justify-end gap-1 pr-0.5">
|
|
<Text className="font-t3-medium text-xs tabular-nums text-neutral-600 dark:text-neutral-400">
|
|
{timestampLabel}
|
|
</Text>
|
|
{message.text.trim().length > 0 ? (
|
|
<CopyTextButton
|
|
accessibilityLabel="Copy message"
|
|
text={message.text}
|
|
tintColor={iconSubtleColor}
|
|
buttonSize={28}
|
|
iconSize={13}
|
|
/>
|
|
) : null}
|
|
</View>
|
|
</View>
|
|
);
|
|
}
|
|
|
|
// Skip empty assistant messages (no text, no attachments) — they would
|
|
// render as an orphaned timestamp and break adjacent activity-group merging.
|
|
if (message.text.trim().length === 0 && attachments.length === 0) {
|
|
return null;
|
|
}
|
|
|
|
return (
|
|
<View className={cn(showAssistantMeta ? "mb-5 px-1" : "mb-2 px-1")}>
|
|
{message.text.trim().length > 0 ? (
|
|
hasNativeSelectableMarkdownText() ? (
|
|
<SelectableMarkdownText
|
|
markdown={message.text}
|
|
skills={props.skills}
|
|
textStyle={styles.nativeTextStyle}
|
|
onLinkPress={props.onMarkdownLinkPress}
|
|
/>
|
|
) : (
|
|
<Markdown
|
|
options={{ gfm: true }}
|
|
renderers={styles.renderers}
|
|
styles={styles.styles}
|
|
theme={styles.theme}
|
|
>
|
|
{message.text}
|
|
</Markdown>
|
|
)
|
|
) : null}
|
|
{attachments.map((attachment) => {
|
|
return (
|
|
<MessageAttachmentImage
|
|
key={attachment.id}
|
|
environmentId={props.environmentId}
|
|
attachmentId={attachment.id}
|
|
className="mt-1.5 aspect-[1.3] w-full rounded-[18px] bg-neutral-200 dark:bg-neutral-800"
|
|
onPressImage={props.onPressImage}
|
|
/>
|
|
);
|
|
})}
|
|
{showAssistantMeta ? (
|
|
<View className="mt-1 flex-row items-center gap-1">
|
|
<CopyTextButton
|
|
accessibilityLabel="Copy message"
|
|
text={message.text}
|
|
tintColor={iconSubtleColor}
|
|
buttonSize={28}
|
|
iconSize={13}
|
|
/>
|
|
<Text className="font-t3-medium text-xs tabular-nums text-neutral-600 dark:text-neutral-400">
|
|
{timestampLabel}
|
|
</Text>
|
|
</View>
|
|
) : null}
|
|
</View>
|
|
);
|
|
}
|
|
|
|
return (
|
|
<ThreadWorkLog
|
|
activities={entry.activities}
|
|
copiedRowId={props.copiedRowId}
|
|
expandedRows={props.expandedWorkRows}
|
|
iconSubtleColor={iconSubtleColor}
|
|
onCopyRow={props.onCopyWorkRow}
|
|
onToggleRow={props.onToggleWorkRow}
|
|
/>
|
|
);
|
|
}
|
|
|
|
function UserMessageContent(props: {
|
|
readonly text: string;
|
|
readonly markdownStyles: MarkdownStyleSet;
|
|
readonly reviewCommentColors: ReviewCommentColors;
|
|
readonly skills?: ReadonlyArray<SelectableMarkdownSkill>;
|
|
readonly onLinkPress: (href: string) => void;
|
|
}) {
|
|
const segments = parseReviewCommentMessageSegments(props.text);
|
|
const hasReviewComment = segments.some((segment) => segment.kind === "review-comment");
|
|
if (!hasReviewComment) {
|
|
if (hasNativeSelectableMarkdownText()) {
|
|
return (
|
|
<SelectableMarkdownText
|
|
markdown={props.text}
|
|
skills={props.skills}
|
|
textStyle={props.markdownStyles.nativeTextStyle}
|
|
preserveSoftBreaks
|
|
onLinkPress={props.onLinkPress}
|
|
/>
|
|
);
|
|
}
|
|
return (
|
|
<Markdown
|
|
options={{ gfm: true }}
|
|
renderers={props.markdownStyles.renderers}
|
|
styles={props.markdownStyles.styles}
|
|
theme={props.markdownStyles.theme}
|
|
>
|
|
{props.text}
|
|
</Markdown>
|
|
);
|
|
}
|
|
|
|
return (
|
|
<View className="w-full gap-2">
|
|
{segments.map((segment) => {
|
|
if (segment.kind === "review-comment") {
|
|
return (
|
|
<ReviewCommentCard
|
|
key={segment.comment.id}
|
|
comment={segment.comment}
|
|
colors={props.reviewCommentColors}
|
|
/>
|
|
);
|
|
}
|
|
|
|
const text = segment.text.trim();
|
|
if (text.length === 0) {
|
|
return null;
|
|
}
|
|
|
|
return hasNativeSelectableMarkdownText() ? (
|
|
<SelectableMarkdownText
|
|
key={segment.id}
|
|
markdown={text}
|
|
skills={props.skills}
|
|
textStyle={props.markdownStyles.nativeTextStyle}
|
|
preserveSoftBreaks
|
|
onLinkPress={props.onLinkPress}
|
|
/>
|
|
) : (
|
|
<Markdown
|
|
key={segment.id}
|
|
options={{ gfm: true }}
|
|
renderers={props.markdownStyles.renderers}
|
|
styles={props.markdownStyles.styles}
|
|
theme={props.markdownStyles.theme}
|
|
>
|
|
{text}
|
|
</Markdown>
|
|
);
|
|
})}
|
|
</View>
|
|
);
|
|
}
|
|
|
|
const ReviewCommentCard = memo(function ReviewCommentCard(props: {
|
|
readonly comment: ReviewInlineComment;
|
|
readonly colors: ReviewCommentColors;
|
|
}) {
|
|
const colorScheme = useColorScheme();
|
|
const appearanceScheme = colorScheme === "light" ? "light" : "dark";
|
|
const NativeReviewDiffView = resolveNativeReviewDiffView();
|
|
const patch = useMemo(() => buildReviewCommentPatch(props.comment), [props.comment]);
|
|
const parsedDiff = useMemo(
|
|
() => buildReviewParsedDiff(patch, `thread-review-comment:${props.comment.id}`),
|
|
[patch, props.comment.id],
|
|
);
|
|
const nativeReviewDiffData = useMemo(() => buildNativeReviewDiffData(parsedDiff), [parsedDiff]);
|
|
const compactNativeRows = useMemo(
|
|
() => nativeReviewDiffData.rows.filter((row) => row.kind !== "file"),
|
|
[nativeReviewDiffData.rows],
|
|
);
|
|
const nativeReviewDiffTheme = useMemo(
|
|
() => createNativeReviewDiffTheme(appearanceScheme),
|
|
[appearanceScheme],
|
|
);
|
|
const nativeRowsJson = useMemo(() => JSON.stringify(compactNativeRows), [compactNativeRows]);
|
|
const nativeThemeJson = useMemo(
|
|
() => JSON.stringify(nativeReviewDiffTheme),
|
|
[nativeReviewDiffTheme],
|
|
);
|
|
const nativeStyleJson = useMemo(() => JSON.stringify(NATIVE_REVIEW_DIFF_STYLE), []);
|
|
const nativeDiffHeight = useMemo(
|
|
() =>
|
|
Math.min(
|
|
360,
|
|
Math.max(
|
|
112,
|
|
compactNativeRows.length * NATIVE_REVIEW_DIFF_ROW_HEIGHT +
|
|
NATIVE_REVIEW_DIFF_STYLE.fileHeaderVerticalMargin,
|
|
),
|
|
),
|
|
[compactNativeRows.length],
|
|
);
|
|
const shouldRenderNativeDiff = NativeReviewDiffView != null && compactNativeRows.length > 0;
|
|
|
|
return (
|
|
<View
|
|
className="w-full overflow-hidden rounded-[16px] border"
|
|
style={{
|
|
backgroundColor: props.colors.background,
|
|
borderColor: props.colors.border,
|
|
borderCurve: "continuous",
|
|
}}
|
|
>
|
|
<View
|
|
className="flex-row items-center gap-2 border-b px-3 py-2"
|
|
style={{ borderColor: props.colors.border }}
|
|
>
|
|
<View
|
|
className="size-6 items-center justify-center rounded-[7px]"
|
|
style={{ backgroundColor: props.colors.mutedBackground, borderCurve: "continuous" }}
|
|
>
|
|
<SymbolView
|
|
name="doc.text"
|
|
size={13}
|
|
tintColor={props.colors.mutedText}
|
|
type="monochrome"
|
|
/>
|
|
</View>
|
|
<View className="min-w-0 flex-1">
|
|
<Text
|
|
className="font-mono text-xs leading-[16px]"
|
|
numberOfLines={1}
|
|
style={{ color: props.colors.text }}
|
|
>
|
|
{compactFileName(props.comment.filePath)}
|
|
</Text>
|
|
</View>
|
|
</View>
|
|
{shouldRenderNativeDiff ? (
|
|
<View
|
|
className="border-t"
|
|
collapsable={false}
|
|
style={{
|
|
backgroundColor: nativeReviewDiffTheme.background,
|
|
borderColor: props.colors.border,
|
|
height: nativeDiffHeight,
|
|
}}
|
|
>
|
|
<NativeReviewDiffView
|
|
collapsable={false}
|
|
style={StyleSheet.absoluteFill}
|
|
appearanceScheme={appearanceScheme}
|
|
contentWidth={NATIVE_REVIEW_DIFF_CONTENT_WIDTH}
|
|
rowHeight={NATIVE_REVIEW_DIFF_ROW_HEIGHT}
|
|
rowsJson={nativeRowsJson}
|
|
styleJson={nativeStyleJson}
|
|
themeJson={nativeThemeJson}
|
|
/>
|
|
</View>
|
|
) : props.comment.diff.trim().length > 0 ? (
|
|
<ScrollView
|
|
horizontal
|
|
nestedScrollEnabled
|
|
directionalLockEnabled
|
|
showsHorizontalScrollIndicator={false}
|
|
bounces={false}
|
|
className="border-t"
|
|
style={{ backgroundColor: props.colors.codeBackground, borderColor: props.colors.border }}
|
|
contentContainerStyle={{ padding: 10 }}
|
|
>
|
|
<NativeText
|
|
selectable
|
|
style={{
|
|
color: props.colors.text,
|
|
fontFamily: "ui-monospace",
|
|
fontSize: MOBILE_CODE_SURFACE.fontSize,
|
|
lineHeight: MOBILE_CODE_SURFACE.rowHeight,
|
|
}}
|
|
>
|
|
{props.comment.diff.trim()}
|
|
</NativeText>
|
|
</ScrollView>
|
|
) : null}
|
|
{props.comment.text.length > 0 ? (
|
|
<View className="border-t px-3 py-3" style={{ borderColor: props.colors.border }}>
|
|
<Text
|
|
selectable
|
|
className="text-base leading-[21px]"
|
|
style={{ color: props.colors.text }}
|
|
>
|
|
{props.comment.text}
|
|
</Text>
|
|
</View>
|
|
) : null}
|
|
</View>
|
|
);
|
|
});
|
|
|
|
function buildReviewCommentPatch(comment: ReviewInlineComment): string {
|
|
if ((comment.fenceLanguage ?? "diff") !== "diff") {
|
|
return "";
|
|
}
|
|
const diff = comment.diff.trim();
|
|
if (!diff) {
|
|
return "";
|
|
}
|
|
|
|
if (diff.startsWith("diff --git ")) {
|
|
return diff;
|
|
}
|
|
|
|
const normalizedPath = comment.filePath.replaceAll("\\", "/");
|
|
return [
|
|
`diff --git a/${normalizedPath} b/${normalizedPath}`,
|
|
`--- a/${normalizedPath}`,
|
|
`+++ b/${normalizedPath}`,
|
|
diff,
|
|
].join("\n");
|
|
}
|
|
|
|
function compactFileName(filePath: string): string {
|
|
const normalized = filePath.replaceAll("\\", "/");
|
|
const lastSlashIndex = normalized.lastIndexOf("/");
|
|
return lastSlashIndex >= 0 ? normalized.slice(lastSlashIndex + 1) : normalized;
|
|
}
|
|
|
|
function ThreadFeedPlaceholder(props: {
|
|
readonly bottomInset: number;
|
|
readonly detail: string;
|
|
readonly horizontalPadding: number;
|
|
readonly loading?: boolean;
|
|
readonly title: string;
|
|
readonly topInset: number;
|
|
}) {
|
|
return (
|
|
<View
|
|
style={{
|
|
flex: 1,
|
|
flexGrow: 1,
|
|
alignItems: "center",
|
|
justifyContent: "center",
|
|
paddingTop: props.topInset,
|
|
paddingBottom: props.bottomInset,
|
|
paddingHorizontal: props.horizontalPadding + 24,
|
|
}}
|
|
>
|
|
<View className="max-w-[320px] items-center gap-2">
|
|
{props.loading ? <ActivityIndicator style={{ marginBottom: 6 }} /> : null}
|
|
<Text className="text-center font-t3-bold text-lg text-foreground">{props.title}</Text>
|
|
<Text className="text-center text-sm leading-5 text-foreground-secondary">
|
|
{props.detail}
|
|
</Text>
|
|
</View>
|
|
</View>
|
|
);
|
|
}
|
|
|
|
export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
|
const router = useAppNavigation();
|
|
const copyFeedbackTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
|
const foldSettleFrameRef = useRef<number | null>(null);
|
|
const foldSettleSecondFrameRef = useRef<number | null>(null);
|
|
const disclosureAnchorKeyRef = useRef<string | null>(null);
|
|
const headerMaterialVisibleRef = useRef(false);
|
|
const previousLatestTurnRef = useRef(props.latestTurn);
|
|
const { width: windowWidth } = useWindowDimensions();
|
|
const [viewportWidth, setViewportWidth] = useState(() =>
|
|
props.layoutVariant === "split" ? 0 : windowWidth,
|
|
);
|
|
const [disclosureToggleSettling, setDisclosureToggleSettling] = useState(false);
|
|
const [interactionState, setInteractionState] = useState<{
|
|
readonly copiedRowId: string | null;
|
|
readonly expandedWorkGroups: Record<string, boolean>;
|
|
readonly expandedWorkRows: Record<string, boolean>;
|
|
readonly expandedTurnIds: ReadonlySet<TurnId>;
|
|
}>({
|
|
copiedRowId: null,
|
|
expandedWorkGroups: {},
|
|
expandedWorkRows: {},
|
|
expandedTurnIds: new Set(),
|
|
});
|
|
const { copiedRowId, expandedWorkGroups, expandedWorkRows, expandedTurnIds } = interactionState;
|
|
const [expandedImage, setExpandedImage] = useState<{
|
|
uri: string;
|
|
headers?: Record<string, string>;
|
|
} | null>(null);
|
|
const horizontalPadding = props.layoutVariant === "split" ? 20 : 16;
|
|
const contentHorizontalPadding = deriveCenteredContentHorizontalPadding({
|
|
viewportWidth,
|
|
maxContentWidth: props.contentMaxWidth ?? null,
|
|
minimumPadding: horizontalPadding,
|
|
});
|
|
const contentWidth = Math.max(0, viewportWidth - contentHorizontalPadding * 2);
|
|
const userBubbleMaxWidth = contentWidth * 0.85;
|
|
const reviewCommentBubbleWidth = Math.min(Math.max(280, contentWidth * 0.85), contentWidth);
|
|
const insets = useSafeAreaInsets();
|
|
const topContentInset = props.contentTopInset ?? insets.top + 44;
|
|
const bottomContentInset = props.contentBottomInset ?? 18;
|
|
const usesNativeAutomaticInsets =
|
|
props.usesAutomaticContentInsets === true && Platform.OS === "ios";
|
|
|
|
const iconSubtleColor = useThemeColor("--color-icon-subtle");
|
|
const userBubbleColor = useThemeColor("--color-user-bubble");
|
|
const onMarkdownLinkPress = useCallback(
|
|
(href: string) => {
|
|
const presentation = resolveMarkdownLinkPresentation(href);
|
|
if (presentation.kind === "file") {
|
|
const relativePath = resolveWorkspaceRelativeFilePath(
|
|
props.workspaceRoot,
|
|
presentation.path,
|
|
);
|
|
if (relativePath) {
|
|
void Haptics.selectionAsync();
|
|
router.push(
|
|
buildThreadFilesNavigation(
|
|
{ environmentId: props.environmentId, threadId: props.threadId },
|
|
relativePath,
|
|
presentation.line,
|
|
),
|
|
);
|
|
}
|
|
return;
|
|
}
|
|
|
|
if (presentation.href) {
|
|
void Linking.openURL(presentation.href);
|
|
}
|
|
},
|
|
[props.environmentId, props.threadId, props.workspaceRoot, router],
|
|
);
|
|
const markdownStyles = useMarkdownStyles(onMarkdownLinkPress);
|
|
const reviewCommentColors = useReviewCommentColors();
|
|
// LegendList does not invalidate visible rows when only the renderItem closure changes.
|
|
// Keep row-local interaction props in extraData so disclosures and copy feedback repaint.
|
|
const listAppearanceData = useMemo(
|
|
() => ({
|
|
copiedRowId,
|
|
expandedWorkRows,
|
|
iconSubtleColor,
|
|
markdownStyles,
|
|
reviewCommentColors,
|
|
userBubbleColor,
|
|
viewportWidth,
|
|
}),
|
|
[
|
|
copiedRowId,
|
|
expandedWorkRows,
|
|
iconSubtleColor,
|
|
markdownStyles,
|
|
reviewCommentColors,
|
|
userBubbleColor,
|
|
viewportWidth,
|
|
],
|
|
);
|
|
const reportHeaderMaterialVisibility = useCallback(
|
|
(visible: boolean) => {
|
|
if (headerMaterialVisibleRef.current === visible) {
|
|
return;
|
|
}
|
|
headerMaterialVisibleRef.current = visible;
|
|
props.onHeaderMaterialVisibilityChange?.(visible);
|
|
},
|
|
[props.onHeaderMaterialVisibilityChange],
|
|
);
|
|
const handleScroll = useCallback(
|
|
(event: NativeSyntheticEvent<NativeScrollEvent>) => {
|
|
reportHeaderMaterialVisibility(event.nativeEvent.contentOffset.y + topContentInset > 6);
|
|
},
|
|
[reportHeaderMaterialVisibility, topContentInset],
|
|
);
|
|
const handleViewportLayout = useCallback((event: LayoutChangeEvent) => {
|
|
const nextWidth = Math.round(event.nativeEvent.layout.width);
|
|
setViewportWidth((current) => (Math.abs(current - nextWidth) > 1 ? nextWidth : current));
|
|
}, []);
|
|
|
|
useEffect(() => {
|
|
reportHeaderMaterialVisibility(false);
|
|
}, [props.threadId, reportHeaderMaterialVisibility]);
|
|
|
|
const expandedWorkGroupIds = useMemo(() => {
|
|
const ids = new Set<string>();
|
|
for (const [groupId, expanded] of Object.entries(expandedWorkGroups)) {
|
|
if (expanded) {
|
|
ids.add(groupId);
|
|
}
|
|
}
|
|
return ids;
|
|
}, [expandedWorkGroups]);
|
|
const presentedFeed = useMemo(
|
|
() =>
|
|
deriveThreadFeedPresentation(
|
|
props.feed,
|
|
props.latestTurn,
|
|
expandedTurnIds,
|
|
expandedWorkGroupIds,
|
|
),
|
|
[expandedTurnIds, expandedWorkGroupIds, props.feed, props.latestTurn],
|
|
);
|
|
|
|
const anchoredEndSpace = useMemo(
|
|
() =>
|
|
resolveChatListAnchoredEndSpace(
|
|
presentedFeed,
|
|
props.anchorMessageId,
|
|
(entry) => (entry.type === "message" ? entry.id : null),
|
|
{ anchorOffset: topContentInset + CHAT_LIST_ANCHOR_OFFSET },
|
|
),
|
|
[presentedFeed, props.anchorMessageId, topContentInset],
|
|
);
|
|
const terminalAssistantMessageIds = useMemo(() => {
|
|
const terminalIdsByTurn = new Map<TurnId, string>();
|
|
for (const entry of props.feed) {
|
|
if (entry.type === "message" && entry.message.role === "assistant" && entry.message.turnId) {
|
|
terminalIdsByTurn.set(entry.message.turnId, entry.message.id);
|
|
}
|
|
}
|
|
return new Set(terminalIdsByTurn.values());
|
|
}, [props.feed]);
|
|
const unsettledTurnId =
|
|
props.latestTurn &&
|
|
(props.latestTurn.completedAt === null || props.latestTurn.state === "running")
|
|
? props.latestTurn.turnId
|
|
: null;
|
|
|
|
useEffect(() => {
|
|
const previous = previousLatestTurnRef.current;
|
|
previousLatestTurnRef.current = props.latestTurn;
|
|
if (!props.latestTurn || !previous) {
|
|
return;
|
|
}
|
|
if (props.latestTurn.turnId === previous.turnId) {
|
|
if (previous.state === "running" && props.latestTurn.state === "interrupted") {
|
|
const interruptedTurnId = props.latestTurn.turnId;
|
|
setInteractionState((current) => ({
|
|
...current,
|
|
expandedTurnIds: new Set(current.expandedTurnIds).add(interruptedTurnId),
|
|
}));
|
|
}
|
|
return;
|
|
}
|
|
setInteractionState((current) => {
|
|
if (!current.expandedTurnIds.has(previous.turnId)) {
|
|
return current;
|
|
}
|
|
const next = new Set(current.expandedTurnIds);
|
|
next.delete(previous.turnId);
|
|
return { ...current, expandedTurnIds: next };
|
|
});
|
|
}, [props.latestTurn]);
|
|
|
|
useEffect(() => {
|
|
return () => {
|
|
if (copyFeedbackTimeoutRef.current) {
|
|
clearTimeout(copyFeedbackTimeoutRef.current);
|
|
}
|
|
if (foldSettleFrameRef.current !== null) {
|
|
cancelAnimationFrame(foldSettleFrameRef.current);
|
|
}
|
|
if (foldSettleSecondFrameRef.current !== null) {
|
|
cancelAnimationFrame(foldSettleSecondFrameRef.current);
|
|
}
|
|
};
|
|
}, []);
|
|
|
|
const suspendEndScrollMaintenanceForDisclosure = useCallback((anchorKey: string | null) => {
|
|
disclosureAnchorKeyRef.current = anchorKey;
|
|
setDisclosureToggleSettling(true);
|
|
if (foldSettleFrameRef.current !== null) {
|
|
cancelAnimationFrame(foldSettleFrameRef.current);
|
|
}
|
|
if (foldSettleSecondFrameRef.current !== null) {
|
|
cancelAnimationFrame(foldSettleSecondFrameRef.current);
|
|
}
|
|
foldSettleFrameRef.current = requestAnimationFrame(() => {
|
|
foldSettleSecondFrameRef.current = requestAnimationFrame(() => {
|
|
disclosureAnchorKeyRef.current = null;
|
|
setDisclosureToggleSettling(false);
|
|
foldSettleFrameRef.current = null;
|
|
foldSettleSecondFrameRef.current = null;
|
|
});
|
|
});
|
|
}, []);
|
|
|
|
const shouldRestoreVisibleContentPosition = useCallback((entry: ThreadFeedEntry) => {
|
|
const disclosureAnchorKey = disclosureAnchorKeyRef.current;
|
|
return disclosureAnchorKey === null || entry.id === disclosureAnchorKey;
|
|
}, []);
|
|
|
|
const maintainVisibleContentPosition = useMemo(
|
|
() => ({
|
|
data: true,
|
|
size: true,
|
|
shouldRestorePosition: shouldRestoreVisibleContentPosition,
|
|
}),
|
|
[shouldRestoreVisibleContentPosition],
|
|
);
|
|
|
|
const onCopyWorkRow = useCallback((rowId: string, value: string) => {
|
|
copyTextWithHaptic(value, {
|
|
target: "thread-work-row",
|
|
feedback: "selection",
|
|
});
|
|
setInteractionState((current) => ({ ...current, copiedRowId: rowId }));
|
|
if (copyFeedbackTimeoutRef.current) {
|
|
clearTimeout(copyFeedbackTimeoutRef.current);
|
|
}
|
|
copyFeedbackTimeoutRef.current = setTimeout(() => {
|
|
setInteractionState((current) =>
|
|
current.copiedRowId === rowId ? { ...current, copiedRowId: null } : current,
|
|
);
|
|
copyFeedbackTimeoutRef.current = null;
|
|
}, 1200);
|
|
}, []);
|
|
|
|
const onToggleWorkGroup = useCallback(
|
|
(groupId: string) => {
|
|
suspendEndScrollMaintenanceForDisclosure(`work-toggle:${groupId}`);
|
|
setInteractionState((current) => ({
|
|
...current,
|
|
expandedWorkGroups: {
|
|
...current.expandedWorkGroups,
|
|
[groupId]: !(current.expandedWorkGroups[groupId] ?? false),
|
|
},
|
|
}));
|
|
},
|
|
[suspendEndScrollMaintenanceForDisclosure],
|
|
);
|
|
|
|
const onToggleWorkRow = useCallback(
|
|
(rowId: string) => {
|
|
suspendEndScrollMaintenanceForDisclosure(rowId);
|
|
setInteractionState((current) => ({
|
|
...current,
|
|
expandedWorkRows: {
|
|
...current.expandedWorkRows,
|
|
[rowId]: !(current.expandedWorkRows[rowId] ?? false),
|
|
},
|
|
}));
|
|
},
|
|
[suspendEndScrollMaintenanceForDisclosure],
|
|
);
|
|
|
|
const onToggleTurnFold = useCallback(
|
|
(turnId: TurnId) => {
|
|
suspendEndScrollMaintenanceForDisclosure(`turn-fold:${turnId}`);
|
|
setInteractionState((current) => {
|
|
const next = new Set(current.expandedTurnIds);
|
|
if (next.has(turnId)) {
|
|
next.delete(turnId);
|
|
} else {
|
|
next.add(turnId);
|
|
}
|
|
return { ...current, expandedTurnIds: next };
|
|
});
|
|
},
|
|
[suspendEndScrollMaintenanceForDisclosure],
|
|
);
|
|
|
|
const onPressImage = useCallback((uri: string, headers?: Record<string, string>) => {
|
|
setExpandedImage({ uri, headers });
|
|
}, []);
|
|
|
|
const renderItem = useCallback(
|
|
(info: { item: ThreadFeedEntry; index: number }) =>
|
|
renderFeedEntry(info, {
|
|
environmentId: props.environmentId,
|
|
copiedRowId,
|
|
expandedWorkRows,
|
|
terminalAssistantMessageIds,
|
|
unsettledTurnId,
|
|
onCopyWorkRow,
|
|
onToggleWorkGroup,
|
|
onToggleWorkRow,
|
|
onToggleTurnFold,
|
|
onPressImage,
|
|
onMarkdownLinkPress,
|
|
iconSubtleColor,
|
|
userBubbleColor,
|
|
markdownStyles,
|
|
reviewCommentColors,
|
|
reviewCommentBubbleWidth,
|
|
userBubbleMaxWidth,
|
|
skills: props.skills,
|
|
}),
|
|
[
|
|
copiedRowId,
|
|
expandedWorkRows,
|
|
terminalAssistantMessageIds,
|
|
unsettledTurnId,
|
|
iconSubtleColor,
|
|
userBubbleColor,
|
|
markdownStyles,
|
|
reviewCommentColors,
|
|
reviewCommentBubbleWidth,
|
|
userBubbleMaxWidth,
|
|
onCopyWorkRow,
|
|
onMarkdownLinkPress,
|
|
onPressImage,
|
|
onToggleTurnFold,
|
|
onToggleWorkGroup,
|
|
onToggleWorkRow,
|
|
props.environmentId,
|
|
props.skills,
|
|
],
|
|
);
|
|
|
|
if (props.contentPresentation.kind === "loading") {
|
|
return (
|
|
<ThreadFeedPlaceholder
|
|
title="Loading conversation"
|
|
detail="Fetching the latest messages from this environment."
|
|
loading
|
|
topInset={topContentInset}
|
|
bottomInset={bottomContentInset}
|
|
horizontalPadding={horizontalPadding}
|
|
/>
|
|
);
|
|
}
|
|
|
|
if (props.contentPresentation.kind === "unavailable") {
|
|
return (
|
|
<ThreadFeedPlaceholder
|
|
title={props.contentPresentation.title}
|
|
detail={props.contentPresentation.detail}
|
|
topInset={topContentInset}
|
|
bottomInset={bottomContentInset}
|
|
horizontalPadding={horizontalPadding}
|
|
/>
|
|
);
|
|
}
|
|
|
|
return (
|
|
<>
|
|
<View style={{ flex: 1 }} onLayout={handleViewportLayout}>
|
|
<ScrollViewMarker style={{ flex: 1 }} scrollEdgeEffects={HEADER_SCROLL_EDGE_EFFECTS}>
|
|
<KeyboardAwareLegendList
|
|
ref={props.listRef}
|
|
key={props.threadId}
|
|
style={{ flex: 1 }}
|
|
contentInsetAdjustmentBehavior={usesNativeAutomaticInsets ? "automatic" : "never"}
|
|
automaticallyAdjustsScrollIndicatorInsets={usesNativeAutomaticInsets}
|
|
{...(usesNativeAutomaticInsets
|
|
? {
|
|
contentInset: { top: topContentInset, left: 0, right: 0, bottom: 0 },
|
|
scrollIndicatorInsets: { top: 0, left: 0, right: 0, bottom: 0 },
|
|
}
|
|
: { scrollIndicatorInsets: { top: topContentInset, bottom: 0 } })}
|
|
{...(anchoredEndSpace ? { anchoredEndSpace } : {})}
|
|
contentInsetEndAdjustment={props.contentInsetEndAdjustment}
|
|
freeze={props.freeze}
|
|
maintainScrollAtEnd={
|
|
disclosureToggleSettling
|
|
? false
|
|
: {
|
|
animated: false,
|
|
on: {
|
|
dataChange: true,
|
|
itemLayout: true,
|
|
layout: true,
|
|
},
|
|
}
|
|
}
|
|
maintainVisibleContentPosition={maintainVisibleContentPosition}
|
|
data={presentedFeed}
|
|
extraData={listAppearanceData}
|
|
renderItem={renderItem}
|
|
keyExtractor={(entry) => entry.id}
|
|
getItemType={(entry) =>
|
|
entry.type === "message" ? `message:${entry.message.role}` : entry.type
|
|
}
|
|
keyboardShouldPersistTaps="always"
|
|
keyboardDismissMode="none"
|
|
keyboardLiftBehavior="whenAtEnd"
|
|
estimatedItemSize={180}
|
|
initialScrollAtEnd
|
|
onScroll={handleScroll}
|
|
scrollEventThrottle={16}
|
|
ListHeaderComponent={
|
|
usesNativeAutomaticInsets ? null : <View style={{ height: topContentInset }} />
|
|
}
|
|
contentContainerStyle={{
|
|
paddingTop: 12,
|
|
paddingHorizontal: contentHorizontalPadding,
|
|
}}
|
|
/>
|
|
</ScrollViewMarker>
|
|
{props.feed.length === 0 ? (
|
|
<View pointerEvents="none" style={StyleSheet.absoluteFill}>
|
|
<ThreadFeedPlaceholder
|
|
title="No conversation yet"
|
|
detail="Ask the agent to inspect the repo, run a command, or continue the active thread."
|
|
topInset={topContentInset}
|
|
bottomInset={bottomContentInset}
|
|
horizontalPadding={horizontalPadding}
|
|
/>
|
|
</View>
|
|
) : null}
|
|
</View>
|
|
|
|
<ImageViewing
|
|
images={
|
|
expandedImage
|
|
? [
|
|
{
|
|
uri: expandedImage.uri,
|
|
headers: expandedImage.headers,
|
|
},
|
|
]
|
|
: []
|
|
}
|
|
imageIndex={0}
|
|
visible={expandedImage !== null}
|
|
onRequestClose={() => setExpandedImage(null)}
|
|
swipeToCloseEnabled
|
|
doubleTapToZoomEnabled
|
|
/>
|
|
</>
|
|
);
|
|
});
|