Compare commits

..
Author SHA1 Message Date
Cursor AgentandJulius Marminge 40624c1a71 Use typed file system override in browse test
Co-authored-by: Julius Marminge <[email protected]>
2026-06-23 16:12:45 +00:00
Cursor AgentandJulius Marminge 5a994cd866 Format workspace entries browse filter
Co-authored-by: Julius Marminge <[email protected]>
2026-06-23 16:11:10 +00:00
Cursor AgentandJulius Marminge 4c853e3714 Fix workspace browse file system mock
Co-authored-by: Julius Marminge <[email protected]>
2026-06-23 16:10:33 +00:00
Cursor AgentandJulius Marminge 7e7a18de0c Use Effect file system in workspace services
Co-authored-by: Julius Marminge <[email protected]>
2026-06-23 16:08:14 +00:00
27 changed files with 549 additions and 781 deletions

No files matched your search

+3 -3
View File
@@ -44,7 +44,7 @@
"@effect/atom-react": "catalog:",
"@expo-google-fonts/dm-sans": "^0.4.2",
"@expo/ui": "~56.0.8",
"@legendapp/list": "3.2.0",
"@legendapp/list": "3.0.0-beta.44",
"@noble/curves": "catalog:",
"@noble/hashes": "catalog:",
"@pierre/diffs": "catalog:",
@@ -93,9 +93,9 @@
"react-native": "0.85.3",
"react-native-gesture-handler": "~2.31.1",
"react-native-image-viewing": "^0.2.2",
"react-native-keyboard-controller": "1.21.7",
"react-native-keyboard-controller": "1.21.6",
"react-native-nitro-markdown": "^0.5.0",
"react-native-nitro-modules": "0.35.9",
"react-native-nitro-modules": "^0.35.4",
"react-native-reanimated": "4.3.1",
"react-native-safe-area-context": "~5.7.0",
"react-native-screens": "4.25.2",
@@ -1,7 +1,6 @@
import { isLiquidGlassSupported, LiquidGlassView } from "@callstack/liquid-glass";
import type {
EnvironmentId,
MessageId,
ModelSelection,
OrchestrationThreadShell,
ProviderInteractionMode,
@@ -92,7 +91,7 @@ export interface ThreadComposerProps {
readonly onNativePasteImages: (uris: ReadonlyArray<string>) => Promise<void>;
readonly onRemoveDraftImage: (imageId: string) => void;
readonly onStopThread: () => void;
readonly onSendMessage: () => Promise<MessageId | null>;
readonly onSendMessage: () => Promise<void>;
readonly onUpdateModelSelection: (modelSelection: ModelSelection) => void;
readonly onUpdateRuntimeMode: (runtimeMode: RuntimeMode) => void;
readonly onUpdateInteractionMode: (interactionMode: ProviderInteractionMode) => void;
@@ -448,7 +447,9 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
const { onChangeDraftMessage, onUpdateInteractionMode, draftMessage, onSendMessage } = props;
const handleSend = useCallback(() => {
void onSendMessage();
void onSendMessage().then(() => {
inputRef.current?.blur();
});
}, [onSendMessage]);
const handleCommandSelect = useCallback(
(item: ComposerCommandItem) => {
@@ -1,10 +1,7 @@
import { type EnvironmentConnectionPhase } from "@t3tools/client-runtime/connection";
import { useKeyboardChatComposerInset, useKeyboardScrollToEnd } from "@legendapp/list/keyboard";
import type { LegendListRef } from "@legendapp/list/react-native";
import type {
ApprovalRequestId,
EnvironmentId,
MessageId,
ModelSelection,
OrchestrationThreadShell,
ProviderApprovalDecision,
@@ -16,8 +13,8 @@ import type {
import { formatElapsed } from "@t3tools/shared/orchestrationTiming";
import * as Haptics from "expo-haptics";
import { useHeaderHeight } from "expo-router/build/react-navigation/elements";
import { memo, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
import { View, type GestureResponderEvent } from "react-native";
import { memo, useCallback, useEffect, useMemo, useRef, useState } from "react";
import { View, type GestureResponderEvent, type LayoutChangeEvent } from "react-native";
import { Gesture, GestureDetector } from "react-native-gesture-handler";
import { KeyboardStickyView } from "react-native-keyboard-controller";
import { useSafeAreaInsets } from "react-native-safe-area-context";
@@ -28,7 +25,7 @@ import type { ComposerEditorHandle } from "../../components/ComposerEditor";
import type { StatusTone } from "../../components/StatusPill";
import type { DraftComposerImageAttachment } from "../../lib/composerImages";
import type { LayoutVariant } from "../../lib/layout";
import { scopedThreadKey } from "../../lib/scopedEntities";
import { resolveThreadFeedBottomInset } from "../../lib/threadFeedLayout";
import type {
PendingApproval,
PendingUserInput,
@@ -76,7 +73,7 @@ export interface ThreadDetailScreenProps {
readonly onNativePasteImages: (uris: ReadonlyArray<string>) => Promise<void>;
readonly onRemoveDraftImage: (imageId: string) => void;
readonly onStopThread: () => void;
readonly onSendMessage: () => Promise<MessageId | null>;
readonly onSendMessage: () => Promise<void>;
readonly onReconnectEnvironment: () => void;
readonly onUpdateThreadModelSelection: (modelSelection: ModelSelection) => void;
readonly onUpdateThreadRuntimeMode: (runtimeMode: RuntimeMode) => void;
@@ -209,33 +206,25 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
const insets = useSafeAreaInsets();
const headerHeight = useHeaderHeight();
const agentLabel = `${props.selectedThread.modelSelection.instanceId} agent`;
const selectedThreadKey = scopedThreadKey(props.environmentId, props.selectedThread.id);
const composerEditorRef = useRef<ComposerEditorHandle>(null);
const composerOverlayRef = useRef<View>(null);
const listRef = useRef<LegendListRef>(null);
const composerRef = useRef<ComposerEditorHandle>(null);
const feedTouchStartRef = useRef<{ pageX: number; pageY: number } | null>(null);
const selectedThreadKeyRef = useRef(selectedThreadKey);
const lastScrolledAnchorMessageIdRef = useRef<MessageId | null>(null);
const [composerExpanded, setComposerExpanded] = useState(false);
const [anchorMessageId, setAnchorMessageId] = useState<MessageId | null>(null);
const composerBottomInset = composerExpanded ? 0 : Math.max(insets.bottom, 12);
const contentPresentationKind = props.contentPresentation.kind;
const selectedThreadFeed = props.selectedThreadFeed;
const composerChrome = composerExpanded ? COMPOSER_EXPANDED_CHROME : COMPOSER_COLLAPSED_CHROME;
const composerOverlapHeight = composerChrome + composerBottomInset;
const activeWorkIndicatorHeight = props.activeWorkStartedAt ? WORKING_INDICATOR_HEIGHT : 0;
const estimatedOverlayHeight = composerOverlapHeight + activeWorkIndicatorHeight + 8;
const { contentInsetEndAdjustment, onComposerLayout } = useKeyboardChatComposerInset(
listRef,
composerOverlayRef,
estimatedOverlayHeight,
);
const { freeze, scrollMessageToEnd } = useKeyboardScrollToEnd({ listRef });
const estimatedOverlayHeight = composerOverlapHeight + activeWorkIndicatorHeight;
const [measuredOverlayHeight, setMeasuredOverlayHeight] = useState(0);
const showContent = props.showContent ?? true;
const layoutVariant = props.layoutVariant ?? "compact";
const isSplitLayout = layoutVariant === "split";
const selectedInstanceId = props.selectedThread.modelSelection.instanceId;
useStreamingHaptics(props.selectedThread.id, props.selectedThreadFeed);
const feedBottomInset = resolveThreadFeedBottomInset({
estimatedOverlayHeight,
measuredOverlayHeight,
gap: 8,
});
const selectedProviderSkills = useMemo(
() =>
props.serverConfig?.providers.find((provider) => provider.instanceId === selectedInstanceId)
@@ -265,67 +254,15 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
[completeDrawerGesture, isSplitLayout],
);
useLayoutEffect(() => {
selectedThreadKeyRef.current = selectedThreadKey;
}, [selectedThreadKey]);
useEffect(() => {
setAnchorMessageId(null);
lastScrolledAnchorMessageIdRef.current = null;
freeze.set(false);
}, [freeze, selectedThreadKey]);
useEffect(() => {
if (
anchorMessageId === null ||
lastScrolledAnchorMessageIdRef.current === anchorMessageId ||
contentPresentationKind !== "ready" ||
!selectedThreadFeed.some((entry) => entry.type === "message" && entry.id === anchorMessageId)
) {
return;
}
const targetThreadKey = selectedThreadKey;
const frame = requestAnimationFrame(() => {
if (selectedThreadKeyRef.current !== targetThreadKey) {
return;
}
lastScrolledAnchorMessageIdRef.current = anchorMessageId;
void scrollMessageToEnd({ animated: true, closeKeyboard: false }).catch(() => {
if (
selectedThreadKeyRef.current !== targetThreadKey ||
lastScrolledAnchorMessageIdRef.current !== anchorMessageId
) {
return;
}
lastScrolledAnchorMessageIdRef.current = null;
freeze.set(false);
});
});
return () => cancelAnimationFrame(frame);
}, [
anchorMessageId,
freeze,
contentPresentationKind,
selectedThreadFeed,
scrollMessageToEnd,
selectedThreadKey,
]);
const handleSendMessage = useCallback(async () => {
const targetThreadKey = selectedThreadKey;
const messageId = await props.onSendMessage();
if (messageId === null || selectedThreadKeyRef.current !== targetThreadKey) {
return messageId;
}
setAnchorMessageId(messageId);
composerEditorRef.current?.blur();
return messageId;
}, [props.onSendMessage, selectedThreadKey]);
const handleOverlayLayout = useCallback((event: LayoutChangeEvent) => {
const nextHeight = Math.ceil(event.nativeEvent.layout.height);
setMeasuredOverlayHeight((current) =>
Math.abs(current - nextHeight) > 1 ? nextHeight : current,
);
}, []);
const collapseComposer = useCallback(() => {
composerEditorRef.current?.blur();
composerRef.current?.blur();
}, []);
const handleFeedTouchStart = useCallback((event: GestureResponderEvent) => {
@@ -378,13 +315,10 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
contentPresentation={props.contentPresentation}
agentLabel={agentLabel}
latestTurn={props.selectedThread.latestTurn}
listRef={listRef}
freeze={freeze}
anchorMessageId={anchorMessageId}
contentInsetEndAdjustment={contentInsetEndAdjustment}
contentTopInset={headerHeight}
contentBottomInset={estimatedOverlayHeight}
contentBottomInset={feedBottomInset}
layoutVariant={layoutVariant}
composerExpanded={composerExpanded}
skills={selectedProviderSkills}
/>
</View>
@@ -398,7 +332,7 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
style={{ position: "absolute", bottom: 0, left: 0, right: 0 }}
offset={{ closed: 0, opened: 0 }}
>
<View ref={composerOverlayRef} onLayout={onComposerLayout} style={{ paddingTop: 8 }}>
<View onLayout={handleOverlayLayout}>
{props.activeWorkStartedAt ? (
<WorkingDurationPill startedAt={props.activeWorkStartedAt} />
) : null}
@@ -427,7 +361,7 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
) : null}
<ThreadComposer
editorRef={composerEditorRef}
editorRef={composerRef}
draftMessage={props.draftMessage}
draftAttachments={props.draftAttachments}
placeholder="Ask the repo agent, or run a command…"
@@ -446,7 +380,7 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
onNativePasteImages={props.onNativePasteImages}
onRemoveDraftImage={props.onRemoveDraftImage}
onStopThread={props.onStopThread}
onSendMessage={handleSendMessage}
onSendMessage={props.onSendMessage}
onReconnectEnvironment={props.onReconnectEnvironment}
onUpdateModelSelection={props.onUpdateThreadModelSelection}
onUpdateRuntimeMode={props.onUpdateThreadRuntimeMode}
+122 -62
View File
@@ -1,20 +1,10 @@
import * as Haptics from "expo-haptics";
import { KeyboardAwareLegendList } from "@legendapp/list/keyboard";
import { KeyboardAvoidingLegendList } 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 type { EnvironmentId, ThreadId, TurnId } from "@t3tools/contracts";
import { SymbolView } from "expo-symbols";
import { useRouter } from "expo-router";
import {
memo,
useCallback,
useEffect,
useMemo,
useRef,
useState,
type ReactNode,
type RefObject,
} from "react";
import { memo, useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from "react";
import {
Markdown,
type CustomRenderers,
@@ -25,6 +15,8 @@ import {
ActivityIndicator,
Image,
Linking,
type NativeScrollEvent,
type NativeSyntheticEvent,
Pressable,
ScrollView,
StyleSheet,
@@ -37,7 +29,6 @@ import {
import { TouchableOpacity } from "react-native-gesture-handler";
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 {
@@ -73,11 +64,14 @@ import {
type ThreadFeedEntry,
type ThreadFeedLatestTurn,
} from "../../lib/threadActivity";
import { isThreadFeedNearEnd } from "../../lib/threadFeedLayout";
import { relativeTime } from "../../lib/time";
import type { ThreadContentPresentation } from "./threadContentPresentation";
import { ThreadWorkLog } from "./thread-work-log";
import { useAssetUrl } from "../../state/assets";
import { resolveWorkspaceRelativeFilePath } from "../files/filePath";
const THREAD_FEED_END_THRESHOLD = 80;
const MESSAGE_TIME_FORMATTER = new Intl.DateTimeFormat(undefined, {
hour: "numeric",
minute: "2-digit",
@@ -99,13 +93,10 @@ export interface ThreadFeedProps {
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 layoutVariant?: LayoutVariant;
readonly composerExpanded?: boolean;
readonly skills?: ReadonlyArray<SelectableMarkdownSkill>;
}
@@ -821,6 +812,30 @@ function renderFeedEntry(
);
}
if (entry.type === "queued-message") {
return (
<View className="mb-5 items-end">
<View
className="max-w-[85%] gap-2 rounded-[22px] rounded-br-[6px] px-3.5 py-2.5 opacity-60"
style={{ backgroundColor: userBubbleColor }}
>
<Text className="font-sans text-base leading-[22px] text-white">
{entry.queuedMessage.text}
</Text>
{entry.queuedMessage.attachments.length > 0 ? (
<Text className="font-t3-medium text-xs text-white/75">
{entry.queuedMessage.attachments.length} image
{entry.queuedMessage.attachments.length === 1 ? "" : "s"} attached
</Text>
) : null}
</View>
<Text className="mt-1.5 px-1 text-right font-t3-medium text-xs text-neutral-600 dark:text-neutral-400">
{entry.sending ? "dispatching" : `${relativeTime(entry.createdAt)} • pending`}
</Text>
</View>
);
}
return (
<ThreadWorkLog
activities={entry.activities}
@@ -1107,12 +1122,17 @@ function ThreadFeedPlaceholder(props: {
export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
const router = useRouter();
const listRef = useRef<LegendListRef>(null);
const copyFeedbackTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const scrollFrameRef = useRef<number | null>(null);
const foldSettleFrameRef = useRef<number | null>(null);
const foldSettleSecondFrameRef = useRef<number | null>(null);
const suppressAutoFollowRef = useRef(false);
const previousLatestTurnRef = useRef(props.latestTurn);
const isNearEndRef = useRef(true);
const initialScrollReadyRef = useRef(false);
const lastContentHeightRef = useRef(0);
const { width: viewportWidth } = useWindowDimensions();
const [foldToggleSettling, setFoldToggleSettling] = useState(false);
const [interactionState, setInteractionState] = useState<{
readonly copiedRowId: string | null;
readonly expandedWorkGroups: Record<string, boolean>;
@@ -1194,16 +1214,6 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
() => deriveThreadFeedPresentation(props.feed, props.latestTurn, expandedTurnIds),
[expandedTurnIds, 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) {
@@ -1219,6 +1229,54 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
? props.latestTurn.turnId
: null;
const scrollToEnd = useCallback(() => {
if (scrollFrameRef.current !== null) {
return;
}
scrollFrameRef.current = requestAnimationFrame(() => {
scrollFrameRef.current = null;
listRef.current?.scrollToEnd({ animated: false });
});
}, []);
const onListScroll = useCallback(
(event: NativeSyntheticEvent<NativeScrollEvent> | NativeScrollEvent) => {
const scrollEvent = "nativeEvent" in event ? event.nativeEvent : event;
const { contentInset, contentOffset, contentSize, layoutMeasurement } = scrollEvent;
isNearEndRef.current = isThreadFeedNearEnd(
{
contentHeight: contentSize.height,
viewportHeight: layoutMeasurement.height,
offsetY: contentOffset.y,
bottomInset: contentInset.bottom,
},
THREAD_FEED_END_THRESHOLD,
);
},
[],
);
const onListContentSizeChange = useCallback(
(_width: number, height: number) => {
const contentGrew = height > lastContentHeightRef.current + 0.5;
lastContentHeightRef.current = height;
if (
initialScrollReadyRef.current &&
contentGrew &&
isNearEndRef.current &&
!suppressAutoFollowRef.current
) {
scrollToEnd();
}
},
[scrollToEnd],
);
const onListLoad = useCallback(() => {
initialScrollReadyRef.current = true;
}, []);
useEffect(() => {
const previous = previousLatestTurnRef.current;
previousLatestTurnRef.current = props.latestTurn;
@@ -1250,6 +1308,9 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
if (copyFeedbackTimeoutRef.current) {
clearTimeout(copyFeedbackTimeoutRef.current);
}
if (scrollFrameRef.current !== null) {
cancelAnimationFrame(scrollFrameRef.current);
}
if (foldSettleFrameRef.current !== null) {
cancelAnimationFrame(foldSettleFrameRef.current);
}
@@ -1297,7 +1358,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
}, []);
const onToggleTurnFold = useCallback((turnId: TurnId) => {
setFoldToggleSettling(true);
suppressAutoFollowRef.current = true;
if (foldSettleFrameRef.current !== null) {
cancelAnimationFrame(foldSettleFrameRef.current);
}
@@ -1315,7 +1376,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
});
foldSettleFrameRef.current = requestAnimationFrame(() => {
foldSettleSecondFrameRef.current = requestAnimationFrame(() => {
setFoldToggleSettling(false);
suppressAutoFollowRef.current = false;
foldSettleFrameRef.current = null;
foldSettleSecondFrameRef.current = null;
});
@@ -1397,60 +1458,59 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
);
}
if (props.feed.length === 0) {
return (
<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}
/>
);
}
return (
<>
<View style={{ flex: 1 }}>
<KeyboardAwareLegendList
ref={props.listRef}
<KeyboardAvoidingLegendList
ref={listRef}
key={props.threadId}
style={{ flex: 1 }}
automaticallyAdjustsScrollIndicatorInsets={false}
contentInset={{ top: 0, bottom: 0 }}
scrollIndicatorInsets={{ top: topContentInset, bottom: 0 }}
{...(anchoredEndSpace ? { anchoredEndSpace } : {})}
contentInsetEndAdjustment={props.contentInsetEndAdjustment}
freeze={props.freeze}
maintainScrollAtEnd={
foldToggleSettling
? false
: {
animated: false,
on: {
dataChange: true,
itemLayout: true,
layout: true,
},
}
}
maintainVisibleContentPosition
alignItemsAtEnd
maintainScrollAtEnd={{
animated: false,
on: {
dataChange: true,
itemLayout: true,
layout: true,
},
}}
data={presentedFeed}
extraData={listAppearanceData}
renderItem={renderItem}
keyExtractor={(entry) => entry.id}
keyExtractor={(entry) => `${entry.type}:${entry.id}`}
getItemType={(entry) =>
entry.type === "message" ? `message:${entry.message.role}` : entry.type
}
keyboardShouldPersistTaps="always"
keyboardDismissMode="none"
keyboardLiftBehavior="whenAtEnd"
estimatedItemSize={180}
initialScrollAtEnd
onContentSizeChange={onListContentSizeChange}
onLoad={onListLoad}
onScroll={onListScroll}
scrollEventThrottle={16}
ListHeaderComponent={<View style={{ height: topContentInset }} />}
contentContainerStyle={{
paddingTop: 12,
paddingBottom: bottomContentInset,
paddingHorizontal: horizontalPadding,
}}
/>
{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
+6 -6
View File
@@ -86,7 +86,7 @@ describe("buildThreadFeed", () => {
],
});
const feed = buildThreadFeed(thread);
const feed = buildThreadFeed(thread, [], null);
expect(feed).toMatchObject([
{
type: "activity-group",
@@ -144,7 +144,7 @@ describe("buildThreadFeed", () => {
],
});
const feed = buildThreadFeed(thread);
const feed = buildThreadFeed(thread, [], null);
const group = feed[0];
expect(group).toMatchObject({
@@ -209,7 +209,7 @@ describe("buildThreadFeed", () => {
],
});
const group = buildThreadFeed(thread)[0];
const group = buildThreadFeed(thread, [], null)[0];
expect(group).toMatchObject({ type: "activity-group" });
if (!group || group.type !== "activity-group") {
return;
@@ -271,7 +271,7 @@ describe("buildThreadFeed", () => {
],
});
const feed = buildThreadFeed(thread);
const feed = buildThreadFeed(thread, [], null);
const collapsed = deriveThreadFeedPresentation(feed, thread.latestTurn, new Set());
expect(collapsed.map((entry) => entry.id)).toEqual(["turn-fold:turn-1", "assistant-final"]);
expect(collapsed[0]).toMatchObject({
@@ -359,7 +359,7 @@ describe("buildThreadFeed", () => {
],
});
const feed = buildThreadFeed(thread);
const feed = buildThreadFeed(thread, [], null);
const collapsed = deriveThreadFeedPresentation(feed, thread.latestTurn, new Set());
expect(collapsed.find((entry) => entry.type === "turn-fold")).toMatchObject({
turnId: firstTurnId,
@@ -399,7 +399,7 @@ describe("buildThreadFeed", () => {
],
});
const feed = buildThreadFeed(thread);
const feed = buildThreadFeed(thread, [], null);
expect(deriveThreadFeedPresentation(feed, thread.latestTurn, new Set())).toEqual(feed);
expect(feed[0]).toMatchObject({
type: "activity-group",
+19 -1
View File
@@ -1,5 +1,6 @@
import { ApprovalRequestId, isToolLifecycleItemType } from "@t3tools/contracts";
import type {
MessageId,
OrchestrationLatestTurn,
OrchestrationThread,
OrchestrationThreadActivity,
@@ -9,6 +10,7 @@ import type {
} from "@t3tools/contracts";
import { formatDuration } from "@t3tools/shared/orchestrationTiming";
import type { QueuedThreadMessage } from "../state/thread-outbox-model";
import * as Arr from "effect/Array";
import * as Order from "effect/Order";
@@ -86,6 +88,13 @@ type RawThreadFeedEntry =
readonly createdAt: string;
readonly message: OrchestrationThread["messages"][number];
}
| {
readonly type: "queued-message";
readonly id: string;
readonly createdAt: string;
readonly queuedMessage: QueuedThreadMessage;
readonly sending: boolean;
}
| {
readonly type: "activity";
readonly id: string;
@@ -95,7 +104,7 @@ type RawThreadFeedEntry =
};
export type ThreadFeedEntry =
| Extract<RawThreadFeedEntry, { type: "message" }>
| Extract<RawThreadFeedEntry, { type: "message" | "queued-message" }>
| {
readonly type: "activity-group";
readonly id: string;
@@ -1246,6 +1255,8 @@ export function buildPendingUserInputAnswers(
export function buildThreadFeed(
thread: OrchestrationThread,
queuedMessages: ReadonlyArray<QueuedThreadMessage>,
dispatchingQueuedMessageId: MessageId | null,
options?: {
readonly loadedMessages?: ReadonlyArray<OrchestrationThread["messages"][number]>;
},
@@ -1262,6 +1273,13 @@ export function buildThreadFeed(
createdAt: message.createdAt,
message,
})),
...queuedMessages.map<RawThreadFeedEntry>((queuedMessage) => ({
type: "queued-message",
id: queuedMessage.messageId,
createdAt: queuedMessage.createdAt,
queuedMessage,
sending: queuedMessage.messageId === dispatchingQueuedMessageId,
})),
...workLogEntries
.filter((entry) => {
if (options?.loadedMessages === undefined) {
@@ -0,0 +1,32 @@
import { describe, expect, it } from "vite-plus/test";
import {
isThreadFeedNearEnd,
resolveThreadFeedBottomInset,
threadFeedDistanceFromEnd,
} from "./threadFeedLayout";
describe("thread feed layout", () => {
it("accounts for the bottom inset when measuring distance from the end", () => {
const metrics = {
contentHeight: 900,
viewportHeight: 600,
offsetY: 380,
bottomInset: 100,
};
expect(threadFeedDistanceFromEnd(metrics)).toBe(20);
expect(isThreadFeedNearEnd(metrics, 50)).toBe(true);
expect(isThreadFeedNearEnd(metrics, 10)).toBe(false);
});
it("does not double count chrome already included in the measured composer overlay", () => {
expect(
resolveThreadFeedBottomInset({
estimatedOverlayHeight: 162,
measuredOverlayHeight: 182,
gap: 8,
}),
).toBe(190);
});
});
+22
View File
@@ -0,0 +1,22 @@
export interface ThreadFeedScrollMetrics {
readonly contentHeight: number;
readonly viewportHeight: number;
readonly offsetY: number;
readonly bottomInset: number;
}
export function threadFeedDistanceFromEnd(metrics: ThreadFeedScrollMetrics): number {
return metrics.contentHeight + metrics.bottomInset - metrics.viewportHeight - metrics.offsetY;
}
export function isThreadFeedNearEnd(metrics: ThreadFeedScrollMetrics, threshold: number): boolean {
return threadFeedDistanceFromEnd(metrics) <= threshold;
}
export function resolveThreadFeedBottomInset(input: {
readonly estimatedOverlayHeight: number;
readonly measuredOverlayHeight: number;
readonly gap: number;
}): number {
return Math.max(input.estimatedOverlayHeight, input.measuredOverlayHeight) + input.gap;
}
@@ -40,6 +40,7 @@ import { useSelectedThreadDetail } from "../state/use-thread-detail";
import { useThreadSelection } from "../state/use-thread-selection";
import { enqueueThreadOutboxMessage } from "./thread-outbox";
import { useThreadOutboxMessages } from "./use-thread-outbox";
import { dispatchingQueuedMessageIdAtom } from "./use-thread-outbox-drain";
export function appendReviewCommentToDraft(input: {
readonly environmentId: EnvironmentId;
@@ -76,6 +77,7 @@ export function useThreadComposerState() {
const { selectedThread: selectedThreadShell } = useThreadSelection();
const selectedThreadDetail = useSelectedThreadDetail();
const composerDrafts = useAtomValue(composerDraftsAtom);
const dispatchingQueuedMessageId = useAtomValue(dispatchingQueuedMessageIdAtom);
const queuedMessagesByThreadKey = useThreadOutboxMessages();
useEffect(() => {
@@ -89,9 +91,17 @@ export function useThreadComposerState() {
() => (selectedThreadKey ? (queuedMessagesByThreadKey[selectedThreadKey] ?? []) : []),
[queuedMessagesByThreadKey, selectedThreadKey],
);
const selectedThreadFeed = useMemo(
() => (selectedThreadDetail ? buildThreadFeed(selectedThreadDetail) : []),
[selectedThreadDetail],
() =>
selectedThreadDetail
? buildThreadFeed(
selectedThreadDetail,
selectedThreadQueuedMessages,
dispatchingQueuedMessageId,
)
: [],
[dispatchingQueuedMessageId, selectedThreadDetail, selectedThreadQueuedMessages],
);
const selectedDraft = selectedThreadKey ? composerDrafts[selectedThreadKey] : null;
@@ -115,6 +125,7 @@ export function useThreadComposerState() {
};
}, [selectedThreadDetail, selectedThreadShell]);
const queuedSendStartedAt = selectedThreadQueuedMessages[0]?.createdAt ?? null;
const activeWorkStartedAt = useMemo(() => {
const selectedThread = selectedThreadDetail ?? selectedThreadShell;
if (!selectedThread) {
@@ -124,9 +135,14 @@ export function useThreadComposerState() {
return deriveActiveWorkStartedAt(
selectedThread.latestTurn,
selectedThreadSessionActivity,
null,
queuedSendStartedAt,
);
}, [selectedThreadDetail, selectedThreadSessionActivity, selectedThreadShell]);
}, [
queuedSendStartedAt,
selectedThreadDetail,
selectedThreadSessionActivity,
selectedThreadShell,
]);
const activeThreadBusy =
!!selectedThread &&
@@ -134,7 +150,7 @@ export function useThreadComposerState() {
const onSendMessage = useCallback(async () => {
if (!selectedThreadShell) {
return null;
return;
}
const threadKey = scopedThreadKey(selectedThreadShell.environmentId, selectedThreadShell.id);
@@ -143,16 +159,15 @@ export function useThreadComposerState() {
const text = draft.text.trim();
const attachments = draft.attachments;
if (text.length === 0 && attachments.length === 0) {
return null;
return;
}
const metadata = makeQueuedMessageMetadata();
const messageId = MessageId.make(metadata.messageId);
try {
await enqueueThreadOutboxMessage({
environmentId: selectedThreadShell.environmentId,
threadId: selectedThreadShell.id,
messageId,
messageId: MessageId.make(metadata.messageId),
commandId: CommandId.make(metadata.commandId),
text,
attachments,
@@ -162,12 +177,10 @@ export function useThreadComposerState() {
createdAt: metadata.createdAt,
});
clearComposerDraftContent(threadKey);
return messageId;
} catch (error) {
setPendingConnectionError(
error instanceof Error ? error.message : "Failed to save the queued message.",
);
return null;
}
}, [selectedThreadDetail, selectedThreadShell]);
@@ -1,8 +1,6 @@
// @effect-diagnostics nodeBuiltinImport:off
import * as NodeFSP from "node:fs/promises";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { FileFinder } from "@ff-labs/fff-node";
import { it, afterEach, describe, expect } from "@effect/vitest";
import { assert, it, afterEach, describe, expect } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
@@ -16,11 +14,6 @@ import * as VcsProcess from "../vcs/VcsProcess.ts";
import * as WorkspaceEntries from "./WorkspaceEntries.ts";
import * as WorkspacePaths from "./WorkspacePaths.ts";
vi.mock("node:fs/promises", async (importOriginal) => {
const actual = await importOriginal<typeof import("node:fs/promises")>();
return { ...actual, readdir: vi.fn(actual.readdir) };
});
const TestLayer = Layer.empty.pipe(
Layer.provideMerge(WorkspaceEntries.layer.pipe(Layer.provide(WorkspacePaths.layer))),
Layer.provideMerge(WorkspacePaths.layer),
@@ -378,16 +371,36 @@ it.layer(TestLayer, { excludeTestServices: true })("WorkspaceEntries", (it) => {
it.effect("returns an empty listing when the OS denies directory access", () =>
Effect.gen(function* () {
const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries;
const fileSystem = yield* FileSystem.FileSystem;
const cwd = yield* makeTempDir({ prefix: "t3code-workspace-browse-eacces-" });
const denied = Object.assign(new Error("EACCES: permission denied"), { code: "EACCES" });
vi.mocked(NodeFSP.readdir).mockRejectedValueOnce(denied);
const denied = PlatformError.systemError({
_tag: "PermissionDenied",
module: "FileSystem",
method: "readDirectory",
pathOrDescriptor: cwd,
description: "Test PermissionDenied readDirectory failure.",
});
const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries.pipe(
Effect.provide(
WorkspaceEntries.layer.pipe(
Layer.provide(WorkspacePaths.layer),
Layer.provide(
Layer.succeed(
FileSystem.FileSystem,
FileSystem.FileSystem.of({
...fileSystem,
readDirectory: () => Effect.fail(denied),
}),
),
),
),
),
);
const result = yield* workspaceEntries.browse({
partialPath: yield* appendSeparator(cwd),
});
expect(result).toEqual({ parentPath: cwd, entries: [] });
assert.deepEqual(result, { parentPath: cwd, entries: [] });
}),
);
});
+24 -25
View File
@@ -1,10 +1,11 @@
// @effect-diagnostics nodeBuiltinImport:off
import * as NodeFSP from "node:fs/promises";
import * as NodeOS from "node:os";
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Path from "effect/Path";
import * as RcMap from "effect/RcMap";
import * as Schema from "effect/Schema";
@@ -133,6 +134,7 @@ const resolveBrowseTarget = Effect.fn("WorkspaceEntries.resolveBrowseTarget")(fu
});
export const make = Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const workspacePaths = yield* WorkspacePaths.WorkspacePaths;
const workspaceSearchIndexes = yield* WorkspaceSearchIndex.WorkspaceSearchIndexMap;
@@ -185,37 +187,34 @@ export const make = Effect.gen(function* () {
const parentPath = endsWithSeparator ? resolvedInputPath : path.dirname(resolvedInputPath);
const prefix = endsWithSeparator ? "" : path.basename(resolvedInputPath);
const dirents = yield* Effect.tryPromise({
try: () => NodeFSP.readdir(parentPath, { withFileTypes: true }),
catch: (cause) =>
new WorkspaceEntriesReadDirectoryError({
cwd: input.cwd,
partialPath: input.partialPath,
parentPath,
cause,
}),
}).pipe(
Effect.catchIf(
(error) => {
const code = (error.cause as NodeJS.ErrnoException | undefined)?.code;
return code === "EACCES" || code === "EPERM";
},
() => Effect.succeed([]),
const entryNames = yield* fileSystem.readDirectory(parentPath).pipe(
Effect.catchTag("PlatformError", (cause) =>
cause.reason._tag === "PermissionDenied"
? Effect.succeed([])
: Effect.fail(
new WorkspaceEntriesReadDirectoryError({
cwd: input.cwd,
partialPath: input.partialPath,
parentPath,
cause,
}),
),
),
);
const showHidden = endsWithSeparator || prefix.startsWith(".");
const lowerPrefix = prefix.toLowerCase();
const entries: Array<{ readonly name: string; readonly fullPath: string }> = [];
for (const dirent of dirents) {
if (
dirent.isDirectory() &&
dirent.name.toLowerCase().startsWith(lowerPrefix) &&
(showHidden || !dirent.name.startsWith("."))
) {
for (const name of entryNames) {
if (name.toLowerCase().startsWith(lowerPrefix) && (showHidden || !name.startsWith("."))) {
const fullPath = path.join(parentPath, name);
const info = yield* fileSystem.stat(fullPath).pipe(Effect.option);
if (Option.isNone(info) || info.value.type !== "Directory") {
continue;
}
entries.push({
name: dirent.name,
fullPath: path.join(parentPath, dirent.name),
name,
fullPath,
});
}
}
@@ -1,9 +1,10 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { it, describe, expect } from "@effect/vitest";
import { assert, it, describe, expect } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Path from "effect/Path";
import * as PlatformError from "effect/PlatformError";
import * as ServerConfig from "../config.ts";
import * as VcsDriverRegistry from "../vcs/VcsDriverRegistry.ts";
@@ -185,8 +186,8 @@ it.layer(TestLayer, { excludeTestServices: true })("WorkspaceFileSystemLive", (i
operationPath: resolvedPath,
operation: "realpath-target",
});
expect(error.cause).toBeInstanceOf(Error);
expect((error.cause as NodeJS.ErrnoException).code).toBe("ENOENT");
expect(error.cause).toBeInstanceOf(PlatformError.PlatformError);
assert.equal((error.cause as PlatformError.PlatformError).reason._tag, "NotFound");
}),
);
});
@@ -1,4 +1,3 @@
// @effect-diagnostics nodeBuiltinImport:off
/**
* WorkspaceFileSystem - Effect service contract for workspace file mutations.
*
@@ -7,8 +6,6 @@
*
* @module WorkspaceFileSystem
*/
import * as NodeFSP from "node:fs/promises";
import type {
ProjectReadFileInput,
ProjectReadFileResult,
@@ -19,6 +16,7 @@ import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Path from "effect/Path";
import * as Schema from "effect/Schema";
@@ -140,30 +138,28 @@ export const make = Effect.gen(function* () {
relativePath: input.relativePath,
});
const realWorkspaceRoot = yield* Effect.tryPromise({
try: () => NodeFSP.realpath(input.cwd),
catch: (cause) =>
const toOperationError =
(
operation: WorkspaceFileSystemOperationError["operation"],
operationPath: string,
resolvedPath = target.absolutePath,
) =>
(cause: unknown) =>
new WorkspaceFileSystemOperationError({
workspaceRoot: input.cwd,
relativePath: input.relativePath,
resolvedPath: target.absolutePath,
operationPath: input.cwd,
operation: "realpath-workspace-root",
resolvedPath,
operationPath,
operation,
cause,
}),
});
const realTargetPath = yield* Effect.tryPromise({
try: () => NodeFSP.realpath(target.absolutePath),
catch: (cause) =>
new WorkspaceFileSystemOperationError({
workspaceRoot: input.cwd,
relativePath: input.relativePath,
resolvedPath: target.absolutePath,
operationPath: target.absolutePath,
operation: "realpath-target",
cause,
}),
});
});
const realWorkspaceRoot = yield* fileSystem
.realPath(input.cwd)
.pipe(Effect.mapError(toOperationError("realpath-workspace-root", input.cwd)));
const realTargetPath = yield* fileSystem
.realPath(target.absolutePath)
.pipe(Effect.mapError(toOperationError("realpath-target", target.absolutePath)));
const relativeRealPath = path.relative(realWorkspaceRoot, realTargetPath);
if (
relativeRealPath.startsWith(`..${path.sep}`) ||
@@ -178,84 +174,45 @@ export const make = Effect.gen(function* () {
});
}
return yield* Effect.acquireUseRelease(
Effect.tryPromise({
try: () => NodeFSP.open(realTargetPath, "r"),
catch: (cause) =>
new WorkspaceFileSystemOperationError({
return yield* Effect.scoped(
Effect.gen(function* () {
const handle = yield* fileSystem
.open(realTargetPath, { flag: "r" })
.pipe(Effect.mapError(toOperationError("open", realTargetPath, realTargetPath)));
const stat = yield* handle.stat.pipe(
Effect.mapError(toOperationError("stat", realTargetPath, realTargetPath)),
);
if (stat.type !== "File") {
return yield* new WorkspacePathNotFileError({
workspaceRoot: input.cwd,
relativePath: input.relativePath,
resolvedPath: realTargetPath,
operationPath: realTargetPath,
operation: "open",
cause,
}),
});
}
const byteLength = Number(stat.size);
const bytesToRead = Math.min(byteLength, PROJECT_READ_FILE_MAX_BYTES);
const fileBytes = Option.getOrElse(
yield* handle
.readAlloc(bytesToRead)
.pipe(Effect.mapError(toOperationError("read", realTargetPath, realTargetPath))),
() => new Uint8Array(0),
);
if (fileBytes.includes(0)) {
return yield* new WorkspaceBinaryFileError({
workspaceRoot: input.cwd,
relativePath: input.relativePath,
resolvedPath: realTargetPath,
});
}
return {
relativePath: target.relativePath,
contents: new TextDecoder("utf-8").decode(fileBytes),
byteLength,
truncated: byteLength > PROJECT_READ_FILE_MAX_BYTES,
};
}),
(handle) =>
Effect.gen(function* () {
const stat = yield* Effect.tryPromise({
try: () => handle.stat(),
catch: (cause) =>
new WorkspaceFileSystemOperationError({
workspaceRoot: input.cwd,
relativePath: input.relativePath,
resolvedPath: realTargetPath,
operationPath: realTargetPath,
operation: "stat",
cause,
}),
});
if (!stat.isFile()) {
return yield* new WorkspacePathNotFileError({
workspaceRoot: input.cwd,
relativePath: input.relativePath,
resolvedPath: realTargetPath,
});
}
const bytesToRead = Math.min(stat.size, PROJECT_READ_FILE_MAX_BYTES);
const buffer = Buffer.alloc(bytesToRead);
const { bytesRead } = yield* Effect.tryPromise({
try: () => handle.read(buffer, 0, bytesToRead, 0),
catch: (cause) =>
new WorkspaceFileSystemOperationError({
workspaceRoot: input.cwd,
relativePath: input.relativePath,
resolvedPath: realTargetPath,
operationPath: realTargetPath,
operation: "read",
cause,
}),
});
const fileBytes = buffer.subarray(0, bytesRead);
if (fileBytes.includes(0)) {
return yield* new WorkspaceBinaryFileError({
workspaceRoot: input.cwd,
relativePath: input.relativePath,
resolvedPath: realTargetPath,
});
}
return {
relativePath: target.relativePath,
contents: new TextDecoder("utf-8").decode(fileBytes),
byteLength: stat.size,
truncated: stat.size > PROJECT_READ_FILE_MAX_BYTES,
};
}),
(handle) =>
Effect.tryPromise({
try: () => handle.close(),
catch: (cause) =>
new WorkspaceFileSystemOperationError({
workspaceRoot: input.cwd,
relativePath: input.relativePath,
resolvedPath: realTargetPath,
operationPath: realTargetPath,
operation: "close",
cause,
}),
}),
);
});
+1 -1
View File
@@ -22,7 +22,7 @@
"@fontsource-variable/dm-sans": "^5.2.8",
"@fontsource/jetbrains-mono": "^5.2.8",
"@formkit/auto-animate": "^0.9.0",
"@legendapp/list": "3.2.0",
"@legendapp/list": "3.0.0-beta.44",
"@lexical/react": "^0.41.0",
"@pierre/diffs": "catalog:",
"@pierre/trees": "1.0.0-beta.4",
@@ -518,7 +518,7 @@ export function BranchToolbarBranchSelector({
return;
}
void branchListRef.current?.scrollToOffset?.({ offset: 0, animated: false });
branchListRef.current?.scrollToOffset?.({ offset: 0, animated: false });
}, [deferredTrimmedBranchQuery, isBranchMenuOpen]);
useEffect(() => {
@@ -628,7 +628,7 @@ export function BranchToolbarBranchSelector({
if (!isBranchMenuOpen || eventDetails.index < 0 || eventDetails.reason !== "keyboard") {
return;
}
void branchListRef.current?.scrollIndexIntoView?.({
branchListRef.current?.scrollIndexIntoView?.({
index: eventDetails.index,
animated: false,
});
@@ -696,13 +696,6 @@ export function BranchToolbarBranchSelector({
ref={branchListRef}
data={filteredBranchPickerItems}
keyExtractor={(item) => item}
getItemType={(item) =>
item === checkoutPullRequestItemValue
? "checkout-pull-request"
: item === createBranchItemValue
? "create-branch"
: "branch"
}
renderItem={({ item, index }) => renderPickerItem(item, index)}
estimatedItemSize={28}
drawDistance={336}
+3 -7
View File
@@ -54,7 +54,7 @@ import { resolveDiffThemeName, type DiffThemeName } from "../lib/diffRendering";
import { fnv1a32 } from "../lib/diffRendering";
import { LRUCache } from "../lib/lruCache";
import { useTheme } from "../hooks/useTheme";
import { getClientSettings } from "../hooks/useSettings";
import { useClientSettings } from "../hooks/useSettings";
import {
chatMarkdownClipboardPayload,
serializeTableElementToCsv,
@@ -293,14 +293,10 @@ function getHighlighterPromise(language: string): Promise<DiffsHighlighter> {
return promise;
}
function readInitialWordWrapSetting(): boolean {
return getClientSettings().wordWrap;
}
function MarkdownTable({ children, ...props }: React.ComponentProps<"table">) {
const containerRef = useRef<HTMLDivElement | null>(null);
const tableRef = useRef<HTMLTableElement | null>(null);
const [expanded, setExpanded] = useState(readInitialWordWrapSetting);
const [expanded, setExpanded] = useState(useClientSettings((settings) => settings.wordWrap));
const [copied, setCopied] = useState(false);
const copiedTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const expandLabel = expanded ? "Collapse table cells" : "Expand table cells";
@@ -530,7 +526,7 @@ function MarkdownCodeBlock({
children: ReactNode;
}) {
const [copied, setCopied] = useState(false);
const [wrapped, setWrapped] = useState(readInitialWordWrapSetting);
const [wrapped, setWrapped] = useState(useClientSettings((settings) => settings.wordWrap));
const copiedTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const wrapLabel = wrapped ? "Disable line wrap" : "Wrap lines";
const copyLabel = copied ? "Copied" : "Copy code";
+114 -178
View File
@@ -41,17 +41,7 @@ import { truncate } from "@t3tools/shared/String";
import { nextTerminalId, resolveTerminalSessionLabel } from "@t3tools/shared/terminalLabels";
import { Debouncer } from "@tanstack/react-pacer";
import { useAtomValue } from "@effect/atom-react";
import {
lazy,
memo,
Suspense,
useCallback,
useEffect,
useLayoutEffect,
useMemo,
useRef,
useState,
} from "react";
import { lazy, memo, Suspense, useCallback, useEffect, useMemo, useRef, useState } from "react";
import { useNavigate } from "@tanstack/react-router";
import { useShallow } from "zustand/react/shallow";
import {
@@ -1147,32 +1137,12 @@ function ChatViewContent(props: ChatViewProps) {
LastInvokedScriptByProjectSchema,
);
const legendListRef = useRef<LegendListRef | null>(null);
const [composerOverlayElement, setComposerOverlayElement] = useState<HTMLDivElement | null>(null);
const [composerOverlayHeight, setComposerOverlayHeight] = useState(0);
const isAtEndRef = useRef(true);
const attachmentPreviewHandoffByMessageIdRef = useRef<Record<string, string[]>>({});
const attachmentPreviewPromotionInFlightByMessageIdRef = useRef<Record<string, true>>({});
const sendInFlightRef = useRef(false);
const terminalUiOpenByThreadRef = useRef<Record<string, boolean>>({});
useLayoutEffect(() => {
if (!composerOverlayElement) return;
const updateHeight = () => {
const nextHeight = Math.ceil(composerOverlayElement.getBoundingClientRect().height);
setComposerOverlayHeight((currentHeight) =>
currentHeight === nextHeight ? currentHeight : nextHeight,
);
};
updateHeight();
if (typeof ResizeObserver === "undefined") return;
const observer = new ResizeObserver(updateHeight);
observer.observe(composerOverlayElement);
return () => observer.disconnect();
}, [composerOverlayElement]);
const terminalUiState = useTerminalUiStateStore((state) =>
selectThreadTerminalUiState(state.terminalUiStateByThreadKey, routeThreadRef),
);
@@ -1284,14 +1254,6 @@ function ChatViewContent(props: ChatViewProps) {
[activeThread],
);
const activeThreadKey = activeThreadRef ? scopedThreadKey(activeThreadRef) : null;
const [timelineAnchor, setTimelineAnchor] = useState<{
readonly threadKey: string | null;
readonly messageId: MessageId | null;
}>({ threadKey: activeThreadKey, messageId: null });
if (timelineAnchor.threadKey !== activeThreadKey) {
setTimelineAnchor({ threadKey: activeThreadKey, messageId: null });
}
const timelineAnchorMessageId = timelineAnchor.messageId;
const activeRightPanelKind = useRightPanelStore((state) =>
selectActiveRightPanel(state.byThreadKey, activeThreadRef),
);
@@ -3149,7 +3111,7 @@ function ChatViewContent(props: ChatViewProps) {
// Scroll helpers — LegendList handles auto-scroll via maintainScrollAtEnd.
const scrollToEnd = useCallback((animated = false) => {
void legendListRef.current?.scrollToEnd?.({ animated });
legendListRef.current?.scrollToEnd?.({ animated });
}, []);
// Debounce *showing* the scroll-to-bottom pill so it doesn't flash during
@@ -3728,16 +3690,14 @@ function ChatViewContent(props: ChatViewProps) {
sizeBytes: image.sizeBytes,
previewUrl: image.previewUrl,
}));
// Sending always returns to the live edge. The new row becomes the
// anchored end-space target so it lands near the top while the response
// streams into the reserved space below it.
// Scroll to the current end *before* adding the optimistic message.
// This sets LegendList's internal isAtEnd=true so maintainScrollAtEnd
// automatically pins to the new item when the data changes.
isAtEndRef.current = true;
showScrollDebouncer.current.cancel();
setShowScrollToBottom(false);
setTimelineAnchor({
threadKey: scopedThreadKey(scopeThreadRef(activeThread.environmentId, threadIdForSend)),
messageId: messageIdForSend,
});
await legendListRef.current?.scrollToEnd?.({ animated: false });
setOptimisticUserMessages((existing) => [
...existing,
{
@@ -3751,7 +3711,6 @@ function ChatViewContent(props: ChatViewProps) {
streaming: false,
},
]);
void legendListRef.current?.scrollToEnd?.({ animated: false });
setThreadError(threadIdForSend, null);
if (expiredTerminalContextCount > 0) {
@@ -4763,7 +4722,7 @@ function ChatViewContent(props: ChatViewProps) {
{/* Main content area with optional plan sidebar */}
<div className="flex min-h-0 min-w-0 flex-1">
{/* Chat column */}
<div className="relative flex min-h-0 min-w-0 flex-1 flex-col">
<div className="flex min-h-0 min-w-0 flex-1 flex-col">
{/* Messages Wrapper */}
<div className="relative flex min-h-0 flex-1 flex-col">
{/* Messages — LegendList handles virtualization and scrolling internally */}
@@ -4788,17 +4747,12 @@ function ChatViewContent(props: ChatViewProps) {
timestampFormat={timestampFormat}
workspaceRoot={activeWorkspaceRoot}
skills={activeProviderStatus?.skills ?? EMPTY_PROVIDER_SKILLS}
anchorMessageId={timelineAnchorMessageId}
contentInsetEndAdjustment={composerOverlayHeight}
onIsAtEndChange={onIsAtEndChange}
/>
{/* scroll to bottom pill — shown when user has scrolled away from the bottom */}
{showScrollToBottom && (
<div
className="pointer-events-none absolute left-1/2 z-30 flex -translate-x-1/2 justify-center py-1.5"
style={{ bottom: composerOverlayHeight + 4 }}
>
<div className="pointer-events-none absolute bottom-1 left-1/2 z-30 flex -translate-x-1/2 justify-center py-1.5">
<button
type="button"
onClick={() => scrollToEnd(true)}
@@ -4813,133 +4767,115 @@ function ChatViewContent(props: ChatViewProps) {
{/* Input bar */}
<div
ref={setComposerOverlayElement}
data-chat-composer-overlay="true"
className="pointer-events-none absolute inset-x-0 bottom-0 z-20 pt-1.5 sm:pt-2"
className={cn(
"pl-[calc(env(safe-area-inset-left)+0.75rem)] pr-[calc(env(safe-area-inset-right)+0.75rem)] pt-1.5 sm:pl-[calc(env(safe-area-inset-left)+1.25rem)] sm:pr-[calc(env(safe-area-inset-right)+1.25rem)] sm:pt-2",
isGitRepo
? "pb-[calc(env(safe-area-inset-bottom)+0.25rem)]"
: "pb-[calc(env(safe-area-inset-bottom)+0.75rem)] sm:pb-[calc(env(safe-area-inset-bottom)+1rem)]",
)}
>
<div
aria-hidden="true"
className="chat-composer-horizontal-inset pointer-events-none absolute inset-x-0 top-1.5 bottom-0 z-0 sm:top-2"
>
<div className="relative mx-auto h-full w-full max-w-208 overflow-clip rounded-t-[20px]">
<div className="chat-composer-shared-blur absolute -inset-8" />
<div className="relative isolate">
<ComposerBannerStack className="relative z-0" items={composerBannerItems} />
<div className="relative z-10">
<ChatComposer
composerRef={composerRef}
composerDraftTarget={composerDraftTarget}
environmentId={environmentId}
routeKind={routeKind}
routeThreadRef={routeThreadRef}
draftId={draftId}
activeThreadId={activeThreadId}
activeThreadEnvironmentId={activeThread?.environmentId}
activeThread={activeThread}
isServerThread={isServerThread}
isLocalDraftThread={isLocalDraftThread}
phase={phase}
isConnecting={isConnecting}
isSendBusy={isSendBusy}
isPreparingWorktree={isPreparingWorktree}
environmentUnavailable={activeEnvironmentUnavailableState}
activePendingApproval={activePendingApproval}
pendingApprovals={pendingApprovals}
pendingUserInputs={pendingUserInputs}
activePendingProgress={activePendingProgress}
activePendingResolvedAnswers={activePendingResolvedAnswers}
activePendingIsResponding={activePendingIsResponding}
activePendingDraftAnswers={activePendingDraftAnswers}
activePendingQuestionIndex={activePendingQuestionIndex}
respondingRequestIds={respondingRequestIds}
showPlanFollowUpPrompt={showPlanFollowUpPrompt}
activeProposedPlan={activeProposedPlan}
activePlan={activePlan as { turnId?: TurnId } | null}
sidebarProposedPlan={sidebarProposedPlan as { turnId?: TurnId } | null}
planSidebarLabel={planSidebarLabel}
planSidebarOpen={planSidebarOpen}
runtimeMode={runtimeMode}
interactionMode={interactionMode}
lockedProvider={lockedProvider}
providerStatuses={providerStatuses as ServerProvider[]}
activeProjectDefaultModelSelection={activeProject?.defaultModelSelection}
activeThreadModelSelection={activeThread?.modelSelection}
activeThreadActivities={activeThread?.activities}
resolvedTheme={resolvedTheme}
settings={settings}
keybindings={keybindings}
terminalOpen={Boolean(terminalUiState.terminalOpen)}
gitCwd={gitCwd}
promptRef={promptRef}
composerImagesRef={composerImagesRef}
composerTerminalContextsRef={composerTerminalContextsRef}
composerElementContextsRef={composerElementContextsRef}
shouldAutoScrollRef={isAtEndRef}
scheduleStickToBottom={scrollToEnd}
onSend={onSend}
onInterrupt={onInterrupt}
onImplementPlanInNewThread={onImplementPlanInNewThread}
onRespondToApproval={onRespondToApproval}
onSelectActivePendingUserInputOption={onSelectActivePendingUserInputOption}
onAdvanceActivePendingUserInput={onAdvanceActivePendingUserInput}
onPreviousActivePendingUserInputQuestion={
onPreviousActivePendingUserInputQuestion
}
onChangeActivePendingUserInputCustomAnswer={
onChangeActivePendingUserInputCustomAnswer
}
onProviderModelSelect={onProviderModelSelect}
getModelDisabledReason={getModelDisabledReason}
toggleInteractionMode={toggleInteractionMode}
handleRuntimeModeChange={handleRuntimeModeChange}
handleInteractionModeChange={handleInteractionModeChange}
togglePlanSidebar={togglePlanSidebar}
focusComposer={focusComposer}
scheduleComposerFocus={scheduleComposerFocus}
setThreadError={setThreadError}
onExpandImage={onExpandTimelineImage}
/>
</div>
</div>
<div className="chat-composer-horizontal-inset">
<div className="pointer-events-auto relative z-10 isolate">
<ComposerBannerStack className="relative z-0" items={composerBannerItems} />
<div className="relative z-10">
<ChatComposer
composerRef={composerRef}
composerDraftTarget={composerDraftTarget}
environmentId={environmentId}
routeKind={routeKind}
routeThreadRef={routeThreadRef}
draftId={draftId}
activeThreadId={activeThreadId}
activeThreadEnvironmentId={activeThread?.environmentId}
activeThread={activeThread}
isServerThread={isServerThread}
isLocalDraftThread={isLocalDraftThread}
phase={phase}
isConnecting={isConnecting}
isSendBusy={isSendBusy}
isPreparingWorktree={isPreparingWorktree}
environmentUnavailable={activeEnvironmentUnavailableState}
activePendingApproval={activePendingApproval}
pendingApprovals={pendingApprovals}
pendingUserInputs={pendingUserInputs}
activePendingProgress={activePendingProgress}
activePendingResolvedAnswers={activePendingResolvedAnswers}
activePendingIsResponding={activePendingIsResponding}
activePendingDraftAnswers={activePendingDraftAnswers}
activePendingQuestionIndex={activePendingQuestionIndex}
respondingRequestIds={respondingRequestIds}
showPlanFollowUpPrompt={showPlanFollowUpPrompt}
activeProposedPlan={activeProposedPlan}
activePlan={activePlan as { turnId?: TurnId } | null}
sidebarProposedPlan={sidebarProposedPlan as { turnId?: TurnId } | null}
planSidebarLabel={planSidebarLabel}
planSidebarOpen={planSidebarOpen}
runtimeMode={runtimeMode}
interactionMode={interactionMode}
lockedProvider={lockedProvider}
providerStatuses={providerStatuses as ServerProvider[]}
activeProjectDefaultModelSelection={activeProject?.defaultModelSelection}
activeThreadModelSelection={activeThread?.modelSelection}
activeThreadActivities={activeThread?.activities}
resolvedTheme={resolvedTheme}
settings={settings}
keybindings={keybindings}
terminalOpen={Boolean(terminalUiState.terminalOpen)}
gitCwd={gitCwd}
promptRef={promptRef}
composerImagesRef={composerImagesRef}
composerTerminalContextsRef={composerTerminalContextsRef}
composerElementContextsRef={composerElementContextsRef}
onSend={onSend}
onInterrupt={onInterrupt}
onImplementPlanInNewThread={onImplementPlanInNewThread}
onRespondToApproval={onRespondToApproval}
onSelectActivePendingUserInputOption={onSelectActivePendingUserInputOption}
onAdvanceActivePendingUserInput={onAdvanceActivePendingUserInput}
onPreviousActivePendingUserInputQuestion={
onPreviousActivePendingUserInputQuestion
{isGitRepo && (
<BranchToolbar
environmentId={activeThread.environmentId}
threadId={activeThread.id}
{...(routeKind === "draft" && draftId ? { draftId } : {})}
onEnvModeChange={onEnvModeChange}
startFromOrigin={startFromOrigin}
onStartFromOriginChange={onStartFromOriginChange}
{...(canOverrideServerThreadEnvMode ? { effectiveEnvModeOverride: envMode } : {})}
{...(canOverrideServerThreadEnvMode
? {
activeThreadBranchOverride: activeThreadBranch,
onActiveThreadBranchOverrideChange: setPendingServerThreadBranch,
}
onChangeActivePendingUserInputCustomAnswer={
onChangeActivePendingUserInputCustomAnswer
}
onProviderModelSelect={onProviderModelSelect}
getModelDisabledReason={getModelDisabledReason}
toggleInteractionMode={toggleInteractionMode}
handleRuntimeModeChange={handleRuntimeModeChange}
handleInteractionModeChange={handleInteractionModeChange}
togglePlanSidebar={togglePlanSidebar}
focusComposer={focusComposer}
scheduleComposerFocus={scheduleComposerFocus}
setThreadError={setThreadError}
onExpandImage={onExpandTimelineImage}
/>
</div>
</div>
</div>
<div
className={cn(
"chat-composer-horizontal-inset chat-composer-lower-chrome relative z-10",
isGitRepo
? "pb-[calc(env(safe-area-inset-bottom)+0.25rem)]"
: "pb-[calc(env(safe-area-inset-bottom)+0.75rem)] sm:pb-[calc(env(safe-area-inset-bottom)+1rem)]",
)}
>
{isGitRepo && (
<div className="pointer-events-auto">
<BranchToolbar
environmentId={activeThread.environmentId}
threadId={activeThread.id}
{...(routeKind === "draft" && draftId ? { draftId } : {})}
onEnvModeChange={onEnvModeChange}
startFromOrigin={startFromOrigin}
onStartFromOriginChange={onStartFromOriginChange}
{...(canOverrideServerThreadEnvMode
? { effectiveEnvModeOverride: envMode }
: {})}
{...(canOverrideServerThreadEnvMode
? {
activeThreadBranchOverride: activeThreadBranch,
onActiveThreadBranchOverrideChange: setPendingServerThreadBranch,
}
: {})}
envLocked={envLocked}
onComposerFocusRequest={scheduleComposerFocus}
{...(canCheckoutPullRequestIntoThread
? { onCheckoutPullRequestRequest: openPullRequestDialog }
: {})}
{...(hasMultipleEnvironments ? { onEnvironmentChange } : {})}
availableEnvironments={logicalProjectEnvironments}
/>
</div>
)}
</div>
: {})}
envLocked={envLocked}
onComposerFocusRequest={scheduleComposerFocus}
{...(canCheckoutPullRequestIntoThread
? { onCheckoutPullRequestRequest: openPullRequestDialog }
: {})}
{...(hasMultipleEnvironments ? { onEnvironmentChange } : {})}
availableEnvironments={logicalProjectEnvironments}
/>
)}
</div>
{pullRequestDialogState ? (
+26 -4
View File
@@ -504,6 +504,10 @@ export interface ChatComposerProps {
composerElementContextsRef: React.RefObject<ElementContextDraft[]>;
composerRef: React.RefObject<ChatComposerHandle | null>;
// Scroll
shouldAutoScrollRef: React.RefObject<boolean>;
scheduleStickToBottom: () => void;
// Callbacks
onSend: (e?: { preventDefault: () => void }) => void;
onInterrupt: () => void;
@@ -589,6 +593,8 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
composerImagesRef,
composerTerminalContextsRef,
composerElementContextsRef,
shouldAutoScrollRef,
scheduleStickToBottom,
onSend,
onInterrupt,
onImplementPlanInNewThread,
@@ -890,6 +896,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
const composerEditorRef = useRef<ComposerPromptEditorHandle>(null);
const composerFormRef = useRef<HTMLFormElement>(null);
const composerSurfaceRef = useRef<HTMLDivElement>(null);
const composerFormHeightRef = useRef(0);
const composerSelectLockRef = useRef(false);
const composerMenuOpenRef = useRef(false);
const composerMenuItemsRef = useRef<ComposerCommandItem[]>([]);
@@ -1322,12 +1329,15 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
};
};
composerFormHeightRef.current = composerForm.getBoundingClientRect().height;
const initialCompactness = measureFooterCompactness();
setIsComposerPrimaryActionsCompact(initialCompactness.primaryActionsCompact);
setIsComposerFooterCompact(initialCompactness.footerCompact);
if (typeof ResizeObserver === "undefined") return;
const observer = new ResizeObserver(() => {
const observer = new ResizeObserver((entries) => {
const [entry] = entries;
if (!entry) return;
const nextCompactness = measureFooterCompactness();
setIsComposerPrimaryActionsCompact((previous) =>
previous === nextCompactness.primaryActionsCompact
@@ -1337,13 +1347,25 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
setIsComposerFooterCompact((previous) =>
previous === nextCompactness.footerCompact ? previous : nextCompactness.footerCompact,
);
const nextHeight = entry.contentRect.height;
const previousHeight = composerFormHeightRef.current;
composerFormHeightRef.current = nextHeight;
if (previousHeight > 0 && Math.abs(nextHeight - previousHeight) < 0.5) return;
if (!shouldAutoScrollRef.current) return;
scheduleStickToBottom();
});
observer.observe(composerForm);
return () => {
observer.disconnect();
};
}, [activeThreadId, composerFooterActionLayoutKey, composerFooterHasWideActions]);
}, [
activeThreadId,
composerFooterActionLayoutKey,
composerFooterHasWideActions,
scheduleStickToBottom,
shouldAutoScrollRef,
]);
// ------------------------------------------------------------------
// Image persist effect
@@ -2061,8 +2083,8 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
ref={composerSurfaceRef}
data-chat-composer-mobile-collapsed={isComposerCollapsedMobile ? "true" : "false"}
className={cn(
"chat-composer-glass rounded-[20px] border transition-colors duration-200 has-focus-visible:border-ring/45",
isDragOverComposer ? "border-primary/70 bg-accent/45" : "border-border",
"rounded-[20px] border bg-card transition-colors duration-200 has-focus-visible:border-ring/45",
isDragOverComposer ? "border-primary/70 bg-accent/30" : "border-border",
environmentUnavailable ? "opacity-75" : null,
composerProviderState.composerSurfaceClassName,
)}
@@ -13,21 +13,9 @@ vi.mock("@legendapp/list/react", async () => {
renderItem: (args: { item: { id: string } }) => ReactNode;
ListHeaderComponent?: ReactNode;
ListFooterComponent?: ReactNode;
anchoredEndSpace?: {
anchorIndex: number;
anchorMaxSize?: number;
anchorOffset?: number;
};
contentInsetEndAdjustment?: number;
ref?: Ref<LegendListRef>;
}) => (
<div
data-testid={legendListTestId}
data-anchor-index={props.anchoredEndSpace?.anchorIndex}
data-anchor-max-size={props.anchoredEndSpace?.anchorMaxSize}
data-anchor-offset={props.anchoredEndSpace?.anchorOffset}
data-content-inset-end={props.contentInsetEndAdjustment}
>
<div data-testid={legendListTestId}>
{props.ListHeaderComponent}
{props.data.map((item) => (
<div key={props.keyExtractor(item)}>{props.renderItem({ item })}</div>
@@ -121,8 +109,6 @@ function buildProps() {
resolvedTheme: "light" as const,
timestampFormat: "locale" as const,
workspaceRoot: undefined,
anchorMessageId: null,
contentInsetEndAdjustment: 0,
onIsAtEndChange: () => {},
};
}
@@ -151,42 +137,6 @@ function buildUserTimelineEntry(text: string) {
}
describe("MessagesTimeline", () => {
it("anchors a sent attachment message using its measured height", async () => {
const { MessagesTimeline } = await import("./MessagesTimeline");
const firstEntry = buildUserTimelineEntry("First prompt.");
const secondEntry = {
...buildUserTimelineEntry("Newest prompt."),
id: "entry-2",
message: {
...buildUserTimelineEntry("Newest prompt.").message,
id: MessageId.make("message-2"),
attachments: [
{
type: "image" as const,
id: "attachment-1",
name: "screenshot.png",
mimeType: "image/png",
sizeBytes: 1,
previewUrl: "data:image/png;base64,iVBORw0KGgo=",
},
],
},
};
const markup = renderToStaticMarkup(
<MessagesTimeline
{...buildProps()}
anchorMessageId={secondEntry.message.id}
contentInsetEndAdjustment={144}
timelineEntries={[firstEntry, secondEntry]}
/>,
);
expect(markup).toContain('data-anchor-index="1"');
expect(markup).toContain('data-anchor-offset="16"');
expect(markup).not.toContain("data-anchor-max-size=");
expect(markup).toContain('data-content-inset-end="144"');
});
it("renders collapse controls for long user messages", async () => {
const { MessagesTimeline } = await import("./MessagesTimeline");
const markup = renderToStaticMarkup(
@@ -243,33 +193,6 @@ describe("MessagesTimeline", () => {
expect(markup).toContain("Show full message");
}, 20_000);
it("renders chips for standalone element-pick context messages", async () => {
const { MessagesTimeline } = await import("./MessagesTimeline");
const markup = renderToStaticMarkup(
<MessagesTimeline
{...buildProps()}
timelineEntries={[
buildUserTimelineEntry(
[
"<element_context>",
"- <SubmitButton> (Button.tsx:12):",
" url: https://example.com/dashboard",
" selector: button.submit",
" source: /repo/src/Button.tsx:12:5",
" html:",
' <button class="submit">Save</button>',
"</element_context>",
].join("\n"),
),
]}
/>,
);
expect(markup).toContain("SubmitButton");
expect(markup).not.toContain("&lt;element_context");
expect(markup).not.toContain("<element_context");
});
it("keeps the copy button for collapsed long user messages", async () => {
const { MessagesTimeline } = await import("./MessagesTimeline");
const markup = renderToStaticMarkup(
@@ -6,7 +6,6 @@ import {
type TurnId,
} from "@t3tools/contracts";
import { parseScopedThreadKey } from "@t3tools/client-runtime/environment";
import { resolveChatListAnchoredEndSpace } from "@t3tools/shared/chatList";
import {
createContext,
Fragment,
@@ -166,8 +165,6 @@ interface MessagesTimelineProps {
timestampFormat: TimestampFormat;
workspaceRoot: string | undefined;
skills?: ReadonlyArray<Pick<ServerProviderSkill, "name" | "displayName">>;
anchorMessageId: MessageId | null;
contentInsetEndAdjustment: number;
onIsAtEndChange: (isAtEnd: boolean) => void;
}
@@ -195,8 +192,6 @@ export const MessagesTimeline = memo(function MessagesTimeline({
timestampFormat,
workspaceRoot,
skills = EMPTY_TIMELINE_SKILLS,
anchorMessageId,
contentInsetEndAdjustment,
onIsAtEndChange,
}: MessagesTimelineProps) {
const [expandedTurnIds, setExpandedTurnIds] = useState<ReadonlySet<TurnId>>(new Set());
@@ -289,13 +284,6 @@ export const MessagesTimeline = memo(function MessagesTimeline({
],
);
const rows = useStableRows(rawRows);
const anchoredEndSpace = useMemo(
() =>
resolveChatListAnchoredEndSpace(rows, anchorMessageId, (row) =>
row.kind === "message" ? row.message.id : null,
),
[anchorMessageId, rows],
);
const handleScroll = useCallback(() => {
const state = listRef.current?.getState?.();
@@ -304,6 +292,24 @@ export const MessagesTimeline = memo(function MessagesTimeline({
}
}, [listRef, onIsAtEndChange]);
const previousRowCountRef = useRef(rows.length);
useEffect(() => {
const previousRowCount = previousRowCountRef.current;
previousRowCountRef.current = rows.length;
if (previousRowCount > 0 || rows.length === 0) {
return;
}
onIsAtEndChange(true);
const frameId = window.requestAnimationFrame(() => {
void listRef.current?.scrollToEnd?.({ animated: false });
});
return () => {
window.cancelAnimationFrame(frameId);
};
}, [listRef, onIsAtEndChange, rows.length]);
const sharedState = useMemo<TimelineRowSharedState>(
() => ({
timestampFormat,
@@ -370,17 +376,14 @@ export const MessagesTimeline = memo(function MessagesTimeline({
ref={listRef}
data={rows}
keyExtractor={keyExtractor}
getItemType={getItemType}
renderItem={renderItem}
estimatedItemSize={90}
initialScrollAtEnd
{...(anchoredEndSpace ? { anchoredEndSpace } : {})}
contentInsetEndAdjustment={contentInsetEndAdjustment}
maintainScrollAtEnd={!foldToggleSettling}
maintainScrollAtEndThreshold={0.1}
maintainVisibleContentPosition
onScroll={handleScroll}
className="scrollbar-gutter-both h-full min-h-0 overflow-x-hidden overscroll-y-contain px-3 sm:px-5"
className="scrollbar-gutter-both h-full overflow-x-hidden overscroll-y-contain px-3 sm:px-5"
ListHeaderComponent={TIMELINE_LIST_HEADER}
ListFooterComponent={TIMELINE_LIST_FOOTER}
/>
@@ -393,10 +396,6 @@ function keyExtractor(item: MessagesTimelineRow) {
return item.id;
}
function getItemType(item: MessagesTimelineRow) {
return item.kind === "message" ? `message:${item.message.role}` : item.kind;
}
// ---------------------------------------------------------------------------
// TimelineRowContent — the actual row component
// ---------------------------------------------------------------------------
@@ -449,10 +448,6 @@ function UserTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "message"
visibleText = extracted.promptText;
}
const elementContextState = extractTrailingElementContexts(visibleText);
const elementContexts = [
...displayedUserMessage.elementContexts,
...elementContextState.contexts,
];
const previewImages = userImages.filter((image) => image.name.startsWith("preview-annotation-"));
const regularImages = userImages.filter((image) => !image.name.startsWith("preview-annotation-"));
const canRevertAgentWork = typeof row.revertTurnCount === "number";
@@ -500,9 +495,9 @@ function UserTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "message"
image={previewImages[index] ?? null}
/>
))}
{elementContexts.length > 0 ? (
{elementContextState.contexts.length > 0 ? (
<div className="mb-2 flex flex-wrap gap-1.5">
{elementContexts.map((context) => (
{elementContextState.contexts.map((context) => (
<UserMessageElementContextChip
key={`${context.header}:${context.body}`}
context={context}
@@ -554,7 +554,7 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: {
onItemHighlighted={(modelKey, eventDetails) => {
highlightedModelKeyRef.current = typeof modelKey === "string" ? modelKey : null;
if (eventDetails.reason === "keyboard" && eventDetails.index >= 0) {
void modelListRef.current?.scrollIndexIntoView?.({
modelListRef.current?.scrollIndexIntoView?.({
index: eventDetails.index,
animated: false,
});
@@ -1561,22 +1561,7 @@ const DesktopSshHostRow = memo(function DesktopSshHostRow({
</div>
</div>
);
}, areDesktopSshHostRowPropsEqual);
function areDesktopSshHostRowPropsEqual(
previous: Readonly<DesktopSshHostRowProps>,
next: Readonly<DesktopSshHostRowProps>,
): boolean {
return (
previous.connectingHostAlias === next.connectingHostAlias &&
previous.onConnect === next.onConnect &&
previous.target.alias === next.target.alias &&
previous.target.hostname === next.target.hostname &&
previous.target.username === next.target.username &&
previous.target.port === next.target.port &&
previous.target.source === next.target.source
);
}
});
function CloudLinkSwitch({
checked,
@@ -2764,7 +2749,7 @@ export function ConnectionsSettings() {
key={`${target.alias}:${target.hostname}:${target.port ?? ""}`}
target={target}
connectingHostAlias={connectingSshHostAlias}
onConnect={handleConnectSshHost}
onConnect={(nextTarget) => void handleConnectSshHost(nextTarget)}
/>
))}
{hasLoadedDiscoveredSshHosts &&
+1 -54
View File
@@ -5,7 +5,6 @@
@custom-variant wco (&:is(.wco, .wco *));
:root {
--app-scrollbar-width: 6px;
--workspace-topbar-height: 52px;
--workspace-controls-top: 0px;
--workspace-controls-left: calc(env(safe-area-inset-left) + 0.75rem);
@@ -145,58 +144,6 @@
.surface-subheader {
@apply flex h-10 min-h-10 shrink-0 items-center border-b border-border/60 bg-background;
}
.chat-composer-horizontal-inset {
padding-inline-start: calc(env(safe-area-inset-left) + 0.75rem);
padding-inline-end: calc(env(safe-area-inset-right) + 0.75rem);
}
.chat-composer-glass,
.chat-composer-lower-chrome {
background: color-mix(in srgb, var(--card) 20%, transparent);
}
.chat-composer-glass {
box-shadow:
0 18px 48px -20px rgb(0 0 0 / 28%),
0 4px 14px -7px rgb(0 0 0 / 22%);
}
.chat-composer-shared-blur {
-webkit-backdrop-filter: blur(16px);
backdrop-filter: blur(16px);
}
.dark .chat-composer-glass,
.dark .chat-composer-lower-chrome {
background: color-mix(in srgb, var(--card) 45%, transparent);
}
.dark .chat-composer-glass {
box-shadow:
0 18px 48px -20px rgb(0 0 0 / 60%),
0 4px 14px -7px rgb(0 0 0 / 40%);
}
.chat-composer-lower-chrome {
margin-top: -1px;
margin-inline-end: var(--app-scrollbar-width);
padding-top: 1px;
}
@media (min-width: 40rem) {
.chat-composer-horizontal-inset {
padding-inline-start: calc(env(safe-area-inset-left) + 1.25rem);
padding-inline-end: calc(env(safe-area-inset-right) + 1.25rem);
}
}
@supports not ((-webkit-backdrop-filter: blur(1px)) or (backdrop-filter: blur(1px))) {
.chat-composer-glass,
.chat-composer-lower-chrome {
background: var(--card);
}
}
}
/* Safe-area inset utilities for surfaces that opt into edge-to-edge rendering.
@@ -352,7 +299,7 @@ code {
/* Scrollbar styling */
::-webkit-scrollbar {
width: var(--app-scrollbar-width);
width: 6px;
}
::-webkit-scrollbar-track {
-4
View File
@@ -167,10 +167,6 @@
"types": "./src/filePreview.ts",
"import": "./src/filePreview.ts"
},
"./chatList": {
"types": "./src/chatList.ts",
"import": "./src/chatList.ts"
},
"./hostProcess": {
"types": "./src/hostProcess.ts",
"import": "./src/hostProcess.ts"
-42
View File
@@ -1,42 +0,0 @@
import { describe, expect, it } from "vite-plus/test";
import { CHAT_LIST_ANCHOR_OFFSET, resolveChatListAnchoredEndSpace } from "./chatList.js";
interface Row {
readonly id: string;
readonly anchorable: boolean;
}
const rows: ReadonlyArray<Row> = [
{ id: "first", anchorable: true },
{ id: "ignored", anchorable: false },
{ id: "latest", anchorable: true },
];
const getAnchorId = (row: Row) => (row.anchorable ? row.id : null);
describe("resolveChatListAnchoredEndSpace", () => {
it("anchors the matching row using its measured height", () => {
expect(resolveChatListAnchoredEndSpace(rows, "latest", getAnchorId)).toEqual({
anchorIndex: 2,
anchorOffset: CHAT_LIST_ANCHOR_OFFSET,
});
});
it("allows a surface to keep the anchor below its own header", () => {
expect(
resolveChatListAnchoredEndSpace(rows, "latest", getAnchorId, {
anchorOffset: 132,
}),
).toEqual({
anchorIndex: 2,
anchorOffset: 132,
});
});
it("ignores ineligible rows and missing anchors", () => {
expect(resolveChatListAnchoredEndSpace(rows, "ignored", getAnchorId)).toBeUndefined();
expect(resolveChatListAnchoredEndSpace(rows, "missing", getAnchorId)).toBeUndefined();
expect(resolveChatListAnchoredEndSpace(rows, null, getAnchorId)).toBeUndefined();
});
});
-33
View File
@@ -1,33 +0,0 @@
export const CHAT_LIST_ANCHOR_OFFSET = 16;
export interface ChatListAnchoredEndSpace {
readonly anchorIndex: number;
readonly anchorOffset: number;
}
export interface ChatListAnchorOptions {
readonly anchorOffset?: number;
}
export function resolveChatListAnchoredEndSpace<Item, AnchorId>(
items: ReadonlyArray<Item>,
anchorId: AnchorId | null,
getAnchorId: (item: Item) => AnchorId | null,
options: ChatListAnchorOptions = {},
): ChatListAnchoredEndSpace | undefined {
if (anchorId === null) {
return undefined;
}
for (let index = items.length - 1; index >= 0; index -= 1) {
const item = items[index];
if (item !== undefined && getAnchorId(item) === anchorId) {
return {
anchorIndex: index,
anchorOffset: options.anchorOffset ?? CHAT_LIST_ANCHOR_OFFSET,
};
}
}
return undefined;
}
+14 -14
View File
@@ -208,8 +208,8 @@ importers:
specifier: ~56.0.8
version: 56.0.15(ab3f255d102c60ba0fd2bbe4e47ba584)
'@legendapp/list':
specifier: 3.2.0
version: 3.2.0([email protected]([email protected]))([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected])
specifier: 3.0.0-beta.44
version: 3.0.0-beta.44([email protected]([email protected]))([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected])
'@noble/curves':
specifier: 'catalog:'
version: 1.9.1
@@ -355,13 +355,13 @@ importers:
specifier: ^0.2.2
version: 0.2.2([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected])
react-native-keyboard-controller:
specifier: 1.21.7
version: 1.21.7([email protected]([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected]))([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected]))([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected])
specifier: 1.21.6
version: 1.21.6([email protected]([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected]))([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected]))([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected])
react-native-nitro-markdown:
specifier: ^0.5.0
version: 0.5.8([email protected](patch_hash=825622aae63a8fb5b904f3c77908a0e216261d727ea171709f2c0b6088422675)([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected]))([email protected]([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected]))([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected])
react-native-nitro-modules:
specifier: 0.35.9
specifier: ^0.35.4
version: 0.35.9(patch_hash=825622aae63a8fb5b904f3c77908a0e216261d727ea171709f2c0b6088422675)([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected])
react-native-reanimated:
specifier: 4.3.1
@@ -513,8 +513,8 @@ importers:
specifier: ^0.9.0
version: 0.9.0
'@legendapp/list':
specifier: 3.2.0
version: 3.2.0([email protected]([email protected]))([email protected])
specifier: 3.0.0-beta.44
version: 3.0.0-beta.44([email protected]([email protected]))([email protected])
'@lexical/react':
specifier: ^0.41.0
version: 0.41.0([email protected]([email protected]))([email protected])([email protected])
@@ -2745,8 +2745,8 @@ packages:
resolution: {integrity: sha512-hloP58zRVCRSpgDxmqCWJNlizAlUgJFqG2ypq79DCvyv9tHjRYMDOcPFjzfl/A1/YxDvRCZz8wvZvmapQnKwFQ==}
engines: {node: '>=12'}
'@legendapp/list@3.2.0':
resolution: {integrity: sha512-bN+g/oQYjFz+UAyuBN4cmYJAwdJS1TdNcZZOVlh3+VwCQUWrsg0PH46Mvm76gdZSCYMfoFanPY4dKnILcYEzeg==}
'@legendapp/list@3.0.0-beta.44':
resolution: {integrity: sha512-loGRve78NuZ5k8Z54ZSDNOtv3dVBM1SeBCRtm1EYtZiDIZ8SyMVcYpUGgFpGuNKk71+9/NuM9hvScrgf7+4E+A==}
peerDependencies:
react: '*'
react-dom: '*'
@@ -8516,8 +8516,8 @@ packages:
react: '*'
react-native: '*'
[email protected].7:
resolution: {integrity: sha512-gs+8nI8HYnRdDt4NWbk1iVuS6kDLf2taJvp+h/TjM1FBdtnQmlYLJ6buNiUqSnkIH4OFEAxdNr3/GOOYdLfkUQ==}
[email protected].6:
resolution: {integrity: sha512-nAXCmar/W8Gn4iQV7O5fAVuTh57JszCsqTS+cfR95WFOLR/AfbwfPz/+sWyz/q2SOIe2VpyQzq6hzYiwErhqqw==}
peerDependencies:
react: '*'
react-native: '*'
@@ -12155,7 +12155,7 @@ snapshots:
dependencies:
jsbi: 4.3.2
'@legendapp/list@3.2.0([email protected]([email protected]))([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected])':
'@legendapp/list@3.0.0-beta.44([email protected]([email protected]))([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected])':
dependencies:
react: 19.2.3
use-sync-external-store: 1.6.0([email protected])
@@ -12163,7 +12163,7 @@ snapshots:
react-dom: 19.2.3([email protected])
react-native: 0.85.3(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])([email protected])([email protected])
'@legendapp/list@3.2.0([email protected]([email protected]))([email protected])':
'@legendapp/list@3.0.0-beta.44([email protected]([email protected]))([email protected])':
dependencies:
react: 19.2.6
use-sync-external-store: 1.6.0([email protected])
@@ -18311,7 +18311,7 @@ snapshots:
react: 19.2.3
react-native: 0.85.3(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])([email protected])([email protected])
[email protected].7([email protected]([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected]))([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected]))([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected]):
[email protected].6([email protected]([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected]))([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected]))([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected]):
dependencies:
react: 19.2.3
react-native: 0.85.3(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])([email protected])([email protected])