Compare commits

...
Author SHA1 Message Date
Julius Marminge b1a7386972 Fix Claude auth probe fallback 2026-06-25 15:08:26 -07:00
Julius MarmingeandJulius Marminge 31dfe3596e Fix Electron dev and packaged renderer startup (#3557)
Co-authored-by: Julius Marminge <[email protected]>
2026-06-25 20:58:38 +00:00
Julius Marminge c2776c2336 Restore right panel inset when maximized (#3555) 2026-06-25 17:07:33 +00:00
Julius MarmingeandJulius Marminge 22f021ed69 [codex] Upgrade Legend List chat scrolling (#3545)
Co-authored-by: Julius Marminge <[email protected]>
2026-06-24 15:39:17 -07:00
Wout StiensandCodex a4964b3b36 [codex] fix: show standalone element-pick context (#3527)
Co-authored-by: Codex <[email protected]>
2026-06-23 13:04:20 -07:00
c6c64918f8 Reduce ChatMarkdown settings rerenders (#3536)
Co-authored-by: Cursor Agent <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
2026-06-23 11:47:26 -07:00
32 changed files with 1990 additions and 1182 deletions

No files matched your search

@@ -43,7 +43,16 @@ describe("ElectronProtocol", () => {
assert.isDefined(handler);
const response = yield* Effect.promise(() =>
handler!(new Request("t3code-dev://app/api/health?verbose=1")),
handler!(
new Request("t3code-dev://app/api/health?verbose=1", {
headers: {
accept: "application/json",
origin: "t3code-dev://app",
referer: "t3code-dev://app/",
"sec-fetch-site": "same-origin",
},
}),
),
);
assert.equal(yield* Effect.promise(() => response.text()), "ok");
assert.include(
@@ -70,6 +79,11 @@ describe("ElectronProtocol", () => {
["t3code-dev"],
);
assert.equal(netFetchMock.mock.calls[0]?.[0], "http://127.0.0.1:3773/api/health?verbose=1");
const forwardedHeaders = new Headers(netFetchMock.mock.calls[0]?.[1]?.headers);
assert.equal(forwardedHeaders.get("accept"), "application/json");
assert.isNull(forwardedHeaders.get("origin"));
assert.isNull(forwardedHeaders.get("referer"));
assert.isNull(forwardedHeaders.get("sec-fetch-site"));
assert.deepEqual(unhandleMock.mock.calls, [["t3code-dev"]]);
}).pipe(Effect.provide(ElectronProtocol.layer)),
);
@@ -99,6 +113,34 @@ describe("ElectronProtocol", () => {
}).pipe(Effect.provide(ElectronProtocol.layer)),
);
it.effect("retries transient renderer target failures", () =>
Effect.gen(function* () {
let handler: ((request: Request) => Promise<Response>) | undefined;
handleMock.mockImplementation((_scheme, nextHandler) => {
handler = nextHandler;
});
netFetchMock
.mockRejectedValueOnce(new Error("connect ECONNREFUSED 127.0.0.1:5733"))
.mockResolvedValueOnce(new Response("ready"));
const response = yield* Effect.scoped(
Effect.gen(function* () {
const protocol = yield* ElectronProtocol.ElectronProtocol;
yield* protocol.registerDesktopProtocol({
scheme: "t3code-dev",
targetOrigin: new URL("http://127.0.0.1:5733/"),
backendOrigin: new URL("http://127.0.0.1:3773/"),
clerkFrontendApiHostname: undefined,
});
return yield* Effect.promise(() => handler!(new Request("t3code-dev://app/")));
}),
);
assert.equal(yield* Effect.promise(() => response.text()), "ready");
assert.equal(netFetchMock.mock.calls.length, 2);
}).pipe(Effect.provide(ElectronProtocol.layer)),
);
it.effect("preserves protocol registration failures", () =>
Effect.gen(function* () {
const cause = new Error("protocol registration failed");
+45 -2
View File
@@ -1,6 +1,7 @@
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as NodeTimersPromises from "node:timers/promises";
import * as Ref from "effect/Ref";
import * as Schema from "effect/Schema";
import * as Scope from "effect/Scope";
@@ -114,18 +115,60 @@ async function proxyRequest(
}
const targetUrl = new URL(`${requestUrl.pathname}${requestUrl.search}`, targetOrigin);
const headers = new Headers(request.headers);
const headersToRemove: string[] = [];
for (const name of headers.keys()) {
if (
name === "host" ||
name === "origin" ||
name === "referer" ||
name === "connection" ||
name === "content-length" ||
name === "accept-encoding" ||
name === "upgrade-insecure-requests" ||
name.startsWith("sec-fetch-")
) {
headersToRemove.push(name);
}
}
for (const name of headersToRemove) {
headers.delete(name);
}
const init: RequestInit = {
method: request.method,
headers: request.headers,
headers,
};
if (request.method !== "GET" && request.method !== "HEAD") {
init.body = request.body;
(init as RequestInit & { duplex: "half" }).duplex = "half";
}
const response = await Electron.net.fetch(targetUrl.toString(), init);
const response =
request.method === "GET" || request.method === "HEAD"
? await fetchWithTransientRetry(targetUrl.toString(), init)
: await Electron.net.fetch(targetUrl.toString(), init);
return withContentSecurityPolicy(response, contentSecurityPolicy);
}
const TRANSIENT_FETCH_RETRY_DELAYS_MS = [0, 50, 150] as const;
async function fetchWithTransientRetry(url: string, init: RequestInit): Promise<Response> {
let lastError: unknown;
for (const delayMs of TRANSIENT_FETCH_RETRY_DELAYS_MS) {
if (delayMs > 0) {
await NodeTimersPromises.setTimeout(delayMs);
}
try {
return await Electron.net.fetch(url, init);
} catch (error) {
lastError = error;
}
}
throw lastError;
}
export const make = Effect.gen(function* () {
const registered = yield* Ref.make(false);
+1 -1
View File
@@ -10,7 +10,7 @@
"typecheck": "astro check"
},
"dependencies": {
"astro": "^6.0.4"
"astro": "^7.0.3"
},
"devDependencies": {
"@astrojs/check": "^0.9.7",
+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.0.0-beta.44",
"@legendapp/list": "3.2.0",
"@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.6",
"react-native-keyboard-controller": "1.21.7",
"react-native-nitro-markdown": "^0.5.0",
"react-native-nitro-modules": "^0.35.4",
"react-native-nitro-modules": "0.35.9",
"react-native-reanimated": "4.3.1",
"react-native-safe-area-context": "~5.7.0",
"react-native-screens": "4.25.2",
@@ -1,6 +1,7 @@
import { isLiquidGlassSupported, LiquidGlassView } from "@callstack/liquid-glass";
import type {
EnvironmentId,
MessageId,
ModelSelection,
OrchestrationThreadShell,
ProviderInteractionMode,
@@ -91,7 +92,7 @@ export interface ThreadComposerProps {
readonly onNativePasteImages: (uris: ReadonlyArray<string>) => Promise<void>;
readonly onRemoveDraftImage: (imageId: string) => void;
readonly onStopThread: () => void;
readonly onSendMessage: () => Promise<void>;
readonly onSendMessage: () => Promise<MessageId | null>;
readonly onUpdateModelSelection: (modelSelection: ModelSelection) => void;
readonly onUpdateRuntimeMode: (runtimeMode: RuntimeMode) => void;
readonly onUpdateInteractionMode: (interactionMode: ProviderInteractionMode) => void;
@@ -447,9 +448,7 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
const { onChangeDraftMessage, onUpdateInteractionMode, draftMessage, onSendMessage } = props;
const handleSend = useCallback(() => {
void onSendMessage().then(() => {
inputRef.current?.blur();
});
void onSendMessage();
}, [onSendMessage]);
const handleCommandSelect = useCallback(
(item: ComposerCommandItem) => {
@@ -1,7 +1,10 @@
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,
@@ -13,8 +16,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, useMemo, useRef, useState } from "react";
import { View, type GestureResponderEvent, type LayoutChangeEvent } from "react-native";
import { memo, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
import { View, type GestureResponderEvent } 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";
@@ -25,7 +28,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 { resolveThreadFeedBottomInset } from "../../lib/threadFeedLayout";
import { scopedThreadKey } from "../../lib/scopedEntities";
import type {
PendingApproval,
PendingUserInput,
@@ -73,7 +76,7 @@ export interface ThreadDetailScreenProps {
readonly onNativePasteImages: (uris: ReadonlyArray<string>) => Promise<void>;
readonly onRemoveDraftImage: (imageId: string) => void;
readonly onStopThread: () => void;
readonly onSendMessage: () => Promise<void>;
readonly onSendMessage: () => Promise<MessageId | null>;
readonly onReconnectEnvironment: () => void;
readonly onUpdateThreadModelSelection: (modelSelection: ModelSelection) => void;
readonly onUpdateThreadRuntimeMode: (runtimeMode: RuntimeMode) => void;
@@ -206,25 +209,33 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
const insets = useSafeAreaInsets();
const headerHeight = useHeaderHeight();
const agentLabel = `${props.selectedThread.modelSelection.instanceId} agent`;
const composerRef = useRef<ComposerEditorHandle>(null);
const selectedThreadKey = scopedThreadKey(props.environmentId, props.selectedThread.id);
const composerEditorRef = useRef<ComposerEditorHandle>(null);
const composerOverlayRef = useRef<View>(null);
const listRef = useRef<LegendListRef>(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;
const [measuredOverlayHeight, setMeasuredOverlayHeight] = useState(0);
const estimatedOverlayHeight = composerOverlapHeight + activeWorkIndicatorHeight + 8;
const { contentInsetEndAdjustment, onComposerLayout } = useKeyboardChatComposerInset(
listRef,
composerOverlayRef,
estimatedOverlayHeight,
);
const { freeze, scrollMessageToEnd } = useKeyboardScrollToEnd({ listRef });
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)
@@ -254,15 +265,67 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
[completeDrawerGesture, isSplitLayout],
);
const handleOverlayLayout = useCallback((event: LayoutChangeEvent) => {
const nextHeight = Math.ceil(event.nativeEvent.layout.height);
setMeasuredOverlayHeight((current) =>
Math.abs(current - nextHeight) > 1 ? nextHeight : current,
);
}, []);
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 collapseComposer = useCallback(() => {
composerRef.current?.blur();
composerEditorRef.current?.blur();
}, []);
const handleFeedTouchStart = useCallback((event: GestureResponderEvent) => {
@@ -315,10 +378,13 @@ 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={feedBottomInset}
contentBottomInset={estimatedOverlayHeight}
layoutVariant={layoutVariant}
composerExpanded={composerExpanded}
skills={selectedProviderSkills}
/>
</View>
@@ -332,7 +398,7 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
style={{ position: "absolute", bottom: 0, left: 0, right: 0 }}
offset={{ closed: 0, opened: 0 }}
>
<View onLayout={handleOverlayLayout}>
<View ref={composerOverlayRef} onLayout={onComposerLayout} style={{ paddingTop: 8 }}>
{props.activeWorkStartedAt ? (
<WorkingDurationPill startedAt={props.activeWorkStartedAt} />
) : null}
@@ -361,7 +427,7 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
) : null}
<ThreadComposer
editorRef={composerRef}
editorRef={composerEditorRef}
draftMessage={props.draftMessage}
draftAttachments={props.draftAttachments}
placeholder="Ask the repo agent, or run a command…"
@@ -380,7 +446,7 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
onNativePasteImages={props.onNativePasteImages}
onRemoveDraftImage={props.onRemoveDraftImage}
onStopThread={props.onStopThread}
onSendMessage={props.onSendMessage}
onSendMessage={handleSendMessage}
onReconnectEnvironment={props.onReconnectEnvironment}
onUpdateModelSelection={props.onUpdateThreadModelSelection}
onUpdateRuntimeMode={props.onUpdateThreadRuntimeMode}
+62 -122
View File
@@ -1,10 +1,20 @@
import * as Haptics from "expo-haptics";
import { KeyboardAvoidingLegendList } from "@legendapp/list/keyboard";
import { KeyboardAwareLegendList } from "@legendapp/list/keyboard";
import { type LegendListRef } from "@legendapp/list/react-native";
import type { EnvironmentId, ThreadId, TurnId } from "@t3tools/contracts";
import type { EnvironmentId, MessageId, ThreadId, TurnId } from "@t3tools/contracts";
import { CHAT_LIST_ANCHOR_OFFSET, resolveChatListAnchoredEndSpace } from "@t3tools/shared/chatList";
import { SymbolView } from "expo-symbols";
import { useRouter } from "expo-router";
import { memo, useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from "react";
import {
memo,
useCallback,
useEffect,
useMemo,
useRef,
useState,
type ReactNode,
type RefObject,
} from "react";
import {
Markdown,
type CustomRenderers,
@@ -15,8 +25,6 @@ import {
ActivityIndicator,
Image,
Linking,
type NativeScrollEvent,
type NativeSyntheticEvent,
Pressable,
ScrollView,
StyleSheet,
@@ -29,6 +37,7 @@ 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 {
@@ -64,14 +73,11 @@ 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",
@@ -93,10 +99,13 @@ 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>;
}
@@ -812,30 +821,6 @@ 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}
@@ -1122,17 +1107,12 @@ 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>;
@@ -1214,6 +1194,16 @@ 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) {
@@ -1229,54 +1219,6 @@ 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;
@@ -1308,9 +1250,6 @@ 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);
}
@@ -1358,7 +1297,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
}, []);
const onToggleTurnFold = useCallback((turnId: TurnId) => {
suppressAutoFollowRef.current = true;
setFoldToggleSettling(true);
if (foldSettleFrameRef.current !== null) {
cancelAnimationFrame(foldSettleFrameRef.current);
}
@@ -1376,7 +1315,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
});
foldSettleFrameRef.current = requestAnimationFrame(() => {
foldSettleSecondFrameRef.current = requestAnimationFrame(() => {
suppressAutoFollowRef.current = false;
setFoldToggleSettling(false);
foldSettleFrameRef.current = null;
foldSettleSecondFrameRef.current = null;
});
@@ -1458,59 +1397,60 @@ 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 }}>
<KeyboardAvoidingLegendList
ref={listRef}
<KeyboardAwareLegendList
ref={props.listRef}
key={props.threadId}
style={{ flex: 1 }}
automaticallyAdjustsScrollIndicatorInsets={false}
contentInset={{ top: 0, bottom: 0 }}
scrollIndicatorInsets={{ top: topContentInset, bottom: 0 }}
alignItemsAtEnd
maintainScrollAtEnd={{
animated: false,
on: {
dataChange: true,
itemLayout: true,
layout: true,
},
}}
{...(anchoredEndSpace ? { anchoredEndSpace } : {})}
contentInsetEndAdjustment={props.contentInsetEndAdjustment}
freeze={props.freeze}
maintainScrollAtEnd={
foldToggleSettling
? false
: {
animated: false,
on: {
dataChange: true,
itemLayout: true,
layout: true,
},
}
}
maintainVisibleContentPosition
data={presentedFeed}
extraData={listAppearanceData}
renderItem={renderItem}
keyExtractor={(entry) => `${entry.type}:${entry.id}`}
keyExtractor={(entry) => 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, [], null);
const feed = buildThreadFeed(thread);
expect(feed).toMatchObject([
{
type: "activity-group",
@@ -144,7 +144,7 @@ describe("buildThreadFeed", () => {
],
});
const feed = buildThreadFeed(thread, [], null);
const feed = buildThreadFeed(thread);
const group = feed[0];
expect(group).toMatchObject({
@@ -209,7 +209,7 @@ describe("buildThreadFeed", () => {
],
});
const group = buildThreadFeed(thread, [], null)[0];
const group = buildThreadFeed(thread)[0];
expect(group).toMatchObject({ type: "activity-group" });
if (!group || group.type !== "activity-group") {
return;
@@ -271,7 +271,7 @@ describe("buildThreadFeed", () => {
],
});
const feed = buildThreadFeed(thread, [], null);
const feed = buildThreadFeed(thread);
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, [], null);
const feed = buildThreadFeed(thread);
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, [], null);
const feed = buildThreadFeed(thread);
expect(deriveThreadFeedPresentation(feed, thread.latestTurn, new Set())).toEqual(feed);
expect(feed[0]).toMatchObject({
type: "activity-group",
+1 -19
View File
@@ -1,6 +1,5 @@
import { ApprovalRequestId, isToolLifecycleItemType } from "@t3tools/contracts";
import type {
MessageId,
OrchestrationLatestTurn,
OrchestrationThread,
OrchestrationThreadActivity,
@@ -10,7 +9,6 @@ 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";
@@ -88,13 +86,6 @@ 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;
@@ -104,7 +95,7 @@ type RawThreadFeedEntry =
};
export type ThreadFeedEntry =
| Extract<RawThreadFeedEntry, { type: "message" | "queued-message" }>
| Extract<RawThreadFeedEntry, { type: "message" }>
| {
readonly type: "activity-group";
readonly id: string;
@@ -1255,8 +1246,6 @@ export function buildPendingUserInputAnswers(
export function buildThreadFeed(
thread: OrchestrationThread,
queuedMessages: ReadonlyArray<QueuedThreadMessage>,
dispatchingQueuedMessageId: MessageId | null,
options?: {
readonly loadedMessages?: ReadonlyArray<OrchestrationThread["messages"][number]>;
},
@@ -1273,13 +1262,6 @@ 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) {
@@ -1,32 +0,0 @@
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
@@ -1,22 +0,0 @@
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,7 +40,6 @@ 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;
@@ -77,7 +76,6 @@ export function useThreadComposerState() {
const { selectedThread: selectedThreadShell } = useThreadSelection();
const selectedThreadDetail = useSelectedThreadDetail();
const composerDrafts = useAtomValue(composerDraftsAtom);
const dispatchingQueuedMessageId = useAtomValue(dispatchingQueuedMessageIdAtom);
const queuedMessagesByThreadKey = useThreadOutboxMessages();
useEffect(() => {
@@ -91,17 +89,9 @@ export function useThreadComposerState() {
() => (selectedThreadKey ? (queuedMessagesByThreadKey[selectedThreadKey] ?? []) : []),
[queuedMessagesByThreadKey, selectedThreadKey],
);
const selectedThreadFeed = useMemo(
() =>
selectedThreadDetail
? buildThreadFeed(
selectedThreadDetail,
selectedThreadQueuedMessages,
dispatchingQueuedMessageId,
)
: [],
[dispatchingQueuedMessageId, selectedThreadDetail, selectedThreadQueuedMessages],
() => (selectedThreadDetail ? buildThreadFeed(selectedThreadDetail) : []),
[selectedThreadDetail],
);
const selectedDraft = selectedThreadKey ? composerDrafts[selectedThreadKey] : null;
@@ -125,7 +115,6 @@ export function useThreadComposerState() {
};
}, [selectedThreadDetail, selectedThreadShell]);
const queuedSendStartedAt = selectedThreadQueuedMessages[0]?.createdAt ?? null;
const activeWorkStartedAt = useMemo(() => {
const selectedThread = selectedThreadDetail ?? selectedThreadShell;
if (!selectedThread) {
@@ -135,14 +124,9 @@ export function useThreadComposerState() {
return deriveActiveWorkStartedAt(
selectedThread.latestTurn,
selectedThreadSessionActivity,
queuedSendStartedAt,
null,
);
}, [
queuedSendStartedAt,
selectedThreadDetail,
selectedThreadSessionActivity,
selectedThreadShell,
]);
}, [selectedThreadDetail, selectedThreadSessionActivity, selectedThreadShell]);
const activeThreadBusy =
!!selectedThread &&
@@ -150,7 +134,7 @@ export function useThreadComposerState() {
const onSendMessage = useCallback(async () => {
if (!selectedThreadShell) {
return;
return null;
}
const threadKey = scopedThreadKey(selectedThreadShell.environmentId, selectedThreadShell.id);
@@ -159,15 +143,16 @@ export function useThreadComposerState() {
const text = draft.text.trim();
const attachments = draft.attachments;
if (text.length === 0 && attachments.length === 0) {
return;
return null;
}
const metadata = makeQueuedMessageMetadata();
const messageId = MessageId.make(metadata.messageId);
try {
await enqueueThreadOutboxMessage({
environmentId: selectedThreadShell.environmentId,
threadId: selectedThreadShell.id,
messageId: MessageId.make(metadata.messageId),
messageId,
commandId: CommandId.make(metadata.commandId),
text,
attachments,
@@ -177,10 +162,12 @@ 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]);
+6 -1
View File
@@ -44,13 +44,18 @@ import { browserApiCorsAllowedHeaders, browserApiCorsAllowedMethods } from "./ht
const OTLP_TRACES_PROXY_PATH = "/api/observability/v1/traces";
const LOOPBACK_HOSTNAMES = new Set(["127.0.0.1", "::1", "localhost"]);
const DESKTOP_RENDERER_ORIGINS = ["t3code://app", "t3code-dev://app"];
export const browserApiCorsLayer = Layer.unwrap(
Effect.gen(function* () {
const config = yield* ServerConfig.ServerConfig;
const devOrigin = config.devUrl?.origin;
// Dev uses credentialed requests from Vite or the Electron custom origin, so both must be
// explicit. Packaged desktop omits credentials and uses Effect's default wildcard origin.
return HttpRouter.cors({
...(devOrigin ? { allowedOrigins: [devOrigin], credentials: true } : {}),
...(devOrigin
? { allowedOrigins: [devOrigin, ...DESKTOP_RENDERER_ORIGINS], credentials: true }
: {}),
allowedMethods: browserApiCorsAllowedMethods,
allowedHeaders: browserApiCorsAllowedHeaders,
maxAge: 600,
@@ -3,8 +3,10 @@ import {
type ModelCapabilities,
type ModelSelection,
ProviderDriverKind,
type ServerProviderAuth,
type ServerProviderModel,
type ServerProviderSlashCommand,
type ServerProviderState,
} from "@t3tools/contracts";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
@@ -30,11 +32,14 @@ import {
buildBooleanOptionDescriptor,
buildSelectOptionDescriptor,
buildServerProvider,
AUTH_PROBE_TIMEOUT_MS,
DEFAULT_TIMEOUT_MS,
extractAuthBoolean,
isCommandMissingCause,
parseGenericCliVersion,
providerModelsFromSettings,
spawnAndCollect,
type CommandResult,
type ServerProviderDraft,
} from "../providerSnapshot.ts";
import { makeClaudeEnvironment } from "../Drivers/ClaudeHome.ts";
@@ -444,6 +449,81 @@ function claudeAuthMetadata(input: {
return undefined;
}
function parseClaudeAuthStatusFromOutput(result: CommandResult): {
readonly status: Exclude<ServerProviderState, "disabled">;
readonly auth: Pick<ServerProviderAuth, "status">;
readonly message?: string;
} {
const lowerOutput = `${result.stdout}\n${result.stderr}`.toLowerCase();
if (
lowerOutput.includes("unknown command") ||
lowerOutput.includes("unrecognized command") ||
lowerOutput.includes("unexpected argument")
) {
return {
status: "warning",
auth: { status: "unknown" },
message:
"Claude Agent authentication status command is unavailable in this version of Claude.",
};
}
if (
lowerOutput.includes("not logged in") ||
lowerOutput.includes("login required") ||
lowerOutput.includes("authentication required") ||
lowerOutput.includes("run `claude login`") ||
lowerOutput.includes("run claude login")
) {
return {
status: "error",
auth: { status: "unauthenticated" },
message: "Claude is not authenticated. Run `claude auth login` and try again.",
};
}
const trimmedStdout = result.stdout.trim();
let parsedAuth: boolean | undefined;
let parsedJson = false;
if (trimmedStdout.startsWith("{") || trimmedStdout.startsWith("[")) {
try {
parsedAuth = extractAuthBoolean(JSON.parse(trimmedStdout) as unknown);
parsedJson = true;
} catch {
// Fall through to the command exit status for non-JSON output.
}
}
if (parsedAuth === true) {
return { status: "ready", auth: { status: "authenticated" } };
}
if (parsedAuth === false) {
return {
status: "error",
auth: { status: "unauthenticated" },
message: "Claude is not authenticated. Run `claude auth login` and try again.",
};
}
if (parsedJson) {
return {
status: "warning",
auth: { status: "unknown" },
message:
"Could not verify Claude authentication status from JSON output (missing auth marker).",
};
}
if (result.code === 0) {
return { status: "ready", auth: { status: "authenticated" } };
}
return {
status: "warning",
auth: { status: "unknown" },
message: "Could not verify Claude authentication status.",
};
}
// ── SDK capability probe ────────────────────────────────────────────
const CAPABILITIES_PROBE_TIMEOUT_MS = 8_000;
@@ -741,6 +821,34 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(
const dedupedSlashCommands = dedupeSlashCommands(slashCommands);
if (!capabilities) {
const authProbe = yield* runClaudeCommand(
claudeSettings,
["auth", "status"],
resolvedEnvironment,
).pipe(Effect.timeoutOption(AUTH_PROBE_TIMEOUT_MS), Effect.result);
if (Result.isSuccess(authProbe) && Option.isSome(authProbe.success)) {
const parsedAuth = parseClaudeAuthStatusFromOutput(authProbe.success.value);
return buildServerProvider({
presentation: CLAUDE_PRESENTATION,
enabled: claudeSettings.enabled,
checkedAt,
models,
slashCommands: dedupedSlashCommands,
probe: {
installed: true,
version: parsedVersion,
status: parsedAuth.status,
auth: parsedAuth.auth,
...(parsedAuth.message
? { message: parsedAuth.message }
: versionUpgradeMessage
? { message: versionUpgradeMessage }
: {}),
},
});
}
return buildServerProvider({
presentation: CLAUDE_PRESENTATION,
enabled: claudeSettings.enabled,
@@ -752,7 +860,10 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(
version: parsedVersion,
status: "warning",
auth: { status: "unknown" },
message: "Could not verify Claude authentication status from initialization result.",
message:
Result.isSuccess(authProbe) && Option.isNone(authProbe.success)
? "Could not verify Claude authentication status. Timed out while running command."
: "Could not verify Claude authentication status.",
},
});
}
@@ -1902,18 +1902,44 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsModule.layerTest(), Te
);
});
it.effect("returns warning when the Claude initialization result is unavailable", () =>
it.effect("falls back to CLI auth when the Claude initialization result is unavailable", () =>
Effect.gen(function* () {
const status = yield* checkClaudeProviderStatus(
defaultClaudeSettings,
noClaudeCapabilities,
);
assert.strictEqual(status.status, "warning");
assert.strictEqual(status.status, "ready");
assert.strictEqual(status.installed, true);
assert.strictEqual(status.auth.status, "unknown");
assert.strictEqual(status.auth.status, "authenticated");
}).pipe(
Effect.provide(
mockSpawnerLayer((args) => {
const joined = args.join(" ");
if (joined === "--version") return { stdout: "1.0.0\n", stderr: "", code: 0 };
if (joined === "auth status")
return {
stdout: '{"loggedIn":true,"authMethod":"third_party","apiProvider":"bedrock"}\n',
stderr: "",
code: 0,
};
throw new Error(`Unexpected args: ${joined}`);
}),
),
),
);
it.effect("returns unauthenticated when the CLI auth fallback reports logged out", () =>
Effect.gen(function* () {
const status = yield* checkClaudeProviderStatus(
defaultClaudeSettings,
noClaudeCapabilities,
);
assert.strictEqual(status.status, "error");
assert.strictEqual(status.installed, true);
assert.strictEqual(status.auth.status, "unauthenticated");
assert.strictEqual(
status.message,
"Could not verify Claude authentication status from initialization result.",
"Claude is not authenticated. Run `claude auth login` and try again.",
);
}).pipe(
Effect.provide(
+26
View File
@@ -3233,6 +3233,32 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
);
for (const desktopOrigin of ["t3code://app", "t3code-dev://app"]) {
it.effect(`allows credentialed preflights from ${desktopOrigin} in development`, () =>
Effect.gen(function* () {
yield* buildAppUnderTest({
config: { devUrl: new URL(crossOriginClientOrigin) },
});
const sessionUrl = yield* getHttpServerUrl("/api/auth/session");
const response = yield* fetchEffect(sessionUrl, {
method: "OPTIONS",
headers: {
origin: desktopOrigin,
"access-control-request-method": "GET",
"access-control-request-headers": "content-type",
},
});
assert.equal(response.status, 204);
assertBrowserApiCorsPreflightHeaders(response.headers, {
origin: desktopOrigin,
credentials: true,
});
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
);
}
it.effect("includes CORS headers on remote websocket-ticket auth failures", () =>
Effect.gen(function* () {
yield* buildAppUnderTest();
+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.0.0-beta.44",
"@legendapp/list": "3.2.0",
"@lexical/react": "^0.41.0",
"@pierre/diffs": "catalog:",
"@pierre/trees": "1.0.0-beta.4",
@@ -518,7 +518,7 @@ export function BranchToolbarBranchSelector({
return;
}
branchListRef.current?.scrollToOffset?.({ offset: 0, animated: false });
void 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;
}
branchListRef.current?.scrollIndexIntoView?.({
void branchListRef.current?.scrollIndexIntoView?.({
index: eventDetails.index,
animated: false,
});
@@ -696,6 +696,13 @@ 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}
+7 -3
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 { useClientSettings } from "../hooks/useSettings";
import { getClientSettings } from "../hooks/useSettings";
import {
chatMarkdownClipboardPayload,
serializeTableElementToCsv,
@@ -293,10 +293,14 @@ 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(useClientSettings((settings) => settings.wordWrap));
const [expanded, setExpanded] = useState(readInitialWordWrapSetting);
const [copied, setCopied] = useState(false);
const copiedTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const expandLabel = expanded ? "Collapse table cells" : "Expand table cells";
@@ -526,7 +530,7 @@ function MarkdownCodeBlock({
children: ReactNode;
}) {
const [copied, setCopied] = useState(false);
const [wrapped, setWrapped] = useState(useClientSettings((settings) => settings.wordWrap));
const [wrapped, setWrapped] = useState(readInitialWordWrapSetting);
const copiedTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const wrapLabel = wrapped ? "Disable line wrap" : "Wrap lines";
const copyLabel = copied ? "Copied" : "Copy code";
+178 -114
View File
@@ -41,7 +41,17 @@ 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, useMemo, useRef, useState } from "react";
import {
lazy,
memo,
Suspense,
useCallback,
useEffect,
useLayoutEffect,
useMemo,
useRef,
useState,
} from "react";
import { useNavigate } from "@tanstack/react-router";
import { useShallow } from "zustand/react/shallow";
import {
@@ -1137,12 +1147,32 @@ 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),
);
@@ -1254,6 +1284,14 @@ 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),
);
@@ -3111,7 +3149,7 @@ function ChatViewContent(props: ChatViewProps) {
// Scroll helpers — LegendList handles auto-scroll via maintainScrollAtEnd.
const scrollToEnd = useCallback((animated = false) => {
legendListRef.current?.scrollToEnd?.({ animated });
void legendListRef.current?.scrollToEnd?.({ animated });
}, []);
// Debounce *showing* the scroll-to-bottom pill so it doesn't flash during
@@ -3690,14 +3728,16 @@ function ChatViewContent(props: ChatViewProps) {
sizeBytes: image.sizeBytes,
previewUrl: image.previewUrl,
}));
// 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.
// 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.
isAtEndRef.current = true;
showScrollDebouncer.current.cancel();
setShowScrollToBottom(false);
await legendListRef.current?.scrollToEnd?.({ animated: false });
setTimelineAnchor({
threadKey: scopedThreadKey(scopeThreadRef(activeThread.environmentId, threadIdForSend)),
messageId: messageIdForSend,
});
setOptimisticUserMessages((existing) => [
...existing,
{
@@ -3711,6 +3751,7 @@ function ChatViewContent(props: ChatViewProps) {
streaming: false,
},
]);
void legendListRef.current?.scrollToEnd?.({ animated: false });
setThreadError(threadIdForSend, null);
if (expiredTerminalContextCount > 0) {
@@ -4722,7 +4763,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="flex min-h-0 min-w-0 flex-1 flex-col">
<div className="relative 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 */}
@@ -4747,12 +4788,17 @@ 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 bottom-1 left-1/2 z-30 flex -translate-x-1/2 justify-center py-1.5">
<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 }}
>
<button
type="button"
onClick={() => scrollToEnd(true)}
@@ -4767,115 +4813,133 @@ function ChatViewContent(props: ChatViewProps) {
{/* Input bar */}
<div
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)]",
)}
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"
>
<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
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>
</div>
{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,
<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
}
: {})}
envLocked={envLocked}
onComposerFocusRequest={scheduleComposerFocus}
{...(canCheckoutPullRequestIntoThread
? { onCheckoutPullRequestRequest: openPullRequestDialog }
: {})}
{...(hasMultipleEnvironments ? { onEnvironmentChange } : {})}
availableEnvironments={logicalProjectEnvironments}
/>
)}
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>
</div>
{pullRequestDialogState ? (
@@ -20,6 +20,7 @@ import { Menu, MenuItem, MenuPopup, MenuTrigger } from "~/components/ui/menu";
import { ScrollArea } from "~/components/ui/scroll-area";
import { faviconUrlForOrigin } from "~/lib/favicon";
import { useTheme } from "~/hooks/useTheme";
import { COLLAPSED_SIDEBAR_TITLEBAR_INSET_CLASS } from "~/workspaceTitlebar";
import { PreviewPanelShell, type PreviewPanelMode } from "./preview/PreviewPanelShell";
import { PierreEntryIcon } from "./chat/PierreEntryIcon";
@@ -346,6 +347,7 @@ export function RightPanelTabs(props: RightPanelTabsProps) {
"workspace-topbar gap-1 pl-2",
props.mode === "inline" ? "pr-28" : "pr-3",
ownsDesktopTitleBar && "wco:pr-[calc(var(--workspace-native-controls-inset)+6rem)]",
props.mode === "inline" && props.maximized && COLLAPSED_SIDEBAR_TITLEBAR_INSET_CLASS,
)}
data-right-panel-tabbar
>
+4 -26
View File
@@ -504,10 +504,6 @@ 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;
@@ -593,8 +589,6 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
composerImagesRef,
composerTerminalContextsRef,
composerElementContextsRef,
shouldAutoScrollRef,
scheduleStickToBottom,
onSend,
onInterrupt,
onImplementPlanInNewThread,
@@ -896,7 +890,6 @@ 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[]>([]);
@@ -1329,15 +1322,12 @@ 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((entries) => {
const [entry] = entries;
if (!entry) return;
const observer = new ResizeObserver(() => {
const nextCompactness = measureFooterCompactness();
setIsComposerPrimaryActionsCompact((previous) =>
previous === nextCompactness.primaryActionsCompact
@@ -1347,25 +1337,13 @@ 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,
scheduleStickToBottom,
shouldAutoScrollRef,
]);
}, [activeThreadId, composerFooterActionLayoutKey, composerFooterHasWideActions]);
// ------------------------------------------------------------------
// Image persist effect
@@ -2083,8 +2061,8 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
ref={composerSurfaceRef}
data-chat-composer-mobile-collapsed={isComposerCollapsedMobile ? "true" : "false"}
className={cn(
"rounded-[20px] border bg-card transition-colors duration-200 has-focus-visible:border-ring/45",
isDragOverComposer ? "border-primary/70 bg-accent/30" : "border-border",
"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",
environmentUnavailable ? "opacity-75" : null,
composerProviderState.composerSurfaceClassName,
)}
@@ -13,9 +13,21 @@ 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}>
<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}
>
{props.ListHeaderComponent}
{props.data.map((item) => (
<div key={props.keyExtractor(item)}>{props.renderItem({ item })}</div>
@@ -109,6 +121,8 @@ function buildProps() {
resolvedTheme: "light" as const,
timestampFormat: "locale" as const,
workspaceRoot: undefined,
anchorMessageId: null,
contentInsetEndAdjustment: 0,
onIsAtEndChange: () => {},
};
}
@@ -137,6 +151,42 @@ 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(
@@ -193,6 +243,33 @@ 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,6 +6,7 @@ import {
type TurnId,
} from "@t3tools/contracts";
import { parseScopedThreadKey } from "@t3tools/client-runtime/environment";
import { resolveChatListAnchoredEndSpace } from "@t3tools/shared/chatList";
import {
createContext,
Fragment,
@@ -165,6 +166,8 @@ interface MessagesTimelineProps {
timestampFormat: TimestampFormat;
workspaceRoot: string | undefined;
skills?: ReadonlyArray<Pick<ServerProviderSkill, "name" | "displayName">>;
anchorMessageId: MessageId | null;
contentInsetEndAdjustment: number;
onIsAtEndChange: (isAtEnd: boolean) => void;
}
@@ -192,6 +195,8 @@ export const MessagesTimeline = memo(function MessagesTimeline({
timestampFormat,
workspaceRoot,
skills = EMPTY_TIMELINE_SKILLS,
anchorMessageId,
contentInsetEndAdjustment,
onIsAtEndChange,
}: MessagesTimelineProps) {
const [expandedTurnIds, setExpandedTurnIds] = useState<ReadonlySet<TurnId>>(new Set());
@@ -284,6 +289,13 @@ 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?.();
@@ -292,24 +304,6 @@ 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,
@@ -376,14 +370,17 @@ 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 overflow-x-hidden overscroll-y-contain px-3 sm:px-5"
className="scrollbar-gutter-both h-full min-h-0 overflow-x-hidden overscroll-y-contain px-3 sm:px-5"
ListHeaderComponent={TIMELINE_LIST_HEADER}
ListFooterComponent={TIMELINE_LIST_FOOTER}
/>
@@ -396,6 +393,10 @@ 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
// ---------------------------------------------------------------------------
@@ -448,6 +449,10 @@ 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";
@@ -495,9 +500,9 @@ function UserTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "message"
image={previewImages[index] ?? null}
/>
))}
{elementContextState.contexts.length > 0 ? (
{elementContexts.length > 0 ? (
<div className="mb-2 flex flex-wrap gap-1.5">
{elementContextState.contexts.map((context) => (
{elementContexts.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) {
modelListRef.current?.scrollIndexIntoView?.({
void modelListRef.current?.scrollIndexIntoView?.({
index: eventDetails.index,
animated: false,
});
+54 -1
View File
@@ -5,6 +5,7 @@
@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);
@@ -144,6 +145,58 @@
.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.
@@ -299,7 +352,7 @@ code {
/* Scrollbar styling */
::-webkit-scrollbar {
width: 6px;
width: var(--app-scrollbar-width);
}
::-webkit-scrollbar-track {
+1
View File
@@ -156,6 +156,7 @@ export default defineConfig(() => {
// connection logs — enable "Verbose" in DevTools to see them.
protocol: "ws",
host,
clientPort: port,
},
},
build: {
+4
View File
@@ -167,6 +167,10 @@
"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
@@ -0,0 +1,42 @@
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
@@ -0,0 +1,33 @@
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;
}
+1108 -739
View File
File diff suppressed because it is too large. Load diff
+4 -8
View File
@@ -27,13 +27,11 @@ catalog:
"@pierre/diffs": 1.3.0-beta.5
"@types/node": 24.12.4
"@typescript/native-preview": 7.0.0-dev.20260604.1
"@vitest/runner": 4.1.8
effect: 4.0.0-beta.78
jose: 6.2.2
typescript: ~6.0.3
vite: npm:@voidzero-dev/vite-plus-core@0.1.24
vite-plus: 0.1.24
vitest: npm:@voidzero-dev/[email protected]
vite: npm:@voidzero-dev/vite-plus-core@0.2.1
vite-plus: 0.2.1
yaml: ^2.9.0
ignoredBuiltDependencies:
@@ -70,14 +68,14 @@ overrides:
"@effect/sql-pg": "catalog:"
"@effect/sql-sqlite-bun": "catalog:"
"@effect/vitest": "catalog:"
"@effect/vitest>@vitest/runner": "-"
# @effect/vitest is patched to use vite-plus/test; do not auto-install its
# upstream Vitest peer and create a second Vite/Vitest toolchain.
"@effect/vitest>vitest": "-"
"@expo/metro-config": 56.0.13
"@pierre/diffs>@shikijs/transformers": ^4.2.0
"@types/node": "catalog:"
effect: "catalog:"
vite: "catalog:"
vitest: "catalog:"
yaml: "catalog:"
packageExtensions:
@@ -102,7 +100,5 @@ patchedDependencies:
peerDependencyRules:
allowAny:
- vite
- vitest
allowedVersions:
vite: "*"
vitest: "*"