Compare commits

...
Author SHA1 Message Date
Julius Marmingeandcodex 96c762e5bd refine sidebar project settings dialog
Co-authored-by: codex <[email protected]>
2026-07-23 18:04:22 +02:00
Julius Marmingeandcodex aee5f8d304 replace nested project actions with management dialog
Co-authored-by: codex <[email protected]>
2026-07-23 17:56:32 +02:00
Julius Marmingeandcodex 46e15372d1 add member-targeted sidebar v2 project actions
Co-authored-by: codex <[email protected]>
2026-07-23 17:53:41 +02:00
Julius Marmingeandcodex 9744d5cb3a keep sidebar settle actions transparent
Co-authored-by: codex <[email protected]>
2026-07-23 17:45:25 +02:00
Julius Marmingeandcodex 4daac86f03 show logical project names on sidebar threads
Co-authored-by: codex <[email protected]>
2026-07-23 17:41:13 +02:00
Julius Marmingeandcodex 17d9be34cd combine project grouping PRs for testing
Co-authored-by: codex <[email protected]>
2026-07-23 17:37:00 +02:00
Julius Marmingeandcodex 72ee1dd345 align draft hero group label
Co-authored-by: codex <[email protected]>
2026-07-23 17:36:50 +02:00
Julius Marmingeandcodex 8576aeb90a group draft hero project picker
Co-authored-by: codex <[email protected]>
2026-07-23 17:33:27 +02:00
Julius Marmingeandcodex 4078fa6ed1 preserve grouped picker search and context
Co-authored-by: codex <[email protected]>
2026-07-23 14:54:59 +02:00
Julius Marmingeandcodex 96998bc210 fix grouped new-thread picker inputs
Co-authored-by: codex <[email protected]>
2026-07-23 14:54:59 +02:00
Julius Marmingeandcodex a499f30f7e group projects in new-thread pickers
Co-authored-by: codex <[email protected]>
2026-07-23 14:54:59 +02:00
Julius Marmingeandcodex c71bc867a1 keep stale project refs in mobile filters
Co-authored-by: codex <[email protected]>
2026-07-23 14:54:30 +02:00
Julius Marmingeandcodex ee44f639a3 handle partial grouped project removal
Co-authored-by: codex <[email protected]>
2026-07-23 14:53:57 +02:00
Julius Marmingeandcodex 221377f094 deduplicate connection failure messaging
Co-authored-by: codex <[email protected]>
2026-07-23 14:42:41 +02:00
Yukun Shan b41e89eba9 fix(web): warn before silent Windows updates (#4350) 2026-07-23 14:36:56 +02:00
Julius Marmingeandcodex 7e09d54f0e fix logical project scopes on mobile
Co-authored-by: codex <[email protected]>
2026-07-23 14:33:54 +02:00
Julius Marmingeandcodex ebb4fa0b56 fix grouped project menu actions
Co-authored-by: codex <[email protected]>
2026-07-23 14:31:48 +02:00
Julius Marmingeandcodex 2e484a2707 restore grouped project sorter import
Co-authored-by: codex <[email protected]>
2026-07-23 14:22:07 +02:00
Julius Marmingeandcodex e95a0cc3cc fix mobile grouping preference handoff
Co-authored-by: codex <[email protected]>
2026-07-23 14:21:26 +02:00
Julius Marmingeandcodex b38c09fa07 move mobile project grouping to general settings
Co-authored-by: codex <[email protected]>
2026-07-23 14:21:26 +02:00
Julius Marmingeandcodex d089f8f49f fix grouped mobile project scoping
Co-authored-by: codex <[email protected]>
2026-07-23 14:21:22 +02:00
Julius Marmingeandcodex 987d79a86e group project scopes in mobile thread lists
Co-authored-by: codex <[email protected]>
2026-07-23 14:21:22 +02:00
Julius Marmingeandcodex dfd23a5d0c restore grouping mode across cold loads
Co-authored-by: codex <[email protected]>
2026-07-23 14:21:15 +02:00
Julius Marmingeandcodex 05cde4d5da persist the last enabled grouping mode
Co-authored-by: codex <[email protected]>
2026-07-23 14:21:15 +02:00
Julius Marmingeandcodex 0d5988e256 move project grouping to general settings
Co-authored-by: codex <[email protected]>
2026-07-23 14:21:15 +02:00
Julius Marmingeandcodex a4061ce9ad fix grouped project callback dependency
Co-authored-by: codex <[email protected]>
2026-07-23 14:20:20 +02:00
Julius Marmingeandcodex ce8d699b9e restore grouped projects in Sidebar V2
Co-authored-by: codex <[email protected]>
2026-07-23 14:20:20 +02:00
Julius Marmingeandcodex 4d83436415 Unify dialog glass and fix composer overlays (#4365)
Co-authored-by: codex <[email protected]>
2026-07-23 14:15:29 +02:00
Julius Marminge e51538b812 Restore light-mode surfaces and refine dialog styling
- Restore light-mode glass, dialog, dropdown, and composer colors
- Refine provider wizard, changed-file cards, sidebar controls, and buttons
- Update wizard step tests for the new list structure
2026-07-23 13:09:55 +02:00
Julius Marminge 1c9a6de26e Add shared t3.json project configuration support (#4317) 2026-07-23 09:42:35 +00:00
Theo BrowneandClaude Fable 5 fbd77420f2 feat: add "Auto" runtime mode — AI-reviewed approvals for Codex and Claude (#4272)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-07-23 02:06:24 -07:00
Theo BrowneandClaude Fable 5 16491a84b9 fix(web): new-thread defaults ignored for remote environments (#4276)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-07-23 02:06:00 -07:00
maria-rcks b44ed835c6 fix(web): sync provider banner dismissal 2026-07-23 01:13:29 -04:00
maria-rcks 9c9916aefe fix(web): address redesign review findings 2026-07-23 01:13:29 -04:00
maria-rcks 936394b6f2 test(desktop): include glass opacity in settings fixture 2026-07-23 01:13:29 -04:00
maria-rcks c38225ef1c style(web): fade settings content beneath navbar 2026-07-23 01:13:29 -04:00
maria-rcks 39cd15b954 test(web): stabilize timeline module setup 2026-07-23 01:13:29 -04:00
maria-rcks 160d97f403 fix(web): honor composer glass opacity 2026-07-23 01:13:29 -04:00
maria-rcks d330759f58 fix(web): add glass composer alerts 2026-07-23 01:13:29 -04:00
maria-rcks 5961d36769 fix(web): apply glass opacity to command palette 2026-07-23 01:13:29 -04:00
maria-rcks 0b1ce58824 style(web): polish glass opacity slider 2026-07-23 01:13:29 -04:00
maria-rcks 10da67b9da fix(web): apply glass opacity to model picker 2026-07-23 01:13:29 -04:00
maria-rcks 6e5df67f15 fix(web): override thread tooltip background 2026-07-23 01:13:29 -04:00
maria-rcks 29b1abc45e fix(web): apply glass opacity to thread tooltip 2026-07-23 01:13:29 -04:00
Julius Marmingeandcodex 14b6bfdf15 fix(web): unify and tune glass surfaces
Co-authored-by: codex <[email protected]>
2026-07-23 01:13:29 -04:00
maria-rcks b6a2563db7 style(web): polish dark mode dialogs 2026-07-23 01:13:29 -04:00
maria-rcks c5ff51ec1f feat(web): refresh application surfaces 2026-07-23 01:13:29 -04:00
2d31cb022d improve and prevent silent thread branch drift and PR fetching (#2284)
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: codex <[email protected]>
2026-07-23 01:13:21 +02:00
Rushikesh Gaikwad bc9428a06a fix(mobile): don't mark Android VPN/Tailscale as offline when connected (#3949) 2026-07-22 21:59:20 +00:00
593289c3c7 Refine light-mode sidebar surfaces (#4268)
Co-authored-by: Claude Fable 5 <[email protected]>
Co-authored-by: codex <[email protected]>
2026-07-22 23:51:31 +02:00
Julius Marmingeandcodex ab4a88386d Add remote server updates and standalone service management (#4286)
Co-authored-by: codex <[email protected]>
2026-07-22 23:49:21 +02:00
Theo BrowneandClaude Fable 5 78a0ea55c1 feat(web): copy branch name via right-click in the branch selector (#4275)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-07-22 23:33:07 +02:00
164 changed files with 8915 additions and 2001 deletions

No files matched your search

+2
View File
@@ -54,6 +54,8 @@ There's no public docs site yet, checkout the miscellaneous markdown files in [d
## Documentation
- [Getting started](./docs/getting-started/quick-start.md)
- [Remote access](./docs/user/remote-access.md)
- [Keeping T3 Code in sync](./docs/user/server-updates.md)
- [Architecture overview](./docs/architecture/overview.md)
- [Provider guides](./docs/providers/codex.md)
- [Operations](./docs/operations/ci.md)
@@ -19,6 +19,7 @@ const clientSettings: ClientSettings = {
dismissedProviderUpdateNotificationKeys: [],
diffIgnoreWhitespace: true,
favorites: [],
glassOpacity: 80,
providerModelPreferences: {},
sidebarAutoSettleAfterDays: 3,
sidebarProjectGroupingMode: "repository_path",
+1
View File
@@ -10,6 +10,7 @@
"typecheck": "astro check"
},
"dependencies": {
"@t3tools/shared": "workspace:*",
"astro": "^7.0.3"
},
"devDependencies": {
@@ -0,0 +1,10 @@
import type { APIRoute } from "astro";
import { buildT3ProjectFileJsonSchema } from "@t3tools/shared/t3ProjectFile";
// Rendered at build time; published at https://t3.codes/schema/t3.json so
// t3.json files can reference it via "$schema" for editor/LSP support.
export const GET: APIRoute = () =>
new Response(`${JSON.stringify(buildT3ProjectFileJsonSchema(), null, 2)}\n`, {
headers: { "Content-Type": "application/json" },
});
+1 -1
View File
@@ -1,7 +1,7 @@
import type { VercelConfig } from "@vercel/config/v1";
export const config: VercelConfig = {
installCommand: "npm install -g vite-plus && vp install --filter '@t3tools/marketing'",
installCommand: "npm install -g vite-plus && vp install --filter '@t3tools/marketing...'",
buildCommand: "vp run --filter @t3tools/marketing build",
outputDirectory: "dist",
};
+19 -5
View File
@@ -13,7 +13,10 @@ import { ConfirmDialogHost } from "./components/ConfirmDialogHost";
import { CloudAuthProvider } from "./features/cloud/CloudAuthProvider";
import { prepareNativeShowcaseCapture } from "./features/showcase/nativeShowcaseScene";
import { IncomingShareProvider } from "./features/sharing/IncomingShareProvider";
import { AppearancePreferencesProvider } from "./features/settings/appearance/AppearancePreferencesProvider";
import {
AppearancePreferencesProvider,
useAppearancePreferences,
} from "./features/settings/appearance/AppearancePreferencesProvider";
import { RootStack } from "./Stack";
import { appAtomRegistry } from "./state/atom-registry";
import { OverlayPortalHost } from "./components/OverlayPortal";
@@ -26,6 +29,10 @@ if (process.env.EXPO_PUBLIC_SHOWCASE === "1") {
prepareNativeShowcaseCapture();
}
void SplashScreen.preventAutoHideAsync().catch(() => {
// The native module can be unavailable in non-native test environments.
});
const appLinking = {
prefixes: [Linking.createURL("/"), "t3code://", "t3code-dev://", "t3code-preview://"],
// The Expo dev client launches the app via
@@ -40,18 +47,25 @@ const appLinking = {
const Navigation = createStaticNavigation(RootStack);
function SplashScreenCoordinator() {
const { isReady } = useAppearancePreferences();
useEffect(() => {
if (isReady) void SplashScreen.hide();
}, [isReady]);
return null;
}
export default function App() {
const colorScheme = useColorScheme();
const statusBarBg = useThemeColor("--color-status-bar");
useEffect(() => {
SplashScreen.hide();
}, []);
return (
<RegistryContext.Provider value={appAtomRegistry}>
<CloudAuthProvider>
<AppearancePreferencesProvider>
<SplashScreenCoordinator />
<GestureHandlerRootView className="flex-1">
<KeyboardProvider statusBarTranslucent>
<SafeAreaProvider>
+1 -1
View File
@@ -33,7 +33,7 @@ import { clearComposerDraftsEnvironment } from "../state/use-composer-drafts";
import { connectionStorageLayer } from "./storage";
function networkStatus(state: Network.NetworkState): "unknown" | "offline" | "online" {
if (state.isConnected === false || state.isInternetReachable === false) {
if (state.isConnected === false) {
return "offline";
}
if (state.isConnected === true) {
+111 -60
View File
@@ -1,9 +1,7 @@
import type {
EnvironmentId,
SidebarProjectGroupingMode,
SidebarThreadSortOrder,
} from "@t3tools/contracts";
import type { EnvironmentId, SidebarThreadSortOrder } from "@t3tools/contracts";
import type { MenuAction } from "@react-native-menu/menu";
import { useAtomValue } from "@effect/atom-react";
import { AsyncResult } from "effect/unstable/reactivity";
import { NativeHeaderToolbar, NativeStackScreenOptions } from "../../native/StackHeader";
import { useCallback, useMemo, useRef } from "react";
import { Platform, Pressable, Text as RNText, TextInput, View } from "react-native";
@@ -14,6 +12,7 @@ import { ControlPillMenu } from "../../components/ControlPill";
import { SymbolView } from "../../components/AppSymbol";
import { T3Wordmark } from "../../components/T3Wordmark";
import { useThemeColor } from "../../lib/useThemeColor";
import { mobilePreferencesAtom } from "../../state/preferences";
import { useHardwareKeyboardCommand } from "../keyboard/hardwareKeyboardCommands";
import { withNativeGlassHeaderItem } from "../layout/native-glass-header-items";
import { createNativeMailSearchToolbarItem } from "../layout/native-mail-search-toolbar";
@@ -21,10 +20,10 @@ import type { HomeProjectSortOrder } from "./homeThreadList";
import {
buildHomeListFilterMenu,
type HomeListFilterMenuEnvironment,
type HomeListFilterMenuProject,
} from "./home-list-filter-menu";
import {
hasCustomHomeListOptions,
PROJECT_GROUPING_OPTIONS,
PROJECT_SORT_OPTIONS,
THREAD_SORT_OPTIONS,
} from "./home-list-options";
@@ -33,16 +32,17 @@ export type HomeHeaderEnvironment = HomeListFilterMenuEnvironment;
export function HomeHeader(props: {
readonly environments: ReadonlyArray<HomeHeaderEnvironment>;
readonly projects: ReadonlyArray<HomeListFilterMenuProject>;
readonly searchQuery: string;
readonly selectedEnvironmentId: EnvironmentId | null;
readonly selectedProjectKey: string | null;
readonly projectSortOrder: HomeProjectSortOrder;
readonly threadSortOrder: SidebarThreadSortOrder;
readonly projectGroupingMode: SidebarProjectGroupingMode;
readonly onSearchQueryChange: (query: string) => void;
readonly onEnvironmentChange: (environmentId: EnvironmentId | null) => void;
readonly onProjectChange: (projectKey: string | null) => void;
readonly onProjectSortOrderChange: (sortOrder: HomeProjectSortOrder) => void;
readonly onThreadSortOrderChange: (sortOrder: SidebarThreadSortOrder) => void;
readonly onProjectGroupingModeChange: (mode: SidebarProjectGroupingMode) => void;
readonly onOpenSettings: () => void;
readonly onStartNewTask: () => void;
}) {
@@ -59,11 +59,24 @@ function checkedMenuState(checked: boolean) {
return checked ? ("on" as const) : undefined;
}
/** Thread List v2 lays the list out in fixed creation order, so the
sort/group filter controls would be silently ignored — hide them and
key the "customized" icon state off the environment filter alone. */
function useThreadListV2FilterGate() {
const preferencesResult = useAtomValue(mobilePreferencesAtom);
return (
AsyncResult.isSuccess(preferencesResult) && preferencesResult.value.threadListV2Enabled === true
);
}
function AndroidHomeHeader(props: HomeHeaderProps) {
const insets = useSafeAreaInsets();
const iconColor = useThemeColor("--color-icon");
const mutedColor = useThemeColor("--color-foreground-muted");
const hasCustomListOptions = hasCustomHomeListOptions(props);
const threadListV2Enabled = useThreadListV2FilterGate();
const hasCustomListOptions = threadListV2Enabled
? props.selectedEnvironmentId !== null || props.selectedProjectKey !== null
: hasCustomHomeListOptions(props);
const menuActions = useMemo<MenuAction[]>(
() => [
{
@@ -82,40 +95,57 @@ function AndroidHomeHeader(props: HomeHeaderProps) {
})),
],
},
{
id: "project-sort",
title: "Sort projects",
subactions: PROJECT_SORT_OPTIONS.map((option) => ({
id: `project-sort:${option.value}`,
title: option.label,
state: checkedMenuState(props.projectSortOrder === option.value),
})),
},
{
id: "thread-sort",
title: "Sort threads",
subactions: THREAD_SORT_OPTIONS.map((option) => ({
id: `thread-sort:${option.value}`,
title: option.label,
state: checkedMenuState(props.threadSortOrder === option.value),
})),
},
{
id: "project-grouping",
title: "Group projects",
subactions: PROJECT_GROUPING_OPTIONS.map((option) => ({
id: `project-grouping:${option.value}`,
title: option.label,
state: checkedMenuState(props.projectGroupingMode === option.value),
})),
},
...(props.projects.length === 0
? []
: ([
{
id: "project",
title: "Project",
subactions: [
{
id: "project:all",
title: "All projects",
state: checkedMenuState(props.selectedProjectKey === null),
},
...props.projects.map((project) => ({
id: `project:${project.key}`,
title: project.label,
state: checkedMenuState(props.selectedProjectKey === project.key),
})),
],
},
] satisfies MenuAction[])),
...(threadListV2Enabled
? []
: ([
{
id: "project-sort",
title: "Sort projects",
subactions: PROJECT_SORT_OPTIONS.map((option) => ({
id: `project-sort:${option.value}`,
title: option.label,
state: checkedMenuState(props.projectSortOrder === option.value),
})),
},
{
id: "thread-sort",
title: "Sort threads",
subactions: THREAD_SORT_OPTIONS.map((option) => ({
id: `thread-sort:${option.value}`,
title: option.label,
state: checkedMenuState(props.threadSortOrder === option.value),
})),
},
] satisfies MenuAction[])),
],
[
props.environments,
props.projectGroupingMode,
props.projectSortOrder,
props.projects,
props.selectedEnvironmentId,
props.selectedProjectKey,
props.threadSortOrder,
threadListV2Enabled,
],
);
const handleMenuAction = useCallback(
@@ -137,6 +167,19 @@ function AndroidHomeHeader(props: HomeHeaderProps) {
return;
}
if (id === "project:all") {
props.onProjectChange(null);
return;
}
if (id.startsWith("project:")) {
const projectKey = id.slice("project:".length);
if (props.projects.some((project) => project.key === projectKey)) {
props.onProjectChange(projectKey);
}
return;
}
const projectSort = PROJECT_SORT_OPTIONS.find(
(option) => id === `project-sort:${option.value}`,
);
@@ -150,13 +193,6 @@ function AndroidHomeHeader(props: HomeHeaderProps) {
props.onThreadSortOrderChange(threadSort.value);
return;
}
const grouping = PROJECT_GROUPING_OPTIONS.find(
(option) => id === `project-grouping:${option.value}`,
);
if (grouping) {
props.onProjectGroupingModeChange(grouping.value);
}
},
[props],
);
@@ -255,17 +291,24 @@ function AndroidHomeHeader(props: HomeHeaderProps) {
function IosHomeHeader(props: HomeHeaderProps) {
const searchBarRef = useRef<SearchBarCommands>(null);
const iconColor = useThemeColor("--color-icon");
const hasCustomListOptions = hasCustomHomeListOptions(props);
const threadListV2Enabled = useThreadListV2FilterGate();
const hasCustomListOptions = threadListV2Enabled
? props.selectedEnvironmentId !== null || props.selectedProjectKey !== null
: hasCustomHomeListOptions(props);
const focusSearch = useCallback(() => {
searchBarRef.current?.focus();
return searchBarRef.current !== null;
}, []);
useHardwareKeyboardCommand("focusSearch", focusSearch);
const filterMenu = buildHomeListFilterMenu(props);
const filterMenu = buildHomeListFilterMenu({
...props,
listOrganization: !threadListV2Enabled,
});
return (
<>
<NativeStackScreenOptions
optionsVersion={filterMenu.items}
options={{
// Static header config (glass, title, fonts) lives in Stack.tsx
// (GLASS_HEADER_OPTIONS). Only dynamic values are set here.
@@ -366,6 +409,28 @@ function IosHomeHeader(props: HomeHeaderProps) {
))}
</NativeHeaderToolbar.Menu>
{props.projects.length > 0 ? (
<NativeHeaderToolbar.Menu title="Project">
<NativeHeaderToolbar.Label>Project</NativeHeaderToolbar.Label>
<NativeHeaderToolbar.MenuAction
isOn={props.selectedProjectKey === null}
onPress={() => props.onProjectChange(null)}
subtitle="Show threads from every project"
>
<NativeHeaderToolbar.Label>All projects</NativeHeaderToolbar.Label>
</NativeHeaderToolbar.MenuAction>
{props.projects.map((project) => (
<NativeHeaderToolbar.MenuAction
key={project.key}
isOn={props.selectedProjectKey === project.key}
onPress={() => props.onProjectChange(project.key)}
>
<NativeHeaderToolbar.Label>{project.label}</NativeHeaderToolbar.Label>
</NativeHeaderToolbar.MenuAction>
))}
</NativeHeaderToolbar.Menu>
) : null}
<NativeHeaderToolbar.Menu title="Sort projects">
<NativeHeaderToolbar.Label>Sort projects</NativeHeaderToolbar.Label>
{PROJECT_SORT_OPTIONS.map((option) => (
@@ -391,20 +456,6 @@ function IosHomeHeader(props: HomeHeaderProps) {
</NativeHeaderToolbar.MenuAction>
))}
</NativeHeaderToolbar.Menu>
<NativeHeaderToolbar.Menu title="Group projects">
<NativeHeaderToolbar.Label>Group projects</NativeHeaderToolbar.Label>
{PROJECT_GROUPING_OPTIONS.map((option) => (
<NativeHeaderToolbar.MenuAction
key={option.value}
isOn={props.projectGroupingMode === option.value}
onPress={() => props.onProjectGroupingModeChange(option.value)}
subtitle={option.subtitle}
>
<NativeHeaderToolbar.Label>{option.label}</NativeHeaderToolbar.Label>
</NativeHeaderToolbar.MenuAction>
))}
</NativeHeaderToolbar.Menu>
</NativeHeaderToolbar.Menu>
<NativeHeaderToolbar.Spacer width={8} sharesBackground={false} />
<NativeHeaderToolbar.SearchBarSlot />
@@ -1,9 +1,10 @@
import * as Arr from "effect/Array";
import * as Order from "effect/Order";
import { useNavigation } from "@react-navigation/native";
import { useMemo, useState } from "react";
import { useEffect, useMemo, useState } from "react";
import { NativeHeaderToolbar, NativeStackScreenOptions } from "../../native/StackHeader";
import { scopedProjectKey } from "../../lib/scopedEntities";
import { useProjects, useThreadShells } from "../../state/entities";
import { usePendingNewTasks } from "../../state/use-pending-new-tasks";
import { useWorkspaceState } from "../../state/workspace";
@@ -53,11 +54,32 @@ export function HomeRouteScreen() {
const {
options: listOptions,
setSelectedEnvironmentId,
setProjectGroupingMode,
setProjectSortOrder,
setThreadSortOrder,
} = useHomeListOptions(availableEnvironmentIds);
const selectedEnvironmentId = listOptions.selectedEnvironmentId;
const [selectedProjectKey, setSelectedProjectKey] = useState<string | null>(null);
const projectFilterOptions = useMemo(
() =>
projects
.filter(
(project) =>
selectedEnvironmentId === null || project.environmentId === selectedEnvironmentId,
)
.map((project) => ({
key: scopedProjectKey(project.environmentId, project.id),
label: project.title,
})),
[projects, selectedEnvironmentId],
);
useEffect(() => {
if (
selectedProjectKey !== null &&
!projectFilterOptions.some((project) => project.key === selectedProjectKey)
) {
setSelectedProjectKey(null);
}
}, [projectFilterOptions, selectedProjectKey]);
// In split layouts the persistent sidebar IS the thread list — Home becomes
// an empty detail pane so selecting a thread never transitions layouts.
@@ -90,14 +112,15 @@ export function HomeRouteScreen() {
<NativeStackScreenOptions options={{ title: "Threads", headerTitle: "Threads" }} />
<HomeHeader
environments={environments}
projects={projectFilterOptions}
searchQuery={searchQuery}
selectedEnvironmentId={selectedEnvironmentId}
selectedProjectKey={selectedProjectKey}
projectSortOrder={listOptions.projectSortOrder}
threadSortOrder={listOptions.threadSortOrder}
projectGroupingMode={listOptions.projectGroupingMode}
onEnvironmentChange={setSelectedEnvironmentId}
onProjectChange={setSelectedProjectKey}
onOpenSettings={() => navigation.navigate("SettingsSheet", { screen: "Settings" })}
onProjectGroupingModeChange={setProjectGroupingMode}
onProjectSortOrderChange={setProjectSortOrder}
onSearchQueryChange={setSearchQuery}
onStartNewTask={() => navigation.navigate("NewTaskSheet", { screen: "NewTask" })}
@@ -115,11 +138,11 @@ export function HomeRouteScreen() {
onSettleThread={settleThread}
onUnsettleThread={unsettleThread}
onEnvironmentChange={setSelectedEnvironmentId}
onProjectChange={setSelectedProjectKey}
onOpenEnvironments={() =>
navigation.navigate("SettingsSheet", { screen: "SettingsEnvironments" })
}
onOpenSettings={() => navigation.navigate("SettingsSheet", { screen: "Settings" })}
onProjectGroupingModeChange={setProjectGroupingMode}
onProjectSortOrderChange={setProjectSortOrder}
onSearchQueryChange={setSearchQuery}
onSelectThread={(thread) => {
@@ -151,6 +174,7 @@ export function HomeRouteScreen() {
savedConnectionsById={savedConnectionsById}
searchQuery={searchQuery}
selectedEnvironmentId={selectedEnvironmentId}
selectedProjectKey={selectedProjectKey}
threads={threads}
threadSortOrder={listOptions.threadSortOrder}
/>
+128 -122
View File
@@ -15,17 +15,15 @@ import type {
import { useAtomSet, useAtomValue } from "@effect/atom-react";
import { AsyncResult } from "effect/unstable/reactivity";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { ActivityIndicator, FlatList, Platform, Pressable, ScrollView, View } from "react-native";
import { ActivityIndicator, FlatList, Platform, Pressable, View } from "react-native";
import type { SwipeableMethods } from "react-native-gesture-handler/ReanimatedSwipeable";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { useThemeColor } from "../../lib/useThemeColor";
import { AppText as Text } from "../../components/AppText";
import { EmptyState } from "../../components/EmptyState";
import { ProjectFavicon } from "../../components/ProjectFavicon";
import type { WorkspaceState } from "../../state/workspaceModel";
import type { SavedRemoteConnection } from "../../lib/connection";
import { cn } from "../../lib/cn";
import { scopedProjectKey } from "../../lib/scopedEntities";
import { NATIVE_LIQUID_GLASS_SUPPORTED } from "../../native/native-glass";
import { mobilePreferencesAtom, updateMobilePreferencesAtom } from "../../state/preferences";
@@ -38,7 +36,12 @@ import {
ThreadListShowMoreRow,
} from "../threads/thread-list-items";
import { ThreadListV2Row } from "../threads/thread-list-v2-items";
import { buildThreadListV2Items, type ThreadListV2Item } from "../threads/threadListV2";
import {
buildThreadListV2Items,
THREAD_LIST_V2_SETTLED_INITIAL_COUNT,
THREAD_LIST_V2_SETTLED_PAGE_COUNT,
type ThreadListV2Item,
} from "../threads/threadListV2";
import type { HomeListFilterMenuEnvironment } from "./home-list-filter-menu";
import {
buildHomeListLayout,
@@ -49,7 +52,12 @@ import {
type HomeGroupDisplayState,
type HomeListItem,
} from "./homeListItems";
import { buildHomeThreadGroups, type HomeProjectSortOrder } from "./homeThreadList";
import {
buildHomeProjectScopes,
buildHomeThreadGroups,
sortHomeProjectScopes,
type HomeProjectSortOrder,
} from "./homeThreadList";
import { SwipeableScrollGateProvider, useSwipeableScrollGate } from "./thread-swipe-actions";
import { WorkspaceConnectionStatus } from "./WorkspaceConnectionStatus";
import { shouldShowWorkspaceConnectionStatus } from "./workspace-connection-status";
@@ -65,14 +73,15 @@ interface HomeScreenProps {
readonly environments: ReadonlyArray<HomeListFilterMenuEnvironment>;
readonly searchQuery: string;
readonly selectedEnvironmentId: EnvironmentId | null;
readonly selectedProjectKey: string | null;
readonly projectSortOrder: HomeProjectSortOrder;
readonly threadSortOrder: SidebarThreadSortOrder;
readonly projectGroupingMode: SidebarProjectGroupingMode;
readonly onSearchQueryChange: (query: string) => void;
readonly onEnvironmentChange: (environmentId: EnvironmentId | null) => void;
readonly onProjectChange: (projectKey: string | null) => void;
readonly onProjectSortOrderChange: (sortOrder: HomeProjectSortOrder) => void;
readonly onThreadSortOrderChange: (sortOrder: SidebarThreadSortOrder) => void;
readonly onProjectGroupingModeChange: (mode: SidebarProjectGroupingMode) => void;
readonly onAddConnection: () => void;
readonly onOpenEnvironments: () => void;
readonly onOpenSettings: () => void;
@@ -91,10 +100,6 @@ interface HomeScreenProps {
/* ─── Layout constants ───────────────────────────────────────────────── */
const ESTIMATED_THREAD_ROW_HEIGHT = 72;
// v2 settled-tail paging: recent history is the common lookup; the deep
// tail stays behind an explicit Show more.
const THREAD_LIST_V2_SETTLED_INITIAL_COUNT = 10;
const THREAD_LIST_V2_SETTLED_PAGE_COUNT = 25;
/**
* Top spacing between the list and the Android custom header. The Android
* header (AndroidHomeHeader) is rendered in-flow above this screen and
@@ -169,80 +174,6 @@ function HomeTopContentSpacer() {
return <View className="h-4" />;
}
function ThreadListV2ProjectScope(props: {
readonly projects: ReadonlyArray<EnvironmentProject>;
readonly selectedKey: string | null;
readonly onChange: (key: string | null) => void;
}) {
if (props.projects.length === 0) return null;
return (
<ScrollView
horizontal
contentContainerStyle={{
gap: 8,
paddingHorizontal: 16,
paddingBottom: 8,
paddingTop: Platform.OS === "ios" ? 12 : 4,
}}
keyboardShouldPersistTaps="handled"
showsHorizontalScrollIndicator={false}
>
{props.projects.length > 1 ? (
<Pressable
accessibilityLabel="Show all threads"
accessibilityRole="button"
accessibilityState={{ selected: props.selectedKey === null }}
hitSlop={4}
onPress={() => props.onChange(null)}
className={cn(
"min-h-8 items-center justify-center rounded-lg border px-3",
props.selectedKey === null
? "border-border bg-subtle-strong"
: "border-black/15 dark:border-white/15",
)}
>
<Text className="text-sm font-t3-medium text-foreground">All</Text>
</Pressable>
) : null}
{props.projects.map((project) => {
const key = scopedProjectKey(project.environmentId, project.id);
const selected = props.selectedKey === key;
return (
<Pressable
key={key}
accessibilityLabel={`Show ${project.title} threads`}
accessibilityRole="button"
accessibilityState={{ selected }}
hitSlop={4}
onPress={() => props.onChange(selected ? null : key)}
className={cn(
"min-h-8 flex-row items-center gap-1.5 rounded-lg border py-1 pl-2 pr-3",
selected ? "border-border bg-subtle-strong" : "border-black/15 dark:border-white/15",
)}
>
<ProjectFavicon
environmentId={project.environmentId}
projectTitle={project.title}
size={15}
workspaceRoot={project.workspaceRoot}
/>
<Text
className={cn(
"max-w-36 text-sm font-t3-medium",
selected ? "text-foreground" : "text-foreground-muted",
)}
numberOfLines={1}
>
{project.title}
</Text>
</Pressable>
);
})}
</ScrollView>
);
}
/* ─── Main screen ────────────────────────────────────────────────────── */
export function HomeScreen(props: HomeScreenProps) {
@@ -314,12 +245,51 @@ export function HomeScreen(props: HomeScreenProps) {
onScrollBeginDrag: handleScrollBeginDrag,
});
const scopedProject = useMemo(
() =>
props.selectedProjectKey === null
? null
: (props.projects.find(
(project) =>
scopedProjectKey(project.environmentId, project.id) === props.selectedProjectKey &&
(props.selectedEnvironmentId === null ||
project.environmentId === props.selectedEnvironmentId),
) ?? null),
[props.projects, props.selectedEnvironmentId, props.selectedProjectKey],
);
const scopedProjects = useMemo(
() => (scopedProject === null ? props.projects : [scopedProject]),
[props.projects, scopedProject],
);
const scopedThreads = useMemo(
() =>
scopedProject === null
? props.threads
: props.threads.filter(
(thread) =>
thread.environmentId === scopedProject.environmentId &&
thread.projectId === scopedProject.id,
),
[props.threads, scopedProject],
);
const scopedPendingTasks = useMemo(
() =>
scopedProject === null
? props.pendingTasks
: props.pendingTasks.filter(
(pendingTask) =>
pendingTask.message.environmentId === scopedProject.environmentId &&
pendingTask.creation.projectId === scopedProject.id,
),
[props.pendingTasks, scopedProject],
);
const projectGroups = useMemo(
() =>
buildHomeThreadGroups({
projects: props.projects,
threads: props.threads,
pendingTasks: props.pendingTasks,
projects: scopedProjects,
threads: scopedThreads,
pendingTasks: scopedPendingTasks,
environmentId: props.selectedEnvironmentId,
searchQuery: props.searchQuery,
projectSortOrder: props.projectSortOrder,
@@ -327,14 +297,14 @@ export function HomeScreen(props: HomeScreenProps) {
projectGroupingMode: props.projectGroupingMode,
}),
[
props.pendingTasks,
props.projectGroupingMode,
props.projects,
props.projectSortOrder,
props.searchQuery,
props.selectedEnvironmentId,
props.threadSortOrder,
props.threads,
scopedPendingTasks,
scopedProjects,
scopedThreads,
],
);
@@ -365,29 +335,54 @@ export function HomeScreen(props: HomeScreenProps) {
return map;
}, [props.projects]);
const [v2ProjectScopeKey, setV2ProjectScopeKey] = useState<string | null>(null);
const v2ProjectScopeKey = props.selectedProjectKey;
const v2ScopeProjects = useMemo(
() =>
props.selectedEnvironmentId === null
? props.projects
: props.projects.filter((project) => project.environmentId === props.selectedEnvironmentId),
[props.projects, props.selectedEnvironmentId],
sortHomeProjectScopes({
scopes: buildHomeProjectScopes({
projects: props.projects,
environmentId: props.selectedEnvironmentId,
projectGroupingMode: props.projectGroupingMode,
}),
threads: props.threads,
pendingTasks: props.pendingTasks,
projectSortOrder: props.projectSortOrder,
}),
[
props.pendingTasks,
props.projectGroupingMode,
props.projects,
props.projectSortOrder,
props.selectedEnvironmentId,
props.threads,
],
);
const v2ScopedProject = useMemo(
const v2ScopedProjectGroup = useMemo(
() =>
v2ProjectScopeKey === null
? null
: (v2ScopeProjects.find(
(project) => scopedProjectKey(project.environmentId, project.id) === v2ProjectScopeKey,
(scope) =>
scope.key === v2ProjectScopeKey ||
scope.projectRefs.some(
(projectRef) =>
scopedProjectKey(projectRef.environmentId, projectRef.projectId) ===
v2ProjectScopeKey,
),
) ?? null),
[v2ProjectScopeKey, v2ScopeProjects],
);
useEffect(() => {
if (v2ProjectScopeKey !== null && v2ScopedProject === null) {
setV2ProjectScopeKey(null);
}
}, [v2ProjectScopeKey, v2ScopedProject]);
const v2ScopedProjectKeys = useMemo(
() =>
v2ScopedProjectGroup === null
? null
: new Set(
v2ScopedProjectGroup.projectRefs.map((projectRef) =>
scopedProjectKey(projectRef.environmentId, projectRef.projectId),
),
),
[v2ScopedProjectGroup],
);
// Thread List v2 (beta): one flat list in creation order, no grouping.
// Settled threads collapse into a recency tail below the card block.
// Settled threads stay in the live shell stream (settled ≠ archived), so
@@ -442,6 +437,10 @@ export function HomeScreen(props: HomeScreenProps) {
const [nowMinute, setNowMinute] = useState(() => new Date().toISOString().slice(0, 16));
useEffect(() => {
if (!threadListV2Enabled) return;
// Refresh immediately on enable: the mount-time value can be hours old
// by the time the beta is switched on, which would misclassify the
// inactivity auto-settle boundary until the first tick.
setNowMinute(new Date().toISOString().slice(0, 16));
const id = setInterval(() => setNowMinute(new Date().toISOString().slice(0, 16)), 60_000);
return () => clearInterval(id);
}, [threadListV2Enabled]);
@@ -464,13 +463,7 @@ export function HomeScreen(props: HomeScreenProps) {
return buildThreadListV2Items({
threads: props.threads.filter((thread) => thread.archivedAt === null),
environmentId: props.selectedEnvironmentId,
projectRef:
v2ScopedProject === null
? null
: {
environmentId: v2ScopedProject.environmentId,
projectId: v2ScopedProject.id,
},
projectRefs: v2ScopedProjectGroup === null ? null : v2ScopedProjectGroup.projectRefs,
searchQuery: props.searchQuery,
changeRequestStateByKey,
settlementEnvironmentIds,
@@ -486,7 +479,7 @@ export function HomeScreen(props: HomeScreenProps) {
props.selectedEnvironmentId,
props.threads,
threadListV2Enabled,
v2ScopedProject,
v2ScopedProjectGroup,
]);
const threadListV2Items = threadListV2Layout.items;
@@ -509,6 +502,11 @@ export function HomeScreen(props: HomeScreenProps) {
(item.thread.session?.providerInstanceId ?? item.thread.modelSelection.instanceId),
)?.driver ?? null
}
environmentLabel={
Object.keys(props.savedConnectionsById).length > 1
? (props.savedConnectionsById[item.thread.environmentId]?.environmentLabel ?? null)
: null
}
onSelectThread={props.onSelectThread}
onDeleteThread={handleDeleteThread}
onArchiveThread={props.onArchiveThread}
@@ -535,6 +533,7 @@ export function HomeScreen(props: HomeScreenProps) {
projectCwdByKey,
props.onArchiveThread,
props.onSelectThread,
props.savedConnectionsById,
serverConfigs,
settlementEnvironmentIds,
],
@@ -726,19 +725,17 @@ export function HomeScreen(props: HomeScreenProps) {
(pendingTask) =>
(props.selectedEnvironmentId === null ||
pendingTask.message.environmentId === props.selectedEnvironmentId) &&
(v2ScopedProject === null ||
(pendingTask.message.environmentId === v2ScopedProject.environmentId &&
pendingTask.creation.projectId === v2ScopedProject.id)) &&
(v2ScopedProjectKeys === null ||
v2ScopedProjectKeys.has(
scopedProjectKey(pendingTask.message.environmentId, pendingTask.creation.projectId),
)) &&
(v2SearchQuery.length === 0 || pendingTask.title.toLocaleLowerCase().includes(v2SearchQuery)),
);
// Project scoping lives in the header filter menu (no inline chip row on
// mobile — the menu is the one filter surface).
const v2ListHeader = (
<>
{listHeader}
<ThreadListV2ProjectScope
projects={v2ScopeProjects}
selectedKey={v2ProjectScopeKey}
onChange={setV2ProjectScopeKey}
/>
{v2PendingTasks.map((pendingTask, index) => (
<PendingTaskListRow
key={pendingTask.message.messageId}
@@ -758,6 +755,11 @@ export function HomeScreen(props: HomeScreenProps) {
const listEmpty = !hasResults ? (
hasSearchQuery ? (
<EmptyState title="No results" detail={`No threads matching "${props.searchQuery}".`} />
) : scopedProject !== null ? (
<EmptyState
title={`No threads in ${scopedProject.title}`}
detail="Choose another project or create a new task."
/>
) : selectedEnvironmentLabel ? (
<EmptyState
title={`No threads in ${selectedEnvironmentLabel}`}
@@ -775,9 +777,9 @@ export function HomeScreen(props: HomeScreenProps) {
const v2ListEmpty =
v2PendingTasks.length > 0 ? null : hasSearchQuery ? (
<EmptyState title="No results" detail={`No threads matching "${props.searchQuery}".`} />
) : v2ScopedProject !== null ? (
) : v2ScopedProjectGroup !== null ? (
<EmptyState
title={`No threads in ${v2ScopedProject.title}`}
title={`No threads in ${v2ScopedProjectGroup.title}`}
detail="Choose another project or create a new task."
/>
) : (
@@ -792,7 +794,11 @@ export function HomeScreen(props: HomeScreenProps) {
data={threadListV2Items}
renderItem={renderV2Item}
keyExtractor={v2KeyExtractor}
extraData={{ projectByKey, serverConfigs }}
extraData={{
projectByKey,
serverConfigs,
savedConnectionsById: props.savedConnectionsById,
}}
ListHeaderComponent={v2ListHeader}
ListFooterComponent={
threadListV2Layout.hiddenSettledCount > 0 ? (
@@ -0,0 +1,42 @@
import { describe, expect, it, vi } from "vite-plus/test";
import { buildHomeListFilterMenu } from "./home-list-filter-menu";
describe("buildHomeListFilterMenu", () => {
it("adds a project scope submenu that selects and clears the same scope as the chips", () => {
const onProjectChange = vi.fn();
const menu = buildHomeListFilterMenu({
environments: [],
projects: [
{ key: "environment-1:project-1", label: "Codething" },
{ key: "environment-1:project-2", label: "Website" },
],
selectedEnvironmentId: null,
selectedProjectKey: "environment-1:project-1",
projectSortOrder: "updated_at",
threadSortOrder: "updated_at",
onEnvironmentChange: vi.fn(),
onProjectChange,
onProjectSortOrderChange: vi.fn(),
onThreadSortOrderChange: vi.fn(),
});
const projectMenu = menu.items.find(
(item) => item.type === "submenu" && item.title === "Project",
);
expect(projectMenu).toMatchObject({
type: "submenu",
items: [
{ title: "All projects", state: "off" },
{ title: "Codething", state: "on" },
{ title: "Website", state: "off" },
],
});
if (projectMenu?.type !== "submenu") throw new Error("Expected project submenu");
projectMenu.items[0]?.onPress();
projectMenu.items[2]?.onPress();
expect(onProjectChange).toHaveBeenNthCalledWith(1, null);
expect(onProjectChange).toHaveBeenNthCalledWith(2, "environment-1:project-2");
});
});
@@ -1,21 +1,18 @@
import type {
EnvironmentId,
SidebarProjectGroupingMode,
SidebarThreadSortOrder,
} from "@t3tools/contracts";
import type { EnvironmentId, SidebarThreadSortOrder } from "@t3tools/contracts";
import type { HomeProjectSortOrder } from "./homeThreadList";
import {
PROJECT_GROUPING_OPTIONS,
PROJECT_SORT_OPTIONS,
THREAD_SORT_OPTIONS,
} from "./home-list-options";
import { PROJECT_SORT_OPTIONS, THREAD_SORT_OPTIONS } from "./home-list-options";
export interface HomeListFilterMenuEnvironment {
readonly environmentId: EnvironmentId;
readonly label: string;
}
export interface HomeListFilterMenuProject {
readonly key: string;
readonly label: string;
}
type HomeListFilterMenuAction = {
readonly type: "action";
readonly title: string;
@@ -37,15 +34,20 @@ export interface HomeListFilterMenu {
export function buildHomeListFilterMenu(props: {
readonly environments: ReadonlyArray<HomeListFilterMenuEnvironment>;
readonly projects: ReadonlyArray<HomeListFilterMenuProject>;
readonly selectedEnvironmentId: EnvironmentId | null;
readonly selectedProjectKey: string | null;
readonly projectSortOrder: HomeProjectSortOrder;
readonly threadSortOrder: SidebarThreadSortOrder;
readonly projectGroupingMode: SidebarProjectGroupingMode;
readonly onEnvironmentChange: (environmentId: EnvironmentId | null) => void;
readonly onProjectChange: (projectKey: string | null) => void;
readonly onProjectSortOrderChange: (sortOrder: HomeProjectSortOrder) => void;
readonly onThreadSortOrderChange: (sortOrder: SidebarThreadSortOrder) => void;
readonly onProjectGroupingModeChange: (mode: SidebarProjectGroupingMode) => void;
readonly onOpenSettings?: () => void;
/** False hides the sort/group submenus. Thread List v2 uses a fixed
creation-order layout, so offering those controls while it silently
ignores them would be a lie; the environment filter still applies. */
readonly listOrganization?: boolean;
}): HomeListFilterMenu {
const items: Array<HomeListFilterMenuAction | HomeListFilterMenuSubmenu> = [];
@@ -57,61 +59,75 @@ export function buildHomeListFilterMenu(props: {
});
}
items.push(
{
items.push({
type: "submenu",
title: "Environment",
items: [
{
type: "action",
title: "All environments",
subtitle: "Show threads from every environment",
state: props.selectedEnvironmentId === null ? "on" : "off",
onPress: () => props.onEnvironmentChange(null),
},
...props.environments.map((environment) => ({
type: "action" as const,
title: environment.label,
state:
props.selectedEnvironmentId === environment.environmentId
? ("on" as const)
: ("off" as const),
onPress: () => props.onEnvironmentChange(environment.environmentId),
})),
],
});
if (props.projects.length > 0) {
items.push({
type: "submenu",
title: "Environment",
title: "Project",
items: [
{
type: "action",
title: "All environments",
subtitle: "Show threads from every environment",
state: props.selectedEnvironmentId === null ? "on" : "off",
onPress: () => props.onEnvironmentChange(null),
title: "All projects",
subtitle: "Show threads from every project",
state: props.selectedProjectKey === null ? "on" : "off",
onPress: () => props.onProjectChange(null),
},
...props.environments.map((environment) => ({
...props.projects.map((project) => ({
type: "action" as const,
title: environment.label,
state:
props.selectedEnvironmentId === environment.environmentId
? ("on" as const)
: ("off" as const),
onPress: () => props.onEnvironmentChange(environment.environmentId),
title: project.label,
state: props.selectedProjectKey === project.key ? ("on" as const) : ("off" as const),
onPress: () => props.onProjectChange(project.key),
})),
],
},
{
type: "submenu",
title: "Sort projects",
items: PROJECT_SORT_OPTIONS.map((option) => ({
type: "action",
title: option.label,
state: props.projectSortOrder === option.value ? "on" : "off",
onPress: () => props.onProjectSortOrderChange(option.value),
})),
},
{
type: "submenu",
title: "Sort threads",
items: THREAD_SORT_OPTIONS.map((option) => ({
type: "action",
title: option.label,
state: props.threadSortOrder === option.value ? "on" : "off",
onPress: () => props.onThreadSortOrderChange(option.value),
})),
},
{
type: "submenu",
title: "Group projects",
items: PROJECT_GROUPING_OPTIONS.map((option) => ({
type: "action",
title: option.label,
subtitle: option.subtitle,
state: props.projectGroupingMode === option.value ? "on" : "off",
onPress: () => props.onProjectGroupingModeChange(option.value),
})),
},
);
});
}
if (props.listOrganization !== false) {
items.push(
{
type: "submenu",
title: "Sort projects",
items: PROJECT_SORT_OPTIONS.map((option) => ({
type: "action",
title: option.label,
state: props.projectSortOrder === option.value ? "on" : "off",
onPress: () => props.onProjectSortOrderChange(option.value),
})),
},
{
type: "submenu",
title: "Sort threads",
items: THREAD_SORT_OPTIONS.map((option) => ({
type: "action",
title: option.label,
state: props.threadSortOrder === option.value ? "on" : "off",
onPress: () => props.onThreadSortOrderChange(option.value),
})),
},
);
}
return {
title: "Thread list options",
@@ -1,5 +1,4 @@
import {
DEFAULT_SIDEBAR_PROJECT_GROUPING_MODE,
DEFAULT_SIDEBAR_PROJECT_SORT_ORDER,
DEFAULT_SIDEBAR_THREAD_SORT_ORDER,
} from "@t3tools/contracts";
@@ -14,7 +13,6 @@ const defaults: HomeListOptions = {
? "updated_at"
: DEFAULT_SIDEBAR_PROJECT_SORT_ORDER,
threadSortOrder: DEFAULT_SIDEBAR_THREAD_SORT_ORDER,
projectGroupingMode: DEFAULT_SIDEBAR_PROJECT_GROUPING_MODE,
};
describe("home list options", () => {
@@ -22,10 +20,12 @@ describe("home list options", () => {
expect(hasCustomHomeListOptions(defaults)).toBe(false);
});
it("marks environment filters and grouping changes as customized", () => {
it("marks environment filters as customized", () => {
expect(
hasCustomHomeListOptions({ ...defaults, selectedEnvironmentId: "environment-1" as never }),
).toBe(true);
expect(hasCustomHomeListOptions({ ...defaults, projectGroupingMode: "separate" })).toBe(true);
expect(
hasCustomHomeListOptions({ ...defaults, selectedProjectKey: "environment-1:project-1" }),
).toBe(true);
});
});
@@ -4,7 +4,6 @@ import type {
SidebarThreadSortOrder,
} from "@t3tools/contracts";
import {
DEFAULT_SIDEBAR_PROJECT_GROUPING_MODE,
DEFAULT_SIDEBAR_PROJECT_SORT_ORDER,
DEFAULT_SIDEBAR_THREAD_SORT_ORDER,
} from "@t3tools/contracts";
@@ -26,9 +25,18 @@ export interface HomeListOptions {
readonly selectedEnvironmentId: EnvironmentId | null;
readonly projectSortOrder: HomeProjectSortOrder;
readonly threadSortOrder: SidebarThreadSortOrder;
}
export interface ResolvedHomeListOptions extends HomeListOptions {
readonly projectGroupingMode: SidebarProjectGroupingMode;
}
export function resolveProjectGroupingMode(
projectGroupingEnabled: boolean | undefined,
): SidebarProjectGroupingMode {
return projectGroupingEnabled === false ? "separate" : "repository";
}
export const PROJECT_SORT_OPTIONS: ReadonlyArray<{
readonly value: HomeProjectSortOrder;
readonly label: string;
@@ -45,28 +53,6 @@ export const THREAD_SORT_OPTIONS: ReadonlyArray<{
{ value: "created_at", label: "Created at" },
];
export const PROJECT_GROUPING_OPTIONS: ReadonlyArray<{
readonly value: SidebarProjectGroupingMode;
readonly label: string;
readonly subtitle: string;
}> = [
{
value: "repository",
label: "Group by repository",
subtitle: "Combine matching repositories across environments",
},
{
value: "repository_path",
label: "Group by repository path",
subtitle: "Combine only matching paths within a repository",
},
{
value: "separate",
label: "Keep separate",
subtitle: "Show every project path separately",
},
];
function defaultHomeListOptions(): HomeListOptions {
return {
selectedEnvironmentId: null,
@@ -75,34 +61,44 @@ function defaultHomeListOptions(): HomeListOptions {
? "updated_at"
: DEFAULT_SIDEBAR_PROJECT_SORT_ORDER,
threadSortOrder: DEFAULT_SIDEBAR_THREAD_SORT_ORDER,
projectGroupingMode: DEFAULT_SIDEBAR_PROJECT_GROUPING_MODE,
};
}
interface HomeListOptionsContextValue {
readonly options: HomeListOptions;
readonly setOptions: Dispatch<SetStateAction<HomeListOptions>>;
readonly projectGroupingMode: SidebarProjectGroupingMode;
}
const HomeListOptionsContext = createContext<HomeListOptionsContextValue | null>(null);
/** Keeps list preferences stable while the app moves between compact and split shells. */
export function HomeListOptionsProvider({ children }: PropsWithChildren) {
export function HomeListOptionsProvider({
children,
projectGroupingMode,
}: PropsWithChildren<{ readonly projectGroupingMode: SidebarProjectGroupingMode }>) {
const [options, setOptions] = useState<HomeListOptions>(defaultHomeListOptions);
const value = useMemo(() => ({ options, setOptions }), [options]);
const value = useMemo(
() => ({ options, setOptions, projectGroupingMode }),
[options, projectGroupingMode],
);
return createElement(HomeListOptionsContext, { value }, children);
}
export function hasCustomHomeListOptions(options: HomeListOptions): boolean {
export function hasCustomHomeListOptions(
options: HomeListOptions & {
readonly selectedProjectKey?: string | null;
},
): boolean {
const defaultProjectSortOrder =
DEFAULT_SIDEBAR_PROJECT_SORT_ORDER === "manual"
? "updated_at"
: DEFAULT_SIDEBAR_PROJECT_SORT_ORDER;
return (
options.selectedEnvironmentId !== null ||
(options.selectedProjectKey !== null && options.selectedProjectKey !== undefined) ||
options.projectSortOrder !== defaultProjectSortOrder ||
options.threadSortOrder !== DEFAULT_SIDEBAR_THREAD_SORT_ORDER ||
options.projectGroupingMode !== DEFAULT_SIDEBAR_PROJECT_GROUPING_MODE
options.threadSortOrder !== DEFAULT_SIDEBAR_THREAD_SORT_ORDER
);
}
@@ -116,10 +112,14 @@ export function useHomeListOptions(availableEnvironmentIds: ReadonlySet<Environm
availableEnvironmentIds.has(options.selectedEnvironmentId)
? options.selectedEnvironmentId
: null;
const resolvedOptions =
const availableOptions =
selectedEnvironmentId === options.selectedEnvironmentId
? options
: { ...options, selectedEnvironmentId };
const resolvedOptions: ResolvedHomeListOptions = {
...availableOptions,
projectGroupingMode: shared?.projectGroupingMode ?? "repository",
};
const setSelectedEnvironmentId = useCallback((value: EnvironmentId | null) => {
setOptions((current) => ({ ...current, selectedEnvironmentId: value }));
@@ -130,15 +130,10 @@ export function useHomeListOptions(availableEnvironmentIds: ReadonlySet<Environm
const setThreadSortOrder = useCallback((value: SidebarThreadSortOrder) => {
setOptions((current) => ({ ...current, threadSortOrder: value }));
}, []);
const setProjectGroupingMode = useCallback((value: SidebarProjectGroupingMode) => {
setOptions((current) => ({ ...current, projectGroupingMode: value }));
}, []);
return {
options: resolvedOptions,
setSelectedEnvironmentId,
setProjectSortOrder,
setThreadSortOrder,
setProjectGroupingMode,
} as const;
}
@@ -5,7 +5,11 @@ import type {
import { EnvironmentId, ProjectId, ProviderInstanceId, ThreadId } from "@t3tools/contracts";
import { describe, expect, it } from "vite-plus/test";
import { buildHomeThreadGroups } from "./homeThreadList";
import {
buildHomeProjectScopes,
buildHomeThreadGroups,
sortHomeProjectScopes,
} from "./homeThreadList";
function makeProject(
input: Partial<EnvironmentProject> & Pick<EnvironmentProject, "environmentId" | "id" | "title">,
@@ -67,6 +71,308 @@ function buildGroups(
}
describe("buildHomeThreadGroups", () => {
it("builds one v2 scope for the same repository across environments", () => {
const localEnvironmentId = EnvironmentId.make("environment-local");
const remoteEnvironmentId = EnvironmentId.make("environment-remote");
const repositoryIdentity = {
canonicalKey: "github.com/pingdotgg/t3code",
locator: {
source: "git-remote" as const,
remoteName: "origin",
remoteUrl: "[email protected]:pingdotgg/t3code.git",
},
};
const projects = [
makeProject({
environmentId: localEnvironmentId,
id: ProjectId.make("project-local"),
title: "t3code",
repositoryIdentity,
}),
makeProject({
environmentId: remoteEnvironmentId,
id: ProjectId.make("project-remote"),
title: "t3code",
repositoryIdentity,
}),
];
const scopes = buildHomeProjectScopes({
projects,
environmentId: null,
projectGroupingMode: "repository",
});
expect(scopes).toHaveLength(1);
expect(scopes[0]?.projects).toEqual(projects);
expect(scopes[0]?.projectRefs).toEqual(
projects.map((project) => ({
environmentId: project.environmentId,
projectId: project.id,
})),
);
});
it("routes stale duplicate project refs through the canonical repository group", () => {
const localEnvironmentId = EnvironmentId.make("environment-local");
const remoteEnvironmentId = EnvironmentId.make("environment-remote");
const repositoryIdentity = {
canonicalKey: "github.com/pingdotgg/t3code",
locator: {
source: "git-remote" as const,
remoteName: "origin",
remoteUrl: "[email protected]:pingdotgg/t3code.git",
},
};
const local = makeProject({
id: ProjectId.make("project-local"),
environmentId: localEnvironmentId,
title: "t3code",
workspaceRoot: "/workspaces/t3code",
repositoryIdentity,
});
const stale = makeProject({
environmentId: remoteEnvironmentId,
id: ProjectId.make("project-stale"),
title: "t3code",
workspaceRoot: "/remote/t3code",
updatedAt: "2026-06-01T00:00:00.000Z",
});
const canonicalRemote = makeProject({
environmentId: remoteEnvironmentId,
id: ProjectId.make("project-canonical-remote"),
title: "t3code",
workspaceRoot: "/remote/t3code/",
repositoryIdentity,
updatedAt: "2026-06-02T00:00:00.000Z",
});
const projects = [local, stale, canonicalRemote];
const staleThread = makeThread({
environmentId: remoteEnvironmentId,
id: ThreadId.make("thread-stale-project-ref"),
projectId: stale.id,
title: "Still visible",
updatedAt: "2026-06-03T00:00:00.000Z",
});
const scopes = buildHomeProjectScopes({
projects,
environmentId: null,
projectGroupingMode: "repository",
});
const groups = buildGroups(projects, [staleThread]);
expect(scopes).toHaveLength(1);
expect(scopes[0]?.projects.map((project) => project.id)).toEqual([
local.id,
canonicalRemote.id,
]);
expect(scopes[0]?.projectRefs.map((projectRef) => projectRef.projectId)).toEqual([
local.id,
stale.id,
canonicalRemote.id,
]);
expect(groups).toHaveLength(1);
expect(groups[0]?.threads.map((thread) => thread.id)).toEqual([staleThread.id]);
expect(groups[0]?.newThreadTarget?.id).toBe(canonicalRemote.id);
});
it("keeps repository identity from an older duplicate when the freshness winner lacks it", () => {
const localEnvironmentId = EnvironmentId.make("environment-local");
const remoteEnvironmentId = EnvironmentId.make("environment-remote");
const repositoryIdentity = {
canonicalKey: "github.com/pingdotgg/t3code",
locator: {
source: "git-remote" as const,
remoteName: "origin",
remoteUrl: "[email protected]:pingdotgg/t3code.git",
},
};
const projects = [
makeProject({
environmentId: localEnvironmentId,
id: ProjectId.make("project-local"),
title: "t3code",
repositoryIdentity,
}),
makeProject({
environmentId: remoteEnvironmentId,
id: ProjectId.make("project-remote-with-identity"),
title: "t3code",
workspaceRoot: "/remote/t3code",
repositoryIdentity,
updatedAt: "2026-06-01T00:00:00.000Z",
}),
makeProject({
environmentId: remoteEnvironmentId,
id: ProjectId.make("project-remote-fresh"),
title: "t3code",
workspaceRoot: "/remote/t3code/",
updatedAt: "2026-06-02T00:00:00.000Z",
}),
];
const scopes = buildHomeProjectScopes({
projects,
environmentId: null,
projectGroupingMode: "repository",
});
expect(scopes).toHaveLength(1);
expect(scopes[0]?.representative.id).toBe(ProjectId.make("project-local"));
expect(scopes[0]?.projects.map((project) => project.id)).toContain(
ProjectId.make("project-remote-fresh"),
);
expect(scopes[0]?.projectRefs).toHaveLength(3);
});
it("sorts v2 project scopes by their grouped thread activity", () => {
const environmentId = EnvironmentId.make("environment-1");
const olderProject = makeProject({
environmentId,
id: ProjectId.make("project-older"),
title: "Older project",
});
const newerProject = makeProject({
environmentId,
id: ProjectId.make("project-newer"),
title: "Newer project",
});
const scopes = buildHomeProjectScopes({
projects: [newerProject, olderProject],
environmentId: null,
projectGroupingMode: "separate",
});
expect(
sortHomeProjectScopes({
scopes,
threads: [
makeThread({
environmentId,
id: ThreadId.make("thread-older-project"),
projectId: olderProject.id,
title: "Most recently active",
updatedAt: "2026-06-03T00:00:00.000Z",
}),
makeThread({
environmentId,
id: ThreadId.make("thread-newer-project"),
projectId: newerProject.id,
title: "Less recently active",
updatedAt: "2026-06-02T00:00:00.000Z",
}),
],
pendingTasks: [],
projectSortOrder: "updated_at",
}).map((scope) => scope.representative.id),
).toEqual([olderProject.id, newerProject.id]);
});
it("sorts invalid project creation timestamps after valid ones", () => {
const environmentId = EnvironmentId.make("environment-1");
const invalidProject = makeProject({
environmentId,
id: ProjectId.make("project-invalid"),
title: "A invalid timestamp",
createdAt: "invalid",
});
const validProject = makeProject({
environmentId,
id: ProjectId.make("project-valid"),
title: "Z valid timestamp",
createdAt: "2026-06-02T00:00:00.000Z",
});
const scopes = buildHomeProjectScopes({
projects: [invalidProject, validProject],
environmentId: null,
projectGroupingMode: "separate",
});
expect(
sortHomeProjectScopes({
scopes,
threads: [],
pendingTasks: [],
projectSortOrder: "created_at",
}).map((scope) => scope.representative.id),
).toEqual([validProject.id, invalidProject.id]);
});
it("uses the freshest member when a grouped scope has no activity", () => {
const localEnvironmentId = EnvironmentId.make("environment-local");
const remoteEnvironmentId = EnvironmentId.make("environment-remote");
const repositoryIdentity = {
canonicalKey: "github.com/pingdotgg/t3code",
locator: {
source: "git-remote" as const,
remoteName: "origin",
remoteUrl: "[email protected]:pingdotgg/t3code.git",
},
};
const olderMember = makeProject({
environmentId: localEnvironmentId,
id: ProjectId.make("project-older-member"),
title: "t3code",
updatedAt: "2026-06-01T00:00:00.000Z",
repositoryIdentity,
});
const newerMember = makeProject({
environmentId: remoteEnvironmentId,
id: ProjectId.make("project-newer-member"),
title: "t3code",
updatedAt: "2026-06-03T00:00:00.000Z",
repositoryIdentity,
});
const otherProject = makeProject({
environmentId: localEnvironmentId,
id: ProjectId.make("project-other"),
title: "other",
updatedAt: "2026-06-02T00:00:00.000Z",
});
const scopes = buildHomeProjectScopes({
projects: [olderMember, newerMember, otherProject],
environmentId: null,
projectGroupingMode: "repository",
});
expect(
sortHomeProjectScopes({
scopes,
threads: [],
pendingTasks: [],
projectSortOrder: "updated_at",
})[0]?.key,
).toBe(scopes.find((scope) => scope.projects.length === 2)?.key);
});
it("does not merge unrelated repositories that share a title", () => {
const environmentId = EnvironmentId.make("environment-1");
const projects = ["one", "two"].map((name) =>
makeProject({
environmentId,
id: ProjectId.make(`project-${name}`),
title: "app",
repositoryIdentity: {
canonicalKey: `github.com/example/${name}`,
locator: {
source: "git-remote" as const,
remoteName: "origin",
remoteUrl: `[email protected]:example/${name}.git`,
},
},
}),
);
expect(
buildHomeProjectScopes({
projects,
environmentId: null,
projectGroupingMode: "repository",
}),
).toHaveLength(2);
});
it("sorts the newest thread first regardless of snapshot order", () => {
const environmentId = EnvironmentId.make("environment-1");
const project = makeProject({
+187 -25
View File
@@ -1,14 +1,20 @@
import {
deriveLogicalProjectKey,
derivePhysicalProjectKey,
deriveProjectGroupLabel,
} from "@t3tools/client-runtime/state/project-grouping";
import type {
EnvironmentProject,
EnvironmentThreadShell,
} from "@t3tools/client-runtime/state/shell";
import { getThreadSortTimestamp, sortThreads } from "@t3tools/client-runtime/state/thread-sort";
import {
getThreadSortTimestamp,
sortThreads,
toSortableTimestamp,
} from "@t3tools/client-runtime/state/thread-sort";
import type {
EnvironmentId,
ScopedProjectRef,
SidebarProjectGroupingMode,
SidebarProjectSortOrder,
SidebarThreadSortOrder,
@@ -22,6 +28,164 @@ import type { PendingNewTask } from "../../state/use-pending-new-tasks";
export type HomeProjectSortOrder = Exclude<SidebarProjectSortOrder, "manual">;
export interface HomeProjectScope {
readonly key: string;
readonly title: string;
readonly representative: EnvironmentProject;
readonly projects: ReadonlyArray<EnvironmentProject>;
readonly projectRefs: ReadonlyArray<ScopedProjectRef>;
}
function getProjectFreshnessTimestamp(project: EnvironmentProject): number {
return toSortableTimestamp(project.updatedAt) ?? toSortableTimestamp(project.createdAt) ?? 0;
}
function getProjectSortTimestamp(
project: EnvironmentProject,
sortOrder: HomeProjectSortOrder,
): number {
return sortOrder === "created_at"
? (toSortableTimestamp(project.createdAt) ?? Number.NEGATIVE_INFINITY)
: (toSortableTimestamp(project.updatedAt) ??
toSortableTimestamp(project.createdAt) ??
Number.NEGATIVE_INFINITY);
}
export function buildHomeProjectScopes(input: {
readonly projects: ReadonlyArray<EnvironmentProject>;
readonly environmentId: EnvironmentId | null;
readonly projectGroupingMode: SidebarProjectGroupingMode;
}): ReadonlyArray<HomeProjectScope> {
const projects = input.projects.filter(
(project) => input.environmentId === null || project.environmentId === input.environmentId,
);
const projectsByPhysicalKey = new Map<string, EnvironmentProject[]>();
for (const project of projects) {
const physicalKey = derivePhysicalProjectKey(project);
const existing = projectsByPhysicalKey.get(physicalKey);
if (existing) existing.push(project);
else projectsByPhysicalKey.set(physicalKey, [project]);
}
const winnersByPhysicalKey = new Map<
string,
{ readonly key: string; readonly project: EnvironmentProject }
>();
for (const [physicalKey, members] of projectsByPhysicalKey) {
const project = members.reduce((winner, candidate) => {
const freshnessDelta =
getProjectFreshnessTimestamp(candidate) - getProjectFreshnessTimestamp(winner);
return freshnessDelta > 0 || (freshnessDelta === 0 && candidate.id > winner.id)
? candidate
: winner;
});
const identitySource = members.find((member) => member.repositoryIdentity !== null) ?? project;
winnersByPhysicalKey.set(physicalKey, {
key: deriveLogicalProjectKey(identitySource, { groupingMode: input.projectGroupingMode }),
project,
});
}
const groups = new Map<string, EnvironmentProject[]>();
for (const { key, project } of winnersByPhysicalKey.values()) {
const existing = groups.get(key);
if (existing) existing.push(project);
else groups.set(key, [project]);
}
const projectRefsByGroup = new Map<string, ScopedProjectRef[]>();
const seenProjectRefs = new Set<string>();
for (const project of projects) {
const refKey = scopedProjectKey(project.environmentId, project.id);
if (seenProjectRefs.has(refKey)) continue;
seenProjectRefs.add(refKey);
const key =
winnersByPhysicalKey.get(derivePhysicalProjectKey(project))?.key ??
deriveLogicalProjectKey(project, { groupingMode: input.projectGroupingMode });
const refs = projectRefsByGroup.get(key);
const projectRef = { environmentId: project.environmentId, projectId: project.id };
if (refs) refs.push(projectRef);
else projectRefsByGroup.set(key, [projectRef]);
}
return Array.from(groups, ([key, projects]) => {
const representative = projects[0]!;
return {
key,
title:
projects.length > 1
? deriveProjectGroupLabel({ representative, members: projects })
: representative.title,
representative,
projects,
projectRefs: projectRefsByGroup.get(key) ?? [],
};
});
}
export function sortHomeProjectScopes(input: {
readonly scopes: ReadonlyArray<HomeProjectScope>;
readonly threads: ReadonlyArray<EnvironmentThreadShell>;
readonly pendingTasks: ReadonlyArray<PendingNewTask>;
readonly projectSortOrder: HomeProjectSortOrder;
}): ReadonlyArray<HomeProjectScope> {
const scopeKeyByProjectRef = new Map(
input.scopes.flatMap((scope) =>
scope.projectRefs.map(
(projectRef) =>
[scopedProjectKey(projectRef.environmentId, projectRef.projectId), scope.key] as const,
),
),
);
const latestActivityByScope = new Map<string, number>();
const recordActivity = (scopeKey: string | undefined, timestamp: number) => {
if (!scopeKey || !Number.isFinite(timestamp)) return;
latestActivityByScope.set(
scopeKey,
Math.max(latestActivityByScope.get(scopeKey) ?? Number.NEGATIVE_INFINITY, timestamp),
);
};
for (const thread of input.threads) {
if (thread.archivedAt !== null) continue;
recordActivity(
scopeKeyByProjectRef.get(scopedProjectKey(thread.environmentId, thread.projectId)),
getThreadSortTimestamp(thread, input.projectSortOrder),
);
}
for (const pendingTask of input.pendingTasks) {
recordActivity(
scopeKeyByProjectRef.get(
scopedProjectKey(pendingTask.message.environmentId, pendingTask.creation.projectId),
),
Date.parse(pendingTask.message.createdAt),
);
}
return Arr.sort(
input.scopes,
Order.mapInput(
Order.Struct({
timestamp: Order.flip(Order.Number),
title: Order.String,
key: Order.String,
}),
(scope: HomeProjectScope) => ({
timestamp:
latestActivityByScope.get(scope.key) ??
Math.max(
...scope.projects.map((project) =>
getProjectSortTimestamp(project, input.projectSortOrder),
),
),
title: scope.title,
key: scope.key,
}),
),
);
}
/**
* Default home view only surfaces threads active within this window, to keep the
* screen compact while keeping recent work visible.
@@ -103,22 +267,18 @@ export function buildHomeThreadGroups(input: {
const groups = new Map<string, MutableHomeThreadGroup>();
const groupKeyByProjectKey = new Map<string, string>();
for (const project of input.projects) {
if (input.environmentId !== null && project.environmentId !== input.environmentId) {
continue;
}
const groupKey = deriveLogicalProjectKey(project, {
groupingMode: input.projectGroupingMode,
for (const scope of buildHomeProjectScopes(input)) {
groups.set(scope.key, {
key: scope.key,
projects: [...scope.projects],
pendingTasks: [],
threads: [],
});
const physicalKey = scopedProjectKey(project.environmentId, project.id);
groupKeyByProjectKey.set(physicalKey, groupKey);
const existing = groups.get(groupKey);
if (existing) {
existing.projects.push(project);
} else {
groups.set(groupKey, { key: groupKey, projects: [project], pendingTasks: [], threads: [] });
for (const projectRef of scope.projectRefs) {
groupKeyByProjectKey.set(
scopedProjectKey(projectRef.environmentId, projectRef.projectId),
scope.key,
);
}
}
@@ -215,19 +375,21 @@ export function buildHomeThreadGroups(input: {
? selectRecentThreads(sortedThreads, input.threadSortOrder, now)
: sortedThreads;
// Sorted newest-first, so the first thread whose project is a group member
// marks the machine the user last worked on.
const lastActiveProject = Arr.findFirst(sortedThreads, (thread) =>
group.projects.some(
(project) =>
project.environmentId === thread.environmentId && project.id === thread.projectId,
),
).pipe(
// A stale project id still resolves to the canonical member with the same
// environment/path, so quick creation follows the machine with the newest activity.
const lastActiveProject = Arr.head(sortedThreads).pipe(
Option.flatMap((thread) =>
Arr.findFirst(
input.projects,
(project) =>
project.environmentId === thread.environmentId && project.id === thread.projectId,
),
),
Option.flatMap((threadProject) =>
Arr.findFirst(
group.projects,
(project) =>
project.environmentId === thread.environmentId && project.id === thread.projectId,
derivePhysicalProjectKey(project) === derivePhysicalProjectKey(threadProject),
),
),
Option.getOrNull,
@@ -36,6 +36,8 @@ import { AppText as Text } from "../../components/AppText";
const ACTION_ITEM_WIDTH = 58;
const ACTION_CIRCLE_SIZE = 36;
const ACTION_ICON_SIZE = 15;
const COMPACT_ACTION_CIRCLE_SIZE = 28;
const COMPACT_ACTION_ICON_SIZE = 13;
export const THREAD_SWIPE_ACTIONS_WIDTH = ACTION_ITEM_WIDTH * 2;
export const THREAD_SWIPE_SPRING = {
@@ -163,6 +165,9 @@ export function useSwipeableScrollGate(options?: {
export function ThreadSwipeable(props: {
readonly backgroundColor: ColorValue;
readonly children: (close: () => void) => ReactNode;
/** Uses action visuals that fit inside compact 44pt rows. The press target
* still spans the row's full height and width. */
readonly compactActions?: boolean;
readonly containerStyle?: StyleProp<ViewStyle>;
/** Disables NEW swipe activations (e.g. while the list scrolls). */
readonly enabled?: boolean;
@@ -258,6 +263,7 @@ export function ThreadSwipeable(props: {
renderRightActions={(_progress, translation, methods) => (
<ThreadSwipeActions
backgroundColor={props.backgroundColor}
compact={props.compactActions === true}
fullSwipeAction={props.fullSwipeAction ?? "delete"}
fullSwipeThreshold={fullSwipeThreshold}
onDelete={props.onDelete}
@@ -285,6 +291,7 @@ export function ThreadSwipeable(props: {
function SwipeActionButton(props: {
readonly accessibilityLabel: string;
readonly backgroundColor: string;
readonly compact: boolean;
readonly entryRange: readonly [number, number];
readonly fullSwipeThreshold: number;
readonly icon: ComponentProps<typeof SymbolView>["name"];
@@ -293,6 +300,8 @@ function SwipeActionButton(props: {
readonly stretchesOnFullSwipe: boolean;
readonly translation: SharedValue<number>;
}) {
const circleSize = props.compact ? COMPACT_ACTION_CIRCLE_SIZE : ACTION_CIRCLE_SIZE;
const iconSize = props.compact ? COMPACT_ACTION_ICON_SIZE : ACTION_ICON_SIZE;
const actionStyle = useAnimatedStyle(() => {
const reveal = Math.max(-props.translation.value, 0);
const entryProgress = interpolate(reveal, props.entryRange, [0, 1], Extrapolation.CLAMP);
@@ -324,7 +333,7 @@ function SwipeActionButton(props: {
return {
transform: [{ translateX: -stretch }],
width: ACTION_CIRCLE_SIZE + stretch,
width: circleSize + stretch,
};
});
const iconStyle = useAnimatedStyle(() => {
@@ -386,13 +395,13 @@ function SwipeActionButton(props: {
width: "100%",
})}
>
<View style={{ height: ACTION_CIRCLE_SIZE, width: ACTION_CIRCLE_SIZE }}>
<View style={{ height: circleSize, width: circleSize }}>
<Animated.View
style={[
{
backgroundColor: props.backgroundColor,
borderRadius: 999,
height: ACTION_CIRCLE_SIZE,
height: circleSize,
left: 0,
position: "absolute",
top: 0,
@@ -404,25 +413,25 @@ function SwipeActionButton(props: {
style={[
{
alignItems: "center",
height: ACTION_CIRCLE_SIZE,
height: circleSize,
justifyContent: "center",
left: 0,
position: "absolute",
top: 0,
width: ACTION_CIRCLE_SIZE,
width: circleSize,
},
iconStyle,
]}
>
<SymbolView
name={props.icon}
size={ACTION_ICON_SIZE}
tintColor="#ffffff"
type="monochrome"
/>
<SymbolView name={props.icon} size={iconSize} tintColor="#ffffff" type="monochrome" />
</Animated.View>
</View>
<Animated.View style={[{ paddingTop: 2 }, labelStyle]}>
<Animated.View
style={[
{ height: 14, justifyContent: "center", paddingTop: props.compact ? 0 : 2 },
labelStyle,
]}
>
<Text className="text-3xs font-t3-medium text-foreground-muted" numberOfLines={1}>
{props.label}
</Text>
@@ -434,6 +443,7 @@ function SwipeActionButton(props: {
export function ThreadSwipeActions(props: {
readonly backgroundColor: ColorValue;
readonly compact: boolean;
readonly fullSwipeAction?: "delete" | "primary";
readonly fullSwipeThreshold: number;
readonly onDelete: () => void;
@@ -466,6 +476,7 @@ export function ThreadSwipeActions(props: {
<SwipeActionButton
accessibilityLabel={props.primaryAction.accessibilityLabel}
backgroundColor="#007aff"
compact={props.compact}
entryRange={[ACTION_ITEM_WIDTH * 0.55, THREAD_SWIPE_ACTIONS_WIDTH * 0.85]}
fullSwipeThreshold={props.fullSwipeThreshold}
icon={props.primaryAction.icon}
@@ -477,6 +488,7 @@ export function ThreadSwipeActions(props: {
<SwipeActionButton
accessibilityLabel={`Delete ${props.threadTitle}`}
backgroundColor="#ff2d55"
compact={props.compact}
entryRange={[8, ACTION_ITEM_WIDTH * 0.72]}
fullSwipeThreshold={props.fullSwipeThreshold}
icon="trash"
@@ -2,7 +2,8 @@ import type {
EnvironmentProject,
EnvironmentThreadShell,
} from "@t3tools/client-runtime/state/shell";
import { EnvironmentId, ThreadId } from "@t3tools/contracts";
import { EnvironmentId, ThreadId, type SidebarProjectGroupingMode } from "@t3tools/contracts";
import { useAtomValue } from "@effect/atom-react";
import { useFocusEffect } from "@react-navigation/native";
import {
NavigationContext,
@@ -22,6 +23,7 @@ import {
} from "react";
import { useWindowDimensions, View } from "react-native";
import Animated, { useAnimatedStyle, useSharedValue, withTiming } from "react-native-reanimated";
import { AsyncResult } from "effect/unstable/reactivity";
import {
deriveFileInspectorPaneLayout,
@@ -34,11 +36,12 @@ import {
} from "../../lib/layout";
import { resolveThreadSelectionNavigationAction } from "../../lib/adaptive-navigation";
import { scopedThreadKey } from "../../lib/scopedEntities";
import { mobilePreferencesAtom } from "../../state/preferences";
import {
parseActiveThreadPath,
useHardwareKeyboardCommand,
} from "../keyboard/hardwareKeyboardCommands";
import { HomeListOptionsProvider } from "../home/home-list-options";
import { HomeListOptionsProvider, resolveProjectGroupingMode } from "../home/home-list-options";
import { ThreadNavigationSidebar } from "../threads/ThreadNavigationSidebar";
import { WORKSPACE_PANE_TIMING } from "./workspace-pane-animation";
import { WorkspaceInspectorPane } from "./workspace-inspector-pane";
@@ -184,6 +187,31 @@ export function AdaptiveWorkspaceLayout(props: {
readonly children: ReactNode;
readonly pathname: string;
}) {
const preferencesResult = useAtomValue(mobilePreferencesAtom);
if (!AsyncResult.isSuccess(preferencesResult)) {
return AsyncResult.isFailure(preferencesResult) ? (
<AdaptiveWorkspaceLayoutContent {...props} projectGroupingMode="repository" />
) : null;
}
return (
<AdaptiveWorkspaceLayoutContent
{...props}
projectGroupingMode={resolveProjectGroupingMode(
preferencesResult.value.projectGroupingEnabled,
)}
/>
);
}
function AdaptiveWorkspaceLayoutContent(
props: {
readonly children: ReactNode;
readonly pathname: string;
} & {
readonly projectGroupingMode: SidebarProjectGroupingMode;
},
) {
const projectGroupingMode = props.projectGroupingMode;
const { width, height } = useWindowDimensions();
const pathname = props.pathname;
const navigation = useNavigation();
@@ -474,7 +502,7 @@ export function AdaptiveWorkspaceLayout(props: {
);
return (
<HomeListOptionsProvider>
<HomeListOptionsProvider projectGroupingMode={projectGroupingMode}>
<AdaptiveWorkspaceContext.Provider value={contextValue}>
<View testID="adaptive-workspace-layout" className="flex-1 flex-row">
{shouldRenderPrimarySidebar && layout.listPaneWidth !== null ? (
@@ -119,6 +119,8 @@ function LocalSettingsRouteScreen() {
/>
</SettingsSection>
<GeneralSettingsSection />
<SettingsSection title="Appearance">
<SettingsRow icon="paintbrush" label="Appearance" target="SettingsAppearance" />
</SettingsSection>
@@ -504,6 +506,8 @@ function ConfiguredSettingsRouteScreen() {
/>
</SettingsSection>
<GeneralSettingsSection />
<SettingsSection title="Appearance">
<SettingsRow icon="paintbrush" label="Appearance" target="SettingsAppearance" />
</SettingsSection>
@@ -518,6 +522,25 @@ function ConfiguredSettingsRouteScreen() {
);
}
function GeneralSettingsSection() {
const preferencesResult = useAtomValue(mobilePreferencesAtom);
const savePreferences = useAtomSet(updateMobilePreferencesAtom);
const projectGroupingEnabled = AsyncResult.isSuccess(preferencesResult)
? preferencesResult.value.projectGroupingEnabled !== false
: true;
return (
<SettingsSection title="General">
<SettingsSwitchRow
icon="folder"
label="Project Grouping"
value={projectGroupingEnabled}
onValueChange={(value) => savePreferences({ projectGroupingEnabled: value })}
/>
</SettingsSection>
);
}
/**
* Device-local beta toggles. Mobile has no client-settings sync, so this is
* the counterpart of web's Settings → Beta backed by mobile preferences.
@@ -582,10 +582,13 @@ export function NewTaskDraftScreen(props: {
? "Approve actions"
: flow.runtimeMode === "auto-accept-edits"
? "Auto-accept edits"
: "Full access",
: flow.runtimeMode === "auto"
? "Auto"
: "Full access",
subactions: [
{ id: "options:runtime:approval-required", title: "Approve actions" },
{ id: "options:runtime:auto-accept-edits", title: "Auto-accept edits" },
{ id: "options:runtime:auto", title: "Auto" },
{ id: "options:runtime:full-access", title: "Full access" },
].map((option) => {
const value = option.id.replace("options:runtime:", "");
@@ -638,10 +638,13 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
? "Approve actions"
: currentRuntimeMode === "auto-accept-edits"
? "Auto-accept edits"
: "Full access",
: currentRuntimeMode === "auto"
? "Auto"
: "Full access",
subactions: [
{ id: "options:runtime:approval-required", title: "Approve actions" },
{ id: "options:runtime:auto-accept-edits", title: "Auto-accept edits" },
{ id: "options:runtime:auto", title: "Auto" },
{ id: "options:runtime:full-access", title: "Full access" },
].map((option) => {
const value = option.id.replace("options:runtime:", "");
@@ -5,9 +5,12 @@ import type {
} from "@t3tools/client-runtime/state/shell";
import { LegendList } from "@legendapp/list/react-native";
import type { MenuAction } from "@react-native-menu/menu";
import { useCallback, useMemo, useRef, useState, type ReactNode } from "react";
import { useAtomValue } from "@effect/atom-react";
import { AsyncResult } from "effect/unstable/reactivity";
import type { EnvironmentId } from "@t3tools/contracts";
import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from "react";
import type { LayoutChangeEvent, NativeScrollEvent, NativeSyntheticEvent } from "react-native";
import { Platform, StyleSheet, TextInput, View, useColorScheme } from "react-native";
import { Platform, Pressable, StyleSheet, TextInput, View, useColorScheme } from "react-native";
import { Gesture, GestureDetector } from "react-native-gesture-handler";
import type { SwipeableMethods } from "react-native-gesture-handler/ReanimatedSwipeable";
import { useSafeAreaInsets } from "react-native-safe-area-context";
@@ -22,13 +25,14 @@ import { NativeStackScreenOptions } from "../../native/StackHeader";
import { scopedProjectKey, scopedThreadKey } from "../../lib/scopedEntities";
import { useThemeColor } from "../../lib/useThemeColor";
import { useProjects, useThreadShells } from "../../state/entities";
import { usePendingNewTasks } from "../../state/use-pending-new-tasks";
import { mobilePreferencesAtom } from "../../state/preferences";
import { environmentServerConfigsAtom } from "../../state/server";
import { usePendingNewTasks, type PendingNewTask } from "../../state/use-pending-new-tasks";
import { useWorkspaceState } from "../../state/workspace";
import { useSavedRemoteConnections } from "../../state/use-remote-environment-registry";
import { useHardwareKeyboardCommand } from "../keyboard/hardwareKeyboardCommands";
import {
hasCustomHomeListOptions,
PROJECT_GROUPING_OPTIONS,
PROJECT_SORT_OPTIONS,
THREAD_SORT_OPTIONS,
useHomeListOptions,
@@ -43,7 +47,7 @@ import {
type HomeGroupDisplayState,
type HomeListItem,
} from "../home/homeListItems";
import { buildHomeThreadGroups } from "../home/homeThreadList";
import { buildHomeProjectScopes, buildHomeThreadGroups } from "../home/homeThreadList";
import { SwipeableScrollGateProvider, useSwipeableScrollGate } from "../home/thread-swipe-actions";
import { usePendingTaskListActions } from "../home/usePendingTaskListActions";
import { useThreadListActions } from "../home/useThreadListActions";
@@ -59,6 +63,27 @@ import {
ThreadListRow,
ThreadListShowMoreRow,
} from "./thread-list-items";
import { ThreadListV2Row } from "./thread-list-v2-items";
import {
buildThreadListV2Items,
THREAD_LIST_V2_SETTLED_INITIAL_COUNT,
THREAD_LIST_V2_SETTLED_PAGE_COUNT,
type ThreadListV2Item,
} from "./threadListV2";
/** The sidebar list serves both lists: v1 grouped items or, when the Thread
List v2 beta is on, queued offline tasks, flat v2 rows, and a settled
"Show more" pager. */
type SidebarListItem =
| HomeListItem
| {
readonly type: "v2-pending-task";
readonly key: string;
readonly pendingTask: PendingNewTask;
readonly isLast: boolean;
}
| { readonly type: "v2-thread"; readonly key: string; readonly item: ThreadListV2Item }
| { readonly type: "v2-show-more"; readonly key: string; readonly hiddenCount: number };
/**
* Shared capsule behind the sidebar header buttons — a native liquid-glass
@@ -169,7 +194,12 @@ function ThreadNavigationSidebarPane(
const openSwipeableRef = useRef<SwipeableMethods | null>(null);
const headerIsOverContentRef = useRef(false);
const sidebarScrollGesture = useMemo(() => Gesture.Native(), []);
const { archiveThread, confirmDeleteThread } = useThreadListActions();
const { archiveThread, confirmDeleteThread, settleThread, unsettleThread } =
useThreadListActions();
const preferencesResult = useAtomValue(mobilePreferencesAtom);
const threadListV2Enabled =
AsyncResult.isSuccess(preferencesResult) &&
preferencesResult.value.threadListV2Enabled === true;
const pendingTasks = usePendingNewTasks();
const { openPendingTask, confirmDeletePendingTask } = usePendingTaskListActions();
const environments = useMemo(
@@ -186,26 +216,94 @@ function ThreadNavigationSidebarPane(
() => new Set(environments.map((environment) => environment.environmentId)),
[environments],
);
const {
options,
setSelectedEnvironmentId,
setProjectGroupingMode,
setProjectSortOrder,
setThreadSortOrder,
} = useHomeListOptions(availableEnvironmentIds);
const { options, setSelectedEnvironmentId, setProjectSortOrder, setThreadSortOrder } =
useHomeListOptions(availableEnvironmentIds);
const [selectedProjectKey, setSelectedProjectKey] = useState<string | null>(null);
const projectScopes = useMemo(
() =>
buildHomeProjectScopes({
projects,
environmentId: options.selectedEnvironmentId,
projectGroupingMode: options.projectGroupingMode,
}),
[options.projectGroupingMode, options.selectedEnvironmentId, projects],
);
const projectFilterOptions = useMemo(
() =>
projectScopes.map((scope) => ({
key: scope.key,
label: scope.title,
})),
[projectScopes],
);
const selectedProjectScope = useMemo(
() =>
selectedProjectKey === null
? null
: (projectScopes.find((scope) => scope.key === selectedProjectKey) ?? null),
[projectScopes, selectedProjectKey],
);
useEffect(() => {
if (
selectedProjectKey !== null &&
!projectFilterOptions.some((project) => project.key === selectedProjectKey)
) {
setSelectedProjectKey(null);
}
}, [projectFilterOptions, selectedProjectKey]);
const selectedProjectRefs = useMemo(
() =>
selectedProjectScope === null
? null
: new Set(
selectedProjectScope.projectRefs.map((projectRef) =>
scopedProjectKey(projectRef.environmentId, projectRef.projectId),
),
),
[selectedProjectScope],
);
const scopedProjects = useMemo(
() =>
selectedProjectRefs === null
? projects
: projects.filter((project) =>
selectedProjectRefs.has(scopedProjectKey(project.environmentId, project.id)),
),
[projects, selectedProjectRefs],
);
const scopedThreads = useMemo(
() =>
selectedProjectRefs === null
? threads
: threads.filter((thread) =>
selectedProjectRefs.has(scopedProjectKey(thread.environmentId, thread.projectId)),
),
[selectedProjectRefs, threads],
);
const scopedPendingTasks = useMemo(
() =>
selectedProjectRefs === null
? pendingTasks
: pendingTasks.filter((pendingTask) =>
selectedProjectRefs.has(
scopedProjectKey(pendingTask.message.environmentId, pendingTask.creation.projectId),
),
),
[pendingTasks, selectedProjectRefs],
);
const groups = useMemo(
() =>
buildHomeThreadGroups({
projects,
threads,
pendingTasks,
projects: scopedProjects,
threads: scopedThreads,
pendingTasks: scopedPendingTasks,
environmentId: options.selectedEnvironmentId,
searchQuery: props.searchQuery,
projectSortOrder: options.projectSortOrder,
threadSortOrder: options.threadSortOrder,
projectGroupingMode: options.projectGroupingMode,
}),
[options, pendingTasks, projects, props.searchQuery, threads],
[options, props.searchQuery, scopedPendingTasks, scopedProjects, scopedThreads],
);
const [groupDisplayStates, setGroupDisplayStates] = useState<
ReadonlyMap<string, HomeGroupDisplayState>
@@ -237,6 +335,148 @@ function ThreadNavigationSidebarPane(
}
return map;
}, [projects]);
const projectByKey = useMemo(() => {
const map = new Map<string, EnvironmentProject>();
for (const project of projects) {
map.set(scopedProjectKey(project.environmentId, project.id), project);
}
return map;
}, [projects]);
// Thread List v2 (beta) support — same model as the compact Home list
// (HomeScreen.tsx): flat creation-order card block + settled recency tail.
// PR states stream in per-row; merged/closed PRs auto-settle their thread
// on the next partition.
const [changeRequestStateByKey, setChangeRequestStateByKey] = useState<
ReadonlyMap<string, "open" | "closed" | "merged">
>(() => new Map());
const handleChangeRequestState = useCallback(
(threadKey: string, state: "open" | "closed" | "merged" | null) => {
setChangeRequestStateByKey((current) => {
if ((current.get(threadKey) ?? null) === state) return current;
const next = new Map(current);
if (state === null) {
next.delete(threadKey);
} else {
next.set(threadKey, state);
}
return next;
});
},
[],
);
// The settled tail renders in pages; expansion resets when the filter
// context changes so environment/search flips never inherit a deep page.
const [settledVisibleCount, setSettledVisibleCount] = useState(
THREAD_LIST_V2_SETTLED_INITIAL_COUNT,
);
const settledResetKey = `${options.selectedEnvironmentId ?? "all"}:${selectedProjectKey ?? "all"}:${props.searchQuery.trim()}`;
const lastSettledResetKeyRef = useRef(settledResetKey);
if (lastSettledResetKeyRef.current !== settledResetKey) {
lastSettledResetKeyRef.current = settledResetKey;
setSettledVisibleCount(THREAD_LIST_V2_SETTLED_INITIAL_COUNT);
}
const showMoreSettled = useCallback(
() => setSettledVisibleCount((count) => count + THREAD_LIST_V2_SETTLED_PAGE_COUNT),
[],
);
// now ticks per minute so the inactivity auto-settle boundary is actually
// crossed while the pane stays open; without a clock dependency the
// partition memoizes a frozen "now".
const [nowMinute, setNowMinute] = useState(() => new Date().toISOString().slice(0, 16));
useEffect(() => {
if (!threadListV2Enabled) return;
// Refresh immediately on enable: the mount-time value can be hours old
// by the time the beta is switched on, which would misclassify the
// inactivity auto-settle boundary until the first tick.
setNowMinute(new Date().toISOString().slice(0, 16));
const id = setInterval(() => setNowMinute(new Date().toISOString().slice(0, 16)), 60_000);
return () => clearInterval(id);
}, [threadListV2Enabled]);
// Threads on servers without the settlement capability never classify as
// settled (the user could neither un-settle nor pin them).
const serverConfigs = useAtomValue(environmentServerConfigsAtom);
const settlementEnvironmentIds = useMemo(() => {
const supported = new Set<EnvironmentId>();
for (const [environmentId, config] of serverConfigs) {
if (config.environment.capabilities.threadSettlement === true) {
supported.add(environmentId);
}
}
return supported;
}, [serverConfigs]);
const threadListV2Layout = useMemo(() => {
if (!threadListV2Enabled) return { items: [], hiddenSettledCount: 0 };
return buildThreadListV2Items({
threads: threads.filter((thread) => thread.archivedAt === null),
environmentId: options.selectedEnvironmentId,
projectRefs: selectedProjectScope === null ? null : selectedProjectScope.projectRefs,
searchQuery: props.searchQuery,
changeRequestStateByKey,
settlementEnvironmentIds,
settledLimit: settledVisibleCount,
now: `${nowMinute}:00.000Z`,
});
}, [
changeRequestStateByKey,
nowMinute,
options.selectedEnvironmentId,
props.searchQuery,
settledVisibleCount,
settlementEnvironmentIds,
threadListV2Enabled,
threads,
selectedProjectScope,
]);
const listItems = useMemo<readonly SidebarListItem[]>(() => {
if (!threadListV2Enabled) return listLayout.items;
// Queued offline tasks render above the thread rows (mirrors the
// compact Home v2 list): they are not thread shells, so the v2 item
// builder never sees them, but they must stay visible and deletable
// while their environment is offline. Same environment scope and
// search filter as the list.
const v2SearchQuery = props.searchQuery.trim().toLocaleLowerCase();
const v2PendingTasks = pendingTasks.filter(
(pendingTask) =>
(options.selectedEnvironmentId === null ||
pendingTask.message.environmentId === options.selectedEnvironmentId) &&
(selectedProjectRefs === null ||
selectedProjectRefs.has(
scopedProjectKey(pendingTask.message.environmentId, pendingTask.creation.projectId),
)) &&
(v2SearchQuery.length === 0 ||
pendingTask.title.toLocaleLowerCase().includes(v2SearchQuery)),
);
const items: SidebarListItem[] = v2PendingTasks.map((pendingTask, index) => ({
type: "v2-pending-task" as const,
key: `v2-pending:${pendingTask.message.messageId}`,
pendingTask,
isLast: index === v2PendingTasks.length - 1,
}));
for (const item of threadListV2Layout.items) {
items.push({
type: "v2-thread" as const,
key: scopedThreadKey(item.thread.environmentId, item.thread.id),
item,
});
}
if (threadListV2Layout.hiddenSettledCount > 0) {
items.push({
type: "v2-show-more",
key: "v2-show-more",
hiddenCount: threadListV2Layout.hiddenSettledCount,
});
}
return items;
}, [
listLayout.items,
options.selectedEnvironmentId,
pendingTasks,
props.searchQuery,
selectedProjectRefs,
threadListV2Enabled,
threadListV2Layout,
]);
const showsConnectionStatus = shouldShowWorkspaceConnectionStatus(catalogState);
const listMenuActions = useMemo<MenuAction[]>(
() => [
@@ -260,36 +500,54 @@ function ThreadNavigationSidebarPane(
})),
],
},
{
id: "project-sort",
title: "Sort projects",
subactions: PROJECT_SORT_OPTIONS.map((option) => ({
id: `project-sort:${option.value}`,
title: option.label,
state: options.projectSortOrder === option.value ? "on" : "off",
})),
},
{
id: "thread-sort",
title: "Sort threads",
subactions: THREAD_SORT_OPTIONS.map((option) => ({
id: `thread-sort:${option.value}`,
title: option.label,
state: options.threadSortOrder === option.value ? "on" : "off",
})),
},
{
id: "project-grouping",
title: "Group projects",
subactions: PROJECT_GROUPING_OPTIONS.map((option) => ({
id: `project-grouping:${option.value}`,
title: option.label,
subtitle: option.subtitle,
state: options.projectGroupingMode === option.value ? "on" : "off",
})),
},
...(projectFilterOptions.length === 0
? []
: ([
{
id: "project",
title: "Project",
subactions: [
{
id: "project:all",
title: "All projects",
subtitle: "Show threads from every project",
state: selectedProjectKey === null ? "on" : "off",
},
...projectFilterOptions.map((project) => ({
id: `project:${project.key}`,
title: project.label,
state: selectedProjectKey === project.key ? ("on" as const) : ("off" as const),
})),
],
},
] satisfies MenuAction[])),
// v2 lays the list out in fixed creation order — offering sort/group
// controls it silently ignores would be a lie. Environment still
// scopes the v2 partition, so it stays.
...(threadListV2Enabled
? []
: ([
{
id: "project-sort",
title: "Sort projects",
subactions: PROJECT_SORT_OPTIONS.map((option) => ({
id: `project-sort:${option.value}`,
title: option.label,
state: options.projectSortOrder === option.value ? "on" : "off",
})),
},
{
id: "thread-sort",
title: "Sort threads",
subactions: THREAD_SORT_OPTIONS.map((option) => ({
id: `thread-sort:${option.value}`,
title: option.label,
state: options.threadSortOrder === option.value ? "on" : "off",
})),
},
] satisfies MenuAction[])),
],
[environments, options],
[environments, options, projectFilterOptions, selectedProjectKey, threadListV2Enabled],
);
const handleListMenuAction = useCallback(
({ nativeEvent }: { readonly nativeEvent: { readonly event: string } }) => {
@@ -305,6 +563,17 @@ function ThreadNavigationSidebarPane(
if (environment) setSelectedEnvironmentId(environment.environmentId);
return;
}
if (event === "project:all") {
setSelectedProjectKey(null);
return;
}
if (event.startsWith("project:")) {
const projectKey = event.slice("project:".length);
if (projectFilterOptions.some((project) => project.key === projectKey)) {
setSelectedProjectKey(projectKey);
}
return;
}
const projectSort = PROJECT_SORT_OPTIONS.find(
(option) => `project-sort:${option.value}` === event,
);
@@ -319,14 +588,10 @@ function ThreadNavigationSidebarPane(
setThreadSortOrder(threadSort.value);
return;
}
const grouping = PROJECT_GROUPING_OPTIONS.find(
(option) => `project-grouping:${option.value}` === event,
);
if (grouping) setProjectGroupingMode(grouping.value);
},
[
environments,
setProjectGroupingMode,
projectFilterOptions,
setProjectSortOrder,
setSelectedEnvironmentId,
setThreadSortOrder,
@@ -382,7 +647,44 @@ function ThreadNavigationSidebarPane(
onScroll: handleScroll,
onScrollBeginDrag: handleScrollBeginDrag,
});
const listExtraData = props.selectedThreadKey ?? "";
const listExtraData = useMemo(
() => ({
selectedThreadKey: props.selectedThreadKey ?? "",
savedConnectionsById,
serverConfigs,
}),
[props.selectedThreadKey, savedConnectionsById, serverConfigs],
);
const sidebarItemsAreEqual = useCallback(
(previous: SidebarListItem, item: SidebarListItem): boolean => {
if (previous.type === "v2-thread" && item.type === "v2-thread") {
return (
previous.key === item.key &&
previous.item.thread === item.item.thread &&
previous.item.variant === item.item.variant &&
previous.item.showSettledDivider === item.item.showSettledDivider
);
}
if (previous.type === "v2-show-more" && item.type === "v2-show-more") {
return previous.hiddenCount === item.hiddenCount;
}
if (previous.type === "v2-pending-task" && item.type === "v2-pending-task") {
return previous.pendingTask === item.pendingTask && previous.isLast === item.isLast;
}
if (
previous.type === "v2-thread" ||
previous.type === "v2-show-more" ||
previous.type === "v2-pending-task" ||
item.type === "v2-thread" ||
item.type === "v2-show-more" ||
item.type === "v2-pending-task"
) {
return false;
}
return homeListItemsAreEqual(previous, item);
},
[],
);
const focusSearch = useCallback(() => {
const focus = () => {
if (props.nativeChrome) {
@@ -401,8 +703,78 @@ function ThreadNavigationSidebarPane(
}, [props.nativeChrome, props.onRequestVisibility, props.visible]);
useHardwareKeyboardCommand("focusSearch", focusSearch);
const renderListItem = useCallback(
({ item }: { readonly item: HomeListItem }) => {
({ item }: { readonly item: SidebarListItem }) => {
switch (item.type) {
case "v2-pending-task":
return (
<PendingTaskListRow
variant="sidebar"
pendingTask={item.pendingTask}
environmentLabel={
savedConnectionsById[item.pendingTask.message.environmentId]?.environmentLabel ??
null
}
isLast={item.isLast}
onSelectPendingTask={openPendingTask}
onDeletePendingTask={confirmDeletePendingTask}
/>
);
case "v2-thread": {
const thread = item.item.thread;
const scopeKey = scopedProjectKey(thread.environmentId, thread.projectId);
return (
<ThreadListV2Row
thread={thread}
variant={item.item.variant}
showSettledDivider={item.item.showSettledDivider}
project={projectByKey.get(scopeKey) ?? null}
providerDriver={
serverConfigs
.get(thread.environmentId)
?.providers.find(
(provider) =>
provider.instanceId ===
(thread.session?.providerInstanceId ?? thread.modelSelection.instanceId),
)?.driver ?? null
}
environmentLabel={
Object.keys(savedConnectionsById).length > 1
? (savedConnectionsById[thread.environmentId]?.environmentLabel ?? null)
: null
}
pane="sidebar"
selected={
scopedThreadKey(thread.environmentId, thread.id) === props.selectedThreadKey
}
fullSwipeWidth={props.width - 20}
onSelectThread={handleSelectThread}
onDeleteThread={confirmDeleteThread}
onArchiveThread={archiveThread}
settlementSupported={settlementEnvironmentIds.has(thread.environmentId)}
onSettleThread={settleThread}
onUnsettleThread={unsettleThread}
onChangeRequestState={handleChangeRequestState}
projectCwd={projectCwdByKey.get(scopeKey) ?? null}
onSwipeableClose={handleSwipeableClose}
onSwipeableWillOpen={handleSwipeableWillOpen}
simultaneousSwipeGesture={sidebarScrollGesture}
/>
);
}
case "v2-show-more":
return (
<Pressable
accessibilityRole="button"
accessibilityLabel={`Show ${Math.min(item.hiddenCount, THREAD_LIST_V2_SETTLED_PAGE_COUNT)} more settled threads`}
onPress={showMoreSettled}
className="mx-4 mt-2 items-center rounded-lg border border-dashed border-border py-2.5"
style={({ pressed }) => ({ opacity: pressed ? 0.6 : 1 })}
>
<Text className="text-xs font-t3-medium text-foreground-muted">
Show more ({item.hiddenCount} settled hidden)
</Text>
</Pressable>
);
case "header":
return (
<ThreadListGroupHeader
@@ -478,42 +850,58 @@ function ThreadNavigationSidebarPane(
archiveThread,
confirmDeletePendingTask,
confirmDeleteThread,
handleChangeRequestState,
handleSelectThread,
handleSwipeableClose,
handleSwipeableWillOpen,
openPendingTask,
projectByKey,
projectCwdByKey,
props.onNewThreadInProject,
props.selectedThreadKey,
props.width,
savedConnectionsById,
serverConfigs,
settleThread,
settlementEnvironmentIds,
showMoreSettled,
sidebarScrollGesture,
unsettleThread,
updateGroupDisplay,
],
);
const filterIcon = hasCustomHomeListOptions(options)
// v2 ignores the sort/group options, so only the environment filter can
// light the "customized" state while the beta is on.
const filterCustomized = threadListV2Enabled
? options.selectedEnvironmentId !== null || selectedProjectKey !== null
: hasCustomHomeListOptions({ ...options, selectedProjectKey });
const filterIcon = filterCustomized
? "line.3.horizontal.decrease.circle.fill"
: "line.3.horizontal.decrease.circle";
const filterMenu = useMemo(
() =>
buildHomeListFilterMenu({
environments,
projects: projectFilterOptions,
selectedEnvironmentId: options.selectedEnvironmentId,
selectedProjectKey,
projectSortOrder: options.projectSortOrder,
threadSortOrder: options.threadSortOrder,
projectGroupingMode: options.projectGroupingMode,
onEnvironmentChange: setSelectedEnvironmentId,
onProjectChange: setSelectedProjectKey,
onProjectSortOrderChange: setProjectSortOrder,
onThreadSortOrderChange: setThreadSortOrder,
onProjectGroupingModeChange: setProjectGroupingMode,
listOrganization: !threadListV2Enabled,
}),
[
environments,
options,
setProjectGroupingMode,
projectFilterOptions,
selectedProjectKey,
setProjectSortOrder,
setSelectedEnvironmentId,
setThreadSortOrder,
threadListV2Enabled,
],
);
const nativeHeaderItems = useMemo(
@@ -531,7 +919,9 @@ function ThreadNavigationSidebarPane(
? "Loading threads…"
: props.searchQuery.trim().length > 0
? "No matching threads"
: "No threads yet"}
: selectedProjectScope !== null
? `No threads in ${selectedProjectScope.title}`
: "No threads yet"}
</Text>
);
@@ -539,6 +929,7 @@ function ThreadNavigationSidebarPane(
return (
<>
<NativeStackScreenOptions
optionsVersion={nativeHeaderItems}
options={{
headerSearchBarOptions: {
ref: searchBarRef,
@@ -564,12 +955,12 @@ function ThreadNavigationSidebarPane(
<SwipeableScrollGateProvider enabled={swipeEnabled}>
<GestureDetector gesture={sidebarScrollGesture}>
<LegendList
data={listLayout.items}
data={listItems}
drawDistance={500}
estimatedItemSize={64}
extraData={listExtraData}
getItemType={(item) => item.type}
itemsAreEqual={homeListItemsAreEqual}
itemsAreEqual={sidebarItemsAreEqual}
keyExtractor={(item) => item.key}
renderItem={renderListItem}
automaticallyAdjustsScrollIndicatorInsets={NATIVE_LIQUID_GLASS_SUPPORTED}
@@ -625,12 +1016,12 @@ function ThreadNavigationSidebarPane(
<SwipeableScrollGateProvider enabled={swipeEnabled}>
<GestureDetector gesture={sidebarScrollGesture}>
<LegendList
data={listLayout.items}
data={listItems}
drawDistance={500}
estimatedItemSize={64}
extraData={listExtraData}
getItemType={(item) => item.type}
itemsAreEqual={homeListItemsAreEqual}
itemsAreEqual={sidebarItemsAreEqual}
keyExtractor={(item) => item.key}
renderItem={renderListItem}
contentContainerStyle={[
@@ -19,8 +19,10 @@ import { ThreadSwipeable } from "../home/thread-swipe-actions";
import { resolveThreadListV2Status, type ThreadListV2Status } from "./threadListV2";
/**
* Thread List v2 rows mirror the web sidebar's compact tonal cards and
* receded settled tail while retaining native swipe and long-press actions.
* Thread List v2 renders one flat native list: rich edge-to-edge rows for
* active work and a receded settled tail, all with native swipe and
* long-press actions. State reads through colored status labels and text
* hierarchy rather than card fills.
*/
const MONO_FONT = Platform.select({
@@ -29,12 +31,15 @@ const MONO_FONT = Platform.select({
default: "monospace",
});
// Status hues follow the system-wide convention set by sidebar v1 and the
// Live Activity/widgets (amber approval, indigo input, sky working) so a
// thread reads the same color everywhere it surfaces.
const STATUS_LABEL_BY_STATUS: Partial<
Record<ThreadListV2Status, { label: string; className: string }>
> = {
approval: { label: "Approval", className: "text-amber-700 dark:text-amber-300" },
input: { label: "Input", className: "text-amber-700 dark:text-amber-300" },
working: { label: "Working", className: "text-blue-600 dark:text-blue-400" },
input: { label: "Input", className: "text-indigo-600 dark:text-indigo-300" },
working: { label: "Working", className: "text-sky-600 dark:text-sky-400" },
failed: { label: "Failed", className: "text-red-700 dark:text-red-300" },
};
@@ -60,10 +65,20 @@ const LEGACY_MENU_ACTIONS: MenuAction[] = [
{ id: "delete", title: "Delete", image: "trash", attributes: { destructive: true } },
];
export const ThreadListV2SettledDivider = memo(function ThreadListV2SettledDivider() {
/** Rounded-row radius shared with the v1 sidebar rows. */
const SIDEBAR_V2_ROW_RADIUS = 12;
export const ThreadListV2SettledDivider = memo(function ThreadListV2SettledDivider(props: {
readonly pane?: "screen" | "sidebar";
}) {
const borderColor = useThemeColor("--color-border");
return (
<View className="mb-1.5 mt-4 flex-row items-center gap-2.5 px-5">
<View
className={cn(
"mb-1.5 mt-4 flex-row items-center gap-2.5",
props.pane === "sidebar" ? "px-3" : "px-5",
)}
>
<Text className="text-xs font-t3-medium text-foreground-tertiary">Settled</Text>
<View className="h-px flex-1" style={{ backgroundColor: borderColor }} />
</View>
@@ -76,6 +91,22 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
readonly showSettledDivider: boolean;
readonly project: EnvironmentProject | null;
readonly providerDriver: string | null;
/** Which machine hosts the thread. Null when only one environment is
connected — repeating the same label on every row is noise. Mirrors
the web sidebar's remote-environment cloud icon, but as text since
phones have no hover tooltips. */
readonly environmentLabel: string | null;
/** Hosting surface. "screen" (default) renders the compact Home idiom:
flat edge-to-edge rows on the screen background with inset hairlines.
"sidebar" renders the iPad split-view idiom: rounded rows blending
into the drawer surface, selection filled with the accent color —
matching the v1 sidebar rows. */
readonly pane?: "screen" | "sidebar";
/** Highlights the thread open in the detail pane (iPad split view). The
compact Home list never sets it — phones navigate away on select. */
readonly selected?: boolean;
/** Override for narrow panes (iPad sidebar); defaults to window width. */
readonly fullSwipeWidth?: number;
readonly onSelectThread: (thread: EnvironmentThreadShell) => void;
readonly onDeleteThread: (thread: EnvironmentThreadShell) => void;
readonly onSettleThread: (thread: EnvironmentThreadShell) => void;
@@ -117,6 +148,11 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
}, [onChangeRequestState, prState, threadKey]);
const screenColor = useThemeColor("--color-screen");
const drawerColor = useThemeColor("--color-drawer");
const pressedBackgroundColor = useThemeColor("--color-subtle");
const selectedBackgroundColor = useThemeColor("--color-user-bubble");
const sidebarPane = props.pane === "sidebar";
const selected = props.selected === true;
const status = resolveThreadListV2Status(thread);
const statusLabel = STATUS_LABEL_BY_STATUS[status];
@@ -174,99 +210,184 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
thread.title,
]);
// The sidebar pane fills selected rows with the accent color (matching the
// v1 sidebar), so every piece of row text needs a white-on-accent variant.
const cardContent = (
<>
<View className="flex-row items-center gap-1.5">
{props.project ? (
<ProjectFavicon
environmentId={thread.environmentId}
size={15}
projectTitle={props.project.title}
workspaceRoot={props.project.workspaceRoot}
/>
) : null}
<Text
className={cn(
"flex-1 text-sm font-t3-medium",
selected ? "text-user-bubble-foreground-muted" : "text-foreground-muted",
)}
numberOfLines={1}
>
{props.project?.title ?? ""}
</Text>
<Text
className={cn(
"text-xs tabular-nums",
selected ? "text-white" : (statusLabel?.className ?? "text-foreground-tertiary"),
)}
>
{statusLabel?.label ?? timeLabel}
</Text>
</View>
<Text
className={cn(
"mt-1 text-base font-t3-medium",
selected ? "text-user-bubble-foreground" : "text-foreground",
)}
numberOfLines={2}
>
{thread.title}
</Text>
<View className="mt-1 flex-row items-center gap-2">
{status === "failed" && thread.session?.lastError ? (
<Text
className={cn(
"flex-1 text-xs",
selected
? "text-user-bubble-foreground-muted"
: "text-red-600/80 dark:text-red-400/80",
)}
numberOfLines={1}
>
{thread.session.lastError}
</Text>
) : thread.branch || props.environmentLabel ? (
/* "branch · machine" share one truncating line. The machine sits
last so a tight fit cuts the repetitive label, not the branch —
and machine-only fills the row for non-git projects. */
<Text
className={cn(
"flex-1 text-xs",
selected ? "text-user-bubble-foreground-muted" : "text-foreground-muted",
)}
numberOfLines={1}
>
{thread.branch ? (
<Text
className={cn(
"text-xs",
selected ? "text-user-bubble-foreground-muted" : "text-foreground-muted",
)}
style={{ fontFamily: MONO_FONT }}
>
{thread.branch}
</Text>
) : null}
{thread.branch && props.environmentLabel ? " · " : null}
{props.environmentLabel ? (
<Text
className={cn(
"text-xs",
selected ? "text-user-bubble-foreground-muted" : "text-foreground-tertiary",
)}
>
{props.environmentLabel}
</Text>
) : null}
</Text>
) : (
<View className="flex-1" />
)}
{pr ? (
<Text
accessibilityLabel={pr.accessibilityLabel}
className={cn("text-xs", selected ? "text-white" : pr.textClassName)}
style={{ fontFamily: MONO_FONT }}
>
#{pr.label}
</Text>
) : null}
{props.providerDriver ? (
<View className="opacity-60">
<ProviderIcon provider={props.providerDriver} size={14} />
</View>
) : null}
</View>
</>
);
const rowContent = (close: () => void) =>
variant === "card" ? (
<Pressable
accessibilityHint={`Opens the thread. Swipe left to ${primaryAction.label.toLowerCase()}.`}
accessibilityLabel={thread.title}
accessibilityRole="button"
accessibilityState={{ selected }}
onPress={() => {
close();
onSelectThread(thread);
}}
style={({ pressed }) => ({ opacity: pressed ? 0.7 : 1 })}
style={
sidebarPane
? ({ pressed }) => ({
backgroundColor: selected
? selectedBackgroundColor
: pressed
? pressedBackgroundColor
: drawerColor,
borderRadius: SIDEBAR_V2_ROW_RADIUS,
paddingHorizontal: 12,
paddingVertical: 10,
})
: ({ pressed }) => ({ opacity: pressed ? 0.7 : 1 })
}
>
<View className="bg-screen px-4 py-1">
<View
className={cn(
"overflow-hidden",
status === "ready"
? "bg-black/[0.025] dark:bg-white/[0.025]"
: "bg-black/[0.04] dark:bg-white/[0.04]",
)}
style={{ borderRadius: 12, borderCurve: "continuous", minHeight: 84 }}
>
<View className="px-3 py-2.5">
<View className="flex-row items-center gap-1.5">
{props.project ? (
<ProjectFavicon
environmentId={thread.environmentId}
size={15}
projectTitle={props.project.title}
workspaceRoot={props.project.workspaceRoot}
/>
) : null}
<Text
className="flex-1 text-sm font-t3-medium text-foreground-muted"
numberOfLines={1}
>
{props.project?.title ?? ""}
</Text>
<Text
className={cn(
"text-xs tabular-nums",
statusLabel?.className ?? "text-foreground-tertiary",
)}
>
{statusLabel?.label ?? timeLabel}
</Text>
</View>
<Text className="mt-1 text-base font-t3-medium text-foreground" numberOfLines={2}>
{thread.title}
</Text>
<View className="mt-1 flex-row items-center gap-2">
{status === "failed" && thread.session?.lastError ? (
<Text
className="flex-1 text-xs text-red-600/80 dark:text-red-400/80"
numberOfLines={1}
>
{thread.session.lastError}
</Text>
) : thread.branch ? (
<Text
className="flex-1 text-xs text-foreground-muted"
numberOfLines={1}
style={{ fontFamily: MONO_FONT }}
>
{thread.branch}
</Text>
) : (
<View className="flex-1" />
)}
{props.providerDriver ? (
<View className="opacity-60">
<ProviderIcon provider={props.providerDriver} size={14} />
</View>
) : null}
</View>
</View>
{sidebarPane ? (
cardContent
) : (
/* Flat native list rows: no tonal containers — colored status
labels and text hierarchy carry state, an inset hairline
separates rows. The opaque screen background stays so swipe
actions reveal behind the row. */
<View className="bg-screen">
<View className="px-5 py-2.5">{cardContent}</View>
<View className="ml-5 h-px bg-border-subtle" />
</View>
</View>
)}
</Pressable>
) : (
<Pressable
accessibilityHint={`Opens the thread. Swipe left to ${primaryAction.label.toLowerCase()}.`}
accessibilityLabel={thread.title}
accessibilityRole="button"
className="bg-screen"
accessibilityState={{ selected }}
className={sidebarPane ? undefined : "bg-screen"}
onPress={() => {
close();
onSelectThread(thread);
}}
style={({ pressed }) => ({ opacity: pressed ? 0.7 : 1 })}
style={
sidebarPane
? ({ pressed }) => ({
backgroundColor: selected
? selectedBackgroundColor
: pressed
? pressedBackgroundColor
: drawerColor,
borderRadius: SIDEBAR_V2_ROW_RADIUS,
})
: ({ pressed }) => ({ opacity: pressed ? 0.7 : 1 })
}
>
{/* Settled history recedes: dimmed favicon + muted title. */}
<View className="min-h-[44px] flex-row items-center gap-2.5 px-5 py-2">
<View
className={cn(
"min-h-[44px] flex-row items-center gap-2.5 py-2",
sidebarPane ? "px-3" : "px-5",
)}
>
{props.project ? (
<View className="opacity-40">
<ProjectFavicon
@@ -277,11 +398,20 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
/>
</View>
) : null}
<Text className="flex-1 text-base text-foreground-muted" numberOfLines={1}>
<Text
className={cn(
"flex-1 text-base",
selected ? "text-user-bubble-foreground" : "text-foreground-muted",
)}
numberOfLines={1}
>
{thread.title}
</Text>
<Text
className="text-sm tabular-nums text-foreground-tertiary"
className={cn(
"text-sm tabular-nums",
selected ? "text-user-bubble-foreground-muted" : "text-foreground-tertiary",
)}
style={{ fontFamily: MONO_FONT }}
>
{relativeTime(thread.latestUserMessageAt ?? thread.updatedAt ?? thread.createdAt)}
@@ -292,14 +422,18 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
return (
<>
{props.showSettledDivider ? <ThreadListV2SettledDivider /> : null}
{props.showSettledDivider ? <ThreadListV2SettledDivider pane={props.pane} /> : null}
<ThreadSwipeable
backgroundColor={screenColor}
backgroundColor={sidebarPane ? drawerColor : screenColor}
compactActions={variant === "slim"}
containerStyle={
sidebarPane ? { borderRadius: SIDEBAR_V2_ROW_RADIUS, overflow: "hidden" } : undefined
}
enableTrackpadSwipe
// Full swipe commits the advertised lifecycle action (Settle /
// Un-settle), never the destructive delete.
fullSwipeAction="primary"
fullSwipeWidth={windowWidth - 32}
fullSwipeWidth={props.fullSwipeWidth ?? windowWidth - 32}
onDelete={handleDelete}
onSwipeableClose={props.onSwipeableClose}
onSwipeableWillOpen={props.onSwipeableWillOpen}
@@ -166,13 +166,36 @@ describe("buildThreadListV2Items", () => {
}),
],
environmentId: null,
projectRef: { environmentId, projectId: ProjectId.make("project-1") },
projectRefs: [{ environmentId, projectId: ProjectId.make("project-1") }],
searchQuery: "",
now: NOW,
});
expect(items.map((item) => item.thread.id)).toEqual(["included"]);
});
it("scopes the flat list to every environment member of a logical project", () => {
const remoteEnvironmentId = EnvironmentId.make("environment-remote");
const { items } = buildThreadListV2Items({
threads: [
makeThread({ id: ThreadId.make("local"), title: "Local" }),
makeThread({
environmentId: remoteEnvironmentId,
id: ThreadId.make("remote"),
title: "Remote",
}),
],
environmentId: null,
projectRefs: [
{ environmentId, projectId: ProjectId.make("project-1") },
{ environmentId: remoteEnvironmentId, projectId: ProjectId.make("project-1") },
],
searchQuery: "",
now: NOW,
});
expect(items.map((item) => item.thread.id)).toEqual(["local", "remote"]);
});
});
describe("buildThreadListV2Items settled paging", () => {
@@ -12,6 +12,12 @@ import type { EnvironmentId, ProjectId } from "@t3tools/contracts";
*/
export type ThreadListV2Status = "approval" | "input" | "working" | "failed" | "ready";
// Settled-tail paging: recent history is the common lookup; the deep tail
// stays behind an explicit Show more. Shared by the compact Home list and
// the iPad sidebar so both page identically.
export const THREAD_LIST_V2_SETTLED_INITIAL_COUNT = 10;
export const THREAD_LIST_V2_SETTLED_PAGE_COUNT = 25;
export function resolveThreadListV2Status(
thread: Pick<EnvironmentThreadShell, "hasPendingApprovals" | "hasPendingUserInput" | "session">,
): ThreadListV2Status {
@@ -89,10 +95,10 @@ export interface ThreadListV2Layout {
export function buildThreadListV2Items(input: {
readonly threads: ReadonlyArray<EnvironmentThreadShell>;
readonly environmentId: EnvironmentId | null;
readonly projectRef?: {
readonly projectRefs?: ReadonlyArray<{
readonly environmentId: EnvironmentId;
readonly projectId: ProjectId;
} | null;
}> | null;
readonly searchQuery: string;
/** Per-row PR state reported up by visible rows ("env:threadId" keys). */
readonly changeRequestStateByKey?: ReadonlyMap<string, "open" | "closed" | "merged">;
@@ -109,6 +115,9 @@ export function buildThreadListV2Items(input: {
const now = input.now ?? new Date().toISOString();
const autoSettleAfterDays = input.autoSettleAfterDays ?? 3;
const query = input.searchQuery.trim().toLocaleLowerCase();
const projectKeys = input.projectRefs
? new Set(input.projectRefs.map((ref) => `${ref.environmentId}:${ref.projectId}`))
: null;
const active: EnvironmentThreadShell[] = [];
const settled: EnvironmentThreadShell[] = [];
@@ -116,11 +125,7 @@ export function buildThreadListV2Items(input: {
// Callers pass live (unarchived) shells; settled threads are among them
// and partition into the tail via effectiveSettled.
if (input.environmentId !== null && thread.environmentId !== input.environmentId) continue;
if (
input.projectRef != null &&
(thread.environmentId !== input.projectRef.environmentId ||
thread.projectId !== input.projectRef.projectId)
) {
if (projectKeys !== null && !projectKeys.has(`${thread.environmentId}:${thread.projectId}`)) {
continue;
}
if (query.length > 0 && !thread.title.toLocaleLowerCase().includes(query)) continue;
+9 -2
View File
@@ -142,6 +142,13 @@ function stabilizeOptionFunctions(
export function NativeStackScreenOptions(props: {
readonly options?: AppNativeStackNavigationOptions;
/**
* Causes dynamic native header factories to be reapplied when their closed-over
* menu content changes. Factory functions are intentionally stabilized, so
* their source alone cannot capture a menu that was initially empty while
* asynchronous data was loading.
*/
readonly optionsVersion?: unknown;
readonly listeners?: Record<string, (event: never) => void>;
readonly name?: string;
}) {
@@ -163,7 +170,7 @@ export function NativeStackScreenOptions(props: {
if (!navigation || !stableOptions) {
return;
}
const signature = optionsSignature(stableOptions);
const signature = optionsSignature([stableOptions, props.optionsVersion]);
// Avoid re-entering navigation state when semantically equal options are
// reapplied every layout (common when callers pass unstable object literals).
if (lastAppliedOptionsSignatureRef.current === signature) {
@@ -171,7 +178,7 @@ export function NativeStackScreenOptions(props: {
}
lastAppliedOptionsSignatureRef.current = signature;
navigation.setOptions(stableOptions);
}, [navigation, stableOptions]);
}, [navigation, props.optionsVersion, stableOptions]);
useEffect(() => {
if (!navigation || !props.listeners) {
@@ -22,6 +22,7 @@ export interface Preferences {
readonly codeWordBreak?: boolean;
readonly connectOnboardingOptOutAccounts?: ReadonlyArray<string>;
readonly collapsedProjectGroups?: readonly string[];
readonly projectGroupingEnabled?: boolean;
/**
* Device-local mirror of the web beta's `sidebarV2Enabled`. Mobile has no
* client-settings sync, so the flat v2 thread list is opted into per
@@ -77,6 +78,7 @@ function sanitizePreferences(parsed: Preferences): Preferences {
codeWordBreak?: boolean;
connectOnboardingOptOutAccounts?: ReadonlyArray<string>;
collapsedProjectGroups?: readonly string[];
projectGroupingEnabled?: boolean;
threadListV2Enabled?: boolean;
} = {};
@@ -104,6 +106,9 @@ function sanitizePreferences(parsed: Preferences): Preferences {
(key): key is string => typeof key === "string",
);
}
if (typeof parsed.projectGroupingEnabled === "boolean") {
preferences.projectGroupingEnabled = parsed.projectGroupingEnabled;
}
if (typeof parsed.threadListV2Enabled === "boolean") {
preferences.threadListV2Enabled = parsed.threadListV2Enabled;
}
+5 -1
View File
@@ -11,6 +11,7 @@ import * as PlatformError from "effect/PlatformError";
import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
import * as ServerConfig from "../config.ts";
import * as ProjectFaviconResolver from "../project/ProjectFaviconResolver.ts";
import * as T3ProjectFileLoader from "../project/T3ProjectFileLoader.ts";
import * as WorkspacePaths from "../workspace/WorkspacePaths.ts";
import { ASSET_ROUTE_PREFIX, issueAssetUrl, resolveAsset } from "./AssetAccess.ts";
@@ -20,7 +21,10 @@ const configLayer = ServerConfig.ServerConfig.layerTest(process.cwd(), {
const testLayer = Layer.mergeAll(
configLayer,
WorkspacePaths.layer,
ProjectFaviconResolver.layer.pipe(Layer.provide(WorkspacePaths.layer)),
ProjectFaviconResolver.layer.pipe(
Layer.provide(WorkspacePaths.layer),
Layer.provide(T3ProjectFileLoader.layer),
),
ServerSecretStore.layer.pipe(Layer.provide(configLayer)),
).pipe(Layer.provideMerge(NodeServices.layer));
+16 -1
View File
@@ -202,6 +202,18 @@ it.layer(NodeServices.layer)("bin cli parsing", (it) => {
}).pipe(Effect.provide(Layer.mergeAll(CliRuntimeLayer, TestConsole.layer))),
);
it.effect("exposes service lifecycle commands without T3 Connect configuration", () =>
Effect.gen(function* () {
const { output } = yield* captureStdout(runCli(["service", "--help"], noConnectCli));
assert.include(output, "Manage the T3 Code background service.");
assert.include(output, "install");
assert.include(output, "uninstall");
assert.include(output, "update");
assert.include(output, "status");
}),
);
it.effect("reports fresh headless connect state without requiring local configuration", () =>
Effect.gen(function* () {
const baseDir = NodeFS.mkdtempSync(
@@ -305,7 +317,10 @@ it.layer(NodeServices.layer)("bin cli parsing", (it) => {
runConnectCli(["connect", "logout", "--base-dir", baseDir]),
);
assert.equal(output, "Signed out of T3 Connect locally.");
assert.equal(
output,
"Signed out of T3 Connect locally.\nThe background service is managed separately with `t3 service`.",
);
assert.isFalse(NodeFS.existsSync(tokenPath));
}),
);
+2
View File
@@ -13,6 +13,7 @@ import { hasCloudPublicConfig } from "./cloud/publicConfig.ts";
import { sharedServerCommandFlags } from "./cli/config.ts";
import { projectCommand } from "./cli/project.ts";
import { runServerCommand, serveCommand, startCommand } from "./cli/server.ts";
import { serviceCommand } from "./cli/service.ts";
const CliRuntimeLayer = Layer.mergeAll(NodeServices.layer, NetService.layer);
@@ -47,6 +48,7 @@ export const makeCli = ({ cloudEnabled = hasCloudPublicConfig } = {}) =>
serveCommand,
authCommand,
projectCommand,
serviceCommand,
cloudEnabled ? connectCommand : connectUnavailableCommand,
]),
);
+2 -2
View File
@@ -16,9 +16,9 @@ import {
formatRelayClientReady,
headlessSessionConfig,
isPublishAgentActivityEnabledValue,
recoverBootServiceOffer,
reportCloudDisconnectResults,
} from "./connect.ts";
import { recoverServiceOnboardingOffer } from "./service.ts";
it("explains how to complete headless authorization", () => {
assert.equal(
@@ -58,7 +58,7 @@ it.effect("detects headless operation from individual SSH config values", () =>
it.effect("treats cancelling optional background setup as a successful skip", () =>
Effect.gen(function* () {
const result = yield* recoverBootServiceOffer(Effect.fail(new Terminal.QuitError({})));
const result = yield* recoverServiceOnboardingOffer(Effect.fail(new Terminal.QuitError({})));
assert.isFalse(result);
}),
);
+11 -69
View File
@@ -6,7 +6,6 @@ import {
} from "@t3tools/contracts";
import { RelayOkResponse } from "@t3tools/contracts/relay";
import * as RelayClient from "@t3tools/shared/relayClient";
import * as Terminal from "effect/Terminal";
import { withRelayClientTracing } from "@t3tools/shared/relayTracing";
import * as Cause from "effect/Cause";
import * as Config from "effect/Config";
@@ -20,6 +19,7 @@ import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as References from "effect/References";
import * as Schema from "effect/Schema";
import * as Terminal from "effect/Terminal";
import { Command, Flag, GlobalFlag, Prompt } from "effect/unstable/cli";
import {
FetchHttpClient,
@@ -29,7 +29,6 @@ import {
} from "effect/unstable/http";
import * as HttpApiClient from "effect/unstable/httpapi/HttpApiClient";
import packageJson from "../../package.json" with { type: "json" };
import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts";
import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
import * as BootService from "../cloud/bootService.ts";
@@ -45,9 +44,13 @@ import { headlessRelayClientTracingLayer } from "../cloud/relayTracing.ts";
import * as ServerConfig from "../config.ts";
import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
import * as ExternalLauncher from "../process/externalLauncher.ts";
import * as ProcessRunner from "../processRunner.ts";
import { readPersistedServerRuntimeState } from "../serverRuntimeState.ts";
import { projectLocationFlags, resolveCliAuthConfig } from "./config.ts";
import {
bootServiceLayer,
offerServiceDuringOnboarding,
recoverServiceOnboardingOffer,
} from "./service.ts";
const jsonFlag = Flag.boolean("json").pipe(
Flag.withDescription("Emit JSON instead of human-readable output."),
@@ -396,21 +399,6 @@ const disconnectCloud = Effect.fn("cloud.cli.disconnect")(function* (options: {
if (options.clearAuthorization) {
const tokens = yield* CliTokenManager.CloudCliTokenManager;
yield* tokens.clear;
// uninstall itself no-ops when nothing is installed (and on non-Linux),
// so no status pre-check that could mask a real removal failure.
const bootService = yield* BootService.BootService;
yield* bootService.uninstall.pipe(
Effect.tap((removed) =>
removed ? Console.log("Removed the T3 Code background service.") : Effect.void,
),
Effect.catchTag("BootServiceUnsupportedError", () => Effect.succeed(false)),
Effect.catch((error) =>
Console.warn(`Could not remove the background service: ${error.message}`).pipe(
Effect.as(false),
),
),
);
}
yield* reportCloudDisconnectResults({
@@ -420,7 +408,9 @@ const disconnectCloud = Effect.fn("cloud.cli.disconnect")(function* (options: {
});
if (options.clearAuthorization) {
yield* Console.log("Signed out of T3 Connect locally.");
yield* Console.log(
"Signed out of T3 Connect locally.\nThe background service is managed separately with `t3 service`.",
);
}
});
@@ -457,11 +447,7 @@ const runCloudCommand = Effect.fn("cloud.cli.run_cloud_command")(function* <A, E
RelayClient.layerCloudflared({ baseDir: config.baseDir }),
EnvironmentAuth.runtimeLayer,
ServerEnvironment.layer,
BootService.layer({
baseDir: config.baseDir,
logsDir: config.logsDir,
cliVersion: packageJson.version,
}).pipe(Layer.provide(ProcessRunner.layer)),
bootServiceLayer(config),
headlessRelayClientTracingLayer,
).pipe(
Layer.provideMerge(FetchHttpClient.layer),
@@ -683,50 +669,6 @@ const connectLogoutCommand = Command.make("logout", {
),
);
const offerBootService = Effect.gen(function* () {
const bootService = yield* BootService.BootService;
const { supported, installed, current } = yield* bootService.status;
if (!supported) {
// Don't prompt for something that can only fail; background setup is
// Linux/systemd-only for now.
return false;
}
if (installed && current) {
yield* Console.log("T3 Code is already set up to run in the background on this machine.");
return true;
}
const wanted = yield* Prompt.run(
Prompt.confirm({
message: installed
? "The installed T3 Code background service is from an older setup. Update it now?"
: "Run T3 Code in the background whenever this machine boots? " +
"It stays reachable through T3 Connect even after you log out.",
initial: true,
}),
);
if (!wanted) {
return false;
}
const plan = yield* bootService.install;
yield* Console.log(`Background service installed. Logs: ${plan.logPath}`);
return true;
});
export const recoverBootServiceOffer = <R>(
offer: Effect.Effect<boolean, BootService.BootServiceError | Terminal.QuitError, R>,
) =>
offer.pipe(
Effect.catchTags({
QuitError: () => Effect.succeed(false),
BootServiceUnsupportedError: (error) =>
Console.log(`Skipping background setup: ${error.message}`).pipe(Effect.as(false)),
BootServiceCommandError: (error) =>
Console.warn(`Background setup did not finish: ${error.message}`).pipe(Effect.as(false)),
BootServiceInstallError: (error) =>
Console.warn(`Background setup did not finish: ${error.message}`).pipe(Effect.as(false)),
}),
);
export const connectCommand = Command.make("connect", {
...projectLocationFlags,
headless: headlessFlag,
@@ -748,7 +690,7 @@ export const connectCommand = Command.make("connect", {
// Connect itself already succeeded; a boot-service failure must not
// fail the command, just tell the user what happened and move on.
const background = yield* recoverBootServiceOffer(offerBootService);
const background = yield* recoverServiceOnboardingOffer(offerServiceDuringOnboarding);
yield* Console.log(
background
? "\n✓ Background service ready\n\nT3 Code will stay reachable after you log out."
+37
View File
@@ -0,0 +1,37 @@
import { assert, it } from "@effect/vitest";
import { formatServiceStatus } from "./service.ts";
const status = {
supported: true,
installed: true,
current: true,
unitPath: "/home/me/.config/systemd/user/t3code.service",
logPath: "/home/me/.t3/userdata/logs/boot-service.log",
} as const;
it("reports the installed service version and host paths", () => {
assert.equal(
formatServiceStatus(status, "0.0.29"),
[
"T3 Code service",
" Status: installed · [email protected]",
" Unit: /home/me/.config/systemd/user/t3code.service",
" Logs: /home/me/.t3/userdata/logs/boot-service.log",
].join("\n"),
);
});
it("gives a direct repair command for a stale service", () => {
assert.include(
formatServiceStatus({ ...status, current: false }, "0.0.29"),
"Next: Run `npx t3@latest service update`.",
);
});
it("explains service availability without systemd", () => {
assert.include(
formatServiceStatus({ ...status, supported: false, installed: false }, "0.0.29"),
"Supported on: Linux with systemd",
);
});
+199
View File
@@ -0,0 +1,199 @@
import * as Console from "effect/Console";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Terminal from "effect/Terminal";
import { Command, GlobalFlag, Prompt } from "effect/unstable/cli";
import packageJson from "../../package.json" with { type: "json" };
import * as BootService from "../cloud/bootService.ts";
import type * as ServerConfig from "../config.ts";
import * as ProcessRunner from "../processRunner.ts";
import { projectLocationFlags, resolveCliAuthConfig } from "./config.ts";
export const bootServiceLayer = (config: ServerConfig.ServerConfig["Service"]) =>
BootService.layer({
baseDir: config.baseDir,
logsDir: config.logsDir,
cliVersion: packageJson.version,
}).pipe(Layer.provide(ProcessRunner.layer));
export type ServiceReconcileResult =
| {
readonly changed: false;
readonly status: BootService.BootServiceStatus;
}
| {
readonly changed: true;
readonly previouslyInstalled: boolean;
readonly plan: BootService.BootServicePlan;
};
/** Install, update, or repair the service using the CLI version running this command. */
export const reconcileService = Effect.fn("cli.service.reconcile")(function* () {
const service = yield* BootService.BootService;
const status = yield* service.status;
if (status.installed && status.current) {
return { changed: false, status } satisfies ServiceReconcileResult;
}
const plan = yield* service.install;
return {
changed: true,
previouslyInstalled: status.installed,
plan,
} satisfies ServiceReconcileResult;
});
export function formatServiceStatus(
status: BootService.BootServiceStatus,
cliVersion: string,
): string {
if (!status.supported) {
return "T3 Code service\n Status: unavailable on this machine\n Supported on: Linux with systemd";
}
if (!status.installed) {
return "T3 Code service\n Status: not installed\n Next: Run `t3 service install`.";
}
return [
"T3 Code service",
` Status: ${status.current ? `installed · t3@${cliVersion}` : "needs an update or repair"}`,
` Unit: ${status.unitPath}`,
` Logs: ${status.logPath}`,
...(status.current ? [] : [" Next: Run `npx t3@latest service update`."]),
].join("\n");
}
const runServiceCommand = Effect.fn("cli.service.run")(function* <A, E>(
flags: { readonly baseDir: Parameters<typeof resolveCliAuthConfig>[0]["baseDir"] },
run: Effect.Effect<A, E, BootService.BootService>,
) {
const logLevel = yield* GlobalFlag.LogLevel;
const config = yield* resolveCliAuthConfig(flags, logLevel);
return yield* run.pipe(Effect.provide(bootServiceLayer(config)));
});
const serviceInstallCommand = Command.make("install", projectLocationFlags).pipe(
Command.withDescription("Install T3 Code as a background service for this user."),
Command.withHandler((flags) =>
runServiceCommand(
flags,
Effect.gen(function* () {
const result = yield* reconcileService();
if (!result.changed) {
yield* Console.log(
`T3 Code service is already installed with t3@${packageJson.version}.`,
);
return;
}
yield* Console.log(
`${result.previouslyInstalled ? "Updated" : "Installed"} T3 Code service with t3@${packageJson.version}.\nLogs: ${result.plan.logPath}`,
);
}),
),
),
);
const serviceUpdateCommand = Command.make("update", projectLocationFlags).pipe(
Command.withDescription(
"Update or repair the background service using this CLI version. Use `npx t3@latest service update` for the latest release.",
),
Command.withHandler((flags) =>
runServiceCommand(
flags,
Effect.gen(function* () {
const result = yield* reconcileService();
if (!result.changed) {
yield* Console.log(`T3 Code service is already using t3@${packageJson.version}.`);
return;
}
yield* Console.log(
`${result.previouslyInstalled ? "Updated" : "Installed"} T3 Code service with t3@${packageJson.version}.\nLogs: ${result.plan.logPath}`,
);
}),
),
),
);
const serviceUninstallCommand = Command.make("uninstall", projectLocationFlags).pipe(
Command.withDescription("Stop and remove the T3 Code background service."),
Command.withHandler((flags) =>
runServiceCommand(
flags,
Effect.gen(function* () {
const service = yield* BootService.BootService;
const removed = yield* service.uninstall;
yield* Console.log(
removed ? "Removed the T3 Code service." : "T3 Code service is not installed.",
);
}),
),
),
);
const serviceStatusCommand = Command.make("status", projectLocationFlags).pipe(
Command.withDescription("Show whether the T3 Code background service is installed."),
Command.withHandler((flags) =>
runServiceCommand(
flags,
Effect.gen(function* () {
const service = yield* BootService.BootService;
yield* Console.log(formatServiceStatus(yield* service.status, packageJson.version));
}),
),
),
);
export const offerServiceDuringOnboarding = Effect.gen(function* () {
const service = yield* BootService.BootService;
const { supported, installed, current } = yield* service.status;
if (!supported) {
return false;
}
if (installed && current) {
yield* Console.log("T3 Code is already set up to run in the background on this machine.");
return true;
}
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.",
initial: true,
}),
);
if (!wanted) {
return false;
}
const result = yield* reconcileService();
if (result.changed) {
yield* Console.log(
`Background service ${result.previouslyInstalled ? "updated" : "installed"}. Logs: ${result.plan.logPath}`,
);
}
return true;
});
export const recoverServiceOnboardingOffer = <R>(
offer: Effect.Effect<boolean, BootService.BootServiceError | Terminal.QuitError, R>,
) =>
offer.pipe(
Effect.catchTags({
QuitError: () => Effect.succeed(false),
BootServiceUnsupportedError: (error) =>
Console.log(`Skipping background setup: ${error.message}`).pipe(Effect.as(false)),
BootServiceCommandError: (error) =>
Console.warn(`Background setup did not finish: ${error.message}`).pipe(Effect.as(false)),
BootServiceInstallError: (error) =>
Console.warn(`Background setup did not finish: ${error.message}`).pipe(Effect.as(false)),
}),
);
export const serviceCommand = Command.make("service").pipe(
Command.withDescription("Manage the T3 Code background service."),
Command.withSubcommands([
serviceInstallCommand,
serviceUninstallCommand,
serviceUpdateCommand,
serviceStatusCommand,
]),
);
+33 -4
View File
@@ -14,6 +14,7 @@ import {
HostProcessPlatform,
} from "@t3tools/shared/hostProcess";
import { reconcileService } from "../cli/service.ts";
import * as ProcessRunner from "../processRunner.ts";
import * as BootService from "./bootService.ts";
@@ -100,7 +101,7 @@ it("renders a systemd unit with absolute paths and append-mode logging", () => {
unit,
[
"[Unit]",
"Description=T3 Code server (T3 Connect)",
"Description=T3 Code server",
"StartLimitIntervalSec=300",
"StartLimitBurst=5",
"",
@@ -108,6 +109,7 @@ it("renders a systemd unit with absolute paths and append-mode logging", () => {
"Type=simple",
"WorkingDirectory=%h",
"Environment=T3CODE_HOME=/home/theo/.t3",
"Environment=T3_BOOT_SERVICE_UNIT=t3code.service",
"ExecStart=/usr/local/bin/node /home/theo/.t3/runtime/versions/0.0.27/node_modules/t3/dist/bin.mjs serve",
"Restart=always",
"RestartSec=5",
@@ -170,6 +172,33 @@ it("flags package-manager cache entry points as ephemeral", () => {
});
it.layer(NodeServices.layer)("BootService", (it) => {
it.effect("reconciles the standalone service once and is then idempotent", () =>
Effect.gen(function* () {
const { dirs } = yield* makeTestContext();
const commands: Array<RecordedCommand> = [];
const service = yield* BootService.make({
baseDir: dirs.baseDir,
logsDir: dirs.logsDir,
cliVersion: "0.0.27",
host: makeHost(dirs.stableEntry),
}).pipe(Effect.provide(makeRecordingRunnerLayer(commands)), provideHostRefs(dirs.home));
const first = yield* reconcileService().pipe(
Effect.provideService(BootService.BootService, service),
);
assert.isTrue(first.changed);
if (!first.changed) return;
assert.isFalse(first.previouslyInstalled);
const commandCount = commands.length;
const second = yield* reconcileService().pipe(
Effect.provideService(BootService.BootService, service),
);
assert.isFalse(second.changed);
assert.lengthOf(commands, commandCount);
}),
);
it.effect("installs the unit, enables the service, and enables linger", () =>
Effect.gen(function* () {
const { dirs, fs, path } = yield* makeTestContext();
@@ -311,7 +340,7 @@ it.layer(NodeServices.layer)("BootService", (it) => {
}),
);
it.effect("reports an installed-but-stale unit so connect can offer a repair", () =>
it.effect("reports an installed-but-stale unit so the lifecycle can offer a repair", () =>
Effect.gen(function* () {
const { dirs, fs, path } = yield* makeTestContext();
const commands: Array<RecordedCommand> = [];
@@ -402,8 +431,8 @@ it.layer(NodeServices.layer)("BootService", (it) => {
const error = yield* service.install.pipe(Effect.flip);
assert.isTrue(isCommandError(error));
// A leftover unit would make the next connect report "already set up"
// even though linger never happened.
// A leftover unit would make status report "installed" even though
// linger never happened.
assert.isFalse(
yield* fs.exists(path.join(dirs.home, ".config", "systemd", "user", "t3code.service")),
);
+41 -60
View File
@@ -16,21 +16,19 @@ import {
} from "@t3tools/shared/hostProcess";
import * as ProcessRunner from "../processRunner.ts";
import { ensurePinnedRuntimeInstalled, pinnedRuntimePaths } from "./pinnedRuntime.ts";
/**
* Installs T3 Code as a per-user boot service so a connected machine stays
* reachable through T3 Connect after the SSH session ends. Linux-only for
* now: systemd user unit + loginctl enable-linger. The service runs a pinned
* runtime installed under <baseDir>/runtime — never `npx t3`, whose cache is
* ephemeral and whose registry fetch at boot would make startup depend on
* the network.
* Installs T3 Code as a per-user boot service. Linux-only for now: systemd
* user unit + loginctl enable-linger. The service runs a stable or pinned
* runtime — never an ephemeral `npx t3` cache whose eviction could break
* startup.
*/
const BOOT_SERVICE_NAME = "t3code";
const BOOT_RUNTIME_DIR = "runtime";
const BOOT_SERVICE_UNIT_FILE = `${BOOT_SERVICE_NAME}.service`;
const PINNED_RUNTIME_INSTALL_TIMEOUT = Duration.minutes(10);
export const BOOT_SERVICE_UNIT_FILE = `${BOOT_SERVICE_NAME}.service`;
export const BOOT_SERVICE_UNIT_ENV = "T3_BOOT_SERVICE_UNIT";
const EPHEMERAL_CACHE_SEGMENTS = [
"/_npx/", // npx
@@ -92,7 +90,7 @@ export function renderBootServiceUnit(plan: BootServicePlan): string {
// relay connection, and Restart=always covers early-boot failures.
return [
"[Unit]",
"Description=T3 Code server (T3 Connect)",
"Description=T3 Code server",
// Give up after 5 crashes in 5 minutes so a persistently broken install
// (deleted runtime, broken workspace) stops instead of restarting every
// 5s forever and growing the unrotated append log without bound.
@@ -103,6 +101,7 @@ export function renderBootServiceUnit(plan: BootServicePlan): string {
"Type=simple",
"WorkingDirectory=%h",
`Environment=T3CODE_HOME=${quoteSystemdValue(plan.baseDir)}`,
`Environment=${BOOT_SERVICE_UNIT_ENV}=${BOOT_SERVICE_UNIT_FILE}`,
`ExecStart=${quoteSystemdValue(plan.nodePath)} ${quoteSystemdValue(plan.t3EntryPath)} serve`,
"Restart=always",
"RestartSec=5",
@@ -206,14 +205,7 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: {
const unitDir = path.join(homeDir, ".config", "systemd", "user");
const unitPath = path.join(unitDir, BOOT_SERVICE_UNIT_FILE);
const logPath = path.join(input.logsDir, "boot-service.log");
const runtimeVersionDir = path.join(
input.baseDir,
BOOT_RUNTIME_DIR,
"versions",
input.cliVersion,
);
const runtimeEntryPath = path.join(runtimeVersionDir, "node_modules", "t3", "dist", "bin.mjs");
const runtimeSentinelPath = path.join(runtimeVersionDir, ".install-complete");
const runtimePaths = pinnedRuntimePaths(path, input.baseDir, input.cliVersion);
const requireSystemdLinux = Effect.gen(function* () {
if (platform !== "linux" || homeDir === "") {
@@ -263,52 +255,41 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: {
if (!isEphemeralCacheEntry(host.cliEntryPath)) {
return;
}
// The sentinel is written only after npm exits 0. Checking the entry
// file alone is not enough: npm extracts files before running native
// builds (node-pty), so a killed install leaves a plausible-looking but
// broken tree behind.
const alreadyPinned = yield* Effect.all([
fs.exists(runtimeSentinelPath),
fs.exists(runtimeEntryPath),
]).pipe(
Effect.map(([sentinelExists, entryExists]) => sentinelExists && entryExists),
Effect.mapError((cause) => new BootServiceInstallError({ cause })),
);
if (alreadyPinned) {
return;
}
yield* fs.remove(runtimeVersionDir, { recursive: true, force: true }).pipe(
Effect.andThen(fs.makeDirectory(runtimeVersionDir, { recursive: true })),
Effect.mapError((cause) => new BootServiceInstallError({ cause })),
);
yield* runStep(
"installing the pinned t3 runtime (this can take a few minutes)",
"npm",
[
"install",
"--prefix",
runtimeVersionDir,
"--no-fund",
"--no-audit",
`t3@${input.cliVersion}`,
],
// Native deps (node-pty) can compile from source on slow boxes; the
// ProcessRunner default of 60s would kill a healthy install.
{ timeout: PINNED_RUNTIME_INSTALL_TIMEOUT },
).pipe(
Effect.tapError(() =>
fs.remove(runtimeVersionDir, { recursive: true, force: true }).pipe(Effect.ignore),
yield* ensurePinnedRuntimeInstalled({
baseDir: input.baseDir,
version: input.cliVersion,
fs,
path,
runner,
}).pipe(
Effect.mapError((error) =>
error.step.startsWith("installing")
? new BootServiceCommandError({
step: error.step,
exitCode: error.exitCode,
stdoutLength: error.stdoutLength,
stderrLength: error.stderrLength,
cause: error.cause,
})
: new BootServiceInstallError({ cause: error }),
),
Effect.tapError((error) =>
DateTime.now.pipe(
Effect.flatMap((now) =>
fs.writeFileString(logPath, `${DateTime.formatIso(now)} ${error.message}\n`, {
flag: "a",
}),
),
Effect.ignore,
),
),
);
yield* fs
.writeFileString(runtimeSentinelPath, `${input.cliVersion}\n`)
.pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause })));
});
// Where the unit will point: derivable without touching the network, so
// status can compare units purely; install materializes it first.
const plannedEntryPath = isEphemeralCacheEntry(host.cliEntryPath)
? runtimeEntryPath
? runtimePaths.entryPath
: host.cliEntryPath;
const plan: BootServicePlan = {
nodePath: host.execPath,
@@ -341,8 +322,8 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: {
);
// If any activation step fails, remove the unit again: a leftover file
// would make the next `t3 connect` report the service as already set up
// even though it was never enabled or lingered.
// would make service status report it as installed even though it was
// never enabled or lingered.
yield* Effect.gen(function* () {
yield* runStep("reloading systemd user units", "systemctl", ["--user", "daemon-reload"]);
yield* runStep("enabling the service", "systemctl", [
@@ -372,7 +353,7 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: {
// fails), leave nothing behind: disable removes the enable symlink, remove
// deletes the file, daemon-reload clears the stale definition — otherwise a
// dangling wants/ symlink logs "Failed to load unit" at every boot and the
// next connect misreports the state.
// next lifecycle command misreports the state.
const rollbackFailedInstall = Effect.fn("cloud.boot_service.rollback_failed_install")(function* (
previousUnit: Option.Option<string>,
) {
+129
View File
@@ -0,0 +1,129 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, it } from "@effect/vitest";
import * as Deferred from "effect/Deferred";
import * as Effect from "effect/Effect";
import * as Fiber from "effect/Fiber";
import * as FileSystem from "effect/FileSystem";
import * as Path from "effect/Path";
import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
import * as ProcessRunner from "../processRunner.ts";
import {
ensurePinnedRuntimeInstalled,
pinnedRuntimePaths,
removePinnedRuntimeInstallation,
} from "./pinnedRuntime.ts";
it.layer(NodeServices.layer)("ensurePinnedRuntimeInstalled", (it) => {
it.effect("serializes concurrent installs of the same runtime", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-pinned-runtime-test-" });
const installStarted = yield* Deferred.make<void>();
const allowInstallToFinish = yield* Deferred.make<void>();
const paths = pinnedRuntimePaths(path, baseDir, "0.0.29");
let npmRuns = 0;
const runner = ProcessRunner.ProcessRunner.of({
run: (_input) =>
Effect.gen(function* () {
npmRuns += 1;
yield* Deferred.succeed(installStarted, undefined);
yield* Deferred.await(allowInstallToFinish);
yield* fs
.makeDirectory(path.dirname(paths.entryPath), { recursive: true })
.pipe(Effect.orDie);
yield* fs.writeFileString(paths.entryPath, "export {};\n").pipe(Effect.orDie);
return {
stdout: "",
stderr: "",
code: ChildProcessSpawner.ExitCode(0),
timedOut: false,
stdoutTruncated: false,
stderrTruncated: false,
};
}),
});
const install = ensurePinnedRuntimeInstalled({
baseDir,
version: "0.0.29",
fs,
path,
runner,
});
const first = yield* Effect.forkChild(install, { startImmediately: true });
yield* Deferred.await(installStarted);
const second = yield* Effect.forkChild(install, { startImmediately: true });
yield* Effect.yieldNow;
assert.equal(npmRuns, 1);
yield* Deferred.succeed(allowInstallToFinish, undefined);
yield* Fiber.join(first);
yield* Fiber.join(second);
assert.equal(npmRuns, 1);
assert.isTrue(yield* fs.exists(paths.sentinelPath));
assert.isTrue(yield* fs.exists(paths.entryPath));
}),
);
it.effect("waits for an active install before removing its runtime", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-pinned-runtime-test-" });
const installStarted = yield* Deferred.make<void>();
const allowInstallToFinish = yield* Deferred.make<void>();
const paths = pinnedRuntimePaths(path, baseDir, "0.0.30");
const runner = ProcessRunner.ProcessRunner.of({
run: (_input) =>
Effect.gen(function* () {
yield* Deferred.succeed(installStarted, undefined);
yield* Deferred.await(allowInstallToFinish);
yield* fs
.makeDirectory(path.dirname(paths.entryPath), { recursive: true })
.pipe(Effect.orDie);
yield* fs.writeFileString(paths.entryPath, "export {};\n").pipe(Effect.orDie);
return {
stdout: "",
stderr: "",
code: ChildProcessSpawner.ExitCode(0),
timedOut: false,
stdoutTruncated: false,
stderrTruncated: false,
};
}),
});
const installFiber = yield* Effect.forkChild(
ensurePinnedRuntimeInstalled({
baseDir,
version: "0.0.30",
fs,
path,
runner,
}),
{ startImmediately: true },
);
yield* Deferred.await(installStarted);
const removeFiber = yield* Effect.forkChild(
removePinnedRuntimeInstallation({
baseDir,
version: "0.0.30",
fs,
path,
}),
{ startImmediately: true },
);
yield* Effect.yieldNow;
assert.isTrue(yield* fs.exists(paths.versionDir));
yield* Deferred.succeed(allowInstallToFinish, undefined);
yield* Fiber.join(installFiber);
yield* Fiber.join(removeFiber);
assert.isFalse(yield* fs.exists(paths.versionDir));
}),
);
});
+176
View File
@@ -0,0 +1,176 @@
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Path from "effect/Path";
import * as Schema from "effect/Schema";
import * as Semaphore from "effect/Semaphore";
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
* switching over — never `npx t3`, whose cache is ephemeral and whose
* registry fetch at boot would make startup depend on the network.
*/
const PINNED_RUNTIME_DIR = "runtime";
const PINNED_RUNTIME_INSTALL_TIMEOUT = Duration.minutes(10);
// Boot-service setup and remote self-update share this module but can be
// constructed in separate layers. Serialize the complete check/install/
// sentinel transaction across all callers in this process.
const pinnedRuntimeInstallLock = Semaphore.makeUnsafe(1);
export interface PinnedRuntimePaths {
readonly versionDir: string;
readonly entryPath: string;
readonly sentinelPath: string;
}
export function pinnedRuntimePaths(
path: Path.Path,
baseDir: string,
version: string,
): PinnedRuntimePaths {
const versionDir = path.join(baseDir, PINNED_RUNTIME_DIR, "versions", version);
return {
versionDir,
entryPath: path.join(versionDir, "node_modules", "t3", "dist", "bin.mjs"),
sentinelPath: path.join(versionDir, ".install-complete"),
};
}
export class PinnedRuntimeInstallError extends Schema.TaggedErrorClass<PinnedRuntimeInstallError>()(
"PinnedRuntimeInstallError",
{
step: Schema.String,
exitCode: Schema.optional(Schema.Number),
stdoutLength: Schema.optional(Schema.Number),
stderrLength: Schema.optional(Schema.Number),
cause: Schema.optional(Schema.Defect()),
},
) {
override get message(): string {
return this.exitCode === undefined
? `Pinned runtime install failed while ${this.step}.`
: `Pinned runtime install failed while ${this.step} (exit code ${this.exitCode}).`;
}
}
/**
* Installs `t3@<version>` into the pinned runtime directory unless a complete
* install is already there, and returns its paths. The sentinel is written
* only after npm exits 0; checking the entry file alone is not enough — npm
* extracts files before running native builds (node-pty), so a killed
* install leaves a plausible-looking but broken tree behind.
*/
export const ensurePinnedRuntimeInstalled = Effect.fn("cloud.pinned_runtime.ensure_installed")(
function* (input: {
readonly baseDir: string;
readonly version: string;
readonly fs: FileSystem.FileSystem;
readonly path: Path.Path;
readonly runner: ProcessRunner.ProcessRunner["Service"];
}) {
const { fs, runner } = input;
const paths = pinnedRuntimePaths(input.path, input.baseDir, input.version);
return yield* pinnedRuntimeInstallLock.withPermit(
Effect.gen(function* () {
const alreadyPinned = yield* Effect.all([
fs.exists(paths.sentinelPath),
fs.exists(paths.entryPath),
]).pipe(
Effect.map(([sentinelExists, entryExists]) => sentinelExists && entryExists),
Effect.mapError(
(cause) =>
new PinnedRuntimeInstallError({ step: "checking the pinned runtime", cause }),
),
);
if (alreadyPinned) {
return paths;
}
yield* fs.remove(paths.versionDir, { recursive: true, force: true }).pipe(
Effect.andThen(fs.makeDirectory(paths.versionDir, { recursive: true })),
Effect.mapError(
(cause) =>
new PinnedRuntimeInstallError({
step: "preparing the pinned runtime directory",
cause,
}),
),
);
const installStep = "installing the pinned t3 runtime (this can take a few minutes)";
yield* runner
.run({
command: "npm",
args: [
"install",
"--prefix",
paths.versionDir,
"--no-fund",
"--no-audit",
`t3@${input.version}`,
],
// Native deps (node-pty) can compile from source on slow boxes; the
// ProcessRunner default of 60s would kill a healthy install.
timeout: PINNED_RUNTIME_INSTALL_TIMEOUT,
})
.pipe(
Effect.mapError((cause) => new PinnedRuntimeInstallError({ step: installStep, cause })),
Effect.filterOrFail(
(result) => result.code === 0,
(result) =>
new PinnedRuntimeInstallError({
step: installStep,
exitCode: Number(result.code),
stdoutLength: result.stdout.length,
stderrLength: result.stderr.length,
}),
),
Effect.tapError(() =>
fs.remove(paths.versionDir, { recursive: true, force: true }).pipe(Effect.ignore),
),
);
yield* fs
.writeFileString(paths.sentinelPath, `${input.version}\n`)
.pipe(
Effect.mapError(
(cause) =>
new PinnedRuntimeInstallError({ step: "recording the completed install", cause }),
),
);
return paths;
}),
);
},
);
/** Removes one pinned runtime while holding the same process-wide lock used
* by install/check/sentinel work, so cleanup cannot race another caller that
* is materializing or reusing the runtime tree. */
export const removePinnedRuntimeInstallation = Effect.fn("cloud.pinned_runtime.remove")(
function* (input: {
readonly baseDir: string;
readonly version: string;
readonly fs: FileSystem.FileSystem;
readonly path: Path.Path;
}) {
const paths = pinnedRuntimePaths(input.path, input.baseDir, input.version);
yield* pinnedRuntimeInstallLock.withPermit(
input.fs
.remove(paths.versionDir, { recursive: true, force: true })
.pipe(
Effect.mapError(
(cause) =>
new PinnedRuntimeInstallError({ step: "removing the pinned runtime", cause }),
),
),
);
},
);
+589
View File
@@ -0,0 +1,589 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, it } from "@effect/vitest";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Path from "effect/Path";
import * as TestClock from "effect/testing/TestClock";
import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
import {
HostProcessArguments,
HostProcessEnvironment,
HostProcessExecutablePath,
HostProcessPlatform,
} from "@t3tools/shared/hostProcess";
import * as ServerConfig from "../config.ts";
import * as ProcessRunner from "../processRunner.ts";
import {
BOOT_SERVICE_UNIT_ENV,
BOOT_SERVICE_UNIT_FILE,
renderBootServiceUnit,
} from "./bootService.ts";
import * as SelfUpdate from "./selfUpdate.ts";
const NODE_PATH = "/usr/local/bin/node";
interface RecordedCommand {
readonly command: string;
readonly args: ReadonlyArray<string>;
}
const makeRecordingRunnerLayer = (
commands: Array<RecordedCommand>,
options?: {
readonly failWhen?: ((command: string, args: ReadonlyArray<string>) => boolean) | undefined;
readonly stdoutFor?:
| ((command: string, args: ReadonlyArray<string>) => string | undefined)
| undefined;
},
) =>
Layer.succeed(
ProcessRunner.ProcessRunner,
ProcessRunner.ProcessRunner.of({
run: (input) =>
Effect.sync(() => {
commands.push({ command: input.command, args: input.args });
const failed = options?.failWhen?.(input.command, input.args) === true;
const versionFromPath =
input.command === NODE_PATH && input.args[1] === "--version"
? /[/\\]runtime[/\\]versions[/\\]([^/\\]+)/.exec(input.args[0] ?? "")?.[1]
: undefined;
return {
stdout:
options?.stdoutFor?.(input.command, input.args) ??
(versionFromPath === undefined ? "" : `${versionFromPath}\n`),
stderr: failed ? `${input.command} exploded` : "",
code: ChildProcessSpawner.ExitCode(failed ? 1 : 0),
timedOut: false,
stdoutTruncated: false,
stderrTruncated: false,
};
}),
}),
);
const provideHostRefs = (input: {
readonly platform: NodeJS.Platform;
readonly env: NodeJS.ProcessEnv;
readonly entryPath: string;
}) =>
Effect.provide(
Layer.mergeAll(
Layer.succeed(HostProcessPlatform, input.platform),
Layer.succeed(HostProcessEnvironment, input.env),
Layer.succeed(HostProcessExecutablePath, NODE_PATH),
Layer.succeed(HostProcessArguments, [NODE_PATH, input.entryPath, "serve"]),
),
);
it("recognizes published npm artifacts as swappable entry points", () => {
assert.isTrue(SelfUpdate.isPublishedCliEntry("/usr/local/lib/node_modules/t3/dist/bin.mjs"));
assert.isTrue(
SelfUpdate.isPublishedCliEntry("/home/theo/.npm/_npx/abc123/node_modules/t3/dist/bin.mjs"),
);
assert.isTrue(
SelfUpdate.isPublishedCliEntry(
"C:\\Users\\theo\\AppData\\Roaming\\npm\\node_modules\\t3\\dist\\bin.mjs",
),
);
// Dev checkouts and the desktop bundle run apps/server/dist directly.
assert.isFalse(SelfUpdate.isPublishedCliEntry("/home/theo/dev/t3/apps/server/dist/bin.mjs"));
assert.isFalse(SelfUpdate.isPublishedCliEntry(""));
});
it.layer(NodeServices.layer)("resolveServerSelfUpdateCapability", (it) => {
const makeHome = Effect.fn("test.makeHome")(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const home = yield* fs.makeTempDirectoryScoped({ prefix: "t3-self-update-test-" });
return { fs, path, home };
});
const writeUnitReferencing = Effect.fn("test.writeUnitReferencing")(function* (
home: string,
entryPath: string,
) {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const unitDir = path.join(home, ".config", "systemd", "user");
yield* fs.makeDirectory(unitDir, { recursive: true });
yield* fs.writeFileString(
path.join(unitDir, "t3code.service"),
renderBootServiceUnit({
nodePath: NODE_PATH,
t3EntryPath: entryPath,
baseDir: path.join(home, ".t3"),
logPath: path.join(home, ".t3", "userdata", "logs", "boot-service.log"),
unitPath: path.join(unitDir, "t3code.service"),
}),
);
});
it.effect("reports boot-service for the systemd-spawned unit process", () =>
Effect.gen(function* () {
const { home, path } = yield* makeHome();
const entryPath = path.join(home, ".t3/runtime/versions/0.0.28/node_modules/t3/dist/bin.mjs");
yield* writeUnitReferencing(home, entryPath);
const method = yield* SelfUpdate.resolveServerSelfUpdateCapability({
desktopManaged: false,
}).pipe(
provideHostRefs({
platform: "linux",
env: {
HOME: home,
INVOCATION_ID: "abc123",
[BOOT_SERVICE_UNIT_ENV]: BOOT_SERVICE_UNIT_FILE,
},
entryPath,
}),
);
assert.equal(method, "boot-service");
}),
);
it.effect("does not claim a systemd process owned by another unit", () =>
Effect.gen(function* () {
const { home, path } = yield* makeHome();
const entryPath = path.join(home, ".t3/runtime/versions/0.0.28/node_modules/t3/dist/bin.mjs");
yield* writeUnitReferencing(home, entryPath);
const method = yield* SelfUpdate.resolveServerSelfUpdateCapability({
desktopManaged: false,
}).pipe(
provideHostRefs({
platform: "linux",
env: { HOME: home, INVOCATION_ID: "abc123" },
entryPath,
}),
);
assert.isNull(method);
}),
);
it.effect("reports respawn for a manual run of the pinned artifact", () =>
Effect.gen(function* () {
const { home, path } = yield* makeHome();
const entryPath = path.join(home, ".t3/runtime/versions/0.0.28/node_modules/t3/dist/bin.mjs");
yield* writeUnitReferencing(home, entryPath);
// Same unit on disk, but no INVOCATION_ID: restarting the unit would
// not replace this process, so it must respawn itself instead.
const method = yield* SelfUpdate.resolveServerSelfUpdateCapability({
desktopManaged: false,
}).pipe(provideHostRefs({ platform: "linux", env: { HOME: home }, entryPath }));
assert.equal(method, "respawn");
}),
);
it.effect("reports respawn for a foreground npx artifact on darwin", () =>
Effect.gen(function* () {
const { home } = yield* makeHome();
const method = yield* SelfUpdate.resolveServerSelfUpdateCapability({
desktopManaged: false,
}).pipe(
provideHostRefs({
platform: "darwin",
env: { HOME: home },
entryPath: `${home}/.npm/_npx/abc123/node_modules/t3/dist/bin.mjs`,
}),
);
assert.equal(method, "respawn");
}),
);
it.effect("reports desktop-managed for desktop-supervised backends", () =>
Effect.gen(function* () {
const { home, path } = yield* makeHome();
// Desktop ownership wins over every process-shape heuristic: even a
// systemd-looking pinned artifact belongs to the app that spawned it.
const entryPath = path.join(home, ".t3/runtime/versions/0.0.28/node_modules/t3/dist/bin.mjs");
yield* writeUnitReferencing(home, entryPath);
const method = yield* SelfUpdate.resolveServerSelfUpdateCapability({
desktopManaged: true,
}).pipe(
provideHostRefs({
platform: "linux",
env: {
HOME: home,
INVOCATION_ID: "abc123",
[BOOT_SERVICE_UNIT_ENV]: BOOT_SERVICE_UNIT_FILE,
},
entryPath,
}),
);
assert.equal(method, "desktop-managed");
}),
);
it.effect("reports no method for dev checkouts and Windows", () =>
Effect.gen(function* () {
const { home } = yield* makeHome();
const devMethod = yield* SelfUpdate.resolveServerSelfUpdateCapability({
desktopManaged: false,
}).pipe(
provideHostRefs({
platform: "darwin",
env: { HOME: home },
entryPath: `${home}/dev/t3/apps/server/dist/bin.mjs`,
}),
);
assert.isNull(devMethod);
const windowsMethod = yield* SelfUpdate.resolveServerSelfUpdateCapability({
desktopManaged: false,
}).pipe(
provideHostRefs({
platform: "win32",
env: { HOME: home },
entryPath: "C:\\Users\\theo\\AppData\\Roaming\\npm\\node_modules\\t3\\dist\\bin.mjs",
}),
);
assert.isNull(windowsMethod);
}),
);
});
it.layer(NodeServices.layer)("ServerSelfUpdate.update", (it) => {
interface RecordedSpawn {
readonly command: string;
readonly args: ReadonlyArray<string>;
}
const makeContext = Effect.fn("test.makeContext")(function* (options?: {
readonly platform?: NodeJS.Platform;
readonly bootService?: boolean;
readonly desktopManaged?: boolean;
readonly entryPath?: string;
readonly failWhen?: (command: string, args: ReadonlyArray<string>) => boolean;
readonly stdoutFor?: (command: string, args: ReadonlyArray<string>) => string | undefined;
readonly failSpawn?: boolean;
}) {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const home = yield* fs.makeTempDirectoryScoped({ prefix: "t3-self-update-test-" });
const baseDir = path.join(home, ".t3");
const entryPath =
options?.entryPath ??
path.join(home, ".t3/runtime/versions/0.0.28/node_modules/t3/dist/bin.mjs");
const env: NodeJS.ProcessEnv =
options?.bootService === true
? {
HOME: home,
INVOCATION_ID: "abc123",
[BOOT_SERVICE_UNIT_ENV]: BOOT_SERVICE_UNIT_FILE,
}
: { HOME: home };
if (options?.bootService === true) {
const unitDir = path.join(home, ".config", "systemd", "user");
yield* fs.makeDirectory(unitDir, { recursive: true });
yield* fs.writeFileString(
path.join(unitDir, "t3code.service"),
renderBootServiceUnit({
nodePath: NODE_PATH,
t3EntryPath: entryPath,
baseDir,
logPath: path.join(baseDir, "userdata", "logs", "boot-service.log"),
unitPath: path.join(unitDir, "t3code.service"),
}),
);
}
const commands: Array<RecordedCommand> = [];
const spawns: Array<RecordedSpawn> = [];
let exited = 0;
// layerTest always reports mode "web"; desktop-managed contexts overlay
// the mode the desktop app's bootstrap envelope would set.
const configLayer =
options?.desktopManaged === true
? Layer.effect(
ServerConfig.ServerConfig,
Effect.gen(function* () {
const config = yield* ServerConfig.ServerConfig;
return { ...config, mode: "desktop" as const };
}),
).pipe(Layer.provide(ServerConfig.layerTest(home, baseDir)))
: ServerConfig.layerTest(home, baseDir);
const service = yield* SelfUpdate.make({
host: {
spawnDetached: (command, args) =>
Effect.sync(() => spawns.push({ command, args })).pipe(
Effect.andThen(
options?.failSpawn === true
? Effect.fail(
new ProcessRunner.ProcessSpawnError({
command,
argumentCount: args.length,
cause: new Error("detached spawn failed"),
}),
)
: Effect.void,
),
),
exitProcess: () => {
exited += 1;
},
},
}).pipe(
Effect.provide(
Layer.mergeAll(
makeRecordingRunnerLayer(commands, {
failWhen: options?.failWhen,
stdoutFor: options?.stdoutFor,
}),
configLayer,
),
),
provideHostRefs({ platform: options?.platform ?? "linux", env, entryPath }),
);
return {
fs,
path,
home,
baseDir,
entryPath,
commands,
spawns,
exitCount: () => exited,
service,
};
});
it.effect("rejects dist-tags and other non-exact versions", () =>
Effect.gen(function* () {
const context = yield* makeContext();
const error = yield* context.service.update({ targetVersion: "latest" }).pipe(Effect.flip);
assert.include(error.reason, "not an exact t3 version");
assert.lengthOf(context.commands, 0);
}),
);
it.effect("refuses to update a desktop-managed backend and points at the app", () =>
Effect.gen(function* () {
const context = yield* makeContext({ desktopManaged: true, bootService: true });
const error = yield* context.service.update({ targetVersion: "0.0.29" }).pipe(Effect.flip);
assert.include(error.reason, "desktop app");
assert.lengthOf(context.commands, 0);
assert.lengthOf(context.spawns, 0);
}),
);
it.effect("fails without touching anything when no update method applies", () =>
Effect.gen(function* () {
const context = yield* makeContext({
entryPath: "/home/theo/dev/t3/apps/server/dist/bin.mjs",
});
const error = yield* context.service.update({ targetVersion: "0.0.29" }).pipe(Effect.flip);
assert.include(error.reason, "cannot update itself");
assert.lengthOf(context.commands, 0);
}),
);
it.effect("surfaces a failed npm install and never schedules a restart", () =>
Effect.gen(function* () {
const context = yield* makeContext({ failWhen: (command) => command === "npm" });
const error = yield* context.service.update({ targetVersion: "0.0.29" }).pipe(Effect.flip);
assert.equal(error.reason, "Could not install the requested t3 version.");
yield* TestClock.adjust(Duration.seconds(10));
assert.lengthOf(context.spawns, 0);
assert.equal(context.exitCount(), 0);
}).pipe(Effect.provide(TestClock.layer())),
);
it.effect("reinstalls the same version after a failed preflight", () =>
Effect.gen(function* () {
let preflightAttempts = 0;
const context = yield* makeContext({
failWhen: (command) => {
if (command !== NODE_PATH) return false;
preflightAttempts += 1;
return preflightAttempts === 1;
},
});
const versionDir = context.path.join(context.baseDir, "runtime", "versions", "0.0.29");
const entryPath = context.path.join(versionDir, "node_modules", "t3", "dist", "bin.mjs");
yield* context.fs.makeDirectory(context.path.dirname(entryPath), { recursive: true });
yield* context.fs.writeFileString(entryPath, "export {};\n");
yield* context.fs.writeFileString(
context.path.join(versionDir, ".install-complete"),
"0.0.29\n",
);
const firstError = yield* context.service
.update({ targetVersion: "0.0.29" })
.pipe(Effect.flip);
assert.include(firstError.reason, "failed its version check");
assert.isFalse(yield* context.fs.exists(versionDir));
const result = yield* context.service.update({ targetVersion: "0.0.29" });
assert.deepEqual(result, { targetVersion: "0.0.29", method: "respawn" });
assert.deepEqual(
context.commands.map((entry) => entry.command),
[NODE_PATH, "npm", NODE_PATH],
);
}).pipe(Effect.provide(TestClock.layer())),
);
it.effect("rejects and removes an installed runtime that reports the wrong version", () =>
Effect.gen(function* () {
const context = yield* makeContext({
stdoutFor: (command, args) =>
command === NODE_PATH && args[1] === "--version" ? "0.0.28\n" : undefined,
});
const versionDir = context.path.join(context.baseDir, "runtime", "versions", "0.0.29");
const error = yield* context.service.update({ targetVersion: "0.0.29" }).pipe(Effect.flip);
assert.include(error.reason, "did not report the requested");
assert.isFalse(yield* context.fs.exists(versionDir));
assert.lengthOf(context.spawns, 0);
}),
);
it.effect("reports a detached replacement spawn failure and leaves updates retryable", () =>
Effect.gen(function* () {
const context = yield* makeContext({ failSpawn: true });
const first = yield* context.service.update({ targetVersion: "0.0.29" }).pipe(Effect.flip);
assert.include(first.reason, "Could not start the replacement");
const second = yield* context.service.update({ targetVersion: "0.0.29" }).pipe(Effect.flip);
assert.include(second.reason, "Could not start the replacement");
assert.notInclude(second.reason, "already in progress");
assert.lengthOf(context.spawns, 2);
assert.equal(context.exitCount(), 0);
}),
);
it.effect("installs, preflights, and respawns a foreground server", () =>
Effect.gen(function* () {
const context = yield* makeContext();
const result = yield* context.service.update({ targetVersion: "0.0.29" });
assert.deepEqual(result, { targetVersion: "0.0.29", method: "respawn" });
assert.lengthOf(context.spawns, 1);
const concurrentError = yield* context.service
.update({ targetVersion: "0.0.30" })
.pipe(Effect.flip);
assert.include(concurrentError.reason, "already in progress");
const pinnedEntry = context.path.join(
context.baseDir,
"runtime/versions/0.0.29/node_modules/t3/dist/bin.mjs",
);
assert.deepEqual(
context.commands.map((entry) => [entry.command, ...entry.args].join(" ")),
[
`npm install --prefix ${context.path.join(context.baseDir, "runtime/versions/0.0.29")} --no-fund --no-audit [email protected]`,
`${NODE_PATH} ${pinnedEntry} --version`,
],
);
// The restart is deferred so the RPC acknowledgement flushes first.
yield* TestClock.adjust(Duration.seconds(10));
assert.lengthOf(context.spawns, 1);
const spawn = context.spawns[0];
assert.equal(spawn?.command, "/bin/sh");
assert.include(spawn?.args ?? [], pinnedEntry);
// The replacement replays the original CLI arguments.
assert.include(spawn?.args ?? [], "serve");
assert.equal(context.exitCount(), 1);
}).pipe(Effect.provide(TestClock.layer())),
);
it.effect("rewrites the systemd unit and restarts the boot service", () =>
Effect.gen(function* () {
const context = yield* makeContext({ bootService: true });
const result = yield* context.service.update({ targetVersion: "0.0.29" });
assert.deepEqual(result, { targetVersion: "0.0.29", method: "boot-service" });
const pinnedEntry = context.path.join(
context.baseDir,
"runtime/versions/0.0.29/node_modules/t3/dist/bin.mjs",
);
const unit = yield* context.fs.readFileString(
context.path.join(context.home, ".config", "systemd", "user", "t3code.service"),
);
assert.include(unit, `ExecStart=${NODE_PATH} ${pinnedEntry} serve`);
assert.deepEqual(
context.commands.map((entry) => entry.command),
["npm", NODE_PATH, "systemctl", "systemctl"],
);
assert.deepEqual(context.commands[2]?.args, ["--user", "daemon-reload"]);
assert.deepEqual(context.commands[3], {
command: "systemctl",
args: ["--user", "restart", "t3code.service"],
});
assert.lengthOf(context.spawns, 0);
// systemd replaces the process; the server must not exit itself.
assert.equal(context.exitCount(), 0);
}).pipe(Effect.provide(TestClock.layer())),
);
it.effect("restores the previous unit and permits a retry when systemd restart fails", () =>
Effect.gen(function* () {
let failRestart = true;
const context = yield* makeContext({
bootService: true,
failWhen: (command, args) => {
if (command !== "systemctl" || args[1] !== "restart" || !failRestart) {
return false;
}
failRestart = false;
return true;
},
});
const unitPath = context.path.join(
context.home,
".config",
"systemd",
"user",
BOOT_SERVICE_UNIT_FILE,
);
const previousUnit = yield* context.fs.readFileString(unitPath);
const first = yield* context.service.update({ targetVersion: "0.0.29" }).pipe(Effect.flip);
assert.include(first.reason, "Restarting the systemd boot service failed");
assert.equal(yield* context.fs.readFileString(unitPath), previousUnit);
assert.deepEqual(
context.commands.slice(-2).map((entry) => entry.args),
[
["--user", "restart", BOOT_SERVICE_UNIT_FILE],
["--user", "daemon-reload"],
],
);
const retry = yield* context.service.update({ targetVersion: "0.0.30" });
assert.deepEqual(retry, { targetVersion: "0.0.30", method: "boot-service" });
}).pipe(Effect.provide(TestClock.layer())),
);
it.effect("restores the previous systemd unit when daemon-reload fails", () =>
Effect.gen(function* () {
const context = yield* makeContext({
bootService: true,
failWhen: (command) => command === "systemctl",
});
const unitPath = context.path.join(
context.home,
".config",
"systemd",
"user",
BOOT_SERVICE_UNIT_FILE,
);
const previousUnit = yield* context.fs.readFileString(unitPath);
const error = yield* context.service.update({ targetVersion: "0.0.29" }).pipe(Effect.flip);
assert.include(error.reason, "Reloading systemd units failed");
assert.equal(yield* context.fs.readFileString(unitPath), previousUnit);
assert.deepEqual(
context.commands.map((entry) => entry.command),
["npm", NODE_PATH, "systemctl", "systemctl"],
);
yield* TestClock.adjust(Duration.seconds(10));
assert.lengthOf(context.spawns, 0);
assert.equal(context.exitCount(), 0);
}).pipe(Effect.provide(TestClock.layer())),
);
});
+428
View File
@@ -0,0 +1,428 @@
// @effect-diagnostics nodeBuiltinImport:off
// node:child_process directly: the foreground-server replacement must be a
// detached fire-and-forget child that outlives this process, while Effect's
// ChildProcessSpawner ties every child to a scope that kills it.
import {
ServerSelfUpdateError,
type ServerSelfUpdateCapability,
type ServerSelfUpdateInput,
type ServerSelfUpdateResult,
} from "@t3tools/contracts";
import {
HostProcessArguments,
HostProcessEnvironment,
HostProcessExecutablePath,
HostProcessPlatform,
} from "@t3tools/shared/hostProcess";
import * as NodeChildProcess from "node:child_process";
import * as Context from "effect/Context";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Path from "effect/Path";
import * as Ref from "effect/Ref";
import * as ServerConfig from "../config.ts";
import { writeFileStringAtomically } from "../atomicWrite.ts";
import * as ProcessRunner from "../processRunner.ts";
import {
BOOT_SERVICE_UNIT_ENV,
BOOT_SERVICE_UNIT_FILE,
quoteSystemdValue,
renderBootServiceUnit,
} from "./bootService.ts";
import { ensurePinnedRuntimeInstalled, removePinnedRuntimeInstallation } from "./pinnedRuntime.ts";
/**
* Lets a connected client replace this server with another published `t3`
* version over RPC — the only update path that works when the user is not at
* the machine (phone against a home server, relay-managed box). The target
* version is npm-installed into the pinned runtime and verified before
* anything restarts, so a failed install leaves the running server untouched.
*/
const PREFLIGHT_TIMEOUT = Duration.seconds(30);
/** Grace between acknowledging the RPC and killing the process, so the
response (and its relay hop) flushes before the socket drops. */
const RESTART_DELAY = Duration.seconds(2);
/** Exact npm versions only — never dist-tags — so the acknowledgement names
the version that was actually installed. Also keeps the value safe to
pass to npm and embed in filesystem paths. */
const EXACT_VERSION_PATTERN = /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/;
export interface ServerSelfUpdateHost {
readonly execPath: string;
readonly cliEntryPath: string;
/** Original CLI arguments after the entry path, replayed on respawn. */
readonly cliArgs: ReadonlyArray<string>;
/** Resolves once the foreground replacement process has actually spawned. */
readonly spawnDetached: (
command: string,
args: ReadonlyArray<string>,
) => Effect.Effect<void, ProcessRunner.ProcessSpawnError>;
readonly exitProcess: () => void;
}
function normalizeEntryPath(entryPath: string): string {
return entryPath.replaceAll("\\", "/");
}
/**
* Only a published npm artifact can be swapped for another version: dev
* checkouts (apps/server/dist) and the desktop app's bundled backend have no
* npm identity, and the desktop manages its own updates.
*/
export function isPublishedCliEntry(entryPath: string): boolean {
return normalizeEntryPath(entryPath).includes("/node_modules/t3/dist/");
}
/**
* The update path this process can offer, or null when only a manual
* relaunch works. "desktop-managed" — the T3 Code desktop app spawned this
* backend and owns its version; only updating the app updates it.
* "boot-service" — this is the systemd-supervised process from
* bootService.ts: rewrite the unit and let systemd swap it. "respawn" — a
* foreground POSIX process running a published artifact: replace it with a
* detached child. Windows foreground runs are unsupported for now (no
* equivalent of the detach-and-exec handoff below).
*/
export const resolveServerSelfUpdateCapability = Effect.fn(
"cloud.server_self_update.resolve_capability",
)(function* (input: {
/** True when the desktop app supervises this backend (mode "desktop"). */
readonly desktopManaged: boolean;
}) {
if (input.desktopManaged) {
return "desktop-managed" as const;
}
const platform = yield* HostProcessPlatform;
const env = yield* HostProcessEnvironment;
const hostArguments = yield* HostProcessArguments;
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const entryPath = hostArguments[1] ?? "";
if (entryPath === "") {
return null;
}
const homeDir = env.HOME ?? "";
if (platform === "linux" && homeDir !== "") {
const unitPath = path.join(homeDir, ".config", "systemd", "user", BOOT_SERVICE_UNIT_FILE);
const unitReferencesEntry = yield* fs.readFileString(unitPath).pipe(
Effect.map((unit) => unit.includes(quoteSystemdValue(entryPath))),
Effect.orElseSucceed(() => false),
);
// INVOCATION_ID only proves that some systemd unit launched us. The
// explicit marker written into t3code.service identifies this unit as the
// supervisor that will replace the current process when restarted.
if (
unitReferencesEntry &&
(env.INVOCATION_ID ?? "") !== "" &&
env[BOOT_SERVICE_UNIT_ENV] === BOOT_SERVICE_UNIT_FILE
) {
return "boot-service" as const;
}
// A process owned by another (or a legacy unmarked) systemd unit must not
// use the foreground respawn path: Restart=always could otherwise launch
// the old unit beside the detached replacement.
if ((env.INVOCATION_ID ?? "") !== "") {
return null;
}
}
if ((platform === "linux" || platform === "darwin") && isPublishedCliEntry(entryPath)) {
return "respawn" as const;
}
return null;
});
export class ServerSelfUpdate extends Context.Service<
ServerSelfUpdate,
{
readonly update: (
input: ServerSelfUpdateInput,
) => Effect.Effect<ServerSelfUpdateResult, ServerSelfUpdateError>;
}
>()("t3/cloud/selfUpdate/ServerSelfUpdate") {}
export const make = Effect.fn("cloud.server_self_update.make")(function* (options?: {
readonly host?: Partial<ServerSelfUpdateHost>;
}) {
const serverConfig = yield* ServerConfig.ServerConfig;
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const runner = yield* ProcessRunner.ProcessRunner;
const env = yield* HostProcessEnvironment;
const hostExecPath = yield* HostProcessExecutablePath;
const hostArguments = yield* HostProcessArguments;
const capability: ServerSelfUpdateCapability | null = yield* resolveServerSelfUpdateCapability({
desktopManaged: serverConfig.mode === "desktop",
});
const host: ServerSelfUpdateHost = {
execPath: options?.host?.execPath ?? hostExecPath,
cliEntryPath: options?.host?.cliEntryPath ?? hostArguments[1] ?? "",
cliArgs: options?.host?.cliArgs ?? hostArguments.slice(2),
spawnDetached:
options?.host?.spawnDetached ??
((command, args) =>
Effect.callback<void, ProcessRunner.ProcessSpawnError>((resume) => {
const spawnError = (cause: unknown) =>
new ProcessRunner.ProcessSpawnError({
command,
argumentCount: args.length,
cause,
});
let child: NodeChildProcess.ChildProcess;
try {
child = NodeChildProcess.spawn(command, [...args], {
detached: true,
stdio: "ignore",
});
} catch (cause) {
resume(Effect.fail(spawnError(cause)));
return;
}
const onSpawnError = (cause: Error) => resume(Effect.fail(spawnError(cause)));
child.once("error", onSpawnError);
child.once("spawn", () => {
child.removeListener("error", onSpawnError);
// Keep asynchronous child errors from becoming uncaught after the
// successful spawn handoff has already been acknowledged.
child.on("error", () => undefined);
child.unref();
resume(Effect.void);
});
})),
exitProcess: options?.host?.exitProcess ?? (() => process.exit(0)),
};
const inFlight = yield* Ref.make(false);
const failWith = (reason: string, cause?: unknown) =>
cause === undefined
? new ServerSelfUpdateError({ reason })
: new ServerSelfUpdateError({ reason, cause });
/** Deferred so the RPC acknowledgement flushes before the process dies.
Detached from the request scope: the triggering connection is exactly
what the restart tears down. */
const scheduleRestart = (restart: Effect.Effect<void>) =>
Effect.sleep(RESTART_DELAY).pipe(
Effect.andThen(restart),
Effect.forkDetach({ startImmediately: true }),
);
const writeUnitAtomically = (filePath: string, contents: string) =>
writeFileStringAtomically({ filePath, contents }).pipe(
Effect.provideService(FileSystem.FileSystem, fs),
Effect.provideService(Path.Path, path),
);
const update: ServerSelfUpdate["Service"]["update"] = Effect.fn(
"cloud.server_self_update.update",
)(function* (input) {
if (capability === "desktop-managed") {
return yield* failWith(
"This server is managed by the T3 Code desktop app on its machine; update the desktop app to update it.",
);
}
if (capability === null) {
return yield* failWith(
"This server cannot update itself; relaunch it manually with the new version.",
);
}
const activeMethod = capability;
const targetVersion = input.targetVersion.trim();
if (!EXACT_VERSION_PATTERN.test(targetVersion)) {
return yield* failWith(`'${targetVersion}' is not an exact t3 version.`);
}
const alreadyRunning = yield* Ref.getAndSet(inFlight, true);
if (alreadyRunning) {
return yield* failWith("A server update is already in progress.");
}
return yield* Effect.gen(function* () {
const runtimePaths = yield* ensurePinnedRuntimeInstalled({
baseDir: serverConfig.baseDir,
version: targetVersion,
fs,
path,
runner,
}).pipe(
Effect.mapError((error) => failWith("Could not install the requested t3 version.", error)),
);
// A broken artifact (failed native build, incompatible node) must be
// caught while the current server is still alive to report it.
const preflight = yield* runner
.run({
command: host.execPath,
args: [runtimePaths.entryPath, "--version"],
timeout: PREFLIGHT_TIMEOUT,
})
.pipe(
Effect.mapError((cause) =>
failWith(`Could not verify the installed t3@${targetVersion}.`, cause),
),
);
const preflightVersion = preflight.stdout.trim();
if (preflight.code !== 0 || preflightVersion !== targetVersion) {
// A completed npm install can still be unusable under this Node or on
// this machine. Remove its sentinel and tree so a retry of the same
// version performs a clean install instead of reusing a known-bad one.
yield* removePinnedRuntimeInstallation({
baseDir: serverConfig.baseDir,
version: targetVersion,
fs,
path,
}).pipe(
Effect.mapError((error) =>
failWith(`Could not remove the failed t3@${targetVersion} installation.`, error),
),
);
return yield* failWith(
preflight.code !== 0
? `The installed t3@${targetVersion} failed its version check (exit code ${String(preflight.code)}).`
: `The installed runtime did not report the requested t3@${targetVersion} version.`,
);
}
if (activeMethod === "boot-service") {
const homeDir = env.HOME ?? "";
const unitPath = path.join(homeDir, ".config", "systemd", "user", BOOT_SERVICE_UNIT_FILE);
const previousUnit = yield* fs
.readFileString(unitPath)
.pipe(
Effect.mapError((cause) => failWith("Could not read the current systemd unit.", cause)),
);
// Same shape bootService.install writes, so host lifecycle commands
// still recognize the unit as current.
const unit = renderBootServiceUnit({
nodePath: host.execPath,
t3EntryPath: runtimePaths.entryPath,
baseDir: serverConfig.baseDir,
logPath: path.join(serverConfig.logsDir, "boot-service.log"),
unitPath,
});
yield* writeUnitAtomically(unitPath, unit).pipe(
Effect.mapError((cause) => failWith("Could not update the systemd unit.", cause)),
);
const reloadSystemd = Effect.fn("cloud.server_self_update.reload_systemd")(function* () {
const reload = yield* runner
.run({ command: "systemctl", args: ["--user", "daemon-reload"] })
.pipe(Effect.mapError((cause) => failWith("Could not reload systemd units.", cause)));
if (reload.code !== 0) {
return yield* failWith(
`Reloading systemd units failed (exit code ${String(reload.code)}).`,
);
}
});
yield* reloadSystemd().pipe(
Effect.catch((reloadError) =>
writeUnitAtomically(unitPath, previousUnit).pipe(
Effect.mapError((rollbackCause) =>
failWith("Could not restore the previous systemd unit.", {
reloadError,
rollbackCause,
}),
),
// Systemd should still have the old unit in memory after the
// failed reload, but retry after restoring in case it applied a
// partial update before returning an error.
Effect.andThen(reloadSystemd().pipe(Effect.ignore)),
Effect.andThen(Effect.fail(reloadError)),
),
),
);
yield* Effect.logInfo("Server self-update installed; restarting boot service.", {
targetVersion,
});
// A successful systemd restart stops this process, so the RPC is
// interrupted and the reconnecting client observes the new version.
// A rejected restart returns while the old process is still alive;
// restore the previous unit and report that failure through the RPC.
yield* Effect.gen(function* () {
const restart = yield* runner
.run({
command: "systemctl",
args: ["--user", "restart", BOOT_SERVICE_UNIT_FILE],
})
.pipe(
Effect.mapError((cause) =>
failWith("Could not restart the systemd boot service.", cause),
),
);
if (restart.code !== 0) {
return yield* failWith(
`Restarting the systemd boot service failed (exit code ${String(restart.code)}).`,
);
}
}).pipe(
Effect.catch((restartError) =>
writeUnitAtomically(unitPath, previousUnit).pipe(
Effect.andThen(reloadSystemd()),
Effect.mapError((rollbackError) =>
failWith("Could not restore the previous systemd unit.", {
restartError,
rollbackError,
}),
),
Effect.andThen(Effect.fail(restartError)),
),
),
);
} else {
// Spawn the shim before acknowledging the RPC so ENOENT/EACCES and
// other launch failures leave this server alive and return a useful
// error. The shim itself waits until after the acknowledgement and
// deferred exit before binding the replacement server.
yield* host
.spawnDetached("/bin/sh", [
"-c",
'sleep 3; exec "$@"',
"t3-self-update",
host.execPath,
runtimePaths.entryPath,
...host.cliArgs,
])
.pipe(
Effect.mapError((cause) =>
failWith("Could not start the replacement t3 process.", cause),
),
);
yield* Effect.logInfo("Server self-update installed; respawning.", { targetVersion });
yield* scheduleRestart(
Effect.try({
try: () => host.exitProcess(),
catch: (cause) => failWith("Could not exit the replaced t3 process.", cause),
}).pipe(
Effect.catch((error) =>
Effect.logError("Server self-update could not exit the replaced process.").pipe(
Effect.annotateLogs({ targetVersion, error: error.reason }),
Effect.ensuring(Ref.set(inFlight, false)),
),
),
),
);
}
return { targetVersion, method: activeMethod };
}).pipe(Effect.onError(() => Ref.set(inFlight, false)));
});
return ServerSelfUpdate.of({ update });
});
export const layer = Layer.effect(ServerSelfUpdate, make()).pipe(
Layer.provide(ProcessRunner.layer),
);
@@ -9,6 +9,7 @@ import * as Path from "effect/Path";
import * as Schema from "effect/Schema";
import packageJson from "../../package.json" with { type: "json" };
import { resolveServerSelfUpdateCapability } from "../cloud/selfUpdate.ts";
import * as ServerConfig from "../config.ts";
import * as ProcessRunner from "../processRunner.ts";
import { resolveServerEnvironmentLabel } from "./ServerEnvironmentLabel.ts";
@@ -124,6 +125,9 @@ export const make = Effect.gen(function* () {
const environmentId = EnvironmentId.make(environmentIdRaw);
const cwdBaseName = path.basename(serverConfig.cwd).trim();
const label = yield* resolveServerEnvironmentLabel({ cwdBaseName });
const serverSelfUpdate = yield* resolveServerSelfUpdateCapability({
desktopManaged: serverConfig.mode === "desktop",
});
const descriptor: ExecutionEnvironmentDescriptor = {
environmentId,
@@ -137,6 +141,7 @@ export const make = Effect.gen(function* () {
repositoryIdentity: true,
connectionProbe: true,
threadSettlement: true,
...(serverSelfUpdate === null ? {} : { serverSelfUpdate }),
},
};
+118
View File
@@ -8,6 +8,7 @@ import { it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as PlatformError from "effect/PlatformError";
import * as Scope from "effect/Scope";
import { ChildProcessSpawner } from "effect/unstable/process";
@@ -2413,6 +2414,123 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
12_000,
);
it.effect(
"does not reuse a cross-repo PR when GitHub omits head identity metadata",
() =>
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
yield* initRepo(repoDir);
yield* runGit(repoDir, ["checkout", "-b", "statemachine"]);
const forkDir = yield* createBareRemote();
yield* runGit(repoDir, ["remote", "add", "fork-seed", forkDir]);
yield* runGit(repoDir, ["push", "-u", "fork-seed", "statemachine"]);
yield* runGit(repoDir, [
"config",
"remote.fork-seed.url",
"[email protected]:octocat/codething-mvp.git",
]);
const { manager, ghCalls } = yield* makeManager({
ghScenario: {
prListSequenceByHeadSelector: {
"octocat:statemachine": [
`[{"number":41,"title":"Ambiguous fork PR","url":"https://github.com/pingdotgg/codething-mvp/pull/41","baseRefName":"main","headRefName":"statemachine","state":"OPEN"}]`,
`[{"number":142,"title":"Add stacked git actions","url":"https://github.com/pingdotgg/codething-mvp/pull/142","baseRefName":"main","headRefName":"statemachine","state":"OPEN","isCrossRepository":true,"headRepository":{"nameWithOwner":"octocat/codething-mvp"},"headRepositoryOwner":{"login":"octocat"}}]`,
],
"fork-seed:statemachine": ["[]"],
statemachine: ["[]"],
},
},
});
const result = yield* runStackedAction(manager, {
cwd: repoDir,
action: "commit_push_pr",
});
expect(result.pr.status).toBe("created");
expect(result.pr.number).toBe(142);
expect(ghCalls.some((call) => call.startsWith("pr create "))).toBe(true);
}),
20_000,
);
it.effect("rejects same-repo PR metadata when matching a cross-repo head context", () =>
Effect.sync(() => {
const headContext = {
headBranch: "statemachine",
headRepositoryNameWithOwner: "pingdotgg/codething-mvp",
headRepositoryOwnerLogin: "pingdotgg",
isCrossRepository: true,
};
expect(
GitManager.matchesBranchHeadContext(
{
number: 41,
title: "Same-repo PR",
url: "https://github.com/pingdotgg/codething-mvp/pull/41",
baseRefName: "main",
headRefName: "statemachine",
state: "open",
updatedAt: Option.none(),
isCrossRepository: false,
headRepositoryNameWithOwner: "pingdotgg/codething-mvp",
headRepositoryOwnerLogin: "pingdotgg",
},
headContext,
),
).toBe(false);
expect(
GitManager.matchesBranchHeadContext(
{
number: 142,
title: "Fork PR",
url: "https://github.com/pingdotgg/codething-mvp/pull/142",
baseRefName: "main",
headRefName: "statemachine",
state: "open",
updatedAt: Option.none(),
isCrossRepository: true,
headRepositoryNameWithOwner: "pingdotgg/codething-mvp",
headRepositoryOwnerLogin: "pingdotgg",
},
headContext,
),
).toBe(true);
}),
);
it.effect("accepts fork PR metadata when origin is the fork checkout remote", () =>
Effect.sync(() => {
const headContext = {
headBranch: "t3code/git-audit-stability",
headRepositoryNameWithOwner: "justsomelegs/t3code",
headRepositoryOwnerLogin: "justsomelegs",
isCrossRepository: false,
};
expect(
GitManager.matchesBranchHeadContext(
{
number: 2284,
title: "Improve branch mismatch warnings",
url: "https://github.com/pingdotgg/t3code/pull/2284",
baseRefName: "main",
headRefName: "t3code/git-audit-stability",
state: "open",
updatedAt: Option.none(),
isCrossRepository: true,
headRepositoryNameWithOwner: "justsomelegs/t3code",
headRepositoryOwnerLogin: "justsomelegs",
},
headContext,
),
).toBe(true);
}),
);
it.effect("creates PR when one does not already exist", () =>
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
+65 -27
View File
@@ -252,7 +252,38 @@ function resolvePullRequestHeadRepositoryNameWithOwner(
return `${ownerLogin}/${repositoryName}`;
}
function matchesBranchHeadContext(
interface PullRequestHeadIdentity {
readonly repositoryNameWithOwner: string | null;
readonly ownerLogin: string | null;
}
function resolveExpectedHeadIdentity(
headContext: Pick<BranchHeadContext, "headRepositoryNameWithOwner" | "headRepositoryOwnerLogin">,
): PullRequestHeadIdentity {
const repositoryNameWithOwner = normalizeOptionalRepositoryNameWithOwner(
headContext.headRepositoryNameWithOwner,
);
return {
repositoryNameWithOwner,
ownerLogin:
normalizeOptionalOwnerLogin(headContext.headRepositoryOwnerLogin) ??
parseRepositoryOwnerLogin(repositoryNameWithOwner),
};
}
function resolvePullRequestHeadIdentity(pr: PullRequestInfo): PullRequestHeadIdentity {
const repositoryNameWithOwner = normalizeOptionalRepositoryNameWithOwner(
resolvePullRequestHeadRepositoryNameWithOwner(pr),
);
return {
repositoryNameWithOwner,
ownerLogin:
normalizeOptionalOwnerLogin(pr.headRepositoryOwnerLogin) ??
parseRepositoryOwnerLogin(repositoryNameWithOwner),
};
}
export function matchesBranchHeadContext(
pr: PullRequestInfo,
headContext: Pick<
BranchHeadContext,
@@ -263,44 +294,51 @@ function matchesBranchHeadContext(
return false;
}
const expectedHeadRepository = normalizeOptionalRepositoryNameWithOwner(
headContext.headRepositoryNameWithOwner,
);
const expectedHeadOwner =
normalizeOptionalOwnerLogin(headContext.headRepositoryOwnerLogin) ??
parseRepositoryOwnerLogin(expectedHeadRepository);
const prHeadRepository = normalizeOptionalRepositoryNameWithOwner(
resolvePullRequestHeadRepositoryNameWithOwner(pr),
);
const prHeadOwner =
normalizeOptionalOwnerLogin(pr.headRepositoryOwnerLogin) ??
parseRepositoryOwnerLogin(prHeadRepository);
const expectedHead = resolveExpectedHeadIdentity(headContext);
const pullRequestHead = resolvePullRequestHeadIdentity(pr);
if (expectedHead.repositoryNameWithOwner) {
if (pullRequestHead.repositoryNameWithOwner) {
if (expectedHead.repositoryNameWithOwner !== pullRequestHead.repositoryNameWithOwner) {
return false;
}
}
if (expectedHead.ownerLogin && pullRequestHead.ownerLogin) {
if (expectedHead.ownerLogin !== pullRequestHead.ownerLogin) {
return false;
}
}
}
if (expectedHead.ownerLogin && pullRequestHead.ownerLogin) {
if (expectedHead.ownerLogin !== pullRequestHead.ownerLogin) {
return false;
}
}
if (headContext.isCrossRepository) {
if (pr.isCrossRepository === false) {
return false;
}
if ((expectedHeadRepository || expectedHeadOwner) && !prHeadRepository && !prHeadOwner) {
return false;
}
if (expectedHeadRepository && prHeadRepository && expectedHeadRepository !== prHeadRepository) {
return false;
}
if (expectedHeadOwner && prHeadOwner && expectedHeadOwner !== prHeadOwner) {
if (
(expectedHead.repositoryNameWithOwner || expectedHead.ownerLogin) &&
!pullRequestHead.repositoryNameWithOwner &&
!pullRequestHead.ownerLogin
) {
return false;
}
return true;
}
if (pr.isCrossRepository === true) {
return false;
}
if (expectedHeadRepository && prHeadRepository && expectedHeadRepository !== prHeadRepository) {
return false;
}
if (expectedHeadOwner && prHeadOwner && expectedHeadOwner !== prHeadOwner) {
return false;
if (
(!expectedHead.repositoryNameWithOwner && !expectedHead.ownerLogin) ||
(!pullRequestHead.repositoryNameWithOwner && !pullRequestHead.ownerLogin)
) {
return false;
}
}
return true;
}
@@ -8,9 +8,15 @@ import * as PlatformError from "effect/PlatformError";
import * as WorkspacePaths from "../workspace/WorkspacePaths.ts";
import * as ProjectFaviconResolver from "./ProjectFaviconResolver.ts";
import * as T3ProjectFileLoader from "./T3ProjectFileLoader.ts";
const TestLayer = Layer.empty.pipe(
Layer.provideMerge(ProjectFaviconResolver.layer.pipe(Layer.provide(WorkspacePaths.layer))),
Layer.provideMerge(
ProjectFaviconResolver.layer.pipe(
Layer.provide(WorkspacePaths.layer),
Layer.provide(T3ProjectFileLoader.layer),
),
),
Layer.provideMerge(NodeServices.layer),
);
@@ -37,7 +43,7 @@ const writeTextFile = Effect.fn("writeTextFile")(function* (
const makeResolverWithFileSystem = (fileSystem: FileSystem.FileSystem) =>
ProjectFaviconResolver.make.pipe(
Effect.provide(WorkspacePaths.layer),
Effect.provide([WorkspacePaths.layer, T3ProjectFileLoader.layer]),
Effect.provideService(FileSystem.FileSystem, fileSystem),
);
@@ -56,6 +62,63 @@ it.layer(TestLayer)("ProjectFaviconResolverLive", (it) => {
}),
);
it.effect("prefers a t3.json iconPath over well-known files", () =>
Effect.gen(function* () {
const resolver = yield* ProjectFaviconResolver.ProjectFaviconResolver;
const cwd = yield* makeTempDir;
yield* writeTextFile(cwd, "t3.json", '{ "iconPath": "brand/mark.svg" }');
yield* writeTextFile(cwd, "brand/mark.svg", "<svg>mark</svg>");
yield* writeTextFile(cwd, "favicon.svg", "<svg>favicon</svg>");
const resolved = yield* resolver.resolvePath(cwd);
expect(resolved).not.toBeNull();
expect(resolved).toContain("brand/mark.svg");
}),
);
it.effect("falls back to well-known files when the t3.json iconPath does not exist", () =>
Effect.gen(function* () {
const resolver = yield* ProjectFaviconResolver.ProjectFaviconResolver;
const cwd = yield* makeTempDir;
yield* writeTextFile(cwd, "t3.json", '{ "iconPath": "brand/missing.svg" }');
yield* writeTextFile(cwd, "favicon.svg", "<svg>favicon</svg>");
const resolved = yield* resolver.resolvePath(cwd);
expect(resolved).not.toBeNull();
expect(resolved).toContain("favicon.svg");
}),
);
it.effect("ignores invalid t3.json files", () =>
Effect.gen(function* () {
const resolver = yield* ProjectFaviconResolver.ProjectFaviconResolver;
const cwd = yield* makeTempDir;
yield* writeTextFile(cwd, "t3.json", "{ not json");
yield* writeTextFile(cwd, "favicon.svg", "<svg>favicon</svg>");
const resolved = yield* resolver.resolvePath(cwd);
expect(resolved).not.toBeNull();
expect(resolved).toContain("favicon.svg");
}),
);
it.effect("does not resolve a t3.json iconPath outside the workspace root", () =>
Effect.gen(function* () {
const resolver = yield* ProjectFaviconResolver.ProjectFaviconResolver;
const parent = yield* makeTempDir;
const cwd = `${parent}/app`;
yield* writeTextFile(parent, "secret.svg", "<svg>secret</svg>");
yield* writeTextFile(cwd, "t3.json", '{ "iconPath": "../secret.svg" }');
const resolved = yield* resolver.resolvePath(cwd);
expect(resolved).toBeNull();
}),
);
it.effect("resolves icon hrefs from project source files", () =>
Effect.gen(function* () {
const resolver = yield* ProjectFaviconResolver.ProjectFaviconResolver;
@@ -16,6 +16,7 @@ import * as PlatformError from "effect/PlatformError";
import * as Schema from "effect/Schema";
import * as WorkspacePaths from "../workspace/WorkspacePaths.ts";
import * as T3ProjectFileLoader from "./T3ProjectFileLoader.ts";
// Well-known favicon paths checked in order.
const FAVICON_CANDIDATES = [
@@ -117,6 +118,7 @@ export const make = Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const workspacePaths = yield* WorkspacePaths.WorkspacePaths;
const projectFileLoader = yield* T3ProjectFileLoader.T3ProjectFileLoader;
const resolveIconHref = (href: string): ReadonlyArray<string> => {
const clean = href.replace(/^\//, "");
@@ -177,6 +179,15 @@ export const make = Effect.gen(function* () {
}),
),
);
// A t3.json iconPath takes precedence over the well-known locations.
const projectFile = yield* projectFileLoader.load(projectCwd);
if (Option.isSome(projectFile) && projectFile.value.iconPath !== undefined) {
const existing = yield* findExistingFile(projectCwd, [projectFile.value.iconPath]);
if (existing) {
return existing;
}
}
for (const candidate of FAVICON_CANDIDATES) {
const existing = yield* findExistingFile(projectCwd, [candidate]);
if (existing) {
@@ -0,0 +1,89 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { it, describe, expect } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Path from "effect/Path";
import * as T3ProjectFileLoader from "./T3ProjectFileLoader.ts";
const TestLayer = Layer.empty.pipe(
Layer.provideMerge(T3ProjectFileLoader.layer),
Layer.provideMerge(NodeServices.layer),
);
const makeTempDir = Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
return yield* fileSystem.makeTempDirectoryScoped({
prefix: "t3code-project-file-",
});
});
const writeProjectFile = Effect.fn("writeProjectFile")(function* (cwd: string, contents: string) {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
yield* fileSystem.writeFileString(path.join(cwd, "t3.json"), contents).pipe(Effect.orDie);
});
it.layer(TestLayer)("T3ProjectFileLoader", (it) => {
describe("load", () => {
it.effect("loads and decodes a valid t3.json", () =>
Effect.gen(function* () {
const loader = yield* T3ProjectFileLoader.T3ProjectFileLoader;
const cwd = yield* makeTempDir;
yield* writeProjectFile(
cwd,
`{
// JSONC is tolerated
"iconPath": "assets/logo.svg",
"scripts": [{ "name": "Dev", "command": "pnpm dev" }],
}`,
);
const loaded = yield* loader.load(cwd);
expect(Option.isSome(loaded)).toBe(true);
if (Option.isSome(loaded)) {
expect(loaded.value.iconPath).toBe("assets/logo.svg");
expect(loaded.value.scripts).toEqual([{ name: "Dev", command: "pnpm dev" }]);
}
}),
);
it.effect("returns none when t3.json is missing", () =>
Effect.gen(function* () {
const loader = yield* T3ProjectFileLoader.T3ProjectFileLoader;
const cwd = yield* makeTempDir;
const loaded = yield* loader.load(cwd);
expect(Option.isNone(loaded)).toBe(true);
}),
);
it.effect("returns none for malformed JSON without failing", () =>
Effect.gen(function* () {
const loader = yield* T3ProjectFileLoader.T3ProjectFileLoader;
const cwd = yield* makeTempDir;
yield* writeProjectFile(cwd, "{ not json");
const loaded = yield* loader.load(cwd);
expect(Option.isNone(loaded)).toBe(true);
}),
);
it.effect("returns none for schema-invalid files without failing", () =>
Effect.gen(function* () {
const loader = yield* T3ProjectFileLoader.T3ProjectFileLoader;
const cwd = yield* makeTempDir;
yield* writeProjectFile(cwd, '{ "scripts": [{ "name": "Dev" }] }');
const loaded = yield* loader.load(cwd);
expect(Option.isNone(loaded)).toBe(true);
}),
);
});
});
@@ -0,0 +1,108 @@
/**
* T3ProjectFileLoader - Effect service that loads the checked-in `t3.json`
* project file from a workspace root.
*
* Loading is best-effort: a missing file resolves to `Option.none`, and
* unreadable or invalid files are logged and treated as absent so callers
* can fall back to their defaults.
*
* @module T3ProjectFileLoader
*/
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Path from "effect/Path";
import * as Schema from "effect/Schema";
import { T3_PROJECT_FILE_NAME, type T3ProjectFile } from "@t3tools/contracts";
import { T3ProjectFileFromJson } from "@t3tools/shared/t3ProjectFile";
const decodeT3ProjectFileJson = Schema.decodeEffect(T3ProjectFileFromJson);
export class T3ProjectFileLoadError extends Schema.TaggedErrorClass<T3ProjectFileLoadError>()(
"T3ProjectFileLoadError",
{
operation: Schema.Literals(["read", "decode"]),
workspaceRoot: Schema.String,
filePath: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to ${this.operation} ${T3_PROJECT_FILE_NAME} at ${this.filePath}.`;
}
}
/** Service tag for t3.json project file loading. */
export class T3ProjectFileLoader extends Context.Service<
T3ProjectFileLoader,
{
/**
* Load and decode `t3.json` at the workspace root.
*
* Never fails: missing, unreadable, or invalid files resolve to
* `Option.none` (invalid files are logged as warnings).
*/
readonly load: (workspaceRoot: string) => Effect.Effect<Option.Option<T3ProjectFile>>;
}
>()("t3/project/T3ProjectFileLoader") {}
const logT3ProjectFileLoadError = (error: T3ProjectFileLoadError) =>
Effect.logWarning(error).pipe(
Effect.annotateLogs({
operation: error.operation,
workspaceRoot: error.workspaceRoot,
filePath: error.filePath,
errorTag: error._tag,
}),
);
export const make = Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const load: T3ProjectFileLoader["Service"]["load"] = Effect.fn("T3ProjectFileLoader.load")(
function* (workspaceRoot) {
const filePath = path.join(workspaceRoot, T3_PROJECT_FILE_NAME);
const raw = yield* fileSystem.readFileString(filePath).pipe(
Effect.map(Option.some),
Effect.catchTags({
PlatformError: (error) =>
error.reason._tag === "NotFound"
? Effect.succeed(Option.none<string>())
: logT3ProjectFileLoadError(
new T3ProjectFileLoadError({
operation: "read",
workspaceRoot,
filePath,
cause: error,
}),
).pipe(Effect.as(Option.none<string>())),
}),
);
if (Option.isNone(raw)) {
return Option.none<T3ProjectFile>();
}
return yield* decodeT3ProjectFileJson(raw.value).pipe(
Effect.map(Option.some),
Effect.catchTags({
SchemaError: (error) =>
logT3ProjectFileLoadError(
new T3ProjectFileLoadError({
operation: "decode",
workspaceRoot,
filePath,
cause: error,
}),
).pipe(Effect.as(Option.none<T3ProjectFile>())),
}),
);
},
);
return T3ProjectFileLoader.of({ load });
});
export const layer = Layer.effect(T3ProjectFileLoader, make);
@@ -356,6 +356,25 @@ describe("ClaudeAdapterLive", () => {
);
});
it.effect("derives auto permission mode from auto runtime policy without skip flag", () => {
const harness = makeHarness();
return Effect.gen(function* () {
const adapter = yield* ClaudeAdapter;
yield* adapter.startSession({
threadId: THREAD_ID,
provider: ProviderDriverKind.make("claudeAgent"),
runtimeMode: "auto",
});
const createInput = harness.getLastCreateQueryInput();
assert.equal(createInput?.options.permissionMode, "auto");
assert.equal(createInput?.options.allowDangerouslySkipPermissions, undefined);
}).pipe(
Effect.provideService(Random.Random, makeDeterministicRandomService()),
Effect.provide(harness.layer),
);
});
it.effect("loads Claude filesystem settings sources for SDK sessions", () => {
const harness = makeHarness();
return Effect.gen(function* () {
@@ -3509,6 +3509,7 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
const effectiveEffort = getEffectiveClaudeAgentEffort(effort, modelSelection?.model);
const runtimeModeToPermission: Record<string, PermissionMode> = {
"auto-accept-edits": "acceptEdits",
auto: "auto",
"full-access": "bypassPermissions",
};
const permissionMode = runtimeModeToPermission[input.runtimeMode];
@@ -104,6 +104,7 @@ describe("buildTurnStartParams", () => {
NodeAssert.deepStrictEqual(params, {
threadId: "provider-thread-1",
approvalPolicy: "never",
approvalsReviewer: "user",
sandboxPolicy: {
type: "dangerFullAccess",
},
@@ -149,6 +150,7 @@ describe("buildTurnStartParams", () => {
NodeAssert.deepStrictEqual(params, {
threadId: "provider-thread-1",
approvalPolicy: "on-request",
approvalsReviewer: "user",
sandboxPolicy: {
type: "workspaceWrite",
},
@@ -193,6 +195,31 @@ describe("buildTurnStartParams", () => {
NodeAssert.ok(settings?.developer_instructions?.includes(`as ${DEFAULT_MODEL} with medium`));
});
it.effect("routes approvals to the auto reviewer in auto mode", () =>
Effect.gen(function* () {
const params = yield* buildTurnStartParams({
threadId: "provider-thread-1",
runtimeMode: "auto",
prompt: "Ship it",
});
NodeAssert.deepStrictEqual(params, {
threadId: "provider-thread-1",
approvalPolicy: "on-request",
approvalsReviewer: "auto_review",
sandboxPolicy: {
type: "workspaceWrite",
},
input: [
{
type: "text",
text: "Ship it",
},
],
});
}),
);
it("omits collaboration mode when interaction mode is absent", () => {
const params = Effect.runSync(
buildTurnStartParams({
@@ -205,6 +232,7 @@ describe("buildTurnStartParams", () => {
NodeAssert.deepStrictEqual(params, {
threadId: "provider-thread-1",
approvalPolicy: "untrusted",
approvalsReviewer: "user",
sandboxPolicy: {
type: "readOnly",
},
@@ -264,23 +264,35 @@ function readResumeCursorThreadId(
function runtimeModeToThreadConfig(input: RuntimeMode): {
readonly approvalPolicy: EffectCodexSchema.V2ThreadStartParams__AskForApproval;
readonly sandbox: EffectCodexSchema.V2ThreadStartParams__SandboxMode;
// Always explicit: omitting the field on resume keeps the thread's previous
// reviewer, which would leave auto_review sticky after switching modes.
readonly approvalsReviewer: EffectCodexSchema.V2ThreadStartParams__ApprovalsReviewer;
} {
switch (input) {
case "approval-required":
return {
approvalPolicy: "untrusted",
sandbox: "read-only",
approvalsReviewer: "user",
};
case "auto-accept-edits":
return {
approvalPolicy: "on-request",
sandbox: "workspace-write",
approvalsReviewer: "user",
};
case "auto":
return {
approvalPolicy: "on-request",
sandbox: "workspace-write",
approvalsReviewer: "auto_review",
};
case "full-access":
default:
return {
approvalPolicy: "never",
sandbox: "danger-full-access",
approvalsReviewer: "user",
};
}
}
@@ -296,6 +308,7 @@ function buildThreadStartParams(input: {
cwd: input.cwd,
approvalPolicy: config.approvalPolicy,
sandbox: config.sandbox,
approvalsReviewer: config.approvalsReviewer,
...(input.model ? { model: input.model } : {}),
...(input.serviceTier ? { serviceTier: input.serviceTier } : {}),
};
@@ -310,6 +323,7 @@ function runtimeModeToTurnSandboxPolicy(
type: "readOnly",
};
case "auto-accept-edits":
case "auto":
return {
type: "workspaceWrite",
};
@@ -382,6 +396,7 @@ export function buildTurnStartParams(input: {
threadId: input.threadId,
input: turnInput,
approvalPolicy: config.approvalPolicy,
approvalsReviewer: config.approvalsReviewer,
sandboxPolicy: runtimeModeToTurnSandboxPolicy(input.runtimeMode),
...(input.model ? { model: input.model } : {}),
...(input.serviceTier ? { serviceTier: input.serviceTier } : {}),
+5 -1
View File
@@ -92,6 +92,7 @@ import * as PreviewManager from "./preview/Manager.ts";
import * as PortScanner from "./preview/PortScanner.ts";
import * as BrowserTraceCollector from "./observability/BrowserTraceCollector.ts";
import * as ProjectFaviconResolver from "./project/ProjectFaviconResolver.ts";
import * as T3ProjectFileLoader from "./project/T3ProjectFileLoader.ts";
import * as ProjectSetupScriptRunner from "./project/ProjectSetupScriptRunner.ts";
import * as RepositoryIdentityResolver from "./project/RepositoryIdentityResolver.ts";
import * as ServerEnvironment from "./environment/ServerEnvironment.ts";
@@ -501,7 +502,10 @@ const buildAppUnderTest = (options?: {
Layer.provide(WorkspacePaths.layer),
Layer.provide(workspaceEntriesLayer),
),
ProjectFaviconResolver.layer.pipe(Layer.provide(WorkspacePaths.layer)),
ProjectFaviconResolver.layer.pipe(
Layer.provide(WorkspacePaths.layer),
Layer.provide(T3ProjectFileLoader.layer),
),
);
const gitWorkflowLayer = GitWorkflowService.layer.pipe(
Layer.provideMerge(vcsDriverRegistryLayer),
+8 -1
View File
@@ -54,6 +54,7 @@ import { hasCloudPublicConfig } from "./cloud/publicConfig.ts";
import { ProviderRegistryLive } from "./provider/Layers/ProviderRegistry.ts";
import * as ServerSettings from "./serverSettings.ts";
import * as ProjectFaviconResolver from "./project/ProjectFaviconResolver.ts";
import * as T3ProjectFileLoader from "./project/T3ProjectFileLoader.ts";
import * as RepositoryIdentityResolver from "./project/RepositoryIdentityResolver.ts";
import * as WorkspaceEntries from "./workspace/WorkspaceEntries.ts";
import * as WorkspaceFileSystem from "./workspace/WorkspaceFileSystem.ts";
@@ -79,6 +80,7 @@ import { serverRelayBrokerTracingLayer } from "./cloud/relayTracing.ts";
import * as CloudManagedEndpointRuntime from "./cloud/ManagedEndpointRuntime.ts";
import * as CloudCliTokenManager from "./cloud/CliTokenManager.ts";
import * as CloudCliState from "./cloud/CliState.ts";
import * as ServerSelfUpdate from "./cloud/selfUpdate.ts";
import * as ProcessDiagnostics from "./diagnostics/ProcessDiagnostics.ts";
import * as ProcessResourceMonitor from "./diagnostics/ProcessResourceMonitor.ts";
import * as TraceDiagnostics from "./diagnostics/TraceDiagnostics.ts";
@@ -264,6 +266,7 @@ const WorkspaceLayerLive = Layer.mergeAll(
const ProjectFaviconResolverLayerLive = ProjectFaviconResolver.layer.pipe(
Layer.provide(WorkspacePaths.layer),
Layer.provide(T3ProjectFileLoader.layer),
);
const AuthLayerLive = EnvironmentAuth.layer.pipe(
@@ -361,7 +364,11 @@ export const makeRoutesLayer = Layer.mergeAll(
websocketRpcRouteLayer,
),
McpHttpServer.layer.pipe(Layer.provide(McpSessionRegistry.layer)),
).pipe(Layer.provide(PreviewAutomationBroker.layer), Layer.provide(browserApiCorsLayer));
).pipe(
Layer.provide(PreviewAutomationBroker.layer),
Layer.provide(ServerSelfUpdate.layer),
Layer.provide(browserApiCorsLayer),
);
export const makeServerLayer = Layer.unwrap(
Effect.gen(function* () {
@@ -713,6 +713,20 @@ it.layer(TestLayer)("GitVcsDriver core integration", (it) => {
});
assert.equal(reusedForSshScheme, "origin");
const reusedForBareSshScheme = yield* driver.ensureRemote({
cwd,
preferredName: "pingdotgg",
url: "ssh://github.com/pingdotgg/t3code",
});
assert.equal(reusedForBareSshScheme, "origin");
const reusedForSshPort = yield* driver.ensureRemote({
cwd,
preferredName: "pingdotgg",
url: "ssh://[email protected]:22/pingdotgg/t3code",
});
assert.equal(reusedForSshPort, "origin");
const reusedForSshWithPort = yield* driver.ensureRemote({
cwd,
preferredName: "pingdotgg",
+9
View File
@@ -78,6 +78,7 @@ import {
} from "./observability/RpcInstrumentation.ts";
import * as ProviderRegistry from "./provider/Services/ProviderRegistry.ts";
import * as ProviderMaintenanceRunner from "./provider/providerMaintenanceRunner.ts";
import * as ServerSelfUpdate from "./cloud/selfUpdate.ts";
import * as ServerLifecycleEvents from "./serverLifecycleEvents.ts";
import * as ServerRuntimeStartup from "./serverRuntimeStartup.ts";
import * as ServerSettings from "./serverSettings.ts";
@@ -296,6 +297,7 @@ const RPC_REQUIRED_SCOPE = new Map<string, AuthEnvironmentScope>([
[WS_METHODS.serverGetConfig, AuthOrchestrationReadScope],
[WS_METHODS.serverRefreshProviders, AuthOrchestrationOperateScope],
[WS_METHODS.serverUpdateProvider, AuthOrchestrationOperateScope],
[WS_METHODS.serverUpdateServer, AuthOrchestrationOperateScope],
[WS_METHODS.serverUpsertKeybinding, AuthOrchestrationOperateScope],
[WS_METHODS.serverRemoveKeybinding, AuthOrchestrationOperateScope],
[WS_METHODS.serverGetSettings, AuthOrchestrationReadScope],
@@ -418,6 +420,7 @@ const makeWsRpcLayer = (
const portDiscovery = yield* PortScanner.PortDiscovery;
const providerRegistry = yield* ProviderRegistry.ProviderRegistry;
const providerMaintenanceRunner = yield* ProviderMaintenanceRunner.ProviderMaintenanceRunner;
const serverSelfUpdate = yield* ServerSelfUpdate.ServerSelfUpdate;
const config = yield* ServerConfig.ServerConfig;
const lifecycleEvents = yield* ServerLifecycleEvents.ServerLifecycleEvents;
const serverSettings = yield* ServerSettings.ServerSettingsService;
@@ -1476,6 +1479,10 @@ const makeWsRpcLayer = (
"rpc.aggregate": "server",
},
),
[WS_METHODS.serverUpdateServer]: (input) =>
observeRpcEffect(WS_METHODS.serverUpdateServer, serverSelfUpdate.update(input), {
"rpc.aggregate": "server",
}),
[WS_METHODS.serverUpsertKeybinding]: (rule) =>
observeRpcEffect(
WS_METHODS.serverUpsertKeybinding,
@@ -2079,6 +2086,7 @@ const makeWsRpcLayer = (
export const websocketRpcRouteLayer = Layer.unwrap(
Effect.gen(function* () {
const previewAutomationBroker = yield* PreviewAutomationBroker.PreviewAutomationBroker;
const serverSelfUpdate = yield* ServerSelfUpdate.ServerSelfUpdate;
return HttpRouter.add(
"GET",
"/ws",
@@ -2101,6 +2109,7 @@ export const websocketRpcRouteLayer = Layer.unwrap(
makeWsRpcLayer(session, previewAutomationBroker).pipe(
Layer.provideMerge(RpcSerialization.layerJson),
Layer.provide(ProviderMaintenanceRunner.layer),
Layer.provide(Layer.succeed(ServerSelfUpdate.ServerSelfUpdate, serverSelfUpdate)),
Layer.provide(
SourceControlDiscovery.layer.pipe(
Layer.provide(
+5 -5
View File
@@ -84,7 +84,7 @@ function SidebarControl() {
"pointer-events-auto",
isSidebarVisible &&
stageBackdropVariant &&
"hover:bg-white/15 [&_svg]:text-white/85! [&_svg]:hover:text-white!",
"[:hover,[data-pressed]]:bg-white/15 focus-visible:ring-white/90 focus-visible:ring-offset-blue-700 [&_svg]:stroke-white/90! [&_svg]:opacity-100! [&_svg]:hover:stroke-white!",
)}
aria-label="Toggle main sidebar"
/>
@@ -106,6 +106,7 @@ export function AppSidebarLayout({ children }: { children: ReactNode }) {
const pathname = useLocation({ select: (location) => location.pathname });
const isOnSettings = pathname === "/settings" || pathname.startsWith("/settings/");
const useSidebarV2 = sidebarV2Enabled && !isOnSettings;
const useSidebarV2Theme = useSidebarV2 || isOnSettings;
const isMacosDesktop = isElectron && isMacPlatform(navigator.platform);
const [sidebarWidth, setSidebarWidth] = useState(readInitialThreadSidebarWidth);
const sidebarMaximumWidth = resolveThreadSidebarMaximumWidth(window.innerWidth);
@@ -164,10 +165,9 @@ export function AppSidebarLayout({ children }: { children: ReactNode }) {
<Sidebar
side="left"
collapsible="offcanvas"
className={cn(
"border-r border-border text-foreground",
useSidebarV2 ? "app-sidebar" : "bg-card",
)}
data-app-sidebar=""
data-sidebar-version={useSidebarV2Theme ? "v2" : "v1"}
className="border-r border-sidebar-border bg-sidebar text-sidebar-foreground"
resizable={{
maxWidth: sidebarMaximumWidth,
minWidth: THREAD_SIDEBAR_MIN_WIDTH,
@@ -11,6 +11,7 @@ import {
resolveEnvModeLabel,
resolveBranchToolbarValue,
resolveLockedWorkspaceLabel,
resolveLocalCheckoutBranchMismatch,
shouldIncludeBranchPickerItem,
shouldShowEnvironmentIndicator,
} from "./BranchToolbar.logic";
@@ -85,6 +86,55 @@ describe("resolveBranchToolbarValue", () => {
});
});
describe("resolveLocalCheckoutBranchMismatch", () => {
it("detects when a local thread is associated with a different branch than the checkout", () => {
expect(
resolveLocalCheckoutBranchMismatch({
effectiveEnvMode: "local",
activeWorktreePath: null,
activeThreadBranch: "feature/thread",
currentGitBranch: "feature/current",
}),
).toEqual({
threadBranch: "feature/thread",
currentBranch: "feature/current",
});
});
it("ignores matching local checkout state", () => {
expect(
resolveLocalCheckoutBranchMismatch({
effectiveEnvMode: "local",
activeWorktreePath: null,
activeThreadBranch: "feature/thread",
currentGitBranch: "feature/thread",
}),
).toBeNull();
});
it("ignores dedicated worktrees because their checkout is already thread-scoped", () => {
expect(
resolveLocalCheckoutBranchMismatch({
effectiveEnvMode: "worktree",
activeWorktreePath: "/repo/.t3/worktrees/feature-thread",
activeThreadBranch: "feature/thread",
currentGitBranch: "feature/current",
}),
).toBeNull();
});
it("ignores new-worktree base selection before a worktree exists", () => {
expect(
resolveLocalCheckoutBranchMismatch({
effectiveEnvMode: "worktree",
activeWorktreePath: null,
activeThreadBranch: "feature/base",
currentGitBranch: "main",
}),
).toBeNull();
});
});
describe("resolveEnvironmentOptionLabel", () => {
it("prefers the primary environment's machine label", () => {
expect(
@@ -108,6 +108,22 @@ export function resolveBranchToolbarValue(input: {
return currentGitBranch ?? activeThreadBranch;
}
export function resolveLocalCheckoutBranchMismatch(input: {
effectiveEnvMode: EnvMode;
activeWorktreePath: string | null;
activeThreadBranch: string | null;
currentGitBranch: string | null;
}): { threadBranch: string; currentBranch: string } | null {
const { effectiveEnvMode, activeWorktreePath, activeThreadBranch, currentGitBranch } = input;
if (effectiveEnvMode !== "local" || activeWorktreePath !== null) {
return null;
}
if (!activeThreadBranch || !currentGitBranch || activeThreadBranch === currentGitBranch) {
return null;
}
return { threadBranch: activeThreadBranch, currentBranch: currentGitBranch };
}
export function resolveBranchSelectionTarget(input: {
activeProjectCwd: string;
activeWorktreePath: string | null;
+1 -1
View File
@@ -248,7 +248,7 @@ export const BranchToolbar = memo(function BranchToolbar({
if (!hasActiveThread || !activeProject) return null;
return (
<div className="mx-auto flex w-full max-w-3xl items-center gap-2 px-2.5 pb-3 pt-1 sm:px-3">
<div className="flex w-full items-center gap-2 border-t border-border/60 px-3 py-2">
{isMobile ? (
<MobileRunContextSelector
envLocked={envLocked}
@@ -3,7 +3,7 @@ import {
isAtomCommandInterrupted,
squashAtomCommandFailure,
} from "@t3tools/client-runtime/state/runtime";
import type { EnvironmentId, VcsRef, ThreadId } from "@t3tools/contracts";
import type { ContextMenuItem, EnvironmentId, VcsRef, ThreadId } from "@t3tools/contracts";
import { LegendList, type LegendListRef } from "@legendapp/list/react";
import { ChevronDownIcon, GitBranchIcon, RefreshCwIcon, SearchIcon } from "lucide-react";
import {
@@ -17,9 +17,12 @@ import {
useRef,
useState,
useTransition,
type MouseEvent as ReactMouseEvent,
} from "react";
import { useComposerDraftStore, type DraftId } from "../composerDraftStore";
import { writeTextToClipboard } from "../hooks/useCopyToClipboard";
import { readLocalApi } from "../localApi";
import { useOpenPrLink } from "../lib/openPullRequestLink";
import { usePaginatedBranches } from "../state/queries";
import { useProject, useThread } from "../state/entities";
@@ -317,6 +320,45 @@ export function BranchToolbarBranchSelector({
// ---------------------------------------------------------------------------
// Branch actions
// ---------------------------------------------------------------------------
const copyBranchName = useCallback((branchName: string) => {
void writeTextToClipboard(branchName, "branch name").then(
(didCopy) => {
if (!didCopy) return;
toastManager.add({
type: "success",
title: "Branch name copied",
description: branchName,
});
},
(error: unknown) => {
toastManager.add(
stackedThreadToast({
type: "error",
title: "Failed to copy branch name",
description: toBranchActionErrorMessage(error),
}),
);
},
);
}, []);
const handleBranchContextMenu = useCallback(
(event: ReactMouseEvent, branchName: string | null) => {
if (!branchName) return;
const api = readLocalApi();
if (!api) return;
event.preventDefault();
event.stopPropagation();
const items: ContextMenuItem<"copy-branch-name">[] = [
{ id: "copy-branch-name", label: "Copy branch name", icon: "copy" },
];
void api.contextMenu.show(items, { x: event.clientX, y: event.clientY }).then((action) => {
if (action === "copy-branch-name") copyBranchName(branchName);
});
},
[copyBranchName],
);
const runBranchAction = (action: () => Promise<void>) => {
startBranchActionTransition(async () => {
await action();
@@ -431,6 +473,7 @@ export function BranchToolbarBranchSelector({
const worktreeBaseBranchCandidate = isInitialBranchesLoadPending
? null
: (defaultBranchName ?? currentGitBranch);
useEffect(() => {
if (
effectiveEnvMode !== "worktree" ||
@@ -547,7 +590,11 @@ export function BranchToolbarBranchSelector({
});
// PR pill shown next to the branch selector when the active branch has one.
const branchPr = resolveThreadPr(resolvedActiveBranch, branchStatusQuery.data ?? null);
const branchPr = resolveThreadPr({
threadBranch: resolvedActiveBranch,
gitStatus: branchStatusQuery.data ?? null,
hasDedicatedWorktree: activeWorktreePath !== null,
});
const branchPrStatus = prStatusIndicator(branchPr, branchStatusQuery.data?.sourceControlProvider);
// Action-oriented tooltip (the pill opens the PR), distinct from the sidebar's
// state-description tooltip.
@@ -624,6 +671,7 @@ export function BranchToolbarBranchSelector({
value={itemValue}
className="pe-1.5"
onClick={() => selectBranch(refName)}
onContextMenu={(event) => handleBranchContextMenu(event, itemValue)}
>
<div className="flex w-full min-w-0 items-center justify-between gap-2">
<span className="min-w-0 flex-1 truncate">{itemValue}</span>
@@ -674,15 +722,23 @@ export function BranchToolbarBranchSelector({
<TooltipPopup side="top">{branchPrTooltip}</TooltipPopup>
</Tooltip>
) : null}
<ComboboxTrigger
render={<Button variant="ghost" size="xs" />}
className="min-w-0 text-muted-foreground/70 hover:text-foreground/80"
disabled={isInitialBranchesLoadPending || isBranchActionPending}
{/* Context menu lives on the wrapper: the disabled Button has
pointer-events-none, so the trigger itself never sees right-clicks
while refs are loading or a branch action is pending. */}
<span
className="flex min-w-0"
onContextMenu={(event) => handleBranchContextMenu(event, resolvedActiveBranch)}
>
<GitBranchIcon className="size-3 shrink-0 opacity-70" />
<span className="min-w-0 max-w-[240px] truncate">{triggerLabel}</span>
<ChevronDownIcon className="size-3 shrink-0 opacity-50" />
</ComboboxTrigger>
<ComboboxTrigger
render={<Button variant="ghost" size="xs" />}
className="min-w-0 text-muted-foreground/70 hover:text-foreground/80"
disabled={isInitialBranchesLoadPending || isBranchActionPending}
>
<GitBranchIcon className="size-3 shrink-0 opacity-70" />
<span className="min-w-0 max-w-[240px] truncate">{triggerLabel}</span>
<ChevronDownIcon className="size-3 shrink-0 opacity-50" />
</ComboboxTrigger>
</span>
</div>
<ComboboxPopup align="end" side="top" className="flex w-80 flex-col">
<div className="shrink-0 px-3 pt-2.5">
@@ -20,6 +20,7 @@ import {
hasServerAcknowledgedLocalDispatch,
reconcileMountedTerminalThreadIds,
reconcileRetainedMountedThreadIds,
resolveThreadMetadataUpdateForNextTurn,
resolveSendEnvMode,
shouldWriteThreadErrorToCurrentServerThread,
} from "./ChatView.logic";
@@ -79,6 +80,34 @@ const readySession = {
updatedAt: "2026-03-29T00:00:10.000Z",
};
describe("resolveThreadMetadataUpdateForNextTurn", () => {
const modelSelection = {
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5.4",
};
it("updates a stale local thread branch to the active checkout", () => {
expect(
resolveThreadMetadataUpdateForNextTurn({
currentModelSelection: modelSelection,
currentBranch: "feature/thread",
nextBranch: "feature/checkout",
}),
).toEqual({ branch: "feature/checkout", worktreePath: null });
});
it("does not write metadata when the model and branch are unchanged", () => {
expect(
resolveThreadMetadataUpdateForNextTurn({
currentModelSelection: modelSelection,
nextModelSelection: modelSelection,
currentBranch: "feature/current",
nextBranch: "feature/current",
}),
).toBeNull();
});
});
describe("buildThreadTurnInterruptInput", () => {
it("targets the session's active running turn", () => {
const activeTurnId = TurnId.make("turn-running");
+27
View File
@@ -27,6 +27,33 @@ export const MAX_HIDDEN_MOUNTED_PREVIEW_THREADS = 3;
export const LastInvokedScriptByProjectSchema = Schema.Record(ProjectId, Schema.String);
export function resolveThreadMetadataUpdateForNextTurn(input: {
currentModelSelection: ModelSelection;
nextModelSelection?: ModelSelection;
currentBranch: string | null;
nextBranch?: string;
}): {
modelSelection?: ModelSelection;
branch?: string;
worktreePath?: null;
} | null {
const nextModelSelection = input.nextModelSelection;
const modelSelectionChanged =
nextModelSelection !== undefined &&
(nextModelSelection.model !== input.currentModelSelection.model ||
nextModelSelection.instanceId !== input.currentModelSelection.instanceId ||
JSON.stringify(nextModelSelection.options ?? null) !==
JSON.stringify(input.currentModelSelection.options ?? null));
const branchChanged = input.nextBranch !== undefined && input.nextBranch !== input.currentBranch;
if (!modelSelectionChanged && !branchChanged) {
return null;
}
return {
...(modelSelectionChanged ? { modelSelection: nextModelSelection } : {}),
...(branchChanged ? { branch: input.nextBranch, worktreePath: null } : {}),
};
}
export function buildLocalDraftThread(
threadId: ThreadId,
draftThread: DraftThreadState,
+383 -154
View File
@@ -22,7 +22,7 @@ import {
TerminalOpenInput,
} from "@t3tools/contracts";
import {
connectionStatusText,
connectionStatusTitle,
type EnvironmentConnectionPresentation,
} from "@t3tools/client-runtime/connection";
import {
@@ -189,6 +189,7 @@ import { useEnvironmentQuery } from "../state/query";
import {
primaryServerAvailableEditorsAtom,
primaryServerKeybindingsAtom,
primaryServerSettingsAtom,
serverEnvironment,
} from "../state/server";
import { terminalEnvironment } from "../state/terminal";
@@ -212,8 +213,12 @@ import { ChatHeader } from "./chat/ChatHeader";
import { PanelLayoutControls, RightPanelMaximizeControl } from "./chat/PanelLayoutControls";
import { type ExpandedImagePreview } from "./chat/ExpandedImagePreview";
import { NoActiveThreadState } from "./NoActiveThreadState";
import { resolveEffectiveEnvMode } from "./BranchToolbar.logic";
import { ProviderStatusBanner } from "./chat/ProviderStatusBanner";
import { resolveEffectiveEnvMode, resolveLocalCheckoutBranchMismatch } from "./BranchToolbar.logic";
import {
getProviderStatusBannerKey,
ProviderStatusBanner,
shouldShowProviderStatusBanner,
} from "./chat/ProviderStatusBanner";
import { ThreadErrorBanner } from "./chat/ThreadErrorBanner";
import { ComposerBannerStack, type ComposerBannerStackItem } from "./chat/ComposerBannerStack";
import {
@@ -242,6 +247,7 @@ import {
deriveLockedProvider,
readFileAsDataUrl,
reconcileMountedTerminalThreadIds,
resolveThreadMetadataUpdateForNextTurn,
resolveSendEnvMode,
revokeBlobPreviewUrl,
revokeUserMessagePreviewUrls,
@@ -254,11 +260,14 @@ import { RightPanelSheet } from "./RightPanelSheet";
import { previewEnvironment } from "../state/preview";
import { useAtomCommand } from "../state/use-atom-command";
import { Button } from "./ui/button";
import { ServerUpdateAction } from "./ServerUpdateAction";
import {
buildVersionMismatchDismissalKey,
dismissVersionMismatch,
isVersionMismatchDismissed,
resolveServerConfigVersionMismatch,
resolveServerSelfUpdateCapability,
serverUpdateGuidance,
} from "../versionSkew";
import { useAssetUrls } from "../assets/assetUrls";
@@ -1077,6 +1086,10 @@ type LocalThreadErrorEntry = {
readonly at: number;
};
function chatActionErrorMessage(error: unknown): string {
return error instanceof Error ? error.message : "An error occurred.";
}
function ChatViewContent(props: ChatViewProps) {
const {
environmentId,
@@ -1104,6 +1117,7 @@ function ChatViewContent(props: ChatViewProps) {
const updateThreadMetadata = useAtomCommand(threadEnvironment.updateMetadata, {
reportFailure: false,
});
const switchGitRef = useAtomCommand(vcsEnvironment.switchRef, { reportFailure: false });
const setThreadRuntimeMode = useAtomCommand(threadEnvironment.setRuntimeMode, {
reportFailure: false,
});
@@ -1140,6 +1154,10 @@ function ChatViewContent(props: ChatViewProps) {
(store) => store.threadLastVisitedAtById[routeThreadKey],
);
const settings = useEnvironmentSettings(environmentId);
// New-thread defaults live in the primary environment's settings.json (the
// settings UI never writes to remote environments), so read them from the
// primary server rather than the thread's environment.
const primaryServerSettings = useAtomValue(primaryServerSettingsAtom);
const setStickyComposerModelSelection = useComposerDraftStore(
(store) => store.setStickyModelSelection,
);
@@ -1784,7 +1802,10 @@ function ChatViewContent(props: ChatViewProps) {
hasMultipleRegisteredEnvironments && activeThread
? `${environmentById.get(activeThread.environmentId)?.label ?? serverConfig?.environment.label ?? activeThread.environmentId} server`
: "server";
const composerBannerItems = useMemo<ComposerBannerStackItem[]>(() => {
const versionMismatchEnvironmentId =
versionMismatch && activeThread ? activeThread.environmentId : null;
const versionMismatchSelfUpdate = resolveServerSelfUpdateCapability(serverConfig);
const systemComposerBannerItems = useMemo<ComposerBannerStackItem[]>(() => {
const items: ComposerBannerStackItem[] = [];
if (activeEnvironmentUnavailableState) {
const connection = activeEnvironmentUnavailableState.connection;
@@ -1794,7 +1815,7 @@ function ChatViewContent(props: ChatViewProps) {
id: `environment-unavailable:${activeEnvironmentUnavailableState.environmentId}`,
variant: connection.phase === "error" ? "error" : "warning",
icon: <WifiOffIcon />,
title: `${activeEnvironmentUnavailableState.label}: ${connectionStatusText(connection)}`,
title: `${activeEnvironmentUnavailableState.label}: ${connectionStatusTitle(connection)}`,
description:
connection.error ??
"Reconnect this environment before sending messages or running actions.",
@@ -1822,7 +1843,12 @@ function ChatViewContent(props: ChatViewProps) {
),
});
}
if (showVersionMismatchBanner && versionMismatch && versionMismatchDismissKey) {
if (
showVersionMismatchBanner &&
versionMismatch &&
versionMismatchDismissKey &&
versionMismatchEnvironmentId
) {
items.push({
id: `version-mismatch:${versionMismatchDismissKey}`,
variant: "warning",
@@ -1831,9 +1857,21 @@ function ChatViewContent(props: ChatViewProps) {
description: (
<>
Client {versionMismatch.clientVersion} is connected to {versionMismatchServerLabel}{" "}
{versionMismatch.serverVersion}. Sync them if RPC calls or reconnects fail.
{versionMismatch.serverVersion}.{" "}
{serverUpdateGuidance(versionMismatchSelfUpdate, versionMismatchServerLabel)}
</>
),
// The desktop-managed guidance is already the description; the action
// slot would only repeat it.
actions:
versionMismatchSelfUpdate === "desktop-managed" ? undefined : (
<ServerUpdateAction
environmentId={versionMismatchEnvironmentId}
serverLabel={versionMismatchServerLabel}
selfUpdate={versionMismatchSelfUpdate}
targetVersion={versionMismatch.clientVersion}
/>
),
dismissLabel: "Dismiss version mismatch warning",
onDismiss: () => {
dismissVersionMismatch(versionMismatchDismissKey);
@@ -1846,9 +1884,12 @@ function ChatViewContent(props: ChatViewProps) {
activeEnvironmentUnavailableState,
handleReconnectActiveEnvironment,
navigate,
setDismissedVersionMismatchKey,
showVersionMismatchBanner,
versionMismatch,
versionMismatchDismissKey,
versionMismatchEnvironmentId,
versionMismatchSelfUpdate,
versionMismatchServerLabel,
]);
const providerStatuses = serverConfig?.providers ?? EMPTY_PROVIDERS;
@@ -2288,6 +2329,22 @@ function ChatViewContent(props: ChatViewProps) {
const defaultInstanceId = defaultInstanceIdForDriver(selectedProvider);
return providerStatuses.find((status) => status.instanceId === defaultInstanceId) ?? null;
}, [activeProviderInstanceId, providerStatuses, selectedProvider]);
const providerStatusBannerKey = getProviderStatusBannerKey(activeProviderStatus);
const [dismissedProviderStatusBannerKey, setDismissedProviderStatusBannerKey] = useState<
string | null
>(null);
useEffect(() => {
if (providerStatusBannerKey === null && dismissedProviderStatusBannerKey !== null) {
setDismissedProviderStatusBannerKey(null);
}
}, [dismissedProviderStatusBannerKey, providerStatusBannerKey]);
const visibleProviderStatus = shouldShowProviderStatusBanner(
activeProviderStatus,
dismissedProviderStatusBannerKey,
)
? activeProviderStatus
: null;
const hasTimelineTopBanner = Boolean(threadError) || visibleProviderStatus !== null;
const activeProjectCwd = activeProject?.workspaceRoot ?? null;
const activeThreadWorktreePath = activeThread?.worktreePath ?? null;
const activeWorkspaceRoot = activeThreadWorktreePath ?? activeProjectCwd ?? undefined;
@@ -3224,6 +3281,7 @@ function ChatViewContent(props: ChatViewProps) {
threadId: ThreadId;
createdAt: string;
modelSelection?: ModelSelection;
branch?: string;
runtimeMode: RuntimeMode;
interactionMode: ProviderInteractionMode;
}): Promise<AtomCommandResult<void, unknown>> => {
@@ -3232,19 +3290,19 @@ function ChatViewContent(props: ChatViewProps) {
}
let result: AtomCommandResult<void, unknown> = AsyncResult.success(undefined);
if (
input.modelSelection !== undefined &&
(input.modelSelection.model !== serverThread.modelSelection.model ||
input.modelSelection.instanceId !== serverThread.modelSelection.instanceId ||
JSON.stringify(input.modelSelection.options ?? null) !==
JSON.stringify(serverThread.modelSelection.options ?? null))
) {
const metadataUpdate = resolveThreadMetadataUpdateForNextTurn({
currentModelSelection: serverThread.modelSelection,
...(input.modelSelection ? { nextModelSelection: input.modelSelection } : {}),
currentBranch: serverThread.branch,
...(input.branch ? { nextBranch: input.branch } : {}),
});
if (metadataUpdate) {
result = mapAtomCommandResult(
await updateThreadMetadata({
environmentId,
input: {
threadId: input.threadId,
modelSelection: input.modelSelection,
...metadataUpdate,
},
}),
() => undefined,
@@ -3732,12 +3790,185 @@ function ChatViewContent(props: ChatViewProps) {
? (draftThread?.startFromOrigin ?? false)
: canOverrideServerThreadEnvMode
? (pendingServerThreadStartFromOriginByThreadId[activeThread?.id ?? ""] ??
settings.newWorktreesStartFromOrigin)
primaryServerSettings.newWorktreesStartFromOrigin)
: false;
const sendEnvMode = resolveSendEnvMode({
requestedEnvMode: envMode,
isGitRepo,
});
const localCheckoutBranchMismatch = useMemo(
() =>
isServerThread
? resolveLocalCheckoutBranchMismatch({
effectiveEnvMode: envMode,
activeWorktreePath,
activeThreadBranch,
currentGitBranch: gitStatusQuery.data?.refName ?? null,
})
: null,
[activeThreadBranch, activeWorktreePath, envMode, gitStatusQuery.data?.refName, isServerThread],
);
const [branchRepairAction, setBranchRepairAction] = useState<
"update-thread" | "switch-checkout" | null
>(null);
const handleUpdateThreadToCheckout = useCallback(async () => {
if (!activeThread || !localCheckoutBranchMismatch || branchRepairAction !== null) {
return;
}
setBranchRepairAction("update-thread");
const updateResult = await updateThreadMetadata({
environmentId,
input: {
threadId: activeThread.id,
branch: localCheckoutBranchMismatch.currentBranch,
worktreePath: null,
},
});
setBranchRepairAction(null);
if (updateResult._tag === "Failure" && !isAtomCommandInterrupted(updateResult)) {
toastManager.add(
stackedThreadToast({
type: "error",
title: "Failed to update thread branch",
description: chatActionErrorMessage(squashAtomCommandFailure(updateResult)),
}),
);
return;
}
scheduleComposerFocus();
}, [
activeThread,
branchRepairAction,
environmentId,
localCheckoutBranchMismatch,
scheduleComposerFocus,
updateThreadMetadata,
]);
const handleSwitchCheckoutToThread = useCallback(async () => {
if (
!activeProjectCwd ||
!activeThread ||
!localCheckoutBranchMismatch ||
branchRepairAction !== null
) {
return;
}
setBranchRepairAction("switch-checkout");
const checkoutResult = await switchGitRef({
environmentId,
input: {
cwd: activeProjectCwd,
refName: localCheckoutBranchMismatch.threadBranch,
},
});
if (checkoutResult._tag === "Failure") {
setBranchRepairAction(null);
if (!isAtomCommandInterrupted(checkoutResult)) {
toastManager.add(
stackedThreadToast({
type: "error",
title: "Failed to switch checkout",
description: chatActionErrorMessage(squashAtomCommandFailure(checkoutResult)),
}),
);
}
return;
}
const nextBranch = checkoutResult.value.refName ?? localCheckoutBranchMismatch.threadBranch;
if (nextBranch !== activeThread.branch) {
const updateResult = await updateThreadMetadata({
environmentId,
input: { threadId: activeThread.id, branch: nextBranch, worktreePath: null },
});
if (updateResult._tag === "Failure") {
setBranchRepairAction(null);
if (!isAtomCommandInterrupted(updateResult)) {
toastManager.add(
stackedThreadToast({
type: "error",
title: "Checkout switched, but the thread could not be updated",
description: chatActionErrorMessage(squashAtomCommandFailure(updateResult)),
}),
);
}
gitStatusQuery.refresh();
return;
}
}
gitStatusQuery.refresh();
setBranchRepairAction(null);
scheduleComposerFocus();
}, [
activeProjectCwd,
activeThread,
branchRepairAction,
environmentId,
gitStatusQuery,
localCheckoutBranchMismatch,
scheduleComposerFocus,
switchGitRef,
updateThreadMetadata,
]);
const composerBannerItems = useMemo<ComposerBannerStackItem[]>(() => {
if (!localCheckoutBranchMismatch) {
return systemComposerBannerItems;
}
const isRepairingBranch = branchRepairAction !== null;
return [
...systemComposerBannerItems,
{
id: `branch-mismatch:${activeThread?.id ?? "unknown"}:${localCheckoutBranchMismatch.threadBranch}:${localCheckoutBranchMismatch.currentBranch}`,
variant: "warning",
icon: <TriangleAlertIcon />,
title: "You're on a different branch",
className:
"text-base sm:text-sm [&>div]:items-start max-sm:[&>div]:flex-wrap max-sm:[&>div>div:last-child]:w-full max-sm:[&>div>div:last-child]:self-start dark:shadow-none",
actionClassName:
"max-sm:w-full max-sm:border-t max-sm:border-border/60 max-sm:pt-2 max-sm:pl-6 sm:border-l sm:border-border/60 sm:pl-3",
description: (
<p className="text-pretty">
This thread is on{" "}
<code className="font-medium text-foreground">
{localCheckoutBranchMismatch.threadBranch}
</code>
, but you're currently checked out at{" "}
<code className="font-medium text-foreground">
{localCheckoutBranchMismatch.currentBranch}
</code>
. Sending a message will update the thread.
</p>
),
actions: (
<>
<Button
size="xs"
variant="outline"
disabled={isRepairingBranch}
onClick={() => void handleUpdateThreadToCheckout()}
>
{branchRepairAction === "update-thread" ? "Moving..." : "Move thread here"}
</Button>
<Button
size="xs"
variant="ghost"
disabled={isRepairingBranch}
onClick={() => void handleSwitchCheckoutToThread()}
>
{branchRepairAction === "switch-checkout" ? "Switching..." : "Checkout thread branch"}
</Button>
</>
),
},
];
}, [
activeThread?.id,
branchRepairAction,
handleSwitchCheckoutToThread,
handleUpdateThreadToCheckout,
localCheckoutBranchMismatch,
systemComposerBannerItems,
]);
useEffect(() => {
setPendingServerThreadEnvMode(null);
@@ -4287,6 +4518,9 @@ function ChatViewContent(props: ChatViewProps) {
threadId: threadIdForSend,
createdAt: messageCreatedAt,
...(ctxSelectedModel ? { modelSelection: ctxSelectedModelSelection } : {}),
...(localCheckoutBranchMismatch
? { branch: localCheckoutBranchMismatch.currentBranch }
: {}),
runtimeMode,
interactionMode,
});
@@ -4668,6 +4902,9 @@ function ChatViewContent(props: ChatViewProps) {
threadId: threadIdForSend,
createdAt: messageCreatedAt,
modelSelection: ctxSelectedModelSelection,
...(localCheckoutBranchMismatch
? { branch: localCheckoutBranchMismatch.currentBranch }
: {}),
runtimeMode,
interactionMode: nextInteractionMode,
});
@@ -4744,6 +4981,7 @@ function ChatViewContent(props: ChatViewProps) {
isConnecting,
isSendBusy,
isServerThread,
localCheckoutBranchMismatch,
persistThreadSettingsForNextTurn,
resetLocalDispatch,
runtimeMode,
@@ -5021,7 +5259,7 @@ function ChatViewContent(props: ChatViewProps) {
envMode: mode,
startFromOrigin: resolveNewDraftStartFromOrigin({
envMode: mode,
newWorktreesStartFromOrigin: settings.newWorktreesStartFromOrigin,
newWorktreesStartFromOrigin: primaryServerSettings.newWorktreesStartFromOrigin,
}),
...(mode === "worktree" && draftThread?.worktreePath ? { worktreePath: null } : {}),
});
@@ -5033,7 +5271,7 @@ function ChatViewContent(props: ChatViewProps) {
composerDraftTarget,
draftThread?.worktreePath,
isLocalDraftThread,
settings.newWorktreesStartFromOrigin,
primaryServerSettings.newWorktreesStartFromOrigin,
setPendingServerThreadEnvMode,
scheduleComposerFocus,
setDraftThreadContext,
@@ -5199,7 +5437,7 @@ function ChatViewContent(props: ChatViewProps) {
<header
data-chat-header
className={cn(
"border-b border-border transition-[padding-left] duration-200 ease-linear motion-reduce:transition-none",
"bg-background transition-[padding-left] duration-200 ease-linear motion-reduce:transition-none",
isElectron
? cn(
"workspace-topbar drag-region relative px-3 sm:px-5",
@@ -5235,8 +5473,6 @@ function ChatViewContent(props: ChatViewProps) {
/>
</header>
{/* Error banner */}
<ProviderStatusBanner status={activeProviderStatus} />
<ThreadErrorBanner
error={threadError}
onDismiss={() => setThreadError(activeThread.id, null)}
@@ -5245,6 +5481,13 @@ function ChatViewContent(props: ChatViewProps) {
<div className="flex min-h-0 min-w-0 flex-1">
{/* Chat column */}
<div className="relative flex min-h-0 min-w-0 flex-1 flex-col">
{/* Provider status overlays the timeline without changing its content height. */}
<div className="pointer-events-none absolute inset-x-0 top-0 z-20">
<ProviderStatusBanner
status={visibleProviderStatus}
onDismiss={() => setDismissedProviderStatusBannerKey(providerStatusBannerKey)}
/>
</div>
{/* Messages Wrapper */}
<div className="relative flex min-h-0 flex-1 flex-col">
{/* Messages — LegendList handles virtualization and scrolling internally */}
@@ -5281,6 +5524,7 @@ function ChatViewContent(props: ChatViewProps) {
onIsAtEndChange={onIsAtEndChange}
onManualNavigation={cancelTimelineLiveFollowForUserNavigation}
hideEmptyPlaceholder={isDraftHeroState}
topFadeEnabled={!hasTimelineTopBanner}
/>
{/* scroll to end pill — shown when user has scrolled away from the live edge */}
@@ -5313,22 +5557,11 @@ function ChatViewContent(props: ChatViewProps) {
: "pointer-events-none absolute inset-x-0 bottom-0 z-20 pt-1.5 sm:pt-2"
}
>
{!isDraftHeroState ? (
<div
key="docked-composer-blur"
aria-hidden="true"
className="chat-composer-horizontal-inset pointer-events-none absolute inset-x-0 top-1.5 bottom-0 z-0 sm:top-2"
>
<div className="relative mx-auto h-full w-full max-w-3xl overflow-clip rounded-t-[20px]">
<div className="chat-composer-shared-blur absolute -inset-8" />
</div>
</div>
) : null}
<div
ref={attachDraftHeroTransitionGroupRef}
className="chat-composer-horizontal-inset w-full"
>
<div className="pointer-events-auto relative z-10 isolate">
<div className="pointer-events-auto relative z-10">
{isDraftHeroState ? (
<div className="absolute inset-x-0 bottom-full z-0">
<div
@@ -5359,129 +5592,125 @@ function ChatViewContent(props: ChatViewProps) {
: undefined
}
>
<div
ref={attachDraftHeroComposerAnchorRef}
className="relative z-10 mx-auto w-full max-w-3xl"
>
<ChatComposer
composerRef={composerRef}
composerDraftTarget={composerDraftTarget}
environmentId={environmentId}
routeKind={routeKind}
routeThreadRef={routeThreadRef}
draftId={draftId}
activeThreadId={activeThreadId}
activeThreadEnvironmentId={activeThread?.environmentId}
activeThread={activeThread}
isServerThread={isServerThread}
isLocalDraftThread={isLocalDraftThread}
forceExpandedOnMobile={forceExpandedMobileComposer && isDraftHeroState}
projectSelectionRequired={isLocalDraftThread && activeProject === null}
phase={phase}
isConnecting={isConnecting}
isSendBusy={isSendBusy}
isPreparingWorktree={isPreparingWorktree}
environmentUnavailable={activeEnvironmentUnavailableState}
activePendingApproval={activePendingApproval}
pendingApprovals={pendingApprovals}
pendingUserInputs={pendingUserInputs}
activePendingProgress={activePendingProgress}
activePendingResolvedAnswers={activePendingResolvedAnswers}
activePendingIsResponding={activePendingIsResponding}
activePendingDraftAnswers={activePendingDraftAnswers}
activePendingQuestionIndex={activePendingQuestionIndex}
respondingRequestIds={respondingRequestIds}
showPlanFollowUpPrompt={showPlanFollowUpPrompt}
activeProposedPlan={activeProposedPlan}
activePlan={activePlan as { turnId?: TurnId } | null}
sidebarProposedPlan={sidebarProposedPlan as { turnId?: TurnId } | null}
planSidebarLabel={planSidebarLabel}
planSidebarOpen={planSidebarOpen}
runtimeMode={runtimeMode}
interactionMode={interactionMode}
lockedProvider={lockedProvider}
providerStatuses={providerStatuses as ServerProvider[]}
activeProjectDefaultModelSelection={activeProject?.defaultModelSelection}
activeThreadModelSelection={activeThread?.modelSelection}
activeThreadActivities={activeThread?.activities}
resolvedTheme={resolvedTheme}
settings={settings}
keybindings={keybindings}
terminalOpen={Boolean(terminalUiState.terminalOpen)}
gitCwd={gitCwd}
promptRef={promptRef}
composerImagesRef={composerImagesRef}
composerTerminalContextsRef={composerTerminalContextsRef}
composerElementContextsRef={composerElementContextsRef}
onSend={onSend}
onInterrupt={onInterrupt}
onImplementPlanInNewThread={onImplementPlanInNewThread}
onRespondToApproval={onRespondToApproval}
onSelectActivePendingUserInputOption={onSelectActivePendingUserInputOption}
onAdvanceActivePendingUserInput={onAdvanceActivePendingUserInput}
onPreviousActivePendingUserInputQuestion={
onPreviousActivePendingUserInputQuestion
}
onChangeActivePendingUserInputCustomAnswer={
onChangeActivePendingUserInputCustomAnswer
}
onProviderModelSelect={onProviderModelSelect}
getModelDisabledReason={getModelDisabledReason}
toggleInteractionMode={toggleInteractionMode}
handleRuntimeModeChange={handleRuntimeModeChange}
handleInteractionModeChange={handleInteractionModeChange}
togglePlanSidebar={togglePlanSidebar}
focusComposer={focusComposer}
scheduleComposerFocus={scheduleComposerFocus}
setThreadError={setThreadError}
onExpandImage={onExpandTimelineImage}
/>
</div>
<div
className={cn(
"min-h-0",
isDraftHeroState ? "absolute inset-x-0 top-full" : null,
)}
>
<div
className={cn(
"chat-composer-lower-chrome relative z-10",
isGitRepo
? "pb-[calc(env(safe-area-inset-bottom)+0.25rem)]"
: "pb-[calc(env(safe-area-inset-bottom)+0.75rem)] sm:pb-[calc(env(safe-area-inset-bottom)+1rem)]",
)}
>
{isGitRepo && (
<div className="pointer-events-auto">
<BranchToolbar
environmentId={activeThread.environmentId}
threadId={activeThread.id}
{...(routeKind === "draft" && draftId ? { draftId } : {})}
onEnvModeChange={onEnvModeChange}
startFromOrigin={startFromOrigin}
onStartFromOriginChange={onStartFromOriginChange}
{...(canOverrideServerThreadEnvMode
? { effectiveEnvModeOverride: envMode }
: {})}
{...(canOverrideServerThreadEnvMode
? {
activeThreadBranchOverride: activeThreadBranch,
onActiveThreadBranchOverrideChange:
setPendingServerThreadBranch,
}
: {})}
envLocked={envLocked}
onComposerFocusRequest={scheduleComposerFocus}
{...(canCheckoutPullRequestIntoThread
? { onCheckoutPullRequestRequest: openPullRequestDialog }
: {})}
{...(hasMultipleEnvironments ? { onEnvironmentChange } : {})}
availableEnvironments={logicalProjectEnvironments}
/>
</div>
)}
<div className="chat-composer-glass-host mx-auto w-full max-w-3xl rounded-[22px]">
<div ref={attachDraftHeroComposerAnchorRef} className="relative z-10">
<ChatComposer
composerRef={composerRef}
composerDraftTarget={composerDraftTarget}
environmentId={environmentId}
routeKind={routeKind}
routeThreadRef={routeThreadRef}
draftId={draftId}
activeThreadId={activeThreadId}
activeThreadEnvironmentId={activeThread?.environmentId}
activeThread={activeThread}
isServerThread={isServerThread}
isLocalDraftThread={isLocalDraftThread}
forceExpandedOnMobile={forceExpandedMobileComposer && isDraftHeroState}
projectSelectionRequired={isLocalDraftThread && activeProject === null}
phase={phase}
isConnecting={isConnecting}
isSendBusy={isSendBusy}
isPreparingWorktree={isPreparingWorktree}
environmentUnavailable={activeEnvironmentUnavailableState}
activePendingApproval={activePendingApproval}
pendingApprovals={pendingApprovals}
pendingUserInputs={pendingUserInputs}
activePendingProgress={activePendingProgress}
activePendingResolvedAnswers={activePendingResolvedAnswers}
activePendingIsResponding={activePendingIsResponding}
activePendingDraftAnswers={activePendingDraftAnswers}
activePendingQuestionIndex={activePendingQuestionIndex}
respondingRequestIds={respondingRequestIds}
showPlanFollowUpPrompt={showPlanFollowUpPrompt}
activeProposedPlan={activeProposedPlan}
activePlan={activePlan as { turnId?: TurnId } | null}
sidebarProposedPlan={sidebarProposedPlan as { turnId?: TurnId } | null}
planSidebarLabel={planSidebarLabel}
planSidebarOpen={planSidebarOpen}
runtimeMode={runtimeMode}
interactionMode={interactionMode}
lockedProvider={lockedProvider}
providerStatuses={providerStatuses as ServerProvider[]}
activeProjectDefaultModelSelection={activeProject?.defaultModelSelection}
activeThreadModelSelection={activeThread?.modelSelection}
activeThreadActivities={activeThread?.activities}
resolvedTheme={resolvedTheme}
settings={settings}
keybindings={keybindings}
terminalOpen={Boolean(terminalUiState.terminalOpen)}
gitCwd={gitCwd}
promptRef={promptRef}
composerImagesRef={composerImagesRef}
composerTerminalContextsRef={composerTerminalContextsRef}
composerElementContextsRef={composerElementContextsRef}
onSend={onSend}
onInterrupt={onInterrupt}
onImplementPlanInNewThread={onImplementPlanInNewThread}
onRespondToApproval={onRespondToApproval}
onSelectActivePendingUserInputOption={
onSelectActivePendingUserInputOption
}
onAdvanceActivePendingUserInput={onAdvanceActivePendingUserInput}
onPreviousActivePendingUserInputQuestion={
onPreviousActivePendingUserInputQuestion
}
onChangeActivePendingUserInputCustomAnswer={
onChangeActivePendingUserInputCustomAnswer
}
onProviderModelSelect={onProviderModelSelect}
getModelDisabledReason={getModelDisabledReason}
toggleInteractionMode={toggleInteractionMode}
handleRuntimeModeChange={handleRuntimeModeChange}
handleInteractionModeChange={handleInteractionModeChange}
togglePlanSidebar={togglePlanSidebar}
focusComposer={focusComposer}
scheduleComposerFocus={scheduleComposerFocus}
setThreadError={setThreadError}
onExpandImage={onExpandTimelineImage}
/>
</div>
<div className="min-h-0">
<div
data-terminal-open={terminalUiState.terminalOpen ? "true" : undefined}
className="relative z-0"
>
{isGitRepo && (
<div className="pointer-events-auto">
<BranchToolbar
environmentId={activeThread.environmentId}
threadId={activeThread.id}
{...(routeKind === "draft" && draftId ? { draftId } : {})}
onEnvModeChange={onEnvModeChange}
startFromOrigin={startFromOrigin}
onStartFromOriginChange={onStartFromOriginChange}
{...(canOverrideServerThreadEnvMode
? { effectiveEnvModeOverride: envMode }
: {})}
{...(canOverrideServerThreadEnvMode
? {
activeThreadBranchOverride: activeThreadBranch,
onActiveThreadBranchOverrideChange:
setPendingServerThreadBranch,
}
: {})}
envLocked={envLocked}
onComposerFocusRequest={scheduleComposerFocus}
{...(canCheckoutPullRequestIntoThread
? { onCheckoutPullRequestRequest: openPullRequestDialog }
: {})}
{...(hasMultipleEnvironments ? { onEnvironmentChange } : {})}
availableEnvironments={logicalProjectEnvironments}
/>
</div>
)}
</div>
</div>
</div>
<div
aria-hidden
className="h-[calc(env(safe-area-inset-bottom)+1rem)] sm:h-[calc(env(safe-area-inset-bottom)+1.25rem)]"
/>
</div>
</div>
</div>
@@ -3,10 +3,38 @@ import { EnvironmentId, ProjectId, ProviderInstanceId, ThreadId } from "@t3tools
import type { Thread } from "../types";
import {
buildThreadActionItems,
enumerateCommandPaletteItems,
filterCommandPaletteGroups,
type CommandPaletteGroup,
} from "./CommandPalette.logic";
describe("enumerateCommandPaletteItems", () => {
it("assigns positional jump shortcuts to the first nine displayed items", () => {
const items = Array.from({ length: 10 }, (_, index) => ({
kind: "action" as const,
value: `project-${index + 1}`,
searchTerms: [],
title: `Project ${index + 1}`,
icon: null,
shortcutCommand: "chat.new" as const,
run: async () => undefined,
}));
expect(enumerateCommandPaletteItems(items).map((item) => item.shortcutCommand)).toEqual([
"thread.jump.1",
"thread.jump.2",
"thread.jump.3",
"thread.jump.4",
"thread.jump.5",
"thread.jump.6",
"thread.jump.7",
"thread.jump.8",
"thread.jump.9",
undefined,
]);
});
});
const LOCAL_ENVIRONMENT_ID = EnvironmentId.make("environment-local");
const PROJECT_ID = ProjectId.make("project-1");
@@ -1,4 +1,8 @@
import { type KeybindingCommand, type FilesystemBrowseEntry } from "@t3tools/contracts";
import {
type KeybindingCommand,
type FilesystemBrowseEntry,
THREAD_JUMP_KEYBINDING_COMMANDS,
} from "@t3tools/contracts";
import type { SidebarThreadSortOrder } from "@t3tools/contracts/settings";
import * as Arr from "effect/Array";
import * as Result from "effect/Result";
@@ -52,6 +56,18 @@ export interface CommandPaletteView {
readonly initialQuery?: string;
}
export function enumerateCommandPaletteItems(
items: ReadonlyArray<CommandPaletteActionItem>,
): CommandPaletteActionItem[] {
return items.map((item, index) => {
const shortcutCommand = THREAD_JUMP_KEYBINDING_COMMANDS[index];
if (shortcutCommand) return { ...item, shortcutCommand };
const { shortcutCommand: _shortcutCommand, ...itemWithoutShortcut } = item;
return itemWithoutShortcut;
});
}
export type CommandPaletteMode = "root" | "root-browse" | "submenu" | "submenu-browse";
export function filterBrowseEntries(input: {
@@ -95,12 +111,13 @@ export function buildProjectActionItems(input: {
valuePrefix: string;
icon: (project: Project) => ReactNode;
runProject: (project: Project) => Promise<void>;
searchTerms?: (project: Project) => ReadonlyArray<string>;
shortcutCommand?: KeybindingCommand;
}): CommandPaletteActionItem[] {
return input.projects.map((project) => ({
kind: "action",
value: `${input.valuePrefix}:${project.environmentId}:${project.id}`,
searchTerms: [project.title, project.workspaceRoot],
searchTerms: [project.title, project.workspaceRoot, ...(input.searchTerms?.(project) ?? [])],
title: project.title,
description: project.workspaceRoot,
icon: input.icon(project),
+220 -50
View File
@@ -56,9 +56,10 @@ import { useEnvironmentQuery } from "../state/query";
import { sourceControlEnvironment } from "../state/sourceControl";
import { useAtomCommand } from "../state/use-atom-command";
import { useAtomQueryRunner } from "../state/use-atom-query-runner";
import { useEnvironments, usePrimaryEnvironment } from "../state/environments";
import { useEnvironments, usePrimaryEnvironmentId } from "../state/environments";
import { useProjects, useThreadShells } from "../state/entities";
import {
resolveThreadActionProjectRef,
startNewThreadInProjectFromContext,
startNewThreadFromContext,
} from "../lib/chatThreadActions";
@@ -79,7 +80,7 @@ import {
} from "../lib/projectPaths";
import { onOpenCommandPalette } from "../commandPaletteBus";
import { isTerminalFocused } from "../lib/terminalFocus";
import { getLatestThreadForProject } from "../lib/threadSort";
import { getLatestThreadForProject, sortThreads } from "../lib/threadSort";
import { cn, isMacPlatform, isWindowsPlatform, newProjectId } from "../lib/utils";
import { selectThreadTerminalUiState, useTerminalUiStateStore } from "../terminalUiStateStore";
import { buildThreadRouteParams, resolveThreadRouteTarget } from "../threadRoutes";
@@ -95,6 +96,7 @@ import {
buildProjectActionItems,
buildRootGroups,
buildThreadActionItems,
enumerateCommandPaletteItems,
type CommandPaletteActionItem,
type CommandPaletteSubmenuItem,
type CommandPaletteView,
@@ -105,6 +107,7 @@ import {
ITEM_ICON_CLASS,
RECENT_THREAD_LIMIT,
} from "./CommandPalette.logic";
import { orderItemsByPreferredIds, sortLogicalProjectsForSidebar } from "./Sidebar.logic";
import { resolveEnvironmentOptionLabel } from "./BranchToolbar.logic";
import { CommandPaletteResults } from "./CommandPaletteResults";
import { AzureDevOpsIcon, BitbucketIcon, GitHubIcon, GitLabIcon } from "./Icons";
@@ -112,7 +115,7 @@ import { ProjectFavicon } from "./ProjectFavicon";
import { ThreadRowLeadingStatus, ThreadRowTrailingStatus } from "./ThreadStatusIndicators";
import { primaryServerKeybindingsAtom, primaryServerProvidersAtom } from "../state/server";
import { resolveDefaultProviderModelSelection } from "../providerInstances";
import { resolveShortcutCommand } from "../keybindings";
import { resolveShortcutCommand, threadJumpIndexFromCommand } from "../keybindings";
import {
Command,
CommandDialog,
@@ -127,6 +130,12 @@ import { stackedThreadToast, toastManager } from "./ui/toast";
import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip";
import { ComposerHandleContext, useComposerHandleContext } from "../composerHandleContext";
import type { ChatComposerHandle } from "./chat/ChatComposer";
import { getProjectOrderKey, selectProjectGroupingSettings } from "../logicalProject";
import { legacyProjectCwdPreferenceKey, useUiStateStore } from "../uiStateStore";
import {
buildSidebarProjectPickerEntries,
buildSidebarProjectSnapshots,
} from "../sidebarProjectGrouping";
const EMPTY_BROWSE_ENTRIES: FilesystemBrowseResult["entries"] = [];
@@ -486,10 +495,11 @@ function OpenCommandPaletteDialog(props: {
});
const { environments } = useEnvironments();
const desktopLocalBootstraps = useDesktopLocalBootstraps();
const primaryEnvironment = usePrimaryEnvironment();
const primaryEnvironmentId = usePrimaryEnvironmentId();
const { activeDraftThread, activeThread, defaultProjectRef, handleNewThread } =
useHandleNewThread();
const projects = useProjects();
const projectOrder = useUiStateStore((store) => store.projectOrder);
const threads = useThreadShells();
const keybindings = useAtomValue(primaryServerKeybindingsAtom);
const providers = useAtomValue(primaryServerProvidersAtom);
@@ -503,7 +513,93 @@ function OpenCommandPaletteDialog(props: {
const [addProjectCloneFlow, setAddProjectCloneFlow] = useState<AddProjectCloneFlow | null>(null);
const [isRemoteProjectLookingUp, setIsRemoteProjectLookingUp] = useState(false);
const [isRemoteProjectCloning, setIsRemoteProjectCloning] = useState(false);
const primaryEnvironmentId = primaryEnvironment?.environmentId ?? null;
const projectGroupingSettings = useMemo(
() => selectProjectGroupingSettings(clientSettings),
[clientSettings],
);
const environmentLabelById = useMemo(
() =>
new Map(
environments.map((environment) => [environment.environmentId, environment.label] as const),
),
[environments],
);
const orderedProjects = useMemo(
() =>
orderItemsByPreferredIds({
items: projects,
preferredIds: projectOrder,
getId: getProjectOrderKey,
getPreferenceIds: (project) => [
getProjectOrderKey(project),
legacyProjectCwdPreferenceKey(project.workspaceRoot),
],
}),
[projectOrder, projects],
);
const unsortedProjectGroups = useMemo(
() =>
buildSidebarProjectSnapshots({
projects: clientSettings.sidebarProjectSortOrder === "manual" ? orderedProjects : projects,
settings: projectGroupingSettings,
primaryEnvironmentId,
resolveEnvironmentLabel: (environmentId) => environmentLabelById.get(environmentId) ?? null,
}),
[
clientSettings.sidebarProjectSortOrder,
environmentLabelById,
orderedProjects,
primaryEnvironmentId,
projectGroupingSettings,
projects,
],
);
const projectGroups = useMemo(
() =>
sortLogicalProjectsForSidebar(
unsortedProjectGroups,
threads,
clientSettings.sidebarProjectSortOrder,
),
[clientSettings.sidebarProjectSortOrder, threads, unsortedProjectGroups],
);
const contextualProjectRef = useMemo(
() =>
resolveThreadActionProjectRef({
activeDraftThread,
activeThread: activeThread ?? undefined,
defaultProjectRef,
handleNewThread,
}),
[activeDraftThread, activeThread, defaultProjectRef, handleNewThread],
);
const projectPickerEntries = useMemo(
() =>
buildSidebarProjectPickerEntries({
groups: projectGroups,
preferredProjectRef: contextualProjectRef,
}),
[contextualProjectRef, projectGroups],
);
const pickerProjects = useMemo(
() =>
projectPickerEntries.map(({ group, targetProject }) => ({
...targetProject,
title: group.displayName,
})),
[projectPickerEntries],
);
const projectGroupByTargetKey = useMemo(
() =>
new Map(
projectPickerEntries.map(({ group, targetProject }) => [
`${targetProject.environmentId}:${targetProject.id}`,
group,
]),
),
[projectPickerEntries],
);
const addProjectEnvironmentOptions = useMemo(() => {
const options = environments.map((environment): AddProjectEnvironmentOption => {
@@ -647,11 +743,28 @@ function OpenCommandPaletteDialog(props: {
const openProjectFromSearch = useMemo(
() => async (project: (typeof projects)[number]) => {
const latestThread = getLatestThreadForProject(
threads.filter((thread) => thread.environmentId === project.environmentId),
project.id,
clientSettings.sidebarThreadSortOrder,
);
const group = projectGroupByTargetKey.get(`${project.environmentId}:${project.id}`);
const groupedProjectKeys = group
? new Set(
group.memberProjectRefs.map(
(projectRef) => `${projectRef.environmentId}:${projectRef.projectId}`,
),
)
: null;
const latestThread = groupedProjectKeys
? (sortThreads(
threads.filter(
(thread) =>
thread.archivedAt === null &&
groupedProjectKeys.has(`${thread.environmentId}:${thread.projectId}`),
),
clientSettings.sidebarThreadSortOrder,
)[0] ?? null)
: getLatestThreadForProject(
threads.filter((thread) => thread.environmentId === project.environmentId),
project.id,
clientSettings.sidebarThreadSortOrder,
);
if (latestThread) {
await navigate({
to: "/$environmentId/$threadId",
@@ -664,14 +777,26 @@ function OpenCommandPaletteDialog(props: {
await handleNewThread(scopeProjectRef(project.environmentId, project.id));
},
[handleNewThread, navigate, clientSettings.sidebarThreadSortOrder, threads],
[
clientSettings.sidebarThreadSortOrder,
handleNewThread,
navigate,
projectGroupByTargetKey,
threads,
],
);
const projectSearchItems = useMemo(
() =>
buildProjectActionItems({
projects,
projects: pickerProjects,
valuePrefix: "project",
searchTerms: (project) => {
const group = projectGroupByTargetKey.get(`${project.environmentId}:${project.id}`);
return (
group?.memberProjects.flatMap((member) => [member.title, member.workspaceRoot]) ?? []
);
},
icon: (project) => (
<ProjectFavicon
environmentId={project.environmentId}
@@ -681,35 +806,60 @@ function OpenCommandPaletteDialog(props: {
),
runProject: openProjectFromSearch,
}),
[openProjectFromSearch, projects],
[openProjectFromSearch, pickerProjects, projectGroupByTargetKey],
);
const projectThreadItems = useMemo(
() =>
buildProjectActionItems({
projects,
valuePrefix: "new-thread-in",
shortcutCommand: "chat.new",
icon: (project) => (
<ProjectFavicon
environmentId={project.environmentId}
cwd={project.workspaceRoot}
className={ITEM_ICON_CLASS}
/>
),
runProject: async (project) => {
await startNewThreadInProjectFromContext(
{
activeDraftThread,
activeThread: activeThread ?? undefined,
defaultProjectRef,
handleNewThread,
},
scopeProjectRef(project.environmentId, project.id),
);
},
}),
[activeDraftThread, activeThread, defaultProjectRef, handleNewThread, projects],
enumerateCommandPaletteItems(
buildProjectActionItems({
projects: pickerProjects,
valuePrefix: "new-thread-in",
searchTerms: (project) => {
const group = projectGroupByTargetKey.get(`${project.environmentId}:${project.id}`);
return (
group?.memberProjects.flatMap((member) => [member.title, member.workspaceRoot]) ?? []
);
},
icon: (project) => (
<ProjectFavicon
environmentId={project.environmentId}
cwd={project.workspaceRoot}
className={ITEM_ICON_CLASS}
/>
),
runProject: async (project) => {
const group = projectGroupByTargetKey.get(`${project.environmentId}:${project.id}`);
const contextualRefBelongsToGroup =
contextualProjectRef !== null &&
group?.memberProjectRefs.some(
(projectRef) =>
projectRef.environmentId === contextualProjectRef.environmentId &&
projectRef.projectId === contextualProjectRef.projectId,
);
await startNewThreadInProjectFromContext(
{
activeDraftThread,
activeThread: activeThread ?? undefined,
defaultProjectRef,
handleNewThread,
},
contextualRefBelongsToGroup
? contextualProjectRef
: scopeProjectRef(project.environmentId, project.id),
);
},
}),
),
[
activeDraftThread,
activeThread,
contextualProjectRef,
defaultProjectRef,
handleNewThread,
pickerProjects,
projectGroupByTargetKey,
],
);
const allThreadItems = useMemo(
@@ -997,7 +1147,13 @@ function OpenCommandPaletteDialog(props: {
: projectThreadItems;
pushPaletteView({
addonIcon: <SquarePenIcon className={ADDON_ICON_CLASS} />,
groups: [{ value: "projects", label: "Projects", items: prioritized }],
groups: [
{
value: "projects",
label: "Projects",
items: enumerateCommandPaletteItems(prioritized),
},
],
});
}, [
clearOpenIntent,
@@ -1010,9 +1166,9 @@ function OpenCommandPaletteDialog(props: {
const actionItems: Array<CommandPaletteActionItem | CommandPaletteSubmenuItem> = [];
if (projects.length > 0) {
const activeProjectTitle = currentProjectId
? (projectTitleById.get(currentProjectId) ?? null)
: null;
const activeProjectTitle =
projectPickerEntries.find((entry) => entry.isPreferred)?.group.displayName ??
(currentProjectId ? (projectTitleById.get(currentProjectId) ?? null) : null);
if (activeProjectTitle) {
actionItems.push({
@@ -1545,6 +1701,22 @@ function OpenCommandPaletteDialog(props: {
}
function handleKeyDown(event: KeyboardEvent<HTMLInputElement>): void {
const command = resolveShortcutCommand(event, keybindings, {
platform: navigator.platform,
context: { modelPickerOpen: false },
});
if (threadJumpIndexFromCommand(command ?? "") !== null) {
const matchingItem = displayedGroups
.flatMap((group) => group.items)
.find((item) => item.shortcutCommand === command);
if (matchingItem) {
event.preventDefault();
event.stopPropagation();
executeItem(matchingItem);
return;
}
}
if (addProjectCloneFlow?.step === "repository" && event.key === "Enter") {
event.preventDefault();
void submitAddProjectCloneFlow();
@@ -1855,7 +2027,7 @@ function OpenCommandPaletteDialog(props: {
<span className="truncate text-foreground text-sm">
{remoteProjectContext.title}
</span>
<span className="truncate text-muted-foreground/70 text-xs">
<span className="truncate text-muted-foreground/85 text-xs">
{remoteProjectContext.description}
</span>
</span>
@@ -1896,37 +2068,35 @@ function OpenCommandPaletteDialog(props: {
<Kbd>
<ArrowDownIcon />
</Kbd>
<span className={cn("text-muted-foreground/80")}>Navigate</span>
<span>Navigate</span>
</KbdGroup>
{addProjectCloneFlow?.step === "repository" ? (
<KbdGroup className="items-center gap-1.5">
<Kbd>Enter</Kbd>
<span className={cn("text-muted-foreground/80")}>
{remoteProjectButtonLabel ?? "Continue"}
</span>
<span>{remoteProjectButtonLabel ?? "Continue"}</span>
</KbdGroup>
) : !canSubmitBrowsePath || hasHighlightedBrowseItem ? (
<KbdGroup className="items-center gap-1.5">
<Kbd>Enter</Kbd>
<span className={cn("text-muted-foreground/80")}>Select</span>
<span>Select</span>
</KbdGroup>
) : null}
{isSubmenu ? (
<KbdGroup className="items-center gap-1.5">
<Kbd>Backspace</Kbd>
<span className={cn("text-muted-foreground/80")}>Back</span>
<span>Back</span>
</KbdGroup>
) : null}
<KbdGroup className="items-center gap-1.5">
<Kbd>Esc</Kbd>
<span className={cn("text-muted-foreground/80")}>Close</span>
<span>Close</span>
</KbdGroup>
</div>
{canOpenProjectFromFileManager ? (
<Button
variant="ghost"
size="xs"
className="h-auto px-2 text-xs text-muted-foreground/80 hover:bg-transparent hover:text-foreground"
className="h-auto px-2 text-muted-foreground text-xs hover:bg-transparent hover:text-foreground"
disabled={isPickingProjectFolder}
onClick={() => {
void handleOpenProjectFromFileManager();
@@ -75,7 +75,7 @@ function DisabledCommandPaletteResultRow(props: {
{props.item.titleLeadingContent}
<span className="truncate">{props.item.title}</span>
</span>
<span className="truncate text-muted-foreground/70 text-xs">
<span className="truncate text-muted-foreground/85 text-xs">
{props.item.description}
</span>
</span>
@@ -121,7 +121,7 @@ function CommandPaletteResultRow(props: {
{props.item.titleLeadingContent}
<span className="truncate">{props.item.title}</span>
</span>
<span className="truncate text-muted-foreground/70 text-xs">
<span className="truncate text-muted-foreground/85 text-xs">
{props.item.description}
</span>
</span>
+26 -14
View File
@@ -521,27 +521,37 @@ export default function DiffPanel({
<ChevronDownIcon className="size-3.5 shrink-0 text-muted-foreground" />
</DropdownMenuTrigger>
<DropdownMenuContent align="start" className="w-60">
<DropdownMenuItem onClick={() => selectGitScope("unstaged")}>
<DropdownMenuItem
className={
selectedTurnId === null && selectedGitScope === "unstaged"
? "bg-foreground/[0.08]"
: undefined
}
onClick={() => selectGitScope("unstaged")}
>
<span>Working tree</span>
{selectedTurnId === null && selectedGitScope === "unstaged" && (
<CheckIcon className="ml-auto" />
)}
</DropdownMenuItem>
<DropdownMenuItem onClick={() => selectGitScope("branch")}>
<span>Branch changes</span>
{selectedTurnId === null && selectedGitScope === "branch" && (
<CheckIcon className="ml-auto" />
)}
</DropdownMenuItem>
<DropdownMenuItem
className={
selectedTurnId === null && selectedGitScope === "branch"
? "bg-foreground/[0.08]"
: undefined
}
onClick={() => selectGitScope("branch")}
>
<span>Branch changes</span>
</DropdownMenuItem>
<DropdownMenuItem
className={
selectedTurnId !== null && selectedTurn?.turnId === latestTurn?.turnId
? "bg-foreground/[0.08]"
: undefined
}
onClick={() => {
if (latestTurn) selectTurn(latestTurn.turnId);
}}
>
<span>Latest turn</span>
{selectedTurnId !== null && selectedTurn?.turnId === latestTurn?.turnId && (
<CheckIcon className="ml-auto" />
)}
</DropdownMenuItem>
<DropdownMenuSub>
<DropdownMenuSubTrigger>Turn</DropdownMenuSubTrigger>
@@ -554,13 +564,15 @@ export default function DiffPanel({
return (
<DropdownMenuItem
key={summary.turnId}
className={
summary.turnId === selectedTurn?.turnId ? "bg-foreground/[0.08]" : undefined
}
onClick={() => selectTurn(summary.turnId)}
>
<span>Turn {turnCount}</span>
<span className="ml-auto text-xs tabular-nums text-muted-foreground">
{formatShortTimestamp(summary.completedAt, settings.timestampFormat)}
</span>
{summary.turnId === selectedTurn?.turnId && <CheckIcon className="ml-1" />}
</DropdownMenuItem>
);
})}
+27 -29
View File
@@ -545,8 +545,8 @@ function PublishRepositoryDialog(props: PublishRepositoryDialogProps) {
return (
<Dialog open={props.open} onOpenChange={handleOpenChange}>
<DialogPopup className="max-w-xl overflow-hidden">
<div className="flex min-h-0 flex-col overflow-hidden border-foreground/10 bg-background shadow-2xl">
<DialogHeader className="border-b border-border/70 bg-background">
<div className="flex min-h-0 flex-col overflow-hidden border-foreground/10 bg-transparent">
<DialogHeader className="border-b border-border/70 bg-foreground/[0.025] dark:border-transparent dark:bg-transparent">
<DialogTitle>Publish repository</DialogTitle>
<DialogDescription>
Pick where to host it, then point us at a repo to push to.
@@ -567,10 +567,10 @@ function PublishRepositoryDialog(props: PublishRepositoryDialogProps) {
className={cn(
"grid min-w-0 grid-cols-[1rem_minmax(0,1fr)] gap-x-2 rounded-lg border px-3 py-2 text-left",
index === publishWizardStep
? "border-primary bg-primary/10 ring-1 ring-primary/25"
? "border-primary bg-primary/10 ring-1 ring-primary/25 dark:border-transparent"
: isComplete
? "border-border bg-background"
: "border-border bg-muted/40",
? "border-border bg-background dark:border-transparent dark:bg-white/[0.05]"
: "border-border bg-muted/40 dark:border-transparent dark:bg-white/[0.025]",
!isClickable && "cursor-default",
)}
>
@@ -602,7 +602,7 @@ function PublishRepositoryDialog(props: PublishRepositoryDialogProps) {
</div>
</DialogHeader>
<DialogPanel className="space-y-5 border-b border-border/70 bg-muted/20 px-6 py-5">
<DialogPanel className="space-y-5 border-b border-border/70 bg-muted/20 px-6 py-5 dark:border-transparent dark:bg-transparent">
<AnimatedHeight>
<div className={cn("space-y-2", publishWizardStep !== 0 && "hidden")}>
<span
@@ -627,7 +627,7 @@ function PublishRepositoryDialog(props: PublishRepositoryDialogProps) {
return (
<div
key={option.value}
className="relative flex cursor-not-allowed items-center gap-3 rounded-lg border border-border bg-background px-3 py-3 text-left opacity-55"
className="relative flex cursor-not-allowed items-center gap-3 rounded-lg border border-border bg-background px-3 py-3 text-left opacity-55 dark:border-transparent dark:bg-white/[0.035]"
>
<option.Icon
className="size-5 shrink-0 text-muted-foreground"
@@ -670,8 +670,8 @@ function PublishRepositoryDialog(props: PublishRepositoryDialogProps) {
"relative flex cursor-pointer items-center gap-3 rounded-lg border px-3 py-3 text-left outline-none transition-[background-color,border-color,box-shadow]",
"focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-1 focus-visible:ring-offset-background",
isSelected
? "border-primary bg-background shadow-sm ring-2 ring-primary/35"
: "border-border bg-background hover:border-foreground/20 hover:bg-muted/50",
? "border-primary bg-background shadow-sm ring-2 ring-primary/35 dark:border-transparent dark:bg-primary/10 dark:shadow-none dark:ring-1 dark:ring-primary/30"
: "border-border bg-background hover:border-foreground/20 hover:bg-muted/50 dark:border-transparent dark:bg-white/[0.035] dark:hover:bg-accent",
)}
>
<option.Icon className="size-5 shrink-0" aria-hidden />
@@ -756,8 +756,8 @@ function PublishRepositoryDialog(props: PublishRepositoryDialogProps) {
"relative flex cursor-pointer items-center gap-3 rounded-lg border px-3 py-2.5 text-left outline-none transition-[background-color,border-color,box-shadow]",
"focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-1 focus-visible:ring-offset-background",
isSelected
? "border-primary bg-background shadow-sm ring-2 ring-primary/35"
: "border-border bg-background hover:border-foreground/20 hover:bg-muted/50",
? "border-primary bg-background shadow-sm ring-2 ring-primary/35 dark:border-transparent dark:bg-primary/10 dark:shadow-none dark:ring-1 dark:ring-primary/30"
: "border-border bg-background hover:border-foreground/20 hover:bg-muted/50 dark:border-transparent dark:bg-white/[0.035] dark:hover:bg-accent",
)}
>
<option.Icon
@@ -831,8 +831,8 @@ function PublishRepositoryDialog(props: PublishRepositoryDialogProps) {
"rounded-md border px-3 py-1.5 text-center text-sm font-medium outline-none transition",
"focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-1 focus-visible:ring-offset-background",
isSelected
? "border-primary bg-background ring-2 ring-primary/35 text-foreground"
: "border-border bg-background text-muted-foreground hover:border-foreground/20 hover:text-foreground",
? "border-primary bg-background ring-2 ring-primary/35 text-foreground dark:border-transparent dark:bg-primary/10 dark:ring-1 dark:ring-primary/30"
: "border-border bg-background text-muted-foreground hover:border-foreground/20 hover:text-foreground dark:border-transparent dark:bg-white/[0.035]",
)}
>
{value === "ssh" ? "SSH" : "HTTPS"}
@@ -849,7 +849,7 @@ function PublishRepositoryDialog(props: PublishRepositoryDialogProps) {
<div
role="status"
aria-live="polite"
className="flex items-center gap-2 rounded-md border border-input bg-muted/40 px-3 py-2 text-xs text-muted-foreground"
className="flex items-center gap-2 rounded-md border border-input bg-muted/40 px-3 py-2 text-xs text-muted-foreground dark:border-transparent dark:bg-white/[0.035]"
>
<Spinner className="size-3.5" aria-hidden />
Publishing repository to {publishProviderLabel}...
@@ -884,7 +884,7 @@ function PublishRepositoryDialog(props: PublishRepositoryDialogProps) {
: `Remote "${publishResult.remoteName}" is set up. Make a commit and push it to share your code.`}
</p>
</div>
<div className="flex items-center gap-2 rounded-lg border border-input bg-muted/40 px-3 py-2">
<div className="flex items-center gap-2 rounded-lg border border-input bg-muted/40 px-3 py-2 dark:border-transparent dark:bg-white/[0.035]">
<currentPublishProvider.Icon className="size-3.5 shrink-0 text-muted-foreground" />
<span className="min-w-0 flex-1 truncate font-mono text-xs text-foreground">
{publishResult.repository.nameWithOwner}
@@ -905,7 +905,7 @@ function PublishRepositoryDialog(props: PublishRepositoryDialogProps) {
</Button>
</>
) : (
<div className="rounded-md border border-input bg-background px-3 py-2 text-xs text-muted-foreground">
<div className="rounded-md border border-input bg-background px-3 py-2 text-xs text-muted-foreground dark:border-transparent dark:bg-white/[0.035]">
Publish result unavailable.
</div>
)}
@@ -913,7 +913,7 @@ function PublishRepositoryDialog(props: PublishRepositoryDialogProps) {
</AnimatedHeight>
</DialogPanel>
<DialogFooter>
<DialogFooter className="dark:border-transparent dark:bg-transparent">
{publishWizardStep === 2 ? (
<Button size="sm" onClick={() => handleOpenChange(false)}>
Done
@@ -1117,12 +1117,12 @@ export default function GitActionsControl({
activeDraftThread.worktreePath === null;
useEffect(() => {
if (isGitActionRunning || isSelectingWorktreeBase) {
if (isGitActionRunning || isSelectingWorktreeBase || activeServerThread) {
return;
}
const branchUpdate = resolveLiveThreadBranchUpdate({
threadBranch: activeServerThread?.branch ?? activeDraftThread?.branch ?? null,
threadBranch: activeDraftThread?.branch ?? null,
gitStatus: gitStatusForActions,
});
if (!branchUpdate) {
@@ -1131,7 +1131,7 @@ export default function GitActionsControl({
persistThreadBranchSync(branchUpdate.branch);
}, [
activeServerThread?.branch,
activeServerThread,
activeDraftThread?.branch,
gitStatusForActions,
isGitActionRunning,
@@ -1831,7 +1831,7 @@ export default function GitActionsControl({
<DialogDescription>{COMMIT_DIALOG_DESCRIPTION}</DialogDescription>
</DialogHeader>
<DialogPanel className="space-y-4">
<div className="space-y-3 rounded-lg border border-input bg-muted/40 p-3 text-xs">
<div className="space-y-3 rounded-xl bg-zinc-25 p-3 text-sm ring-1 ring-black/5 dark:bg-white/[0.035] dark:ring-white/5">
<div className="grid grid-cols-[auto_1fr] items-center gap-x-2 gap-y-1">
<span className="text-muted-foreground">Branch</span>
<span className="flex items-center justify-between gap-2">
@@ -1839,9 +1839,7 @@ export default function GitActionsControl({
{gitStatusForActions?.refName ?? "(detached HEAD)"}
</span>
{isDefaultRef && (
<span className="text-right text-warning text-xs">
Warning: default refName
</span>
<span className="text-right text-warning">Warning: default refName</span>
)}
</span>
</div>
@@ -1880,14 +1878,14 @@ export default function GitActionsControl({
<p className="font-medium">none</p>
) : (
<div className="space-y-2">
<ScrollArea className="h-44 rounded-md border border-input bg-background">
<ScrollArea className="h-44 rounded-lg bg-card ring-1 ring-black/5 dark:bg-white/[0.025] dark:ring-white/5">
<div className="space-y-1 p-1">
{allFiles.map((file) => {
const isExcluded = excludedFiles.has(file.path);
return (
<div
key={file.path}
className="flex w-full items-center gap-2 rounded-md px-2 py-1 font-mono text-xs transition-colors hover:bg-accent/50"
className="flex w-full items-center gap-2 rounded-md px-2 py-1 font-mono hover:bg-accent/50"
>
{isEditingFiles && (
<Checkbox
@@ -1946,7 +1944,7 @@ export default function GitActionsControl({
</div>
</div>
<div className="space-y-1">
<p className="text-xs font-medium">Commit message (optional)</p>
<p className="text-sm font-medium">Commit message (optional)</p>
<Textarea
value={dialogCommitMessage}
onChange={(event) => setDialogCommitMessage(event.target.value)}
@@ -1955,7 +1953,7 @@ export default function GitActionsControl({
/>
</div>
</DialogPanel>
<DialogFooter>
<DialogFooter variant="bare">
<Button
variant="outline"
size="sm"
@@ -2005,7 +2003,7 @@ export default function GitActionsControl({
</DialogTitle>
<DialogDescription>{pendingDefaultBranchActionCopy?.description}</DialogDescription>
</DialogHeader>
<DialogFooter className="sm:flex-wrap sm:items-center">
<DialogFooter className="dark:border-transparent dark:bg-transparent sm:flex-wrap sm:items-center">
<Button
className="w-full sm:mr-auto sm:w-auto"
variant="outline"
@@ -2,6 +2,7 @@ import type {
ProjectScript,
ProjectScriptIcon,
ResolvedKeybindingsConfig,
T3ProjectFileScript,
} from "@t3tools/contracts";
import {
isAtomCommandInterrupted,
@@ -11,6 +12,7 @@ import {
import {
BugIcon,
ChevronDownIcon,
DownloadIcon,
FlaskConicalIcon,
HammerIcon,
ListChecksIcon,
@@ -54,7 +56,16 @@ import {
import { Group, GroupSeparator } from "./ui/group";
import { Input } from "./ui/input";
import { Label } from "./ui/label";
import { Menu, MenuItem, MenuPopup, MenuShortcut, MenuTrigger } from "./ui/menu";
import {
Menu,
MenuGroup,
MenuGroupLabel,
MenuItem,
MenuPopup,
MenuSeparator,
MenuShortcut,
MenuTrigger,
} from "./ui/menu";
import { Popover, PopoverPopup, PopoverTrigger } from "./ui/popover";
import { Switch } from "./ui/switch";
import { Textarea } from "./ui/textarea";
@@ -98,8 +109,12 @@ export interface NewProjectScriptInput {
export type ProjectScriptActionResult = AtomCommandResult<void, unknown>;
const NO_FILE_SCRIPTS: ReadonlyArray<T3ProjectFileScript> = [];
interface ProjectScriptsControlProps {
scripts: ReadonlyArray<ProjectScript>;
/** Scripts declared in the project's checked-in t3.json, offered for import. */
fileScripts?: ReadonlyArray<T3ProjectFileScript>;
keybindings: ResolvedKeybindingsConfig;
preferredScriptId?: string | null;
onRunScript: (script: ProjectScript) => void;
@@ -113,6 +128,7 @@ interface ProjectScriptsControlProps {
export default function ProjectScriptsControl({
scripts,
fileScripts = NO_FILE_SCRIPTS,
keybindings,
preferredScriptId = null,
onRunScript,
@@ -141,6 +157,18 @@ export default function ProjectScriptsControl({
}
return primaryProjectScript(scripts);
}, [preferredScriptId, scripts]);
const importableScripts = useMemo(
() =>
fileScripts.filter(
(fileScript) =>
!scripts.some(
(script) =>
script.command === fileScript.command ||
script.name.toLowerCase() === fileScript.name.toLowerCase(),
),
),
[fileScripts, scripts],
);
const isEditing = editingScriptId !== null;
const dropdownItemClassName =
"data-highlighted:bg-transparent data-highlighted:text-foreground hover:bg-accent hover:text-accent-foreground focus-visible:bg-accent focus-visible:text-accent-foreground data-highlighted:hover:bg-accent data-highlighted:hover:text-accent-foreground data-highlighted:focus-visible:bg-accent data-highlighted:focus-visible:text-accent-foreground";
@@ -247,6 +275,57 @@ export default function ProjectScriptsControl({
void onDeleteScript(editingScriptId);
}, [editingScriptId, onDeleteScript]);
const importFileScript = async (fileScript: T3ProjectFileScript) => {
const payload: NewProjectScriptInput = {
name: fileScript.name,
command: fileScript.command,
icon: fileScript.icon ?? "play",
runOnWorktreeCreate: fileScript.runOnWorktreeCreate ?? false,
keybinding: null,
previewUrl: fileScript.previewUrl ?? null,
autoOpenPreview: fileScript.previewUrl ? (fileScript.autoOpenPreview ?? false) : false,
};
const result = await onAddScript(payload);
if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
// Surface the failure through the regular add dialog, prefilled so the
// user can adjust and retry.
const error = squashAtomCommandFailure(result);
setEditingScriptId(null);
setName(payload.name);
setCommand(payload.command);
setIcon(payload.icon);
setIconPickerOpen(false);
setRunOnWorktreeCreate(payload.runOnWorktreeCreate);
setKeybinding("");
setPreviewUrl(payload.previewUrl ?? "");
setAutoOpenPreview(payload.autoOpenPreview);
setValidationError(error instanceof Error ? error.message : "Failed to import action.");
setDialogOpen(true);
}
};
const importMenuItems = importableScripts.length > 0 && (
<>
{primaryScript && <MenuSeparator />}
<MenuGroup>
<MenuGroupLabel>From t3.json</MenuGroupLabel>
{importableScripts.map((fileScript) => (
<MenuItem
key={`${fileScript.name} ${fileScript.command}`}
className={dropdownItemClassName}
onClick={() => void importFileScript(fileScript)}
>
<ScriptIcon icon={fileScript.icon ?? "play"} className="size-4" />
<span className="truncate">{fileScript.name}</span>
<MenuShortcut className="ms-auto">
<DownloadIcon className="size-3.5" aria-label="Import" />
</MenuShortcut>
</MenuItem>
))}
</MenuGroup>
</>
);
return (
<>
{primaryScript ? (
@@ -320,6 +399,7 @@ export default function ProjectScriptsControl({
</MenuItem>
);
})}
{importMenuItems}
<MenuItem className={dropdownItemClassName} onClick={openAddDialog}>
<PlusIcon className="size-4" />
Add action
@@ -327,6 +407,23 @@ export default function ProjectScriptsControl({
</MenuPopup>
</Menu>
</Group>
) : importableScripts.length > 0 ? (
<Menu highlightItemOnHover={false}>
<MenuTrigger render={<Button size="xs" variant="outline" aria-label="Project actions" />}>
<PlusIcon className="size-3.5" />
<span className="sr-only @3xl/header-actions:not-sr-only @3xl/header-actions:ml-0.5">
Add action
</span>
<ChevronDownIcon className="size-3.5" />
</MenuTrigger>
<MenuPopup align="end">
{importMenuItems}
<MenuItem className={dropdownItemClassName} onClick={openAddDialog}>
<PlusIcon className="size-4" />
Add action
</MenuItem>
</MenuPopup>
</Menu>
) : (
<Tooltip>
<TooltipTrigger
@@ -382,7 +479,7 @@ export default function ProjectScriptsControl({
<Button
type="button"
variant="outline"
className="size-9 shrink-0 hover:bg-popover active:bg-popover data-pressed:bg-popover data-pressed:shadow-xs/5 data-pressed:before:shadow-[0_1px_--theme(--color-black/4%)] dark:data-pressed:before:shadow-[0_-1px_--theme(--color-white/6%)]"
className="size-9 shrink-0 hover:bg-popover active:bg-popover data-pressed:bg-popover data-pressed:shadow-xs/5 data-pressed:before:shadow-[0_1px_--theme(--color-black/4%)] dark:border-transparent dark:bg-white/[0.035] dark:data-pressed:before:shadow-none"
aria-label="Choose icon"
/>
}
@@ -397,10 +494,10 @@ export default function ProjectScriptsControl({
<button
key={entry.id}
type="button"
className={`relative flex flex-col items-center gap-2 rounded-md border px-2 py-2 text-xs ${
className={`relative flex flex-col items-center gap-2 rounded-md border px-2 py-2 text-xs dark:border-transparent ${
isSelected
? "border-primary/70 bg-primary/10"
: "border-border/70 hover:bg-accent/60"
? "border-primary/70 bg-primary/10 dark:ring-1 dark:ring-primary/30"
: "border-border/70 hover:bg-accent/60 dark:bg-white/[0.035]"
}`}
onClick={() => {
setIcon(entry.id);
@@ -458,7 +555,7 @@ export default function ProjectScriptsControl({
Open this URL in the in-app preview when this action runs.
</p>
</div>
<label className="flex items-center justify-between gap-3 rounded-md border border-border/70 px-3 py-2 text-sm">
<label className="flex items-center justify-between gap-3 rounded-md border border-border/70 px-3 py-2 text-sm dark:border-transparent dark:bg-white/[0.035]">
<span>Run automatically on worktree creation</span>
<Switch
checked={runOnWorktreeCreate}
@@ -466,7 +563,7 @@ export default function ProjectScriptsControl({
/>
</label>
<label
className={`flex items-center justify-between gap-3 rounded-md border border-border/70 px-3 py-2 text-sm ${
className={`flex items-center justify-between gap-3 rounded-md border border-border/70 px-3 py-2 text-sm dark:border-transparent dark:bg-white/[0.035] ${
previewUrl.trim().length === 0 ? "opacity-60" : ""
}`}
>
@@ -480,7 +577,7 @@ export default function ProjectScriptsControl({
{validationError && <p className="text-sm text-destructive">{validationError}</p>}
</form>
</DialogPanel>
<DialogFooter>
<DialogFooter className="dark:border-transparent dark:bg-transparent">
{isEditing && (
<Button
type="button"
+2 -2
View File
@@ -157,7 +157,7 @@ function RightPanelEmptyState(props: {
key={action.label}
type="button"
onClick={action.onClick}
className="flex min-h-28 w-full flex-col items-start rounded-lg border border-border/80 bg-card/40 p-4 text-left transition hover:border-border hover:bg-accent/60"
className="flex min-h-28 w-full flex-col items-start rounded-lg border border-border/80 bg-card p-4 text-left transition hover:border-border hover:bg-accent/60 dark:border-transparent dark:shadow-none dark:inset-ring-1 dark:inset-ring-white/5"
>
{content}
</button>
@@ -166,7 +166,7 @@ function RightPanelEmptyState(props: {
const disabledCard = (
<button
type="button"
className="flex min-h-28 w-full cursor-not-allowed flex-col items-start rounded-lg border border-border/80 bg-card/40 p-4 text-left opacity-40"
className="flex min-h-28 w-full cursor-not-allowed flex-col items-start rounded-lg border border-border/80 bg-card p-4 text-left opacity-40 dark:border-transparent dark:shadow-none dark:inset-ring-1 dark:inset-ring-white/5"
aria-disabled="true"
>
{content}
@@ -0,0 +1,198 @@
import type { Dispatch, ReactElement, SetStateAction } from "react";
import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
import * as Cause from "effect/Cause";
import { AsyncResult } from "effect/unstable/reactivity";
import type { EnvironmentId } from "@t3tools/contracts";
const testState = vi.hoisted(() => ({
updateServer: vi.fn(),
toast: vi.fn(),
}));
const hooks = vi.hoisted(() => {
let cursor = 0;
let slots: unknown[] = [];
const nextIndex = () => cursor++;
return {
beginRender() {
cursor = 0;
},
reset() {
cursor = 0;
slots = [];
},
useEffect() {
nextIndex();
},
useMemoCache(size: number): unknown[] {
const index = nextIndex();
if (!slots[index]) {
slots[index] = Array.from({ length: size }, () => Symbol.for("react.memo_cache_sentinel"));
}
return slots[index] as unknown[];
},
useRef<T>(initialValue: T): { current: T } {
const index = nextIndex();
if (!slots[index]) {
slots[index] = { current: initialValue };
}
return slots[index] as { current: T };
},
useState<T>(initialValue: T | (() => T)): [T, Dispatch<SetStateAction<T>>] {
const index = nextIndex();
if (index >= slots.length) {
slots[index] =
typeof initialValue === "function" ? (initialValue as () => T)() : initialValue;
}
const setValue: Dispatch<SetStateAction<T>> = (nextValue) => {
const previous = slots[index] as T;
slots[index] =
typeof nextValue === "function" ? (nextValue as (value: T) => T)(previous) : nextValue;
};
return [slots[index] as T, setValue];
},
};
});
vi.mock("react", async (importOriginal) => {
const actual = await importOriginal<typeof import("react")>();
return {
...actual,
useEffect: hooks.useEffect,
useRef: hooks.useRef,
useState: hooks.useState,
};
});
vi.mock("react/compiler-runtime", () => ({ c: hooks.useMemoCache }));
vi.mock("~/hooks/useCopyToClipboard", () => ({
useCopyToClipboard: () => ({ copyToClipboard: vi.fn() }),
}));
vi.mock("~/state/server", () => ({
serverEnvironment: { updateServer: Symbol("updateServer") },
}));
vi.mock("~/state/use-atom-command", () => ({
useAtomCommand: () => testState.updateServer,
}));
vi.mock("./ui/toast", () => ({
toastManager: { add: testState.toast },
}));
import { ServerUpdateAction } from "./ServerUpdateAction";
type ActionElement = ReactElement<{
readonly disabled?: boolean;
readonly onClick?: () => void;
}>;
function renderAction(): ActionElement {
hooks.beginRender();
return ServerUpdateAction({
environmentId: "env-test" as EnvironmentId,
serverLabel: "Test server",
selfUpdate: "boot-service",
targetVersion: "0.0.29",
}) as ActionElement;
}
function deferred<T>() {
let resolve!: (value: T) => void;
const promise = new Promise<T>((complete) => {
resolve = complete;
});
return { promise, resolve };
}
async function flushPromises(): Promise<void> {
await Promise.resolve();
await Promise.resolve();
await Promise.resolve();
await Promise.resolve();
await Promise.resolve();
}
describe("ServerUpdateAction", () => {
beforeEach(() => {
vi.useFakeTimers();
hooks.reset();
testState.updateServer.mockReset();
testState.toast.mockReset();
});
afterEach(() => {
vi.useRealTimers();
});
it("starts a fresh reconnect timeout after a long install succeeds", async () => {
const update =
deferred<
ReturnType<typeof AsyncResult.success<{ targetVersion: string; method: "boot-service" }>>
>();
testState.updateServer.mockReturnValue(update.promise);
renderAction().props.onClick?.();
expect(renderAction().props.disabled).toBe(true);
await vi.advanceTimersByTimeAsync(11 * 60_000);
update.resolve(
AsyncResult.success({
targetVersion: "0.0.29",
method: "boot-service",
}),
);
await flushPromises();
// The click-based deadline would have fired by now. Success gets a fresh
// twelve-minute reconnect window, so the action remains disabled.
await vi.advanceTimersByTimeAsync(2 * 60_000);
expect(renderAction().props.disabled).toBe(true);
expect(testState.toast).not.toHaveBeenCalledWith(
expect.objectContaining({ title: "Server update timed out" }),
);
await vi.advanceTimersByTimeAsync(10 * 60_000);
expect(renderAction().props.disabled).not.toBe(true);
expect(testState.toast).toHaveBeenCalledWith(
expect.objectContaining({ title: "Server update timed out" }),
);
});
it("does not let an expired request clear a newer retry", async () => {
const first = deferred<ReturnType<typeof AsyncResult.failure>>();
const retry =
deferred<
ReturnType<typeof AsyncResult.success<{ targetVersion: string; method: "boot-service" }>>
>();
testState.updateServer.mockReturnValueOnce(first.promise).mockReturnValueOnce(retry.promise);
renderAction().props.onClick?.();
await vi.advanceTimersByTimeAsync(12 * 60_000);
expect(renderAction().props.disabled).not.toBe(true);
renderAction().props.onClick?.();
expect(renderAction().props.disabled).toBe(true);
first.resolve(AsyncResult.failure(Cause.fail(new Error("first request failed late"))));
await flushPromises();
expect(renderAction().props.disabled).toBe(true);
expect(testState.updateServer).toHaveBeenCalledTimes(2);
retry.resolve(AsyncResult.success({ targetVersion: "0.0.29", method: "boot-service" }));
await flushPromises();
expect(renderAction().props.disabled).toBe(true);
});
it("quietly releases the action when a restart RPC is interrupted", async () => {
testState.updateServer.mockResolvedValue(AsyncResult.failure(Cause.interrupt()));
renderAction().props.onClick?.();
await flushPromises();
expect(renderAction().props.disabled).not.toBe(true);
expect(testState.toast).not.toHaveBeenCalledWith(
expect.objectContaining({ title: "Server update failed" }),
);
});
});
@@ -0,0 +1,201 @@
import { useEffect, useRef, useState } from "react";
import type { EnvironmentId, ServerSelfUpdateCapability } from "@t3tools/contracts";
import {
isAtomCommandInterrupted,
squashAtomCommandFailure,
} from "@t3tools/client-runtime/state/runtime";
import { useCopyToClipboard } from "~/hooks/useCopyToClipboard";
import { serverEnvironment } from "~/state/server";
import { useAtomCommand } from "~/state/use-atom-command";
import { manualServerUpdateCommand } from "~/versionSkew";
import { Button } from "./ui/button";
import { Spinner } from "./ui/spinner";
import { toastManager } from "./ui/toast";
/**
* The npm install on the server side is capped at 10 minutes; expire the
* spinner a bit beyond that so a dead transport never strands a disabled
* button, while a legitimately slow install is never cut off.
*/
const UPDATE_PENDING_EXPIRY_MS = 12 * 60_000;
function updateFailureMessage(error: unknown): string {
return error instanceof Error ? error.message : "Server update failed.";
}
/**
* The call-to-action for a version-skewed server, matched to the update path
* it advertises: a one-click install-and-restart for servers that can update
* themselves, an update-the-desktop-app hint for desktop-managed backends
* (running `npx t3` there would start a second server, not update this one),
* and copying the manual relaunch command for everything else — so the skew
* warning always offers a way out.
*/
export function ServerUpdateAction({
environmentId,
serverLabel,
selfUpdate,
targetVersion,
}: {
readonly environmentId: EnvironmentId;
readonly serverLabel: string;
readonly selfUpdate: ServerSelfUpdateCapability | null;
readonly targetVersion: string;
}) {
const updateServer = useAtomCommand(serverEnvironment.updateServer, {
reportFailure: false,
});
const [pending, setPending] = useState(false);
const inFlightRef = useRef(false);
const attemptRef = useRef(0);
const expiryRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const { copyToClipboard } = useCopyToClipboard<{ command: string }>({
target: "update command",
onCopy: ({ command }) => {
toastManager.add({
type: "success",
title: "Update command copied",
description: `Run \`${command}\` on ${serverLabel} to update it.`,
});
},
onError: (error) => {
toastManager.add({
type: "error",
title: "Could not copy update command",
description: error.message,
});
},
});
useEffect(
() => () => {
if (expiryRef.current !== null) {
clearTimeout(expiryRef.current);
expiryRef.current = null;
}
attemptRef.current += 1;
inFlightRef.current = false;
},
[],
);
const handleUpdate = () => {
// Synchronous re-entry guard: setPending is async, so a rapid
// double-click would otherwise dispatch two updates.
if (inFlightRef.current) {
return;
}
inFlightRef.current = true;
const attempt = attemptRef.current + 1;
attemptRef.current = attempt;
const ownsAttempt = () => attemptRef.current === attempt;
setPending(true);
const armExpiry = () => {
const expiry = setTimeout(() => {
if (!ownsAttempt()) return;
expiryRef.current = null;
attemptRef.current += 1;
inFlightRef.current = false;
setPending(false);
toastManager.add({
type: "error",
title: "Server update timed out",
description: "The update may still be running on the server — check again in a minute.",
});
}, UPDATE_PENDING_EXPIRY_MS);
expiryRef.current = expiry;
return expiry;
};
let expiry = armExpiry();
let restartAccepted = false;
const keepPendingForRestart = () => {
restartAccepted = true;
if (expiryRef.current === expiry) {
clearTimeout(expiry);
expiry = armExpiry();
}
};
void Promise.resolve()
.then(() =>
updateServer({
environmentId,
input: { targetVersion },
}),
)
.then((result) => {
if (!ownsAttempt()) return;
if (result._tag === "Failure") {
// An interrupt may be the expected boot-service disconnect, but it
// can also be client-side cancellation before restart was accepted.
// Release the action quietly; version sync will remove it when a
// successful replacement reconnects.
if (isAtomCommandInterrupted(result)) {
return;
}
toastManager.add({
type: "error",
title: "Server update failed",
description: updateFailureMessage(squashAtomCommandFailure(result)),
});
return;
}
keepPendingForRestart();
// Installation can legitimately consume most of the request window.
// Give restart/reconnect a fresh full window after the server accepts
// the handoff instead of expiring based on the original click time.
toastManager.add({
type: "success",
title: `Updating ${serverLabel}`,
description: `t3@${result.value.targetVersion} is installed — the server is restarting and will reconnect shortly.`,
});
})
.catch((error: unknown) => {
if (!ownsAttempt()) return;
toastManager.add({
type: "error",
title: "Server update failed",
description: updateFailureMessage(error),
});
})
.finally(() => {
// A successful RPC only acknowledges that restart is scheduled. Keep
// the action disabled until version sync unmounts it, or until the
// safety expiry reports that reconnection never arrived.
if (restartAccepted || !ownsAttempt() || expiryRef.current !== expiry) return;
expiryRef.current = null;
clearTimeout(expiry);
attemptRef.current += 1;
inFlightRef.current = false;
setPending(false);
});
};
if (selfUpdate === "desktop-managed") {
return (
<span className="text-muted-foreground text-xs">
Update the desktop app on that machine to update this server.
</span>
);
}
if (selfUpdate === null) {
const command = manualServerUpdateCommand(targetVersion);
return (
<Button size="xs" variant="outline" onClick={() => copyToClipboard(command, { command })}>
Copy update command
</Button>
);
}
return pending ? (
<Button size="xs" disabled>
<Spinner className="size-3.5" />
Updating...
</Button>
) : (
<Button size="xs" onClick={() => void handleUpdate()}>
Update server
</Button>
);
}
+100 -12
View File
@@ -20,7 +20,9 @@ import {
resolveThreadRowClassName,
resolveSidebarV2Status,
resolveThreadStatusPill,
shouldNavigateAfterProjectRemoval,
shouldClearThreadSelectionOnMouseDown,
sortLogicalProjectsForSidebar,
sortThreadsForSidebarV2,
sortProjectsForSidebar,
sortScopedProjectsForSidebar,
@@ -33,6 +35,7 @@ import {
ProviderInstanceId,
ThreadId,
} from "@t3tools/contracts";
import {
DEFAULT_INTERACTION_MODE,
DEFAULT_RUNTIME_MODE,
@@ -42,6 +45,56 @@ import {
const localEnvironmentId = EnvironmentId.make("environment-local");
describe("shouldNavigateAfterProjectRemoval", () => {
const projectThreads = [{ environmentId: "environment-local", id: "thread-1" }];
it("navigates away from a draft route owned by the removed project", () => {
expect(
shouldNavigateAfterProjectRemoval({
routeTarget: { kind: "draft", draftId: "draft-1" as never },
projectThreads,
projectDraftId: "draft-1",
}),
).toBe(true);
});
it("does not navigate away from a different draft route", () => {
expect(
shouldNavigateAfterProjectRemoval({
routeTarget: { kind: "draft", draftId: "draft-2" as never },
projectThreads,
projectDraftId: "draft-1",
}),
).toBe(false);
});
it("navigates away from a server thread owned by the removed project", () => {
expect(
shouldNavigateAfterProjectRemoval({
routeTarget: {
kind: "server",
threadRef: {
environmentId: EnvironmentId.make("environment-local"),
threadId: ThreadId.make("thread-1"),
},
},
projectThreads,
projectDraftId: null,
}),
).toBe(true);
});
it("does not navigate from an unrelated route", () => {
expect(
shouldNavigateAfterProjectRemoval({
routeTarget: null,
projectThreads,
projectDraftId: null,
}),
).toBe(false);
});
});
describe("archiveSelectedThreadEntries", () => {
const entries = [{ threadKey: "one" }, { threadKey: "two" }, { threadKey: "three" }] as const;
const success = { _tag: "Success" } as const;
@@ -834,26 +887,24 @@ describe("resolveThreadStatusPill", () => {
});
describe("resolveThreadRowClassName", () => {
it("uses the darker selected palette when a thread is both selected and active", () => {
it("uses the active sidebar surface when a thread is both selected and active", () => {
const className = resolveThreadRowClassName({ isActive: true, isSelected: true });
expect(className).toContain("bg-primary/22");
expect(className).toContain("hover:bg-primary/26");
expect(className).toContain("dark:bg-primary/30");
expect(className).not.toContain("bg-accent/85");
expect(className).toContain("bg-sidebar-row-active");
expect(className).toContain("text-sidebar-foreground");
expect(className).not.toContain("bg-primary");
});
it("uses selected hover colors for selected threads", () => {
const className = resolveThreadRowClassName({ isActive: false, isSelected: true });
expect(className).toContain("bg-primary/15");
expect(className).toContain("hover:bg-primary/19");
expect(className).toContain("dark:bg-primary/22");
expect(className).not.toContain("hover:bg-accent");
expect(className).toContain("bg-sidebar-row-selected");
expect(className).toContain("hover:bg-sidebar-row-active");
expect(className).not.toContain("bg-primary");
});
it("keeps the accent palette for active-only threads", () => {
it("uses the active sidebar surface for active-only threads", () => {
const className = resolveThreadRowClassName({ isActive: true, isSelected: false });
expect(className).toContain("bg-accent/85");
expect(className).toContain("hover:bg-accent");
expect(className).toContain("bg-sidebar-row-active");
expect(className).toContain("hover:bg-sidebar-row-active");
});
});
@@ -1304,3 +1355,40 @@ describe("sortScopedProjectsForSidebar", () => {
]);
});
});
describe("sortLogicalProjectsForSidebar", () => {
it("uses saved order only in manual mode and activity order otherwise", () => {
const olderProjectId = ProjectId.make("project-older");
const newerProjectId = ProjectId.make("project-newer");
const projects = [
{
...makeProject({ id: olderProjectId, title: "Older project" }),
projectKey: "logical-older",
memberProjectRefs: [{ environmentId: localEnvironmentId, projectId: olderProjectId }],
},
{
...makeProject({ id: newerProjectId, title: "Newer project" }),
projectKey: "logical-newer",
memberProjectRefs: [{ environmentId: localEnvironmentId, projectId: newerProjectId }],
},
];
const threads = [
makeThread({
projectId: olderProjectId,
updatedAt: "2026-03-09T10:01:00.000Z",
}),
makeThread({
id: ThreadId.make("thread-newer"),
projectId: newerProjectId,
updatedAt: "2026-03-09T10:05:00.000Z",
}),
];
expect(sortLogicalProjectsForSidebar(projects, threads, "manual")).toEqual(projects);
expect(
sortLogicalProjectsForSidebar(projects, threads, "updated_at").map(
(project) => project.projectKey,
),
).toEqual(["logical-newer", "logical-older"]);
});
});
+77 -5
View File
@@ -8,6 +8,7 @@ import {
type ThreadSortInput,
} from "../lib/threadSort";
import type { SidebarThreadSummary, Thread } from "../types";
import type { ThreadRouteTarget } from "../threadRoutes";
import { cn } from "../lib/utils";
import { isLatestTurnSettled } from "../session-logic";
import { resolveServerBackedAppStageLabel } from "../branding.logic";
@@ -35,6 +36,14 @@ type ScopedSidebarThread = ThreadSortInput & {
archivedAt: string | null;
};
type LogicalSidebarProject = SidebarProject & {
projectKey: string;
memberProjectRefs: readonly {
environmentId: string;
projectId: string;
}[];
};
export type ThreadTraversalDirection = "previous" | "next";
export async function archiveSelectedThreadEntries<
@@ -377,6 +386,28 @@ export function resolveAdjacentThreadId<T>(input: {
return currentIndex < threadIds.length - 1 ? (threadIds[currentIndex + 1] ?? null) : null;
}
export function shouldNavigateAfterProjectRemoval(input: {
routeTarget: ThreadRouteTarget | null;
projectThreads: readonly {
environmentId: string;
id: string;
}[];
projectDraftId: string | null;
}): boolean {
const { projectDraftId, projectThreads, routeTarget } = input;
if (routeTarget?.kind === "draft") {
return projectDraftId === routeTarget.draftId;
}
if (routeTarget?.kind !== "server") {
return false;
}
return projectThreads.some(
(thread) =>
thread.environmentId === routeTarget.threadRef.environmentId &&
thread.id === routeTarget.threadRef.threadId,
);
}
export function isContextMenuPointerDown(input: {
button: number;
ctrlKey: boolean;
@@ -391,30 +422,33 @@ export function resolveThreadRowClassName(input: {
isSelected: boolean;
}): string {
const baseClassName =
"h-6 w-full translate-x-0 cursor-pointer justify-start px-2 text-left select-none focus-visible:ring-1 focus-visible:ring-inset focus-visible:ring-ring sm:h-7";
"h-8 w-full translate-x-0 cursor-pointer justify-start rounded-md px-2 text-left text-sm select-none focus-visible:ring-1 focus-visible:ring-inset focus-visible:ring-ring";
if (input.isSelected && input.isActive) {
return cn(
baseClassName,
"bg-primary/22 text-foreground font-medium hover:bg-primary/26 hover:text-foreground dark:bg-primary/30 dark:hover:bg-primary/36",
"bg-sidebar-row-active text-sidebar-foreground font-medium hover:bg-sidebar-row-active hover:text-sidebar-foreground",
);
}
if (input.isSelected) {
return cn(
baseClassName,
"bg-primary/15 text-foreground hover:bg-primary/19 hover:text-foreground dark:bg-primary/22 dark:hover:bg-primary/28",
"bg-sidebar-row-selected text-sidebar-foreground hover:bg-sidebar-row-active hover:text-sidebar-foreground",
);
}
if (input.isActive) {
return cn(
baseClassName,
"bg-accent/85 text-foreground font-medium hover:bg-accent hover:text-foreground dark:bg-accent/55 dark:hover:bg-accent/70",
"bg-sidebar-row-active text-sidebar-foreground font-medium hover:bg-sidebar-row-active hover:text-sidebar-foreground",
);
}
return cn(baseClassName, "text-muted-foreground hover:bg-accent hover:text-foreground");
return cn(
baseClassName,
"text-sidebar-muted-foreground/80 hover:bg-sidebar-row-hover hover:text-sidebar-foreground",
);
}
// ── Sidebar v2 status model ─────────────────────────────────────────
@@ -701,6 +735,44 @@ export function sortProjectsForSidebar<
);
}
export function sortLogicalProjectsForSidebar<
TProject extends LogicalSidebarProject,
TThread extends ScopedSidebarThread,
>(
projects: readonly TProject[],
threads: readonly TThread[],
sortOrder: SidebarProjectSortOrder,
): TProject[] {
const groupKeyByProjectRef = new Map(
projects.flatMap((project) =>
project.memberProjectRefs.map(
(projectRef) =>
[`${projectRef.environmentId}\0${projectRef.projectId}`, project.projectKey] as const,
),
),
);
const threadsByProjectKey = new Map<string, TThread[]>();
for (const thread of threads) {
if (thread.archivedAt !== null) continue;
const projectKey = groupKeyByProjectRef.get(`${thread.environmentId}\0${thread.projectId}`);
if (!projectKey) continue;
const existing = threadsByProjectKey.get(projectKey);
if (existing) {
existing.push(thread);
} else {
threadsByProjectKey.set(projectKey, [thread]);
}
}
return sortProjectsByActivity(
projects,
sortOrder,
(project) => threadsByProjectKey.get(project.projectKey) ?? [],
(left, right) =>
left.title.localeCompare(right.title) || left.projectKey.localeCompare(right.projectKey),
);
}
/**
* Sorts the cross-environment project collection used by landing surfaces.
* Project ids are only unique within an environment, and archived threads
+29 -74
View File
@@ -15,6 +15,7 @@ import {
import {
ChangeRequestStatusIcon,
prStatusIndicator,
PrStatusTooltipContent,
resolveThreadPr,
terminalStatusFromRunningIds,
ThreadStatusLabel,
@@ -42,7 +43,6 @@ import { restrictToFirstScrollableAncestor, restrictToVerticalAxis } from "@dnd-
import { CSS } from "@dnd-kit/utilities";
import {
type ContextMenuItem,
DEFAULT_SERVER_SETTINGS,
ProjectId,
type ScopedThreadRef,
type ResolvedKeybindingsConfig,
@@ -80,7 +80,6 @@ import {
readThreadShell,
useProject,
useProjects,
useServerConfigs,
useThreadShells,
useThreadShellsForProjectRefs,
} from "../state/entities";
@@ -146,15 +145,7 @@ import {
DialogTitle,
} from "./ui/dialog";
import { Input } from "./ui/input";
import {
Menu,
MenuGroup,
MenuPopup,
MenuRadioGroup,
MenuRadioItem,
MenuSeparator,
MenuTrigger,
} from "./ui/menu";
import { Menu, MenuGroup, MenuPopup, MenuRadioGroup, MenuRadioItem, MenuTrigger } from "./ui/menu";
import {
NumberField,
NumberFieldDecrement,
@@ -202,7 +193,7 @@ import { useCopyToClipboard } from "~/hooks/useCopyToClipboard";
import { useIsMobile } from "~/hooks/useMediaQuery";
import { CommandDialogTrigger } from "./ui/command";
import { useClientSettings, useUpdateClientSettings } from "~/hooks/useSettings";
import { primaryServerKeybindingsAtom } from "../state/server";
import { primaryServerKeybindingsAtom, primaryServerSettingsAtom } from "../state/server";
import {
derivePhysicalProjectKey,
deriveProjectGroupingOverrideKey,
@@ -460,7 +451,11 @@ export const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThr
lastVisitedAt,
},
});
const pr = resolveThreadPr(thread.branch, gitStatus.data);
const pr = resolveThreadPr({
threadBranch: thread.branch,
gitStatus: gitStatus.data,
hasDedicatedWorktree: thread.worktreePath !== null,
});
const prStatus = prStatusIndicator(pr, gitStatus.data?.sourceControlProvider);
const terminalStatus = terminalStatusFromRunningIds(runningTerminalIds);
const isConfirmingArchive = confirmingArchiveThreadKey === threadKey && !isThreadRunning;
@@ -700,14 +695,16 @@ export const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThr
</button>
}
/>
<TooltipPopup side="top">{prStatus.tooltip}</TooltipPopup>
<TooltipPopup side="top">
<PrStatusTooltipContent status={prStatus} />
</TooltipPopup>
</Tooltip>
)}
{threadStatus && <ThreadStatusLabel status={threadStatus} />}
{renamingThreadKey === threadKey ? (
<input
ref={handleRenameInputRef}
className="min-w-0 flex-1 truncate text-base sm:text-xs bg-transparent outline-none border border-ring rounded px-0.5"
className="min-w-0 flex-1 truncate rounded border border-ring bg-transparent px-0.5 text-sm outline-none"
value={renamingTitle}
onChange={handleRenameInputChange}
onKeyDown={handleRenameInputKeyDown}
@@ -720,7 +717,7 @@ export const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThr
<TooltipTrigger
render={
<span
className="min-w-0 flex-1 truncate text-xs"
className="min-w-0 flex-1 truncate text-sm"
data-testid={`thread-title-${thread.id}`}
>
{thread.title}
@@ -975,13 +972,13 @@ const SidebarProjectThreadList = memo(function SidebarProjectThreadList(
return (
<SidebarMenuSub
ref={attachThreadListAutoAnimateRef}
className="mx-0.5 my-0 w-full translate-x-0 gap-0.5 overflow-hidden px-1 py-0 sm:mx-1 sm:px-1.5"
className="mx-0.5 my-0 w-full translate-x-0 gap-0.5 overflow-hidden border-l-0 px-1 py-0 sm:mx-1 sm:px-1.5"
>
{shouldShowThreadPanel && showEmptyThreadState ? (
<SidebarMenuSubItem className="w-full" data-thread-selection-safe>
<div
data-thread-selection-safe
className="flex h-6 w-full translate-x-0 items-center px-2 text-left text-[10px] text-muted-foreground/60"
className="flex h-8 w-full translate-x-0 items-center px-2 text-left text-xs text-sidebar-muted-foreground/75"
>
<span>No threads yet</span>
</div>
@@ -1027,7 +1024,7 @@ const SidebarProjectThreadList = memo(function SidebarProjectThreadList(
render={showMoreButtonRender}
data-thread-selection-safe
size="sm"
className="h-6 w-full translate-x-0 justify-start px-2 text-left text-[10px] text-muted-foreground/60 hover:bg-accent hover:text-muted-foreground/80"
className="h-8 w-full translate-x-0 justify-start px-2 text-left text-xs text-sidebar-muted-foreground/75 hover:bg-sidebar-row-hover hover:text-sidebar-foreground"
onClick={() => {
expandThreadListForProject(projectKey);
}}
@@ -1045,7 +1042,7 @@ const SidebarProjectThreadList = memo(function SidebarProjectThreadList(
render={showLessButtonRender}
data-thread-selection-safe
size="sm"
className="h-6 w-full translate-x-0 justify-start px-2 text-left text-[10px] text-muted-foreground/60 hover:bg-accent hover:text-muted-foreground/80"
className="h-8 w-full translate-x-0 justify-start px-2 text-left text-xs text-sidebar-muted-foreground/75 hover:bg-sidebar-row-hover hover:text-sidebar-foreground"
onClick={() => {
collapseThreadListForProject(projectKey);
}}
@@ -1106,7 +1103,7 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
(settings) => settings.confirmThreadArchive,
);
const projectGroupingSettings = useClientSettings(selectProjectGroupingSettings);
const serverConfigs = useServerConfigs();
const primaryServerSettings = useAtomValue(primaryServerSettingsAtom);
const deleteProject = useAtomCommand(projectEnvironment.delete, {
reportFailure: false,
});
@@ -1894,10 +1891,10 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
: null;
const seedContext = resolveSidebarNewThreadSeedContext({
projectId: member.id,
// The default env mode is a user preference stored on the primary
// environment's settings.json; remote environments never carry it.
defaultEnvMode: resolveSidebarNewThreadEnvMode({
defaultEnvMode:
serverConfigs.get(member.environmentId)?.settings.defaultThreadEnvMode ??
DEFAULT_SERVER_SETTINGS.defaultThreadEnvMode,
defaultEnvMode: primaryServerSettings.defaultThreadEnvMode,
}),
activeThread:
currentActiveThread && currentActiveThread.projectId === member.id
@@ -1946,7 +1943,7 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
}
})();
},
[handleNewThread, isMobile, router, serverConfigs, setOpenMobile],
[handleNewThread, isMobile, primaryServerSettings.defaultThreadEnvMode, router, setOpenMobile],
);
const handleCreateThreadClick = useCallback(
@@ -2245,7 +2242,7 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
<SidebarMenuButton
ref={isManualProjectSorting ? dragHandleProps?.setActivatorNodeRef : undefined}
size="sm"
className={`gap-2 px-2 py-1.5 pr-8 text-left hover:bg-accent group-hover/project-header:bg-accent group-hover/project-header:text-sidebar-accent-foreground max-sm:pr-14 ${
className={`h-8 gap-2 rounded-md px-2 py-1.5 pr-8 text-left hover:bg-sidebar-row-hover group-hover/project-header:bg-sidebar-row-hover group-hover/project-header:text-sidebar-foreground max-sm:pr-14 ${
isManualProjectSorting ? "cursor-grab active:cursor-grabbing" : "cursor-pointer"
}`}
{...(isManualProjectSorting && dragHandleProps ? dragHandleProps.attributes : {})}
@@ -2285,7 +2282,7 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
)}
<ProjectFavicon environmentId={project.environmentId} cwd={project.workspaceRoot} />
<span className="flex min-w-0 flex-1 items-center gap-2">
<span className="truncate text-xs font-medium text-foreground/90">
<span className="truncate text-sm font-medium text-sidebar-foreground/90">
{project.displayName}
</span>
{project.groupedProjectCount > 1 ? (
@@ -2596,20 +2593,16 @@ type SortableProjectHandleProps = Pick<
function ProjectSortMenu({
projectSortOrder,
threadSortOrder,
projectGroupingMode,
threadPreviewCount,
onProjectSortOrderChange,
onThreadSortOrderChange,
onProjectGroupingModeChange,
onThreadPreviewCountChange,
}: {
projectSortOrder: SidebarProjectSortOrder;
threadSortOrder: SidebarThreadSortOrder;
projectGroupingMode: SidebarProjectGroupingMode;
threadPreviewCount: SidebarThreadPreviewCount;
onProjectSortOrderChange: (sortOrder: SidebarProjectSortOrder) => void;
onThreadSortOrderChange: (sortOrder: SidebarThreadSortOrder) => void;
onProjectGroupingModeChange: (mode: SidebarProjectGroupingMode) => void;
onThreadPreviewCountChange: (count: SidebarThreadPreviewCount) => void;
}) {
const handleThreadPreviewCountChange = useCallback(
@@ -2713,30 +2706,6 @@ function ProjectSortMenu({
</NumberField>
</div>
</MenuGroup>
<MenuSeparator />
<MenuGroup>
<div className="px-2 pt-2 pb-1 font-medium text-muted-foreground sm:text-xs">
Group projects
</div>
<MenuRadioGroup
value={projectGroupingMode}
onValueChange={(value) => {
if (value === "repository" || value === "repository_path" || value === "separate") {
onProjectGroupingModeChange(value);
}
}}
>
{(
Object.entries(PROJECT_GROUPING_MODE_LABELS) as Array<
[SidebarProjectGroupingMode, string]
>
).map(([value, label]) => (
<MenuRadioItem key={value} value={value} className="min-h-7 py-1 sm:text-xs">
{label}
</MenuRadioItem>
))}
</MenuRadioGroup>
</MenuGroup>
</MenuPopup>
</Menu>
);
@@ -2787,7 +2756,6 @@ interface SidebarProjectsContentProps {
handleDesktopUpdateButtonClick: () => void;
projectSortOrder: SidebarProjectSortOrder;
threadSortOrder: SidebarThreadSortOrder;
projectGroupingMode: SidebarProjectGroupingMode;
threadPreviewCount: SidebarThreadPreviewCount;
updateSettings: ReturnType<typeof useUpdateClientSettings>;
openAddProject: () => void;
@@ -2828,7 +2796,6 @@ const SidebarProjectsContent = memo(function SidebarProjectsContent(
handleDesktopUpdateButtonClick,
projectSortOrder,
threadSortOrder,
projectGroupingMode,
threadPreviewCount,
updateSettings,
openAddProject,
@@ -2870,12 +2837,6 @@ const SidebarProjectsContent = memo(function SidebarProjectsContent(
},
[updateSettings],
);
const handleProjectGroupingModeChange = useCallback(
(groupingMode: SidebarProjectGroupingMode) => {
updateSettings({ sidebarProjectGroupingMode: groupingMode });
},
[updateSettings],
);
const handleThreadPreviewCountChange = useCallback(
(count: SidebarThreadPreviewCount) => {
updateSettings({ sidebarThreadPreviewCount: count });
@@ -2892,13 +2853,13 @@ const SidebarProjectsContent = memo(function SidebarProjectsContent(
render={
<SidebarMenuButton
size="sm"
className="gap-2 px-2 py-1.5 text-muted-foreground/70 hover:bg-accent hover:text-foreground focus-visible:ring-0"
className="h-8 gap-2 rounded-md px-2 py-1.5 text-sidebar-muted-foreground/80 hover:bg-sidebar-row-hover hover:text-sidebar-foreground focus-visible:ring-0"
data-testid="command-palette-trigger"
/>
}
>
<SearchIcon className="size-3.5 text-muted-foreground/70" />
<span className="flex-1 truncate text-left text-xs">Search</span>
<SearchIcon className="size-4 shrink-0 text-sidebar-muted-foreground/80" />
<span className="flex-1 truncate text-left text-sm font-medium">Search</span>
{commandPaletteShortcutLabel ? (
<Kbd className="h-4 min-w-0 rounded-sm px-1.5 text-[10px]">
{commandPaletteShortcutLabel}
@@ -2934,18 +2895,14 @@ const SidebarProjectsContent = memo(function SidebarProjectsContent(
<LocalSecondaryStatus />
<SidebarGroup className="px-2 py-2">
<div className="mb-1 flex items-center justify-between pl-2 pr-1.5">
<span className="text-[10px] font-medium uppercase tracking-wider text-muted-foreground/60">
Projects
</span>
<span className="text-xs font-medium text-sidebar-muted-foreground/80">Projects</span>
<div className="flex items-center gap-1">
<ProjectSortMenu
projectSortOrder={projectSortOrder}
threadSortOrder={threadSortOrder}
projectGroupingMode={projectGroupingMode}
threadPreviewCount={threadPreviewCount}
onProjectSortOrderChange={handleProjectSortOrderChange}
onThreadSortOrderChange={handleThreadSortOrderChange}
onProjectGroupingModeChange={handleProjectGroupingModeChange}
onThreadPreviewCountChange={handleThreadPreviewCountChange}
/>
<Tooltip>
@@ -3061,7 +3018,6 @@ export default function Sidebar() {
const isOnSettings = pathname.startsWith("/settings");
const sidebarThreadSortOrder = useClientSettings((s) => s.sidebarThreadSortOrder);
const sidebarProjectSortOrder = useClientSettings((s) => s.sidebarProjectSortOrder);
const sidebarProjectGroupingMode = useClientSettings((s) => s.sidebarProjectGroupingMode);
const projectGroupingSettings = useClientSettings(selectProjectGroupingSettings);
const sidebarThreadPreviewCount = useClientSettings((s) => s.sidebarThreadPreviewCount);
const updateSettings = useUpdateClientSettings();
@@ -3605,7 +3561,7 @@ export default function Sidebar() {
if (desktopUpdateButtonAction === "install") {
const confirmed = window.confirm(
getDesktopUpdateInstallConfirmationMessage(desktopUpdateState),
getDesktopUpdateInstallConfirmationMessage(desktopUpdateState, navigator.platform),
);
if (!confirmed) return;
void bridge
@@ -3671,7 +3627,6 @@ export default function Sidebar() {
handleDesktopUpdateButtonClick={handleDesktopUpdateButtonClick}
projectSortOrder={sidebarProjectSortOrder}
threadSortOrder={sidebarThreadSortOrder}
projectGroupingMode={sidebarProjectGroupingMode}
threadPreviewCount={sidebarThreadPreviewCount}
updateSettings={updateSettings}
openAddProject={openAddProjectCommandPalette}
@@ -0,0 +1,22 @@
import { describe, expect, it } from "vite-plus/test";
import { renderToStaticMarkup } from "react-dom/server";
import { StageBackdropArt, StageBackdropButtonArt } from "./SidebarStageBackdrop";
describe("SidebarStageBackdrop", () => {
it.each(["nightly", "dev"] as const)(
"uses unique SVG definition ids when %s artwork is rendered more than once",
(variant) => {
const markup = renderToStaticMarkup(
<>
<StageBackdropArt variant={variant} />
<StageBackdropButtonArt variant={variant} />
</>,
);
const ids = Array.from(markup.matchAll(/\sid="([^"]+)"/g), (match) => match[1]);
expect(ids.length).toBeGreaterThan(0);
expect(new Set(ids).size).toBe(ids.length);
},
);
});
@@ -1,4 +1,5 @@
import { useAtomValue } from "@effect/atom-react";
import { useId } from "react";
import { APP_STAGE_LABEL } from "../branding";
import { resolveServerBackedAppStageLabel } from "../branding.logic";
@@ -47,6 +48,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;
@@ -78,18 +83,26 @@ 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`;
const cloudId = `${idPrefix}-stage-night-cloud`;
const softId = `${idPrefix}-stage-night-soft`;
const starsId = `${idPrefix}-stage-night-stars`;
const glowsId = `${idPrefix}-stage-night-glows`;
return (
<svg
className="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>
<linearGradient
id="stage-night-sky"
id={skyId}
x1="24"
y1="0"
x2="264"
@@ -102,7 +115,7 @@ function NightlySkyArt() {
<stop offset="1" stopColor="#32155B" />
</linearGradient>
<radialGradient
id="stage-night-glow"
id={glowId}
cx="0"
cy="0"
r="1"
@@ -113,29 +126,15 @@ function NightlySkyArt() {
<stop offset="0.5" stopColor="#283075" stopOpacity="0.16" />
<stop offset="1" stopColor="#111635" stopOpacity="0" />
</radialGradient>
<linearGradient
id="stage-night-cloud"
x1="0"
y1="60"
x2="288"
y2="96"
gradientUnits="userSpaceOnUse"
>
<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" />
</linearGradient>
<filter
id="stage-night-soft"
x="-24"
y="-24"
width="336"
height="144"
filterUnits="userSpaceOnUse"
>
<filter id={softId} x="-24" y="-24" width="336" height="144" filterUnits="userSpaceOnUse">
<feGaussianBlur stdDeviation="4" />
</filter>
<pattern id="stage-night-stars" width="288" height="96" patternUnits="userSpaceOnUse">
<pattern id={starsId} width="288" height="96" patternUnits="userSpaceOnUse">
<g fill="#E4EAFF">
{NIGHTLY_STARS.map((star) => (
<circle
@@ -156,25 +155,25 @@ function NightlySkyArt() {
))}
</g>
</pattern>
<pattern id="stage-night-glows" width="640" height="96" patternUnits="userSpaceOnUse">
<rect width="640" height="96" fill="url(#stage-night-glow)" />
<pattern id={glowsId} width="640" height="96" patternUnits="userSpaceOnUse">
<rect width="640" height="96" fill={`url(#${glowId})`} />
</pattern>
</defs>
<rect width="100%" height="96" fill="url(#stage-night-sky)" />
<rect width="100%" height="96" fill="url(#stage-night-glows)" />
<rect width="100%" height="96" fill="url(#stage-night-stars)" />
<rect width="100%" height="96" fill={`url(#${skyId})`} />
<rect width="100%" height="96" fill={`url(#${glowsId})`} />
<rect width="100%" height="96" fill={`url(#${starsId})`} />
<g filter="url(#stage-night-soft)">
<g filter={`url(#${softId})`}>
<path
d="M-12 88C-12 74 0 63 14 63C18 50 30 41 44 41C58 41 70 49 74 62C79 57 86 54 94 54C110 54 123 66 124 82C132 83 138 88 141 96H-12V88Z"
fill="url(#stage-night-cloud)"
fill={`url(#${cloudId})`}
/>
</g>
<g filter="url(#stage-night-soft)">
<g filter={`url(#${softId})`}>
<path
d="M150 96C151 84 161 75 173 75C176 64 186 57 198 57C210 57 220 64 223 75C231 75 238 80 241 87C250 87 257 91 260 96H150Z"
fill="url(#stage-night-cloud)"
fill={`url(#${cloudId})`}
fillOpacity="0.8"
/>
</g>
@@ -182,18 +181,29 @@ 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`;
const celesteGlowId = `${idPrefix}-stage-bp-glow-celeste`;
const violetGlowId = `${idPrefix}-stage-bp-glow-violet`;
const minorGridId = `${idPrefix}-stage-bp-grid-minor`;
const majorGridId = `${idPrefix}-stage-bp-grid-major`;
const rulerId = `${idPrefix}-stage-bp-ruler`;
const glowsId = `${idPrefix}-stage-bp-glows`;
const annotationsId = `${idPrefix}-stage-bp-annotations`;
return (
<svg
className="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>
<linearGradient
id="stage-bp-paper"
id={paperId}
x1="60"
y1="0"
x2="220"
@@ -206,7 +216,7 @@ function DevBlueprintArt() {
<stop offset="1" style={{ stopColor: "var(--stage-bp-top)" }} />
</linearGradient>
<radialGradient
id="stage-bp-glow"
id={glowId}
cx="0"
cy="0"
r="1"
@@ -218,7 +228,7 @@ function DevBlueprintArt() {
<stop offset="1" stopColor="#276AF1" stopOpacity="0" />
</radialGradient>
<radialGradient
id="stage-bp-glow-celeste"
id={celesteGlowId}
cx="0"
cy="0"
r="1"
@@ -230,7 +240,7 @@ function DevBlueprintArt() {
<stop offset="1" stopColor="#277EF1" stopOpacity="0" />
</radialGradient>
<radialGradient
id="stage-bp-glow-violet"
id={violetGlowId}
cx="0"
cy="0"
r="1"
@@ -241,13 +251,13 @@ function DevBlueprintArt() {
<stop offset="0.52" stopColor="#7C8BFF" stopOpacity="0.14" />
<stop offset="1" stopColor="#3155DF" stopOpacity="0" />
</radialGradient>
<pattern id="stage-bp-grid-minor" width="8" height="8" patternUnits="userSpaceOnUse">
<pattern id={minorGridId} width="8" height="8" patternUnits="userSpaceOnUse">
<path d="M8 0H0V8" stroke="#EAF6FF" strokeOpacity="0.14" strokeWidth="0.5" />
</pattern>
<pattern id="stage-bp-grid-major" width="32" height="32" patternUnits="userSpaceOnUse">
<pattern id={majorGridId} width="32" height="32" patternUnits="userSpaceOnUse">
<path d="M32 0H0V32" stroke="#EAF6FF" strokeOpacity="0.26" strokeWidth="0.6" />
</pattern>
<pattern id="stage-bp-ruler" width="32" height="6" patternUnits="userSpaceOnUse">
<pattern id={rulerId} width="32" height="6" patternUnits="userSpaceOnUse">
<path
d="M4 0V2.5M12 0V2.5M20 0V4M28 0V2.5"
stroke="#DDF7FF"
@@ -255,12 +265,12 @@ function DevBlueprintArt() {
strokeWidth="0.5"
/>
</pattern>
<pattern id="stage-bp-glows" width="768" height="96" patternUnits="userSpaceOnUse">
<rect width="768" height="96" fill="url(#stage-bp-glow)" />
<rect width="768" height="96" fill="url(#stage-bp-glow-celeste)" />
<rect width="768" height="96" fill="url(#stage-bp-glow-violet)" />
<pattern id={glowsId} width="768" height="96" patternUnits="userSpaceOnUse">
<rect width="768" height="96" fill={`url(#${glowId})`} />
<rect width="768" height="96" fill={`url(#${celesteGlowId})`} />
<rect width="768" height="96" fill={`url(#${violetGlowId})`} />
</pattern>
<pattern id="stage-bp-annotations" width="768" height="96" patternUnits="userSpaceOnUse">
<pattern id={annotationsId} width="768" height="96" patternUnits="userSpaceOnUse">
<g stroke="#DDF7FF" strokeLinecap="round" strokeOpacity="0.6" strokeWidth="0.7">
<path d="M180 64H264" strokeDasharray="5 4" />
<path d="M180 61V67M264 61V67" />
@@ -309,12 +319,12 @@ function DevBlueprintArt() {
</pattern>
</defs>
<rect width="100%" height="96" fill="url(#stage-bp-paper)" />
<rect width="100%" height="96" fill="url(#stage-bp-glows)" />
<rect width="100%" height="96" fill="url(#stage-bp-grid-minor)" />
<rect width="100%" height="96" fill="url(#stage-bp-grid-major)" />
<rect width="100%" height="6" fill="url(#stage-bp-ruler)" />
<rect width="100%" height="96" fill="url(#stage-bp-annotations)" />
<rect width="100%" height="96" fill={`url(#${paperId})`} />
<rect width="100%" height="96" fill={`url(#${glowsId})`} />
<rect width="100%" height="96" fill={`url(#${minorGridId})`} />
<rect width="100%" height="96" fill={`url(#${majorGridId})`} />
<rect width="100%" height="6" fill={`url(#${rulerId})`} />
<rect width="100%" height="96" fill={`url(#${annotationsId})`} />
</svg>
);
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,73 @@
import type { VcsStatusResult } from "@t3tools/contracts";
import { describe, expect, it } from "vite-plus/test";
import { prStatusIndicator, resolveThreadPr } from "./ThreadStatusIndicators";
function status(overrides: Partial<VcsStatusResult> = {}): VcsStatusResult {
return {
isRepo: true,
hasPrimaryRemote: true,
isDefaultRef: false,
refName: "feature/current",
hasWorkingTreeChanges: false,
workingTree: { files: [], insertions: 0, deletions: 0 },
hasUpstream: true,
aheadCount: 0,
behindCount: 0,
pr: {
number: 42,
title: "PR branch",
url: "https://github.com/pingdotgg/t3code/pull/42",
baseRef: "main",
headRef: "feature/current",
state: "open",
},
...overrides,
};
}
describe("resolveThreadPr", () => {
it("keeps local-checkout PR indicators scoped to the stored thread branch", () => {
expect(
resolveThreadPr({
threadBranch: "feature/other",
gitStatus: status(),
hasDedicatedWorktree: false,
}),
).toBeNull();
});
it("shows PR indicators for dedicated worktree threads even when branch metadata is stale", () => {
const gitStatus = status();
expect(
resolveThreadPr({
threadBranch: "feature/old-name",
gitStatus,
hasDedicatedWorktree: true,
}),
).toBe(gitStatus.pr);
});
it("shows PR indicators for dedicated worktree threads even when branch metadata is missing", () => {
const gitStatus = status();
expect(
resolveThreadPr({
threadBranch: null,
gitStatus,
hasDedicatedWorktree: true,
}),
).toBe(gitStatus.pr);
});
});
describe("prStatusIndicator", () => {
it("formats PR tooltips with number, uppercase status, and title", () => {
expect(prStatusIndicator(status().pr, undefined)).toMatchObject({
tooltip: "PR #42 - Open: PR branch",
tooltipLead: "PR #42 - Open",
tooltipTitle: "PR branch",
});
});
});
@@ -22,6 +22,8 @@ export interface PrStatusIndicator {
label: string;
colorClass: string;
tooltip: string;
tooltipLead: string;
tooltipTitle: string;
url: string;
}
@@ -37,14 +39,26 @@ export function prStatusIndicator(
pr: ThreadPr,
provider: VcsStatusResult["sourceControlProvider"] | null | undefined,
): PrStatusIndicator | null {
function formatPrState(state: NonNullable<ThreadPr>["state"]): string {
return state.charAt(0).toUpperCase() + state.slice(1);
}
function formatPrStatusLead(pr: NonNullable<ThreadPr>, changeRequestShortName: string): string {
return `${changeRequestShortName} #${pr.number} - ${formatPrState(pr.state)}`;
}
if (!pr) return null;
const presentation = resolveChangeRequestPresentation(provider);
const tooltipLead = formatPrStatusLead(pr, presentation.shortName);
const tooltip = `${tooltipLead}: ${pr.title}`;
if (pr.state === "open") {
return {
label: `${presentation.shortName} open`,
colorClass: "text-emerald-600 dark:text-emerald-300/90",
tooltip: `#${pr.number} ${presentation.shortName} open: ${pr.title}`,
tooltip,
tooltipLead,
tooltipTitle: pr.title,
url: pr.url,
};
}
@@ -52,7 +66,9 @@ export function prStatusIndicator(
return {
label: `${presentation.shortName} closed`,
colorClass: "text-zinc-500 dark:text-zinc-400/80",
tooltip: `#${pr.number} ${presentation.shortName} closed: ${pr.title}`,
tooltip,
tooltipLead,
tooltipTitle: pr.title,
url: pr.url,
};
}
@@ -60,7 +76,9 @@ export function prStatusIndicator(
return {
label: `${presentation.shortName} merged`,
colorClass: "text-violet-600 dark:text-violet-300/90",
tooltip: `#${pr.number} ${presentation.shortName} merged: ${pr.title}`,
tooltip,
tooltipLead,
tooltipTitle: pr.title,
url: pr.url,
};
}
@@ -71,11 +89,31 @@ export function ChangeRequestStatusIcon({ className }: { className?: string }) {
return <GitPullRequestIcon className={className} />;
}
export function resolveThreadPr(
threadBranch: string | null,
gitStatus: VcsStatusResult | null,
): ThreadPr | null {
if (threadBranch === null || gitStatus === null || gitStatus.refName !== threadBranch) {
export function PrStatusTooltipContent({ status }: { status: PrStatusIndicator }) {
return (
<span className="flex max-w-[min(34rem,calc(100vw-2rem))] items-stretch overflow-hidden whitespace-nowrap">
<span className="shrink-0 pr-2 font-medium">{status.tooltipLead}</span>
<span className="min-h-4 shrink-0 border-border/70 border-l" aria-hidden="true" />
<span className="min-w-0 truncate pl-2">{status.tooltipTitle}</span>
</span>
);
}
export function resolveThreadPr(input: {
threadBranch: string | null;
gitStatus: VcsStatusResult | null;
hasDedicatedWorktree: boolean;
}): ThreadPr | null {
const { threadBranch, gitStatus, hasDedicatedWorktree } = input;
if (gitStatus === null) {
return null;
}
if (hasDedicatedWorktree) {
return gitStatus.pr ?? null;
}
if (threadBranch === null || gitStatus.refName !== threadBranch) {
return null;
}
@@ -199,14 +237,18 @@ export function ThreadRowLeadingStatus({ thread }: { thread: SidebarThreadSummar
const threadProjectCwd = threadProject?.workspaceRoot ?? null;
const gitCwd = thread.worktreePath ?? threadProjectCwd;
const gitStatus = useEnvironmentQuery(
thread.branch != null && gitCwd !== null
(thread.branch != null || thread.worktreePath !== null) && gitCwd !== null
? vcsEnvironment.status({
environmentId: thread.environmentId,
input: { cwd: gitCwd },
})
: null,
);
const pr = resolveThreadPr(thread.branch, gitStatus.data);
const pr = resolveThreadPr({
threadBranch: thread.branch,
gitStatus: gitStatus.data,
hasDedicatedWorktree: thread.worktreePath !== null,
});
const prStatus = prStatusIndicator(pr, gitStatus.data?.sourceControlProvider);
const threadStatus = resolveThreadStatusPill({
thread: {
@@ -233,7 +275,9 @@ export function ThreadRowLeadingStatus({ thread }: { thread: SidebarThreadSummar
>
<ChangeRequestStatusIcon className="size-3" />
</TooltipTrigger>
<TooltipPopup side="top">{prStatus.tooltip}</TooltipPopup>
<TooltipPopup side="top">
<PrStatusTooltipContent status={prStatus} />
</TooltipPopup>
</Tooltip>
) : null}
{threadStatus ? <ThreadStatusLabel status={threadStatus} /> : null}
@@ -41,8 +41,8 @@ export const ChangedFilesCard = memo(function ChangedFilesCard(props: {
const summaryStat = useMemo(() => summarizeTurnDiffStats(files), [files]);
return (
<div className="mt-4 rounded-2xl border border-input bg-background p-2 pt-4 shadow-xs/5 not-dark:bg-clip-padding dark:bg-input/32">
<div className="sticky top-0 z-10 mb-3 flex items-center justify-between gap-2 bg-background px-2 before:absolute before:inset-x-0 before:-top-4 before:h-4 before:bg-background before:content-[''] dark:bg-[color-mix(in_srgb,var(--foreground)_2.5%,var(--background))] dark:before:bg-[color-mix(in_srgb,var(--foreground)_2.5%,var(--background))]">
<div className="mt-4 rounded-2xl border border-border/70 bg-secondary p-2 pt-4 dark:border-transparent dark:bg-input/32">
<div className="sticky top-0 z-10 mb-3 flex items-center justify-between gap-2 bg-secondary px-2 before:absolute before:inset-x-0 before:-top-4 before:h-4 before:bg-secondary before:content-[''] dark:bg-[color-mix(in_srgb,var(--foreground)_2.5%,var(--background))] dark:before:bg-[color-mix(in_srgb,var(--foreground)_2.5%,var(--background))]">
<p className="flex items-center gap-1 whitespace-nowrap font-medium text-foreground text-xs leading-4">
<span>
{files.length} changed file{files.length === 1 ? "" : "s"}
+78 -27
View File
@@ -18,14 +18,12 @@ import {
PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
PROVIDER_SEND_TURN_MAX_IMAGE_BYTES,
} from "@t3tools/contracts";
import {
connectionStatusText,
type EnvironmentConnectionPresentation,
} from "@t3tools/client-runtime/connection";
import type { EnvironmentConnectionPresentation } from "@t3tools/client-runtime/connection";
import { serializeComposerFileLink } from "@t3tools/shared/composerTrigger";
import { createModelSelection, normalizeModelSlug } from "@t3tools/shared/model";
import {
memo,
type ReactNode,
useCallback,
useEffect,
useImperativeHandle,
@@ -34,6 +32,7 @@ import {
useRef,
useState,
} from "react";
import { createPortal } from "react-dom";
import {
clampCollapsedComposerCursor,
type ComposerTrigger,
@@ -93,13 +92,70 @@ import { buildExpandedImagePreview, type ExpandedImagePreview } from "./Expanded
import { basenameOfPath } from "../../pierre-icons";
import { cn, randomUUID } from "~/lib/utils";
import { Separator } from "../ui/separator";
function ComposerCommandMenuLayer(props: { anchor: HTMLElement | null; children: ReactNode }) {
const [position, setPosition] = useState<{
bottom: number;
left: number;
maxHeight: number;
width: number;
} | null>(null);
useLayoutEffect(() => {
const anchor = props.anchor;
if (!anchor) {
setPosition(null);
return;
}
const updatePosition = () => {
const rect = anchor.getBoundingClientRect();
setPosition({
bottom: window.innerHeight - rect.top + 8,
left: rect.left,
maxHeight: Math.max(96, rect.top - 24),
width: rect.width,
});
};
updatePosition();
window.addEventListener("resize", updatePosition);
window.addEventListener("scroll", updatePosition, true);
const observer =
typeof ResizeObserver === "undefined" ? null : new ResizeObserver(updatePosition);
observer?.observe(anchor);
return () => {
observer?.disconnect();
window.removeEventListener("resize", updatePosition);
window.removeEventListener("scroll", updatePosition, true);
};
}, [props.anchor]);
if (!position) return null;
return createPortal(
<div
className="pointer-events-auto fixed z-[70]"
style={{
bottom: position.bottom,
left: position.left,
maxHeight: position.maxHeight,
width: position.width,
}}
>
{props.children}
</div>,
document.body,
);
}
import { Button } from "../ui/button";
import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "../ui/select";
import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
import { toastManager } from "../ui/toast";
import {
BotIcon,
CheckIcon,
CircleAlertIcon,
ListTodoIcon,
PencilRulerIcon,
@@ -107,6 +163,7 @@ import {
LockIcon,
LockOpenIcon,
PenLineIcon,
SparklesIcon,
XIcon,
} from "lucide-react";
import { proposedPlanTitle } from "../../proposedPlan";
@@ -150,6 +207,11 @@ const runtimeModeConfig: Record<
description: "Auto-approve edits, ask before other actions.",
icon: PenLineIcon,
},
auto: {
label: "Auto",
description: "An AI reviewer approves routine actions; risky ones still ask.",
icon: SparklesIcon,
},
"full-access": {
label: "Full access",
description: "Allow commands and edits without prompts.",
@@ -280,7 +342,6 @@ const ComposerFooterModeControls = memo(function ComposerFooterModeControls(prop
{runtimeModeOptions.map((mode) => {
const option = runtimeModeConfig[mode];
const OptionIcon = option.icon;
const isSelected = props.runtimeMode === mode;
return (
<SelectItem key={mode} value={mode} hideIndicator className="min-w-64 py-2">
<div className="flex min-w-0 items-center gap-3">
@@ -293,12 +354,6 @@ const ComposerFooterModeControls = memo(function ComposerFooterModeControls(prop
{option.description}
</span>
</div>
<CheckIcon
className={cn(
"size-4 text-blue-400",
isSelected ? "opacity-100" : "opacity-0",
)}
/>
</div>
</SelectItem>
);
@@ -905,6 +960,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
const [isComposerPrimaryActionsCompact, setIsComposerPrimaryActionsCompact] = useState(false);
const [isComposerModelPickerOpen, setIsComposerModelPickerOpen] = useState(false);
const [isComposerFocused, setIsComposerFocused] = useState(false);
const [composerMenuAnchor, setComposerMenuAnchor] = useState<HTMLDivElement | null>(null);
const isMobileViewport = useMediaQuery("max-sm");
const isComposerCollapsedMobile =
isMobileViewport && !forceExpandedOnMobile && !isComposerFocused;
@@ -2162,10 +2218,8 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
ref={composerSurfaceRef}
data-chat-composer-mobile-collapsed={isComposerCollapsedMobile ? "true" : "false"}
className={cn(
"chat-composer-glass rounded-[20px] border transition-[background-color] duration-200 has-focus-visible:border-foreground/40",
isDragOverComposer
? "border-primary/70 bg-accent/45"
: "border-black/12 dark:border-white/12",
"rounded-[20px] transition-[background-color] duration-200",
isDragOverComposer ? "bg-accent/45 ring-1 ring-primary/70" : null,
projectSelectionRequired ? "opacity-75" : null,
composerProviderState.composerSurfaceClassName,
)}
@@ -2341,6 +2395,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
) : null}
<div
ref={setComposerMenuAnchor}
className={cn(
"relative px-3 pb-2 sm:px-4",
hasComposerHeader ? "pt-2.5 sm:pt-3" : "pt-3.5 sm:pt-4",
@@ -2348,7 +2403,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
)}
>
{composerMenuOpen && !isComposerApprovalState && (
<div className="absolute inset-x-0 bottom-full z-20 mb-2">
<ComposerCommandMenuLayer anchor={composerMenuAnchor}>
<ComposerCommandMenu
items={composerMenuItems}
resolvedTheme={resolvedTheme}
@@ -2363,7 +2418,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
onHighlightedItemChange={onComposerMenuItemHighlighted}
onSelect={onSelectComposerItem}
/>
</div>
</ComposerCommandMenuLayer>
)}
{!isComposerCollapsedMobile &&
@@ -2519,15 +2574,11 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
? "Add feedback to refine the plan, or leave this blank to implement it"
: projectSelectionRequired
? "Choose a project above to start a thread"
: environmentUnavailable
? `${environmentUnavailable.label}: ${connectionStatusText(
environmentUnavailable.connection,
)}`
: noProviderAvailable
? "Enable a provider in Settings to send a message"
: phase === "disconnected"
? "Ask for follow-up changes or attach images"
: "Ask anything, @tag files/folders, $use skills, or / for commands"
: noProviderAvailable
? "Enable a provider in Settings to send a message"
: phase === "disconnected"
? "Ask for follow-up changes or attach images"
: "Ask anything, @tag files/folders, $use skills, or / for commands"
}
disabled={isConnecting || isComposerApprovalState || projectSelectionRequired}
/>
@@ -16,6 +16,7 @@ import ProjectScriptsControl, {
} from "../ProjectScriptsControl";
import { OpenInPicker } from "./OpenInPicker";
import { usePrimaryEnvironmentId } from "../../state/environments";
import { useT3ProjectFileScripts } from "~/hooks/useT3ProjectFileScripts";
import { ProjectFavicon } from "../ProjectFavicon";
import { cn } from "~/lib/utils";
@@ -74,6 +75,10 @@ export const ChatHeader = memo(function ChatHeader({
onDeleteProjectScript,
}: ChatHeaderProps) {
const primaryEnvironmentId = usePrimaryEnvironmentId();
const fileScripts = useT3ProjectFileScripts(
activeThreadEnvironmentId,
activeProjectScripts ? activeProjectCwd : null,
);
const showOpenInPicker = shouldShowOpenInPicker({
activeProjectName,
activeThreadEnvironmentId,
@@ -126,6 +131,7 @@ export const ChatHeader = memo(function ChatHeader({
{activeProjectScripts && (
<ProjectScriptsControl
scripts={activeProjectScripts}
fileScripts={fileScripts}
keybindings={keybindings}
preferredScriptId={preferredScriptId}
onRunScript={onRunProjectScript}
@@ -71,6 +71,7 @@ export const CompactComposerControlsMenu = memo(function CompactComposerControls
>
<MenuRadioItem value="approval-required">Supervised</MenuRadioItem>
<MenuRadioItem value="auto-accept-edits">Auto-accept edits</MenuRadioItem>
<MenuRadioItem value="auto">Auto</MenuRadioItem>
<MenuRadioItem value="full-access">Full access</MenuRadioItem>
</MenuRadioGroup>
{props.activePlan ? (
@@ -33,5 +33,27 @@ describe("ComposerBannerStack", () => {
const markup = renderToStaticMarkup(<ComposerBannerStack items={[banner("front")]} />);
expect(markup).not.toContain("data-composer-banner-stack-expanded-items");
expect(markup).toContain("alert-glass");
expect(markup).toContain('data-variant="warning"');
expect(markup).toContain("transform:none");
expect(markup).not.toContain("will-change:transform");
});
it("applies item-specific surface and action layout classes", () => {
const markup = renderToStaticMarkup(
<ComposerBannerStack
items={[
{
...banner("branch"),
className: "branch-surface",
actionClassName: "branch-actions",
actions: <button type="button">Repair</button>,
},
]}
/>,
);
expect(markup).toContain("branch-surface");
expect(markup).toContain("branch-actions");
});
});
@@ -16,11 +16,10 @@ const stackedExitStyle = {
} satisfies CSSProperties;
const restingStyle = {
opacity: 1,
transform: "translate3d(0, 0, 0)",
transform: "none",
} satisfies CSSProperties;
const exitTransitionStyle = {
transition: `transform ${DISMISS_TRANSITION_MS}ms ease-in, opacity ${DISMISS_TRANSITION_MS}ms ease-in`,
willChange: "transform, opacity",
} satisfies CSSProperties;
export interface ComposerBannerStackItem {
@@ -30,6 +29,8 @@ export interface ComposerBannerStackItem {
readonly title: ReactNode;
readonly description?: ReactNode;
readonly actions?: ReactNode;
readonly className?: string;
readonly actionClassName?: string;
readonly dismissLabel?: string;
readonly onDismiss?: () => void;
}
@@ -171,17 +172,22 @@ function ComposerBannerStackAlert({
const dismissOnly = item.onDismiss && !item.actions;
return (
<Alert variant={item.variant}>
<Alert
variant={item.variant}
className={cn("alert-glass", item.className)}
data-variant={item.variant}
>
{item.icon}
<AlertTitle>{item.title}</AlertTitle>
{item.description ? <AlertDescription>{item.description}</AlertDescription> : null}
{item.actions || item.onDismiss ? (
<AlertAction
className={
className={cn(
item.actionClassName,
dismissOnly
? "max-sm:col-start-3 max-sm:row-start-1 max-sm:mt-0 max-sm:self-start"
: undefined
}
: undefined,
)}
>
{item.actions}
{item.onDismiss ? (
@@ -139,10 +139,7 @@ export const ComposerCommandMenu = memo(function ComposerCommandMenu(props: {
);
}}
>
<div
ref={listRef}
className="relative w-full overflow-hidden rounded-[20px] border border-border/80 bg-popover/96 shadow-lg/8 backdrop-blur-xs"
>
<div ref={listRef} className="dropdown-glass relative w-full overflow-hidden rounded-[20px]">
{props.items.length > 0 ? (
<CommandList className="max-h-72">
{groups.map((group, groupIndex) => (
@@ -1,6 +1,7 @@
import { memo, type PointerEventHandler } from "react";
import { ChevronDownIcon, ChevronLeftIcon } from "lucide-react";
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";
@@ -71,6 +72,7 @@ export const ComposerPrimaryActions = memo(function ComposerPrimaryActions({
const pointerFocusProps = preserveComposerFocusOnPointerDown
? { onPointerDown: preventPointerFocus }
: undefined;
const stageBackdropVariant = useSidebarStageBackdropVariant();
if (pendingAction) {
return (
@@ -196,7 +198,12 @@ export const ComposerPrimaryActions = memo(function ComposerPrimaryActions({
return (
<button
type="submit"
className="flex h-9 w-9 enabled:cursor-pointer items-center justify-center rounded-full bg-primary/90 text-primary-foreground shadow-xs enabled:shadow-primary/24 enabled:inset-shadow-[0_1px_--theme(--color-white/16%)] transition-all duration-150 hover:bg-primary 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"
className={cn(
"relative isolate flex h-9 w-9 items-center justify-center overflow-hidden rounded-full text-primary-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",
stageBackdropVariant
? "bg-transparent enabled:shadow-black/24 enabled:hover:brightness-110"
: "bg-primary/90 enabled:shadow-primary/24 hover:bg-primary",
)}
{...pointerFocusProps}
disabled={isSendBusy || isConnecting || isEnvironmentUnavailable || !hasSendableContent}
aria-label={
@@ -211,6 +218,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" />
) : (
@@ -25,7 +25,9 @@ export function ContextWindowMeter(props: {
const totalProcessedTokens = usage.totalProcessedTokens ?? null;
const showTotalProcessed = totalProcessedTokens !== null && totalProcessedTokens > 0;
const isOverloaded = normalizedPercentage > 90;
const usageColor = isOverloaded ? "var(--color-red-500)" : "var(--color-blue-500)";
const usageColor = isOverloaded
? "var(--color-red-500)"
: "color-mix(in oklab, var(--color-muted-foreground) 72%, transparent)";
return (
<Popover>
@@ -37,7 +39,7 @@ export function ContextWindowMeter(props: {
<button
type="button"
className={cn(
"inline-flex size-6 cursor-pointer items-center justify-center rounded-full border border-transparent text-muted-foreground outline-none transition-colors",
"inline-flex size-7 cursor-pointer items-center justify-center rounded-full border border-transparent text-muted-foreground outline-none transition-colors",
"hover:bg-accent data-[pressed]:bg-accent",
"focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-1 focus-visible:ring-offset-background",
)}
@@ -47,7 +49,7 @@ export function ContextWindowMeter(props: {
: `Context window ${formatContextWindowTokens(usage.usedTokens)} tokens used`
}
>
<span className="relative flex size-4 items-center justify-center">
<span className="relative flex size-5 items-center justify-center">
<svg
viewBox="0 0 24 24"
className="-rotate-90 absolute inset-0 size-full transform-gpu"
@@ -58,7 +60,7 @@ export function ContextWindowMeter(props: {
cy="12"
r={radius}
fill="none"
stroke="color-mix(in oklab, var(--color-muted-foreground) 35%, transparent)"
stroke="color-mix(in oklab, var(--color-muted-foreground) 24%, transparent)"
strokeWidth="3"
/>
<circle
@@ -78,7 +80,12 @@ export function ContextWindowMeter(props: {
</button>
}
/>
<PopoverPopup tooltipStyle side="top" align="end" className="w-64 max-w-none p-0">
<PopoverPopup
tooltipStyle
side="top"
align="end"
className="dropdown-glass w-64 max-w-none border-0! bg-secondary! p-0 shadow-none! before:hidden"
>
<div className="flex flex-col gap-2 p-3">
<div className="flex items-center justify-between gap-3">
<div className="font-medium text-muted-foreground text-xs">Context Window</div>
@@ -5,8 +5,15 @@ import { useCallback, useMemo } from "react";
import { openCommandPalette } from "~/commandPaletteBus";
import { useNewThreadHandler } from "~/hooks/useHandleNewThread";
import { useClientSettings } from "~/hooks/useSettings";
import { selectProjectGroupingSettings } from "~/logicalProject";
import {
buildSidebarProjectPickerEntries,
buildSidebarProjectSnapshots,
} from "~/sidebarProjectGrouping";
import { useProjects, useThreadShells } from "~/state/entities";
import { sortScopedProjectsForSidebar } from "../Sidebar.logic";
import { useEnvironments, usePrimaryEnvironmentId } from "~/state/environments";
import { sortLogicalProjectsForSidebar } from "../Sidebar.logic";
import {
Menu,
MenuItem,
@@ -28,29 +35,66 @@ export function DraftHeroHeadline({
}: DraftHeroHeadlineProps) {
const projects = useProjects();
const threads = useThreadShells();
const { environments } = useEnvironments();
const primaryEnvironmentId = usePrimaryEnvironmentId();
const projectGroupingSettings = useClientSettings(selectProjectGroupingSettings);
const projectSortOrder = useClientSettings((settings) => settings.sidebarProjectSortOrder);
const handleNewThread = useNewThreadHandler();
const openAddProject = useCallback(() => openCommandPalette({ open: "add-project" }), []);
const orderedProjects = useMemo(
() => sortScopedProjectsForSidebar(projects, threads, "updated_at"),
[projects, threads],
);
const projectByKey = useMemo(
const environmentLabelById = useMemo(
() =>
new Map(
orderedProjects.map(
(project) =>
[
scopedProjectKey(scopeProjectRef(project.environmentId, project.id)),
project,
] as const,
),
environments.map((environment) => [environment.environmentId, environment.label] as const),
),
[orderedProjects],
[environments],
);
const activeProjectKey = activeProjectRef === null ? "" : scopedProjectKey(activeProjectRef);
const projectGroups = useMemo(
() =>
sortLogicalProjectsForSidebar(
buildSidebarProjectSnapshots({
projects,
settings: projectGroupingSettings,
primaryEnvironmentId,
resolveEnvironmentLabel: (environmentId) =>
environmentLabelById.get(environmentId) ?? null,
}),
threads,
projectSortOrder,
),
[
environmentLabelById,
primaryEnvironmentId,
projectGroupingSettings,
projectSortOrder,
projects,
threads,
],
);
const projectPickerEntries = useMemo(
() =>
buildSidebarProjectPickerEntries({
groups: projectGroups,
preferredProjectRef: activeProjectRef,
}),
[activeProjectRef, projectGroups],
);
const projectEntryByKey = useMemo(
() => new Map(projectPickerEntries.map((entry) => [entry.group.projectKey, entry] as const)),
[projectPickerEntries],
);
const activeProjectGroup =
activeProjectRef === null
? null
: (projectGroups.find((group) =>
group.memberProjectRefs.some(
(projectRef) => scopedProjectKey(projectRef) === scopedProjectKey(activeProjectRef),
),
) ?? null);
const activeProjectKey = activeProjectGroup?.projectKey ?? "";
const activeProjectDisplayName = activeProjectGroup?.displayName ?? activeProjectTitle;
const hasResolvedProject = activeProjectTitle !== null;
const canChooseProject = orderedProjects.length > 0;
const canChooseProject = projectPickerEntries.length > 0;
const shouldShowProjectMenu = canChooseProject;
const projectSelector = shouldShowProjectMenu ? (
@@ -59,26 +103,26 @@ export function DraftHeroHeadline({
aria-label={hasResolvedProject ? "Change project" : "Choose a project"}
className="pointer-events-auto inline cursor-pointer border-current border-b border-dotted text-foreground underline-offset-8 transition-opacity hover:opacity-75 focus-visible:rounded-sm focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-ring"
>
{activeProjectTitle ?? "Choose a project"}
{activeProjectDisplayName ?? "Choose a project"}
</MenuTrigger>
<MenuPopup align="center" className="max-h-80 w-64 overflow-y-auto">
<MenuRadioGroup
value={activeProjectKey}
onValueChange={(value) => {
const project = projectByKey.get(value as string);
if (!project || value === activeProjectKey) {
const entry = projectEntryByKey.get(value as string);
if (!entry || value === activeProjectKey) {
return;
}
const project = entry.targetProject;
void handleNewThread(scopeProjectRef(project.environmentId, project.id), {
replace: true,
});
}}
>
{orderedProjects.map((project) => {
const key = scopedProjectKey(scopeProjectRef(project.environmentId, project.id));
{projectPickerEntries.map(({ group }) => {
return (
<MenuRadioItem key={key} value={key} closeOnClick>
<span className="min-w-0 truncate">{project.title}</span>
<MenuRadioItem key={group.projectKey} value={group.projectKey} closeOnClick>
<span className="min-w-0 truncate">{group.displayName}</span>
</MenuRadioItem>
);
})}
@@ -130,7 +130,9 @@ function matchMedia() {
};
}
beforeAll(() => {
let MessagesTimeline: typeof import("./MessagesTimeline").MessagesTimeline;
beforeAll(async () => {
const classList = {
add: () => {},
remove: () => {},
@@ -161,7 +163,9 @@ beforeAll(() => {
offsetHeight: 0,
},
});
});
({ MessagesTimeline } = await import("./MessagesTimeline"));
}, 30_000);
const ACTIVE_THREAD_ENVIRONMENT_ID = EnvironmentId.make("environment-local");
const MESSAGE_CREATED_AT = "2026-03-17T19:12:28.000Z";
@@ -219,8 +223,23 @@ function buildUserTimelineEntry(text: string) {
}
describe("MessagesTimeline", () => {
it("keeps assistant changed-files headers sticky below the thread header", async () => {
const { MessagesTimeline } = await import("./MessagesTimeline");
it("uses the larger leading inset only when the top fade is enabled", () => {
const timelineEntries = [buildUserTimelineEntry("Hello")];
const compactMarkup = renderToStaticMarkup(
<MessagesTimeline {...buildProps()} timelineEntries={timelineEntries} />,
);
const fadedMarkup = renderToStaticMarkup(
<MessagesTimeline {...buildProps()} timelineEntries={timelineEntries} topFadeEnabled />,
);
expect(compactMarkup).toContain('class="h-3 sm:h-4"');
expect(compactMarkup).not.toContain("chat-timeline-scroll-fade");
expect(fadedMarkup).toContain('class="h-10 sm:h-12"');
expect(fadedMarkup).toContain("chat-timeline-scroll-fade");
});
it("keeps assistant changed-files headers sticky below the thread header", () => {
const assistantMessageId = MessageId.make("message-assistant-with-files");
const turnId = TurnId.make("turn-with-files");
const markup = renderToStaticMarkup(
@@ -332,8 +351,7 @@ describe("MessagesTimeline", () => {
expect(resolveTimelineMinimapInteractiveWidth(40, true)).toBe("22rem");
});
it("anchors a sent attachment message using its measured height", async () => {
const { MessagesTimeline } = await import("./MessagesTimeline");
it("anchors a sent attachment message using its measured height", () => {
const onAnchorReady = vi.fn();
const onAnchorSizeChanged = vi.fn();
const firstEntry = buildUserTimelineEntry("First prompt.");
@@ -381,8 +399,7 @@ describe("MessagesTimeline", () => {
expect(onAnchorSizeChanged).toHaveBeenCalledWith(secondEntry.message.id, 240);
});
it("renders collapse controls for long user messages", async () => {
const { MessagesTimeline } = await import("./MessagesTimeline");
it("renders collapse controls for long user messages", () => {
const markup = renderToStaticMarkup(
<MessagesTimeline
{...buildProps()}
@@ -401,8 +418,7 @@ describe("MessagesTimeline", () => {
expect(markup).toContain('data-user-message-footer="true"');
});
it("does not render collapse controls for short user messages", async () => {
const { MessagesTimeline } = await import("./MessagesTimeline");
it("does not render collapse controls for short user messages", () => {
const markup = renderToStaticMarkup(
<MessagesTimeline
{...buildProps()}
@@ -414,8 +430,7 @@ describe("MessagesTimeline", () => {
expect(markup).toContain('data-user-message-collapsible="false"');
});
it("renders inline terminal labels with the composer chip UI", async () => {
const { MessagesTimeline } = await import("./MessagesTimeline");
it("renders inline terminal labels with the composer chip UI", () => {
const markup = renderToStaticMarkup(
<MessagesTimeline
{...buildProps()}
@@ -442,8 +457,7 @@ describe("MessagesTimeline", () => {
expect(markup).toContain("Show full message");
}, 20_000);
it("renders chips for standalone element-pick context messages", async () => {
const { MessagesTimeline } = await import("./MessagesTimeline");
it("renders chips for standalone element-pick context messages", () => {
const markup = renderToStaticMarkup(
<MessagesTimeline
{...buildProps()}
@@ -469,8 +483,7 @@ describe("MessagesTimeline", () => {
expect(markup).not.toContain("<element_context");
});
it("keeps the copy button for collapsed long user messages", async () => {
const { MessagesTimeline } = await import("./MessagesTimeline");
it("keeps the copy button for collapsed long user messages", () => {
const markup = renderToStaticMarkup(
<MessagesTimeline
{...buildProps()}
@@ -483,8 +496,7 @@ describe("MessagesTimeline", () => {
expect(markup).toContain('data-user-message-footer="true"');
});
it("renders context compaction entries in the normal work log", async () => {
const { MessagesTimeline } = await import("./MessagesTimeline");
it("renders context compaction entries in the normal work log", () => {
const markup = renderToStaticMarkup(
<MessagesTimeline
{...buildProps()}
@@ -508,8 +520,7 @@ describe("MessagesTimeline", () => {
expect(markup).toContain("Work Log");
});
it("formats changed file paths from the workspace root", async () => {
const { MessagesTimeline } = await import("./MessagesTimeline");
it("formats changed file paths from the workspace root", () => {
const markup = renderToStaticMarkup(
<MessagesTimeline
{...buildProps()}
@@ -535,8 +546,7 @@ describe("MessagesTimeline", () => {
expect(markup).not.toContain("C:/Users/mike/dev-stuff/t3code/apps/web/src/session-logic.ts");
});
it("renders review comment contexts as structured cards instead of raw tags", async () => {
const { MessagesTimeline } = await import("./MessagesTimeline");
it("renders review comment contexts as structured cards instead of raw tags", () => {
const markup = renderToStaticMarkup(
<MessagesTimeline
{...buildProps()}
@@ -576,8 +586,7 @@ describe("MessagesTimeline", () => {
expect(markup).not.toContain("&lt;/review_comment&gt;");
});
it("renders file review comments as source code instead of diffs", async () => {
const { MessagesTimeline } = await import("./MessagesTimeline");
it("renders file review comments as source code instead of diffs", () => {
const markup = renderToStaticMarkup(
<MessagesTimeline
{...buildProps()}
@@ -614,8 +623,7 @@ describe("MessagesTimeline", () => {
expect(markup).not.toContain('data-testid="file-diff"');
});
it("renders a failure marker for failed tool lifecycle entries", async () => {
const { MessagesTimeline } = await import("./MessagesTimeline");
it("renders a failure marker for failed tool lifecycle entries", () => {
const markup = renderToStaticMarkup(
<MessagesTimeline
{...buildProps()}
@@ -150,6 +150,7 @@ interface TimelineRowActivityState {
const TimelineRowCtx = createContext<TimelineRowSharedState>(null!);
const TimelineRowActivityCtx = createContext<TimelineRowActivityState>(null!);
const TIMELINE_LIST_HEADER = <div className="h-3 sm:h-4" />;
const TIMELINE_LIST_FADE_HEADER = <div className="h-10 sm:h-12" />;
const TIMELINE_LIST_FOOTER = <div className="h-3 sm:h-4" />;
const EMPTY_TIMELINE_SKILLS: ReadonlyArray<Pick<ServerProviderSkill, "name" | "displayName">> = [];
@@ -185,6 +186,7 @@ interface MessagesTimelineProps {
onIsAtEndChange: (isAtEnd: boolean) => void;
onManualNavigation: () => void;
hideEmptyPlaceholder?: boolean;
topFadeEnabled?: boolean;
}
// ---------------------------------------------------------------------------
@@ -219,6 +221,7 @@ export const MessagesTimeline = memo(function MessagesTimeline({
onIsAtEndChange,
onManualNavigation,
hideEmptyPlaceholder = false,
topFadeEnabled = false,
}: MessagesTimelineProps) {
const [expandedTurnIds, setExpandedTurnIds] = useState<ReadonlySet<TurnId>>(new Set());
const [expandedWorkGroupIds, setExpandedWorkGroupIds] = useState<ReadonlySet<string>>(new Set());
@@ -510,8 +513,11 @@ export const MessagesTimeline = memo(function MessagesTimeline({
size: false,
}}
onScroll={handleScroll}
className="scrollbar-gutter-both h-full min-h-0 overflow-x-hidden overscroll-y-contain px-3 [overflow-anchor:none] sm:px-5"
ListHeaderComponent={TIMELINE_LIST_HEADER}
className={cn(
"scrollbar-gutter-both h-full min-h-0 overflow-x-hidden overscroll-y-contain px-3 [overflow-anchor:none] sm:px-5",
topFadeEnabled && "chat-timeline-scroll-fade",
)}
ListHeaderComponent={topFadeEnabled ? TIMELINE_LIST_FADE_HEADER : TIMELINE_LIST_HEADER}
ListFooterComponent={TIMELINE_LIST_FOOTER}
/>
<TimelineMinimap
@@ -797,7 +803,7 @@ function TimelineMinimap({
transform: `translateY(${activeTooltipTranslate})`,
}}
>
<span className="block rounded-xl border border-border/70 bg-popover/95 p-3 text-left text-popover-foreground shadow-xl shadow-black/25 backdrop-blur">
<span className="dropdown-glass block rounded-xl p-3 text-left text-popover-foreground shadow-xl shadow-black/25">
<span className="block max-w-full overflow-hidden text-ellipsis whitespace-nowrap text-sm font-medium leading-5">
{activeItem.userText ?? "User message"}
</span>
@@ -886,7 +892,7 @@ function UserTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "message"
return (
<div className="group flex flex-col items-end gap-1">
<div className="relative max-w-[80%] rounded-2xl border border-border bg-secondary p-3">
<div className="relative max-w-[80%] rounded-2xl bg-secondary p-3">
{regularImages.length > 0 && (
<div className="mb-2 grid max-w-[420px] grid-cols-2 gap-2">
{regularImages.map((image: NonNullable<TimelineMessage["attachments"]>[number]) => (
@@ -1279,8 +1285,8 @@ function AssistantChangedFilesSectionInner({
const summaryStat = summarizeTurnDiffStats(checkpointFiles);
return (
<div className="mt-4 rounded-2xl border border-input bg-background p-2 pt-4 shadow-xs/5 not-dark:bg-clip-padding dark:bg-input/32">
<div className="sticky top-2 z-10 mb-3 flex items-center justify-between gap-2 bg-background px-2 before:absolute before:inset-x-0 before:-top-4 before:h-4 before:bg-background before:content-[''] dark:bg-[color-mix(in_srgb,var(--foreground)_2.5%,var(--background))] dark:before:bg-[color-mix(in_srgb,var(--foreground)_2.5%,var(--background))]">
<div className="mt-4 rounded-2xl border border-border/70 bg-secondary p-2 pt-4 dark:border-transparent dark:bg-input/32">
<div className="sticky top-2 z-10 mb-3 flex items-center justify-between gap-2 bg-secondary px-2 before:absolute before:inset-x-0 before:-top-4 before:h-4 before:bg-secondary before:content-[''] dark:bg-[color-mix(in_srgb,var(--foreground)_2.5%,var(--background))] dark:before:bg-[color-mix(in_srgb,var(--foreground)_2.5%,var(--background))]">
<p className="flex items-center gap-1 whitespace-nowrap font-medium text-foreground text-xs leading-4">
<span>
{checkpointFiles.length} changed file{checkpointFiles.length === 1 ? "" : "s"}
@@ -1,6 +1,6 @@
import { type ProviderDriverKind, type ProviderInstanceId } from "@t3tools/contracts";
import { memo } from "react";
import { CheckIcon, StarIcon } from "lucide-react";
import { StarIcon } from "lucide-react";
import {
getDisplayModelName,
getTriggerDisplayModelLabel,
@@ -51,7 +51,7 @@ export const ModelListRow = memo(function ModelListRow(props: {
contentClassName="flex w-full items-center gap-3"
className={cn(
"group relative w-full !min-w-0 max-w-full cursor-pointer rounded-md px-2 py-2.5 transition-[background-color,box-shadow,color]",
"data-highlighted:bg-muted/56 data-selected:bg-transparent data-selected:text-foreground data-selected:ring-0",
"data-highlighted:bg-muted/56 data-selected:bg-foreground/[0.08] data-selected:text-foreground data-selected:ring-0",
props.disabledReason &&
"data-disabled:pointer-events-auto data-disabled:cursor-not-allowed data-disabled:hover:bg-transparent",
)}
@@ -66,7 +66,6 @@ export const ModelListRow = memo(function ModelListRow(props: {
props.preferShortName ? { preferShortName: true } : undefined,
)}
</div>
{props.isSelected ? <CheckIcon className="size-3.5 shrink-0 text-blue-400" /> : null}
{props.showNewBadge ? (
<span
className="shrink-0 rounded border border-amber-500/35 bg-amber-500/15 px-0.5 py-px text-[10px] font-bold uppercase leading-none tracking-wide text-amber-800 dark:border-amber-400/30 dark:bg-amber-400/12 dark:text-amber-200"
@@ -521,7 +521,7 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: {
return (
<TooltipProvider delay={0}>
<div
className="relative flex h-screen max-h-96 w-screen max-w-100 flex-row overflow-hidden rounded-lg border bg-popover not-dark:bg-clip-padding text-popover-foreground shadow-lg/5 before:pointer-events-none before:absolute before:inset-0 before:rounded-[calc(var(--radius-lg)-1px)] before:shadow-[0_1px_--theme(--color-black/4%)] dark:before:shadow-[0_-1px_--theme(--color-white/6%)]"
className="dropdown-glass model-picker-surface relative flex h-screen max-h-96 w-screen max-w-100 flex-row overflow-hidden rounded-xl text-popover-foreground"
data-model-picker-content="true"
>
{/* Sidebar */}
@@ -568,23 +568,18 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: {
handleModelSelect(slug, instanceId);
}}
>
<div
className={cn(
"flex min-h-0 flex-1 flex-col overflow-hidden bg-muted/40",
showSidebar && "border-l",
)}
>
<div className="flex min-h-0 flex-1 flex-col overflow-hidden">
{/* Search bar */}
<div className="px-4 pt-2.5">
<div className="-translate-y-px border-b border-border/70 pb-2.5 transition-colors focus-within:border-ring">
<div className="-translate-y-px rounded-lg bg-accent px-2 py-1">
<ComboboxInput
ref={searchInputRef}
className="[&_input]:h-6.5 [&_input]:font-sans [&_input]:leading-6.5"
inputClassName="rounded-none bg-transparent text-sm"
inputClassName="rounded-none bg-transparent text-sm placeholder:text-muted-foreground/80"
placeholder="Search models..."
showTrigger={false}
startAddon={
<SearchIcon className="-translate-x-0.5 size-4 shrink-0 text-muted-foreground/55" />
<SearchIcon className="-translate-x-0.5 size-4 shrink-0 text-muted-foreground/80" />
}
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
@@ -97,10 +97,7 @@ export const ModelPickerSidebar = memo(function ModelPickerSidebar(props: {
}, [props.instanceEntries, props.selectedInstanceId, showFavorites]);
return (
<div
className="w-12 shrink-0 overflow-hidden border-r bg-muted/30"
data-model-picker-sidebar="true"
>
<div className="w-12 shrink-0 overflow-hidden bg-muted/60" data-model-picker-sidebar="true">
<div className="h-full overflow-y-auto overscroll-contain [-ms-overflow-style:none] [scrollbar-width:none] [&::-webkit-scrollbar]:hidden">
<div
ref={sidebarContentRef}
@@ -118,7 +115,7 @@ export const ModelPickerSidebar = memo(function ModelPickerSidebar(props: {
) : null}
{/* Favorites section */}
{showFavorites ? (
<div className="mb-1 border-b pb-1">
<div className="mb-1 pb-1">
<div className="relative w-full">
<Tooltip>
<TooltipTrigger
@@ -0,0 +1,57 @@
import { ProviderDriverKind, ProviderInstanceId, type ServerProvider } from "@t3tools/contracts";
import { renderToStaticMarkup } from "react-dom/server";
import { describe, expect, it } from "vite-plus/test";
import {
getProviderStatusBannerKey,
ProviderStatusBanner,
shouldShowProviderStatusBanner,
} from "./ProviderStatusBanner";
function warningProvider(): ServerProvider {
return {
instanceId: ProviderInstanceId.make("codex"),
driver: ProviderDriverKind.make("codex"),
displayName: "Codex",
enabled: true,
installed: true,
version: "1.0.0",
status: "warning",
auth: { status: "authenticated" },
checkedAt: "2026-07-23T12:00:00.000Z",
message: "Provider is temporarily degraded.",
models: [],
slashCommands: [],
skills: [],
};
}
describe("ProviderStatusBanner", () => {
it("stays hidden after its current warning is dismissed", () => {
const status = warningProvider();
expect(shouldShowProviderStatusBanner(status, null)).toBe(true);
expect(shouldShowProviderStatusBanner(status, getProviderStatusBannerKey(status))).toBe(false);
});
it("renders an accessible dismiss control for provider warnings", () => {
const markup = renderToStaticMarkup(
<ProviderStatusBanner status={warningProvider()} onDismiss={() => {}} />,
);
expect(markup).toContain('role="alert"');
expect(markup).toContain('aria-label="Dismiss Codex provider warning"');
expect(markup).toContain("absolute top-2 right-2");
});
it("labels error dismiss controls with the correct severity", () => {
const markup = renderToStaticMarkup(
<ProviderStatusBanner
status={{ ...warningProvider(), status: "error" }}
onDismiss={() => {}}
/>,
);
expect(markup).toContain('aria-label="Dismiss Codex provider error"');
});
});
@@ -1,13 +1,29 @@
import { type ServerProvider } from "@t3tools/contracts";
import { memo } from "react";
import { InfoIcon } from "lucide-react";
import { InfoIcon, XIcon } from "lucide-react";
import { cn } from "~/lib/utils";
import { formatProviderDriverKindLabel } from "../../providerModels";
import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
export function getProviderStatusBannerKey(status: ServerProvider | null): string | null {
return !status || status.status === "ready" || status.status === "disabled"
? null
: [status.instanceId, status.status, status.auth.status, status.message ?? ""].join("\u0000");
}
export function shouldShowProviderStatusBanner(
status: ServerProvider | null,
dismissedBannerKey: string | null,
): boolean {
const bannerKey = getProviderStatusBannerKey(status);
return bannerKey !== null && bannerKey !== dismissedBannerKey;
}
export const ProviderStatusBanner = memo(function ProviderStatusBanner({
onDismiss,
status,
}: {
onDismiss: () => void;
status: ServerProvider | null;
}) {
if (!status || status.status === "ready" || status.status === "disabled") {
@@ -27,10 +43,10 @@ export const ProviderStatusBanner = memo(function ProviderStatusBanner({
: `${providerName} provider has limited availability.`));
return (
<div className="mx-auto w-fit max-w-[calc(100%-2rem)] pt-3">
<div className="pointer-events-auto mx-auto w-fit max-w-[calc(100%-2rem)] pt-3">
<div
className={cn(
"inline-flex items-center gap-3 rounded-xl border px-3.5 py-3 text-card-foreground text-sm",
"relative inline-flex items-center gap-3 rounded-xl border py-3 ps-3.5 pe-10 text-card-foreground text-sm",
status.status === "warning"
? "border-warning/32 bg-warning/4 [&_svg]:text-warning"
: "border-destructive/32 bg-destructive/4 text-destructive-foreground [&_svg]:text-destructive",
@@ -49,6 +65,14 @@ export const ProviderStatusBanner = memo(function ProviderStatusBanner({
</TooltipPopup>
</Tooltip>
</div>
<button
type="button"
aria-label={`Dismiss ${providerName} provider ${status.status}`}
className="absolute top-2 right-2 inline-flex size-6 cursor-pointer items-center justify-center rounded-md text-muted-foreground outline-none transition-colors hover:bg-foreground/8 hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring"
onClick={onDismiss}
>
<XIcon aria-hidden className="size-3.5" />
</button>
</div>
</div>
);
@@ -16,7 +16,7 @@ import {
} from "@t3tools/shared/model";
import { memo, useCallback, useState } from "react";
import type { VariantProps } from "class-variance-authority";
import { CheckIcon, ChevronDownIcon } from "lucide-react";
import { ChevronDownIcon } from "lucide-react";
import { Button, buttonVariants } from "../ui/button";
import {
Menu,
@@ -337,9 +337,6 @@ export const TraitsMenuContent = memo(function TraitsMenuContentImpl({
</>
) : null}
</span>
{option.id === selectedValue ? (
<CheckIcon className="size-3.5 shrink-0 text-blue-400" />
) : null}
</span>
</MenuRadioItem>
))}
@@ -370,9 +367,6 @@ export const TraitsMenuContent = memo(function TraitsMenuContentImpl({
<MenuRadioItem key={value} value={value} hideIndicator>
<span className="flex w-full min-w-0 items-center justify-between gap-3">
<span>{value === "on" ? "On" : "Off"}</span>
{value === selectedValue ? (
<CheckIcon className="size-3.5 shrink-0 text-blue-400" />
) : null}
</span>
</MenuRadioItem>
))}
@@ -28,7 +28,7 @@ function ConfiguredT3ConnectSidebarAvatar() {
appearance={{
elements: {
avatarBox: "size-7",
userButtonTrigger: "rounded-lg p-1 hover:bg-sidebar-accent",
userButtonTrigger: "rounded-lg p-1 hover:bg-sidebar-row-hover",
},
}}
>
@@ -55,10 +55,10 @@ function ConfiguredT3ConnectSidebarSignIn() {
<SidebarMenuItem>
<SidebarMenuButton
size="sm"
className="gap-2 px-2 py-2 text-xs text-muted-foreground hover:bg-accent hover:text-foreground"
className="h-8 items-center gap-2 rounded-md px-2 py-1.5 text-sm font-medium text-sidebar-muted-foreground/80 hover:bg-sidebar-row-hover hover:text-sidebar-foreground"
onClick={openAuthPrompt}
>
<LogInIcon className="size-4" />
<LogInIcon className="size-4 shrink-0" />
<span>Sign in to T3 Connect</span>
</SidebarMenuButton>
</SidebarMenuItem>
Loaded 100 of 164 files, more files were not shown because too many files have changed in this diff. Show more