Compare commits

..
227 changed files with 3105 additions and 13410 deletions

No files matched your search

-2
View File
@@ -54,8 +54,6 @@ 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)
-6
View File
@@ -1,9 +1,3 @@
for (const stream of [process.stdout, process.stderr]) {
stream.on("error", (err: NodeJS.ErrnoException) => {
if (err.code !== "EPIPE") throw err;
});
}
import * as NodeHttpClient from "@effect/platform-node/NodeHttpClient";
import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
import * as NodeServices from "@effect/platform-node/NodeServices";
@@ -19,7 +19,6 @@ const clientSettings: ClientSettings = {
dismissedProviderUpdateNotificationKeys: [],
diffIgnoreWhitespace: true,
favorites: [],
glassOpacity: 80,
providerModelPreferences: {},
sidebarAutoSettleAfterDays: 3,
sidebarProjectGroupingMode: "repository_path",
-1
View File
@@ -10,7 +10,6 @@
"typecheck": "astro check"
},
"dependencies": {
"@t3tools/shared": "workspace:*",
"astro": "^7.0.3"
},
"devDependencies": {
@@ -1,10 +0,0 @@
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",
};
+5 -19
View File
@@ -13,10 +13,7 @@ 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,
useAppearancePreferences,
} from "./features/settings/appearance/AppearancePreferencesProvider";
import { AppearancePreferencesProvider } from "./features/settings/appearance/AppearancePreferencesProvider";
import { RootStack } from "./Stack";
import { appAtomRegistry } from "./state/atom-registry";
import { OverlayPortalHost } from "./components/OverlayPortal";
@@ -29,10 +26,6 @@ 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
@@ -47,25 +40,18 @@ 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) {
if (state.isConnected === false || state.isInternetReachable === false) {
return "offline";
}
if (state.isConnected === true) {
+60 -111
View File
@@ -1,7 +1,9 @@
import type { EnvironmentId, SidebarThreadSortOrder } from "@t3tools/contracts";
import type {
EnvironmentId,
SidebarProjectGroupingMode,
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";
@@ -12,7 +14,6 @@ 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";
@@ -20,10 +21,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";
@@ -32,17 +33,16 @@ 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,24 +59,11 @@ 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 threadListV2Enabled = useThreadListV2FilterGate();
const hasCustomListOptions = threadListV2Enabled
? props.selectedEnvironmentId !== null || props.selectedProjectKey !== null
: hasCustomHomeListOptions(props);
const hasCustomListOptions = hasCustomHomeListOptions(props);
const menuActions = useMemo<MenuAction[]>(
() => [
{
@@ -95,57 +82,40 @@ function AndroidHomeHeader(props: HomeHeaderProps) {
})),
],
},
...(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[])),
{
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.environments,
props.projectGroupingMode,
props.projectSortOrder,
props.projects,
props.selectedEnvironmentId,
props.selectedProjectKey,
props.threadSortOrder,
threadListV2Enabled,
],
);
const handleMenuAction = useCallback(
@@ -167,19 +137,6 @@ 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}`,
);
@@ -193,6 +150,13 @@ 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],
);
@@ -291,24 +255,17 @@ function AndroidHomeHeader(props: HomeHeaderProps) {
function IosHomeHeader(props: HomeHeaderProps) {
const searchBarRef = useRef<SearchBarCommands>(null);
const iconColor = useThemeColor("--color-icon");
const threadListV2Enabled = useThreadListV2FilterGate();
const hasCustomListOptions = threadListV2Enabled
? props.selectedEnvironmentId !== null || props.selectedProjectKey !== null
: hasCustomHomeListOptions(props);
const hasCustomListOptions = hasCustomHomeListOptions(props);
const focusSearch = useCallback(() => {
searchBarRef.current?.focus();
return searchBarRef.current !== null;
}, []);
useHardwareKeyboardCommand("focusSearch", focusSearch);
const filterMenu = buildHomeListFilterMenu({
...props,
listOrganization: !threadListV2Enabled,
});
const filterMenu = buildHomeListFilterMenu(props);
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.
@@ -409,28 +366,6 @@ 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) => (
@@ -456,6 +391,20 @@ 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,10 +1,9 @@
import * as Arr from "effect/Array";
import * as Order from "effect/Order";
import { useNavigation } from "@react-navigation/native";
import { useEffect, useMemo, useState } from "react";
import { 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";
@@ -54,32 +53,11 @@ 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.
@@ -112,15 +90,14 @@ 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" })}
@@ -138,11 +115,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) => {
@@ -174,7 +151,6 @@ export function HomeRouteScreen() {
savedConnectionsById={savedConnectionsById}
searchQuery={searchQuery}
selectedEnvironmentId={selectedEnvironmentId}
selectedProjectKey={selectedProjectKey}
threads={threads}
threadSortOrder={listOptions.threadSortOrder}
/>
+122 -128
View File
@@ -15,15 +15,17 @@ 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, View } from "react-native";
import { ActivityIndicator, FlatList, Platform, Pressable, ScrollView, 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";
@@ -36,12 +38,7 @@ import {
ThreadListShowMoreRow,
} from "../threads/thread-list-items";
import { ThreadListV2Row } from "../threads/thread-list-v2-items";
import {
buildThreadListV2Items,
THREAD_LIST_V2_SETTLED_INITIAL_COUNT,
THREAD_LIST_V2_SETTLED_PAGE_COUNT,
type ThreadListV2Item,
} from "../threads/threadListV2";
import { buildThreadListV2Items, type ThreadListV2Item } from "../threads/threadListV2";
import type { HomeListFilterMenuEnvironment } from "./home-list-filter-menu";
import {
buildHomeListLayout,
@@ -52,12 +49,7 @@ import {
type HomeGroupDisplayState,
type HomeListItem,
} from "./homeListItems";
import {
buildHomeProjectScopes,
buildHomeThreadGroups,
sortHomeProjectScopes,
type HomeProjectSortOrder,
} from "./homeThreadList";
import { buildHomeThreadGroups, type HomeProjectSortOrder } from "./homeThreadList";
import { SwipeableScrollGateProvider, useSwipeableScrollGate } from "./thread-swipe-actions";
import { WorkspaceConnectionStatus } from "./WorkspaceConnectionStatus";
import { shouldShowWorkspaceConnectionStatus } from "./workspace-connection-status";
@@ -73,15 +65,14 @@ 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;
@@ -100,6 +91,10 @@ 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
@@ -174,6 +169,80 @@ 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) {
@@ -245,51 +314,12 @@ 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: scopedProjects,
threads: scopedThreads,
pendingTasks: scopedPendingTasks,
projects: props.projects,
threads: props.threads,
pendingTasks: props.pendingTasks,
environmentId: props.selectedEnvironmentId,
searchQuery: props.searchQuery,
projectSortOrder: props.projectSortOrder,
@@ -297,14 +327,14 @@ export function HomeScreen(props: HomeScreenProps) {
projectGroupingMode: props.projectGroupingMode,
}),
[
props.pendingTasks,
props.projectGroupingMode,
props.projects,
props.projectSortOrder,
props.searchQuery,
props.selectedEnvironmentId,
props.threadSortOrder,
scopedPendingTasks,
scopedProjects,
scopedThreads,
props.threads,
],
);
@@ -335,54 +365,29 @@ export function HomeScreen(props: HomeScreenProps) {
return map;
}, [props.projects]);
const v2ProjectScopeKey = props.selectedProjectKey;
const [v2ProjectScopeKey, setV2ProjectScopeKey] = useState<string | null>(null);
const v2ScopeProjects = useMemo(
() =>
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,
],
props.selectedEnvironmentId === null
? props.projects
: props.projects.filter((project) => project.environmentId === props.selectedEnvironmentId),
[props.projects, props.selectedEnvironmentId],
);
const v2ScopedProjectGroup = useMemo(
const v2ScopedProject = useMemo(
() =>
v2ProjectScopeKey === null
? null
: (v2ScopeProjects.find(
(scope) =>
scope.key === v2ProjectScopeKey ||
scope.projectRefs.some(
(projectRef) =>
scopedProjectKey(projectRef.environmentId, projectRef.projectId) ===
v2ProjectScopeKey,
),
(project) => scopedProjectKey(project.environmentId, project.id) === v2ProjectScopeKey,
) ?? null),
[v2ProjectScopeKey, v2ScopeProjects],
);
const v2ScopedProjectKeys = useMemo(
() =>
v2ScopedProjectGroup === null
? null
: new Set(
v2ScopedProjectGroup.projectRefs.map((projectRef) =>
scopedProjectKey(projectRef.environmentId, projectRef.projectId),
),
),
[v2ScopedProjectGroup],
);
useEffect(() => {
if (v2ProjectScopeKey !== null && v2ScopedProject === null) {
setV2ProjectScopeKey(null);
}
}, [v2ProjectScopeKey, v2ScopedProject]);
// 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
@@ -437,10 +442,6 @@ 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]);
@@ -463,7 +464,13 @@ export function HomeScreen(props: HomeScreenProps) {
return buildThreadListV2Items({
threads: props.threads.filter((thread) => thread.archivedAt === null),
environmentId: props.selectedEnvironmentId,
projectRefs: v2ScopedProjectGroup === null ? null : v2ScopedProjectGroup.projectRefs,
projectRef:
v2ScopedProject === null
? null
: {
environmentId: v2ScopedProject.environmentId,
projectId: v2ScopedProject.id,
},
searchQuery: props.searchQuery,
changeRequestStateByKey,
settlementEnvironmentIds,
@@ -479,7 +486,7 @@ export function HomeScreen(props: HomeScreenProps) {
props.selectedEnvironmentId,
props.threads,
threadListV2Enabled,
v2ScopedProjectGroup,
v2ScopedProject,
]);
const threadListV2Items = threadListV2Layout.items;
@@ -502,11 +509,6 @@ 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}
@@ -533,7 +535,6 @@ export function HomeScreen(props: HomeScreenProps) {
projectCwdByKey,
props.onArchiveThread,
props.onSelectThread,
props.savedConnectionsById,
serverConfigs,
settlementEnvironmentIds,
],
@@ -725,17 +726,19 @@ export function HomeScreen(props: HomeScreenProps) {
(pendingTask) =>
(props.selectedEnvironmentId === null ||
pendingTask.message.environmentId === props.selectedEnvironmentId) &&
(v2ScopedProjectKeys === null ||
v2ScopedProjectKeys.has(
scopedProjectKey(pendingTask.message.environmentId, pendingTask.creation.projectId),
)) &&
(v2ScopedProject === null ||
(pendingTask.message.environmentId === v2ScopedProject.environmentId &&
pendingTask.creation.projectId === v2ScopedProject.id)) &&
(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}
@@ -755,11 +758,6 @@ 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}`}
@@ -777,9 +775,9 @@ export function HomeScreen(props: HomeScreenProps) {
const v2ListEmpty =
v2PendingTasks.length > 0 ? null : hasSearchQuery ? (
<EmptyState title="No results" detail={`No threads matching "${props.searchQuery}".`} />
) : v2ScopedProjectGroup !== null ? (
) : v2ScopedProject !== null ? (
<EmptyState
title={`No threads in ${v2ScopedProjectGroup.title}`}
title={`No threads in ${v2ScopedProject.title}`}
detail="Choose another project or create a new task."
/>
) : (
@@ -794,11 +792,7 @@ export function HomeScreen(props: HomeScreenProps) {
data={threadListV2Items}
renderItem={renderV2Item}
keyExtractor={v2KeyExtractor}
extraData={{
projectByKey,
serverConfigs,
savedConnectionsById: props.savedConnectionsById,
}}
extraData={{ projectByKey, serverConfigs }}
ListHeaderComponent={v2ListHeader}
ListFooterComponent={
threadListV2Layout.hiddenSettledCount > 0 ? (
@@ -1,42 +0,0 @@
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,18 +1,21 @@
import type { EnvironmentId, SidebarThreadSortOrder } from "@t3tools/contracts";
import type {
EnvironmentId,
SidebarProjectGroupingMode,
SidebarThreadSortOrder,
} from "@t3tools/contracts";
import type { HomeProjectSortOrder } from "./homeThreadList";
import { PROJECT_SORT_OPTIONS, THREAD_SORT_OPTIONS } from "./home-list-options";
import {
PROJECT_GROUPING_OPTIONS,
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;
@@ -34,20 +37,15 @@ 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> = [];
@@ -59,75 +57,61 @@ export function buildHomeListFilterMenu(props: {
});
}
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({
items.push(
{
type: "submenu",
title: "Project",
title: "Environment",
items: [
{
type: "action",
title: "All projects",
subtitle: "Show threads from every project",
state: props.selectedProjectKey === null ? "on" : "off",
onPress: () => props.onProjectChange(null),
title: "All environments",
subtitle: "Show threads from every environment",
state: props.selectedEnvironmentId === null ? "on" : "off",
onPress: () => props.onEnvironmentChange(null),
},
...props.projects.map((project) => ({
...props.environments.map((environment) => ({
type: "action" as const,
title: project.label,
state: props.selectedProjectKey === project.key ? ("on" as const) : ("off" as const),
onPress: () => props.onProjectChange(project.key),
title: environment.label,
state:
props.selectedEnvironmentId === environment.environmentId
? ("on" as const)
: ("off" as const),
onPress: () => props.onEnvironmentChange(environment.environmentId),
})),
],
});
}
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),
})),
},
);
}
},
{
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),
})),
},
);
return {
title: "Thread list options",
@@ -1,4 +1,5 @@
import {
DEFAULT_SIDEBAR_PROJECT_GROUPING_MODE,
DEFAULT_SIDEBAR_PROJECT_SORT_ORDER,
DEFAULT_SIDEBAR_THREAD_SORT_ORDER,
} from "@t3tools/contracts";
@@ -13,6 +14,7 @@ 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", () => {
@@ -20,12 +22,10 @@ describe("home list options", () => {
expect(hasCustomHomeListOptions(defaults)).toBe(false);
});
it("marks environment filters as customized", () => {
it("marks environment filters and grouping changes as customized", () => {
expect(
hasCustomHomeListOptions({ ...defaults, selectedEnvironmentId: "environment-1" as never }),
).toBe(true);
expect(
hasCustomHomeListOptions({ ...defaults, selectedProjectKey: "environment-1:project-1" }),
).toBe(true);
expect(hasCustomHomeListOptions({ ...defaults, projectGroupingMode: "separate" })).toBe(true);
});
});
@@ -4,6 +4,7 @@ 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";
@@ -25,18 +26,9 @@ 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;
@@ -53,6 +45,28 @@ 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,
@@ -61,44 +75,34 @@ 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,
projectGroupingMode,
}: PropsWithChildren<{ readonly projectGroupingMode: SidebarProjectGroupingMode }>) {
export function HomeListOptionsProvider({ children }: PropsWithChildren) {
const [options, setOptions] = useState<HomeListOptions>(defaultHomeListOptions);
const value = useMemo(
() => ({ options, setOptions, projectGroupingMode }),
[options, projectGroupingMode],
);
const value = useMemo(() => ({ options, setOptions }), [options]);
return createElement(HomeListOptionsContext, { value }, children);
}
export function hasCustomHomeListOptions(
options: HomeListOptions & {
readonly selectedProjectKey?: string | null;
},
): boolean {
export function hasCustomHomeListOptions(options: HomeListOptions): 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.threadSortOrder !== DEFAULT_SIDEBAR_THREAD_SORT_ORDER ||
options.projectGroupingMode !== DEFAULT_SIDEBAR_PROJECT_GROUPING_MODE
);
}
@@ -112,14 +116,10 @@ export function useHomeListOptions(availableEnvironmentIds: ReadonlySet<Environm
availableEnvironmentIds.has(options.selectedEnvironmentId)
? options.selectedEnvironmentId
: null;
const availableOptions =
const resolvedOptions =
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,10 +130,15 @@ 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,11 +5,7 @@ import type {
import { EnvironmentId, ProjectId, ProviderInstanceId, ThreadId } from "@t3tools/contracts";
import { describe, expect, it } from "vite-plus/test";
import {
buildHomeProjectScopes,
buildHomeThreadGroups,
sortHomeProjectScopes,
} from "./homeThreadList";
import { buildHomeThreadGroups } from "./homeThreadList";
function makeProject(
input: Partial<EnvironmentProject> & Pick<EnvironmentProject, "environmentId" | "id" | "title">,
@@ -71,308 +67,6 @@ 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({
+25 -187
View File
@@ -1,20 +1,14 @@
import {
deriveLogicalProjectKey,
derivePhysicalProjectKey,
deriveProjectGroupLabel,
} from "@t3tools/client-runtime/state/project-grouping";
import type {
EnvironmentProject,
EnvironmentThreadShell,
} from "@t3tools/client-runtime/state/shell";
import {
getThreadSortTimestamp,
sortThreads,
toSortableTimestamp,
} from "@t3tools/client-runtime/state/thread-sort";
import { getThreadSortTimestamp, sortThreads } from "@t3tools/client-runtime/state/thread-sort";
import type {
EnvironmentId,
ScopedProjectRef,
SidebarProjectGroupingMode,
SidebarProjectSortOrder,
SidebarThreadSortOrder,
@@ -28,164 +22,6 @@ 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.
@@ -267,18 +103,22 @@ export function buildHomeThreadGroups(input: {
const groups = new Map<string, MutableHomeThreadGroup>();
const groupKeyByProjectKey = new Map<string, string>();
for (const scope of buildHomeProjectScopes(input)) {
groups.set(scope.key, {
key: scope.key,
projects: [...scope.projects],
pendingTasks: [],
threads: [],
for (const project of input.projects) {
if (input.environmentId !== null && project.environmentId !== input.environmentId) {
continue;
}
const groupKey = deriveLogicalProjectKey(project, {
groupingMode: input.projectGroupingMode,
});
for (const projectRef of scope.projectRefs) {
groupKeyByProjectKey.set(
scopedProjectKey(projectRef.environmentId, projectRef.projectId),
scope.key,
);
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: [] });
}
}
@@ -375,21 +215,19 @@ export function buildHomeThreadGroups(input: {
? selectRecentThreads(sortedThreads, input.threadSortOrder, now)
: sortedThreads;
// 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,
),
// 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,
),
Option.flatMap((threadProject) =>
).pipe(
Option.flatMap((thread) =>
Arr.findFirst(
group.projects,
(project) =>
derivePhysicalProjectKey(project) === derivePhysicalProjectKey(threadProject),
project.environmentId === thread.environmentId && project.id === thread.projectId,
),
),
Option.getOrNull,
@@ -36,8 +36,6 @@ 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 = {
@@ -165,9 +163,6 @@ 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;
@@ -263,7 +258,6 @@ 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}
@@ -291,7 +285,6 @@ 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"];
@@ -300,8 +293,6 @@ 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);
@@ -333,7 +324,7 @@ function SwipeActionButton(props: {
return {
transform: [{ translateX: -stretch }],
width: circleSize + stretch,
width: ACTION_CIRCLE_SIZE + stretch,
};
});
const iconStyle = useAnimatedStyle(() => {
@@ -395,13 +386,13 @@ function SwipeActionButton(props: {
width: "100%",
})}
>
<View style={{ height: circleSize, width: circleSize }}>
<View style={{ height: ACTION_CIRCLE_SIZE, width: ACTION_CIRCLE_SIZE }}>
<Animated.View
style={[
{
backgroundColor: props.backgroundColor,
borderRadius: 999,
height: circleSize,
height: ACTION_CIRCLE_SIZE,
left: 0,
position: "absolute",
top: 0,
@@ -413,25 +404,25 @@ function SwipeActionButton(props: {
style={[
{
alignItems: "center",
height: circleSize,
height: ACTION_CIRCLE_SIZE,
justifyContent: "center",
left: 0,
position: "absolute",
top: 0,
width: circleSize,
width: ACTION_CIRCLE_SIZE,
},
iconStyle,
]}
>
<SymbolView name={props.icon} size={iconSize} tintColor="#ffffff" type="monochrome" />
<SymbolView
name={props.icon}
size={ACTION_ICON_SIZE}
tintColor="#ffffff"
type="monochrome"
/>
</Animated.View>
</View>
<Animated.View
style={[
{ height: 14, justifyContent: "center", paddingTop: props.compact ? 0 : 2 },
labelStyle,
]}
>
<Animated.View style={[{ paddingTop: 2 }, labelStyle]}>
<Text className="text-3xs font-t3-medium text-foreground-muted" numberOfLines={1}>
{props.label}
</Text>
@@ -443,7 +434,6 @@ function SwipeActionButton(props: {
export function ThreadSwipeActions(props: {
readonly backgroundColor: ColorValue;
readonly compact: boolean;
readonly fullSwipeAction?: "delete" | "primary";
readonly fullSwipeThreshold: number;
readonly onDelete: () => void;
@@ -476,7 +466,6 @@ 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}
@@ -488,7 +477,6 @@ 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,8 +2,7 @@ import type {
EnvironmentProject,
EnvironmentThreadShell,
} from "@t3tools/client-runtime/state/shell";
import { EnvironmentId, ThreadId, type SidebarProjectGroupingMode } from "@t3tools/contracts";
import { useAtomValue } from "@effect/atom-react";
import { EnvironmentId, ThreadId } from "@t3tools/contracts";
import { useFocusEffect } from "@react-navigation/native";
import {
NavigationContext,
@@ -23,7 +22,6 @@ 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,
@@ -36,12 +34,11 @@ 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, resolveProjectGroupingMode } from "../home/home-list-options";
import { HomeListOptionsProvider } from "../home/home-list-options";
import { ThreadNavigationSidebar } from "../threads/ThreadNavigationSidebar";
import { WORKSPACE_PANE_TIMING } from "./workspace-pane-animation";
import { WorkspaceInspectorPane } from "./workspace-inspector-pane";
@@ -187,31 +184,6 @@ 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();
@@ -502,7 +474,7 @@ function AdaptiveWorkspaceLayoutContent(
);
return (
<HomeListOptionsProvider projectGroupingMode={projectGroupingMode}>
<HomeListOptionsProvider>
<AdaptiveWorkspaceContext.Provider value={contextValue}>
<View testID="adaptive-workspace-layout" className="flex-1 flex-row">
{shouldRenderPrimarySidebar && layout.listPaneWidth !== null ? (
@@ -119,8 +119,6 @@ function LocalSettingsRouteScreen() {
/>
</SettingsSection>
<GeneralSettingsSection />
<SettingsSection title="Appearance">
<SettingsRow icon="paintbrush" label="Appearance" target="SettingsAppearance" />
</SettingsSection>
@@ -506,8 +504,6 @@ function ConfiguredSettingsRouteScreen() {
/>
</SettingsSection>
<GeneralSettingsSection />
<SettingsSection title="Appearance">
<SettingsRow icon="paintbrush" label="Appearance" target="SettingsAppearance" />
</SettingsSection>
@@ -522,25 +518,6 @@ 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,13 +582,10 @@ export function NewTaskDraftScreen(props: {
? "Approve actions"
: flow.runtimeMode === "auto-accept-edits"
? "Auto-accept edits"
: flow.runtimeMode === "auto"
? "Auto"
: "Full access",
: "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:", "");
@@ -26,13 +26,7 @@ import {
type ViewStyle,
} from "react-native";
import ImageViewing from "react-native-image-viewing";
import Animated, {
FadeIn,
FadeInDown,
FadeOut,
FadeOutDown,
LinearTransition,
} from "react-native-reanimated";
import Animated, { FadeIn, FadeOut, LinearTransition } from "react-native-reanimated";
import { useThemeColor } from "../../lib/useThemeColor";
import { armAgentAwarenessLiveActivityForLocalWork } from "../agent-awareness/remoteRegistration";
import { scopedThreadKey } from "../../lib/scopedEntities";
@@ -238,12 +232,7 @@ const ComposerConnectionStatusPill = memo(function ComposerConnectionStatusPill(
const isReconnecting = props.status.kind !== "unavailable";
return (
<Animated.View
className="absolute inset-x-0 bottom-full items-center pb-2"
entering={FadeInDown.duration(180)}
exiting={FadeOutDown.duration(140)}
pointerEvents="box-none"
>
<View className="items-center pb-2">
<Pressable
accessibilityRole="button"
onPress={props.onPress}
@@ -261,7 +250,7 @@ const ComposerConnectionStatusPill = memo(function ComposerConnectionStatusPill(
{props.status.label}
</Text>
</Pressable>
</Animated.View>
</View>
);
});
@@ -638,13 +627,10 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
? "Approve actions"
: currentRuntimeMode === "auto-accept-edits"
? "Auto-accept edits"
: currentRuntimeMode === "auto"
? "Auto"
: "Full access",
: "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:", "");
@@ -14,18 +14,21 @@ import type {
ServerConfig as T3ServerConfig,
ThreadId,
} from "@t3tools/contracts";
import { formatElapsed } from "@t3tools/shared/orchestrationTiming";
import * as Haptics from "expo-haptics";
import { memo, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
import { Platform, View, type GestureResponderEvent } from "react-native";
import { KeyboardController, KeyboardStickyView } from "react-native-keyboard-controller";
import Animated, { FadeInDown, FadeOut } from "react-native-reanimated";
import Animated, { FadeInDown, FadeOut, LinearTransition } from "react-native-reanimated";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { AppText as Text } from "../../components/AppText";
import type { ComposerEditorHandle } from "../../components/ComposerEditor";
import type { StatusTone } from "../../components/StatusPill";
import type { DraftComposerImageAttachment } from "../../lib/composerImages";
import { CHAT_CONTENT_MAX_WIDTH, type LayoutVariant } from "../../lib/layout";
import { scopedThreadKey } from "../../lib/scopedEntities";
import { NATIVE_LIQUID_GLASS_SUPPORTED } from "../../native/native-glass";
import type {
PendingApproval,
PendingUserInput,
@@ -169,6 +172,54 @@ function useStreamingHaptics(threadId: ThreadId, feed: ReadonlyArray<ThreadFeedE
}, [threadId, feed]);
}
// Pre-measurement estimate for the working pill's slot (the real height is
// measured via onComposerLayout since the pill lives inside the composer
// overlay). Matches the rendered pill: pt-2 + pb-2 (16) wrapping a bordered
// px-3/py-2 row (~36), so ~52 — keep it in sync with WorkingDurationPill.
const WORKING_INDICATOR_HEIGHT = 52;
const WorkingDurationPill = memo(function WorkingDurationPill(props: {
readonly startedAt: string;
}) {
const [nowMs, setNowMs] = useState(() => Date.now());
useEffect(() => {
const intervalId = setInterval(() => {
setNowMs(Date.now());
}, 1_000);
return () => clearInterval(intervalId);
}, [props.startedAt]);
const durationLabel = formatElapsed(props.startedAt, new Date(nowMs).toISOString()) ?? "0s";
return (
<Animated.View
className="shrink-0 px-4 pb-2 pt-2"
entering={FadeInDown.duration(200)}
exiting={FadeOut.duration(140)}
>
<View
className={
Platform.OS === "ios" && !NATIVE_LIQUID_GLASS_SUPPORTED
? "self-start rounded-full border border-border bg-card px-3 py-2"
: "self-start rounded-full border border-neutral-200/80 bg-neutral-50/90 px-3 py-2 dark:border-white/[0.08] dark:bg-white/[0.04]"
}
>
<View className="flex-row items-center gap-2">
<View className="flex-row items-center gap-1">
<View className="h-1.5 w-1.5 rounded-full bg-neutral-400 dark:bg-neutral-500" />
<View className="h-1.5 w-1.5 rounded-full bg-neutral-400/80 dark:bg-neutral-500/80" />
<View className="h-1.5 w-1.5 rounded-full bg-neutral-400/60 dark:bg-neutral-500/60" />
</View>
<Text className="font-t3-medium text-xs text-neutral-600 dark:text-neutral-400">
Working for {durationLabel}
</Text>
</View>
</View>
</Animated.View>
);
});
export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: ThreadDetailScreenProps) {
const insets = useSafeAreaInsets();
const agentLabel = `${props.selectedThread.modelSelection.instanceId} agent`;
@@ -202,7 +253,8 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
const selectedThreadFeed = props.selectedThreadFeed;
const composerChrome = composerExpanded ? COMPOSER_EXPANDED_CHROME : COMPOSER_COLLAPSED_CHROME;
const composerOverlapHeight = composerChrome + composerBottomInset;
const estimatedOverlayHeight = composerOverlapHeight;
const activeWorkIndicatorHeight = props.activeWorkStartedAt ? WORKING_INDICATOR_HEIGHT : 0;
const estimatedOverlayHeight = composerOverlapHeight + activeWorkIndicatorHeight;
// The overlay's measured height includes the home-indicator inset (the
// composer pads it), but contentInsetAdjustmentBehavior="automatic" makes
// UIKit add the safe-area bottom to the content inset AGAIN — leaving a
@@ -359,7 +411,6 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
contentPresentation={props.contentPresentation}
agentLabel={agentLabel}
latestTurn={props.selectedThread.latestTurn}
activeWorkStartedAt={props.activeWorkStartedAt}
listRef={listRef}
freeze={freeze}
anchorMessageId={anchorMessageId}
@@ -387,7 +438,15 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
list's bottom inset, so any padding above the pill/composer
pushes the resting content floor up by the same amount. */}
<View ref={composerOverlayRef} onLayout={onComposerLayout} className="w-full">
<View className="w-full self-center" style={{ maxWidth: contentMaxWidth }}>
<Animated.View
className="w-full self-center"
layout={LinearTransition.duration(220)}
style={{ maxWidth: contentMaxWidth }}
>
{props.activeWorkStartedAt ? (
<WorkingDurationPill startedAt={props.activeWorkStartedAt} />
) : null}
{props.activePendingApproval || props.activePendingUserInput ? (
<Animated.View
className="shrink-0 gap-3 px-4 pb-3"
@@ -414,7 +473,7 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
) : null}
</Animated.View>
) : null}
</View>
</Animated.View>
<ThreadComposer
editorRef={composerEditorRef}
@@ -3,7 +3,6 @@ import { KeyboardAwareLegendList } from "@legendapp/list/keyboard";
import { type LegendListRef } from "@legendapp/list/react-native";
import type { EnvironmentId, MessageId, ThreadId, TurnId } from "@t3tools/contracts";
import { CHAT_LIST_ANCHOR_OFFSET, resolveChatListAnchoredEndSpace } from "@t3tools/shared/chatList";
import { formatElapsed } from "@t3tools/shared/orchestrationTiming";
import { SymbolView } from "../../components/AppSymbol";
import { HeaderHeightContext } from "@react-navigation/elements";
import { useNavigation } from "@react-navigation/native";
@@ -129,7 +128,6 @@ export interface ThreadFeedProps {
readonly contentPresentation: ThreadContentPresentation;
readonly agentLabel: string;
readonly latestTurn: ThreadFeedLatestTurn | null;
readonly activeWorkStartedAt: string | null;
readonly listRef: RefObject<LegendListRef | null>;
readonly freeze: SharedValue<boolean>;
readonly anchorMessageId: MessageId | null;
@@ -818,10 +816,6 @@ function renderFeedEntry(
const entry = info.item;
const { markdownStyles, iconSubtleColor, userBubbleColor } = props;
if (entry.type === "working") {
return <WorkingTimelineRow startedAt={entry.createdAt} />;
}
if (entry.type === "turn-fold") {
return (
<Pressable
@@ -999,32 +993,6 @@ function renderFeedEntry(
);
}
const WorkingTimelineRow = memo(function WorkingTimelineRow(props: { readonly startedAt: string }) {
const [nowMs, setNowMs] = useState(() => Date.now());
useEffect(() => {
const intervalId = setInterval(() => {
setNowMs(Date.now());
}, 1_000);
return () => clearInterval(intervalId);
}, [props.startedAt]);
const durationLabel = formatElapsed(props.startedAt, new Date(nowMs).toISOString()) ?? "0s";
return (
<View className="mb-4 flex-row items-center gap-2 px-1.5 py-1">
<View className="flex-row items-center gap-1">
<View className="h-1 w-1 rounded-full bg-neutral-400 dark:bg-neutral-500" />
<View className="h-1 w-1 rounded-full bg-neutral-400/80 dark:bg-neutral-500/80" />
<View className="h-1 w-1 rounded-full bg-neutral-400/60 dark:bg-neutral-500/60" />
</View>
<Text className="font-t3-medium text-xs tabular-nums text-neutral-600 dark:text-neutral-400">
Working for {durationLabel}
</Text>
</View>
);
});
function UserMessageContent(props: {
readonly text: string;
readonly markdownStyles: MarkdownStyleSet;
@@ -1447,15 +1415,8 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
props.latestTurn,
expandedTurnIds,
expandedWorkGroupIds,
props.activeWorkStartedAt,
),
[
expandedTurnIds,
expandedWorkGroupIds,
props.activeWorkStartedAt,
props.feed,
props.latestTurn,
],
[expandedTurnIds, expandedWorkGroupIds, props.feed, props.latestTurn],
);
// The empty↔filled key below remounts the list, which resets its imperative
@@ -1800,9 +1761,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
}}
/>
</View>
{props.feed.length === 0 &&
props.activeWorkStartedAt === null &&
props.contentPresentation.kind === "ready" ? (
{props.feed.length === 0 && props.contentPresentation.kind === "ready" ? (
<View pointerEvents="none" style={StyleSheet.absoluteFill}>
<ThreadFeedPlaceholder
title="No conversation yet"
@@ -5,12 +5,9 @@ import type {
} from "@t3tools/client-runtime/state/shell";
import { LegendList } from "@legendapp/list/react-native";
import type { MenuAction } from "@react-native-menu/menu";
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 { useCallback, useMemo, useRef, useState, type ReactNode } from "react";
import type { LayoutChangeEvent, NativeScrollEvent, NativeSyntheticEvent } from "react-native";
import { Platform, Pressable, StyleSheet, TextInput, View, useColorScheme } from "react-native";
import { Platform, 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";
@@ -25,14 +22,13 @@ import { NativeStackScreenOptions } from "../../native/StackHeader";
import { scopedProjectKey, scopedThreadKey } from "../../lib/scopedEntities";
import { useThemeColor } from "../../lib/useThemeColor";
import { useProjects, useThreadShells } from "../../state/entities";
import { mobilePreferencesAtom } from "../../state/preferences";
import { environmentServerConfigsAtom } from "../../state/server";
import { usePendingNewTasks, type PendingNewTask } from "../../state/use-pending-new-tasks";
import { usePendingNewTasks } 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,
@@ -47,7 +43,7 @@ import {
type HomeGroupDisplayState,
type HomeListItem,
} from "../home/homeListItems";
import { buildHomeProjectScopes, buildHomeThreadGroups } from "../home/homeThreadList";
import { buildHomeThreadGroups } from "../home/homeThreadList";
import { SwipeableScrollGateProvider, useSwipeableScrollGate } from "../home/thread-swipe-actions";
import { usePendingTaskListActions } from "../home/usePendingTaskListActions";
import { useThreadListActions } from "../home/useThreadListActions";
@@ -63,27 +59,6 @@ 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
@@ -194,12 +169,7 @@ function ThreadNavigationSidebarPane(
const openSwipeableRef = useRef<SwipeableMethods | null>(null);
const headerIsOverContentRef = useRef(false);
const sidebarScrollGesture = useMemo(() => Gesture.Native(), []);
const { archiveThread, confirmDeleteThread, settleThread, unsettleThread } =
useThreadListActions();
const preferencesResult = useAtomValue(mobilePreferencesAtom);
const threadListV2Enabled =
AsyncResult.isSuccess(preferencesResult) &&
preferencesResult.value.threadListV2Enabled === true;
const { archiveThread, confirmDeleteThread } = useThreadListActions();
const pendingTasks = usePendingNewTasks();
const { openPendingTask, confirmDeletePendingTask } = usePendingTaskListActions();
const environments = useMemo(
@@ -216,94 +186,26 @@ function ThreadNavigationSidebarPane(
() => new Set(environments.map((environment) => environment.environmentId)),
[environments],
);
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 {
options,
setSelectedEnvironmentId,
setProjectGroupingMode,
setProjectSortOrder,
setThreadSortOrder,
} = useHomeListOptions(availableEnvironmentIds);
const groups = useMemo(
() =>
buildHomeThreadGroups({
projects: scopedProjects,
threads: scopedThreads,
pendingTasks: scopedPendingTasks,
projects,
threads,
pendingTasks,
environmentId: options.selectedEnvironmentId,
searchQuery: props.searchQuery,
projectSortOrder: options.projectSortOrder,
threadSortOrder: options.threadSortOrder,
projectGroupingMode: options.projectGroupingMode,
}),
[options, props.searchQuery, scopedPendingTasks, scopedProjects, scopedThreads],
[options, pendingTasks, projects, props.searchQuery, threads],
);
const [groupDisplayStates, setGroupDisplayStates] = useState<
ReadonlyMap<string, HomeGroupDisplayState>
@@ -335,148 +237,6 @@ 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[]>(
() => [
@@ -500,54 +260,36 @@ function ThreadNavigationSidebarPane(
})),
],
},
...(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[])),
{
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",
})),
},
],
[environments, options, projectFilterOptions, selectedProjectKey, threadListV2Enabled],
[environments, options],
);
const handleListMenuAction = useCallback(
({ nativeEvent }: { readonly nativeEvent: { readonly event: string } }) => {
@@ -563,17 +305,6 @@ 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,
);
@@ -588,10 +319,14 @@ function ThreadNavigationSidebarPane(
setThreadSortOrder(threadSort.value);
return;
}
const grouping = PROJECT_GROUPING_OPTIONS.find(
(option) => `project-grouping:${option.value}` === event,
);
if (grouping) setProjectGroupingMode(grouping.value);
},
[
environments,
projectFilterOptions,
setProjectGroupingMode,
setProjectSortOrder,
setSelectedEnvironmentId,
setThreadSortOrder,
@@ -647,44 +382,7 @@ function ThreadNavigationSidebarPane(
onScroll: handleScroll,
onScrollBeginDrag: handleScrollBeginDrag,
});
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 listExtraData = props.selectedThreadKey ?? "";
const focusSearch = useCallback(() => {
const focus = () => {
if (props.nativeChrome) {
@@ -703,78 +401,8 @@ function ThreadNavigationSidebarPane(
}, [props.nativeChrome, props.onRequestVisibility, props.visible]);
useHardwareKeyboardCommand("focusSearch", focusSearch);
const renderListItem = useCallback(
({ item }: { readonly item: SidebarListItem }) => {
({ item }: { readonly item: HomeListItem }) => {
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
@@ -850,58 +478,42 @@ 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,
],
);
// 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
const filterIcon = hasCustomHomeListOptions(options)
? "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,
listOrganization: !threadListV2Enabled,
onProjectGroupingModeChange: setProjectGroupingMode,
}),
[
environments,
options,
projectFilterOptions,
selectedProjectKey,
setProjectGroupingMode,
setProjectSortOrder,
setSelectedEnvironmentId,
setThreadSortOrder,
threadListV2Enabled,
],
);
const nativeHeaderItems = useMemo(
@@ -919,9 +531,7 @@ function ThreadNavigationSidebarPane(
? "Loading threads…"
: props.searchQuery.trim().length > 0
? "No matching threads"
: selectedProjectScope !== null
? `No threads in ${selectedProjectScope.title}`
: "No threads yet"}
: "No threads yet"}
</Text>
);
@@ -929,7 +539,6 @@ function ThreadNavigationSidebarPane(
return (
<>
<NativeStackScreenOptions
optionsVersion={nativeHeaderItems}
options={{
headerSearchBarOptions: {
ref: searchBarRef,
@@ -955,12 +564,12 @@ function ThreadNavigationSidebarPane(
<SwipeableScrollGateProvider enabled={swipeEnabled}>
<GestureDetector gesture={sidebarScrollGesture}>
<LegendList
data={listItems}
data={listLayout.items}
drawDistance={500}
estimatedItemSize={64}
extraData={listExtraData}
getItemType={(item) => item.type}
itemsAreEqual={sidebarItemsAreEqual}
itemsAreEqual={homeListItemsAreEqual}
keyExtractor={(item) => item.key}
renderItem={renderListItem}
automaticallyAdjustsScrollIndicatorInsets={NATIVE_LIQUID_GLASS_SUPPORTED}
@@ -1016,12 +625,12 @@ function ThreadNavigationSidebarPane(
<SwipeableScrollGateProvider enabled={swipeEnabled}>
<GestureDetector gesture={sidebarScrollGesture}>
<LegendList
data={listItems}
data={listLayout.items}
drawDistance={500}
estimatedItemSize={64}
extraData={listExtraData}
getItemType={(item) => item.type}
itemsAreEqual={sidebarItemsAreEqual}
itemsAreEqual={homeListItemsAreEqual}
keyExtractor={(item) => item.key}
renderItem={renderListItem}
contentContainerStyle={[
@@ -19,10 +19,8 @@ import { ThreadSwipeable } from "../home/thread-swipe-actions";
import { resolveThreadListV2Status, type ThreadListV2Status } from "./threadListV2";
/**
* 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.
* Thread List v2 rows mirror the web sidebar's compact tonal cards and
* receded settled tail while retaining native swipe and long-press actions.
*/
const MONO_FONT = Platform.select({
@@ -31,15 +29,12 @@ 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-indigo-600 dark:text-indigo-300" },
working: { label: "Working", className: "text-sky-600 dark:text-sky-400" },
input: { label: "Input", className: "text-amber-700 dark:text-amber-300" },
working: { label: "Working", className: "text-blue-600 dark:text-blue-400" },
failed: { label: "Failed", className: "text-red-700 dark:text-red-300" },
};
@@ -65,20 +60,10 @@ const LEGACY_MENU_ACTIONS: MenuAction[] = [
{ id: "delete", title: "Delete", image: "trash", attributes: { destructive: true } },
];
/** 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";
}) {
export const ThreadListV2SettledDivider = memo(function ThreadListV2SettledDivider() {
const borderColor = useThemeColor("--color-border");
return (
<View
className={cn(
"mb-1.5 mt-4 flex-row items-center gap-2.5",
props.pane === "sidebar" ? "px-3" : "px-5",
)}
>
<View className="mb-1.5 mt-4 flex-row items-center gap-2.5 px-5">
<Text className="text-xs font-t3-medium text-foreground-tertiary">Settled</Text>
<View className="h-px flex-1" style={{ backgroundColor: borderColor }} />
</View>
@@ -91,22 +76,6 @@ 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;
@@ -148,11 +117,6 @@ 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];
@@ -210,184 +174,99 @@ 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={
sidebarPane
? ({ pressed }) => ({
backgroundColor: selected
? selectedBackgroundColor
: pressed
? pressedBackgroundColor
: drawerColor,
borderRadius: SIDEBAR_V2_ROW_RADIUS,
paddingHorizontal: 12,
paddingVertical: 10,
})
: ({ pressed }) => ({ opacity: pressed ? 0.7 : 1 })
}
style={({ pressed }) => ({ opacity: pressed ? 0.7 : 1 })}
>
{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 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>
</View>
)}
</View>
</Pressable>
) : (
<Pressable
accessibilityHint={`Opens the thread. Swipe left to ${primaryAction.label.toLowerCase()}.`}
accessibilityLabel={thread.title}
accessibilityRole="button"
accessibilityState={{ selected }}
className={sidebarPane ? undefined : "bg-screen"}
className="bg-screen"
onPress={() => {
close();
onSelectThread(thread);
}}
style={
sidebarPane
? ({ pressed }) => ({
backgroundColor: selected
? selectedBackgroundColor
: pressed
? pressedBackgroundColor
: drawerColor,
borderRadius: SIDEBAR_V2_ROW_RADIUS,
})
: ({ pressed }) => ({ opacity: pressed ? 0.7 : 1 })
}
style={({ pressed }) => ({ opacity: pressed ? 0.7 : 1 })}
>
{/* Settled history recedes: dimmed favicon + muted title. */}
<View
className={cn(
"min-h-[44px] flex-row items-center gap-2.5 py-2",
sidebarPane ? "px-3" : "px-5",
)}
>
<View className="min-h-[44px] flex-row items-center gap-2.5 px-5 py-2">
{props.project ? (
<View className="opacity-40">
<ProjectFavicon
@@ -398,20 +277,11 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
/>
</View>
) : null}
<Text
className={cn(
"flex-1 text-base",
selected ? "text-user-bubble-foreground" : "text-foreground-muted",
)}
numberOfLines={1}
>
<Text className="flex-1 text-base text-foreground-muted" numberOfLines={1}>
{thread.title}
</Text>
<Text
className={cn(
"text-sm tabular-nums",
selected ? "text-user-bubble-foreground-muted" : "text-foreground-tertiary",
)}
className="text-sm tabular-nums text-foreground-tertiary"
style={{ fontFamily: MONO_FONT }}
>
{relativeTime(thread.latestUserMessageAt ?? thread.updatedAt ?? thread.createdAt)}
@@ -422,18 +292,14 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
return (
<>
{props.showSettledDivider ? <ThreadListV2SettledDivider pane={props.pane} /> : null}
{props.showSettledDivider ? <ThreadListV2SettledDivider /> : null}
<ThreadSwipeable
backgroundColor={sidebarPane ? drawerColor : screenColor}
compactActions={variant === "slim"}
containerStyle={
sidebarPane ? { borderRadius: SIDEBAR_V2_ROW_RADIUS, overflow: "hidden" } : undefined
}
backgroundColor={screenColor}
enableTrackpadSwipe
// Full swipe commits the advertised lifecycle action (Settle /
// Un-settle), never the destructive delete.
fullSwipeAction="primary"
fullSwipeWidth={props.fullSwipeWidth ?? windowWidth - 32}
fullSwipeWidth={windowWidth - 32}
onDelete={handleDelete}
onSwipeableClose={props.onSwipeableClose}
onSwipeableWillOpen={props.onSwipeableWillOpen}
@@ -166,36 +166,13 @@ describe("buildThreadListV2Items", () => {
}),
],
environmentId: null,
projectRefs: [{ environmentId, projectId: ProjectId.make("project-1") }],
projectRef: { 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,12 +12,6 @@ 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 {
@@ -95,10 +89,10 @@ export interface ThreadListV2Layout {
export function buildThreadListV2Items(input: {
readonly threads: ReadonlyArray<EnvironmentThreadShell>;
readonly environmentId: EnvironmentId | null;
readonly projectRefs?: ReadonlyArray<{
readonly projectRef?: {
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">;
@@ -115,9 +109,6 @@ 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[] = [];
@@ -125,7 +116,11 @@ 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 (projectKeys !== null && !projectKeys.has(`${thread.environmentId}:${thread.projectId}`)) {
if (
input.projectRef != null &&
(thread.environmentId !== input.projectRef.environmentId ||
thread.projectId !== input.projectRef.projectId)
) {
continue;
}
if (query.length > 0 && !thread.title.toLocaleLowerCase().includes(query)) continue;
@@ -414,20 +414,6 @@ describe("buildThreadFeed", () => {
});
});
it("appends active work as a normal timeline row", () => {
const startedAt = "2026-04-01T00:00:01.000Z";
const presented = deriveThreadFeedPresentation([], null, new Set(), new Set(), startedAt);
expect(presented).toEqual([
{
type: "working",
id: "working-indicator-row",
createdAt: startedAt,
},
]);
expect(deriveThreadFeedPresentation(presented, null, new Set())).toEqual([]);
});
it("models work-log overflow as list rows", () => {
const activity = (
id: string,
+2 -16
View File
@@ -98,11 +98,6 @@ type RawThreadFeedEntry =
export type ThreadFeedEntry =
| Extract<RawThreadFeedEntry, { type: "message" }>
| {
readonly type: "working";
readonly id: string;
readonly createdAt: string;
}
| {
readonly type: "activity-group";
readonly id: string;
@@ -1110,11 +1105,9 @@ export function deriveThreadFeedPresentation(
latestTurn: ThreadFeedLatestTurn | null,
expandedTurnIds: ReadonlySet<TurnId>,
expandedWorkGroupIds: ReadonlySet<string> = new Set(),
activeWorkStartedAt: string | null = null,
): ThreadFeedEntry[] {
const sourceFeed = feed.filter(
(entry) =>
entry.type !== "turn-fold" && entry.type !== "work-toggle" && entry.type !== "working",
(entry) => entry.type !== "turn-fold" && entry.type !== "work-toggle",
);
const foldsByAnchorId = deriveThreadFeedTurnFolds(sourceFeed, latestTurn);
const collapsedEntryIds = new Set<string>();
@@ -1143,19 +1136,12 @@ export function deriveThreadFeedPresentation(
appendPresentedFeedEntry(result, entry, expandedWorkGroupIds);
}
}
if (activeWorkStartedAt !== null) {
result.push({
type: "working",
id: "working-indicator-row",
createdAt: activeWorkStartedAt,
});
}
return result;
}
function appendPresentedFeedEntry(
result: ThreadFeedEntry[],
entry: Exclude<ThreadFeedEntry, { readonly type: "turn-fold" | "work-toggle" | "working" }>,
entry: Exclude<ThreadFeedEntry, { readonly type: "turn-fold" | "work-toggle" }>,
expandedWorkGroupIds: ReadonlySet<string>,
): void {
if (entry.type !== "activity-group") {
+2 -9
View File
@@ -142,13 +142,6 @@ 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;
}) {
@@ -170,7 +163,7 @@ export function NativeStackScreenOptions(props: {
if (!navigation || !stableOptions) {
return;
}
const signature = optionsSignature([stableOptions, props.optionsVersion]);
const signature = optionsSignature(stableOptions);
// Avoid re-entering navigation state when semantically equal options are
// reapplied every layout (common when callers pass unstable object literals).
if (lastAppliedOptionsSignatureRef.current === signature) {
@@ -178,7 +171,7 @@ export function NativeStackScreenOptions(props: {
}
lastAppliedOptionsSignatureRef.current = signature;
navigation.setOptions(stableOptions);
}, [navigation, props.optionsVersion, stableOptions]);
}, [navigation, stableOptions]);
useEffect(() => {
if (!navigation || !props.listeners) {
@@ -22,7 +22,6 @@ 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
@@ -78,7 +77,6 @@ function sanitizePreferences(parsed: Preferences): Preferences {
codeWordBreak?: boolean;
connectOnboardingOptOutAccounts?: ReadonlyArray<string>;
collapsedProjectGroups?: readonly string[];
projectGroupingEnabled?: boolean;
threadListV2Enabled?: boolean;
} = {};
@@ -106,9 +104,6 @@ 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;
}
+1 -5
View File
@@ -11,7 +11,6 @@ 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";
@@ -21,10 +20,7 @@ const configLayer = ServerConfig.ServerConfig.layerTest(process.cwd(), {
const testLayer = Layer.mergeAll(
configLayer,
WorkspacePaths.layer,
ProjectFaviconResolver.layer.pipe(
Layer.provide(WorkspacePaths.layer),
Layer.provide(T3ProjectFileLoader.layer),
),
ProjectFaviconResolver.layer.pipe(Layer.provide(WorkspacePaths.layer)),
ServerSecretStore.layer.pipe(Layer.provide(configLayer)),
).pipe(Layer.provideMerge(NodeServices.layer));
+1 -16
View File
@@ -202,18 +202,6 @@ 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(
@@ -317,10 +305,7 @@ it.layer(NodeServices.layer)("bin cli parsing", (it) => {
runConnectCli(["connect", "logout", "--base-dir", baseDir]),
);
assert.equal(
output,
"Signed out of T3 Connect locally.\nThe background service is managed separately with `t3 service`.",
);
assert.equal(output, "Signed out of T3 Connect locally.");
assert.isFalse(NodeFS.existsSync(tokenPath));
}),
);
-2
View File
@@ -13,7 +13,6 @@ 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);
@@ -48,7 +47,6 @@ export const makeCli = ({ cloudEnabled = hasCloudPublicConfig } = {}) =>
serveCommand,
authCommand,
projectCommand,
serviceCommand,
cloudEnabled ? connectCommand : connectUnavailableCommand,
]),
);
@@ -69,7 +69,6 @@ describe("CheckpointDiffQuery.layer", () => {
return "full thread diff patch";
}),
deleteCheckpointRefs: () => Effect.void,
attributeCheckpointDiff: () => Effect.succeed(null),
};
const layer = CheckpointDiffQuery.layer.pipe(
@@ -178,7 +177,6 @@ describe("CheckpointDiffQuery.layer", () => {
return "diff patch";
}),
deleteCheckpointRefs: () => Effect.void,
attributeCheckpointDiff: () => Effect.succeed(null),
};
const layer = CheckpointDiffQuery.layer.pipe(
@@ -262,7 +260,6 @@ describe("CheckpointDiffQuery.layer", () => {
return "diff patch";
}),
deleteCheckpointRefs: () => Effect.void,
attributeCheckpointDiff: () => Effect.succeed(null),
};
const layer = CheckpointDiffQuery.layer.pipe(
@@ -304,102 +301,6 @@ describe("CheckpointDiffQuery.layer", () => {
}),
);
it.effect("filters git-attributed sections and reports gitFileCount from patch sections", () =>
Effect.gen(function* () {
const projectId = ProjectId.make("project-attribution");
const threadId = ThreadId.make("thread-attribution");
const toCheckpointRef = checkpointRefForThreadTurn(threadId, 1);
const patch = [
"diff --git a/agent.ts b/agent.ts",
"index 1111111..2222222 100644",
"--- a/agent.ts",
"+++ b/agent.ts",
"@@ -1,1 +1,1 @@",
"-old",
"+new",
"diff --git a/pulled.ts b/pulled.ts",
"index 3333333..4444444 100644",
"--- a/pulled.ts",
"+++ b/pulled.ts",
"@@ -1,1 +1,1 @@",
"-before",
"+after",
"",
].join("\n");
// Attribution also tags a path that has no section in this patch
// (e.g. whitespace-only change elided by ignoreWhitespace) — it must
// not count toward gitFileCount.
const attribution = new Map<string, "agent" | "git">([
["agent.ts", "agent"],
["pulled.ts", "git"],
["whitespace-only.ts", "git"],
]);
const threadCheckpointContext = makeThreadCheckpointContext({
projectId,
threadId,
workspaceRoot: "/tmp/workspace",
worktreePath: null,
checkpointTurnCount: 1,
checkpointRef: toCheckpointRef,
});
const checkpointStore: CheckpointStore.CheckpointStore["Service"] = {
isGitRepository: () => Effect.succeed(true),
captureCheckpoint: () => Effect.void,
hasCheckpointRef: () => Effect.succeed(true),
restoreCheckpoint: () => Effect.succeed(true),
diffCheckpoints: () => Effect.succeed(patch),
deleteCheckpointRefs: () => Effect.void,
attributeCheckpointDiff: () => Effect.succeed(attribution),
};
const layer = CheckpointDiffQuery.layer.pipe(
Layer.provideMerge(Layer.succeed(CheckpointStore.CheckpointStore, checkpointStore)),
Layer.provideMerge(
Layer.succeed(ProjectionSnapshotQuery.ProjectionSnapshotQuery, {
getCommandReadModel: () => Effect.die("unused"),
getSnapshot: () => Effect.die("unused"),
getShellSnapshot: () => Effect.die("unused"),
getArchivedShellSnapshot: () => Effect.die("unused"),
getSnapshotSequence: () => Effect.succeed({ snapshotSequence: 0 }),
getCounts: () => Effect.succeed({ projectCount: 0, threadCount: 0 }),
getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()),
getProjectShellById: () => Effect.succeed(Option.none()),
getFirstActiveThreadIdByProjectId: () => Effect.succeed(Option.none()),
getThreadCheckpointContext: () => Effect.succeed(Option.some(threadCheckpointContext)),
getFullThreadDiffContext: () => Effect.die("unused"),
getThreadShellById: () => Effect.succeed(Option.none()),
getThreadDetailById: () => Effect.succeed(Option.none()),
getThreadDetailSnapshot: () => Effect.succeed(Option.none()),
}),
),
);
const { filtered, revealed } = yield* Effect.gen(function* () {
const query = yield* CheckpointDiffQuery.CheckpointDiffQuery;
const filtered = yield* query.getTurnDiff({
threadId,
fromTurnCount: 0,
toTurnCount: 1,
});
const revealed = yield* query.getTurnDiff({
threadId,
fromTurnCount: 0,
toTurnCount: 1,
includeGitChanges: true,
});
return { filtered, revealed };
}).pipe(Effect.provide(layer));
expect(filtered.diff).toContain("agent.ts");
expect(filtered.diff).not.toContain("pulled.ts");
expect(filtered.gitFileCount).toBe(1);
expect(revealed.diff).toBe(patch);
expect(revealed.gitFileCount).toBe(1);
}),
);
it.effect("does not preflight checkpoint refs before diffing", () =>
Effect.gen(function* () {
const projectId = ProjectId.make("project-no-preflight");
@@ -427,7 +328,6 @@ describe("CheckpointDiffQuery.layer", () => {
restoreCheckpoint: () => Effect.succeed(true),
diffCheckpoints: () => Effect.succeed("diff patch"),
deleteCheckpointRefs: () => Effect.void,
attributeCheckpointDiff: () => Effect.succeed(null),
};
const layer = CheckpointDiffQuery.layer.pipe(
@@ -481,7 +381,6 @@ describe("CheckpointDiffQuery.layer", () => {
restoreCheckpoint: () => Effect.succeed(true),
diffCheckpoints: () => Effect.succeed(""),
deleteCheckpointRefs: () => Effect.void,
attributeCheckpointDiff: () => Effect.succeed(null),
};
const layer = CheckpointDiffQuery.layer.pipe(
@@ -31,7 +31,6 @@ import {
} from "./Errors.ts";
import type { CheckpointServiceError } from "./Errors.ts";
import { checkpointRefForThreadTurn } from "./Utils.ts";
import { filterUnifiedDiffFiles, listUnifiedDiffPaths } from "./Diffs.ts";
import * as CheckpointStore from "./CheckpointStore.ts";
/** Service tag for checkpoint diff queries. */
@@ -67,14 +66,12 @@ function buildTurnDiffResult(
readonly toTurnCount: number;
},
diff: string,
gitFileCount?: number,
): OrchestrationGetTurnDiffResultType {
return {
threadId: input.threadId,
fromTurnCount: input.fromTurnCount,
toTurnCount: input.toTurnCount,
diff,
...(gitFileCount !== undefined ? { gitFileCount } : {}),
};
}
@@ -82,51 +79,6 @@ export const make = Effect.gen(function* () {
const projectionSnapshotQuery = yield* ProjectionSnapshotQuery.ProjectionSnapshotQuery;
const checkpointStore = yield* CheckpointStore.CheckpointStore;
// Drop file sections attributed to pre-existing git history from a patch
// unless the caller opted in. Attribution failures degrade to the
// unfiltered patch — never block the diff on attribution. The returned
// gitFileCount comes from the SAME attribution pass that produced the
// patch, so UI driven by it always agrees with what is rendered;
// undefined means attribution was unavailable and nothing was filtered.
const applyAttributionFilter = Effect.fn("applyAttributionFilter")(function* (input: {
readonly cwd: string;
readonly fromCheckpointRef: CheckpointRef;
readonly toCheckpointRef: CheckpointRef;
readonly diff: string;
readonly includeGitChanges: boolean;
}): Effect.fn.Return<{ readonly diff: string; readonly gitFileCount: number | undefined }> {
if (input.diff.trim().length === 0) {
return { diff: input.diff, gitFileCount: undefined };
}
const attribution = yield* checkpointStore
.attributeCheckpointDiff({
cwd: input.cwd,
fromCheckpointRef: input.fromCheckpointRef,
toCheckpointRef: input.toCheckpointRef,
})
.pipe(Effect.catch(() => Effect.succeed(null)));
if (attribution === null) {
return { diff: input.diff, gitFileCount: undefined };
}
// Count only git-attributed paths with a section in THIS patch. The
// attribution map can include paths absent from the patch (e.g.
// whitespace-only changes elided by ignoreWhitespace) — counting those
// would advertise hidden files the toggle can never reveal.
let gitFileCount = 0;
for (const path of listUnifiedDiffPaths(input.diff)) {
if (attribution.get(path) === "git") {
gitFileCount += 1;
}
}
if (input.includeGitChanges || gitFileCount === 0) {
return { diff: input.diff, gitFileCount };
}
return {
diff: filterUnifiedDiffFiles(input.diff, (path) => attribution.get(path) !== "git"),
gitFileCount,
};
});
const getTurnDiff: CheckpointDiffQuery["Service"]["getTurnDiff"] = Effect.fn("getTurnDiff")(
function* (input) {
const operation = "CheckpointDiffQuery.getTurnDiff";
@@ -212,7 +164,7 @@ export const make = Effect.gen(function* () {
});
}
const rawDiff = yield* checkpointStore
const diff = yield* checkpointStore
.diffCheckpoints({
cwd: workspaceCwd,
fromCheckpointRef,
@@ -221,15 +173,8 @@ export const make = Effect.gen(function* () {
ignoreWhitespace,
})
.pipe(Effect.withSpan("checkpoint.turnDiff.diffCheckpoints"));
const filtered = yield* applyAttributionFilter({
cwd: workspaceCwd,
fromCheckpointRef,
toCheckpointRef,
diff: rawDiff,
includeGitChanges: input.includeGitChanges ?? false,
});
const turnDiff = buildTurnDiffResult(input, filtered.diff, filtered.gitFileCount);
const turnDiff = buildTurnDiffResult(input, diff);
if (!isTurnDiffResult(turnDiff)) {
return yield* new CheckpointDiffResultInvalidError({
operation,
@@ -309,24 +254,15 @@ export const make = Effect.gen(function* () {
});
}
const fromCheckpointRef = checkpointRefForThreadTurn(input.threadId, 0);
const toCheckpointRef = threadContext.value.toCheckpointRef as CheckpointRef;
const rawDiff = yield* checkpointStore
const diff = yield* checkpointStore
.diffCheckpoints({
cwd: workspaceCwd,
fromCheckpointRef,
toCheckpointRef,
fromCheckpointRef: checkpointRefForThreadTurn(input.threadId, 0),
toCheckpointRef: threadContext.value.toCheckpointRef as CheckpointRef,
fallbackFromToHead: false,
ignoreWhitespace,
})
.pipe(Effect.withSpan("checkpoint.fullThread.diffCheckpoints"));
const filtered = yield* applyAttributionFilter({
cwd: workspaceCwd,
fromCheckpointRef,
toCheckpointRef,
diff: rawDiff,
includeGitChanges: input.includeGitChanges ?? false,
});
const turnDiff = buildTurnDiffResult(
{
@@ -334,8 +270,7 @@ export const make = Effect.gen(function* () {
fromTurnCount: 0,
toTurnCount: input.toTurnCount,
},
filtered.diff,
filtered.gitFileCount,
diff,
);
if (!isTurnDiffResult(turnDiff)) {
return yield* new CheckpointDiffResultInvalidError({
@@ -55,7 +55,6 @@ function writeTextFile(
function git(
cwd: string,
args: ReadonlyArray<string>,
env?: NodeJS.ProcessEnv,
): Effect.Effect<string, VcsError, VcsProcess.VcsProcess> {
return Effect.gen(function* () {
const process = yield* VcsProcess.VcsProcess;
@@ -64,19 +63,12 @@ function git(
command: "git",
cwd,
args,
...(env ? { env: { ...global.process.env, ...env } } : {}),
timeoutMs: 10_000,
});
return result.stdout.trim();
});
}
/** Author and committer dates both in the past: a genuinely pre-existing commit. */
const PRE_EXISTING_COMMIT_ENV: NodeJS.ProcessEnv = {
GIT_AUTHOR_DATE: "2020-01-01T00:00:00Z",
GIT_COMMITTER_DATE: "2020-01-01T00:00:00Z",
};
function initRepoWithCommit(
cwd: string,
): Effect.Effect<
@@ -230,237 +222,4 @@ it.layer(TestLayer)("CheckpointStore.layer", (it) => {
}),
);
});
describe("attributeCheckpointDiff", () => {
it.effect("returns an empty map when HEAD did not move", () =>
Effect.gen(function* () {
const tmp = yield* makeTmpDir();
yield* initRepoWithCommit(tmp);
const checkpointStore = yield* CheckpointStore.CheckpointStore;
const threadId = ThreadId.make("thread-attr-no-head-move");
const fromCheckpointRef = checkpointRefForThreadTurn(threadId, 0);
const toCheckpointRef = checkpointRefForThreadTurn(threadId, 1);
yield* checkpointStore.captureCheckpoint({ cwd: tmp, checkpointRef: fromCheckpointRef });
yield* writeTextFile(NodePath.join(tmp, "edited.ts"), "export const edited = true;\n");
yield* checkpointStore.captureCheckpoint({ cwd: tmp, checkpointRef: toCheckpointRef });
const attribution = yield* checkpointStore.attributeCheckpointDiff({
cwd: tmp,
fromCheckpointRef,
toCheckpointRef,
});
expect(attribution).not.toBe(null);
expect(attribution!.size).toBe(0);
}),
);
it.effect("attributes a branch switch to git while keeping tool edits as agent work", () =>
Effect.gen(function* () {
const tmp = yield* makeTmpDir();
yield* initRepoWithCommit(tmp);
const defaultBranch = yield* git(tmp, ["rev-parse", "--abbrev-ref", "HEAD"]);
// A second branch with a pre-existing commit, created before the turn.
yield* git(tmp, ["checkout", "-b", "feature"]);
yield* writeTextFile(NodePath.join(tmp, "feature.ts"), "export const feature = 1;\n");
yield* git(tmp, ["add", "."]);
yield* git(tmp, ["commit", "-m", "feature work"], PRE_EXISTING_COMMIT_ENV);
yield* git(tmp, ["checkout", defaultBranch]);
const checkpointStore = yield* CheckpointStore.CheckpointStore;
const threadId = ThreadId.make("thread-attr-branch-switch");
const fromCheckpointRef = checkpointRefForThreadTurn(threadId, 0);
const toCheckpointRef = checkpointRefForThreadTurn(threadId, 1);
yield* checkpointStore.captureCheckpoint({ cwd: tmp, checkpointRef: fromCheckpointRef });
// The "turn": switch branches (history-driven) and also edit a file.
yield* git(tmp, ["checkout", "feature"]);
yield* writeTextFile(NodePath.join(tmp, "edited.ts"), "export const edited = true;\n");
yield* checkpointStore.captureCheckpoint({ cwd: tmp, checkpointRef: toCheckpointRef });
const attribution = yield* checkpointStore.attributeCheckpointDiff({
cwd: tmp,
fromCheckpointRef,
toCheckpointRef,
});
expect(attribution).not.toBe(null);
expect(attribution!.get("feature.ts")).toBe("git");
expect(attribution!.get("edited.ts")).toBe("agent");
}),
);
it.effect("keeps files committed during the turn as agent work", () =>
Effect.gen(function* () {
const tmp = yield* makeTmpDir();
yield* initRepoWithCommit(tmp);
const checkpointStore = yield* CheckpointStore.CheckpointStore;
const threadId = ThreadId.make("thread-attr-own-commit");
const fromCheckpointRef = checkpointRefForThreadTurn(threadId, 0);
const toCheckpointRef = checkpointRefForThreadTurn(threadId, 1);
yield* checkpointStore.captureCheckpoint({ cwd: tmp, checkpointRef: fromCheckpointRef });
// The "turn": edit and commit — HEAD moves, but by a turn-authored commit.
yield* writeTextFile(NodePath.join(tmp, "committed.ts"), "export const done = true;\n");
yield* git(tmp, ["add", "."]);
yield* git(tmp, ["commit", "-m", "agent commit"]);
yield* checkpointStore.captureCheckpoint({ cwd: tmp, checkpointRef: toCheckpointRef });
const attribution = yield* checkpointStore.attributeCheckpointDiff({
cwd: tmp,
fromCheckpointRef,
toCheckpointRef,
});
expect(attribution).not.toBe(null);
expect(attribution!.get("committed.ts")).toBe("agent");
}),
);
it.effect("attributes a cherry-pick of a pre-existing commit to git", () =>
Effect.gen(function* () {
const tmp = yield* makeTmpDir();
yield* initRepoWithCommit(tmp);
const defaultBranch = yield* git(tmp, ["rev-parse", "--abbrev-ref", "HEAD"]);
// Pre-existing commit on another branch, authored before the turn.
yield* git(tmp, ["checkout", "-b", "source"]);
yield* writeTextFile(NodePath.join(tmp, "picked.ts"), "export const picked = 1;\n");
yield* git(tmp, ["add", "."]);
yield* git(
tmp,
[
"-c",
"[email protected]",
"-c",
"user.name=Other",
"commit",
"-m",
"source work",
],
PRE_EXISTING_COMMIT_ENV,
);
const pickedOid = yield* git(tmp, ["rev-parse", "HEAD"]);
yield* git(tmp, ["checkout", defaultBranch]);
const checkpointStore = yield* CheckpointStore.CheckpointStore;
const threadId = ThreadId.make("thread-attr-cherry-pick");
const fromCheckpointRef = checkpointRefForThreadTurn(threadId, 0);
const toCheckpointRef = checkpointRefForThreadTurn(threadId, 1);
yield* checkpointStore.captureCheckpoint({ cwd: tmp, checkpointRef: fromCheckpointRef });
yield* git(tmp, ["cherry-pick", pickedOid]);
yield* checkpointStore.captureCheckpoint({ cwd: tmp, checkpointRef: toCheckpointRef });
const attribution = yield* checkpointStore.attributeCheckpointDiff({
cwd: tmp,
fromCheckpointRef,
toCheckpointRef,
});
expect(attribution).not.toBe(null);
expect(attribution!.get("picked.ts")).toBe("git");
}),
);
it.effect("keeps an amend of a pre-turn commit as agent work", () =>
Effect.gen(function* () {
const tmp = yield* makeTmpDir();
yield* initRepoWithCommit(tmp);
// Pre-turn commit with an old author date, as amend preserves it.
yield* writeTextFile(NodePath.join(tmp, "amended.ts"), "export const value = 1;\n");
yield* git(tmp, ["add", "."]);
yield* git(tmp, ["commit", "-m", "pre-turn work", "--date", "2020-01-01T00:00:00Z"]);
const checkpointStore = yield* CheckpointStore.CheckpointStore;
const threadId = ThreadId.make("thread-attr-amend");
const fromCheckpointRef = checkpointRefForThreadTurn(threadId, 0);
const toCheckpointRef = checkpointRefForThreadTurn(threadId, 1);
yield* checkpointStore.captureCheckpoint({ cwd: tmp, checkpointRef: fromCheckpointRef });
// The "turn": edit the file and amend it into the pre-turn commit.
// The author date stays 2020, but the content is new agent work.
yield* writeTextFile(NodePath.join(tmp, "amended.ts"), "export const value = 2;\n");
yield* git(tmp, ["add", "."]);
yield* git(tmp, ["commit", "--amend", "--no-edit"]);
yield* checkpointStore.captureCheckpoint({ cwd: tmp, checkpointRef: toCheckpointRef });
const attribution = yield* checkpointStore.attributeCheckpointDiff({
cwd: tmp,
fromCheckpointRef,
toCheckpointRef,
});
expect(attribution).not.toBe(null);
expect(attribution!.get("amended.ts")).toBe("agent");
}),
);
it.effect("keeps a whitespace-only amend of a pre-turn commit as agent work", () =>
Effect.gen(function* () {
const tmp = yield* makeTmpDir();
yield* initRepoWithCommit(tmp);
// Pre-turn commit; its pre-amend state stays reachable via reflog,
// which is exactly the patch-id collision candidate.
yield* writeTextFile(NodePath.join(tmp, "style.ts"), "export const x = 1;\n");
yield* git(tmp, ["add", "."]);
yield* git(tmp, ["commit", "-m", "pre-turn work"], PRE_EXISTING_COMMIT_ENV);
const checkpointStore = yield* CheckpointStore.CheckpointStore;
const threadId = ThreadId.make("thread-attr-ws-amend");
const fromCheckpointRef = checkpointRefForThreadTurn(threadId, 0);
const toCheckpointRef = checkpointRefForThreadTurn(threadId, 1);
yield* checkpointStore.captureCheckpoint({ cwd: tmp, checkpointRef: fromCheckpointRef });
// The "turn": whitespace-only reformat amended into the pre-turn
// commit. `git patch-id --stable` would hash this identically to the
// original (it strips whitespace); --verbatim must not.
yield* writeTextFile(NodePath.join(tmp, "style.ts"), "export const x = 1;\n");
yield* git(tmp, ["add", "."]);
yield* git(tmp, ["commit", "--amend", "--no-edit"]);
yield* checkpointStore.captureCheckpoint({ cwd: tmp, checkpointRef: toCheckpointRef });
const attribution = yield* checkpointStore.attributeCheckpointDiff({
cwd: tmp,
fromCheckpointRef,
toCheckpointRef,
});
expect(attribution).not.toBe(null);
expect(attribution!.get("style.ts")).toBe("agent");
}),
);
it.effect("returns null for legacy checkpoints without head metadata", () =>
Effect.gen(function* () {
const tmp = yield* makeTmpDir();
yield* initRepoWithCommit(tmp);
const checkpointStore = yield* CheckpointStore.CheckpointStore;
const threadId = ThreadId.make("thread-attr-legacy");
const fromCheckpointRef = checkpointRefForThreadTurn(threadId, 0);
const toCheckpointRef = checkpointRefForThreadTurn(threadId, 1);
// Simulate a pre-attribution checkpoint: commit the tree with the old
// single-line message format.
const treeOid = yield* git(tmp, ["write-tree"]);
const legacyCommit = yield* git(tmp, [
"commit-tree",
treeOid,
"-m",
`t3 checkpoint ref=${fromCheckpointRef}`,
]);
yield* git(tmp, ["update-ref", fromCheckpointRef, legacyCommit]);
yield* writeTextFile(NodePath.join(tmp, "edited.ts"), "export const edited = true;\n");
yield* checkpointStore.captureCheckpoint({ cwd: tmp, checkpointRef: toCheckpointRef });
const attribution = yield* checkpointStore.attributeCheckpointDiff({
cwd: tmp,
fromCheckpointRef,
toCheckpointRef,
});
expect(attribution).toBe(null);
}),
);
});
});
@@ -46,18 +46,6 @@ export interface DeleteCheckpointRefsInput {
readonly checkpointRefs: ReadonlyArray<CheckpointRef>;
}
export interface AttributeCheckpointDiffInput {
readonly cwd: string;
readonly fromCheckpointRef: CheckpointRef;
readonly toCheckpointRef: CheckpointRef;
}
/**
* Per-path origin classification of a checkpoint tree delta, or null when
* attribution is unavailable (see VcsCheckpointAttribution).
*/
export type CheckpointAttribution = ReadonlyMap<string, "agent" | "git"> | null;
/** Service tag for checkpoint persistence and restore operations. */
export class CheckpointStore extends Context.Service<
CheckpointStore,
@@ -105,17 +93,6 @@ export class CheckpointStore extends Context.Service<
readonly deleteCheckpointRefs: (
input: DeleteCheckpointRefsInput,
) => Effect.Effect<void, CheckpointStoreError>;
/**
* Classify each path in a checkpoint-to-checkpoint tree delta as
* agent-authored or explained by pre-existing git history.
*
* Returns null when attribution is unavailable (legacy checkpoints
* without HEAD metadata, or truncated git output).
*/
readonly attributeCheckpointDiff: (
input: AttributeCheckpointDiffInput,
) => Effect.Effect<CheckpointAttribution, CheckpointStoreError>;
}
>()("t3/checkpointing/CheckpointStore") {}
@@ -180,16 +157,6 @@ export const make = Effect.gen(function* () {
return yield* checkpoints.deleteCheckpointRefs(input);
});
const attributeCheckpointDiff: CheckpointStore["Service"]["attributeCheckpointDiff"] = Effect.fn(
"attributeCheckpointDiff",
)(function* (input) {
const checkpoints = yield* resolveCheckpoints(
"CheckpointStore.attributeCheckpointDiff",
input.cwd,
);
return yield* checkpoints.attributeCheckpointDiff(input);
});
return CheckpointStore.of({
isGitRepository,
captureCheckpoint,
@@ -197,7 +164,6 @@ export const make = Effect.gen(function* () {
restoreCheckpoint,
diffCheckpoints,
deleteCheckpointRefs,
attributeCheckpointDiff,
});
});
+1 -157
View File
@@ -1,6 +1,6 @@
import { describe, expect, it } from "vite-plus/test";
import { filterUnifiedDiffFiles, parseTurnDiffFilesFromUnifiedDiff } from "./Diffs.ts";
import { parseTurnDiffFilesFromUnifiedDiff } from "./Diffs.ts";
describe("parseTurnDiffFilesFromUnifiedDiff", () => {
it("returns empty list for empty diff", () => {
@@ -66,159 +66,3 @@ describe("parseTurnDiffFilesFromUnifiedDiff", () => {
]);
});
});
describe("filterUnifiedDiffFiles", () => {
const twoFileDiff = [
"diff --git a/kept.ts b/kept.ts",
"index 1111111..2222222 100644",
"--- a/kept.ts",
"+++ b/kept.ts",
"@@ -1,1 +1,1 @@",
"-old",
"+new",
"diff --git a/dropped.ts b/dropped.ts",
"index 3333333..4444444 100644",
"--- a/dropped.ts",
"+++ b/dropped.ts",
"@@ -1,1 +1,1 @@",
"-before",
"+after",
"",
].join("\n");
it("removes sections whose path is rejected", () => {
const filtered = filterUnifiedDiffFiles(twoFileDiff, (path) => path !== "dropped.ts");
expect(filtered).toContain("kept.ts");
expect(filtered).not.toContain("dropped.ts");
expect(parseTurnDiffFilesFromUnifiedDiff(filtered)).toEqual([
{ path: "kept.ts", additions: 1, deletions: 1 },
]);
});
it("returns the diff unchanged when everything is kept", () => {
expect(filterUnifiedDiffFiles(twoFileDiff, () => true)).toBe(twoFileDiff);
});
it("filters deleted files via the --- a/ path", () => {
const deletionDiff = [
"diff --git a/removed.ts b/removed.ts",
"deleted file mode 100644",
"index 1111111..0000000",
"--- a/removed.ts",
"+++ /dev/null",
"@@ -1,1 +0,0 @@",
"-gone",
"",
].join("\n");
expect(filterUnifiedDiffFiles(deletionDiff, (path) => path !== "removed.ts").trim()).toBe("");
});
it("filters simple header-only sections via the diff --git header", () => {
const oddDiff = ["diff --git a/x b/x", "Binary files differ", ""].join("\n");
expect(filterUnifiedDiffFiles(oddDiff, (path) => path !== "x").trim()).toBe("");
});
it("keeps unparseable sections", () => {
const oddDiff = ["diff --git malformed-header", "Binary files differ", ""].join("\n");
expect(filterUnifiedDiffFiles(oddDiff, () => false)).toBe(oddDiff);
});
it("returns empty diff unchanged", () => {
expect(filterUnifiedDiffFiles("", () => false)).toBe("");
});
});
describe("resolveDiffSectionPath via renames", () => {
it("filters rename sections by the post-image path", () => {
const renameDiff = [
"diff --git a/old/name.ts b/new/name.ts",
"similarity index 90%",
"rename from old/name.ts",
"rename to new/name.ts",
"index 1111111..2222222 100644",
"--- a/old/name.ts",
"+++ b/new/name.ts",
"@@ -1,1 +1,1 @@",
"-before",
"+after",
"",
].join("\n");
// The attribution map is keyed by post-image paths; a filter that only
// knows the new path must still match this section.
expect(filterUnifiedDiffFiles(renameDiff, (path) => path !== "new/name.ts").trim()).toBe("");
expect(filterUnifiedDiffFiles(renameDiff, (path) => path !== "old/name.ts")).toBe(renameDiff);
});
});
describe("filterUnifiedDiffFiles fallback paths", () => {
it("filters binary sections via the diff --git header", () => {
const binaryDiff = [
"diff --git a/assets/logo.png b/assets/logo.png",
"index 1111111..2222222 100644",
"Binary files a/assets/logo.png and b/assets/logo.png differ",
"",
].join("\n");
expect(filterUnifiedDiffFiles(binaryDiff, (path) => path !== "assets/logo.png").trim()).toBe(
"",
);
expect(filterUnifiedDiffFiles(binaryDiff, () => true)).toBe(binaryDiff);
});
it("filters mode-only sections via the diff --git header", () => {
const modeDiff = [
"diff --git a/scripts/run.sh b/scripts/run.sh",
"old mode 100644",
"new mode 100755",
"",
].join("\n");
expect(filterUnifiedDiffFiles(modeDiff, (path) => path !== "scripts/run.sh").trim()).toBe("");
});
it("filters binary sections with spaces in the path", () => {
const binaryDiff = [
"diff --git a/my assets/logo file.png b/my assets/logo file.png",
"Binary files differ",
"",
].join("\n");
expect(
filterUnifiedDiffFiles(binaryDiff, (path) => path !== "my assets/logo file.png").trim(),
).toBe("");
});
it("decodes git C-style quoted paths", () => {
const quotedDiff = [
'diff --git "a/sp\\303\\244ce.ts" "b/sp\\303\\244ce.ts"',
"index 1111111..2222222 100644",
'--- "a/sp\\303\\244ce.ts"',
'+++ "b/sp\\303\\244ce.ts"',
"@@ -1,1 +1,1 @@",
"-old",
"+new",
"",
].join("\n");
// git octal-escapes the raw UTF-8 bytes (`ä` = \303\244); the decoder
// must reassemble them into the real character, not per-byte mojibake.
expect(filterUnifiedDiffFiles(quotedDiff, (path) => path !== "späce.ts").trim()).toBe("");
});
it("filters rename-only sections without hunks via rename metadata", () => {
const renameOnlyDiff = [
"diff --git a/old.ts b/new.ts",
"similarity index 100%",
"rename from old.ts",
"rename to new.ts",
"",
].join("\n");
expect(filterUnifiedDiffFiles(renameOnlyDiff, (path) => path !== "new.ts").trim()).toBe("");
expect(filterUnifiedDiffFiles(renameOnlyDiff, (path) => path !== "old.ts")).toBe(
renameOnlyDiff,
);
});
it("keeps ambiguous unquoted rename headers", () => {
// Rename of a space-containing path is ambiguous in the header when git
// does not quote; with no other metadata the section must be kept.
const ambiguous = ["diff --git a/x y b/y z", "Binary files differ", ""].join("\n");
expect(filterUnifiedDiffFiles(ambiguous, () => false)).toBe(ambiguous);
});
});
-176
View File
@@ -25,179 +25,3 @@ export function parseTurnDiffFilesFromUnifiedDiff(
return files.toSorted((left, right) => left.path.localeCompare(right.path));
}
const SIMPLE_ESCAPES: Record<string, number> = {
"\\": 0x5c,
'"': 0x22,
a: 0x07,
b: 0x08,
f: 0x0c,
n: 0x0a,
r: 0x0d,
t: 0x09,
v: 0x0b,
};
function stripGitPathQuoting(value: string): string {
if (!(value.startsWith('"') && value.endsWith('"') && value.length >= 2)) {
return value;
}
// Git C-style quoting: octal escapes are raw UTF-8 BYTES (e.g. `ä` is
// `\303\244`), so decode into a byte buffer first and UTF-8-decode the
// whole path at the end — per-escape String.fromCharCode would yield
// mojibake that never matches attribution map keys.
const inner = value.slice(1, -1);
const bytes: Array<number> = [];
const encoder = new TextEncoder();
for (let index = 0; index < inner.length; index += 1) {
const char = inner[index]!;
if (char !== "\\" || index === inner.length - 1) {
bytes.push(...encoder.encode(char));
continue;
}
const next = inner[index + 1]!;
const simple = SIMPLE_ESCAPES[next];
if (simple !== undefined) {
bytes.push(simple);
index += 1;
continue;
}
const octal = /^[0-7]{1,3}/.exec(inner.slice(index + 1))?.[0];
if (octal) {
bytes.push(parseInt(octal, 8) & 0xff);
index += octal.length;
continue;
}
bytes.push(...encoder.encode(char));
}
return new TextDecoder("utf-8", { fatal: false }).decode(new Uint8Array(bytes));
}
/**
* Parse the post-image path out of a `diff --git a/<path> b/<path>` header.
*
* Only trustworthy when both paths are quoted or the two paths are equal
* (no rename): for unquoted renamed paths containing spaces the split is
* ambiguous, so return null and let the caller keep the section.
*/
function resolveDiffGitHeaderPath(headerLine: string): string | null {
const spec = headerLine.slice("diff --git ".length).trim();
const quotedMatch = /^("(?:[^"\\]|\\.)*"|\S+) ("(?:[^"\\]|\\.)*"|\S+)$/.exec(spec);
if (quotedMatch) {
const source = stripGitPathQuoting(quotedMatch[1]!);
const target = stripGitPathQuoting(quotedMatch[2]!);
if (source.startsWith("a/") && target.startsWith("b/")) {
return target.slice(2);
}
}
// Paths with spaces are unquoted in this header; recover the symmetric
// a/X b/X form (covers everything but renames of space-containing paths).
if (spec.length % 2 === 1) {
const midpoint = (spec.length - 1) / 2;
const source = spec.slice(0, midpoint);
const target = spec.slice(midpoint + 1);
if (source.startsWith("a/") && target.startsWith("b/") && source.slice(2) === target.slice(2)) {
return target.slice(2);
}
}
return null;
}
/**
* Extract the post-image path of one `diff --git` section, preferring the
* `+++ b/` line and falling back to `--- a/` for deletions. Binary and
* mode-only sections have neither, so fall back to rename/copy metadata and
* finally the `diff --git` header itself. Returns null when the section is
* unparseable; callers should keep such sections.
*/
function resolveDiffSectionPath(section: string): string | null {
// `--- a/` precedes `+++ b/` in a section, so resolve the post-image path
// in a full pass before falling back — for renames the two differ, and the
// attribution map is keyed by the post-image path.
let fallbackSource: string | null = null;
let renameTarget: string | null = null;
let headerPath: string | null = null;
for (const line of section.split("\n")) {
if (line.startsWith("+++ ")) {
const target = stripGitPathQuoting(line.slice(4).trim());
if (target !== "/dev/null") {
return target.startsWith("b/") ? target.slice(2) : target;
}
} else if (line.startsWith("--- ") && fallbackSource === null) {
const source = stripGitPathQuoting(line.slice(4).trim());
if (source !== "/dev/null" && source.startsWith("a/")) {
fallbackSource = source.slice(2);
}
} else if (
(line.startsWith("rename to ") || line.startsWith("copy to ")) &&
renameTarget === null
) {
renameTarget = stripGitPathQuoting(line.slice(line.indexOf(" to ") + 4));
} else if (line.startsWith("diff --git ") && headerPath === null) {
headerPath = resolveDiffGitHeaderPath(line);
}
}
return fallbackSource ?? renameTarget ?? headerPath;
}
function splitUnifiedDiffSections(diff: string): ReadonlyArray<string> {
const normalized = diff.replace(/\r\n/g, "\n");
if (normalized.trim().length === 0) {
return [];
}
const sections: Array<string> = [];
let currentStart = -1;
const lines = normalized.split("\n");
const flush = (endExclusive: number) => {
if (currentStart >= 0) {
sections.push(lines.slice(currentStart, endExclusive).join("\n"));
}
};
for (let index = 0; index < lines.length; index += 1) {
if (lines[index]!.startsWith("diff --git ")) {
flush(index);
currentStart = index;
}
}
flush(lines.length);
return sections;
}
/**
* List the resolvable post-image paths of a unified diff's file sections.
* Unparseable sections are omitted.
*/
export function listUnifiedDiffPaths(diff: string): ReadonlyArray<string> {
const paths: Array<string> = [];
for (const section of splitUnifiedDiffSections(diff)) {
const path = resolveDiffSectionPath(section);
if (path !== null) {
paths.push(path);
}
}
return paths;
}
/**
* Remove file sections from a unified diff by path.
*
* Sections whose path cannot be determined are kept (fail toward showing).
*/
export function filterUnifiedDiffFiles(
diff: string,
shouldKeepPath: (path: string) => boolean,
): string {
const sections = splitUnifiedDiffSections(diff);
if (sections.length === 0) {
return diff;
}
const kept = sections.filter((section) => {
const path = resolveDiffSectionPath(section);
return path === null || shouldKeepPath(path);
});
if (kept.length === sections.length) {
return diff;
}
return kept.join("\n");
}
+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* recoverServiceOnboardingOffer(Effect.fail(new Terminal.QuitError({})));
const result = yield* recoverBootServiceOffer(Effect.fail(new Terminal.QuitError({})));
assert.isFalse(result);
}),
);
+69 -11
View File
@@ -6,6 +6,7 @@ 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";
@@ -19,7 +20,6 @@ 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,6 +29,7 @@ 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";
@@ -44,13 +45,9 @@ 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."),
@@ -399,6 +396,21 @@ 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({
@@ -408,9 +420,7 @@ const disconnectCloud = Effect.fn("cloud.cli.disconnect")(function* (options: {
});
if (options.clearAuthorization) {
yield* Console.log(
"Signed out of T3 Connect locally.\nThe background service is managed separately with `t3 service`.",
);
yield* Console.log("Signed out of T3 Connect locally.");
}
});
@@ -447,7 +457,11 @@ const runCloudCommand = Effect.fn("cloud.cli.run_cloud_command")(function* <A, E
RelayClient.layerCloudflared({ baseDir: config.baseDir }),
EnvironmentAuth.runtimeLayer,
ServerEnvironment.layer,
bootServiceLayer(config),
BootService.layer({
baseDir: config.baseDir,
logsDir: config.logsDir,
cliVersion: packageJson.version,
}).pipe(Layer.provide(ProcessRunner.layer)),
headlessRelayClientTracingLayer,
).pipe(
Layer.provideMerge(FetchHttpClient.layer),
@@ -669,6 +683,50 @@ 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,
@@ -690,7 +748,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* recoverServiceOnboardingOffer(offerServiceDuringOnboarding);
const background = yield* recoverBootServiceOffer(offerBootService);
yield* Console.log(
background
? "\n✓ Background service ready\n\nT3 Code will stay reachable after you log out."
-37
View File
@@ -1,37 +0,0 @@
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
@@ -1,199 +0,0 @@
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,
]),
);
+4 -33
View File
@@ -14,7 +14,6 @@ import {
HostProcessPlatform,
} from "@t3tools/shared/hostProcess";
import { reconcileService } from "../cli/service.ts";
import * as ProcessRunner from "../processRunner.ts";
import * as BootService from "./bootService.ts";
@@ -101,7 +100,7 @@ it("renders a systemd unit with absolute paths and append-mode logging", () => {
unit,
[
"[Unit]",
"Description=T3 Code server",
"Description=T3 Code server (T3 Connect)",
"StartLimitIntervalSec=300",
"StartLimitBurst=5",
"",
@@ -109,7 +108,6 @@ 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",
@@ -172,33 +170,6 @@ 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();
@@ -340,7 +311,7 @@ it.layer(NodeServices.layer)("BootService", (it) => {
}),
);
it.effect("reports an installed-but-stale unit so the lifecycle can offer a repair", () =>
it.effect("reports an installed-but-stale unit so connect can offer a repair", () =>
Effect.gen(function* () {
const { dirs, fs, path } = yield* makeTestContext();
const commands: Array<RecordedCommand> = [];
@@ -431,8 +402,8 @@ it.layer(NodeServices.layer)("BootService", (it) => {
const error = yield* service.install.pipe(Effect.flip);
assert.isTrue(isCommandError(error));
// A leftover unit would make status report "installed" even though
// linger never happened.
// A leftover unit would make the next connect report "already set up"
// even though linger never happened.
assert.isFalse(
yield* fs.exists(path.join(dirs.home, ".config", "systemd", "user", "t3code.service")),
);
+60 -41
View File
@@ -16,19 +16,21 @@ 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. 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.
* 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.
*/
const BOOT_SERVICE_NAME = "t3code";
const BOOT_RUNTIME_DIR = "runtime";
export const BOOT_SERVICE_UNIT_FILE = `${BOOT_SERVICE_NAME}.service`;
export const BOOT_SERVICE_UNIT_ENV = "T3_BOOT_SERVICE_UNIT";
const BOOT_SERVICE_UNIT_FILE = `${BOOT_SERVICE_NAME}.service`;
const PINNED_RUNTIME_INSTALL_TIMEOUT = Duration.minutes(10);
const EPHEMERAL_CACHE_SEGMENTS = [
"/_npx/", // npx
@@ -90,7 +92,7 @@ export function renderBootServiceUnit(plan: BootServicePlan): string {
// relay connection, and Restart=always covers early-boot failures.
return [
"[Unit]",
"Description=T3 Code server",
"Description=T3 Code server (T3 Connect)",
// 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.
@@ -101,7 +103,6 @@ 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",
@@ -205,7 +206,14 @@ 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 runtimePaths = pinnedRuntimePaths(path, input.baseDir, input.cliVersion);
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 requireSystemdLinux = Effect.gen(function* () {
if (platform !== "linux" || homeDir === "") {
@@ -255,41 +263,52 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: {
if (!isEphemeralCacheEntry(host.cliEntryPath)) {
return;
}
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,
),
// 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* 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)
? runtimePaths.entryPath
? runtimeEntryPath
: host.cliEntryPath;
const plan: BootServicePlan = {
nodePath: host.execPath,
@@ -322,8 +341,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 service status report it as installed even though it was
// never enabled or lingered.
// would make the next `t3 connect` report the service as already set up
// 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", [
@@ -353,7 +372,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 lifecycle command misreports the state.
// next connect misreports the state.
const rollbackFailedInstall = Effect.fn("cloud.boot_service.rollback_failed_install")(function* (
previousUnit: Option.Option<string>,
) {
-129
View File
@@ -1,129 +0,0 @@
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
@@ -1,176 +0,0 @@
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
@@ -1,589 +0,0 @@
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 ? "" : `t3 v${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" ? "t3 v0.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())),
);
});
-430
View File
@@ -1,430 +0,0 @@
// @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),
),
);
// Effect CLI's unstable formatVersion currently emits `${name} v${version}`.
// Extract the version token so surrounding presentation changes do not break updates.
const reportedVersion = /\bv(\S+)\s*$/.exec(preflight.stdout)?.[1];
if (preflight.code !== 0 || reportedVersion !== 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,7 +9,6 @@ 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";
@@ -125,9 +124,6 @@ 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,
@@ -141,7 +137,6 @@ export const make = Effect.gen(function* () {
repositoryIdentity: true,
connectionProbe: true,
threadSettlement: true,
...(serverSelfUpdate === null ? {} : { serverSelfUpdate }),
},
};
+1 -345
View File
@@ -8,7 +8,6 @@ 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";
@@ -51,8 +50,6 @@ interface FakeGhScenario {
};
repositoryCloneUrls?: Record<string, { url: string; sshUrl: string }>;
failWith?: GitHubCli.GitHubCliError;
/** Let this many gh calls succeed before failWith kicks in (default 0 = fail immediately). */
failAfterCalls?: number;
}
function fakeGhOutput(stdout: string): VcsProcess.VcsProcessOutput {
@@ -385,7 +382,7 @@ function createGitHubCliWithFakeGh(scenario: FakeGhScenario = {}): {
const args = [...input.args];
ghCalls.push(args.join(" "));
if (scenario.failWith && ghCalls.length > (scenario.failAfterCalls ?? 0)) {
if (scenario.failWith) {
return Effect.fail(scenario.failWith);
}
@@ -1339,230 +1336,6 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
}),
);
it.effect("status keeps the last known PR when a later lookup fails", () =>
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
yield* initRepo(repoDir);
yield* runGit(repoDir, ["checkout", "-b", "feature/pr-sticky"]);
const remoteDir = yield* createBareRemote();
yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]);
yield* runGit(repoDir, ["push", "-u", "origin", "feature/pr-sticky"]);
const existingPr = {
number: 214,
title: "Sticky PR",
url: "https://github.com/pingdotgg/codething-mvp/pull/214",
baseRefName: "main",
headRefName: "feature/pr-sticky",
};
const { manager } = yield* makeManager({
ghScenario: {
// @effect-diagnostics-next-line preferSchemaOverJson:off
prListSequence: [JSON.stringify([existingPr])],
failWith: new GitHubCli.GitHubCliUnavailableError({
command: "gh",
cwd: repoDir,
cause: new Error("rate limited"),
}),
failAfterCalls: 1,
},
});
const first = yield* manager.status({ cwd: repoDir });
expect(first.pr?.number).toBe(214);
// An explicit invalidation (user refresh, git action) bypasses the PR
// cache and forces a live lookup — which now fails. The badge must keep
// the last known PR instead of blanking out.
yield* manager.invalidateStatus(repoDir);
const second = yield* manager.status({ cwd: repoDir });
expect(second.pr?.number).toBe(214);
}),
);
it.effect(
"status does not reuse a stale PR after the branch is retargeted to a different upstream",
() =>
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
yield* initRepo(repoDir);
yield* runGit(repoDir, ["checkout", "-b", "feature/pr-retarget"]);
const originRemote = yield* createBareRemote();
yield* runGit(repoDir, ["remote", "add", "origin", originRemote]);
yield* runGit(repoDir, ["push", "-u", "origin", "feature/pr-retarget"]);
const existingPr = {
number: 214,
title: "Sticky PR",
url: "https://github.com/pingdotgg/codething-mvp/pull/214",
baseRefName: "main",
headRefName: "feature/pr-retarget",
};
const { manager } = yield* makeManager({
ghScenario: {
// @effect-diagnostics-next-line preferSchemaOverJson:off
prListSequence: [JSON.stringify([existingPr])],
failWith: new GitHubCli.GitHubCliUnavailableError({
command: "gh",
cwd: repoDir,
cause: new Error("rate limited"),
}),
failAfterCalls: 1,
},
});
const first = yield* manager.status({ cwd: repoDir });
expect(first.pr?.number).toBe(214);
// Retarget the branch to a different remote/upstream (e.g. the PR was
// reopened against a fork). The previously cached PR belonged to the
// old upstream and must not be shown against the new one.
const forkRemote = yield* createBareRemote();
yield* runGit(repoDir, ["remote", "add", "fork", forkRemote]);
yield* runGit(repoDir, ["push", "fork", "feature/pr-retarget"]);
yield* runGit(repoDir, [
"branch",
"--set-upstream-to=fork/feature/pr-retarget",
"feature/pr-retarget",
]);
yield* manager.invalidateStatus(repoDir);
const second = yield* manager.status({ cwd: repoDir });
expect(second.pr).toBeNull();
}),
);
it.effect("status keeps the last known PR when the branch gains its first upstream", () =>
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
yield* initRepo(repoDir);
yield* runGit(repoDir, ["checkout", "-b", "feature/pr-sticky-first-push"]);
const remoteDir = yield* createBareRemote();
yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]);
const existingPr = {
number: 215,
title: "Sticky first-push PR",
url: "https://github.com/pingdotgg/codething-mvp/pull/215",
baseRefName: "main",
headRefName: "feature/pr-sticky-first-push",
};
const { manager } = yield* makeManager({
ghScenario: {
// @effect-diagnostics-next-line preferSchemaOverJson:off
prListSequence: [JSON.stringify([existingPr])],
failWith: new GitHubCli.GitHubCliUnavailableError({
command: "gh",
cwd: repoDir,
cause: new Error("rate limited"),
}),
failAfterCalls: 1,
},
});
const first = yield* manager.status({ cwd: repoDir });
expect(first.pr?.number).toBe(215);
yield* runGit(repoDir, ["push", "-u", "origin", "feature/pr-sticky-first-push"]);
yield* manager.invalidateStatus(repoDir);
const second = yield* manager.status({ cwd: repoDir });
expect(second.pr?.number).toBe(215);
}),
);
it.effect("status drops the last known PR when the tracked remote is repointed", () =>
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
yield* initRepo(repoDir);
yield* runGit(repoDir, ["checkout", "-b", "feature/pr-repointed"]);
const originalRemoteDir = yield* createBareRemote();
yield* runGit(repoDir, ["remote", "add", "origin", originalRemoteDir]);
yield* runGit(repoDir, ["push", "-u", "origin", "feature/pr-repointed"]);
const existingPr = {
number: 216,
title: "Old remote PR",
url: "https://github.com/pingdotgg/codething-mvp/pull/216",
baseRefName: "main",
headRefName: "feature/pr-repointed",
};
const { manager } = yield* makeManager({
ghScenario: {
// @effect-diagnostics-next-line preferSchemaOverJson:off
prListSequence: [JSON.stringify([existingPr])],
failWith: new GitHubCli.GitHubCliUnavailableError({
command: "gh",
cwd: repoDir,
cause: new Error("rate limited"),
}),
failAfterCalls: 1,
},
});
const first = yield* manager.status({ cwd: repoDir });
expect(first.pr?.number).toBe(216);
const replacementRemoteDir = yield* createBareRemote();
yield* runGit(repoDir, ["remote", "add", "replacement", replacementRemoteDir]);
yield* runGit(repoDir, ["push", "replacement", "feature/pr-repointed"]);
yield* runGit(repoDir, ["remote", "set-url", "origin", replacementRemoteDir]);
yield* manager.invalidateStatus(repoDir);
const second = yield* manager.status({ cwd: repoDir });
expect(second.pr).toBeNull();
}),
);
it.effect("status keeps the last known PR when the current remote URL can't be resolved", () =>
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
yield* initRepo(repoDir);
yield* runGit(repoDir, ["checkout", "-b", "feature/pr-config-hiccup"]);
const remoteDir = yield* createBareRemote();
yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]);
yield* runGit(repoDir, ["push", "-u", "origin", "feature/pr-config-hiccup"]);
const existingPr = {
number: 217,
title: "Config hiccup PR",
url: "https://github.com/pingdotgg/codething-mvp/pull/217",
baseRefName: "main",
headRefName: "feature/pr-config-hiccup",
};
const { manager } = yield* makeManager({
ghScenario: {
// @effect-diagnostics-next-line preferSchemaOverJson:off
prListSequence: [JSON.stringify([existingPr])],
failWith: new GitHubCli.GitHubCliUnavailableError({
command: "gh",
cwd: repoDir,
cause: new Error("rate limited"),
}),
failAfterCalls: 1,
},
});
const first = yield* manager.status({ cwd: repoDir });
expect(first.pr?.number).toBe(217);
// `remote.origin.url` reads go through readConfigValueNullable, which
// maps ANY failed read (a real "no remote configured" state or a
// transient git-config hiccup) to null the same way. Unsetting the
// key here reproduces that ambiguity without touching branch
// tracking (refs/remotes/origin/* and branch.<b>.remote are
// untouched) — the remote identity has not actually changed, so the
// sticky PR must survive even though the current lookup can no
// longer resolve a remote URL to compare against.
yield* runGit(repoDir, ["config", "--unset", "remote.origin.url"]);
yield* manager.invalidateStatus(repoDir);
const second = yield* manager.status({ cwd: repoDir });
expect(second.pr?.number).toBe(217);
}),
);
it.effect("creates a commit when working tree is dirty", () =>
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
@@ -2414,123 +2187,6 @@ 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-");
+42 -232
View File
@@ -32,7 +32,6 @@ import {
import {
detectSourceControlProviderFromGitRemoteUrl,
mergeGitStatusParts,
normalizeGitRemoteUrl,
resolveAutoFeatureBranchName,
sanitizeBranchFragment,
sanitizeFeatureBranchName,
@@ -96,9 +95,6 @@ const SHORT_SHA_LENGTH = 7;
const TOAST_DESCRIPTION_MAX = 72;
const STATUS_RESULT_CACHE_TTL = Duration.seconds(1);
const STATUS_RESULT_CACHE_CAPACITY = 2_048;
const PR_LOOKUP_CACHE_TTL = Duration.minutes(2);
const PR_LOOKUP_FAILURE_TTL = Duration.seconds(20);
const PR_LOOKUP_CACHE_CAPACITY = 2_048;
type StripProgressContext<T> = T extends any ? Omit<T, "actionId" | "cwd" | "action"> : never;
type GitActionProgressPayload = StripProgressContext<GitActionProgressEvent>;
type GitActionProgressEmitter = (event: GitActionProgressPayload) => Effect.Effect<void, never>;
@@ -146,7 +142,6 @@ interface BranchHeadContext {
headSelectors: ReadonlyArray<string>;
preferredHeadSelector: string;
remoteName: string | null;
headRemoteUrlKey: string | null;
headRepositoryNameWithOwner: string | null;
headRepositoryOwnerLogin: string | null;
isCrossRepository: boolean;
@@ -252,38 +247,7 @@ function resolvePullRequestHeadRepositoryNameWithOwner(
return `${ownerLogin}/${repositoryName}`;
}
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(
function matchesBranchHeadContext(
pr: PullRequestInfo,
headContext: Pick<
BranchHeadContext,
@@ -294,51 +258,44 @@ export function matchesBranchHeadContext(
return false;
}
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;
}
}
const expectedHeadRepository = normalizeOptionalRepositoryNameWithOwner(
headContext.headRepositoryNameWithOwner,
);
const expectedHeadOwner =
normalizeOptionalOwnerLogin(headContext.headRepositoryOwnerLogin) ??
parseRepositoryOwnerLogin(expectedHeadRepository);
const prHeadRepository = normalizeOptionalRepositoryNameWithOwner(
resolvePullRequestHeadRepositoryNameWithOwner(pr),
);
const prHeadOwner =
normalizeOptionalOwnerLogin(pr.headRepositoryOwnerLogin) ??
parseRepositoryOwnerLogin(prHeadRepository);
if (headContext.isCrossRepository) {
if (pr.isCrossRepository === false) {
return false;
}
if (
(expectedHead.repositoryNameWithOwner || expectedHead.ownerLogin) &&
!pullRequestHead.repositoryNameWithOwner &&
!pullRequestHead.ownerLogin
) {
if ((expectedHeadRepository || expectedHeadOwner) && !prHeadRepository && !prHeadOwner) {
return false;
}
if (expectedHeadRepository && prHeadRepository && expectedHeadRepository !== prHeadRepository) {
return false;
}
if (expectedHeadOwner && prHeadOwner && expectedHeadOwner !== prHeadOwner) {
return false;
}
return true;
}
if (pr.isCrossRepository === true) {
if (
(!expectedHead.repositoryNameWithOwner && !expectedHead.ownerLogin) ||
(!pullRequestHead.repositoryNameWithOwner && !pullRequestHead.ownerLogin)
) {
return false;
}
return false;
}
if (expectedHeadRepository && prHeadRepository && expectedHeadRepository !== prHeadRepository) {
return false;
}
if (expectedHeadOwner && prHeadOwner && expectedHeadOwner !== prHeadOwner) {
return false;
}
return true;
}
@@ -811,154 +768,6 @@ export const make = Effect.gen(function* () {
normalizeStatusCacheKey(cwd).pipe(
Effect.flatMap((cacheKey) => Cache.invalidate(localStatusResultCache, cacheKey)),
);
// PR lookups hit the hosting provider's API (gh/glab/...), so they refresh
// on their own, slower cadence: ahead/behind counts stay fresh on every
// status poll while the PR association is re-fetched at most once per
// PR_LOOKUP_CACHE_TTL per branch. Git actions and user-driven refreshes bump
// the epoch (invalidateStatus) to bypass the cache immediately.
const prLookupEpochByCwd = new Map<string, number>();
const prLookupEpoch = (cwd: string) => prLookupEpochByCwd.get(cwd) ?? 0;
const bumpPrLookupEpoch = (cwd: string) =>
normalizeStatusCacheKey(cwd).pipe(
Effect.map((cacheKey) => {
prLookupEpochByCwd.set(cacheKey, prLookupEpoch(cacheKey) + 1);
}),
);
// Cache keys are NUL-joined [cwd, branch, upstreamRef, epoch] — none of the
// segments can contain a NUL byte, and refs are never empty, so "" decodes
// back to a null upstreamRef.
const prLookupCacheKey = (cwd: string, details: { branch: string; upstreamRef: string | null }) =>
[cwd, details.branch, details.upstreamRef ?? "", String(prLookupEpoch(cwd))].join("\u0000");
const prLookupCache = yield* Cache.makeWith(
(key: string) => {
const [cwd = "", branch = "", upstreamRef = ""] = key.split("\u0000");
const details = {
branch,
upstreamRef: upstreamRef.length > 0 ? upstreamRef : null,
};
return resolveBranchHeadContext(cwd, details).pipe(
Effect.flatMap((headContext) =>
findLatestPrForHeadContext(cwd, headContext).pipe(
Effect.map((latest) => ({ latest, headContext })),
),
),
);
},
{
capacity: PR_LOOKUP_CACHE_CAPACITY,
timeToLive: (exit) => (Exit.isSuccess(exit) ? PR_LOOKUP_CACHE_TTL : PR_LOOKUP_FAILURE_TTL),
},
);
// A transient lookup failure (rate limit, network blip) must not clear an
// already-known PR badge, so the last successful answer per branch sticks
// around as the fallback. Keep the resolved head context with it so a
// branch retargeted to another remote/fork cannot inherit the old badge.
interface LastKnownPr {
readonly pr: ReturnType<typeof toStatusPr> | null;
readonly upstreamRef: string | null;
readonly headBranch: string;
readonly remoteName: string | null;
readonly headRemoteUrlKey: string | null;
}
const lastKnownPrByBranchKey = new Map<string, LastKnownPr>();
const rememberLastKnownPr = (branchKey: string, entry: LastKnownPr) => {
if (
!lastKnownPrByBranchKey.has(branchKey) &&
lastKnownPrByBranchKey.size >= PR_LOOKUP_CACHE_CAPACITY
) {
const oldestKey = lastKnownPrByBranchKey.keys().next().value;
if (oldestKey !== undefined) {
lastKnownPrByBranchKey.delete(oldestKey);
}
}
lastKnownPrByBranchKey.set(branchKey, entry);
};
const resolveLastKnownPr = (
branchKey: string,
current: Pick<LastKnownPr, "upstreamRef" | "headBranch" | "remoteName" | "headRemoteUrlKey">,
): ReturnType<typeof toStatusPr> | null => {
const lastKnown = lastKnownPrByBranchKey.get(branchKey);
if (!lastKnown) return null;
if (lastKnown.headBranch !== current.headBranch) {
return null;
}
// The normalized URL catches both remote-alias changes and an existing
// alias being repointed. Both sides must be resolved before treating a
// mismatch as real: `readConfigValueNullable` swallows any git-config
// read failure into `null`, so a transient failure to resolve the
// *current* remote URL must read as "unknown", not as "no remote" — the
// latter would otherwise drop an already-known PR badge on every hiccup.
if (lastKnown.headRemoteUrlKey !== null && current.headRemoteUrlKey !== null) {
return lastKnown.headRemoteUrlKey === current.headRemoteUrlKey ? lastKnown.pr : null;
}
// If the remote URL can't be compared, fall back to the remote identity
// encoded by tracked branches — same "both sides known" requirement, for
// the same reason. A null-to-non-null transition (upstream/remoteName)
// is allowed because that is the expected first-push case.
if (
lastKnown.upstreamRef !== null &&
current.upstreamRef !== null &&
lastKnown.remoteName !== null &&
current.remoteName !== null
) {
return lastKnown.remoteName === current.remoteName ? lastKnown.pr : null;
}
return lastKnown.pr;
};
const lookupStatusPr = Effect.fn("lookupStatusPr")(function* (
cwd: string,
details: { branch: string; upstreamRef: string | null; isDefaultBranch: boolean },
) {
// Keyed by (cwd, branch) only: the upstream ref changing (e.g. a first
// `push -u`) must not orphan the fallback value for the same branch.
const branchKey = `${cwd}\u0000${details.branch}`;
return yield* Cache.get(prLookupCache, prLookupCacheKey(cwd, details)).pipe(
Effect.map(({ latest, headContext }) => {
if (!latest) return { pr: null, headContext };
// On the default branch, only surface open PRs.
// Merged/closed matches are usually reverse-merge history, not the thread's PR context.
if (details.isDefaultBranch && latest.state !== "open") {
return { pr: null, headContext };
}
return { pr: toStatusPr(latest), headContext };
}),
Effect.tap(({ pr, headContext }) =>
Effect.sync(() =>
rememberLastKnownPr(branchKey, {
pr,
upstreamRef: details.upstreamRef,
headBranch: headContext.headBranch,
remoteName: headContext.remoteName,
headRemoteUrlKey: headContext.headRemoteUrlKey,
}),
),
),
Effect.map(({ pr }) => pr),
Effect.catch((error) =>
Effect.logWarning("PR lookup failed; keeping last known PR state.").pipe(
Effect.annotateLogs({
operation: "lookupStatusPr",
branch: details.branch,
errorTag:
typeof error === "object" && error !== null && "_tag" in error
? String(error._tag)
: typeof error,
}),
Effect.andThen(resolveBranchHeadContext(cwd, details)),
Effect.map((headContext) =>
resolveLastKnownPr(branchKey, {
upstreamRef: details.upstreamRef,
headBranch: headContext.headBranch,
remoteName: headContext.remoteName,
headRemoteUrlKey: headContext.headRemoteUrlKey,
}),
),
),
),
);
});
const readRemoteStatus = Effect.fn("readRemoteStatus")(function* (
cwd: string,
options?: GitVcsDriver.GitRemoteStatusOptions,
@@ -972,11 +781,19 @@ export const make = Effect.gen(function* () {
const pr =
details.branch !== null
? yield* lookupStatusPr(cwd, {
? yield* findLatestPr(cwd, {
branch: details.branch,
upstreamRef: details.upstreamRef,
isDefaultBranch: details.isDefaultBranch,
})
}).pipe(
Effect.map((latest) => {
if (!latest) return null;
// On the default branch, only surface open PRs.
// Merged/closed matches are usually reverse-merge history, not the thread's PR context.
if (details.isDefaultBranch && latest.state !== "open") return null;
return toStatusPr(latest);
}),
Effect.orElseSucceed(() => null),
)
: null;
return {
@@ -1020,7 +837,6 @@ export const make = Effect.gen(function* () {
) {
if (!remoteName) {
return {
remoteUrlKey: null,
repositoryNameWithOwner: null,
ownerLogin: null,
};
@@ -1029,7 +845,6 @@ export const make = Effect.gen(function* () {
const remoteUrl = yield* readConfigValueNullable(cwd, `remote.${remoteName}.url`);
const repositoryNameWithOwner = parseGitHubRepositoryNameWithOwnerFromRemoteUrl(remoteUrl);
return {
remoteUrlKey: remoteUrl ? normalizeGitRemoteUrl(remoteUrl) : null,
repositoryNameWithOwner,
ownerLogin: parseRepositoryOwnerLogin(repositoryNameWithOwner),
};
@@ -1100,9 +915,6 @@ export const make = Effect.gen(function* () {
preferredHeadSelector:
ownerHeadSelector && isCrossRepository ? ownerHeadSelector : headBranch,
remoteName,
headRemoteUrlKey:
remoteRepository.remoteUrlKey ??
(remoteName === null ? originRepository.remoteUrlKey : null),
headRepositoryNameWithOwner: remoteRepository.repositoryNameWithOwner,
headRepositoryOwnerLogin: remoteRepository.ownerLogin,
isCrossRepository,
@@ -1148,10 +960,11 @@ export const make = Effect.gen(function* () {
return null;
});
const findLatestPrForHeadContext = Effect.fn("findLatestPrForHeadContext")(function* (
const findLatestPr = Effect.fn("findLatestPr")(function* (
cwd: string,
headContext: BranchHeadContext,
details: { branch: string; upstreamRef: string | null },
) {
const headContext = yield* resolveBranchHeadContext(cwd, details);
const parsedByNumber = new Map<number, PullRequestInfo>();
for (const headSelector of headContext.headSelectors) {
@@ -1178,6 +991,7 @@ export const make = Effect.gen(function* () {
}
return parsed[0] ?? null;
});
const buildCompletionToast = Effect.fn("buildCompletionToast")(function* (
cwd: string,
result: Pick<GitRunStackedActionResult, "action" | "branch" | "commit" | "push" | "pr">,
@@ -1628,10 +1442,6 @@ export const make = Effect.gen(function* () {
function* (cwd) {
yield* invalidateLocalStatusResultCache(cwd);
yield* invalidateRemoteStatusResultCache(cwd);
// Full invalidation is the explicit-freshness path (git actions, user
// refresh); it also bypasses the slow PR-lookup cache. The periodic
// status poll only invalidates local/remote and keeps the PR cache warm.
yield* bumpPrLookupEpoch(cwd);
},
);
@@ -256,27 +256,6 @@ const make = Effect.gen(function* () {
// reflects files created or deleted during this turn.
yield* workspaceEntries.refresh(input.cwd);
// Best-effort per-path attribution: paths whose change is fully explained
// by pre-existing history moving through HEAD (pull, checkout,
// cherry-pick, rebase) are tagged origin "git" so the UI can demote them.
// Attribution must never block the checkpoint pipeline — any failure
// degrades to unattributed files (all shown as agent work).
const attribution = yield* checkpointStore
.attributeCheckpointDiff({
cwd: input.cwd,
fromCheckpointRef,
toCheckpointRef: targetCheckpointRef,
})
.pipe(
Effect.catch((error) =>
Effect.logWarning("failed to attribute checkpoint diff", {
threadId: input.threadId,
turnId: input.turnId,
detail: error.message,
}).pipe(Effect.as(null)),
),
);
const files = yield* checkpointStore
.diffCheckpoints({
cwd: input.cwd,
@@ -292,7 +271,6 @@ const make = Effect.gen(function* () {
kind: "modified" as const,
additions: file.additions,
deletions: file.deletions,
...(attribution ? { origin: attribution.get(file.path) ?? "agent" } : {}),
})),
),
Effect.tapError((error) =>
@@ -1,4 +1,5 @@
import {
ApprovalRequestId,
CheckpointRef,
CommandId,
CorrelationId,
@@ -2462,76 +2463,190 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => {
]);
}),
);
it.effect("only clears pending turn starts targeted by failure signals", () =>
Effect.gen(function* () {
const projectionPipeline = yield* OrchestrationProjectionPipeline;
const eventStore = yield* OrchestrationEventStore;
const sql = yield* SqlClient.SqlClient;
const threadId = ThreadId.make("thread-start-failed");
const appendAndProject = (event: Parameters<typeof eventStore.append>[0]) =>
eventStore
.append(event)
.pipe(Effect.flatMap((savedEvent) => projectionPipeline.projectEvent(savedEvent)));
const listPendingStarts = () => sql<{ readonly messageId: string }>`
SELECT pending_message_id AS "messageId"
FROM projection_turns
WHERE thread_id = ${threadId}
AND turn_id IS NULL
AND state = 'pending'
`;
yield* appendAndProject({
type: "thread.turn-start-requested",
eventId: EventId.make("evt-start-failed-1"),
aggregateKind: "thread",
aggregateId: threadId,
occurredAt: "2026-02-26T13:00:00.000Z",
commandId: CommandId.make("cmd-start-failed-1"),
causationEventId: null,
correlationId: CorrelationId.make("cmd-start-failed-1"),
metadata: {},
payload: {
threadId,
messageId: MessageId.make("message-start-old"),
runtimeMode: "full-access",
createdAt: "2026-02-26T13:00:00.000Z",
},
});
yield* appendAndProject({
type: "thread.turn-start-requested",
eventId: EventId.make("evt-start-failed-2"),
aggregateKind: "thread",
aggregateId: threadId,
occurredAt: "2026-02-26T13:00:00.100Z",
commandId: CommandId.make("cmd-start-failed-2"),
causationEventId: null,
correlationId: CorrelationId.make("cmd-start-failed-2"),
metadata: {},
payload: {
threadId,
messageId: MessageId.make("message-start-new"),
runtimeMode: "full-access",
createdAt: "2026-02-26T13:00:00.100Z",
},
});
yield* appendAndProject({
type: "thread.activity-appended",
eventId: EventId.make("evt-start-failed-3"),
aggregateKind: "thread",
aggregateId: threadId,
occurredAt: "2026-02-26T13:00:00.200Z",
commandId: CommandId.make("cmd-start-failed-3"),
causationEventId: null,
correlationId: CorrelationId.make("cmd-start-failed-3"),
metadata: { requestId: ApprovalRequestId.make("message-start-old") },
payload: {
threadId,
activity: {
id: EventId.make("activity-start-failed-old"),
tone: "error",
kind: "provider.turn.start.failed",
summary: "Provider turn start failed",
payload: { requestId: "message-start-old", detail: "Provider startup failed" },
turnId: null,
createdAt: "2026-02-26T13:00:00.200Z",
},
},
});
const pendingRows = yield* listPendingStarts();
assert.deepEqual(pendingRows, [{ messageId: "message-start-new" }]);
yield* appendAndProject({
type: "thread.activity-appended",
eventId: EventId.make("evt-start-failed-4"),
aggregateKind: "thread",
aggregateId: threadId,
occurredAt: "2026-02-26T13:00:00.300Z",
commandId: CommandId.make("cmd-start-failed-4"),
causationEventId: null,
correlationId: CorrelationId.make("cmd-start-failed-4"),
metadata: { requestId: ApprovalRequestId.make("message-start-new") },
payload: {
threadId,
activity: {
id: EventId.make("activity-start-failed-new"),
tone: "error",
kind: "provider.turn.start.failed",
summary: "Provider turn start failed",
payload: { requestId: "message-start-new", detail: "Provider startup failed" },
turnId: null,
createdAt: "2026-02-26T13:00:00.300Z",
},
},
});
const clearedRows = yield* listPendingStarts();
assert.deepEqual(clearedRows, []);
yield* appendAndProject({
type: "thread.turn-start-requested",
eventId: EventId.make("evt-start-failed-5"),
aggregateKind: "thread",
aggregateId: threadId,
occurredAt: "2026-02-26T13:00:00.500Z",
commandId: CommandId.make("cmd-start-failed-5"),
causationEventId: null,
correlationId: CorrelationId.make("cmd-start-failed-5"),
metadata: {},
payload: {
threadId,
messageId: MessageId.make("message-start-terminal"),
runtimeMode: "full-access",
createdAt: "2026-02-26T13:00:00.500Z",
},
});
yield* appendAndProject({
type: "thread.session-set",
eventId: EventId.make("evt-start-failed-6"),
aggregateKind: "thread",
aggregateId: threadId,
occurredAt: "2026-02-26T13:00:00.600Z",
commandId: CommandId.make("cmd-start-failed-6"),
causationEventId: null,
correlationId: CorrelationId.make("cmd-start-failed-6"),
metadata: {},
payload: {
threadId,
session: {
threadId,
status: "error",
providerName: "codex",
runtimeMode: "full-access",
activeTurnId: null,
lastError: "Earlier session failed",
updatedAt: "2026-02-26T13:00:00.400Z",
},
},
});
const rowsAfterStaleSession = yield* listPendingStarts();
assert.deepEqual(rowsAfterStaleSession, [{ messageId: "message-start-terminal" }]);
yield* appendAndProject({
type: "thread.session-set",
eventId: EventId.make("evt-start-failed-7"),
aggregateKind: "thread",
aggregateId: threadId,
occurredAt: "2026-02-26T13:00:00.700Z",
commandId: CommandId.make("cmd-start-failed-7"),
causationEventId: null,
correlationId: CorrelationId.make("cmd-start-failed-7"),
metadata: {},
payload: {
threadId,
session: {
threadId,
status: "stopped",
providerName: "codex",
runtimeMode: "full-access",
activeTurnId: null,
lastError: null,
updatedAt: "2026-02-26T13:00:00.700Z",
},
},
});
const rowsAfterCurrentSession = yield* listPendingStarts();
assert.deepEqual(rowsAfterCurrentSession, []);
}),
);
});
it.layer(makeProjectionPipelinePrefixedTestLayer("t3-pending-turn-terminal-test-"))(
"OrchestrationProjectionPipeline pending turn cleanup",
(it) => {
it.effect("clears pending turn starts when startup reaches a terminal session state", () =>
Effect.gen(function* () {
const projectionPipeline = yield* OrchestrationProjectionPipeline;
const eventStore = yield* OrchestrationEventStore;
const sql = yield* SqlClient.SqlClient;
for (const [index, status] of (["error", "interrupted", "stopped"] as const).entries()) {
const threadId = ThreadId.make(`thread-terminal-${status}`);
const requestedAt = `2026-02-26T14:00:0${index}.000Z`;
yield* eventStore.append({
type: "thread.turn-start-requested",
eventId: EventId.make(`evt-terminal-pending-${status}`),
aggregateKind: "thread",
aggregateId: threadId,
occurredAt: requestedAt,
commandId: CommandId.make(`cmd-terminal-pending-${status}`),
causationEventId: null,
correlationId: CorrelationId.make(`cmd-terminal-pending-${status}`),
metadata: {},
payload: {
threadId,
messageId: MessageId.make(`message-terminal-${status}`),
runtimeMode: "approval-required",
createdAt: requestedAt,
},
});
yield* eventStore.append({
type: "thread.session-set",
eventId: EventId.make(`evt-terminal-session-${status}`),
aggregateKind: "thread",
aggregateId: threadId,
occurredAt: requestedAt,
commandId: CommandId.make(`cmd-terminal-session-${status}`),
causationEventId: null,
correlationId: CorrelationId.make(`cmd-terminal-session-${status}`),
metadata: {},
payload: {
threadId,
session: {
threadId,
status,
providerName: "codex",
runtimeMode: "approval-required",
activeTurnId: null,
lastError: status === "error" ? "startup failed" : null,
updatedAt: requestedAt,
},
},
});
}
yield* projectionPipeline.bootstrap;
const pendingRows = yield* sql<{ readonly threadId: string }>`
SELECT thread_id AS "threadId"
FROM projection_turns
WHERE turn_id IS NULL
AND state = 'pending'
`;
assert.deepEqual(pendingRows, []);
}),
);
},
);
it.effect("restores pending turn-start metadata across projection pipeline restart", () =>
Effect.gen(function* () {
const { dbPath } = yield* ServerConfig;
@@ -1056,18 +1056,52 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
return;
}
case "thread.activity-appended": {
if (event.payload.activity.kind !== "provider.turn.start.failed") {
return;
}
const requestId = event.metadata.requestId;
if (requestId === undefined) {
return;
}
const pendingTurnStart = yield* projectionTurnRepository.getPendingTurnStartByThreadId({
threadId: event.payload.threadId,
});
if (
Option.isNone(pendingTurnStart) ||
String(requestId) !== pendingTurnStart.value.messageId
) {
return;
}
yield* projectionTurnRepository.deletePendingTurnStartByThreadId({
threadId: event.payload.threadId,
});
return;
}
case "thread.session-set": {
const turnId = event.payload.session.activeTurnId;
if (turnId === null || event.payload.session.status !== "running") {
if (
event.payload.session.lastError !== null ||
event.payload.session.status === "error" ||
event.payload.session.status === "stopped" ||
event.payload.session.status === "interrupted"
event.payload.session.status === "interrupted" ||
event.payload.session.status === "stopped"
) {
yield* projectionTurnRepository.deletePendingTurnStartByThreadId({
threadId: event.payload.threadId,
});
const pendingTurnStart =
yield* projectionTurnRepository.getPendingTurnStartByThreadId({
threadId: event.payload.threadId,
});
if (
Option.isSome(pendingTurnStart) &&
pendingTurnStart.value.requestedAt <= event.payload.session.updatedAt
) {
yield* projectionTurnRepository.deletePendingTurnStartByThreadId({
threadId: event.payload.threadId,
});
}
}
// Leaving the "running" session status is the turn-end signal:
// settle still-running turns so their duration reflects the whole
// turn rather than the last assistant message.
@@ -217,22 +217,39 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
checkpoint_status,
checkpoint_files_json
)
VALUES (
'thread-1',
'turn-1',
NULL,
'thread-1',
'plan-1',
'message-1',
'completed',
'2026-02-24T00:00:08.000Z',
'2026-02-24T00:00:08.000Z',
'2026-02-24T00:00:08.000Z',
1,
'checkpoint-1',
'ready',
'[{"path":"README.md","kind":"modified","additions":2,"deletions":1}]'
)
VALUES
(
'thread-1',
'turn-1',
NULL,
'thread-1',
'plan-1',
'message-1',
'completed',
'2026-02-24T00:00:08.000Z',
'2026-02-24T00:00:08.000Z',
'2026-02-24T00:00:08.000Z',
1,
'checkpoint-1',
'ready',
'[{"path":"README.md","kind":"modified","additions":2,"deletions":1}]'
),
(
'thread-1',
NULL,
'message-pending',
NULL,
NULL,
NULL,
'pending',
'2026-02-24T00:00:09.000Z',
NULL,
NULL,
NULL,
NULL,
NULL,
'[]'
)
`;
let sequence = 5;
@@ -432,12 +449,17 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
updatedAt: "2026-02-24T00:00:07.000Z",
},
latestUserMessageAt: "2026-02-24T00:00:04.000Z",
hasPendingTurnStart: true,
hasPendingApprovals: true,
hasPendingUserInput: false,
hasActionableProposedPlan: false,
},
]);
const threadShell = yield* snapshotQuery.getThreadShellById(ThreadId.make("thread-1"));
assert.equal(threadShell._tag, "Some");
assert.equal(threadShell._tag === "Some" && threadShell.value.hasPendingTurnStart, true);
const threadDetail = yield* snapshotQuery.getThreadDetailById(ThreadId.make("thread-1"));
assert.equal(threadDetail._tag, "Some");
if (threadDetail._tag === "Some") {
@@ -103,6 +103,9 @@ const ProjectionLatestTurnDbRowSchema = Schema.Struct({
sourceProposedPlanThreadId: Schema.NullOr(ThreadId),
sourceProposedPlanId: Schema.NullOr(OrchestrationProposedPlanId),
});
const ProjectionPendingTurnStartDbRowSchema = Schema.Struct({
threadId: ThreadId,
});
const ProjectionStateDbRowSchema = ProjectionState;
const ProjectionCountsRowSchema = Schema.Struct({
projectCount: Schema.Number,
@@ -614,6 +617,23 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
`,
});
const listActivePendingTurnStartRows = SqlSchema.findAll({
Request: Schema.Void,
Result: ProjectionPendingTurnStartDbRowSchema,
execute: () =>
sql`
SELECT turns.thread_id AS "threadId"
FROM projection_turns turns
INNER JOIN projection_threads threads
ON threads.thread_id = turns.thread_id
WHERE threads.deleted_at IS NULL
AND threads.archived_at IS NULL
AND turns.turn_id IS NULL
AND turns.state = 'pending'
ORDER BY turns.thread_id ASC
`,
});
const listArchivedLatestTurnRows = SqlSchema.findAll({
Request: Schema.Void,
Result: ProjectionLatestTurnDbRowSchema,
@@ -886,6 +906,20 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
`,
});
const getPendingTurnStartRowByThread = SqlSchema.findOneOption({
Request: ThreadIdLookupInput,
Result: ProjectionPendingTurnStartDbRowSchema,
execute: ({ threadId }) =>
sql`
SELECT thread_id AS "threadId"
FROM projection_turns
WHERE thread_id = ${threadId}
AND turn_id IS NULL
AND state = 'pending'
LIMIT 1
`,
});
const listCheckpointRowsByThread = SqlSchema.findAll({
Request: ThreadIdLookupInput,
Result: ProjectionCheckpointDbRowSchema,
@@ -1449,14 +1483,24 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
),
),
),
listActiveLatestTurnRows(undefined).pipe(
Effect.mapError(
toPersistenceSqlOrDecodeError(
"ProjectionSnapshotQuery.getShellSnapshot:listLatestTurns:query",
"ProjectionSnapshotQuery.getShellSnapshot:listLatestTurns:decodeRows",
Effect.all({
latestTurnRows: listActiveLatestTurnRows(undefined).pipe(
Effect.mapError(
toPersistenceSqlOrDecodeError(
"ProjectionSnapshotQuery.getShellSnapshot:listLatestTurns:query",
"ProjectionSnapshotQuery.getShellSnapshot:listLatestTurns:decodeRows",
),
),
),
),
pendingTurnStartRows: listActivePendingTurnStartRows(undefined).pipe(
Effect.mapError(
toPersistenceSqlOrDecodeError(
"ProjectionSnapshotQuery.getShellSnapshot:listPendingTurnStarts:query",
"ProjectionSnapshotQuery.getShellSnapshot:listPendingTurnStarts:decodeRows",
),
),
),
}),
listProjectionStateRows(undefined).pipe(
Effect.mapError(
toPersistenceSqlOrDecodeError(
@@ -1468,8 +1512,9 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
]),
)
.pipe(
Effect.flatMap(([projectRows, threadRows, sessionRows, latestTurnRows, stateRows]) =>
Effect.flatMap(([projectRows, threadRows, sessionRows, turnRows, stateRows]) =>
Effect.gen(function* () {
const { latestTurnRows, pendingTurnStartRows } = turnRows;
let updatedAt: string | null = null;
for (const row of projectRows) {
updatedAt = maxIso(updatedAt, row.updatedAt);
@@ -1500,6 +1545,9 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
const sessionByThread = new Map(
sessionRows.map((row) => [row.threadId, mapSessionRow(row)] as const),
);
const pendingTurnStartThreadIds = new Set(
pendingTurnStartRows.map((row) => row.threadId),
);
const snapshot = {
snapshotSequence: computeSnapshotSequence(stateRows),
@@ -1529,6 +1577,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
settledAt: row.settledAt,
session: sessionByThread.get(row.threadId) ?? null,
latestUserMessageAt: row.latestUserMessageAt,
hasPendingTurnStart: pendingTurnStartThreadIds.has(row.threadId),
hasPendingApprovals: row.pendingApprovalCount > 0,
hasPendingUserInput: row.pendingUserInputCount > 0,
hasActionableProposedPlan: row.hasActionableProposedPlan > 0,
@@ -1858,60 +1907,81 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
});
const getThreadShellById: ProjectionSnapshotQueryShape["getThreadShellById"] = (threadId) =>
Effect.gen(function* () {
const [threadRow, latestTurnRow, sessionRow] = yield* Effect.all([
getActiveThreadRowById({ threadId }).pipe(
Effect.mapError(
toPersistenceSqlOrDecodeError(
"ProjectionSnapshotQuery.getThreadShellById:getThread:query",
"ProjectionSnapshotQuery.getThreadShellById:getThread:decodeRow",
sql
.withTransaction(
Effect.gen(function* () {
const [threadRow, latestTurnRow, sessionRow, pendingTurnStartRow] = yield* Effect.all([
getActiveThreadRowById({ threadId }).pipe(
Effect.mapError(
toPersistenceSqlOrDecodeError(
"ProjectionSnapshotQuery.getThreadShellById:getThread:query",
"ProjectionSnapshotQuery.getThreadShellById:getThread:decodeRow",
),
),
),
),
),
getLatestTurnRowByThread({ threadId }).pipe(
Effect.mapError(
toPersistenceSqlOrDecodeError(
"ProjectionSnapshotQuery.getThreadShellById:getLatestTurn:query",
"ProjectionSnapshotQuery.getThreadShellById:getLatestTurn:decodeRow",
getLatestTurnRowByThread({ threadId }).pipe(
Effect.mapError(
toPersistenceSqlOrDecodeError(
"ProjectionSnapshotQuery.getThreadShellById:getLatestTurn:query",
"ProjectionSnapshotQuery.getThreadShellById:getLatestTurn:decodeRow",
),
),
),
),
),
getThreadSessionRowByThread({ threadId }).pipe(
Effect.mapError(
toPersistenceSqlOrDecodeError(
"ProjectionSnapshotQuery.getThreadShellById:getSession:query",
"ProjectionSnapshotQuery.getThreadShellById:getSession:decodeRow",
getThreadSessionRowByThread({ threadId }).pipe(
Effect.mapError(
toPersistenceSqlOrDecodeError(
"ProjectionSnapshotQuery.getThreadShellById:getSession:query",
"ProjectionSnapshotQuery.getThreadShellById:getSession:decodeRow",
),
),
),
),
),
]);
getPendingTurnStartRowByThread({ threadId }).pipe(
Effect.mapError(
toPersistenceSqlOrDecodeError(
"ProjectionSnapshotQuery.getThreadShellById:getPendingTurnStart:query",
"ProjectionSnapshotQuery.getThreadShellById:getPendingTurnStart:decodeRow",
),
),
),
]);
if (Option.isNone(threadRow)) {
return Option.none<OrchestrationThreadShell>();
}
if (Option.isNone(threadRow)) {
return Option.none<OrchestrationThreadShell>();
}
return Option.some({
id: threadRow.value.threadId,
projectId: threadRow.value.projectId,
title: threadRow.value.title,
modelSelection: threadRow.value.modelSelection,
runtimeMode: threadRow.value.runtimeMode,
interactionMode: threadRow.value.interactionMode,
branch: threadRow.value.branch,
worktreePath: threadRow.value.worktreePath,
latestTurn: Option.isSome(latestTurnRow) ? mapLatestTurn(latestTurnRow.value) : null,
createdAt: threadRow.value.createdAt,
updatedAt: threadRow.value.updatedAt,
archivedAt: threadRow.value.archivedAt,
settledOverride: threadRow.value.settledOverride,
settledAt: threadRow.value.settledAt,
session: Option.isSome(sessionRow) ? mapSessionRow(sessionRow.value) : null,
latestUserMessageAt: threadRow.value.latestUserMessageAt,
hasPendingApprovals: threadRow.value.pendingApprovalCount > 0,
hasPendingUserInput: threadRow.value.pendingUserInputCount > 0,
hasActionableProposedPlan: threadRow.value.hasActionableProposedPlan > 0,
} satisfies OrchestrationThreadShell);
});
return Option.some({
id: threadRow.value.threadId,
projectId: threadRow.value.projectId,
title: threadRow.value.title,
modelSelection: threadRow.value.modelSelection,
runtimeMode: threadRow.value.runtimeMode,
interactionMode: threadRow.value.interactionMode,
branch: threadRow.value.branch,
worktreePath: threadRow.value.worktreePath,
latestTurn: Option.isSome(latestTurnRow) ? mapLatestTurn(latestTurnRow.value) : null,
createdAt: threadRow.value.createdAt,
updatedAt: threadRow.value.updatedAt,
archivedAt: threadRow.value.archivedAt,
settledOverride: threadRow.value.settledOverride,
settledAt: threadRow.value.settledAt,
session: Option.isSome(sessionRow) ? mapSessionRow(sessionRow.value) : null,
latestUserMessageAt: threadRow.value.latestUserMessageAt,
hasPendingTurnStart: Option.isSome(pendingTurnStartRow),
hasPendingApprovals: threadRow.value.pendingApprovalCount > 0,
hasPendingUserInput: threadRow.value.pendingUserInputCount > 0,
hasActionableProposedPlan: threadRow.value.hasActionableProposedPlan > 0,
} satisfies OrchestrationThreadShell);
}),
)
.pipe(
Effect.mapError((error) =>
isPersistenceError(error)
? error
: toPersistenceSqlError("ProjectionSnapshotQuery.getThreadShellById:transaction")(
error,
),
),
);
const getThreadDetailById: ProjectionSnapshotQueryShape["getThreadDetailById"] = (threadId) =>
Effect.gen(function* () {
@@ -22,7 +22,6 @@ import {
TurnId,
} from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import * as Deferred from "effect/Deferred";
import * as Exit from "effect/Exit";
import * as Layer from "effect/Layer";
import * as ManagedRuntime from "effect/ManagedRuntime";
@@ -146,9 +145,6 @@ describe("ProviderCommandReactor", () => {
readonly threadModelSelection?: ModelSelection;
readonly sessionModelSwitch?: "unsupported" | "in-session";
readonly requiresNewThreadForModelChange?: boolean;
readonly startSessionEffect?: (
session: ProviderSession,
) => Effect.Effect<ProviderSession, ProviderAdapterRequestError>;
}) {
const now = "2026-01-01T00:00:00.000Z";
const baseDir =
@@ -163,7 +159,6 @@ describe("ProviderCommandReactor", () => {
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5-codex",
};
const startSessionEffect = input?.startSessionEffect;
const startSession = vi.fn((_: unknown, input: unknown) => {
const sessionIndex = nextSessionIndex++;
const resumeCursor =
@@ -217,13 +212,8 @@ describe("ProviderCommandReactor", () => {
createdAt: now,
updatedAt: now,
};
return (startSessionEffect?.(session) ?? Effect.succeed(session)).pipe(
Effect.tap((startedSession) =>
Effect.sync(() => {
runtimeSessions.push(startedSession);
}),
),
);
runtimeSessions.push(session);
return Effect.succeed(session);
});
const sendTurn = vi.fn((_: unknown) =>
Effect.succeed({
@@ -381,6 +371,7 @@ describe("ProviderCommandReactor", () => {
Layer.provideMerge(ServerSettingsService.layerTest()),
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), baseDir)),
Layer.provideMerge(NodeServices.layer),
Layer.provide(SqlitePersistenceMemory),
);
runtime = ManagedRuntime.make(layer);
@@ -421,6 +412,7 @@ describe("ProviderCommandReactor", () => {
return {
engine,
readModel: () => Effect.runPromise(snapshotQuery.getSnapshot()),
snapshotQuery,
startSession,
sendTurn,
interruptTurn,
@@ -473,75 +465,26 @@ describe("ProviderCommandReactor", () => {
const readModel = await harness.readModel();
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
expect(thread?.session?.threadId).toBe("thread-1");
expect(thread?.session?.status).toBe("starting");
expect(thread?.session?.runtimeMode).toBe("approval-required");
});
effectIt.effect("projects starting before a slow provider session finishes", () =>
effectIt.effect("clears pending work when session startup fails before binding", () =>
Effect.gen(function* () {
const releaseStart = yield* Deferred.make<void>();
const harness = yield* Effect.promise(() =>
createHarness({
startSessionEffect: (session) => Deferred.await(releaseStart).pipe(Effect.as(session)),
}),
);
const harness = yield* Effect.promise(() => createHarness());
const now = "2026-01-01T00:00:00.000Z";
const messageId = asMessageId("user-message-start-failed");
harness.startSession.mockImplementationOnce(
(_: unknown, __: unknown) => Effect.fail("simulated startup failure") as never,
);
yield* harness.engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.make("cmd-turn-start-slow-provider"),
commandId: CommandId.make("cmd-turn-start-failed"),
threadId: ThreadId.make("thread-1"),
message: {
messageId: asMessageId("user-message-slow-provider"),
messageId,
role: "user",
text: "start slowly",
attachments: [],
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
createdAt: now,
});
yield* Effect.promise(() => waitFor(() => harness.startSession.mock.calls.length === 1));
const duringStartup = yield* Effect.promise(() => harness.readModel());
expect(
duringStartup.threads.find((entry) => entry.id === ThreadId.make("thread-1"))?.session
?.status,
).toBe("starting");
expect(harness.sendTurn).not.toHaveBeenCalled();
yield* Deferred.succeed(releaseStart, undefined);
yield* Effect.promise(() => waitFor(() => harness.sendTurn.mock.calls.length === 1));
}),
);
effectIt.effect("settles a failed provider startup and allows a clean retry", () =>
Effect.gen(function* () {
let failStartup = true;
const harness = yield* Effect.promise(() =>
createHarness({
startSessionEffect: (session) =>
failStartup
? Effect.fail(
new ProviderAdapterRequestError({
provider: "codex",
method: "thread.start",
detail: "deterministic startup failure",
}),
)
: Effect.succeed(session),
}),
);
const now = "2026-01-01T00:00:00.000Z";
yield* harness.engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.make("cmd-turn-start-provider-failure"),
threadId: ThreadId.make("thread-1"),
message: {
messageId: asMessageId("user-message-provider-failure"),
role: "user",
text: "fail once",
text: "hello reactor",
attachments: [],
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
@@ -553,37 +496,66 @@ describe("ProviderCommandReactor", () => {
waitFor(async () => {
const readModel = await harness.readModel();
return (
readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"))?.session
?.status === "error"
readModel.threads[0]?.activities.some(
(activity) => activity.kind === "provider.turn.start.failed",
) ?? false
);
}),
);
let readModel = yield* Effect.promise(() => harness.readModel());
let thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
expect(thread?.session?.lastError).toContain("deterministic startup failure");
expect(harness.sendTurn).not.toHaveBeenCalled();
failStartup = false;
const readModel = yield* harness.snapshotQuery.getSnapshot();
expect(readModel.threads[0]?.session).toBeNull();
expect(
readModel.threads[0]?.activities.find(
(activity) => activity.kind === "provider.turn.start.failed",
),
).toMatchObject({ payload: { requestId: messageId } });
const shellSnapshot = yield* harness.snapshotQuery.getShellSnapshot();
expect(shellSnapshot.threads[0]?.hasPendingTurnStart).toBe(false);
}),
);
effectIt.effect("clears pending work when turn startup is interrupted", () =>
Effect.gen(function* () {
const harness = yield* Effect.promise(() => createHarness());
const now = "2026-01-01T00:00:00.000Z";
const messageId = asMessageId("user-message-start-interrupted");
harness.sendTurn.mockImplementationOnce(() => Effect.interrupt);
yield* harness.engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.make("cmd-turn-start-provider-retry"),
commandId: CommandId.make("cmd-turn-start-interrupted"),
threadId: ThreadId.make("thread-1"),
message: {
messageId: asMessageId("user-message-provider-retry"),
messageId,
role: "user",
text: "retry",
text: "hello reactor",
attachments: [],
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
createdAt: "2026-01-01T00:00:01.000Z",
createdAt: now,
});
yield* Effect.promise(() => waitFor(() => harness.sendTurn.mock.calls.length === 1));
readModel = yield* Effect.promise(() => harness.readModel());
thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
expect(thread?.session?.status).toBe("starting");
expect(thread?.session?.lastError).toBeNull();
yield* Effect.promise(() =>
waitFor(async () => {
const readModel = await harness.readModel();
return (
readModel.threads[0]?.activities.some(
(activity) => activity.kind === "provider.turn.start.failed",
) ?? false
);
}),
);
const readModel = yield* harness.snapshotQuery.getSnapshot();
expect(
readModel.threads[0]?.activities.find(
(activity) => activity.kind === "provider.turn.start.failed",
),
).toMatchObject({ payload: { requestId: messageId } });
const shellSnapshot = yield* harness.snapshotQuery.getShellSnapshot();
expect(shellSnapshot.threads[0]?.hasPendingTurnStart).toBe(false);
}),
);
@@ -29,6 +29,8 @@ import { resolveThreadWorkspaceCwd } from "../../checkpointing/Utils.ts";
import { increment, orchestrationEventsProcessedTotal } from "../../observability/Metrics.ts";
import { ProviderAdapterRequestError } from "../../provider/Errors.ts";
import type { ProviderServiceError } from "../../provider/Errors.ts";
import { ProjectionTurnRepositoryLive } from "../../persistence/Layers/ProjectionTurns.ts";
import { ProjectionTurnRepository } from "../../persistence/Services/ProjectionTurns.ts";
import { TextGeneration } from "../../textGeneration/TextGeneration.ts";
import { ProviderService } from "../../provider/Services/ProviderService.ts";
import { ProviderRegistry } from "../../provider/Services/ProviderRegistry.ts";
@@ -190,6 +192,7 @@ const make = Effect.gen(function* () {
const crypto = yield* Crypto.Crypto;
const orchestrationEngine = yield* OrchestrationEngineService;
const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;
const projectionTurnRepository = yield* ProjectionTurnRepository;
const providerService = yield* ProviderService;
const providerRegistry = yield* ProviderRegistry;
const gitWorkflow = yield* GitWorkflowService;
@@ -288,20 +291,15 @@ const make = Effect.gen(function* () {
readonly createdAt: string;
}) {
const thread = yield* resolveThread(input.threadId);
if (!thread) {
const session = thread?.session;
if (!session) {
return;
}
const session = thread.session;
yield* setThreadSession({
threadId: input.threadId,
session: {
...(session ?? {
threadId: input.threadId,
providerName: null,
providerInstanceId: thread.modelSelection.instanceId,
runtimeMode: thread.runtimeMode,
}),
status: session?.status === "stopped" ? "stopped" : "error",
...session,
status: session.status === "stopped" ? "stopped" : "ready",
activeTurnId: null,
lastError: input.detail,
updatedAt: input.createdAt,
@@ -359,7 +357,6 @@ const make = Effect.gen(function* () {
createdAt: string,
options?: {
readonly modelSelection?: ModelSelection;
readonly pendingTurnStart?: boolean;
},
) {
const thread = yield* resolveThread(threadId);
@@ -434,22 +431,6 @@ const make = Effect.gen(function* () {
});
}
const preferredProvider: ProviderDriverKind = desiredDriverKind;
if (options?.pendingTurnStart === true && thread.session?.status !== "running") {
yield* setThreadSession({
threadId,
session: {
threadId,
status: "starting",
providerName: activeSession?.provider ?? preferredProvider,
providerInstanceId: activeSession?.providerInstanceId ?? desiredInstanceId,
runtimeMode: desiredRuntimeMode,
activeTurnId: null,
lastError: null,
updatedAt: createdAt,
},
createdAt,
});
}
if (thread.session !== null) {
yield* rejectStartedThreadModelChangeIfRequired({
threadId,
@@ -520,10 +501,7 @@ const make = Effect.gen(function* () {
threadId,
session: {
threadId,
status:
options?.pendingTurnStart === true && session.status === "ready"
? "starting"
: mapProviderSessionStatusToOrchestrationStatus(session.status),
status: mapProviderSessionStatusToOrchestrationStatus(session.status),
providerName: session.provider,
providerInstanceId: session.providerInstanceId,
runtimeMode: desiredRuntimeMode,
@@ -622,10 +600,11 @@ const make = Effect.gen(function* () {
new Error(`Thread '${input.threadId}' was not found in read model.`),
);
}
yield* ensureSessionForThread(input.threadId, input.createdAt, {
...(input.modelSelection !== undefined ? { modelSelection: input.modelSelection } : {}),
pendingTurnStart: true,
});
yield* ensureSessionForThread(
input.threadId,
input.createdAt,
input.modelSelection !== undefined ? { modelSelection: input.modelSelection } : {},
);
if (input.modelSelection !== undefined) {
threadModelSelections.set(input.threadId, input.modelSelection);
}
@@ -790,6 +769,7 @@ const make = Effect.gen(function* () {
detail: `User message '${event.payload.messageId}' was not found for turn start request.`,
turnId: null,
createdAt: event.payload.createdAt,
requestId: event.payload.messageId,
});
return;
}
@@ -825,29 +805,40 @@ const make = Effect.gen(function* () {
}
}
const handleTurnStartFailure = (cause: Cause.Cause<unknown>) => {
if (Cause.hasInterruptsOnly(cause)) {
return Effect.void;
const handleTurnStartFailure = Effect.fnUntraced(function* (cause: Cause.Cause<unknown>) {
const interrupted = Cause.hasInterruptsOnly(cause);
if (interrupted) {
const pendingTurnStart = yield* projectionTurnRepository.getPendingTurnStartByThreadId({
threadId: event.payload.threadId,
});
if (
Option.isNone(pendingTurnStart) ||
pendingTurnStart.value.messageId !== event.payload.messageId
) {
return;
}
}
const detail = formatFailureDetail(cause);
return setThreadSessionErrorOnTurnStartFailure({
const detail = interrupted
? "Provider turn start was interrupted before it began."
: formatFailureDetail(cause);
if (!interrupted) {
yield* setThreadSessionErrorOnTurnStartFailure({
threadId: event.payload.threadId,
detail,
createdAt: event.payload.createdAt,
});
}
yield* appendProviderFailureActivity({
threadId: event.payload.threadId,
kind: "provider.turn.start.failed",
summary: "Provider turn start failed",
detail,
turnId: null,
createdAt: event.payload.createdAt,
}).pipe(
Effect.flatMap(() =>
appendProviderFailureActivity({
threadId: event.payload.threadId,
kind: "provider.turn.start.failed",
summary: "Provider turn start failed",
detail,
turnId: null,
createdAt: event.payload.createdAt,
}),
),
Effect.asVoid,
);
};
requestId: event.payload.messageId,
});
});
const recoverTurnStartFailure = (cause: Cause.Cause<unknown>) =>
handleTurnStartFailure(cause).pipe(
@@ -1109,4 +1100,6 @@ const make = Effect.gen(function* () {
} satisfies ProviderCommandReactorShape;
});
export const ProviderCommandReactorLive = Layer.effect(ProviderCommandReactor, make);
export const ProviderCommandReactorLive = Layer.effect(ProviderCommandReactor, make).pipe(
Layer.provide(ProjectionTurnRepositoryLive),
);
@@ -30,7 +30,6 @@ import * as ManagedRuntime from "effect/ManagedRuntime";
import * as PubSub from "effect/PubSub";
import * as Scope from "effect/Scope";
import * as Stream from "effect/Stream";
import { it as effectIt } from "@effect/vitest";
import { afterEach, describe, expect, it } from "vite-plus/test";
import { OrchestrationEventStoreLive } from "../../persistence/Layers/OrchestrationEventStore.ts";
@@ -494,185 +493,6 @@ describe("ProviderRuntimeIngestion", () => {
expect(thread.session?.lastError).toBeNull();
});
effectIt.effect(
"keeps a reconnecting pending turn starting while ready clears stale active state",
() =>
Effect.gen(function* () {
const harness = yield* Effect.promise(() => createHarness());
const threadId = asThreadId("thread-1");
const staleTurnId = asTurnId("turn-stale-before-reconnect");
yield* harness.engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.make("cmd-turn-start-pending-reconnect"),
threadId,
message: {
messageId: MessageId.make("message-pending-reconnect"),
role: "user",
text: "resume after reconnect",
attachments: [],
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
createdAt: "2026-01-01T00:00:01.000Z",
});
yield* harness.engine.dispatch({
type: "thread.session.set",
commandId: CommandId.make("cmd-session-starting-pending-reconnect"),
threadId,
session: {
threadId,
status: "starting",
providerName: "codex",
runtimeMode: "approval-required",
activeTurnId: staleTurnId,
lastError: null,
updatedAt: "2026-01-01T00:00:01.000Z",
},
createdAt: "2026-01-01T00:00:01.000Z",
});
harness.emit({
type: "session.state.changed",
eventId: asEventId("evt-session-ready-pending-reconnect"),
provider: ProviderDriverKind.make("codex"),
threadId,
createdAt: "2026-01-01T00:00:02.000Z",
payload: { state: "ready" },
});
let thread = yield* Effect.promise(() =>
waitForThread(
harness.readModel,
(entry) => entry.session?.status === "starting" && entry.session.activeTurnId === null,
),
);
expect(thread.session?.status).toBe("starting");
expect(thread.session?.activeTurnId).toBeNull();
harness.emit({
type: "session.started",
eventId: asEventId("evt-session-started-pending-reconnect"),
provider: ProviderDriverKind.make("codex"),
threadId,
createdAt: "2026-01-01T00:00:03.000Z",
});
yield* Effect.promise(() => harness.drain());
thread = (yield* Effect.promise(() => harness.readModel())).threads.find(
(entry) => entry.id === threadId,
)!;
expect(thread.session?.status).toBe("starting");
expect(thread.session?.activeTurnId).toBeNull();
harness.emit({
type: "turn.started",
eventId: asEventId("evt-turn-started-pending-reconnect"),
provider: ProviderDriverKind.make("codex"),
threadId,
turnId: asTurnId("turn-after-reconnect"),
createdAt: "2026-01-01T00:00:04.000Z",
});
thread = yield* Effect.promise(() =>
waitForThread(
harness.readModel,
(entry) =>
entry.session?.status === "running" &&
entry.session.activeTurnId === asTurnId("turn-after-reconnect"),
),
);
expect(thread.session?.status).toBe("running");
harness.emit({
type: "session.started",
eventId: asEventId("evt-session-started-duplicate-midturn"),
provider: ProviderDriverKind.make("codex"),
threadId,
createdAt: "2026-01-01T00:00:05.000Z",
});
yield* Effect.promise(() => harness.drain());
thread = (yield* Effect.promise(() => harness.readModel())).threads.find(
(entry) => entry.id === threadId,
)!;
expect(thread.session?.status).toBe("running");
expect(thread.session?.activeTurnId).toBe(asTurnId("turn-after-reconnect"));
}),
);
effectIt.effect("keeps an aborted pending start stopped across duplicate exit events", () =>
Effect.gen(function* () {
const harness = yield* Effect.promise(() => createHarness());
const threadId = asThreadId("thread-1");
const stoppedAt = "2026-01-01T00:00:02.000Z";
yield* harness.engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.make("cmd-turn-start-before-stop"),
threadId,
message: {
messageId: MessageId.make("message-before-stop"),
role: "user",
text: "stop this startup",
attachments: [],
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
createdAt: "2026-01-01T00:00:01.000Z",
});
yield* harness.engine.dispatch({
type: "thread.session.set",
commandId: CommandId.make("cmd-session-starting-before-stop"),
threadId,
session: {
threadId,
status: "starting",
providerName: "codex",
runtimeMode: "approval-required",
activeTurnId: null,
lastError: null,
updatedAt: "2026-01-01T00:00:01.000Z",
},
createdAt: "2026-01-01T00:00:01.000Z",
});
yield* harness.engine.dispatch({
type: "thread.session.set",
commandId: CommandId.make("cmd-session-stop-pending-start"),
threadId,
session: {
threadId,
status: "stopped",
providerName: "codex",
runtimeMode: "approval-required",
activeTurnId: null,
lastError: null,
updatedAt: stoppedAt,
},
createdAt: stoppedAt,
});
harness.emit({
type: "session.exited",
eventId: asEventId("evt-session-exited-after-stop"),
provider: ProviderDriverKind.make("codex"),
threadId,
createdAt: "2026-01-01T00:00:03.000Z",
});
harness.emit({
type: "session.exited",
eventId: asEventId("evt-duplicate-session-exited-after-stop"),
provider: ProviderDriverKind.make("codex"),
threadId,
createdAt: "2026-01-01T00:00:04.000Z",
});
yield* Effect.promise(() => harness.drain());
const thread = (yield* Effect.promise(() => harness.readModel())).threads.find(
(entry) => entry.id === threadId,
);
expect(thread?.session?.status).toBe("stopped");
expect(thread?.session?.activeTurnId).toBeNull();
}),
);
it("does not clear active turn when session/thread started arrives mid-turn", async () => {
const harness = await createHarness();
const now = "2026-01-01T00:00:00.000Z";
@@ -1308,11 +1308,6 @@ const make = Effect.gen(function* () {
const now = event.createdAt;
const eventTurnId = toTurnId(event.turnId);
const activeTurnId = thread.session?.activeTurnId ?? null;
const pendingTurnStart = yield* projectionTurnRepository.getPendingTurnStartByThreadId({
threadId: thread.id,
});
const hasPendingTurnStart =
Option.isSome(pendingTurnStart) && thread.session?.status === "starting";
const conflictsWithActiveTurn =
activeTurnId !== null && eventTurnId !== undefined && !sameId(activeTurnId, eventTurnId);
@@ -1327,7 +1322,11 @@ const make = Effect.gen(function* () {
const conflictingTurnStartIsPendingTurnStart =
event.type === "turn.started" && conflictsWithActiveTurn
? sameId(yield* getExpectedProviderTurnIdForThread(thread.id), eventTurnId) &&
Option.isSome(pendingTurnStart)
Option.isSome(
yield* projectionTurnRepository.getPendingTurnStartByThreadId({
threadId: thread.id,
}),
)
: false;
const shouldApplyThreadLifecycle = (() => {
@@ -1371,10 +1370,8 @@ const make = Effect.gen(function* () {
) {
const status = (() => {
switch (event.type) {
case "session.state.changed": {
const runtimeStatus = orchestrationSessionStatusFromRuntimeState(event.payload.state);
return hasPendingTurnStart && runtimeStatus === "ready" ? "starting" : runtimeStatus;
}
case "session.state.changed":
return orchestrationSessionStatusFromRuntimeState(event.payload.state);
case "turn.started":
return "running";
case "session.exited":
@@ -1386,8 +1383,8 @@ const make = Effect.gen(function* () {
case "session.started":
case "thread.started":
// Provider thread/session start notifications can arrive during an
// active or pending turn; preserve that lifecycle state.
return activeTurnId !== null ? "running" : hasPendingTurnStart ? "starting" : "ready";
// active turn; preserve turn-running state in that case.
return activeTurnId !== null ? "running" : "ready";
}
})();
const nextActiveTurnId =
@@ -1395,10 +1392,7 @@ const make = Effect.gen(function* () {
? (eventTurnId ?? null)
: event.type === "turn.completed" || event.type === "session.exited"
? null
: event.type === "session.state.changed" &&
!sessionStatusAllowsActiveTurn(
orchestrationSessionStatusFromRuntimeState(event.payload.state),
)
: event.type === "session.state.changed" && !sessionStatusAllowsActiveTurn(status)
? null
: activeTurnId;
const lastError =
@@ -8,15 +8,9 @@ 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.provide(T3ProjectFileLoader.layer),
),
),
Layer.provideMerge(ProjectFaviconResolver.layer.pipe(Layer.provide(WorkspacePaths.layer))),
Layer.provideMerge(NodeServices.layer),
);
@@ -43,7 +37,7 @@ const writeTextFile = Effect.fn("writeTextFile")(function* (
const makeResolverWithFileSystem = (fileSystem: FileSystem.FileSystem) =>
ProjectFaviconResolver.make.pipe(
Effect.provide([WorkspacePaths.layer, T3ProjectFileLoader.layer]),
Effect.provide(WorkspacePaths.layer),
Effect.provideService(FileSystem.FileSystem, fileSystem),
);
@@ -62,63 +56,6 @@ 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,7 +16,6 @@ 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 = [
@@ -118,7 +117,6 @@ 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(/^\//, "");
@@ -179,15 +177,6 @@ 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) {
@@ -1,89 +0,0 @@
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);
}),
);
});
});
@@ -1,108 +0,0 @@
/**
* 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,25 +356,6 @@ 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,7 +3509,6 @@ 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];
@@ -1,138 +0,0 @@
import { ClaudeSettings } from "@t3tools/contracts";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, it } from "@effect/vitest";
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 {
buildClaudeCapabilitiesProbeQueryOptions,
CLAUDE_CAPABILITIES_PROBE_SETTING_SOURCES,
probeClaudeCapabilities,
} from "./ClaudeProvider.ts";
const decodeClaudeSettings = Schema.decodeSync(ClaudeSettings);
it("isolates Claude capability probes without dropping workspace setting sources", () => {
const abortController = new AbortController();
const options = buildClaudeCapabilitiesProbeQueryOptions({
executablePath: "/usr/bin/claude",
abortController,
environment: {
HOME: "/home/user",
ENABLE_CLAUDEAI_MCP_SERVERS: "true",
},
cwd: "/workspace/project",
});
assert.deepEqual(options.mcpServers, {});
assert.equal(options.strictMcpConfig, true);
assert.equal(options.cwd, "/workspace/project");
assert.deepEqual(options.settingSources, [...CLAUDE_CAPABILITIES_PROBE_SETTING_SOURCES]);
assert.deepEqual(options.allowedTools, []);
assert.equal(options.persistSession, false);
assert.equal(options.pathToClaudeCodeExecutable, "/usr/bin/claude");
assert.equal(options.abortController, abortController);
assert.equal(options.env?.HOME, "/home/user");
assert.equal(options.env?.ENABLE_CLAUDEAI_MCP_SERVERS, "false");
});
it.layer(NodeServices.layer)("Claude capability probe SDK boundary", (it) => {
it.effect("serializes strict no-MCP options and still resolves account capabilities", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const tempDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-claude-probe-sdk-" });
const executablePath = path.join(tempDir, "fake-claude.mjs");
const invocationPath = path.join(tempDir, "invocation.json");
const workspaceCwd = path.join(tempDir, "workspace");
yield* fs.makeDirectory(workspaceCwd, { recursive: true });
yield* fs.writeFileString(
executablePath,
[
"#!/usr/bin/env node",
'import { existsSync, readFileSync, writeFileSync } from "node:fs";',
'import { createInterface } from "node:readline";',
"const args = process.argv.slice(2);",
'const mcpConfigIndex = args.indexOf("--mcp-config");',
"const rawMcpConfig = mcpConfigIndex >= 0 ? args[mcpConfigIndex + 1] : undefined;",
"let mcpConfig;",
"if (rawMcpConfig) {",
' const contents = existsSync(rawMcpConfig) ? readFileSync(rawMcpConfig, "utf8") : rawMcpConfig;',
" try { mcpConfig = JSON.parse(contents); } catch { mcpConfig = contents; }",
"}",
"writeFileSync(process.env.T3_PROBE_INVOCATION_PATH, JSON.stringify({",
" args,",
" cwd: process.cwd(),",
" connectorEnv: process.env.ENABLE_CLAUDEAI_MCP_SERVERS,",
" mcpConfig,",
"}));",
"const lines = createInterface({ input: process.stdin });",
'lines.on("line", (line) => {',
" const message = JSON.parse(line);",
' if (message.type !== "control_request" || message.request?.subtype !== "initialize") return;',
" process.stdout.write(JSON.stringify({",
' type: "control_response",',
" response: {",
' subtype: "success",',
" request_id: message.request_id,",
" response: {",
' commands: [{ name: "review", description: "Review changes", argumentHint: "[path]" }],',
" agents: [],",
' output_style: "default",',
' available_output_styles: ["default"],',
" models: [],",
' account: { email: "[email protected]", subscriptionType: "pro", tokenSource: "oauth" },',
" },",
" },",
' }) + "\\n");',
"});",
"setInterval(() => {}, 1_000);",
"",
].join("\n"),
);
yield* fs.chmod(executablePath, 0o755);
const capabilities = yield* probeClaudeCapabilities(
decodeClaudeSettings({ binaryPath: executablePath }),
{
...process.env,
T3_PROBE_INVOCATION_PATH: invocationPath,
ENABLE_CLAUDEAI_MCP_SERVERS: "true",
},
workspaceCwd,
);
assert.deepEqual(capabilities, {
email: "[email protected]",
subscriptionType: "pro",
tokenSource: "oauth",
apiProvider: undefined,
slashCommands: [
{
name: "review",
description: "Review changes",
input: { hint: "[path]" },
},
],
});
// @effect-diagnostics-next-line preferSchemaOverJson:off
const invocation = JSON.parse(yield* fs.readFileString(invocationPath)) as {
readonly args: ReadonlyArray<string>;
readonly cwd: string;
readonly connectorEnv: string;
readonly mcpConfig: unknown;
};
assert.equal(invocation.cwd, yield* fs.realPath(workspaceCwd));
assert.equal(invocation.connectorEnv, "false");
assert.equal(invocation.args.includes("--strict-mcp-config"), true);
assert.equal(invocation.args.includes("--mcp-config"), false);
assert.equal(invocation.mcpConfig, undefined);
assert.equal(invocation.args.includes("--setting-sources=user,project,local"), true);
}).pipe(Effect.scoped),
);
});
@@ -21,10 +21,8 @@ import { resolveSpawnCommand } from "@t3tools/shared/shell";
import { compareSemverVersions } from "@t3tools/shared/semver";
import {
query as claudeQuery,
type Options as ClaudeQueryOptions,
type SlashCommand as ClaudeSlashCommand,
type SDKUserMessage,
type SettingSource,
} from "@anthropic-ai/claude-agent-sdk";
import {
@@ -510,44 +508,6 @@ function apiProviderAuthMetadata(
// `undefined` and left the provider unverified and unselectable in the picker.
const CAPABILITIES_PROBE_TIMEOUT_MS = 25_000;
/**
* Keep workspace-scoped command discovery intact while isolating the periodic
* health check from configured MCP servers.
*/
export const CLAUDE_CAPABILITIES_PROBE_SETTING_SOURCES = [
"user",
"project",
"local",
] as const satisfies ReadonlyArray<SettingSource>;
/** Build the exact SDK options used by the periodic Claude capability probe. */
export function buildClaudeCapabilitiesProbeQueryOptions(input: {
readonly executablePath: string;
readonly abortController: AbortController;
readonly environment: NodeJS.ProcessEnv;
readonly cwd: string | undefined;
}): ClaudeQueryOptions {
return {
persistSession: false,
pathToClaudeCodeExecutable: input.executablePath,
abortController: input.abortController,
settingSources: [...CLAUDE_CAPABILITIES_PROBE_SETTING_SOURCES],
allowedTools: [],
// Ignore MCP definitions from every filesystem setting source above. The
// SDK combines this empty explicit map with --strict-mcp-config.
mcpServers: {},
strictMcpConfig: true,
env: {
...input.environment,
// Connected claude.ai MCP servers are discovered outside filesystem
// config; disable them independently for this health check.
ENABLE_CLAUDEAI_MCP_SERVERS: "false",
},
...(input.cwd ? { cwd: input.cwd } : {}),
stderr: () => {},
};
}
function nonEmptyProbeString(value: string): string | undefined {
const candidate = value.trim();
return candidate ? candidate : undefined;
@@ -671,12 +631,16 @@ const probeClaudeCapabilities = (
prompt: (async function* (): AsyncGenerator<SDKUserMessage> {
await waitForAbortSignal(abort.signal);
})(),
options: buildClaudeCapabilitiesProbeQueryOptions({
executablePath,
options: {
persistSession: false,
pathToClaudeCodeExecutable: executablePath,
abortController: abort,
environment: claudeEnvironment,
cwd,
}),
settingSources: ["user", "project", "local"],
allowedTools: [],
env: claudeEnvironment,
...(cwd ? { cwd } : {}),
stderr: () => {},
},
});
const init = await q.initializationResult();
const account = init.account as
@@ -104,7 +104,6 @@ describe("buildTurnStartParams", () => {
NodeAssert.deepStrictEqual(params, {
threadId: "provider-thread-1",
approvalPolicy: "never",
approvalsReviewer: "user",
sandboxPolicy: {
type: "dangerFullAccess",
},
@@ -150,7 +149,6 @@ describe("buildTurnStartParams", () => {
NodeAssert.deepStrictEqual(params, {
threadId: "provider-thread-1",
approvalPolicy: "on-request",
approvalsReviewer: "user",
sandboxPolicy: {
type: "workspaceWrite",
},
@@ -195,31 +193,6 @@ 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({
@@ -232,7 +205,6 @@ describe("buildTurnStartParams", () => {
NodeAssert.deepStrictEqual(params, {
threadId: "provider-thread-1",
approvalPolicy: "untrusted",
approvalsReviewer: "user",
sandboxPolicy: {
type: "readOnly",
},
@@ -264,35 +264,23 @@ 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",
};
}
}
@@ -308,7 +296,6 @@ 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 } : {}),
};
@@ -323,7 +310,6 @@ function runtimeModeToTurnSandboxPolicy(
type: "readOnly",
};
case "auto-accept-edits":
case "auto":
return {
type: "workspaceWrite",
};
@@ -396,7 +382,6 @@ 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 } : {}),
@@ -97,13 +97,10 @@ const OpenCodeRuntimeTestDouble: OpenCodeRuntimeShape = {
: Effect.succeed(runtimeMock.state.inventory as OpenCodeInventory),
loadInventoryFromCli: () =>
runtimeMock.state.inventoryError
? Effect.fail(
new OpenCodeRuntimeError({
operation: "loadInventoryFromCli",
detail: runtimeMock.state.inventoryError.message,
cause: runtimeMock.state.inventoryError,
}),
)
? Effect.succeed({
providerList: { all: [], default: {}, connected: [] as string[] },
agents: [],
} as OpenCodeInventory)
: Effect.succeed(runtimeMock.state.inventory as OpenCodeInventory),
};
@@ -215,18 +212,14 @@ it.layer(testLayer)("checkOpenCodeProviderStatus", (it) => {
}),
);
it.effect("reports local model inventory failures without treating them as empty", () =>
it.effect("degrades gracefully on CLI failure for local installs", () =>
Effect.gen(function* () {
runtimeMock.state.inventoryError = new Error("opencode models failed");
const snapshot = yield* checkOpenCodeProviderStatus(makeOpenCodeSettings(), process.cwd());
NodeAssert.equal(snapshot.status, "error");
NodeAssert.equal(snapshot.status, "warning");
NodeAssert.equal(snapshot.installed, true);
NodeAssert.equal(snapshot.models.length, 0);
NodeAssert.equal(
snapshot.message,
"Failed to execute OpenCode CLI health check: opencode models failed",
);
}),
);
});
@@ -563,176 +563,6 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsModule.layerTest(), Te
]);
});
it("drops stale OpenCode models missing from a successful refresh", () => {
const previousProvider = {
instanceId: ProviderInstanceId.make("opencode"),
driver: ProviderDriverKind.make("opencode"),
status: "ready",
enabled: true,
installed: true,
auth: { status: "authenticated" },
checkedAt: "2026-07-17T00:00:00.000Z",
version: "1.0.0",
models: [
{
slug: "github/gpt-5",
name: "GPT-5",
subProvider: "GitHub",
isCustom: false,
capabilities: null,
},
{
slug: "removed-plugin/model",
name: "Removed Plugin Model",
subProvider: "Removed Plugin",
isCustom: false,
capabilities: null,
},
],
slashCommands: [],
skills: [],
} as const satisfies ServerProvider;
const refreshedProvider = {
...previousProvider,
checkedAt: "2026-07-17T00:01:00.000Z",
models: [
{
slug: "github/gpt-5",
name: "GPT-5",
subProvider: "GitHub",
isCustom: false,
capabilities: null,
},
],
} satisfies ServerProvider;
assert.deepStrictEqual(mergeProviderSnapshot(previousProvider, refreshedProvider).models, [
...refreshedProvider.models,
]);
});
it("retains stale OpenCode models when a refresh fails", () => {
const previousProvider = {
instanceId: ProviderInstanceId.make("opencode"),
driver: ProviderDriverKind.make("opencode"),
status: "ready",
enabled: true,
installed: true,
auth: { status: "authenticated" },
checkedAt: "2026-07-17T00:00:00.000Z",
version: "1.0.0",
models: [
{
slug: "github/gpt-5",
name: "GPT-5",
subProvider: "GitHub",
isCustom: false,
capabilities: null,
},
],
slashCommands: [],
skills: [],
} as const satisfies ServerProvider;
const refreshedProvider = {
...previousProvider,
status: "error",
auth: { status: "unknown" },
checkedAt: "2026-07-17T00:01:00.000Z",
models: [],
message: "Failed to refresh OpenCode models.",
} satisfies ServerProvider;
assert.deepStrictEqual(mergeProviderSnapshot(previousProvider, refreshedProvider).models, [
...previousProvider.models,
]);
});
it("classifies pending, logout, uninstall, and reconnect OpenCode inventories", () => {
const previousProvider = {
instanceId: ProviderInstanceId.make("opencode"),
driver: ProviderDriverKind.make("opencode"),
status: "ready",
enabled: true,
installed: true,
auth: { status: "authenticated" },
checkedAt: "2026-07-17T00:00:00.000Z",
version: "1.0.0",
models: [
{
slug: "github/gpt-5",
name: "GPT-5",
subProvider: "GitHub",
isCustom: false,
capabilities: null,
},
{
slug: "removed-plugin/model",
name: "Removed Plugin Model",
subProvider: "Removed Plugin",
isCustom: false,
capabilities: null,
},
],
slashCommands: [],
skills: [],
} as const satisfies ServerProvider;
const pendingProvider = {
...previousProvider,
status: "warning",
installed: false,
auth: { status: "unknown" },
checkedAt: "2026-07-17T00:01:00.000Z",
version: null,
models: [],
message: "OpenCode provider status has not been checked in this session yet.",
} satisfies ServerProvider;
const loggedOutProvider = {
...previousProvider,
status: "warning",
auth: { status: "unknown" },
checkedAt: "2026-07-17T00:02:00.000Z",
models: [],
message: "OpenCode is available, but it did not report any connected upstream providers.",
} satisfies ServerProvider;
const missingProvider = {
...previousProvider,
status: "error",
installed: false,
auth: { status: "unknown" },
checkedAt: "2026-07-17T00:03:00.000Z",
version: null,
models: [],
message: "OpenCode CLI (`opencode`) is not installed or not on PATH.",
} satisfies ServerProvider;
const authoritativeProvider = {
...previousProvider,
checkedAt: "2026-07-17T00:04:00.000Z",
models: [previousProvider.models[0]!],
} satisfies ServerProvider;
const failedProvider = {
...authoritativeProvider,
status: "error",
auth: { status: "unknown" },
checkedAt: "2026-07-17T00:05:00.000Z",
models: [],
message: "Failed to refresh OpenCode models.",
} satisfies ServerProvider;
assert.deepStrictEqual(mergeProviderSnapshot(previousProvider, pendingProvider).models, [
...previousProvider.models,
]);
assert.deepStrictEqual(
mergeProviderSnapshot(previousProvider, loggedOutProvider).models,
[],
);
assert.deepStrictEqual(mergeProviderSnapshot(previousProvider, missingProvider).models, []);
const afterRemoval = mergeProviderSnapshot(previousProvider, authoritativeProvider);
const afterFailure = mergeProviderSnapshot(afterRemoval, failedProvider);
assert.deepStrictEqual(afterFailure.models, [authoritativeProvider.models[0]!]);
});
it("fills missing capabilities from the previous provider snapshot", () => {
const previousProvider = {
instanceId: ProviderInstanceId.make("cursor"),
@@ -1036,144 +866,6 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsModule.layerTest(), Te
}),
);
it.effect(
"persists authoritative OpenCode removals without resurrecting them on a failed live refresh",
() =>
Effect.gen(function* () {
const openCodeDriver = ProviderDriverKind.make("opencode");
const openCodeInstanceId = ProviderInstanceId.make("opencode");
const initialProvider = {
instanceId: openCodeInstanceId,
driver: openCodeDriver,
status: "ready",
enabled: true,
installed: true,
auth: { status: "authenticated" },
checkedAt: "2026-07-17T00:00:00.000Z",
version: "1.0.0",
models: [
{
slug: "github/gpt-5",
name: "GPT-5",
subProvider: "GitHub",
isCustom: false,
capabilities: null,
},
{
slug: "removed-plugin/model",
name: "Removed Plugin Model",
subProvider: "Removed Plugin",
isCustom: false,
capabilities: null,
},
],
slashCommands: [],
skills: [],
} as const satisfies ServerProvider;
const authoritativeProvider = {
...initialProvider,
checkedAt: "2026-07-17T00:01:00.000Z",
models: [initialProvider.models[0]!],
} satisfies ServerProvider;
const failedProvider = {
...authoritativeProvider,
status: "error",
auth: { status: "unknown" },
checkedAt: "2026-07-17T00:02:00.000Z",
models: [],
message: "Failed to refresh OpenCode models.",
} satisfies ServerProvider;
const changes = yield* PubSub.unbounded<ServerProvider>();
const instance = {
instanceId: openCodeInstanceId,
driverKind: openCodeDriver,
continuationIdentity: {
driverKind: openCodeDriver,
continuationKey: "opencode:instance:opencode",
},
displayName: undefined,
enabled: true,
snapshot: {
maintenanceCapabilities: makeManualOnlyProviderMaintenanceCapabilities({
provider: openCodeDriver,
packageName: null,
}),
getSnapshot: Effect.succeed(initialProvider),
refresh: Effect.succeed(authoritativeProvider),
streamChanges: Stream.fromPubSub(changes),
},
adapter: {} as ProviderInstance["adapter"],
textGeneration: {} as ProviderInstance["textGeneration"],
} satisfies ProviderInstance;
const instanceRegistryLayer = Layer.succeed(
ProviderInstanceRegistry.ProviderInstanceRegistry,
{
getInstance: (instanceId) =>
Effect.succeed(instanceId === openCodeInstanceId ? instance : undefined),
listInstances: Effect.succeed([instance]),
listUnavailable: Effect.succeed([]),
streamChanges: Stream.empty,
subscribeChanges: Effect.flatMap(PubSub.unbounded<void>(), (pubsub) =>
PubSub.subscribe(pubsub),
),
},
);
const scope = yield* Scope.make();
yield* Effect.addFinalizer(() => Scope.close(scope, Exit.void));
const runtimeServices = yield* Layer.build(
ProviderRegistryLive.pipe(
Layer.provideMerge(instanceRegistryLayer),
Layer.provideMerge(
ServerConfig.layerTest(process.cwd(), {
prefix: "t3-provider-registry-opencode-authoritative-persist-",
}),
),
Layer.provideMerge(NodeServices.layer),
),
).pipe(Scope.provide(scope));
yield* Effect.gen(function* () {
const registry = yield* ProviderRegistry.ProviderRegistry;
const config = yield* ServerConfig.ServerConfig;
const filePath = yield* resolveProviderStatusCachePath({
cacheDir: config.providerStatusCacheDir,
instanceId: openCodeInstanceId,
});
yield* PubSub.publish(changes, authoritativeProvider);
let cachedProvider = yield* readProviderStatusCache(filePath);
for (
let attempt = 0;
attempt < 50 && cachedProvider?.checkedAt !== authoritativeProvider.checkedAt;
attempt += 1
) {
yield* TestClock.adjust("10 millis");
yield* Effect.yieldNow;
cachedProvider = yield* readProviderStatusCache(filePath);
}
assert.deepStrictEqual(cachedProvider?.models, [authoritativeProvider.models[0]!]);
yield* PubSub.publish(changes, failedProvider);
for (
let attempt = 0;
attempt < 50 && cachedProvider?.checkedAt !== failedProvider.checkedAt;
attempt += 1
) {
yield* TestClock.adjust("10 millis");
yield* Effect.yieldNow;
cachedProvider = yield* readProviderStatusCache(filePath);
}
assert.deepStrictEqual(cachedProvider?.models, [authoritativeProvider.models[0]!]);
assert.deepStrictEqual((yield* registry.getProviders)[0]?.models, [
authoritativeProvider.models[0]!,
]);
}).pipe(Effect.provide(runtimeServices));
}),
);
it.effect("returns the cached provider list when a manual refresh fails", () =>
Effect.gen(function* () {
const codexDriver = ProviderDriverKind.make("codex");
@@ -78,31 +78,11 @@ const makeManualProviderMaintenanceCapabilities = (provider: ProviderDriverKind)
const hasModelCapabilities = (model: ServerProvider["models"][number]): boolean =>
(model.capabilities?.optionDescriptors?.length ?? 0) > 0;
const shouldRetainMissingProviderModels = (provider: ServerProvider): boolean => {
if (provider.driver !== ProviderDriverKind.make("opencode")) {
return true;
}
// OpenCode's initial snapshot is deliberately non-authoritative while its
// first probe is still running. A probe error from an installed CLI/server
// is likewise partial: it could not establish the current inventory.
// Conversely, disabled and missing-CLI snapshots are authoritative removals,
// as are successful ready/warning inventories (including an empty one after
// logout or plugin removal).
const isPendingInitialProbe =
provider.enabled && !provider.installed && provider.status === "warning";
const didInstalledProviderProbeFail = provider.installed && provider.status === "error";
return isPendingInitialProbe || didInstalledProviderProbeFail;
};
const mergeProviderModels = (
provider: ServerProvider,
previousModels: ReadonlyArray<ServerProvider["models"][number]>,
nextModels: ReadonlyArray<ServerProvider["models"][number]>,
): ReadonlyArray<ServerProvider["models"][number]> => {
const shouldRetainMissingModels = shouldRetainMissingProviderModels(provider);
if (shouldRetainMissingModels && nextModels.length === 0 && previousModels.length > 0) {
if (nextModels.length === 0 && previousModels.length > 0) {
return previousModels;
}
@@ -118,9 +98,7 @@ const mergeProviderModels = (
};
});
const nextSlugs = new Set(nextModels.map((model) => model.slug));
return shouldRetainMissingModels
? [...mergedModels, ...previousModels.filter((model) => !nextSlugs.has(model.slug))]
: mergedModels;
return [...mergedModels, ...previousModels.filter((model) => !nextSlugs.has(model.slug))];
};
export const mergeProviderSnapshot = (
@@ -131,7 +109,7 @@ export const mergeProviderSnapshot = (
? nextProvider
: {
...nextProvider,
models: mergeProviderModels(nextProvider, previousProvider.models, nextProvider.models),
models: mergeProviderModels(previousProvider.models, nextProvider.models),
};
export const mergeProviderSnapshots = (
+12 -26
View File
@@ -690,36 +690,22 @@ const makeOpenCodeRuntime = Effect.gen(function* () {
agentsResult = a2;
}
if (modelsResult._tag === "Failure") {
const cause = Cause.squash(modelsResult.cause);
return yield* ensureRuntimeError(
"loadInventoryFromCli",
`Failed to load OpenCode models: ${openCodeRuntimeErrorDetail(cause)}`,
cause,
);
}
if (modelsResult.value.code !== 0) {
return yield* new OpenCodeRuntimeError({
operation: "loadInventoryFromCli",
detail: `OpenCode models command exited with code ${modelsResult.value.code}.`,
});
}
const parsed = parseModelsCliOutput(modelsResult.value.stdout);
const connected = [...parsed.connected];
const allProviders: ProviderListResponse["all"] = [...parsed.providers.values()].map(
(provider) => ({
id: provider.id,
name: provider.name,
// Degrade gracefully on failure — return empty inventory (warning status, not error)
let connected: string[] = [];
let allProviders: ProviderListResponse["all"] = [];
if (modelsResult._tag === "Success" && modelsResult.value.code === 0) {
const parsed = parseModelsCliOutput(modelsResult.value.stdout);
connected = [...parsed.connected];
allProviders = [...parsed.providers.values()].map((p) => ({
id: p.id,
name: p.name,
source: "config" as const,
env: [],
options: {},
models: provider.models,
}),
);
models: p.models,
}));
}
// Agent metadata enriches model capabilities but is not required for an
// authoritative model inventory, so it may still degrade to an empty list.
let agents: ReadonlyArray<Agent> = [];
if (agentsResult._tag === "Success" && agentsResult.value.code === 0) {
agents = parseAgentListCliOutput(agentsResult.value.stdout);
+1 -8
View File
@@ -92,7 +92,6 @@ 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";
@@ -502,10 +501,7 @@ const buildAppUnderTest = (options?: {
Layer.provide(WorkspacePaths.layer),
Layer.provide(workspaceEntriesLayer),
),
ProjectFaviconResolver.layer.pipe(
Layer.provide(WorkspacePaths.layer),
Layer.provide(T3ProjectFileLoader.layer),
),
ProjectFaviconResolver.layer.pipe(Layer.provide(WorkspacePaths.layer)),
);
const gitWorkflowLayer = GitWorkflowService.layer.pipe(
Layer.provideMerge(vcsDriverRegistryLayer),
@@ -5289,7 +5285,6 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
gitManager: {
invalidateLocalStatus: () => Effect.void,
invalidateRemoteStatus: () => Effect.void,
invalidateStatus: () => Effect.void,
localStatus: () =>
Effect.succeed({
isRepo: true,
@@ -5336,7 +5331,6 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
gitManager: {
invalidateLocalStatus: () => Effect.void,
invalidateRemoteStatus: () => Effect.void,
invalidateStatus: () => Effect.void,
localStatus: () =>
Effect.succeed({
isRepo: true,
@@ -5413,7 +5407,6 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
gitManager: {
invalidateLocalStatus: () => Effect.void,
invalidateRemoteStatus: () => Effect.void,
invalidateStatus: () => Effect.void,
localStatus: () =>
Deferred.succeed(localRefreshStarted, undefined).pipe(
Effect.ignore,
+1 -8
View File
@@ -54,7 +54,6 @@ 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";
@@ -80,7 +79,6 @@ 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";
@@ -266,7 +264,6 @@ const WorkspaceLayerLive = Layer.mergeAll(
const ProjectFaviconResolverLayerLive = ProjectFaviconResolver.layer.pipe(
Layer.provide(WorkspacePaths.layer),
Layer.provide(T3ProjectFileLoader.layer),
);
const AuthLayerLive = EnvironmentAuth.layer.pipe(
@@ -364,11 +361,7 @@ export const makeRoutesLayer = Layer.mergeAll(
websocketRpcRouteLayer,
),
McpHttpServer.layer.pipe(Layer.provide(McpSessionRegistry.layer)),
).pipe(
Layer.provide(PreviewAutomationBroker.layer),
Layer.provide(ServerSelfUpdate.layer),
Layer.provide(browserApiCorsLayer),
);
).pipe(Layer.provide(PreviewAutomationBroker.layer), Layer.provide(browserApiCorsLayer));
export const makeServerLayer = Layer.unwrap(
Effect.gen(function* () {
@@ -208,61 +208,6 @@ describe("GitHubCli.layer", () => {
}).pipe(Effect.provide(layer)),
);
it.effect("keeps pull requests from gh versions without headRepository.nameWithOwner", () =>
// gh < 2.47 (e.g. Ubuntu-packaged 2.46) exports headRepository as
// {id, name} only. These entries must decode instead of being dropped,
// with nameWithOwner rebuilt from the owner login.
Effect.gen(function* () {
mockRun.mockReturnValueOnce(
Effect.succeed(
processOutput(
// @effect-diagnostics-next-line preferSchemaOverJson:off
JSON.stringify([
{
number: 2829,
title: "Codex turn mapping",
url: "https://github.com/pingdotgg/codething-mvp/pull/2829",
baseRefName: "main",
headRefName: "t3code/codex-turn-mapping",
state: "OPEN",
mergedAt: null,
isCrossRepository: false,
headRepository: {
id: "R_kgDORLtfbQ",
name: "codething-mvp",
},
headRepositoryOwner: {
id: "MDEyOk9yZ2FuaXphdGlvbjg5MTkxNzI3",
login: "pingdotgg",
},
},
]),
),
),
);
const gh = yield* GitHubCli.GitHubCli;
const result = yield* gh.listOpenPullRequests({
cwd: "/repo",
headSelector: "t3code/codex-turn-mapping",
});
assert.deepStrictEqual(result, [
{
number: 2829,
title: "Codex turn mapping",
url: "https://github.com/pingdotgg/codething-mvp/pull/2829",
baseRefName: "main",
headRefName: "t3code/codex-turn-mapping",
state: "open",
isCrossRepository: false,
headRepositoryNameWithOwner: "pingdotgg/codething-mvp",
headRepositoryOwnerLogin: "pingdotgg",
},
]);
}).pipe(Effect.provide(layer)),
);
it.effect("reads repository clone URLs", () =>
Effect.gen(function* () {
mockRun.mockReturnValueOnce(
@@ -30,21 +30,17 @@ const GitHubPullRequestSchema = Schema.Struct({
mergedAt: Schema.optional(Schema.NullOr(Schema.String)),
updatedAt: Schema.optional(Schema.OptionFromNullOr(Schema.DateTimeUtcFromString)),
isCrossRepository: Schema.optional(Schema.Boolean),
// gh < 2.47 exports headRepository as {id, name} only; nameWithOwner was
// added later. Both fields stay optional so a version-drifted gh CLI can
// never fail the decode and silently drop the PR from the list.
headRepository: Schema.optional(
Schema.NullOr(
Schema.Struct({
nameWithOwner: Schema.optional(Schema.NullOr(Schema.String)),
name: Schema.optional(Schema.NullOr(Schema.String)),
nameWithOwner: Schema.String,
}),
),
),
headRepositoryOwner: Schema.optional(
Schema.NullOr(
Schema.Struct({
login: Schema.optional(Schema.NullOr(Schema.String)),
login: Schema.String,
}),
),
),
@@ -75,15 +71,11 @@ function normalizeGitHubPullRequestState(input: {
function normalizeGitHubPullRequestRecord(
raw: Schema.Schema.Type<typeof GitHubPullRequestSchema>,
): NormalizedGitHubPullRequestRecord {
const explicitNameWithOwner = trimOptionalString(raw.headRepository?.nameWithOwner);
const headRepositoryName = trimOptionalString(raw.headRepository?.name);
const headRepositoryNameWithOwner = trimOptionalString(raw.headRepository?.nameWithOwner);
const headRepositoryOwnerLogin =
trimOptionalString(raw.headRepositoryOwner?.login) ??
(explicitNameWithOwner?.includes("/") ? (explicitNameWithOwner.split("/")[0] ?? null) : null);
const headRepositoryNameWithOwner =
explicitNameWithOwner ??
(headRepositoryOwnerLogin && headRepositoryName
? `${headRepositoryOwnerLogin}/${headRepositoryName}`
(typeof headRepositoryNameWithOwner === "string" && headRepositoryNameWithOwner.includes("/")
? (headRepositoryNameWithOwner.split("/")[0] ?? null)
: null);
return {
@@ -1,152 +0,0 @@
import { describe, expect, it } from "vite-plus/test";
import {
classifyCheckpointPaths,
formatCheckpointCommitMessage,
parseCheckpointCommitMessage,
parseRawDiffEntries,
type RawDiffEntry,
} from "./CheckpointAttribution.ts";
const ZERO_OID = "0".repeat(40);
function entry(overrides: Partial<RawDiffEntry> & { path: string }): RawDiffEntry {
return {
srcMode: "100644",
dstMode: "100644",
srcOid: "a".repeat(40),
dstOid: "b".repeat(40),
status: "M",
...overrides,
};
}
describe("checkpoint commit message metadata", () => {
it("round-trips head and branch", () => {
const message = formatCheckpointCommitMessage({
checkpointRef: "refs/t3/checkpoints/x/turn/3",
headOid: "c".repeat(40),
branch: "feature/attribution",
});
expect(parseCheckpointCommitMessage(message)).toEqual({
headOid: "c".repeat(40),
branch: "feature/attribution",
});
});
it("round-trips null head (unborn HEAD)", () => {
const message = formatCheckpointCommitMessage({
checkpointRef: "refs/t3/checkpoints/x/turn/0",
headOid: null,
branch: null,
});
expect(parseCheckpointCommitMessage(message)).toEqual({ headOid: null, branch: null });
});
it("returns null for legacy messages without metadata", () => {
expect(parseCheckpointCommitMessage("t3 checkpoint ref=refs/t3/checkpoints/x/turn/1")).toBe(
null,
);
});
});
describe("parseRawDiffEntries", () => {
it("parses NUL-separated raw records", () => {
const src = "a".repeat(40);
const dst = "b".repeat(40);
const output = `:100644 100644 ${src} ${dst} M\0src/index.ts\0:000000 100644 ${ZERO_OID} ${dst} A\0new file.ts\0`;
expect(parseRawDiffEntries(output)).toEqual([
{
srcMode: "100644",
dstMode: "100644",
srcOid: src,
dstOid: dst,
status: "M",
path: "src/index.ts",
},
{
srcMode: "000000",
dstMode: "100644",
srcOid: ZERO_OID,
dstOid: dst,
status: "A",
path: "new file.ts",
},
]);
});
it("returns empty for empty output", () => {
expect(parseRawDiffEntries("")).toEqual([]);
});
});
describe("classifyCheckpointPaths", () => {
it("attributes a pull-only change to git", () => {
const pulled = entry({ path: "upstream.ts" });
const origins = classifyCheckpointPaths({
treeDelta: [pulled],
historyDelta: [pulled],
turnAuthoredPaths: new Set(),
});
expect(origins.get("upstream.ts")).toBe("git");
});
it("attributes tool edits to agent (no history match)", () => {
const origins = classifyCheckpointPaths({
treeDelta: [entry({ path: "edited.ts" })],
historyDelta: [],
turnAuthoredPaths: new Set(),
});
expect(origins.get("edited.ts")).toBe("agent");
});
it("keeps a file the agent committed during the turn as agent work", () => {
const committed = entry({ path: "committed.ts" });
const origins = classifyCheckpointPaths({
treeDelta: [committed],
historyDelta: [committed],
turnAuthoredPaths: new Set(["committed.ts"]),
});
expect(origins.get("committed.ts")).toBe("agent");
});
it("attributes a pulled-then-edited file to agent (blob transition differs)", () => {
const origins = classifyCheckpointPaths({
treeDelta: [entry({ path: "both.ts", dstOid: "d".repeat(40) })],
historyDelta: [entry({ path: "both.ts", dstOid: "e".repeat(40) })],
turnAuthoredPaths: new Set(),
});
expect(origins.get("both.ts")).toBe("agent");
});
it("attributes mode-only mismatches to agent", () => {
const origins = classifyCheckpointPaths({
treeDelta: [entry({ path: "script.sh", dstMode: "100755" })],
historyDelta: [entry({ path: "script.sh", dstMode: "100644" })],
turnAuthoredPaths: new Set(),
});
expect(origins.get("script.sh")).toBe("agent");
});
it("attributes checkout deletions and additions to git", () => {
const removed = entry({
path: "only-on-old-branch.ts",
dstMode: "000000",
dstOid: ZERO_OID,
status: "D",
});
const added = entry({
path: "only-on-new-branch.ts",
srcMode: "000000",
srcOid: ZERO_OID,
status: "A",
});
const origins = classifyCheckpointPaths({
treeDelta: [removed, added],
historyDelta: [removed, added],
turnAuthoredPaths: new Set(),
});
expect(origins.get("only-on-old-branch.ts")).toBe("git");
expect(origins.get("only-on-new-branch.ts")).toBe("git");
});
});
Binary file not shown.
+3 -286
View File
@@ -29,12 +29,6 @@ import {
type VcsStatusResult,
} from "@t3tools/contracts";
import { makeGitVcsDriverCore } from "./GitVcsDriverCore.ts";
import {
classifyCheckpointPaths,
formatCheckpointCommitMessage,
parseCheckpointCommitMessage,
parseRawDiffEntries,
} from "./CheckpointAttribution.ts";
import * as VcsDriver from "./VcsDriver.ts";
import * as VcsProcess from "./VcsProcess.ts";
@@ -642,22 +636,6 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* (
}),
);
const resolveHeadBranch = (cwd: string) =>
execute({
operation: "GitVcsDriver.checkpoints.resolveHeadBranch",
cwd,
args: ["symbolic-ref", "--short", "--quiet", "HEAD"],
allowNonZeroExit: true,
}).pipe(
Effect.map((result) => {
if (result.exitCode !== 0) {
return null;
}
const branch = result.stdout.trim();
return branch.length > 0 ? branch : null;
}),
);
const resolveGitCommonDir = (cwd: string) =>
Effect.gen(function* () {
const result = yield* execute({
@@ -691,9 +669,8 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* (
.pipe(Effect.ignore);
yield* Effect.gen(function* () {
const headCommit = yield* resolveHeadCommit(input.cwd);
const headBranch = yield* resolveHeadBranch(input.cwd);
if (headCommit) {
const headExists = yield* hasHeadCommit(input.cwd);
if (headExists) {
yield* execute({
operation,
cwd: input.cwd,
@@ -726,11 +703,7 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* (
});
}
const message = formatCheckpointCommitMessage({
checkpointRef: input.checkpointRef,
headOid: headCommit,
branch: headBranch,
});
const message = `t3 checkpoint ref=${input.checkpointRef}`;
const commitTreeResult = yield* execute({
operation,
cwd: input.cwd,
@@ -875,262 +848,6 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* (
);
},
),
attributeCheckpointDiff: Effect.fn("GitVcsDriver.checkpoints.attributeCheckpointDiff")(
function* (input) {
const operation = "GitVcsDriver.checkpoints.attributeCheckpointDiff";
const readCommitField = (revision: string, format: string) =>
execute({
operation,
cwd: input.cwd,
args: ["log", "-1", `--format=${format}`, revision, "--"],
allowNonZeroExit: true,
}).pipe(Effect.map((result) => (result.exitCode === 0 ? result.stdout.trimEnd() : null)));
const fromMessage = yield* readCommitField(`${input.fromCheckpointRef}^{commit}`, "%B");
const toMessage = yield* readCommitField(`${input.toCheckpointRef}^{commit}`, "%B");
if (fromMessage === null || toMessage === null) {
return null;
}
const fromMetadata = parseCheckpointCommitMessage(fromMessage);
const toMetadata = parseCheckpointCommitMessage(toMessage);
// Checkpoints captured before attribution metadata existed: unavailable.
if (fromMetadata === null || toMetadata === null) {
return null;
}
// HEAD did not move during the turn (or the repo has no commits):
// every tree change is agent-authored. An empty map means "classified,
// no git-origin paths".
if (fromMetadata.headOid === toMetadata.headOid || fromMetadata.headOid === null) {
return new Map<string, "agent" | "git">();
}
if (toMetadata.headOid === null) {
// HEAD disappeared mid-turn (e.g. re-init); fail toward "agent".
return new Map<string, "agent" | "git">();
}
const rawDiff = (fromRevision: string, toRevision: string) =>
execute({
operation,
cwd: input.cwd,
args: [
"diff-tree",
"-r",
"-z",
"--no-abbrev",
"--no-renames",
fromRevision,
toRevision,
],
allowNonZeroExit: true,
maxOutputBytes: CHECKPOINT_DIFF_MAX_OUTPUT_BYTES,
}).pipe(
Effect.map((result) =>
result.exitCode === 0 && !result.stdoutTruncated
? parseRawDiffEntries(result.stdout)
: null,
),
);
const treeDelta = yield* rawDiff(
`${input.fromCheckpointRef}^{commit}`,
`${input.toCheckpointRef}^{commit}`,
);
const historyDelta = yield* rawDiff(fromMetadata.headOid, toMetadata.headOid);
if (treeDelta === null || historyDelta === null) {
return null;
}
// The baseline checkpoint commit is created at turn start, so its
// committer timestamp is the turn-start time. Commits in the HEAD
// range split three ways:
// - authored at/after turn start: made during the turn → agent work.
// - authored before AND committed before: pre-existing content that
// moved into the range wholesale (pull, checkout, merge fast path).
// - authored before but COMMITTED during the turn: rewritten by a
// history-editing command. Cherry-pick and rebase preserve author
// dates while re-committing, and so does `commit --amend` — but an
// amend carries NEW agent content while a replay carries old
// content. Disambiguated below by patch-id (--verbatim, so
// whitespace-only amends don't collide with their pre-amend
// original): a rewritten commit whose byte-exact patch exists
// elsewhere in the repo (branches, remotes, or reflog — the
// latter catches pre-rebase originals) is a replay → demote;
// otherwise treat as agent work → show.
const fromCommitTimeRaw = yield* readCommitField(
`${input.fromCheckpointRef}^{commit}`,
"%ct",
);
const fromCommitTime = fromCommitTimeRaw === null ? NaN : Number(fromCommitTimeRaw);
if (!Number.isFinite(fromCommitTime)) {
return null;
}
const headRangeResult = yield* execute({
operation,
cwd: input.cwd,
args: [
"log",
"--format=%H %at %ct %p",
`${fromMetadata.headOid}..${toMetadata.headOid}`,
"--",
],
allowNonZeroExit: true,
maxOutputBytes: CHECKPOINT_DIFF_MAX_OUTPUT_BYTES,
});
if (headRangeResult.exitCode !== 0 || headRangeResult.stdoutTruncated) {
return null;
}
interface RangeCommit {
readonly oid: string;
readonly isMerge: boolean;
}
const turnAuthoredCommits: Array<RangeCommit> = [];
const rewrittenCommits: Array<RangeCommit> = [];
for (const line of headRangeResult.stdout.split("\n")) {
const [oid, authorTime, commitTime, ...parents] = line.trim().split(" ");
if (!oid || !authorTime || !commitTime) {
continue;
}
const authoredAt = Number(authorTime);
const committedAt = Number(commitTime);
if (!Number.isFinite(authoredAt) || !Number.isFinite(committedAt)) {
continue;
}
const commit: RangeCommit = { oid, isMerge: parents.length > 1 };
if (authoredAt >= fromCommitTime) {
turnAuthoredCommits.push(commit);
} else if (committedAt >= fromCommitTime) {
rewrittenCommits.push(commit);
}
}
if (rewrittenCommits.length > 100) {
return null;
}
// Batch patch-id computation: diff-tree --stdin -p streams every
// commit's patch prefixed by its oid, which `git patch-id` consumes
// directly. Failures degrade to an empty map, which classifies the
// affected rewritten commits as agent work (shown).
const patchIdsForCommits = (oids: ReadonlyArray<string>) =>
Effect.gen(function* () {
if (oids.length === 0) {
return new Map<string, string>();
}
const patches = yield* execute({
operation,
cwd: input.cwd,
args: ["diff-tree", "--stdin", "-p", "--no-renames", "--root"],
stdin: `${oids.join("\n")}\n`,
allowNonZeroExit: true,
maxOutputBytes: CHECKPOINT_DIFF_MAX_OUTPUT_BYTES,
});
if (patches.exitCode !== 0 || patches.stdoutTruncated) {
return new Map<string, string>();
}
const ids = yield* execute({
operation,
cwd: input.cwd,
args: ["patch-id", "--verbatim"],
stdin: patches.stdout,
allowNonZeroExit: true,
maxOutputBytes: CHECKPOINT_DIFF_MAX_OUTPUT_BYTES,
});
if (ids.exitCode !== 0 || ids.stdoutTruncated) {
return new Map<string, string>();
}
const byCommit = new Map<string, string>();
for (const line of ids.stdout.split("\n")) {
const [patchId, commitId] = line.trim().split(" ");
if (patchId && commitId) {
byCommit.set(commitId, patchId);
}
}
return byCommit;
});
if (rewrittenCommits.length > 0) {
const candidatesResult = yield* execute({
operation,
cwd: input.cwd,
args: [
"rev-list",
"-n",
"500",
"--branches",
"--tags",
"--remotes",
"--reflog",
"--not",
toMetadata.headOid,
],
allowNonZeroExit: true,
maxOutputBytes: CHECKPOINT_DIFF_MAX_OUTPUT_BYTES,
});
const candidateOids =
candidatesResult.exitCode === 0 && !candidatesResult.stdoutTruncated
? candidatesResult.stdout.split("\n").filter((line) => line.length > 0)
: [];
const candidatePatchIds = new Set((yield* patchIdsForCommits(candidateOids)).values());
const rewrittenPatchIds = yield* patchIdsForCommits(
rewrittenCommits.map((commit) => commit.oid),
);
for (const commit of rewrittenCommits) {
const patchId = rewrittenPatchIds.get(commit.oid);
if (patchId === undefined || !candidatePatchIds.has(patchId)) {
turnAuthoredCommits.push(commit);
}
}
}
// A pathological number of turn-authored commits (e.g. clock skew
// misclassifying a pulled range) would mean one diff-tree call per
// commit; skip attribution instead — the diff renders unfiltered.
if (turnAuthoredCommits.length > 100) {
return null;
}
const turnAuthoredPaths = new Set<string>();
for (const commit of turnAuthoredCommits) {
const pathsResult = yield* execute({
operation,
cwd: input.cwd,
args: [
"diff-tree",
"-r",
"-z",
"--no-commit-id",
"--name-only",
// Root commits (orphan branches) have no parent; without
// --root they would list no paths and their agent-authored
// content would be misattributed to history.
"--root",
// For merges, the combined diff lists only paths whose result
// differs from every parent — i.e. conflict resolutions the
// agent authored. Paths taken wholesale from one side are
// pre-existing content and stay attributable to history.
...(commit.isMerge ? ["-c"] : []),
commit.oid,
],
allowNonZeroExit: true,
maxOutputBytes: CHECKPOINT_DIFF_MAX_OUTPUT_BYTES,
});
if (pathsResult.exitCode !== 0 || pathsResult.stdoutTruncated) {
return null;
}
for (const pathValue of pathsResult.stdout.split("\0")) {
if (pathValue.length > 0) {
turnAuthoredPaths.add(pathValue);
}
}
}
return classifyCheckpointPaths({ treeDelta, historyDelta, turnAuthoredPaths });
},
),
};
return {
@@ -690,61 +690,6 @@ it.layer(TestLayer)("GitVcsDriver core integration", (it) => {
);
});
describe("remote operations", () => {
it.effect("ensureRemote reuses an existing remote across ssh/https transport variants", () =>
Effect.gen(function* () {
const cwd = yield* makeTmpDir();
yield* initRepoWithCommit(cwd);
const driver = yield* GitVcsDriver.GitVcsDriver;
yield* git(cwd, ["remote", "add", "origin", "https://github.com/pingdotgg/t3code.git"]);
const reusedForSsh = yield* driver.ensureRemote({
cwd,
preferredName: "pingdotgg",
url: "[email protected]:pingdotgg/t3code.git",
});
assert.equal(reusedForSsh, "origin");
const reusedForSshScheme = yield* driver.ensureRemote({
cwd,
preferredName: "pingdotgg",
url: "ssh://[email protected]/pingdotgg/t3code",
});
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",
url: "ssh://[email protected]:22/pingdotgg/t3code.git",
});
assert.equal(reusedForSshWithPort, "origin");
const addedForFork = yield* driver.ensureRemote({
cwd,
preferredName: "octocat",
url: "[email protected]:octocat/t3code.git",
});
assert.equal(addedForFork, "octocat");
assert.equal(yield* git(cwd, ["remote"]), "octocat\norigin");
}),
);
});
describe("commit context", () => {
it.effect("stages selected files and commits only those files", () =>
Effect.gen(function* () {
+11 -3
View File
@@ -25,7 +25,7 @@ import {
type ReviewDiffPreviewSource,
type VcsRef,
} from "@t3tools/contracts";
import { dedupeRemoteBranchesWithLocalMatches, normalizeGitRemoteUrl } from "@t3tools/shared/git";
import { dedupeRemoteBranchesWithLocalMatches } from "@t3tools/shared/git";
import { compactTraceAttributes } from "@t3tools/shared/observability";
import { decodeJsonResult } from "@t3tools/shared/schemaJson";
import { gitCommandDuration, gitCommandsTotal, withMetrics } from "../observability/Metrics.ts";
@@ -235,6 +235,14 @@ function sanitizeRemoteName(value: string): string {
return sanitized.length > 0 ? sanitized : "fork";
}
function normalizeRemoteUrl(value: string): string {
return value
.trim()
.replace(/\/+$/g, "")
.replace(/\.git$/i, "")
.toLowerCase();
}
function parseRemoteFetchUrls(stdout: string): Map<string, string> {
const remotes = new Map<string, string>();
for (const line of stdout.split("\n")) {
@@ -1084,7 +1092,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
"ensureRemote",
)(function* (input) {
const preferredName = sanitizeRemoteName(input.preferredName);
const normalizedTargetUrl = normalizeGitRemoteUrl(input.url);
const normalizedTargetUrl = normalizeRemoteUrl(input.url);
const remoteFetchUrls = yield* runGitStdout(
"GitVcsDriver.ensureRemote.listRemoteUrls",
input.cwd,
@@ -1092,7 +1100,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
).pipe(Effect.map((stdout) => parseRemoteFetchUrls(stdout)));
for (const [remoteName, remoteUrl] of remoteFetchUrls.entries()) {
if (normalizeGitRemoteUrl(remoteUrl) === normalizedTargetUrl) {
if (normalizeRemoteUrl(remoteUrl) === normalizedTargetUrl) {
return remoteName;
}
}
-21
View File
@@ -38,24 +38,6 @@ export interface VcsDeleteCheckpointRefsInput {
readonly checkpointRefs: ReadonlyArray<CheckpointRef>;
}
export interface VcsAttributeCheckpointDiffInput {
readonly cwd: string;
readonly fromCheckpointRef: CheckpointRef;
readonly toCheckpointRef: CheckpointRef;
}
/**
* Per-path attribution of a checkpoint-to-checkpoint tree delta.
*
* Paths mapped to "git" are byte-for-byte explained by pre-existing commits
* that moved through HEAD during the turn (pull, checkout, cherry-pick,
* rebase). Paths mapped to "agent" — and paths absent from the map — were
* authored during the turn. `null` means attribution is unavailable (HEAD
* metadata missing on either snapshot); callers must treat every path as
* agent-authored.
*/
export type VcsCheckpointAttribution = ReadonlyMap<string, "agent" | "git"> | null;
export interface VcsCheckpointOps {
readonly captureCheckpoint: (input: VcsCaptureCheckpointInput) => Effect.Effect<void, VcsError>;
readonly hasCheckpointRef: (
@@ -68,9 +50,6 @@ export interface VcsCheckpointOps {
readonly deleteCheckpointRefs: (
input: VcsDeleteCheckpointRefsInput,
) => Effect.Effect<void, VcsError>;
readonly attributeCheckpointDiff: (
input: VcsAttributeCheckpointDiffInput,
) => Effect.Effect<VcsCheckpointAttribution, VcsError>;
}
export class VcsDriver extends Context.Service<
@@ -94,11 +94,6 @@ function makeTestLayer(state: {
Effect.sync(() => {
state.remoteInvalidationCalls += 1;
}),
invalidateStatus: () =>
Effect.sync(() => {
state.localInvalidationCalls += 1;
state.remoteInvalidationCalls += 1;
}),
}),
),
);
@@ -211,11 +206,6 @@ describe("VcsStatusBroadcaster", () => {
Effect.sync(() => {
state.remoteInvalidationCalls += 1;
}),
invalidateStatus: () =>
Effect.sync(() => {
state.localInvalidationCalls += 1;
state.remoteInvalidationCalls += 1;
}),
}),
),
);
+4 -3
View File
@@ -366,9 +366,10 @@ export const make = Effect.gen(function* () {
"VcsStatusBroadcaster.refreshStatus",
)(function* (rawCwd) {
const cwd = yield* withFileSystem(normalizeCwd(rawCwd));
// invalidateStatus (not the two partial invalidations) so an explicit
// refresh also bypasses GitManager's slow PR-lookup cache.
yield* workflow.invalidateStatus(cwd);
yield* Effect.all([workflow.invalidateLocalStatus(cwd), workflow.invalidateRemoteStatus(cwd)], {
concurrency: "unbounded",
discard: true,
});
const [local, remote] = yield* Effect.all(
[workflow.localStatus({ cwd }), workflow.remoteStatus({ cwd })],
{ concurrency: "unbounded" },
-9
View File
@@ -78,7 +78,6 @@ 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";
@@ -297,7 +296,6 @@ 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],
@@ -420,7 +418,6 @@ 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;
@@ -1479,10 +1476,6 @@ 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,
@@ -2086,7 +2079,6 @@ 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",
@@ -2109,7 +2101,6 @@ 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(
-30
View File
@@ -1,30 +0,0 @@
// Tiny event bus allowing components to programmatically open the command palette
// without owning its React state.
const COMMAND_PALETTE_OPEN_EVENT = "t3code:open-command-palette";
export interface CommandPaletteOpenDetail {
readonly open?: "add-project" | "new-thread-in";
}
export function openCommandPalette(detail?: CommandPaletteOpenDetail): void {
window.dispatchEvent(
new CustomEvent(COMMAND_PALETTE_OPEN_EVENT, detail ? { detail } : undefined),
);
}
export function onOpenCommandPalette(
listener: (detail: CommandPaletteOpenDetail) => void,
): () => void {
const handler = (event: Event) => {
listener((event as CustomEvent<CommandPaletteOpenDetail>).detail ?? {});
};
window.addEventListener(COMMAND_PALETTE_OPEN_EVENT, handler);
return () => window.removeEventListener(COMMAND_PALETTE_OPEN_EVENT, handler);
}
/** Read at event time so consumers do not subscribe to transient dialog state. */
export function isCommandPaletteOpen(): boolean {
return (
typeof document !== "undefined" && document.querySelector("[data-command-palette]") !== null
);
}
+29
View File
@@ -0,0 +1,29 @@
import { createContext, use, type ReactNode } from "react";
const OpenAddProjectCommandPaletteContext = createContext<(() => void) | null>(null);
export function OpenAddProjectCommandPaletteProvider(props: {
readonly children: ReactNode;
readonly openAddProject: () => void;
}) {
return (
<OpenAddProjectCommandPaletteContext value={props.openAddProject}>
{props.children}
</OpenAddProjectCommandPaletteContext>
);
}
export function useOpenAddProjectCommandPalette(): () => void {
const openAddProject = use(OpenAddProjectCommandPaletteContext);
if (!openAddProject) {
throw new Error("Command palette actions must be used inside CommandPalette");
}
return openAddProject;
}
/** Read at event time so the chat tree does not subscribe to transient dialog state. */
export function isCommandPaletteOpen(): boolean {
return (
typeof document !== "undefined" && document.querySelector("[data-command-palette]") !== null
);
}
+5 -5
View File
@@ -84,7 +84,7 @@ function SidebarControl() {
"pointer-events-auto",
isSidebarVisible &&
stageBackdropVariant &&
"[:hover,[data-pressed]]:bg-white/15 focus-visible:ring-white/90 focus-visible:ring-offset-blue-700 [&_svg]:stroke-white/90! [&_svg]:opacity-100! [&_svg]:hover:stroke-white!",
"hover:bg-white/15 [&_svg]:text-white/85! [&_svg]:hover:text-white!",
)}
aria-label="Toggle main sidebar"
/>
@@ -106,7 +106,6 @@ 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);
@@ -165,9 +164,10 @@ export function AppSidebarLayout({ children }: { children: ReactNode }) {
<Sidebar
side="left"
collapsible="offcanvas"
data-app-sidebar=""
data-sidebar-version={useSidebarV2Theme ? "v2" : "v1"}
className="border-r border-sidebar-border bg-sidebar text-sidebar-foreground"
className={cn(
"border-r border-border text-foreground",
useSidebarV2 ? "app-sidebar" : "bg-card",
)}
resizable={{
maxWidth: sidebarMaximumWidth,
minWidth: THREAD_SIDEBAR_MIN_WIDTH,
@@ -11,7 +11,6 @@ import {
resolveEnvModeLabel,
resolveBranchToolbarValue,
resolveLockedWorkspaceLabel,
resolveLocalCheckoutBranchMismatch,
shouldIncludeBranchPickerItem,
shouldShowEnvironmentIndicator,
} from "./BranchToolbar.logic";
@@ -86,55 +85,6 @@ 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,22 +108,6 @@ 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="chat-composer-context-strip -mt-4 mx-auto flex w-[calc(100%-1.5rem)] max-w-[calc(48rem-1.5rem)] items-center gap-2 pt-5 pb-1 ps-1">
<div className="mx-auto flex w-full max-w-3xl items-center gap-2 px-2.5 pb-3 pt-1 sm:px-3">
{isMobile ? (
<MobileRunContextSelector
envLocked={envLocked}
@@ -3,7 +3,7 @@ import {
isAtomCommandInterrupted,
squashAtomCommandFailure,
} from "@t3tools/client-runtime/state/runtime";
import type { ContextMenuItem, EnvironmentId, VcsRef, ThreadId } from "@t3tools/contracts";
import type { EnvironmentId, VcsRef, ThreadId } from "@t3tools/contracts";
import { LegendList, type LegendListRef } from "@legendapp/list/react";
import { ChevronDownIcon, GitBranchIcon, RefreshCwIcon, SearchIcon } from "lucide-react";
import {
@@ -17,12 +17,9 @@ 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";
@@ -320,45 +317,6 @@ 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();
@@ -473,7 +431,6 @@ export function BranchToolbarBranchSelector({
const worktreeBaseBranchCandidate = isInitialBranchesLoadPending
? null
: (defaultBranchName ?? currentGitBranch);
useEffect(() => {
if (
effectiveEnvMode !== "worktree" ||
@@ -590,11 +547,7 @@ export function BranchToolbarBranchSelector({
});
// PR pill shown next to the branch selector when the active branch has one.
const branchPr = resolveThreadPr({
threadBranch: resolvedActiveBranch,
gitStatus: branchStatusQuery.data ?? null,
hasDedicatedWorktree: activeWorktreePath !== null,
});
const branchPr = resolveThreadPr(resolvedActiveBranch, branchStatusQuery.data ?? null);
const branchPrStatus = prStatusIndicator(branchPr, branchStatusQuery.data?.sourceControlProvider);
// Action-oriented tooltip (the pill opens the PR), distinct from the sidebar's
// state-description tooltip.
@@ -671,7 +624,6 @@ 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>
@@ -722,23 +674,15 @@ export function BranchToolbarBranchSelector({
<TooltipPopup side="top">{branchPrTooltip}</TooltipPopup>
</Tooltip>
) : null}
{/* 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)}
<ComboboxTrigger
render={<Button variant="ghost" size="xs" />}
className="min-w-0 text-muted-foreground/70 hover:text-foreground/80"
disabled={isInitialBranchesLoadPending || isBranchActionPending}
>
<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>
<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>
</div>
<ComboboxPopup align="end" side="top" className="flex w-80 flex-col">
<div className="shrink-0 px-3 pt-2.5">
+37 -24
View File
@@ -42,10 +42,6 @@ import remarkGfm from "remark-gfm";
import { renderSkillInlineMarkdownChildren } from "./chat/SkillInlineText";
import { CHAT_FILE_TAG_CHIP_CLASS_NAME, FileTagChipContent } from "./chat/FileTagChip";
import { PierreEntryIcon } from "./chat/PierreEntryIcon";
import {
resolveExternalWebLinkHost,
showExternalLinkContextMenu,
} from "./chat/externalLinkContextMenu";
import { hasSpecificPierreIconForFileName, syntheticFileNameForLanguageId } from "../pierre-icons";
import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip";
import { Button } from "./ui/button";
@@ -80,7 +76,6 @@ import { usePreparedConnection } from "../state/session";
import { previewEnvironment } from "../state/preview";
import { useAtomCommand } from "../state/use-atom-command";
import { useAtomQueryRunner } from "../state/use-atom-query-runner";
import { writeTextToClipboard } from "../hooks/useCopyToClipboard";
import { isPreviewSupportedInRuntime } from "../previewStateStore";
import {
isBrowserPreviewFile,
@@ -836,6 +831,17 @@ const MARKDOWN_LINK_FAVICON_CLASS_NAME = "block size-full shrink-0 select-none";
/** Hosts whose favicon request already failed this session — skip straight to the globe. */
const failedFaviconHosts = new Set<string>();
function resolveExternalLinkHost(href: string | undefined): string | null {
if (!href) return null;
try {
const url = new URL(href);
if (url.protocol !== "http:" && url.protocol !== "https:") return null;
return url.hostname || null;
} catch {
return null;
}
}
const MarkdownLinkFavicon = memo(function MarkdownLinkFavicon({ host }: { host: string }) {
const [failedHost, setFailedHost] = useState<string | null>(null);
return (
@@ -1387,7 +1393,7 @@ function ChatMarkdown({
const normalizedHref = href ? normalizeMarkdownLinkHrefKey(href) : "";
const fileLinkMeta = normalizedHref ? markdownFileLinkMetaByHref.get(normalizedHref) : null;
if (!fileLinkMeta) {
const faviconHost = resolveExternalWebLinkHost(href);
const faviconHost = resolveExternalLinkHost(href);
const isSameDocumentLink = href?.startsWith("#") ?? false;
const onClick = props.onClick;
const canOpenInPreview = Boolean(threadRef) && isPreviewSupportedInRuntime();
@@ -1404,30 +1410,37 @@ function ChatMarkdown({
}
}}
onContextMenu={(event) => {
if (!canOpenInPreview || !href || !faviconHost) return;
if (!canOpenInPreview || !href) return;
event.preventDefault();
event.stopPropagation();
const api = readLocalApi();
if (!api) return;
void showExternalLinkContextMenu({
href,
position: { x: event.clientX, y: event.clientY },
showContextMenu: (items, position) => api.contextMenu.show(items, position),
openInPreview: async (target) => {
const result = await openExternalLinkInPreview(target);
if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
reportMarkdownActionFailure(
{ operation: "open-link-in-preview", target },
result.cause,
);
void (async () => {
let operation = "show-link-context-menu";
try {
const clicked = await api.contextMenu.show(
[
{ id: "open-in-browser", label: "Open in integrated browser" },
{ id: "open-external", label: "Open in system browser" },
] as const,
{ x: event.clientX, y: event.clientY },
);
if (clicked === "open-in-browser") {
operation = "open-link-in-preview";
const result = await openExternalLinkInPreview(href);
if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
reportMarkdownActionFailure({ operation, target: href }, result.cause);
}
return;
}
},
openExternal: (target) => api.shell.openExternal(target),
copyLink: (target) => writeTextToClipboard(target, "link"),
reportFailure: (operation, cause) => {
if (clicked === "open-external") {
operation = "open-link-external";
await api.shell.openExternal(href);
}
} catch (cause) {
reportMarkdownActionFailure({ operation, target: href }, cause);
},
});
}
})();
}}
>
{faviconHost ? (
@@ -20,7 +20,6 @@ import {
hasServerAcknowledgedLocalDispatch,
reconcileMountedTerminalThreadIds,
reconcileRetainedMountedThreadIds,
resolveThreadMetadataUpdateForNextTurn,
resolveSendEnvMode,
shouldWriteThreadErrorToCurrentServerThread,
} from "./ChatView.logic";
@@ -80,34 +79,6 @@ 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,33 +27,6 @@ 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,
Loaded 100 of 227 files, more files were not shown because too many files have changed in this diff. Show more