Merge branch 'main' into josh/desktop-wsl-parallel-backends

This commit is contained in:
Julius Marminge authored and GitHub committed 2026-06-25 14:04:09 -07:00
commit 520144f76c
42 files changed
+2438 -1323

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]);
+9 -18
View File
@@ -3,7 +3,8 @@ import * as Crypto from "effect/Crypto";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as Encoding from "effect/Encoding";
import type * as HttpServerRequest from "effect/unstable/http/HttpServerRequest";
import * as Option from "effect/Option";
import * as HttpServerRequest from "effect/unstable/http/HttpServerRequest";
import {
ServerAuthDpopReplayKeyCalculationError,
@@ -13,22 +14,6 @@ import {
} from "./EnvironmentAuth.ts";
import * as ServerSecretStore from "./ServerSecretStore.ts";
function firstHeaderValue(value: string | undefined): string | undefined {
const first = value?.split(",")[0]?.trim();
return first && first.length > 0 ? first : undefined;
}
export function requestAbsoluteUrl(request: HttpServerRequest.HttpServerRequest): string {
try {
return new URL(request.originalUrl).href;
} catch {
const host = firstHeaderValue(request.headers.host) ?? "127.0.0.1";
const forwardedProto = firstHeaderValue(request.headers["x-forwarded-proto"]);
const proto = forwardedProto === "https" || forwardedProto === "http" ? forwardedProto : "http";
return new URL(request.originalUrl, `${proto}://${host}`).href;
}
}
export const mapDpopReplayStoreError = (
error: ServerSecretStore.SecretStoreError,
): ServerAuthInvalidCredentialError | ServerAuthInternalError =>
@@ -48,11 +33,17 @@ export const verifyRequestDpopProof = (input: {
}) =>
Effect.gen(function* () {
const proof = input.request.headers.dpop;
const url = HttpServerRequest.toURL(input.request);
if (Option.isNone(url)) {
return yield* new ServerAuthInvalidCredentialError({
diagnostic: "Invalid DPoP request URL.",
});
}
const now = yield* DateTime.now;
const result = verifyDpopProof({
proof,
method: input.request.method,
url: requestAbsoluteUrl(input.request),
url: url.value.href,
nowEpochSeconds: Math.floor(now.epochMilliseconds / 1_000),
...(input.expectedThumbprint ? { expectedThumbprint: input.expectedThumbprint } : {}),
...(input.expectedAccessToken ? { expectedAccessToken: input.expectedAccessToken } : {}),
+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,
@@ -4,6 +4,7 @@ import * as NodeServices from "@effect/platform-node/NodeServices";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Path from "effect/Path";
import type * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
import { describe, expect, it } from "vite-plus/test";
import type * as EffectAcpSchema from "effect-acp/schema";
import type { CursorSettings } from "@t3tools/contracts";
@@ -24,7 +25,11 @@ import {
} from "./CursorProvider.ts";
const runNode = <A, E>(
effect: Effect.Effect<A, E, FileSystem.FileSystem | Path.Path>,
effect: Effect.Effect<
A,
E,
ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem | Path.Path
>,
): Promise<A> => Effect.runPromise(effect.pipe(Effect.provide(NodeServices.layer)));
const resolveMockAgentPath = Effect.fn("resolveMockAgentPath")(function* () {
@@ -293,6 +298,18 @@ const baseCursorSettings: CursorSettings = {
apiEndpoint: "",
customModels: [],
};
const cursorAcpDiscoveryFailedMessage = [
"Cursor ACP model discovery failed.",
"Cursor CLI setup may be incomplete; install or enable the Cursor CLI, restart T3 Code, and try again.",
"See https://cursor.com/docs/cli/installation.",
"Check server logs for ACP details.",
].join(" ");
const missingCursorBinaryPath = "/definitely/not/installed/t3-cursor-agent";
const cursorCliCommandMissingMessage = [
`Cursor CLI command \`${missingCursorBinaryPath}\` was not found.`,
`Install or enable the Cursor CLI, make sure \`${missingCursorBinaryPath}\` is on PATH, then restart T3 Code.`,
"See https://cursor.com/docs/cli/installation.",
].join(" ");
describe("getCursorFallbackModels", () => {
it("does not publish any built-in cursor models before ACP discovery", () => {
@@ -338,12 +355,11 @@ describe("buildCursorProviderSnapshot", () => {
auth: { status: "unauthenticated" },
message: "Cursor Agent is not authenticated. Run `agent login` and try again.",
},
discoveryWarning: "Cursor ACP model discovery failed. Check server logs for details.",
discoveryWarning: cursorAcpDiscoveryFailedMessage,
}),
).toMatchObject({
status: "error",
message:
"Cursor Agent is not authenticated. Run `agent login` and try again. Cursor ACP model discovery failed. Check server logs for details.",
message: `Cursor Agent is not authenticated. Run \`agent login\` and try again. ${cursorAcpDiscoveryFailedMessage}`,
models: [
{
slug: "claude-sonnet-4-6",
@@ -411,10 +427,28 @@ describe("buildCursorCapabilitiesFromConfigOptions", () => {
});
describe("checkCursorProviderStatus", () => {
it("reports the install docs when the Cursor CLI command is missing", async () => {
const provider = await runNode(
checkCursorProviderStatus({
enabled: true,
binaryPath: missingCursorBinaryPath,
apiEndpoint: "",
customModels: [],
}),
);
expect(provider).toMatchObject({
installed: false,
status: "error",
auth: { status: "unknown" },
message: cursorCliCommandMissingMessage,
});
});
it("passes the injected environment to ACP model discovery", async () => {
const { requestLogPath, wrapperPath } = await runNode(makeProviderStatusEnvFixture());
const provider = await Effect.runPromise(
const provider = await runNode(
checkCursorProviderStatus(
{
enabled: true,
@@ -426,7 +460,7 @@ describe("checkCursorProviderStatus", () => {
...process.env,
T3_ACP_REQUEST_LOG_PATH: requestLogPath,
},
).pipe(Effect.provide(NodeServices.layer)),
),
);
expect(provider.models.map((model) => model.slug)).toEqual([
@@ -443,13 +477,13 @@ describe("discoverCursorModelsViaAcp", () => {
it("keeps the ACP probe runtime alive long enough to discover models", async () => {
const wrapperPath = await runNode(makeMockAgentWrapper());
const models = await Effect.runPromise(
const models = await runNode(
discoverCursorModelsViaAcp({
enabled: true,
binaryPath: wrapperPath,
apiEndpoint: "",
customModels: [],
}).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
}).pipe(Effect.scoped),
);
expect(models.map((model) => model.slug)).toEqual([
@@ -465,13 +499,13 @@ describe("discoverCursorModelsViaAcp", () => {
makeExitLogFixture("cursor-provider-exit-log-"),
);
await Effect.runPromise(
await runNode(
discoverCursorModelsViaAcp({
enabled: true,
binaryPath: wrapperPath,
apiEndpoint: "",
customModels: [],
}).pipe(Effect.provide(NodeServices.layer)),
}),
);
const exitLog = await runNode(waitForFileContent(exitLogPath));
@@ -62,6 +62,13 @@ const EMPTY_CAPABILITIES: ModelCapabilities = createModelCapabilities({
const CURSOR_ACP_MODEL_DISCOVERY_TIMEOUT_MS = 15_000;
const CURSOR_PARAMETERIZED_MODEL_PICKER_MIN_VERSION_DATE = 2026_04_08;
const CURSOR_CLI_INSTALLATION_DOCS_URL = "https://cursor.com/docs/cli/installation";
const CURSOR_ACP_MODEL_DISCOVERY_FAILED_MESSAGE = [
"Cursor ACP model discovery failed.",
"Cursor CLI setup may be incomplete; install or enable the Cursor CLI, restart T3 Code, and try again.",
`See ${CURSOR_CLI_INSTALLATION_DOCS_URL}.`,
"Check server logs for ACP details.",
].join(" ");
export const CURSOR_PARAMETERIZED_MODEL_PICKER_CAPABILITIES = {
_meta: {
parameterizedModelPicker: true,
@@ -608,6 +615,14 @@ function joinProviderMessages(...messages: ReadonlyArray<string | undefined>): s
return parts.length > 0 ? parts.join(" ") : undefined;
}
function buildCursorCliCommandMissingMessage(binaryPath: string): string {
return [
`Cursor CLI command \`${binaryPath}\` was not found.`,
`Install or enable the Cursor CLI, make sure \`${binaryPath}\` is on PATH, then restart T3 Code.`,
`See ${CURSOR_CLI_INSTALLATION_DOCS_URL}.`,
].join(" ");
}
export function buildCursorProviderSnapshot(input: {
readonly checkedAt: string;
readonly cursorSettings: CursorSettings;
@@ -1020,7 +1035,7 @@ export const checkCursorProviderStatus = Effect.fn("checkCursorProviderStatus")(
status: "error",
auth: { status: "unknown" },
message: isCommandMissingCause(error)
? "Cursor Agent CLI (`agent`) is not installed or not on PATH."
? buildCursorCliCommandMissingMessage(cursorSettings.binaryPath)
: "Failed to execute Cursor Agent CLI health check.",
},
});
@@ -1079,7 +1094,7 @@ export const checkCursorProviderStatus = Effect.fn("checkCursorProviderStatus")(
yield* Effect.logWarning("Cursor ACP model discovery failed", {
errorTag: causeErrorTag(discoveryExit.cause),
});
discoveryWarning = "Cursor ACP model discovery failed. Check server logs for details.";
discoveryWarning = CURSOR_ACP_MODEL_DISCOVERY_FAILED_MESSAGE;
} else if (Option.isNone(discoveryExit.value)) {
discoveryWarning = `Cursor ACP model discovery timed out after ${CURSOR_ACP_MODEL_DISCOVERY_TIMEOUT_MS}ms.`;
} else if (discoveryExit.value.value.length === 0) {
+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",
@@ -33,6 +33,7 @@ import {
readPrimaryCloudLinkState,
type CloudLinkTarget,
unlinkPrimaryEnvironmentFromCloud,
updatePrimaryCloudPreferences,
} from "./linkEnvironment";
const TARGET: CloudLinkTarget = {
@@ -252,6 +253,38 @@ describe("web cloud link environment client", () => {
}),
);
it.effect("updates agent activity publishing for the explicit primary target", () =>
Effect.gen(function* () {
const fetchMock = vi.fn().mockResolvedValue(
Response.json({
linked: true,
cloudUserId: "user-1",
relayUrl: "https://relay.example.test",
relayIssuer: "https://relay.example.test",
publishAgentActivity: true,
}),
);
vi.stubGlobal("fetch", fetchMock);
const state = yield* withServices(
updatePrimaryCloudPreferences({
target: TARGET,
publishAgentActivity: true,
}),
);
expect(state.publishAgentActivity).toBe(true);
expect(String(fetchMock.mock.calls[0]?.[0])).toBe(
"http://127.0.0.1:3000/api/connect/preferences",
);
expect(fetchMock.mock.calls[0]?.[1]?.method).toBe("POST");
// @effect-diagnostics-next-line preferSchemaOverJson:off
expect(JSON.parse(bodyText(fetchMock.mock.calls[0]?.[1]?.body))).toEqual({
publishAgentActivity: true,
});
}),
);
it.effect("links an available primary environment without invoking installation", () =>
Effect.gen(function* () {
const fetchMock = vi
@@ -8,6 +8,7 @@ import {
linkPrimaryEnvironmentToCloud,
type CloudLinkTarget,
unlinkPrimaryEnvironmentFromCloud,
updatePrimaryCloudPreferences,
} from "./linkEnvironment";
const cloudLinkScheduler = createAtomCommandScheduler();
@@ -31,3 +32,11 @@ export const unlinkPrimaryEnvironment = createRuntimeCommand(connectionAtomRunti
execute: (input: { readonly target: CloudLinkTarget; readonly clerkToken: string | null }) =>
unlinkPrimaryEnvironmentFromCloud(input),
});
export const updatePrimaryEnvironmentPreferences = createRuntimeCommand(connectionAtomRuntime, {
label: "web:cloud:update-primary-environment-preferences",
scheduler: cloudLinkScheduler,
concurrency: cloudLinkConcurrency,
execute: (input: { readonly target: CloudLinkTarget; readonly publishAgentActivity: boolean }) =>
updatePrimaryCloudPreferences(input),
});
@@ -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,
});
@@ -0,0 +1,65 @@
import type { RelayClientDeviceRecord } from "@t3tools/contracts/relay";
import { describe, expect, it } from "vite-plus/test";
import {
mobileClientNotificationDetail,
mobileClientPlatformLabel,
mobileClientUpdatedAtLabel,
} from "./MobileClientsUserProfilePage.logic";
function device(overrides: Partial<RelayClientDeviceRecord> = {}): RelayClientDeviceRecord {
return {
deviceId: "device-1",
label: "Julius’s iPhone",
platform: "ios",
iosMajorVersion: 18,
appVersion: "1.2.3",
notifications: {
enabled: true,
notifyOnApproval: true,
notifyOnInput: false,
notifyOnCompletion: true,
notifyOnFailure: false,
},
liveActivities: { enabled: true },
updatedAt: "2026-06-21T12:00:00.000Z",
...overrides,
};
}
describe("mobile client presentation", () => {
it("describes the client platform and enabled notification events", () => {
const client = device();
expect(mobileClientPlatformLabel(client)).toBe("iOS 18 · T3 Code 1.2.3");
expect(mobileClientNotificationDetail(client)).toBe(
"Alerts enabled for approvals, completions.",
);
});
it("distinguishes disabled notifications from an empty event selection", () => {
expect(
mobileClientNotificationDetail(
device({ notifications: { ...device().notifications, enabled: false } }),
),
).toBe("Push notifications are disabled on this device.");
expect(
mobileClientNotificationDetail(
device({
notifications: {
enabled: true,
notifyOnApproval: false,
notifyOnInput: false,
notifyOnCompletion: false,
notifyOnFailure: false,
},
}),
),
).toBe("Push notifications are enabled, but no alert types are selected.");
});
it("handles missing app versions and invalid update timestamps", () => {
expect(mobileClientPlatformLabel(device({ appVersion: null }))).toBe("iOS 18");
expect(mobileClientUpdatedAtLabel("not-a-date")).toBe("Update time unavailable");
});
});
@@ -0,0 +1,39 @@
import type { RelayClientDeviceRecord } from "@t3tools/contracts/relay";
const mobileClientUpdatedAtFormatter = new Intl.DateTimeFormat(undefined, {
dateStyle: "medium",
timeStyle: "short",
});
const NOTIFICATION_PREFERENCES = [
["notifyOnApproval", "approvals"],
["notifyOnInput", "input requests"],
["notifyOnCompletion", "completions"],
["notifyOnFailure", "failures"],
] as const satisfies ReadonlyArray<
readonly [keyof RelayClientDeviceRecord["notifications"], string]
>;
export function mobileClientPlatformLabel(device: RelayClientDeviceRecord): string {
return `iOS ${device.iosMajorVersion}${device.appVersion ? ` · T3 Code ${device.appVersion}` : ""}`;
}
export function mobileClientNotificationDetail(device: RelayClientDeviceRecord): string {
if (!device.notifications.enabled) {
return "Push notifications are disabled on this device.";
}
const enabledPreferences = NOTIFICATION_PREFERENCES.flatMap(([preference, label]) =>
device.notifications[preference] ? [label] : [],
);
return enabledPreferences.length > 0
? `Alerts enabled for ${enabledPreferences.join(", ")}.`
: "Push notifications are enabled, but no alert types are selected.";
}
export function mobileClientUpdatedAtLabel(updatedAt: string): string {
const date = new Date(updatedAt);
return Number.isNaN(date.getTime())
? "Update time unavailable"
: `Updated ${mobileClientUpdatedAtFormatter.format(date)}`;
}
@@ -0,0 +1,166 @@
import type { RelayClientDeviceRecord } from "@t3tools/contracts/relay";
import { RefreshCwIcon, SmartphoneIcon } from "lucide-react";
import { useManagedRelayDevices } from "../../cloud/managedRelayState";
import { cn } from "../../lib/utils";
import { Badge } from "../ui/badge";
import { Button } from "../ui/button";
import { Empty, EmptyDescription, EmptyHeader, EmptyMedia, EmptyTitle } from "../ui/empty";
import { Skeleton } from "../ui/skeleton";
import {
mobileClientNotificationDetail,
mobileClientPlatformLabel,
mobileClientUpdatedAtLabel,
} from "./MobileClientsUserProfilePage.logic";
const MOBILE_CLIENT_SKELETON_ROWS = ["primary", "secondary"] as const;
function MobileClientStatusBadge({
enabled,
label,
}: {
readonly enabled: boolean;
readonly label: string;
}) {
return (
<Badge variant={enabled ? "success" : "outline"}>
{label}: {enabled ? "On" : "Off"}
</Badge>
);
}
function MobileClientRow({ device }: { readonly device: RelayClientDeviceRecord }) {
return (
<li className="rounded-xl border bg-card p-4 text-card-foreground shadow-sm/4">
<div className="flex items-start gap-3">
<div className="flex size-9 shrink-0 items-center justify-center rounded-lg border bg-muted/40 text-muted-foreground">
<SmartphoneIcon className="size-4" />
</div>
<div className="min-w-0 flex-1">
<div className="flex flex-col gap-1 sm:flex-row sm:items-start sm:justify-between sm:gap-3">
<div className="min-w-0">
<h3 className="truncate text-sm font-semibold text-foreground">{device.label}</h3>
<p className="text-xs text-muted-foreground">{mobileClientPlatformLabel(device)}</p>
</div>
<p className="shrink-0 text-[11px] text-muted-foreground/75">
{mobileClientUpdatedAtLabel(device.updatedAt)}
</p>
</div>
<div className="mt-3 flex flex-wrap gap-1.5">
<MobileClientStatusBadge
enabled={device.notifications.enabled}
label="Push notifications"
/>
<MobileClientStatusBadge
enabled={device.liveActivities.enabled}
label="Live Activities"
/>
</div>
<p className="mt-2 text-xs leading-relaxed text-muted-foreground/80">
{mobileClientNotificationDetail(device)}
</p>
</div>
</div>
</li>
);
}
function MobileClientsSkeleton() {
return (
<div aria-label="Loading mobile clients" className="space-y-3" role="status">
{MOBILE_CLIENT_SKELETON_ROWS.map((row) => (
<div key={row} className="rounded-xl border p-4">
<div className="flex gap-3">
<Skeleton className="size-9 shrink-0 rounded-lg" />
<div className="flex-1 space-y-2">
<Skeleton className="h-4 w-36" />
<Skeleton className="h-3 w-28" />
<div className="flex gap-2 pt-1">
<Skeleton className="h-5 w-28" />
<Skeleton className="h-5 w-24" />
</div>
</div>
</div>
</div>
))}
</div>
);
}
function EmptyMobileClients() {
return (
<Empty className="min-h-72 rounded-xl border border-dashed bg-muted/15">
<EmptyMedia variant="icon">
<SmartphoneIcon />
</EmptyMedia>
<EmptyHeader>
<EmptyTitle>No mobile clients</EmptyTitle>
<EmptyDescription>
Sign in to T3 Code on your iPhone to register it for push notifications and Live
Activities.
</EmptyDescription>
</EmptyHeader>
</Empty>
);
}
export function MobileClientsUserProfilePage() {
const devicesState = useManagedRelayDevices();
const devices = devicesState.data ?? [];
const isInitialLoad =
!devicesState.accountId || (devicesState.data === null && !devicesState.error);
const hasErrorWithoutData = devicesState.error !== null && devicesState.data === null;
return (
<div className="flex min-h-[30rem] w-full flex-col bg-background text-foreground">
<header className="flex flex-col gap-4 border-b px-6 py-5 sm:flex-row sm:items-center sm:justify-between">
<div>
<h2 className="text-base font-semibold tracking-[-0.01em]">Mobile clients</h2>
<p className="mt-1 text-sm text-muted-foreground">
Devices registered to receive T3 Connect activity from your environments.
</p>
</div>
<Button
size="sm"
variant="outline"
disabled={devicesState.isPending}
onClick={devicesState.refresh}
>
<RefreshCwIcon className={cn("size-3.5", devicesState.isPending && "animate-spin")} />
Refresh
</Button>
</header>
<div className="flex-1 p-6">
{devicesState.error ? (
<div
className="mb-4 flex flex-col gap-3 rounded-lg border border-destructive/25 bg-destructive/5 p-3 text-sm sm:flex-row sm:items-center sm:justify-between"
role="alert"
>
<div>
<p className="font-medium text-destructive-foreground">
Could not load mobile clients
</p>
<p className="mt-0.5 text-xs text-muted-foreground">{devicesState.error}</p>
</div>
<Button size="xs" variant="outline" onClick={devicesState.refresh}>
Try again
</Button>
</div>
) : null}
{isInitialLoad ? (
<MobileClientsSkeleton />
) : hasErrorWithoutData ? null : devices.length > 0 ? (
<ul className="space-y-3">
{devices.map((device) => (
<MobileClientRow key={device.deviceId} device={device} />
))}
</ul>
) : (
<EmptyMobileClients />
)}
</div>
</div>
);
}
@@ -1,8 +1,9 @@
import { UserButton, useAuth } from "@clerk/react";
import { LogInIcon } from "lucide-react";
import { LogInIcon, SmartphoneIcon } from "lucide-react";
import { hasCloudPublicConfig } from "../../cloud/publicConfig";
import { SidebarMenu, SidebarMenuButton, SidebarMenuItem } from "../ui/sidebar";
import { MobileClientsUserProfilePage } from "./MobileClientsUserProfilePage";
import { useT3ConnectAuthPrompt } from "./useT3ConnectAuthPrompt";
export function T3ConnectSidebarSignIn() {
@@ -30,7 +31,15 @@ function ConfiguredT3ConnectSidebarAvatar() {
userButtonTrigger: "rounded-lg p-1 hover:bg-sidebar-accent",
},
}}
/>
>
<UserButton.UserProfilePage
label="Mobile clients"
labelIcon={<SmartphoneIcon className="size-4" />}
url="mobile-clients"
>
<MobileClientsUserProfilePage />
</UserButton.UserProfilePage>
</UserButton>
);
}
@@ -121,6 +121,7 @@ import { hasCloudPublicConfig } from "~/cloud/publicConfig";
import {
linkPrimaryEnvironment as linkPrimaryEnvironmentAtom,
unlinkPrimaryEnvironment as unlinkPrimaryEnvironmentAtom,
updatePrimaryEnvironmentPreferences as updatePrimaryEnvironmentPreferencesAtom,
} from "~/cloud/linkEnvironmentAtoms";
import { authEnvironment } from "~/state/auth";
import { environmentCatalog } from "~/connection/catalog";
@@ -1466,7 +1467,7 @@ function SavedBackendListRow({
: null;
const metadataBits = [
sshTarget ? `SSH ${formatDesktopSshTarget(sshTarget)}` : null,
environment.relayManaged ? "T3 Cloud" : null,
environment.relayManaged ? "T3 Connect" : null,
].filter((value): value is string => value !== null);
// The WSL backend is a desktop-managed local backend (it surfaces as a bearer
@@ -1605,7 +1606,7 @@ function CloudLinkSwitch({
}) {
const control = (
<Switch
aria-label="Enable T3 Cloud"
aria-label="Enable T3 Connect"
checked={checked}
disabled={disabled}
{...(onCheckedChange ? { onCheckedChange } : {})}
@@ -1632,18 +1633,23 @@ function ConfiguredCloudLinkRow({ canManageRelay }: { readonly canManageRelay: b
const unlinkPrimaryEnvironment = useAtomCommand(unlinkPrimaryEnvironmentAtom, {
reportFailure: false,
});
const updatePrimaryEnvironmentPreferences = useAtomCommand(
updatePrimaryEnvironmentPreferencesAtom,
{ reportFailure: false },
);
const primaryCloudLinkState = usePrimaryCloudLinkState();
const [operationError, setOperationError] = useState<string | null>(null);
const [isUpdating, setIsUpdating] = useState(false);
const [isUpdatingPreference, setIsUpdatingPreference] = useState(false);
const reportUpdateFailure = (cause: unknown) => {
const message = cause instanceof Error ? cause.message : "Could not update T3 Cloud access.";
const message = cause instanceof Error ? cause.message : "Could not update T3 Connect access.";
const traceId = findErrorTraceId(cause);
console.error("[t3-cloud] Could not update T3 Cloud", { message, traceId, cause });
console.error("[t3-connect] Could not update T3 Connect", { message, traceId, cause });
setOperationError(traceId ? `${message} Trace ID: ${traceId}` : message);
toastManager.add({
type: "error",
title: "Could not update T3 Cloud",
title: "Could not update T3 Connect",
description: message,
data: traceId
? {
@@ -1673,9 +1679,7 @@ function ConfiguredCloudLinkRow({ canManageRelay }: { readonly canManageRelay: b
return;
}
if (enabled && !tokenResult.value) {
reportUpdateFailure(
new Error("Sign in from T3 Cloud settings before linking this environment."),
);
reportUpdateFailure(new Error("Sign in to T3 Connect before linking this environment."));
setIsUpdating(false);
return;
}
@@ -1710,38 +1714,95 @@ function ConfiguredCloudLinkRow({ canManageRelay }: { readonly canManageRelay: b
toastManager.add({
type: "success",
title: enabled ? "T3 Cloud linked" : "T3 Cloud unlinked",
title: enabled ? "T3 Connect linked" : "T3 Connect unlinked",
description: enabled
? "This environment is available through T3 Cloud."
: "This environment is no longer available through T3 Cloud.",
? "This environment is available through T3 Connect."
: "This environment is no longer available through T3 Connect.",
});
setIsUpdating(false);
};
const updatePublishAgentActivity = async (enabled: boolean) => {
const target = primaryCloudLinkState.target;
if (!target) {
reportUpdateFailure(new Error("Local environment is not ready yet."));
return;
}
setIsUpdatingPreference(true);
setOperationError(null);
const updateResult = await updatePrimaryEnvironmentPreferences({
target,
publishAgentActivity: enabled,
});
if (updateResult._tag === "Failure") {
if (!isAtomCommandInterrupted(updateResult)) {
reportUpdateFailure(squashAtomCommandFailure(updateResult));
}
setIsUpdatingPreference(false);
return;
}
primaryCloudLinkState.refresh();
toastManager.add({
type: "success",
title: enabled ? "Agent activity enabled" : "Agent activity disabled",
description: enabled
? "This environment can publish agent activity to your mobile clients."
: "This environment will stop publishing agent activity.",
});
setIsUpdatingPreference(false);
};
const disabledReason = !isSignedIn
? "Sign in from T3 Cloud settings to manage this environment."
? "Sign in to T3 Connect to manage this environment."
: !canManageRelay
? "Your session does not have permission to manage T3 Cloud access."
? "Your session does not have permission to manage T3 Connect access."
: null;
const linked = primaryCloudLinkState.data?.linked ?? false;
return (
<SettingsRow
title="T3 Cloud"
description={
linked
? "This environment is available to your other devices through T3 Cloud."
: "Make this environment available to your other devices through T3 Cloud."
}
status={operationError ?? primaryCloudLinkState.error}
control={
<CloudLinkSwitch
checked={linked}
disabled={!canManageRelay || !isSignedIn || primaryCloudLinkState.isPending || isUpdating}
disabledReason={disabledReason}
onCheckedChange={(enabled) => void updateLink(enabled)}
<>
<SettingsRow
title="T3 Connect"
description={
linked
? "This environment is available to your other devices through T3 Connect."
: "Make this environment available to your other devices through T3 Connect."
}
status={operationError ?? primaryCloudLinkState.error}
control={
<CloudLinkSwitch
checked={linked}
disabled={
!canManageRelay || !isSignedIn || primaryCloudLinkState.isPending || isUpdating
}
disabledReason={disabledReason}
onCheckedChange={(enabled) => void updateLink(enabled)}
/>
}
/>
{linked ? (
<SettingsRow
title="Publish agent activity"
description="Send activity from this environment to your mobile clients for push notifications and Live Activities."
className="bg-muted/20 pl-7 sm:pl-8"
control={
<Switch
aria-label="Publish agent activity to mobile clients"
checked={primaryCloudLinkState.data?.publishAgentActivity ?? false}
disabled={
!canManageRelay ||
!isSignedIn ||
primaryCloudLinkState.isPending ||
isUpdating ||
isUpdatingPreference
}
onCheckedChange={(enabled) => void updatePublishAgentActivity(enabled)}
/>
}
/>
}
/>
) : null}
</>
);
}
@@ -1759,7 +1820,7 @@ function EmptyRemoteEnvironments({ cloudEnabled = true }: { readonly cloudEnable
<EmptyTitle>No saved remote environments</EmptyTitle>
<EmptyDescription>
{cloudEnabled
? "Click “Add environment” to pair another environment, or connect one from T3 Cloud."
? "Click “Add environment” to pair another environment, or connect one from T3 Connect."
: "Click “Add environment” to pair another environment."}
</EmptyDescription>
</EmptyHeader>
@@ -1824,7 +1885,7 @@ function ConfiguredCloudRemoteEnvironmentRows({
toastManager.add({
type: "success",
title: "Environment connected",
description: `${environment.label} is available through T3 Cloud.`,
description: `${environment.label} is available through T3 Connect.`,
});
return;
}
@@ -1833,9 +1894,9 @@ function ConfiguredCloudRemoteEnvironmentRows({
}
const cause = squashAtomCommandFailure(result);
const message =
cause instanceof Error ? cause.message : "Could not connect the T3 Cloud environment.";
cause instanceof Error ? cause.message : "Could not connect the T3 Connect environment.";
const traceId = findErrorTraceId(cause);
console.error("[t3-cloud] Could not connect environment", { message, traceId, cause });
console.error("[t3-connect] Could not connect environment", { message, traceId, cause });
toastManager.add({
type: "error",
title: "Could not connect environment",
+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: {
@@ -44,6 +44,26 @@ const stubThread = {
} as const;
describe("applyShellStreamEvent", () => {
it("ignores stale project upserts without mutating the snapshot", () => {
const snapshotWithProject: OrchestrationShellSnapshot = {
...baseSnapshot,
snapshotSequence: 4,
projects: [stubProject],
};
for (const sequence of [3, 4]) {
const next = applyShellStreamEvent(snapshotWithProject, {
kind: "project-upserted",
sequence,
project: { ...stubProject, title: "Stale Title" },
});
expect(next).toBe(snapshotWithProject);
expect(next.snapshotSequence).toBe(4);
expect(next.projects[0]?.title).toBe("Test Project");
}
});
describe("project-upserted", () => {
it("adds a new project", () => {
const event: OrchestrationShellStreamEvent = {
@@ -13,6 +13,8 @@ export function applyShellStreamEvent(
snapshot: OrchestrationShellSnapshot,
event: OrchestrationShellStreamEvent,
): OrchestrationShellSnapshot {
if (event.sequence <= snapshot.snapshotSequence) return snapshot;
switch (event.kind) {
case "project-upserted": {
const projects = snapshot.projects.some((p) => p.id === event.project.id)
+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;
}
+1182 -813
View File
File diff suppressed because it is too large. Load diff
+11 -15
View File
@@ -20,13 +20,13 @@ supportedArchitectures:
- glibc
catalog:
"@clerk/backend": 3.8.2-snapshot.v20260619001138
"@clerk/clerk-js": 6.18.2-snapshot.v20260619001138
"@clerk/electron": 0.0.1-snapshot.v20260619001138
"@clerk/electron-passkeys": 0.0.1-snapshot.v20260619001138
"@clerk/expo": 3.4.8-snapshot.v20260619001138
"@clerk/react": 6.10.4-snapshot.v20260619001138
"@clerk/shared": 4.19.2-snapshot.v20260619001138
"@clerk/backend": 3.8.3-snapshot.v20260622234151
"@clerk/clerk-js": 6.21.0-snapshot.v20260622234151
"@clerk/electron": 0.0.2-snapshot.v20260622234151
"@clerk/electron-passkeys": 0.0.2-snapshot.v20260622234151
"@clerk/expo": 3.5.3-snapshot.v20260622234151
"@clerk/react": 6.11.0-snapshot.v20260622234151
"@clerk/shared": 4.21.0-snapshot.v20260622234151
"@effect/atom-react": 4.0.0-beta.78
"@effect/openapi-generator": 4.0.0-beta.78
"@effect/platform-bun": 4.0.0-beta.78
@@ -41,13 +41,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:
@@ -84,14 +82,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:
@@ -116,7 +114,5 @@ patchedDependencies:
peerDependencyRules:
allowAny:
- vite
- vitest
allowedVersions:
vite: "*"
vitest: "*"