Skip to content
TypeScript

feat(mobile): message media, file cards and grouped steers match web (#27373)

mariae4ecaf629dbc
diff --git a/apps/mobile/src/components/MediaVideoPlayer.tsx b/apps/mobile/src/components/MediaVideoPlayer.tsx
index c6dc31ca00a..37a7d0e236f 100644
--- a/apps/mobile/src/components/MediaVideoPlayer.tsx
+++ b/apps/mobile/src/components/MediaVideoPlayer.tsx
@@ -140,6 +140,7 @@ interface MediaVideoPlayerProps {
readonly paused?: boolean;
readonly onPlaybackStart?: () => void;
readonly actionsSource?: MediaActionsSource;
+ readonly borderRadius?: number;
}
function MediaVideoPlayerContent(props: MediaVideoPlayerProps) {
@@ -152,7 +153,10 @@ function MediaVideoPlayerContent(props: MediaVideoPlayerProps) {
<View
collapsable={false}
className="overflow-hidden rounded-[10px] bg-black"
- style={props.expanded ? { flex: 1 } : { width: "100%", maxWidth: 480, aspectRatio: 16 / 9 }}
+ style={[
+ props.expanded ? { flex: 1 } : { width: "100%", maxWidth: 480, aspectRatio: 16 / 9 },
+ props.borderRadius === undefined ? null : { borderRadius: props.borderRadius },
+ ]}
>
{playbackUri ? (
<LoadedMediaVideo
diff --git a/apps/mobile/src/features/threads/ThreadFeed.tsx b/apps/mobile/src/features/threads/ThreadFeed.tsx
index 33a57859ff8..0c63f78b164 100644
--- a/apps/mobile/src/features/threads/ThreadFeed.tsx
+++ b/apps/mobile/src/features/threads/ThreadFeed.tsx
@@ -33,6 +33,7 @@ import { scopeThreadRef } from "@t3tools/client-runtime/environment";
import type { HandoffEndpoints } from "@t3tools/client-runtime/handoff";
import {
IDLE_COMPACTING_LABELS,
+ resolveUserMessageFileCards,
resolveUserMessagePresentation,
} from "@t3tools/client-runtime/user-message";
import { canForkProjectedAssistantItem } from "@t3tools/client-runtime/state/thread-workflows";
@@ -129,7 +130,10 @@ import { useResolveClassNames } from "uniwind";
import { useFilePreviewGallery, FilePreviewGallery } from "../../components/FilePreviewGallery";
import { assetImageSource } from "../../lib/assetImageSource";
import { composerImageGallery } from "../../lib/composerImageGallery";
+import { isFileBackedComposerAttachment } from "../../lib/composerImages";
+import { useLocalAttachmentPreview } from "../../lib/localAttachmentPreview";
import { messageImageGallery } from "./messageImageGallery";
+import { MARKDOWN_IMAGE_MAX_WIDTH, resolveMarkdownImageDisplaySize } from "./markdownImageSize";
import { FilePreviewModal, type FilePreviewSource } from "../../components/FilePreviewModal";
import { inlineFilePreviewKind, isPdfFile } from "../../lib/filePreview";
import { ThreadInlineFilePreview } from "./ThreadInlineFilePreview";
@@ -221,7 +225,9 @@ import {
import {
appendGuestPendingMessages,
appendPendingThreadMessages,
+ createThreadFeedGrouping,
isCompactionCommandFeedEntry,
+ type GroupedThreadFeedRow,
type ThreadFeedRow,
} from "./pending-thread-feed";
import type { QueuedThreadMessage } from "../../state/thread-outbox-model";
@@ -485,12 +491,57 @@ function AssistantForkButton(props: {
);
}
+function MessageImage(props: {
+ readonly source: ComponentPropsWithRef<typeof ExpoImage>["source"];
+ readonly className: string;
+ readonly maxWidth?: number;
+ readonly height?: number;
+ readonly onLoad?: () => void;
+ readonly onError?: () => void;
+}) {
+ const imageStyle = useResolveClassNames(props.className);
+ const [size, setSize] = useState<{ width: number; height: number } | null>(null);
+ const displaySize =
+ props.maxWidth !== undefined && size !== null
+ ? resolveMarkdownImageDisplaySize({
+ sourceWidth: size.width,
+ sourceHeight: size.height,
+ availableWidth: props.maxWidth,
+ })
+ : null;
+ return (
+ <ExpoImage
+ source={props.source}
+ cachePolicy="memory-disk"
+ style={[
+ imageStyle,
+ props.maxWidth !== undefined
+ ? (displaySize ?? {
+ width: Math.min(props.maxWidth, MARKDOWN_IMAGE_MAX_WIDTH),
+ aspectRatio: 1.3,
+ })
+ : props.height !== undefined
+ ? { height: props.height }
+ : undefined,
+ ]}
+ contentFit={props.maxWidth === undefined ? "cover" : "contain"}
+ onLoad={(event) => {
+ if (props.maxWidth !== undefined) setSize(event.source);
+ props.onLoad?.();
+ }}
+ onError={props.onError}
+ />
+ );
+}
+
function MessageAttachmentImage(props: {
readonly environmentId: EnvironmentId;
readonly attachmentId: string;
readonly name: string;
readonly mimeType: string;
readonly className: string;
+ readonly maxWidth?: number;
+ readonly height?: number;
readonly onPressPreview: (source: FilePreviewSource) => void;
}) {
const withGallery = useFilePreviewGallery();
@@ -504,11 +555,19 @@ function MessageAttachmentImage(props: {
const uri = useAssetUrl(props.environmentId, resource);
const refreshAssetUrl = useRefreshAssetUrl(props.environmentId, resource);
const retriedImage = useRef(false);
- const imageStyle = useResolveClassNames(props.className);
if (uri === null) {
return (
- <View className={`${props.className} items-center justify-center`}>
+ <View
+ className={`${props.className} items-center justify-center`}
+ style={
+ props.maxWidth !== undefined
+ ? { width: Math.min(props.maxWidth, MARKDOWN_IMAGE_MAX_WIDTH), aspectRatio: 1.3 }
+ : props.height !== undefined
+ ? { height: props.height }
+ : undefined
+ }
+ >
<AppActivityIndicator />
</View>
);
@@ -537,11 +596,11 @@ function MessageAttachmentImage(props: {
)
}
>
- <ExpoImage
+ <MessageImage
source={assetImageSource(props.environmentId, resource, uri)}
- cachePolicy="memory-disk"
- style={imageStyle}
- contentFit="cover"
+ className={props.className}
+ maxWidth={props.maxWidth}
+ height={props.height}
onLoad={() => {
retriedImage.current = false;
}}
@@ -564,11 +623,21 @@ function isFileAttachment(attachment: ChatAttachment): attachment is ChatFileAtt
return attachment.type === "file";
}
+function isMediaAttachment(attachment: ChatAttachment): boolean {
+ return (
+ isImageAttachment(attachment) ||
+ (isFileAttachment(attachment) && videoMimeType(attachment) !== null)
+ );
+}
+
function MessageAttachmentFile(props: {
readonly environmentId: EnvironmentId;
readonly attachment: ChatFileAttachment;
readonly onPressPreview: (source: FilePreviewSource) => void;
readonly onPlaybackStart: () => void;
+ readonly standaloneMedia?: boolean;
+ readonly standaloneFile?: boolean;
+ readonly available?: boolean;
}) {
const sourceIdentifier = useId();
const navigation = useNavigation();
@@ -603,7 +672,7 @@ function MessageAttachmentFile(props: {
);
const shareFile = (sourceIdentifier?: string) => {
- if (httpBaseUrl === null || openingRef.current) return;
+ if (props.available === false || httpBaseUrl === null || openingRef.current) return;
const controller = new AbortController();
openingRef.current = controller;
setOpening(true);
@@ -703,29 +772,34 @@ function MessageAttachmentFile(props: {
if (videoType !== null) {
return (
- <View className="my-1" style={{ width: 224, maxWidth: "100%" }}>
+ <View
+ className={props.standaloneMedia ? undefined : "my-1"}
+ style={{ width: props.standaloneMedia ? 320 : 224, maxWidth: "100%" }}
+ >
<ThreadMarkdownVideo
source={attachmentVideoPreviewSource(props.environmentId, attachment, sourceIdentifier)}
onPlaybackStart={props.onPlaybackStart}
+ borderRadius={props.standaloneMedia ? 20 : undefined}
/>
</View>
);
}
+ const disabled = props.available === false || opening || httpBaseUrl === null;
return (
- <>
- <PresentationSource
- identifier={sourceIdentifier}
- className="my-1"
- style={{ width: 280, maxWidth: "100%" }}
- >
+ <PresentationSource
+ identifier={sourceIdentifier}
+ className="my-1"
+ style={{ width: 280, maxWidth: "100%" }}
+ >
+ <View className="min-w-0 flex-row items-center overflow-hidden rounded-xl border border-border bg-card">
<Pressable
accessibilityRole="button"
accessibilityLabel={`Open ${attachment.name}`}
accessibilityValue={{ text: `${fileTypeLabel}, ${sizeLabel}` }}
- accessibilityState={{ disabled: opening || httpBaseUrl === null, busy: opening }}
- disabled={opening || httpBaseUrl === null}
- className="min-w-0 flex-row items-center gap-3 rounded-xl border border-border bg-card p-3 active:bg-subtle"
+ accessibilityState={{ disabled, busy: opening }}
+ disabled={disabled}
+ className="min-w-0 flex-1 flex-row items-center gap-3 p-3 active:bg-subtle"
onLongPress={() => shareFile(sourceIdentifier)}
onPress={openAttachment}
>
@@ -751,8 +825,205 @@ function MessageAttachmentFile(props: {
type="monochrome"
/>
</Pressable>
- </PresentationSource>
- </>
+ {props.standaloneFile ? (
+ <Pressable
+ accessibilityRole="button"
+ accessibilityLabel={`Download ${attachment.name}`}
+ accessibilityState={{ disabled, busy: opening }}
+ disabled={disabled}
+ className="mr-1 min-h-11 w-11 items-center justify-center rounded-lg active:bg-subtle disabled:opacity-40"
+ onPress={() => shareFile(sourceIdentifier)}
+ >
+ <SymbolView name="arrow.down" size={16} tintColorClassName="accent-foreground-muted" />
+ </Pressable>
+ ) : null}
+ </View>
+ </PresentationSource>
+ );
+}
+
+function UserMessageMedia(props: {
+ readonly attachments: ReadonlyArray<ChatAttachment>;
+ readonly pendingAttachments: QueuedThreadMessage["attachments"];
+ readonly environmentId: EnvironmentId;
+ readonly maxWidth: number;
+ readonly onPressPreview: (source: FilePreviewSource) => void;
+ readonly onPlaybackStart: () => void;
+}) {
+ const attachments = [...props.pendingAttachments, ...props.attachments];
+ const collage = attachments.length > 1 && attachments.every(isImageAttachment);
+ const imageProps = (index: number) => ({
+ className: "w-full bg-user-bubble-foreground/15",
+ maxWidth: collage ? undefined : props.maxWidth,
+ height: !collage
+ ? undefined
+ : attachments.length === 2 || (attachments.length === 3 && index === 0)
+ ? 192
+ : attachments.length === 3
+ ? (192 - StyleSheet.hairlineWidth) / 2
+ : 96,
+ });
+ const media = [
+ ...props.pendingAttachments.map((attachment, index) => {
+ const image = isImageAttachment(attachment);
+ return {
+ id: attachment.id,
+ image,
+ content:
+ image && attachment.uploadedAttachmentId ? (
+ <MessageAttachmentImage
+ environmentId={props.environmentId}
+ attachmentId={attachment.uploadedAttachmentId}
+ name={attachment.name}
+ mimeType={attachment.mimeType}
+ {...imageProps(index)}
+ onPressPreview={props.onPressPreview}
+ />
+ ) : !image && attachment.uploadedAttachmentId ? (
+ <ThreadMarkdownVideo
+ source={attachmentVideoPreviewSource(props.environmentId, {
+ ...attachment,
+ type: "file",
+ id: attachment.uploadedAttachmentId,
+ })}
+ onPlaybackStart={props.onPlaybackStart}
+ borderRadius={20}
+ />
+ ) : (
+ <PendingMessageMedia
+ attachment={attachment}
+ {...imageProps(index)}
+ onPressPreview={props.onPressPreview}
+ onPlaybackStart={props.onPlaybackStart}
+ />
+ ),
+ };
+ }),
+ ...props.attachments.map((attachment, index) => ({
+ id: attachment.id,
+ image: isImageAttachment(attachment),
+ content: isImageAttachment(attachment) ? (
+ <MessageAttachmentImage
+ environmentId={props.environmentId}
+ attachmentId={attachment.id}
+ name={attachment.name}
+ mimeType={attachment.mimeType}
+ {...imageProps(props.pendingAttachments.length + index)}
+ onPressPreview={props.onPressPreview}
+ />
+ ) : isFileAttachment(attachment) ? (
+ <MessageAttachmentFile
+ environmentId={props.environmentId}
+ attachment={attachment}
+ onPressPreview={props.onPressPreview}
+ onPlaybackStart={props.onPlaybackStart}
+ standaloneMedia
+ />
+ ) : null,
+ })),
+ ];
+ return collage ? (
+ <View
+ className="overflow-hidden rounded-[20px] bg-border"
+ style={{ width: 320, maxWidth: "100%", alignSelf: "flex-end", gap: StyleSheet.hairlineWidth }}
+ >
+ {media.length === 3 ? (
+ <View className="flex-row" style={{ gap: StyleSheet.hairlineWidth }}>
+ <View className="min-w-0" style={{ flex: 3 }}>
+ {media[0]!.content}
+ </View>
+ <View className="min-w-0" style={{ flex: 2, gap: StyleSheet.hairlineWidth }}>
+ {media[1]!.content}
+ {media[2]!.content}
+ </View>
+ </View>
+ ) : (
+ media
+ .filter((_, index) => index % 2 === 0)
+ .map((item, index) => (
+ <View key={item.id} className="flex-row" style={{ gap: StyleSheet.hairlineWidth }}>
+ <View className="min-w-0 flex-1">{item.content}</View>
+ {media[index * 2 + 1] ? (
+ <View className="min-w-0 flex-1">{media[index * 2 + 1]!.content}</View>
+ ) : null}
+ </View>
+ ))
+ )}
+ <View pointerEvents="none" className="absolute inset-0 rounded-[20px] border border-border" />
+ </View>
+ ) : (
+ <View className="items-end gap-2">
+ {media.map((item) => (
+ <View
+ key={item.id}
+ className="overflow-hidden rounded-[20px]"
+ style={{ width: item.image ? undefined : 320, maxWidth: "100%" }}
+ >
+ {item.content}
+ <View
+ pointerEvents="none"
+ className="absolute inset-0 rounded-[20px] border border-border"
+ />
+ </View>
+ ))}
+ </View>
+ );
+}
+
+function PendingMessageMedia(props: {
+ readonly attachment: QueuedThreadMessage["attachments"][number];
+ readonly className: string;
+ readonly maxWidth?: number;
+ readonly height?: number;
+ readonly onPressPreview: (source: FilePreviewSource) => void;
+ readonly onPlaybackStart: () => void;
+}) {
+ const withGallery = useFilePreviewGallery();
+ const { attachment } = props;
+ const fileBacked = isFileBackedComposerAttachment(attachment);
+ const preview = useLocalAttachmentPreview(fileBacked ? attachment : null);
+ if (isImageAttachment(attachment)) {
+ const uri = fileBacked ? preview.uri : (attachment.dataUrl ?? attachment.previewUri);
+ return (
+ <Pressable
+ accessibilityRole="imagebutton"
+ accessibilityLabel={`Open ${attachment.name}`}
+ onPress={() => {
+ const source = composerImageGallery([attachment])[0];
+ if (source) props.onPressPreview(withGallery(source));
+ }}
+ >
+ <MessageImage
+ source={uri === null ? undefined : { uri }}
+ className={props.className}
+ maxWidth={props.maxWidth}
+ height={props.height}
+ />
+ </Pressable>
+ );
+ }
+ if (preview.uri === null) {
+ return (
+ <View className="aspect-video items-center justify-center bg-black">
+ {preview.error ? (
+ <Text className="p-3 text-center text-xs text-white/70">{preview.error.message}</Text>
+ ) : (
+ <AppActivityIndicator />
+ )}
+ </View>
+ );
+ }
+ return (
+ <ThreadMarkdownVideo
+ source={{
+ type: "media",
+ name: attachment.name,
+ mimeType: attachment.mimeType,
+ uri: preview.uri,
+ }}
+ onPlaybackStart={props.onPlaybackStart}
+ borderRadius={20}
+ />
);
}
@@ -1338,6 +1609,7 @@ function renderFeedEntry(
readonly contentWidth: number;
readonly threadTitle: string;
readonly workflowOpening: WorkflowOpening | null;
+ readonly userMessageGrouping: GroupedThreadFeedRow["userMessageGrouping"];
},
) {
const entry = info.item;
@@ -1582,7 +1854,9 @@ function renderFeedEntry(
const foldRowId = presentation.attribution === "agent" ? `agent:${message.id}` : null;
const foldExpanded = foldRowId !== null && (props.expandedWorkRows[foldRowId] ?? false);
const bubbleBodyVisible = foldRowId === null || foldExpanded;
- const intentBadge = resolveUserMessageIntentBadge(message.inputIntent);
+ const intentBadge = props.userMessageGrouping.continuesSteer
+ ? null
+ : resolveUserMessageIntentBadge(message.inputIntent);
const referenceIds = new Set(
collectComposerContextReferences(message.text).map((reference) => reference.contextId),
);
@@ -1593,22 +1867,36 @@ function renderFeedEntry(
: [],
),
);
+ const standaloneMedia = foldRowId === null && presentation.attribution !== "guest";
+ const mediaAttachments = standaloneMedia ? attachments.filter(isMediaAttachment) : [];
const visibleAttachments = attachments.filter(
- (attachment) => isImageAttachment(attachment) || !inlineAttachmentIds.has(attachment.id),
+ (attachment) =>
+ !(standaloneMedia && isMediaAttachment(attachment)) &&
+ (isImageAttachment(attachment) || !inlineAttachmentIds.has(attachment.id)),
);
- // Images sent without words show as images, not as a bubble around them.
- const mediaOnly =
- foldRowId === null &&
- presentation.attribution !== "guest" &&
- presentation.text.trim() === "" &&
- visibleAttachments.length + (entry.pendingMessage?.attachments.length ?? 0) > 0 &&
- visibleAttachments.every(isImageAttachment) &&
- (entry.pendingMessage?.attachments ?? []).every(
- (attachment) => attachment.type === "image",
- );
+ const pendingAttachments = entry.pendingMessage?.attachments ?? [];
+ const pendingMedia = standaloneMedia ? pendingAttachments.filter(isMediaAttachment) : [];
+ const pendingBubbleAttachments = standaloneMedia
+ ? pendingAttachments.filter(
+ (attachment) =>
+ !isMediaAttachment(attachment) && !inlineAttachmentIds.has(attachment.id),
+ )
+ : pendingAttachments;
+ const fileCards = standaloneMedia
+ ? resolveUserMessageFileCards({
+ text: presentation.text,
+ attachments: attachments.length > 0 ? attachments : pendingAttachments,
+ context: message.context,
+ })
+ : null;
+ const hasBubble =
+ fileCards === null &&
+ (foldRowId !== null ||
+ presentation.text.trim().length > 0 ||
+ visibleAttachments.length + pendingBubbleAttachments.length > 0);
return (
<Animated.View
- className="mb-5 items-end"
+ className={cn("items-end", props.userMessageGrouping.groupedWithNext ? "mb-1" : "mb-5")}
{...(enterAnimated ? { entering: FadeInUp.duration(220) } : {})}
>
{presentation.attribution === "t3code" ? (
@@ -1619,136 +1907,174 @@ function renderFeedEntry(
{presentation.guestName !== undefined ? (
<GuestMessageName name={presentation.guestName} />
) : null}
- <View
- className="min-w-0 rounded-[20px]"
- style={{
- backgroundColor: mediaOnly ? undefined : userBubbleColor,
- maxWidth: props.duoColumns ? "85%" : props.userBubbleMaxWidth,
- ...(!bubbleBodyVisible
- ? null
- : hasReviewCommentContext
- ? { width: props.reviewCommentBubbleWidth }
- : hasWideBlock || foldExpanded || (mediaOnly && visibleAttachments.length > 0)
- ? { width: props.duoColumns ? "85%" : props.userBubbleMaxWidth }
- : null),
- }}
- >
- {presentation.attribution === "guest" ? <GuestBubbleTint /> : null}
- {foldRowId !== null ? (
- <AgentMessageFoldHeader
+ {mediaAttachments.length + pendingMedia.length > 0 ? (
+ <View
+ className={hasBubble ? "mb-2" : undefined}
+ style={{ width: props.duoColumns ? "85%" : props.userBubbleMaxWidth }}
+ >
+ <UserMessageMedia
+ attachments={mediaAttachments}
+ pendingAttachments={pendingMedia}
environmentId={props.environmentId}
- senderThreadId={message.senderThreadId}
- summary={
- replaceComposerContextReferences(presentation.text, (ref) => ref.label)
- .split(/\r?\n/)
- .find((line) => line.trim().length > 0)
- ?.trim() ?? ""
- }
- expanded={foldExpanded}
- onToggle={() => props.onToggleWorkRow(foldRowId, entry.id)}
- iconSubtleColor={iconSubtleColor}
+ maxWidth={props.userBubbleMaxWidth}
+ onPressPreview={props.onPressPreview}
+ onPlaybackStart={props.onPlaybackStart}
/>
- ) : null}
- {bubbleBodyVisible ? (
- <View
- className={cn(
- "gap-2",
- !mediaOnly && "px-3.5 pb-2.5",
- !mediaOnly && foldRowId === null && "pt-2.5",
- )}
- >
- {entry.pendingMessage?.attachments.map((attachment) =>
- attachment.type === "image" && attachment.uploadedAttachmentId ? (
- <MessageAttachmentImage
- key={attachment.id}
- environmentId={props.environmentId}
- attachmentId={attachment.uploadedAttachmentId}
- name={attachment.name}
- mimeType={attachment.mimeType}
- className={
- mediaOnly
- ? "h-[140px] w-[180px] rounded-[20px]"
- : "h-[140px] w-[180px] rounded-[14px]"
- }
- onPressPreview={props.onPressPreview}
- />
- ) : attachment.type === "image" ? (
- <Pressable
- key={attachment.id}
- accessibilityRole="imagebutton"
- accessibilityLabel={`Open ${attachment.name}`}
- onPress={() =>
- props.onPressPreview({
- kind: "image",
- name: attachment.name,
- uri: attachment.dataUrl ?? attachment.previewUri,
- gallery: composerImageGallery(entry.pendingMessage?.attachments ?? []),
- })
- }
- >
- <Image
- source={{ uri: attachment.previewUri }}
- style={{ width: 180, height: 140, borderRadius: mediaOnly ? 20 : 14 }}
+ </View>
+ ) : null}
+ {fileCards ? (
+ <View
+ className="items-end"
+ style={{ maxWidth: props.duoColumns ? "85%" : props.userBubbleMaxWidth }}
+ >
+ {fileCards.map((file) => {
+ const pendingFile = pendingAttachments.find(
+ (attachment) => attachment.id === file.id,
+ );
+ return (
+ <MessageAttachmentFile
+ key={file.id}
+ environmentId={props.environmentId}
+ attachment={
+ pendingFile?.uploadedAttachmentId
+ ? { ...file, id: pendingFile.uploadedAttachmentId }
+ : file
+ }
+ available={
+ pendingFile === undefined || pendingFile.uploadedAttachmentId !== undefined
+ }
+ onPressPreview={props.onPressPreview}
+ onPlaybackStart={props.onPlaybackStart}
+ standaloneFile
+ />
+ );
+ })}
+ </View>
+ ) : null}
+ {hasBubble ? (
+ <View
+ className="min-w-0 rounded-[20px]"
+ style={{
+ backgroundColor: userBubbleColor,
+ maxWidth: props.duoColumns ? "85%" : props.userBubbleMaxWidth,
+ ...(!bubbleBodyVisible
+ ? null
+ : hasReviewCommentContext
+ ? { width: props.reviewCommentBubbleWidth }
+ : hasWideBlock || foldExpanded
+ ? { width: props.duoColumns ? "85%" : props.userBubbleMaxWidth }
+ : null),
+ }}
+ >
+ {presentation.attribution === "guest" ? <GuestBubbleTint /> : null}
+ {foldRowId !== null ? (
+ <AgentMessageFoldHeader
+ environmentId={props.environmentId}
+ senderThreadId={message.senderThreadId}
+ summary={
+ replaceComposerContextReferences(presentation.text, (ref) => ref.label)
+ .split(/\r?\n/)
+ .find((line) => line.trim().length > 0)
+ ?.trim() ?? ""
+ }
+ expanded={foldExpanded}
+ onToggle={() => props.onToggleWorkRow(foldRowId, entry.id)}
+ iconSubtleColor={iconSubtleColor}
+ />
+ ) : null}
+ {bubbleBodyVisible ? (
+ <View className={cn("gap-2 px-3.5 pb-2.5", foldRowId === null && "pt-2.5")}>
+ {pendingBubbleAttachments.map((attachment) =>
+ attachment.type === "image" && attachment.uploadedAttachmentId ? (
+ <MessageAttachmentImage
+ key={attachment.id}
+ environmentId={props.environmentId}
+ attachmentId={attachment.uploadedAttachmentId}
+ name={attachment.name}
+ mimeType={attachment.mimeType}
+ className="h-[140px] w-[180px] rounded-[14px]"
+ onPressPreview={props.onPressPreview}
/>
- </Pressable>
- ) : (
- <MessageAttachmentUnknown key={attachment.id} name={attachment.name} />
- ),
- )}
- {/* An empty container still takes a gap, which pads every attachment-free bubble. */}
- {visibleAttachments.length > 0 ? (
- <View className={inlineAttachmentIds.size ? "flex-row flex-wrap gap-2" : "gap-2"}>
- {visibleAttachments.map((attachment) => {
- return isImageAttachment(attachment) ? (
- <MessageAttachmentImage
- key={attachment.id}
- environmentId={props.environmentId}
- attachmentId={attachment.id}
- name={attachment.name}
- mimeType={attachment.mimeType}
- className={
- inlineAttachmentIds.size
- ? "h-24 w-24 rounded-[14px] bg-user-bubble-foreground/15"
- : mediaOnly
- ? // Matches the bubble's corners; native borders sit inside, so the edge adds no size.
- "aspect-[1.3] w-full rounded-[20px] border border-border bg-user-bubble-foreground/15"
- : "aspect-[1.3] w-full rounded-[14px] bg-user-bubble-foreground/15"
- }
- onPressPreview={props.onPressPreview}
+ ) : attachment.type === "image" ? (
+ <Pressable
+ key={attachment.id}
+ accessibilityRole="imagebutton"
+ accessibilityLabel={`Open ${attachment.name}`}
+ onPress={() => {
+ const source = composerImageGallery([attachment])[0];
+ if (source)
+ props.onPressPreview({
+ ...source,
+ gallery: composerImageGallery(
+ entry.pendingMessage?.attachments ?? [],
+ props.environmentId,
+ ),
+ });
+ }}
+ >
+ <Image
+ source={{ uri: attachment.previewUri }}
+ style={{ width: 180, height: 140, borderRadius: 14 }}
/>
- ) : isFileAttachment(attachment) ? (
- <MessageAttachmentFile
- key={attachment.id}
- environmentId={props.environmentId}
- attachment={attachment}
- onPressPreview={props.onPressPreview}
- onPlaybackStart={props.onPlaybackStart}
- />
- ) : (
- <MessageAttachmentUnknown key={attachment.id} name={attachment.name} />
- );
- })}
- </View>
- ) : null}
- {presentation.text.trim().length > 0 ? (
- <MarkdownImageAvailableWidthContext
- value={props.userBubbleMaxWidth - USER_BUBBLE_HORIZONTAL_PADDING * 2}
- >
- <UserMessageContent
- text={renderedText}
- environmentId={props.environmentId}
- context={message.context}
- markdownStyles={styles}
- reviewCommentColors={props.reviewCommentColors}
- skills={props.skills}
- linkHandlers={props.markdownLinkHandlers}
- renderImage={props.renderMarkdownImage}
- />
- </MarkdownImageAvailableWidthContext>
- ) : null}
- </View>
- ) : null}
- </View>
+ </Pressable>
+ ) : (
+ <MessageAttachmentUnknown key={attachment.id} name={attachment.name} />
+ ),
+ )}
+ {/* An empty container still takes a gap, which pads every attachment-free bubble. */}
+ {visibleAttachments.length > 0 ? (
+ <View
+ className={inlineAttachmentIds.size ? "flex-row flex-wrap gap-2" : "gap-2"}
+ >
+ {visibleAttachments.map((attachment) => {
+ return isImageAttachment(attachment) ? (
+ <MessageAttachmentImage
+ key={attachment.id}
+ environmentId={props.environmentId}
+ attachmentId={attachment.id}
+ name={attachment.name}
+ mimeType={attachment.mimeType}
+ className={
+ inlineAttachmentIds.size
+ ? "h-24 w-24 rounded-[14px] bg-user-bubble-foreground/15"
+ : "aspect-[1.3] w-full rounded-[14px] bg-user-bubble-foreground/15"
+ }
+ onPressPreview={props.onPressPreview}
+ />
+ ) : isFileAttachment(attachment) ? (
+ <MessageAttachmentFile
+ key={attachment.id}
+ environmentId={props.environmentId}
+ attachment={attachment}
+ onPressPreview={props.onPressPreview}
+ onPlaybackStart={props.onPlaybackStart}
+ />
+ ) : (
+ <MessageAttachmentUnknown key={attachment.id} name={attachment.name} />
+ );
+ })}
+ </View>
+ ) : null}
+ {presentation.text.trim().length > 0 ? (
+ <MarkdownImageAvailableWidthContext
+ value={props.userBubbleMaxWidth - USER_BUBBLE_HORIZONTAL_PADDING * 2}
+ >
+ <UserMessageContent
+ text={renderedText}
+ environmentId={props.environmentId}
+ context={message.context}
+ markdownStyles={styles}
+ reviewCommentColors={props.reviewCommentColors}
+ skills={props.skills}
+ linkHandlers={props.markdownLinkHandlers}
+ renderImage={props.renderMarkdownImage}
+ />
+ </MarkdownImageAvailableWidthContext>
+ ) : null}
+ </View>
+ ) : null}
+ </View>
+ ) : null}
{bubbleBodyVisible ? (
<View className="mt-1 flex-row items-center justify-end gap-1 pr-0.5">
{foldRowId !== null && message.senderThreadId ? (
@@ -2830,6 +3156,12 @@ export const ThreadFeed = memo(function ThreadFeed({
const setupAnchorIndex = presentedFeed.findIndex(
(entry) => entry.type === "message" && entry.message.role === "user",
);
+ const [groupFeed] = useState(createThreadFeedGrouping);
+ const groupedFeed = groupFeed(presentedFeed, {
+ workflowOpeningMessageId: workflowOpening?.messageId,
+ setupAnchorIndex:
+ props.worktreeSetup || props.setupWorkingStartedAt ? setupAnchorIndex : undefined,
+ });
// The empty↔filled key below remounts the list and resets its imperative
// content-inset override. Seed each fresh instance as it attaches with the
// current overlay height before the scroll integration's next reaction;
@@ -3149,7 +3481,7 @@ export const ThreadFeed = memo(function ThreadFeed({
}
}, [textSizeKey, contentWidth, hasHtmlRenders, beginReflow, listRef]);
- const renderItem = (info: { item: ThreadFeedRow; index: number }) => (
+ const renderItem = (info: { item: GroupedThreadFeedRow; index: number }) => (
<Animated.View
key={info.item.id}
entering={disclosureToggleSettling ? THREAD_FEED_DISCLOSURE_ENTER_TRANSITION : undefined}
@@ -3162,6 +3494,7 @@ export const ThreadFeed = memo(function ThreadFeed({
>
<ThreadMediaVisibility>
{renderFeedEntry(info, {
+ userMessageGrouping: info.item.userMessageGrouping,
environmentId: props.environmentId,
dispatchingMessageId: props.dispatchingMessageId,
onEditPendingMessage: props.onEditPendingMessage,
@@ -3284,7 +3617,7 @@ export const ThreadFeed = memo(function ThreadFeed({
maintainVisibleContentPosition={
followsEnd && !disclosureToggleSettling ? false : maintainVisibleContentPosition
}
- data={presentedFeed}
+ data={groupedFeed}
extraData={listAppearanceData}
renderItem={renderItem}
viewabilityConfig={THREAD_MEDIA_VIEWABILITY_CONFIG}
@@ -3422,7 +3755,7 @@ function MessageImageGalleryScope(props: {
entry.type === "message"
? [
...messageImageGallery(entry.message, { environmentId, threadId, workspaceRoot }),
- ...composerImageGallery(entry.pendingMessage?.attachments ?? []),
+ ...composerImageGallery(entry.pendingMessage?.attachments ?? [], environmentId),
]
: [];
return <FilePreviewGallery value={images}>{props.children}</FilePreviewGallery>;
diff --git a/apps/mobile/src/features/threads/ThreadMarkdownVideo.tsx b/apps/mobile/src/features/threads/ThreadMarkdownVideo.tsx
index 5f4b5ec263d..457b7878ea5 100644
--- a/apps/mobile/src/features/threads/ThreadMarkdownVideo.tsx
+++ b/apps/mobile/src/features/threads/ThreadMarkdownVideo.tsx
@@ -13,6 +13,7 @@ export function ThreadMarkdownVideo(props: {
readonly source: MediaVideoPreviewSource;
readonly thumbnailVisible?: boolean;
readonly onPlaybackStart?: () => void;
+ readonly borderRadius?: number;
}) {
const { source } = props;
const feedVisible = useContext(ThreadMediaVisibleContext);
@@ -43,6 +44,7 @@ export function ThreadMarkdownVideo(props: {
onPlaybackStart={props.onPlaybackStart}
unavailable={"resource" in source && asset._tag === "Failure"}
actionsSource={source.actionsSource}
+ borderRadius={props.borderRadius}
/>
);
}
diff --git a/apps/mobile/src/features/threads/pending-thread-feed.test.ts b/apps/mobile/src/features/threads/pending-thread-feed.test.ts
index 3d9463c79bd..b16fab3a20a 100644
--- a/apps/mobile/src/features/threads/pending-thread-feed.test.ts
+++ b/apps/mobile/src/features/threads/pending-thread-feed.test.ts
@@ -10,6 +10,7 @@ import {
import type { QueuedThreadMessage } from "../../state/thread-outbox-model";
import {
appendPendingThreadMessages,
+ createThreadFeedGrouping,
isCompactionCommandFeedEntry,
selectPendingAcknowledgedMessages,
} from "./pending-thread-feed";
@@ -25,6 +26,71 @@ const pending = (id: string): QueuedThreadMessage => ({
});
describe("pending timeline messages", () => {
+ it("keeps unchanged row identities while text streams and updates adjacent grouping", () => {
+ const group = createThreadFeedGrouping();
+ const [first, second, third] = appendPendingThreadMessages(
+ [],
+ [],
+ [pending("first"), pending("second"), pending("third")],
+ );
+ if (first?.type !== "message" || second?.type !== "message" || third?.type !== "message") {
+ throw new Error("Expected message rows");
+ }
+ const reply = {
+ ...third,
+ id: "reply",
+ message: { ...third.message, role: "assistant" as const, text: "start" },
+ };
+ const initial = group([first, second, reply], {});
+ const streamed = group(
+ [first, second, { ...reply, message: { ...reply.message, text: "streamed" } }],
+ {},
+ );
+ expect(streamed[0]).toBe(initial[0]);
+ expect(streamed[1]).toBe(initial[1]);
+ expect(streamed[2]).not.toBe(initial[2]);
+ const appended = group([first, second, third, reply], {});
+ expect(appended[0]).toBe(initial[0]);
+ expect(appended[1]).not.toBe(initial[1]);
+ expect(appended[1]?.userMessageGrouping.groupedWithNext).toBe(true);
+ expect(appended[2]?.userMessageGrouping.groupedWithPrevious).toBe(true);
+ const removed = group([first, second, reply], {});
+ expect(removed[1]?.userMessageGrouping.groupedWithNext).toBe(false);
+ const steer = {
+ ...second,
+ message: { ...second.message, inputIntent: "promoted_queued_to_steer" as const },
+ };
+ const singleSteer = group([first, steer], {});
+ const steers = group(
+ [{ ...first, message: { ...first.message, inputIntent: "steer" } }, steer],
+ {},
+ );
+ expect(steers[1]?.userMessageGrouping.continuesSteer).toBe(true);
+ expect(singleSteer[1]?.userMessageGrouping.continuesSteer).toBe(false);
+ expect(steers[1]).not.toBe(singleSteer[1]);
+ });
+
+ it("preserves setup, workflow, and compaction grouping boundaries", () => {
+ const group = createThreadFeedGrouping();
+ const feed = appendPendingThreadMessages([], [], [pending("first"), pending("second")]);
+ expect(group(feed, {})[0]?.userMessageGrouping.groupedWithNext).toBe(true);
+ for (const options of [{ setupAnchorIndex: 0 }, { workflowOpeningMessageId: "first" }]) {
+ const rows = group(feed, options);
+ expect(rows[0]?.userMessageGrouping.groupedWithNext).toBe(false);
+ expect(rows[1]?.userMessageGrouping.groupedWithPrevious).toBe(false);
+ }
+ const compact = appendPendingThreadMessages(
+ [],
+ [],
+ [{ ...pending("compact"), text: "/compact" }],
+ )[0]!;
+ expect(group([feed[0]!, compact], {})[0]?.userMessageGrouping.groupedWithNext).toBe(true);
+ expect(
+ group([feed[0]!, { ...compact, pendingMessage: undefined }], {})[0]?.userMessageGrouping
+ .groupedWithNext,
+ ).toBe(false);
+ });
+
it.each([false, true])(
"keeps a queued compact command in the pending message row (attachment: %s)",
(withAttachment) => {
diff --git a/apps/mobile/src/features/threads/pending-thread-feed.ts b/apps/mobile/src/features/threads/pending-thread-feed.ts
index d38cc026fdd..586f8ff3b88 100644
--- a/apps/mobile/src/features/threads/pending-thread-feed.ts
+++ b/apps/mobile/src/features/threads/pending-thread-feed.ts
@@ -6,6 +6,7 @@ import {
import type { ThreadFeedEntry } from "../../lib/threadActivity";
import { scopedThreadKey } from "../../lib/scopedEntities";
import { threadHasCaughtUpTo } from "@t3tools/client-runtime/state/threads";
+import { resolveUserMessageGrouping } from "@t3tools/client-runtime/user-message";
import type {
AcknowledgedThreadMessage,
QueuedThreadMessage,
@@ -53,6 +54,50 @@ export function selectPendingAcknowledgedMessages(
/** A row of the thread feed's list. */
export type ThreadFeedRow = PendingThreadFeedEntry | GuestPendingFeedEntry;
+export type GroupedThreadFeedRow = ThreadFeedRow & {
+ readonly userMessageGrouping: ReturnType<typeof resolveUserMessageGrouping>;
+};
+
+export function createThreadFeedGrouping() {
+ const rows = new WeakMap<ThreadFeedRow, GroupedThreadFeedRow>();
+ const ungrouped = resolveUserMessageGrouping(undefined, undefined, undefined);
+ return (
+ feed: ReadonlyArray<ThreadFeedRow>,
+ options: { readonly workflowOpeningMessageId?: string; readonly setupAnchorIndex?: number },
+ ): ReadonlyArray<GroupedThreadFeedRow> => {
+ const groupingMessage = (index: number) => {
+ const entry = feed[index];
+ return entry?.type === "message" &&
+ entry.message.role === "user" &&
+ !isCompactionCommandFeedEntry(entry) &&
+ entry.message.id !== options.workflowOpeningMessageId
+ ? entry.message
+ : undefined;
+ };
+ return feed.map((entry, index) => {
+ const message = groupingMessage(index);
+ const grouping =
+ message === undefined
+ ? ungrouped
+ : resolveUserMessageGrouping(
+ message,
+ index - 1 === options.setupAnchorIndex ? undefined : groupingMessage(index - 1),
+ index === options.setupAnchorIndex ? undefined : groupingMessage(index + 1),
+ );
+ const previous = rows.get(entry);
+ if (
+ previous?.userMessageGrouping.groupedWithPrevious === grouping.groupedWithPrevious &&
+ previous.userMessageGrouping.groupedWithNext === grouping.groupedWithNext &&
+ previous.userMessageGrouping.continuesSteer === grouping.continuesSteer
+ )
+ return previous;
+ const row = { ...entry, userMessageGrouping: grouping };
+ rows.set(entry, row);
+ return row;
+ });
+ };
+}
+
/** Waiting guest messages go after the transcript, oldest first. */
export function appendGuestPendingMessages(
presentedFeed: ReadonlyArray<PendingThreadFeedEntry>,
diff --git a/apps/mobile/src/lib/composerImageGallery.ts b/apps/mobile/src/lib/composerImageGallery.ts
index 3df558ae5d4..f308dac2ff1 100644
--- a/apps/mobile/src/lib/composerImageGallery.ts
+++ b/apps/mobile/src/lib/composerImageGallery.ts
@@ -1,12 +1,29 @@
import { imageMimeType } from "@t3tools/shared/image";
+import type { EnvironmentId } from "@t3tools/contracts";
import type { FilePreviewItem } from "../components/FilePreviewModal.types";
import { isFileBackedComposerAttachment, type DraftComposerAttachment } from "./composerImages";
export function composerImageGallery(
attachments: readonly DraftComposerAttachment[],
+ environmentId?: EnvironmentId,
): FilePreviewItem[] {
return attachments.flatMap((attachment): FilePreviewItem[] => {
if (attachment.type !== "image" && imageMimeType(attachment) === null) return [];
+ if (environmentId !== undefined && attachment.uploadedAttachmentId) {
+ return [
+ {
+ kind: "image",
+ name: attachment.name,
+ environmentId,
+ resource: {
+ _tag: "attachment",
+ attachmentId: attachment.uploadedAttachmentId,
+ fileName: attachment.name,
+ mimeType: attachment.mimeType,
+ },
+ },
+ ];
+ }
if (isFileBackedComposerAttachment(attachment)) {
return [{ kind: "image", name: attachment.name, attachment }];
}
diff --git a/apps/mobile/src/lib/filePreviewGallery.test.ts b/apps/mobile/src/lib/filePreviewGallery.test.ts
index 95d52e5a7fe..60576317b95 100644
--- a/apps/mobile/src/lib/filePreviewGallery.test.ts
+++ b/apps/mobile/src/lib/filePreviewGallery.test.ts
@@ -1,9 +1,72 @@
-import { describe, expect, it } from "vite-plus/test";
-import { EnvironmentId } from "@t3tools/contracts";
+import { describe, expect, it, vi } from "vite-plus/test";
+import { EnvironmentId, ThreadId } from "@t3tools/contracts";
import type { FilePreviewItem } from "../components/FilePreviewModal.types";
+import type { DraftComposerAttachment } from "./composerImages";
+import { composerImageGallery } from "./composerImageGallery";
+import { messageImageGallery } from "../features/threads/messageImageGallery";
import { filePreviewGallery, filePreviewKey } from "./filePreviewGallery";
+vi.mock("./uuid", () => ({}));
+
describe("image preview groups", () => {
+ it.each([false, true])(
+ "keeps one entry per image through upload and delivery (file: %s)",
+ (fileBacked) => {
+ const environmentId = EnvironmentId.make("test");
+ const context = { environmentId, threadId: ThreadId.make("thread"), workspaceRoot: null };
+ const attachments: DraftComposerAttachment[] = ["a", "b"].map((id) => ({
+ id,
+ type: "image",
+ name: `${id}.png`,
+ mimeType: "image/png",
+ sizeBytes: 3,
+ previewUri: `data:image/png;base64,${id}`,
+ ...(fileBacked ? { fileUri: `file:///documents/${id}.png` } : {}),
+ }));
+ const delivered = (id: string) =>
+ messageImageGallery(
+ {
+ text: "",
+ attachments: [
+ {
+ type: "image",
+ id: `uploaded-${id}`,
+ name: `${id}.png`,
+ mimeType: "image/png",
+ sizeBytes: 3,
+ },
+ ],
+ },
+ context,
+ )[0]!;
+ const local = composerImageGallery(attachments, environmentId);
+ const uploading = composerImageGallery(
+ [{ ...attachments[0]!, uploadedAttachmentId: "uploaded-a" }, attachments[1]!],
+ environmentId,
+ );
+ const uploaded = composerImageGallery(
+ attachments.map((attachment) => ({
+ ...attachment,
+ uploadedAttachmentId: `uploaded-${attachment.id}`,
+ })),
+ environmentId,
+ );
+ for (const [selected, gallery] of [
+ [local[0]!, local],
+ [delivered("a"), uploading],
+ [uploading[1]!, uploading],
+ [delivered("a"), uploaded],
+ [delivered("a"), [...uploaded, delivered("a"), delivered("b")]],
+ [delivered("a"), [delivered("a"), delivered("b")]],
+ ] as const) {
+ const result = filePreviewGallery(selected, gallery);
+ expect(result).toHaveLength(2);
+ expect(result.map(filePreviewKey)).toEqual([...new Set(gallery.map(filePreviewKey))]);
+ }
+ expect(composerImageGallery(attachments)).toEqual(local);
+ },
+ );
+
it("matches remote originals despite metadata and property order differences", () => {
const environmentId = EnvironmentId.make("test");
const a: FilePreviewItem = {
diff --git a/packages/client-runtime/src/userMessage.test.ts b/packages/client-runtime/src/userMessage.test.ts
index 207939cf2f3..44529f6c145 100644
--- a/packages/client-runtime/src/userMessage.test.ts
+++ b/packages/client-runtime/src/userMessage.test.ts
@@ -1,9 +1,157 @@
import { describe, expect, it } from "vite-plus/test";
-import { GuestMessageId } from "@t3tools/contracts";
+import { ComposerContextId, GuestMessageId, ScheduledTaskId } from "@t3tools/contracts";
import { ATTACHMENT_ONLY_BOOTSTRAP_PROMPT } from "@t3tools/shared/composerContextReferences";
-import { resolveUserMessagePresentation } from "./userMessage.ts";
+import {
+ resolveUserMessageFileCards,
+ resolveUserMessageGrouping,
+ resolveUserMessagePresentation,
+} from "./userMessage.ts";
+
+describe("resolveUserMessageGrouping", () => {
+ const own = { role: "user", text: "hello" };
+
+ it("groups only adjacent own messages", () => {
+ expect(resolveUserMessageGrouping(own, own, own)).toEqual({
+ groupedWithPrevious: true,
+ groupedWithNext: true,
+ continuesSteer: false,
+ });
+ expect(resolveUserMessageGrouping(own, undefined, own)).toMatchObject({
+ groupedWithPrevious: false,
+ groupedWithNext: true,
+ });
+ for (const boundary of [
+ undefined,
+ { ...own, role: "assistant" },
+ { ...own, createdBy: "agent" as const },
+ { ...own, createdBy: "agent" as const, creationSource: "server" as const },
+ { ...own, scheduledTaskId: ScheduledTaskId.make("task") },
+ {
+ ...own,
+ context: {
+ guest: { guestMessageId: GuestMessageId.make("guest"), name: "Sam", text: "hi" },
+ },
+ },
+ ]) {
+ expect(resolveUserMessageGrouping(own, boundary, boundary)).toEqual({
+ groupedWithPrevious: false,
+ groupedWithNext: false,
+ continuesSteer: false,
+ });
+ expect(resolveUserMessageGrouping(boundary, own, own)).toEqual({
+ groupedWithPrevious: false,
+ groupedWithNext: false,
+ continuesSteer: false,
+ });
+ }
+ });
+
+ it("shows one label for consecutive steers, including promoted queued messages", () => {
+ for (const inputIntent of ["steer", "promoted_queued_to_steer"] as const) {
+ const steer = { ...own, inputIntent };
+ expect(
+ resolveUserMessageGrouping(steer, { ...own, inputIntent: "steer" }, undefined)
+ .continuesSteer,
+ ).toBe(true);
+ expect(
+ resolveUserMessageGrouping(
+ steer,
+ { ...own, inputIntent: "promoted_queued_to_steer" },
+ undefined,
+ ).continuesSteer,
+ ).toBe(true);
+ expect(resolveUserMessageGrouping(steer, own, undefined).continuesSteer).toBe(false);
+ expect(resolveUserMessageGrouping(own, steer, undefined).continuesSteer).toBe(false);
+ }
+ });
+});
+
+describe("resolveUserMessageFileCards", () => {
+ const file = {
+ type: "file" as const,
+ id: "report",
+ name: "report.pdf",
+ mimeType: "application/pdf",
+ sizeBytes: 1024,
+ };
+ const record = {
+ ...file,
+ version: 1 as const,
+ kind: "file" as const,
+ contextId: ComposerContextId.make("report"),
+ label: file.name,
+ attachmentId: file.id,
+ };
+ const context = { version: 1 as const, records: [record] };
+ const reference = "[report.pdf](t3-context://v1/file/report)";
+
+ it("shows file cards for bare attachments and bound file references", () => {
+ for (const text of ["", " \n", reference]) {
+ expect(resolveUserMessageFileCards({ text, attachments: [file], context })).toEqual([file]);
+ }
+ expect(
+ resolveUserMessageFileCards({
+ text: `${reference}\n${reference}`,
+ attachments: [file],
+ context,
+ }),
+ ).toEqual([file]);
+ });
+
+ it("keeps words and unavailable or non-file references in the bubble", () => {
+ for (const text of [
+ `read ${reference}`,
+ "[missing.pdf](t3-context://v1/file/missing)",
+ "[report.pdf](t3-context://v1/mention/report)",
+ ]) {
+ expect(resolveUserMessageFileCards({ text, attachments: [file], context })).toBeNull();
+ }
+ expect(resolveUserMessageFileCards({ text: reference, attachments: [file] })).toBeNull();
+ expect(
+ resolveUserMessageFileCards({
+ text: reference,
+ attachments: [file],
+ context: {
+ version: 1,
+ records: [
+ {
+ version: 1,
+ kind: "file",
+ contextId: record.contextId,
+ label: file.name,
+ payload: {},
+ },
+ ],
+ },
+ }),
+ ).toBeNull();
+ expect(
+ resolveUserMessageFileCards({
+ text: reference,
+ attachments: [{ ...file, id: "other" }],
+ context,
+ }),
+ ).toBeNull();
+ });
+
+ it("keeps media, unknown attachments, and empty messages out of the file cards", () => {
+ const media = [
+ { ...file, type: "image" as const, name: "photo.png", mimeType: "image/png" },
+ { ...file, name: "photo.png", mimeType: "application/octet-stream" },
+ { ...file, name: "clip.mp4", mimeType: "video/mp4" },
+ { ...file, name: "clip.mov", mimeType: "application/octet-stream" },
+ { ...file, name: "voice.mp3", mimeType: "audio/mpeg" },
+ { ...file, type: "future" },
+ ];
+ expect(resolveUserMessageFileCards({ text: "", attachments: [] })).toBeNull();
+ for (const attachment of media) {
+ expect(resolveUserMessageFileCards({ text: "", attachments: [attachment] })).toBeNull();
+ expect(resolveUserMessageFileCards({ text: "", attachments: [file, attachment] })).toBeNull();
+ }
+ });
+});
describe("resolveUserMessagePresentation", () => {
const legacyText = "[Triggered by schedule task: Daily audit]\n\nCheck for crashes.\n";
diff --git a/packages/client-runtime/src/userMessage.ts b/packages/client-runtime/src/userMessage.ts
index 8a80f31b155..a860c0188b9 100644
--- a/packages/client-runtime/src/userMessage.ts
+++ b/packages/client-runtime/src/userMessage.ts
@@ -1,11 +1,21 @@
import {
+ type ChatAttachment,
+ type ChatFileAttachment,
type GuestMessageAttribution,
+ type OrchestrationMessageContext,
type OrchestrationV2Actor,
type OrchestrationV2CreationSource,
type OrchestrationV2IdleCompaction,
+ type OrchestrationV2UserMessageInputIntent,
ScheduledTaskId,
} from "@t3tools/contracts";
-import { isAttachmentOnlyBootstrapPrompt } from "@t3tools/shared/composerContextReferences";
+import {
+ isAttachmentOnlyBootstrapPrompt,
+ replaceComposerContextReferences,
+} from "@t3tools/shared/composerContextReferences";
+import { filePreviewKind } from "@t3tools/shared/filePreview";
+import { imageMimeType } from "@t3tools/shared/image";
+import { videoMimeType } from "@t3tools/shared/video";
/** The working row while T3 Code's own compaction runs. */
export const IDLE_COMPACTING_LABELS = {
@@ -22,6 +32,32 @@ export const IDLE_COMPACTION_TITLES = {
const LEGACY_AUTOMATION_PREFIX = /^\[Triggered by schedule task: [^\r\n]+\]\r?\n\r?\n/;
const LEGACY_AUTOMATION_MESSAGE_ID = /^scheduled-task-message:(.+):\d+:(?:scheduled|manual)$/;
+export function resolveUserMessageFileCards(message: {
+ readonly text: string;
+ readonly attachments: ReadonlyArray<ChatAttachment>;
+ readonly context?: OrchestrationMessageContext | undefined;
+}): ReadonlyArray<ChatFileAttachment> | null {
+ const files = message.attachments.filter(
+ (attachment): attachment is ChatFileAttachment =>
+ attachment.type === "file" &&
+ imageMimeType(attachment) === null &&
+ videoMimeType(attachment) === null &&
+ filePreviewKind(attachment) !== "audio",
+ );
+ if (files.length === 0 || files.length !== message.attachments.length) return null;
+ const fileIds = new Set(files.map((file) => file.id));
+ const remaining = replaceComposerContextReferences(message.text, (reference) => {
+ const record = message.context?.records.find((item) => item.contextId === reference.contextId);
+ return reference.kind === "file" &&
+ record?.kind === "file" &&
+ "attachmentId" in record &&
+ fileIds.has(record.attachmentId)
+ ? ""
+ : reference.label || reference.kind;
+ });
+ return remaining.trim() === "" ? files : null;
+}
+
export function resolveUserMessagePresentation(message: {
readonly id?: string;
readonly role: string;
@@ -80,3 +116,24 @@ export function resolveUserMessagePresentation(message: {
scheduledTaskId: undefined,
};
}
+
+type GroupableUserMessage = Parameters<typeof resolveUserMessagePresentation>[0] & {
+ readonly inputIntent?: OrchestrationV2UserMessageInputIntent;
+};
+
+export function resolveUserMessageGrouping(
+ message: GroupableUserMessage | undefined,
+ previous: GroupableUserMessage | undefined,
+ next: GroupableUserMessage | undefined,
+) {
+ const isOwnMessage = (value: GroupableUserMessage | undefined) =>
+ value?.role === "user" && resolveUserMessagePresentation(value).attribution === null;
+ const isSteer = (value: GroupableUserMessage | undefined) =>
+ value?.inputIntent === "steer" || value?.inputIntent === "promoted_queued_to_steer";
+ const groupedWithPrevious = isOwnMessage(message) && isOwnMessage(previous);
+ return {
+ groupedWithPrevious,
+ groupedWithNext: isOwnMessage(message) && isOwnMessage(next),
+ continuesSteer: groupedWithPrevious && isSteer(message) && isSteer(previous),
+ };
+}