Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f52f1726c4 |
No files matched your search
@@ -37,4 +37,3 @@ github:shivamhwp
|
||||
github:jappyjan
|
||||
github:justsomelegs
|
||||
github:UtkarshUsername
|
||||
github:SunkenInTime
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 32 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 36 KiB |
@@ -8,14 +8,12 @@ name: Mobile EAS Production
|
||||
#
|
||||
# Every merge to main that touches the mobile app reconciles, per platform:
|
||||
# 1. Store builds: if the latest production build's version differs from
|
||||
# app.config.ts, cut a new build and submit it (TestFlight + Play internal
|
||||
# track). Bumping `version` is therefore all it takes to
|
||||
# app.config.ts, cut a new build with --auto-submit (TestFlight +
|
||||
# Play internal track). Bumping `version` is therefore all it takes to
|
||||
# start the next release train — the first build of a version enters
|
||||
# external-TestFlight beta review immediately, and later builds of the
|
||||
# same version auto-approve until that version is released. After App
|
||||
# Store approval, Apple closes the release train and `version` must be
|
||||
# bumped before another iOS build can be submitted. Releasing to the App
|
||||
# Store stays a manual App Store Connect step.
|
||||
# same version auto-approve. Releasing to the App Store stays a manual
|
||||
# App Store Connect step.
|
||||
# 2. OTA: publish a production-channel update for each platform where at
|
||||
# least one finished production build matches the current native
|
||||
# fingerprint. Old-version binaries with a matching fingerprint receive
|
||||
@@ -44,10 +42,6 @@ on:
|
||||
- ios
|
||||
- android
|
||||
- all
|
||||
version:
|
||||
description: "Optional build version override (blank uses app.config.ts; an override is committed before building)"
|
||||
required: false
|
||||
type: string
|
||||
message:
|
||||
description: "OTA update message (mode=update only)"
|
||||
required: false
|
||||
@@ -95,21 +89,11 @@ jobs:
|
||||
echo "EXPO_TOKEN is not available; skipping EAS production job."
|
||||
fi
|
||||
|
||||
- id: version_app_token
|
||||
name: Mint release app token for version override
|
||||
if: steps.expo-token.outputs.present == 'true' && github.event_name == 'workflow_dispatch' && inputs.mode == 'build' && inputs.version != ''
|
||||
uses: actions/create-github-app-token@v2
|
||||
with:
|
||||
app-id: ${{ secrets.RELEASE_APP_ID }}
|
||||
private-key: ${{ secrets.RELEASE_APP_PRIVATE_KEY }}
|
||||
owner: ${{ github.repository_owner }}
|
||||
|
||||
- name: Checkout
|
||||
if: steps.expo-token.outputs.present == 'true'
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
fetch-depth: 0
|
||||
token: ${{ steps.version_app_token.outputs.token || github.token }}
|
||||
# No sparse-checkout here: it makes actions/checkout fetch with
|
||||
# --filter=blob:none, and eas-cli archives the project via
|
||||
# `git clone --depth 1 file://<workspace>`, which fails (exit 128)
|
||||
@@ -151,65 +135,6 @@ jobs:
|
||||
EXPO_TOKEN: ${{ secrets.EXPO_TOKEN }}
|
||||
run: eas env:pull production --non-interactive
|
||||
|
||||
- name: Apply manual version override
|
||||
if: steps.version_app_token.outcome == 'success'
|
||||
env:
|
||||
GH_TOKEN: ${{ steps.version_app_token.outputs.token }}
|
||||
APP_SLUG: ${{ steps.version_app_token.outputs.app-slug }}
|
||||
RELEASE_VERSION: ${{ inputs.version }}
|
||||
run: |
|
||||
if [ "$GITHUB_REF_TYPE" != "branch" ]; then
|
||||
echo "Version overrides require dispatching this workflow from a branch; received $GITHUB_REF_TYPE '$GITHUB_REF_NAME'." >&2
|
||||
exit 1
|
||||
fi
|
||||
if ! [[ "$RELEASE_VERSION" =~ ^[0-9]+(\.[0-9]+){1,2}$ ]]; then
|
||||
echo "Version override must contain two or three dot-separated integers; received '$RELEASE_VERSION'." >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
node --input-type=module -e '
|
||||
import fs from "node:fs";
|
||||
const path = "apps/mobile/app.config.ts";
|
||||
const source = fs.readFileSync(path, "utf8");
|
||||
const next = source.replace(
|
||||
/^( version: ")[^"]+(".*)$/m,
|
||||
`$1${process.env.RELEASE_VERSION}$2`,
|
||||
);
|
||||
if (next === source && !source.includes(` version: "${process.env.RELEASE_VERSION}"`)) {
|
||||
throw new Error("Could not update app version");
|
||||
}
|
||||
fs.writeFileSync(path, next);
|
||||
'
|
||||
vp fmt apps/mobile/app.config.ts
|
||||
|
||||
if git diff --quiet -- apps/mobile/app.config.ts; then
|
||||
echo "app.config.ts is already at $RELEASE_VERSION; no version commit needed."
|
||||
exit 0
|
||||
fi
|
||||
|
||||
user_id="$(gh api "/users/${APP_SLUG}[bot]" --jq .id)"
|
||||
git config user.name "${APP_SLUG}[bot]"
|
||||
git config user.email "${user_id}+${APP_SLUG}[bot]@users.noreply.github.com"
|
||||
git add apps/mobile/app.config.ts
|
||||
git commit \
|
||||
-m "chore(mobile): bump app version to $RELEASE_VERSION" \
|
||||
-m "Co-authored-by: codex <[email protected]>"
|
||||
git push origin "HEAD:refs/heads/${GITHUB_REF_NAME}"
|
||||
|
||||
- name: Summarize manual build version
|
||||
if: steps.expo-token.outputs.present == 'true' && github.event_name == 'workflow_dispatch' && inputs.mode == 'build'
|
||||
working-directory: apps/mobile
|
||||
run: |
|
||||
version="$(npx expo config --json --type public | jq -r '.version')"
|
||||
{
|
||||
echo "## Manual production build"
|
||||
echo
|
||||
echo "- App version: \`$version\`"
|
||||
echo "- Platform: \`${{ inputs.platform }}\`"
|
||||
echo
|
||||
echo "> Apple closes an iOS release train after App Store approval. Before building iOS, confirm \`$version\` is newer than the approved App Store version."
|
||||
} >> "$GITHUB_STEP_SUMMARY"
|
||||
|
||||
- name: Build and submit (manual)
|
||||
if: steps.expo-token.outputs.present == 'true' && github.event_name == 'workflow_dispatch' && inputs.mode == 'build'
|
||||
working-directory: apps/mobile
|
||||
@@ -232,8 +157,10 @@ jobs:
|
||||
|
||||
# No --status filter on build:list: an in-queue/in-progress build must
|
||||
# count as existing, or every merge during the build window would cut a
|
||||
# duplicate. After an errored build, retry via workflow_dispatch
|
||||
# mode=build — pushes won't re-trigger it until the app version changes.
|
||||
# duplicate. Builds started here stay attached to this serialized run so
|
||||
# the queued run for a later merge cannot overtake them and lose its OTA.
|
||||
# After an errored build, retry via workflow_dispatch mode=build — pushes
|
||||
# won't re-trigger it until the app version changes.
|
||||
- id: store_builds
|
||||
name: Ensure store builds exist for the current app version
|
||||
if: steps.expo-token.outputs.present == 'true' && github.event_name == 'push'
|
||||
@@ -251,8 +178,8 @@ jobs:
|
||||
continue
|
||||
fi
|
||||
echo "$platform: latest production build is $latest, app.config.ts says $version — building"
|
||||
if eas build --platform "$platform" --profile production --auto-submit --non-interactive --no-wait; then
|
||||
echo ":building_construction: $platform: scheduled production build and submission for $version" >> "$GITHUB_STEP_SUMMARY"
|
||||
if eas build --platform "$platform" --profile production --auto-submit --non-interactive; then
|
||||
echo ":building_construction: $platform: cut production build for $version (auto-submitted)" >> "$GITHUB_STEP_SUMMARY"
|
||||
else
|
||||
failed=1
|
||||
echo ":x: $platform: production build or submission failed for $version" >> "$GITHUB_STEP_SUMMARY"
|
||||
|
||||
@@ -161,7 +161,7 @@ const config: ExpoConfig = {
|
||||
slug: "t3-code",
|
||||
platforms: ["ios", "android"],
|
||||
scheme: variant.scheme,
|
||||
version: "1.0.3",
|
||||
version: "1.0.2",
|
||||
runtimeVersion: {
|
||||
// Fingerprint (not appVersion) so an OTA only reaches binaries whose native
|
||||
// project — native deps, config plugins, AND patches/ — matches the update.
|
||||
|
||||
@@ -49,7 +49,7 @@
|
||||
"@expo-google-fonts/dm-sans": "^0.4.2",
|
||||
"@expo/metro-runtime": "~56.0.15",
|
||||
"@expo/ui": "~56.0.18",
|
||||
"@legendapp/list": "catalog:",
|
||||
"@legendapp/list": "3.3.3",
|
||||
"@noble/curves": "catalog:",
|
||||
"@noble/hashes": "catalog:",
|
||||
"@pierre/diffs": "catalog:",
|
||||
|
||||
+13
-20
@@ -18,6 +18,7 @@ import { AppText as Text } from "./components/AppText";
|
||||
import { getCompactBrandHeaderOptions } from "./components/CompactBrandTitle";
|
||||
import { ArchivedThreadsRouteScreen } from "./features/archive/ArchivedThreadsRouteScreen";
|
||||
import { useAgentNotificationNavigation } from "./features/agent-awareness/notificationNavigation";
|
||||
import { ClerkSettingsSheetDetentProvider } from "./features/cloud/ClerkSettingsSheetDetent";
|
||||
import { ConnectOnboardingRouteScreen } from "./features/cloud/ConnectOnboardingRouteScreen";
|
||||
import { useConnectOnboardingNavigation } from "./features/cloud/connectOnboardingNavigation";
|
||||
import { ThreadFilesTreeScreen, ThreadFileScreen } from "./features/files/ThreadFilesRouteScreen";
|
||||
@@ -133,7 +134,7 @@ const LEGAL_DOCUMENT_HEADER_OPTIONS: AppScreenOptions = {
|
||||
presentation: "fullScreenModal",
|
||||
};
|
||||
|
||||
const SettingsContentStack = createNativeStackNavigator({
|
||||
const SettingsSheetStack = createNativeStackNavigator({
|
||||
initialRouteName: "Settings",
|
||||
screenOptions: {
|
||||
...GLASS_HEADER_OPTIONS,
|
||||
@@ -197,30 +198,20 @@ const SettingsContentStack = createNativeStackNavigator({
|
||||
title: "Usage",
|
||||
},
|
||||
}),
|
||||
},
|
||||
});
|
||||
|
||||
// The outer stack never owns visible chrome. Settings routes render inside a
|
||||
// nested stack whose native header remains mounted, while Clerk owns auth chrome.
|
||||
// Keeping bar visibility invariant avoids iOS 26's headerless-to-headered jump.
|
||||
const SettingsSheetStack = createNativeStackNavigator({
|
||||
initialRouteName: "SettingsContent",
|
||||
screenOptions: {
|
||||
headerShown: false,
|
||||
},
|
||||
screens: {
|
||||
SettingsContent: createNativeStackScreen({
|
||||
screen: SettingsContentStack,
|
||||
linking: "",
|
||||
}),
|
||||
SettingsAuth: createNativeStackScreen({
|
||||
screen: SettingsAuthRouteScreen,
|
||||
linking: "auth",
|
||||
options: {
|
||||
title: "Sign in",
|
||||
},
|
||||
}),
|
||||
SettingsWaitlist: createNativeStackScreen({
|
||||
// Keep the old deep link working after the Connect GA launch.
|
||||
screen: SettingsAuthRouteScreen,
|
||||
linking: "waitlist",
|
||||
options: {
|
||||
title: "Sign in",
|
||||
},
|
||||
}),
|
||||
},
|
||||
});
|
||||
@@ -356,9 +347,11 @@ function RootStackLayout(props: {
|
||||
<HardwareKeyboardCommandProvider pathname={pathname}>
|
||||
<ThreadOutboxDrainWorker />
|
||||
<ShowcaseCaptureCoordinator pathname={pathname} />
|
||||
<AdaptiveWorkspaceLayout pathname={workspacePathname}>
|
||||
{props.children}
|
||||
</AdaptiveWorkspaceLayout>
|
||||
<ClerkSettingsSheetDetentProvider initiallyExpanded={false}>
|
||||
<AdaptiveWorkspaceLayout pathname={workspacePathname}>
|
||||
{props.children}
|
||||
</AdaptiveWorkspaceLayout>
|
||||
</ClerkSettingsSheetDetentProvider>
|
||||
</HardwareKeyboardCommandProvider>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -6,7 +6,6 @@ import {
|
||||
type ComponentProps,
|
||||
type ReactElement,
|
||||
type ReactNode,
|
||||
useRef,
|
||||
} from "react";
|
||||
import { Platform, Pressable, useColorScheme, View } from "react-native";
|
||||
import { useThemeColor } from "../lib/useThemeColor";
|
||||
@@ -22,31 +21,10 @@ export function ControlPill(props: {
|
||||
readonly label?: string;
|
||||
readonly accessibilityLabel?: string;
|
||||
readonly onPress?: () => void;
|
||||
readonly activateOnPressIn?: boolean;
|
||||
readonly variant?: "circle" | "pill" | "primary" | "danger";
|
||||
readonly disabled?: boolean;
|
||||
readonly className?: string;
|
||||
}) {
|
||||
const variant = props.variant ?? "circle";
|
||||
const activatedOnPressInRef = useRef(false);
|
||||
|
||||
const handlePressIn = () => {
|
||||
activatedOnPressInRef.current = true;
|
||||
props.onPress?.();
|
||||
};
|
||||
const handlePressOut = () => {
|
||||
// Pressability invokes onPressOut immediately before onPress on release.
|
||||
// Defer the reset so onPress can identify the same physical gesture.
|
||||
setTimeout(() => {
|
||||
activatedOnPressInRef.current = false;
|
||||
}, 0);
|
||||
};
|
||||
const handlePress = () => {
|
||||
if (activatedOnPressInRef.current) {
|
||||
return;
|
||||
}
|
||||
props.onPress?.();
|
||||
};
|
||||
|
||||
const iconColor = useThemeColor("--color-icon");
|
||||
const iconSubtle = useThemeColor("--color-icon-subtle");
|
||||
@@ -76,7 +54,6 @@ export function ControlPill(props: {
|
||||
: variant === "danger"
|
||||
? "bg-danger"
|
||||
: "bg-subtle",
|
||||
props.className,
|
||||
);
|
||||
const labelClassName = cn(
|
||||
"text-center text-xs font-t3-bold",
|
||||
@@ -91,9 +68,7 @@ export function ControlPill(props: {
|
||||
<Pressable
|
||||
accessibilityLabel={props.accessibilityLabel ?? props.label}
|
||||
accessibilityRole="button"
|
||||
onPress={props.activateOnPressIn ? handlePress : props.onPress}
|
||||
onPressIn={props.activateOnPressIn ? handlePressIn : undefined}
|
||||
onPressOut={props.activateOnPressIn ? handlePressOut : undefined}
|
||||
onPress={props.onPress}
|
||||
disabled={props.disabled}
|
||||
className={containerClassName}
|
||||
>
|
||||
|
||||
@@ -5,6 +5,7 @@ import { useFocusEffect } from "@react-navigation/native";
|
||||
import { useCallback, useMemo, useState } from "react";
|
||||
|
||||
import { useSavedRemoteConnections } from "../../state/use-remote-environment-registry";
|
||||
import { useClerkSettingsSheetDetent } from "../cloud/ClerkSettingsSheetDetent";
|
||||
import { useArchivedThreadListActions } from "../home/useThreadListActions";
|
||||
import {
|
||||
ArchivedThreadsScreen,
|
||||
@@ -17,6 +18,7 @@ import {
|
||||
} from "./useArchivedThreadSnapshots";
|
||||
|
||||
export function ArchivedThreadsRouteScreen() {
|
||||
const { expand } = useClerkSettingsSheetDetent();
|
||||
const { savedConnectionsById } = useSavedRemoteConnections();
|
||||
const [searchQuery, setSearchQuery] = useState("");
|
||||
const [selectedEnvironmentId, setSelectedEnvironmentId] = useState<EnvironmentId | null>(null);
|
||||
@@ -68,8 +70,9 @@ export function ArchivedThreadsRouteScreen() {
|
||||
|
||||
useFocusEffect(
|
||||
useCallback(() => {
|
||||
expand();
|
||||
refresh();
|
||||
}, [refresh]),
|
||||
}, [expand, refresh]),
|
||||
);
|
||||
|
||||
return (
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
import {
|
||||
createContext,
|
||||
type PropsWithChildren,
|
||||
useCallback,
|
||||
useContext,
|
||||
useMemo,
|
||||
useState,
|
||||
} from "react";
|
||||
|
||||
interface ClerkSettingsSheetDetentValue {
|
||||
collapse: () => void;
|
||||
expand: () => void;
|
||||
isExpanded: boolean;
|
||||
}
|
||||
|
||||
const ClerkSettingsSheetDetentContext = createContext<ClerkSettingsSheetDetentValue | null>(null);
|
||||
|
||||
interface ClerkSettingsSheetDetentProviderProps extends PropsWithChildren {
|
||||
initiallyExpanded: boolean;
|
||||
}
|
||||
|
||||
export function ClerkSettingsSheetDetentProvider({
|
||||
children,
|
||||
initiallyExpanded,
|
||||
}: ClerkSettingsSheetDetentProviderProps) {
|
||||
const [isExpanded, setIsExpanded] = useState(initiallyExpanded);
|
||||
const collapse = useCallback(() => setIsExpanded(false), []);
|
||||
const expand = useCallback(() => setIsExpanded(true), []);
|
||||
const value = useMemo(() => ({ collapse, expand, isExpanded }), [collapse, expand, isExpanded]);
|
||||
|
||||
return (
|
||||
<ClerkSettingsSheetDetentContext value={value}>{children}</ClerkSettingsSheetDetentContext>
|
||||
);
|
||||
}
|
||||
|
||||
export function useClerkSettingsSheetDetent(): ClerkSettingsSheetDetentValue {
|
||||
const value = useContext(ClerkSettingsSheetDetentContext);
|
||||
if (!value) {
|
||||
throw new Error(
|
||||
"useClerkSettingsSheetDetent must be used inside ClerkSettingsSheetDetentProvider",
|
||||
);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
@@ -6,8 +6,8 @@ import { appAtomRegistry } from "../../state/atom-registry";
|
||||
import { clearConnectOnboardingRequest, connectOnboardingRequestAtom } from "./connectOnboarding";
|
||||
import { isConnectOnboardingOptedOut } from "./connectOnboardingOptOut";
|
||||
|
||||
// Sign-in happens inside the Settings sheet; give its session-state transition
|
||||
// a beat to settle before presenting another formSheet on top.
|
||||
// Sign-in happens inside the Settings sheet; give its detent/session-state
|
||||
// transitions a beat to settle before presenting another formSheet on top.
|
||||
const PRESENT_ONBOARDING_DELAY_MS = 600;
|
||||
|
||||
/**
|
||||
|
||||
@@ -45,7 +45,6 @@ export function HomeRouteScreen() {
|
||||
pinThread,
|
||||
unpinThread,
|
||||
movePinnedThread,
|
||||
regenerateThreadTitle,
|
||||
unsettleThread,
|
||||
} = useThreadListActions();
|
||||
const pendingTasks = usePendingNewTasks();
|
||||
@@ -135,10 +134,7 @@ export function HomeRouteScreen() {
|
||||
<NativeStackScreenOptions
|
||||
options={getConnectionAwareBrandHeaderOptions({
|
||||
onOpenEnvironments: () =>
|
||||
navigation.navigate("SettingsSheet", {
|
||||
screen: "SettingsContent",
|
||||
params: { screen: "SettingsEnvironments" },
|
||||
}),
|
||||
navigation.navigate("SettingsSheet", { screen: "SettingsEnvironments" }),
|
||||
})}
|
||||
/>
|
||||
<HomeHeader
|
||||
@@ -152,17 +148,9 @@ export function HomeRouteScreen() {
|
||||
onEnvironmentChange={setSelectedEnvironmentId}
|
||||
onProjectChange={setSelectedProjectKey}
|
||||
onOpenEnvironments={() =>
|
||||
navigation.navigate("SettingsSheet", {
|
||||
screen: "SettingsContent",
|
||||
params: { screen: "SettingsEnvironments" },
|
||||
})
|
||||
}
|
||||
onOpenSettings={() =>
|
||||
navigation.navigate("SettingsSheet", {
|
||||
screen: "SettingsContent",
|
||||
params: { screen: "Settings" },
|
||||
})
|
||||
navigation.navigate("SettingsSheet", { screen: "SettingsEnvironments" })
|
||||
}
|
||||
onOpenSettings={() => navigation.navigate("SettingsSheet", { screen: "Settings" })}
|
||||
onProjectSortOrderChange={setProjectSortOrder}
|
||||
onSearchQueryChange={setSearchQuery}
|
||||
onStartNewTask={() => navigation.navigate("NewTaskSheet", { screen: "NewTask" })}
|
||||
@@ -173,10 +161,7 @@ export function HomeRouteScreen() {
|
||||
catalogState={catalogState}
|
||||
environments={environments}
|
||||
onAddConnection={() =>
|
||||
navigation.navigate("SettingsSheet", {
|
||||
screen: "SettingsContent",
|
||||
params: { screen: "SettingsEnvironmentNew" },
|
||||
})
|
||||
navigation.navigate("SettingsSheet", { screen: "SettingsEnvironmentNew" })
|
||||
}
|
||||
onArchiveThread={archiveThread}
|
||||
onDeleteThread={confirmDeleteThread}
|
||||
@@ -187,15 +172,9 @@ export function HomeRouteScreen() {
|
||||
onPinThread={pinThread}
|
||||
onUnpinThread={unpinThread}
|
||||
onMovePinnedThread={movePinnedThread}
|
||||
onRegenerateThreadTitle={regenerateThreadTitle}
|
||||
onEnvironmentChange={setSelectedEnvironmentId}
|
||||
onProjectChange={setSelectedProjectKey}
|
||||
onOpenSettings={() =>
|
||||
navigation.navigate("SettingsSheet", {
|
||||
screen: "SettingsContent",
|
||||
params: { screen: "Settings" },
|
||||
})
|
||||
}
|
||||
onOpenSettings={() => navigation.navigate("SettingsSheet", { screen: "Settings" })}
|
||||
onProjectSortOrderChange={setProjectSortOrder}
|
||||
onSearchQueryChange={setSearchQuery}
|
||||
onSelectThread={(thread) => {
|
||||
|
||||
@@ -115,7 +115,6 @@ interface HomeScreenProps {
|
||||
thread: EnvironmentThreadShell,
|
||||
direction: "up" | "down",
|
||||
) => Promise<boolean>;
|
||||
readonly onRegenerateThreadTitle: (thread: EnvironmentThreadShell) => Promise<boolean>;
|
||||
readonly onSelectPendingTask: (pendingTask: PendingNewTask) => void;
|
||||
readonly onDeletePendingTask: (pendingTask: PendingNewTask) => void;
|
||||
readonly onNewThreadInProject: (project: EnvironmentProject) => void;
|
||||
@@ -539,12 +538,6 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
},
|
||||
[props.onUnpinThread],
|
||||
);
|
||||
const handleRegenerateThreadTitle = useCallback(
|
||||
(thread: EnvironmentThreadShell) => {
|
||||
void props.onRegenerateThreadTitle(thread);
|
||||
},
|
||||
[props.onRegenerateThreadTitle],
|
||||
);
|
||||
const handleDeleteThread = props.onDeleteThread;
|
||||
const handleUnsettleThread = props.onUnsettleThread;
|
||||
// The settled tail renders in pages; expansion resets when the filter
|
||||
@@ -622,15 +615,6 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
}
|
||||
return supported;
|
||||
}, [serverConfigs]);
|
||||
const titleRegenerationEnvironmentIds = useMemo(() => {
|
||||
const supported = new Set<EnvironmentId>();
|
||||
for (const [environmentId, config] of serverConfigs) {
|
||||
if (config.environment.capabilities.threadTitleRegeneration === true) {
|
||||
supported.add(environmentId);
|
||||
}
|
||||
}
|
||||
return supported;
|
||||
}, [serverConfigs]);
|
||||
// Canonical arranged pinned order (reorder-capable threads only) for the
|
||||
// Move up/down position flags. Computed from all shells, not the rendered
|
||||
// list, so search/scope filtering never disables or misdirects a move.
|
||||
@@ -827,8 +811,6 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
onSelectThread={props.onSelectThread}
|
||||
onDeleteThread={handleDeleteThread}
|
||||
onArchiveThread={props.onArchiveThread}
|
||||
onRegenerateThreadTitle={handleRegenerateThreadTitle}
|
||||
titleRegenerationSupported={titleRegenerationEnvironmentIds.has(thread.environmentId)}
|
||||
settlementSupported={settlementEnvironmentIds.has(thread.environmentId)}
|
||||
onSettleThread={handleSettleThread}
|
||||
snoozeSupported={snoozeEnvironmentIds.has(thread.environmentId)}
|
||||
@@ -860,7 +842,6 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
arrangedPinnedKeys,
|
||||
handleMovePinnedThread,
|
||||
handlePinThread,
|
||||
handleRegenerateThreadTitle,
|
||||
handleSettleThread,
|
||||
handleSnoozeThread,
|
||||
handleUnpinThread,
|
||||
@@ -882,7 +863,6 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
snoozeEnvironmentIds,
|
||||
threadListV2Items,
|
||||
threadSearchMatchByKey,
|
||||
titleRegenerationEnvironmentIds,
|
||||
toggleSettledShelf,
|
||||
toggleSnoozedShelf,
|
||||
v2ProjectTitleByProjectKey,
|
||||
@@ -987,8 +967,6 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
searchQuery={props.searchQuery}
|
||||
onArchiveThread={props.onArchiveThread}
|
||||
onDeleteThread={props.onDeleteThread}
|
||||
onRegenerateThreadTitle={handleRegenerateThreadTitle}
|
||||
titleRegenerationSupported={titleRegenerationEnvironmentIds.has(thread.environmentId)}
|
||||
onSelectThread={props.onSelectThread}
|
||||
onSwipeableClose={handleSwipeableClose}
|
||||
onSwipeableWillOpen={handleSwipeableWillOpen}
|
||||
@@ -1010,7 +988,6 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
[
|
||||
handleSwipeableClose,
|
||||
handleSwipeableWillOpen,
|
||||
handleRegenerateThreadTitle,
|
||||
projectCwdByKey,
|
||||
props.onArchiveThread,
|
||||
props.onDeletePendingTask,
|
||||
@@ -1021,7 +998,6 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
props.searchQuery,
|
||||
props.savedConnectionsById,
|
||||
threadSearchMatchByKey,
|
||||
titleRegenerationEnvironmentIds,
|
||||
updateGroupDisplay,
|
||||
],
|
||||
);
|
||||
|
||||
@@ -48,15 +48,6 @@ function environmentSupportsPinReorder(environmentId: EnvironmentThreadShell["en
|
||||
);
|
||||
}
|
||||
|
||||
function environmentSupportsTitleRegeneration(
|
||||
environmentId: EnvironmentThreadShell["environmentId"],
|
||||
) {
|
||||
return (
|
||||
appAtomRegistry.get(environmentServerConfigsAtom).get(environmentId)?.environment.capabilities
|
||||
.threadTitleRegeneration === true
|
||||
);
|
||||
}
|
||||
|
||||
type ThreadListAction = "archive" | "unarchive" | "delete" | "settle" | "unsettle";
|
||||
|
||||
const ACTION_VERBS: Record<ThreadListAction, string> = {
|
||||
@@ -236,18 +227,13 @@ export function useThreadListActions(): {
|
||||
thread: EnvironmentThreadShell,
|
||||
direction: "up" | "down",
|
||||
) => Promise<boolean>;
|
||||
readonly regenerateThreadTitle: (thread: EnvironmentThreadShell) => Promise<boolean>;
|
||||
} {
|
||||
const executeAction = useThreadActionExecutor();
|
||||
const snoozeMutation = useAtomCommand(threadEnvironment.snooze, { reportFailure: false });
|
||||
const unsnoozeMutation = useAtomCommand(threadEnvironment.unsnooze, { reportFailure: false });
|
||||
const pinMutation = useAtomCommand(threadEnvironment.pin, { reportFailure: false });
|
||||
const unpinMutation = useAtomCommand(threadEnvironment.unpin, { reportFailure: false });
|
||||
const updateThreadMetadata = useAtomCommand(threadEnvironment.updateMetadata, {
|
||||
reportFailure: false,
|
||||
});
|
||||
const snoozeInFlightThreadKeys = useRef(new Set<string>());
|
||||
const titleRegenerationInFlightThreadKeys = useRef(new Set<string>());
|
||||
|
||||
const archiveThread = useCallback(
|
||||
(thread: EnvironmentThreadShell) => {
|
||||
@@ -419,47 +405,6 @@ export function useThreadListActions(): {
|
||||
},
|
||||
[unpinMutation],
|
||||
);
|
||||
const regenerateThreadTitle = useCallback(
|
||||
async (thread: EnvironmentThreadShell) => {
|
||||
const key = scopedThreadKey(thread.environmentId, thread.id);
|
||||
if (
|
||||
thread.titleRegeneration != null ||
|
||||
titleRegenerationInFlightThreadKeys.current.has(key)
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
if (!environmentSupportsTitleRegeneration(thread.environmentId)) {
|
||||
Alert.alert(
|
||||
"Could not regenerate title",
|
||||
"This environment's server does not support title regeneration yet. Update the server to regenerate thread titles.",
|
||||
);
|
||||
return false;
|
||||
}
|
||||
|
||||
titleRegenerationInFlightThreadKeys.current.add(key);
|
||||
selectionHaptic();
|
||||
try {
|
||||
const result = await updateThreadMetadata({
|
||||
environmentId: thread.environmentId,
|
||||
input: { threadId: thread.id, regenerateTitle: true },
|
||||
});
|
||||
if (result._tag === "Failure") {
|
||||
const error = Cause.squash(result.cause);
|
||||
Alert.alert(
|
||||
"Could not regenerate title",
|
||||
error instanceof Error && error.message.trim().length > 0
|
||||
? error.message
|
||||
: "The thread title could not be regenerated.",
|
||||
);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
} finally {
|
||||
titleRegenerationInFlightThreadKeys.current.delete(key);
|
||||
}
|
||||
},
|
||||
[updateThreadMetadata],
|
||||
);
|
||||
|
||||
// Move up / Move down for the pinned block. Computed against the CANONICAL
|
||||
// keyed pinned order (not the rendered list), so the move is valid even
|
||||
@@ -552,7 +497,6 @@ export function useThreadListActions(): {
|
||||
pinThread,
|
||||
unpinThread,
|
||||
movePinnedThread,
|
||||
regenerateThreadTitle,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -429,19 +429,13 @@ function AdaptiveWorkspaceLayoutContent(
|
||||
);
|
||||
|
||||
const handleOpenSettings = useCallback(() => {
|
||||
navigation.navigate("SettingsSheet", {
|
||||
screen: "SettingsContent",
|
||||
params: { screen: "Settings" },
|
||||
});
|
||||
navigation.navigate("SettingsSheet", { screen: "Settings" });
|
||||
}, [navigation]);
|
||||
|
||||
// Minted here (root stack navigation) so the sidebar pane stays free of
|
||||
// navigation hooks — on iOS it renders inside an independent nav tree.
|
||||
const handleOpenEnvironmentSettings = useCallback(() => {
|
||||
navigation.navigate("SettingsSheet", {
|
||||
screen: "SettingsContent",
|
||||
params: { screen: "SettingsEnvironments" },
|
||||
});
|
||||
navigation.navigate("SettingsSheet", { screen: "SettingsEnvironments" });
|
||||
}, [navigation]);
|
||||
|
||||
const handleNewThreadInProject = useCallback(
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import { useAuth } from "@clerk/expo";
|
||||
import { AuthView, UserProfileView } from "@clerk/expo/native";
|
||||
import { StackActions, useNavigation } from "@react-navigation/native";
|
||||
import { useCallback, useLayoutEffect } from "react";
|
||||
import { NativeStackScreenOptions } from "../../native/StackHeader";
|
||||
import { useCallback, useEffect } from "react";
|
||||
import { View } from "react-native";
|
||||
|
||||
import { hasCloudPublicConfig } from "../cloud/publicConfig";
|
||||
@@ -9,9 +10,9 @@ import { hasCloudPublicConfig } from "../cloud/publicConfig";
|
||||
export function SettingsAuthRouteScreen() {
|
||||
const navigation = useNavigation();
|
||||
|
||||
useLayoutEffect(() => {
|
||||
useEffect(() => {
|
||||
if (!hasCloudPublicConfig()) {
|
||||
navigation.dispatch(StackActions.replace("SettingsContent"));
|
||||
navigation.dispatch(StackActions.replace("Settings"));
|
||||
}
|
||||
}, [navigation]);
|
||||
|
||||
@@ -21,20 +22,20 @@ export function SettingsAuthRouteScreen() {
|
||||
function ConfiguredSettingsAuthRouteScreen() {
|
||||
const { isLoaded, isSignedIn } = useAuth({ treatPendingAsSignedOut: false });
|
||||
const navigation = useNavigation();
|
||||
const handleHostBack = useCallback(
|
||||
() => navigation.dispatch(StackActions.popTo("SettingsContent")),
|
||||
[navigation],
|
||||
);
|
||||
const handleHostBack = useCallback(() => navigation.goBack(), [navigation]);
|
||||
|
||||
return (
|
||||
<View collapsable={false} className="flex-1 overflow-hidden bg-sheet">
|
||||
{isLoaded ? (
|
||||
isSignedIn ? (
|
||||
<UserProfileView isDismissible={false} onHostBack={handleHostBack} />
|
||||
) : (
|
||||
<AuthView isDismissible={false} onHostBack={handleHostBack} />
|
||||
)
|
||||
) : null}
|
||||
</View>
|
||||
<>
|
||||
<NativeStackScreenOptions options={{ headerShown: false }} />
|
||||
<View collapsable={false} className="flex-1 overflow-hidden bg-sheet">
|
||||
{isLoaded ? (
|
||||
isSignedIn ? (
|
||||
<UserProfileView isDismissible={false} onHostBack={handleHostBack} />
|
||||
) : (
|
||||
<AuthView isDismissible={false} onHostBack={handleHostBack} />
|
||||
)
|
||||
) : null}
|
||||
</View>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -98,10 +98,7 @@ export function SettingsEnvironmentsRouteScreen() {
|
||||
accessibilityLabel: "Add environment",
|
||||
icon: "plus",
|
||||
onPress: () =>
|
||||
navigation.navigate("SettingsSheet", {
|
||||
screen: "SettingsContent",
|
||||
params: { screen: "SettingsEnvironmentNew" },
|
||||
}),
|
||||
navigation.navigate("SettingsSheet", { screen: "SettingsEnvironmentNew" }),
|
||||
},
|
||||
]}
|
||||
/>
|
||||
@@ -111,10 +108,7 @@ export function SettingsEnvironmentsRouteScreen() {
|
||||
<NativeHeaderToolbar.Button
|
||||
icon="plus"
|
||||
onPress={() =>
|
||||
navigation.navigate("SettingsSheet", {
|
||||
screen: "SettingsContent",
|
||||
params: { screen: "SettingsEnvironmentNew" },
|
||||
})
|
||||
navigation.navigate("SettingsSheet", { screen: "SettingsEnvironmentNew" })
|
||||
}
|
||||
separateBackground
|
||||
tintColor={headerIconColor}
|
||||
|
||||
@@ -2,6 +2,7 @@ import { useAuth, useUser } from "@clerk/expo";
|
||||
import { useAtomSet, useAtomValue } from "@effect/atom-react";
|
||||
import Constants from "expo-constants";
|
||||
import * as Notifications from "expo-notifications";
|
||||
import * as Updates from "expo-updates";
|
||||
import { useNavigation } from "@react-navigation/native";
|
||||
import { NativeStackScreenOptions } from "../../native/StackHeader";
|
||||
import { SymbolView } from "../../components/AppSymbol";
|
||||
@@ -29,6 +30,7 @@ import {
|
||||
subscribeAgentAwarenessRegistrationStatus,
|
||||
} from "../agent-awareness/remoteRegistration";
|
||||
import { refreshManagedRelayEnvironments } from "../cloud/managedRelayState";
|
||||
import { useClerkSettingsSheetDetent } from "../cloud/ClerkSettingsSheetDetent";
|
||||
import { hasCloudPublicConfig, resolveRelayClerkTokenOptions } from "../cloud/publicConfig";
|
||||
import { withNativeGlassHeaderItem } from "../layout/native-glass-header-items";
|
||||
import { WorkspaceSidebarToolbar } from "../layout/workspace-sidebar-toolbar";
|
||||
@@ -38,7 +40,6 @@ import { mobilePreferencesAtom, updateMobilePreferencesAtom } from "../../state/
|
||||
import { useThreadListV2Enabled } from "../threads/use-thread-list-v2-enabled";
|
||||
import {
|
||||
type AppUpdateCheckState,
|
||||
isAppUpdateCheckAvailable,
|
||||
registerHiddenUpdateTap,
|
||||
runAppUpdateCheck,
|
||||
} from "../updates/app-updates";
|
||||
@@ -146,6 +147,7 @@ function ConfiguredSettingsRouteScreen() {
|
||||
const agentAwarenessPushAvailable = supportsAgentAwarenessPush();
|
||||
const insets = useSafeAreaInsets();
|
||||
const navigation = useNavigation();
|
||||
const { expand: expandClerkSheet } = useClerkSettingsSheetDetent();
|
||||
const { getToken, isLoaded, isSignedIn } = useAuth({ treatPendingAsSignedOut: false });
|
||||
const { user } = useUser();
|
||||
const { savedConnectionsById } = useSavedRemoteConnections();
|
||||
@@ -434,8 +436,14 @@ function ConfiguredSettingsRouteScreen() {
|
||||
|
||||
const openAccount = useCallback(() => {
|
||||
if (!isLoaded) return;
|
||||
if (!isSignedIn) {
|
||||
expandClerkSheet();
|
||||
navigation.navigate("SettingsSheet", { screen: "SettingsAuth" });
|
||||
return;
|
||||
}
|
||||
expandClerkSheet();
|
||||
navigation.navigate("SettingsSheet", { screen: "SettingsAuth" });
|
||||
}, [isLoaded, navigation]);
|
||||
}, [expandClerkSheet, isLoaded, isSignedIn, navigation]);
|
||||
|
||||
return (
|
||||
<View collapsable={false} className="flex-1 bg-sheet">
|
||||
@@ -569,7 +577,6 @@ function AppSettingsSection() {
|
||||
const variant = (Constants.expoConfig?.extra?.appVariant as string | undefined) ?? "production";
|
||||
const variantLabel = variant === "production" ? "" : capitalize(variant);
|
||||
const versionLabel = variantLabel ? `${version} · ${variantLabel}` : version;
|
||||
const updateCheckAvailable = isAppUpdateCheckAvailable();
|
||||
const busy =
|
||||
updateState === "checking" || updateState === "downloading" || updateState === "restarting";
|
||||
|
||||
@@ -597,13 +604,13 @@ function AppSettingsSection() {
|
||||
}, []);
|
||||
|
||||
const handleVersionPress = useCallback(() => {
|
||||
if (!updateCheckAvailable || updateInFlight.current) return;
|
||||
if (!Updates.isEnabled || updateInFlight.current) return;
|
||||
const tap = registerHiddenUpdateTap(hiddenUpdateTapCount.current);
|
||||
hiddenUpdateTapCount.current = tap.nextCount;
|
||||
if (tap.shouldCheck) {
|
||||
void checkForUpdate();
|
||||
}
|
||||
}, [checkForUpdate, updateCheckAvailable]);
|
||||
}, [checkForUpdate]);
|
||||
|
||||
const statusLabel =
|
||||
updateState === "checking"
|
||||
@@ -639,7 +646,7 @@ function AppSettingsSection() {
|
||||
<SettingsSection title="App">
|
||||
<SettingsRow icon="internaldrive" label="Client Storage" target="SettingsClientStorage" />
|
||||
<SettingsRow icon="doc.text" label="Legal" fullScreenTarget="SettingsLegal" />
|
||||
{updateCheckAvailable ? (
|
||||
{Updates.isEnabled ? (
|
||||
<Pressable
|
||||
accessibilityLabel={`Version ${versionLabel}`}
|
||||
accessibilityRole="text"
|
||||
|
||||
@@ -64,8 +64,7 @@ export function SettingsRow(props: {
|
||||
disabled={props.disabled}
|
||||
onPress={() =>
|
||||
navigation.navigate("SettingsSheet", {
|
||||
screen: "SettingsContent",
|
||||
params: { screen: target },
|
||||
screen: target,
|
||||
})
|
||||
}
|
||||
>
|
||||
|
||||
@@ -1,12 +1,6 @@
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { Keyboard, View } from "react-native";
|
||||
import {
|
||||
CommonActions,
|
||||
type NavigationState,
|
||||
type PartialState,
|
||||
StackActions,
|
||||
useNavigation,
|
||||
} from "@react-navigation/native";
|
||||
import { CommonActions, StackActions, useNavigation } from "@react-navigation/native";
|
||||
import { AsyncResult } from "effect/unstable/reactivity";
|
||||
|
||||
import { useConnectionController } from "../connection/useConnectionController";
|
||||
@@ -31,8 +25,6 @@ import { retryShowcaseOperation } from "./showcaseRetry";
|
||||
const SHOWCASE_ENABLED = process.env.EXPO_PUBLIC_SHOWCASE === "1";
|
||||
const SHOWCASE_THREAD_ID = "remote-command-center";
|
||||
|
||||
type ShowcaseResetRoute = PartialState<NavigationState>["routes"][number];
|
||||
|
||||
function sceneFromPathname(pathname: string): ShowcaseScene | null {
|
||||
const routePath = pathname.split(/[?#]/u, 1)[0] ?? pathname;
|
||||
if (routePath === "/settings" || routePath.endsWith("/settings/environments")) {
|
||||
@@ -174,21 +166,17 @@ export function ShowcaseCaptureCoordinator(props: { readonly pathname: string })
|
||||
navigation.dispatch(StackActions.popToTop());
|
||||
return;
|
||||
}
|
||||
const routes: ShowcaseResetRoute[] = [{ name: "Home" }];
|
||||
const routes: Array<{
|
||||
name: string;
|
||||
params?: Record<string, unknown>;
|
||||
state?: { index: number; routes: Array<{ name: string }> };
|
||||
}> = [{ name: "Home" }];
|
||||
if (requestedScene === "environments") {
|
||||
routes.push({
|
||||
name: "SettingsSheet",
|
||||
state: {
|
||||
index: 0,
|
||||
routes: [
|
||||
{
|
||||
name: "SettingsContent",
|
||||
state: {
|
||||
index: 1,
|
||||
routes: [{ name: "Settings" }, { name: "SettingsEnvironments" }],
|
||||
},
|
||||
},
|
||||
],
|
||||
index: 1,
|
||||
routes: [{ name: "Settings" }, { name: "SettingsEnvironments" }],
|
||||
},
|
||||
});
|
||||
} else {
|
||||
|
||||
@@ -2,11 +2,7 @@ import { NativeStackScreenOptions } from "../../native/StackHeader";
|
||||
import { StackActions, useNavigation, usePreventRemove } from "@react-navigation/native";
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import { Alert, InteractionManager, Platform, View, useColorScheme } from "react-native";
|
||||
import {
|
||||
KeyboardAvoidingView,
|
||||
KeyboardStickyView,
|
||||
useKeyboardState,
|
||||
} from "react-native-keyboard-controller";
|
||||
import { KeyboardAvoidingView, useKeyboardState } from "react-native-keyboard-controller";
|
||||
import { useSafeAreaInsets } from "react-native-safe-area-context";
|
||||
import { useThemeColor } from "../../lib/useThemeColor";
|
||||
import { useFontFamily } from "../../lib/useFontFamily";
|
||||
@@ -989,29 +985,14 @@ export function NewTaskDraftScreen(props: {
|
||||
// The draft is a thread that doesn't exist yet, so it mirrors the thread
|
||||
// page: in-screen header, empty feed canvas above, and the same floating
|
||||
// composer chrome as ThreadComposer (collapsed pill → expanded card).
|
||||
//
|
||||
// Composer positioning mirrors ThreadDetailScreen's floating overlay
|
||||
// (KeyboardStickyView, absolute bottom overlay) rather than
|
||||
// KeyboardAvoidingView's automaticOffset+padding: automaticOffset
|
||||
// resolves the composer's on-screen frame via a native
|
||||
// viewPositionInWindow measurement, which this app's Android
|
||||
// edge-to-edge setup (KeyboardProvider's native content-view margin
|
||||
// handling neutralizes windowSoftInputMode="adjustResize" while active)
|
||||
// makes unreliable — the composer stayed under the keyboard instead of
|
||||
// translating above it. KeyboardStickyView sticks directly to the
|
||||
// animated keyboard height instead, sidestepping that measurement.
|
||||
return (
|
||||
<View className="flex-1 bg-screen">
|
||||
<NativeStackScreenOptions options={{ headerShown: false }} />
|
||||
<AndroidScreenHeader title="New Thread" onBack={() => navigation.goBack()} />
|
||||
|
||||
<View className="flex-1" />
|
||||
<KeyboardAvoidingView automaticOffset behavior="padding" className="flex-1">
|
||||
<View className="flex-1" />
|
||||
|
||||
<KeyboardStickyView
|
||||
enabled={isKeyboardVisible}
|
||||
style={{ position: "absolute", bottom: 0, left: 0, right: 0 }}
|
||||
offset={{ closed: 0, opened: 0 }}
|
||||
>
|
||||
<View
|
||||
className="px-4 pt-2"
|
||||
style={{
|
||||
@@ -1075,7 +1056,7 @@ export function NewTaskDraftScreen(props: {
|
||||
</ComposerToolbarRow>
|
||||
) : null}
|
||||
</View>
|
||||
</KeyboardStickyView>
|
||||
</KeyboardAvoidingView>
|
||||
{settingsSheet}
|
||||
</View>
|
||||
);
|
||||
|
||||
@@ -1,64 +1,18 @@
|
||||
import type { ApprovalRequestId, UserInputQuestion } from "@t3tools/contracts";
|
||||
import { useCallback, useRef } from "react";
|
||||
import { Platform, Pressable, ScrollView, View, type LayoutChangeEvent } from "react-native";
|
||||
import Animated, {
|
||||
Easing,
|
||||
FadeInUp,
|
||||
FadeOutDown,
|
||||
LinearTransition,
|
||||
useAnimatedStyle,
|
||||
useSharedValue,
|
||||
withTiming,
|
||||
type SharedValue,
|
||||
} from "react-native-reanimated";
|
||||
import type { ApprovalRequestId } from "@t3tools/contracts";
|
||||
import { Pressable, View } from "react-native";
|
||||
|
||||
import { USER_INPUT_TOGGLE_DURATION_MS } from "./pendingUserInputLayout";
|
||||
|
||||
import { SymbolView } from "../../components/AppSymbol";
|
||||
import { AppText as Text, AppTextInput as TextInput } from "../../components/AppText";
|
||||
import { ControlPill } from "../../components/ControlPill";
|
||||
import { cn } from "../../lib/cn";
|
||||
import { useThemeColor } from "../../lib/useThemeColor";
|
||||
import {
|
||||
isPendingUserInputOptionSelected,
|
||||
type PendingUserInput,
|
||||
type PendingUserInputDraftAnswer,
|
||||
} from "../../lib/threadActivity";
|
||||
import type { PendingUserInput, PendingUserInputDraftAnswer } from "../../lib/threadActivity";
|
||||
|
||||
export interface PendingUserInputCardProps {
|
||||
readonly pendingUserInput: PendingUserInput;
|
||||
/**
|
||||
* Constant while a request is pending (it reserves keyboard space), so the
|
||||
* keyboard transition is pure translation; changes only on rare discrete
|
||||
* corrections, which the layout transition smooths.
|
||||
*/
|
||||
readonly maxHeight: number;
|
||||
readonly collapsed: boolean;
|
||||
readonly onToggleCollapsed: () => void;
|
||||
/** Renders a stop control on the collapsed bar, which replaces the composer. */
|
||||
readonly onStopThread?: () => void;
|
||||
/**
|
||||
* 0 collapsed → 1 expanded. Slides the iOS overlay card down behind the
|
||||
* collapsed bar (inside a clipping window) on the UI thread; the host
|
||||
* animates it directly from the tap handler so the card and the feed
|
||||
* inset glide start the same frame.
|
||||
*/
|
||||
readonly cardProgress?: SharedValue<number>;
|
||||
/**
|
||||
* Receives how far the expanded card extends above the bar footprint
|
||||
* (written from onLayout with no re-render); the host adds it to the
|
||||
* thread feed's end inset so the end of the chat stays visible above the
|
||||
* card.
|
||||
*/
|
||||
readonly cardCoverage?: SharedValue<number>;
|
||||
/** Fires on custom-answer focus/blur; hosts use it to vet stale keyboard state. */
|
||||
readonly onInputFocusChange?: (focused: boolean) => void;
|
||||
readonly drafts: Record<string, PendingUserInputDraftAnswer>;
|
||||
readonly answers: Record<string, string | ReadonlyArray<string>> | null;
|
||||
readonly answers: Record<string, string> | null;
|
||||
readonly respondingUserInputId: ApprovalRequestId | null;
|
||||
readonly onSelectOption: (
|
||||
requestId: ApprovalRequestId,
|
||||
question: UserInputQuestion,
|
||||
questionId: string,
|
||||
label: string,
|
||||
) => void;
|
||||
readonly onChangeCustomAnswer: (
|
||||
@@ -69,242 +23,74 @@ export interface PendingUserInputCardProps {
|
||||
readonly onSubmit: () => Promise<unknown>;
|
||||
}
|
||||
|
||||
/**
|
||||
* On iOS the collapsed bar is the PERMANENT in-flow footprint — the expanded
|
||||
* card is an absolutely-positioned overlay rising above it. The overlay's
|
||||
* measured height (which drives the thread feed's bottom inset) therefore
|
||||
* never changes on collapse/expand, so the transcript stays perfectly still
|
||||
* while the card animates over it.
|
||||
*
|
||||
* Android cannot use the overlay: it does not hit-test touches outside a
|
||||
* parent's bounds, which made everything above the bar-sized wrapper
|
||||
* untouchable. There the expanded card renders in-flow instead (the wrapper
|
||||
* grows with it, and the host skips the coverage inset since the measured
|
||||
* overlay already includes the card).
|
||||
*/
|
||||
const EXPANDED_CARD_IS_OVERLAY = Platform.OS === "ios";
|
||||
|
||||
const CARD_LAYOUT_TRANSITION = LinearTransition.duration(200);
|
||||
|
||||
export function PendingUserInputCard(props: PendingUserInputCardProps) {
|
||||
const iconSubtle = useThemeColor("--color-icon-subtle");
|
||||
const questionCount = props.pendingUserInput.questions.length;
|
||||
|
||||
const cardCoverage = props.cardCoverage;
|
||||
const barHeightRef = useRef(0);
|
||||
const cardHeightRef = useRef(0);
|
||||
// Measured card height, written straight from onLayout: the collapse slide
|
||||
// distance. Not animated — it only changes on discrete relayouts.
|
||||
const cardHeight = useSharedValue(0);
|
||||
const notifyCoverage = useCallback(() => {
|
||||
if (!cardCoverage) {
|
||||
return;
|
||||
}
|
||||
const coverage = Math.max(0, cardHeightRef.current - barHeightRef.current);
|
||||
if (coverage === cardCoverage.value) {
|
||||
return;
|
||||
}
|
||||
if (cardCoverage.value === 0) {
|
||||
// First measurement lands while the list is doing its initial
|
||||
// end-pin (thread opened onto a pending request); animating it from
|
||||
// zero would move the end anchor out from under that scroll.
|
||||
cardCoverage.value = coverage;
|
||||
return;
|
||||
}
|
||||
// Animated so a coverage change at rest (discrete max-height
|
||||
// corrections) glides the feed instead of stepping it; toggle timing is
|
||||
// owned by the host's progress values.
|
||||
cardCoverage.value = withTiming(coverage, {
|
||||
duration: USER_INPUT_TOGGLE_DURATION_MS,
|
||||
easing: Easing.out(Easing.cubic),
|
||||
});
|
||||
}, [cardCoverage]);
|
||||
const handleBarLayout = useCallback(
|
||||
(event: LayoutChangeEvent) => {
|
||||
barHeightRef.current = event.nativeEvent.layout.height;
|
||||
notifyCoverage();
|
||||
},
|
||||
[notifyCoverage],
|
||||
);
|
||||
const handleCardLayout = useCallback(
|
||||
(event: LayoutChangeEvent) => {
|
||||
cardHeightRef.current = event.nativeEvent.layout.height;
|
||||
cardHeight.value = event.nativeEvent.layout.height;
|
||||
notifyCoverage();
|
||||
},
|
||||
[cardHeight, notifyCoverage],
|
||||
);
|
||||
const cardProgress = props.cardProgress;
|
||||
// No opacity: fading an opaque card over the live transcript reads as a
|
||||
// crossfade (card text, transcript, and bar all half-visible at once).
|
||||
// Instead the card stays opaque and slides its full height down past the
|
||||
// clipping window's bottom edge, so the transcript is only revealed where
|
||||
// the card has physically left.
|
||||
const cardAnimatedStyle = useAnimatedStyle(() => {
|
||||
const progress = cardProgress === undefined ? 1 : cardProgress.value;
|
||||
return {
|
||||
transform: [{ translateY: (1 - progress) * cardHeight.value }],
|
||||
};
|
||||
});
|
||||
|
||||
// On iOS the card stays MOUNTED while collapsed (hidden via the animated
|
||||
// style): expanding animates existing views on the UI thread the same
|
||||
// frame the host starts the progress timing, instead of paying a React
|
||||
// mount + layout before anything moves.
|
||||
const renderCard = EXPANDED_CARD_IS_OVERLAY || !props.collapsed;
|
||||
const showBar = props.collapsed || EXPANDED_CARD_IS_OVERLAY;
|
||||
// The bar renders UNDER the card (earlier in JSX), always opaque: while
|
||||
// expanded the opaque card covers it, and during the collapse slide the
|
||||
// card's top edge wipes past and reveals it — no opacity handoff, so no
|
||||
// crossfade frames.
|
||||
const bar = showBar ? (
|
||||
<View
|
||||
onLayout={handleBarLayout}
|
||||
pointerEvents={props.collapsed ? "auto" : "none"}
|
||||
accessibilityElementsHidden={!props.collapsed}
|
||||
importantForAccessibility={props.collapsed ? "auto" : "no-hide-descendants"}
|
||||
className="flex-row items-center gap-2 rounded-full border border-neutral-200 bg-neutral-100 py-1.5 pl-4 pr-1.5 dark:border-white/6 dark:bg-neutral-900"
|
||||
>
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel={`Expand user input, ${questionCount} question${
|
||||
questionCount === 1 ? "" : "s"
|
||||
}`}
|
||||
onPress={props.onToggleCollapsed}
|
||||
className="min-h-10 flex-1 flex-row items-center gap-2 active:opacity-70"
|
||||
>
|
||||
<Text className="font-t3-bold text-2xs uppercase tracking-[1.1px] text-sky-700 dark:text-sky-300">
|
||||
User input needed
|
||||
</Text>
|
||||
<Text className="font-sans text-xs text-neutral-500 dark:text-neutral-400">
|
||||
{questionCount} question{questionCount === 1 ? "" : "s"}
|
||||
</Text>
|
||||
<View className="flex-1" />
|
||||
<SymbolView name="chevron.up" size={12} tintColor={iconSubtle} type="monochrome" />
|
||||
</Pressable>
|
||||
{props.onStopThread ? (
|
||||
<ControlPill
|
||||
accessibilityLabel="Stop"
|
||||
icon="stop.fill"
|
||||
variant="danger"
|
||||
className="h-9 w-9"
|
||||
onPress={props.onStopThread}
|
||||
/>
|
||||
) : null}
|
||||
</View>
|
||||
) : null;
|
||||
const card = renderCard ? (
|
||||
// The surface is opaque on purpose: the card floats over the thread
|
||||
// feed with no blur behind it, so a translucent background renders
|
||||
// the questions on top of whatever message happens to sit underneath.
|
||||
<Animated.View
|
||||
onLayout={handleCardLayout}
|
||||
pointerEvents={props.collapsed ? "none" : "auto"}
|
||||
accessibilityElementsHidden={props.collapsed}
|
||||
importantForAccessibility={props.collapsed ? "no-hide-descendants" : "auto"}
|
||||
entering={
|
||||
EXPANDED_CARD_IS_OVERLAY
|
||||
? undefined
|
||||
: FadeInUp.duration(USER_INPUT_TOGGLE_DURATION_MS).easing(Easing.out(Easing.cubic))
|
||||
}
|
||||
exiting={
|
||||
EXPANDED_CARD_IS_OVERLAY
|
||||
? undefined
|
||||
: FadeOutDown.duration(USER_INPUT_TOGGLE_DURATION_MS).easing(Easing.out(Easing.cubic))
|
||||
}
|
||||
layout={CARD_LAYOUT_TRANSITION}
|
||||
className="overflow-hidden gap-2.5 rounded-[20px] border border-neutral-200 bg-neutral-100 p-4 dark:border-white/6 dark:bg-neutral-900"
|
||||
style={
|
||||
EXPANDED_CARD_IS_OVERLAY
|
||||
? [{ maxHeight: props.maxHeight }, cardAnimatedStyle]
|
||||
: { maxHeight: props.maxHeight }
|
||||
}
|
||||
>
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel="Collapse user input"
|
||||
onPress={props.onToggleCollapsed}
|
||||
className="flex-row items-start gap-2"
|
||||
>
|
||||
<View className="flex-1 gap-2.5">
|
||||
<Text className="font-t3-bold text-2xs uppercase tracking-[1.1px] text-sky-700 dark:text-sky-300">
|
||||
User input needed
|
||||
</Text>
|
||||
<Text className="font-t3-bold text-lg text-neutral-950 dark:text-neutral-50">
|
||||
Fill in the pending answers
|
||||
</Text>
|
||||
</View>
|
||||
<View className="h-8 w-8 items-center justify-center rounded-full bg-neutral-200/70 dark:bg-white/8">
|
||||
<SymbolView name="chevron.down" size={13} tintColor={iconSubtle} type="monochrome" />
|
||||
</View>
|
||||
</Pressable>
|
||||
<ScrollView
|
||||
bounces={false}
|
||||
className="min-h-0"
|
||||
contentContainerClassName="gap-2.5 pb-1"
|
||||
keyboardShouldPersistTaps="handled"
|
||||
nestedScrollEnabled
|
||||
showsVerticalScrollIndicator
|
||||
style={{ flexShrink: 1 }}
|
||||
>
|
||||
{props.pendingUserInput.questions.map((question) => {
|
||||
const draft = props.drafts[question.id];
|
||||
return (
|
||||
<View key={question.id} className="gap-2 pt-1">
|
||||
<Text className="font-t3-bold text-xs uppercase tracking-[1px] text-neutral-500 dark:text-neutral-500">
|
||||
{question.header}
|
||||
</Text>
|
||||
<Text className="font-sans text-base leading-snug text-neutral-950 dark:text-neutral-50">
|
||||
{question.question}
|
||||
</Text>
|
||||
<View className="flex-row flex-wrap gap-2.5">
|
||||
{question.options.map((option) => {
|
||||
const selected = isPendingUserInputOptionSelected(draft, option.label);
|
||||
return (
|
||||
<Pressable
|
||||
key={option.label}
|
||||
// The surface is opaque on purpose: the card floats over the thread feed
|
||||
// with no blur behind it, so a translucent background renders the questions
|
||||
// on top of whatever message happens to sit underneath.
|
||||
return (
|
||||
<View className="gap-2.5 rounded-[20px] border border-neutral-200 bg-neutral-100 p-4 dark:border-white/6 dark:bg-neutral-900">
|
||||
<Text className="font-t3-bold text-2xs uppercase tracking-[1.1px] text-sky-700 dark:text-sky-300">
|
||||
User input needed
|
||||
</Text>
|
||||
<Text className="font-t3-bold text-lg text-neutral-950 dark:text-neutral-50">
|
||||
Fill in the pending answers
|
||||
</Text>
|
||||
{props.pendingUserInput.questions.map((question) => {
|
||||
const draft = props.drafts[question.id];
|
||||
return (
|
||||
<View key={question.id} className="gap-2 pt-1">
|
||||
<Text className="font-t3-bold text-xs uppercase tracking-[1px] text-neutral-500 dark:text-neutral-500">
|
||||
{question.header}
|
||||
</Text>
|
||||
<Text className="font-sans text-base leading-snug text-neutral-950 dark:text-neutral-50">
|
||||
{question.question}
|
||||
</Text>
|
||||
<View className="flex-row flex-wrap gap-2.5">
|
||||
{question.options.map((option) => {
|
||||
const selected =
|
||||
draft?.selectedOptionLabel === option.label && !draft.customAnswer?.trim().length;
|
||||
return (
|
||||
<Pressable
|
||||
key={option.label}
|
||||
className={cn(
|
||||
"rounded-full border px-3 py-2.5 ",
|
||||
selected
|
||||
? "border-blue-300/50 bg-blue-50 dark:border-blue-400/28 dark:bg-blue-400/14"
|
||||
: "border-neutral-200 bg-white dark:border-white/6 dark:bg-neutral-950/70",
|
||||
)}
|
||||
onPress={() =>
|
||||
props.onSelectOption(
|
||||
props.pendingUserInput.requestId,
|
||||
question.id,
|
||||
option.label,
|
||||
)
|
||||
}
|
||||
>
|
||||
<Text
|
||||
className={cn(
|
||||
"rounded-full border px-3 py-2.5 ",
|
||||
"font-t3-bold text-sm",
|
||||
selected
|
||||
? "border-blue-300/50 bg-blue-50 dark:border-blue-400/28 dark:bg-blue-400/14"
|
||||
: "border-neutral-200 bg-white dark:border-white/6 dark:bg-neutral-950/70",
|
||||
? "text-sky-700 dark:text-sky-300"
|
||||
: "text-neutral-600 dark:text-neutral-300",
|
||||
)}
|
||||
onPress={() =>
|
||||
props.onSelectOption(
|
||||
props.pendingUserInput.requestId,
|
||||
question,
|
||||
option.label,
|
||||
)
|
||||
}
|
||||
>
|
||||
<Text
|
||||
className={cn(
|
||||
"font-t3-bold text-sm",
|
||||
selected
|
||||
? "text-sky-700 dark:text-sky-300"
|
||||
: "text-neutral-600 dark:text-neutral-300",
|
||||
)}
|
||||
>
|
||||
{option.label}
|
||||
</Text>
|
||||
</Pressable>
|
||||
);
|
||||
})}
|
||||
</View>
|
||||
<TextInput
|
||||
value={draft?.customAnswer ?? ""}
|
||||
onChangeText={(value) =>
|
||||
props.onChangeCustomAnswer(props.pendingUserInput.requestId, question.id, value)
|
||||
}
|
||||
onFocus={() => props.onInputFocusChange?.(true)}
|
||||
onBlur={() => props.onInputFocusChange?.(false)}
|
||||
placeholder="Or type a custom answer"
|
||||
className="min-h-[54px] rounded-2xl border border-neutral-200 bg-white px-3.5 py-3 font-sans text-base text-neutral-950 dark:border-white/8 dark:bg-neutral-950/70 dark:text-neutral-50"
|
||||
/>
|
||||
{option.label}
|
||||
</Text>
|
||||
</Pressable>
|
||||
);
|
||||
})}
|
||||
</View>
|
||||
);
|
||||
})}
|
||||
</ScrollView>
|
||||
<TextInput
|
||||
value={draft?.customAnswer ?? ""}
|
||||
onChangeText={(value) =>
|
||||
props.onChangeCustomAnswer(props.pendingUserInput.requestId, question.id, value)
|
||||
}
|
||||
placeholder="Or type a custom answer"
|
||||
className="min-h-[54px] rounded-2xl border border-neutral-200 bg-white px-3.5 py-3 font-sans text-base text-neutral-950 dark:border-white/8 dark:bg-neutral-950/70 dark:text-neutral-50"
|
||||
/>
|
||||
</View>
|
||||
);
|
||||
})}
|
||||
<Pressable
|
||||
className={cn(
|
||||
"items-center justify-center rounded-2xl px-4 py-3.5",
|
||||
@@ -317,26 +103,6 @@ export function PendingUserInputCard(props: PendingUserInputCardProps) {
|
||||
>
|
||||
<Text className="font-t3-extrabold text-sm text-white">Submit answers</Text>
|
||||
</Pressable>
|
||||
</Animated.View>
|
||||
) : null;
|
||||
return (
|
||||
<View className="relative">
|
||||
{bar}
|
||||
{EXPANDED_CARD_IS_OVERLAY ? (
|
||||
// Clipping window for the collapse slide: same footprint as the
|
||||
// expanded card, bottom edge on the bar's bottom edge. The sliding
|
||||
// card exits through the bottom edge instead of drawing over the
|
||||
// composer area, wiping the bar (and the transcript) into view.
|
||||
<View
|
||||
pointerEvents={props.collapsed ? "none" : "box-none"}
|
||||
className="absolute inset-x-0 bottom-0 justify-end overflow-hidden"
|
||||
style={{ height: props.maxHeight }}
|
||||
>
|
||||
{card}
|
||||
</View>
|
||||
) : (
|
||||
card
|
||||
)}
|
||||
</View>
|
||||
);
|
||||
}
|
||||
@@ -14,7 +14,6 @@ import {
|
||||
serializeComposerFileLink,
|
||||
type ComposerTrigger,
|
||||
} from "@t3tools/shared/composerTrigger";
|
||||
import * as Haptics from "expo-haptics";
|
||||
import type { ReactNode } from "react";
|
||||
import { memo, useCallback, useEffect, useMemo, useRef, useState, type RefObject } from "react";
|
||||
import {
|
||||
@@ -52,7 +51,7 @@ import {
|
||||
ComposerToolbarScroller,
|
||||
ComposerToolbarTrigger,
|
||||
} from "../../components/ComposerToolbarTrigger";
|
||||
import { ControlPill, ControlPillMenu } from "../../components/ControlPill";
|
||||
import { ControlPill } from "../../components/ControlPill";
|
||||
import { ProviderIcon } from "../../components/ProviderIcon";
|
||||
import type { DraftComposerImageAttachment } from "../../lib/composerImages";
|
||||
import { buildModelOptions, groupByProvider } from "../../lib/modelOptions";
|
||||
@@ -63,13 +62,9 @@ import {
|
||||
normalizeSearchQuery,
|
||||
scoreQueryMatch,
|
||||
} from "@t3tools/shared/searchRanking";
|
||||
import {
|
||||
applyProviderOptionSelection,
|
||||
resolveProviderOptionDescriptors,
|
||||
} from "../../lib/providerOptions";
|
||||
import { resolveProviderOptionDescriptors } from "../../lib/providerOptions";
|
||||
import { useComposerPathSearch } from "../../state/use-composer-path-search";
|
||||
import { ComposerCommandPopover, type ComposerCommandItem } from "./ComposerCommandPopover";
|
||||
import { buildThreadSettingsMenu } from "./thread-settings-menu";
|
||||
import { ThreadSettingsSheet, threadSettingsSummaryLabel } from "./ThreadSettingsSheet";
|
||||
import { useThreadSettingsSheetPresentation } from "./use-thread-settings-sheet-presentation";
|
||||
|
||||
@@ -118,8 +113,6 @@ export interface ThreadComposerProps {
|
||||
readonly onUpdateInteractionMode: (interactionMode: ProviderInteractionMode) => void;
|
||||
readonly onReconnectEnvironment: () => void;
|
||||
readonly onExpandedChange?: (expanded: boolean) => void;
|
||||
/** Fires on editor focus/blur; hosts use it to vet stale keyboard state. */
|
||||
readonly onEditorFocusChange?: (focused: boolean) => void;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -314,16 +307,13 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
|
||||
}
|
||||
}, [inputRef]);
|
||||
|
||||
const onEditorFocusChange = props.onEditorFocusChange;
|
||||
const handleFocus = useCallback(() => {
|
||||
setIsFocused(true);
|
||||
onEditorFocusChange?.(true);
|
||||
}, [onEditorFocusChange]);
|
||||
}, []);
|
||||
|
||||
const handleBlur = useCallback(() => {
|
||||
setIsFocused(false);
|
||||
onEditorFocusChange?.(false);
|
||||
}, [onEditorFocusChange]);
|
||||
}, []);
|
||||
const showStopAction =
|
||||
props.selectedThread.session?.status === "running" ||
|
||||
props.selectedThread.session?.status === "starting";
|
||||
@@ -633,61 +623,6 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
|
||||
interactionMode: currentInteractionMode,
|
||||
});
|
||||
|
||||
// iOS gets a native menu on the trigger pill: the everyday adjustments
|
||||
// apply without resigning the keyboard, while "All Settings…" (and the
|
||||
// Android trigger) still route through the sheet, which must dismiss it.
|
||||
const settingsMenu = useMemo(
|
||||
() =>
|
||||
Platform.OS === "ios"
|
||||
? buildThreadSettingsMenu({
|
||||
providerGroups: threadProviderGroups,
|
||||
selectedModel: currentModelSelection,
|
||||
optionDescriptors: providerOptionDescriptors,
|
||||
runtimeMode: currentRuntimeMode,
|
||||
})
|
||||
: null,
|
||||
[threadProviderGroups, currentModelSelection, providerOptionDescriptors, currentRuntimeMode],
|
||||
);
|
||||
|
||||
const onUpdateModelSelection = props.onUpdateModelSelection;
|
||||
const onUpdateRuntimeMode = props.onUpdateRuntimeMode;
|
||||
const handleSettingsMenuAction = useCallback(
|
||||
(eventId: string) => {
|
||||
const event = settingsMenu?.events.get(eventId);
|
||||
if (!event) {
|
||||
return;
|
||||
}
|
||||
switch (event.type) {
|
||||
case "select-model":
|
||||
void Haptics.selectionAsync();
|
||||
onUpdateModelSelection(event.option.selection);
|
||||
return;
|
||||
case "set-option": {
|
||||
const options = applyProviderOptionSelection(providerOptionDescriptors, {
|
||||
id: event.optionId,
|
||||
value: event.value,
|
||||
});
|
||||
if (options) {
|
||||
void Haptics.selectionAsync();
|
||||
onUpdateModelSelection({ ...currentModelSelection, options });
|
||||
}
|
||||
return;
|
||||
}
|
||||
case "set-runtime":
|
||||
void Haptics.selectionAsync();
|
||||
onUpdateRuntimeMode(event.mode);
|
||||
return;
|
||||
}
|
||||
},
|
||||
[
|
||||
currentModelSelection,
|
||||
onUpdateModelSelection,
|
||||
onUpdateRuntimeMode,
|
||||
providerOptionDescriptors,
|
||||
settingsMenu,
|
||||
],
|
||||
);
|
||||
|
||||
return (
|
||||
<Animated.View
|
||||
className="px-4"
|
||||
@@ -857,31 +792,15 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
|
||||
onPress={() => void props.onPickDraftImages()}
|
||||
showChevron={false}
|
||||
/>
|
||||
{settingsMenu ? (
|
||||
<ControlPillMenu
|
||||
actions={settingsMenu.actions}
|
||||
onPressAction={({ nativeEvent }) => handleSettingsMenuAction(nativeEvent.event)}
|
||||
>
|
||||
<ComposerToolbarTrigger
|
||||
accessibilityLabel="Thread settings"
|
||||
iconNode={
|
||||
<ProviderIcon provider={currentModelOption?.providerDriver} size={16} />
|
||||
}
|
||||
label={settingsSummaryLabel}
|
||||
maxWidth={320}
|
||||
/>
|
||||
</ControlPillMenu>
|
||||
) : (
|
||||
<ComposerToolbarTrigger
|
||||
accessibilityLabel="Thread settings"
|
||||
iconNode={
|
||||
<ProviderIcon provider={currentModelOption?.providerDriver} size={16} />
|
||||
}
|
||||
label={settingsSummaryLabel}
|
||||
maxWidth={320}
|
||||
onPress={settingsSheetPresentation.open}
|
||||
/>
|
||||
)}
|
||||
<ComposerToolbarTrigger
|
||||
accessibilityLabel="Thread settings"
|
||||
iconNode={
|
||||
<ProviderIcon provider={currentModelOption?.providerDriver} size={16} />
|
||||
}
|
||||
label={settingsSummaryLabel}
|
||||
maxWidth={320}
|
||||
onPress={settingsSheetPresentation.open}
|
||||
/>
|
||||
{showStopAction ? (
|
||||
<ComposerToolbarButton
|
||||
accessibilityLabel="Stop"
|
||||
|
||||
@@ -2,7 +2,6 @@ import { type EnvironmentConnectionPhase } from "@t3tools/client-runtime/connect
|
||||
import type { EnvironmentThreadStatus } from "@t3tools/client-runtime/state/threads";
|
||||
import { useKeyboardChatComposerInset, useKeyboardScrollToEnd } from "@legendapp/list/keyboard";
|
||||
import type { LegendListRef } from "@legendapp/list/react-native";
|
||||
import { HeaderHeightContext } from "@react-navigation/elements";
|
||||
import type {
|
||||
ApprovalRequestId,
|
||||
EnvironmentId,
|
||||
@@ -14,45 +13,14 @@ import type {
|
||||
RuntimeMode,
|
||||
ServerConfig as T3ServerConfig,
|
||||
ThreadId,
|
||||
UserInputQuestion,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Haptics from "expo-haptics";
|
||||
import {
|
||||
memo,
|
||||
useCallback,
|
||||
useContext,
|
||||
useEffect,
|
||||
useLayoutEffect,
|
||||
useMemo,
|
||||
useRef,
|
||||
useState,
|
||||
} from "react";
|
||||
import { isLiquidGlassSupported, LiquidGlassView } from "@callstack/liquid-glass";
|
||||
import {
|
||||
AppState,
|
||||
Keyboard,
|
||||
Platform,
|
||||
useColorScheme,
|
||||
useWindowDimensions,
|
||||
View,
|
||||
type GestureResponderEvent,
|
||||
} from "react-native";
|
||||
import {
|
||||
KeyboardController,
|
||||
KeyboardStickyView,
|
||||
useKeyboardState,
|
||||
} from "react-native-keyboard-controller";
|
||||
import Animated, {
|
||||
Easing,
|
||||
FadeInDown,
|
||||
FadeOut,
|
||||
useAnimatedReaction,
|
||||
useSharedValue,
|
||||
withTiming,
|
||||
} from "react-native-reanimated";
|
||||
import { memo, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
|
||||
import { Platform, View, type GestureResponderEvent } from "react-native";
|
||||
import { KeyboardController, KeyboardStickyView } from "react-native-keyboard-controller";
|
||||
import Animated, { FadeInDown, FadeOut } from "react-native-reanimated";
|
||||
import { useSafeAreaInsets } from "react-native-safe-area-context";
|
||||
|
||||
import { ControlPill } from "../../components/ControlPill";
|
||||
import type { ComposerEditorHandle } from "../../components/ComposerEditor";
|
||||
import type { StatusTone } from "../../components/StatusPill";
|
||||
import type { DraftComposerImageAttachment } from "../../lib/composerImages";
|
||||
@@ -66,11 +34,6 @@ import type {
|
||||
} from "../../lib/threadActivity";
|
||||
import { PendingApprovalCard } from "./PendingApprovalCard";
|
||||
import { PendingUserInputCard } from "./PendingUserInputCard";
|
||||
import {
|
||||
derivePendingUserInputMaxHeight,
|
||||
ESTIMATED_KEYBOARD_HEIGHT,
|
||||
USER_INPUT_TOGGLE_DURATION_MS,
|
||||
} from "./pendingUserInputLayout";
|
||||
import {
|
||||
COMPOSER_COLLAPSED_CHROME,
|
||||
COMPOSER_EXPANDED_CHROME,
|
||||
@@ -91,7 +54,7 @@ export interface ThreadDetailScreenProps {
|
||||
readonly respondingApprovalId: ApprovalRequestId | null;
|
||||
readonly activePendingUserInput: PendingUserInput | null;
|
||||
readonly activePendingUserInputDrafts: Record<string, PendingUserInputDraftAnswer>;
|
||||
readonly activePendingUserInputAnswers: Record<string, string | ReadonlyArray<string>> | null;
|
||||
readonly activePendingUserInputAnswers: Record<string, string> | null;
|
||||
readonly respondingUserInputId: ApprovalRequestId | null;
|
||||
readonly draftMessage: string;
|
||||
readonly draftAttachments: ReadonlyArray<DraftComposerImageAttachment>;
|
||||
@@ -126,7 +89,7 @@ export interface ThreadDetailScreenProps {
|
||||
) => Promise<unknown>;
|
||||
readonly onSelectUserInputOption: (
|
||||
requestId: ApprovalRequestId,
|
||||
question: UserInputQuestion,
|
||||
questionId: string,
|
||||
label: string,
|
||||
) => void;
|
||||
readonly onChangeUserInputCustomAnswer: (
|
||||
@@ -208,48 +171,8 @@ function useStreamingHaptics(threadId: ThreadId, feed: ReadonlyArray<ThreadFeedE
|
||||
}, [threadId, feed]);
|
||||
}
|
||||
|
||||
const USER_INPUT_TOGGLE_TIMING = {
|
||||
duration: USER_INPUT_TOGGLE_DURATION_MS,
|
||||
easing: Easing.out(Easing.cubic),
|
||||
};
|
||||
|
||||
export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: ThreadDetailScreenProps) {
|
||||
const insets = useSafeAreaInsets();
|
||||
const isKeyboardVisible = useKeyboardState((state) => state.isVisible);
|
||||
const liveKeyboardHeight = useKeyboardState((state) => state.height);
|
||||
// Android can swallow the IME hide callbacks when the app is backgrounded
|
||||
// mid keyboard-hide (the reported repro: send — which blurs and starts the
|
||||
// hide — then Home within a second). The keyboard library's height AND
|
||||
// visibility then stay frozen open, so gating the sticky translation on
|
||||
// visibility alone still strands the composer after resume. Quarantine the
|
||||
// translation on every Android resume instead; any sign of a live keyboard
|
||||
// stream — an owned input gaining focus, or any visibility/height movement —
|
||||
// lifts it. A healthy resume sees no visual difference (the translation is
|
||||
// already zero while the keyboard is closed).
|
||||
const [keyboardStateSuspect, setKeyboardStateSuspect] = useState(false);
|
||||
useEffect(() => {
|
||||
if (Platform.OS !== "android") {
|
||||
return;
|
||||
}
|
||||
const subscription = AppState.addEventListener("change", (state) => {
|
||||
if (state === "active") {
|
||||
setKeyboardStateSuspect(true);
|
||||
}
|
||||
});
|
||||
return () => {
|
||||
subscription.remove();
|
||||
};
|
||||
}, []);
|
||||
useEffect(() => {
|
||||
setKeyboardStateSuspect(false);
|
||||
}, [isKeyboardVisible, liveKeyboardHeight]);
|
||||
const handleOwnedInputFocusChange = useCallback((focused: boolean) => {
|
||||
if (focused) {
|
||||
setKeyboardStateSuspect(false);
|
||||
}
|
||||
}, []);
|
||||
const windowHeight = useWindowDimensions().height;
|
||||
const navigationHeaderHeight = useContext(HeaderHeightContext) || insets.top + 44;
|
||||
const agentLabel = `${props.selectedThread.modelSelection.instanceId} agent`;
|
||||
const selectedThreadKey = scopedThreadKey(props.environmentId, props.selectedThread.id);
|
||||
const composerEditorRef = useRef<ComposerEditorHandle>(null);
|
||||
@@ -260,17 +183,7 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
|
||||
const lastScrolledAnchorMessageIdRef = useRef<MessageId | null>(null);
|
||||
const [composerExpanded, setComposerExpanded] = useState(false);
|
||||
const [anchorMessageId, setAnchorMessageId] = useState<MessageId | null>(null);
|
||||
const [endFollowEnabled, setEndFollowEnabled] = useState(true);
|
||||
// Android keys the safe-area padding on keyboard visibility (#5988): the
|
||||
// back gesture closes the keyboard while the editor stays focused, and a
|
||||
// focus-keyed inset would leave the toolbar under the gesture bar. iOS must
|
||||
// NOT use visibility — it only flips on keyboardDidHide, after the hide
|
||||
// animation, so the composer would ride down flush to the screen edge and
|
||||
// then snap up into the inset. On iOS blur precedes the hide, so the
|
||||
// focus-keyed inset is already in place while the composer rides down.
|
||||
const composerBottomInset = (Platform.OS === "android" ? isKeyboardVisible : composerExpanded)
|
||||
? 0
|
||||
: Math.max(insets.bottom, 12);
|
||||
const composerBottomInset = composerExpanded ? 0 : Math.max(insets.bottom, 12);
|
||||
const contentPresentationKind = props.contentPresentation.kind;
|
||||
// The raw sync status enters "synchronizing" on every full fetch, cached or
|
||||
// not. Whether messages are already on screen decides the pill label: no
|
||||
@@ -291,41 +204,6 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
|
||||
const selectedThreadFeed = props.selectedThreadFeed;
|
||||
const composerChrome = composerExpanded ? COMPOSER_EXPANDED_CHROME : COMPOSER_COLLAPSED_CHROME;
|
||||
const composerOverlapHeight = composerChrome + composerBottomInset;
|
||||
// While a user-input request is pending, the questionnaire owns the
|
||||
// composer slot outright: expanded it is the full card, collapsed it is a
|
||||
// composer-style bar in the same place (with its own stop control). The
|
||||
// composer never mounts into the transition, which keeps the collapse and
|
||||
// keyboard animations coherent. Collapse state is keyed by request id so a
|
||||
// new request re-expands automatically.
|
||||
const [collapsedUserInputRequestId, setCollapsedUserInputRequestId] =
|
||||
useState<ApprovalRequestId | null>(null);
|
||||
const activeUserInputRequestId = props.activePendingUserInput?.requestId ?? null;
|
||||
const userInputCollapsed =
|
||||
activeUserInputRequestId !== null && collapsedUserInputRequestId === activeUserInputRequestId;
|
||||
// The card's height RESERVES keyboard space at all times instead of
|
||||
// tracking the keyboard: transforms (the sticky translation) apply
|
||||
// same-frame on the UI thread while layout props lag a Yoga pass behind,
|
||||
// so any height that follows the keyboard flashes the card over the nav
|
||||
// header on the way up. With a constant height the keyboard transition is
|
||||
// pure translation — frame-perfect by construction — and the resting card
|
||||
// stays compact over the transcript. Before the first open the reserve is
|
||||
// an estimate; once a real height is known the card corrects once,
|
||||
// discretely.
|
||||
const [lastKnownKeyboardHeight, setLastKnownKeyboardHeight] = useState(0);
|
||||
useEffect(() => {
|
||||
if (liveKeyboardHeight > 0 && liveKeyboardHeight !== lastKnownKeyboardHeight) {
|
||||
setLastKnownKeyboardHeight(liveKeyboardHeight);
|
||||
}
|
||||
}, [lastKnownKeyboardHeight, liveKeyboardHeight]);
|
||||
const pendingUserInputMaxHeight = derivePendingUserInputMaxHeight({
|
||||
windowHeight,
|
||||
keyboardHeight:
|
||||
lastKnownKeyboardHeight > 0 ? lastKnownKeyboardHeight : ESTIMATED_KEYBOARD_HEIGHT,
|
||||
navigationHeaderHeight,
|
||||
// The questionnaire owns the composer slot, so only the composer's
|
||||
// bottom inset still overlaps.
|
||||
composerOverlapHeight: composerBottomInset,
|
||||
});
|
||||
const estimatedOverlayHeight = composerOverlapHeight;
|
||||
// The overlay's measured height includes the home-indicator inset (the
|
||||
// composer pads it), but contentInsetAdjustmentBehavior="automatic" makes
|
||||
@@ -342,103 +220,7 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
|
||||
Math.max(0, estimatedOverlayHeight - nativeInsetOvercount),
|
||||
-nativeInsetOvercount,
|
||||
);
|
||||
// The expanded questionnaire is an absolute overlay on iOS, so it never
|
||||
// changes the measured overlay height (that constancy is what keeps the
|
||||
// feed from snapping on collapse/expand). The toggle choreography runs on
|
||||
// SHARED VALUES set directly in the tap handler — one JS hop, then the
|
||||
// card's rise/sink and the feed's end-inset glide animate in lockstep on
|
||||
// the UI thread, keyboard-style, instead of waiting on React mount +
|
||||
// onLayout + state round trips. Coverage (how far the card extends above
|
||||
// the bar) is measured straight into a shared value by the card's
|
||||
// onLayout, with no re-render.
|
||||
const userInputCardProgress = useSharedValue(1);
|
||||
const userInputInsetProgress = useSharedValue(1);
|
||||
const userInputCardCoverage = useSharedValue(0);
|
||||
// Android renders the expanded card in-flow (it cannot hit-test the iOS
|
||||
// overlay outside the bar's bounds), so its measured overlay height already
|
||||
// includes the card — the coverage extra is iOS-only.
|
||||
const userInputCoverageApplies = Platform.OS === "ios" && activeUserInputRequestId !== null;
|
||||
const combinedContentInsetEndAdjustment = useSharedValue(
|
||||
Math.max(0, estimatedOverlayHeight - nativeInsetOvercount),
|
||||
);
|
||||
useAnimatedReaction(
|
||||
() =>
|
||||
contentInsetEndAdjustment.value +
|
||||
(userInputCoverageApplies ? userInputInsetProgress.value * userInputCardCoverage.value : 0),
|
||||
(value) => {
|
||||
combinedContentInsetEndAdjustment.value = value;
|
||||
},
|
||||
[userInputCoverageApplies],
|
||||
);
|
||||
const { freeze, scrollMessageToEnd } = useKeyboardScrollToEnd({ listRef });
|
||||
const endFollowEnabledRef = useRef(true);
|
||||
endFollowEnabledRef.current = endFollowEnabled;
|
||||
const userInputRepinTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
// The list's own corrections for these inset changes drift on short
|
||||
// content (and the error compounds across toggles), so deterministically
|
||||
// re-pin the end once a toggle settles: a no-op when the resting position
|
||||
// is already right, corrective when it is not. Follow state is re-checked
|
||||
// inside the callback — the user may grab the list during the settle
|
||||
// window, and yanking them back would override a live gesture.
|
||||
const scheduleUserInputRepin = useCallback(
|
||||
(delayMs: number) => {
|
||||
if (userInputRepinTimerRef.current !== null) {
|
||||
clearTimeout(userInputRepinTimerRef.current);
|
||||
}
|
||||
userInputRepinTimerRef.current = setTimeout(() => {
|
||||
userInputRepinTimerRef.current = null;
|
||||
if (!endFollowEnabledRef.current) {
|
||||
return;
|
||||
}
|
||||
void scrollMessageToEnd({ animated: false, closeKeyboard: false }).catch(() => {
|
||||
freeze.set(false);
|
||||
});
|
||||
}, delayMs);
|
||||
},
|
||||
[freeze, scrollMessageToEnd],
|
||||
);
|
||||
useEffect(
|
||||
() => () => {
|
||||
if (userInputRepinTimerRef.current !== null) {
|
||||
clearTimeout(userInputRepinTimerRef.current);
|
||||
}
|
||||
},
|
||||
[],
|
||||
);
|
||||
const handleToggleUserInputCollapsed = useCallback(() => {
|
||||
if (activeUserInputRequestId === null) {
|
||||
return;
|
||||
}
|
||||
if (userInputCollapsed) {
|
||||
// Expanding: card and feed glide start NOW, on the UI thread.
|
||||
userInputCardProgress.value = withTiming(1, USER_INPUT_TOGGLE_TIMING);
|
||||
userInputInsetProgress.value = withTiming(1, USER_INPUT_TOGGLE_TIMING);
|
||||
setCollapsedUserInputRequestId(null);
|
||||
scheduleUserInputRepin(USER_INPUT_TOGGLE_DURATION_MS + 50);
|
||||
} else {
|
||||
// Collapsing hides the custom-answer inputs; release the keyboard with
|
||||
// them instead of leaving it up over a dead responder.
|
||||
Keyboard.dismiss();
|
||||
userInputCardProgress.value = withTiming(0, USER_INPUT_TOGGLE_TIMING);
|
||||
// Instant: the sinking card still covers the strip being revealed, and
|
||||
// animating the inset downward is what drifted the short-content end
|
||||
// anchor.
|
||||
userInputInsetProgress.value = 0;
|
||||
setCollapsedUserInputRequestId(activeUserInputRequestId);
|
||||
scheduleUserInputRepin(60);
|
||||
}
|
||||
}, [
|
||||
activeUserInputRequestId,
|
||||
scheduleUserInputRepin,
|
||||
userInputCardProgress,
|
||||
userInputCollapsed,
|
||||
userInputInsetProgress,
|
||||
]);
|
||||
useEffect(() => {
|
||||
// A new request always arrives expanded.
|
||||
userInputCardProgress.value = 1;
|
||||
userInputInsetProgress.value = 1;
|
||||
}, [activeUserInputRequestId, userInputCardProgress, userInputInsetProgress]);
|
||||
const showContent = props.showContent ?? true;
|
||||
const layoutVariant = props.layoutVariant ?? "compact";
|
||||
const isSplitLayout = layoutVariant === "split";
|
||||
@@ -459,7 +241,6 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
|
||||
useEffect(() => {
|
||||
setAnchorMessageId(null);
|
||||
lastScrolledAnchorMessageIdRef.current = null;
|
||||
setEndFollowEnabled(true);
|
||||
freeze.set(false);
|
||||
}, [freeze, selectedThreadKey]);
|
||||
|
||||
@@ -531,16 +312,6 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
|
||||
composerEditorRef.current?.blur();
|
||||
}, []);
|
||||
|
||||
const handleScrollToEnd = useCallback(() => {
|
||||
void Haptics.selectionAsync();
|
||||
void scrollMessageToEnd({ animated: true, closeKeyboard: false }).catch(() => {
|
||||
freeze.set(false);
|
||||
});
|
||||
}, [freeze, scrollMessageToEnd]);
|
||||
|
||||
const showScrollToEndButton = contentPresentationKind === "ready" && !endFollowEnabled;
|
||||
const isDarkMode = useColorScheme() === "dark";
|
||||
|
||||
const handleFeedTouchStart = useCallback((event: GestureResponderEvent) => {
|
||||
feedTouchStartRef.current = {
|
||||
pageX: event.nativeEvent.pageX,
|
||||
@@ -594,14 +365,13 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
|
||||
listRef={listRef}
|
||||
freeze={freeze}
|
||||
anchorMessageId={anchorMessageId}
|
||||
contentInsetEndAdjustment={combinedContentInsetEndAdjustment}
|
||||
contentInsetEndAdjustment={contentInsetEndAdjustment}
|
||||
contentTopInset={0}
|
||||
contentBottomInset={estimatedOverlayHeight}
|
||||
contentMaxWidth={contentMaxWidth}
|
||||
layoutVariant={layoutVariant}
|
||||
usesAutomaticContentInsets={props.usesAutomaticContentInsets}
|
||||
onHeaderMaterialVisibilityChange={props.onHeaderMaterialVisibilityChange}
|
||||
onEndFollowEnabledChange={setEndFollowEnabled}
|
||||
skills={selectedProviderSkills}
|
||||
loadEarlier={props.loadEarlier ?? null}
|
||||
/>
|
||||
@@ -613,10 +383,6 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
|
||||
{/* Floating composer — sticks to keyboard via KeyboardStickyView */}
|
||||
{showContent ? (
|
||||
<KeyboardStickyView
|
||||
// The animated keyboard height can remain stale after a dismissed
|
||||
// IME on both platforms. Visibility is the authoritative closed
|
||||
// state, so disable the translation rather than stranding the pill.
|
||||
enabled={isKeyboardVisible && !keyboardStateSuspect}
|
||||
style={{ position: "absolute", bottom: 0, left: 0, right: 0 }}
|
||||
offset={{ closed: 0, opened: 0 }}
|
||||
>
|
||||
@@ -624,60 +390,10 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
|
||||
list's bottom inset, so any padding above the pill/composer
|
||||
pushes the resting content floor up by the same amount. */}
|
||||
<View ref={composerOverlayRef} onLayout={onComposerLayout} className="w-full">
|
||||
{showScrollToEndButton ? (
|
||||
<Animated.View
|
||||
pointerEvents="box-none"
|
||||
className="absolute -top-11 left-0 right-0 z-20 items-center"
|
||||
entering={FadeInDown.duration(160)}
|
||||
exiting={FadeOut.duration(100)}
|
||||
>
|
||||
{isLiquidGlassSupported ? (
|
||||
<LiquidGlassView
|
||||
colorScheme={isDarkMode ? "dark" : "light"}
|
||||
effect="regular"
|
||||
interactive
|
||||
// Interactive glass can render larger than the requested
|
||||
// box (minimum touch size), so center the pill instead of
|
||||
// relying on it filling the glass exactly.
|
||||
style={{
|
||||
alignItems: "center",
|
||||
borderRadius: 18,
|
||||
height: 36,
|
||||
justifyContent: "center",
|
||||
overflow: "hidden",
|
||||
width: 36,
|
||||
}}
|
||||
>
|
||||
<ControlPill
|
||||
accessibilityLabel="Scroll to end"
|
||||
activateOnPressIn
|
||||
className="h-9 w-9 bg-transparent"
|
||||
icon={{ ios: "chevron.down", android: "keyboard_arrow_down" }}
|
||||
onPress={handleScrollToEnd}
|
||||
/>
|
||||
</LiquidGlassView>
|
||||
) : (
|
||||
<ControlPill
|
||||
accessibilityLabel="Scroll to end"
|
||||
activateOnPressIn
|
||||
className="h-9 w-9 border border-border bg-card shadow-md shadow-black/10"
|
||||
icon={{ ios: "chevron.down", android: "keyboard_arrow_down" }}
|
||||
onPress={handleScrollToEnd}
|
||||
/>
|
||||
)}
|
||||
</Animated.View>
|
||||
) : null}
|
||||
<View className="w-full self-center" style={{ maxWidth: contentMaxWidth }}>
|
||||
{props.activePendingApproval || props.activePendingUserInput ? (
|
||||
<Animated.View
|
||||
className="shrink-0 gap-3 px-4 pb-3"
|
||||
// The questionnaire replaces the composer, so it must pad
|
||||
// the home indicator the composer normally covers.
|
||||
style={
|
||||
activeUserInputRequestId !== null
|
||||
? { paddingBottom: composerBottomInset }
|
||||
: undefined
|
||||
}
|
||||
entering={FadeInDown.duration(220)}
|
||||
exiting={FadeOut.duration(140)}
|
||||
>
|
||||
@@ -691,13 +407,6 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
|
||||
{props.activePendingUserInput ? (
|
||||
<PendingUserInputCard
|
||||
pendingUserInput={props.activePendingUserInput}
|
||||
maxHeight={pendingUserInputMaxHeight}
|
||||
collapsed={userInputCollapsed}
|
||||
onToggleCollapsed={handleToggleUserInputCollapsed}
|
||||
onStopThread={props.onStopThread}
|
||||
cardProgress={userInputCardProgress}
|
||||
cardCoverage={userInputCardCoverage}
|
||||
onInputFocusChange={handleOwnedInputFocusChange}
|
||||
drafts={props.activePendingUserInputDrafts}
|
||||
answers={props.activePendingUserInputAnswers}
|
||||
respondingUserInputId={props.respondingUserInputId}
|
||||
@@ -710,40 +419,35 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
|
||||
) : null}
|
||||
</View>
|
||||
|
||||
{/* Hidden (not unmounted) while a user-input request owns the
|
||||
composer slot, so composer drafts and editor state survive. */}
|
||||
<View style={activeUserInputRequestId !== null ? { display: "none" } : undefined}>
|
||||
<ThreadComposer
|
||||
editorRef={composerEditorRef}
|
||||
draftMessage={props.draftMessage}
|
||||
draftAttachments={props.draftAttachments}
|
||||
placeholder="Ask the repo agent, or run a command…"
|
||||
contentMaxWidth={contentMaxWidth}
|
||||
connectionState={props.connectionStateLabel}
|
||||
connectionError={props.connectionError}
|
||||
environmentLabel={props.environmentLabel}
|
||||
threadSyncPhase={threadSyncPhase}
|
||||
selectedThread={props.selectedThread}
|
||||
serverConfig={props.serverConfig}
|
||||
queueCount={props.selectedThreadQueueCount}
|
||||
activeThreadBusy={props.activeThreadBusy}
|
||||
environmentId={props.environmentId}
|
||||
projectCwd={props.projectWorkspaceRoot}
|
||||
bottomInset={composerBottomInset}
|
||||
onChangeDraftMessage={props.onChangeDraftMessage}
|
||||
onPickDraftImages={props.onPickDraftImages}
|
||||
onNativePasteImages={props.onNativePasteImages}
|
||||
onRemoveDraftImage={props.onRemoveDraftImage}
|
||||
onStopThread={props.onStopThread}
|
||||
onSendMessage={handleSendMessage}
|
||||
onReconnectEnvironment={props.onReconnectEnvironment}
|
||||
onUpdateModelSelection={props.onUpdateThreadModelSelection}
|
||||
onUpdateRuntimeMode={props.onUpdateThreadRuntimeMode}
|
||||
onUpdateInteractionMode={props.onUpdateThreadInteractionMode}
|
||||
onExpandedChange={setComposerExpanded}
|
||||
onEditorFocusChange={handleOwnedInputFocusChange}
|
||||
/>
|
||||
</View>
|
||||
<ThreadComposer
|
||||
editorRef={composerEditorRef}
|
||||
draftMessage={props.draftMessage}
|
||||
draftAttachments={props.draftAttachments}
|
||||
placeholder="Ask the repo agent, or run a command…"
|
||||
contentMaxWidth={contentMaxWidth}
|
||||
connectionState={props.connectionStateLabel}
|
||||
connectionError={props.connectionError}
|
||||
environmentLabel={props.environmentLabel}
|
||||
threadSyncPhase={threadSyncPhase}
|
||||
selectedThread={props.selectedThread}
|
||||
serverConfig={props.serverConfig}
|
||||
queueCount={props.selectedThreadQueueCount}
|
||||
activeThreadBusy={props.activeThreadBusy}
|
||||
environmentId={props.environmentId}
|
||||
projectCwd={props.projectWorkspaceRoot}
|
||||
bottomInset={composerBottomInset}
|
||||
onChangeDraftMessage={props.onChangeDraftMessage}
|
||||
onPickDraftImages={props.onPickDraftImages}
|
||||
onNativePasteImages={props.onNativePasteImages}
|
||||
onRemoveDraftImage={props.onRemoveDraftImage}
|
||||
onStopThread={props.onStopThread}
|
||||
onSendMessage={handleSendMessage}
|
||||
onReconnectEnvironment={props.onReconnectEnvironment}
|
||||
onUpdateModelSelection={props.onUpdateThreadModelSelection}
|
||||
onUpdateRuntimeMode={props.onUpdateThreadRuntimeMode}
|
||||
onUpdateInteractionMode={props.onUpdateThreadInteractionMode}
|
||||
onExpandedChange={setComposerExpanded}
|
||||
/>
|
||||
</View>
|
||||
</KeyboardStickyView>
|
||||
) : null}
|
||||
|
||||
@@ -48,7 +48,6 @@ import { useSafeAreaInsets } from "react-native-safe-area-context";
|
||||
import Animated, { FadeIn, FadeInUp, type SharedValue } from "react-native-reanimated";
|
||||
import { useThemeColor } from "../../lib/useThemeColor";
|
||||
import { useFontFamily } from "../../lib/useFontFamily";
|
||||
import { scopedThreadKey } from "../../lib/scopedEntities";
|
||||
import { copyTextWithHaptic } from "../../lib/copyTextWithHaptic";
|
||||
import { hasWideMarkdownBlock } from "../../lib/wideMarkdownBlocks";
|
||||
import {
|
||||
@@ -90,10 +89,6 @@ import {
|
||||
type ThreadFeedLatestTurn,
|
||||
} from "../../lib/threadActivity";
|
||||
import type { ThreadContentPresentation } from "./threadContentPresentation";
|
||||
import {
|
||||
resolveThreadFeedLiveFollow,
|
||||
type ThreadFeedLiveFollowEvent,
|
||||
} from "./thread-feed-live-follow";
|
||||
import {
|
||||
collapsedWorkLogHeight,
|
||||
ThreadWorkGroupToggle,
|
||||
@@ -104,10 +99,6 @@ import { useMarkdownCodeHighlight } from "./markdownCodeHighlightState";
|
||||
import { useAssetUrl } from "../../state/assets";
|
||||
import { resolveWorkspaceRelativeFilePath } from "../files/filePath";
|
||||
|
||||
const WIDE_MARKDOWN_BLOCK_OPTIONS = {
|
||||
includeOrderedLists: Platform.OS === "android",
|
||||
} as const;
|
||||
|
||||
const MESSAGE_TIME_FORMATTER = new Intl.DateTimeFormat(undefined, {
|
||||
hour: "numeric",
|
||||
minute: "2-digit",
|
||||
@@ -158,7 +149,6 @@ export interface ThreadFeedProps {
|
||||
readonly layoutVariant?: LayoutVariant;
|
||||
readonly usesAutomaticContentInsets?: boolean;
|
||||
readonly onHeaderMaterialVisibilityChange?: (visible: boolean) => void;
|
||||
readonly onEndFollowEnabledChange?: (enabled: boolean) => void;
|
||||
readonly skills?: ReadonlyArray<SelectableMarkdownSkill>;
|
||||
/** Non-null when older turns exist beyond the loaded window. */
|
||||
readonly loadEarlier?: {
|
||||
@@ -892,7 +882,7 @@ function renderFeedEntry(
|
||||
// children during the unclamped pass and never moves them once the width
|
||||
// is clamped, so the paragraphs around the block end up drawn on top of
|
||||
// each other. Pinning the width removes that pass.
|
||||
const hasWideBlock = hasWideMarkdownBlock(message.text, WIDE_MARKDOWN_BLOCK_OPTIONS);
|
||||
const hasWideBlock = hasWideMarkdownBlock(message.text);
|
||||
const assistantTurnStillInProgress =
|
||||
message.role === "assistant" &&
|
||||
props.unsettledTurnId !== null &&
|
||||
@@ -1334,7 +1324,6 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
const disclosureAnchorKeyRef = useRef<string | null>(null);
|
||||
const headerMaterialVisibleRef = useRef(false);
|
||||
const previousLatestTurnRef = useRef(props.latestTurn);
|
||||
const userScrollSettleTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
const { width: windowWidth } = useWindowDimensions();
|
||||
const { appearance } = useAppearancePreferences();
|
||||
const [viewportWidth, setViewportWidth] = useState(() =>
|
||||
@@ -1353,23 +1342,13 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
// momentum; only motion inside a session can break follow, so MVCP
|
||||
// compensations and programmatic scrolls never strand a follower.
|
||||
const userScrollSessionRef = useRef(false);
|
||||
const setEndFollow = useCallback(
|
||||
(enabled: boolean) => {
|
||||
if (endFollowEnabledRef.current === enabled) {
|
||||
return;
|
||||
}
|
||||
endFollowEnabledRef.current = enabled;
|
||||
setEndFollowEnabled(enabled);
|
||||
props.onEndFollowEnabledChange?.(enabled);
|
||||
},
|
||||
[props.onEndFollowEnabledChange],
|
||||
);
|
||||
const transitionEndFollow = useCallback(
|
||||
(event: ThreadFeedLiveFollowEvent) => {
|
||||
setEndFollow(resolveThreadFeedLiveFollow(endFollowEnabledRef.current, event));
|
||||
},
|
||||
[setEndFollow],
|
||||
);
|
||||
const setEndFollow = useCallback((enabled: boolean) => {
|
||||
if (endFollowEnabledRef.current === enabled) {
|
||||
return;
|
||||
}
|
||||
endFollowEnabledRef.current = enabled;
|
||||
setEndFollowEnabled(enabled);
|
||||
}, []);
|
||||
const [interactionState, setInteractionState] = useState<{
|
||||
readonly copiedRowId: string | null;
|
||||
readonly expandedWorkGroups: Record<string, boolean>;
|
||||
@@ -1481,72 +1460,40 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
// UIKit's adjustedContentInset, so topContentInset is 0 here). Add the
|
||||
// header height back or the material toggles a full header too late.
|
||||
reportHeaderMaterialVisibility(event.nativeEvent.contentOffset.y + anchorTopInset > 6);
|
||||
// LegendList recomputes its inset-aware end distance before invoking
|
||||
// this handler, so getState() is current. Only the actual end re-arms
|
||||
// follow: its broader maintain-scroll threshold is large enough for a
|
||||
// streaming chunk to pull a user back before their upward drag escapes.
|
||||
// A live user-scroll session still wins even if the first scroll event
|
||||
// remains inside LegendList's at-end tolerance.
|
||||
// Latch bookkeeping. LegendList recomputes its inset-aware end distance
|
||||
// before invoking this handler, so getState() is current. Returning to
|
||||
// the end re-arms follow no matter who scrolled (the user, or our own
|
||||
// scroll-to-end); moving away breaks it only during a user-initiated
|
||||
// scroll session, so MVCP compensations and programmatic repositioning
|
||||
// can never strand a follower.
|
||||
const listState = props.listRef.current?.getState();
|
||||
if (listState) {
|
||||
transitionEndFollow({
|
||||
type: "scroll",
|
||||
isAtEnd: listState.isAtEnd,
|
||||
userScrollSessionActive: userScrollSessionRef.current,
|
||||
});
|
||||
if (listState.isWithinMaintainScrollAtEndThreshold) {
|
||||
setEndFollow(true);
|
||||
} else if (userScrollSessionRef.current) {
|
||||
setEndFollow(false);
|
||||
}
|
||||
}
|
||||
},
|
||||
[reportHeaderMaterialVisibility, anchorTopInset, props.listRef, transitionEndFollow],
|
||||
[reportHeaderMaterialVisibility, anchorTopInset, props.listRef, setEndFollow],
|
||||
);
|
||||
const clearUserScrollSettle = useCallback(() => {
|
||||
if (userScrollSettleTimerRef.current !== null) {
|
||||
clearTimeout(userScrollSettleTimerRef.current);
|
||||
userScrollSettleTimerRef.current = null;
|
||||
const handleScrollBeginDrag = useCallback(() => {
|
||||
userScrollSessionRef.current = true;
|
||||
}, []);
|
||||
// The session must survive past finger-lift so momentum that carries the
|
||||
// user away from the end still breaks follow; a drag released with no
|
||||
// momentum ends its session at the release itself, otherwise at momentum
|
||||
// end. Leaving a session open would let a later animated maintain-scroll
|
||||
// read as user motion and break follow spuriously.
|
||||
const handleScrollEndDrag = useCallback((event: NativeSyntheticEvent<NativeScrollEvent>) => {
|
||||
const velocity = event.nativeEvent.velocity?.y ?? 0;
|
||||
if (Math.abs(velocity) < 0.05) {
|
||||
userScrollSessionRef.current = false;
|
||||
}
|
||||
}, []);
|
||||
const handleScrollBeginDrag = useCallback(() => {
|
||||
clearUserScrollSettle();
|
||||
userScrollSessionRef.current = true;
|
||||
// Pause before the first scroll event. Otherwise a stream update can run
|
||||
// maintainScrollAtEnd between touch-down and the drag leaving its threshold.
|
||||
transitionEndFollow({ type: "user-scroll-begin" });
|
||||
}, [clearUserScrollSettle, transitionEndFollow]);
|
||||
const finishUserScroll = useCallback(
|
||||
(releaseIsAtEnd?: boolean) => {
|
||||
clearUserScrollSettle();
|
||||
const userScrollSessionActive = userScrollSessionRef.current;
|
||||
userScrollSessionRef.current = false;
|
||||
transitionEndFollow({
|
||||
type: "user-scroll-end",
|
||||
// With no momentum, preserve the finger-release position. Streaming
|
||||
// growth during the native momentum-detection window must not turn a
|
||||
// release at the live edge into an opt-out from follow.
|
||||
isAtEnd: releaseIsAtEnd ?? props.listRef.current?.getState().isAtEnd ?? false,
|
||||
userScrollSessionActive,
|
||||
});
|
||||
},
|
||||
[clearUserScrollSettle, props.listRef, transitionEndFollow],
|
||||
);
|
||||
// Finger-lift velocity is not a reliable momentum signal: a gentle fling
|
||||
// can report zero and still decelerate. Give native momentum a short window
|
||||
// to announce itself; if it does, onMomentumScrollBegin cancels this fallback
|
||||
// and the session survives until the settled momentum-end position. This
|
||||
// mirrors the native-event handoff used by the home thread list's scroll gate.
|
||||
const handleScrollEndDrag = useCallback(() => {
|
||||
clearUserScrollSettle();
|
||||
const releaseIsAtEnd = props.listRef.current?.getState().isAtEnd ?? false;
|
||||
userScrollSettleTimerRef.current = setTimeout(() => finishUserScroll(releaseIsAtEnd), 160);
|
||||
}, [clearUserScrollSettle, finishUserScroll, props.listRef]);
|
||||
const handleMomentumScrollBegin = useCallback(() => {
|
||||
if (userScrollSessionRef.current) {
|
||||
clearUserScrollSettle();
|
||||
}
|
||||
}, [clearUserScrollSettle]);
|
||||
const handleMomentumScrollEnd = useCallback(() => {
|
||||
finishUserScroll();
|
||||
}, [finishUserScroll]);
|
||||
|
||||
useEffect(() => clearUserScrollSettle, [clearUserScrollSettle]);
|
||||
userScrollSessionRef.current = false;
|
||||
}, []);
|
||||
|
||||
const handleViewportLayout = useCallback((event: LayoutChangeEvent) => {
|
||||
const nextWidth = Math.round(event.nativeEvent.layout.width);
|
||||
@@ -1555,30 +1502,23 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
setViewportHeight((current) => (Math.abs(current - nextHeight) > 1 ? nextHeight : current));
|
||||
}, []);
|
||||
|
||||
// Thread identity is env-scoped: two environments can hold the same
|
||||
// ThreadId, and keying resets (or the list mount) on the bare id would
|
||||
// carry stale scroll/follow state across an environment switch.
|
||||
const feedThreadKey = scopedThreadKey(props.environmentId, props.threadId);
|
||||
|
||||
useEffect(() => {
|
||||
reportHeaderMaterialVisibility(false);
|
||||
}, [feedThreadKey, reportHeaderMaterialVisibility]);
|
||||
}, [props.threadId, reportHeaderMaterialVisibility]);
|
||||
|
||||
// A thread switch opens pinned to the end; a send explicitly returns to the
|
||||
// live edge (ThreadDetailScreen scrolls the new message into place). Both
|
||||
// re-arm follow regardless of where the user had scrolled before.
|
||||
useEffect(() => {
|
||||
clearUserScrollSettle();
|
||||
userScrollSessionRef.current = false;
|
||||
transitionEndFollow({ type: "reset" });
|
||||
}, [clearUserScrollSettle, feedThreadKey, transitionEndFollow]);
|
||||
setEndFollow(true);
|
||||
}, [props.threadId, setEndFollow]);
|
||||
useEffect(() => {
|
||||
if (props.anchorMessageId !== null) {
|
||||
clearUserScrollSettle();
|
||||
userScrollSessionRef.current = false;
|
||||
transitionEndFollow({ type: "reset" });
|
||||
setEndFollow(true);
|
||||
}
|
||||
}, [clearUserScrollSettle, props.anchorMessageId, transitionEndFollow]);
|
||||
}, [props.anchorMessageId, setEndFollow]);
|
||||
|
||||
const expandedWorkGroupIds = useMemo(() => {
|
||||
const ids = new Set<string>();
|
||||
@@ -1614,7 +1554,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
// initial scroll-to-end computes with a zero end inset and rests one
|
||||
// composer-height short of the end. Layout effect: it must land before the
|
||||
// list's first positioning tick or the one-shot initial scroll misses it.
|
||||
const listMountKey = `${feedThreadKey}:${props.feed.length === 0 ? "empty" : "filled"}`;
|
||||
const listMountKey = `${props.threadId}:${props.feed.length === 0 ? "empty" : "filled"}`;
|
||||
useLayoutEffect(() => {
|
||||
const bottom = props.contentInsetEndAdjustment.value;
|
||||
if (bottom > 0) {
|
||||
@@ -1981,7 +1921,6 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
onScroll={handleScroll}
|
||||
onScrollBeginDrag={handleScrollBeginDrag}
|
||||
onScrollEndDrag={handleScrollEndDrag}
|
||||
onMomentumScrollBegin={handleMomentumScrollBegin}
|
||||
onMomentumScrollEnd={handleMomentumScrollEnd}
|
||||
scrollEventThrottle={16}
|
||||
ListHeaderComponent={
|
||||
|
||||
@@ -211,7 +211,6 @@ function ThreadNavigationSidebarPane(
|
||||
pinThread,
|
||||
unpinThread,
|
||||
movePinnedThread,
|
||||
regenerateThreadTitle,
|
||||
} = useThreadListActions();
|
||||
const threadListV2Enabled = useThreadListV2Enabled();
|
||||
const pendingTasks = usePendingNewTasks();
|
||||
@@ -506,15 +505,6 @@ function ThreadNavigationSidebarPane(
|
||||
}
|
||||
return supported;
|
||||
}, [serverConfigs]);
|
||||
const titleRegenerationEnvironmentIds = useMemo(() => {
|
||||
const supported = new Set<EnvironmentId>();
|
||||
for (const [environmentId, config] of serverConfigs) {
|
||||
if (config.environment.capabilities.threadTitleRegeneration === true) {
|
||||
supported.add(environmentId);
|
||||
}
|
||||
}
|
||||
return supported;
|
||||
}, [serverConfigs]);
|
||||
// Canonical arranged pinned order for Move up/down flags — computed from
|
||||
// all shells so search/scope filtering never disables a valid move.
|
||||
const arrangedPinnedKeys = useMemo(() => {
|
||||
@@ -960,8 +950,6 @@ function ThreadNavigationSidebarPane(
|
||||
onSelectThread={handleSelectThread}
|
||||
onDeleteThread={confirmDeleteThread}
|
||||
onArchiveThread={archiveThread}
|
||||
onRegenerateThreadTitle={regenerateThreadTitle}
|
||||
titleRegenerationSupported={titleRegenerationEnvironmentIds.has(thread.environmentId)}
|
||||
settlementSupported={settlementEnvironmentIds.has(thread.environmentId)}
|
||||
onSettleThread={settleThread}
|
||||
snoozeSupported={snoozeEnvironmentIds.has(thread.environmentId)}
|
||||
@@ -1079,8 +1067,6 @@ function ThreadNavigationSidebarPane(
|
||||
fullSwipeWidth={props.width - 20}
|
||||
onArchiveThread={archiveThread}
|
||||
onDeleteThread={confirmDeleteThread}
|
||||
onRegenerateThreadTitle={regenerateThreadTitle}
|
||||
titleRegenerationSupported={titleRegenerationEnvironmentIds.has(thread.environmentId)}
|
||||
onSelectThread={handleSelectThread}
|
||||
onSwipeableClose={handleSwipeableClose}
|
||||
onSwipeableWillOpen={handleSwipeableWillOpen}
|
||||
@@ -1117,7 +1103,6 @@ function ThreadNavigationSidebarPane(
|
||||
projectByKey,
|
||||
projectCwdByKey,
|
||||
projectTitleByProjectKey,
|
||||
regenerateThreadTitle,
|
||||
props.onNewThreadInProject,
|
||||
props.searchQuery,
|
||||
props.selectedThreadKey,
|
||||
@@ -1125,7 +1110,6 @@ function ThreadNavigationSidebarPane(
|
||||
savedConnectionsById,
|
||||
serverConfigs,
|
||||
threadSearchMatchByKey,
|
||||
titleRegenerationEnvironmentIds,
|
||||
settleThread,
|
||||
settlementEnvironmentIds,
|
||||
showMoreSettled,
|
||||
|
||||
@@ -56,6 +56,8 @@ import {
|
||||
useThreadGitRightHeaderItems,
|
||||
} from "./ThreadGitControls";
|
||||
import { GitOverviewSheet } from "./git/GitOverviewSheet";
|
||||
import { appAtomRegistry } from "../../state/atom-registry";
|
||||
import { environmentServerConfigsAtom } from "../../state/server";
|
||||
import { useAtomCommand } from "../../state/use-atom-command";
|
||||
import { useSelectedThreadGitActions } from "../../state/use-selected-thread-git-actions";
|
||||
import { useSelectedThreadGitState } from "../../state/use-selected-thread-git-state";
|
||||
@@ -214,6 +216,28 @@ function ThreadRouteContent(
|
||||
const gitActions = useSelectedThreadGitActions();
|
||||
const requests = useSelectedThreadRequests();
|
||||
const interruptThreadTurn = useAtomCommand(threadEnvironment.interruptTurn, "thread interrupt");
|
||||
const visitThreadMutation = useAtomCommand(threadEnvironment.visit, { reportFailure: false });
|
||||
// Server-synced "seen it" acknowledgement, mirroring web's ChatView: having
|
||||
// the finished thread open stamps a visit at the turn's completedAt so the
|
||||
// unread cue clears on every device, not just this one. Guarded on the
|
||||
// shell's synced value so the echo of our own visit does not re-dispatch;
|
||||
// the decider is monotonic, so a raced older visit is a server-side no-op.
|
||||
// Version skew: never send thread.visit to a server that predates it.
|
||||
useEffect(() => {
|
||||
if (selectedThread === null) return;
|
||||
const supportsThreadVisits =
|
||||
appAtomRegistry.get(environmentServerConfigsAtom).get(selectedThread.environmentId)
|
||||
?.environment.capabilities.threadVisits === true;
|
||||
if (!supportsThreadVisits) return;
|
||||
const completedAt = selectedThread.latestTurn?.completedAt;
|
||||
if (!completedAt) return;
|
||||
const syncedVisitedAt = selectedThread.lastVisitedAt;
|
||||
if (syncedVisitedAt != null && Date.parse(syncedVisitedAt) >= Date.parse(completedAt)) return;
|
||||
void visitThreadMutation({
|
||||
environmentId: selectedThread.environmentId,
|
||||
input: { threadId: selectedThread.id, visitedAt: completedAt },
|
||||
});
|
||||
}, [selectedThread, visitThreadMutation]);
|
||||
const navigation = useNavigation();
|
||||
const params = props.route.params;
|
||||
const environmentIdRaw = firstRouteParam(params.environmentId);
|
||||
|
||||
@@ -30,7 +30,6 @@ import { cn } from "../../lib/cn";
|
||||
import type { ModelOption, ProviderGroup } from "../../lib/modelOptions";
|
||||
import { applyProviderOptionSelection, providerOptionValueLabels } from "../../lib/providerOptions";
|
||||
import { useThemeColor } from "../../lib/useThemeColor";
|
||||
import { RUNTIME_MODE_CHOICES, selectableChoices } from "./thread-settings-menu";
|
||||
import { pendingModelAfterPress } from "./thread-settings-sheet-state";
|
||||
import type { ThreadSettingsSheetCloseReason } from "./use-thread-settings-sheet-presentation";
|
||||
|
||||
@@ -41,6 +40,26 @@ import type { ThreadSettingsSheetCloseReason } from "./use-thread-settings-sheet
|
||||
*/
|
||||
const PRIMARY_PROVIDER_DRIVERS: ReadonlySet<string> = new Set(["claudeAgent", "codex"]);
|
||||
|
||||
/**
|
||||
* Desktop-oriented effort keywords that don't belong in the phone picker.
|
||||
* Prompt-injected values (ultrathink and friends) are filtered from the
|
||||
* descriptor metadata; ultracode is a real option but a workflow trigger, not
|
||||
* a reasoning level. A value set elsewhere still displays, it just isn't
|
||||
* offered.
|
||||
*/
|
||||
const HIDDEN_EFFORT_OPTION_IDS: ReadonlySet<string> = new Set(["ultracode"]);
|
||||
|
||||
const RUNTIME_MODE_CHOICES: ReadonlyArray<{
|
||||
readonly mode: RuntimeMode;
|
||||
readonly label: string;
|
||||
readonly shortLabel: string;
|
||||
}> = [
|
||||
{ mode: "approval-required", label: "Approve actions", shortLabel: "Approve" },
|
||||
{ mode: "auto-accept-edits", label: "Auto-accept edits", shortLabel: "Edits" },
|
||||
{ mode: "auto", label: "Auto", shortLabel: "Auto" },
|
||||
{ mode: "full-access", label: "Full access", shortLabel: "Full" },
|
||||
];
|
||||
|
||||
/**
|
||||
* Compact "Fable 5 · Max · Auto" style summary for the composer trigger pill,
|
||||
* covering model, provider options, runtime mode, and plan mode in one label.
|
||||
@@ -60,6 +79,13 @@ export function threadSettingsSummaryLabel(input: {
|
||||
].join(" · ");
|
||||
}
|
||||
|
||||
function selectableChoices(descriptor: Extract<ProviderOptionDescriptor, { type: "select" }>) {
|
||||
const injected = new Set(descriptor.promptInjectedValues ?? []);
|
||||
return descriptor.options.filter(
|
||||
(option) => !injected.has(option.id) && !HIDDEN_EFFORT_OPTION_IDS.has(option.id),
|
||||
);
|
||||
}
|
||||
|
||||
function ModelRow(props: {
|
||||
readonly option: ModelOption;
|
||||
readonly selected: boolean;
|
||||
|
||||
@@ -1,38 +0,0 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { derivePendingUserInputMaxHeight } from "./pendingUserInputLayout";
|
||||
|
||||
describe("derivePendingUserInputMaxHeight", () => {
|
||||
it("caps a tall portrait viewport", () => {
|
||||
expect(
|
||||
derivePendingUserInputMaxHeight({
|
||||
windowHeight: 932,
|
||||
keyboardHeight: 0,
|
||||
navigationHeaderHeight: 103,
|
||||
composerOverlapHeight: 94,
|
||||
}),
|
||||
).toBe(560);
|
||||
});
|
||||
|
||||
it("subtracts the keyboard while editing a custom answer", () => {
|
||||
expect(
|
||||
derivePendingUserInputMaxHeight({
|
||||
windowHeight: 932,
|
||||
keyboardHeight: 336,
|
||||
navigationHeaderHeight: 103,
|
||||
composerOverlapHeight: 94,
|
||||
}),
|
||||
).toBe(387);
|
||||
});
|
||||
|
||||
it("keeps the fixed action area usable in a short keyboard-open viewport", () => {
|
||||
expect(
|
||||
derivePendingUserInputMaxHeight({
|
||||
windowHeight: 375,
|
||||
keyboardHeight: 240,
|
||||
navigationHeaderHeight: 44,
|
||||
composerOverlapHeight: 94,
|
||||
}),
|
||||
).toBe(160);
|
||||
});
|
||||
});
|
||||
@@ -1,37 +0,0 @@
|
||||
const PENDING_USER_INPUT_MAX_HEIGHT = 560;
|
||||
const PENDING_USER_INPUT_MIN_HEIGHT = 160;
|
||||
const PENDING_USER_INPUT_VERTICAL_GAP = 12;
|
||||
|
||||
/**
|
||||
* Reserve for a portrait iPhone keyboard with the QuickType bar until a real
|
||||
* height has been observed. Overestimating only costs card height; an
|
||||
* underestimate would let the card overshoot on the first keyboard open.
|
||||
*/
|
||||
export const ESTIMATED_KEYBOARD_HEIGHT = 336;
|
||||
|
||||
/**
|
||||
* One clock for the questionnaire expand/collapse choreography: the card's
|
||||
* enter/exit and the feed-inset glide must share it or they visibly drift.
|
||||
* Sized for the near-full-height slide (the card travels its own height),
|
||||
* in the same class as the iOS keyboard's ~250ms.
|
||||
*/
|
||||
export const USER_INPUT_TOGGLE_DURATION_MS = 220;
|
||||
|
||||
export function derivePendingUserInputMaxHeight(input: {
|
||||
readonly windowHeight: number;
|
||||
readonly keyboardHeight: number;
|
||||
readonly navigationHeaderHeight: number;
|
||||
readonly composerOverlapHeight: number;
|
||||
}): number {
|
||||
const availableHeight =
|
||||
input.windowHeight -
|
||||
Math.max(0, input.keyboardHeight) -
|
||||
Math.max(0, input.navigationHeaderHeight) -
|
||||
Math.max(0, input.composerOverlapHeight) -
|
||||
PENDING_USER_INPUT_VERTICAL_GAP;
|
||||
|
||||
return Math.min(
|
||||
PENDING_USER_INPUT_MAX_HEIGHT,
|
||||
Math.max(PENDING_USER_INPUT_MIN_HEIGHT, availableHeight),
|
||||
);
|
||||
}
|
||||
@@ -1,70 +0,0 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { resolveThreadFeedLiveFollow } from "./thread-feed-live-follow";
|
||||
|
||||
describe("resolveThreadFeedLiveFollow", () => {
|
||||
it("pauses immediately when the user starts scrolling", () => {
|
||||
expect(resolveThreadFeedLiveFollow(true, { type: "user-scroll-begin" })).toBe(false);
|
||||
});
|
||||
|
||||
it("stays paused away from the actual end", () => {
|
||||
expect(
|
||||
resolveThreadFeedLiveFollow(false, {
|
||||
type: "scroll",
|
||||
isAtEnd: false,
|
||||
userScrollSessionActive: true,
|
||||
}),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("does not mistake programmatic layout compensation for a user scroll", () => {
|
||||
expect(
|
||||
resolveThreadFeedLiveFollow(true, {
|
||||
type: "scroll",
|
||||
isAtEnd: false,
|
||||
userScrollSessionActive: false,
|
||||
}),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("does not re-arm at the end while a user scroll session is active", () => {
|
||||
expect(
|
||||
resolveThreadFeedLiveFollow(false, {
|
||||
type: "scroll",
|
||||
isAtEnd: true,
|
||||
userScrollSessionActive: true,
|
||||
}),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("re-arms at the actual end only after the user scroll session ends", () => {
|
||||
expect(
|
||||
resolveThreadFeedLiveFollow(false, {
|
||||
type: "user-scroll-end",
|
||||
isAtEnd: true,
|
||||
userScrollSessionActive: true,
|
||||
}),
|
||||
).toBe(true);
|
||||
expect(
|
||||
resolveThreadFeedLiveFollow(false, {
|
||||
type: "user-scroll-end",
|
||||
isAtEnd: false,
|
||||
userScrollSessionActive: true,
|
||||
}),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("ignores momentum-end events from programmatic scrolling", () => {
|
||||
expect(
|
||||
resolveThreadFeedLiveFollow(true, {
|
||||
type: "user-scroll-end",
|
||||
isAtEnd: false,
|
||||
userScrollSessionActive: false,
|
||||
}),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("re-arms after an explicit reset", () => {
|
||||
expect(resolveThreadFeedLiveFollow(false, { type: "reset" })).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -1,35 +0,0 @@
|
||||
export type ThreadFeedLiveFollowEvent =
|
||||
| { readonly type: "reset" }
|
||||
| { readonly type: "user-scroll-begin" }
|
||||
| {
|
||||
readonly type: "user-scroll-end";
|
||||
readonly isAtEnd: boolean;
|
||||
readonly userScrollSessionActive: boolean;
|
||||
}
|
||||
| {
|
||||
readonly type: "scroll";
|
||||
readonly isAtEnd: boolean;
|
||||
readonly userScrollSessionActive: boolean;
|
||||
};
|
||||
|
||||
export function resolveThreadFeedLiveFollow(
|
||||
current: boolean,
|
||||
event: ThreadFeedLiveFollowEvent,
|
||||
): boolean {
|
||||
switch (event.type) {
|
||||
case "reset":
|
||||
return true;
|
||||
case "user-scroll-begin":
|
||||
return false;
|
||||
case "user-scroll-end":
|
||||
return event.userScrollSessionActive ? event.isAtEnd : current;
|
||||
case "scroll":
|
||||
if (event.userScrollSessionActive) {
|
||||
return false;
|
||||
}
|
||||
if (event.isAtEnd) {
|
||||
return true;
|
||||
}
|
||||
return current;
|
||||
}
|
||||
}
|
||||
@@ -22,7 +22,6 @@ import type { PendingNewTask } from "../../state/use-pending-new-tasks";
|
||||
import { useThreadPr, type ThreadPr } from "../../state/use-thread-pr";
|
||||
import type { HomeGroupDisplayAction } from "../home/homeListItems";
|
||||
import { ThreadSwipeable } from "../home/thread-swipe-actions";
|
||||
import { buildThreadTitleRegenerationMenuItems } from "./thread-title-regeneration-menu";
|
||||
import { resolveThreadStatus } from "./threadPresentation";
|
||||
import { ThreadSearchMatchExcerpt } from "./thread-search-match";
|
||||
|
||||
@@ -431,8 +430,6 @@ export const ThreadListRow = memo(function ThreadListRow(props: {
|
||||
readonly onSelectThread: (thread: EnvironmentThreadShell) => void;
|
||||
readonly onArchiveThread: (thread: EnvironmentThreadShell) => void;
|
||||
readonly onDeleteThread: (thread: EnvironmentThreadShell) => void;
|
||||
readonly onRegenerateThreadTitle: (thread: EnvironmentThreadShell) => void;
|
||||
readonly titleRegenerationSupported: boolean;
|
||||
readonly onSwipeableWillOpen: (methods: SwipeableMethods) => void;
|
||||
readonly onSwipeableClose: (methods: SwipeableMethods) => void;
|
||||
readonly simultaneousSwipeGesture?: ComponentProps<
|
||||
@@ -454,8 +451,7 @@ export const ThreadListRow = memo(function ThreadListRow(props: {
|
||||
const pressedBackgroundColor = useThemeColor("--color-subtle");
|
||||
const selectedBackgroundColor = useThemeColor("--color-user-bubble");
|
||||
|
||||
const { thread, onSelectThread, onArchiveThread, onDeleteThread, onRegenerateThreadTitle } =
|
||||
props;
|
||||
const { thread, onSelectThread, onArchiveThread, onDeleteThread } = props;
|
||||
const status = resolveThreadStatus(thread);
|
||||
const pr = useThreadPr(thread, props.projectCwd);
|
||||
const timestamp = relativeTime(
|
||||
@@ -475,21 +471,6 @@ export const ThreadListRow = memo(function ThreadListRow(props: {
|
||||
|
||||
const handleDelete = useCallback(() => onDeleteThread(thread), [onDeleteThread, thread]);
|
||||
const handleArchive = useCallback(() => onArchiveThread(thread), [onArchiveThread, thread]);
|
||||
const handleRegenerateTitle = useCallback(
|
||||
() => onRegenerateThreadTitle(thread),
|
||||
[onRegenerateThreadTitle, thread],
|
||||
);
|
||||
const menuActions = useMemo<MenuAction[]>(
|
||||
() => [
|
||||
THREAD_ROW_MENU_ACTIONS[0]!,
|
||||
...buildThreadTitleRegenerationMenuItems({
|
||||
supported: props.titleRegenerationSupported,
|
||||
isRegenerating: thread.titleRegeneration != null,
|
||||
}),
|
||||
THREAD_ROW_MENU_ACTIONS[1]!,
|
||||
],
|
||||
[props.titleRegenerationSupported, thread.titleRegeneration],
|
||||
);
|
||||
const primaryAction = useMemo(
|
||||
() => ({
|
||||
accessibilityLabel: `Archive ${thread.title}`,
|
||||
@@ -502,10 +483,9 @@ export const ThreadListRow = memo(function ThreadListRow(props: {
|
||||
const handleMenuAction = useCallback(
|
||||
({ nativeEvent }: { readonly nativeEvent: { readonly event: string } }) => {
|
||||
if (nativeEvent.event === "archive") handleArchive();
|
||||
if (nativeEvent.event === "regenerate-title") handleRegenerateTitle();
|
||||
if (nativeEvent.event === "delete") handleDelete();
|
||||
},
|
||||
[handleArchive, handleDelete, handleRegenerateTitle],
|
||||
[handleArchive, handleDelete],
|
||||
);
|
||||
|
||||
const statusPill = effectiveStatus ? (
|
||||
@@ -694,7 +674,7 @@ export const ThreadListRow = memo(function ThreadListRow(props: {
|
||||
// ControlPillMenu injects onLongPress into the row and anchors the
|
||||
// token-styled dropdown to it; taps and swipes are untouched.
|
||||
<ControlPillMenu
|
||||
actions={menuActions}
|
||||
actions={THREAD_ROW_MENU_ACTIONS}
|
||||
onPressAction={handleMenuAction}
|
||||
shouldOpenOnLongPress
|
||||
>
|
||||
|
||||
@@ -27,7 +27,6 @@ import { useThemeColor } from "../../lib/useThemeColor";
|
||||
import type { PendingNewTask } from "../../state/use-pending-new-tasks";
|
||||
import { useThreadPr } from "../../state/use-thread-pr";
|
||||
import { ThreadSwipeable } from "../home/thread-swipe-actions";
|
||||
import { buildThreadTitleRegenerationMenuItems } from "./thread-title-regeneration-menu";
|
||||
import {
|
||||
resolveThreadListV2SnoozeMenuSelection,
|
||||
resolveThreadListV2SnoozeGateExpiryMs,
|
||||
@@ -66,8 +65,8 @@ function threadTimeLabel(thread: EnvironmentThreadShell): string {
|
||||
return relativeTime(thread.latestUserMessageAt ?? thread.updatedAt ?? thread.createdAt);
|
||||
}
|
||||
|
||||
// Menus keep lifecycle and title regeneration together. Archive keeps its
|
||||
// own surface (thread screen / settings) rather than crowding v2 rows.
|
||||
// Menus stay lifecycle-focused: settle/un-settle plus delete. Archive keeps
|
||||
// its own surface (thread screen / settings) rather than crowding the row.
|
||||
const CARD_MENU_ACTIONS: MenuAction[] = [
|
||||
{ id: "settle", title: "Settle", image: "checkmark" },
|
||||
{ id: "delete", title: "Delete", image: "trash", attributes: { destructive: true } },
|
||||
@@ -342,7 +341,6 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
|
||||
readonly fullSwipeWidth?: number;
|
||||
readonly onSelectThread: (thread: EnvironmentThreadShell) => void;
|
||||
readonly onDeleteThread: (thread: EnvironmentThreadShell) => void;
|
||||
readonly onRegenerateThreadTitle: (thread: EnvironmentThreadShell) => void;
|
||||
readonly onSettleThread: (thread: EnvironmentThreadShell) => void;
|
||||
readonly onSnoozeThread: (thread: EnvironmentThreadShell, snoozedUntil: string) => void;
|
||||
readonly onUnsnoozeThread: (thread: EnvironmentThreadShell) => void;
|
||||
@@ -357,8 +355,6 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
|
||||
readonly snoozeSupported: boolean;
|
||||
/** False on servers that predate thread.pin/unpin. */
|
||||
readonly pinningSupported: boolean;
|
||||
/** False on servers that predate thread title regeneration. */
|
||||
readonly titleRegenerationSupported: boolean;
|
||||
/** False on servers that predate thread.pin.reorder. Gates the pinned
|
||||
Move up / Move down menu items. */
|
||||
readonly pinReorderSupported?: boolean;
|
||||
@@ -388,7 +384,6 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
|
||||
variant,
|
||||
onSelectThread,
|
||||
onDeleteThread,
|
||||
onRegenerateThreadTitle,
|
||||
onSettleThread,
|
||||
onSnoozeThread,
|
||||
onUnsnoozeThread,
|
||||
@@ -422,10 +417,6 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
|
||||
const timeLabel = threadTimeLabel(thread);
|
||||
|
||||
const handleDelete = useCallback(() => onDeleteThread(thread), [onDeleteThread, thread]);
|
||||
const handleRegenerateTitle = useCallback(
|
||||
() => onRegenerateThreadTitle(thread),
|
||||
[onRegenerateThreadTitle, thread],
|
||||
);
|
||||
const handleSettle = useCallback(() => onSettleThread(thread), [onSettleThread, thread]);
|
||||
const handleSnooze = useCallback(
|
||||
(snoozedUntil: string) => onSnoozeThread(thread, snoozedUntil),
|
||||
@@ -515,14 +506,6 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
|
||||
props.pinningSupported,
|
||||
],
|
||||
);
|
||||
const titleRegenerationMenuItems = useMemo<MenuAction[]>(
|
||||
() =>
|
||||
buildThreadTitleRegenerationMenuItems({
|
||||
supported: props.titleRegenerationSupported,
|
||||
isRegenerating: thread.titleRegeneration != null,
|
||||
}),
|
||||
[props.titleRegenerationSupported, thread.titleRegeneration],
|
||||
);
|
||||
const snoozableCardMenuActions = useMemo<MenuAction[]>(
|
||||
() => [
|
||||
{ id: "settle", title: "Settle", image: "checkmark" },
|
||||
@@ -533,31 +516,13 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
|
||||
subactions: snoozePresetActions,
|
||||
},
|
||||
...pinMenuItem,
|
||||
...titleRegenerationMenuItems,
|
||||
{ id: "delete", title: "Delete", image: "trash", attributes: { destructive: true } },
|
||||
],
|
||||
[pinMenuItem, snoozePresetActions, titleRegenerationMenuItems],
|
||||
[pinMenuItem, snoozePresetActions],
|
||||
);
|
||||
const cardMenuActions = useMemo<MenuAction[]>(
|
||||
() => [
|
||||
CARD_MENU_ACTIONS[0]!,
|
||||
...pinMenuItem,
|
||||
...titleRegenerationMenuItems,
|
||||
...CARD_MENU_ACTIONS.slice(1),
|
||||
],
|
||||
[pinMenuItem, titleRegenerationMenuItems],
|
||||
);
|
||||
const slimMenuActions = useMemo<MenuAction[]>(
|
||||
() => [SLIM_MENU_ACTIONS[0]!, ...titleRegenerationMenuItems, SLIM_MENU_ACTIONS[1]!],
|
||||
[titleRegenerationMenuItems],
|
||||
);
|
||||
const snoozedMenuActions = useMemo<MenuAction[]>(
|
||||
() => [SNOOZED_MENU_ACTIONS[0]!, ...titleRegenerationMenuItems, SNOOZED_MENU_ACTIONS[1]!],
|
||||
[titleRegenerationMenuItems],
|
||||
);
|
||||
const legacyMenuActions = useMemo<MenuAction[]>(
|
||||
() => [LEGACY_MENU_ACTIONS[0]!, ...titleRegenerationMenuItems, LEGACY_MENU_ACTIONS[1]!],
|
||||
[titleRegenerationMenuItems],
|
||||
() => [CARD_MENU_ACTIONS[0]!, ...pinMenuItem, ...CARD_MENU_ACTIONS.slice(1)],
|
||||
[pinMenuItem],
|
||||
);
|
||||
const handleMenuAction = useCallback(
|
||||
({ nativeEvent }: { readonly nativeEvent: { readonly event: string } }) => {
|
||||
@@ -569,7 +534,6 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
|
||||
if (nativeEvent.event === "move-pin-up") handleMovePinnedUp();
|
||||
if (nativeEvent.event === "move-pin-down") handleMovePinnedDown();
|
||||
if (nativeEvent.event === "archive") handleArchive();
|
||||
if (nativeEvent.event === "regenerate-title") handleRegenerateTitle();
|
||||
if (nativeEvent.event === "delete") handleDelete();
|
||||
const snoozeSelection = resolveThreadListV2SnoozeMenuSelection({
|
||||
event: nativeEvent.event,
|
||||
@@ -585,7 +549,6 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
|
||||
[
|
||||
handleArchive,
|
||||
handleDelete,
|
||||
handleRegenerateTitle,
|
||||
handleMovePinnedDown,
|
||||
handleMovePinnedUp,
|
||||
handlePin,
|
||||
@@ -927,11 +890,11 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
|
||||
<ControlPillMenu
|
||||
actions={
|
||||
snoozedRow
|
||||
? snoozedMenuActions
|
||||
? SNOOZED_MENU_ACTIONS
|
||||
: !props.settlementSupported
|
||||
? legacyMenuActions
|
||||
? LEGACY_MENU_ACTIONS
|
||||
: canUnsettle
|
||||
? slimMenuActions
|
||||
? SLIM_MENU_ACTIONS
|
||||
: swipeActions.secondary === "snooze"
|
||||
? snoozableCardMenuActions
|
||||
: cardMenuActions
|
||||
|
||||
@@ -1,284 +0,0 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { ProviderInstanceId, type ProviderOptionDescriptor } from "@t3tools/contracts";
|
||||
|
||||
import type { ModelOption, ProviderGroup } from "../../lib/modelOptions";
|
||||
import { buildThreadSettingsMenu, type ThreadSettingsMenuEvent } from "./thread-settings-menu";
|
||||
|
||||
function modelOption(
|
||||
model: string,
|
||||
overrides: Partial<Pick<ModelOption, "isDefault" | "isLegacy" | "providerKey">> = {},
|
||||
): ModelOption {
|
||||
const providerKey = overrides.providerKey ?? "codex";
|
||||
return {
|
||||
key: `${providerKey}:${model}`,
|
||||
label: model,
|
||||
subtitle: providerKey,
|
||||
providerKey,
|
||||
providerLabel: providerKey === "codex" ? "Codex" : "Claude",
|
||||
providerDriver: providerKey === "codex" ? "codex" : "claudeAgent",
|
||||
isDefault: overrides.isDefault ?? false,
|
||||
isLegacy: overrides.isLegacy ?? false,
|
||||
capabilities: null,
|
||||
selection: {
|
||||
instanceId: ProviderInstanceId.make(providerKey),
|
||||
model,
|
||||
options: [],
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function group(models: ReadonlyArray<ModelOption>): ProviderGroup {
|
||||
const first = models[0];
|
||||
if (!first) {
|
||||
throw new Error("group requires at least one model");
|
||||
}
|
||||
return {
|
||||
providerKey: first.providerKey,
|
||||
providerLabel: first.providerLabel,
|
||||
models,
|
||||
};
|
||||
}
|
||||
|
||||
const effortDescriptor: ProviderOptionDescriptor = {
|
||||
id: "effort",
|
||||
label: "Reasoning",
|
||||
type: "select",
|
||||
options: [
|
||||
{ id: "low", label: "Low" },
|
||||
{ id: "medium", label: "Medium", isDefault: true },
|
||||
{ id: "high", label: "High" },
|
||||
{ id: "ultrathink", label: "Ultrathink" },
|
||||
{ id: "ultracode", label: "Ultracode" },
|
||||
],
|
||||
currentValue: "high",
|
||||
promptInjectedValues: ["ultrathink"],
|
||||
};
|
||||
|
||||
const fastModeDescriptor: ProviderOptionDescriptor = {
|
||||
id: "fastMode",
|
||||
label: "Fast mode",
|
||||
type: "boolean",
|
||||
currentValue: false,
|
||||
};
|
||||
|
||||
function baseInput() {
|
||||
const models = [
|
||||
modelOption("gpt-current", { isDefault: true }),
|
||||
modelOption("gpt-next"),
|
||||
modelOption("gpt-old", { isLegacy: true }),
|
||||
];
|
||||
return {
|
||||
providerGroups: [group(models)],
|
||||
selectedModel: models[0]?.selection ?? null,
|
||||
optionDescriptors: [effortDescriptor, fastModeDescriptor],
|
||||
runtimeMode: "auto",
|
||||
} as const;
|
||||
}
|
||||
|
||||
function eventFor(menu: ReturnType<typeof buildThreadSettingsMenu>, id: string | undefined) {
|
||||
return id === undefined ? undefined : menu.events.get(id);
|
||||
}
|
||||
|
||||
describe("buildThreadSettingsMenu", () => {
|
||||
it("orders the top level as model, options, runtime", () => {
|
||||
const menu = buildThreadSettingsMenu(baseInput());
|
||||
|
||||
expect(menu.actions.map((action) => action.title)).toEqual([
|
||||
"Model",
|
||||
"Reasoning",
|
||||
"Fast mode",
|
||||
"Runtime",
|
||||
]);
|
||||
});
|
||||
|
||||
it("summarizes the current choice on each submenu row", () => {
|
||||
const menu = buildThreadSettingsMenu(baseInput());
|
||||
|
||||
expect(menu.actions.find((action) => action.title === "Model")?.subtitle).toBe("gpt-current");
|
||||
expect(menu.actions.find((action) => action.title === "Reasoning")?.subtitle).toBe("High");
|
||||
expect(menu.actions.find((action) => action.title === "Runtime")?.subtitle).toBe("Auto");
|
||||
});
|
||||
|
||||
it("checkmarks the selected model and resolves selection events", () => {
|
||||
const menu = buildThreadSettingsMenu(baseInput());
|
||||
|
||||
const modelItems = menu.actions.find((action) => action.title === "Model")?.subactions ?? [];
|
||||
const current = modelItems.find((action) => action.title === "gpt-current");
|
||||
expect(current?.state).toBe("on");
|
||||
expect(current?.subtitle).toBe("Default");
|
||||
expect(modelItems.find((action) => action.title === "gpt-next")?.state).toBe("off");
|
||||
|
||||
const event = eventFor(menu, modelItems.find((action) => action.title === "gpt-next")?.id);
|
||||
expect(event?.type).toBe("select-model");
|
||||
expect(event?.type === "select-model" ? event.option.selection.model : null).toBe("gpt-next");
|
||||
});
|
||||
|
||||
it("folds unselected legacy models behind a nested submenu", () => {
|
||||
const menu = buildThreadSettingsMenu(baseInput());
|
||||
|
||||
const modelItems = menu.actions.find((action) => action.title === "Model")?.subactions ?? [];
|
||||
expect(modelItems.map((action) => action.title)).toEqual([
|
||||
"gpt-current",
|
||||
"gpt-next",
|
||||
"Legacy Models",
|
||||
]);
|
||||
expect(
|
||||
modelItems
|
||||
.find((action) => action.title === "Legacy Models")
|
||||
?.subactions?.map((action) => action.title),
|
||||
).toEqual(["gpt-old"]);
|
||||
});
|
||||
|
||||
it("keeps a selected legacy model in the main list", () => {
|
||||
const input = baseInput();
|
||||
const legacy = input.providerGroups[0]?.models.find((model) => model.isLegacy);
|
||||
const menu = buildThreadSettingsMenu({
|
||||
...input,
|
||||
selectedModel: legacy?.selection ?? null,
|
||||
});
|
||||
|
||||
const modelItems = menu.actions.find((action) => action.title === "Model")?.subactions ?? [];
|
||||
expect(modelItems.map((action) => action.title)).toEqual([
|
||||
"gpt-current",
|
||||
"gpt-next",
|
||||
"gpt-old",
|
||||
]);
|
||||
expect(modelItems.find((action) => action.title === "gpt-old")?.state).toBe("on");
|
||||
});
|
||||
|
||||
it("hides prompt-injected and workflow-trigger efforts but still summarizes them", () => {
|
||||
const menu = buildThreadSettingsMenu({
|
||||
...baseInput(),
|
||||
optionDescriptors: [{ ...effortDescriptor, currentValue: "ultracode" }],
|
||||
});
|
||||
|
||||
const reasoning = menu.actions.find((action) => action.title === "Reasoning");
|
||||
expect(reasoning?.subactions?.map((action) => action.title)).toEqual(["Low", "Medium", "High"]);
|
||||
// The hidden value stays visible as the current summary; it just can't be
|
||||
// picked from the phone.
|
||||
expect(reasoning?.subtitle).toBe("Ultracode");
|
||||
expect(reasoning?.subactions?.every((action) => action.state === "off")).toBe(true);
|
||||
});
|
||||
|
||||
it("resolves select-option and runtime events with checkmarked current values", () => {
|
||||
const menu = buildThreadSettingsMenu(baseInput());
|
||||
|
||||
const reasoningItems =
|
||||
menu.actions.find((action) => action.title === "Reasoning")?.subactions ?? [];
|
||||
expect(reasoningItems.find((action) => action.title === "High")?.state).toBe("on");
|
||||
expect(eventFor(menu, reasoningItems.find((action) => action.title === "Low")?.id)).toEqual({
|
||||
type: "set-option",
|
||||
optionId: "effort",
|
||||
value: "low",
|
||||
});
|
||||
|
||||
const runtimeItems =
|
||||
menu.actions.find((action) => action.title === "Runtime")?.subactions ?? [];
|
||||
expect(runtimeItems.find((action) => action.title === "Auto")?.state).toBe("on");
|
||||
expect(
|
||||
eventFor(menu, runtimeItems.find((action) => action.title === "Full access")?.id),
|
||||
).toEqual({ type: "set-runtime", mode: "full-access" });
|
||||
});
|
||||
|
||||
it("toggles boolean options with the inverted current value", () => {
|
||||
const menu = buildThreadSettingsMenu(baseInput());
|
||||
|
||||
const fastMode = menu.actions.find((action) => action.title === "Fast mode");
|
||||
expect(fastMode?.state).toBe("off");
|
||||
expect(fastMode?.subactions).toBeUndefined();
|
||||
expect(eventFor(menu, fastMode?.id)).toEqual({
|
||||
type: "set-option",
|
||||
optionId: "fastMode",
|
||||
value: true,
|
||||
});
|
||||
|
||||
const enabled = buildThreadSettingsMenu({
|
||||
...baseInput(),
|
||||
optionDescriptors: [{ ...fastModeDescriptor, currentValue: true }],
|
||||
});
|
||||
const enabledRow = enabled.actions.find((action) => action.title === "Fast mode");
|
||||
expect(enabledRow?.state).toBe("on");
|
||||
expect(eventFor(enabled, enabledRow?.id)).toEqual({
|
||||
type: "set-option",
|
||||
optionId: "fastMode",
|
||||
value: false,
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps the menu presented only for top-level toggles", () => {
|
||||
const menu = buildThreadSettingsMenu(baseInput());
|
||||
|
||||
// Root-level boolean toggles refresh in place with clean chrome, so they
|
||||
// keep the menu presented.
|
||||
expect(
|
||||
menu.actions.find((action) => action.title === "Fast mode")?.attributes?.keepsMenuPresented,
|
||||
).toBe(true);
|
||||
|
||||
// Picks inside nested submenus close the menu: staying presented leaves
|
||||
// the submenu on screen with an expanded-submenu header, and the
|
||||
// bottom-anchored collapse back out drops by the levels' height delta.
|
||||
const expected = undefined;
|
||||
const modelItems = menu.actions.find((action) => action.title === "Model")?.subactions ?? [];
|
||||
const reasoningItems =
|
||||
menu.actions.find((action) => action.title === "Reasoning")?.subactions ?? [];
|
||||
const runtimeItems =
|
||||
menu.actions.find((action) => action.title === "Runtime")?.subactions ?? [];
|
||||
const nestedPicks = [...modelItems, ...reasoningItems, ...runtimeItems].filter(
|
||||
(action) => action.subactions === undefined,
|
||||
);
|
||||
expect(nestedPicks.length).toBeGreaterThan(0);
|
||||
expect(nestedPicks.every((action) => action.attributes?.keepsMenuPresented === expected)).toBe(
|
||||
true,
|
||||
);
|
||||
});
|
||||
|
||||
it("sections models by provider only when multiple groups are offered", () => {
|
||||
const codexModels = [modelOption("gpt-current", { isDefault: true })];
|
||||
const claudeModels = [modelOption("fable-5", { providerKey: "claude" })];
|
||||
const menu = buildThreadSettingsMenu({
|
||||
providerGroups: [group(codexModels), group(claudeModels)],
|
||||
selectedModel: codexModels[0]?.selection ?? null,
|
||||
optionDescriptors: [],
|
||||
runtimeMode: "auto",
|
||||
});
|
||||
|
||||
const modelItems = menu.actions.find((action) => action.title === "Model")?.subactions ?? [];
|
||||
expect(
|
||||
modelItems.map((action) => ({ title: action.title, inline: action.displayInline ?? false })),
|
||||
).toEqual([
|
||||
{ title: "Codex", inline: true },
|
||||
{ title: "Claude", inline: true },
|
||||
]);
|
||||
const claudeSection = modelItems.find((action) => action.title === "Claude");
|
||||
expect(claudeSection?.subactions?.map((action) => action.title)).toEqual(["fable-5"]);
|
||||
});
|
||||
|
||||
const eventTypes = (menu: ReturnType<typeof buildThreadSettingsMenu>) => {
|
||||
const types = new Set<ThreadSettingsMenuEvent["type"]>();
|
||||
for (const event of menu.events.values()) {
|
||||
types.add(event.type);
|
||||
}
|
||||
return types;
|
||||
};
|
||||
|
||||
it("registers an event for every leaf action id", () => {
|
||||
const menu = buildThreadSettingsMenu(baseInput());
|
||||
const leafIds: string[] = [];
|
||||
const collect = (items: ReadonlyArray<{ id?: string; subactions?: unknown[] }>) => {
|
||||
for (const item of items) {
|
||||
if (Array.isArray(item.subactions) && item.subactions.length > 0) {
|
||||
collect(item.subactions as ReadonlyArray<{ id?: string; subactions?: unknown[] }>);
|
||||
} else if (item.id !== undefined) {
|
||||
leafIds.push(item.id);
|
||||
}
|
||||
}
|
||||
};
|
||||
collect(menu.actions);
|
||||
|
||||
for (const id of leafIds) {
|
||||
expect(menu.events.get(id), `missing event for ${id}`).toBeDefined();
|
||||
}
|
||||
expect(eventTypes(menu)).toEqual(new Set(["select-model", "set-option", "set-runtime"]));
|
||||
});
|
||||
});
|
||||
@@ -1,202 +0,0 @@
|
||||
import type { MenuAction } from "@react-native-menu/menu";
|
||||
import type { ModelSelection, ProviderOptionDescriptor, RuntimeMode } from "@t3tools/contracts";
|
||||
import {
|
||||
getProviderOptionCurrentLabel,
|
||||
getProviderOptionCurrentValue,
|
||||
} from "@t3tools/shared/model";
|
||||
|
||||
import type { ModelOption, ProviderGroup } from "../../lib/modelOptions";
|
||||
|
||||
/**
|
||||
* Desktop-oriented effort keywords that don't belong in the phone picker.
|
||||
* Prompt-injected values (ultrathink and friends) are filtered from the
|
||||
* descriptor metadata; ultracode is a real option but a workflow trigger, not
|
||||
* a reasoning level. A value set elsewhere still displays, it just isn't
|
||||
* offered.
|
||||
*/
|
||||
export const HIDDEN_EFFORT_OPTION_IDS: ReadonlySet<string> = new Set(["ultracode"]);
|
||||
|
||||
export const RUNTIME_MODE_CHOICES: ReadonlyArray<{
|
||||
readonly mode: RuntimeMode;
|
||||
readonly label: string;
|
||||
readonly shortLabel: string;
|
||||
}> = [
|
||||
{ mode: "approval-required", label: "Approve actions", shortLabel: "Approve" },
|
||||
{ mode: "auto-accept-edits", label: "Auto-accept edits", shortLabel: "Edits" },
|
||||
{ mode: "auto", label: "Auto", shortLabel: "Auto" },
|
||||
{ mode: "full-access", label: "Full access", shortLabel: "Full" },
|
||||
];
|
||||
|
||||
export function selectableChoices(
|
||||
descriptor: Extract<ProviderOptionDescriptor, { type: "select" }>,
|
||||
) {
|
||||
const injected = new Set(descriptor.promptInjectedValues ?? []);
|
||||
return descriptor.options.filter(
|
||||
(option) => !injected.has(option.id) && !HIDDEN_EFFORT_OPTION_IDS.has(option.id),
|
||||
);
|
||||
}
|
||||
|
||||
export type ThreadSettingsMenuEvent =
|
||||
| { readonly type: "select-model"; readonly option: ModelOption }
|
||||
| { readonly type: "set-option"; readonly optionId: string; readonly value: string | boolean }
|
||||
| { readonly type: "set-runtime"; readonly mode: RuntimeMode };
|
||||
|
||||
export type ThreadSettingsMenu = {
|
||||
readonly actions: MenuAction[];
|
||||
/** Menu action id → the change it applies, for the onPressAction dispatch. */
|
||||
readonly events: ReadonlyMap<string, ThreadSettingsMenuEvent>;
|
||||
};
|
||||
|
||||
/**
|
||||
* Native menu replacement for the thread settings sheet (model, select and
|
||||
* boolean provider options, runtime mode). The menu presents from the
|
||||
* composer pill without resigning the keyboard, so adjusting settings never
|
||||
* bounces focus. A thread is bound to one harness, so the menu covers the
|
||||
* sheet's full surface for existing threads; the sheet remains the Android
|
||||
* and new-task-draft surface.
|
||||
*
|
||||
* Selections apply immediately — the sheet's stage-then-Save flow only exists
|
||||
* because the sheet batches a model change with its option edits.
|
||||
*/
|
||||
export function buildThreadSettingsMenu(input: {
|
||||
readonly providerGroups: ReadonlyArray<ProviderGroup>;
|
||||
readonly selectedModel: ModelSelection | null;
|
||||
readonly optionDescriptors: ReadonlyArray<ProviderOptionDescriptor>;
|
||||
readonly runtimeMode: RuntimeMode;
|
||||
}): ThreadSettingsMenu {
|
||||
const events = new Map<string, ThreadSettingsMenuEvent>();
|
||||
const actions: MenuAction[] = [];
|
||||
|
||||
const isSelected = (option: ModelOption) =>
|
||||
option.selection.instanceId === input.selectedModel?.instanceId &&
|
||||
option.selection.model === input.selectedModel.model;
|
||||
|
||||
// Only top-level leaves (boolean toggles) keep the menu presented (iOS
|
||||
// 16+): the root refreshes in place with clean chrome. Picks inside nested
|
||||
// submenus close the menu — keeping the submenu presented renders an
|
||||
// expanded-submenu header with no way to pop back to the root, and the
|
||||
// bottom-anchored collapse back out travels the levels' height difference.
|
||||
const keepPresented = { keepsMenuPresented: true } as const;
|
||||
|
||||
const modelAction = (option: ModelOption, id: string): MenuAction => {
|
||||
events.set(id, { type: "select-model", option });
|
||||
return {
|
||||
id,
|
||||
title: option.label,
|
||||
...(option.isDefault ? { subtitle: "Default" } : {}),
|
||||
state: isSelected(option) ? "on" : "off",
|
||||
};
|
||||
};
|
||||
|
||||
const modelItems: MenuAction[] = [];
|
||||
const legacyItems: MenuAction[] = [];
|
||||
let selectedModelLabel: string | undefined;
|
||||
input.providerGroups.forEach((group, groupIndex) => {
|
||||
const groupItems: MenuAction[] = [];
|
||||
group.models.forEach((option, modelIndex) => {
|
||||
if (isSelected(option)) {
|
||||
selectedModelLabel = option.label;
|
||||
}
|
||||
const id = `model:${groupIndex}:${modelIndex}`;
|
||||
// A highlighted legacy model stays in the main list (mirroring the
|
||||
// sheet) so the checkmark isn't hidden behind the Legacy fold.
|
||||
if (option.isLegacy && !isSelected(option)) {
|
||||
legacyItems.push(modelAction(option, id));
|
||||
} else {
|
||||
groupItems.push(modelAction(option, id));
|
||||
}
|
||||
});
|
||||
if (groupItems.length === 0) {
|
||||
return;
|
||||
}
|
||||
// A thread is bound to one harness, so provider sections only appear for
|
||||
// multi-group callers (the new-task draft, if it ever adopts the menu).
|
||||
if (input.providerGroups.length > 1) {
|
||||
modelItems.push({
|
||||
id: `model-group:${groupIndex}`,
|
||||
title: group.providerLabel,
|
||||
displayInline: true,
|
||||
subactions: groupItems,
|
||||
});
|
||||
} else {
|
||||
modelItems.push(...groupItems);
|
||||
}
|
||||
});
|
||||
if (legacyItems.length > 0) {
|
||||
modelItems.push({
|
||||
id: "legacy-models",
|
||||
title: "Legacy Models",
|
||||
subactions: legacyItems,
|
||||
});
|
||||
}
|
||||
if (modelItems.length > 0) {
|
||||
actions.push({
|
||||
id: "model",
|
||||
title: "Model",
|
||||
...(selectedModelLabel === undefined
|
||||
? input.selectedModel
|
||||
? { subtitle: input.selectedModel.model }
|
||||
: {}
|
||||
: { subtitle: selectedModelLabel }),
|
||||
subactions: modelItems,
|
||||
});
|
||||
}
|
||||
|
||||
for (const descriptor of input.optionDescriptors) {
|
||||
if (descriptor.type === "boolean") {
|
||||
const id = `option:${descriptor.id}`;
|
||||
events.set(id, {
|
||||
type: "set-option",
|
||||
optionId: descriptor.id,
|
||||
value: !(descriptor.currentValue ?? false),
|
||||
});
|
||||
actions.push({
|
||||
id,
|
||||
title: descriptor.label,
|
||||
state: descriptor.currentValue ? "on" : "off",
|
||||
attributes: keepPresented,
|
||||
});
|
||||
continue;
|
||||
}
|
||||
const currentValue = getProviderOptionCurrentValue(descriptor);
|
||||
const choices = selectableChoices(descriptor).map((choice): MenuAction => {
|
||||
const id = `option:${descriptor.id}:${choice.id}`;
|
||||
events.set(id, { type: "set-option", optionId: descriptor.id, value: choice.id });
|
||||
return {
|
||||
id,
|
||||
title: choice.label,
|
||||
state: choice.id === currentValue ? "on" : "off",
|
||||
};
|
||||
});
|
||||
if (choices.length === 0) {
|
||||
continue;
|
||||
}
|
||||
const currentLabel = getProviderOptionCurrentLabel(descriptor);
|
||||
actions.push({
|
||||
id: `option:${descriptor.id}`,
|
||||
title: descriptor.label,
|
||||
...(currentLabel === undefined ? {} : { subtitle: currentLabel }),
|
||||
subactions: choices,
|
||||
});
|
||||
}
|
||||
|
||||
const runtimeLabel = RUNTIME_MODE_CHOICES.find(
|
||||
(choice) => choice.mode === input.runtimeMode,
|
||||
)?.label;
|
||||
actions.push({
|
||||
id: "runtime",
|
||||
title: "Runtime",
|
||||
...(runtimeLabel === undefined ? {} : { subtitle: runtimeLabel }),
|
||||
subactions: RUNTIME_MODE_CHOICES.map((choice): MenuAction => {
|
||||
const id = `runtime:${choice.mode}`;
|
||||
events.set(id, { type: "set-runtime", mode: choice.mode });
|
||||
return {
|
||||
id,
|
||||
title: choice.label,
|
||||
state: choice.mode === input.runtimeMode ? "on" : "off",
|
||||
};
|
||||
}),
|
||||
});
|
||||
|
||||
return { actions, events };
|
||||
}
|
||||
@@ -1,36 +0,0 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { buildThreadTitleRegenerationMenuItems } from "./thread-title-regeneration-menu";
|
||||
|
||||
describe("buildThreadTitleRegenerationMenuItems", () => {
|
||||
it("hides regeneration when the environment does not advertise support", () => {
|
||||
expect(
|
||||
buildThreadTitleRegenerationMenuItems({ supported: false, isRegenerating: false }),
|
||||
).toEqual([]);
|
||||
});
|
||||
|
||||
it("offers regeneration for a supported environment", () => {
|
||||
expect(
|
||||
buildThreadTitleRegenerationMenuItems({ supported: true, isRegenerating: false }),
|
||||
).toEqual([
|
||||
{
|
||||
id: "regenerate-title",
|
||||
title: "Regenerate title",
|
||||
image: "arrow.clockwise",
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("shows and disables the pending state", () => {
|
||||
expect(
|
||||
buildThreadTitleRegenerationMenuItems({ supported: true, isRegenerating: true }),
|
||||
).toEqual([
|
||||
{
|
||||
id: "regenerate-title",
|
||||
title: "Regenerating…",
|
||||
image: "arrow.clockwise",
|
||||
attributes: { disabled: true },
|
||||
},
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -1,17 +0,0 @@
|
||||
import type { MenuAction } from "@react-native-menu/menu";
|
||||
|
||||
export function buildThreadTitleRegenerationMenuItems(input: {
|
||||
readonly supported: boolean;
|
||||
readonly isRegenerating: boolean;
|
||||
}): MenuAction[] {
|
||||
if (!input.supported) return [];
|
||||
|
||||
return [
|
||||
{
|
||||
id: "regenerate-title",
|
||||
title: input.isRegenerating ? "Regenerating…" : "Regenerate title",
|
||||
image: "arrow.clockwise",
|
||||
...(input.isRegenerating ? { attributes: { disabled: true } } : {}),
|
||||
},
|
||||
];
|
||||
}
|
||||
@@ -32,19 +32,6 @@ function makeUpdateClient(overrides: Partial<AppUpdateClient> = {}): AppUpdateCl
|
||||
}
|
||||
|
||||
describe("runAppUpdateCheck", () => {
|
||||
it("does nothing while running from the Metro development server", async () => {
|
||||
vi.stubGlobal("__DEV__", true);
|
||||
const client = makeUpdateClient();
|
||||
|
||||
try {
|
||||
await runAppUpdateCheck({ client });
|
||||
} finally {
|
||||
vi.unstubAllGlobals();
|
||||
}
|
||||
|
||||
expect(client.checkForUpdateAsync).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("downloads and restarts when a new update is available", async () => {
|
||||
const client = makeUpdateClient({
|
||||
checkForUpdateAsync: vi.fn(async () => ({
|
||||
@@ -113,32 +100,6 @@ describe("runAppUpdateCheck", () => {
|
||||
reportError.mockRestore();
|
||||
});
|
||||
|
||||
it.each(["ERR_NOT_AVAILABLE_IN_DEV_CLIENT", "ERR_UPDATES_DISABLED"])(
|
||||
"treats Expo's %s failure as an unavailable update check",
|
||||
async (code) => {
|
||||
const reportError = vi.spyOn(console, "error").mockImplementation(() => {});
|
||||
const error = Object.assign(new Error("Updates are unavailable"), { code });
|
||||
const client = makeUpdateClient({
|
||||
checkForUpdateAsync: vi.fn(async () => {
|
||||
throw error;
|
||||
}),
|
||||
});
|
||||
const failures: string[] = [];
|
||||
const states: AppUpdateCheckState[] = [];
|
||||
|
||||
await runAppUpdateCheck({
|
||||
client,
|
||||
onFailure: (message) => failures.push(message),
|
||||
onStateChange: (state) => states.push(state),
|
||||
});
|
||||
|
||||
expect(reportError).not.toHaveBeenCalled();
|
||||
expect(failures).toEqual([]);
|
||||
expect(states).toEqual(["checking", "idle"]);
|
||||
reportError.mockRestore();
|
||||
},
|
||||
);
|
||||
|
||||
it("coalesces overlapping launch and manual checks", async () => {
|
||||
let resolveCheck!: (result: {
|
||||
readonly isAvailable: boolean;
|
||||
|
||||
@@ -48,17 +48,8 @@ interface Deferred {
|
||||
}
|
||||
|
||||
const HIDDEN_UPDATE_TAP_COUNT = 5;
|
||||
const UPDATE_CHECK_UNAVAILABLE_ERROR_CODES = new Set([
|
||||
"ERR_NOT_AVAILABLE_IN_DEV_CLIENT",
|
||||
"ERR_UPDATES_DISABLED",
|
||||
]);
|
||||
let appUpdateCheckInFlight: AppUpdateCheckInFlight | undefined;
|
||||
|
||||
/** Expo's development launcher reports updates as enabled even though its OTA APIs reject. */
|
||||
export function isAppUpdateCheckAvailable(client: Pick<AppUpdateClient, "isEnabled"> = Updates) {
|
||||
return client.isEnabled && !(typeof __DEV__ !== "undefined" && __DEV__);
|
||||
}
|
||||
|
||||
/**
|
||||
* Keeps the manual update affordance discoverable only to someone deliberately
|
||||
* tapping the version row five times.
|
||||
@@ -82,7 +73,7 @@ export function registerHiddenUpdateTap(count: number): {
|
||||
|
||||
export async function runAppUpdateCheck(options: AppUpdateCheckOptions = {}): Promise<void> {
|
||||
const client = options.client ?? Updates;
|
||||
if (!isAppUpdateCheckAvailable(client)) return;
|
||||
if (!client.isEnabled) return;
|
||||
|
||||
if (appUpdateCheckInFlight) {
|
||||
await observeAppUpdateCheck(appUpdateCheckInFlight, options);
|
||||
@@ -216,27 +207,19 @@ function reportUpdateFailure(
|
||||
fallback: string,
|
||||
onFailure: AppUpdateCheckOptions["onFailure"],
|
||||
): void {
|
||||
reportAtomCommandResult(result, { label: "app update check" });
|
||||
if (result._tag !== "Failure" || isAtomCommandInterrupted(result)) return;
|
||||
const error = squashAtomCommandFailure(result);
|
||||
if (isAppUpdateUnavailableError(error)) return;
|
||||
|
||||
reportAtomCommandResult(result, { label: "app update check" });
|
||||
onFailure?.(error instanceof Error ? error.message : fallback);
|
||||
}
|
||||
|
||||
function isAppUpdateUnavailableError(error: unknown): boolean {
|
||||
if (typeof error !== "object" || error === null || !("code" in error)) return false;
|
||||
const code = error.code;
|
||||
return typeof code === "string" && UPDATE_CHECK_UNAVAILABLE_ERROR_CODES.has(code);
|
||||
}
|
||||
|
||||
export function createAppUpdateLaunchCheck(
|
||||
client: AppUpdateClient = Updates,
|
||||
): () => Promise<void> | undefined {
|
||||
let started = false;
|
||||
|
||||
return () => {
|
||||
if (started || !isAppUpdateCheckAvailable(client)) return undefined;
|
||||
if (started || !client.isEnabled) return undefined;
|
||||
started = true;
|
||||
return runAppUpdateCheck({ client });
|
||||
};
|
||||
|
||||
@@ -1,11 +1,9 @@
|
||||
import { useNavigation } from "@react-navigation/native";
|
||||
import type { DailyTotals, MergedUsage } from "@t3tools/shared/usageMerge";
|
||||
import type { MergedUsage } from "@t3tools/shared/usageMerge";
|
||||
import {
|
||||
enumerateDays,
|
||||
enumerateHourStarts,
|
||||
formatCount,
|
||||
formatDayShort,
|
||||
formatHourShort,
|
||||
formatPercent,
|
||||
formatTokens,
|
||||
formatUsd,
|
||||
@@ -25,7 +23,6 @@ import type { UsageChartMetric } from "./usageChartData";
|
||||
import { PROVIDER_LABEL, useProviderColors } from "./usageProviders";
|
||||
|
||||
const WINDOW_OPTIONS = [
|
||||
{ days: 1, label: "Past 24h" },
|
||||
{ days: 7, label: "7 days" },
|
||||
{ days: 30, label: "30 days" },
|
||||
{ days: 90, label: "90 days" },
|
||||
@@ -36,62 +33,23 @@ const CHART_HEIGHT = 180;
|
||||
export function UsageRouteScreen() {
|
||||
const navigation = useNavigation();
|
||||
const insets = useSafeAreaInsets();
|
||||
const [windowSelection, setWindowSelection] = useState(() => ({
|
||||
days: 30,
|
||||
window: makeWindow(30),
|
||||
}));
|
||||
const [windowDays, setWindowDays] = useState<number>(30);
|
||||
const [metric, setMetric] = useState<UsageChartMetric>("cost");
|
||||
const { days: windowDays, window } = windowSelection;
|
||||
const isPast24Hours = windowDays === 1;
|
||||
|
||||
// Recomputed only when the window length changes, so a re-render does not
|
||||
// shift the range and refetch every environment.
|
||||
const window = useMemo(() => makeWindow(windowDays), [windowDays]);
|
||||
const { merged, environments, isPending, isPartial, refresh } = useUsage(window);
|
||||
|
||||
const days = useMemo(
|
||||
() => enumerateDays(window.sinceDay, window.untilDay),
|
||||
[window.sinceDay, window.untilDay],
|
||||
);
|
||||
const chartDays = useMemo(
|
||||
() =>
|
||||
isPast24Hours && window.sinceTime !== undefined && window.untilTime !== undefined
|
||||
? enumerateHourStarts(window.sinceTime, window.untilTime)
|
||||
: days,
|
||||
[days, isPast24Hours, window.sinceTime, window.untilTime],
|
||||
);
|
||||
const chartTotals = useMemo(
|
||||
(): readonly DailyTotals[] =>
|
||||
isPast24Hours
|
||||
? merged.hourly.map((hour) => ({
|
||||
day: hour.hourStart,
|
||||
costUsd: hour.costUsd,
|
||||
totalTokens: hour.totalTokens,
|
||||
byProvider: hour.byProvider,
|
||||
}))
|
||||
: merged.daily,
|
||||
[isPast24Hours, merged.daily, merged.hourly],
|
||||
);
|
||||
|
||||
// The pull spinner tracks re-scans of environments that have answered
|
||||
// before. The initial scan renders its own placeholder, and an unreachable
|
||||
// environment stays pending forever — neither may pin the spinner on.
|
||||
const refreshing = environments.some((entry) => entry.isPending && entry.summary !== null);
|
||||
const selectWindow = (days: number) => {
|
||||
setWindowSelection({
|
||||
days,
|
||||
window: makeWindow(days, undefined, days === 1 ? "hour" : "day"),
|
||||
});
|
||||
};
|
||||
const refreshWindow = () => {
|
||||
const nextWindow = makeWindow(windowDays, undefined, isPast24Hours ? "hour" : "day");
|
||||
if (
|
||||
nextWindow.sinceDay === window.sinceDay &&
|
||||
nextWindow.untilDay === window.untilDay &&
|
||||
nextWindow.sinceTime === window.sinceTime &&
|
||||
nextWindow.untilTime === window.untilTime
|
||||
) {
|
||||
refresh();
|
||||
} else {
|
||||
setWindowSelection({ days: windowDays, window: nextWindow });
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<View collapsable={false} className="flex-1 bg-sheet">
|
||||
@@ -107,12 +65,12 @@ export function UsageRouteScreen() {
|
||||
className="flex-1"
|
||||
contentContainerClassName="gap-6 px-5 pt-4"
|
||||
contentContainerStyle={{ paddingBottom: Math.max(insets.bottom, 18) + 18 }}
|
||||
refreshControl={<RefreshControl refreshing={refreshing} onRefresh={refreshWindow} />}
|
||||
refreshControl={<RefreshControl refreshing={refreshing} onRefresh={refresh} />}
|
||||
>
|
||||
<SegmentedControl
|
||||
options={WINDOW_OPTIONS.map((option) => ({ value: option.days, label: option.label }))}
|
||||
selected={windowDays}
|
||||
onSelect={selectWindow}
|
||||
onSelect={setWindowDays}
|
||||
/>
|
||||
|
||||
<UsageCoverageNotice environments={environments} merged={merged} isPartial={isPartial} />
|
||||
@@ -129,17 +87,14 @@ export function UsageRouteScreen() {
|
||||
<>
|
||||
<ChartCard
|
||||
merged={merged}
|
||||
days={chartDays}
|
||||
daily={chartTotals}
|
||||
days={days}
|
||||
metric={metric}
|
||||
onMetricChange={setMetric}
|
||||
sinceDay={window.sinceDay}
|
||||
untilDay={window.untilDay}
|
||||
isPast24Hours={isPast24Hours}
|
||||
timeZone={window.timeZone}
|
||||
/>
|
||||
<ProviderSection merged={merged} metric={metric} />
|
||||
<TotalsSection merged={merged} isPast24Hours={isPast24Hours} />
|
||||
<TotalsSection merged={merged} />
|
||||
<ModelsSection merged={merged} />
|
||||
</>
|
||||
)}
|
||||
@@ -187,17 +142,14 @@ function SegmentedControl<Value extends number | string>(props: {
|
||||
function ChartCard(props: {
|
||||
readonly merged: MergedUsage;
|
||||
readonly days: readonly string[];
|
||||
readonly daily: readonly DailyTotals[];
|
||||
readonly metric: UsageChartMetric;
|
||||
readonly onMetricChange: (metric: UsageChartMetric) => void;
|
||||
readonly sinceDay: string;
|
||||
readonly untilDay: string;
|
||||
readonly isPast24Hours: boolean;
|
||||
readonly timeZone: string;
|
||||
}) {
|
||||
const { merged, metric } = props;
|
||||
const colors = useProviderColors();
|
||||
const hasActivity = props.daily.some((period) => period.totalTokens > 0);
|
||||
const hasActivity = merged.daily.some((day) => day.totalTokens > 0);
|
||||
|
||||
return (
|
||||
<View className="gap-4 rounded-[24px] border-continuous bg-card p-4">
|
||||
@@ -221,7 +173,7 @@ function ChartCard(props: {
|
||||
{hasActivity ? (
|
||||
<UsageDailyChart
|
||||
days={props.days}
|
||||
daily={props.daily}
|
||||
daily={merged.daily}
|
||||
metric={metric}
|
||||
height={CHART_HEIGHT}
|
||||
/>
|
||||
@@ -232,11 +184,7 @@ function ChartCard(props: {
|
||||
)}
|
||||
|
||||
<View className="flex-row items-center justify-between">
|
||||
<Text className="text-xs text-foreground-tertiary">
|
||||
{props.isPast24Hours
|
||||
? formatHourShort(props.days[0] ?? "", props.timeZone)
|
||||
: formatDayShort(props.sinceDay)}
|
||||
</Text>
|
||||
<Text className="text-xs text-foreground-tertiary">{formatDayShort(props.sinceDay)}</Text>
|
||||
<View className="flex-row items-center gap-4">
|
||||
{merged.providers.map((provider) => (
|
||||
<View key={provider.provider} className="flex-row items-center gap-1.5">
|
||||
@@ -250,11 +198,7 @@ function ChartCard(props: {
|
||||
</View>
|
||||
))}
|
||||
</View>
|
||||
<Text className="text-xs text-foreground-tertiary">
|
||||
{props.isPast24Hours
|
||||
? formatHourShort(props.days[props.days.length - 1] ?? "", props.timeZone)
|
||||
: formatDayShort(props.untilDay)}
|
||||
</Text>
|
||||
<Text className="text-xs text-foreground-tertiary">{formatDayShort(props.untilDay)}</Text>
|
||||
</View>
|
||||
</View>
|
||||
);
|
||||
@@ -348,12 +292,10 @@ function ProviderSection(props: {
|
||||
);
|
||||
}
|
||||
|
||||
function TotalsSection(props: { readonly merged: MergedUsage; readonly isPast24Hours: boolean }) {
|
||||
function TotalsSection(props: { readonly merged: MergedUsage }) {
|
||||
const { merged } = props;
|
||||
const activePeriods = (props.isPast24Hours ? merged.hourly : merged.daily).filter(
|
||||
(period) => period.totalTokens > 0,
|
||||
).length;
|
||||
const periodAverage = activePeriods === 0 ? 0 : merged.totalTokens / activePeriods;
|
||||
const activeDays = merged.daily.filter((day) => day.totalTokens > 0).length;
|
||||
const dailyAverage = activeDays === 0 ? 0 : merged.totalTokens / activeDays;
|
||||
const observedInput = merged.uncachedInputTokens + merged.cachedInputTokens;
|
||||
const cachedShare = observedInput === 0 ? 0 : merged.cachedInputTokens / observedInput;
|
||||
|
||||
@@ -363,7 +305,7 @@ function TotalsSection(props: { readonly merged: MergedUsage; readonly isPast24H
|
||||
<MetricCell
|
||||
label="Processed tokens"
|
||||
value={formatTokens(merged.totalTokens)}
|
||||
detail={`${formatTokens(periodAverage)} per active ${props.isPast24Hours ? "hour" : "day"}`}
|
||||
detail={`${formatTokens(dailyAverage)} per active day`}
|
||||
/>
|
||||
<MetricCell
|
||||
label="Cache savings"
|
||||
|
||||
@@ -12,107 +12,12 @@ import {
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
import {
|
||||
buildPendingUserInputAnswers,
|
||||
buildThreadFeed,
|
||||
deriveThreadFeedPresentation,
|
||||
isPendingUserInputOptionSelected,
|
||||
setPendingUserInputCustomAnswer,
|
||||
togglePendingUserInputOptionSelection,
|
||||
type ThreadFeedActivity,
|
||||
type ThreadFeedEntry,
|
||||
} from "./threadActivity";
|
||||
|
||||
const singleSelectQuestion = {
|
||||
id: "runtime",
|
||||
header: "Runtime",
|
||||
question: "Which runtime should be used?",
|
||||
options: [
|
||||
{ label: "Go", description: "One binary" },
|
||||
{ label: "Node.js", description: "Reuse TypeScript" },
|
||||
],
|
||||
multiSelect: false,
|
||||
} as const;
|
||||
|
||||
const multiSelectQuestion = {
|
||||
id: "scope",
|
||||
header: "Scope",
|
||||
question: "Which data should be collected?",
|
||||
options: [
|
||||
{ label: "Orders", description: "Receipts" },
|
||||
{ label: "Listings", description: "Inventory" },
|
||||
],
|
||||
multiSelect: true,
|
||||
} as const;
|
||||
|
||||
describe("pending user input answers", () => {
|
||||
it("replaces single-select options and toggles multi-select options", () => {
|
||||
expect(
|
||||
togglePendingUserInputOptionSelection(
|
||||
singleSelectQuestion,
|
||||
{ selectedOptionLabels: ["Go"] },
|
||||
"Node.js",
|
||||
),
|
||||
).toEqual({ customAnswer: "", selectedOptionLabels: ["Node.js"] });
|
||||
|
||||
const orders = togglePendingUserInputOptionSelection(multiSelectQuestion, undefined, "Orders");
|
||||
const ordersAndListings = togglePendingUserInputOptionSelection(
|
||||
multiSelectQuestion,
|
||||
orders,
|
||||
"Listings",
|
||||
);
|
||||
expect(ordersAndListings).toEqual({
|
||||
customAnswer: "",
|
||||
selectedOptionLabels: ["Orders", "Listings"],
|
||||
});
|
||||
expect(
|
||||
togglePendingUserInputOptionSelection(multiSelectQuestion, ordersAndListings, "Orders"),
|
||||
).toEqual({ customAnswer: "", selectedOptionLabels: ["Listings"] });
|
||||
|
||||
const paddedOrders = togglePendingUserInputOptionSelection(
|
||||
multiSelectQuestion,
|
||||
undefined,
|
||||
" Orders ",
|
||||
);
|
||||
expect(paddedOrders).toEqual({ customAnswer: "", selectedOptionLabels: ["Orders"] });
|
||||
expect(
|
||||
togglePendingUserInputOptionSelection(multiSelectQuestion, paddedOrders, " Orders "),
|
||||
).toEqual({ customAnswer: "" });
|
||||
});
|
||||
|
||||
it("builds array answers for multi-select questions", () => {
|
||||
expect(
|
||||
buildPendingUserInputAnswers([singleSelectQuestion, multiSelectQuestion], {
|
||||
runtime: { selectedOptionLabels: ["Go"] },
|
||||
scope: { selectedOptionLabels: ["Orders", "Listings"] },
|
||||
}),
|
||||
).toEqual({
|
||||
runtime: "Go",
|
||||
scope: ["Orders", "Listings"],
|
||||
});
|
||||
});
|
||||
|
||||
it("clears selected options while a custom answer is active", () => {
|
||||
expect(
|
||||
setPendingUserInputCustomAnswer(
|
||||
{ selectedOptionLabels: ["Orders", "Listings"] },
|
||||
"Orders first",
|
||||
),
|
||||
).toEqual({ customAnswer: "Orders first" });
|
||||
});
|
||||
|
||||
it("matches selected chips against normalized option labels", () => {
|
||||
expect(
|
||||
isPendingUserInputOptionSelected({ selectedOptionLabels: ["Orders"] }, " Orders "),
|
||||
).toBe(true);
|
||||
expect(
|
||||
isPendingUserInputOptionSelected(
|
||||
{ selectedOptionLabels: ["Orders"], customAnswer: "Orders first" },
|
||||
" Orders ",
|
||||
),
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
function makeActivity(
|
||||
input: Partial<OrchestrationThreadActivity> &
|
||||
Pick<OrchestrationThreadActivity, "id" | "kind" | "summary" | "createdAt">,
|
||||
|
||||
@@ -26,7 +26,7 @@ export interface PendingUserInput {
|
||||
}
|
||||
|
||||
export interface PendingUserInputDraftAnswer {
|
||||
readonly selectedOptionLabels?: ReadonlyArray<string>;
|
||||
readonly selectedOptionLabel?: string;
|
||||
readonly customAnswer?: string;
|
||||
}
|
||||
|
||||
@@ -227,32 +227,14 @@ function normalizeDraftAnswer(value: string | undefined): string | null {
|
||||
return trimmed.length > 0 ? trimmed : null;
|
||||
}
|
||||
|
||||
function normalizeSelectedOptionLabels(
|
||||
value: ReadonlyArray<string> | undefined,
|
||||
): ReadonlyArray<string> {
|
||||
if (!Array.isArray(value)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return Array.from(
|
||||
new Set(value.map((entry) => entry.trim()).filter((entry) => entry.length > 0)),
|
||||
);
|
||||
}
|
||||
|
||||
function resolvePendingUserInputAnswer(
|
||||
question: UserInputQuestion,
|
||||
draft: PendingUserInputDraftAnswer | undefined,
|
||||
): string | ReadonlyArray<string> | null {
|
||||
): string | null {
|
||||
const customAnswer = normalizeDraftAnswer(draft?.customAnswer);
|
||||
if (customAnswer) {
|
||||
return customAnswer;
|
||||
}
|
||||
|
||||
const selectedOptionLabels = normalizeSelectedOptionLabels(draft?.selectedOptionLabels);
|
||||
if (question.multiSelect) {
|
||||
return selectedOptionLabels.length > 0 ? selectedOptionLabels : null;
|
||||
}
|
||||
return selectedOptionLabels[0] ?? null;
|
||||
return normalizeDraftAnswer(draft?.selectedOptionLabel);
|
||||
}
|
||||
|
||||
/** Codex children settle via task.updated (idle/failed/interrupted), never
|
||||
@@ -1446,62 +1428,22 @@ export function setPendingUserInputCustomAnswer(
|
||||
draft: PendingUserInputDraftAnswer | undefined,
|
||||
customAnswer: string,
|
||||
): PendingUserInputDraftAnswer {
|
||||
const selectedOptionLabels =
|
||||
customAnswer.trim().length > 0
|
||||
? undefined
|
||||
: normalizeSelectedOptionLabels(draft?.selectedOptionLabels);
|
||||
const selectedOptionLabel =
|
||||
customAnswer.trim().length > 0 ? undefined : draft?.selectedOptionLabel;
|
||||
return {
|
||||
customAnswer,
|
||||
...(selectedOptionLabels && selectedOptionLabels.length > 0 ? { selectedOptionLabels } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
export function isPendingUserInputOptionSelected(
|
||||
draft: PendingUserInputDraftAnswer | undefined,
|
||||
optionLabel: string,
|
||||
): boolean {
|
||||
if (normalizeDraftAnswer(draft?.customAnswer)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return normalizeSelectedOptionLabels(draft?.selectedOptionLabels).includes(optionLabel.trim());
|
||||
}
|
||||
|
||||
export function togglePendingUserInputOptionSelection(
|
||||
question: UserInputQuestion,
|
||||
draft: PendingUserInputDraftAnswer | undefined,
|
||||
optionLabel: string,
|
||||
): PendingUserInputDraftAnswer {
|
||||
const normalizedOptionLabel = optionLabel.trim();
|
||||
|
||||
if (question.multiSelect) {
|
||||
const selectedOptionLabels = normalizeSelectedOptionLabels(draft?.selectedOptionLabels);
|
||||
const nextSelectedOptionLabels = selectedOptionLabels.includes(normalizedOptionLabel)
|
||||
? selectedOptionLabels.filter((label) => label !== normalizedOptionLabel)
|
||||
: [...selectedOptionLabels, normalizedOptionLabel];
|
||||
|
||||
return {
|
||||
customAnswer: "",
|
||||
...(nextSelectedOptionLabels.length > 0
|
||||
? { selectedOptionLabels: nextSelectedOptionLabels }
|
||||
: {}),
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
customAnswer: "",
|
||||
selectedOptionLabels: [normalizedOptionLabel],
|
||||
...(selectedOptionLabel ? { selectedOptionLabel } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
export function buildPendingUserInputAnswers(
|
||||
questions: ReadonlyArray<UserInputQuestion>,
|
||||
draftAnswers: Record<string, PendingUserInputDraftAnswer>,
|
||||
): Record<string, string | ReadonlyArray<string>> | null {
|
||||
const answers: Record<string, string | ReadonlyArray<string>> = {};
|
||||
): Record<string, string> | null {
|
||||
const answers: Record<string, string> = {};
|
||||
|
||||
for (const question of questions) {
|
||||
const answer = resolvePendingUserInputAnswer(question, draftAnswers[question.id]);
|
||||
const answer = resolvePendingUserInputAnswer(draftAnswers[question.id]);
|
||||
if (!answer) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -17,30 +17,6 @@ describe("hasWideMarkdownBlock", () => {
|
||||
expect(hasWideMarkdownBlock(" ```\ncode\n```")).toBe(true);
|
||||
});
|
||||
|
||||
it("detects top-level and blockquoted ordered-list markers", () => {
|
||||
expect(hasWideMarkdownBlock("1. One\n2. Two\n3. Three\n4. Four\n5. Five")).toBe(true);
|
||||
expect(hasWideMarkdownBlock("before\n3) Three")).toBe(true);
|
||||
expect(hasWideMarkdownBlock("> 1. One\n> 2. Two")).toBe(true);
|
||||
expect(hasWideMarkdownBlock("> > 3) Three")).toBe(true);
|
||||
});
|
||||
|
||||
it("detects nested ordered lists without treating indented code as a list", () => {
|
||||
expect(hasWideMarkdownBlock("- Parent\n 1. Child\n 2. Child")).toBe(true);
|
||||
expect(hasWideMarkdownBlock("> - Parent\n> 1. Child")).toBe(true);
|
||||
expect(hasWideMarkdownBlock(" 1. indented code")).toBe(false);
|
||||
expect(hasWideMarkdownBlock(" - code-like bullet\n 1. indented code")).toBe(false);
|
||||
});
|
||||
|
||||
it("can limit ordered-list width pinning to Android", () => {
|
||||
const orderedList = "1. One\n2. Two";
|
||||
expect(hasWideMarkdownBlock(orderedList, { includeOrderedLists: true })).toBe(true);
|
||||
expect(hasWideMarkdownBlock(orderedList, { includeOrderedLists: false })).toBe(false);
|
||||
expect(hasWideMarkdownBlock("```\ncode\n```", { includeOrderedLists: false })).toBe(true);
|
||||
expect(hasWideMarkdownBlock("| a | b |\n| --- | --- |", { includeOrderedLists: false })).toBe(
|
||||
true,
|
||||
);
|
||||
});
|
||||
|
||||
it("detects GFM tables", () => {
|
||||
expect(hasWideMarkdownBlock("| a | b |\n| --- | --- |\n| 1 | 2 |")).toBe(true);
|
||||
expect(hasWideMarkdownBlock("a | b\n:-- | --:\n1 | 2")).toBe(true);
|
||||
|
||||
@@ -1,10 +1,9 @@
|
||||
/**
|
||||
* Detects markdown that the JS renderer draws as a block requiring a definite
|
||||
* user-bubble width — fenced code blocks, GFM tables, and ordered lists.
|
||||
* Detects markdown that the JS renderer draws as a standalone block View
|
||||
* wrapping a horizontal ScrollView — fenced code blocks and GFM tables.
|
||||
*
|
||||
* Fenced code blocks and tables report an intrinsic width equal to their
|
||||
* widest line, which is effectively unbounded. A user bubble sizes itself
|
||||
* from its content
|
||||
* Those blocks report an intrinsic width equal to their widest line, which is
|
||||
* effectively unbounded. A user bubble sizes itself from its content
|
||||
* (`maxWidth` with no `width`), so Android lays the bubble's children out
|
||||
* during the unclamped intrinsic pass — where the surrounding paragraphs
|
||||
* collapse to a single line — and never repositions them once the width is
|
||||
@@ -13,57 +12,12 @@
|
||||
* intrinsic pass entirely, which is the same reason review-comment bubbles
|
||||
* already carry an explicit width.
|
||||
*
|
||||
* Ordered lists hit the same Android layout bug because each item contains a
|
||||
* flexing content column inside a shrink-to-fit row.
|
||||
*
|
||||
* A four-space ordered marker is only treated as a list when the preceding
|
||||
* non-empty line is a less-indented list item. This keeps standalone indented
|
||||
* code out of the heuristic while covering nested lists.
|
||||
* Indented (four-space) code blocks are deliberately not detected: they are
|
||||
* vanishingly rare in chat input and the check would fire on ordinary nested
|
||||
* list continuations.
|
||||
*/
|
||||
|
||||
const FENCED_CODE_BLOCK = /^ {0,3}(?:```|~~~)/m;
|
||||
// Trades some precision for a simple check, favoring false positives over false
|
||||
// negatives: list-shaped paragraph may get a wider bubble
|
||||
const ORDERED_LIST_ITEM = /^ {0,3}\d{1,9}[.)](?:[ \t]+|$)/;
|
||||
const INDENTED_ORDERED_LIST_ITEM = /^( {4,})\d{1,9}[.)](?:[ \t]+|$)/;
|
||||
const ANY_LIST_ITEM = /^( *)(?:[-+*]|\d{1,9}[.)])(?:[ \t]+|$)/;
|
||||
const BLOCKQUOTE_PREFIX = /^ {0,3}>[ \t]?/;
|
||||
|
||||
export interface WideMarkdownBlockOptions {
|
||||
readonly includeOrderedLists?: boolean;
|
||||
}
|
||||
|
||||
function stripBlockquotePrefixes(line: string): string {
|
||||
let content = line;
|
||||
while (BLOCKQUOTE_PREFIX.test(content)) {
|
||||
content = content.replace(BLOCKQUOTE_PREFIX, "");
|
||||
}
|
||||
return content;
|
||||
}
|
||||
|
||||
function hasOrderedListItem(text: string): boolean {
|
||||
let previousNonEmptyLine: string | null = null;
|
||||
|
||||
for (const rawLine of text.split("\n")) {
|
||||
const line = stripBlockquotePrefixes(rawLine);
|
||||
if (ORDERED_LIST_ITEM.test(line)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
const nestedMatch = INDENTED_ORDERED_LIST_ITEM.exec(line);
|
||||
const parentMatch =
|
||||
previousNonEmptyLine === null ? null : ANY_LIST_ITEM.exec(previousNonEmptyLine);
|
||||
if (nestedMatch && parentMatch && parentMatch[1].length < nestedMatch[1].length) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (line.trim().length > 0) {
|
||||
previousNonEmptyLine = line;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
function isTableDelimiterRow(line: string): boolean {
|
||||
const trimmed = line.trim();
|
||||
@@ -73,16 +27,10 @@ function isTableDelimiterRow(line: string): boolean {
|
||||
return /^[|\-: \t]+$/.test(trimmed);
|
||||
}
|
||||
|
||||
export function hasWideMarkdownBlock(
|
||||
text: string,
|
||||
options: WideMarkdownBlockOptions = {},
|
||||
): boolean {
|
||||
export function hasWideMarkdownBlock(text: string): boolean {
|
||||
if (FENCED_CODE_BLOCK.test(text)) {
|
||||
return true;
|
||||
}
|
||||
if (options.includeOrderedLists !== false && hasOrderedListItem(text)) {
|
||||
return true;
|
||||
}
|
||||
if (!text.includes("|")) {
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -81,18 +81,8 @@ export function useUsage(input: UsageSummaryInput): UsageView {
|
||||
sinceDay: input.sinceDay,
|
||||
untilDay: input.untilDay,
|
||||
timeZone: input.timeZone,
|
||||
resolution: input.resolution,
|
||||
sinceTime: input.sinceTime,
|
||||
untilTime: input.untilTime,
|
||||
}),
|
||||
[
|
||||
input.sinceDay,
|
||||
input.untilDay,
|
||||
input.timeZone,
|
||||
input.resolution,
|
||||
input.sinceTime,
|
||||
input.untilTime,
|
||||
],
|
||||
[input.sinceDay, input.untilDay, input.timeZone],
|
||||
);
|
||||
const atom = usageByWindowAtom(windowKey);
|
||||
const environments = useAtomValue(atom);
|
||||
|
||||
@@ -1,11 +1,7 @@
|
||||
import { useAtomValue } from "@effect/atom-react";
|
||||
import { useCallback, useMemo, useState } from "react";
|
||||
|
||||
import {
|
||||
ApprovalRequestId,
|
||||
type ProviderApprovalDecision,
|
||||
type UserInputQuestion,
|
||||
} from "@t3tools/contracts";
|
||||
import { ApprovalRequestId, type ProviderApprovalDecision } from "@t3tools/contracts";
|
||||
import { Atom } from "effect/unstable/reactivity";
|
||||
|
||||
import { threadEnvironment } from "../state/threads";
|
||||
@@ -16,7 +12,6 @@ import {
|
||||
derivePendingUserInputs,
|
||||
setPendingUserInputCustomAnswer,
|
||||
sortThreadActivities,
|
||||
togglePendingUserInputOptionSelection,
|
||||
type PendingUserInputDraftAnswer,
|
||||
} from "../lib/threadActivity";
|
||||
import { appAtomRegistry } from "./atom-registry";
|
||||
@@ -28,21 +23,15 @@ const userInputDraftsByRequestKeyAtom = Atom.make<
|
||||
Record<string, Record<string, PendingUserInputDraftAnswer>>
|
||||
>({}).pipe(Atom.keepAlive, Atom.withLabel("mobile:user-input-drafts"));
|
||||
|
||||
function setUserInputDraftOption(
|
||||
requestKey: string,
|
||||
question: UserInputQuestion,
|
||||
label: string,
|
||||
): void {
|
||||
function setUserInputDraftOption(requestKey: string, questionId: string, label: string): void {
|
||||
const current = appAtomRegistry.get(userInputDraftsByRequestKeyAtom);
|
||||
appAtomRegistry.set(userInputDraftsByRequestKeyAtom, {
|
||||
...current,
|
||||
[requestKey]: {
|
||||
...current[requestKey],
|
||||
[question.id]: togglePendingUserInputOptionSelection(
|
||||
question,
|
||||
current[requestKey]?.[question.id],
|
||||
label,
|
||||
),
|
||||
[questionId]: {
|
||||
selectedOptionLabel: label,
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -108,13 +97,13 @@ export function useSelectedThreadRequests() {
|
||||
: null;
|
||||
|
||||
const onSelectUserInputOption = useCallback(
|
||||
(requestId: ApprovalRequestId, question: UserInputQuestion, label: string) => {
|
||||
(requestId: ApprovalRequestId, questionId: string, label: string) => {
|
||||
if (!selectedThreadShell) {
|
||||
return;
|
||||
}
|
||||
|
||||
const requestKey = scopedRequestKey(selectedThreadShell.environmentId, requestId);
|
||||
setUserInputDraftOption(requestKey, question, label);
|
||||
setUserInputDraftOption(requestKey, questionId, label);
|
||||
},
|
||||
[selectedThreadShell],
|
||||
);
|
||||
|
||||
@@ -26,6 +26,7 @@ import * as HttpServerResponse from "effect/unstable/http/HttpServerResponse";
|
||||
|
||||
import {
|
||||
buildConnectAuthorizeRequestUrl,
|
||||
buildConnectClerkAuthorizeUrl,
|
||||
checkConnectAuthCode,
|
||||
connectCallbackUrl,
|
||||
} from "@t3tools/shared/connectAuth";
|
||||
@@ -366,7 +367,6 @@ export const make = Effect.gen(function* () {
|
||||
|
||||
const login = Effect.fn("cloud.cli_token.login")(function* () {
|
||||
const metadata = yield* cloudCliOAuthConfig;
|
||||
const hostedAppUrl = yield* hostedAppUrlConfig;
|
||||
const { verifier, challenge, state } = yield* makePkceRequest;
|
||||
const callback = yield* Deferred.make<string>();
|
||||
const callbackRoute = HttpRouter.add(
|
||||
@@ -392,21 +392,19 @@ export const make = Effect.gen(function* () {
|
||||
Layer.provide(
|
||||
NodeHttpServer.layer(NodeHttp.createServer, {
|
||||
host: "127.0.0.1",
|
||||
port: metadata.loopbackPort,
|
||||
port: 34338,
|
||||
disablePreemptiveShutdown: true,
|
||||
}),
|
||||
),
|
||||
Layer.build,
|
||||
);
|
||||
// The hosted /connect page establishes a Clerk session before forwarding
|
||||
// the request to /oauth/authorize with the loopback redirect URI. Sending
|
||||
// a signed-out browser to /oauth/authorize directly loses the authorize
|
||||
// parameters across Clerk's sign-in redirect (#5051).
|
||||
const authorizationUrl = buildConnectAuthorizeRequestUrl({
|
||||
hostedAppUrl,
|
||||
const authorizationUrl = buildConnectClerkAuthorizeUrl({
|
||||
authorizationEndpoint: metadata.authorizationEndpoint,
|
||||
clientId: metadata.clientId,
|
||||
redirectUri: metadata.redirectUri,
|
||||
scopes: metadata.scopes,
|
||||
state,
|
||||
challenge,
|
||||
loopbackPort: metadata.loopbackPort,
|
||||
});
|
||||
yield* Console.log(formatLoopbackAuthorizationPrompt(authorizationUrl));
|
||||
const authorization = yield* waitForLoopbackAuthorization({
|
||||
|
||||
@@ -90,9 +90,9 @@ it.effect("derives direct Clerk OAuth endpoints from statically injected public
|
||||
}).pipe(provideEnv({}));
|
||||
|
||||
assert.deepEqual(config, {
|
||||
authorizationEndpoint: "https://clerk.example.test/oauth/authorize",
|
||||
tokenEndpoint: "https://clerk.example.test/oauth/token",
|
||||
clientId: "oauth_client_embedded",
|
||||
loopbackPort: 34338,
|
||||
redirectUri: "http://127.0.0.1:34338/callback",
|
||||
scopes: ["openid", "profile", "email"],
|
||||
});
|
||||
@@ -111,6 +111,7 @@ it.effect("prefers runtime Clerk OAuth config overrides over statically injected
|
||||
}),
|
||||
);
|
||||
|
||||
assert.equal(config.authorizationEndpoint, "https://runtime.example.test/oauth/authorize");
|
||||
assert.equal(config.tokenEndpoint, "https://runtime.example.test/oauth/token");
|
||||
assert.equal(config.clientId, "oauth_client_runtime");
|
||||
}),
|
||||
|
||||
@@ -1,8 +1,4 @@
|
||||
import {
|
||||
connectLoopbackRedirectUri,
|
||||
CONNECT_OAUTH_SCOPES,
|
||||
DEFAULT_HOSTED_APP_URL,
|
||||
} from "@t3tools/shared/connectAuth";
|
||||
import { CONNECT_OAUTH_SCOPES, DEFAULT_HOSTED_APP_URL } from "@t3tools/shared/connectAuth";
|
||||
import { clerkFrontendApiUrlFromPublishableKey } from "@t3tools/shared/relayAuth";
|
||||
import { normalizeSecureRelayUrl } from "@t3tools/shared/relayUrl";
|
||||
import * as Config from "effect/Config";
|
||||
@@ -18,7 +14,7 @@ declare const __T3CODE_BUILD_RELAY_CLIENT_OTLP_TRACES_URL__: string | undefined;
|
||||
declare const __T3CODE_BUILD_RELAY_CLIENT_OTLP_TRACES_DATASET__: string | undefined;
|
||||
declare const __T3CODE_BUILD_RELAY_CLIENT_OTLP_TRACES_TOKEN__: string | undefined;
|
||||
|
||||
const CLOUD_CLI_OAUTH_LOOPBACK_PORT = 34338;
|
||||
const CLOUD_CLI_OAUTH_REDIRECT_URI = "http://127.0.0.1:34338/callback";
|
||||
const CLOUD_CLI_OAUTH_SCOPES = CONNECT_OAUTH_SCOPES;
|
||||
|
||||
function validateRelayUrl(value: string) {
|
||||
@@ -149,16 +145,10 @@ function makePublicValueConfig(name: string, fallback: string) {
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* The CLI never calls Clerk's /oauth/authorize itself: the browser leg goes
|
||||
* through the hosted /connect page, which builds the authorize URL after a
|
||||
* Clerk session exists (see CliTokenManager.login). Only the token endpoint
|
||||
* is contacted directly.
|
||||
*/
|
||||
export interface CloudCliOAuthConfig {
|
||||
readonly authorizationEndpoint: string;
|
||||
readonly tokenEndpoint: string;
|
||||
readonly clientId: string;
|
||||
readonly loopbackPort: number;
|
||||
readonly redirectUri: string;
|
||||
readonly scopes: typeof CLOUD_CLI_OAUTH_SCOPES;
|
||||
}
|
||||
@@ -194,10 +184,10 @@ export function makeCloudCliOAuthConfig({
|
||||
Effect.map(
|
||||
(clerkFrontendApiUrl) =>
|
||||
({
|
||||
authorizationEndpoint: `${clerkFrontendApiUrl}/oauth/authorize`,
|
||||
tokenEndpoint: `${clerkFrontendApiUrl}/oauth/token`,
|
||||
clientId,
|
||||
loopbackPort: CLOUD_CLI_OAUTH_LOOPBACK_PORT,
|
||||
redirectUri: connectLoopbackRedirectUri(CLOUD_CLI_OAUTH_LOOPBACK_PORT),
|
||||
redirectUri: CLOUD_CLI_OAUTH_REDIRECT_URI,
|
||||
scopes: CLOUD_CLI_OAUTH_SCOPES,
|
||||
}) satisfies CloudCliOAuthConfig,
|
||||
),
|
||||
|
||||
@@ -146,6 +146,7 @@ export const make = Effect.gen(function* () {
|
||||
pullRequests: true,
|
||||
threadSettlement: true,
|
||||
threadSnooze: true,
|
||||
threadVisits: true,
|
||||
threadPinning: true,
|
||||
threadPinReorder: true,
|
||||
threadTitleRegeneration: true,
|
||||
|
||||
@@ -619,6 +619,7 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
|
||||
settledAt: null,
|
||||
snoozedUntil: null,
|
||||
snoozedAt: null,
|
||||
lastVisitedAt: null,
|
||||
pinnedAt: null,
|
||||
pinOrderKey: null,
|
||||
titleRegenerationRequestId: null,
|
||||
@@ -727,6 +728,21 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
|
||||
return;
|
||||
}
|
||||
|
||||
case "thread.visited": {
|
||||
const existingRow = yield* projectionThreadRepository.getById({
|
||||
threadId: event.payload.threadId,
|
||||
});
|
||||
if (Option.isNone(existingRow)) {
|
||||
return;
|
||||
}
|
||||
yield* projectionThreadRepository.upsert({
|
||||
...existingRow.value,
|
||||
lastVisitedAt: event.payload.lastVisitedAt,
|
||||
updatedAt: event.payload.updatedAt,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
case "thread.pinned": {
|
||||
const existingRow = yield* projectionThreadRepository.getById({
|
||||
threadId: event.payload.threadId,
|
||||
|
||||
@@ -323,6 +323,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
|
||||
settledAt: null,
|
||||
snoozedUntil: null,
|
||||
snoozedAt: null,
|
||||
lastVisitedAt: null,
|
||||
pinnedAt: "2026-02-24T00:00:01.000Z",
|
||||
pinOrderKey: "gm",
|
||||
titleRegeneration: null,
|
||||
@@ -442,6 +443,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
|
||||
settledAt: null,
|
||||
snoozedUntil: null,
|
||||
snoozedAt: null,
|
||||
lastVisitedAt: null,
|
||||
pinnedAt: "2026-02-24T00:00:01.000Z",
|
||||
pinOrderKey: "gm",
|
||||
titleRegeneration: null,
|
||||
|
||||
@@ -426,6 +426,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
settled_at AS "settledAt",
|
||||
snoozed_until AS "snoozedUntil",
|
||||
snoozed_at AS "snoozedAt",
|
||||
last_visited_at AS "lastVisitedAt",
|
||||
pinned_at AS "pinnedAt",
|
||||
pin_order_key AS "pinOrderKey",
|
||||
title_regeneration_request_id AS "titleRegenerationRequestId",
|
||||
@@ -462,6 +463,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
settled_at AS "settledAt",
|
||||
snoozed_until AS "snoozedUntil",
|
||||
snoozed_at AS "snoozedAt",
|
||||
last_visited_at AS "lastVisitedAt",
|
||||
pinned_at AS "pinnedAt",
|
||||
pin_order_key AS "pinOrderKey",
|
||||
title_regeneration_request_id AS "titleRegenerationRequestId",
|
||||
@@ -500,6 +502,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
settled_at AS "settledAt",
|
||||
snoozed_until AS "snoozedUntil",
|
||||
snoozed_at AS "snoozedAt",
|
||||
last_visited_at AS "lastVisitedAt",
|
||||
pinned_at AS "pinnedAt",
|
||||
pin_order_key AS "pinOrderKey",
|
||||
title_regeneration_request_id AS "titleRegenerationRequestId",
|
||||
@@ -942,6 +945,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
settled_at AS "settledAt",
|
||||
snoozed_until AS "snoozedUntil",
|
||||
snoozed_at AS "snoozedAt",
|
||||
last_visited_at AS "lastVisitedAt",
|
||||
pinned_at AS "pinnedAt",
|
||||
pin_order_key AS "pinOrderKey",
|
||||
title_regeneration_request_id AS "titleRegenerationRequestId",
|
||||
@@ -1575,6 +1579,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
settledAt: row.settledAt,
|
||||
snoozedUntil: row.snoozedUntil,
|
||||
snoozedAt: row.snoozedAt,
|
||||
lastVisitedAt: row.lastVisitedAt,
|
||||
pinnedAt: row.pinnedAt,
|
||||
pinOrderKey: row.pinOrderKey ?? null,
|
||||
titleRegeneration: mapTitleRegeneration(row),
|
||||
@@ -1782,6 +1787,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
settledAt: row.settledAt,
|
||||
snoozedUntil: row.snoozedUntil,
|
||||
snoozedAt: row.snoozedAt,
|
||||
lastVisitedAt: row.lastVisitedAt,
|
||||
pinnedAt: row.pinnedAt,
|
||||
pinOrderKey: row.pinOrderKey ?? null,
|
||||
titleRegeneration: mapTitleRegeneration(row),
|
||||
@@ -1918,6 +1924,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
settledAt: row.settledAt,
|
||||
snoozedUntil: row.snoozedUntil,
|
||||
snoozedAt: row.snoozedAt,
|
||||
lastVisitedAt: row.lastVisitedAt,
|
||||
pinnedAt: row.pinnedAt,
|
||||
pinOrderKey: row.pinOrderKey ?? null,
|
||||
titleRegeneration: mapTitleRegeneration(row),
|
||||
@@ -2063,6 +2070,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
settledAt: row.settledAt,
|
||||
snoozedUntil: row.snoozedUntil,
|
||||
snoozedAt: row.snoozedAt,
|
||||
lastVisitedAt: row.lastVisitedAt,
|
||||
pinnedAt: row.pinnedAt,
|
||||
pinOrderKey: row.pinOrderKey ?? null,
|
||||
titleRegeneration: mapTitleRegeneration(row),
|
||||
@@ -2342,6 +2350,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
settledAt: threadRow.value.settledAt,
|
||||
snoozedUntil: threadRow.value.snoozedUntil,
|
||||
snoozedAt: threadRow.value.snoozedAt,
|
||||
lastVisitedAt: threadRow.value.lastVisitedAt,
|
||||
pinnedAt: threadRow.value.pinnedAt,
|
||||
pinOrderKey: threadRow.value.pinOrderKey ?? null,
|
||||
titleRegeneration: mapTitleRegeneration(threadRow.value),
|
||||
@@ -2463,6 +2472,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
settledAt: threadRow.value.settledAt,
|
||||
snoozedUntil: threadRow.value.snoozedUntil,
|
||||
snoozedAt: threadRow.value.snoozedAt,
|
||||
lastVisitedAt: threadRow.value.lastVisitedAt,
|
||||
pinnedAt: threadRow.value.pinnedAt,
|
||||
pinOrderKey: threadRow.value.pinOrderKey ?? null,
|
||||
titleRegeneration: mapTitleRegeneration(threadRow.value),
|
||||
|
||||
@@ -13,6 +13,7 @@ import {
|
||||
ThreadUnsettledPayload as ContractsThreadUnsettledPayloadSchema,
|
||||
ThreadSnoozedPayload as ContractsThreadSnoozedPayloadSchema,
|
||||
ThreadUnsnoozedPayload as ContractsThreadUnsnoozedPayloadSchema,
|
||||
ThreadVisitedPayload as ContractsThreadVisitedPayloadSchema,
|
||||
ThreadPinnedPayload as ContractsThreadPinnedPayloadSchema,
|
||||
ThreadUnpinnedPayload as ContractsThreadUnpinnedPayloadSchema,
|
||||
ThreadPinReorderedPayload as ContractsThreadPinReorderedPayloadSchema,
|
||||
@@ -45,6 +46,7 @@ export const ThreadUnarchivedPayload = ContractsThreadUnarchivedPayloadSchema;
|
||||
export const ThreadUnsettledPayload = ContractsThreadUnsettledPayloadSchema;
|
||||
export const ThreadSnoozedPayload = ContractsThreadSnoozedPayloadSchema;
|
||||
export const ThreadUnsnoozedPayload = ContractsThreadUnsnoozedPayloadSchema;
|
||||
export const ThreadVisitedPayload = ContractsThreadVisitedPayloadSchema;
|
||||
export const ThreadPinnedPayload = ContractsThreadPinnedPayloadSchema;
|
||||
export const ThreadUnpinnedPayload = ContractsThreadUnpinnedPayloadSchema;
|
||||
export const ThreadPinReorderedPayload = ContractsThreadPinReorderedPayloadSchema;
|
||||
|
||||
@@ -658,6 +658,43 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
||||
};
|
||||
}
|
||||
|
||||
case "thread.visit": {
|
||||
// requireThread, not requireThreadNotArchived: archived threads stay
|
||||
// openable, and acknowledging one must not fail.
|
||||
const thread = yield* requireThread({
|
||||
readModel,
|
||||
command,
|
||||
threadId: command.threadId,
|
||||
});
|
||||
// Monotonic: a visit never moves the acknowledgement backwards, so a
|
||||
// raced or replayed older visit re-emits the existing value (the
|
||||
// engine rejects zero-event commands) and projects as a no-op. NaN
|
||||
// from an unparseable stored value fails the comparison and lets the
|
||||
// fresh visit through.
|
||||
const existingVisitedAt = thread.lastVisitedAt ?? null;
|
||||
const lastVisitedAt =
|
||||
existingVisitedAt !== null && Date.parse(existingVisitedAt) >= Date.parse(command.visitedAt)
|
||||
? existingVisitedAt
|
||||
: command.visitedAt;
|
||||
const occurredAt = yield* nowIso;
|
||||
return {
|
||||
...(yield* withEventBase({
|
||||
aggregateKind: "thread",
|
||||
aggregateId: command.threadId,
|
||||
occurredAt,
|
||||
commandId: command.commandId,
|
||||
})),
|
||||
type: "thread.visited",
|
||||
payload: {
|
||||
threadId: command.threadId,
|
||||
lastVisitedAt,
|
||||
// A visit is passive acknowledgement: always keep the thread's
|
||||
// existing updatedAt so reading never churns ordering.
|
||||
updatedAt: thread.updatedAt,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
case "thread.pin": {
|
||||
const thread = yield* requireThreadNotArchived({
|
||||
readModel,
|
||||
|
||||
@@ -0,0 +1,149 @@
|
||||
import {
|
||||
CommandId,
|
||||
ProjectId,
|
||||
ProviderInstanceId,
|
||||
ThreadId,
|
||||
type OrchestrationReadModel,
|
||||
} from "@t3tools/contracts";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { expect, it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
|
||||
import { decideOrchestrationCommand } from "./decider.ts";
|
||||
|
||||
const NOW = "2026-01-01T00:00:00.000Z";
|
||||
const EARLIER_VISIT = "2025-12-30T00:00:00.000Z";
|
||||
const LATER_VISIT = "2025-12-31T00:00:00.000Z";
|
||||
|
||||
function makeReadModel(input: {
|
||||
readonly lastVisitedAt?: string | null;
|
||||
readonly archivedAt?: string | null;
|
||||
}): OrchestrationReadModel {
|
||||
return {
|
||||
snapshotSequence: 0,
|
||||
projects: [],
|
||||
threads: [
|
||||
{
|
||||
id: ThreadId.make("thread-1"),
|
||||
projectId: ProjectId.make("project-1"),
|
||||
title: "Thread",
|
||||
modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
latestTurn: null,
|
||||
createdAt: NOW,
|
||||
updatedAt: NOW,
|
||||
archivedAt: input.archivedAt ?? null,
|
||||
settledOverride: null,
|
||||
settledAt: null,
|
||||
snoozedUntil: null,
|
||||
snoozedAt: null,
|
||||
lastVisitedAt: input.lastVisitedAt ?? null,
|
||||
deletedAt: null,
|
||||
messages: [],
|
||||
proposedPlans: [],
|
||||
activities: [],
|
||||
checkpoints: [],
|
||||
session: null,
|
||||
},
|
||||
],
|
||||
updatedAt: NOW,
|
||||
};
|
||||
}
|
||||
|
||||
it.layer(NodeServices.layer)("visited thread decider", (it) => {
|
||||
it.effect("stamps a first visit without churning updatedAt", () =>
|
||||
Effect.gen(function* () {
|
||||
const event = yield* decideOrchestrationCommand({
|
||||
command: {
|
||||
type: "thread.visit",
|
||||
commandId: CommandId.make("cmd-visit"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
visitedAt: LATER_VISIT,
|
||||
},
|
||||
readModel: makeReadModel({}),
|
||||
});
|
||||
const events = Array.isArray(event) ? event : [event];
|
||||
expect(events).toHaveLength(1);
|
||||
expect(events[0]?.type).toBe("thread.visited");
|
||||
if (events[0]?.type === "thread.visited") {
|
||||
expect(events[0].payload.lastVisitedAt).toBe(LATER_VISIT);
|
||||
// A visit is passive acknowledgement: ordering must not move.
|
||||
expect(events[0].payload.updatedAt).toBe(NOW);
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("advances a newer visit past an older one", () =>
|
||||
Effect.gen(function* () {
|
||||
const event = yield* decideOrchestrationCommand({
|
||||
command: {
|
||||
type: "thread.visit",
|
||||
commandId: CommandId.make("cmd-visit-advance"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
visitedAt: LATER_VISIT,
|
||||
},
|
||||
readModel: makeReadModel({ lastVisitedAt: EARLIER_VISIT }),
|
||||
});
|
||||
const events = Array.isArray(event) ? event : [event];
|
||||
if (events[0]?.type === "thread.visited") {
|
||||
expect(events[0].payload.lastVisitedAt).toBe(LATER_VISIT);
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("keeps the existing stamp when a raced older visit arrives", () =>
|
||||
Effect.gen(function* () {
|
||||
// Monotonic: a stale visit from a lagging device re-emits the current
|
||||
// value instead of moving the acknowledgement backwards.
|
||||
const event = yield* decideOrchestrationCommand({
|
||||
command: {
|
||||
type: "thread.visit",
|
||||
commandId: CommandId.make("cmd-visit-stale"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
visitedAt: EARLIER_VISIT,
|
||||
},
|
||||
readModel: makeReadModel({ lastVisitedAt: LATER_VISIT }),
|
||||
});
|
||||
const events = Array.isArray(event) ? event : [event];
|
||||
if (events[0]?.type === "thread.visited") {
|
||||
expect(events[0].payload.lastVisitedAt).toBe(LATER_VISIT);
|
||||
expect(events[0].payload.updatedAt).toBe(NOW);
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("accepts a visit on an archived thread", () =>
|
||||
Effect.gen(function* () {
|
||||
// Archived threads stay openable; acknowledging one must not fail.
|
||||
const event = yield* decideOrchestrationCommand({
|
||||
command: {
|
||||
type: "thread.visit",
|
||||
commandId: CommandId.make("cmd-visit-archived"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
visitedAt: LATER_VISIT,
|
||||
},
|
||||
readModel: makeReadModel({ archivedAt: NOW }),
|
||||
});
|
||||
const events = Array.isArray(event) ? event : [event];
|
||||
expect(events[0]?.type).toBe("thread.visited");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("rejects a visit for an unknown thread", () =>
|
||||
Effect.gen(function* () {
|
||||
const error = yield* decideOrchestrationCommand({
|
||||
command: {
|
||||
type: "thread.visit",
|
||||
commandId: CommandId.make("cmd-visit-unknown"),
|
||||
threadId: ThreadId.make("thread-unknown"),
|
||||
visitedAt: LATER_VISIT,
|
||||
},
|
||||
readModel: makeReadModel({}),
|
||||
}).pipe(Effect.flip);
|
||||
expect(error._tag).toBe("OrchestrationCommandInvariantError");
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -30,6 +30,7 @@ import {
|
||||
ThreadUnarchivedPayload,
|
||||
ThreadUnsettledPayload,
|
||||
ThreadUnsnoozedPayload,
|
||||
ThreadVisitedPayload,
|
||||
ThreadRevertedPayload,
|
||||
ThreadSessionSetPayload,
|
||||
ThreadTurnDiffCompletedPayload,
|
||||
@@ -405,6 +406,17 @@ export function projectEvent(
|
||||
})),
|
||||
);
|
||||
|
||||
case "thread.visited":
|
||||
return decodeForEvent(ThreadVisitedPayload, event.payload, event.type, "payload").pipe(
|
||||
Effect.map((payload) => ({
|
||||
...nextBase,
|
||||
threads: updateThread(nextBase.threads, payload.threadId, {
|
||||
lastVisitedAt: payload.lastVisitedAt,
|
||||
updatedAt: payload.updatedAt,
|
||||
}),
|
||||
})),
|
||||
);
|
||||
|
||||
case "thread.pinned":
|
||||
return decodeForEvent(ThreadPinnedPayload, event.payload, event.type, "payload").pipe(
|
||||
Effect.map((payload) => ({
|
||||
|
||||
@@ -96,6 +96,7 @@ projectionRepositoriesLayer("Projection repositories", (it) => {
|
||||
settledAt: null,
|
||||
snoozedUntil: null,
|
||||
snoozedAt: null,
|
||||
lastVisitedAt: null,
|
||||
pinnedAt: null,
|
||||
latestUserMessageAt: null,
|
||||
pendingApprovalCount: 0,
|
||||
@@ -159,6 +160,7 @@ projectionRepositoriesLayer("Projection repositories", (it) => {
|
||||
settledAt: "2026-03-25T00:00:00.000Z",
|
||||
snoozedUntil: "2026-03-26T09:00:00.000Z",
|
||||
snoozedAt: "2026-03-25T00:00:00.000Z",
|
||||
lastVisitedAt: "2026-03-25T00:00:00.000Z",
|
||||
pinnedAt: "2026-03-25T00:00:00.000Z",
|
||||
latestUserMessageAt: null,
|
||||
pendingApprovalCount: 0,
|
||||
@@ -178,6 +180,7 @@ projectionRepositoriesLayer("Projection repositories", (it) => {
|
||||
assert.strictEqual(row.settledAt, "2026-03-25T00:00:00.000Z");
|
||||
assert.strictEqual(row.snoozedUntil, "2026-03-26T09:00:00.000Z");
|
||||
assert.strictEqual(row.snoozedAt, "2026-03-25T00:00:00.000Z");
|
||||
assert.strictEqual(row.lastVisitedAt, "2026-03-25T00:00:00.000Z");
|
||||
assert.strictEqual(row.pinnedAt, "2026-03-25T00:00:00.000Z");
|
||||
|
||||
// Un-settle to the keep-active pin and wake the snooze; confirm the
|
||||
@@ -188,6 +191,7 @@ projectionRepositoriesLayer("Projection repositories", (it) => {
|
||||
settledAt: null,
|
||||
snoozedUntil: null,
|
||||
snoozedAt: null,
|
||||
lastVisitedAt: null,
|
||||
pinnedAt: null,
|
||||
});
|
||||
const repersisted = yield* threads.getById({
|
||||
|
||||
@@ -47,6 +47,7 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
|
||||
settled_at,
|
||||
snoozed_until,
|
||||
snoozed_at,
|
||||
last_visited_at,
|
||||
pinned_at,
|
||||
pin_order_key,
|
||||
title_regeneration_request_id,
|
||||
@@ -74,6 +75,7 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
|
||||
${row.settledAt},
|
||||
${row.snoozedUntil},
|
||||
${row.snoozedAt},
|
||||
${row.lastVisitedAt},
|
||||
${row.pinnedAt},
|
||||
${row.pinOrderKey ?? null},
|
||||
${row.titleRegenerationRequestId ?? null},
|
||||
@@ -101,6 +103,7 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
|
||||
settled_at = excluded.settled_at,
|
||||
snoozed_until = excluded.snoozed_until,
|
||||
snoozed_at = excluded.snoozed_at,
|
||||
last_visited_at = excluded.last_visited_at,
|
||||
pinned_at = excluded.pinned_at,
|
||||
pin_order_key = excluded.pin_order_key,
|
||||
title_regeneration_request_id = excluded.title_regeneration_request_id,
|
||||
@@ -135,6 +138,7 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
|
||||
settled_at AS "settledAt",
|
||||
snoozed_until AS "snoozedUntil",
|
||||
snoozed_at AS "snoozedAt",
|
||||
last_visited_at AS "lastVisitedAt",
|
||||
pinned_at AS "pinnedAt",
|
||||
pin_order_key AS "pinOrderKey",
|
||||
title_regeneration_request_id AS "titleRegenerationRequestId",
|
||||
@@ -171,6 +175,7 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
|
||||
settled_at AS "settledAt",
|
||||
snoozed_until AS "snoozedUntil",
|
||||
snoozed_at AS "snoozedAt",
|
||||
last_visited_at AS "lastVisitedAt",
|
||||
pinned_at AS "pinnedAt",
|
||||
pin_order_key AS "pinOrderKey",
|
||||
title_regeneration_request_id AS "titleRegenerationRequestId",
|
||||
|
||||
@@ -53,6 +53,7 @@ import Migration0037 from "./Migrations/037_ProjectionTurnsKeysetIndex.ts";
|
||||
import Migration0038 from "./Migrations/038_ProjectionThreadsPinOrderKey.ts";
|
||||
import Migration0039 from "./Migrations/039_ProjectionProjectsDefaultThreadEnvMode.ts";
|
||||
import Migration0040 from "./Migrations/040_ProjectionProjectFaviconPath.ts";
|
||||
import Migration0041 from "./Migrations/041_ProjectionThreadsLastVisitedAt.ts";
|
||||
|
||||
/**
|
||||
* Migration loader with all migrations defined inline.
|
||||
@@ -105,6 +106,7 @@ export const migrationEntries = [
|
||||
[38, "ProjectionThreadsPinOrderKey", Migration0038],
|
||||
[39, "ProjectionProjectsDefaultThreadEnvMode", Migration0039],
|
||||
[40, "ProjectionProjectFaviconPath", Migration0040],
|
||||
[41, "ProjectionThreadsLastVisitedAt", Migration0041],
|
||||
] as const;
|
||||
|
||||
export const migrationManifest = migrationEntries.map(([id, name]) => [id, name] as const);
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
|
||||
export default Effect.gen(function* () {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
const columns = yield* sql<{ readonly name: string }>`
|
||||
PRAGMA table_info(projection_threads)
|
||||
`;
|
||||
|
||||
if (!columns.some((column) => column.name === "last_visited_at")) {
|
||||
yield* sql`
|
||||
ALTER TABLE projection_threads
|
||||
ADD COLUMN last_visited_at TEXT
|
||||
`;
|
||||
}
|
||||
});
|
||||
@@ -41,6 +41,7 @@ export const ProjectionThread = Schema.Struct({
|
||||
settledAt: Schema.NullOr(IsoDateTime),
|
||||
snoozedUntil: Schema.NullOr(IsoDateTime),
|
||||
snoozedAt: Schema.NullOr(IsoDateTime),
|
||||
lastVisitedAt: Schema.NullOr(IsoDateTime),
|
||||
pinnedAt: Schema.NullOr(IsoDateTime),
|
||||
pinOrderKey: Schema.optional(Schema.NullOr(Schema.String)),
|
||||
titleRegenerationRequestId: Schema.optional(Schema.NullOr(CommandId)),
|
||||
|
||||
@@ -125,31 +125,6 @@ describe("parseModelsCliOutput", () => {
|
||||
NodeAssert.ok(model.variants);
|
||||
NodeAssert.equal(model.variants!["medium"] !== undefined, true);
|
||||
});
|
||||
|
||||
it("keeps a model whose JSON body has a slash and no interior whitespace", () => {
|
||||
// OpenRouter-style: the model id contains a `/` and no string value has a
|
||||
// space, so the JSON body line itself matches the slug regex. It must still
|
||||
// be treated as the body of the preceding slug, not a new slug.
|
||||
const stdout = [
|
||||
"openrouter/qwen/qwen3-coder",
|
||||
JSON.stringify({
|
||||
id: "qwen/qwen3-coder",
|
||||
providerID: "openrouter",
|
||||
name: "qwen3-coder",
|
||||
status: "active",
|
||||
}),
|
||||
].join("\n");
|
||||
|
||||
const result = parseModelsCliOutput(stdout);
|
||||
NodeAssert.equal(result.providers.size, 1);
|
||||
NodeAssert.deepEqual([...result.connected], ["openrouter"]);
|
||||
const provider = result.providers.get("openrouter")!;
|
||||
NodeAssert.ok(provider);
|
||||
const model = provider.models["qwen/qwen3-coder"]!;
|
||||
NodeAssert.ok(model);
|
||||
NodeAssert.equal(model.id, "qwen/qwen3-coder");
|
||||
NodeAssert.equal(model.providerID, "openrouter");
|
||||
});
|
||||
});
|
||||
|
||||
describe("parseAgentListCliOutput", () => {
|
||||
|
||||
@@ -216,13 +216,7 @@ export function parseModelsCliOutput(stdout: string): {
|
||||
};
|
||||
|
||||
for (const line of lines) {
|
||||
// A model's JSON body is a single `JSON.stringify` line starting with `{`,
|
||||
// while a provider/model slug is a bare `provider/model` header. Only the
|
||||
// latter can be a slug: without this guard a body line with no interior
|
||||
// whitespace and a `/` in one of its values (e.g. an OpenRouter model whose
|
||||
// `id` is `vendor/model`) matches SLUG_LINE_RE, so flushModel runs against
|
||||
// an empty body and the model is silently dropped.
|
||||
const slugMatch = line.trimStart().startsWith("{") ? null : SLUG_LINE_RE.exec(line);
|
||||
const slugMatch = SLUG_LINE_RE.exec(line);
|
||||
if (slugMatch) {
|
||||
flushModel();
|
||||
currentSlug = slugMatch[1]!;
|
||||
|
||||
@@ -10,7 +10,6 @@ import type {
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
import * as ProjectionSnapshotQuery from "../orchestration/Services/ProjectionSnapshotQuery.ts";
|
||||
import * as SourceControlProviderRegistry from "../sourceControl/SourceControlProviderRegistry.ts";
|
||||
import {
|
||||
PullRequestProviderError,
|
||||
type ProviderChangeRequest,
|
||||
@@ -145,16 +144,11 @@ function fakeProvider(
|
||||
function makeService(input: {
|
||||
readonly projects: ReadonlyArray<OrchestrationProjectShell>;
|
||||
readonly providers: ReadonlyArray<PullRequestProviderApi>;
|
||||
readonly resolveHandle?: SourceControlProviderRegistry.SourceControlProviderRegistry["Service"]["resolveHandle"];
|
||||
}) {
|
||||
return PullRequestService.make.pipe(
|
||||
Effect.provide(
|
||||
Layer.mergeAll(
|
||||
Layer.succeed(PullRequestProviderRegistry, fromProviders(input.providers)),
|
||||
Layer.mock(SourceControlProviderRegistry.SourceControlProviderRegistry)({
|
||||
resolveHandle:
|
||||
input.resolveHandle ?? (() => Effect.die("Unexpected provider refinement")),
|
||||
}),
|
||||
Layer.mock(ProjectionSnapshotQuery.ProjectionSnapshotQuery)({
|
||||
getShellSnapshot: () =>
|
||||
Effect.succeed({
|
||||
@@ -169,110 +163,6 @@ function makeService(input: {
|
||||
);
|
||||
}
|
||||
|
||||
it.effect("refines unknown self-hosted GitLab projects before listing merge requests", () =>
|
||||
Effect.gen(function* () {
|
||||
let refinementCalls = 0;
|
||||
const selfHosted = project({
|
||||
id: "p1",
|
||||
title: "self-hosted",
|
||||
workspaceRoot: "/gitlab",
|
||||
repository: "group/project",
|
||||
provider: "unknown",
|
||||
host: "code.example.test",
|
||||
});
|
||||
const service = yield* makeService({
|
||||
projects: [
|
||||
selfHosted,
|
||||
{ ...selfHosted, id: "p2" as ProjectId, workspaceRoot: "/gitlab-worktree" },
|
||||
],
|
||||
providers: [fakeProvider("gitlab")],
|
||||
resolveHandle: ({ context }) => {
|
||||
refinementCalls += 1;
|
||||
assert.strictEqual(context?.remoteUrl, "https://code.example.test/group/project.git");
|
||||
return Effect.succeed({
|
||||
context: { ...context!, provider: { ...context!.provider, kind: "gitlab" } },
|
||||
provider: undefined as never,
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
const result = yield* service.list({ state: "open" });
|
||||
|
||||
assert.strictEqual(refinementCalls, 1);
|
||||
assert.strictEqual(result.providers[0]?.host, "code.example.test");
|
||||
assert.strictEqual(result.providers[0]?.kind, "gitlab");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("derives a legacy repository host after refining its provider", () =>
|
||||
Effect.gen(function* () {
|
||||
const current = project({
|
||||
id: "p1",
|
||||
title: "legacy self-hosted",
|
||||
workspaceRoot: "/gitlab",
|
||||
repository: "group/project",
|
||||
provider: "unknown",
|
||||
host: "code.example.test",
|
||||
});
|
||||
const identity = current.repositoryIdentity!;
|
||||
// Persisted identities from before canonicalKey existed are still accepted at runtime.
|
||||
const legacy = {
|
||||
...current,
|
||||
repositoryIdentity: {
|
||||
locator: identity.locator,
|
||||
provider: identity.provider,
|
||||
displayName: identity.displayName,
|
||||
},
|
||||
} as unknown as OrchestrationProjectShell;
|
||||
const service = yield* makeService({
|
||||
projects: [legacy],
|
||||
providers: [fakeProvider("gitlab")],
|
||||
resolveHandle: ({ context }) =>
|
||||
Effect.succeed({
|
||||
context: { ...context!, provider: { ...context!.provider, kind: "gitlab" } },
|
||||
provider: undefined as never,
|
||||
}),
|
||||
});
|
||||
|
||||
const result = yield* service.list({ state: "open", host: "gitlab" });
|
||||
|
||||
assert.strictEqual(result.providers[0]?.host, "gitlab");
|
||||
assert.strictEqual(result.providers[0]?.kind, "gitlab");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("tries another checkout when provider refinement remains unknown", () =>
|
||||
Effect.gen(function* () {
|
||||
const asked: string[] = [];
|
||||
const selfHosted = project({
|
||||
id: "p1",
|
||||
title: "self-hosted",
|
||||
workspaceRoot: "/gone",
|
||||
repository: "group/project",
|
||||
provider: "unknown",
|
||||
host: "code.example.test",
|
||||
});
|
||||
const service = yield* makeService({
|
||||
projects: [selfHosted, { ...selfHosted, id: "p2" as ProjectId, workspaceRoot: "/healthy" }],
|
||||
providers: [fakeProvider("gitlab")],
|
||||
resolveHandle: ({ cwd, context }) => {
|
||||
asked.push(cwd);
|
||||
return cwd === "/gone"
|
||||
? Effect.succeed({ context: context!, provider: undefined as never })
|
||||
: Effect.succeed({
|
||||
context: { ...context!, provider: { ...context!.provider, kind: "gitlab" } },
|
||||
provider: undefined as never,
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
const result = yield* service.list({ state: "open" });
|
||||
|
||||
assert.deepStrictEqual(asked, ["/gone", "/healthy"]);
|
||||
assert.strictEqual(result.providers[0]?.kind, "gitlab");
|
||||
}),
|
||||
);
|
||||
|
||||
/** A row as a host that reads several repositories at once hands it over. */
|
||||
function batchedChangeRequest(number: number, repository: string, updatedAt: string) {
|
||||
return { ...changeRequest(number, updatedAt), repository };
|
||||
|
||||
@@ -36,13 +36,10 @@ import {
|
||||
type PullRequestSubmitReviewInput,
|
||||
type PullRequestThreadReplyInput,
|
||||
type PullRequestThreadResolutionInput,
|
||||
type SourceControlProviderInfo,
|
||||
type SourceControlProviderKind,
|
||||
} from "@t3tools/contracts";
|
||||
import { detectSourceControlProviderFromRemoteUrl } from "@t3tools/shared/sourceControl";
|
||||
|
||||
import * as ProjectionSnapshotQuery from "../orchestration/Services/ProjectionSnapshotQuery.ts";
|
||||
import * as SourceControlProviderRegistry from "../sourceControl/SourceControlProviderRegistry.ts";
|
||||
import {
|
||||
type ProviderChangeRequest,
|
||||
type ProviderListCursor,
|
||||
@@ -363,65 +360,6 @@ function repositoryIdentityOf(project: OrchestrationProjectShell): string | null
|
||||
export const make = Effect.gen(function* () {
|
||||
const registry = yield* PullRequestProviderRegistry;
|
||||
const projections = yield* ProjectionSnapshotQuery.ProjectionSnapshotQuery;
|
||||
const sourceControlProviders = yield* SourceControlProviderRegistry.SourceControlProviderRegistry;
|
||||
|
||||
const refineUnknownProjectKinds = (
|
||||
projects: ReadonlyArray<OrchestrationProjectShell>,
|
||||
filter: Pick<PullRequestListInput, "projectId" | "host">,
|
||||
) => {
|
||||
type RefinementCandidate = {
|
||||
readonly project: OrchestrationProjectShell;
|
||||
readonly provider: SourceControlProviderInfo;
|
||||
readonly remoteName: string;
|
||||
readonly remoteUrl: string;
|
||||
};
|
||||
const refinements = new Map<string, RefinementCandidate[]>();
|
||||
for (const project of projects) {
|
||||
if (filter.projectId !== undefined && project.id !== filter.projectId) continue;
|
||||
const identity = project.repositoryIdentity;
|
||||
if (identity?.provider !== "unknown" || repositoryIdentityOf(project) === null) continue;
|
||||
const host = pullRequestHostOf(identity, "unknown");
|
||||
// A legacy identity has no canonical host until its provider is refined, so it must reach
|
||||
// the refinement before a host filter can decide whether it belongs in the result.
|
||||
if (filter.host !== undefined && host !== "unknown" && host !== filter.host.toLowerCase()) {
|
||||
continue;
|
||||
}
|
||||
const { remoteName, remoteUrl } = identity.locator;
|
||||
const provider = detectSourceControlProviderFromRemoteUrl(remoteUrl);
|
||||
if (provider !== null) {
|
||||
const candidates = refinements.get(provider.baseUrl);
|
||||
const candidate = { project, provider, remoteName, remoteUrl };
|
||||
if (candidates === undefined) refinements.set(provider.baseUrl, [candidate]);
|
||||
else candidates.push(candidate);
|
||||
}
|
||||
}
|
||||
|
||||
return Effect.forEach(
|
||||
refinements,
|
||||
([baseUrl, candidates]) =>
|
||||
Effect.firstSuccessOf(
|
||||
candidates.map(({ project, provider, remoteName, remoteUrl }) =>
|
||||
Effect.suspend(() =>
|
||||
sourceControlProviders.resolveHandle({
|
||||
cwd: project.workspaceRoot,
|
||||
context: { provider, remoteName, remoteUrl },
|
||||
}),
|
||||
).pipe(
|
||||
Effect.flatMap((handle) => {
|
||||
const kind = handle.context?.provider.kind;
|
||||
return kind === undefined || kind === "unknown"
|
||||
? Effect.fail(undefined)
|
||||
: Effect.succeed(kind);
|
||||
}),
|
||||
),
|
||||
),
|
||||
).pipe(
|
||||
Effect.map((kind) => [baseUrl, kind] as const),
|
||||
Effect.orElseSucceed(() => [baseUrl, "unknown"] as const),
|
||||
),
|
||||
{ concurrency: REPOSITORY_CONCURRENCY },
|
||||
).pipe(Effect.map((resolved) => new Map(resolved)));
|
||||
};
|
||||
|
||||
const listWorkspaceProjects = (
|
||||
filter: Pick<PullRequestListInput, "projectId" | "host">,
|
||||
@@ -435,12 +373,7 @@ export const make = Effect.gen(function* () {
|
||||
cause: error,
|
||||
}),
|
||||
),
|
||||
Effect.flatMap((snapshot) =>
|
||||
refineUnknownProjectKinds(snapshot.projects, filter).pipe(
|
||||
Effect.map((refinedKinds) => ({ refinedKinds, snapshot })),
|
||||
),
|
||||
),
|
||||
Effect.map(({ refinedKinds, snapshot }) => {
|
||||
Effect.map((snapshot) => {
|
||||
const supported: SupportedProject[] = [];
|
||||
const unimplemented = new Map<
|
||||
string,
|
||||
@@ -450,18 +383,15 @@ export const make = Effect.gen(function* () {
|
||||
const seen = new Set<string>();
|
||||
for (const project of snapshot.projects) {
|
||||
if (filter.projectId !== undefined && project.id !== filter.projectId) continue;
|
||||
const identity = project.repositoryIdentity;
|
||||
let kind = identity?.provider as SourceControlProviderKind | undefined;
|
||||
const kind = project.repositoryIdentity?.provider as
|
||||
| SourceControlProviderKind
|
||||
| undefined;
|
||||
const repository = repositoryIdentityOf(project);
|
||||
if (!identity || kind === undefined || repository === null) continue;
|
||||
if (kind === undefined || repository === null) continue;
|
||||
// Worktrees of one repository are separate projects; reading the remote once keeps
|
||||
// the page from repeating every change request per local checkout. The host is part
|
||||
// of the key, so the same `owner/repo` on two hosts stays two repositories.
|
||||
if (kind === "unknown") {
|
||||
const provider = detectSourceControlProviderFromRemoteUrl(identity.locator.remoteUrl);
|
||||
kind = provider === null ? kind : (refinedKinds.get(provider.baseUrl) ?? kind);
|
||||
}
|
||||
const host = pullRequestHostOf(identity, kind);
|
||||
const host = pullRequestHostOf(project.repositoryIdentity, kind);
|
||||
if (filter.host !== undefined && host !== filter.host.toLowerCase()) continue;
|
||||
const api = registry.get(kind);
|
||||
// Recorded before the de-duplication below, so the viewer lookup keeps the alternates
|
||||
|
||||
@@ -4,7 +4,7 @@ import {
|
||||
HostProcessEnvironment,
|
||||
HostProcessPlatform,
|
||||
} from "@t3tools/shared/hostProcess";
|
||||
import { afterEach, assert, describe, expect, it, vi } from "@effect/vitest";
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
|
||||
@@ -12,36 +12,6 @@ import { ServerConfig } from "../config.ts";
|
||||
import * as ResourceMonitorBinary from "./ResourceMonitorBinary.ts";
|
||||
|
||||
describe("ResourceMonitorBinary", () => {
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it.effect("skips Linux libc detection on Windows", () =>
|
||||
Effect.gen(function* () {
|
||||
const getReport = vi.spyOn(process.report, "getReport").mockImplementation(() => {
|
||||
throw new Error("Linux libc detection must not run on Windows");
|
||||
});
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-resource-monitor-binary-",
|
||||
});
|
||||
const binaryPath = `${baseDir}/t3-resource-monitor.exe`;
|
||||
yield* fileSystem.writeFileString(binaryPath, "binary");
|
||||
|
||||
const service = yield* ResourceMonitorBinary.make().pipe(
|
||||
Effect.provide(ServerConfig.layerTest(process.cwd(), baseDir)),
|
||||
Effect.provideService(HostProcessPlatform, "win32"),
|
||||
Effect.provideService(HostProcessArchitecture, "arm64"),
|
||||
Effect.provideService(HostProcessEnvironment, {
|
||||
T3CODE_RESOURCE_MONITOR_PATH: binaryPath,
|
||||
}),
|
||||
);
|
||||
|
||||
assert.equal(yield* service.resolve, binaryPath);
|
||||
expect(getReport).not.toHaveBeenCalled();
|
||||
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
it.effect("resolves an executable override", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
|
||||
@@ -106,7 +106,7 @@ export function resourceMonitorPlatformKey(
|
||||
export function resourceMonitorRustTarget(
|
||||
platform: NodeJS.Platform,
|
||||
architecture: NodeJS.Architecture,
|
||||
linuxLibc?: ResourceMonitorLinuxLibc,
|
||||
linuxLibc: ResourceMonitorLinuxLibc,
|
||||
): string | undefined {
|
||||
if (platform === "darwin") {
|
||||
return architecture === "arm64"
|
||||
@@ -142,7 +142,7 @@ export const make = Effect.fn("resourceTelemetry.resourceMonitorBinary.make")(fu
|
||||
const platform = yield* HostProcessPlatform;
|
||||
const architecture = yield* HostProcessArchitecture;
|
||||
const environment = yield* HostProcessEnvironment;
|
||||
const linuxLibc = platform === "linux" ? yield* ResourceMonitorHostLinuxLibc : undefined;
|
||||
const linuxLibc = yield* ResourceMonitorHostLinuxLibc;
|
||||
const executableName = binaryName(platform);
|
||||
const platformKey = resourceMonitorPlatformKey(platform, architecture);
|
||||
const rustTarget = resourceMonitorRustTarget(platform, architecture, linuxLibc);
|
||||
|
||||
@@ -435,7 +435,6 @@ const commandReadinessLayer = HttpRouter.middleware(
|
||||
const PullRequestServiceLive = PullRequestService.layer.pipe(
|
||||
// One registry entry per supported host; the service only knows the registry.
|
||||
Layer.provide(PullRequestProviderRegistry.layer),
|
||||
Layer.provide(SourceControlProviderRegistryLayerLive),
|
||||
Layer.provide(VcsProcess.layer),
|
||||
);
|
||||
|
||||
|
||||
@@ -203,38 +203,6 @@ self-hosted.example.test
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("refines the caller-selected remote instead of choosing another configured remote", () =>
|
||||
Effect.gen(function* () {
|
||||
const registry = yield* makeRegistry({
|
||||
remotes: [{ name: "origin", url: "[email protected]:fork/project.git" }],
|
||||
process: {
|
||||
run: () =>
|
||||
Effect.succeed(
|
||||
processOutput(`self-hosted.example.test
|
||||
✓ Logged in to self-hosted.example.test as gitlab-user
|
||||
`),
|
||||
),
|
||||
},
|
||||
});
|
||||
|
||||
const handle = yield* registry.resolveHandle({
|
||||
cwd: "/repo",
|
||||
context: {
|
||||
provider: {
|
||||
kind: "unknown",
|
||||
name: "self-hosted.example.test",
|
||||
baseUrl: "https://self-hosted.example.test",
|
||||
},
|
||||
remoteName: "upstream",
|
||||
remoteUrl: "https://self-hosted.example.test/group/project.git",
|
||||
},
|
||||
});
|
||||
|
||||
assert.strictEqual(handle.context?.provider.kind, "gitlab");
|
||||
assert.strictEqual(handle.context?.remoteName, "upstream");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("routes authenticated self-hosted GitLab remotes on non-standard ports", () =>
|
||||
Effect.gen(function* () {
|
||||
const registry = yield* makeRegistry({
|
||||
|
||||
@@ -50,7 +50,6 @@ export class SourceControlProviderRegistry extends Context.Service<
|
||||
>;
|
||||
readonly resolveHandle: (input: {
|
||||
readonly cwd: string;
|
||||
readonly context?: SourceControlProvider.SourceControlProviderContext;
|
||||
}) => Effect.Effect<SourceControlProviderHandle, SourceControlProviderError>;
|
||||
readonly resolve: (input: {
|
||||
readonly cwd: string;
|
||||
@@ -255,15 +254,7 @@ export const makeWithProviders = Effect.fn("makeSourceControlProviderRegistryWit
|
||||
});
|
||||
|
||||
const resolveHandle: SourceControlProviderRegistry["Service"]["resolveHandle"] = (input) =>
|
||||
(input.context === undefined
|
||||
? Cache.get(providerContextCache, input.cwd)
|
||||
: refineUnknownRemoteProvider({
|
||||
specs: discoverySpecs,
|
||||
process,
|
||||
cwd: input.cwd,
|
||||
context: input.context,
|
||||
})
|
||||
).pipe(
|
||||
Cache.get(providerContextCache, input.cwd).pipe(
|
||||
Effect.map((context) => {
|
||||
const kind = context?.provider.kind ?? "unknown";
|
||||
const provider = providers.get(kind) ?? unsupportedProvider(kind);
|
||||
|
||||
@@ -33,7 +33,6 @@ const testLayer = NodePtyAdapter.layer.pipe(
|
||||
|
||||
it.effect("spawns through the public adapter with the provided host references", () =>
|
||||
Effect.gen(function* () {
|
||||
spawn.mockClear();
|
||||
const adapter = yield* PtyAdapter.PtyAdapter;
|
||||
const process = yield* adapter.spawn({
|
||||
shell: "powershell.exe",
|
||||
@@ -53,35 +52,8 @@ it.effect("spawns through the public adapter with the provided host references",
|
||||
cwd: "C:\\workspace",
|
||||
cols: 120,
|
||||
rows: 40,
|
||||
env: { TERM: "xterm-256color" },
|
||||
name: "xterm-256color",
|
||||
},
|
||||
]);
|
||||
}).pipe(Effect.provide(testLayer)),
|
||||
);
|
||||
|
||||
it.effect("preserves a caller-provided TERM in the spawn env on win32", () =>
|
||||
Effect.gen(function* () {
|
||||
spawn.mockClear();
|
||||
const adapter = yield* PtyAdapter.PtyAdapter;
|
||||
yield* adapter.spawn({
|
||||
shell: "powershell.exe",
|
||||
cwd: "C:\\workspace",
|
||||
cols: 80,
|
||||
rows: 24,
|
||||
env: { TERM: "xterm-direct" },
|
||||
});
|
||||
|
||||
assert.equal(spawn.mock.calls.length, 1);
|
||||
assert.deepEqual(spawn.mock.calls[0], [
|
||||
"powershell.exe",
|
||||
[],
|
||||
{
|
||||
cwd: "C:\\workspace",
|
||||
cols: 80,
|
||||
rows: 24,
|
||||
env: { TERM: "xterm-direct" },
|
||||
name: "xterm-256color",
|
||||
env: {},
|
||||
name: "xterm-color",
|
||||
},
|
||||
]);
|
||||
}).pipe(Effect.provide(testLayer)),
|
||||
|
||||
@@ -141,21 +141,14 @@ export const make = Effect.fn("NodePtyAdapter.make")(function* (
|
||||
return PtyAdapter.PtyAdapter.of({
|
||||
spawn: Effect.fn("NodePtyAdapter.spawn")(function* (input) {
|
||||
yield* ensureNodePtySpawnHelperExecutableCached;
|
||||
// node-pty only writes `name` into the child's TERM on the Unix path;
|
||||
// the ConPTY path leaves the environment untouched, so Windows children
|
||||
// inherit a missing or 16-color TERM unless it is set here.
|
||||
const env =
|
||||
platform === "win32" && input.env["TERM"] === undefined
|
||||
? { ...input.env, TERM: "xterm-256color" }
|
||||
: input.env;
|
||||
const ptyProcess = yield* Effect.try({
|
||||
try: () =>
|
||||
nodePty.spawn(input.shell, input.args ?? [], {
|
||||
cwd: input.cwd,
|
||||
cols: input.cols,
|
||||
rows: input.rows,
|
||||
env,
|
||||
name: "xterm-256color",
|
||||
env: input.env,
|
||||
name: platform === "win32" ? "xterm-color" : "xterm-256color",
|
||||
}),
|
||||
catch: (cause) =>
|
||||
new PtyAdapter.PtySpawnError({
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/**
|
||||
* UsageService - scans provider transcripts and returns priced usage buckets.
|
||||
* UsageService - scans provider transcripts and returns priced daily usage.
|
||||
*
|
||||
* The scan reads the provider CLIs' own session files rather than T3 Code's
|
||||
* orchestration projections, so usage covers turns driven outside T3 Code too.
|
||||
@@ -64,7 +64,6 @@ const RATES_TTL_MS = 24 * 60 * 60 * 1000;
|
||||
* last write lands just before local midnight on the window's first day.
|
||||
*/
|
||||
const MTIME_SLACK_MS = 36 * 60 * 60 * 1000;
|
||||
const MAX_HOURLY_WINDOW_MS = 24 * 60 * 60 * 1000;
|
||||
|
||||
/** Longest window the UI offers, plus slack. Older entries are pruned. */
|
||||
const CACHE_RETENTION_DAYS = 90;
|
||||
@@ -298,30 +297,6 @@ export const make = Effect.gen(function* () {
|
||||
});
|
||||
}
|
||||
|
||||
let hourlyWindow: { readonly sinceTimeMs: number; readonly untilTimeMs: number } | null = null;
|
||||
if (input.resolution === "hour") {
|
||||
const sinceTime =
|
||||
input.sinceTime === undefined ? Option.none() : DateTime.make(input.sinceTime);
|
||||
const untilTime =
|
||||
input.untilTime === undefined ? Option.none() : DateTime.make(input.untilTime);
|
||||
if (Option.isNone(sinceTime) || Option.isNone(untilTime)) {
|
||||
return yield* new UsageReadError({
|
||||
reason: "invalidWindow",
|
||||
detail: "Hourly usage requires valid sinceTime and untilTime instants",
|
||||
});
|
||||
}
|
||||
const sinceTimeMs = DateTime.toEpochMillis(sinceTime.value);
|
||||
const untilTimeMs = DateTime.toEpochMillis(untilTime.value);
|
||||
const durationMs = untilTimeMs - sinceTimeMs;
|
||||
if (durationMs <= 0 || durationMs > MAX_HOURLY_WINDOW_MS) {
|
||||
return yield* new UsageReadError({
|
||||
reason: "invalidWindow",
|
||||
detail: "Hourly usage window must be greater than zero and at most 24 hours",
|
||||
});
|
||||
}
|
||||
hourlyWindow = { sinceTimeMs, untilTimeMs };
|
||||
}
|
||||
|
||||
const startedAtMs = yield* Clock.currentTimeMillis;
|
||||
yield* ensureRates();
|
||||
yield* ensureScanCacheLoaded;
|
||||
@@ -337,15 +312,12 @@ export const make = Effect.gen(function* () {
|
||||
detail: `sinceDay '${input.sinceDay}' is not a valid date`,
|
||||
});
|
||||
}
|
||||
const windowStartMs =
|
||||
(hourlyWindow?.sinceTimeMs ?? DateTime.toEpochMillis(windowStart.value)) - MTIME_SLACK_MS;
|
||||
const windowStartMs = DateTime.toEpochMillis(windowStart.value) - MTIME_SLACK_MS;
|
||||
|
||||
const aggregator = new UsageAggregator({
|
||||
timeZone: input.timeZone,
|
||||
sinceDay: input.sinceDay,
|
||||
untilDay: input.untilDay,
|
||||
resolution: input.resolution ?? "day",
|
||||
...hourlyWindow,
|
||||
rates,
|
||||
});
|
||||
|
||||
|
||||
@@ -36,24 +36,11 @@ function record(overrides: Partial<UsageRecord> = {}): UsageRecord {
|
||||
};
|
||||
}
|
||||
|
||||
function aggregate(
|
||||
records: readonly UsageRecord[],
|
||||
timeZone = "UTC",
|
||||
resolution: "day" | "hour" = "day",
|
||||
) {
|
||||
const hourlyBounds =
|
||||
resolution === "hour"
|
||||
? {
|
||||
sinceTimeMs: Date.parse("2026-08-06T04:37:00.000Z"),
|
||||
untilTimeMs: Date.parse("2026-08-07T04:37:00.000Z"),
|
||||
}
|
||||
: {};
|
||||
function aggregate(records: readonly UsageRecord[], timeZone = "UTC") {
|
||||
const aggregator = new UsageAggregator({
|
||||
timeZone,
|
||||
sinceDay: "2026-08-01",
|
||||
untilDay: "2026-08-31",
|
||||
resolution,
|
||||
...hourlyBounds,
|
||||
rates,
|
||||
});
|
||||
for (const item of records) aggregator.add(item);
|
||||
@@ -61,19 +48,6 @@ function aggregate(
|
||||
}
|
||||
|
||||
describe("UsageAggregator", () => {
|
||||
it("requires exact bounds for hourly aggregation", () => {
|
||||
expect(
|
||||
() =>
|
||||
new UsageAggregator({
|
||||
timeZone: "UTC",
|
||||
sinceDay: "2026-08-01",
|
||||
untilDay: "2026-08-31",
|
||||
resolution: "hour",
|
||||
rates,
|
||||
}),
|
||||
).toThrow("requires exact time bounds");
|
||||
});
|
||||
|
||||
it("keeps only the first record for a repeated dedupe key", () => {
|
||||
const result = aggregate([
|
||||
record({ dedupeKey: "msg_1:" }),
|
||||
@@ -102,52 +76,6 @@ describe("UsageAggregator", () => {
|
||||
expect(losAngeles.buckets[0]?.day).toBe("2026-08-06");
|
||||
});
|
||||
|
||||
it("splits an hourly request into fixed buckets anchored to its exact start", () => {
|
||||
const result = aggregate(
|
||||
[
|
||||
record({ timestampMs: Date.parse("2026-08-07T02:40:13.944Z") }),
|
||||
record({ timestampMs: Date.parse("2026-08-07T03:40:13.944Z") }),
|
||||
],
|
||||
"America/Los_Angeles",
|
||||
"hour",
|
||||
);
|
||||
|
||||
expect(result.buckets.map((bucket) => [bucket.day, bucket.hourStart])).toEqual([
|
||||
["2026-08-06", "2026-08-07T02:37:00.000Z"],
|
||||
["2026-08-06", "2026-08-07T03:37:00.000Z"],
|
||||
]);
|
||||
});
|
||||
|
||||
it("uses an inclusive start and exclusive end for rolling windows", () => {
|
||||
const result = aggregate(
|
||||
[
|
||||
record({ timestampMs: Date.parse("2026-08-06T04:36:59.999Z") }),
|
||||
record({ timestampMs: Date.parse("2026-08-06T04:37:00.000Z") }),
|
||||
record({ timestampMs: Date.parse("2026-08-07T04:36:59.999Z") }),
|
||||
record({ timestampMs: Date.parse("2026-08-07T04:37:00.000Z") }),
|
||||
],
|
||||
"UTC",
|
||||
"hour",
|
||||
);
|
||||
|
||||
expect(result.outOfWindow).toBe(2);
|
||||
expect(result.buckets.map((bucket) => bucket.hourStart)).toEqual([
|
||||
"2026-08-06T04:37:00.000Z",
|
||||
"2026-08-07T03:37:00.000Z",
|
||||
]);
|
||||
});
|
||||
|
||||
it("keeps daily payloads collapsed when hourly resolution is not requested", () => {
|
||||
const result = aggregate([
|
||||
record({ timestampMs: Date.parse("2026-08-07T04:05:13.944Z") }),
|
||||
record({ timestampMs: Date.parse("2026-08-07T05:05:13.944Z") }),
|
||||
]);
|
||||
|
||||
expect(result.buckets).toHaveLength(1);
|
||||
expect(result.buckets[0]?.hourStart).toBeUndefined();
|
||||
expect(result.buckets[0]?.records).toBe(2);
|
||||
});
|
||||
|
||||
it("prices against the rate table", () => {
|
||||
const result = aggregate([record()]);
|
||||
|
||||
|
||||
Binary file not shown.
@@ -1001,23 +1001,6 @@ it.layer(TestLayer)("GitVcsDriver core integration", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("reports remote status on unborn HEAD without failing", () =>
|
||||
Effect.gen(function* () {
|
||||
const cwd = yield* makeTmpDir();
|
||||
const driver = yield* GitVcsDriver.GitVcsDriver;
|
||||
yield* driver.initRepo({ cwd });
|
||||
const initialBranch = yield* git(cwd, ["symbolic-ref", "--short", "HEAD"]);
|
||||
|
||||
const status = yield* driver.statusDetailsRemote(cwd, { refreshUpstream: false });
|
||||
|
||||
assert.equal(status.isRepo, true);
|
||||
assert.equal(status.branch, initialBranch);
|
||||
assert.equal(status.hasUpstream, false);
|
||||
assert.equal(status.aheadCount, 0);
|
||||
assert.equal(status.behindCount, 0);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("can read cached remote divergence without fetching upstream", () =>
|
||||
Effect.gen(function* () {
|
||||
const cwd = yield* makeTmpDir();
|
||||
|
||||
@@ -1477,35 +1477,25 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
|
||||
if (branchResult === null) {
|
||||
return NON_REPOSITORY_REMOTE_STATUS_DETAILS;
|
||||
}
|
||||
let branch: string | null;
|
||||
if (branchResult.exitCode !== 0) {
|
||||
if (isNonRepositoryGitStderr(branchResult.stderr)) {
|
||||
return NON_REPOSITORY_REMOTE_STATUS_DETAILS;
|
||||
}
|
||||
if (!isUnbornHeadStderr(branchResult.stderr)) {
|
||||
return yield* new GitCommandError({
|
||||
...gitCommandContext({
|
||||
operation: "GitVcsDriver.statusDetailsRemote.branch",
|
||||
cwd,
|
||||
args: ["rev-parse", "--abbrev-ref", "HEAD"],
|
||||
}),
|
||||
detail: "Git branch lookup failed.",
|
||||
exitCode: branchResult.exitCode,
|
||||
stdoutLength: branchResult.stdout.length,
|
||||
stderrLength: branchResult.stderr.length,
|
||||
});
|
||||
}
|
||||
|
||||
const branchValue = yield* runGitStdout(
|
||||
"GitVcsDriver.statusDetailsRemote.unbornBranch",
|
||||
cwd,
|
||||
["symbolic-ref", "--quiet", "--short", "HEAD"],
|
||||
);
|
||||
branch = branchValue.trim() || null;
|
||||
} else {
|
||||
const branchValue = branchResult.stdout.trim();
|
||||
branch = branchValue.length > 0 && branchValue !== "HEAD" ? branchValue : null;
|
||||
return yield* new GitCommandError({
|
||||
...gitCommandContext({
|
||||
operation: "GitVcsDriver.statusDetailsRemote.branch",
|
||||
cwd,
|
||||
args: ["rev-parse", "--abbrev-ref", "HEAD"],
|
||||
}),
|
||||
detail: "Git branch lookup failed.",
|
||||
exitCode: branchResult.exitCode,
|
||||
stdoutLength: branchResult.stdout.length,
|
||||
stderrLength: branchResult.stderr.length,
|
||||
});
|
||||
}
|
||||
|
||||
const branchValue = branchResult.stdout.trim();
|
||||
const branch = branchValue.length > 0 && branchValue !== "HEAD" ? branchValue : null;
|
||||
const upstream = yield* resolveCurrentUpstream(cwd);
|
||||
const upstreamRef = upstream?.upstreamRef ?? null;
|
||||
let aheadCount = 0;
|
||||
|
||||
+55
-72
@@ -35,16 +35,16 @@
|
||||
// app colors before React mounts.
|
||||
const DEFAULT_THEME_PALETTES = {
|
||||
light: {
|
||||
background: "oklch(0.982446 0.010114 325.653)",
|
||||
foreground: "oklch(0.325698 0.116116 325.037)",
|
||||
accent: "oklch(0.591646 0.217985 0.584)",
|
||||
chrome: "oklch(0.982446 0.010114 325.653)",
|
||||
background: "#fdf7fd",
|
||||
foreground: "#501854",
|
||||
accent: "#db2777",
|
||||
chrome: "#fdf7fd",
|
||||
},
|
||||
dark: {
|
||||
background: "oklch(0.22813 0.020366 307.469)",
|
||||
foreground: "oklch(0.980735 0.004092 301.426)",
|
||||
accent: "oklch(0.460685 0.185347 4.099)",
|
||||
chrome: "oklch(0.22813 0.020366 307.469)",
|
||||
background: "#1f1a24",
|
||||
foreground: "#f9f8fb",
|
||||
accent: "#a3004c",
|
||||
chrome: "#1f1a24",
|
||||
},
|
||||
};
|
||||
// Keep this small boot-time copy in sync with the built-in palettes so
|
||||
@@ -52,72 +52,72 @@
|
||||
const BUILT_IN_THEME_PALETTES = {
|
||||
"t3-chat": {
|
||||
light: {
|
||||
background: "oklch(0.982446 0.010114 325.653)",
|
||||
foreground: "oklch(0.325698 0.116116 325.037)",
|
||||
accent: "oklch(0.591646 0.217985 0.584)",
|
||||
chrome: "oklch(0.982446 0.010114 325.653)",
|
||||
background: "#fdf7fd",
|
||||
foreground: "#501854",
|
||||
accent: "#db2777",
|
||||
chrome: "#fdf7fd",
|
||||
},
|
||||
dark: {
|
||||
background: "oklch(0.22813 0.020366 307.469)",
|
||||
foreground: "oklch(0.980735 0.004092 301.426)",
|
||||
accent: "oklch(0.460685 0.185347 4.099)",
|
||||
chrome: "oklch(0.22813 0.020366 307.469)",
|
||||
background: "#1f1a24",
|
||||
foreground: "#f9f8fb",
|
||||
accent: "#a3004c",
|
||||
chrome: "#1f1a24",
|
||||
},
|
||||
},
|
||||
grove: {
|
||||
light: {
|
||||
background: "oklch(0.972369 0.005497 157.15)",
|
||||
foreground: "oklch(0.222003 0.03479 328.979)",
|
||||
accent: "oklch(0.523295 0.112292 158.089)",
|
||||
chrome: "oklch(0.972369 0.005497 157.15)",
|
||||
background: "#f3f7f4",
|
||||
foreground: "#241523",
|
||||
accent: "#1b7d50",
|
||||
chrome: "#f3f7f4",
|
||||
},
|
||||
dark: {
|
||||
background: "oklch(0.260865 0.02152 162.75)",
|
||||
foreground: "oklch(0.990339 0.008411 325.64)",
|
||||
accent: "oklch(0.796228 0.133058 157.319)",
|
||||
chrome: "oklch(0.260865 0.02152 162.75)",
|
||||
background: "#1b2821",
|
||||
foreground: "#fffaff",
|
||||
accent: "#69d69a",
|
||||
chrome: "#1b2821",
|
||||
},
|
||||
},
|
||||
ocean: {
|
||||
light: {
|
||||
background: "oklch(0.974199 0.002856 241.597)",
|
||||
foreground: "oklch(0.222003 0.03479 328.979)",
|
||||
accent: "oklch(0.536684 0.120219 247.01)",
|
||||
chrome: "oklch(0.974199 0.002856 241.597)",
|
||||
background: "#f5f7f8",
|
||||
foreground: "#241523",
|
||||
accent: "#2672af",
|
||||
chrome: "#f5f7f8",
|
||||
},
|
||||
dark: {
|
||||
background: "oklch(0.242641 0.024125 250.573)",
|
||||
foreground: "oklch(0.990339 0.008411 325.64)",
|
||||
accent: "oklch(0.758933 0.105833 241.548)",
|
||||
chrome: "oklch(0.242641 0.024125 250.573)",
|
||||
background: "#17212b",
|
||||
foreground: "#fffaff",
|
||||
accent: "#70b9ee",
|
||||
chrome: "#17212b",
|
||||
},
|
||||
},
|
||||
ember: {
|
||||
light: {
|
||||
background: "oklch(0.976527 0.002685 60.725)",
|
||||
foreground: "oklch(0.222003 0.03479 328.979)",
|
||||
accent: "oklch(0.552831 0.129438 44.656)",
|
||||
chrome: "oklch(0.976527 0.002685 60.725)",
|
||||
background: "#f9f7f5",
|
||||
foreground: "#241523",
|
||||
accent: "#ae552a",
|
||||
chrome: "#f9f7f5",
|
||||
},
|
||||
dark: {
|
||||
background: "oklch(0.245899 0.019144 42.044)",
|
||||
foreground: "oklch(0.990339 0.008411 325.64)",
|
||||
accent: "oklch(0.762174 0.124117 52.082)",
|
||||
chrome: "oklch(0.245899 0.019144 42.044)",
|
||||
background: "#291e1a",
|
||||
foreground: "#fffaff",
|
||||
accent: "#f09a64",
|
||||
chrome: "#291e1a",
|
||||
},
|
||||
},
|
||||
iris: {
|
||||
light: {
|
||||
background: "oklch(0.976531 0.003855 303.226)",
|
||||
foreground: "oklch(0.222003 0.03479 328.979)",
|
||||
accent: "oklch(0.525348 0.15373 294.176)",
|
||||
chrome: "oklch(0.976531 0.003855 303.226)",
|
||||
background: "#f8f7f9",
|
||||
foreground: "#241523",
|
||||
accent: "#7253b9",
|
||||
chrome: "#f8f7f9",
|
||||
},
|
||||
dark: {
|
||||
background: "oklch(0.225975 0.031062 293.741)",
|
||||
foreground: "oklch(0.990339 0.008411 325.64)",
|
||||
accent: "oklch(0.671712 0.169136 293.929)",
|
||||
chrome: "oklch(0.225975 0.031062 293.741)",
|
||||
background: "#1d1929",
|
||||
foreground: "#fffaff",
|
||||
accent: "#9d7df2",
|
||||
chrome: "#1d1929",
|
||||
},
|
||||
},
|
||||
};
|
||||
@@ -152,26 +152,9 @@
|
||||
}
|
||||
};
|
||||
|
||||
// The runtime decodes the same literal CSS formats into OKLCH. Keep
|
||||
// contextual colors out: they cannot be resolved from stored data.
|
||||
const SYSTEM_COLOR_KEYWORD =
|
||||
/^(?:accentcolor(?:text)?|active(?:border|caption|text)|appworkspace|background|button(?:border|face|highlight|shadow|text)|canvas(?:text)?|captiontext|field(?:text)?|graytext|highlight(?:text)?|inactive(?:border|caption(?:text)?)|info(?:background|text)|linktext|mark(?:text)?|menu(?:text)?|scrollbar|selecteditem(?:text)?|threed(?:darkshadow|face|highlight|lightshadow|shadow)|visitedtext|window(?:frame|text)?)$/i;
|
||||
const isThemeColor = (value) => {
|
||||
if (typeof value !== "string" || typeof CSS === "undefined") return false;
|
||||
const color = value.trim();
|
||||
if (
|
||||
/^(?:currentcolor|inherit|initial|revert|revert-layer|unset)$/i.test(color) ||
|
||||
SYSTEM_COLOR_KEYWORD.test(color) ||
|
||||
/\bfrom\b|(?:var|env|attr|calc|min|max|clamp)\(/i.test(color)
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
const isLiteralColor =
|
||||
/^#(?:[0-9a-f]{3}|[0-9a-f]{4}|[0-9a-f]{6}|[0-9a-f]{8})$/i.test(color) ||
|
||||
/^[a-z]+$/i.test(color) ||
|
||||
/^(?:rgba?|hsla?|hwb|lab|lch|oklab|oklch|color)\(/i.test(color);
|
||||
return isLiteralColor && CSS.supports("color", color);
|
||||
};
|
||||
const isHexColor = (value) =>
|
||||
typeof value === "string" &&
|
||||
/^#(?:[0-9a-f]{3}|[0-9a-f]{4}|[0-9a-f]{6}|[0-9a-f]{8})$/i.test(value);
|
||||
const isRecord = (value) =>
|
||||
typeof value === "object" && value !== null && !Array.isArray(value);
|
||||
const isThemeId = (value) =>
|
||||
@@ -339,13 +322,13 @@
|
||||
const fallbackSplash = isDark ? SPLASH_COLORS.dark : SPLASH_COLORS.light;
|
||||
const customSplash = customColors
|
||||
? {
|
||||
background: isThemeColor(customColors.canvas)
|
||||
background: isHexColor(customColors.canvas)
|
||||
? customColors.canvas
|
||||
: (customDefaults?.background ?? fallbackSplash.background),
|
||||
foreground: isThemeColor(customColors.text)
|
||||
foreground: isHexColor(customColors.text)
|
||||
? customColors.text
|
||||
: (customDefaults?.foreground ?? fallbackSplash.foreground),
|
||||
accent: isThemeColor(customColors.accent)
|
||||
accent: isHexColor(customColors.accent)
|
||||
? customColors.accent
|
||||
: (customDefaults?.accent ?? fallbackSplash.accent),
|
||||
}
|
||||
@@ -367,7 +350,7 @@
|
||||
}
|
||||
document.documentElement.classList.toggle("dark", isDark);
|
||||
const chromeColor = customColors
|
||||
? isThemeColor(customColors.chrome)
|
||||
? isHexColor(customColors.chrome)
|
||||
? customColors.chrome
|
||||
: (customDefaults?.chrome ?? fallbackSplash.background)
|
||||
: builtInSplash
|
||||
|
||||
@@ -21,9 +21,8 @@
|
||||
"@dnd-kit/utilities": "^3.2.2",
|
||||
"@effect/atom-react": "catalog:",
|
||||
"@formkit/auto-animate": "^0.9.0",
|
||||
"@legendapp/list": "catalog:",
|
||||
"@legendapp/list": "3.3.3",
|
||||
"@lexical/react": "^0.41.0",
|
||||
"@noble/hashes": "catalog:",
|
||||
"@pierre/diffs": "catalog:",
|
||||
"@pierre/trees": "1.0.0-beta.4",
|
||||
"@t3tools/client-runtime": "workspace:*",
|
||||
@@ -32,11 +31,8 @@
|
||||
"@tanstack/react-pacer": "^0.19.4",
|
||||
"@tanstack/react-router": "^1.160.2",
|
||||
"class-variance-authority": "^0.7.1",
|
||||
"culori": "^4.0.2",
|
||||
"effect": "catalog:",
|
||||
"jose": "catalog:",
|
||||
"jsonc-parser": "3.3.1",
|
||||
"jszip": "3.10.1",
|
||||
"lexical": "^0.41.0",
|
||||
"lucide-react": "^0.564.0",
|
||||
"react": "19.2.6",
|
||||
@@ -57,7 +53,6 @@
|
||||
"@tanstack/router-plugin": "^1.161.0",
|
||||
"@types/babel__core": "^7.20.5",
|
||||
"@types/compression": "^1.8.1",
|
||||
"@types/culori": "^4.0.1",
|
||||
"@types/react": "~19.2.14",
|
||||
"@types/react-dom": "~19.2.3",
|
||||
"@vercel/config": "^0.3.0",
|
||||
|
||||
@@ -46,22 +46,6 @@ describe("connectCliAuth", () => {
|
||||
expect(url.searchParams.get("code_challenge_method")).toBe("S256");
|
||||
});
|
||||
|
||||
it("redirects straight to the CLI's loopback listener when the request carries a port", () => {
|
||||
vi.stubEnv("VITE_CLERK_PUBLISHABLE_KEY", TEST_PUBLISHABLE_KEY);
|
||||
vi.stubEnv("VITE_CLERK_CLI_OAUTH_CLIENT_ID", "oauthapp_123");
|
||||
|
||||
const authorizeUrl = buildConnectCliClerkAuthorizeUrl({
|
||||
state: "state-1",
|
||||
challenge: "challenge-1",
|
||||
loopbackPort: 34338,
|
||||
});
|
||||
expect(authorizeUrl).not.toBeNull();
|
||||
|
||||
const url = new URL(authorizeUrl!);
|
||||
expect(url.searchParams.get("redirect_uri")).toBe("http://127.0.0.1:34338/callback");
|
||||
expect(url.searchParams.get("state")).toBe("state-1");
|
||||
});
|
||||
|
||||
it("returns null when the CLI OAuth client id is not configured", () => {
|
||||
vi.stubEnv("VITE_CLERK_PUBLISHABLE_KEY", TEST_PUBLISHABLE_KEY);
|
||||
expect(
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import {
|
||||
buildConnectClerkAuthorizeUrl,
|
||||
connectCallbackUrl,
|
||||
connectLoopbackRedirectUri,
|
||||
CONNECT_OAUTH_SCOPES,
|
||||
type ConnectAuthorizeRequest,
|
||||
} from "@t3tools/shared/connectAuth";
|
||||
@@ -35,11 +34,6 @@ export function connectCliAuthRoutesEnabled(): boolean {
|
||||
* Builds the Clerk authorize URL for a CLI-initiated connect request. The
|
||||
* state is mirrored into sessionStorage so the callback page can verify the
|
||||
* response matches a request this browser actually started.
|
||||
*
|
||||
* A request carrying a loopback port came from a CLI with a local callback
|
||||
* listener: the authorization code must return to `127.0.0.1` directly, so
|
||||
* the hosted callback page never sees it. Clerk enforces its registered
|
||||
* redirect URI allowlist either way.
|
||||
*/
|
||||
export function buildConnectCliClerkAuthorizeUrl(request: ConnectAuthorizeRequest): string | null {
|
||||
const { clerkPublishableKey } = resolveCloudPublicConfig();
|
||||
@@ -50,10 +44,7 @@ export function buildConnectCliClerkAuthorizeUrl(request: ConnectAuthorizeReques
|
||||
return buildConnectClerkAuthorizeUrl({
|
||||
authorizationEndpoint: `${clerkFrontendApiUrlFromPublishableKey(clerkPublishableKey)}/oauth/authorize`,
|
||||
clientId,
|
||||
redirectUri:
|
||||
request.loopbackPort === undefined
|
||||
? connectCallbackUrl(configuredHostedAppUrl())
|
||||
: connectLoopbackRedirectUri(request.loopbackPort),
|
||||
redirectUri: connectCallbackUrl(configuredHostedAppUrl()),
|
||||
scopes: CONNECT_OAUTH_SCOPES,
|
||||
state: request.state,
|
||||
challenge: request.challenge,
|
||||
|
||||
@@ -10,7 +10,7 @@ import {
|
||||
import { useLocation, useNavigate } from "@tanstack/react-router";
|
||||
|
||||
import { isElectron } from "../env";
|
||||
import { getLocalStorageItem, removeLocalStorageItem } from "../hooks/useLocalStorage";
|
||||
import { getLocalStorageItem } from "../hooks/useLocalStorage";
|
||||
import { resolveShortcutCommand, shortcutLabelForCommand } from "../keybindings";
|
||||
import { cn, isMacPlatform } from "../lib/utils";
|
||||
import { primaryServerKeybindingsAtom } from "../state/server";
|
||||
@@ -19,10 +19,7 @@ import LegacyThreadSidebar from "./LegacySidebar";
|
||||
import ThreadSidebar from "./Sidebar";
|
||||
import { SettingsSidebarNav } from "./settings/SettingsSidebarNav";
|
||||
import { SidebarChromeHeader } from "./sidebar/SidebarChrome";
|
||||
import {
|
||||
resolveSidebarStageFocusRingOffsetClass,
|
||||
useSidebarStageBackdropVariant,
|
||||
} from "./SidebarStageBackdrop";
|
||||
import { useSidebarStageBackdropVariant } from "./SidebarStageBackdrop";
|
||||
import { useProjects } from "../state/entities";
|
||||
import {
|
||||
resolveInitialThreadSidebarWidth,
|
||||
@@ -108,10 +105,7 @@ function SidebarControl() {
|
||||
"pointer-events-auto",
|
||||
isSidebarVisible &&
|
||||
stageBackdropVariant &&
|
||||
"focus-visible:ring-white/90 [&_svg]:stroke-white/90! [&_svg]:opacity-100! [&_svg]:hover:stroke-white! [:hover,[data-pressed]]:bg-white/15",
|
||||
isSidebarVisible &&
|
||||
stageBackdropVariant &&
|
||||
resolveSidebarStageFocusRingOffsetClass(stageBackdropVariant),
|
||||
"[:hover,[data-pressed]]:bg-white/15 focus-visible:ring-white/90 focus-visible:ring-offset-blue-700 [&_svg]:stroke-white/90! [&_svg]:opacity-100! [&_svg]:hover:stroke-white!",
|
||||
)}
|
||||
aria-label="Toggle main sidebar"
|
||||
/>
|
||||
@@ -147,14 +141,6 @@ export function AppSidebarLayout({ children }: { children: ReactNode }) {
|
||||
// that would otherwise refresh a render-time snapshot.
|
||||
const viewportWidth = useSyncExternalStore(subscribeToViewportWidth, readViewportWidth);
|
||||
const sidebarMaximumWidth = resolveThreadSidebarMaximumWidth(viewportWidth);
|
||||
const resetSidebarWidth = () => {
|
||||
try {
|
||||
removeLocalStorageItem(THREAD_SIDEBAR_WIDTH_STORAGE_KEY);
|
||||
} catch (error) {
|
||||
console.error("Could not clear persisted thread sidebar width.", error);
|
||||
}
|
||||
setSidebarWidth(resolveInitialThreadSidebarWidth(null, viewportWidth));
|
||||
};
|
||||
const [isWindowFullscreen, setIsWindowFullscreen] = useState(() => {
|
||||
const getWindowFullscreenState = window.desktopBridge?.getWindowFullscreenState;
|
||||
return isMacosDesktop && typeof getWindowFullscreenState === "function"
|
||||
@@ -233,7 +219,7 @@ export function AppSidebarLayout({ children }: { children: ReactNode }) {
|
||||
) : (
|
||||
<ThreadSidebar />
|
||||
)}
|
||||
<SidebarRail onDoubleClick={resetSidebarWidth} />
|
||||
<SidebarRail />
|
||||
</Sidebar>
|
||||
{children}
|
||||
<SidebarControl />
|
||||
|
||||
@@ -9,7 +9,7 @@ import {
|
||||
HistoryIcon,
|
||||
MonitorIcon,
|
||||
} from "lucide-react";
|
||||
import { memo, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
|
||||
import { memo, useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
|
||||
import { useComposerDraftStore, type DraftId } from "../composerDraftStore";
|
||||
import { useProject, useThread, useThreadShellsForProjectRefs } from "../state/entities";
|
||||
@@ -218,20 +218,16 @@ const MobileRunContextSelector = memo(function MobileRunContextSelector({
|
||||
/**
|
||||
* Collapse the strip's labels to icons only when the text no longer fits.
|
||||
*
|
||||
* Hidden labels stay measurable because their inner text keeps its natural
|
||||
* width while the outer layout box collapses. This lets every pass recompute
|
||||
* the expanded width without remembered values that could go stale or latch
|
||||
* the strip compact. A small hysteresis keeps the boundary from flapping.
|
||||
* Hidden labels stay measurable (they collapse to invisible absolute boxes,
|
||||
* which keep their natural width), so the required width can be recomputed in
|
||||
* either state on every pass - no remembered widths that could go stale or
|
||||
* latch the strip compact. A small hysteresis keeps the boundary from
|
||||
* flapping between states.
|
||||
*/
|
||||
const COMPACT_EXPAND_HYSTERESIS_PX = 16;
|
||||
const COMPOSER_CONTEXT_MOTION_DURATION_MS = 180;
|
||||
const COMPOSER_CONTEXT_MOTION_EASING = "cubic-bezier(0.32, 0.72, 0, 1)";
|
||||
const COMPOSER_CONTEXT_CONTROL_SELECTOR = "[data-composer-context-control]";
|
||||
|
||||
function useLabelsOverflow(element: HTMLDivElement | null): boolean {
|
||||
const [overflows, setOverflows] = useState(false);
|
||||
const pendingControlRectsRef = useRef<Map<HTMLElement, DOMRect> | null>(null);
|
||||
const controlAnimationsRef = useRef(new Map<HTMLElement, Animation>());
|
||||
// A render-synced mirror instead of useEffectEvent: the compiler memoizes
|
||||
// the event callback, which left observers reading the first render's null
|
||||
// element forever.
|
||||
@@ -245,7 +241,7 @@ function useLabelsOverflow(element: HTMLDivElement | null): boolean {
|
||||
if (available === 0) return;
|
||||
// flex-1 stretches the groups to fill the strip, so their own boxes always
|
||||
// measure "full". Sum the laid-out content instead, skipping hidden form
|
||||
// artifacts and other out-of-flow nodes.
|
||||
// artifacts and absolutely-positioned nodes (the compact-hidden labels).
|
||||
const contentWidth = (parent: Element): number => {
|
||||
const gap = Number.parseFloat(getComputedStyle(parent).columnGap) || 0;
|
||||
let width = 0;
|
||||
@@ -287,71 +283,9 @@ function useLabelsOverflow(element: HTMLDivElement | null): boolean {
|
||||
needed += Math.max(0, textWidth - label.clientWidth);
|
||||
}
|
||||
}
|
||||
const nextOverflows = compact
|
||||
? needed > available - COMPACT_EXPAND_HYSTERESIS_PX
|
||||
: needed > available;
|
||||
if (nextOverflows !== compact) {
|
||||
pendingControlRectsRef.current = new Map(
|
||||
Array.from(current.querySelectorAll<HTMLElement>(COMPOSER_CONTEXT_CONTROL_SELECTOR)).map(
|
||||
(control) => [control, control.getBoundingClientRect()],
|
||||
),
|
||||
);
|
||||
}
|
||||
setOverflows(nextOverflows);
|
||||
setOverflows(compact ? needed > available - COMPACT_EXPAND_HYSTERESIS_PX : needed > available);
|
||||
}, []);
|
||||
|
||||
useLayoutEffect(() => {
|
||||
const previousRects = pendingControlRectsRef.current;
|
||||
if (!previousRects) return;
|
||||
pendingControlRectsRef.current = null;
|
||||
|
||||
for (const animation of controlAnimationsRef.current.values()) {
|
||||
animation.cancel();
|
||||
}
|
||||
controlAnimationsRef.current.clear();
|
||||
|
||||
if (window.matchMedia("(prefers-reduced-motion: reduce)").matches) return;
|
||||
|
||||
for (const [control, previousRect] of previousRects) {
|
||||
if (!control.isConnected) continue;
|
||||
const nextRect = control.getBoundingClientRect();
|
||||
const deltaX = previousRect.left - nextRect.left;
|
||||
const deltaY = previousRect.top - nextRect.top;
|
||||
if (Math.abs(deltaX) < 0.5 && Math.abs(deltaY) < 0.5) continue;
|
||||
|
||||
const animation = control.animate(
|
||||
[
|
||||
{ transform: `translate3d(${deltaX}px, ${deltaY}px, 0)` },
|
||||
{ transform: "translate3d(0, 0, 0)" },
|
||||
],
|
||||
{
|
||||
duration: COMPOSER_CONTEXT_MOTION_DURATION_MS,
|
||||
easing: COMPOSER_CONTEXT_MOTION_EASING,
|
||||
fill: "backwards",
|
||||
},
|
||||
);
|
||||
controlAnimationsRef.current.set(control, animation);
|
||||
animation.addEventListener(
|
||||
"finish",
|
||||
() => {
|
||||
if (controlAnimationsRef.current.get(control) === animation) {
|
||||
controlAnimationsRef.current.delete(control);
|
||||
}
|
||||
},
|
||||
{ once: true },
|
||||
);
|
||||
}
|
||||
}, [overflows]);
|
||||
|
||||
useEffect(
|
||||
() => () => {
|
||||
for (const animation of controlAnimationsRef.current.values()) {
|
||||
animation.cancel();
|
||||
}
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
// Label widths can change without the strip box moving (font family or
|
||||
// size preferences), so re-measure on every render as well as on resize
|
||||
// and font loads.
|
||||
@@ -469,7 +403,7 @@ export const BranchToolbar = memo(function BranchToolbar({
|
||||
<div
|
||||
ref={setStripElement}
|
||||
data-compact={labelsOverflow ? "" : undefined}
|
||||
className="chat-composer-context-strip group/composer-context -mt-4 mx-auto flex w-[calc(100%-2.75rem)] max-w-[calc(48rem-2.75rem)] items-center gap-2 overflow-x-clip overflow-y-visible ps-1 pe-2 pt-5 pb-1"
|
||||
className="chat-composer-context-strip group/composer-context -mt-4 mx-auto flex w-[calc(100%-2.75rem)] max-w-[calc(48rem-2.75rem)] items-center gap-2 ps-1 pe-2 pt-5 pb-1"
|
||||
>
|
||||
{isMobile && showGitControls ? (
|
||||
<MobileRunContextSelector
|
||||
@@ -497,11 +431,7 @@ export const BranchToolbar = memo(function BranchToolbar({
|
||||
{...(showEnvironmentPicker && onEnvironmentChange ? { onEnvironmentChange } : {})}
|
||||
/>
|
||||
{showGitControls ? (
|
||||
<Separator
|
||||
orientation="vertical"
|
||||
className="mx-0.5 h-3.5!"
|
||||
data-composer-context-control
|
||||
/>
|
||||
<Separator orientation="vertical" className="mx-0.5 h-3.5!" />
|
||||
) : null}
|
||||
</>
|
||||
)}
|
||||
|
||||
@@ -714,10 +714,7 @@ export function BranchToolbarBranchSelector({
|
||||
open={isBranchMenuOpen}
|
||||
value={resolvedActiveBranch}
|
||||
>
|
||||
<div
|
||||
className={cn("flex min-w-0 items-center gap-1", className)}
|
||||
data-composer-context-control
|
||||
>
|
||||
<div className={cn("flex min-w-0 items-center gap-1", className)}>
|
||||
{branchPr && branchPrStatus ? (
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
@@ -754,14 +751,9 @@ export function BranchToolbarBranchSelector({
|
||||
<GitBranchIcon className="size-3 shrink-0 opacity-70" />
|
||||
<span
|
||||
data-composer-label
|
||||
className="min-w-0 max-w-[240px] group-data-[compact]/composer-context:max-w-0"
|
||||
className="min-w-0 max-w-[240px] truncate transition-[max-width,opacity] duration-300 ease-out group-data-[compact]/composer-context:max-w-0 group-data-[compact]/composer-context:opacity-0"
|
||||
>
|
||||
<span
|
||||
data-composer-label-motion
|
||||
className="block w-full min-w-0 max-w-[240px] origin-left truncate transition-[opacity,transform] duration-180 ease-[cubic-bezier(0.32,0.72,0,1)] group-data-[compact]/composer-context:[transform:translateX(-0.25rem)_scaleX(0.95)] group-data-[compact]/composer-context:opacity-0 motion-reduce:transform-none motion-reduce:transition-opacity"
|
||||
>
|
||||
{triggerLabel}
|
||||
</span>
|
||||
{triggerLabel}
|
||||
</span>
|
||||
<ChevronDownIcon className="size-3 shrink-0 opacity-50" />
|
||||
</ComboboxTrigger>
|
||||
|
||||
@@ -50,10 +50,7 @@ export const BranchToolbarEnvModeSelector = memo(function BranchToolbarEnvModeSe
|
||||
|
||||
if (envLocked) {
|
||||
return (
|
||||
<span
|
||||
className="inline-flex h-7 shrink-0 items-center gap-1 border border-transparent px-[calc(--spacing(3)-1px)] text-sm font-medium text-muted-foreground/70 sm:h-6 sm:text-xs"
|
||||
data-composer-context-control
|
||||
>
|
||||
<span className="inline-flex h-7 shrink-0 items-center gap-1 border border-transparent px-[calc(--spacing(3)-1px)] text-sm font-medium text-muted-foreground/70 sm:h-6 sm:text-xs">
|
||||
{activeWorktreePath ? (
|
||||
<>
|
||||
<FolderGitIcon className="size-3" />
|
||||
@@ -87,7 +84,6 @@ export const BranchToolbarEnvModeSelector = memo(function BranchToolbarEnvModeSe
|
||||
size="xs"
|
||||
className="min-w-0 shrink font-medium"
|
||||
aria-label="Workspace"
|
||||
data-composer-context-control
|
||||
>
|
||||
{effectiveEnvMode === "worktree" ? (
|
||||
<FolderGit2Icon className="size-3" />
|
||||
@@ -98,14 +94,9 @@ export const BranchToolbarEnvModeSelector = memo(function BranchToolbarEnvModeSe
|
||||
)}
|
||||
<span
|
||||
data-composer-label
|
||||
className="min-w-0 max-w-[240px] group-data-[compact]/composer-context:max-w-0"
|
||||
className="min-w-0 max-w-[240px] truncate transition-[max-width,opacity] duration-300 ease-out group-data-[compact]/composer-context:max-w-0 group-data-[compact]/composer-context:opacity-0"
|
||||
>
|
||||
<span
|
||||
data-composer-label-motion
|
||||
className="block w-full min-w-0 max-w-[240px] origin-left truncate transition-[opacity,transform] duration-180 ease-[cubic-bezier(0.32,0.72,0,1)] group-data-[compact]/composer-context:[transform:translateX(-0.25rem)_scaleX(0.95)] group-data-[compact]/composer-context:opacity-0 motion-reduce:transform-none motion-reduce:transition-opacity"
|
||||
>
|
||||
<SelectValue />
|
||||
</span>
|
||||
<SelectValue />
|
||||
</span>
|
||||
</SelectTrigger>
|
||||
<SelectPopup>
|
||||
|
||||
@@ -48,10 +48,7 @@ export const BranchToolbarEnvironmentSelector = memo(function BranchToolbarEnvir
|
||||
// only thing in the strip.
|
||||
if (envLocked || onEnvironmentChange === undefined) {
|
||||
return (
|
||||
<span
|
||||
className="inline-flex h-7 min-w-0 max-w-full items-center gap-1 border border-transparent px-[calc(--spacing(3)-1px)] text-sm font-medium text-muted-foreground/70 sm:h-6 sm:text-xs"
|
||||
data-composer-context-control
|
||||
>
|
||||
<span className="inline-flex h-7 min-w-0 max-w-full items-center gap-1 border border-transparent px-[calc(--spacing(3)-1px)] text-sm font-medium text-muted-foreground/70 sm:h-6 sm:text-xs">
|
||||
{activeEnvironment?.isPrimary ? (
|
||||
<MonitorIcon className="size-3 shrink-0" />
|
||||
) : (
|
||||
@@ -59,14 +56,9 @@ export const BranchToolbarEnvironmentSelector = memo(function BranchToolbarEnvir
|
||||
)}
|
||||
<span
|
||||
data-composer-label
|
||||
className="min-w-0 max-w-[240px] group-data-[compact]/composer-context:max-w-0"
|
||||
className="min-w-0 max-w-[240px] truncate transition-[max-width,opacity] duration-300 ease-out group-data-[compact]/composer-context:max-w-0 group-data-[compact]/composer-context:opacity-0"
|
||||
>
|
||||
<span
|
||||
data-composer-label-motion
|
||||
className="block w-full min-w-0 max-w-[240px] origin-left truncate transition-[opacity,transform] duration-180 ease-[cubic-bezier(0.32,0.72,0,1)] group-data-[compact]/composer-context:[transform:translateX(-0.25rem)_scaleX(0.95)] group-data-[compact]/composer-context:opacity-0 motion-reduce:transform-none motion-reduce:transition-opacity"
|
||||
>
|
||||
{activeEnvironment?.label ?? "Run on"}
|
||||
</span>
|
||||
{activeEnvironment?.label ?? "Run on"}
|
||||
</span>
|
||||
</span>
|
||||
);
|
||||
@@ -84,7 +76,6 @@ export const BranchToolbarEnvironmentSelector = memo(function BranchToolbarEnvir
|
||||
size="xs"
|
||||
className="min-w-0 max-w-full font-medium"
|
||||
aria-label="Run on"
|
||||
data-composer-context-control
|
||||
>
|
||||
{activeEnvironment?.isPrimary ? (
|
||||
<MonitorIcon className="size-3 shrink-0" />
|
||||
@@ -93,14 +84,9 @@ export const BranchToolbarEnvironmentSelector = memo(function BranchToolbarEnvir
|
||||
)}
|
||||
<span
|
||||
data-composer-label
|
||||
className="min-w-0 max-w-[240px] group-data-[compact]/composer-context:max-w-0"
|
||||
className="min-w-0 max-w-[240px] truncate transition-[max-width,opacity] duration-300 ease-out group-data-[compact]/composer-context:max-w-0 group-data-[compact]/composer-context:opacity-0"
|
||||
>
|
||||
<span
|
||||
data-composer-label-motion
|
||||
className="block w-full min-w-0 max-w-[240px] origin-left truncate transition-[opacity,transform] duration-180 ease-[cubic-bezier(0.32,0.72,0,1)] group-data-[compact]/composer-context:[transform:translateX(-0.25rem)_scaleX(0.95)] group-data-[compact]/composer-context:opacity-0 motion-reduce:transform-none motion-reduce:transition-opacity"
|
||||
>
|
||||
<SelectValue />
|
||||
</span>
|
||||
<SelectValue />
|
||||
</span>
|
||||
</SelectTrigger>
|
||||
<SelectPopup>
|
||||
|
||||
@@ -264,13 +264,7 @@ import {
|
||||
ProviderStatusBanner,
|
||||
shouldShowProviderStatusBanner,
|
||||
} from "./chat/ProviderStatusBanner";
|
||||
import {
|
||||
dismissThreadErrorBannerForSession,
|
||||
getThreadErrorBannerKey,
|
||||
isThreadErrorBannerDismissedForSession,
|
||||
shouldShowThreadErrorBanner,
|
||||
ThreadErrorBanner,
|
||||
} from "./chat/ThreadErrorBanner";
|
||||
import { ThreadErrorBanner } from "./chat/ThreadErrorBanner";
|
||||
import { resolveThreadPr } from "./ThreadStatusIndicators";
|
||||
import { ComposerBannerStack, type ComposerBannerStackItem } from "./chat/ComposerBannerStack";
|
||||
import { ThreadSyncStatusPill } from "./chat/ThreadSyncStatusPill";
|
||||
@@ -480,14 +474,6 @@ function shouldTypeToFocusComposer(event: KeyboardEvent): boolean {
|
||||
if (eventPathContainsSelector(event, TYPE_TO_FOCUS_INTERACTIVE_SELECTOR)) return false;
|
||||
if (document.querySelector(TYPE_TO_FOCUS_FLOATING_LAYER_SELECTOR)) return false;
|
||||
|
||||
// The right-panel surface launcher claims its shortcut letters while it is
|
||||
// visible (data attribute set in RightPanelTabs); those keys open surfaces
|
||||
// instead of typing into the composer.
|
||||
const launcherKeys = document
|
||||
.querySelector("[data-surface-launcher-keys]")
|
||||
?.getAttribute("data-surface-launcher-keys");
|
||||
if (launcherKeys && launcherKeys.toLowerCase().includes(event.key.toLowerCase())) return false;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -1507,24 +1493,6 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
const threadError = isServerThread
|
||||
? (localServerError ?? activeServerThread?.session?.lastError ?? null)
|
||||
: localDraftError;
|
||||
// Dismissals can only mask the shown error, never clear it: a server thread
|
||||
// keeps its error in session.lastError, so clearing the local shadow would
|
||||
// just fall through to the persisted one. Mask the current error until a
|
||||
// different error arrives, mirroring the provider status banner.
|
||||
const threadErrorBannerKey = getThreadErrorBannerKey(routeThreadKey, threadError);
|
||||
const visibleThreadError = shouldShowThreadErrorBanner(
|
||||
routeThreadKey,
|
||||
threadError,
|
||||
isThreadErrorBannerDismissedForSession(threadErrorBannerKey),
|
||||
)
|
||||
? threadError
|
||||
: null;
|
||||
// Dismissing only mutates the session-scoped mask set, which does not
|
||||
// trigger a render on its own; setThreadError(null) can also bail when the
|
||||
// local shadow is already empty and the banner is driven purely by
|
||||
// session.lastError. Bump a tick so the banner hides immediately. Mirrors
|
||||
// the branch mismatch banner.
|
||||
const [, setThreadErrorBannerDismissTick] = useState(0);
|
||||
const runtimeMode = composerRuntimeMode ?? activeThread?.runtimeMode ?? DEFAULT_RUNTIME_MODE;
|
||||
// Plan mode is legacy (Settings → Beta). With the flag off the effective
|
||||
// mode is forced to "default" — even for threads with a stored plan mode —
|
||||
@@ -2650,7 +2618,7 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
)
|
||||
? activeProviderStatus
|
||||
: null;
|
||||
const hasTimelineTopBanner = Boolean(visibleThreadError) || visibleProviderStatus !== null;
|
||||
const hasTimelineTopBanner = Boolean(threadError) || visibleProviderStatus !== null;
|
||||
const activeProjectCwd = activeProject?.workspaceRoot ?? null;
|
||||
const activeThreadWorktreePath = activeThread?.worktreePath ?? null;
|
||||
const activeWorkspaceRoot = activeThreadWorktreePath ?? activeProjectCwd ?? undefined;
|
||||
@@ -4110,6 +4078,24 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
supportsPullRequests && activeThreadPr !== null && threadRepository !== null;
|
||||
const supportsSettlement = serverConfig?.environment.capabilities.threadSettlement === true;
|
||||
const supportsSnooze = serverConfig?.environment.capabilities.threadSnooze === true;
|
||||
const supportsThreadVisits = serverConfig?.environment.capabilities.threadVisits === true;
|
||||
// Server-side twin of the markThreadVisited stamp above: reading a finished
|
||||
// thread here must clear the unread cue on every device, so sync the same
|
||||
// completedAt acknowledgement to the server. Guarded on the shell's current
|
||||
// value so re-renders and the echo of our own visit don't re-dispatch; the
|
||||
// decider is monotonic, so a raced older visit is a server-side no-op.
|
||||
const visitThreadMutation = useAtomCommand(threadEnvironment.visit, { reportFailure: false });
|
||||
useEffect(() => {
|
||||
if (!supportsThreadVisits || activeThreadShell === null) return;
|
||||
const completedAt = activeThreadShell.latestTurn?.completedAt;
|
||||
if (!completedAt) return;
|
||||
const syncedVisitedAt = activeThreadShell.lastVisitedAt;
|
||||
if (syncedVisitedAt != null && Date.parse(syncedVisitedAt) >= Date.parse(completedAt)) return;
|
||||
void visitThreadMutation({
|
||||
environmentId: activeThreadShell.environmentId,
|
||||
input: { threadId: activeThreadShell.id, visitedAt: completedAt },
|
||||
});
|
||||
}, [activeThreadShell, supportsThreadVisits, visitThreadMutation]);
|
||||
const nowMinute = useNowMinute();
|
||||
const snoozeNow = new Date().toISOString();
|
||||
const activeThreadSnoozed =
|
||||
@@ -6178,12 +6164,8 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
</header>
|
||||
|
||||
<ThreadErrorBanner
|
||||
error={visibleThreadError}
|
||||
onDismiss={() => {
|
||||
setThreadError(activeThread.id, null);
|
||||
dismissThreadErrorBannerForSession(threadErrorBannerKey);
|
||||
setThreadErrorBannerDismissTick((tick) => tick + 1);
|
||||
}}
|
||||
error={threadError}
|
||||
onDismiss={() => setThreadError(activeThread.id, null)}
|
||||
/>
|
||||
{/* Main content area with optional plan sidebar */}
|
||||
<div className="flex min-h-0 min-w-0 flex-1">
|
||||
|
||||
@@ -22,7 +22,6 @@ import { flushSync } from "react-dom";
|
||||
import {
|
||||
CheckIcon,
|
||||
ChevronDownIcon,
|
||||
CloudDownloadIcon,
|
||||
CloudUploadIcon,
|
||||
ExternalLinkIcon,
|
||||
GitBranchPlusIcon,
|
||||
@@ -358,7 +357,7 @@ function GitQuickActionIcon({
|
||||
const iconClassName = "size-3.5";
|
||||
if (quickAction.kind === "open_pr") return <SourceControlIcon className={iconClassName} />;
|
||||
if (quickAction.kind === "open_publish") return <CloudUploadIcon className={iconClassName} />;
|
||||
if (quickAction.kind === "run_pull") return <CloudDownloadIcon className={iconClassName} />;
|
||||
if (quickAction.kind === "run_pull") return <InfoIcon className={iconClassName} />;
|
||||
if (quickAction.kind === "run_action") {
|
||||
if (quickAction.action === "commit") return <GitCommitIcon className={iconClassName} />;
|
||||
if (quickAction.action === "push" || quickAction.action === "commit_push") {
|
||||
@@ -367,7 +366,6 @@ function GitQuickActionIcon({
|
||||
return <SourceControlIcon className={iconClassName} />;
|
||||
}
|
||||
if (quickAction.label === "Commit") return <GitCommitIcon className={iconClassName} />;
|
||||
if (quickAction.label === "Push") return <CloudUploadIcon className={iconClassName} />;
|
||||
return <InfoIcon className={iconClassName} />;
|
||||
}
|
||||
|
||||
|
||||
@@ -372,7 +372,10 @@ export const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThr
|
||||
} = props;
|
||||
const threadRef = scopeThreadRef(thread.environmentId, thread.id);
|
||||
const threadKey = scopedThreadKey(threadRef);
|
||||
const lastVisitedAt = useUiStateStore((state) => state.threadLastVisitedAtById[threadKey]);
|
||||
// Local visit stamps win; the shell's server-synced lastVisitedAt fills the
|
||||
// gap so a visit on another device still clears the unread cue here.
|
||||
const localLastVisitedAt = useUiStateStore((state) => state.threadLastVisitedAtById[threadKey]);
|
||||
const lastVisitedAt = localLastVisitedAt ?? thread.lastVisitedAt ?? undefined;
|
||||
const isSelected = useThreadSelectionStore((state) => state.selectedThreadKeys.has(threadKey));
|
||||
const runningTerminalIds = useThreadRunningTerminalIds({
|
||||
environmentId: thread.environmentId,
|
||||
|
||||
@@ -11,7 +11,6 @@ import {
|
||||
X,
|
||||
} from "lucide-react";
|
||||
import {
|
||||
type KeyboardEvent as ReactKeyboardEvent,
|
||||
type MouseEvent as ReactMouseEvent,
|
||||
type ReactElement,
|
||||
type ReactNode,
|
||||
@@ -26,7 +25,6 @@ import type { RightPanelSurface } from "~/rightPanelStore";
|
||||
import { cn } from "~/lib/utils";
|
||||
import { readLocalApi } from "~/localApi";
|
||||
import { Tooltip, TooltipPopup, TooltipTrigger } from "~/components/ui/tooltip";
|
||||
import { Kbd } from "~/components/ui/kbd";
|
||||
import { Menu, MenuItem, MenuPopup, MenuTrigger } from "~/components/ui/menu";
|
||||
import { ScrollArea } from "~/components/ui/scroll-area";
|
||||
import { faviconUrlForOrigin } from "~/lib/favicon";
|
||||
@@ -90,28 +88,6 @@ const SURFACE_DISABLED_REASONS = {
|
||||
agents: "Agents are only available from a thread.",
|
||||
} as const;
|
||||
|
||||
/** Overlays that must win over the launcher's letter shortcuts. */
|
||||
const LAUNCHER_SHORTCUT_BLOCKING_LAYERS = [
|
||||
'[data-slot="dialog-popup"]',
|
||||
'[data-slot="alert-dialog-popup"]',
|
||||
'[data-slot="command-dialog-popup"]',
|
||||
'[data-slot="menu-popup"]',
|
||||
'[data-slot="select-popup"]',
|
||||
'[data-slot="popover-popup"]',
|
||||
'[data-slot="combobox-popup"]',
|
||||
'[data-slot="autocomplete-popup"]',
|
||||
].join(",");
|
||||
|
||||
/** One-line unavailability hints for the empty-state cards. */
|
||||
const SURFACE_UNAVAILABLE_HINTS = {
|
||||
browser: "Only available in the desktop app.",
|
||||
terminal: "Available when a project is open.",
|
||||
files: "Available when a project is open.",
|
||||
diff: "Available for Git repositories.",
|
||||
pullRequest: "No pull request on this branch yet.",
|
||||
agents: "Available from a thread.",
|
||||
} as const;
|
||||
|
||||
type TabContextMenuAction = "copy-path" | "close" | "close-others" | "close-to-right" | "close-all";
|
||||
|
||||
function DisabledReasonTooltip(props: { reason: string; trigger: ReactElement }) {
|
||||
@@ -142,13 +118,6 @@ function SurfaceMenuItem(props: {
|
||||
return <DisabledReasonTooltip reason={props.disabledReason} trigger={item} />;
|
||||
}
|
||||
|
||||
/**
|
||||
* Card launcher shown when the right panel has no surfaces. Keyboard-first
|
||||
* without palette chrome: a surface's letter opens it directly from anywhere
|
||||
* outside a typing context, and arrows plus Enter work while the launcher is
|
||||
* focused. The highlight only appears on hover or arrow use. Unavailable
|
||||
* surfaces stay visible with a one-line reason.
|
||||
*/
|
||||
function RightPanelEmptyState(props: {
|
||||
onAddBrowser: () => void;
|
||||
onAddTerminal: () => void;
|
||||
@@ -164,17 +133,13 @@ function RightPanelEmptyState(props: {
|
||||
agentsAvailable: boolean;
|
||||
liveAgentCount: number;
|
||||
}) {
|
||||
// -1 means no highlight: it only appears on hover or arrow use.
|
||||
const [highlight, setHighlight] = useState(-1);
|
||||
|
||||
const actions = [
|
||||
{
|
||||
label: "Browser",
|
||||
description: "Open a local app or URL.",
|
||||
icon: Globe2,
|
||||
shortcut: "B",
|
||||
available: props.browserAvailable,
|
||||
disabledReason: SURFACE_UNAVAILABLE_HINTS.browser,
|
||||
disabledReason: SURFACE_DISABLED_REASONS.browser,
|
||||
onClick: props.onAddBrowser,
|
||||
badgeCount: 0,
|
||||
},
|
||||
@@ -182,9 +147,8 @@ function RightPanelEmptyState(props: {
|
||||
label: "Terminal",
|
||||
description: "Start a shell in this workspace.",
|
||||
icon: TerminalSquare,
|
||||
shortcut: "T",
|
||||
available: props.terminalAvailable,
|
||||
disabledReason: SURFACE_UNAVAILABLE_HINTS.terminal,
|
||||
disabledReason: SURFACE_DISABLED_REASONS.terminal,
|
||||
onClick: props.onAddTerminal,
|
||||
badgeCount: 0,
|
||||
},
|
||||
@@ -192,9 +156,8 @@ function RightPanelEmptyState(props: {
|
||||
label: "Files",
|
||||
description: "Browse and read workspace files.",
|
||||
icon: Files,
|
||||
shortcut: "F",
|
||||
available: props.filesAvailable,
|
||||
disabledReason: SURFACE_UNAVAILABLE_HINTS.files,
|
||||
disabledReason: SURFACE_DISABLED_REASONS.files,
|
||||
onClick: props.onAddFiles,
|
||||
badgeCount: 0,
|
||||
},
|
||||
@@ -202,199 +165,91 @@ function RightPanelEmptyState(props: {
|
||||
label: "Diff",
|
||||
description: "Review changes in this thread.",
|
||||
icon: FileDiff,
|
||||
shortcut: "D",
|
||||
available: props.diffAvailable,
|
||||
disabledReason: SURFACE_UNAVAILABLE_HINTS.diff,
|
||||
disabledReason: SURFACE_DISABLED_REASONS.diff,
|
||||
onClick: props.onAddDiff,
|
||||
badgeCount: 0,
|
||||
},
|
||||
{
|
||||
label: "Pull request",
|
||||
description: "Open this branch's pull request.",
|
||||
description: "Open the pull request for this thread's branch.",
|
||||
icon: GitPullRequest,
|
||||
shortcut: "P",
|
||||
available: props.pullRequestAvailable,
|
||||
disabledReason: SURFACE_UNAVAILABLE_HINTS.pullRequest,
|
||||
disabledReason: SURFACE_DISABLED_REASONS.pullRequest,
|
||||
onClick: props.onAddPullRequest,
|
||||
badgeCount: 0,
|
||||
},
|
||||
{
|
||||
label: "Agents",
|
||||
description: "Follow subagents and workflows.",
|
||||
description: "Watch subagents and workflows run.",
|
||||
icon: Bot,
|
||||
shortcut: "A",
|
||||
available: props.agentsAvailable,
|
||||
disabledReason: SURFACE_UNAVAILABLE_HINTS.agents,
|
||||
disabledReason: SURFACE_DISABLED_REASONS.agents,
|
||||
onClick: props.onAddAgents,
|
||||
badgeCount: props.liveAgentCount,
|
||||
},
|
||||
] as const;
|
||||
|
||||
type SurfaceAction = (typeof actions)[number];
|
||||
|
||||
const availableActions = actions.filter((action) => action.available);
|
||||
const highlightIndex =
|
||||
availableActions.length === 0 ? -1 : Math.min(highlight, availableActions.length - 1);
|
||||
|
||||
// Letter shortcuts work while the launcher is visible, not only while it
|
||||
// is focused; focus moves around too easily (stray clicks) to carry them.
|
||||
// Capture phase so app-level key handlers cannot swallow the event first;
|
||||
// typing contexts and already-handled events are left alone.
|
||||
const shortcutActionsRef = useRef(availableActions);
|
||||
useEffect(() => {
|
||||
shortcutActionsRef.current = availableActions;
|
||||
});
|
||||
useEffect(() => {
|
||||
const handler = (event: KeyboardEvent) => {
|
||||
if (event.defaultPrevented || event.isComposing) return;
|
||||
if (event.metaKey || event.ctrlKey || event.altKey) return;
|
||||
if (document.querySelector(LAUNCHER_SHORTCUT_BLOCKING_LAYERS)) return;
|
||||
const target = event.target;
|
||||
if (target instanceof HTMLElement) {
|
||||
if (target.closest("input, textarea, select")) return;
|
||||
// An empty contenteditable (the chat composer at rest) does not
|
||||
// count as typing; letters only become text once a draft exists.
|
||||
const editable = target.isContentEditable ? target : target.closest("[contenteditable]");
|
||||
if (editable && (editable.textContent ?? "").trim().length > 0) return;
|
||||
}
|
||||
const action = shortcutActionsRef.current.find(
|
||||
(candidate) => candidate.shortcut.toLowerCase() === event.key.toLowerCase(),
|
||||
);
|
||||
if (!action) return;
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
action.onClick();
|
||||
};
|
||||
window.addEventListener("keydown", handler, true);
|
||||
return () => window.removeEventListener("keydown", handler, true);
|
||||
}, []);
|
||||
|
||||
const handleKeyDown = (event: ReactKeyboardEvent<HTMLDivElement>) => {
|
||||
if (event.defaultPrevented || event.metaKey || event.ctrlKey || event.altKey) return;
|
||||
if (availableActions.length === 0) return;
|
||||
if (event.key === "ArrowDown" || event.key === "ArrowRight") {
|
||||
event.preventDefault();
|
||||
setHighlight((highlightIndex + 1) % availableActions.length);
|
||||
return;
|
||||
}
|
||||
if (event.key === "ArrowUp" || event.key === "ArrowLeft") {
|
||||
event.preventDefault();
|
||||
setHighlight(
|
||||
highlightIndex === -1
|
||||
? availableActions.length - 1
|
||||
: (highlightIndex - 1 + availableActions.length) % availableActions.length,
|
||||
);
|
||||
return;
|
||||
}
|
||||
if (event.key === "Enter") {
|
||||
// A focused card button owns its own activation; only open from the
|
||||
// highlight when the container itself has focus.
|
||||
if (event.target instanceof HTMLElement && event.target.closest("button")) return;
|
||||
const action = availableActions[highlightIndex];
|
||||
if (!action) return;
|
||||
event.preventDefault();
|
||||
action.onClick();
|
||||
}
|
||||
};
|
||||
|
||||
// Stable identity so React only runs this callback ref on mount/unmount;
|
||||
// an inline arrow would re-attach and re-focus on every render.
|
||||
const focusOnMount = useCallback((node: HTMLDivElement | null) => {
|
||||
node?.focus();
|
||||
}, []);
|
||||
|
||||
const isHighlighted = (action: SurfaceAction) =>
|
||||
highlightIndex !== -1 && availableActions[highlightIndex] === action;
|
||||
|
||||
const actionIcon = (action: SurfaceAction, iconClassName = "size-4") => {
|
||||
const Icon = action.icon;
|
||||
return (
|
||||
<span className="relative inline-flex shrink-0">
|
||||
<Icon className={iconClassName} />
|
||||
{action.badgeCount > 0 ? (
|
||||
<span
|
||||
aria-hidden
|
||||
className="absolute -top-1.5 -right-2 flex h-3.5 min-w-3.5 items-center justify-center rounded-full bg-info px-1 text-[9px] font-semibold tabular-nums text-white"
|
||||
>
|
||||
{action.badgeCount}
|
||||
</span>
|
||||
) : null}
|
||||
</span>
|
||||
);
|
||||
};
|
||||
|
||||
const cardShellClass =
|
||||
"rounded-lg border border-border/80 bg-card dark:border-transparent dark:shadow-none dark:inset-ring-1 dark:inset-ring-white/5";
|
||||
const highlightedCardClass = "bg-accent/60 dark:inset-ring-white/20";
|
||||
|
||||
return (
|
||||
<div
|
||||
ref={focusOnMount}
|
||||
tabIndex={0}
|
||||
onKeyDown={handleKeyDown}
|
||||
aria-label="Open a surface"
|
||||
data-surface-launcher-keys={availableActions.map((action) => action.shortcut).join("")}
|
||||
className={cn(
|
||||
"flex min-h-0 flex-1 items-center justify-center overflow-y-auto px-6 pt-6 outline-none",
|
||||
// The panel topbar sits above this container; matching bottom padding
|
||||
// keeps the cards centered against the full panel, not the leftover.
|
||||
"pb-[calc(var(--workspace-topbar-height)+--spacing(6))]",
|
||||
)}
|
||||
>
|
||||
<div className="relative w-full max-w-lg">
|
||||
<div className="absolute inset-x-0 bottom-full mb-5 text-center">
|
||||
<h3 className="font-medium text-foreground text-sm">Open a surface</h3>
|
||||
<p className="mt-1 text-muted-foreground text-xs">
|
||||
<div className="flex min-h-0 flex-1 items-center justify-center p-6">
|
||||
<div className="w-full max-w-xl">
|
||||
<div className="mb-5 text-center">
|
||||
<h3 className="text-sm font-medium text-foreground">Open a surface</h3>
|
||||
<p className="mt-1 text-xs text-muted-foreground">
|
||||
Choose what to show in the right panel.
|
||||
</p>
|
||||
</div>
|
||||
<div className="grid grid-cols-2 gap-2">
|
||||
{actions.map((action) =>
|
||||
action.available ? (
|
||||
<button
|
||||
key={action.label}
|
||||
type="button"
|
||||
onClick={action.onClick}
|
||||
onMouseEnter={() => setHighlight(availableActions.indexOf(action))}
|
||||
onMouseLeave={() =>
|
||||
setHighlight((current) =>
|
||||
current === availableActions.indexOf(action) ? -1 : current,
|
||||
)
|
||||
}
|
||||
className={cn(
|
||||
"relative flex w-full cursor-pointer flex-col items-start p-4 text-left transition hover:border-border hover:bg-accent/60",
|
||||
cardShellClass,
|
||||
isHighlighted(action) && highlightedCardClass,
|
||||
)}
|
||||
>
|
||||
<Kbd className="absolute top-3 right-3">{action.shortcut}</Kbd>
|
||||
<span className="flex items-center gap-2 pe-8">
|
||||
{actionIcon(action)}
|
||||
<span className="font-medium text-sm">{action.label}</span>
|
||||
{actions.map((action) => {
|
||||
const Icon = action.icon;
|
||||
const content = (
|
||||
<>
|
||||
<span className="relative mb-3 inline-flex">
|
||||
<Icon className="size-5" />
|
||||
{action.badgeCount > 0 ? (
|
||||
<span
|
||||
aria-hidden
|
||||
className="absolute -top-1.5 -right-2 flex h-3.5 min-w-3.5 items-center justify-center rounded-full bg-info px-1 text-[9px] font-semibold tabular-nums text-white"
|
||||
>
|
||||
{action.badgeCount}
|
||||
</span>
|
||||
) : null}
|
||||
</span>
|
||||
<span className="mt-1.5 text-muted-foreground text-xs leading-relaxed">
|
||||
<span className="text-sm font-medium">{action.label}</span>
|
||||
<span className="mt-1 text-xs leading-relaxed text-muted-foreground">
|
||||
{action.description}
|
||||
</span>
|
||||
</button>
|
||||
) : (
|
||||
<div
|
||||
key={action.label}
|
||||
className={cn(
|
||||
"relative flex w-full flex-col items-start p-4 opacity-40",
|
||||
cardShellClass,
|
||||
)}
|
||||
</>
|
||||
);
|
||||
if (action.available) {
|
||||
return (
|
||||
<button
|
||||
key={action.label}
|
||||
type="button"
|
||||
onClick={action.onClick}
|
||||
className="cursor-pointer flex min-h-28 w-full flex-col items-start rounded-lg border border-border/80 bg-card p-4 text-left transition hover:border-border hover:bg-accent/60 dark:border-transparent dark:shadow-none dark:inset-ring-1 dark:inset-ring-white/5"
|
||||
>
|
||||
{content}
|
||||
</button>
|
||||
);
|
||||
}
|
||||
const disabledCard = (
|
||||
<button
|
||||
type="button"
|
||||
className="flex min-h-28 w-full cursor-not-allowed flex-col items-start rounded-lg border border-border/80 bg-card p-4 text-left opacity-40 dark:border-transparent dark:shadow-none dark:inset-ring-1 dark:inset-ring-white/5"
|
||||
aria-disabled="true"
|
||||
>
|
||||
<Kbd className="absolute top-3 right-3">{action.shortcut}</Kbd>
|
||||
<span className="flex items-center gap-2 pe-8">
|
||||
{actionIcon(action)}
|
||||
<span className="font-medium text-sm">{action.label}</span>
|
||||
</span>
|
||||
<span className="mt-1.5 text-muted-foreground text-xs leading-relaxed">
|
||||
{action.disabledReason}
|
||||
</span>
|
||||
</div>
|
||||
),
|
||||
)}
|
||||
{content}
|
||||
</button>
|
||||
);
|
||||
return (
|
||||
<DisabledReasonTooltip
|
||||
key={action.label}
|
||||
reason={action.disabledReason}
|
||||
trigger={disabledCard}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -32,7 +32,6 @@ import {
|
||||
sortThreadsForSidebar,
|
||||
sortProjectsForSidebar,
|
||||
sortScopedProjectsForSidebar,
|
||||
shouldCreateNewThreadInCurrentProject,
|
||||
THREAD_JUMP_HINT_SHOW_DELAY_MS,
|
||||
} from "./Sidebar.logic";
|
||||
import {
|
||||
@@ -411,21 +410,6 @@ describe("isTrailingDoubleClick", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("shouldCreateNewThreadInCurrentProject", () => {
|
||||
it("creates directly on shift+click in a multi-project setup", () => {
|
||||
expect(shouldCreateNewThreadInCurrentProject(true, 2)).toBe(true);
|
||||
});
|
||||
|
||||
it("opens the picker on a plain click in a multi-project setup", () => {
|
||||
expect(shouldCreateNewThreadInCurrentProject(false, 2)).toBe(false);
|
||||
});
|
||||
|
||||
it("creates directly on any click with a single project", () => {
|
||||
expect(shouldCreateNewThreadInCurrentProject(false, 1)).toBe(true);
|
||||
expect(shouldCreateNewThreadInCurrentProject(true, 1)).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("orderItemsByPreferredIds", () => {
|
||||
it("keeps preferred ids first, skips stale ids, and preserves the relative order of remaining items", () => {
|
||||
const ordered = orderItemsByPreferredIds({
|
||||
|
||||
@@ -154,7 +154,8 @@ type ThreadStatusInput = Pick<
|
||||
| "session"
|
||||
| "backgroundLiveness"
|
||||
> & {
|
||||
lastVisitedAt?: string | undefined;
|
||||
// Nullable to accept the shell's server-synced lastVisitedAt directly.
|
||||
lastVisitedAt?: string | null | undefined;
|
||||
};
|
||||
|
||||
export interface ThreadJumpHintVisibilityController {
|
||||
@@ -274,17 +275,6 @@ export function isTrailingDoubleClick(detail: number): boolean {
|
||||
return detail > 1;
|
||||
}
|
||||
|
||||
// Shift+click on the new thread button creates directly in the current
|
||||
// project, skipping the command palette's project picker. With a single
|
||||
// project there is nothing to pick, so a plain click already creates
|
||||
// immediately and the modifier changes nothing.
|
||||
export function shouldCreateNewThreadInCurrentProject(
|
||||
shiftKey: boolean,
|
||||
projectGroupCount: number,
|
||||
): boolean {
|
||||
return shiftKey || projectGroupCount <= 1;
|
||||
}
|
||||
|
||||
export function orderItemsByPreferredIds<TItem, TId>(input: {
|
||||
items: readonly TItem[];
|
||||
preferredIds: readonly TId[];
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import { autoAnimate } from "@formkit/auto-animate";
|
||||
import { useAtomValue } from "@effect/atom-react";
|
||||
import * as Schema from "effect/Schema";
|
||||
import {
|
||||
DndContext,
|
||||
PointerSensor,
|
||||
@@ -29,7 +28,7 @@ import {
|
||||
scopeThreadRef,
|
||||
scopedThreadKey,
|
||||
} from "@t3tools/client-runtime/environment";
|
||||
import type { ScopedThreadRef, ThreadId } from "@t3tools/contracts";
|
||||
import type { ScopedThreadRef } from "@t3tools/contracts";
|
||||
import type { TimestampFormat } from "@t3tools/contracts/settings";
|
||||
import {
|
||||
AlarmClockIcon,
|
||||
@@ -101,7 +100,6 @@ import { openCommandPalette } from "../commandPaletteBus";
|
||||
import { startNewThreadFromContext } from "../lib/chatThreadActions";
|
||||
import { useClientSettings } from "../hooks/useSettings";
|
||||
import { useCopyToClipboard } from "../hooks/useCopyToClipboard";
|
||||
import { useLocalStorage } from "../hooks/useLocalStorage";
|
||||
import { useNowMinute } from "../hooks/useNowMinute";
|
||||
import { useEnvironments, usePrimaryEnvironmentId } from "../state/environments";
|
||||
import { useProjects, useThreadShells } from "../state/entities";
|
||||
@@ -131,7 +129,6 @@ import {
|
||||
resolveSettledTimestamp,
|
||||
resolveSidebarThreadStatus,
|
||||
searchSidebarThreadsByTitle,
|
||||
shouldCreateNewThreadInCurrentProject,
|
||||
resolveWorkingStartedAt,
|
||||
sortLogicalProjectsForSidebar,
|
||||
sortPinnedThreadsForSidebar,
|
||||
@@ -179,9 +176,6 @@ import {
|
||||
// stays behind an explicit Show more.
|
||||
const SETTLED_TAIL_INITIAL_COUNT = 10;
|
||||
const SETTLED_TAIL_PAGE_COUNT = 25;
|
||||
// Keep the v2 key so existing preferences survive the v2-to-default rename.
|
||||
const SETTLED_SHELF_EXPANDED_KEY = "t3code:sidebar-v2:settled-expanded";
|
||||
const SNOOZED_SHELF_EXPANDED_KEY = "t3code:sidebar-v2:snoozed-expanded";
|
||||
|
||||
function compactSidebarTimeLabel(label: string): string {
|
||||
if (label === "just now") return "now";
|
||||
@@ -731,7 +725,11 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: {
|
||||
);
|
||||
const threadKey = scopedThreadKey(threadRef);
|
||||
const isRegeneratingTitle = thread.titleRegeneration != null;
|
||||
const lastVisitedAt = useUiStateStore((state) => state.threadLastVisitedAtById[threadKey]);
|
||||
// Local visit stamps win (they carry this device's latest intent, incl.
|
||||
// mark-unread); the shell's server-synced lastVisitedAt fills the gap so a
|
||||
// visit on another device still clears the unread cue here.
|
||||
const localLastVisitedAt = useUiStateStore((state) => state.threadLastVisitedAtById[threadKey]);
|
||||
const lastVisitedAt = localLastVisitedAt ?? thread.lastVisitedAt ?? undefined;
|
||||
const isSelected = useThreadSelectionStore((state) => state.selectedThreadKeys.has(threadKey));
|
||||
const openPrLink = useOpenPrLink();
|
||||
const runningTerminalIds = useThreadRunningTerminalIds({
|
||||
@@ -1647,24 +1645,6 @@ export default function Sidebar() {
|
||||
);
|
||||
},
|
||||
});
|
||||
const { copyToClipboard: copyThreadIdToClipboard } = useCopyToClipboard<{ threadId: ThreadId }>({
|
||||
onCopy: ({ threadId }) => {
|
||||
toastManager.add({
|
||||
type: "success",
|
||||
title: "Thread ID copied",
|
||||
description: threadId,
|
||||
});
|
||||
},
|
||||
onError: (error) => {
|
||||
toastManager.add(
|
||||
stackedThreadToast({
|
||||
type: "error",
|
||||
title: "Failed to copy thread ID",
|
||||
description: error instanceof Error ? error.message : "An error occurred.",
|
||||
}),
|
||||
);
|
||||
},
|
||||
});
|
||||
const [projectScopeMenuOpen, setProjectScopeMenuOpen] = useState(false);
|
||||
const newThreadContext = useHandleNewThread();
|
||||
const openAddProjectCommandPalette = useCallback(
|
||||
@@ -2068,15 +2048,8 @@ export default function Sidebar() {
|
||||
() => setSettledVisibleCount((count) => count + SETTLED_TAIL_PAGE_COUNT),
|
||||
[],
|
||||
);
|
||||
const [settledShelfExpanded, setSettledShelfExpanded] = useLocalStorage(
|
||||
SETTLED_SHELF_EXPANDED_KEY,
|
||||
true,
|
||||
Schema.Boolean,
|
||||
);
|
||||
const toggleSettledShelf = useCallback(
|
||||
() => setSettledShelfExpanded((value) => !value),
|
||||
[setSettledShelfExpanded],
|
||||
);
|
||||
const [settledShelfExpanded, setSettledShelfExpanded] = useState(true);
|
||||
const toggleSettledShelf = useCallback(() => setSettledShelfExpanded((value) => !value), []);
|
||||
const renderedSettledThreads = useMemo(() => {
|
||||
if (settledShelfExpanded) return visibleSettledThreads;
|
||||
if (routeThreadKey === null) return [];
|
||||
@@ -2090,15 +2063,8 @@ export default function Sidebar() {
|
||||
// The snoozed shelf is collapsed by default: out of the way, never gone.
|
||||
// Collapsed threads don't render (and so don't participate in jump
|
||||
// shortcuts or multi-select), matching the settled tail's paging model.
|
||||
const [snoozedShelfExpanded, setSnoozedShelfExpanded] = useLocalStorage(
|
||||
SNOOZED_SHELF_EXPANDED_KEY,
|
||||
false,
|
||||
Schema.Boolean,
|
||||
);
|
||||
const toggleSnoozedShelf = useCallback(
|
||||
() => setSnoozedShelfExpanded((value) => !value),
|
||||
[setSnoozedShelfExpanded],
|
||||
);
|
||||
const [snoozedShelfExpanded, setSnoozedShelfExpanded] = useState(false);
|
||||
const toggleSnoozedShelf = useCallback(() => setSnoozedShelfExpanded((value) => !value), []);
|
||||
const visibleSnoozedThreads = useMemo(() => {
|
||||
if (snoozedShelfExpanded) return snoozedThreads;
|
||||
// The open thread must never vanish behind the collapsed shelf: a
|
||||
@@ -3055,9 +3021,6 @@ export default function Sidebar() {
|
||||
copyBranchToClipboard(thread.branch, { branch: thread.branch });
|
||||
}
|
||||
return;
|
||||
case "copy-thread-id":
|
||||
copyThreadIdToClipboard(thread.id, { threadId: thread.id });
|
||||
return;
|
||||
case "delete": {
|
||||
if (confirmThreadDelete) {
|
||||
const confirmed = await settlePromise(() =>
|
||||
@@ -3100,7 +3063,6 @@ export default function Sidebar() {
|
||||
confirmThreadDelete,
|
||||
copyBranchToClipboard,
|
||||
copyPathToClipboard,
|
||||
copyThreadIdToClipboard,
|
||||
deleteThread,
|
||||
handleMultiSelectContextMenu,
|
||||
markThreadUnread,
|
||||
@@ -3187,39 +3149,29 @@ export default function Sidebar() {
|
||||
// falling back to the top project) — same resolution the command palette
|
||||
// uses. The command palette already offers a "New thread in..." submenu
|
||||
// for multi-project setups.
|
||||
const handleNewThreadClick = useCallback(
|
||||
(event?: ReactMouseEvent) => {
|
||||
// One project: nothing to pick, create immediately. Shift+click creates
|
||||
// directly in the current project even with several projects, skipping
|
||||
// the palette picker.
|
||||
if (shouldCreateNewThreadInCurrentProject(event?.shiftKey ?? false, projectGroups.length)) {
|
||||
if (isMobile) setOpenMobile(false);
|
||||
void startNewThreadFromContext({
|
||||
activeDraftThread: newThreadContext.activeDraftThread,
|
||||
activeThread: newThreadContext.activeThread ?? undefined,
|
||||
defaultProjectRef: newThreadContext.defaultProjectRef,
|
||||
handleNewThread: newThreadContext.handleNewThread,
|
||||
});
|
||||
return;
|
||||
}
|
||||
const handleNewThreadClick = useCallback(() => {
|
||||
// One project: nothing to pick, create immediately.
|
||||
if (projectGroups.length <= 1) {
|
||||
if (isMobile) setOpenMobile(false);
|
||||
openCommandPalette({ open: "new-thread-in" });
|
||||
},
|
||||
[isMobile, newThreadContext, projectGroups.length, setOpenMobile],
|
||||
);
|
||||
void startNewThreadFromContext({
|
||||
activeDraftThread: newThreadContext.activeDraftThread,
|
||||
activeThread: newThreadContext.activeThread ?? undefined,
|
||||
defaultProjectRef: newThreadContext.defaultProjectRef,
|
||||
handleNewThread: newThreadContext.handleNewThread,
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (isMobile) setOpenMobile(false);
|
||||
openCommandPalette({ open: "new-thread-in" });
|
||||
}, [isMobile, newThreadContext, projectGroups.length, setOpenMobile]);
|
||||
|
||||
// The button mirrors chat.new: in multi-project setups both route through
|
||||
// the command palette's "New thread in..." picker, and in single-project
|
||||
// setups both create immediately. In multi-project setups the label is only
|
||||
// the picker's shortcut: falling back to chat.newLocal would advertise the
|
||||
// same shortcut for both the picker and direct create. In single-project
|
||||
// setups both commands create directly, so chat.newLocal is a valid
|
||||
// fallback. The second tooltip line (multi-project only) advertises
|
||||
// shift+click and its keyboard twin chat.newLocal for direct create.
|
||||
// setups both create immediately. chat.newLocal always creates directly, so
|
||||
// it is only a correct label when chat.new is unbound.
|
||||
const newThreadShortcutLabel =
|
||||
shortcutLabelForCommand(keybindings, "chat.new") ??
|
||||
(projectGroups.length <= 1 ? shortcutLabelForCommand(keybindings, "chat.newLocal") : undefined);
|
||||
const newThreadInProjectShortcutLabel = shortcutLabelForCommand(keybindings, "chat.newLocal");
|
||||
shortcutLabelForCommand(keybindings, "chat.newLocal");
|
||||
return (
|
||||
<>
|
||||
<SidebarChromeHeader isElectron={isElectron} />
|
||||
@@ -3297,25 +3249,9 @@ export default function Sidebar() {
|
||||
/>
|
||||
</TooltipTrigger>
|
||||
<TooltipPopup side="right">
|
||||
{projectGroups.length > 1 ? (
|
||||
<span className="flex flex-col gap-0.5">
|
||||
<span>
|
||||
{newThreadShortcutLabel
|
||||
? `New thread (${newThreadShortcutLabel})`
|
||||
: "New thread"}
|
||||
</span>
|
||||
<span className="text-muted-foreground">
|
||||
New thread in current project: Shift+click
|
||||
{newThreadInProjectShortcutLabel
|
||||
? ` (${newThreadInProjectShortcutLabel})`
|
||||
: ""}
|
||||
</span>
|
||||
</span>
|
||||
) : newThreadShortcutLabel ? (
|
||||
`New thread (${newThreadShortcutLabel})`
|
||||
) : (
|
||||
"New thread"
|
||||
)}
|
||||
{newThreadShortcutLabel
|
||||
? `New thread (${newThreadShortcutLabel})`
|
||||
: "New thread"}
|
||||
</TooltipPopup>
|
||||
</Tooltip>
|
||||
</div>
|
||||
|
||||
@@ -4,9 +4,7 @@ import { renderToStaticMarkup } from "react-dom/server";
|
||||
import {
|
||||
resolveEnvironmentIdentificationPillLabel,
|
||||
resolveSidebarStageBackdropVariant,
|
||||
resolveSidebarStageFocusRingOffsetClass,
|
||||
StageBackdropArt,
|
||||
StageBackdropButtonArt,
|
||||
} from "./SidebarStageBackdrop";
|
||||
|
||||
describe("SidebarStageBackdrop", () => {
|
||||
@@ -24,15 +22,6 @@ describe("SidebarStageBackdrop", () => {
|
||||
expect(resolveEnvironmentIdentificationPillLabel("Alpha")).toBeNull();
|
||||
});
|
||||
|
||||
it("matches the focus-ring offset to each artwork palette", () => {
|
||||
expect(resolveSidebarStageFocusRingOffsetClass("nightly")).toBe(
|
||||
"focus-visible:ring-offset-(--stage-night-bottom)",
|
||||
);
|
||||
expect(resolveSidebarStageFocusRingOffsetClass("dev")).toBe(
|
||||
"focus-visible:ring-offset-(--stage-art-bottom)",
|
||||
);
|
||||
});
|
||||
|
||||
it.each(["nightly", "dev"] as const)(
|
||||
"uses unique SVG definition ids when %s artwork is rendered more than once",
|
||||
(variant) => {
|
||||
@@ -48,26 +37,4 @@ describe("SidebarStageBackdrop", () => {
|
||||
expect(new Set(ids).size).toBe(ids.length);
|
||||
},
|
||||
);
|
||||
|
||||
it("paints each artwork variant with theme-owned color tokens", () => {
|
||||
const nightlyMarkup = renderToStaticMarkup(<StageBackdropArt variant="nightly" />);
|
||||
const devMarkup = renderToStaticMarkup(<StageBackdropArt variant="dev" />);
|
||||
|
||||
expect(nightlyMarkup).toContain("var(--stage-night-bottom)");
|
||||
expect(nightlyMarkup).toContain("var(--stage-night-line)");
|
||||
expect(devMarkup).toContain("var(--stage-art-bottom)");
|
||||
expect(devMarkup).toContain("var(--stage-art-line)");
|
||||
expect(nightlyMarkup).not.toMatch(/#[0-9a-f]{3,8}/i);
|
||||
expect(devMarkup).not.toMatch(/#[0-9a-f]{3,8}/i);
|
||||
});
|
||||
|
||||
it.each([
|
||||
["nightly", "96 0 8192 96"],
|
||||
["dev", "64 0 8192 96"],
|
||||
] as const)("uses the compact %s crop inside the send button", (variant, viewBox) => {
|
||||
const markup = renderToStaticMarkup(<StageBackdropButtonArt variant={variant} />);
|
||||
|
||||
expect(markup).toContain(`viewBox="${viewBox}"`);
|
||||
expect(markup).toContain(`stage-${variant === "dev" ? "blueprint" : "nightly"}`);
|
||||
});
|
||||
});
|
||||
@@ -23,14 +23,6 @@ export function resolveSidebarStageBackdropVariant(
|
||||
return null;
|
||||
}
|
||||
|
||||
export function resolveSidebarStageFocusRingOffsetClass(
|
||||
variant: SidebarStageBackdropVariant,
|
||||
): string {
|
||||
return variant === "nightly"
|
||||
? "focus-visible:ring-offset-(--stage-night-bottom)"
|
||||
: "focus-visible:ring-offset-(--stage-art-bottom)";
|
||||
}
|
||||
|
||||
export function resolveEnvironmentIdentificationPillLabel(
|
||||
stageLabel: string,
|
||||
): EnvironmentIdentificationPillLabel | null {
|
||||
@@ -70,10 +62,6 @@ export function StageBackdropArt({ variant }: { variant: SidebarStageBackdropVar
|
||||
return variant === "nightly" ? <NightlySkyArt /> : <DevBlueprintArt />;
|
||||
}
|
||||
|
||||
export function StageBackdropButtonArt({ variant }: { variant: SidebarStageBackdropVariant }) {
|
||||
return variant === "nightly" ? <NightlySkyArt compact /> : <DevBlueprintArt compact />;
|
||||
}
|
||||
|
||||
const NIGHTLY_STARS: ReadonlyArray<{
|
||||
cx: number;
|
||||
cy: number;
|
||||
@@ -105,7 +93,7 @@ const NIGHTLY_SPARKLES: ReadonlyArray<{ x: number; y: number }> = [
|
||||
{ x: 246, y: 26 },
|
||||
];
|
||||
|
||||
function NightlySkyArt({ compact = false }: { compact?: boolean }) {
|
||||
function NightlySkyArt() {
|
||||
const idPrefix = useId().replaceAll(":", "");
|
||||
const skyId = `${idPrefix}-stage-night-sky`;
|
||||
const glowId = `${idPrefix}-stage-night-glow`;
|
||||
@@ -116,10 +104,10 @@ function NightlySkyArt({ compact = false }: { compact?: boolean }) {
|
||||
|
||||
return (
|
||||
<svg
|
||||
className="stage-art stage-nightly h-full w-full"
|
||||
className="h-full w-full"
|
||||
fill="none"
|
||||
preserveAspectRatio="xMinYMin slice"
|
||||
viewBox={compact ? "96 0 8192 96" : STAGE_BACKDROP_VIEW_BOX}
|
||||
viewBox={STAGE_BACKDROP_VIEW_BOX}
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
>
|
||||
<defs>
|
||||
@@ -132,9 +120,9 @@ function NightlySkyArt({ compact = false }: { compact?: boolean }) {
|
||||
gradientUnits="userSpaceOnUse"
|
||||
spreadMethod="reflect"
|
||||
>
|
||||
<stop style={{ stopColor: "var(--stage-night-bottom)" }} />
|
||||
<stop offset="0.5" style={{ stopColor: "var(--stage-night-mid)" }} />
|
||||
<stop offset="1" style={{ stopColor: "var(--stage-night-top)" }} />
|
||||
<stop stopColor="#07152F" />
|
||||
<stop offset="0.5" stopColor="#151443" />
|
||||
<stop offset="1" stopColor="#32155B" />
|
||||
</linearGradient>
|
||||
<radialGradient
|
||||
id={glowId}
|
||||
@@ -144,28 +132,20 @@ function NightlySkyArt({ compact = false }: { compact?: boolean }) {
|
||||
gradientTransform="translate(216 18) rotate(137) scale(120 84)"
|
||||
gradientUnits="userSpaceOnUse"
|
||||
>
|
||||
<stop style={{ stopColor: "var(--stage-night-highlight)" }} stopOpacity="0.4" />
|
||||
<stop
|
||||
offset="0.5"
|
||||
style={{ stopColor: "var(--stage-night-secondary)" }}
|
||||
stopOpacity="0.16"
|
||||
/>
|
||||
<stop offset="1" style={{ stopColor: "var(--stage-night-bottom)" }} stopOpacity="0" />
|
||||
<stop stopColor="#5165D8" stopOpacity="0.4" />
|
||||
<stop offset="0.5" stopColor="#283075" stopOpacity="0.16" />
|
||||
<stop offset="1" stopColor="#111635" stopOpacity="0" />
|
||||
</radialGradient>
|
||||
<linearGradient id={cloudId} x1="0" y1="60" x2="288" y2="96" gradientUnits="userSpaceOnUse">
|
||||
<stop style={{ stopColor: "var(--stage-night-highlight)" }} stopOpacity="0.5" />
|
||||
<stop
|
||||
offset="0.52"
|
||||
style={{ stopColor: "var(--stage-night-secondary)" }}
|
||||
stopOpacity="0.62"
|
||||
/>
|
||||
<stop offset="1" style={{ stopColor: "var(--stage-night-tertiary)" }} stopOpacity="0.5" />
|
||||
<stop stopColor="#4EA4FF" stopOpacity="0.5" />
|
||||
<stop offset="0.52" stopColor="#696FEA" stopOpacity="0.62" />
|
||||
<stop offset="1" stopColor="#A85BEA" stopOpacity="0.5" />
|
||||
</linearGradient>
|
||||
<filter id={softId} x="-24" y="-24" width="336" height="144" filterUnits="userSpaceOnUse">
|
||||
<feGaussianBlur stdDeviation="4" />
|
||||
</filter>
|
||||
<pattern id={starsId} width="288" height="96" patternUnits="userSpaceOnUse">
|
||||
<g style={{ fill: "var(--stage-night-line)" }}>
|
||||
<g fill="#E4EAFF">
|
||||
{NIGHTLY_STARS.map((star) => (
|
||||
<circle
|
||||
key={`${star.cx}-${star.cy}`}
|
||||
@@ -176,12 +156,7 @@ function NightlySkyArt({ compact = false }: { compact?: boolean }) {
|
||||
/>
|
||||
))}
|
||||
</g>
|
||||
<g
|
||||
style={{ stroke: "var(--stage-night-line)" }}
|
||||
strokeLinecap="round"
|
||||
strokeOpacity="0.7"
|
||||
strokeWidth="0.6"
|
||||
>
|
||||
<g stroke="#C8D7FF" strokeLinecap="round" strokeOpacity="0.7" strokeWidth="0.6">
|
||||
{NIGHTLY_SPARKLES.map((sparkle) => (
|
||||
<g key={`${sparkle.x}-${sparkle.y}`}>
|
||||
<path d={`M${sparkle.x - 1.5} ${sparkle.y}H${sparkle.x + 1.5}`} />
|
||||
@@ -216,7 +191,7 @@ function NightlySkyArt({ compact = false }: { compact?: boolean }) {
|
||||
);
|
||||
}
|
||||
|
||||
function DevBlueprintArt({ compact = false }: { compact?: boolean }) {
|
||||
function DevBlueprintArt() {
|
||||
const idPrefix = useId().replaceAll(":", "");
|
||||
const paperId = `${idPrefix}-stage-bp-paper`;
|
||||
const glowId = `${idPrefix}-stage-bp-glow`;
|
||||
@@ -230,10 +205,10 @@ function DevBlueprintArt({ compact = false }: { compact?: boolean }) {
|
||||
|
||||
return (
|
||||
<svg
|
||||
className="stage-art stage-blueprint h-full w-full"
|
||||
className="stage-blueprint h-full w-full"
|
||||
fill="none"
|
||||
preserveAspectRatio="xMinYMin slice"
|
||||
viewBox={compact ? "64 0 8192 96" : STAGE_BACKDROP_VIEW_BOX}
|
||||
viewBox={STAGE_BACKDROP_VIEW_BOX}
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
>
|
||||
<defs>
|
||||
@@ -246,9 +221,9 @@ function DevBlueprintArt({ compact = false }: { compact?: boolean }) {
|
||||
gradientUnits="userSpaceOnUse"
|
||||
spreadMethod="reflect"
|
||||
>
|
||||
<stop style={{ stopColor: "var(--stage-art-bottom)" }} />
|
||||
<stop offset="0.5" style={{ stopColor: "var(--stage-art-mid)" }} />
|
||||
<stop offset="1" style={{ stopColor: "var(--stage-art-top)" }} />
|
||||
<stop style={{ stopColor: "var(--stage-bp-bottom)" }} />
|
||||
<stop offset="0.5" style={{ stopColor: "var(--stage-bp-mid)" }} />
|
||||
<stop offset="1" style={{ stopColor: "var(--stage-bp-top)" }} />
|
||||
</linearGradient>
|
||||
<radialGradient
|
||||
id={glowId}
|
||||
@@ -258,13 +233,9 @@ function DevBlueprintArt({ compact = false }: { compact?: boolean }) {
|
||||
gradientTransform="translate(216 14) rotate(137) scale(120 84)"
|
||||
gradientUnits="userSpaceOnUse"
|
||||
>
|
||||
<stop style={{ stopColor: "var(--stage-art-highlight)" }} stopOpacity="0.4" />
|
||||
<stop
|
||||
offset="0.52"
|
||||
style={{ stopColor: "var(--stage-art-secondary)" }}
|
||||
stopOpacity="0.16"
|
||||
/>
|
||||
<stop offset="1" style={{ stopColor: "var(--stage-art-bottom)" }} stopOpacity="0" />
|
||||
<stop stopColor="#D4F6FF" stopOpacity="0.4" />
|
||||
<stop offset="0.52" stopColor="#65C8FF" stopOpacity="0.16" />
|
||||
<stop offset="1" stopColor="#276AF1" stopOpacity="0" />
|
||||
</radialGradient>
|
||||
<radialGradient
|
||||
id={celesteGlowId}
|
||||
@@ -274,13 +245,9 @@ function DevBlueprintArt({ compact = false }: { compact?: boolean }) {
|
||||
gradientTransform="translate(474 44) rotate(166) scale(156 92)"
|
||||
gradientUnits="userSpaceOnUse"
|
||||
>
|
||||
<stop style={{ stopColor: "var(--stage-art-highlight)" }} stopOpacity="0.34" />
|
||||
<stop
|
||||
offset="0.5"
|
||||
style={{ stopColor: "var(--stage-art-secondary)" }}
|
||||
stopOpacity="0.18"
|
||||
/>
|
||||
<stop offset="1" style={{ stopColor: "var(--stage-art-bottom)" }} stopOpacity="0" />
|
||||
<stop stopColor="#D2FFFF" stopOpacity="0.34" />
|
||||
<stop offset="0.5" stopColor="#48DCF5" stopOpacity="0.18" />
|
||||
<stop offset="1" stopColor="#277EF1" stopOpacity="0" />
|
||||
</radialGradient>
|
||||
<radialGradient
|
||||
id={violetGlowId}
|
||||
@@ -290,34 +257,20 @@ function DevBlueprintArt({ compact = false }: { compact?: boolean }) {
|
||||
gradientTransform="translate(704 18) rotate(145) scale(132 88)"
|
||||
gradientUnits="userSpaceOnUse"
|
||||
>
|
||||
<stop style={{ stopColor: "var(--stage-art-highlight)" }} stopOpacity="0.3" />
|
||||
<stop
|
||||
offset="0.52"
|
||||
style={{ stopColor: "var(--stage-art-tertiary)" }}
|
||||
stopOpacity="0.14"
|
||||
/>
|
||||
<stop offset="1" style={{ stopColor: "var(--stage-art-bottom)" }} stopOpacity="0" />
|
||||
<stop stopColor="#D9D8FF" stopOpacity="0.3" />
|
||||
<stop offset="0.52" stopColor="#7C8BFF" stopOpacity="0.14" />
|
||||
<stop offset="1" stopColor="#3155DF" stopOpacity="0" />
|
||||
</radialGradient>
|
||||
<pattern id={minorGridId} width="8" height="8" patternUnits="userSpaceOnUse">
|
||||
<path
|
||||
d="M8 0H0V8"
|
||||
style={{ stroke: "var(--stage-art-line)" }}
|
||||
strokeOpacity="0.14"
|
||||
strokeWidth="0.5"
|
||||
/>
|
||||
<path d="M8 0H0V8" stroke="#EAF6FF" strokeOpacity="0.14" strokeWidth="0.5" />
|
||||
</pattern>
|
||||
<pattern id={majorGridId} width="32" height="32" patternUnits="userSpaceOnUse">
|
||||
<path
|
||||
d="M32 0H0V32"
|
||||
style={{ stroke: "var(--stage-art-line)" }}
|
||||
strokeOpacity="0.26"
|
||||
strokeWidth="0.6"
|
||||
/>
|
||||
<path d="M32 0H0V32" stroke="#EAF6FF" strokeOpacity="0.26" strokeWidth="0.6" />
|
||||
</pattern>
|
||||
<pattern id={rulerId} width="32" height="6" patternUnits="userSpaceOnUse">
|
||||
<path
|
||||
d="M4 0V2.5M12 0V2.5M20 0V4M28 0V2.5"
|
||||
style={{ stroke: "var(--stage-art-line)" }}
|
||||
stroke="#DDF7FF"
|
||||
strokeOpacity="0.5"
|
||||
strokeWidth="0.5"
|
||||
/>
|
||||
@@ -328,12 +281,7 @@ function DevBlueprintArt({ compact = false }: { compact?: boolean }) {
|
||||
<rect width="768" height="96" fill={`url(#${violetGlowId})`} />
|
||||
</pattern>
|
||||
<pattern id={annotationsId} width="768" height="96" patternUnits="userSpaceOnUse">
|
||||
<g
|
||||
style={{ stroke: "var(--stage-art-line)" }}
|
||||
strokeLinecap="round"
|
||||
strokeOpacity="0.6"
|
||||
strokeWidth="0.7"
|
||||
>
|
||||
<g stroke="#DDF7FF" strokeLinecap="round" strokeOpacity="0.6" strokeWidth="0.7">
|
||||
<path d="M180 64H264" strokeDasharray="5 4" />
|
||||
<path d="M180 61V67M264 61V67" />
|
||||
<path d="M276 10V44" strokeDasharray="4 4" strokeOpacity="0.5" />
|
||||
@@ -346,12 +294,7 @@ function DevBlueprintArt({ compact = false }: { compact?: boolean }) {
|
||||
<path d="M590 67V73M724 67V73" strokeOpacity="0.55" />
|
||||
</g>
|
||||
|
||||
<g
|
||||
style={{ stroke: "var(--stage-art-line)" }}
|
||||
strokeLinecap="round"
|
||||
strokeOpacity="0.55"
|
||||
strokeWidth="0.6"
|
||||
>
|
||||
<g stroke="#DDF7FF" strokeLinecap="round" strokeOpacity="0.55" strokeWidth="0.6">
|
||||
<g>
|
||||
<path d="M34 60L38 64M38 60L34 64" />
|
||||
</g>
|
||||
@@ -375,7 +318,7 @@ function DevBlueprintArt({ compact = false }: { compact?: boolean }) {
|
||||
</g>
|
||||
</g>
|
||||
|
||||
<g style={{ stroke: "var(--stage-art-line)" }} strokeOpacity="0.35" strokeWidth="0.6">
|
||||
<g stroke="#DDF7FF" strokeOpacity="0.35" strokeWidth="0.6">
|
||||
<circle cx="196" cy="38" r="13" strokeDasharray="3.5 4" />
|
||||
<path d="M196 33V43M191 38H201" strokeOpacity="0.6" strokeWidth="0.4" />
|
||||
<circle cx="414" cy="64" r="10" strokeDasharray="2.5 3.5" />
|
||||
|
||||
@@ -258,7 +258,9 @@ export function ThreadRowLeadingStatus({ thread }: { thread: SidebarThreadSummar
|
||||
const threadStatus = resolveThreadStatusPill({
|
||||
thread: {
|
||||
...thread,
|
||||
lastVisitedAt,
|
||||
// Local stamp wins; the shell's server-synced visit fills the gap so a
|
||||
// visit on another device clears the unread cue here too.
|
||||
lastVisitedAt: lastVisitedAt ?? thread.lastVisitedAt ?? undefined,
|
||||
},
|
||||
});
|
||||
|
||||
|
||||
@@ -23,14 +23,6 @@ describe("ChangedFilesCard", () => {
|
||||
expect(markup).toContain('data-changed-files-state="expanded"');
|
||||
expect(markup).toContain('aria-expanded="true"');
|
||||
expect(markup).toContain("whitespace-nowrap");
|
||||
expect(markup).toContain(
|
||||
'class="group flex min-w-0 flex-1 items-center gap-1.5 overflow-hidden',
|
||||
);
|
||||
expect(markup).toContain('class="flex shrink-0 items-center gap-1 whitespace-nowrap');
|
||||
expect(markup).toContain('class="ml-1 hidden min-w-0 flex-1 truncate');
|
||||
expect(markup).toContain("@[24rem]/changed-files:inline");
|
||||
expect(markup).not.toContain("sm:inline");
|
||||
expect(markup).toContain('class="flex shrink-0 items-center gap-1.5"');
|
||||
expect(markup).toContain("!size-[22px]");
|
||||
expect(markup).toContain("size-3");
|
||||
expect(markup).toContain('aria-label="Collapse all folders"');
|
||||
|
||||
@@ -56,7 +56,7 @@ export const ChangedFilesCard = memo(function ChangedFilesCard(props: {
|
||||
|
||||
return (
|
||||
<div
|
||||
className="@container/changed-files mt-4 rounded-2xl border border-border/70 bg-secondary p-2 dark:border-transparent dark:bg-input/32"
|
||||
className="mt-4 rounded-2xl border border-border/70 bg-secondary p-2 dark:border-transparent dark:bg-input/32"
|
||||
data-changed-files-state={
|
||||
expanded ? "expanded" : compactPreviewVisible ? "preview" : "collapsed"
|
||||
}
|
||||
@@ -73,7 +73,7 @@ export const ChangedFilesCard = memo(function ChangedFilesCard(props: {
|
||||
type="button"
|
||||
aria-expanded={expanded}
|
||||
data-scroll-anchor-ignore
|
||||
className="group flex min-w-0 flex-1 items-center gap-1.5 overflow-hidden rounded-lg px-1 py-1.5 text-left transition-colors hover:bg-accent/60 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
|
||||
className="group flex min-w-0 flex-1 items-center gap-1.5 rounded-lg px-1 py-1.5 text-left transition-colors hover:bg-accent/60 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
|
||||
onClick={() => onExpandedChange(!expanded)}
|
||||
>
|
||||
<ChevronRightIcon
|
||||
@@ -83,7 +83,7 @@ export const ChangedFilesCard = memo(function ChangedFilesCard(props: {
|
||||
expanded && "rotate-90",
|
||||
)}
|
||||
/>
|
||||
<span className="flex shrink-0 items-center gap-1 whitespace-nowrap font-medium text-foreground text-xs leading-4">
|
||||
<span className="flex min-w-0 items-center gap-1 whitespace-nowrap font-medium text-foreground text-xs leading-4">
|
||||
<span>
|
||||
{files.length} changed file{files.length === 1 ? "" : "s"}
|
||||
</span>
|
||||
@@ -96,11 +96,11 @@ export const ChangedFilesCard = memo(function ChangedFilesCard(props: {
|
||||
/>
|
||||
)}
|
||||
</span>
|
||||
<span className="ml-1 hidden min-w-0 flex-1 truncate text-[11px] text-muted-foreground group-hover:text-foreground/80 @[24rem]/changed-files:inline">
|
||||
<span className="ml-1 hidden truncate text-[11px] text-muted-foreground group-hover:text-foreground/80 sm:inline">
|
||||
{expanded ? "Hide files" : "Show files"}
|
||||
</span>
|
||||
</button>
|
||||
<div className="flex shrink-0 items-center gap-1.5">
|
||||
<div className="flex items-center gap-1.5">
|
||||
{expanded ? (
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
@@ -142,7 +142,7 @@ export const ChangedFilesCard = memo(function ChangedFilesCard(props: {
|
||||
}
|
||||
>
|
||||
<FileDiffIcon className="size-3" />
|
||||
<span className="hidden @[24rem]/changed-files:inline">Open diff</span>
|
||||
<span className="hidden sm:inline">Open diff</span>
|
||||
</TooltipTrigger>
|
||||
<TooltipPopup side="top">Open the full diff</TooltipPopup>
|
||||
</Tooltip>
|
||||
|
||||
Loaded 100 of 170 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user