Compare commits

...
Author SHA1 Message Date
Theo BrowneandClaude Fable 5 ed497ee20b fix(server): stop steps outlive the service manager's shutdown window
Review findings: raising ExitTimeOut to 90 put the stop above the
ProcessRunner's 60s default, so a slow shutdown got its bootout cancelled
and the strict bootstrap raced a still-loaded job. Stop and deactivate
steps on both platforms now run with a 120s timeout. Also corrects the
launchd default-timeout comment (system-defined, ~5s, not 20s), pins
ExitTimeOut and stop timeouts in tests, and documents the Login Items
toggle.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-12 06:22:34 -07:00
Theo BrowneandClaude Fable 5 653a7880ce fix(server): start the launch agent once via strict bootstrap
Review findings: bootstrap of a RunAtLoad/KeepAlive plist already starts
the job, so the trailing kickstart -k killed a server it just booted.
Bootstrap is now the strict last step. ExitTimeOut raised to 90 to match
systemd's default stop timeout for update handoffs. Docs corrected for
headless SSH installs, TCC prompts, and FileVault vs auto-login.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-12 02:28:33 -07:00
Theo BrowneandClaude Fable 5 adff784c33 feat(server): run the background service on macOS via launchd
t3 service was systemd-only. Adds a per-user LaunchAgent path that reuses
the pinned runtime, launcher, and update protocol unchanged.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-12 01:30:31 -07:00
t3-code[bot]andmaria 5a84614809 fix(web): align the composer model picker (#6252)
Co-authored-by: t3-code[bot] <269035359+t3-code[bot]@users.noreply.github.com>
Co-authored-by: maria <[email protected]>
2026-08-11 22:38:45 -04:00
maria 63e6faef62 chore: add dara to vouched (#6259) 2026-08-11 21:51:00 -04:00
Chris Deeming d37a9b09b8 feat(mobile): add thread title regeneration (#6253) 2026-08-11 21:43:05 -04:00
Exotic 560d4a4560 fix(web): keep sidebar wordmark visible at minimum width (#6246) 2026-08-11 19:57:10 -04:00
maria 52e5a75a87 feat(web): compact sidebar footer actions (#6210) 2026-08-11 18:53:40 -04:00
Exotic c196f422ed fix(web): clean up composer resize animation (#6209) 2026-08-11 23:21:44 +02:00
f0b57ca231 feat(web): add Open VSX theme search (#5654)
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: codex <[email protected]>
2026-08-11 20:06:05 +00:00
t3-code[bot] 2db08457f2 fix(web): use upload icon for disabled push action (#6207) 2026-08-11 20:25:24 +02:00
Wout Stiens 083fa4ab24 feat(web): use OKLCH for theme palettes (#6036) 2026-08-11 20:00:17 +02:00
Exotic 35172010b1 fix(web): use a clearer pull action icon (#6194) 2026-08-11 16:39:59 +00:00
Mina Yacoub 57b1052679 fix(web): thread error banner dismiss survives reconnect and rerenders (#6123) 2026-08-11 12:27:55 -04:00
1e355a2a34 fix(web): render dropdowns above toasts (#6165)
Co-authored-by: Rodrigo Brechard <[email protected]>
Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
2026-08-11 12:27:02 -04:00
Utkarsh Patilandshivam 44621c345f feat(web): add back buttons for the pull requests and usage pages in the sidebar footer (#6031)
Co-authored-by: shivam <[email protected]>
2026-08-11 12:26:24 -04:00
Arham AminandClaude Opus 4.8 220e573b14 fix(shared): detect Azure DevOps SSH remotes (ssh.dev.azure.com) (#6187)
Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
2026-08-11 16:14:02 +00:00
Arham AminandClaude Opus 4.8 6befe42eb0 fix(shared): normalize a bare Windows drive root the same as C:\ / C:/ (#6189)
Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
2026-08-11 15:52:23 +00:00
Julius Marmingeandcodex b30a9bc414 feat(web): make environment artwork theme aware (#6183)
Co-authored-by: codex <[email protected]>
2026-08-11 17:46:52 +02:00
Wout Stiens ac4780f451 fix(web): restore typography font sizes to defaults (#6172) 2026-08-11 17:21:58 +02:00
Julius Marmingeandcodex 3da7f9c5c3 fix(mobile): guard App Store release versions (#6177)
Co-authored-by: codex <[email protected]>
2026-08-11 15:06:54 +00:00
Julius Marminge c842c6f5b9 Add hourly past-24-hour usage view (#6170) 2026-08-11 16:47:13 +02:00
6676f9c83b fix(mobile): stabilize thread composer and interactions (#5986)
Co-authored-by: codex <[email protected]>
Co-authored-by: Thuong Tin <[email protected]>
Co-authored-by: Kapish14 <[email protected]>
Co-authored-by: Claude Fable 5 <[email protected]>
2026-08-11 14:05:03 +00:00
Utkarsh Patilandshivam 65b005f1e4 feat(web): add Copy Thread ID to the sidebar and chat header thread context menu (#5574)
Co-authored-by: shivam <[email protected]>
2026-08-11 18:32:02 +05:30
Utkarsh Patilandshivam 752acbf654 feat: add ability to create a new thread in the current project with shift+click and show shortcut in tooltip (#5994)
Co-authored-by: shivam <[email protected]>
2026-08-11 18:26:53 +05:30
Guilherme Vieira f5fce74169 fix(pull-requests): route self-hosted GitLab remotes (#6061) 2026-08-11 13:11:19 +02:00
t3-code[bot] 9c7622dac3 fix(server): handle unborn HEAD in VCS status (#5944)
Co-authored-by: t3-code[bot] <269035359+t3-code[bot]@users.noreply.github.com>
2026-08-10 23:34:18 -04:00
yassiEmp c14bcca103 fix(server): advertise 256-color TERM on Windows terminals (#5693) 2026-08-10 23:33:58 -04:00
bkntr 1fa315ea93 fix(server): skip Linux libc detection on Windows/macOS (#5354) 2026-08-10 23:33:18 -04:00
Taras f9730979c1 perf(web): skip base64 for oversized image candidates (#5220) 2026-08-10 23:33:08 -04:00
AlexandIllia Panasenko 59d0c922e9 fix(web): persist sidebar shelf collapse state (#5136)
Co-authored-by: Illia Panasenko <[email protected]>
2026-08-10 23:32:22 -04:00
Arham AminandClaude Opus 4.8 2ea51bd31f fix(server): OpenCode model parsing drops models with a slash in the JSON body (#5072)
Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
2026-08-10 23:31:31 -04:00
Pavlo TrinkoandClaude Fable 5 e5c82d79a0 fix(mobile): keep chat composer above the Android gesture bar (#5988)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-08-10 20:31:00 -04:00
139 changed files with 9000 additions and 1555 deletions

No files matched your search

+1
View File
@@ -37,3 +37,4 @@ github:shivamhwp
github:jappyjan
github:justsomelegs
github:UtkarshUsername
github:SunkenInTime
+83 -10
View File
@@ -8,12 +8,14 @@ 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 with --auto-submit (TestFlight +
# Play internal track). Bumping `version` is therefore all it takes to
# app.config.ts, cut a new build and submit it (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. Releasing to the App Store stays a manual
# App Store Connect step.
# 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.
# 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
@@ -42,6 +44,10 @@ 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
@@ -89,11 +95,21 @@ 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)
@@ -135,6 +151,65 @@ 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
@@ -157,10 +232,8 @@ 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. 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.
# duplicate. 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'
@@ -178,8 +251,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; then
echo ":building_construction: $platform: cut production build for $version (auto-submitted)" >> "$GITHUB_STEP_SUMMARY"
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"
else
failed=1
echo ":x: $platform: production build or submission failed for $version" >> "$GITHUB_STEP_SUMMARY"
+1 -1
View File
@@ -161,7 +161,7 @@ const config: ExpoConfig = {
slug: "t3-code",
platforms: ["ios", "android"],
scheme: variant.scheme,
version: "1.0.2",
version: "1.0.3",
runtimeVersion: {
// Fingerprint (not appVersion) so an OTA only reaches binaries whose native
// project — native deps, config plugins, AND patches/ — matches the update.
+1 -1
View File
@@ -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": "3.3.3",
"@legendapp/list": "catalog:",
"@noble/curves": "catalog:",
"@noble/hashes": "catalog:",
"@pierre/diffs": "catalog:",
+20 -13
View File
@@ -18,7 +18,6 @@ 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";
@@ -134,7 +133,7 @@ const LEGAL_DOCUMENT_HEADER_OPTIONS: AppScreenOptions = {
presentation: "fullScreenModal",
};
const SettingsSheetStack = createNativeStackNavigator({
const SettingsContentStack = createNativeStackNavigator({
initialRouteName: "Settings",
screenOptions: {
...GLASS_HEADER_OPTIONS,
@@ -198,20 +197,30 @@ const SettingsSheetStack = 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",
},
}),
},
});
@@ -347,11 +356,9 @@ function RootStackLayout(props: {
<HardwareKeyboardCommandProvider pathname={pathname}>
<ThreadOutboxDrainWorker />
<ShowcaseCaptureCoordinator pathname={pathname} />
<ClerkSettingsSheetDetentProvider initiallyExpanded={false}>
<AdaptiveWorkspaceLayout pathname={workspacePathname}>
{props.children}
</AdaptiveWorkspaceLayout>
</ClerkSettingsSheetDetentProvider>
<AdaptiveWorkspaceLayout pathname={workspacePathname}>
{props.children}
</AdaptiveWorkspaceLayout>
</HardwareKeyboardCommandProvider>
);
}
+26 -1
View File
@@ -6,6 +6,7 @@ import {
type ComponentProps,
type ReactElement,
type ReactNode,
useRef,
} from "react";
import { Platform, Pressable, useColorScheme, View } from "react-native";
import { useThemeColor } from "../lib/useThemeColor";
@@ -21,10 +22,31 @@ 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");
@@ -54,6 +76,7 @@ export function ControlPill(props: {
: variant === "danger"
? "bg-danger"
: "bg-subtle",
props.className,
);
const labelClassName = cn(
"text-center text-xs font-t3-bold",
@@ -68,7 +91,9 @@ export function ControlPill(props: {
<Pressable
accessibilityLabel={props.accessibilityLabel ?? props.label}
accessibilityRole="button"
onPress={props.onPress}
onPress={props.activateOnPressIn ? handlePress : props.onPress}
onPressIn={props.activateOnPressIn ? handlePressIn : undefined}
onPressOut={props.activateOnPressIn ? handlePressOut : undefined}
disabled={props.disabled}
className={containerClassName}
>
@@ -5,7 +5,6 @@ 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,
@@ -18,7 +17,6 @@ import {
} from "./useArchivedThreadSnapshots";
export function ArchivedThreadsRouteScreen() {
const { expand } = useClerkSettingsSheetDetent();
const { savedConnectionsById } = useSavedRemoteConnections();
const [searchQuery, setSearchQuery] = useState("");
const [selectedEnvironmentId, setSelectedEnvironmentId] = useState<EnvironmentId | null>(null);
@@ -70,9 +68,8 @@ export function ArchivedThreadsRouteScreen() {
useFocusEffect(
useCallback(() => {
expand();
refresh();
}, [expand, refresh]),
}, [refresh]),
);
return (
@@ -1,44 +0,0 @@
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 detent/session-state
// transitions a beat to settle before presenting another formSheet on top.
// Sign-in happens inside the Settings sheet; give its session-state transition
// a beat to settle before presenting another formSheet on top.
const PRESENT_ONBOARDING_DELAY_MS = 600;
/**
@@ -45,6 +45,7 @@ export function HomeRouteScreen() {
pinThread,
unpinThread,
movePinnedThread,
regenerateThreadTitle,
unsettleThread,
} = useThreadListActions();
const pendingTasks = usePendingNewTasks();
@@ -134,7 +135,10 @@ export function HomeRouteScreen() {
<NativeStackScreenOptions
options={getConnectionAwareBrandHeaderOptions({
onOpenEnvironments: () =>
navigation.navigate("SettingsSheet", { screen: "SettingsEnvironments" }),
navigation.navigate("SettingsSheet", {
screen: "SettingsContent",
params: { screen: "SettingsEnvironments" },
}),
})}
/>
<HomeHeader
@@ -148,9 +152,17 @@ export function HomeRouteScreen() {
onEnvironmentChange={setSelectedEnvironmentId}
onProjectChange={setSelectedProjectKey}
onOpenEnvironments={() =>
navigation.navigate("SettingsSheet", { screen: "SettingsEnvironments" })
navigation.navigate("SettingsSheet", {
screen: "SettingsContent",
params: { screen: "SettingsEnvironments" },
})
}
onOpenSettings={() =>
navigation.navigate("SettingsSheet", {
screen: "SettingsContent",
params: { screen: "Settings" },
})
}
onOpenSettings={() => navigation.navigate("SettingsSheet", { screen: "Settings" })}
onProjectSortOrderChange={setProjectSortOrder}
onSearchQueryChange={setSearchQuery}
onStartNewTask={() => navigation.navigate("NewTaskSheet", { screen: "NewTask" })}
@@ -161,7 +173,10 @@ export function HomeRouteScreen() {
catalogState={catalogState}
environments={environments}
onAddConnection={() =>
navigation.navigate("SettingsSheet", { screen: "SettingsEnvironmentNew" })
navigation.navigate("SettingsSheet", {
screen: "SettingsContent",
params: { screen: "SettingsEnvironmentNew" },
})
}
onArchiveThread={archiveThread}
onDeleteThread={confirmDeleteThread}
@@ -172,9 +187,15 @@ export function HomeRouteScreen() {
onPinThread={pinThread}
onUnpinThread={unpinThread}
onMovePinnedThread={movePinnedThread}
onRegenerateThreadTitle={regenerateThreadTitle}
onEnvironmentChange={setSelectedEnvironmentId}
onProjectChange={setSelectedProjectKey}
onOpenSettings={() => navigation.navigate("SettingsSheet", { screen: "Settings" })}
onOpenSettings={() =>
navigation.navigate("SettingsSheet", {
screen: "SettingsContent",
params: { screen: "Settings" },
})
}
onProjectSortOrderChange={setProjectSortOrder}
onSearchQueryChange={setSearchQuery}
onSelectThread={(thread) => {
@@ -115,6 +115,7 @@ 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;
@@ -538,6 +539,12 @@ 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
@@ -615,6 +622,15 @@ 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.
@@ -811,6 +827,8 @@ 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)}
@@ -842,6 +860,7 @@ export function HomeScreen(props: HomeScreenProps) {
arrangedPinnedKeys,
handleMovePinnedThread,
handlePinThread,
handleRegenerateThreadTitle,
handleSettleThread,
handleSnoozeThread,
handleUnpinThread,
@@ -863,6 +882,7 @@ export function HomeScreen(props: HomeScreenProps) {
snoozeEnvironmentIds,
threadListV2Items,
threadSearchMatchByKey,
titleRegenerationEnvironmentIds,
toggleSettledShelf,
toggleSnoozedShelf,
v2ProjectTitleByProjectKey,
@@ -967,6 +987,8 @@ 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}
@@ -988,6 +1010,7 @@ export function HomeScreen(props: HomeScreenProps) {
[
handleSwipeableClose,
handleSwipeableWillOpen,
handleRegenerateThreadTitle,
projectCwdByKey,
props.onArchiveThread,
props.onDeletePendingTask,
@@ -998,6 +1021,7 @@ export function HomeScreen(props: HomeScreenProps) {
props.searchQuery,
props.savedConnectionsById,
threadSearchMatchByKey,
titleRegenerationEnvironmentIds,
updateGroupDisplay,
],
);
@@ -48,6 +48,15 @@ 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> = {
@@ -227,13 +236,18 @@ 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) => {
@@ -405,6 +419,47 @@ 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
@@ -497,6 +552,7 @@ export function useThreadListActions(): {
pinThread,
unpinThread,
movePinnedThread,
regenerateThreadTitle,
};
}
@@ -429,13 +429,19 @@ function AdaptiveWorkspaceLayoutContent(
);
const handleOpenSettings = useCallback(() => {
navigation.navigate("SettingsSheet", { screen: "Settings" });
navigation.navigate("SettingsSheet", {
screen: "SettingsContent",
params: { 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: "SettingsEnvironments" });
navigation.navigate("SettingsSheet", {
screen: "SettingsContent",
params: { screen: "SettingsEnvironments" },
});
}, [navigation]);
const handleNewThreadInProject = useCallback(
@@ -1,8 +1,7 @@
import { useAuth } from "@clerk/expo";
import { AuthView, UserProfileView } from "@clerk/expo/native";
import { StackActions, useNavigation } from "@react-navigation/native";
import { NativeStackScreenOptions } from "../../native/StackHeader";
import { useCallback, useEffect } from "react";
import { useCallback, useLayoutEffect } from "react";
import { View } from "react-native";
import { hasCloudPublicConfig } from "../cloud/publicConfig";
@@ -10,9 +9,9 @@ import { hasCloudPublicConfig } from "../cloud/publicConfig";
export function SettingsAuthRouteScreen() {
const navigation = useNavigation();
useEffect(() => {
useLayoutEffect(() => {
if (!hasCloudPublicConfig()) {
navigation.dispatch(StackActions.replace("Settings"));
navigation.dispatch(StackActions.replace("SettingsContent"));
}
}, [navigation]);
@@ -22,20 +21,20 @@ export function SettingsAuthRouteScreen() {
function ConfiguredSettingsAuthRouteScreen() {
const { isLoaded, isSignedIn } = useAuth({ treatPendingAsSignedOut: false });
const navigation = useNavigation();
const handleHostBack = useCallback(() => navigation.goBack(), [navigation]);
const handleHostBack = useCallback(
() => navigation.dispatch(StackActions.popTo("SettingsContent")),
[navigation],
);
return (
<>
<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>
</>
<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,7 +98,10 @@ export function SettingsEnvironmentsRouteScreen() {
accessibilityLabel: "Add environment",
icon: "plus",
onPress: () =>
navigation.navigate("SettingsSheet", { screen: "SettingsEnvironmentNew" }),
navigation.navigate("SettingsSheet", {
screen: "SettingsContent",
params: { screen: "SettingsEnvironmentNew" },
}),
},
]}
/>
@@ -108,7 +111,10 @@ export function SettingsEnvironmentsRouteScreen() {
<NativeHeaderToolbar.Button
icon="plus"
onPress={() =>
navigation.navigate("SettingsSheet", { screen: "SettingsEnvironmentNew" })
navigation.navigate("SettingsSheet", {
screen: "SettingsContent",
params: { screen: "SettingsEnvironmentNew" },
})
}
separateBackground
tintColor={headerIconColor}
@@ -2,7 +2,6 @@ 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";
@@ -30,7 +29,6 @@ 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";
@@ -40,6 +38,7 @@ import { mobilePreferencesAtom, updateMobilePreferencesAtom } from "../../state/
import { useThreadListV2Enabled } from "../threads/use-thread-list-v2-enabled";
import {
type AppUpdateCheckState,
isAppUpdateCheckAvailable,
registerHiddenUpdateTap,
runAppUpdateCheck,
} from "../updates/app-updates";
@@ -147,7 +146,6 @@ 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();
@@ -436,14 +434,8 @@ function ConfiguredSettingsRouteScreen() {
const openAccount = useCallback(() => {
if (!isLoaded) return;
if (!isSignedIn) {
expandClerkSheet();
navigation.navigate("SettingsSheet", { screen: "SettingsAuth" });
return;
}
expandClerkSheet();
navigation.navigate("SettingsSheet", { screen: "SettingsAuth" });
}, [expandClerkSheet, isLoaded, isSignedIn, navigation]);
}, [isLoaded, navigation]);
return (
<View collapsable={false} className="flex-1 bg-sheet">
@@ -577,6 +569,7 @@ 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";
@@ -604,13 +597,13 @@ function AppSettingsSection() {
}, []);
const handleVersionPress = useCallback(() => {
if (!Updates.isEnabled || updateInFlight.current) return;
if (!updateCheckAvailable || updateInFlight.current) return;
const tap = registerHiddenUpdateTap(hiddenUpdateTapCount.current);
hiddenUpdateTapCount.current = tap.nextCount;
if (tap.shouldCheck) {
void checkForUpdate();
}
}, [checkForUpdate]);
}, [checkForUpdate, updateCheckAvailable]);
const statusLabel =
updateState === "checking"
@@ -646,7 +639,7 @@ function AppSettingsSection() {
<SettingsSection title="App">
<SettingsRow icon="internaldrive" label="Client Storage" target="SettingsClientStorage" />
<SettingsRow icon="doc.text" label="Legal" fullScreenTarget="SettingsLegal" />
{Updates.isEnabled ? (
{updateCheckAvailable ? (
<Pressable
accessibilityLabel={`Version ${versionLabel}`}
accessibilityRole="text"
@@ -64,7 +64,8 @@ export function SettingsRow(props: {
disabled={props.disabled}
onPress={() =>
navigation.navigate("SettingsSheet", {
screen: target,
screen: "SettingsContent",
params: { screen: target },
})
}
>
@@ -1,6 +1,12 @@
import { useEffect, useRef, useState } from "react";
import { Keyboard, View } from "react-native";
import { CommonActions, StackActions, useNavigation } from "@react-navigation/native";
import {
CommonActions,
type NavigationState,
type PartialState,
StackActions,
useNavigation,
} from "@react-navigation/native";
import { AsyncResult } from "effect/unstable/reactivity";
import { useConnectionController } from "../connection/useConnectionController";
@@ -25,6 +31,8 @@ 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")) {
@@ -166,17 +174,21 @@ export function ShowcaseCaptureCoordinator(props: { readonly pathname: string })
navigation.dispatch(StackActions.popToTop());
return;
}
const routes: Array<{
name: string;
params?: Record<string, unknown>;
state?: { index: number; routes: Array<{ name: string }> };
}> = [{ name: "Home" }];
const routes: ShowcaseResetRoute[] = [{ name: "Home" }];
if (requestedScene === "environments") {
routes.push({
name: "SettingsSheet",
state: {
index: 1,
routes: [{ name: "Settings" }, { name: "SettingsEnvironments" }],
index: 0,
routes: [
{
name: "SettingsContent",
state: {
index: 1,
routes: [{ name: "Settings" }, { name: "SettingsEnvironments" }],
},
},
],
},
});
} else {
@@ -2,7 +2,11 @@ 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, useKeyboardState } from "react-native-keyboard-controller";
import {
KeyboardAvoidingView,
KeyboardStickyView,
useKeyboardState,
} from "react-native-keyboard-controller";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { useThemeColor } from "../../lib/useThemeColor";
import { useFontFamily } from "../../lib/useFontFamily";
@@ -985,14 +989,29 @@ 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()} />
<KeyboardAvoidingView automaticOffset behavior="padding" className="flex-1">
<View 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={{
@@ -1056,7 +1075,7 @@ export function NewTaskDraftScreen(props: {
</ComposerToolbarRow>
) : null}
</View>
</KeyboardAvoidingView>
</KeyboardStickyView>
{settingsSheet}
</View>
);
@@ -1,18 +1,64 @@
import type { ApprovalRequestId } from "@t3tools/contracts";
import { Pressable, View } from "react-native";
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 { 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 type { PendingUserInput, PendingUserInputDraftAnswer } from "../../lib/threadActivity";
import { useThemeColor } from "../../lib/useThemeColor";
import {
isPendingUserInputOptionSelected,
type PendingUserInput,
type 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> | null;
readonly answers: Record<string, string | ReadonlyArray<string>> | null;
readonly respondingUserInputId: ApprovalRequestId | null;
readonly onSelectOption: (
requestId: ApprovalRequestId,
questionId: string,
question: UserInputQuestion,
label: string,
) => void;
readonly onChangeCustomAnswer: (
@@ -23,74 +69,242 @@ 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) {
// 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
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}
className={cn(
"font-t3-bold text-sm",
"rounded-full border px-3 py-2.5 ",
selected
? "text-sky-700 dark:text-sky-300"
: "text-neutral-600 dark:text-neutral-300",
? "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,
option.label,
)
}
>
{option.label}
</Text>
</Pressable>
);
})}
<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"
/>
</View>
<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>
);
})}
);
})}
</ScrollView>
<Pressable
className={cn(
"items-center justify-center rounded-2xl px-4 py-3.5",
@@ -103,6 +317,26 @@ 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,6 +14,7 @@ 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 {
@@ -51,7 +52,7 @@ import {
ComposerToolbarScroller,
ComposerToolbarTrigger,
} from "../../components/ComposerToolbarTrigger";
import { ControlPill } from "../../components/ControlPill";
import { ControlPill, ControlPillMenu } from "../../components/ControlPill";
import { ProviderIcon } from "../../components/ProviderIcon";
import type { DraftComposerImageAttachment } from "../../lib/composerImages";
import { buildModelOptions, groupByProvider } from "../../lib/modelOptions";
@@ -62,9 +63,13 @@ import {
normalizeSearchQuery,
scoreQueryMatch,
} from "@t3tools/shared/searchRanking";
import { resolveProviderOptionDescriptors } from "../../lib/providerOptions";
import {
applyProviderOptionSelection,
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";
@@ -113,6 +118,8 @@ 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;
}
/**
@@ -307,13 +314,16 @@ 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";
@@ -623,6 +633,61 @@ 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"
@@ -792,15 +857,31 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
onPress={() => void props.onPickDraftImages()}
showChevron={false}
/>
<ComposerToolbarTrigger
accessibilityLabel="Thread settings"
iconNode={
<ProviderIcon provider={currentModelOption?.providerDriver} size={16} />
}
label={settingsSummaryLabel}
maxWidth={320}
onPress={settingsSheetPresentation.open}
/>
{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}
/>
)}
{showStopAction ? (
<ComposerToolbarButton
accessibilityLabel="Stop"
@@ -2,6 +2,7 @@ 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,
@@ -13,14 +14,45 @@ import type {
RuntimeMode,
ServerConfig as T3ServerConfig,
ThreadId,
UserInputQuestion,
} from "@t3tools/contracts";
import * as Haptics from "expo-haptics";
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 {
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 { 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";
@@ -34,6 +66,11 @@ 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,
@@ -54,7 +91,7 @@ export interface ThreadDetailScreenProps {
readonly respondingApprovalId: ApprovalRequestId | null;
readonly activePendingUserInput: PendingUserInput | null;
readonly activePendingUserInputDrafts: Record<string, PendingUserInputDraftAnswer>;
readonly activePendingUserInputAnswers: Record<string, string> | null;
readonly activePendingUserInputAnswers: Record<string, string | ReadonlyArray<string>> | null;
readonly respondingUserInputId: ApprovalRequestId | null;
readonly draftMessage: string;
readonly draftAttachments: ReadonlyArray<DraftComposerImageAttachment>;
@@ -89,7 +126,7 @@ export interface ThreadDetailScreenProps {
) => Promise<unknown>;
readonly onSelectUserInputOption: (
requestId: ApprovalRequestId,
questionId: string,
question: UserInputQuestion,
label: string,
) => void;
readonly onChangeUserInputCustomAnswer: (
@@ -171,8 +208,48 @@ 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);
@@ -183,7 +260,17 @@ 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 composerBottomInset = composerExpanded ? 0 : Math.max(insets.bottom, 12);
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 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
@@ -204,6 +291,41 @@ 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
@@ -220,7 +342,103 @@ 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";
@@ -241,6 +459,7 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
useEffect(() => {
setAnchorMessageId(null);
lastScrolledAnchorMessageIdRef.current = null;
setEndFollowEnabled(true);
freeze.set(false);
}, [freeze, selectedThreadKey]);
@@ -312,6 +531,16 @@ 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,
@@ -365,13 +594,14 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
listRef={listRef}
freeze={freeze}
anchorMessageId={anchorMessageId}
contentInsetEndAdjustment={contentInsetEndAdjustment}
contentInsetEndAdjustment={combinedContentInsetEndAdjustment}
contentTopInset={0}
contentBottomInset={estimatedOverlayHeight}
contentMaxWidth={contentMaxWidth}
layoutVariant={layoutVariant}
usesAutomaticContentInsets={props.usesAutomaticContentInsets}
onHeaderMaterialVisibilityChange={props.onHeaderMaterialVisibilityChange}
onEndFollowEnabledChange={setEndFollowEnabled}
skills={selectedProviderSkills}
loadEarlier={props.loadEarlier ?? null}
/>
@@ -383,6 +613,10 @@ 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 }}
>
@@ -390,10 +624,60 @@ 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)}
>
@@ -407,6 +691,13 @@ 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}
@@ -419,35 +710,40 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
) : null}
</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}
/>
{/* 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>
</View>
</KeyboardStickyView>
) : null}
+96 -39
View File
@@ -48,6 +48,7 @@ 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 {
@@ -89,6 +90,10 @@ import {
type ThreadFeedLatestTurn,
} from "../../lib/threadActivity";
import type { ThreadContentPresentation } from "./threadContentPresentation";
import {
resolveThreadFeedLiveFollow,
type ThreadFeedLiveFollowEvent,
} from "./thread-feed-live-follow";
import {
collapsedWorkLogHeight,
ThreadWorkGroupToggle,
@@ -149,6 +154,7 @@ 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?: {
@@ -1324,6 +1330,7 @@ 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(() =>
@@ -1342,13 +1349,23 @@ 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);
}, []);
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 [interactionState, setInteractionState] = useState<{
readonly copiedRowId: string | null;
readonly expandedWorkGroups: Record<string, boolean>;
@@ -1460,40 +1477,72 @@ 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);
// 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.
// 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.
const listState = props.listRef.current?.getState();
if (listState) {
if (listState.isWithinMaintainScrollAtEndThreshold) {
setEndFollow(true);
} else if (userScrollSessionRef.current) {
setEndFollow(false);
}
transitionEndFollow({
type: "scroll",
isAtEnd: listState.isAtEnd,
userScrollSessionActive: userScrollSessionRef.current,
});
}
},
[reportHeaderMaterialVisibility, anchorTopInset, props.listRef, setEndFollow],
[reportHeaderMaterialVisibility, anchorTopInset, props.listRef, transitionEndFollow],
);
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 clearUserScrollSettle = useCallback(() => {
if (userScrollSettleTimerRef.current !== null) {
clearTimeout(userScrollSettleTimerRef.current);
userScrollSettleTimerRef.current = null;
}
}, []);
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(() => {
userScrollSessionRef.current = false;
}, []);
finishUserScroll();
}, [finishUserScroll]);
useEffect(() => clearUserScrollSettle, [clearUserScrollSettle]);
const handleViewportLayout = useCallback((event: LayoutChangeEvent) => {
const nextWidth = Math.round(event.nativeEvent.layout.width);
@@ -1502,23 +1551,30 @@ 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);
}, [props.threadId, reportHeaderMaterialVisibility]);
}, [feedThreadKey, 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;
setEndFollow(true);
}, [props.threadId, setEndFollow]);
transitionEndFollow({ type: "reset" });
}, [clearUserScrollSettle, feedThreadKey, transitionEndFollow]);
useEffect(() => {
if (props.anchorMessageId !== null) {
clearUserScrollSettle();
userScrollSessionRef.current = false;
setEndFollow(true);
transitionEndFollow({ type: "reset" });
}
}, [props.anchorMessageId, setEndFollow]);
}, [clearUserScrollSettle, props.anchorMessageId, transitionEndFollow]);
const expandedWorkGroupIds = useMemo(() => {
const ids = new Set<string>();
@@ -1554,7 +1610,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 = `${props.threadId}:${props.feed.length === 0 ? "empty" : "filled"}`;
const listMountKey = `${feedThreadKey}:${props.feed.length === 0 ? "empty" : "filled"}`;
useLayoutEffect(() => {
const bottom = props.contentInsetEndAdjustment.value;
if (bottom > 0) {
@@ -1921,6 +1977,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
onScroll={handleScroll}
onScrollBeginDrag={handleScrollBeginDrag}
onScrollEndDrag={handleScrollEndDrag}
onMomentumScrollBegin={handleMomentumScrollBegin}
onMomentumScrollEnd={handleMomentumScrollEnd}
scrollEventThrottle={16}
ListHeaderComponent={
@@ -211,6 +211,7 @@ function ThreadNavigationSidebarPane(
pinThread,
unpinThread,
movePinnedThread,
regenerateThreadTitle,
} = useThreadListActions();
const threadListV2Enabled = useThreadListV2Enabled();
const pendingTasks = usePendingNewTasks();
@@ -505,6 +506,15 @@ 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(() => {
@@ -950,6 +960,8 @@ 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)}
@@ -1067,6 +1079,8 @@ function ThreadNavigationSidebarPane(
fullSwipeWidth={props.width - 20}
onArchiveThread={archiveThread}
onDeleteThread={confirmDeleteThread}
onRegenerateThreadTitle={regenerateThreadTitle}
titleRegenerationSupported={titleRegenerationEnvironmentIds.has(thread.environmentId)}
onSelectThread={handleSelectThread}
onSwipeableClose={handleSwipeableClose}
onSwipeableWillOpen={handleSwipeableWillOpen}
@@ -1103,6 +1117,7 @@ function ThreadNavigationSidebarPane(
projectByKey,
projectCwdByKey,
projectTitleByProjectKey,
regenerateThreadTitle,
props.onNewThreadInProject,
props.searchQuery,
props.selectedThreadKey,
@@ -1110,6 +1125,7 @@ function ThreadNavigationSidebarPane(
savedConnectionsById,
serverConfigs,
threadSearchMatchByKey,
titleRegenerationEnvironmentIds,
settleThread,
settlementEnvironmentIds,
showMoreSettled,
@@ -30,6 +30,7 @@ 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";
@@ -40,26 +41,6 @@ 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.
@@ -79,13 +60,6 @@ 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;
@@ -0,0 +1,38 @@
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);
});
});
@@ -0,0 +1,37 @@
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),
);
}
@@ -0,0 +1,70 @@
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);
});
});
@@ -0,0 +1,35 @@
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,6 +22,7 @@ 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";
@@ -430,6 +431,8 @@ 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<
@@ -451,7 +454,8 @@ export const ThreadListRow = memo(function ThreadListRow(props: {
const pressedBackgroundColor = useThemeColor("--color-subtle");
const selectedBackgroundColor = useThemeColor("--color-user-bubble");
const { thread, onSelectThread, onArchiveThread, onDeleteThread } = props;
const { thread, onSelectThread, onArchiveThread, onDeleteThread, onRegenerateThreadTitle } =
props;
const status = resolveThreadStatus(thread);
const pr = useThreadPr(thread, props.projectCwd);
const timestamp = relativeTime(
@@ -471,6 +475,21 @@ 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}`,
@@ -483,9 +502,10 @@ 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],
[handleArchive, handleDelete, handleRegenerateTitle],
);
const statusPill = effectiveStatus ? (
@@ -674,7 +694,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={THREAD_ROW_MENU_ACTIONS}
actions={menuActions}
onPressAction={handleMenuAction}
shouldOpenOnLongPress
>
@@ -27,6 +27,7 @@ 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,
@@ -65,8 +66,8 @@ function threadTimeLabel(thread: EnvironmentThreadShell): string {
return relativeTime(thread.latestUserMessageAt ?? thread.updatedAt ?? thread.createdAt);
}
// Menus stay lifecycle-focused: settle/un-settle plus delete. Archive keeps
// its own surface (thread screen / settings) rather than crowding the row.
// Menus keep lifecycle and title regeneration together. Archive keeps its
// own surface (thread screen / settings) rather than crowding v2 rows.
const CARD_MENU_ACTIONS: MenuAction[] = [
{ id: "settle", title: "Settle", image: "checkmark" },
{ id: "delete", title: "Delete", image: "trash", attributes: { destructive: true } },
@@ -341,6 +342,7 @@ 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;
@@ -355,6 +357,8 @@ 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;
@@ -384,6 +388,7 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
variant,
onSelectThread,
onDeleteThread,
onRegenerateThreadTitle,
onSettleThread,
onSnoozeThread,
onUnsnoozeThread,
@@ -417,6 +422,10 @@ 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),
@@ -506,6 +515,14 @@ 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" },
@@ -516,13 +533,31 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
subactions: snoozePresetActions,
},
...pinMenuItem,
...titleRegenerationMenuItems,
{ id: "delete", title: "Delete", image: "trash", attributes: { destructive: true } },
],
[pinMenuItem, snoozePresetActions],
[pinMenuItem, snoozePresetActions, titleRegenerationMenuItems],
);
const cardMenuActions = useMemo<MenuAction[]>(
() => [CARD_MENU_ACTIONS[0]!, ...pinMenuItem, ...CARD_MENU_ACTIONS.slice(1)],
[pinMenuItem],
() => [
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],
);
const handleMenuAction = useCallback(
({ nativeEvent }: { readonly nativeEvent: { readonly event: string } }) => {
@@ -534,6 +569,7 @@ 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,
@@ -549,6 +585,7 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
[
handleArchive,
handleDelete,
handleRegenerateTitle,
handleMovePinnedDown,
handleMovePinnedUp,
handlePin,
@@ -890,11 +927,11 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
<ControlPillMenu
actions={
snoozedRow
? SNOOZED_MENU_ACTIONS
? snoozedMenuActions
: !props.settlementSupported
? LEGACY_MENU_ACTIONS
? legacyMenuActions
: canUnsettle
? SLIM_MENU_ACTIONS
? slimMenuActions
: swipeActions.secondary === "snooze"
? snoozableCardMenuActions
: cardMenuActions
@@ -0,0 +1,284 @@
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"]));
});
});
@@ -0,0 +1,202 @@
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 };
}
@@ -0,0 +1,36 @@
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 },
},
]);
});
});
@@ -0,0 +1,17 @@
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,6 +32,19 @@ 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 () => ({
@@ -100,6 +113,32 @@ 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,8 +48,17 @@ 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.
@@ -73,7 +82,7 @@ export function registerHiddenUpdateTap(count: number): {
export async function runAppUpdateCheck(options: AppUpdateCheckOptions = {}): Promise<void> {
const client = options.client ?? Updates;
if (!client.isEnabled) return;
if (!isAppUpdateCheckAvailable(client)) return;
if (appUpdateCheckInFlight) {
await observeAppUpdateCheck(appUpdateCheckInFlight, options);
@@ -207,19 +216,27 @@ 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 || !client.isEnabled) return undefined;
if (started || !isAppUpdateCheckAvailable(client)) return undefined;
started = true;
return runAppUpdateCheck({ client });
};
@@ -1,9 +1,11 @@
import { useNavigation } from "@react-navigation/native";
import type { MergedUsage } from "@t3tools/shared/usageMerge";
import type { DailyTotals, MergedUsage } from "@t3tools/shared/usageMerge";
import {
enumerateDays,
enumerateHourStarts,
formatCount,
formatDayShort,
formatHourShort,
formatPercent,
formatTokens,
formatUsd,
@@ -23,6 +25,7 @@ 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" },
@@ -33,23 +36,62 @@ const CHART_HEIGHT = 180;
export function UsageRouteScreen() {
const navigation = useNavigation();
const insets = useSafeAreaInsets();
const [windowDays, setWindowDays] = useState<number>(30);
const [windowSelection, setWindowSelection] = useState(() => ({
days: 30,
window: makeWindow(30),
}));
const [metric, setMetric] = useState<UsageChartMetric>("cost");
// 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 { days: windowDays, window } = windowSelection;
const isPast24Hours = windowDays === 1;
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">
@@ -65,12 +107,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={refresh} />}
refreshControl={<RefreshControl refreshing={refreshing} onRefresh={refreshWindow} />}
>
<SegmentedControl
options={WINDOW_OPTIONS.map((option) => ({ value: option.days, label: option.label }))}
selected={windowDays}
onSelect={setWindowDays}
onSelect={selectWindow}
/>
<UsageCoverageNotice environments={environments} merged={merged} isPartial={isPartial} />
@@ -87,14 +129,17 @@ export function UsageRouteScreen() {
<>
<ChartCard
merged={merged}
days={days}
days={chartDays}
daily={chartTotals}
metric={metric}
onMetricChange={setMetric}
sinceDay={window.sinceDay}
untilDay={window.untilDay}
isPast24Hours={isPast24Hours}
timeZone={window.timeZone}
/>
<ProviderSection merged={merged} metric={metric} />
<TotalsSection merged={merged} />
<TotalsSection merged={merged} isPast24Hours={isPast24Hours} />
<ModelsSection merged={merged} />
</>
)}
@@ -142,14 +187,17 @@ 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 = merged.daily.some((day) => day.totalTokens > 0);
const hasActivity = props.daily.some((period) => period.totalTokens > 0);
return (
<View className="gap-4 rounded-[24px] border-continuous bg-card p-4">
@@ -173,7 +221,7 @@ function ChartCard(props: {
{hasActivity ? (
<UsageDailyChart
days={props.days}
daily={merged.daily}
daily={props.daily}
metric={metric}
height={CHART_HEIGHT}
/>
@@ -184,7 +232,11 @@ function ChartCard(props: {
)}
<View className="flex-row items-center justify-between">
<Text className="text-xs text-foreground-tertiary">{formatDayShort(props.sinceDay)}</Text>
<Text className="text-xs text-foreground-tertiary">
{props.isPast24Hours
? formatHourShort(props.days[0] ?? "", props.timeZone)
: 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">
@@ -198,7 +250,11 @@ function ChartCard(props: {
</View>
))}
</View>
<Text className="text-xs text-foreground-tertiary">{formatDayShort(props.untilDay)}</Text>
<Text className="text-xs text-foreground-tertiary">
{props.isPast24Hours
? formatHourShort(props.days[props.days.length - 1] ?? "", props.timeZone)
: formatDayShort(props.untilDay)}
</Text>
</View>
</View>
);
@@ -292,10 +348,12 @@ function ProviderSection(props: {
);
}
function TotalsSection(props: { readonly merged: MergedUsage }) {
function TotalsSection(props: { readonly merged: MergedUsage; readonly isPast24Hours: boolean }) {
const { merged } = props;
const activeDays = merged.daily.filter((day) => day.totalTokens > 0).length;
const dailyAverage = activeDays === 0 ? 0 : merged.totalTokens / activeDays;
const activePeriods = (props.isPast24Hours ? merged.hourly : merged.daily).filter(
(period) => period.totalTokens > 0,
).length;
const periodAverage = activePeriods === 0 ? 0 : merged.totalTokens / activePeriods;
const observedInput = merged.uncachedInputTokens + merged.cachedInputTokens;
const cachedShare = observedInput === 0 ? 0 : merged.cachedInputTokens / observedInput;
@@ -305,7 +363,7 @@ function TotalsSection(props: { readonly merged: MergedUsage }) {
<MetricCell
label="Processed tokens"
value={formatTokens(merged.totalTokens)}
detail={`${formatTokens(dailyAverage)} per active day`}
detail={`${formatTokens(periodAverage)} per active ${props.isPast24Hours ? "hour" : "day"}`}
/>
<MetricCell
label="Cache savings"
@@ -12,12 +12,107 @@ 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">,
+67 -9
View File
@@ -26,7 +26,7 @@ export interface PendingUserInput {
}
export interface PendingUserInputDraftAnswer {
readonly selectedOptionLabel?: string;
readonly selectedOptionLabels?: ReadonlyArray<string>;
readonly customAnswer?: string;
}
@@ -227,14 +227,32 @@ 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 | null {
): string | ReadonlyArray<string> | null {
const customAnswer = normalizeDraftAnswer(draft?.customAnswer);
if (customAnswer) {
return customAnswer;
}
return normalizeDraftAnswer(draft?.selectedOptionLabel);
const selectedOptionLabels = normalizeSelectedOptionLabels(draft?.selectedOptionLabels);
if (question.multiSelect) {
return selectedOptionLabels.length > 0 ? selectedOptionLabels : null;
}
return selectedOptionLabels[0] ?? null;
}
/** Codex children settle via task.updated (idle/failed/interrupted), never
@@ -1428,22 +1446,62 @@ export function setPendingUserInputCustomAnswer(
draft: PendingUserInputDraftAnswer | undefined,
customAnswer: string,
): PendingUserInputDraftAnswer {
const selectedOptionLabel =
customAnswer.trim().length > 0 ? undefined : draft?.selectedOptionLabel;
const selectedOptionLabels =
customAnswer.trim().length > 0
? undefined
: normalizeSelectedOptionLabels(draft?.selectedOptionLabels);
return {
customAnswer,
...(selectedOptionLabel ? { selectedOptionLabel } : {}),
...(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],
};
}
export function buildPendingUserInputAnswers(
questions: ReadonlyArray<UserInputQuestion>,
draftAnswers: Record<string, PendingUserInputDraftAnswer>,
): Record<string, string> | null {
const answers: Record<string, string> = {};
): Record<string, string | ReadonlyArray<string>> | null {
const answers: Record<string, string | ReadonlyArray<string>> = {};
for (const question of questions) {
const answer = resolvePendingUserInputAnswer(draftAnswers[question.id]);
const answer = resolvePendingUserInputAnswer(question, draftAnswers[question.id]);
if (!answer) {
return null;
}
+11 -1
View File
@@ -81,8 +81,18 @@ 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.sinceDay,
input.untilDay,
input.timeZone,
input.resolution,
input.sinceTime,
input.untilTime,
],
);
const atom = usageByWindowAtom(windowKey);
const environments = useAtomValue(atom);
@@ -1,7 +1,11 @@
import { useAtomValue } from "@effect/atom-react";
import { useCallback, useMemo, useState } from "react";
import { ApprovalRequestId, type ProviderApprovalDecision } from "@t3tools/contracts";
import {
ApprovalRequestId,
type ProviderApprovalDecision,
type UserInputQuestion,
} from "@t3tools/contracts";
import { Atom } from "effect/unstable/reactivity";
import { threadEnvironment } from "../state/threads";
@@ -12,6 +16,7 @@ import {
derivePendingUserInputs,
setPendingUserInputCustomAnswer,
sortThreadActivities,
togglePendingUserInputOptionSelection,
type PendingUserInputDraftAnswer,
} from "../lib/threadActivity";
import { appAtomRegistry } from "./atom-registry";
@@ -23,15 +28,21 @@ const userInputDraftsByRequestKeyAtom = Atom.make<
Record<string, Record<string, PendingUserInputDraftAnswer>>
>({}).pipe(Atom.keepAlive, Atom.withLabel("mobile:user-input-drafts"));
function setUserInputDraftOption(requestKey: string, questionId: string, label: string): void {
function setUserInputDraftOption(
requestKey: string,
question: UserInputQuestion,
label: string,
): void {
const current = appAtomRegistry.get(userInputDraftsByRequestKeyAtom);
appAtomRegistry.set(userInputDraftsByRequestKeyAtom, {
...current,
[requestKey]: {
...current[requestKey],
[questionId]: {
selectedOptionLabel: label,
},
[question.id]: togglePendingUserInputOptionSelection(
question,
current[requestKey]?.[question.id],
label,
),
},
});
}
@@ -97,13 +108,13 @@ export function useSelectedThreadRequests() {
: null;
const onSelectUserInputOption = useCallback(
(requestId: ApprovalRequestId, questionId: string, label: string) => {
(requestId: ApprovalRequestId, question: UserInputQuestion, label: string) => {
if (!selectedThreadShell) {
return;
}
const requestKey = scopedRequestKey(selectedThreadShell.environmentId, requestId);
setUserInputDraftOption(requestKey, questionId, label);
setUserInputDraftOption(requestKey, question, label);
},
[selectedThreadShell],
);
+5 -1
View File
@@ -5,6 +5,7 @@ import {
type RelayClientInstallProgressStage,
} from "@t3tools/contracts";
import { RelayOkResponse } from "@t3tools/contracts/relay";
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
import * as RelayClient from "@t3tools/shared/relayClient";
import { withRelayClientTracing } from "@t3tools/shared/relayTracing";
import * as Cause from "effect/Cause";
@@ -694,8 +695,11 @@ export const connectCommand = Command.make("connect", {
// fail the command, just tell the user what happened and move on.
const background = yield* recoverServiceOnboardingOffer(offerServiceDuringOnboarding);
if (background) {
const platform = yield* HostProcessPlatform;
yield* Console.log(
"\n✓ Background service ready\n\nT3 Code will stay reachable after you log out.",
platform === "darwin"
? "\n✓ Background service ready\n\nT3 Code will stay reachable while you are logged in to this Mac."
: "\n✓ Background service ready\n\nT3 Code will stay reachable after you log out.",
);
return;
}
+2 -2
View File
@@ -29,9 +29,9 @@ it("gives a direct repair command for a stale service", () => {
);
});
it("explains service availability without systemd", () => {
it("explains where the service is supported", () => {
assert.include(
formatServiceStatus({ ...status, supported: false, installed: false }, "0.0.29"),
"Supported on: Linux with systemd",
"Supported on: Linux with systemd, macOS with launchd",
);
});
+10 -3
View File
@@ -1,3 +1,4 @@
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
import * as Console from "effect/Console";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
@@ -48,7 +49,7 @@ export function formatServiceStatus(
cliVersion: string,
): string {
if (!status.supported) {
return "T3 Code service\n Status: unavailable on this machine\n Supported on: Linux with systemd";
return "T3 Code service\n Status: unavailable on this machine\n Supported on: Linux with systemd, macOS with launchd";
}
if (!status.installed) {
return "T3 Code service\n Status: not installed\n Next: Run `t3 service install`.";
@@ -152,12 +153,18 @@ export const offerServiceDuringOnboarding = Effect.gen(function* () {
yield* Console.log("T3 Code is already set up to run in the background on this machine.");
return true;
}
// A LaunchAgent starts at login and dies at logout; there is no
// enable-linger equivalent on macOS. Do not promise more than that.
const platform = yield* HostProcessPlatform;
const wanted = yield* Prompt.run(
Prompt.confirm({
message: installed
? "The installed T3 Code service needs an update or repair. Update it now?"
: "Run T3 Code in the background whenever this machine boots? " +
"It stays reachable through T3 Connect even after you log out.",
: platform === "darwin"
? "Run T3 Code in the background whenever you log in to this Mac? " +
"It stays reachable through T3 Connect while you are logged in."
: "Run T3 Code in the background whenever this machine boots? " +
"It stays reachable through T3 Connect even after you log out.",
initial: true,
}),
);
+143 -4
View File
@@ -4,8 +4,10 @@ import {
HostProcessArguments,
HostProcessExecutablePath,
HostProcessPlatform,
HostProcessUserId,
} from "@t3tools/shared/hostProcess";
import * as ConfigProvider from "effect/ConfigProvider";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
@@ -47,6 +49,51 @@ it("survives the kernel OOM-killing a greedy agent child", () => {
expect(unit).toContain("OOMPolicy=continue");
});
const macPlan = {
nodePath: "/opt/homebrew/bin/node",
launcherPath: "/Users/theo/.t3/runtime/service-launcher.mjs",
baseDir: "/Users/theo/.t3",
logPath: "/Users/theo/.t3/userdata/logs/boot-service.log",
unitPath: "/Users/theo/Library/LaunchAgents/com.t3tools.t3code.service.plist",
};
it("keeps launchd pinned to the stable launcher rather than a versioned server", () => {
const plist = BootService.renderBootServicePlist(macPlan, { homeDir: "/Users/theo" });
expect(plist).toContain("<string>/opt/homebrew/bin/node</string>");
expect(plist).toContain("<string>/Users/theo/.t3/runtime/service-launcher.mjs</string>");
expect(plist).not.toContain("versions/1.2.3");
});
it("restarts the launch agent on the systemd cadence", () => {
const plist = BootService.renderBootServicePlist(macPlan, { homeDir: "/Users/theo" });
expect(plist).toContain("<key>RunAtLoad</key>\n <true/>");
expect(plist).toContain("<key>KeepAlive</key>\n <true/>");
expect(plist).toContain("<key>ThrottleInterval</key>\n <integer>5</integer>");
expect(plist).toContain("<key>ExitTimeOut</key>\n <integer>90</integer>");
});
it("appends both stdio streams to the boot service log", () => {
const plist = BootService.renderBootServicePlist(macPlan, { homeDir: "/Users/theo" });
expect(plist).toContain(
"<key>StandardOutPath</key>\n <string>/Users/theo/.t3/userdata/logs/boot-service.log</string>",
);
expect(plist).toContain(
"<key>StandardErrorPath</key>\n <string>/Users/theo/.t3/userdata/logs/boot-service.log</string>",
);
});
it("escapes XML in host paths", () => {
const plist = BootService.renderBootServicePlist(
{ ...macPlan, baseDir: "/Users/theo/T3 & <Co>" },
{ homeDir: "/Users/theo" },
);
expect(plist).toContain("<string>/Users/theo/T3 &amp; &lt;Co&gt;</string>");
});
const makeHarness = Effect.fn("test.make_boot_service_harness")(function* (
platform: NodeJS.Platform = "linux",
usePinnedLauncher = false,
@@ -68,12 +115,14 @@ const makeHarness = Effect.fn("test.make_boot_service_harness")(function* (
yield* fs.writeFileString(runtime.sentinelPath, "1.2.3\n");
const commands: string[] = [];
const timeouts = new Map<string, unknown>();
const control: { failCommand: string | undefined } = { failCommand: undefined };
const runner = ProcessRunner.ProcessRunner.of({
run: (input) =>
Effect.sync(() => {
const command = `${input.command} ${input.args.join(" ")}`;
commands.push(command);
timeouts.set(command, input.timeout);
return {
stdout: input.args[1] === "--version" ? "t3 v1.2.3\n" : "",
stderr: "",
@@ -99,19 +148,20 @@ const makeHarness = Effect.fn("test.make_boot_service_harness")(function* (
Effect.provide(
Layer.mergeAll(
Layer.succeed(HostProcessPlatform, platform),
Layer.succeed(HostProcessUserId, 501),
Layer.succeed(HostProcessExecutablePath, "/usr/bin/node"),
Layer.succeed(HostProcessArguments, ["/usr/bin/node", path.join(home, "bin.mjs")]),
ConfigProvider.layer(ConfigProvider.fromEnv({ env: { HOME: home } })),
),
),
);
return { service, fs, statePath, commands, control };
return { service, fs, statePath, commands, timeouts, control };
});
it.layer(NodeServices.layer)("boot service install", (it) => {
it.effect("installs, reports current state, and uninstalls", () =>
Effect.gen(function* () {
const { service, fs, statePath, commands } = yield* makeHarness();
const { service, fs, statePath, commands, timeouts } = yield* makeHarness();
const plan = yield* service.install;
expect(parseServiceState(yield* fs.readFileString(statePath))).toEqual({
@@ -137,6 +187,11 @@ it.layer(NodeServices.layer)("boot service install", (it) => {
expect(yield* service.uninstall).toBe(true);
expect((yield* service.status).installed).toBe(false);
expect(commands.some((command) => command.startsWith("npm "))).toBe(false);
// The stop can block up to systemd's 90s TimeoutStopSec; the runner's
// 60s default would cancel it mid-shutdown.
expect(timeouts.get("systemctl --user disable --now t3code.service")).toEqual(
Duration.seconds(120),
);
}),
);
@@ -195,11 +250,95 @@ it.layer(NodeServices.layer)("boot service install", (it) => {
}),
);
it.effect("fails closed off Linux", () =>
it.effect("fails closed on Windows", () =>
Effect.gen(function* () {
const { service } = yield* makeHarness("darwin");
const { service } = yield* makeHarness("win32");
expect((yield* service.status).supported).toBe(false);
expect((yield* service.install.pipe(Effect.flip))._tag).toBe("BootServiceUnsupportedError");
}),
);
it.effect("installs, reports current state, and uninstalls on macOS", () =>
Effect.gen(function* () {
const { service, fs, statePath, commands, timeouts } = yield* makeHarness("darwin");
const plan = yield* service.install;
expect(plan.unitPath.endsWith("Library/LaunchAgents/com.t3tools.t3code.service.plist")).toBe(
true,
);
expect(parseServiceState(yield* fs.readFileString(statePath))).toEqual({
protocol: SERVICE_LAUNCHER_PROTOCOL,
activeVersion: "1.2.3",
});
expect(yield* fs.readFileString(plan.launcherPath)).toBe("export {};\n");
expect((yield* service.status).current).toBe(true);
expect(yield* service.uninstall).toBe(true);
expect((yield* service.status).installed).toBe(false);
expect(commands.some((command) => command.startsWith("npm "))).toBe(false);
expect(commands.some((command) => command.startsWith("systemctl "))).toBe(false);
// A bootout can block up to the plist's 90s ExitTimeOut; the runner's
// 60s default would cancel it and let bootstrap race a loaded job.
expect(timeouts.get("launchctl bootout gui/501/com.t3tools.t3code.service")).toEqual(
Duration.seconds(120),
);
}),
);
it.effect("restarts the launch agent when repair fails", () =>
Effect.gen(function* () {
const { service, commands, control } = yield* makeHarness("darwin");
yield* service.install;
const plistPath = (yield* service.status).unitPath;
commands.length = 0;
control.failCommand = `launchctl bootstrap gui/501 ${plistPath}`;
const error = yield* service.install.pipe(Effect.flip);
expect(error._tag).toBe("BootServiceCommandError");
expect(commands.filter((command) => command.startsWith("launchctl "))).toEqual([
"launchctl bootout gui/501/com.t3tools.t3code.service",
"launchctl enable gui/501/com.t3tools.t3code.service",
`launchctl bootstrap gui/501 ${plistPath}`,
`launchctl bootstrap gui/501 ${plistPath}`,
]);
}),
);
it.effect("ignores a bootout for an agent that is not loaded", () =>
Effect.gen(function* () {
const { service, control } = yield* makeHarness("darwin");
yield* service.install;
control.failCommand = "launchctl bootout gui/501/com.t3tools.t3code.service";
yield* service.install;
expect((yield* service.status).current).toBe(true);
}),
);
it.effect("restarts without overwriting a pending remote update on macOS", () =>
Effect.gen(function* () {
const { service, fs, statePath, commands } = yield* makeHarness("darwin");
yield* service.install;
const plistPath = (yield* service.status).unitPath;
// @effect-diagnostics-next-line preferSchemaOverJson:off - fixed launcher-owned test document.
const pendingState = JSON.stringify({
protocol: SERVICE_LAUNCHER_PROTOCOL - 1,
activeVersion: "1.2.3",
update: {
id: "remote-update",
fromVersion: "1.2.3",
targetVersion: "1.2.4",
status: "pending",
},
});
yield* fs.writeFileString(statePath, pendingState);
commands.length = 0;
expect((yield* service.install.pipe(Effect.flip))._tag).toBe("BootServiceUpdatePendingError");
expect(serviceStateHasPendingUpdate(yield* fs.readFileString(statePath))).toBe(true);
expect(commands.filter((command) => command.startsWith("launchctl "))).toEqual([
"launchctl bootout gui/501/com.t3tools.t3code.service",
`launchctl bootstrap gui/501 ${plistPath}`,
]);
}),
);
});
+310 -47
View File
@@ -1,4 +1,8 @@
import { HostProcessExecutablePath, HostProcessPlatform } from "@t3tools/shared/hostProcess";
import {
HostProcessExecutablePath,
HostProcessPlatform,
HostProcessUserId,
} from "@t3tools/shared/hostProcess";
import * as Config from "effect/Config";
import * as Context from "effect/Context";
import * as DateTime from "effect/DateTime";
@@ -27,6 +31,10 @@ import {
const BOOT_SERVICE_NAME = "t3code";
export const BOOT_SERVICE_UNIT_FILE = `${BOOT_SERVICE_NAME}.service`;
// `.service` suffix keeps the label distinct from the desktop app's bundle id
// (com.t3tools.t3code), so launchd and TCC records never collide.
export const BOOT_SERVICE_LAUNCHD_LABEL = "com.t3tools.t3code.service";
export const BOOT_SERVICE_PLIST_FILE = `${BOOT_SERVICE_LAUNCHD_LABEL}.plist`;
export const BOOT_SERVICE_UNIT_ENV = "T3_BOOT_SERVICE_UNIT";
/** systemd expands `%` specifiers, including in unquoted append-log paths. */
@@ -83,12 +91,276 @@ export function renderBootServiceUnit(plan: BootServicePlan): string {
].join("\n");
}
/** Plist values are emitted as XML text nodes; only these three need escaping. */
export function escapeXmlText(value: string): string {
return value.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
}
/** Pure renderer: launch agents cannot rely on the user's shell or PATH. */
export function renderBootServicePlist(
plan: BootServicePlan,
options: { readonly homeDir: string },
): string {
// KeepAlive + ThrottleInterval mirror Restart=always + RestartSec=5. launchd
// has no StartLimitBurst analog; a hard crash loop respawns every 5s forever.
// ExitTimeOut 90 matches systemd's default TimeoutStopSec. A plain stop
// completes within the launcher's 5s child grace, but a stop that queues
// behind an in-flight update transition can take much longer; launchd's
// system-defined default (5s on current macOS) would SIGKILL the launcher
// (and, with it, the process group) mid-handoff.
// ProcessType Interactive opts out of background-job resource throttling.
// AbandonProcessGroup stays at its default (false): launchd reaps leftover
// process-group members only when the launcher itself exits — the analog of
// KillMode=mixed's final cgroup kill — and not when the launcher restarts its
// child, so agent children survive server updates.
return [
`<?xml version="1.0" encoding="UTF-8"?>`,
`<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">`,
`<plist version="1.0">`,
`<dict>`,
` <key>Label</key>`,
` <string>${BOOT_SERVICE_LAUNCHD_LABEL}</string>`,
` <key>ProgramArguments</key>`,
` <array>`,
` <string>${escapeXmlText(plan.nodePath)}</string>`,
` <string>${escapeXmlText(plan.launcherPath)}</string>`,
` </array>`,
` <key>EnvironmentVariables</key>`,
` <dict>`,
` <key>T3CODE_HOME</key>`,
` <string>${escapeXmlText(plan.baseDir)}</string>`,
` <key>${BOOT_SERVICE_UNIT_ENV}</key>`,
` <string>${BOOT_SERVICE_PLIST_FILE}</string>`,
` </dict>`,
` <key>WorkingDirectory</key>`,
` <string>${escapeXmlText(options.homeDir)}</string>`,
` <key>RunAtLoad</key>`,
` <true/>`,
` <key>KeepAlive</key>`,
` <true/>`,
` <key>ThrottleInterval</key>`,
` <integer>5</integer>`,
` <key>ExitTimeOut</key>`,
` <integer>90</integer>`,
` <key>ProcessType</key>`,
` <string>Interactive</string>`,
` <key>StandardOutPath</key>`,
` <string>${escapeXmlText(plan.logPath)}</string>`,
` <key>StandardErrorPath</key>`,
` <string>${escapeXmlText(plan.logPath)}</string>`,
`</dict>`,
`</plist>`,
``,
].join("\n");
}
export interface BootServiceStep {
readonly step: string;
readonly command: string;
readonly args: ReadonlyArray<string>;
/**
* Non-zero exit is logged and ignored. Reserved for steps whose common
* failures (not loaded, already enabled) leave a state a later strict step
* either tolerates or fails loudly on.
*/
readonly optional?: boolean;
/** Override the ProcessRunner default (60s) for steps that block longer. */
readonly timeout?: Duration.Input;
}
/**
* Stop commands block until the service manager gives up: 90s by default for
* systemd's TimeoutStopSec, and ExitTimeOut=90 in the rendered plist. This
* must stay above both, or the runner cancels the stop mid-shutdown and the
* next step races a still-loaded service.
*/
const STOP_STEP_TIMEOUT = Duration.seconds(120);
/**
* Platform service-manager integration as data: paths, a pure renderer, and
* the command steps each flow runs. install/uninstall/status consume this and
* never branch on platform.
*/
export interface BootServiceManager {
readonly kind: "systemd" | "launchd";
readonly unitPath: string;
readonly render: (plan: BootServicePlan) => string;
/** Before rewriting files, when a unit is already installed. */
readonly stop: ReadonlyArray<BootServiceStep>;
/** After files are written. The last entry starts the service. */
readonly activate: ReadonlyArray<BootServiceStep>;
/** Best-effort recovery after a failed repair of an installed service. */
readonly restart: ReadonlyArray<BootServiceStep>;
/** Uninstall, before the unit file is removed. */
readonly deactivate: ReadonlyArray<BootServiceStep>;
/** Uninstall, after the unit file is removed. */
readonly finalize: ReadonlyArray<BootServiceStep>;
}
export function systemdManager(input: {
readonly path: Path.Path;
readonly homeDir: string;
}): BootServiceManager {
const unitPath = input.path.join(
input.homeDir,
".config",
"systemd",
"user",
BOOT_SERVICE_UNIT_FILE,
);
return {
kind: "systemd",
unitPath,
render: renderBootServiceUnit,
stop: [
{
step: "stopping the installed service",
command: "systemctl",
args: ["--user", "stop", BOOT_SERVICE_UNIT_FILE],
timeout: STOP_STEP_TIMEOUT,
},
],
activate: [
{
step: "reloading systemd user units",
command: "systemctl",
args: ["--user", "daemon-reload"],
},
{
step: "enabling the service",
command: "systemctl",
args: ["--user", "enable", BOOT_SERVICE_UNIT_FILE],
},
{ step: "enabling lingering for this user", command: "loginctl", args: ["enable-linger"] },
// Start last. No administrative state write occurs after this succeeds.
{
step: "starting the service",
command: "systemctl",
args: ["--user", "restart", BOOT_SERVICE_UNIT_FILE],
},
],
restart: [
{
step: "restarting the service after a failed update",
command: "systemctl",
args: ["--user", "restart", BOOT_SERVICE_UNIT_FILE],
},
],
deactivate: [
{
step: "stopping the service",
command: "systemctl",
args: ["--user", "disable", "--now", BOOT_SERVICE_UNIT_FILE],
timeout: STOP_STEP_TIMEOUT,
},
],
finalize: [
{
step: "reloading systemd user units",
command: "systemctl",
args: ["--user", "daemon-reload"],
},
],
};
}
export function launchdManager(input: {
readonly path: Path.Path;
readonly homeDir: string;
readonly uid: number;
}): BootServiceManager {
const unitPath = input.path.join(
input.homeDir,
"Library",
"LaunchAgents",
BOOT_SERVICE_PLIST_FILE,
);
const domainTarget = `gui/${input.uid}`;
const serviceTarget = `${domainTarget}/${BOOT_SERVICE_LAUNCHD_LABEL}`;
// bootout/enable are optional: they fail on not-loaded states that are fine
// to proceed from. The strict `bootstrap` runs last and is also the start:
// loading a RunAtLoad/KeepAlive plist starts the job, so a separate
// kickstart would kill and restart a server it just booted. A lingering job
// that survived bootout, or a gui domain with nobody logged in at the
// screen (SSH install), makes bootstrap fail the flow loudly rather than
// silently keeping a stale server.
return {
kind: "launchd",
unitPath,
render: (plan) => renderBootServicePlist(plan, { homeDir: input.homeDir }),
stop: [
{
step: "stopping the installed launch agent",
command: "launchctl",
args: ["bootout", serviceTarget],
optional: true,
timeout: STOP_STEP_TIMEOUT,
},
],
activate: [
// A persisted `launchctl disable` override refuses bootstrap; clear it.
{
step: "enabling the launch agent",
command: "launchctl",
args: ["enable", serviceTarget],
optional: true,
},
// Start last. No administrative state write occurs after this succeeds.
{
step: "starting the service",
command: "launchctl",
args: ["bootstrap", domainTarget, unitPath],
},
],
restart: [
{
step: "restarting the service after a failed update",
command: "launchctl",
args: ["bootstrap", domainTarget, unitPath],
},
],
// No `launchctl disable` here: a persisted override would sabotage a
// later reinstall. Removing the plist is what stops the next login load.
// A bootout that fails for a reason other than "not loaded" leaves the
// job running until logout; the failure is in the boot-service log.
deactivate: [
{
step: "stopping the service",
command: "launchctl",
args: ["bootout", serviceTarget],
optional: true,
timeout: STOP_STEP_TIMEOUT,
},
],
finalize: [],
};
}
/** Undefined means this host cannot run the background service. */
export function selectBootServiceManager(input: {
readonly platform: NodeJS.Platform;
readonly homeDir: string;
readonly uid: number | undefined;
readonly path: Path.Path;
}): BootServiceManager | undefined {
if (input.homeDir === "") {
return undefined;
}
if (input.platform === "linux") {
return systemdManager({ path: input.path, homeDir: input.homeDir });
}
if (input.platform === "darwin" && input.uid !== undefined) {
return launchdManager({ path: input.path, homeDir: input.homeDir, uid: input.uid });
}
return undefined;
}
export class BootServiceUnsupportedError extends Schema.TaggedErrorClass<BootServiceUnsupportedError>()(
"BootServiceUnsupportedError",
{ platform: Schema.String },
) {
override get message(): string {
return `Background setup currently supports Linux with systemd; this machine reports '${this.platform}'.`;
return `Background setup supports Linux with systemd and macOS with launchd; this machine reports '${this.platform}'.`;
}
}
@@ -163,14 +435,15 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: {
}) {
const hostExecPath = yield* HostProcessExecutablePath;
const platform = yield* HostProcessPlatform;
const uid = yield* HostProcessUserId;
const homeDir = yield* Config.string("HOME").pipe(Config.withDefault(""));
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const runner = yield* ProcessRunner.ProcessRunner;
const host = input.host ?? { execPath: hostExecPath };
const unitDir = path.join(homeDir, ".config", "systemd", "user");
const unitPath = path.join(unitDir, BOOT_SERVICE_UNIT_FILE);
const detectedManager = selectBootServiceManager({ platform, homeDir, uid, path });
const unitPath = detectedManager?.unitPath ?? "";
const logPath = path.join(input.logsDir, "boot-service.log");
const launcherPath = path.join(input.baseDir, "runtime", SERVICE_LAUNCHER_FILE);
const statePath = path.join(input.baseDir, "runtime", SERVICE_STATE_FILE);
@@ -198,11 +471,11 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: {
unitPath,
};
const requireSystemdLinux = Effect.gen(function* () {
if (platform !== "linux" || homeDir === "") {
return yield* new BootServiceUnsupportedError({ platform });
}
});
const requireManager = Effect.suspend(() =>
detectedManager === undefined
? new BootServiceUnsupportedError({ platform })
: Effect.succeed(detectedManager),
);
const runStep = Effect.fn("cloud.boot_service.run_step")(function* (
step: string,
@@ -235,8 +508,25 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: {
);
});
const runSteps = (steps: ReadonlyArray<BootServiceStep>) =>
Effect.forEach(
steps,
(entry) => {
const run = runStep(
entry.step,
entry.command,
entry.args,
entry.timeout === undefined ? undefined : { timeout: entry.timeout },
);
// runStep's tapError already appends the failure to the log, so an
// ignored optional step still leaves a trace.
return entry.optional === true ? run.pipe(Effect.ignore) : run.pipe(Effect.asVoid);
},
{ discard: true },
);
const install: BootService["Service"]["install"] = Effect.gen(function* () {
yield* requireSystemdLinux;
const manager = yield* requireManager;
yield* fs
.makeDirectory(input.logsDir, { recursive: true })
.pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause })));
@@ -298,11 +588,7 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: {
.exists(unitPath)
.pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause })));
if (installed) {
yield* runStep("stopping the installed service", "systemctl", [
"--user",
"stop",
BOOT_SERVICE_UNIT_FILE,
]);
yield* runSteps(manager.stop);
}
yield* Effect.gen(function* () {
@@ -316,7 +602,7 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: {
}
}
yield* fs
.makeDirectory(unitDir, { recursive: true })
.makeDirectory(path.dirname(unitPath), { recursive: true })
.pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause })));
yield* writeDurably(launcherPath, launcherSource);
yield* writeDurably(
@@ -331,58 +617,35 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: {
2,
)}\n`,
);
yield* writeDurably(unitPath, renderBootServiceUnit(plan));
yield* writeDurably(unitPath, manager.render(plan));
yield* runStep("reloading systemd user units", "systemctl", ["--user", "daemon-reload"]);
yield* runStep("enabling the service", "systemctl", [
"--user",
"enable",
BOOT_SERVICE_UNIT_FILE,
]);
yield* runStep("enabling lingering for this user", "loginctl", ["enable-linger"]);
// Start last. No administrative state write occurs after this succeeds.
yield* runStep("starting the service", "systemctl", [
"--user",
"restart",
BOOT_SERVICE_UNIT_FILE,
]);
yield* runSteps(manager.activate);
}).pipe(
Effect.tapError(() =>
installed
? runStep("restarting the service after a failed update", "systemctl", [
"--user",
"restart",
BOOT_SERVICE_UNIT_FILE,
]).pipe(Effect.ignore)
: Effect.void,
installed ? runSteps(manager.restart).pipe(Effect.ignore) : Effect.void,
),
);
return plan;
}).pipe(Effect.withSpan("cloud.boot_service.install"));
const uninstall: BootService["Service"]["uninstall"] = Effect.gen(function* () {
yield* requireSystemdLinux;
const manager = yield* requireManager;
if (
!(yield* fs
.exists(unitPath)
.pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause }))))
)
return false;
yield* runStep("stopping the service", "systemctl", [
"--user",
"disable",
"--now",
BOOT_SERVICE_UNIT_FILE,
]);
yield* runSteps(manager.deactivate);
yield* fs
.remove(unitPath)
.pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause })));
yield* runStep("reloading systemd user units", "systemctl", ["--user", "daemon-reload"]);
yield* runSteps(manager.finalize);
return true;
}).pipe(Effect.withSpan("cloud.boot_service.uninstall"));
const status: BootService["Service"]["status"] = Effect.gen(function* () {
if (platform !== "linux" || homeDir === "") {
if (detectedManager === undefined) {
return { supported: false, installed: false, current: false, unitPath, logPath };
}
if (!(yield* fs.exists(unitPath))) {
@@ -401,7 +664,7 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: {
supported: true,
installed: true,
current:
unit === renderBootServiceUnit(plan) &&
unit === detectedManager.render(plan) &&
launcherExists &&
runtimeEntryExists &&
Option.isSome(runtimeSentinel) &&
+2 -1
View File
@@ -649,7 +649,8 @@ export const pendingServiceUpdateExists = Effect.gen(function* () {
});
// A pending update alone is not proof a replacement server is coming: an
// explicit launcher stop (`t3 service uninstall`, `systemctl stop`) during
// explicit launcher stop (`t3 service uninstall`, `systemctl stop`,
// `launchctl bootout`) during
// the pending window also tears this server down. The launcher marks that case
// just before it signals the child, so pending + no marker is the handoff.
const pendingUpdateHandoffExists = Effect.gen(function* () {
+2 -2
View File
@@ -10,8 +10,8 @@ import * as ProcessRunner from "../processRunner.ts";
/**
* A pinned runtime is an exact `t3@<version>` npm-installed into
* <baseDir>/runtime/versions/<version>. The boot service points its systemd
* unit here, and server self-update installs the target version here before
* <baseDir>/runtime/versions/<version>. The boot service points its unit or
* launch agent here, and server self-update installs the target version here before
* switching over, never `npx t3`, whose cache is ephemeral and whose
* registry fetch at boot would make startup depend on the network.
*/
@@ -125,6 +125,31 @@ 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", () => {
+7 -1
View File
@@ -216,7 +216,13 @@ export function parseModelsCliOutput(stdout: string): {
};
for (const line of lines) {
const slugMatch = SLUG_LINE_RE.exec(line);
// 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);
if (slugMatch) {
flushModel();
currentSlug = slugMatch[1]!;
@@ -10,6 +10,7 @@ import type {
} from "@t3tools/contracts";
import * as ProjectionSnapshotQuery from "../orchestration/Services/ProjectionSnapshotQuery.ts";
import * as SourceControlProviderRegistry from "../sourceControl/SourceControlProviderRegistry.ts";
import {
PullRequestProviderError,
type ProviderChangeRequest,
@@ -144,11 +145,16 @@ 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({
@@ -163,6 +169,110 @@ 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,10 +36,13 @@ 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,
@@ -360,6 +363,65 @@ 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">,
@@ -373,7 +435,12 @@ export const make = Effect.gen(function* () {
cause: error,
}),
),
Effect.map((snapshot) => {
Effect.flatMap((snapshot) =>
refineUnknownProjectKinds(snapshot.projects, filter).pipe(
Effect.map((refinedKinds) => ({ refinedKinds, snapshot })),
),
),
Effect.map(({ refinedKinds, snapshot }) => {
const supported: SupportedProject[] = [];
const unimplemented = new Map<
string,
@@ -383,15 +450,18 @@ 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 kind = project.repositoryIdentity?.provider as
| SourceControlProviderKind
| undefined;
const identity = project.repositoryIdentity;
let kind = identity?.provider as SourceControlProviderKind | undefined;
const repository = repositoryIdentityOf(project);
if (kind === undefined || repository === null) continue;
if (!identity || 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.
const host = pullRequestHostOf(project.repositoryIdentity, kind);
if (kind === "unknown") {
const provider = detectSourceControlProviderFromRemoteUrl(identity.locator.remoteUrl);
kind = provider === null ? kind : (refinedKinds.get(provider.baseUrl) ?? kind);
}
const host = pullRequestHostOf(identity, 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 { assert, describe, it } from "@effect/vitest";
import { afterEach, assert, describe, expect, it, vi } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
@@ -12,6 +12,36 @@ 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 = yield* ResourceMonitorHostLinuxLibc;
const linuxLibc = platform === "linux" ? yield* ResourceMonitorHostLinuxLibc : undefined;
const executableName = binaryName(platform);
const platformKey = resourceMonitorPlatformKey(platform, architecture);
const rustTarget = resourceMonitorRustTarget(platform, architecture, linuxLibc);
+1
View File
@@ -435,6 +435,7 @@ 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),
);
+3 -1
View File
@@ -317,7 +317,9 @@ export class Launcher {
// This must happen synchronously at signal receipt. A queued update
// transition may already be terminating the active child, and that child
// needs to see the marker in its shutdown finalizer. KillMode=mixed also
// ensures systemd signals the launcher before the rest of the cgroup.
// ensures systemd signals the launcher before the rest of the cgroup, and
// launchd signals only the job's main process (this launcher), so the
// marker lands before the child sees any signal on both platforms.
try {
NodeFS.writeFileSync(stopMarkerPath(this.#baseDir), "", { mode: 0o600 });
} catch {
@@ -203,6 +203,38 @@ 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,6 +50,7 @@ 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;
@@ -254,7 +255,15 @@ export const makeWithProviders = Effect.fn("makeSourceControlProviderRegistryWit
});
const resolveHandle: SourceControlProviderRegistry["Service"]["resolveHandle"] = (input) =>
Cache.get(providerContextCache, input.cwd).pipe(
(input.context === undefined
? Cache.get(providerContextCache, input.cwd)
: refineUnknownRemoteProvider({
specs: discoverySpecs,
process,
cwd: input.cwd,
context: input.context,
})
).pipe(
Effect.map((context) => {
const kind = context?.provider.kind ?? "unknown";
const provider = providers.get(kind) ?? unsupportedProvider(kind);
@@ -33,6 +33,7 @@ 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",
@@ -52,8 +53,35 @@ it.effect("spawns through the public adapter with the provided host references",
cwd: "C:\\workspace",
cols: 120,
rows: 40,
env: {},
name: "xterm-color",
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",
},
]);
}).pipe(Effect.provide(testLayer)),
+9 -2
View File
@@ -141,14 +141,21 @@ 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: input.env,
name: platform === "win32" ? "xterm-color" : "xterm-256color",
env,
name: "xterm-256color",
}),
catch: (cause) =>
new PtyAdapter.PtySpawnError({
+30 -2
View File
@@ -1,5 +1,5 @@
/**
* UsageService - scans provider transcripts and returns priced daily usage.
* UsageService - scans provider transcripts and returns priced usage buckets.
*
* 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,6 +64,7 @@ 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;
@@ -297,6 +298,30 @@ 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;
@@ -312,12 +337,15 @@ export const make = Effect.gen(function* () {
detail: `sinceDay '${input.sinceDay}' is not a valid date`,
});
}
const windowStartMs = DateTime.toEpochMillis(windowStart.value) - MTIME_SLACK_MS;
const windowStartMs =
(hourlyWindow?.sinceTimeMs ?? 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,
});
+73 -1
View File
@@ -36,11 +36,24 @@ function record(overrides: Partial<UsageRecord> = {}): UsageRecord {
};
}
function aggregate(records: readonly UsageRecord[], timeZone = "UTC") {
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"),
}
: {};
const aggregator = new UsageAggregator({
timeZone,
sinceDay: "2026-08-01",
untilDay: "2026-08-31",
resolution,
...hourlyBounds,
rates,
});
for (const item of records) aggregator.add(item);
@@ -48,6 +61,19 @@ function aggregate(records: readonly UsageRecord[], timeZone = "UTC") {
}
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:" }),
@@ -76,6 +102,52 @@ 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,6 +1001,23 @@ 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();
+24 -14
View File
@@ -1477,25 +1477,35 @@ 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;
}
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,
});
}
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 = branchResult.stdout.trim();
const branch = branchValue.length > 0 && branchValue !== "HEAD" ? branchValue : null;
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;
}
const upstream = yield* resolveCurrentUpstream(cwd);
const upstreamRef = upstream?.upstreamRef ?? null;
let aheadCount = 0;
+72 -55
View File
@@ -35,16 +35,16 @@
// app colors before React mounts.
const DEFAULT_THEME_PALETTES = {
light: {
background: "#fdf7fd",
foreground: "#501854",
accent: "#db2777",
chrome: "#fdf7fd",
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)",
},
dark: {
background: "#1f1a24",
foreground: "#f9f8fb",
accent: "#a3004c",
chrome: "#1f1a24",
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)",
},
};
// 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: "#fdf7fd",
foreground: "#501854",
accent: "#db2777",
chrome: "#fdf7fd",
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)",
},
dark: {
background: "#1f1a24",
foreground: "#f9f8fb",
accent: "#a3004c",
chrome: "#1f1a24",
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)",
},
},
grove: {
light: {
background: "#f3f7f4",
foreground: "#241523",
accent: "#1b7d50",
chrome: "#f3f7f4",
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)",
},
dark: {
background: "#1b2821",
foreground: "#fffaff",
accent: "#69d69a",
chrome: "#1b2821",
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)",
},
},
ocean: {
light: {
background: "#f5f7f8",
foreground: "#241523",
accent: "#2672af",
chrome: "#f5f7f8",
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)",
},
dark: {
background: "#17212b",
foreground: "#fffaff",
accent: "#70b9ee",
chrome: "#17212b",
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)",
},
},
ember: {
light: {
background: "#f9f7f5",
foreground: "#241523",
accent: "#ae552a",
chrome: "#f9f7f5",
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)",
},
dark: {
background: "#291e1a",
foreground: "#fffaff",
accent: "#f09a64",
chrome: "#291e1a",
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)",
},
},
iris: {
light: {
background: "#f8f7f9",
foreground: "#241523",
accent: "#7253b9",
chrome: "#f8f7f9",
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)",
},
dark: {
background: "#1d1929",
foreground: "#fffaff",
accent: "#9d7df2",
chrome: "#1d1929",
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)",
},
},
};
@@ -152,9 +152,26 @@
}
};
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);
// 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 isRecord = (value) =>
typeof value === "object" && value !== null && !Array.isArray(value);
const isThemeId = (value) =>
@@ -322,13 +339,13 @@
const fallbackSplash = isDark ? SPLASH_COLORS.dark : SPLASH_COLORS.light;
const customSplash = customColors
? {
background: isHexColor(customColors.canvas)
background: isThemeColor(customColors.canvas)
? customColors.canvas
: (customDefaults?.background ?? fallbackSplash.background),
foreground: isHexColor(customColors.text)
foreground: isThemeColor(customColors.text)
? customColors.text
: (customDefaults?.foreground ?? fallbackSplash.foreground),
accent: isHexColor(customColors.accent)
accent: isThemeColor(customColors.accent)
? customColors.accent
: (customDefaults?.accent ?? fallbackSplash.accent),
}
@@ -350,7 +367,7 @@
}
document.documentElement.classList.toggle("dark", isDark);
const chromeColor = customColors
? isHexColor(customColors.chrome)
? isThemeColor(customColors.chrome)
? customColors.chrome
: (customDefaults?.chrome ?? fallbackSplash.background)
: builtInSplash
+6 -1
View File
@@ -21,8 +21,9 @@
"@dnd-kit/utilities": "^3.2.2",
"@effect/atom-react": "catalog:",
"@formkit/auto-animate": "^0.9.0",
"@legendapp/list": "3.3.3",
"@legendapp/list": "catalog:",
"@lexical/react": "^0.41.0",
"@noble/hashes": "catalog:",
"@pierre/diffs": "catalog:",
"@pierre/trees": "1.0.0-beta.4",
"@t3tools/client-runtime": "workspace:*",
@@ -31,8 +32,11 @@
"@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",
@@ -53,6 +57,7 @@
"@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",
+8 -2
View File
@@ -19,7 +19,10 @@ import LegacyThreadSidebar from "./LegacySidebar";
import ThreadSidebar from "./Sidebar";
import { SettingsSidebarNav } from "./settings/SettingsSidebarNav";
import { SidebarChromeHeader } from "./sidebar/SidebarChrome";
import { useSidebarStageBackdropVariant } from "./SidebarStageBackdrop";
import {
resolveSidebarStageFocusRingOffsetClass,
useSidebarStageBackdropVariant,
} from "./SidebarStageBackdrop";
import { useProjects } from "../state/entities";
import {
resolveInitialThreadSidebarWidth,
@@ -105,7 +108,10 @@ function SidebarControl() {
"pointer-events-auto",
isSidebarVisible &&
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!",
"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),
)}
aria-label="Toggle main sidebar"
/>
+80 -10
View File
@@ -9,7 +9,7 @@ import {
HistoryIcon,
MonitorIcon,
} from "lucide-react";
import { memo, useCallback, useEffect, useMemo, useRef, useState } from "react";
import { memo, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
import { useComposerDraftStore, type DraftId } from "../composerDraftStore";
import { useProject, useThread, useThreadShellsForProjectRefs } from "../state/entities";
@@ -218,16 +218,20 @@ const MobileRunContextSelector = memo(function MobileRunContextSelector({
/**
* Collapse the strip's labels to icons only when the text no longer fits.
*
* 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.
* 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.
*/
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.
@@ -241,7 +245,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 absolutely-positioned nodes (the compact-hidden labels).
// artifacts and other out-of-flow nodes.
const contentWidth = (parent: Element): number => {
const gap = Number.parseFloat(getComputedStyle(parent).columnGap) || 0;
let width = 0;
@@ -283,9 +287,71 @@ function useLabelsOverflow(element: HTMLDivElement | null): boolean {
needed += Math.max(0, textWidth - label.clientWidth);
}
}
setOverflows(compact ? needed > available - COMPACT_EXPAND_HYSTERESIS_PX : needed > available);
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);
}, []);
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.
@@ -403,7 +469,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 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 overflow-x-clip overflow-y-visible ps-1 pe-2 pt-5 pb-1"
>
{isMobile && showGitControls ? (
<MobileRunContextSelector
@@ -431,7 +497,11 @@ export const BranchToolbar = memo(function BranchToolbar({
{...(showEnvironmentPicker && onEnvironmentChange ? { onEnvironmentChange } : {})}
/>
{showGitControls ? (
<Separator orientation="vertical" className="mx-0.5 h-3.5!" />
<Separator
orientation="vertical"
className="mx-0.5 h-3.5!"
data-composer-context-control
/>
) : null}
</>
)}
@@ -714,7 +714,10 @@ export function BranchToolbarBranchSelector({
open={isBranchMenuOpen}
value={resolvedActiveBranch}
>
<div className={cn("flex min-w-0 items-center gap-1", className)}>
<div
className={cn("flex min-w-0 items-center gap-1", className)}
data-composer-context-control
>
{branchPr && branchPrStatus ? (
<Tooltip>
<TooltipTrigger
@@ -751,9 +754,14 @@ export function BranchToolbarBranchSelector({
<GitBranchIcon className="size-3 shrink-0 opacity-70" />
<span
data-composer-label
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"
className="min-w-0 max-w-[240px] group-data-[compact]/composer-context:max-w-0"
>
{triggerLabel}
<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>
</span>
<ChevronDownIcon className="size-3 shrink-0 opacity-50" />
</ComboboxTrigger>
@@ -50,7 +50,10 @@ 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">
<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
>
{activeWorktreePath ? (
<>
<FolderGitIcon className="size-3" />
@@ -84,6 +87,7 @@ 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" />
@@ -94,9 +98,14 @@ export const BranchToolbarEnvModeSelector = memo(function BranchToolbarEnvModeSe
)}
<span
data-composer-label
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"
className="min-w-0 max-w-[240px] group-data-[compact]/composer-context:max-w-0"
>
<SelectValue />
<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>
</span>
</SelectTrigger>
<SelectPopup>
@@ -48,7 +48,10 @@ 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">
<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
>
{activeEnvironment?.isPrimary ? (
<MonitorIcon className="size-3 shrink-0" />
) : (
@@ -56,9 +59,14 @@ export const BranchToolbarEnvironmentSelector = memo(function BranchToolbarEnvir
)}
<span
data-composer-label
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"
className="min-w-0 max-w-[240px] group-data-[compact]/composer-context:max-w-0"
>
{activeEnvironment?.label ?? "Run on"}
<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>
</span>
</span>
);
@@ -76,6 +84,7 @@ 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" />
@@ -84,9 +93,14 @@ export const BranchToolbarEnvironmentSelector = memo(function BranchToolbarEnvir
)}
<span
data-composer-label
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"
className="min-w-0 max-w-[240px] group-data-[compact]/composer-context:max-w-0"
>
<SelectValue />
<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>
</span>
</SelectTrigger>
<SelectPopup>
+32 -4
View File
@@ -264,7 +264,13 @@ import {
ProviderStatusBanner,
shouldShowProviderStatusBanner,
} from "./chat/ProviderStatusBanner";
import { ThreadErrorBanner } from "./chat/ThreadErrorBanner";
import {
dismissThreadErrorBannerForSession,
getThreadErrorBannerKey,
isThreadErrorBannerDismissedForSession,
shouldShowThreadErrorBanner,
ThreadErrorBanner,
} from "./chat/ThreadErrorBanner";
import { resolveThreadPr } from "./ThreadStatusIndicators";
import { ComposerBannerStack, type ComposerBannerStackItem } from "./chat/ComposerBannerStack";
import { ThreadSyncStatusPill } from "./chat/ThreadSyncStatusPill";
@@ -1493,6 +1499,24 @@ 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 —
@@ -2618,7 +2642,7 @@ function ChatViewContent(props: ChatViewProps) {
)
? activeProviderStatus
: null;
const hasTimelineTopBanner = Boolean(threadError) || visibleProviderStatus !== null;
const hasTimelineTopBanner = Boolean(visibleThreadError) || visibleProviderStatus !== null;
const activeProjectCwd = activeProject?.workspaceRoot ?? null;
const activeThreadWorktreePath = activeThread?.worktreePath ?? null;
const activeWorkspaceRoot = activeThreadWorktreePath ?? activeProjectCwd ?? undefined;
@@ -6146,8 +6170,12 @@ function ChatViewContent(props: ChatViewProps) {
</header>
<ThreadErrorBanner
error={threadError}
onDismiss={() => setThreadError(activeThread.id, null)}
error={visibleThreadError}
onDismiss={() => {
setThreadError(activeThread.id, null);
dismissThreadErrorBannerForSession(threadErrorBannerKey);
setThreadErrorBannerDismissTick((tick) => tick + 1);
}}
/>
{/* Main content area with optional plan sidebar */}
<div className="flex min-h-0 min-w-0 flex-1">
@@ -22,6 +22,7 @@ import { flushSync } from "react-dom";
import {
CheckIcon,
ChevronDownIcon,
CloudDownloadIcon,
CloudUploadIcon,
ExternalLinkIcon,
GitBranchPlusIcon,
@@ -357,7 +358,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 <InfoIcon className={iconClassName} />;
if (quickAction.kind === "run_pull") return <CloudDownloadIcon className={iconClassName} />;
if (quickAction.kind === "run_action") {
if (quickAction.action === "commit") return <GitCommitIcon className={iconClassName} />;
if (quickAction.action === "push" || quickAction.action === "commit_push") {
@@ -366,6 +367,7 @@ 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} />;
}
@@ -32,6 +32,7 @@ import {
sortThreadsForSidebar,
sortProjectsForSidebar,
sortScopedProjectsForSidebar,
shouldCreateNewThreadInCurrentProject,
THREAD_JUMP_HINT_SHOW_DELAY_MS,
} from "./Sidebar.logic";
import {
@@ -410,6 +411,21 @@ 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({
+11
View File
@@ -274,6 +274,17 @@ 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[];
+93 -25
View File
@@ -1,5 +1,6 @@
import { autoAnimate } from "@formkit/auto-animate";
import { useAtomValue } from "@effect/atom-react";
import * as Schema from "effect/Schema";
import {
DndContext,
PointerSensor,
@@ -28,7 +29,7 @@ import {
scopeThreadRef,
scopedThreadKey,
} from "@t3tools/client-runtime/environment";
import type { ScopedThreadRef } from "@t3tools/contracts";
import type { ScopedThreadRef, ThreadId } from "@t3tools/contracts";
import type { TimestampFormat } from "@t3tools/contracts/settings";
import {
AlarmClockIcon,
@@ -100,6 +101,7 @@ 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";
@@ -129,6 +131,7 @@ import {
resolveSettledTimestamp,
resolveSidebarThreadStatus,
searchSidebarThreadsByTitle,
shouldCreateNewThreadInCurrentProject,
resolveWorkingStartedAt,
sortLogicalProjectsForSidebar,
sortPinnedThreadsForSidebar,
@@ -176,6 +179,9 @@ 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";
@@ -1641,6 +1647,24 @@ 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(
@@ -2044,8 +2068,15 @@ export default function Sidebar() {
() => setSettledVisibleCount((count) => count + SETTLED_TAIL_PAGE_COUNT),
[],
);
const [settledShelfExpanded, setSettledShelfExpanded] = useState(true);
const toggleSettledShelf = useCallback(() => setSettledShelfExpanded((value) => !value), []);
const [settledShelfExpanded, setSettledShelfExpanded] = useLocalStorage(
SETTLED_SHELF_EXPANDED_KEY,
true,
Schema.Boolean,
);
const toggleSettledShelf = useCallback(
() => setSettledShelfExpanded((value) => !value),
[setSettledShelfExpanded],
);
const renderedSettledThreads = useMemo(() => {
if (settledShelfExpanded) return visibleSettledThreads;
if (routeThreadKey === null) return [];
@@ -2059,8 +2090,15 @@ 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] = useState(false);
const toggleSnoozedShelf = useCallback(() => setSnoozedShelfExpanded((value) => !value), []);
const [snoozedShelfExpanded, setSnoozedShelfExpanded] = useLocalStorage(
SNOOZED_SHELF_EXPANDED_KEY,
false,
Schema.Boolean,
);
const toggleSnoozedShelf = useCallback(
() => setSnoozedShelfExpanded((value) => !value),
[setSnoozedShelfExpanded],
);
const visibleSnoozedThreads = useMemo(() => {
if (snoozedShelfExpanded) return snoozedThreads;
// The open thread must never vanish behind the collapsed shelf: a
@@ -3017,6 +3055,9 @@ 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(() =>
@@ -3059,6 +3100,7 @@ export default function Sidebar() {
confirmThreadDelete,
copyBranchToClipboard,
copyPathToClipboard,
copyThreadIdToClipboard,
deleteThread,
handleMultiSelectContextMenu,
markThreadUnread,
@@ -3145,29 +3187,39 @@ 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(() => {
// One project: nothing to pick, create immediately.
if (projectGroups.length <= 1) {
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;
}
if (isMobile) setOpenMobile(false);
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]);
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. chat.newLocal always creates directly, so
// it is only a correct label when chat.new is unbound.
// 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.
const newThreadShortcutLabel =
shortcutLabelForCommand(keybindings, "chat.new") ??
shortcutLabelForCommand(keybindings, "chat.newLocal");
(projectGroups.length <= 1 ? shortcutLabelForCommand(keybindings, "chat.newLocal") : undefined);
const newThreadInProjectShortcutLabel = shortcutLabelForCommand(keybindings, "chat.newLocal");
return (
<>
<SidebarChromeHeader isElectron={isElectron} />
@@ -3245,9 +3297,25 @@ export default function Sidebar() {
/>
</TooltipTrigger>
<TooltipPopup side="right">
{newThreadShortcutLabel
? `New thread (${newThreadShortcutLabel})`
: "New thread"}
{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"
)}
</TooltipPopup>
</Tooltip>
</div>
@@ -4,7 +4,9 @@ import { renderToStaticMarkup } from "react-dom/server";
import {
resolveEnvironmentIdentificationPillLabel,
resolveSidebarStageBackdropVariant,
resolveSidebarStageFocusRingOffsetClass,
StageBackdropArt,
StageBackdropButtonArt,
} from "./SidebarStageBackdrop";
describe("SidebarStageBackdrop", () => {
@@ -22,6 +24,15 @@ 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) => {
@@ -37,4 +48,26 @@ 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,6 +23,14 @@ 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 {
@@ -62,6 +70,10 @@ 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;
@@ -93,7 +105,7 @@ const NIGHTLY_SPARKLES: ReadonlyArray<{ x: number; y: number }> = [
{ x: 246, y: 26 },
];
function NightlySkyArt() {
function NightlySkyArt({ compact = false }: { compact?: boolean }) {
const idPrefix = useId().replaceAll(":", "");
const skyId = `${idPrefix}-stage-night-sky`;
const glowId = `${idPrefix}-stage-night-glow`;
@@ -104,10 +116,10 @@ function NightlySkyArt() {
return (
<svg
className="h-full w-full"
className="stage-art stage-nightly h-full w-full"
fill="none"
preserveAspectRatio="xMinYMin slice"
viewBox={STAGE_BACKDROP_VIEW_BOX}
viewBox={compact ? "96 0 8192 96" : STAGE_BACKDROP_VIEW_BOX}
xmlns="http://www.w3.org/2000/svg"
>
<defs>
@@ -120,9 +132,9 @@ function NightlySkyArt() {
gradientUnits="userSpaceOnUse"
spreadMethod="reflect"
>
<stop stopColor="#07152F" />
<stop offset="0.5" stopColor="#151443" />
<stop offset="1" stopColor="#32155B" />
<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)" }} />
</linearGradient>
<radialGradient
id={glowId}
@@ -132,20 +144,28 @@ function NightlySkyArt() {
gradientTransform="translate(216 18) rotate(137) scale(120 84)"
gradientUnits="userSpaceOnUse"
>
<stop stopColor="#5165D8" stopOpacity="0.4" />
<stop offset="0.5" stopColor="#283075" stopOpacity="0.16" />
<stop offset="1" stopColor="#111635" stopOpacity="0" />
<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" />
</radialGradient>
<linearGradient id={cloudId} x1="0" y1="60" x2="288" y2="96" gradientUnits="userSpaceOnUse">
<stop stopColor="#4EA4FF" stopOpacity="0.5" />
<stop offset="0.52" stopColor="#696FEA" stopOpacity="0.62" />
<stop offset="1" stopColor="#A85BEA" stopOpacity="0.5" />
<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" />
</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 fill="#E4EAFF">
<g style={{ fill: "var(--stage-night-line)" }}>
{NIGHTLY_STARS.map((star) => (
<circle
key={`${star.cx}-${star.cy}`}
@@ -156,7 +176,12 @@ function NightlySkyArt() {
/>
))}
</g>
<g stroke="#C8D7FF" strokeLinecap="round" strokeOpacity="0.7" strokeWidth="0.6">
<g
style={{ stroke: "var(--stage-night-line)" }}
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}`} />
@@ -191,7 +216,7 @@ function NightlySkyArt() {
);
}
function DevBlueprintArt() {
function DevBlueprintArt({ compact = false }: { compact?: boolean }) {
const idPrefix = useId().replaceAll(":", "");
const paperId = `${idPrefix}-stage-bp-paper`;
const glowId = `${idPrefix}-stage-bp-glow`;
@@ -205,10 +230,10 @@ function DevBlueprintArt() {
return (
<svg
className="stage-blueprint h-full w-full"
className="stage-art stage-blueprint h-full w-full"
fill="none"
preserveAspectRatio="xMinYMin slice"
viewBox={STAGE_BACKDROP_VIEW_BOX}
viewBox={compact ? "64 0 8192 96" : STAGE_BACKDROP_VIEW_BOX}
xmlns="http://www.w3.org/2000/svg"
>
<defs>
@@ -221,9 +246,9 @@ function DevBlueprintArt() {
gradientUnits="userSpaceOnUse"
spreadMethod="reflect"
>
<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)" }} />
<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)" }} />
</linearGradient>
<radialGradient
id={glowId}
@@ -233,9 +258,13 @@ function DevBlueprintArt() {
gradientTransform="translate(216 14) rotate(137) scale(120 84)"
gradientUnits="userSpaceOnUse"
>
<stop stopColor="#D4F6FF" stopOpacity="0.4" />
<stop offset="0.52" stopColor="#65C8FF" stopOpacity="0.16" />
<stop offset="1" stopColor="#276AF1" stopOpacity="0" />
<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" />
</radialGradient>
<radialGradient
id={celesteGlowId}
@@ -245,9 +274,13 @@ function DevBlueprintArt() {
gradientTransform="translate(474 44) rotate(166) scale(156 92)"
gradientUnits="userSpaceOnUse"
>
<stop stopColor="#D2FFFF" stopOpacity="0.34" />
<stop offset="0.5" stopColor="#48DCF5" stopOpacity="0.18" />
<stop offset="1" stopColor="#277EF1" stopOpacity="0" />
<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" />
</radialGradient>
<radialGradient
id={violetGlowId}
@@ -257,20 +290,34 @@ function DevBlueprintArt() {
gradientTransform="translate(704 18) rotate(145) scale(132 88)"
gradientUnits="userSpaceOnUse"
>
<stop stopColor="#D9D8FF" stopOpacity="0.3" />
<stop offset="0.52" stopColor="#7C8BFF" stopOpacity="0.14" />
<stop offset="1" stopColor="#3155DF" stopOpacity="0" />
<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" />
</radialGradient>
<pattern id={minorGridId} width="8" height="8" patternUnits="userSpaceOnUse">
<path d="M8 0H0V8" stroke="#EAF6FF" strokeOpacity="0.14" strokeWidth="0.5" />
<path
d="M8 0H0V8"
style={{ stroke: "var(--stage-art-line)" }}
strokeOpacity="0.14"
strokeWidth="0.5"
/>
</pattern>
<pattern id={majorGridId} width="32" height="32" patternUnits="userSpaceOnUse">
<path d="M32 0H0V32" stroke="#EAF6FF" strokeOpacity="0.26" strokeWidth="0.6" />
<path
d="M32 0H0V32"
style={{ stroke: "var(--stage-art-line)" }}
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"
stroke="#DDF7FF"
style={{ stroke: "var(--stage-art-line)" }}
strokeOpacity="0.5"
strokeWidth="0.5"
/>
@@ -281,7 +328,12 @@ function DevBlueprintArt() {
<rect width="768" height="96" fill={`url(#${violetGlowId})`} />
</pattern>
<pattern id={annotationsId} width="768" height="96" patternUnits="userSpaceOnUse">
<g stroke="#DDF7FF" strokeLinecap="round" strokeOpacity="0.6" strokeWidth="0.7">
<g
style={{ stroke: "var(--stage-art-line)" }}
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" />
@@ -294,7 +346,12 @@ function DevBlueprintArt() {
<path d="M590 67V73M724 67V73" strokeOpacity="0.55" />
</g>
<g stroke="#DDF7FF" strokeLinecap="round" strokeOpacity="0.55" strokeWidth="0.6">
<g
style={{ stroke: "var(--stage-art-line)" }}
strokeLinecap="round"
strokeOpacity="0.55"
strokeWidth="0.6"
>
<g>
<path d="M34 60L38 64M38 60L34 64" />
</g>
@@ -318,7 +375,7 @@ function DevBlueprintArt() {
</g>
</g>
<g stroke="#DDF7FF" strokeOpacity="0.35" strokeWidth="0.6">
<g style={{ stroke: "var(--stage-art-line)" }} 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" />
@@ -3106,7 +3106,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
showMobilePendingAnswerActions && "hidden sm:flex",
)}
>
<div className="-m-1 flex min-w-0 flex-1 items-center gap-1 overflow-x-auto p-1 [scrollbar-width:none] [&::-webkit-scrollbar]:hidden">
<div className="-m-1 -ms-3.5 flex min-w-0 flex-1 items-center gap-1 overflow-x-auto p-1 ps-3.5 [scrollbar-width:none] [&::-webkit-scrollbar]:hidden">
{noProviderAvailable ? (
<Button
type="button"
@@ -3129,7 +3129,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
instanceEntries={providerInstanceEntries}
keybindings={keybindings}
modelOptionsByInstance={modelOptionsByInstance}
triggerClassName="-ms-px"
triggerClassName="-ms-2.5"
terminalOpen={terminalOpen}
open={isComposerModelPickerOpen}
{...(composerProviderState.modelPickerIconClassName
@@ -1,13 +1,18 @@
import { createElement } from "react";
import { renderToStaticMarkup } from "react-dom/server";
import { describe, expect, it, vi } from "vite-plus/test";
import { afterEach, describe, expect, it, vi } from "vite-plus/test";
const stageArtworkState = vi.hoisted(() => ({
mode: "none" as "artwork" | "none",
variant: null as "nightly" | "dev" | null,
}));
vi.mock("~/hooks/useSettings", () => ({
useEnvironmentIdentificationMode: () => "none",
useEnvironmentIdentificationMode: () => stageArtworkState.mode,
}));
vi.mock("../SidebarStageBackdrop", () => ({
StageBackdropButtonArt: () => null,
useSidebarStageBackdropVariant: () => null,
StageBackdropButtonArt: ({ variant }: { variant: string }) => `stage-${variant}`,
useSidebarStageBackdropVariant: (enabled = true) => (enabled ? stageArtworkState.variant : null),
}));
import { ComposerPrimaryActions, formatPendingPrimaryActionLabel } from "./ComposerPrimaryActions";
@@ -60,6 +65,32 @@ function renderStandaloneStop() {
);
}
function renderSendButton() {
return renderToStaticMarkup(
createElement(ComposerPrimaryActions, {
compact: true,
pendingAction: null,
isRunning: false,
showPlanFollowUpPrompt: false,
promptHasText: true,
isSendBusy: false,
sendDisabledReason: null,
isConnecting: false,
isEnvironmentUnavailable: false,
isPreparingWorktree: false,
hasSendableContent: true,
onPreviousPendingQuestion: () => {},
onInterrupt: () => {},
onImplementPlanInNewThread: () => {},
}),
);
}
afterEach(() => {
stageArtworkState.mode = "none";
stageArtworkState.variant = null;
});
describe("formatPendingPrimaryActionLabel", () => {
it("returns 'Submitting...' while responding", () => {
expect(
@@ -164,4 +195,24 @@ describe("ComposerPrimaryActions", () => {
expect(renderStandaloneStop()).toContain("size-8 sm:h-8 sm:w-8");
expect(renderStandaloneStop()).not.toContain("sm:size-7");
});
it("renders stage artwork inside the send button when artwork identification is active", () => {
stageArtworkState.mode = "artwork";
stageArtworkState.variant = "nightly";
const markup = renderSendButton();
expect(markup).toContain("stage-nightly");
expect(markup).toContain("bg-transparent text-white");
expect(markup).not.toContain("bg-message-action text-message-action-foreground");
});
it("keeps the normal send-button fill when artwork identification is inactive", () => {
stageArtworkState.variant = "nightly";
const markup = renderSendButton();
expect(markup).not.toContain("stage-nightly");
expect(markup).toContain("bg-message-action text-message-action-foreground");
});
});
@@ -1,6 +1,8 @@
import { memo, type PointerEventHandler } from "react";
import { ChevronDownIcon, ChevronLeftIcon } from "lucide-react";
import { useEnvironmentIdentificationMode } from "~/hooks/useSettings";
import { cn } from "~/lib/utils";
import { StageBackdropButtonArt, useSidebarStageBackdropVariant } from "../SidebarStageBackdrop";
import { Button } from "../ui/button";
import { Menu, MenuItem, MenuPopup, MenuTrigger } from "../ui/menu";
import { Spinner } from "../ui/spinner";
@@ -73,7 +75,11 @@ export const ComposerPrimaryActions = memo(function ComposerPrimaryActions({
const pointerFocusProps = preserveComposerFocusOnPointerDown
? { onPointerDown: preventPointerFocus }
: undefined;
const environmentIdentificationMode = useEnvironmentIdentificationMode();
const isSendDisabled = sendDisabledReason !== null;
const stageBackdropVariant = useSidebarStageBackdropVariant(
environmentIdentificationMode === "artwork",
);
const renderStopGenerationButton = (insidePendingAction: boolean) => (
<button
@@ -212,8 +218,10 @@ export const ComposerPrimaryActions = memo(function ComposerPrimaryActions({
<button
type="submit"
className={cn(
"relative isolate flex h-9 w-9 items-center justify-center overflow-hidden rounded-full text-message-action-foreground shadow-xs transition-all duration-150 enabled:cursor-pointer enabled:inset-shadow-[0_1px_--theme(--color-white/16%)] hover:scale-105 active:inset-shadow-[0_1px_--theme(--color-black/8%)] active:shadow-none disabled:pointer-events-none disabled:opacity-30 disabled:shadow-none disabled:hover:scale-100 sm:h-8 sm:w-8",
"bg-message-action enabled:shadow-message-action/24 hover:bg-message-action-hover",
"relative isolate flex h-9 w-9 items-center justify-center overflow-hidden rounded-full shadow-xs transition-all duration-150 enabled:cursor-pointer enabled:inset-shadow-[0_1px_--theme(--color-white/16%)] hover:scale-105 active:inset-shadow-[0_1px_--theme(--color-black/8%)] active:shadow-none disabled:pointer-events-none disabled:opacity-30 disabled:shadow-none disabled:hover:scale-100 sm:h-8 sm:w-8",
stageBackdropVariant
? "bg-transparent text-white enabled:shadow-black/24 enabled:hover:brightness-110"
: "bg-message-action text-message-action-foreground enabled:shadow-message-action/24 hover:bg-message-action-hover",
)}
{...pointerFocusProps}
disabled={
@@ -237,6 +245,11 @@ export const ComposerPrimaryActions = memo(function ComposerPrimaryActions({
: "Send message"
}
>
{stageBackdropVariant ? (
<span className="absolute inset-0 -z-10" aria-hidden="true">
<StageBackdropButtonArt variant={stageBackdropVariant} />
</span>
) : null}
{isConnecting || isSendBusy ? (
<Spinner className="size-3.5" aria-hidden="true" />
) : (
@@ -1,9 +1,74 @@
import { renderToStaticMarkup } from "react-dom/server";
import { describe, expect, it } from "vite-plus/test";
import { ThreadErrorBanner } from "./ThreadErrorBanner";
import {
dismissThreadErrorBannerForSession,
getThreadErrorBannerKey,
isThreadErrorBannerDismissedForSession,
shouldShowThreadErrorBanner,
ThreadErrorBanner,
} from "./ThreadErrorBanner";
describe("ThreadErrorBanner", () => {
it("stays hidden after its current error is dismissed", () => {
const bannerKey = getThreadErrorBannerKey("env:thread-a", "Aborted");
dismissThreadErrorBannerForSession(bannerKey);
expect(
shouldShowThreadErrorBanner(
"env:thread-a",
"Aborted",
isThreadErrorBannerDismissedForSession(bannerKey),
),
).toBe(false);
});
it("reappears when a new error arrives on the same thread", () => {
dismissThreadErrorBannerForSession(getThreadErrorBannerKey("env:thread-b", "Turn failed"));
const newErrorKey = getThreadErrorBannerKey("env:thread-b", "Provider crashed");
expect(isThreadErrorBannerDismissedForSession(newErrorKey)).toBe(false);
expect(
shouldShowThreadErrorBanner(
"env:thread-b",
"Provider crashed",
isThreadErrorBannerDismissedForSession(newErrorKey),
),
).toBe(true);
});
it("scopes dismissals to the thread that dismissed them", () => {
dismissThreadErrorBannerForSession(getThreadErrorBannerKey("env:thread-c", "Aborted"));
const otherThreadKey = getThreadErrorBannerKey("env:other-thread", "Aborted");
expect(isThreadErrorBannerDismissedForSession(otherThreadKey)).toBe(false);
expect(
shouldShowThreadErrorBanner(
"env:other-thread",
"Aborted",
isThreadErrorBannerDismissedForSession(otherThreadKey),
),
).toBe(true);
});
it("keeps a dismissal across visiting threads with no error", () => {
const bannerKey = getThreadErrorBannerKey("env:thread-d", "Aborted");
dismissThreadErrorBannerForSession(bannerKey);
expect(shouldShowThreadErrorBanner("env:thread-d", null, false)).toBe(false);
expect(isThreadErrorBannerDismissedForSession(bannerKey)).toBe(true);
expect(
shouldShowThreadErrorBanner(
"env:thread-d",
"Aborted",
isThreadErrorBannerDismissedForSession(bannerKey),
),
).toBe(false);
});
it("never shows a null error", () => {
expect(shouldShowThreadErrorBanner("env:thread-e", null, false)).toBe(false);
});
it("aligns the warning and dismiss icons with the first line of a multi-line error", () => {
const markup = renderToStaticMarkup(
<ThreadErrorBanner
@@ -4,6 +4,35 @@ import { Button } from "../ui/button";
import { CircleAlertIcon, XIcon } from "lucide-react";
import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
export function getThreadErrorBannerKey(threadKey: string, error: string | null): string | null {
return error === null ? null : `${threadKey}\u0000${error}`;
}
export function shouldShowThreadErrorBanner(
threadKey: string,
error: string | null,
isDismissed: boolean,
): boolean {
return getThreadErrorBannerKey(threadKey, error) !== null && !isDismissed;
}
// Session-scoped (module-level so it survives ChatView remounts, e.g. route
// changes between threads). Mirrors the branch-mismatch banner: a dismissal
// is remembered per thread key plus message, so navigating away to a thread
// with no error cannot resurrect the banner, while a different error message
// on the same thread still appears.
const sessionDismissedThreadErrorBannerKeys = new Set<string>();
export function dismissThreadErrorBannerForSession(bannerKey: string | null): void {
if (bannerKey !== null) {
sessionDismissedThreadErrorBannerKeys.add(bannerKey);
}
}
export function isThreadErrorBannerDismissedForSession(bannerKey: string | null): boolean {
return bannerKey !== null && sessionDismissedThreadErrorBannerKeys.has(bannerKey);
}
export const ThreadErrorBanner = memo(function ThreadErrorBanner({
error,
onDismiss,
@@ -12,12 +12,26 @@ import {
backgroundActivitySharedPolicySettings,
buildProviderInstanceUpdatePatch,
formatDiagnosticsDescription,
getChangedTypographySettingLabels,
hasChangedBackgroundActivitySettings,
isProjectGroupingEnabled,
projectGroupingModeFromToggle,
resolveBackgroundActivityProfileOption,
} from "./SettingsPanels.logic";
describe("typography settings restore", () => {
it("detects family and size changes by font row", () => {
expect(getChangedTypographySettingLabels(DEFAULT_UNIFIED_SETTINGS)).toEqual([]);
expect(
getChangedTypographySettingLabels({
...DEFAULT_UNIFIED_SETTINGS,
fontSizeInterface: 18,
fontFamilyCode: "Fira Code",
}),
).toEqual(["Interface font", "Code font"]);
});
});
describe("background activity settings restore", () => {
it("detects legacy interval values even when the structured setting is at its default", () => {
expect(
@@ -74,6 +74,40 @@ export function hasChangedBackgroundActivitySettings(
);
}
type TypographySettings = Pick<
UnifiedSettings,
| "fontFamilySans"
| "fontFamilyComposer"
| "fontFamilyCode"
| "fontFamilyTerminal"
| "fontSizeInterface"
| "fontSizePrompt"
| "fontSizeCode"
| "fontSizeTerminal"
>;
/** Labels the font rows whose family or size differs from the defaults. */
export function getChangedTypographySettingLabels(settings: TypographySettings): string[] {
return [
...(settings.fontFamilySans !== DEFAULT_UNIFIED_SETTINGS.fontFamilySans ||
settings.fontSizeInterface !== DEFAULT_UNIFIED_SETTINGS.fontSizeInterface
? ["Interface font"]
: []),
...(settings.fontFamilyComposer !== DEFAULT_UNIFIED_SETTINGS.fontFamilyComposer ||
settings.fontSizePrompt !== DEFAULT_UNIFIED_SETTINGS.fontSizePrompt
? ["Prompt font"]
: []),
...(settings.fontFamilyCode !== DEFAULT_UNIFIED_SETTINGS.fontFamilyCode ||
settings.fontSizeCode !== DEFAULT_UNIFIED_SETTINGS.fontSizeCode
? ["Code font"]
: []),
...(settings.fontFamilyTerminal !== DEFAULT_UNIFIED_SETTINGS.fontFamilyTerminal ||
settings.fontSizeTerminal !== DEFAULT_UNIFIED_SETTINGS.fontSizeTerminal
? ["Terminal font"]
: []),
];
}
export function resolveBackgroundActivityProfileOption(
settings: ServerSettings,
): BackgroundActivityProfile | "advanced" {
@@ -122,6 +122,7 @@ import {
backgroundActivitySharedPolicySettings,
durationToSeconds,
formatDiagnosticsDescription,
getChangedTypographySettingLabels,
normalizeIntervalSeconds,
PROVIDER_HEALTH_INTERVAL_STEP_SECONDS,
hasChangedBackgroundActivitySettings,
@@ -493,16 +494,7 @@ export function useSettingsRestore(onRestored?: () => void) {
? ["Auto-settle inactive threads"]
: []),
...(settings.wordWrap !== DEFAULT_UNIFIED_SETTINGS.wordWrap ? ["Word wrap"] : []),
...(settings.fontFamilySans !== DEFAULT_UNIFIED_SETTINGS.fontFamilySans
? ["Interface font"]
: []),
...(settings.fontFamilyComposer !== DEFAULT_UNIFIED_SETTINGS.fontFamilyComposer
? ["Prompt font"]
: []),
...(settings.fontFamilyCode !== DEFAULT_UNIFIED_SETTINGS.fontFamilyCode ? ["Code font"] : []),
...(settings.fontFamilyTerminal !== DEFAULT_UNIFIED_SETTINGS.fontFamilyTerminal
? ["Terminal font"]
: []),
...getChangedTypographySettingLabels(settings),
...(settings.diffIgnoreWhitespace !== DEFAULT_UNIFIED_SETTINGS.diffIgnoreWhitespace
? ["Diff whitespace changes"]
: []),
@@ -652,6 +644,10 @@ export function useSettingsRestore(onRestored?: () => void) {
fontFamilyComposer: DEFAULT_UNIFIED_SETTINGS.fontFamilyComposer,
fontFamilyCode: DEFAULT_UNIFIED_SETTINGS.fontFamilyCode,
fontFamilyTerminal: DEFAULT_UNIFIED_SETTINGS.fontFamilyTerminal,
fontSizeInterface: DEFAULT_UNIFIED_SETTINGS.fontSizeInterface,
fontSizePrompt: DEFAULT_UNIFIED_SETTINGS.fontSizePrompt,
fontSizeCode: DEFAULT_UNIFIED_SETTINGS.fontSizeCode,
fontSizeTerminal: DEFAULT_UNIFIED_SETTINGS.fontSizeTerminal,
});
onRestored?.();
}, [
@@ -1105,13 +1101,21 @@ function InterfaceFontRow({ preview }: { preview?: ReactNode }) {
{...searchableSetting("interface-font")}
description="Everything outside code blocks and the terminal."
defaultFamily={defaults.sans}
defaultValue={DEFAULT_UNIFIED_SETTINGS.fontFamilySans}
value={settings.fontFamilySans}
onValueChange={(fontFamilySans) => updateSettings({ fontFamilySans })}
onReset={() =>
updateSettings({
fontFamilySans: DEFAULT_UNIFIED_SETTINGS.fontFamilySans,
fontSizeInterface: DEFAULT_UNIFIED_SETTINGS.fontSizeInterface,
})
}
size={{
label: "Interface font size",
min: MIN_INTERFACE_FONT_SIZE,
max: MAX_INTERFACE_FONT_SIZE,
value: settings.fontSizeInterface,
defaultValue: DEFAULT_UNIFIED_SETTINGS.fontSizeInterface,
onChange: (fontSizeInterface) => updateSettings({ fontSizeInterface }),
}}
{...(preview !== undefined ? { preview } : {})}
@@ -1128,13 +1132,21 @@ function PromptFontRow() {
{...searchableSetting("prompt-font")}
description="Only the box you write prompts in. Mono works well here."
defaultFamily={defaults.interfaceFamily}
defaultValue={DEFAULT_UNIFIED_SETTINGS.fontFamilyComposer}
value={settings.fontFamilyComposer}
onValueChange={(fontFamilyComposer) => updateSettings({ fontFamilyComposer })}
onReset={() =>
updateSettings({
fontFamilyComposer: DEFAULT_UNIFIED_SETTINGS.fontFamilyComposer,
fontSizePrompt: DEFAULT_UNIFIED_SETTINGS.fontSizePrompt,
})
}
size={{
label: "Prompt font size",
min: MIN_PROMPT_FONT_SIZE,
max: MAX_PROMPT_FONT_SIZE,
value: settings.fontSizePrompt,
defaultValue: DEFAULT_UNIFIED_SETTINGS.fontSizePrompt,
onChange: (fontSizePrompt) => updateSettings({ fontSizePrompt }),
}}
preview={<PromptFontPreview />}
@@ -1160,14 +1172,22 @@ function CodeFontRow({
{...(title !== undefined ? { title } : {})}
description={description}
defaultFamily={defaults.code}
defaultValue={DEFAULT_UNIFIED_SETTINGS.fontFamilyCode}
value={settings.fontFamilyCode}
onValueChange={(fontFamilyCode) => updateSettings({ fontFamilyCode })}
onReset={() =>
updateSettings({
fontFamilyCode: DEFAULT_UNIFIED_SETTINGS.fontFamilyCode,
fontSizeCode: DEFAULT_UNIFIED_SETTINGS.fontSizeCode,
})
}
requireMonospace
size={{
label: "Code font size",
min: MIN_CODE_FONT_SIZE,
max: MAX_CODE_FONT_SIZE,
value: settings.fontSizeCode,
defaultValue: DEFAULT_UNIFIED_SETTINGS.fontSizeCode,
onChange: (fontSizeCode) => updateSettings({ fontSizeCode }),
}}
preview={preview ?? <CodeFontPreview />}
@@ -1184,14 +1204,22 @@ function TerminalFontRow() {
{...searchableSetting("terminal-font")}
description="Terminal output, independent from code blocks and diffs."
defaultFamily={defaults.code}
defaultValue={DEFAULT_UNIFIED_SETTINGS.fontFamilyTerminal}
value={settings.fontFamilyTerminal}
onValueChange={(fontFamilyTerminal) => updateSettings({ fontFamilyTerminal })}
onReset={() =>
updateSettings({
fontFamilyTerminal: DEFAULT_UNIFIED_SETTINGS.fontFamilyTerminal,
fontSizeTerminal: DEFAULT_UNIFIED_SETTINGS.fontSizeTerminal,
})
}
requireMonospace
size={{
label: "Terminal font size",
min: MIN_TERMINAL_FONT_SIZE,
max: MAX_TERMINAL_FONT_SIZE,
value: settings.fontSizeTerminal,
defaultValue: DEFAULT_UNIFIED_SETTINGS.fontSizeTerminal,
onChange: (fontSizeTerminal) => updateSettings({ fontSizeTerminal }),
}}
preview={
@@ -1369,9 +1397,11 @@ function FontFamilySettingsRow({
title,
description,
defaultFamily,
defaultValue,
preview,
value,
onValueChange,
onReset,
requireMonospace = false,
size,
}: {
@@ -1380,11 +1410,21 @@ function FontFamilySettingsRow({
description: string;
/** What an unset preference renders as, e.g. "Menlo". */
defaultFamily: string;
/** The persisted family value supplied by the unified settings defaults. */
defaultValue: string;
preview?: ReactNode;
value: string;
onValueChange: (value: string) => void;
onReset: () => void;
requireMonospace?: boolean;
size: { label: string; min: number; max: number; value: number; onChange: (v: number) => void };
size: {
label: string;
min: number;
max: number;
value: number;
defaultValue: number;
onChange: (v: number) => void;
};
}) {
const trimmed = value.trim();
// The fallback input edits a draft; the preference only commits once typing
@@ -1431,12 +1471,18 @@ function FontFamilySettingsRow({
// Flag an unknown name only once typing pauses, and never for an empty
// field - that is the starting state, not a rejected entry.
const draftPending = draftSettled && draftTrimmed.length > 0 && draftTrimmed !== trimmed;
const resetToDefault = () => {
if (commitTimerRef.current !== null) {
window.clearTimeout(commitTimerRef.current);
commitTimerRef.current = null;
}
setDraft(defaultValue);
setDraftSettled(true);
onReset();
};
const resetAction =
trimmed.length > 0 ? (
<SettingResetButton
label={`${title.toLowerCase()} family`}
onClick={() => onValueChange("")}
/>
value !== defaultValue || size.value !== size.defaultValue ? (
<SettingResetButton label={title.toLowerCase()} onClick={resetToDefault} />
) : null;
const fontEnumeration = useFontEnumeration();
// Everyone starts on the plain input; focusing it is the user gesture that
@@ -1,6 +1,6 @@
import type { KeyboardEvent, PointerEvent } from "react";
import { memo, useCallback, useEffect, useRef, useState } from "react";
import { isThemeColor, type ThemeColorRole } from "../../themePalette";
import { isThemeColor, themeColorToHex, type ThemeColorRole } from "../../themePalette";
import { cn } from "../../lib/utils";
import { Input } from "../ui/input";
import { Popover, PopoverPopup, PopoverTrigger } from "../ui/popover";
@@ -37,39 +37,18 @@ function clampThemeColor(value: number, min = 0, max = 1) {
}
/**
* The picker's plane and sliders operate on opaque six-digit hex, but theme
* colors may carry alpha. The suffix is preserved separately and re-attached
* on commit so adjusting hue or brightness cannot change transparency.
* The picker remains an sRGB/hex adapter over the OKLCH palette engine. Alpha
* is preserved separately and re-attached on commit so adjusting hue or
* brightness cannot change transparency.
*/
function themePickerAlphaSuffix(value: string): string {
const trimmed = value.trim().toLowerCase();
const alpha = /^#[0-9a-f]{4}$/.test(trimmed)
? trimmed.slice(4).repeat(2)
: /^#[0-9a-f]{8}$/.test(trimmed)
? trimmed.slice(7)
: "";
const normalized = themeColorToHex(value) ?? "";
const alpha = normalized.length === 9 ? normalized.slice(7) : "";
return alpha === "ff" ? "" : alpha;
}
function normalizeThemePickerColor(value: string): string {
const trimmed = value.trim();
if (/^#[0-9a-f]{3}$/i.test(trimmed)) {
return `#${trimmed
.slice(1)
.split("")
.map((character) => `${character}${character}`)
.join("")}`;
}
if (/^#[0-9a-f]{4}$/i.test(trimmed)) {
return `#${trimmed
.slice(1, 4)
.split("")
.map((character) => `${character}${character}`)
.join("")}`;
}
if (/^#[0-9a-f]{6}$/i.test(trimmed)) return trimmed;
if (/^#[0-9a-f]{8}$/i.test(trimmed)) return trimmed.slice(0, 7);
return "#000000";
return (themeColorToHex(value) ?? "#000000").slice(0, 7);
}
function themeHexToHsv(hex: string): ThemeColorHsv {
@@ -505,6 +484,9 @@ export const ThemeColorField = memo(function ThemeColorField({
const label = customLabel ?? getThemeRoleLabel(role);
const isColorValue = isThemeColor(value);
const swatchValue = isColorValue ? value : "#000000";
const editorValue = value.trim().toLowerCase().startsWith("oklch(")
? (themeColorToHex(value) ?? value)
: value;
return (
<div
@@ -542,7 +524,7 @@ export const ThemeColorField = memo(function ThemeColorField({
onPointerDown={() => onSelect?.(role)}
size="sm"
unstyled
value={value}
value={editorValue}
/>
</div>
</div>
@@ -165,7 +165,6 @@ export function ThemeEditorPanel({
const isEditing = editingTheme !== null;
const [name, setName] = useState("");
const [activeAppearance, setActiveAppearance] = useState<ThemeAppearance>(initialAppearance);
const [sidebarArtwork, setSidebarArtwork] = useState(false);
const [isAdvanced, setIsAdvanced] = useState(false);
const [colorsByAppearance, setColorsByAppearance] = useState<ThemeEditorColorsByAppearance>(() =>
getThemeEditorColorsByAppearance(),
@@ -179,7 +178,6 @@ export function ThemeEditorPanel({
const [isInspecting, setIsInspecting] = useState(false);
const [selectedRole, setSelectedRole] = useState<ThemeColorRole | null>(null);
const [usageCount, setUsageCount] = useState<number | null>(null);
const previousMergeTargetIdRef = useRef<string | null>(null);
// Null parks the panel at its default corner; a value is a dragged spot,
// kept clamped so the header can always be grabbed again.
const [position, setPosition] = useState<{ x: number; y: number } | null>(null);
@@ -230,7 +228,6 @@ export function ThemeEditorPanel({
};
window.addEventListener("resize", clamp);
return () => window.removeEventListener("resize", clamp);
// oxlint-disable-next-line exhaustive-deps -- clampPosition reads live layout only.
}, [isMinimized, open]);
// The draft only reaches the live app once this open has been seeded;
@@ -261,9 +258,6 @@ export function ThemeEditorPanel({
setName(editingTheme?.label ?? seedName ?? "");
setActiveAppearance(nextAppearance);
// Artwork is opt-in for new themes, including duplicates. Editing keeps
// the theme's existing choice.
setSidebarArtwork(editingTheme?.sidebarArtwork === true);
// Themes saved by the guided editor carry the managed flag; anything
// else (imports, hand-edited files, older saves) opens in advanced mode
// so guided regeneration cannot silently discard hand-tuned colors. A
@@ -320,18 +314,6 @@ export function ThemeEditorPanel({
// an explanation instead.
const mergeTargetId = mergeTarget?.id ?? null;
const takenAppearancesKey = takenAppearances.join(",");
useEffect(() => {
if (previousMergeTargetIdRef.current === mergeTargetId) return;
previousMergeTargetIdRef.current = mergeTargetId;
// A matching name makes that existing theme the surviving merge target.
// Seed theme-level options from it so adding a palette or renaming onto it
// does not silently reset them. Leaving the merge restores the edited
// theme's option (or the off-by-default choice for a new theme).
setSidebarArtwork(
mergeTarget ? mergeTarget.sidebarArtwork === true : editingTheme?.sidebarArtwork === true,
);
}, [editingTheme, mergeTarget, mergeTargetId]);
useEffect(() => {
if (isEditing || mergeTargetId === null) return;
const taken = takenAppearancesKey.split(",").filter(Boolean) as ThemeAppearance[];
@@ -347,8 +329,8 @@ export function ThemeEditorPanel({
// comes back when the editor closes, including on cancel.
useEffect(() => {
if (!open || !isDraftSeeded) return;
applyThemeColorPreview(colorsByAppearance[activeAppearance], activeAppearance, sidebarArtwork);
}, [activeAppearance, colorsByAppearance, isDraftSeeded, open, sidebarArtwork]);
applyThemeColorPreview(colorsByAppearance[activeAppearance], activeAppearance);
}, [activeAppearance, colorsByAppearance, isDraftSeeded, open]);
useEffect(() => {
if (!open) return;
@@ -628,7 +610,7 @@ export function ThemeEditorPanel({
[activeAppearance, editingTheme, selectedRole],
);
const handleSubmit = useCallback(() => {
const handleSubmit = () => {
if (!name.trim()) {
setError("Name your theme first.");
return;
@@ -663,8 +645,8 @@ export function ThemeEditorPanel({
return;
}
mergedAppearance = editedModes[0] ?? null;
savedTheme = updateCustomTheme(
parseThemeFile({
savedTheme = updateCustomTheme({
...parseThemeFile({
version: THEME_FILE_VERSION,
id: mergeTarget.id,
name: mergeTarget.label,
@@ -674,10 +656,10 @@ export function ThemeEditorPanel({
...mergeTarget.variants,
...Object.fromEntries(editedModes.map((mode) => [mode, colorsForSave[mode]])),
},
...(sidebarArtwork ? { sidebarArtwork: true } : {}),
...(mergeTarget.managed === true && !isAdvanced ? { managed: true } : {}),
}),
);
...(mergeTarget.collection ? { collection: mergeTarget.collection } : {}),
});
retiredTheme = editingTheme;
try {
removeCustomTheme(editingTheme.id);
@@ -695,8 +677,8 @@ export function ThemeEditorPanel({
} else if (editingTheme) {
const baseAppearance = editingTheme.appearance;
const variantAppearance = baseAppearance === "light" ? "dark" : "light";
savedTheme = updateCustomTheme(
parseThemeFile({
savedTheme = updateCustomTheme({
...parseThemeFile({
version: THEME_FILE_VERSION,
id: editingTheme.id,
name,
@@ -705,10 +687,10 @@ export function ThemeEditorPanel({
...(getThemeModes(editingTheme).length > 1
? { variants: { [variantAppearance]: colorsForSave[variantAppearance] } }
: {}),
...(sidebarArtwork ? { sidebarArtwork: true } : {}),
...(isAdvanced ? {} : { managed: true }),
}),
);
...(editingTheme.collection ? { collection: editingTheme.collection } : {}),
});
} else if (mergeTarget) {
if (takenAppearances.includes(activeAppearance)) {
setError(
@@ -721,8 +703,8 @@ export function ThemeEditorPanel({
// survives when every palette in the theme came from the guided
// editor.
mergedAppearance = activeAppearance;
savedTheme = updateCustomTheme(
parseThemeFile({
savedTheme = updateCustomTheme({
...parseThemeFile({
version: THEME_FILE_VERSION,
id: mergeTarget.id,
name: mergeTarget.label,
@@ -732,10 +714,10 @@ export function ThemeEditorPanel({
...mergeTarget.variants,
[activeAppearance]: colorsForSave[activeAppearance],
},
...(sidebarArtwork ? { sidebarArtwork: true } : {}),
...(mergeTarget.managed === true && !isAdvanced ? { managed: true } : {}),
}),
);
...(mergeTarget.collection ? { collection: mergeTarget.collection } : {}),
});
} else {
savedTheme = installCustomTheme(
parseThemeFile({
@@ -743,7 +725,6 @@ export function ThemeEditorPanel({
name,
appearance: activeAppearance,
colors: colorsForSave[activeAppearance],
...(sidebarArtwork ? { sidebarArtwork: true } : {}),
...(isAdvanced ? {} : { managed: true }),
}),
);
@@ -784,20 +765,7 @@ export function ThemeEditorPanel({
: "Could not create the theme.",
);
}
}, [
activeAppearance,
colorsByAppearance,
editingTheme,
isAdvanced,
isEditing,
mergeTarget,
name,
onOpenChange,
onSaved,
sidebarArtwork,
simpleColorsDirtyByAppearance,
takenAppearances,
]);
};
const renderNameField = () => (
<label className="grid grid-cols-[minmax(0,1fr)_minmax(0,2fr)] items-center gap-3">
@@ -854,20 +822,6 @@ export function ThemeEditorPanel({
</div>
);
const renderSidebarArtworkToggle = () => (
<label className="grid cursor-pointer grid-cols-[minmax(0,1fr)_minmax(0,2fr)] items-center gap-3">
<span className="text-sm font-medium">Sidebar artwork</span>
<span className="flex items-center justify-between gap-3 text-xs text-muted-foreground">
<span>Show T3 Code environment artwork</span>
<Switch
aria-label="Allow sidebar artwork with this theme"
checked={sidebarArtwork}
onCheckedChange={(checked) => setSidebarArtwork(Boolean(checked))}
/>
</span>
</label>
);
const renderColorsHeader = () => (
<div className="grid grid-cols-[minmax(0,1fr)_minmax(0,2fr)] items-start gap-3">
<div>
@@ -1124,7 +1078,6 @@ export function ThemeEditorPanel({
</p>
) : null}
{renderAppearanceButtons()}
{renderSidebarArtworkToggle()}
<div className="space-y-3">
{renderColorsHeader()}
{renderColorFields()}
@@ -28,6 +28,7 @@ import {
DialogPopup,
DialogTitle,
} from "../ui/dialog";
import { ThemeSearchSection } from "./ThemeSearchSection";
/**
* A full theme export is a few KB, so anything past this is not a theme file.
@@ -360,9 +361,16 @@ export function ThemeImportDialog({
: null;
for (const theme of conflicts) {
try {
const existingTheme =
mode === "update"
? getCustomThemes().find((candidate) => candidate.id === theme.id)
: undefined;
const themeToUpdate = existingTheme?.collection
? { ...theme, collection: existingTheme.collection }
: theme;
resolved.push(
mode === "update"
? updateCustomTheme(theme)
? updateCustomTheme(themeToUpdate)
: installCustomTheme(versionedCopy(theme, preferredName)),
);
} catch (cause) {
@@ -426,7 +434,23 @@ export function ThemeImportDialog({
<DialogHeader>
<DialogTitle>Add a theme</DialogTitle>
</DialogHeader>
<DialogPanel className="space-y-4">
<DialogPanel className="space-y-5">
<ThemeSearchSection
onInstalled={(themes, context) => {
onImportedMany(themes, context);
onOpenChange(false);
}}
open={open}
/>
<div className="flex items-center gap-3" aria-hidden>
<div className="h-px flex-1 bg-border" />
<span className="text-muted-foreground text-[11px] uppercase tracking-wider">
or import a file
</span>
<div className="h-px flex-1 bg-border" />
</div>
{(() => {
const dropHandlers = {
onDragEnter: (event: DragEvent<HTMLDivElement>) => {
@@ -0,0 +1,389 @@
import {
ExternalLinkIcon,
PaletteIcon,
PlusIcon,
RefreshCwIcon,
SearchIcon,
ShieldCheckIcon,
} from "lucide-react";
import type { FormEvent } from "react";
import { useCallback, useEffect, useRef, useState } from "react";
import {
importOpenVsxThemeExtension,
searchOpenVsxThemes,
type OpenVsxThemeExtension,
type OpenVsxThemeSort,
} from "../../openVsxThemes";
import {
getCustomThemes,
getStoredCustomThemeCollection,
replaceCustomThemeCollection,
type ThemeDefinition,
} from "../../themePalette";
import {
AlertDialog,
AlertDialogClose,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogPopup,
AlertDialogTitle,
} from "../ui/alert-dialog";
import { Button } from "../ui/button";
import { Input } from "../ui/input";
import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "../ui/select";
import { Spinner } from "../ui/spinner";
const DOWNLOAD_FORMAT = new Intl.NumberFormat(undefined, {
notation: "compact",
maximumFractionDigits: 1,
});
const SUGGESTED_SEARCHES = ["Dracula", "Catppuccin", "Nord", "Tokyo Night"];
const SORT_OPTIONS: ReadonlyArray<{ value: OpenVsxThemeSort; label: string }> = [
{ value: "downloadCount", label: "Most downloaded" },
{ value: "rating", label: "Best rated" },
{ value: "timestamp", label: "Newest" },
{ value: "relevance", label: "Most relevant" },
];
function ThemeExtensionIcon({ extension }: { extension: OpenVsxThemeExtension }) {
const [failed, setFailed] = useState(false);
return (
<div className="flex size-10 shrink-0 items-center justify-center overflow-hidden rounded-lg bg-muted text-muted-foreground">
{extension.iconUrl && !failed ? (
<img
alt=""
className="size-full object-cover"
loading="lazy"
referrerPolicy="no-referrer"
src={extension.iconUrl}
onError={() => setFailed(true)}
/>
) : (
<PaletteIcon className="size-4" />
)}
</div>
);
}
export function ThemeSearchSection({
open,
onInstalled,
}: {
open: boolean;
onInstalled: (themes: ReadonlyArray<ThemeDefinition>, context: { updated: boolean }) => void;
}) {
const [query, setQuery] = useState("");
const [sortBy, setSortBy] = useState<OpenVsxThemeSort>("downloadCount");
const [results, setResults] = useState<ReadonlyArray<OpenVsxThemeExtension> | null>(null);
const [error, setError] = useState<string | null>(null);
const [isSearching, setIsSearching] = useState(false);
const [installingId, setInstallingId] = useState<string | null>(null);
const [pendingUpdate, setPendingUpdate] = useState<OpenVsxThemeExtension | null>(null);
const requestRef = useRef<AbortController | null>(null);
useEffect(() => {
requestRef.current?.abort();
requestRef.current = null;
if (open) {
setQuery("");
setSortBy("downloadCount");
setResults(null);
setError(null);
setIsSearching(false);
setInstallingId(null);
setPendingUpdate(null);
}
return () => {
requestRef.current?.abort();
requestRef.current = null;
};
}, [open]);
const runSearch = useCallback(
async (searchText: string, nextSort = sortBy) => {
const trimmed = searchText.trim();
if (!trimmed) return;
requestRef.current?.abort();
const controller = new AbortController();
requestRef.current = controller;
setQuery(trimmed);
setIsSearching(true);
setError(null);
setResults(null);
try {
const nextResults = await searchOpenVsxThemes(trimmed, {
signal: controller.signal,
sortBy: nextSort,
});
if (!controller.signal.aborted) setResults(nextResults);
} catch (cause) {
if (!controller.signal.aborted) {
setError(cause instanceof Error ? cause.message : "Open VSX search failed.");
}
}
if (requestRef.current === controller) {
requestRef.current = null;
setIsSearching(false);
}
},
[sortBy],
);
const handleSearch = useCallback(
(event: FormEvent<HTMLFormElement>) => {
event.preventDefault();
void runSearch(query);
},
[query, runSearch],
);
const handleSortChange = useCallback(
(value: OpenVsxThemeSort | null) => {
const nextSort = SORT_OPTIONS.find((option) => option.value === value)?.value;
if (!nextSort) return;
setSortBy(nextSort);
if ((results !== null || isSearching) && query.trim()) {
void runSearch(query, nextSort);
}
},
[isSearching, query, results, runSearch],
);
const handleInstall = useCallback(
async (extension: OpenVsxThemeExtension, allowUpdate: boolean) => {
setError(null);
let installedCollection: ReadonlyArray<ThemeDefinition>;
try {
installedCollection = getStoredCustomThemeCollection(extension.collectionId);
} catch (cause) {
setError(cause instanceof Error ? cause.message : "Installed themes could not be read.");
return;
}
const updated = installedCollection.length > 0;
if (updated && !allowUpdate) {
setPendingUpdate(extension);
return;
}
requestRef.current?.abort();
const controller = new AbortController();
requestRef.current = controller;
setInstallingId(extension.id);
try {
const themes = await importOpenVsxThemeExtension(extension, controller.signal);
if (!controller.signal.aborted) {
const imported = replaceCustomThemeCollection(extension.collectionId, themes, {
expectedCollection: installedCollection,
});
onInstalled(imported, { updated });
}
} catch (cause) {
if (!controller.signal.aborted) {
setError(cause instanceof Error ? cause.message : "That theme could not be added.");
}
}
if (requestRef.current === controller) {
requestRef.current = null;
setInstallingId(null);
}
},
[onInstalled],
);
return (
<section className="space-y-3" aria-labelledby="theme-search-heading">
<div>
<h3 className="text-sm font-medium" id="theme-search-heading">
Search community themes
</h3>
<p className="mt-0.5 text-muted-foreground text-xs">
Find open-source themes from Open VSX.
</p>
</div>
<form className="relative flex gap-2" onSubmit={handleSearch}>
<SearchIcon className="pointer-events-none absolute left-3 top-1/2 z-10 size-4 -translate-y-1/2 text-muted-foreground" />
<Input
aria-label="Search Open VSX themes"
className="rounded-xl [&_input]:pl-9"
autoFocus
onChange={(event) => setQuery(event.currentTarget.value)}
placeholder="try dracula, nord, catppuccin..."
size="lg"
type="search"
value={query}
/>
<Button
disabled={!query.trim() || isSearching || installingId !== null}
type="submit"
variant="outline"
>
{isSearching ? <Spinner /> : <SearchIcon />}
Search
</Button>
</form>
{!isSearching ? (
<div className="flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between">
<div className="flex min-w-0 flex-wrap items-center gap-1.5">
<p className="text-muted-foreground text-xs">Popular</p>
{SUGGESTED_SEARCHES.map((suggestion) => (
<Button
key={suggestion}
size="xs"
variant="ghost"
onClick={() => void runSearch(suggestion)}
>
{suggestion}
</Button>
))}
</div>
{results && results.length > 0 ? (
<div className="flex shrink-0 items-center justify-end gap-2">
<p className="text-muted-foreground text-xs">Sort</p>
<Select
disabled={installingId !== null}
value={sortBy}
onValueChange={handleSortChange}
>
<SelectTrigger size="sm" className="w-40" aria-label="Sort themes">
<SelectValue>
{SORT_OPTIONS.find((option) => option.value === sortBy)?.label}
</SelectValue>
</SelectTrigger>
<SelectPopup align="end" alignItemWithTrigger={false}>
{SORT_OPTIONS.map((option) => (
<SelectItem key={option.value} hideIndicator value={option.value}>
{option.label}
</SelectItem>
))}
</SelectPopup>
</Select>
</div>
) : null}
</div>
) : null}
<div className="sr-only" role="status">
{isSearching
? "Finding themes..."
: results
? `${results.length} supported ${results.length === 1 ? "theme" : "themes"} found.`
: ""}
</div>
{error ? (
<div
aria-live="polite"
className="rounded-xl border border-destructive/30 bg-destructive/5 px-3 py-2 text-destructive text-sm"
>
{error}
</div>
) : null}
{isSearching ? (
<div className="flex min-h-20 items-center justify-center gap-2 text-muted-foreground text-sm">
<Spinner /> Finding themes...
</div>
) : null}
{results ? (
results.length === 0 ? (
<div className="flex min-h-40 flex-col items-center justify-center rounded-2xl border border-dashed text-center">
<p className="text-sm font-medium">No supported open-source themes found</p>
<p className="mt-1 text-muted-foreground text-xs">Try a broader search.</p>
</div>
) : (
<div className="grid gap-2 sm:grid-cols-2">
{results.map((extension) => {
const isInstalling = installingId === extension.id;
const isInstalled = getCustomThemes().some(
(theme) => theme.collection?.id === extension.collectionId,
);
const action = isInstalled ? "Update" : "Add";
const progressAction = isInstalled ? "Updating" : "Adding";
return (
<article
className="group flex min-w-0 flex-col gap-3 rounded-xl border border-border/70 bg-card/60 p-3 transition-colors hover:bg-accent/20"
key={extension.id}
>
<div className="flex min-w-0 gap-3">
<ThemeExtensionIcon key={extension.iconUrl} extension={extension} />
<div className="min-w-0 flex-1">
<h4 className="truncate text-sm font-medium">{extension.name}</h4>
<p className="truncate text-muted-foreground text-xs">
{extension.publisher} · {DOWNLOAD_FORMAT.format(extension.downloadCount)}{" "}
downloads
</p>
</div>
</div>
<p className="line-clamp-2 min-h-8 text-muted-foreground text-xs leading-4">
{extension.description || "A community color theme for your editor."}
</p>
<div className="mt-auto flex items-center justify-between gap-2">
<div className="flex min-w-0 items-center gap-2">
<span className="inline-flex items-center gap-1 text-muted-foreground text-[11px]">
<ShieldCheckIcon className="size-3" /> {extension.license}
</span>
{extension.sourceUrl ? (
<a
aria-label={`View source for ${extension.name}`}
className="inline-flex items-center gap-1 text-muted-foreground text-[11px] hover:text-foreground"
href={extension.sourceUrl}
rel="noreferrer"
target="_blank"
>
Source <ExternalLinkIcon className="size-3" />
</a>
) : null}
</div>
<Button
aria-label={`${isInstalling ? progressAction : action} ${extension.name}`}
disabled={installingId !== null}
size="xs"
variant="outline"
onClick={() => void handleInstall(extension, false)}
>
{isInstalling ? <Spinner /> : isInstalled ? <RefreshCwIcon /> : <PlusIcon />}
{isInstalling ? `${progressAction}...` : action}
</Button>
</div>
</article>
);
})}
</div>
)
) : null}
<AlertDialog
open={pendingUpdate !== null}
onOpenChange={(nextOpen) => {
if (!nextOpen) setPendingUpdate(null);
}}
>
<AlertDialogPopup>
<AlertDialogHeader>
<AlertDialogTitle>Update “{pendingUpdate?.name}”?</AlertDialogTitle>
<AlertDialogDescription>
This replaces its installed variants, including any local edits. Variants no longer in
the extension will be removed.
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogClose render={<Button variant="outline" />}>Cancel</AlertDialogClose>
<Button
onClick={() => {
const extension = pendingUpdate;
setPendingUpdate(null);
if (extension) void handleInstall(extension, true);
}}
>
Update theme
</Button>
</AlertDialogFooter>
</AlertDialogPopup>
</AlertDialog>
</section>
);
}
@@ -1,17 +1,20 @@
import {
CheckIcon,
CopyIcon,
DownloadIcon,
MoonIcon,
PenLineIcon,
PlusIcon,
SunIcon,
Trash2Icon,
UploadIcon,
} from "lucide-react";
import { useCallback, useEffect, useRef, useState } from "react";
import { useCallback, useEffect, useState, type ReactElement } from "react";
import { cn } from "../../lib/utils";
import {
getThemeDefinition,
getThemeModes,
removeCustomTheme,
removeCustomThemes,
serializeThemeFile,
type ThemeAppearance,
type ThemeDefinition,
@@ -41,6 +44,7 @@ import {
getThemeCardDefinition,
previewColorsOf,
ThemePreviewCircles,
ThemePreviewCircle,
type ThemeCardDefinition,
type ThemeMode,
} from "./ThemePreviewCircles";
@@ -54,6 +58,21 @@ const MAINTAINER_THEMES: ReadonlyArray<ThemeDefinition> = [
IRIS_THEME,
];
function collectionVariantLabels(themes: ReadonlyArray<ThemeDefinition>): ReadonlyArray<string> {
if (themes.length === 0) return [];
const words = themes.map((theme) => theme.label.trim().split(/\s+/));
const firstWords = words[0]!;
const sharedWordCount = firstWords.findIndex((word, index) =>
words.some((labelWords) => labelWords[index]?.toLocaleLowerCase() !== word.toLocaleLowerCase()),
);
const prefixLength = sharedWordCount === -1 ? firstWords.length - 1 : sharedWordCount;
return themes.map((theme, index) => {
const shortLabel = words[index]?.slice(Math.max(0, prefixLength)).join(" ").trim();
return shortLabel || theme.label;
});
}
function downloadThemeFile(filename: string, contents: string): void {
const url = URL.createObjectURL(new Blob([contents], { type: "application/json" }));
const anchor = document.createElement("a");
@@ -65,6 +84,15 @@ function downloadThemeFile(filename: string, contents: string): void {
setTimeout(() => URL.revokeObjectURL(url), 30_000);
}
function ThemeVariantTooltip({ label, children }: { label: string; children: ReactElement }) {
return (
<Tooltip>
<TooltipTrigger render={children} />
<TooltipPopup>{label}</TooltipPopup>
</Tooltip>
);
}
function ThemeLibraryCard({
theme,
isActive,
@@ -75,6 +103,7 @@ function ThemeLibraryCard({
onDuplicate,
onDownload,
onRemove,
variantNavigation,
}: {
theme: ThemeCardDefinition;
isActive: boolean;
@@ -85,10 +114,33 @@ function ThemeLibraryCard({
onDuplicate?: () => void;
onDownload?: () => void;
onRemove?: () => void;
variantNavigation?: {
collectionLabel: string;
options: ReadonlyArray<{
themeIndex: number;
label: string;
activeModes: ReadonlyArray<ThemeMode>;
preview: ThemeCardDefinition["previews"][number];
}>;
onSelectAndUse: (themeIndex: number, mode: ThemeAppearance) => void;
};
}) {
// A one-appearance theme can only take its own side of the mix, so the card
// tooltip promises exactly what clicking it does.
const cardModes = theme.previews.map((preview) => preview.mode);
const [radialModeOpen, setRadialModeOpen] = useState<ThemeAppearance | null>(null);
const radialModeGroups = (["light", "dark"] as const).map((mode) => {
const options =
variantNavigation?.options.flatMap((option) => {
const preview = option.preview;
return preview.mode === mode ? [{ option, preview }] : [];
}) ?? [];
return {
mode,
options,
selected: options.find(({ option }) => option.activeModes.includes(mode)) ?? options[0],
};
});
return (
// The card surface stays a plain div (buttons cannot nest inside a button
// role); the title button and mode circles carry the accessible actions,
@@ -105,17 +157,147 @@ function ThemeLibraryCard({
onClick={onUse}
style={isActive ? { boxShadow: "inset 0 0 0 1px var(--ring)" } : undefined}
>
<ThemePreviewCircles
label={theme.label}
activeModes={activeModes}
onSelectMode={onUseMode}
previews={theme.previews}
/>
<div className="relative">
{variantNavigation ? (
<div
aria-label="Light and dark theme variants"
className="relative h-20"
role="group"
onBlurCapture={(event) => {
const nextTarget = event.relatedTarget;
if (
!(nextTarget instanceof Node) ||
!event.currentTarget.contains(nextTarget)
) {
setRadialModeOpen(null);
}
}}
onKeyDown={(event) => {
if (event.key === "Escape") setRadialModeOpen(null);
}}
onMouseLeave={() => setRadialModeOpen(null)}
>
{radialModeGroups.map(({ mode, options, selected }) => {
if (!selected) return null;
const rootOffsetX = mode === "light" ? -52 : 52;
const isOpen = radialModeOpen === mode;
const isActive = selected.option.activeModes.includes(mode);
const modeLabel = mode === "light" ? "Light" : "Dark";
return (
<div className="contents" key={mode}>
<ThemeVariantTooltip label={`${modeLabel}: ${selected.option.label}`}>
<button
aria-label={
options.length > 1
? `Choose ${mode} variant, ${options.length} options, currently ${selected.option.label}`
: `Use ${mode} variant, currently ${selected.option.label}`
}
aria-pressed={isActive}
className="absolute left-1/2 top-2 z-20 flex size-14 items-center justify-center rounded-full outline-none focus-visible:ring-2 focus-visible:ring-ring"
style={{
transform: `translateX(calc(-50% + ${rootOffsetX}px))`,
}}
type="button"
onClick={(event) => {
event.stopPropagation();
variantNavigation.onSelectAndUse(selected.option.themeIndex, mode);
}}
onFocus={() => setRadialModeOpen(mode)}
onMouseEnter={() => setRadialModeOpen(mode)}
>
<ThemePreviewCircle
colors={selected.preview.colors}
mode={selected.preview.mode}
/>
{isActive ? (
<span
aria-hidden
className="pointer-events-none absolute inset-0 rounded-full ring-2 ring-ring"
/>
) : null}
{isActive ? (
<span className="pointer-events-none absolute -bottom-0.5 -right-0.5 flex size-4 items-center justify-center rounded-full border border-border/70 bg-background text-foreground shadow-sm">
{mode === "light" ? (
<SunIcon className="size-2.5" />
) : (
<MoonIcon className="size-2.5" />
)}
</span>
) : null}
</button>
</ThemeVariantTooltip>
<span
className="pointer-events-none absolute bottom-0 left-1/2 inline-flex max-w-24 -translate-x-1/2 items-center gap-1 text-[11px] font-medium text-foreground"
style={{ marginLeft: rootOffsetX }}
>
<span className="truncate">{selected.option.label}</span>
{options.length > 1 ? (
<span className="shrink-0 rounded-full bg-muted px-1 text-[9px] text-muted-foreground">
+{options.length - 1}
</span>
) : null}
</span>
{options.length > 1
? options.map(({ option, preview }, optionIndex) => {
const progress = optionIndex / (options.length - 1) - 0.5;
const childOffsetX = rootOffsetX + progress * 68;
const childOffsetY = Math.abs(progress) * 10;
const optionIsActive = option.activeModes.includes(mode);
return (
<ThemeVariantTooltip
key={option.label}
label={`Use ${option.label} for ${mode} mode`}
>
<button
aria-label={`Use ${option.label} for ${mode} mode${optionIsActive ? ", currently active" : ""}`}
aria-pressed={optionIsActive}
className={cn(
"absolute left-1/2 top-1 z-30 flex size-7 items-center justify-center rounded-full bg-background shadow-sm outline-none transition-[transform,opacity] duration-200 ease-out motion-reduce:transition-none focus-visible:ring-2 focus-visible:ring-ring",
optionIsActive ? "ring-2 ring-ring" : "ring-1 ring-border/70",
)}
style={{
opacity: isOpen ? 1 : 0,
pointerEvents: isOpen ? "auto" : "none",
transform: `translate(calc(-50% + ${isOpen ? childOffsetX : rootOffsetX}px), ${isOpen ? childOffsetY : 28}px) scale(${isOpen ? 1 : 0.55})`,
transitionDelay: isOpen ? `${optionIndex * 35}ms` : "0ms",
}}
type="button"
onClick={(event) => {
event.stopPropagation();
variantNavigation.onSelectAndUse(option.themeIndex, mode);
}}
onFocus={() => setRadialModeOpen(mode)}
onMouseEnter={() => setRadialModeOpen(mode)}
>
<span className="pointer-events-none scale-[0.43]">
<ThemePreviewCircle
colors={preview.colors}
mode={preview.mode}
/>
</span>
</button>
</ThemeVariantTooltip>
);
})
: null}
</div>
);
})}
</div>
) : (
<ThemePreviewCircles
label={theme.label}
activeModes={activeModes}
onSelectMode={onUseMode}
previews={theme.previews}
/>
)}
</div>
<div className="flex items-center gap-2 px-3 pb-3 pt-2">
<div className="min-w-0 flex-1">
<div className="flex items-center gap-1.5">
<button
aria-label={`Use ${theme.label} theme${isActive ? ", currently active" : ""}`}
aria-label={`Use ${variantNavigation ? `${variantNavigation.collectionLabel}, ${theme.label} variant` : `${theme.label} theme`}${isActive ? ", currently active" : ""}`}
aria-pressed={isActive}
className="min-w-0 cursor-pointer truncate rounded-sm text-left text-sm font-medium text-foreground outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-card"
type="button"
@@ -124,7 +306,7 @@ function ThemeLibraryCard({
onUse();
}}
>
{theme.label}
{variantNavigation?.collectionLabel ?? theme.label}
</button>
</div>
</div>
@@ -195,7 +377,11 @@ function ThemeLibraryCard({
<TooltipTrigger
render={
<Button
aria-label={`Remove ${theme.label}`}
aria-label={
variantNavigation
? `Remove themes from ${variantNavigation.collectionLabel}`
: `Remove ${theme.label}`
}
size="icon-xs"
variant="ghost"
className="text-muted-foreground hover:text-destructive"
@@ -208,7 +394,9 @@ function ThemeLibraryCard({
</Button>
}
/>
<TooltipPopup>Remove theme</TooltipPopup>
<TooltipPopup>
{variantNavigation ? "Remove themes" : "Remove theme"}
</TooltipPopup>
</Tooltip>
) : null}
</div>
@@ -218,12 +406,97 @@ function ThemeLibraryCard({
}
/>
<TooltipPopup>
{cardModes.length > 1 ? "Use for both light and dark" : `Use for ${cardModes[0]} mode only`}
{variantNavigation
? "Use the first variants for light and dark"
: cardModes.length > 1
? "Use for both light and dark"
: `Use for ${cardModes[0]} mode only`}
</TooltipPopup>
</Tooltip>
);
}
function CustomThemeCollectionCard({
themes,
activeModesFor,
onUse,
onUseMode,
onDuplicate,
onEdit,
onDownload,
onRemove,
}: {
themes: ReadonlyArray<ThemeDefinition>;
activeModesFor: (themeId: string) => ReadonlyArray<ThemeMode>;
onUse: (theme: ThemeDefinition) => void;
onUseMode: (theme: ThemeDefinition, mode: ThemeMode) => void;
onDuplicate: (theme: ThemeDefinition) => void;
onEdit: (theme: ThemeDefinition) => void;
onDownload: (theme: ThemeDefinition) => void;
onRemove: (theme: ThemeDefinition) => void;
}) {
const [variantIndex, setVariantIndex] = useState(() => {
const activeIndex = themes.findIndex((theme) => activeModesFor(theme.id).length > 0);
return activeIndex < 0 ? 0 : activeIndex;
});
const safeIndex = Math.min(variantIndex, themes.length - 1);
const theme = themes[safeIndex];
useEffect(() => {
if (variantIndex !== safeIndex) setVariantIndex(safeIndex);
}, [safeIndex, variantIndex]);
if (!theme) return null;
const collectionLabel = theme.collection?.label ?? theme.label;
const variantLabels = collectionVariantLabels(themes);
const defaultLightTheme = themes.find((candidate) => getThemeModes(candidate).includes("light"));
const defaultDarkTheme = themes.find((candidate) => getThemeModes(candidate).includes("dark"));
const selectCollectionDefaults = () => {
if (themes.length === 1) {
onUse(theme);
return;
}
if (defaultLightTheme) onUseMode(defaultLightTheme, "light");
if (defaultDarkTheme) onUseMode(defaultDarkTheme, "dark");
setVariantIndex(0);
};
return (
<ThemeLibraryCard
activeModes={activeModesFor(theme.id)}
isActive={false}
onDownload={() => onDownload(theme)}
onDuplicate={() => onDuplicate(theme)}
onEdit={() => onEdit(theme)}
onRemove={() => onRemove(theme)}
onUse={selectCollectionDefaults}
onUseMode={(mode) => onUseMode(theme, mode)}
theme={getThemeCardDefinition(theme)}
{...(themes.length > 1
? {
variantNavigation: {
collectionLabel,
options: themes.flatMap((variant, themeIndex) =>
getThemeCardDefinition(variant).previews.map((preview) => ({
themeIndex,
label: variantLabels[themeIndex] ?? variant.label,
activeModes: activeModesFor(variant.id),
preview,
})),
),
onSelectAndUse: (themeIndex, mode) => {
const selectedTheme = themes[themeIndex];
if (!selectedTheme) return;
setVariantIndex(themeIndex);
onUseMode(selectedTheme, mode);
},
},
}
: {})}
/>
);
}
export function ThemeLibrary({
theme,
setTheme,
@@ -250,14 +523,20 @@ export function ThemeLibrary({
setThemeHalf: (appearance: ThemeAppearance, themeId: string | null) => boolean;
}) {
const openThemeEditor = useThemeEditorStore((store) => store.openThemeEditor);
const [themeToRemove, setThemeToRemove] = useState<ThemeDefinition | null>(null);
// Keep the last removal target so the dialog title stays populated while the
// close animation plays after confirming.
const lastThemeToRemoveRef = useRef<ThemeDefinition | null>(null);
useEffect(() => {
if (themeToRemove) lastThemeToRemoveRef.current = themeToRemove;
}, [themeToRemove]);
const removeDialogTheme = themeToRemove ?? lastThemeToRemoveRef.current;
const [themeRemovalTarget, setThemeRemovalTarget] = useState<{
theme: ThemeDefinition;
collectionThemes: ReadonlyArray<ThemeDefinition>;
} | null>(null);
// Keep the target after closing so the dialog text remains populated during
// its exit animation. The next trash action replaces it before reopening.
const [isThemeRemovalOpen, setIsThemeRemovalOpen] = useState(false);
const [themeIdsToRemove, setThemeIdsToRemove] = useState<ReadonlyArray<string>>([]);
const themeIdsToRemoveSet = new Set(themeIdsToRemove);
const removeDialogTheme = themeRemovalTarget?.theme;
const removeDialogCollectionThemes = themeRemovalTarget?.collectionThemes ?? [];
const canRemoveCollection = removeDialogCollectionThemes.length > 1;
const removeDialogCollectionLabel =
removeDialogTheme?.collection?.label ?? removeDialogTheme?.label;
const notifyThemeSaveFailure = useCallback(() => {
toastManager.add(
@@ -288,37 +567,43 @@ export function ThemeLibrary({
[notifyThemeSaveFailure, setTheme],
);
const handleRemoveTheme = useCallback((customTheme: ThemeDefinition) => {
setThemeToRemove(customTheme);
}, []);
const handleRemoveTheme = useCallback(
(customTheme: ThemeDefinition, collectionThemes: ReadonlyArray<ThemeDefinition>) => {
setThemeRemovalTarget({ theme: customTheme, collectionThemes });
setThemeIdsToRemove(collectionThemes.length > 1 ? [] : [customTheme.id]);
setIsThemeRemovalOpen(true);
},
[],
);
const handleConfirmRemoveTheme = useCallback(() => {
if (!themeToRemove) return;
const removesBase = getThemeDefinition(theme)?.id === themeToRemove.id;
// Keep the theme installed if we cannot move the selection off it; the
// dialog stays open so the user can retry or cancel.
if (!themeRemovalTarget) return;
const removedIds = new Set(themeIdsToRemove);
if (removedIds.size === 0) return;
const removesBase = removedIds.has(getThemeDefinition(theme)?.id ?? "");
// Keep the themes installed if we cannot move the selection off one of
// them; the dialog stays open so the user can retry or cancel.
if (removesBase && !persistTheme(appearanceMode === "system" ? "system" : appearanceMode)) {
return;
}
for (const appearance of ["light", "dark"] as const) {
const half = themeHalves?.[appearance];
if (half === undefined) continue;
// Writing a base preference clears the whole mix, so halves that name a
// surviving theme are written back; halves on the removed theme fall
// back to the base.
const next = half === themeToRemove.id ? null : removesBase ? half : undefined;
// Writing a base preference clears the whole mix, so halves that name
// a surviving theme are written back; removed halves fall back to base.
const next = half && removedIds.has(half) ? null : removesBase ? half : undefined;
if (next !== undefined && !setThemeHalf(appearance, next)) {
notifyThemeRemovalFailure();
return;
}
}
try {
removeCustomTheme(themeToRemove.id);
removeCustomThemes([...removedIds]);
} catch {
notifyThemeRemovalFailure();
return;
}
setThemeToRemove(null);
setIsThemeRemovalOpen(false);
}, [
appearanceMode,
notifyThemeRemovalFailure,
@@ -326,7 +611,8 @@ export function ThemeLibrary({
setThemeHalf,
theme,
themeHalves,
themeToRemove,
themeIdsToRemove,
themeRemovalTarget,
]);
// ----- Automatic-mode mixing -------------------------------------------
@@ -460,6 +746,20 @@ export function ThemeLibrary({
</div>
);
const customThemeCollections = [
...customThemes
.reduce((groups, customTheme) => {
const groupId = customTheme.collection
? `collection:${customTheme.collection.id}`
: `theme:${customTheme.id}`;
const group = groups.get(groupId);
if (group) group.push(customTheme);
else groups.set(groupId, [customTheme]);
return groups;
}, new Map<string, ThemeDefinition[]>())
.entries(),
];
const renderPairGrid = () => (
// One shared provider so every tooltip in the grid hands off instantly to
// the next hovered trigger instead of stacking on top of it. The card
@@ -509,43 +809,39 @@ export function ThemeLibrary({
/>
);
})}
{customThemes.map((customTheme) => {
const card = getThemeCardDefinition(customTheme);
return (
<ThemeLibraryCard
activeModes={pickedModesFor(customTheme.id)}
isActive={false}
key={customTheme.id}
onDuplicate={() =>
openThemeEditor({
editingThemeId: null,
seedThemeId: customTheme.id,
seedName: `${customTheme.label} copy`,
initialAppearance,
})
}
onEdit={() =>
openThemeEditor({
editingThemeId: customTheme.id,
seedThemeId: null,
seedName: null,
initialAppearance,
})
}
onDownload={() =>
downloadThemeFile(`${customTheme.id}.json`, serializeThemeFile(customTheme))
}
onRemove={() => handleRemoveTheme(customTheme)}
onUse={() => {
const modes = getThemeModes(customTheme);
if (modes.length === 1) assignHalf(modes[0]!, customTheme.id);
else persistTheme(customTheme.id);
}}
onUseMode={handlePairPick(customTheme.id)}
theme={card}
/>
);
})}
{customThemeCollections.map(([collectionId, themes]) => (
<CustomThemeCollectionCard
activeModesFor={pickedModesFor}
key={collectionId}
onDownload={(customTheme) =>
downloadThemeFile(`${customTheme.id}.json`, serializeThemeFile(customTheme))
}
onDuplicate={(customTheme) =>
openThemeEditor({
editingThemeId: null,
seedThemeId: customTheme.id,
seedName: `${customTheme.label} copy`,
initialAppearance,
})
}
onEdit={(customTheme) =>
openThemeEditor({
editingThemeId: customTheme.id,
seedThemeId: null,
seedName: null,
initialAppearance,
})
}
onRemove={(customTheme) => handleRemoveTheme(customTheme, themes)}
onUse={(customTheme) => {
const modes = getThemeModes(customTheme);
if (modes.length === 1) assignHalf(modes[0]!, customTheme.id);
else persistTheme(customTheme.id);
}}
onUseMode={(customTheme, mode) => handlePairPick(customTheme.id)(mode)}
themes={themes}
/>
))}
</div>
</TooltipProvider>
);
@@ -561,7 +857,7 @@ export function ThemeLibrary({
{renderModeTiles()}
<div className="flex min-h-8 flex-wrap items-center justify-between gap-3 px-3 pt-2 sm:px-4">
<h3 className="text-sm font-medium tracking-[-0.005em] text-foreground">Themes</h3>
<div className="flex flex-wrap items-center justify-end gap-3">
<div className="flex flex-wrap items-center justify-end gap-2">
<Button
size="xs"
variant="outline"
@@ -586,19 +882,9 @@ export function ThemeLibrary({
{renderPairGrid()}
<ThemeImportDialog
onImportedMany={(importedThemes, { updated }) => {
// An updated theme that is showing (as the base or either half)
// needs its palette re-applied.
if (
updated &&
importedThemes.some(
(imported) =>
getThemeDefinition(theme)?.id === imported.id ||
themeHalves?.light === imported.id ||
themeHalves?.dark === imported.id,
)
) {
refreshTheme();
}
// Re-apply after collection updates. The update may remove the
// selected variant, in which case the theme hook falls back safely.
if (updated) refreshTheme();
const verb = updated ? "updated" : "added";
toastManager.add(
stackedThreadToast({
@@ -639,23 +925,80 @@ export function ThemeLibrary({
onOpenChange={onImportOpenChange}
open={isImportOpen}
/>
<AlertDialog
open={themeToRemove !== null}
onOpenChange={(open) => {
if (!open) setThemeToRemove(null);
}}
>
<AlertDialog open={isThemeRemovalOpen} onOpenChange={setIsThemeRemovalOpen}>
<AlertDialogPopup>
<AlertDialogHeader>
<AlertDialogTitle>Remove “{removeDialogTheme?.label}”?</AlertDialogTitle>
<AlertDialogTitle>
{canRemoveCollection
? `Remove themes from “${removeDialogCollectionLabel}”?`
: `Remove “${removeDialogTheme?.label}”?`}
</AlertDialogTitle>
<AlertDialogDescription>
You can bring it back anytime by importing its JSON file.
{canRemoveCollection
? "Select the variants you want to remove. You can restore them by importing the extension again."
: "You can bring it back anytime by importing its JSON file."}
</AlertDialogDescription>
</AlertDialogHeader>
{canRemoveCollection ? (
<div className="grid max-h-72 grid-cols-1 gap-2 overflow-y-auto px-6 pb-6 sm:grid-cols-2">
{removeDialogCollectionThemes.map((customTheme) => {
const checked = themeIdsToRemoveSet.has(customTheme.id);
const card = getThemeCardDefinition(customTheme);
const checkboxId = `remove-theme-${customTheme.id}`;
return (
<label
className="group relative flex min-h-28 cursor-pointer flex-col items-center justify-center gap-2 rounded-lg border border-border/70 bg-muted/25 p-3 has-checked:border-ring has-checked:bg-accent/20 hover:bg-muted/40"
htmlFor={checkboxId}
key={customTheme.id}
>
<span className="absolute right-2 top-2 inline-grid size-5 grid-cols-1 sm:size-4">
<input
checked={checked}
className="col-start-1 row-start-1 size-full appearance-none rounded-sm border border-input bg-background outline-none checked:border-primary checked:bg-primary focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring dark:not-checked:bg-input/32 forced-colors:appearance-auto"
id={checkboxId}
name="themes-to-remove"
type="checkbox"
onChange={(event) => {
const shouldRemove = event.currentTarget.checked;
setThemeIdsToRemove((current) =>
shouldRemove
? [...current, customTheme.id]
: current.filter((themeId) => themeId !== customTheme.id),
);
}}
/>
<CheckIcon className="pointer-events-none col-start-1 row-start-1 size-3.5 shrink-0 self-center justify-self-center stroke-primary-foreground opacity-0 group-has-checked:opacity-100 sm:size-3" />
</span>
<span className="flex min-h-12 items-center justify-center gap-1">
{card.previews.map((preview) => (
<span
className="flex size-11 shrink-0 items-center justify-center"
key={preview.mode}
>
<span className="flex scale-75">
<ThemePreviewCircle colors={preview.colors} mode={preview.mode} />
</span>
</span>
))}
</span>
<p className="max-w-full truncate text-center text-base font-medium text-foreground sm:text-sm">
{customTheme.label}
</p>
</label>
);
})}
</div>
) : null}
<AlertDialogFooter>
<AlertDialogClose render={<Button variant="outline" />}>Cancel</AlertDialogClose>
<Button variant="destructive" onClick={handleConfirmRemoveTheme}>
Remove theme
<Button
disabled={themeIdsToRemove.length === 0}
variant="destructive"
onClick={handleConfirmRemoveTheme}
>
{canRemoveCollection
? `Remove selected${themeIdsToRemove.length > 0 ? ` (${themeIdsToRemove.length})` : ""}`
: "Remove theme"}
</Button>
</AlertDialogFooter>
</AlertDialogPopup>
@@ -1,6 +1,11 @@
import { ChartNoAxesColumnIcon, GitPullRequestIcon, SettingsIcon } from "lucide-react";
import {
ArrowLeftIcon,
ChartNoAxesColumnIcon,
GitPullRequestIcon,
SettingsIcon,
} from "lucide-react";
import { memo, useCallback } from "react";
import { Link, useNavigate } from "@tanstack/react-router";
import { Link, useLocation, useNavigate } from "@tanstack/react-router";
import { useEnvironmentIdentificationMode } from "../../hooks/useSettings";
import { cn } from "../../lib/utils";
@@ -8,6 +13,7 @@ import { usePrimaryEnvironment } from "../../state/environments";
import {
resolveEnvironmentIdentificationPillLabel,
resolveSidebarStageBackdropVariant,
resolveSidebarStageFocusRingOffsetClass,
SidebarStageBackdrop,
useEnvironmentStageLabel,
} from "../SidebarStageBackdrop";
@@ -21,8 +27,9 @@ import {
SidebarTrigger,
useSidebar,
} from "../ui/sidebar";
import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
import { SidebarProviderUpdatePill } from "./SidebarProviderUpdatePill";
import { SidebarUpdatePill } from "./SidebarUpdatePill";
import { SidebarUpdateArchitectureWarning, SidebarUpdatePill } from "./SidebarUpdatePill";
export const SidebarChromeHeader = memo(function SidebarChromeHeader({
isElectron,
@@ -52,7 +59,8 @@ export const SidebarChromeHeader = memo(function SidebarChromeHeader({
className={cn(
"relative z-10 md:hidden",
backdropVariant &&
"[: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!",
"focus-visible:ring-white/90 [&_svg]:stroke-white/90! [&_svg]:opacity-100! [&_svg]:hover:stroke-white! [:hover,[data-pressed]]:bg-white/15",
backdropVariant && resolveSidebarStageFocusRingOffsetClass(backdropVariant),
)}
/>
<SidebarBrand onBackdrop={backdropVariant !== null} />
@@ -112,6 +120,14 @@ function T3Wordmark() {
export const SidebarChromeFooter = memo(function SidebarChromeFooter() {
const navigate = useNavigate();
const { isMobile, setOpenMobile } = useSidebar();
const currentFooterPage = useLocation({
select: (location) =>
location.pathname === "/usage"
? "usage"
: location.pathname === "/pull-requests"
? "pull-requests"
: null,
});
const primaryEnvironment = usePrimaryEnvironment();
const pullRequestsSupported =
primaryEnvironment?.serverConfig?.environment.capabilities.pullRequests === true;
@@ -136,31 +152,74 @@ export const SidebarChromeFooter = memo(function SidebarChromeFooter() {
void navigate({ to: "/usage" });
}, [isMobile, navigate, setOpenMobile]);
const handleBackClick = useCallback(() => {
closeMobileSidebar();
void navigate({ to: "/" });
}, [closeMobileSidebar, navigate]);
return (
<SidebarFooter className="p-[var(--sidebar-content-inset)]">
<SidebarProviderUpdatePill />
<SidebarUpdatePill />
<SidebarMenu>
{pullRequestsSupported ? (
<SidebarMenuItem>
<SidebarMenuButton onClick={handlePullRequestsClick}>
<GitPullRequestIcon />
<span>Pull Requests</span>
<SidebarUpdateArchitectureWarning />
<SidebarMenu className="flex-row items-center">
{currentFooterPage ? (
<SidebarMenuItem className="min-w-0 flex-1">
<SidebarMenuButton onClick={handleBackClick}>
<ArrowLeftIcon />
<span>Back</span>
</SidebarMenuButton>
</SidebarMenuItem>
) : null}
<SidebarMenuItem>
<SidebarMenuButton onClick={handleUsageClick}>
<ChartNoAxesColumnIcon />
<span>Usage</span>
</SidebarMenuButton>
</SidebarMenuItem>
<SidebarMenuItem>
<SidebarMenuButton onClick={handleSettingsClick}>
<SettingsIcon />
<span>Settings</span>
</SidebarMenuButton>
</SidebarMenuItem>
) : (
<>
<SidebarMenuItem className="shrink-0">
<Tooltip>
<TooltipTrigger
render={
<SidebarMenuButton
aria-label="Settings"
onClick={handleSettingsClick}
size="icon"
>
<SettingsIcon />
</SidebarMenuButton>
}
/>
<TooltipPopup side="top">Settings</TooltipPopup>
</Tooltip>
</SidebarMenuItem>
{pullRequestsSupported ? (
<SidebarMenuItem className="shrink-0">
<Tooltip>
<TooltipTrigger
render={
<SidebarMenuButton
aria-label="Pull Requests"
onClick={handlePullRequestsClick}
size="icon"
>
<GitPullRequestIcon />
</SidebarMenuButton>
}
/>
<TooltipPopup side="top">Pull Requests</TooltipPopup>
</Tooltip>
</SidebarMenuItem>
) : null}
<SidebarMenuItem className="shrink-0">
<Tooltip>
<TooltipTrigger
render={
<SidebarMenuButton aria-label="Usage" onClick={handleUsageClick} size="icon">
<ChartNoAxesColumnIcon />
</SidebarMenuButton>
}
/>
<TooltipPopup side="top">Usage</TooltipPopup>
</Tooltip>
</SidebarMenuItem>
</>
)}
<SidebarUpdatePill />
</SidebarMenu>
</SidebarFooter>
);
@@ -1,10 +1,12 @@
import { DownloadIcon, RotateCwIcon, TriangleAlertIcon, XIcon } from "lucide-react";
import { DownloadIcon, RefreshCwIcon, RotateCwIcon, TriangleAlertIcon } from "lucide-react";
import { useCallback, useState } from "react";
import { isElectron } from "../../env";
import { cn } from "../../lib/utils";
import { ensureLocalApi } from "../../localApi";
import { useDesktopUpdateState } from "../../state/desktopUpdate";
import { stackedThreadToast, toastManager } from "../ui/toast";
import {
canCheckForUpdate,
getArm64IntelBuildWarningDescription,
getDesktopUpdateActionError,
getDesktopUpdateButtonTooltip,
@@ -12,12 +14,12 @@ import {
isDesktopUpdateButtonDisabled,
resolveDesktopUpdateButtonAction,
shouldShowArm64IntelBuildWarning,
shouldShowDesktopUpdateButton,
shouldToastDesktopUpdateActionResult,
} from "../desktopUpdate.logic";
import { showDesktopUpdateDownloadedToast } from "../desktopUpdate.toast";
import { Alert, AlertDescription, AlertTitle } from "../ui/alert";
import { Separator } from "../ui/separator";
import { SidebarMenuItem } from "../ui/sidebar";
import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
function keyReleaseNoteItems(items: ReadonlyArray<string>) {
@@ -41,16 +43,29 @@ function SidebarUpdateReleaseNotesTooltip({
}
return (
<div className="w-120 max-w-[calc(100vw-2rem)] text-left">
<div className="w-fit max-w-[min(24rem,calc(100vw-2rem))] text-left">
<div className="px-1">
<div className="text-sm leading-5 font-medium">{tooltip}</div>
{state.status === "available" ? (
<div>
<div className="whitespace-nowrap text-sm leading-5 font-medium">
Update ready to download
</div>
{state.availableVersion ? (
<div className="mt-0.5 text-xs leading-4 text-update-foreground">
{state.availableVersion}
</div>
) : null}
</div>
) : (
<div className="text-sm leading-5 font-medium">{tooltip}</div>
)}
</div>
<div className="max-h-[min(28rem,calc(100vh-6rem))] overflow-y-auto px-1 pt-4 pb-1">
{state.releaseNotes.map((releaseNote, index) => (
<div key={releaseNote.version}>
{index > 0 && <Separator className="my-3 bg-border/60" />}
<section>
<h3 className="text-muted-foreground text-xs leading-4 font-semibold">
<h3 className="text-foreground text-xs leading-4 font-semibold">
{index === 0 ? "What's changed" : `Changes in ${releaseNote.version}`}
</h3>
<ul className="mt-2 space-y-1.5 pl-4 text-xs leading-5 text-popover-foreground/90">
@@ -68,24 +83,50 @@ function SidebarUpdateReleaseNotesTooltip({
);
}
export function SidebarUpdatePill() {
export function SidebarUpdateArchitectureWarning() {
return isElectron ? <SidebarUpdateArchitectureWarningContent /> : null;
}
function SidebarUpdateArchitectureWarningContent() {
const state = useDesktopUpdateState();
const visible = shouldShowArm64IntelBuildWarning(state);
const description = state && visible ? getArm64IntelBuildWarningDescription(state) : null;
if (!visible || !description) return null;
return (
<Alert variant="warning" className="rounded-2xl border-warning/40 bg-warning/8 text-xs">
<TriangleAlertIcon />
<AlertTitle>Intel build on Apple Silicon</AlertTitle>
<AlertDescription>{description}</AlertDescription>
</Alert>
);
}
export function SidebarUpdatePill() {
return isElectron ? <SidebarUpdateControl /> : null;
}
function SidebarUpdateControl() {
const state = useDesktopUpdateState();
const [dismissed, setDismissed] = useState(false);
const [isActionPending, setIsActionPending] = useState(false);
const visible = isElectron && shouldShowDesktopUpdateButton(state) && !dismissed;
const tooltip = state ? getDesktopUpdateButtonTooltip(state) : "Update available";
const disabled = isDesktopUpdateButtonDisabled(state);
const action = state ? resolveDesktopUpdateButtonAction(state) : "none";
const showArm64Warning = isElectron && shouldShowArm64IntelBuildWarning(state);
const arm64Description =
state && showArm64Warning ? getArm64IntelBuildWarningDescription(state) : null;
const isDownloading = state?.status === "downloading";
const isUpdateState = action !== "none" || isDownloading;
const tooltip = isUpdateState
? state
? getDesktopUpdateButtonTooltip(state)
: "Update available"
: state?.status === "checking"
? "Checking for updates…"
: "Check for updates";
const disabled = isUpdateState ? isDesktopUpdateButtonDisabled(state) : !canCheckForUpdate(state);
const handleAction = useCallback(async () => {
const bridge = window.desktopBridge;
if (!bridge || !state) return;
if (disabled || action === "none" || isActionPending) return;
if (disabled || isActionPending) return;
setIsActionPending(true);
@@ -165,99 +206,92 @@ export function SidebarUpdatePill() {
);
})
.finally(() => setIsActionPending(false));
return;
}
void bridge
.checkForUpdate()
.then((result) => {
if (result.checked) return;
toastManager.add(
stackedThreadToast({
type: "error",
title: "Could not check for updates",
description:
result.state.message ?? "Automatic updates are not available in this build.",
}),
);
})
.catch((error) => {
toastManager.add(
stackedThreadToast({
type: "error",
title: "Could not check for updates",
description: error instanceof Error ? error.message : "Update check failed.",
}),
);
})
.finally(() => setIsActionPending(false));
}, [action, disabled, isActionPending, state]);
if (!visible && !showArm64Warning) return null;
return (
<div className="flex flex-col gap-1">
{showArm64Warning && arm64Description && (
<Alert variant="warning" className="rounded-2xl border-warning/40 bg-warning/8 text-xs">
<TriangleAlertIcon />
<AlertTitle>Intel build on Apple Silicon</AlertTitle>
<AlertDescription>{arm64Description}</AlertDescription>
</Alert>
)}
{visible && (
<div
className={`group/update relative flex h-7 w-full items-center rounded-lg bg-update-surface text-xs font-medium text-update-foreground ${
disabled ? " cursor-not-allowed opacity-60" : ""
}`}
>
<div className="pointer-events-none absolute inset-0 rounded-lg transition-colors group-has-[button.update-main:hover]/update:bg-update/12" />
<Tooltip>
<TooltipTrigger
render={
<button
type="button"
aria-label={tooltip}
aria-disabled={disabled || isActionPending || undefined}
disabled={disabled || isActionPending}
className="update-main relative flex h-full flex-1 items-center gap-2 px-2 enabled:cursor-pointer"
onClick={handleAction}
>
{action === "install" ? (
<>
<RotateCwIcon className="size-3.5" />
<span>Restart to update</span>
</>
) : state?.status === "downloading" ? (
<>
<DownloadIcon className="size-3.5" />
<span>
Downloading
{typeof state.downloadPercent === "number"
? ` (${Math.floor(state.downloadPercent)}%)`
: "…"}
</span>
</>
) : (
<>
<DownloadIcon className="size-3.5" />
<span>Update available</span>
</>
)}
</button>
}
/>
<TooltipPopup
align="start"
className={
state?.channel === "nightly" && state.releaseNotes.length > 0
? // pointer-events-auto overrides the positioner's pointer-events-none so the
// release notes stay open (and scrollable) when the cursor moves into them.
"pointer-events-auto max-w-none text-balance"
: undefined
}
side="top"
>
{state ? (
<SidebarUpdateReleaseNotesTooltip state={state} tooltip={tooltip} />
) : (
tooltip
<SidebarMenuItem className="ml-auto shrink-0">
<Tooltip>
<TooltipTrigger
render={
<button
type="button"
aria-label={tooltip}
aria-disabled={disabled || isActionPending || undefined}
disabled={disabled || isActionPending}
className={cn(
"inline-flex size-8 items-center justify-center rounded-full outline-hidden ring-ring transition-colors enabled:cursor-pointer focus-visible:ring-2 disabled:cursor-not-allowed disabled:opacity-60",
isUpdateState
? "bg-update-surface text-update-foreground enabled:hover:bg-update/12"
: "text-[var(--sidebar-icon-color)] enabled:hover:bg-sidebar-row-hover enabled:hover:text-sidebar-foreground",
)}
</TooltipPopup>
</Tooltip>
{action === "download" && (
<Tooltip>
<TooltipTrigger
render={
<button
type="button"
aria-label="Dismiss update"
className="mr-1 inline-flex size-5 items-center justify-center rounded-md text-update-foreground transition-colors"
onClick={() => setDismissed(true)}
>
<XIcon className="size-3.5" />
</button>
onClick={handleAction}
>
{action === "install" ? (
<RotateCwIcon className="size-4" />
) : isUpdateState ? (
<DownloadIcon className="size-4" />
) : (
<RefreshCwIcon
className={cn("size-4", state?.status === "checking" && "animate-spin")}
/>
)}
</button>
}
/>
<TooltipPopup
align="center"
className={
isUpdateState && state?.channel === "nightly" && state.releaseNotes.length > 0
? // pointer-events-auto overrides the positioner's pointer-events-none so the
// release notes stay open (and scrollable) when the cursor moves into them.
"pointer-events-auto max-w-none text-balance"
: undefined
}
side="top"
style={
isUpdateState
? {
background:
"color-mix(in srgb, var(--update) 18%, color-mix(in srgb, var(--popover) var(--glass-opacity), transparent))",
borderColor: "var(--update-foreground)",
}
/>
<TooltipPopup side="top">Dismiss until next launch</TooltipPopup>
</Tooltip>
: undefined
}
variant={isUpdateState ? "glass" : "default"}
>
{isUpdateState && state ? (
<SidebarUpdateReleaseNotesTooltip state={state} tooltip={tooltip} />
) : (
tooltip
)}
</div>
)}
</div>
</TooltipPopup>
</Tooltip>
</SidebarMenuItem>
);
}
@@ -26,7 +26,7 @@ describe("buildThreadActionMenuItems", () => {
...baseState,
supports: { settlement: false, snooze: false, pinning: false, titleRegeneration: false },
}),
).toEqual(["rename", "mark-unread", "copy-path", "delete"]);
).toEqual(["rename", "mark-unread", "copy-path", "copy-thread-id", "delete"]);
});
it("includes branch items only for threads with a branch", () => {
@@ -20,6 +20,7 @@ export type ThreadActionMenuId =
| "mark-unread"
| "copy-path"
| "copy-branch"
| "copy-thread-id"
| "delete";
export interface ThreadActionMenuState {
@@ -100,6 +101,7 @@ export function buildThreadActionMenuItems(
{ id: "mark-unread", label: "Mark unread" },
{ id: "copy-path", label: "Copy path", icon: "copy" },
...(state.branch ? [{ id: "copy-branch" as const, label: "Copy branch", icon: "copy" }] : []),
{ id: "copy-thread-id", label: "Copy thread ID", icon: "copy" },
{ id: "delete", label: "Delete", destructive: true, icon: "trash" },
];
}
@@ -1,3 +1,6 @@
// @effect-diagnostics nodeBuiltinImport:off - Regression coverage compares shipped CSS with the sidebar width contract.
import * as NodeFS from "node:fs";
import { describe, expect, it } from "vite-plus/test";
import {
@@ -31,4 +34,22 @@ describe("thread sidebar width", () => {
it("keeps the sidebar minimum when the whole layout is narrower than its minimums", () => {
expect(resolveInitialThreadSidebarWidth(900, 700)).toBe(THREAD_SIDEBAR_MIN_WIDTH);
});
it("shows the desktop wordmark across the sidebar's full legal width range", () => {
const sidebarStyles = NodeFS.readFileSync(new URL("../index.css", import.meta.url), "utf8");
const desktopHeaderStyles = sidebarStyles.slice(
sidebarStyles.indexOf("@media (min-width: 48rem)"),
sidebarStyles.indexOf("/* Stage-channel sidebar art"),
);
const stageLabelThreshold = desktopHeaderStyles.match(
/@container sidebar-header \(min-width: ([\d.]+)rem\) \{\s*\.sidebar-brand-stage \{\s*display: inline-flex;/,
)?.[1];
expect(sidebarStyles).toMatch(/\.sidebar-brand \{\s*display: none;/);
expect(desktopHeaderStyles).toMatch(
/@media \(min-width: 48rem\) \{\s*\.sidebar-brand \{\s*display: flex;/,
);
expect(THREAD_SIDEBAR_MIN_WIDTH).toBe(13 * 16);
expect(Number(stageLabelThreshold) * 16).toBeGreaterThan(THREAD_SIDEBAR_MIN_WIDTH);
});
});
+1 -1
View File
@@ -97,7 +97,7 @@ function AutocompletePopup({
align={align}
alignOffset={alignOffset}
anchor={anchor}
className="z-50 select-none"
className="z-[130] select-none"
data-slot="autocomplete-positioner"
side={side}
sideOffset={sideOffset}
+1 -1
View File
@@ -163,7 +163,7 @@ function ComboboxPopup({
align={align}
alignOffset={alignOffset}
anchor={anchor}
className="z-50 select-none"
className="z-[130] select-none"
data-slot="combobox-positioner"
side={side}
sideOffset={sideOffset}
Loaded 100 of 139 files, more files were not shown because too many files have changed in this diff. Show more