Compare commits

..
Author SHA1 Message Date
Theo BrowneandClaude Fable 5 f52f1726c4 feat: sync thread read state across devices
Opening a finished thread now stamps a server-synced lastVisitedAt via a
new thread.visit command, so reading a thread on web clears the unread
cue on mobile and vice versa. Local storage stays as the offline and
old-server fallback.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-10 17:24:55 -07:00
272 changed files with 2710 additions and 21995 deletions

No files matched your search

-1
View File
@@ -37,4 +37,3 @@ github:shivamhwp
github:jappyjan
github:justsomelegs
github:UtkarshUsername
github:SunkenInTime
+10 -83
View File
@@ -8,14 +8,12 @@ name: Mobile EAS Production
#
# Every merge to main that touches the mobile app reconciles, per platform:
# 1. Store builds: if the latest production build's version differs from
# app.config.ts, cut a new build and submit it (TestFlight + Play internal
# track). Bumping `version` is therefore all it takes to
# app.config.ts, cut a new build with --auto-submit (TestFlight +
# Play internal track). Bumping `version` is therefore all it takes to
# start the next release train — the first build of a version enters
# external-TestFlight beta review immediately, and later builds of the
# same version auto-approve until that version is released. After App
# Store approval, Apple closes the release train and `version` must be
# bumped before another iOS build can be submitted. Releasing to the App
# Store stays a manual App Store Connect step.
# same version auto-approve. Releasing to the App Store stays a manual
# App Store Connect step.
# 2. OTA: publish a production-channel update for each platform where at
# least one finished production build matches the current native
# fingerprint. Old-version binaries with a matching fingerprint receive
@@ -44,10 +42,6 @@ on:
- ios
- android
- all
version:
description: "Optional build version override (blank uses app.config.ts; an override is committed before building)"
required: false
type: string
message:
description: "OTA update message (mode=update only)"
required: false
@@ -95,21 +89,11 @@ jobs:
echo "EXPO_TOKEN is not available; skipping EAS production job."
fi
- id: version_app_token
name: Mint release app token for version override
if: steps.expo-token.outputs.present == 'true' && github.event_name == 'workflow_dispatch' && inputs.mode == 'build' && inputs.version != ''
uses: actions/create-github-app-token@v2
with:
app-id: ${{ secrets.RELEASE_APP_ID }}
private-key: ${{ secrets.RELEASE_APP_PRIVATE_KEY }}
owner: ${{ github.repository_owner }}
- name: Checkout
if: steps.expo-token.outputs.present == 'true'
uses: actions/checkout@v6
with:
fetch-depth: 0
token: ${{ steps.version_app_token.outputs.token || github.token }}
# No sparse-checkout here: it makes actions/checkout fetch with
# --filter=blob:none, and eas-cli archives the project via
# `git clone --depth 1 file://<workspace>`, which fails (exit 128)
@@ -151,65 +135,6 @@ jobs:
EXPO_TOKEN: ${{ secrets.EXPO_TOKEN }}
run: eas env:pull production --non-interactive
- name: Apply manual version override
if: steps.version_app_token.outcome == 'success'
env:
GH_TOKEN: ${{ steps.version_app_token.outputs.token }}
APP_SLUG: ${{ steps.version_app_token.outputs.app-slug }}
RELEASE_VERSION: ${{ inputs.version }}
run: |
if [ "$GITHUB_REF_TYPE" != "branch" ]; then
echo "Version overrides require dispatching this workflow from a branch; received $GITHUB_REF_TYPE '$GITHUB_REF_NAME'." >&2
exit 1
fi
if ! [[ "$RELEASE_VERSION" =~ ^[0-9]+(\.[0-9]+){1,2}$ ]]; then
echo "Version override must contain two or three dot-separated integers; received '$RELEASE_VERSION'." >&2
exit 1
fi
node --input-type=module -e '
import fs from "node:fs";
const path = "apps/mobile/app.config.ts";
const source = fs.readFileSync(path, "utf8");
const next = source.replace(
/^( version: ")[^"]+(".*)$/m,
`$1${process.env.RELEASE_VERSION}$2`,
);
if (next === source && !source.includes(` version: "${process.env.RELEASE_VERSION}"`)) {
throw new Error("Could not update app version");
}
fs.writeFileSync(path, next);
'
vp fmt apps/mobile/app.config.ts
if git diff --quiet -- apps/mobile/app.config.ts; then
echo "app.config.ts is already at $RELEASE_VERSION; no version commit needed."
exit 0
fi
user_id="$(gh api "/users/${APP_SLUG}[bot]" --jq .id)"
git config user.name "${APP_SLUG}[bot]"
git config user.email "${user_id}+${APP_SLUG}[bot]@users.noreply.github.com"
git add apps/mobile/app.config.ts
git commit \
-m "chore(mobile): bump app version to $RELEASE_VERSION" \
-m "Co-authored-by: codex <[email protected]>"
git push origin "HEAD:refs/heads/${GITHUB_REF_NAME}"
- name: Summarize manual build version
if: steps.expo-token.outputs.present == 'true' && github.event_name == 'workflow_dispatch' && inputs.mode == 'build'
working-directory: apps/mobile
run: |
version="$(npx expo config --json --type public | jq -r '.version')"
{
echo "## Manual production build"
echo
echo "- App version: \`$version\`"
echo "- Platform: \`${{ inputs.platform }}\`"
echo
echo "> Apple closes an iOS release train after App Store approval. Before building iOS, confirm \`$version\` is newer than the approved App Store version."
} >> "$GITHUB_STEP_SUMMARY"
- name: Build and submit (manual)
if: steps.expo-token.outputs.present == 'true' && github.event_name == 'workflow_dispatch' && inputs.mode == 'build'
working-directory: apps/mobile
@@ -232,8 +157,10 @@ jobs:
# No --status filter on build:list: an in-queue/in-progress build must
# count as existing, or every merge during the build window would cut a
# duplicate. After an errored build, retry via workflow_dispatch
# mode=build — pushes won't re-trigger it until the app version changes.
# duplicate. Builds started here stay attached to this serialized run so
# the queued run for a later merge cannot overtake them and lose its OTA.
# After an errored build, retry via workflow_dispatch mode=build — pushes
# won't re-trigger it until the app version changes.
- id: store_builds
name: Ensure store builds exist for the current app version
if: steps.expo-token.outputs.present == 'true' && github.event_name == 'push'
@@ -251,8 +178,8 @@ jobs:
continue
fi
echo "$platform: latest production build is $latest, app.config.ts says $version — building"
if eas build --platform "$platform" --profile production --auto-submit --non-interactive --no-wait; then
echo ":building_construction: $platform: scheduled production build and submission for $version" >> "$GITHUB_STEP_SUMMARY"
if eas build --platform "$platform" --profile production --auto-submit --non-interactive; then
echo ":building_construction: $platform: cut production build for $version (auto-submitted)" >> "$GITHUB_STEP_SUMMARY"
else
failed=1
echo ":x: $platform: production build or submission failed for $version" >> "$GITHUB_STEP_SUMMARY"
+1 -1
View File
@@ -161,7 +161,7 @@ const config: ExpoConfig = {
slug: "t3-code",
platforms: ["ios", "android"],
scheme: variant.scheme,
version: "1.0.3",
version: "1.0.2",
runtimeVersion: {
// Fingerprint (not appVersion) so an OTA only reaches binaries whose native
// project — native deps, config plugins, AND patches/ — matches the update.
+1 -1
View File
@@ -49,7 +49,7 @@
"@expo-google-fonts/dm-sans": "^0.4.2",
"@expo/metro-runtime": "~56.0.15",
"@expo/ui": "~56.0.18",
"@legendapp/list": "catalog:",
"@legendapp/list": "3.3.3",
"@noble/curves": "catalog:",
"@noble/hashes": "catalog:",
"@pierre/diffs": "catalog:",
+13 -20
View File
@@ -18,6 +18,7 @@ import { AppText as Text } from "./components/AppText";
import { getCompactBrandHeaderOptions } from "./components/CompactBrandTitle";
import { ArchivedThreadsRouteScreen } from "./features/archive/ArchivedThreadsRouteScreen";
import { useAgentNotificationNavigation } from "./features/agent-awareness/notificationNavigation";
import { ClerkSettingsSheetDetentProvider } from "./features/cloud/ClerkSettingsSheetDetent";
import { ConnectOnboardingRouteScreen } from "./features/cloud/ConnectOnboardingRouteScreen";
import { useConnectOnboardingNavigation } from "./features/cloud/connectOnboardingNavigation";
import { ThreadFilesTreeScreen, ThreadFileScreen } from "./features/files/ThreadFilesRouteScreen";
@@ -133,7 +134,7 @@ const LEGAL_DOCUMENT_HEADER_OPTIONS: AppScreenOptions = {
presentation: "fullScreenModal",
};
const SettingsContentStack = createNativeStackNavigator({
const SettingsSheetStack = createNativeStackNavigator({
initialRouteName: "Settings",
screenOptions: {
...GLASS_HEADER_OPTIONS,
@@ -197,30 +198,20 @@ const SettingsContentStack = createNativeStackNavigator({
title: "Usage",
},
}),
},
});
// The outer stack never owns visible chrome. Settings routes render inside a
// nested stack whose native header remains mounted, while Clerk owns auth chrome.
// Keeping bar visibility invariant avoids iOS 26's headerless-to-headered jump.
const SettingsSheetStack = createNativeStackNavigator({
initialRouteName: "SettingsContent",
screenOptions: {
headerShown: false,
},
screens: {
SettingsContent: createNativeStackScreen({
screen: SettingsContentStack,
linking: "",
}),
SettingsAuth: createNativeStackScreen({
screen: SettingsAuthRouteScreen,
linking: "auth",
options: {
title: "Sign in",
},
}),
SettingsWaitlist: createNativeStackScreen({
// Keep the old deep link working after the Connect GA launch.
screen: SettingsAuthRouteScreen,
linking: "waitlist",
options: {
title: "Sign in",
},
}),
},
});
@@ -356,9 +347,11 @@ function RootStackLayout(props: {
<HardwareKeyboardCommandProvider pathname={pathname}>
<ThreadOutboxDrainWorker />
<ShowcaseCaptureCoordinator pathname={pathname} />
<AdaptiveWorkspaceLayout pathname={workspacePathname}>
{props.children}
</AdaptiveWorkspaceLayout>
<ClerkSettingsSheetDetentProvider initiallyExpanded={false}>
<AdaptiveWorkspaceLayout pathname={workspacePathname}>
{props.children}
</AdaptiveWorkspaceLayout>
</ClerkSettingsSheetDetentProvider>
</HardwareKeyboardCommandProvider>
);
}
+1 -26
View File
@@ -6,7 +6,6 @@ import {
type ComponentProps,
type ReactElement,
type ReactNode,
useRef,
} from "react";
import { Platform, Pressable, useColorScheme, View } from "react-native";
import { useThemeColor } from "../lib/useThemeColor";
@@ -22,31 +21,10 @@ export function ControlPill(props: {
readonly label?: string;
readonly accessibilityLabel?: string;
readonly onPress?: () => void;
readonly activateOnPressIn?: boolean;
readonly variant?: "circle" | "pill" | "primary" | "danger";
readonly disabled?: boolean;
readonly className?: string;
}) {
const variant = props.variant ?? "circle";
const activatedOnPressInRef = useRef(false);
const handlePressIn = () => {
activatedOnPressInRef.current = true;
props.onPress?.();
};
const handlePressOut = () => {
// Pressability invokes onPressOut immediately before onPress on release.
// Defer the reset so onPress can identify the same physical gesture.
setTimeout(() => {
activatedOnPressInRef.current = false;
}, 0);
};
const handlePress = () => {
if (activatedOnPressInRef.current) {
return;
}
props.onPress?.();
};
const iconColor = useThemeColor("--color-icon");
const iconSubtle = useThemeColor("--color-icon-subtle");
@@ -76,7 +54,6 @@ export function ControlPill(props: {
: variant === "danger"
? "bg-danger"
: "bg-subtle",
props.className,
);
const labelClassName = cn(
"text-center text-xs font-t3-bold",
@@ -91,9 +68,7 @@ export function ControlPill(props: {
<Pressable
accessibilityLabel={props.accessibilityLabel ?? props.label}
accessibilityRole="button"
onPress={props.activateOnPressIn ? handlePress : props.onPress}
onPressIn={props.activateOnPressIn ? handlePressIn : undefined}
onPressOut={props.activateOnPressIn ? handlePressOut : undefined}
onPress={props.onPress}
disabled={props.disabled}
className={containerClassName}
>
@@ -5,6 +5,7 @@ import { useFocusEffect } from "@react-navigation/native";
import { useCallback, useMemo, useState } from "react";
import { useSavedRemoteConnections } from "../../state/use-remote-environment-registry";
import { useClerkSettingsSheetDetent } from "../cloud/ClerkSettingsSheetDetent";
import { useArchivedThreadListActions } from "../home/useThreadListActions";
import {
ArchivedThreadsScreen,
@@ -17,6 +18,7 @@ import {
} from "./useArchivedThreadSnapshots";
export function ArchivedThreadsRouteScreen() {
const { expand } = useClerkSettingsSheetDetent();
const { savedConnectionsById } = useSavedRemoteConnections();
const [searchQuery, setSearchQuery] = useState("");
const [selectedEnvironmentId, setSelectedEnvironmentId] = useState<EnvironmentId | null>(null);
@@ -68,8 +70,9 @@ export function ArchivedThreadsRouteScreen() {
useFocusEffect(
useCallback(() => {
expand();
refresh();
}, [refresh]),
}, [expand, refresh]),
);
return (
@@ -0,0 +1,44 @@
import {
createContext,
type PropsWithChildren,
useCallback,
useContext,
useMemo,
useState,
} from "react";
interface ClerkSettingsSheetDetentValue {
collapse: () => void;
expand: () => void;
isExpanded: boolean;
}
const ClerkSettingsSheetDetentContext = createContext<ClerkSettingsSheetDetentValue | null>(null);
interface ClerkSettingsSheetDetentProviderProps extends PropsWithChildren {
initiallyExpanded: boolean;
}
export function ClerkSettingsSheetDetentProvider({
children,
initiallyExpanded,
}: ClerkSettingsSheetDetentProviderProps) {
const [isExpanded, setIsExpanded] = useState(initiallyExpanded);
const collapse = useCallback(() => setIsExpanded(false), []);
const expand = useCallback(() => setIsExpanded(true), []);
const value = useMemo(() => ({ collapse, expand, isExpanded }), [collapse, expand, isExpanded]);
return (
<ClerkSettingsSheetDetentContext value={value}>{children}</ClerkSettingsSheetDetentContext>
);
}
export function useClerkSettingsSheetDetent(): ClerkSettingsSheetDetentValue {
const value = useContext(ClerkSettingsSheetDetentContext);
if (!value) {
throw new Error(
"useClerkSettingsSheetDetent must be used inside ClerkSettingsSheetDetentProvider",
);
}
return value;
}
@@ -6,8 +6,8 @@ import { appAtomRegistry } from "../../state/atom-registry";
import { clearConnectOnboardingRequest, connectOnboardingRequestAtom } from "./connectOnboarding";
import { isConnectOnboardingOptedOut } from "./connectOnboardingOptOut";
// Sign-in happens inside the Settings sheet; give its session-state transition
// a beat to settle before presenting another formSheet on top.
// Sign-in happens inside the Settings sheet; give its detent/session-state
// transitions a beat to settle before presenting another formSheet on top.
const PRESENT_ONBOARDING_DELAY_MS = 600;
/**
@@ -45,7 +45,6 @@ export function HomeRouteScreen() {
pinThread,
unpinThread,
movePinnedThread,
regenerateThreadTitle,
unsettleThread,
} = useThreadListActions();
const pendingTasks = usePendingNewTasks();
@@ -135,10 +134,7 @@ export function HomeRouteScreen() {
<NativeStackScreenOptions
options={getConnectionAwareBrandHeaderOptions({
onOpenEnvironments: () =>
navigation.navigate("SettingsSheet", {
screen: "SettingsContent",
params: { screen: "SettingsEnvironments" },
}),
navigation.navigate("SettingsSheet", { screen: "SettingsEnvironments" }),
})}
/>
<HomeHeader
@@ -152,17 +148,9 @@ export function HomeRouteScreen() {
onEnvironmentChange={setSelectedEnvironmentId}
onProjectChange={setSelectedProjectKey}
onOpenEnvironments={() =>
navigation.navigate("SettingsSheet", {
screen: "SettingsContent",
params: { screen: "SettingsEnvironments" },
})
}
onOpenSettings={() =>
navigation.navigate("SettingsSheet", {
screen: "SettingsContent",
params: { screen: "Settings" },
})
navigation.navigate("SettingsSheet", { screen: "SettingsEnvironments" })
}
onOpenSettings={() => navigation.navigate("SettingsSheet", { screen: "Settings" })}
onProjectSortOrderChange={setProjectSortOrder}
onSearchQueryChange={setSearchQuery}
onStartNewTask={() => navigation.navigate("NewTaskSheet", { screen: "NewTask" })}
@@ -173,10 +161,7 @@ export function HomeRouteScreen() {
catalogState={catalogState}
environments={environments}
onAddConnection={() =>
navigation.navigate("SettingsSheet", {
screen: "SettingsContent",
params: { screen: "SettingsEnvironmentNew" },
})
navigation.navigate("SettingsSheet", { screen: "SettingsEnvironmentNew" })
}
onArchiveThread={archiveThread}
onDeleteThread={confirmDeleteThread}
@@ -187,15 +172,9 @@ export function HomeRouteScreen() {
onPinThread={pinThread}
onUnpinThread={unpinThread}
onMovePinnedThread={movePinnedThread}
onRegenerateThreadTitle={regenerateThreadTitle}
onEnvironmentChange={setSelectedEnvironmentId}
onProjectChange={setSelectedProjectKey}
onOpenSettings={() =>
navigation.navigate("SettingsSheet", {
screen: "SettingsContent",
params: { screen: "Settings" },
})
}
onOpenSettings={() => navigation.navigate("SettingsSheet", { screen: "Settings" })}
onProjectSortOrderChange={setProjectSortOrder}
onSearchQueryChange={setSearchQuery}
onSelectThread={(thread) => {
@@ -115,7 +115,6 @@ interface HomeScreenProps {
thread: EnvironmentThreadShell,
direction: "up" | "down",
) => Promise<boolean>;
readonly onRegenerateThreadTitle: (thread: EnvironmentThreadShell) => Promise<boolean>;
readonly onSelectPendingTask: (pendingTask: PendingNewTask) => void;
readonly onDeletePendingTask: (pendingTask: PendingNewTask) => void;
readonly onNewThreadInProject: (project: EnvironmentProject) => void;
@@ -539,12 +538,6 @@ export function HomeScreen(props: HomeScreenProps) {
},
[props.onUnpinThread],
);
const handleRegenerateThreadTitle = useCallback(
(thread: EnvironmentThreadShell) => {
void props.onRegenerateThreadTitle(thread);
},
[props.onRegenerateThreadTitle],
);
const handleDeleteThread = props.onDeleteThread;
const handleUnsettleThread = props.onUnsettleThread;
// The settled tail renders in pages; expansion resets when the filter
@@ -622,15 +615,6 @@ export function HomeScreen(props: HomeScreenProps) {
}
return supported;
}, [serverConfigs]);
const titleRegenerationEnvironmentIds = useMemo(() => {
const supported = new Set<EnvironmentId>();
for (const [environmentId, config] of serverConfigs) {
if (config.environment.capabilities.threadTitleRegeneration === true) {
supported.add(environmentId);
}
}
return supported;
}, [serverConfigs]);
// Canonical arranged pinned order (reorder-capable threads only) for the
// Move up/down position flags. Computed from all shells, not the rendered
// list, so search/scope filtering never disables or misdirects a move.
@@ -827,8 +811,6 @@ export function HomeScreen(props: HomeScreenProps) {
onSelectThread={props.onSelectThread}
onDeleteThread={handleDeleteThread}
onArchiveThread={props.onArchiveThread}
onRegenerateThreadTitle={handleRegenerateThreadTitle}
titleRegenerationSupported={titleRegenerationEnvironmentIds.has(thread.environmentId)}
settlementSupported={settlementEnvironmentIds.has(thread.environmentId)}
onSettleThread={handleSettleThread}
snoozeSupported={snoozeEnvironmentIds.has(thread.environmentId)}
@@ -860,7 +842,6 @@ export function HomeScreen(props: HomeScreenProps) {
arrangedPinnedKeys,
handleMovePinnedThread,
handlePinThread,
handleRegenerateThreadTitle,
handleSettleThread,
handleSnoozeThread,
handleUnpinThread,
@@ -882,7 +863,6 @@ export function HomeScreen(props: HomeScreenProps) {
snoozeEnvironmentIds,
threadListV2Items,
threadSearchMatchByKey,
titleRegenerationEnvironmentIds,
toggleSettledShelf,
toggleSnoozedShelf,
v2ProjectTitleByProjectKey,
@@ -987,8 +967,6 @@ export function HomeScreen(props: HomeScreenProps) {
searchQuery={props.searchQuery}
onArchiveThread={props.onArchiveThread}
onDeleteThread={props.onDeleteThread}
onRegenerateThreadTitle={handleRegenerateThreadTitle}
titleRegenerationSupported={titleRegenerationEnvironmentIds.has(thread.environmentId)}
onSelectThread={props.onSelectThread}
onSwipeableClose={handleSwipeableClose}
onSwipeableWillOpen={handleSwipeableWillOpen}
@@ -1010,7 +988,6 @@ export function HomeScreen(props: HomeScreenProps) {
[
handleSwipeableClose,
handleSwipeableWillOpen,
handleRegenerateThreadTitle,
projectCwdByKey,
props.onArchiveThread,
props.onDeletePendingTask,
@@ -1021,7 +998,6 @@ export function HomeScreen(props: HomeScreenProps) {
props.searchQuery,
props.savedConnectionsById,
threadSearchMatchByKey,
titleRegenerationEnvironmentIds,
updateGroupDisplay,
],
);
@@ -48,15 +48,6 @@ function environmentSupportsPinReorder(environmentId: EnvironmentThreadShell["en
);
}
function environmentSupportsTitleRegeneration(
environmentId: EnvironmentThreadShell["environmentId"],
) {
return (
appAtomRegistry.get(environmentServerConfigsAtom).get(environmentId)?.environment.capabilities
.threadTitleRegeneration === true
);
}
type ThreadListAction = "archive" | "unarchive" | "delete" | "settle" | "unsettle";
const ACTION_VERBS: Record<ThreadListAction, string> = {
@@ -236,18 +227,13 @@ export function useThreadListActions(): {
thread: EnvironmentThreadShell,
direction: "up" | "down",
) => Promise<boolean>;
readonly regenerateThreadTitle: (thread: EnvironmentThreadShell) => Promise<boolean>;
} {
const executeAction = useThreadActionExecutor();
const snoozeMutation = useAtomCommand(threadEnvironment.snooze, { reportFailure: false });
const unsnoozeMutation = useAtomCommand(threadEnvironment.unsnooze, { reportFailure: false });
const pinMutation = useAtomCommand(threadEnvironment.pin, { reportFailure: false });
const unpinMutation = useAtomCommand(threadEnvironment.unpin, { reportFailure: false });
const updateThreadMetadata = useAtomCommand(threadEnvironment.updateMetadata, {
reportFailure: false,
});
const snoozeInFlightThreadKeys = useRef(new Set<string>());
const titleRegenerationInFlightThreadKeys = useRef(new Set<string>());
const archiveThread = useCallback(
(thread: EnvironmentThreadShell) => {
@@ -419,47 +405,6 @@ export function useThreadListActions(): {
},
[unpinMutation],
);
const regenerateThreadTitle = useCallback(
async (thread: EnvironmentThreadShell) => {
const key = scopedThreadKey(thread.environmentId, thread.id);
if (
thread.titleRegeneration != null ||
titleRegenerationInFlightThreadKeys.current.has(key)
) {
return false;
}
if (!environmentSupportsTitleRegeneration(thread.environmentId)) {
Alert.alert(
"Could not regenerate title",
"This environment's server does not support title regeneration yet. Update the server to regenerate thread titles.",
);
return false;
}
titleRegenerationInFlightThreadKeys.current.add(key);
selectionHaptic();
try {
const result = await updateThreadMetadata({
environmentId: thread.environmentId,
input: { threadId: thread.id, regenerateTitle: true },
});
if (result._tag === "Failure") {
const error = Cause.squash(result.cause);
Alert.alert(
"Could not regenerate title",
error instanceof Error && error.message.trim().length > 0
? error.message
: "The thread title could not be regenerated.",
);
return false;
}
return true;
} finally {
titleRegenerationInFlightThreadKeys.current.delete(key);
}
},
[updateThreadMetadata],
);
// Move up / Move down for the pinned block. Computed against the CANONICAL
// keyed pinned order (not the rendered list), so the move is valid even
@@ -552,7 +497,6 @@ export function useThreadListActions(): {
pinThread,
unpinThread,
movePinnedThread,
regenerateThreadTitle,
};
}
@@ -429,19 +429,13 @@ function AdaptiveWorkspaceLayoutContent(
);
const handleOpenSettings = useCallback(() => {
navigation.navigate("SettingsSheet", {
screen: "SettingsContent",
params: { screen: "Settings" },
});
navigation.navigate("SettingsSheet", { screen: "Settings" });
}, [navigation]);
// Minted here (root stack navigation) so the sidebar pane stays free of
// navigation hooks — on iOS it renders inside an independent nav tree.
const handleOpenEnvironmentSettings = useCallback(() => {
navigation.navigate("SettingsSheet", {
screen: "SettingsContent",
params: { screen: "SettingsEnvironments" },
});
navigation.navigate("SettingsSheet", { screen: "SettingsEnvironments" });
}, [navigation]);
const handleNewThreadInProject = useCallback(
@@ -1,7 +1,8 @@
import { useAuth } from "@clerk/expo";
import { AuthView, UserProfileView } from "@clerk/expo/native";
import { StackActions, useNavigation } from "@react-navigation/native";
import { useCallback, useLayoutEffect } from "react";
import { NativeStackScreenOptions } from "../../native/StackHeader";
import { useCallback, useEffect } from "react";
import { View } from "react-native";
import { hasCloudPublicConfig } from "../cloud/publicConfig";
@@ -9,9 +10,9 @@ import { hasCloudPublicConfig } from "../cloud/publicConfig";
export function SettingsAuthRouteScreen() {
const navigation = useNavigation();
useLayoutEffect(() => {
useEffect(() => {
if (!hasCloudPublicConfig()) {
navigation.dispatch(StackActions.replace("SettingsContent"));
navigation.dispatch(StackActions.replace("Settings"));
}
}, [navigation]);
@@ -21,20 +22,20 @@ export function SettingsAuthRouteScreen() {
function ConfiguredSettingsAuthRouteScreen() {
const { isLoaded, isSignedIn } = useAuth({ treatPendingAsSignedOut: false });
const navigation = useNavigation();
const handleHostBack = useCallback(
() => navigation.dispatch(StackActions.popTo("SettingsContent")),
[navigation],
);
const handleHostBack = useCallback(() => navigation.goBack(), [navigation]);
return (
<View collapsable={false} className="flex-1 overflow-hidden bg-sheet">
{isLoaded ? (
isSignedIn ? (
<UserProfileView isDismissible={false} onHostBack={handleHostBack} />
) : (
<AuthView isDismissible={false} onHostBack={handleHostBack} />
)
) : null}
</View>
<>
<NativeStackScreenOptions options={{ headerShown: false }} />
<View collapsable={false} className="flex-1 overflow-hidden bg-sheet">
{isLoaded ? (
isSignedIn ? (
<UserProfileView isDismissible={false} onHostBack={handleHostBack} />
) : (
<AuthView isDismissible={false} onHostBack={handleHostBack} />
)
) : null}
</View>
</>
);
}
@@ -98,10 +98,7 @@ export function SettingsEnvironmentsRouteScreen() {
accessibilityLabel: "Add environment",
icon: "plus",
onPress: () =>
navigation.navigate("SettingsSheet", {
screen: "SettingsContent",
params: { screen: "SettingsEnvironmentNew" },
}),
navigation.navigate("SettingsSheet", { screen: "SettingsEnvironmentNew" }),
},
]}
/>
@@ -111,10 +108,7 @@ export function SettingsEnvironmentsRouteScreen() {
<NativeHeaderToolbar.Button
icon="plus"
onPress={() =>
navigation.navigate("SettingsSheet", {
screen: "SettingsContent",
params: { screen: "SettingsEnvironmentNew" },
})
navigation.navigate("SettingsSheet", { screen: "SettingsEnvironmentNew" })
}
separateBackground
tintColor={headerIconColor}
@@ -2,6 +2,7 @@ import { useAuth, useUser } from "@clerk/expo";
import { useAtomSet, useAtomValue } from "@effect/atom-react";
import Constants from "expo-constants";
import * as Notifications from "expo-notifications";
import * as Updates from "expo-updates";
import { useNavigation } from "@react-navigation/native";
import { NativeStackScreenOptions } from "../../native/StackHeader";
import { SymbolView } from "../../components/AppSymbol";
@@ -29,6 +30,7 @@ import {
subscribeAgentAwarenessRegistrationStatus,
} from "../agent-awareness/remoteRegistration";
import { refreshManagedRelayEnvironments } from "../cloud/managedRelayState";
import { useClerkSettingsSheetDetent } from "../cloud/ClerkSettingsSheetDetent";
import { hasCloudPublicConfig, resolveRelayClerkTokenOptions } from "../cloud/publicConfig";
import { withNativeGlassHeaderItem } from "../layout/native-glass-header-items";
import { WorkspaceSidebarToolbar } from "../layout/workspace-sidebar-toolbar";
@@ -38,7 +40,6 @@ import { mobilePreferencesAtom, updateMobilePreferencesAtom } from "../../state/
import { useThreadListV2Enabled } from "../threads/use-thread-list-v2-enabled";
import {
type AppUpdateCheckState,
isAppUpdateCheckAvailable,
registerHiddenUpdateTap,
runAppUpdateCheck,
} from "../updates/app-updates";
@@ -146,6 +147,7 @@ function ConfiguredSettingsRouteScreen() {
const agentAwarenessPushAvailable = supportsAgentAwarenessPush();
const insets = useSafeAreaInsets();
const navigation = useNavigation();
const { expand: expandClerkSheet } = useClerkSettingsSheetDetent();
const { getToken, isLoaded, isSignedIn } = useAuth({ treatPendingAsSignedOut: false });
const { user } = useUser();
const { savedConnectionsById } = useSavedRemoteConnections();
@@ -434,8 +436,14 @@ function ConfiguredSettingsRouteScreen() {
const openAccount = useCallback(() => {
if (!isLoaded) return;
if (!isSignedIn) {
expandClerkSheet();
navigation.navigate("SettingsSheet", { screen: "SettingsAuth" });
return;
}
expandClerkSheet();
navigation.navigate("SettingsSheet", { screen: "SettingsAuth" });
}, [isLoaded, navigation]);
}, [expandClerkSheet, isLoaded, isSignedIn, navigation]);
return (
<View collapsable={false} className="flex-1 bg-sheet">
@@ -569,7 +577,6 @@ function AppSettingsSection() {
const variant = (Constants.expoConfig?.extra?.appVariant as string | undefined) ?? "production";
const variantLabel = variant === "production" ? "" : capitalize(variant);
const versionLabel = variantLabel ? `${version} · ${variantLabel}` : version;
const updateCheckAvailable = isAppUpdateCheckAvailable();
const busy =
updateState === "checking" || updateState === "downloading" || updateState === "restarting";
@@ -597,13 +604,13 @@ function AppSettingsSection() {
}, []);
const handleVersionPress = useCallback(() => {
if (!updateCheckAvailable || updateInFlight.current) return;
if (!Updates.isEnabled || updateInFlight.current) return;
const tap = registerHiddenUpdateTap(hiddenUpdateTapCount.current);
hiddenUpdateTapCount.current = tap.nextCount;
if (tap.shouldCheck) {
void checkForUpdate();
}
}, [checkForUpdate, updateCheckAvailable]);
}, [checkForUpdate]);
const statusLabel =
updateState === "checking"
@@ -639,7 +646,7 @@ function AppSettingsSection() {
<SettingsSection title="App">
<SettingsRow icon="internaldrive" label="Client Storage" target="SettingsClientStorage" />
<SettingsRow icon="doc.text" label="Legal" fullScreenTarget="SettingsLegal" />
{updateCheckAvailable ? (
{Updates.isEnabled ? (
<Pressable
accessibilityLabel={`Version ${versionLabel}`}
accessibilityRole="text"
@@ -64,8 +64,7 @@ export function SettingsRow(props: {
disabled={props.disabled}
onPress={() =>
navigation.navigate("SettingsSheet", {
screen: "SettingsContent",
params: { screen: target },
screen: target,
})
}
>
@@ -1,12 +1,6 @@
import { useEffect, useRef, useState } from "react";
import { Keyboard, View } from "react-native";
import {
CommonActions,
type NavigationState,
type PartialState,
StackActions,
useNavigation,
} from "@react-navigation/native";
import { CommonActions, StackActions, useNavigation } from "@react-navigation/native";
import { AsyncResult } from "effect/unstable/reactivity";
import { useConnectionController } from "../connection/useConnectionController";
@@ -31,8 +25,6 @@ import { retryShowcaseOperation } from "./showcaseRetry";
const SHOWCASE_ENABLED = process.env.EXPO_PUBLIC_SHOWCASE === "1";
const SHOWCASE_THREAD_ID = "remote-command-center";
type ShowcaseResetRoute = PartialState<NavigationState>["routes"][number];
function sceneFromPathname(pathname: string): ShowcaseScene | null {
const routePath = pathname.split(/[?#]/u, 1)[0] ?? pathname;
if (routePath === "/settings" || routePath.endsWith("/settings/environments")) {
@@ -174,21 +166,17 @@ export function ShowcaseCaptureCoordinator(props: { readonly pathname: string })
navigation.dispatch(StackActions.popToTop());
return;
}
const routes: ShowcaseResetRoute[] = [{ name: "Home" }];
const routes: Array<{
name: string;
params?: Record<string, unknown>;
state?: { index: number; routes: Array<{ name: string }> };
}> = [{ name: "Home" }];
if (requestedScene === "environments") {
routes.push({
name: "SettingsSheet",
state: {
index: 0,
routes: [
{
name: "SettingsContent",
state: {
index: 1,
routes: [{ name: "Settings" }, { name: "SettingsEnvironments" }],
},
},
],
index: 1,
routes: [{ name: "Settings" }, { name: "SettingsEnvironments" }],
},
});
} else {
@@ -1,3 +1,4 @@
import { isLiquidGlassSupported, LiquidGlassView } from "@callstack/liquid-glass";
import type { ComposerTriggerKind } from "@t3tools/shared/composerTrigger";
import type { ServerProviderSkill, ServerProviderSlashCommand } from "@t3tools/contracts";
import { SymbolView } from "../../components/AppSymbol";
@@ -5,7 +6,6 @@ import { memo } from "react";
import { Pressable, ScrollView, useColorScheme, View, type ViewStyle } from "react-native";
import { AppText as Text } from "../../components/AppText";
import { GlassSurface } from "../../components/GlassSurface";
import { PierreEntryIcon } from "../../components/PierreEntryIcon";
export type ComposerCommandItem =
| {
@@ -56,14 +56,33 @@ function PopoverSurface(props: {
...props.style,
};
if (isLiquidGlassSupported) {
return (
<LiquidGlassView
effect="clear"
interactive={false}
tintColor={props.isDarkMode ? "rgba(30,30,32,0.95)" : "rgba(255,255,255,0.92)"}
colorScheme={props.isDarkMode ? "dark" : "light"}
style={baseStyle}
>
{props.children}
</LiquidGlassView>
);
}
return (
<GlassSurface
glassEffectStyle="clear"
tintColor={props.isDarkMode ? "rgba(30,30,32,0.95)" : "rgba(255,255,255,0.92)"}
style={baseStyle}
<View
style={[
baseStyle,
{
backgroundColor: props.isDarkMode ? "rgba(44,44,46,0.96)" : "rgba(255,255,255,0.96)",
borderWidth: 1,
borderColor: props.isDarkMode ? "rgba(255,255,255,0.08)" : "rgba(0,0,0,0.06)",
},
]}
>
{props.children}
</GlassSurface>
</View>
);
}
@@ -2,11 +2,7 @@ import { NativeStackScreenOptions } from "../../native/StackHeader";
import { StackActions, useNavigation, usePreventRemove } from "@react-navigation/native";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { Alert, InteractionManager, Platform, View, useColorScheme } from "react-native";
import {
KeyboardAvoidingView,
KeyboardStickyView,
useKeyboardState,
} from "react-native-keyboard-controller";
import { KeyboardAvoidingView, useKeyboardState } from "react-native-keyboard-controller";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { useThemeColor } from "../../lib/useThemeColor";
import { useFontFamily } from "../../lib/useFontFamily";
@@ -989,29 +985,14 @@ export function NewTaskDraftScreen(props: {
// The draft is a thread that doesn't exist yet, so it mirrors the thread
// page: in-screen header, empty feed canvas above, and the same floating
// composer chrome as ThreadComposer (collapsed pill → expanded card).
//
// Composer positioning mirrors ThreadDetailScreen's floating overlay
// (KeyboardStickyView, absolute bottom overlay) rather than
// KeyboardAvoidingView's automaticOffset+padding: automaticOffset
// resolves the composer's on-screen frame via a native
// viewPositionInWindow measurement, which this app's Android
// edge-to-edge setup (KeyboardProvider's native content-view margin
// handling neutralizes windowSoftInputMode="adjustResize" while active)
// makes unreliable — the composer stayed under the keyboard instead of
// translating above it. KeyboardStickyView sticks directly to the
// animated keyboard height instead, sidestepping that measurement.
return (
<View className="flex-1 bg-screen">
<NativeStackScreenOptions options={{ headerShown: false }} />
<AndroidScreenHeader title="New Thread" onBack={() => navigation.goBack()} />
<View className="flex-1" />
<KeyboardAvoidingView automaticOffset behavior="padding" className="flex-1">
<View className="flex-1" />
<KeyboardStickyView
enabled={isKeyboardVisible}
style={{ position: "absolute", bottom: 0, left: 0, right: 0 }}
offset={{ closed: 0, opened: 0 }}
>
<View
className="px-4 pt-2"
style={{
@@ -1075,7 +1056,7 @@ export function NewTaskDraftScreen(props: {
</ComposerToolbarRow>
) : null}
</View>
</KeyboardStickyView>
</KeyboardAvoidingView>
{settingsSheet}
</View>
);
@@ -1,64 +1,18 @@
import type { ApprovalRequestId, UserInputQuestion } from "@t3tools/contracts";
import { useCallback, useRef } from "react";
import { Platform, Pressable, ScrollView, View, type LayoutChangeEvent } from "react-native";
import Animated, {
Easing,
FadeInUp,
FadeOutDown,
LinearTransition,
useAnimatedStyle,
useSharedValue,
withTiming,
type SharedValue,
} from "react-native-reanimated";
import type { ApprovalRequestId } from "@t3tools/contracts";
import { Pressable, View } from "react-native";
import { USER_INPUT_TOGGLE_DURATION_MS } from "./pendingUserInputLayout";
import { SymbolView } from "../../components/AppSymbol";
import { AppText as Text, AppTextInput as TextInput } from "../../components/AppText";
import { ControlPill } from "../../components/ControlPill";
import { cn } from "../../lib/cn";
import { useThemeColor } from "../../lib/useThemeColor";
import {
isPendingUserInputOptionSelected,
type PendingUserInput,
type PendingUserInputDraftAnswer,
} from "../../lib/threadActivity";
import type { PendingUserInput, PendingUserInputDraftAnswer } from "../../lib/threadActivity";
export interface PendingUserInputCardProps {
readonly pendingUserInput: PendingUserInput;
/**
* Constant while a request is pending (it reserves keyboard space), so the
* keyboard transition is pure translation; changes only on rare discrete
* corrections, which the layout transition smooths.
*/
readonly maxHeight: number;
readonly collapsed: boolean;
readonly onToggleCollapsed: () => void;
/** Renders a stop control on the collapsed bar, which replaces the composer. */
readonly onStopThread?: () => void;
/**
* 0 collapsed → 1 expanded. Slides the iOS overlay card down behind the
* collapsed bar (inside a clipping window) on the UI thread; the host
* animates it directly from the tap handler so the card and the feed
* inset glide start the same frame.
*/
readonly cardProgress?: SharedValue<number>;
/**
* Receives how far the expanded card extends above the bar footprint
* (written from onLayout with no re-render); the host adds it to the
* thread feed's end inset so the end of the chat stays visible above the
* card.
*/
readonly cardCoverage?: SharedValue<number>;
/** Fires on custom-answer focus/blur; hosts use it to vet stale keyboard state. */
readonly onInputFocusChange?: (focused: boolean) => void;
readonly drafts: Record<string, PendingUserInputDraftAnswer>;
readonly answers: Record<string, string | ReadonlyArray<string>> | null;
readonly answers: Record<string, string> | null;
readonly respondingUserInputId: ApprovalRequestId | null;
readonly onSelectOption: (
requestId: ApprovalRequestId,
question: UserInputQuestion,
questionId: string,
label: string,
) => void;
readonly onChangeCustomAnswer: (
@@ -69,242 +23,74 @@ export interface PendingUserInputCardProps {
readonly onSubmit: () => Promise<unknown>;
}
/**
* On iOS the collapsed bar is the PERMANENT in-flow footprint — the expanded
* card is an absolutely-positioned overlay rising above it. The overlay's
* measured height (which drives the thread feed's bottom inset) therefore
* never changes on collapse/expand, so the transcript stays perfectly still
* while the card animates over it.
*
* Android cannot use the overlay: it does not hit-test touches outside a
* parent's bounds, which made everything above the bar-sized wrapper
* untouchable. There the expanded card renders in-flow instead (the wrapper
* grows with it, and the host skips the coverage inset since the measured
* overlay already includes the card).
*/
const EXPANDED_CARD_IS_OVERLAY = Platform.OS === "ios";
const CARD_LAYOUT_TRANSITION = LinearTransition.duration(200);
export function PendingUserInputCard(props: PendingUserInputCardProps) {
const iconSubtle = useThemeColor("--color-icon-subtle");
const questionCount = props.pendingUserInput.questions.length;
const cardCoverage = props.cardCoverage;
const barHeightRef = useRef(0);
const cardHeightRef = useRef(0);
// Measured card height, written straight from onLayout: the collapse slide
// distance. Not animated — it only changes on discrete relayouts.
const cardHeight = useSharedValue(0);
const notifyCoverage = useCallback(() => {
if (!cardCoverage) {
return;
}
const coverage = Math.max(0, cardHeightRef.current - barHeightRef.current);
if (coverage === cardCoverage.value) {
return;
}
if (cardCoverage.value === 0) {
// First measurement lands while the list is doing its initial
// end-pin (thread opened onto a pending request); animating it from
// zero would move the end anchor out from under that scroll.
cardCoverage.value = coverage;
return;
}
// Animated so a coverage change at rest (discrete max-height
// corrections) glides the feed instead of stepping it; toggle timing is
// owned by the host's progress values.
cardCoverage.value = withTiming(coverage, {
duration: USER_INPUT_TOGGLE_DURATION_MS,
easing: Easing.out(Easing.cubic),
});
}, [cardCoverage]);
const handleBarLayout = useCallback(
(event: LayoutChangeEvent) => {
barHeightRef.current = event.nativeEvent.layout.height;
notifyCoverage();
},
[notifyCoverage],
);
const handleCardLayout = useCallback(
(event: LayoutChangeEvent) => {
cardHeightRef.current = event.nativeEvent.layout.height;
cardHeight.value = event.nativeEvent.layout.height;
notifyCoverage();
},
[cardHeight, notifyCoverage],
);
const cardProgress = props.cardProgress;
// No opacity: fading an opaque card over the live transcript reads as a
// crossfade (card text, transcript, and bar all half-visible at once).
// Instead the card stays opaque and slides its full height down past the
// clipping window's bottom edge, so the transcript is only revealed where
// the card has physically left.
const cardAnimatedStyle = useAnimatedStyle(() => {
const progress = cardProgress === undefined ? 1 : cardProgress.value;
return {
transform: [{ translateY: (1 - progress) * cardHeight.value }],
};
});
// On iOS the card stays MOUNTED while collapsed (hidden via the animated
// style): expanding animates existing views on the UI thread the same
// frame the host starts the progress timing, instead of paying a React
// mount + layout before anything moves.
const renderCard = EXPANDED_CARD_IS_OVERLAY || !props.collapsed;
const showBar = props.collapsed || EXPANDED_CARD_IS_OVERLAY;
// The bar renders UNDER the card (earlier in JSX), always opaque: while
// expanded the opaque card covers it, and during the collapse slide the
// card's top edge wipes past and reveals it — no opacity handoff, so no
// crossfade frames.
const bar = showBar ? (
<View
onLayout={handleBarLayout}
pointerEvents={props.collapsed ? "auto" : "none"}
accessibilityElementsHidden={!props.collapsed}
importantForAccessibility={props.collapsed ? "auto" : "no-hide-descendants"}
className="flex-row items-center gap-2 rounded-full border border-neutral-200 bg-neutral-100 py-1.5 pl-4 pr-1.5 dark:border-white/6 dark:bg-neutral-900"
>
<Pressable
accessibilityRole="button"
accessibilityLabel={`Expand user input, ${questionCount} question${
questionCount === 1 ? "" : "s"
}`}
onPress={props.onToggleCollapsed}
className="min-h-10 flex-1 flex-row items-center gap-2 active:opacity-70"
>
<Text className="font-t3-bold text-2xs uppercase tracking-[1.1px] text-sky-700 dark:text-sky-300">
User input needed
</Text>
<Text className="font-sans text-xs text-neutral-500 dark:text-neutral-400">
{questionCount} question{questionCount === 1 ? "" : "s"}
</Text>
<View className="flex-1" />
<SymbolView name="chevron.up" size={12} tintColor={iconSubtle} type="monochrome" />
</Pressable>
{props.onStopThread ? (
<ControlPill
accessibilityLabel="Stop"
icon="stop.fill"
variant="danger"
className="h-9 w-9"
onPress={props.onStopThread}
/>
) : null}
</View>
) : null;
const card = renderCard ? (
// The surface is opaque on purpose: the card floats over the thread
// feed with no blur behind it, so a translucent background renders
// the questions on top of whatever message happens to sit underneath.
<Animated.View
onLayout={handleCardLayout}
pointerEvents={props.collapsed ? "none" : "auto"}
accessibilityElementsHidden={props.collapsed}
importantForAccessibility={props.collapsed ? "no-hide-descendants" : "auto"}
entering={
EXPANDED_CARD_IS_OVERLAY
? undefined
: FadeInUp.duration(USER_INPUT_TOGGLE_DURATION_MS).easing(Easing.out(Easing.cubic))
}
exiting={
EXPANDED_CARD_IS_OVERLAY
? undefined
: FadeOutDown.duration(USER_INPUT_TOGGLE_DURATION_MS).easing(Easing.out(Easing.cubic))
}
layout={CARD_LAYOUT_TRANSITION}
className="overflow-hidden gap-2.5 rounded-[20px] border border-neutral-200 bg-neutral-100 p-4 dark:border-white/6 dark:bg-neutral-900"
style={
EXPANDED_CARD_IS_OVERLAY
? [{ maxHeight: props.maxHeight }, cardAnimatedStyle]
: { maxHeight: props.maxHeight }
}
>
<Pressable
accessibilityRole="button"
accessibilityLabel="Collapse user input"
onPress={props.onToggleCollapsed}
className="flex-row items-start gap-2"
>
<View className="flex-1 gap-2.5">
<Text className="font-t3-bold text-2xs uppercase tracking-[1.1px] text-sky-700 dark:text-sky-300">
User input needed
</Text>
<Text className="font-t3-bold text-lg text-neutral-950 dark:text-neutral-50">
Fill in the pending answers
</Text>
</View>
<View className="h-8 w-8 items-center justify-center rounded-full bg-neutral-200/70 dark:bg-white/8">
<SymbolView name="chevron.down" size={13} tintColor={iconSubtle} type="monochrome" />
</View>
</Pressable>
<ScrollView
bounces={false}
className="min-h-0"
contentContainerClassName="gap-2.5 pb-1"
keyboardShouldPersistTaps="handled"
nestedScrollEnabled
showsVerticalScrollIndicator
style={{ flexShrink: 1 }}
>
{props.pendingUserInput.questions.map((question) => {
const draft = props.drafts[question.id];
return (
<View key={question.id} className="gap-2 pt-1">
<Text className="font-t3-bold text-xs uppercase tracking-[1px] text-neutral-500 dark:text-neutral-500">
{question.header}
</Text>
<Text className="font-sans text-base leading-snug text-neutral-950 dark:text-neutral-50">
{question.question}
</Text>
<View className="flex-row flex-wrap gap-2.5">
{question.options.map((option) => {
const selected = isPendingUserInputOptionSelected(draft, option.label);
return (
<Pressable
key={option.label}
// The surface is opaque on purpose: the card floats over the thread feed
// with no blur behind it, so a translucent background renders the questions
// on top of whatever message happens to sit underneath.
return (
<View className="gap-2.5 rounded-[20px] border border-neutral-200 bg-neutral-100 p-4 dark:border-white/6 dark:bg-neutral-900">
<Text className="font-t3-bold text-2xs uppercase tracking-[1.1px] text-sky-700 dark:text-sky-300">
User input needed
</Text>
<Text className="font-t3-bold text-lg text-neutral-950 dark:text-neutral-50">
Fill in the pending answers
</Text>
{props.pendingUserInput.questions.map((question) => {
const draft = props.drafts[question.id];
return (
<View key={question.id} className="gap-2 pt-1">
<Text className="font-t3-bold text-xs uppercase tracking-[1px] text-neutral-500 dark:text-neutral-500">
{question.header}
</Text>
<Text className="font-sans text-base leading-snug text-neutral-950 dark:text-neutral-50">
{question.question}
</Text>
<View className="flex-row flex-wrap gap-2.5">
{question.options.map((option) => {
const selected =
draft?.selectedOptionLabel === option.label && !draft.customAnswer?.trim().length;
return (
<Pressable
key={option.label}
className={cn(
"rounded-full border px-3 py-2.5 ",
selected
? "border-blue-300/50 bg-blue-50 dark:border-blue-400/28 dark:bg-blue-400/14"
: "border-neutral-200 bg-white dark:border-white/6 dark:bg-neutral-950/70",
)}
onPress={() =>
props.onSelectOption(
props.pendingUserInput.requestId,
question.id,
option.label,
)
}
>
<Text
className={cn(
"rounded-full border px-3 py-2.5 ",
"font-t3-bold text-sm",
selected
? "border-blue-300/50 bg-blue-50 dark:border-blue-400/28 dark:bg-blue-400/14"
: "border-neutral-200 bg-white dark:border-white/6 dark:bg-neutral-950/70",
? "text-sky-700 dark:text-sky-300"
: "text-neutral-600 dark:text-neutral-300",
)}
onPress={() =>
props.onSelectOption(
props.pendingUserInput.requestId,
question,
option.label,
)
}
>
<Text
className={cn(
"font-t3-bold text-sm",
selected
? "text-sky-700 dark:text-sky-300"
: "text-neutral-600 dark:text-neutral-300",
)}
>
{option.label}
</Text>
</Pressable>
);
})}
</View>
<TextInput
value={draft?.customAnswer ?? ""}
onChangeText={(value) =>
props.onChangeCustomAnswer(props.pendingUserInput.requestId, question.id, value)
}
onFocus={() => props.onInputFocusChange?.(true)}
onBlur={() => props.onInputFocusChange?.(false)}
placeholder="Or type a custom answer"
className="min-h-[54px] rounded-2xl border border-neutral-200 bg-white px-3.5 py-3 font-sans text-base text-neutral-950 dark:border-white/8 dark:bg-neutral-950/70 dark:text-neutral-50"
/>
{option.label}
</Text>
</Pressable>
);
})}
</View>
);
})}
</ScrollView>
<TextInput
value={draft?.customAnswer ?? ""}
onChangeText={(value) =>
props.onChangeCustomAnswer(props.pendingUserInput.requestId, question.id, value)
}
placeholder="Or type a custom answer"
className="min-h-[54px] rounded-2xl border border-neutral-200 bg-white px-3.5 py-3 font-sans text-base text-neutral-950 dark:border-white/8 dark:bg-neutral-950/70 dark:text-neutral-50"
/>
</View>
);
})}
<Pressable
className={cn(
"items-center justify-center rounded-2xl px-4 py-3.5",
@@ -317,26 +103,6 @@ export function PendingUserInputCard(props: PendingUserInputCardProps) {
>
<Text className="font-t3-extrabold text-sm text-white">Submit answers</Text>
</Pressable>
</Animated.View>
) : null;
return (
<View className="relative">
{bar}
{EXPANDED_CARD_IS_OVERLAY ? (
// Clipping window for the collapse slide: same footprint as the
// expanded card, bottom edge on the bar's bottom edge. The sliding
// card exits through the bottom edge instead of drawing over the
// composer area, wiping the bar (and the transcript) into view.
<View
pointerEvents={props.collapsed ? "none" : "box-none"}
className="absolute inset-x-0 bottom-0 justify-end overflow-hidden"
style={{ height: props.maxHeight }}
>
{card}
</View>
) : (
card
)}
</View>
);
}
@@ -14,7 +14,6 @@ import {
serializeComposerFileLink,
type ComposerTrigger,
} from "@t3tools/shared/composerTrigger";
import * as Haptics from "expo-haptics";
import type { ReactNode } from "react";
import { memo, useCallback, useEffect, useMemo, useRef, useState, type RefObject } from "react";
import {
@@ -52,7 +51,7 @@ import {
ComposerToolbarScroller,
ComposerToolbarTrigger,
} from "../../components/ComposerToolbarTrigger";
import { ControlPill, ControlPillMenu } from "../../components/ControlPill";
import { ControlPill } from "../../components/ControlPill";
import { ProviderIcon } from "../../components/ProviderIcon";
import type { DraftComposerImageAttachment } from "../../lib/composerImages";
import { buildModelOptions, groupByProvider } from "../../lib/modelOptions";
@@ -63,13 +62,9 @@ import {
normalizeSearchQuery,
scoreQueryMatch,
} from "@t3tools/shared/searchRanking";
import {
applyProviderOptionSelection,
resolveProviderOptionDescriptors,
} from "../../lib/providerOptions";
import { resolveProviderOptionDescriptors } from "../../lib/providerOptions";
import { useComposerPathSearch } from "../../state/use-composer-path-search";
import { ComposerCommandPopover, type ComposerCommandItem } from "./ComposerCommandPopover";
import { buildThreadSettingsMenu } from "./thread-settings-menu";
import { ThreadSettingsSheet, threadSettingsSummaryLabel } from "./ThreadSettingsSheet";
import { useThreadSettingsSheetPresentation } from "./use-thread-settings-sheet-presentation";
@@ -118,8 +113,6 @@ export interface ThreadComposerProps {
readonly onUpdateInteractionMode: (interactionMode: ProviderInteractionMode) => void;
readonly onReconnectEnvironment: () => void;
readonly onExpandedChange?: (expanded: boolean) => void;
/** Fires on editor focus/blur; hosts use it to vet stale keyboard state. */
readonly onEditorFocusChange?: (focused: boolean) => void;
}
/**
@@ -314,16 +307,13 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
}
}, [inputRef]);
const onEditorFocusChange = props.onEditorFocusChange;
const handleFocus = useCallback(() => {
setIsFocused(true);
onEditorFocusChange?.(true);
}, [onEditorFocusChange]);
}, []);
const handleBlur = useCallback(() => {
setIsFocused(false);
onEditorFocusChange?.(false);
}, [onEditorFocusChange]);
}, []);
const showStopAction =
props.selectedThread.session?.status === "running" ||
props.selectedThread.session?.status === "starting";
@@ -633,61 +623,6 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
interactionMode: currentInteractionMode,
});
// iOS gets a native menu on the trigger pill: the everyday adjustments
// apply without resigning the keyboard, while "All Settings…" (and the
// Android trigger) still route through the sheet, which must dismiss it.
const settingsMenu = useMemo(
() =>
Platform.OS === "ios"
? buildThreadSettingsMenu({
providerGroups: threadProviderGroups,
selectedModel: currentModelSelection,
optionDescriptors: providerOptionDescriptors,
runtimeMode: currentRuntimeMode,
})
: null,
[threadProviderGroups, currentModelSelection, providerOptionDescriptors, currentRuntimeMode],
);
const onUpdateModelSelection = props.onUpdateModelSelection;
const onUpdateRuntimeMode = props.onUpdateRuntimeMode;
const handleSettingsMenuAction = useCallback(
(eventId: string) => {
const event = settingsMenu?.events.get(eventId);
if (!event) {
return;
}
switch (event.type) {
case "select-model":
void Haptics.selectionAsync();
onUpdateModelSelection(event.option.selection);
return;
case "set-option": {
const options = applyProviderOptionSelection(providerOptionDescriptors, {
id: event.optionId,
value: event.value,
});
if (options) {
void Haptics.selectionAsync();
onUpdateModelSelection({ ...currentModelSelection, options });
}
return;
}
case "set-runtime":
void Haptics.selectionAsync();
onUpdateRuntimeMode(event.mode);
return;
}
},
[
currentModelSelection,
onUpdateModelSelection,
onUpdateRuntimeMode,
providerOptionDescriptors,
settingsMenu,
],
);
return (
<Animated.View
className="px-4"
@@ -857,31 +792,15 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
onPress={() => void props.onPickDraftImages()}
showChevron={false}
/>
{settingsMenu ? (
<ControlPillMenu
actions={settingsMenu.actions}
onPressAction={({ nativeEvent }) => handleSettingsMenuAction(nativeEvent.event)}
>
<ComposerToolbarTrigger
accessibilityLabel="Thread settings"
iconNode={
<ProviderIcon provider={currentModelOption?.providerDriver} size={16} />
}
label={settingsSummaryLabel}
maxWidth={320}
/>
</ControlPillMenu>
) : (
<ComposerToolbarTrigger
accessibilityLabel="Thread settings"
iconNode={
<ProviderIcon provider={currentModelOption?.providerDriver} size={16} />
}
label={settingsSummaryLabel}
maxWidth={320}
onPress={settingsSheetPresentation.open}
/>
)}
<ComposerToolbarTrigger
accessibilityLabel="Thread settings"
iconNode={
<ProviderIcon provider={currentModelOption?.providerDriver} size={16} />
}
label={settingsSummaryLabel}
maxWidth={320}
onPress={settingsSheetPresentation.open}
/>
{showStopAction ? (
<ComposerToolbarButton
accessibilityLabel="Stop"
@@ -2,7 +2,6 @@ import { type EnvironmentConnectionPhase } from "@t3tools/client-runtime/connect
import type { EnvironmentThreadStatus } from "@t3tools/client-runtime/state/threads";
import { useKeyboardChatComposerInset, useKeyboardScrollToEnd } from "@legendapp/list/keyboard";
import type { LegendListRef } from "@legendapp/list/react-native";
import { HeaderHeightContext } from "@react-navigation/elements";
import type {
ApprovalRequestId,
EnvironmentId,
@@ -14,45 +13,14 @@ import type {
RuntimeMode,
ServerConfig as T3ServerConfig,
ThreadId,
UserInputQuestion,
} from "@t3tools/contracts";
import * as Haptics from "expo-haptics";
import {
memo,
useCallback,
useContext,
useEffect,
useLayoutEffect,
useMemo,
useRef,
useState,
} from "react";
import { isLiquidGlassSupported, LiquidGlassView } from "@callstack/liquid-glass";
import {
AppState,
Keyboard,
Platform,
useColorScheme,
useWindowDimensions,
View,
type GestureResponderEvent,
} from "react-native";
import {
KeyboardController,
KeyboardStickyView,
useKeyboardState,
} from "react-native-keyboard-controller";
import Animated, {
Easing,
FadeInDown,
FadeOut,
useAnimatedReaction,
useSharedValue,
withTiming,
} from "react-native-reanimated";
import { memo, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
import { Platform, View, type GestureResponderEvent } from "react-native";
import { KeyboardController, KeyboardStickyView } from "react-native-keyboard-controller";
import Animated, { FadeInDown, FadeOut } from "react-native-reanimated";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { ControlPill } from "../../components/ControlPill";
import type { ComposerEditorHandle } from "../../components/ComposerEditor";
import type { StatusTone } from "../../components/StatusPill";
import type { DraftComposerImageAttachment } from "../../lib/composerImages";
@@ -66,11 +34,6 @@ import type {
} from "../../lib/threadActivity";
import { PendingApprovalCard } from "./PendingApprovalCard";
import { PendingUserInputCard } from "./PendingUserInputCard";
import {
derivePendingUserInputMaxHeight,
ESTIMATED_KEYBOARD_HEIGHT,
USER_INPUT_TOGGLE_DURATION_MS,
} from "./pendingUserInputLayout";
import {
COMPOSER_COLLAPSED_CHROME,
COMPOSER_EXPANDED_CHROME,
@@ -91,7 +54,7 @@ export interface ThreadDetailScreenProps {
readonly respondingApprovalId: ApprovalRequestId | null;
readonly activePendingUserInput: PendingUserInput | null;
readonly activePendingUserInputDrafts: Record<string, PendingUserInputDraftAnswer>;
readonly activePendingUserInputAnswers: Record<string, string | ReadonlyArray<string>> | null;
readonly activePendingUserInputAnswers: Record<string, string> | null;
readonly respondingUserInputId: ApprovalRequestId | null;
readonly draftMessage: string;
readonly draftAttachments: ReadonlyArray<DraftComposerImageAttachment>;
@@ -126,7 +89,7 @@ export interface ThreadDetailScreenProps {
) => Promise<unknown>;
readonly onSelectUserInputOption: (
requestId: ApprovalRequestId,
question: UserInputQuestion,
questionId: string,
label: string,
) => void;
readonly onChangeUserInputCustomAnswer: (
@@ -208,48 +171,8 @@ function useStreamingHaptics(threadId: ThreadId, feed: ReadonlyArray<ThreadFeedE
}, [threadId, feed]);
}
const USER_INPUT_TOGGLE_TIMING = {
duration: USER_INPUT_TOGGLE_DURATION_MS,
easing: Easing.out(Easing.cubic),
};
export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: ThreadDetailScreenProps) {
const insets = useSafeAreaInsets();
const isKeyboardVisible = useKeyboardState((state) => state.isVisible);
const liveKeyboardHeight = useKeyboardState((state) => state.height);
// Android can swallow the IME hide callbacks when the app is backgrounded
// mid keyboard-hide (the reported repro: send — which blurs and starts the
// hide — then Home within a second). The keyboard library's height AND
// visibility then stay frozen open, so gating the sticky translation on
// visibility alone still strands the composer after resume. Quarantine the
// translation on every Android resume instead; any sign of a live keyboard
// stream — an owned input gaining focus, or any visibility/height movement —
// lifts it. A healthy resume sees no visual difference (the translation is
// already zero while the keyboard is closed).
const [keyboardStateSuspect, setKeyboardStateSuspect] = useState(false);
useEffect(() => {
if (Platform.OS !== "android") {
return;
}
const subscription = AppState.addEventListener("change", (state) => {
if (state === "active") {
setKeyboardStateSuspect(true);
}
});
return () => {
subscription.remove();
};
}, []);
useEffect(() => {
setKeyboardStateSuspect(false);
}, [isKeyboardVisible, liveKeyboardHeight]);
const handleOwnedInputFocusChange = useCallback((focused: boolean) => {
if (focused) {
setKeyboardStateSuspect(false);
}
}, []);
const windowHeight = useWindowDimensions().height;
const navigationHeaderHeight = useContext(HeaderHeightContext) || insets.top + 44;
const agentLabel = `${props.selectedThread.modelSelection.instanceId} agent`;
const selectedThreadKey = scopedThreadKey(props.environmentId, props.selectedThread.id);
const composerEditorRef = useRef<ComposerEditorHandle>(null);
@@ -260,17 +183,7 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
const lastScrolledAnchorMessageIdRef = useRef<MessageId | null>(null);
const [composerExpanded, setComposerExpanded] = useState(false);
const [anchorMessageId, setAnchorMessageId] = useState<MessageId | null>(null);
const [endFollowEnabled, setEndFollowEnabled] = useState(true);
// Android keys the safe-area padding on keyboard visibility (#5988): the
// back gesture closes the keyboard while the editor stays focused, and a
// focus-keyed inset would leave the toolbar under the gesture bar. iOS must
// NOT use visibility — it only flips on keyboardDidHide, after the hide
// animation, so the composer would ride down flush to the screen edge and
// then snap up into the inset. On iOS blur precedes the hide, so the
// focus-keyed inset is already in place while the composer rides down.
const composerBottomInset = (Platform.OS === "android" ? isKeyboardVisible : composerExpanded)
? 0
: Math.max(insets.bottom, 12);
const composerBottomInset = composerExpanded ? 0 : Math.max(insets.bottom, 12);
const contentPresentationKind = props.contentPresentation.kind;
// The raw sync status enters "synchronizing" on every full fetch, cached or
// not. Whether messages are already on screen decides the pill label: no
@@ -291,41 +204,6 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
const selectedThreadFeed = props.selectedThreadFeed;
const composerChrome = composerExpanded ? COMPOSER_EXPANDED_CHROME : COMPOSER_COLLAPSED_CHROME;
const composerOverlapHeight = composerChrome + composerBottomInset;
// While a user-input request is pending, the questionnaire owns the
// composer slot outright: expanded it is the full card, collapsed it is a
// composer-style bar in the same place (with its own stop control). The
// composer never mounts into the transition, which keeps the collapse and
// keyboard animations coherent. Collapse state is keyed by request id so a
// new request re-expands automatically.
const [collapsedUserInputRequestId, setCollapsedUserInputRequestId] =
useState<ApprovalRequestId | null>(null);
const activeUserInputRequestId = props.activePendingUserInput?.requestId ?? null;
const userInputCollapsed =
activeUserInputRequestId !== null && collapsedUserInputRequestId === activeUserInputRequestId;
// The card's height RESERVES keyboard space at all times instead of
// tracking the keyboard: transforms (the sticky translation) apply
// same-frame on the UI thread while layout props lag a Yoga pass behind,
// so any height that follows the keyboard flashes the card over the nav
// header on the way up. With a constant height the keyboard transition is
// pure translation — frame-perfect by construction — and the resting card
// stays compact over the transcript. Before the first open the reserve is
// an estimate; once a real height is known the card corrects once,
// discretely.
const [lastKnownKeyboardHeight, setLastKnownKeyboardHeight] = useState(0);
useEffect(() => {
if (liveKeyboardHeight > 0 && liveKeyboardHeight !== lastKnownKeyboardHeight) {
setLastKnownKeyboardHeight(liveKeyboardHeight);
}
}, [lastKnownKeyboardHeight, liveKeyboardHeight]);
const pendingUserInputMaxHeight = derivePendingUserInputMaxHeight({
windowHeight,
keyboardHeight:
lastKnownKeyboardHeight > 0 ? lastKnownKeyboardHeight : ESTIMATED_KEYBOARD_HEIGHT,
navigationHeaderHeight,
// The questionnaire owns the composer slot, so only the composer's
// bottom inset still overlaps.
composerOverlapHeight: composerBottomInset,
});
const estimatedOverlayHeight = composerOverlapHeight;
// The overlay's measured height includes the home-indicator inset (the
// composer pads it), but contentInsetAdjustmentBehavior="automatic" makes
@@ -342,103 +220,7 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
Math.max(0, estimatedOverlayHeight - nativeInsetOvercount),
-nativeInsetOvercount,
);
// The expanded questionnaire is an absolute overlay on iOS, so it never
// changes the measured overlay height (that constancy is what keeps the
// feed from snapping on collapse/expand). The toggle choreography runs on
// SHARED VALUES set directly in the tap handler — one JS hop, then the
// card's rise/sink and the feed's end-inset glide animate in lockstep on
// the UI thread, keyboard-style, instead of waiting on React mount +
// onLayout + state round trips. Coverage (how far the card extends above
// the bar) is measured straight into a shared value by the card's
// onLayout, with no re-render.
const userInputCardProgress = useSharedValue(1);
const userInputInsetProgress = useSharedValue(1);
const userInputCardCoverage = useSharedValue(0);
// Android renders the expanded card in-flow (it cannot hit-test the iOS
// overlay outside the bar's bounds), so its measured overlay height already
// includes the card — the coverage extra is iOS-only.
const userInputCoverageApplies = Platform.OS === "ios" && activeUserInputRequestId !== null;
const combinedContentInsetEndAdjustment = useSharedValue(
Math.max(0, estimatedOverlayHeight - nativeInsetOvercount),
);
useAnimatedReaction(
() =>
contentInsetEndAdjustment.value +
(userInputCoverageApplies ? userInputInsetProgress.value * userInputCardCoverage.value : 0),
(value) => {
combinedContentInsetEndAdjustment.value = value;
},
[userInputCoverageApplies],
);
const { freeze, scrollMessageToEnd } = useKeyboardScrollToEnd({ listRef });
const endFollowEnabledRef = useRef(true);
endFollowEnabledRef.current = endFollowEnabled;
const userInputRepinTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
// The list's own corrections for these inset changes drift on short
// content (and the error compounds across toggles), so deterministically
// re-pin the end once a toggle settles: a no-op when the resting position
// is already right, corrective when it is not. Follow state is re-checked
// inside the callback — the user may grab the list during the settle
// window, and yanking them back would override a live gesture.
const scheduleUserInputRepin = useCallback(
(delayMs: number) => {
if (userInputRepinTimerRef.current !== null) {
clearTimeout(userInputRepinTimerRef.current);
}
userInputRepinTimerRef.current = setTimeout(() => {
userInputRepinTimerRef.current = null;
if (!endFollowEnabledRef.current) {
return;
}
void scrollMessageToEnd({ animated: false, closeKeyboard: false }).catch(() => {
freeze.set(false);
});
}, delayMs);
},
[freeze, scrollMessageToEnd],
);
useEffect(
() => () => {
if (userInputRepinTimerRef.current !== null) {
clearTimeout(userInputRepinTimerRef.current);
}
},
[],
);
const handleToggleUserInputCollapsed = useCallback(() => {
if (activeUserInputRequestId === null) {
return;
}
if (userInputCollapsed) {
// Expanding: card and feed glide start NOW, on the UI thread.
userInputCardProgress.value = withTiming(1, USER_INPUT_TOGGLE_TIMING);
userInputInsetProgress.value = withTiming(1, USER_INPUT_TOGGLE_TIMING);
setCollapsedUserInputRequestId(null);
scheduleUserInputRepin(USER_INPUT_TOGGLE_DURATION_MS + 50);
} else {
// Collapsing hides the custom-answer inputs; release the keyboard with
// them instead of leaving it up over a dead responder.
Keyboard.dismiss();
userInputCardProgress.value = withTiming(0, USER_INPUT_TOGGLE_TIMING);
// Instant: the sinking card still covers the strip being revealed, and
// animating the inset downward is what drifted the short-content end
// anchor.
userInputInsetProgress.value = 0;
setCollapsedUserInputRequestId(activeUserInputRequestId);
scheduleUserInputRepin(60);
}
}, [
activeUserInputRequestId,
scheduleUserInputRepin,
userInputCardProgress,
userInputCollapsed,
userInputInsetProgress,
]);
useEffect(() => {
// A new request always arrives expanded.
userInputCardProgress.value = 1;
userInputInsetProgress.value = 1;
}, [activeUserInputRequestId, userInputCardProgress, userInputInsetProgress]);
const showContent = props.showContent ?? true;
const layoutVariant = props.layoutVariant ?? "compact";
const isSplitLayout = layoutVariant === "split";
@@ -459,7 +241,6 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
useEffect(() => {
setAnchorMessageId(null);
lastScrolledAnchorMessageIdRef.current = null;
setEndFollowEnabled(true);
freeze.set(false);
}, [freeze, selectedThreadKey]);
@@ -531,16 +312,6 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
composerEditorRef.current?.blur();
}, []);
const handleScrollToEnd = useCallback(() => {
void Haptics.selectionAsync();
void scrollMessageToEnd({ animated: true, closeKeyboard: false }).catch(() => {
freeze.set(false);
});
}, [freeze, scrollMessageToEnd]);
const showScrollToEndButton = contentPresentationKind === "ready" && !endFollowEnabled;
const isDarkMode = useColorScheme() === "dark";
const handleFeedTouchStart = useCallback((event: GestureResponderEvent) => {
feedTouchStartRef.current = {
pageX: event.nativeEvent.pageX,
@@ -594,14 +365,13 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
listRef={listRef}
freeze={freeze}
anchorMessageId={anchorMessageId}
contentInsetEndAdjustment={combinedContentInsetEndAdjustment}
contentInsetEndAdjustment={contentInsetEndAdjustment}
contentTopInset={0}
contentBottomInset={estimatedOverlayHeight}
contentMaxWidth={contentMaxWidth}
layoutVariant={layoutVariant}
usesAutomaticContentInsets={props.usesAutomaticContentInsets}
onHeaderMaterialVisibilityChange={props.onHeaderMaterialVisibilityChange}
onEndFollowEnabledChange={setEndFollowEnabled}
skills={selectedProviderSkills}
loadEarlier={props.loadEarlier ?? null}
/>
@@ -613,10 +383,6 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
{/* Floating composer — sticks to keyboard via KeyboardStickyView */}
{showContent ? (
<KeyboardStickyView
// The animated keyboard height can remain stale after a dismissed
// IME on both platforms. Visibility is the authoritative closed
// state, so disable the translation rather than stranding the pill.
enabled={isKeyboardVisible && !keyboardStateSuspect}
style={{ position: "absolute", bottom: 0, left: 0, right: 0 }}
offset={{ closed: 0, opened: 0 }}
>
@@ -624,60 +390,10 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
list's bottom inset, so any padding above the pill/composer
pushes the resting content floor up by the same amount. */}
<View ref={composerOverlayRef} onLayout={onComposerLayout} className="w-full">
{showScrollToEndButton ? (
<Animated.View
pointerEvents="box-none"
className="absolute -top-11 left-0 right-0 z-20 items-center"
entering={FadeInDown.duration(160)}
exiting={FadeOut.duration(100)}
>
{isLiquidGlassSupported ? (
<LiquidGlassView
colorScheme={isDarkMode ? "dark" : "light"}
effect="regular"
interactive
// Interactive glass can render larger than the requested
// box (minimum touch size), so center the pill instead of
// relying on it filling the glass exactly.
style={{
alignItems: "center",
borderRadius: 18,
height: 36,
justifyContent: "center",
overflow: "hidden",
width: 36,
}}
>
<ControlPill
accessibilityLabel="Scroll to end"
activateOnPressIn
className="h-9 w-9 bg-transparent"
icon={{ ios: "chevron.down", android: "keyboard_arrow_down" }}
onPress={handleScrollToEnd}
/>
</LiquidGlassView>
) : (
<ControlPill
accessibilityLabel="Scroll to end"
activateOnPressIn
className="h-9 w-9 border border-border bg-card shadow-md shadow-black/10"
icon={{ ios: "chevron.down", android: "keyboard_arrow_down" }}
onPress={handleScrollToEnd}
/>
)}
</Animated.View>
) : null}
<View className="w-full self-center" style={{ maxWidth: contentMaxWidth }}>
{props.activePendingApproval || props.activePendingUserInput ? (
<Animated.View
className="shrink-0 gap-3 px-4 pb-3"
// The questionnaire replaces the composer, so it must pad
// the home indicator the composer normally covers.
style={
activeUserInputRequestId !== null
? { paddingBottom: composerBottomInset }
: undefined
}
entering={FadeInDown.duration(220)}
exiting={FadeOut.duration(140)}
>
@@ -691,13 +407,6 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
{props.activePendingUserInput ? (
<PendingUserInputCard
pendingUserInput={props.activePendingUserInput}
maxHeight={pendingUserInputMaxHeight}
collapsed={userInputCollapsed}
onToggleCollapsed={handleToggleUserInputCollapsed}
onStopThread={props.onStopThread}
cardProgress={userInputCardProgress}
cardCoverage={userInputCardCoverage}
onInputFocusChange={handleOwnedInputFocusChange}
drafts={props.activePendingUserInputDrafts}
answers={props.activePendingUserInputAnswers}
respondingUserInputId={props.respondingUserInputId}
@@ -710,40 +419,35 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
) : null}
</View>
{/* Hidden (not unmounted) while a user-input request owns the
composer slot, so composer drafts and editor state survive. */}
<View style={activeUserInputRequestId !== null ? { display: "none" } : undefined}>
<ThreadComposer
editorRef={composerEditorRef}
draftMessage={props.draftMessage}
draftAttachments={props.draftAttachments}
placeholder="Ask the repo agent, or run a command…"
contentMaxWidth={contentMaxWidth}
connectionState={props.connectionStateLabel}
connectionError={props.connectionError}
environmentLabel={props.environmentLabel}
threadSyncPhase={threadSyncPhase}
selectedThread={props.selectedThread}
serverConfig={props.serverConfig}
queueCount={props.selectedThreadQueueCount}
activeThreadBusy={props.activeThreadBusy}
environmentId={props.environmentId}
projectCwd={props.projectWorkspaceRoot}
bottomInset={composerBottomInset}
onChangeDraftMessage={props.onChangeDraftMessage}
onPickDraftImages={props.onPickDraftImages}
onNativePasteImages={props.onNativePasteImages}
onRemoveDraftImage={props.onRemoveDraftImage}
onStopThread={props.onStopThread}
onSendMessage={handleSendMessage}
onReconnectEnvironment={props.onReconnectEnvironment}
onUpdateModelSelection={props.onUpdateThreadModelSelection}
onUpdateRuntimeMode={props.onUpdateThreadRuntimeMode}
onUpdateInteractionMode={props.onUpdateThreadInteractionMode}
onExpandedChange={setComposerExpanded}
onEditorFocusChange={handleOwnedInputFocusChange}
/>
</View>
<ThreadComposer
editorRef={composerEditorRef}
draftMessage={props.draftMessage}
draftAttachments={props.draftAttachments}
placeholder="Ask the repo agent, or run a command…"
contentMaxWidth={contentMaxWidth}
connectionState={props.connectionStateLabel}
connectionError={props.connectionError}
environmentLabel={props.environmentLabel}
threadSyncPhase={threadSyncPhase}
selectedThread={props.selectedThread}
serverConfig={props.serverConfig}
queueCount={props.selectedThreadQueueCount}
activeThreadBusy={props.activeThreadBusy}
environmentId={props.environmentId}
projectCwd={props.projectWorkspaceRoot}
bottomInset={composerBottomInset}
onChangeDraftMessage={props.onChangeDraftMessage}
onPickDraftImages={props.onPickDraftImages}
onNativePasteImages={props.onNativePasteImages}
onRemoveDraftImage={props.onRemoveDraftImage}
onStopThread={props.onStopThread}
onSendMessage={handleSendMessage}
onReconnectEnvironment={props.onReconnectEnvironment}
onUpdateModelSelection={props.onUpdateThreadModelSelection}
onUpdateRuntimeMode={props.onUpdateThreadRuntimeMode}
onUpdateInteractionMode={props.onUpdateThreadInteractionMode}
onExpandedChange={setComposerExpanded}
/>
</View>
</KeyboardStickyView>
) : null}
+40 -101
View File
@@ -48,7 +48,6 @@ import { useSafeAreaInsets } from "react-native-safe-area-context";
import Animated, { FadeIn, FadeInUp, type SharedValue } from "react-native-reanimated";
import { useThemeColor } from "../../lib/useThemeColor";
import { useFontFamily } from "../../lib/useFontFamily";
import { scopedThreadKey } from "../../lib/scopedEntities";
import { copyTextWithHaptic } from "../../lib/copyTextWithHaptic";
import { hasWideMarkdownBlock } from "../../lib/wideMarkdownBlocks";
import {
@@ -90,10 +89,6 @@ import {
type ThreadFeedLatestTurn,
} from "../../lib/threadActivity";
import type { ThreadContentPresentation } from "./threadContentPresentation";
import {
resolveThreadFeedLiveFollow,
type ThreadFeedLiveFollowEvent,
} from "./thread-feed-live-follow";
import {
collapsedWorkLogHeight,
ThreadWorkGroupToggle,
@@ -104,10 +99,6 @@ import { useMarkdownCodeHighlight } from "./markdownCodeHighlightState";
import { useAssetUrl } from "../../state/assets";
import { resolveWorkspaceRelativeFilePath } from "../files/filePath";
const WIDE_MARKDOWN_BLOCK_OPTIONS = {
includeOrderedLists: Platform.OS === "android",
} as const;
const MESSAGE_TIME_FORMATTER = new Intl.DateTimeFormat(undefined, {
hour: "numeric",
minute: "2-digit",
@@ -158,7 +149,6 @@ export interface ThreadFeedProps {
readonly layoutVariant?: LayoutVariant;
readonly usesAutomaticContentInsets?: boolean;
readonly onHeaderMaterialVisibilityChange?: (visible: boolean) => void;
readonly onEndFollowEnabledChange?: (enabled: boolean) => void;
readonly skills?: ReadonlyArray<SelectableMarkdownSkill>;
/** Non-null when older turns exist beyond the loaded window. */
readonly loadEarlier?: {
@@ -892,7 +882,7 @@ function renderFeedEntry(
// children during the unclamped pass and never moves them once the width
// is clamped, so the paragraphs around the block end up drawn on top of
// each other. Pinning the width removes that pass.
const hasWideBlock = hasWideMarkdownBlock(message.text, WIDE_MARKDOWN_BLOCK_OPTIONS);
const hasWideBlock = hasWideMarkdownBlock(message.text);
const assistantTurnStillInProgress =
message.role === "assistant" &&
props.unsettledTurnId !== null &&
@@ -1334,7 +1324,6 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
const disclosureAnchorKeyRef = useRef<string | null>(null);
const headerMaterialVisibleRef = useRef(false);
const previousLatestTurnRef = useRef(props.latestTurn);
const userScrollSettleTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const { width: windowWidth } = useWindowDimensions();
const { appearance } = useAppearancePreferences();
const [viewportWidth, setViewportWidth] = useState(() =>
@@ -1353,23 +1342,13 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
// momentum; only motion inside a session can break follow, so MVCP
// compensations and programmatic scrolls never strand a follower.
const userScrollSessionRef = useRef(false);
const setEndFollow = useCallback(
(enabled: boolean) => {
if (endFollowEnabledRef.current === enabled) {
return;
}
endFollowEnabledRef.current = enabled;
setEndFollowEnabled(enabled);
props.onEndFollowEnabledChange?.(enabled);
},
[props.onEndFollowEnabledChange],
);
const transitionEndFollow = useCallback(
(event: ThreadFeedLiveFollowEvent) => {
setEndFollow(resolveThreadFeedLiveFollow(endFollowEnabledRef.current, event));
},
[setEndFollow],
);
const setEndFollow = useCallback((enabled: boolean) => {
if (endFollowEnabledRef.current === enabled) {
return;
}
endFollowEnabledRef.current = enabled;
setEndFollowEnabled(enabled);
}, []);
const [interactionState, setInteractionState] = useState<{
readonly copiedRowId: string | null;
readonly expandedWorkGroups: Record<string, boolean>;
@@ -1481,72 +1460,40 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
// UIKit's adjustedContentInset, so topContentInset is 0 here). Add the
// header height back or the material toggles a full header too late.
reportHeaderMaterialVisibility(event.nativeEvent.contentOffset.y + anchorTopInset > 6);
// LegendList recomputes its inset-aware end distance before invoking
// this handler, so getState() is current. Only the actual end re-arms
// follow: its broader maintain-scroll threshold is large enough for a
// streaming chunk to pull a user back before their upward drag escapes.
// A live user-scroll session still wins even if the first scroll event
// remains inside LegendList's at-end tolerance.
// Latch bookkeeping. LegendList recomputes its inset-aware end distance
// before invoking this handler, so getState() is current. Returning to
// the end re-arms follow no matter who scrolled (the user, or our own
// scroll-to-end); moving away breaks it only during a user-initiated
// scroll session, so MVCP compensations and programmatic repositioning
// can never strand a follower.
const listState = props.listRef.current?.getState();
if (listState) {
transitionEndFollow({
type: "scroll",
isAtEnd: listState.isAtEnd,
userScrollSessionActive: userScrollSessionRef.current,
});
if (listState.isWithinMaintainScrollAtEndThreshold) {
setEndFollow(true);
} else if (userScrollSessionRef.current) {
setEndFollow(false);
}
}
},
[reportHeaderMaterialVisibility, anchorTopInset, props.listRef, transitionEndFollow],
[reportHeaderMaterialVisibility, anchorTopInset, props.listRef, setEndFollow],
);
const clearUserScrollSettle = useCallback(() => {
if (userScrollSettleTimerRef.current !== null) {
clearTimeout(userScrollSettleTimerRef.current);
userScrollSettleTimerRef.current = null;
const handleScrollBeginDrag = useCallback(() => {
userScrollSessionRef.current = true;
}, []);
// The session must survive past finger-lift so momentum that carries the
// user away from the end still breaks follow; a drag released with no
// momentum ends its session at the release itself, otherwise at momentum
// end. Leaving a session open would let a later animated maintain-scroll
// read as user motion and break follow spuriously.
const handleScrollEndDrag = useCallback((event: NativeSyntheticEvent<NativeScrollEvent>) => {
const velocity = event.nativeEvent.velocity?.y ?? 0;
if (Math.abs(velocity) < 0.05) {
userScrollSessionRef.current = false;
}
}, []);
const handleScrollBeginDrag = useCallback(() => {
clearUserScrollSettle();
userScrollSessionRef.current = true;
// Pause before the first scroll event. Otherwise a stream update can run
// maintainScrollAtEnd between touch-down and the drag leaving its threshold.
transitionEndFollow({ type: "user-scroll-begin" });
}, [clearUserScrollSettle, transitionEndFollow]);
const finishUserScroll = useCallback(
(releaseIsAtEnd?: boolean) => {
clearUserScrollSettle();
const userScrollSessionActive = userScrollSessionRef.current;
userScrollSessionRef.current = false;
transitionEndFollow({
type: "user-scroll-end",
// With no momentum, preserve the finger-release position. Streaming
// growth during the native momentum-detection window must not turn a
// release at the live edge into an opt-out from follow.
isAtEnd: releaseIsAtEnd ?? props.listRef.current?.getState().isAtEnd ?? false,
userScrollSessionActive,
});
},
[clearUserScrollSettle, props.listRef, transitionEndFollow],
);
// Finger-lift velocity is not a reliable momentum signal: a gentle fling
// can report zero and still decelerate. Give native momentum a short window
// to announce itself; if it does, onMomentumScrollBegin cancels this fallback
// and the session survives until the settled momentum-end position. This
// mirrors the native-event handoff used by the home thread list's scroll gate.
const handleScrollEndDrag = useCallback(() => {
clearUserScrollSettle();
const releaseIsAtEnd = props.listRef.current?.getState().isAtEnd ?? false;
userScrollSettleTimerRef.current = setTimeout(() => finishUserScroll(releaseIsAtEnd), 160);
}, [clearUserScrollSettle, finishUserScroll, props.listRef]);
const handleMomentumScrollBegin = useCallback(() => {
if (userScrollSessionRef.current) {
clearUserScrollSettle();
}
}, [clearUserScrollSettle]);
const handleMomentumScrollEnd = useCallback(() => {
finishUserScroll();
}, [finishUserScroll]);
useEffect(() => clearUserScrollSettle, [clearUserScrollSettle]);
userScrollSessionRef.current = false;
}, []);
const handleViewportLayout = useCallback((event: LayoutChangeEvent) => {
const nextWidth = Math.round(event.nativeEvent.layout.width);
@@ -1555,30 +1502,23 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
setViewportHeight((current) => (Math.abs(current - nextHeight) > 1 ? nextHeight : current));
}, []);
// Thread identity is env-scoped: two environments can hold the same
// ThreadId, and keying resets (or the list mount) on the bare id would
// carry stale scroll/follow state across an environment switch.
const feedThreadKey = scopedThreadKey(props.environmentId, props.threadId);
useEffect(() => {
reportHeaderMaterialVisibility(false);
}, [feedThreadKey, reportHeaderMaterialVisibility]);
}, [props.threadId, reportHeaderMaterialVisibility]);
// A thread switch opens pinned to the end; a send explicitly returns to the
// live edge (ThreadDetailScreen scrolls the new message into place). Both
// re-arm follow regardless of where the user had scrolled before.
useEffect(() => {
clearUserScrollSettle();
userScrollSessionRef.current = false;
transitionEndFollow({ type: "reset" });
}, [clearUserScrollSettle, feedThreadKey, transitionEndFollow]);
setEndFollow(true);
}, [props.threadId, setEndFollow]);
useEffect(() => {
if (props.anchorMessageId !== null) {
clearUserScrollSettle();
userScrollSessionRef.current = false;
transitionEndFollow({ type: "reset" });
setEndFollow(true);
}
}, [clearUserScrollSettle, props.anchorMessageId, transitionEndFollow]);
}, [props.anchorMessageId, setEndFollow]);
const expandedWorkGroupIds = useMemo(() => {
const ids = new Set<string>();
@@ -1614,7 +1554,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
// initial scroll-to-end computes with a zero end inset and rests one
// composer-height short of the end. Layout effect: it must land before the
// list's first positioning tick or the one-shot initial scroll misses it.
const listMountKey = `${feedThreadKey}:${props.feed.length === 0 ? "empty" : "filled"}`;
const listMountKey = `${props.threadId}:${props.feed.length === 0 ? "empty" : "filled"}`;
useLayoutEffect(() => {
const bottom = props.contentInsetEndAdjustment.value;
if (bottom > 0) {
@@ -1981,7 +1921,6 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
onScroll={handleScroll}
onScrollBeginDrag={handleScrollBeginDrag}
onScrollEndDrag={handleScrollEndDrag}
onMomentumScrollBegin={handleMomentumScrollBegin}
onMomentumScrollEnd={handleMomentumScrollEnd}
scrollEventThrottle={16}
ListHeaderComponent={
@@ -211,7 +211,6 @@ function ThreadNavigationSidebarPane(
pinThread,
unpinThread,
movePinnedThread,
regenerateThreadTitle,
} = useThreadListActions();
const threadListV2Enabled = useThreadListV2Enabled();
const pendingTasks = usePendingNewTasks();
@@ -506,15 +505,6 @@ function ThreadNavigationSidebarPane(
}
return supported;
}, [serverConfigs]);
const titleRegenerationEnvironmentIds = useMemo(() => {
const supported = new Set<EnvironmentId>();
for (const [environmentId, config] of serverConfigs) {
if (config.environment.capabilities.threadTitleRegeneration === true) {
supported.add(environmentId);
}
}
return supported;
}, [serverConfigs]);
// Canonical arranged pinned order for Move up/down flags — computed from
// all shells so search/scope filtering never disables a valid move.
const arrangedPinnedKeys = useMemo(() => {
@@ -960,8 +950,6 @@ function ThreadNavigationSidebarPane(
onSelectThread={handleSelectThread}
onDeleteThread={confirmDeleteThread}
onArchiveThread={archiveThread}
onRegenerateThreadTitle={regenerateThreadTitle}
titleRegenerationSupported={titleRegenerationEnvironmentIds.has(thread.environmentId)}
settlementSupported={settlementEnvironmentIds.has(thread.environmentId)}
onSettleThread={settleThread}
snoozeSupported={snoozeEnvironmentIds.has(thread.environmentId)}
@@ -1079,8 +1067,6 @@ function ThreadNavigationSidebarPane(
fullSwipeWidth={props.width - 20}
onArchiveThread={archiveThread}
onDeleteThread={confirmDeleteThread}
onRegenerateThreadTitle={regenerateThreadTitle}
titleRegenerationSupported={titleRegenerationEnvironmentIds.has(thread.environmentId)}
onSelectThread={handleSelectThread}
onSwipeableClose={handleSwipeableClose}
onSwipeableWillOpen={handleSwipeableWillOpen}
@@ -1117,7 +1103,6 @@ function ThreadNavigationSidebarPane(
projectByKey,
projectCwdByKey,
projectTitleByProjectKey,
regenerateThreadTitle,
props.onNewThreadInProject,
props.searchQuery,
props.selectedThreadKey,
@@ -1125,7 +1110,6 @@ function ThreadNavigationSidebarPane(
savedConnectionsById,
serverConfigs,
threadSearchMatchByKey,
titleRegenerationEnvironmentIds,
settleThread,
settlementEnvironmentIds,
showMoreSettled,
@@ -56,6 +56,8 @@ import {
useThreadGitRightHeaderItems,
} from "./ThreadGitControls";
import { GitOverviewSheet } from "./git/GitOverviewSheet";
import { appAtomRegistry } from "../../state/atom-registry";
import { environmentServerConfigsAtom } from "../../state/server";
import { useAtomCommand } from "../../state/use-atom-command";
import { useSelectedThreadGitActions } from "../../state/use-selected-thread-git-actions";
import { useSelectedThreadGitState } from "../../state/use-selected-thread-git-state";
@@ -214,6 +216,28 @@ function ThreadRouteContent(
const gitActions = useSelectedThreadGitActions();
const requests = useSelectedThreadRequests();
const interruptThreadTurn = useAtomCommand(threadEnvironment.interruptTurn, "thread interrupt");
const visitThreadMutation = useAtomCommand(threadEnvironment.visit, { reportFailure: false });
// Server-synced "seen it" acknowledgement, mirroring web's ChatView: having
// the finished thread open stamps a visit at the turn's completedAt so the
// unread cue clears on every device, not just this one. Guarded on the
// shell's synced value so the echo of our own visit does not re-dispatch;
// the decider is monotonic, so a raced older visit is a server-side no-op.
// Version skew: never send thread.visit to a server that predates it.
useEffect(() => {
if (selectedThread === null) return;
const supportsThreadVisits =
appAtomRegistry.get(environmentServerConfigsAtom).get(selectedThread.environmentId)
?.environment.capabilities.threadVisits === true;
if (!supportsThreadVisits) return;
const completedAt = selectedThread.latestTurn?.completedAt;
if (!completedAt) return;
const syncedVisitedAt = selectedThread.lastVisitedAt;
if (syncedVisitedAt != null && Date.parse(syncedVisitedAt) >= Date.parse(completedAt)) return;
void visitThreadMutation({
environmentId: selectedThread.environmentId,
input: { threadId: selectedThread.id, visitedAt: completedAt },
});
}, [selectedThread, visitThreadMutation]);
const navigation = useNavigation();
const params = props.route.params;
const environmentIdRaw = firstRouteParam(params.environmentId);
@@ -30,7 +30,6 @@ import { cn } from "../../lib/cn";
import type { ModelOption, ProviderGroup } from "../../lib/modelOptions";
import { applyProviderOptionSelection, providerOptionValueLabels } from "../../lib/providerOptions";
import { useThemeColor } from "../../lib/useThemeColor";
import { RUNTIME_MODE_CHOICES, selectableChoices } from "./thread-settings-menu";
import { pendingModelAfterPress } from "./thread-settings-sheet-state";
import type { ThreadSettingsSheetCloseReason } from "./use-thread-settings-sheet-presentation";
@@ -41,6 +40,26 @@ import type { ThreadSettingsSheetCloseReason } from "./use-thread-settings-sheet
*/
const PRIMARY_PROVIDER_DRIVERS: ReadonlySet<string> = new Set(["claudeAgent", "codex"]);
/**
* Desktop-oriented effort keywords that don't belong in the phone picker.
* Prompt-injected values (ultrathink and friends) are filtered from the
* descriptor metadata; ultracode is a real option but a workflow trigger, not
* a reasoning level. A value set elsewhere still displays, it just isn't
* offered.
*/
const HIDDEN_EFFORT_OPTION_IDS: ReadonlySet<string> = new Set(["ultracode"]);
const RUNTIME_MODE_CHOICES: ReadonlyArray<{
readonly mode: RuntimeMode;
readonly label: string;
readonly shortLabel: string;
}> = [
{ mode: "approval-required", label: "Approve actions", shortLabel: "Approve" },
{ mode: "auto-accept-edits", label: "Auto-accept edits", shortLabel: "Edits" },
{ mode: "auto", label: "Auto", shortLabel: "Auto" },
{ mode: "full-access", label: "Full access", shortLabel: "Full" },
];
/**
* Compact "Fable 5 · Max · Auto" style summary for the composer trigger pill,
* covering model, provider options, runtime mode, and plan mode in one label.
@@ -60,6 +79,13 @@ export function threadSettingsSummaryLabel(input: {
].join(" · ");
}
function selectableChoices(descriptor: Extract<ProviderOptionDescriptor, { type: "select" }>) {
const injected = new Set(descriptor.promptInjectedValues ?? []);
return descriptor.options.filter(
(option) => !injected.has(option.id) && !HIDDEN_EFFORT_OPTION_IDS.has(option.id),
);
}
function ModelRow(props: {
readonly option: ModelOption;
readonly selected: boolean;
@@ -1,38 +0,0 @@
import { describe, expect, it } from "vite-plus/test";
import { derivePendingUserInputMaxHeight } from "./pendingUserInputLayout";
describe("derivePendingUserInputMaxHeight", () => {
it("caps a tall portrait viewport", () => {
expect(
derivePendingUserInputMaxHeight({
windowHeight: 932,
keyboardHeight: 0,
navigationHeaderHeight: 103,
composerOverlapHeight: 94,
}),
).toBe(560);
});
it("subtracts the keyboard while editing a custom answer", () => {
expect(
derivePendingUserInputMaxHeight({
windowHeight: 932,
keyboardHeight: 336,
navigationHeaderHeight: 103,
composerOverlapHeight: 94,
}),
).toBe(387);
});
it("keeps the fixed action area usable in a short keyboard-open viewport", () => {
expect(
derivePendingUserInputMaxHeight({
windowHeight: 375,
keyboardHeight: 240,
navigationHeaderHeight: 44,
composerOverlapHeight: 94,
}),
).toBe(160);
});
});
@@ -1,37 +0,0 @@
const PENDING_USER_INPUT_MAX_HEIGHT = 560;
const PENDING_USER_INPUT_MIN_HEIGHT = 160;
const PENDING_USER_INPUT_VERTICAL_GAP = 12;
/**
* Reserve for a portrait iPhone keyboard with the QuickType bar until a real
* height has been observed. Overestimating only costs card height; an
* underestimate would let the card overshoot on the first keyboard open.
*/
export const ESTIMATED_KEYBOARD_HEIGHT = 336;
/**
* One clock for the questionnaire expand/collapse choreography: the card's
* enter/exit and the feed-inset glide must share it or they visibly drift.
* Sized for the near-full-height slide (the card travels its own height),
* in the same class as the iOS keyboard's ~250ms.
*/
export const USER_INPUT_TOGGLE_DURATION_MS = 220;
export function derivePendingUserInputMaxHeight(input: {
readonly windowHeight: number;
readonly keyboardHeight: number;
readonly navigationHeaderHeight: number;
readonly composerOverlapHeight: number;
}): number {
const availableHeight =
input.windowHeight -
Math.max(0, input.keyboardHeight) -
Math.max(0, input.navigationHeaderHeight) -
Math.max(0, input.composerOverlapHeight) -
PENDING_USER_INPUT_VERTICAL_GAP;
return Math.min(
PENDING_USER_INPUT_MAX_HEIGHT,
Math.max(PENDING_USER_INPUT_MIN_HEIGHT, availableHeight),
);
}
@@ -1,70 +0,0 @@
import { describe, expect, it } from "vite-plus/test";
import { resolveThreadFeedLiveFollow } from "./thread-feed-live-follow";
describe("resolveThreadFeedLiveFollow", () => {
it("pauses immediately when the user starts scrolling", () => {
expect(resolveThreadFeedLiveFollow(true, { type: "user-scroll-begin" })).toBe(false);
});
it("stays paused away from the actual end", () => {
expect(
resolveThreadFeedLiveFollow(false, {
type: "scroll",
isAtEnd: false,
userScrollSessionActive: true,
}),
).toBe(false);
});
it("does not mistake programmatic layout compensation for a user scroll", () => {
expect(
resolveThreadFeedLiveFollow(true, {
type: "scroll",
isAtEnd: false,
userScrollSessionActive: false,
}),
).toBe(true);
});
it("does not re-arm at the end while a user scroll session is active", () => {
expect(
resolveThreadFeedLiveFollow(false, {
type: "scroll",
isAtEnd: true,
userScrollSessionActive: true,
}),
).toBe(false);
});
it("re-arms at the actual end only after the user scroll session ends", () => {
expect(
resolveThreadFeedLiveFollow(false, {
type: "user-scroll-end",
isAtEnd: true,
userScrollSessionActive: true,
}),
).toBe(true);
expect(
resolveThreadFeedLiveFollow(false, {
type: "user-scroll-end",
isAtEnd: false,
userScrollSessionActive: true,
}),
).toBe(false);
});
it("ignores momentum-end events from programmatic scrolling", () => {
expect(
resolveThreadFeedLiveFollow(true, {
type: "user-scroll-end",
isAtEnd: false,
userScrollSessionActive: false,
}),
).toBe(true);
});
it("re-arms after an explicit reset", () => {
expect(resolveThreadFeedLiveFollow(false, { type: "reset" })).toBe(true);
});
});
@@ -1,35 +0,0 @@
export type ThreadFeedLiveFollowEvent =
| { readonly type: "reset" }
| { readonly type: "user-scroll-begin" }
| {
readonly type: "user-scroll-end";
readonly isAtEnd: boolean;
readonly userScrollSessionActive: boolean;
}
| {
readonly type: "scroll";
readonly isAtEnd: boolean;
readonly userScrollSessionActive: boolean;
};
export function resolveThreadFeedLiveFollow(
current: boolean,
event: ThreadFeedLiveFollowEvent,
): boolean {
switch (event.type) {
case "reset":
return true;
case "user-scroll-begin":
return false;
case "user-scroll-end":
return event.userScrollSessionActive ? event.isAtEnd : current;
case "scroll":
if (event.userScrollSessionActive) {
return false;
}
if (event.isAtEnd) {
return true;
}
return current;
}
}
@@ -22,7 +22,6 @@ import type { PendingNewTask } from "../../state/use-pending-new-tasks";
import { useThreadPr, type ThreadPr } from "../../state/use-thread-pr";
import type { HomeGroupDisplayAction } from "../home/homeListItems";
import { ThreadSwipeable } from "../home/thread-swipe-actions";
import { buildThreadTitleRegenerationMenuItems } from "./thread-title-regeneration-menu";
import { resolveThreadStatus } from "./threadPresentation";
import { ThreadSearchMatchExcerpt } from "./thread-search-match";
@@ -431,8 +430,6 @@ export const ThreadListRow = memo(function ThreadListRow(props: {
readonly onSelectThread: (thread: EnvironmentThreadShell) => void;
readonly onArchiveThread: (thread: EnvironmentThreadShell) => void;
readonly onDeleteThread: (thread: EnvironmentThreadShell) => void;
readonly onRegenerateThreadTitle: (thread: EnvironmentThreadShell) => void;
readonly titleRegenerationSupported: boolean;
readonly onSwipeableWillOpen: (methods: SwipeableMethods) => void;
readonly onSwipeableClose: (methods: SwipeableMethods) => void;
readonly simultaneousSwipeGesture?: ComponentProps<
@@ -454,8 +451,7 @@ export const ThreadListRow = memo(function ThreadListRow(props: {
const pressedBackgroundColor = useThemeColor("--color-subtle");
const selectedBackgroundColor = useThemeColor("--color-user-bubble");
const { thread, onSelectThread, onArchiveThread, onDeleteThread, onRegenerateThreadTitle } =
props;
const { thread, onSelectThread, onArchiveThread, onDeleteThread } = props;
const status = resolveThreadStatus(thread);
const pr = useThreadPr(thread, props.projectCwd);
const timestamp = relativeTime(
@@ -475,21 +471,6 @@ export const ThreadListRow = memo(function ThreadListRow(props: {
const handleDelete = useCallback(() => onDeleteThread(thread), [onDeleteThread, thread]);
const handleArchive = useCallback(() => onArchiveThread(thread), [onArchiveThread, thread]);
const handleRegenerateTitle = useCallback(
() => onRegenerateThreadTitle(thread),
[onRegenerateThreadTitle, thread],
);
const menuActions = useMemo<MenuAction[]>(
() => [
THREAD_ROW_MENU_ACTIONS[0]!,
...buildThreadTitleRegenerationMenuItems({
supported: props.titleRegenerationSupported,
isRegenerating: thread.titleRegeneration != null,
}),
THREAD_ROW_MENU_ACTIONS[1]!,
],
[props.titleRegenerationSupported, thread.titleRegeneration],
);
const primaryAction = useMemo(
() => ({
accessibilityLabel: `Archive ${thread.title}`,
@@ -502,10 +483,9 @@ export const ThreadListRow = memo(function ThreadListRow(props: {
const handleMenuAction = useCallback(
({ nativeEvent }: { readonly nativeEvent: { readonly event: string } }) => {
if (nativeEvent.event === "archive") handleArchive();
if (nativeEvent.event === "regenerate-title") handleRegenerateTitle();
if (nativeEvent.event === "delete") handleDelete();
},
[handleArchive, handleDelete, handleRegenerateTitle],
[handleArchive, handleDelete],
);
const statusPill = effectiveStatus ? (
@@ -694,7 +674,7 @@ export const ThreadListRow = memo(function ThreadListRow(props: {
// ControlPillMenu injects onLongPress into the row and anchors the
// token-styled dropdown to it; taps and swipes are untouched.
<ControlPillMenu
actions={menuActions}
actions={THREAD_ROW_MENU_ACTIONS}
onPressAction={handleMenuAction}
shouldOpenOnLongPress
>
@@ -27,7 +27,6 @@ import { useThemeColor } from "../../lib/useThemeColor";
import type { PendingNewTask } from "../../state/use-pending-new-tasks";
import { useThreadPr } from "../../state/use-thread-pr";
import { ThreadSwipeable } from "../home/thread-swipe-actions";
import { buildThreadTitleRegenerationMenuItems } from "./thread-title-regeneration-menu";
import {
resolveThreadListV2SnoozeMenuSelection,
resolveThreadListV2SnoozeGateExpiryMs,
@@ -66,8 +65,8 @@ function threadTimeLabel(thread: EnvironmentThreadShell): string {
return relativeTime(thread.latestUserMessageAt ?? thread.updatedAt ?? thread.createdAt);
}
// Menus keep lifecycle and title regeneration together. Archive keeps its
// own surface (thread screen / settings) rather than crowding v2 rows.
// Menus stay lifecycle-focused: settle/un-settle plus delete. Archive keeps
// its own surface (thread screen / settings) rather than crowding the row.
const CARD_MENU_ACTIONS: MenuAction[] = [
{ id: "settle", title: "Settle", image: "checkmark" },
{ id: "delete", title: "Delete", image: "trash", attributes: { destructive: true } },
@@ -342,7 +341,6 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
readonly fullSwipeWidth?: number;
readonly onSelectThread: (thread: EnvironmentThreadShell) => void;
readonly onDeleteThread: (thread: EnvironmentThreadShell) => void;
readonly onRegenerateThreadTitle: (thread: EnvironmentThreadShell) => void;
readonly onSettleThread: (thread: EnvironmentThreadShell) => void;
readonly onSnoozeThread: (thread: EnvironmentThreadShell, snoozedUntil: string) => void;
readonly onUnsnoozeThread: (thread: EnvironmentThreadShell) => void;
@@ -357,8 +355,6 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
readonly snoozeSupported: boolean;
/** False on servers that predate thread.pin/unpin. */
readonly pinningSupported: boolean;
/** False on servers that predate thread title regeneration. */
readonly titleRegenerationSupported: boolean;
/** False on servers that predate thread.pin.reorder. Gates the pinned
Move up / Move down menu items. */
readonly pinReorderSupported?: boolean;
@@ -388,7 +384,6 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
variant,
onSelectThread,
onDeleteThread,
onRegenerateThreadTitle,
onSettleThread,
onSnoozeThread,
onUnsnoozeThread,
@@ -422,10 +417,6 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
const timeLabel = threadTimeLabel(thread);
const handleDelete = useCallback(() => onDeleteThread(thread), [onDeleteThread, thread]);
const handleRegenerateTitle = useCallback(
() => onRegenerateThreadTitle(thread),
[onRegenerateThreadTitle, thread],
);
const handleSettle = useCallback(() => onSettleThread(thread), [onSettleThread, thread]);
const handleSnooze = useCallback(
(snoozedUntil: string) => onSnoozeThread(thread, snoozedUntil),
@@ -515,14 +506,6 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
props.pinningSupported,
],
);
const titleRegenerationMenuItems = useMemo<MenuAction[]>(
() =>
buildThreadTitleRegenerationMenuItems({
supported: props.titleRegenerationSupported,
isRegenerating: thread.titleRegeneration != null,
}),
[props.titleRegenerationSupported, thread.titleRegeneration],
);
const snoozableCardMenuActions = useMemo<MenuAction[]>(
() => [
{ id: "settle", title: "Settle", image: "checkmark" },
@@ -533,31 +516,13 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
subactions: snoozePresetActions,
},
...pinMenuItem,
...titleRegenerationMenuItems,
{ id: "delete", title: "Delete", image: "trash", attributes: { destructive: true } },
],
[pinMenuItem, snoozePresetActions, titleRegenerationMenuItems],
[pinMenuItem, snoozePresetActions],
);
const cardMenuActions = useMemo<MenuAction[]>(
() => [
CARD_MENU_ACTIONS[0]!,
...pinMenuItem,
...titleRegenerationMenuItems,
...CARD_MENU_ACTIONS.slice(1),
],
[pinMenuItem, titleRegenerationMenuItems],
);
const slimMenuActions = useMemo<MenuAction[]>(
() => [SLIM_MENU_ACTIONS[0]!, ...titleRegenerationMenuItems, SLIM_MENU_ACTIONS[1]!],
[titleRegenerationMenuItems],
);
const snoozedMenuActions = useMemo<MenuAction[]>(
() => [SNOOZED_MENU_ACTIONS[0]!, ...titleRegenerationMenuItems, SNOOZED_MENU_ACTIONS[1]!],
[titleRegenerationMenuItems],
);
const legacyMenuActions = useMemo<MenuAction[]>(
() => [LEGACY_MENU_ACTIONS[0]!, ...titleRegenerationMenuItems, LEGACY_MENU_ACTIONS[1]!],
[titleRegenerationMenuItems],
() => [CARD_MENU_ACTIONS[0]!, ...pinMenuItem, ...CARD_MENU_ACTIONS.slice(1)],
[pinMenuItem],
);
const handleMenuAction = useCallback(
({ nativeEvent }: { readonly nativeEvent: { readonly event: string } }) => {
@@ -569,7 +534,6 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
if (nativeEvent.event === "move-pin-up") handleMovePinnedUp();
if (nativeEvent.event === "move-pin-down") handleMovePinnedDown();
if (nativeEvent.event === "archive") handleArchive();
if (nativeEvent.event === "regenerate-title") handleRegenerateTitle();
if (nativeEvent.event === "delete") handleDelete();
const snoozeSelection = resolveThreadListV2SnoozeMenuSelection({
event: nativeEvent.event,
@@ -585,7 +549,6 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
[
handleArchive,
handleDelete,
handleRegenerateTitle,
handleMovePinnedDown,
handleMovePinnedUp,
handlePin,
@@ -927,11 +890,11 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
<ControlPillMenu
actions={
snoozedRow
? snoozedMenuActions
? SNOOZED_MENU_ACTIONS
: !props.settlementSupported
? legacyMenuActions
? LEGACY_MENU_ACTIONS
: canUnsettle
? slimMenuActions
? SLIM_MENU_ACTIONS
: swipeActions.secondary === "snooze"
? snoozableCardMenuActions
: cardMenuActions
@@ -1,284 +0,0 @@
import { describe, expect, it } from "vite-plus/test";
import { ProviderInstanceId, type ProviderOptionDescriptor } from "@t3tools/contracts";
import type { ModelOption, ProviderGroup } from "../../lib/modelOptions";
import { buildThreadSettingsMenu, type ThreadSettingsMenuEvent } from "./thread-settings-menu";
function modelOption(
model: string,
overrides: Partial<Pick<ModelOption, "isDefault" | "isLegacy" | "providerKey">> = {},
): ModelOption {
const providerKey = overrides.providerKey ?? "codex";
return {
key: `${providerKey}:${model}`,
label: model,
subtitle: providerKey,
providerKey,
providerLabel: providerKey === "codex" ? "Codex" : "Claude",
providerDriver: providerKey === "codex" ? "codex" : "claudeAgent",
isDefault: overrides.isDefault ?? false,
isLegacy: overrides.isLegacy ?? false,
capabilities: null,
selection: {
instanceId: ProviderInstanceId.make(providerKey),
model,
options: [],
},
};
}
function group(models: ReadonlyArray<ModelOption>): ProviderGroup {
const first = models[0];
if (!first) {
throw new Error("group requires at least one model");
}
return {
providerKey: first.providerKey,
providerLabel: first.providerLabel,
models,
};
}
const effortDescriptor: ProviderOptionDescriptor = {
id: "effort",
label: "Reasoning",
type: "select",
options: [
{ id: "low", label: "Low" },
{ id: "medium", label: "Medium", isDefault: true },
{ id: "high", label: "High" },
{ id: "ultrathink", label: "Ultrathink" },
{ id: "ultracode", label: "Ultracode" },
],
currentValue: "high",
promptInjectedValues: ["ultrathink"],
};
const fastModeDescriptor: ProviderOptionDescriptor = {
id: "fastMode",
label: "Fast mode",
type: "boolean",
currentValue: false,
};
function baseInput() {
const models = [
modelOption("gpt-current", { isDefault: true }),
modelOption("gpt-next"),
modelOption("gpt-old", { isLegacy: true }),
];
return {
providerGroups: [group(models)],
selectedModel: models[0]?.selection ?? null,
optionDescriptors: [effortDescriptor, fastModeDescriptor],
runtimeMode: "auto",
} as const;
}
function eventFor(menu: ReturnType<typeof buildThreadSettingsMenu>, id: string | undefined) {
return id === undefined ? undefined : menu.events.get(id);
}
describe("buildThreadSettingsMenu", () => {
it("orders the top level as model, options, runtime", () => {
const menu = buildThreadSettingsMenu(baseInput());
expect(menu.actions.map((action) => action.title)).toEqual([
"Model",
"Reasoning",
"Fast mode",
"Runtime",
]);
});
it("summarizes the current choice on each submenu row", () => {
const menu = buildThreadSettingsMenu(baseInput());
expect(menu.actions.find((action) => action.title === "Model")?.subtitle).toBe("gpt-current");
expect(menu.actions.find((action) => action.title === "Reasoning")?.subtitle).toBe("High");
expect(menu.actions.find((action) => action.title === "Runtime")?.subtitle).toBe("Auto");
});
it("checkmarks the selected model and resolves selection events", () => {
const menu = buildThreadSettingsMenu(baseInput());
const modelItems = menu.actions.find((action) => action.title === "Model")?.subactions ?? [];
const current = modelItems.find((action) => action.title === "gpt-current");
expect(current?.state).toBe("on");
expect(current?.subtitle).toBe("Default");
expect(modelItems.find((action) => action.title === "gpt-next")?.state).toBe("off");
const event = eventFor(menu, modelItems.find((action) => action.title === "gpt-next")?.id);
expect(event?.type).toBe("select-model");
expect(event?.type === "select-model" ? event.option.selection.model : null).toBe("gpt-next");
});
it("folds unselected legacy models behind a nested submenu", () => {
const menu = buildThreadSettingsMenu(baseInput());
const modelItems = menu.actions.find((action) => action.title === "Model")?.subactions ?? [];
expect(modelItems.map((action) => action.title)).toEqual([
"gpt-current",
"gpt-next",
"Legacy Models",
]);
expect(
modelItems
.find((action) => action.title === "Legacy Models")
?.subactions?.map((action) => action.title),
).toEqual(["gpt-old"]);
});
it("keeps a selected legacy model in the main list", () => {
const input = baseInput();
const legacy = input.providerGroups[0]?.models.find((model) => model.isLegacy);
const menu = buildThreadSettingsMenu({
...input,
selectedModel: legacy?.selection ?? null,
});
const modelItems = menu.actions.find((action) => action.title === "Model")?.subactions ?? [];
expect(modelItems.map((action) => action.title)).toEqual([
"gpt-current",
"gpt-next",
"gpt-old",
]);
expect(modelItems.find((action) => action.title === "gpt-old")?.state).toBe("on");
});
it("hides prompt-injected and workflow-trigger efforts but still summarizes them", () => {
const menu = buildThreadSettingsMenu({
...baseInput(),
optionDescriptors: [{ ...effortDescriptor, currentValue: "ultracode" }],
});
const reasoning = menu.actions.find((action) => action.title === "Reasoning");
expect(reasoning?.subactions?.map((action) => action.title)).toEqual(["Low", "Medium", "High"]);
// The hidden value stays visible as the current summary; it just can't be
// picked from the phone.
expect(reasoning?.subtitle).toBe("Ultracode");
expect(reasoning?.subactions?.every((action) => action.state === "off")).toBe(true);
});
it("resolves select-option and runtime events with checkmarked current values", () => {
const menu = buildThreadSettingsMenu(baseInput());
const reasoningItems =
menu.actions.find((action) => action.title === "Reasoning")?.subactions ?? [];
expect(reasoningItems.find((action) => action.title === "High")?.state).toBe("on");
expect(eventFor(menu, reasoningItems.find((action) => action.title === "Low")?.id)).toEqual({
type: "set-option",
optionId: "effort",
value: "low",
});
const runtimeItems =
menu.actions.find((action) => action.title === "Runtime")?.subactions ?? [];
expect(runtimeItems.find((action) => action.title === "Auto")?.state).toBe("on");
expect(
eventFor(menu, runtimeItems.find((action) => action.title === "Full access")?.id),
).toEqual({ type: "set-runtime", mode: "full-access" });
});
it("toggles boolean options with the inverted current value", () => {
const menu = buildThreadSettingsMenu(baseInput());
const fastMode = menu.actions.find((action) => action.title === "Fast mode");
expect(fastMode?.state).toBe("off");
expect(fastMode?.subactions).toBeUndefined();
expect(eventFor(menu, fastMode?.id)).toEqual({
type: "set-option",
optionId: "fastMode",
value: true,
});
const enabled = buildThreadSettingsMenu({
...baseInput(),
optionDescriptors: [{ ...fastModeDescriptor, currentValue: true }],
});
const enabledRow = enabled.actions.find((action) => action.title === "Fast mode");
expect(enabledRow?.state).toBe("on");
expect(eventFor(enabled, enabledRow?.id)).toEqual({
type: "set-option",
optionId: "fastMode",
value: false,
});
});
it("keeps the menu presented only for top-level toggles", () => {
const menu = buildThreadSettingsMenu(baseInput());
// Root-level boolean toggles refresh in place with clean chrome, so they
// keep the menu presented.
expect(
menu.actions.find((action) => action.title === "Fast mode")?.attributes?.keepsMenuPresented,
).toBe(true);
// Picks inside nested submenus close the menu: staying presented leaves
// the submenu on screen with an expanded-submenu header, and the
// bottom-anchored collapse back out drops by the levels' height delta.
const expected = undefined;
const modelItems = menu.actions.find((action) => action.title === "Model")?.subactions ?? [];
const reasoningItems =
menu.actions.find((action) => action.title === "Reasoning")?.subactions ?? [];
const runtimeItems =
menu.actions.find((action) => action.title === "Runtime")?.subactions ?? [];
const nestedPicks = [...modelItems, ...reasoningItems, ...runtimeItems].filter(
(action) => action.subactions === undefined,
);
expect(nestedPicks.length).toBeGreaterThan(0);
expect(nestedPicks.every((action) => action.attributes?.keepsMenuPresented === expected)).toBe(
true,
);
});
it("sections models by provider only when multiple groups are offered", () => {
const codexModels = [modelOption("gpt-current", { isDefault: true })];
const claudeModels = [modelOption("fable-5", { providerKey: "claude" })];
const menu = buildThreadSettingsMenu({
providerGroups: [group(codexModels), group(claudeModels)],
selectedModel: codexModels[0]?.selection ?? null,
optionDescriptors: [],
runtimeMode: "auto",
});
const modelItems = menu.actions.find((action) => action.title === "Model")?.subactions ?? [];
expect(
modelItems.map((action) => ({ title: action.title, inline: action.displayInline ?? false })),
).toEqual([
{ title: "Codex", inline: true },
{ title: "Claude", inline: true },
]);
const claudeSection = modelItems.find((action) => action.title === "Claude");
expect(claudeSection?.subactions?.map((action) => action.title)).toEqual(["fable-5"]);
});
const eventTypes = (menu: ReturnType<typeof buildThreadSettingsMenu>) => {
const types = new Set<ThreadSettingsMenuEvent["type"]>();
for (const event of menu.events.values()) {
types.add(event.type);
}
return types;
};
it("registers an event for every leaf action id", () => {
const menu = buildThreadSettingsMenu(baseInput());
const leafIds: string[] = [];
const collect = (items: ReadonlyArray<{ id?: string; subactions?: unknown[] }>) => {
for (const item of items) {
if (Array.isArray(item.subactions) && item.subactions.length > 0) {
collect(item.subactions as ReadonlyArray<{ id?: string; subactions?: unknown[] }>);
} else if (item.id !== undefined) {
leafIds.push(item.id);
}
}
};
collect(menu.actions);
for (const id of leafIds) {
expect(menu.events.get(id), `missing event for ${id}`).toBeDefined();
}
expect(eventTypes(menu)).toEqual(new Set(["select-model", "set-option", "set-runtime"]));
});
});
@@ -1,202 +0,0 @@
import type { MenuAction } from "@react-native-menu/menu";
import type { ModelSelection, ProviderOptionDescriptor, RuntimeMode } from "@t3tools/contracts";
import {
getProviderOptionCurrentLabel,
getProviderOptionCurrentValue,
} from "@t3tools/shared/model";
import type { ModelOption, ProviderGroup } from "../../lib/modelOptions";
/**
* Desktop-oriented effort keywords that don't belong in the phone picker.
* Prompt-injected values (ultrathink and friends) are filtered from the
* descriptor metadata; ultracode is a real option but a workflow trigger, not
* a reasoning level. A value set elsewhere still displays, it just isn't
* offered.
*/
export const HIDDEN_EFFORT_OPTION_IDS: ReadonlySet<string> = new Set(["ultracode"]);
export const RUNTIME_MODE_CHOICES: ReadonlyArray<{
readonly mode: RuntimeMode;
readonly label: string;
readonly shortLabel: string;
}> = [
{ mode: "approval-required", label: "Approve actions", shortLabel: "Approve" },
{ mode: "auto-accept-edits", label: "Auto-accept edits", shortLabel: "Edits" },
{ mode: "auto", label: "Auto", shortLabel: "Auto" },
{ mode: "full-access", label: "Full access", shortLabel: "Full" },
];
export function selectableChoices(
descriptor: Extract<ProviderOptionDescriptor, { type: "select" }>,
) {
const injected = new Set(descriptor.promptInjectedValues ?? []);
return descriptor.options.filter(
(option) => !injected.has(option.id) && !HIDDEN_EFFORT_OPTION_IDS.has(option.id),
);
}
export type ThreadSettingsMenuEvent =
| { readonly type: "select-model"; readonly option: ModelOption }
| { readonly type: "set-option"; readonly optionId: string; readonly value: string | boolean }
| { readonly type: "set-runtime"; readonly mode: RuntimeMode };
export type ThreadSettingsMenu = {
readonly actions: MenuAction[];
/** Menu action id → the change it applies, for the onPressAction dispatch. */
readonly events: ReadonlyMap<string, ThreadSettingsMenuEvent>;
};
/**
* Native menu replacement for the thread settings sheet (model, select and
* boolean provider options, runtime mode). The menu presents from the
* composer pill without resigning the keyboard, so adjusting settings never
* bounces focus. A thread is bound to one harness, so the menu covers the
* sheet's full surface for existing threads; the sheet remains the Android
* and new-task-draft surface.
*
* Selections apply immediately — the sheet's stage-then-Save flow only exists
* because the sheet batches a model change with its option edits.
*/
export function buildThreadSettingsMenu(input: {
readonly providerGroups: ReadonlyArray<ProviderGroup>;
readonly selectedModel: ModelSelection | null;
readonly optionDescriptors: ReadonlyArray<ProviderOptionDescriptor>;
readonly runtimeMode: RuntimeMode;
}): ThreadSettingsMenu {
const events = new Map<string, ThreadSettingsMenuEvent>();
const actions: MenuAction[] = [];
const isSelected = (option: ModelOption) =>
option.selection.instanceId === input.selectedModel?.instanceId &&
option.selection.model === input.selectedModel.model;
// Only top-level leaves (boolean toggles) keep the menu presented (iOS
// 16+): the root refreshes in place with clean chrome. Picks inside nested
// submenus close the menu — keeping the submenu presented renders an
// expanded-submenu header with no way to pop back to the root, and the
// bottom-anchored collapse back out travels the levels' height difference.
const keepPresented = { keepsMenuPresented: true } as const;
const modelAction = (option: ModelOption, id: string): MenuAction => {
events.set(id, { type: "select-model", option });
return {
id,
title: option.label,
...(option.isDefault ? { subtitle: "Default" } : {}),
state: isSelected(option) ? "on" : "off",
};
};
const modelItems: MenuAction[] = [];
const legacyItems: MenuAction[] = [];
let selectedModelLabel: string | undefined;
input.providerGroups.forEach((group, groupIndex) => {
const groupItems: MenuAction[] = [];
group.models.forEach((option, modelIndex) => {
if (isSelected(option)) {
selectedModelLabel = option.label;
}
const id = `model:${groupIndex}:${modelIndex}`;
// A highlighted legacy model stays in the main list (mirroring the
// sheet) so the checkmark isn't hidden behind the Legacy fold.
if (option.isLegacy && !isSelected(option)) {
legacyItems.push(modelAction(option, id));
} else {
groupItems.push(modelAction(option, id));
}
});
if (groupItems.length === 0) {
return;
}
// A thread is bound to one harness, so provider sections only appear for
// multi-group callers (the new-task draft, if it ever adopts the menu).
if (input.providerGroups.length > 1) {
modelItems.push({
id: `model-group:${groupIndex}`,
title: group.providerLabel,
displayInline: true,
subactions: groupItems,
});
} else {
modelItems.push(...groupItems);
}
});
if (legacyItems.length > 0) {
modelItems.push({
id: "legacy-models",
title: "Legacy Models",
subactions: legacyItems,
});
}
if (modelItems.length > 0) {
actions.push({
id: "model",
title: "Model",
...(selectedModelLabel === undefined
? input.selectedModel
? { subtitle: input.selectedModel.model }
: {}
: { subtitle: selectedModelLabel }),
subactions: modelItems,
});
}
for (const descriptor of input.optionDescriptors) {
if (descriptor.type === "boolean") {
const id = `option:${descriptor.id}`;
events.set(id, {
type: "set-option",
optionId: descriptor.id,
value: !(descriptor.currentValue ?? false),
});
actions.push({
id,
title: descriptor.label,
state: descriptor.currentValue ? "on" : "off",
attributes: keepPresented,
});
continue;
}
const currentValue = getProviderOptionCurrentValue(descriptor);
const choices = selectableChoices(descriptor).map((choice): MenuAction => {
const id = `option:${descriptor.id}:${choice.id}`;
events.set(id, { type: "set-option", optionId: descriptor.id, value: choice.id });
return {
id,
title: choice.label,
state: choice.id === currentValue ? "on" : "off",
};
});
if (choices.length === 0) {
continue;
}
const currentLabel = getProviderOptionCurrentLabel(descriptor);
actions.push({
id: `option:${descriptor.id}`,
title: descriptor.label,
...(currentLabel === undefined ? {} : { subtitle: currentLabel }),
subactions: choices,
});
}
const runtimeLabel = RUNTIME_MODE_CHOICES.find(
(choice) => choice.mode === input.runtimeMode,
)?.label;
actions.push({
id: "runtime",
title: "Runtime",
...(runtimeLabel === undefined ? {} : { subtitle: runtimeLabel }),
subactions: RUNTIME_MODE_CHOICES.map((choice): MenuAction => {
const id = `runtime:${choice.mode}`;
events.set(id, { type: "set-runtime", mode: choice.mode });
return {
id,
title: choice.label,
state: choice.mode === input.runtimeMode ? "on" : "off",
};
}),
});
return { actions, events };
}
@@ -1,36 +0,0 @@
import { describe, expect, it } from "vite-plus/test";
import { buildThreadTitleRegenerationMenuItems } from "./thread-title-regeneration-menu";
describe("buildThreadTitleRegenerationMenuItems", () => {
it("hides regeneration when the environment does not advertise support", () => {
expect(
buildThreadTitleRegenerationMenuItems({ supported: false, isRegenerating: false }),
).toEqual([]);
});
it("offers regeneration for a supported environment", () => {
expect(
buildThreadTitleRegenerationMenuItems({ supported: true, isRegenerating: false }),
).toEqual([
{
id: "regenerate-title",
title: "Regenerate title",
image: "arrow.clockwise",
},
]);
});
it("shows and disables the pending state", () => {
expect(
buildThreadTitleRegenerationMenuItems({ supported: true, isRegenerating: true }),
).toEqual([
{
id: "regenerate-title",
title: "Regenerating…",
image: "arrow.clockwise",
attributes: { disabled: true },
},
]);
});
});
@@ -1,17 +0,0 @@
import type { MenuAction } from "@react-native-menu/menu";
export function buildThreadTitleRegenerationMenuItems(input: {
readonly supported: boolean;
readonly isRegenerating: boolean;
}): MenuAction[] {
if (!input.supported) return [];
return [
{
id: "regenerate-title",
title: input.isRegenerating ? "Regenerating…" : "Regenerate title",
image: "arrow.clockwise",
...(input.isRegenerating ? { attributes: { disabled: true } } : {}),
},
];
}
@@ -32,19 +32,6 @@ function makeUpdateClient(overrides: Partial<AppUpdateClient> = {}): AppUpdateCl
}
describe("runAppUpdateCheck", () => {
it("does nothing while running from the Metro development server", async () => {
vi.stubGlobal("__DEV__", true);
const client = makeUpdateClient();
try {
await runAppUpdateCheck({ client });
} finally {
vi.unstubAllGlobals();
}
expect(client.checkForUpdateAsync).not.toHaveBeenCalled();
});
it("downloads and restarts when a new update is available", async () => {
const client = makeUpdateClient({
checkForUpdateAsync: vi.fn(async () => ({
@@ -113,32 +100,6 @@ describe("runAppUpdateCheck", () => {
reportError.mockRestore();
});
it.each(["ERR_NOT_AVAILABLE_IN_DEV_CLIENT", "ERR_UPDATES_DISABLED"])(
"treats Expo's %s failure as an unavailable update check",
async (code) => {
const reportError = vi.spyOn(console, "error").mockImplementation(() => {});
const error = Object.assign(new Error("Updates are unavailable"), { code });
const client = makeUpdateClient({
checkForUpdateAsync: vi.fn(async () => {
throw error;
}),
});
const failures: string[] = [];
const states: AppUpdateCheckState[] = [];
await runAppUpdateCheck({
client,
onFailure: (message) => failures.push(message),
onStateChange: (state) => states.push(state),
});
expect(reportError).not.toHaveBeenCalled();
expect(failures).toEqual([]);
expect(states).toEqual(["checking", "idle"]);
reportError.mockRestore();
},
);
it("coalesces overlapping launch and manual checks", async () => {
let resolveCheck!: (result: {
readonly isAvailable: boolean;
@@ -48,17 +48,8 @@ interface Deferred {
}
const HIDDEN_UPDATE_TAP_COUNT = 5;
const UPDATE_CHECK_UNAVAILABLE_ERROR_CODES = new Set([
"ERR_NOT_AVAILABLE_IN_DEV_CLIENT",
"ERR_UPDATES_DISABLED",
]);
let appUpdateCheckInFlight: AppUpdateCheckInFlight | undefined;
/** Expo's development launcher reports updates as enabled even though its OTA APIs reject. */
export function isAppUpdateCheckAvailable(client: Pick<AppUpdateClient, "isEnabled"> = Updates) {
return client.isEnabled && !(typeof __DEV__ !== "undefined" && __DEV__);
}
/**
* Keeps the manual update affordance discoverable only to someone deliberately
* tapping the version row five times.
@@ -82,7 +73,7 @@ export function registerHiddenUpdateTap(count: number): {
export async function runAppUpdateCheck(options: AppUpdateCheckOptions = {}): Promise<void> {
const client = options.client ?? Updates;
if (!isAppUpdateCheckAvailable(client)) return;
if (!client.isEnabled) return;
if (appUpdateCheckInFlight) {
await observeAppUpdateCheck(appUpdateCheckInFlight, options);
@@ -216,27 +207,19 @@ function reportUpdateFailure(
fallback: string,
onFailure: AppUpdateCheckOptions["onFailure"],
): void {
reportAtomCommandResult(result, { label: "app update check" });
if (result._tag !== "Failure" || isAtomCommandInterrupted(result)) return;
const error = squashAtomCommandFailure(result);
if (isAppUpdateUnavailableError(error)) return;
reportAtomCommandResult(result, { label: "app update check" });
onFailure?.(error instanceof Error ? error.message : fallback);
}
function isAppUpdateUnavailableError(error: unknown): boolean {
if (typeof error !== "object" || error === null || !("code" in error)) return false;
const code = error.code;
return typeof code === "string" && UPDATE_CHECK_UNAVAILABLE_ERROR_CODES.has(code);
}
export function createAppUpdateLaunchCheck(
client: AppUpdateClient = Updates,
): () => Promise<void> | undefined {
let started = false;
return () => {
if (started || !isAppUpdateCheckAvailable(client)) return undefined;
if (started || !client.isEnabled) return undefined;
started = true;
return runAppUpdateCheck({ client });
};
@@ -1,11 +1,9 @@
import { useNavigation } from "@react-navigation/native";
import type { DailyTotals, MergedUsage } from "@t3tools/shared/usageMerge";
import type { MergedUsage } from "@t3tools/shared/usageMerge";
import {
enumerateDays,
enumerateHourStarts,
formatCount,
formatDayShort,
formatHourShort,
formatPercent,
formatTokens,
formatUsd,
@@ -25,7 +23,6 @@ import type { UsageChartMetric } from "./usageChartData";
import { PROVIDER_LABEL, useProviderColors } from "./usageProviders";
const WINDOW_OPTIONS = [
{ days: 1, label: "Past 24h" },
{ days: 7, label: "7 days" },
{ days: 30, label: "30 days" },
{ days: 90, label: "90 days" },
@@ -36,62 +33,23 @@ const CHART_HEIGHT = 180;
export function UsageRouteScreen() {
const navigation = useNavigation();
const insets = useSafeAreaInsets();
const [windowSelection, setWindowSelection] = useState(() => ({
days: 30,
window: makeWindow(30),
}));
const [windowDays, setWindowDays] = useState<number>(30);
const [metric, setMetric] = useState<UsageChartMetric>("cost");
const { days: windowDays, window } = windowSelection;
const isPast24Hours = windowDays === 1;
// Recomputed only when the window length changes, so a re-render does not
// shift the range and refetch every environment.
const window = useMemo(() => makeWindow(windowDays), [windowDays]);
const { merged, environments, isPending, isPartial, refresh } = useUsage(window);
const days = useMemo(
() => enumerateDays(window.sinceDay, window.untilDay),
[window.sinceDay, window.untilDay],
);
const chartDays = useMemo(
() =>
isPast24Hours && window.sinceTime !== undefined && window.untilTime !== undefined
? enumerateHourStarts(window.sinceTime, window.untilTime)
: days,
[days, isPast24Hours, window.sinceTime, window.untilTime],
);
const chartTotals = useMemo(
(): readonly DailyTotals[] =>
isPast24Hours
? merged.hourly.map((hour) => ({
day: hour.hourStart,
costUsd: hour.costUsd,
totalTokens: hour.totalTokens,
byProvider: hour.byProvider,
}))
: merged.daily,
[isPast24Hours, merged.daily, merged.hourly],
);
// The pull spinner tracks re-scans of environments that have answered
// before. The initial scan renders its own placeholder, and an unreachable
// environment stays pending forever — neither may pin the spinner on.
const refreshing = environments.some((entry) => entry.isPending && entry.summary !== null);
const selectWindow = (days: number) => {
setWindowSelection({
days,
window: makeWindow(days, undefined, days === 1 ? "hour" : "day"),
});
};
const refreshWindow = () => {
const nextWindow = makeWindow(windowDays, undefined, isPast24Hours ? "hour" : "day");
if (
nextWindow.sinceDay === window.sinceDay &&
nextWindow.untilDay === window.untilDay &&
nextWindow.sinceTime === window.sinceTime &&
nextWindow.untilTime === window.untilTime
) {
refresh();
} else {
setWindowSelection({ days: windowDays, window: nextWindow });
}
};
return (
<View collapsable={false} className="flex-1 bg-sheet">
@@ -107,12 +65,12 @@ export function UsageRouteScreen() {
className="flex-1"
contentContainerClassName="gap-6 px-5 pt-4"
contentContainerStyle={{ paddingBottom: Math.max(insets.bottom, 18) + 18 }}
refreshControl={<RefreshControl refreshing={refreshing} onRefresh={refreshWindow} />}
refreshControl={<RefreshControl refreshing={refreshing} onRefresh={refresh} />}
>
<SegmentedControl
options={WINDOW_OPTIONS.map((option) => ({ value: option.days, label: option.label }))}
selected={windowDays}
onSelect={selectWindow}
onSelect={setWindowDays}
/>
<UsageCoverageNotice environments={environments} merged={merged} isPartial={isPartial} />
@@ -129,17 +87,14 @@ export function UsageRouteScreen() {
<>
<ChartCard
merged={merged}
days={chartDays}
daily={chartTotals}
days={days}
metric={metric}
onMetricChange={setMetric}
sinceDay={window.sinceDay}
untilDay={window.untilDay}
isPast24Hours={isPast24Hours}
timeZone={window.timeZone}
/>
<ProviderSection merged={merged} metric={metric} />
<TotalsSection merged={merged} isPast24Hours={isPast24Hours} />
<TotalsSection merged={merged} />
<ModelsSection merged={merged} />
</>
)}
@@ -187,17 +142,14 @@ function SegmentedControl<Value extends number | string>(props: {
function ChartCard(props: {
readonly merged: MergedUsage;
readonly days: readonly string[];
readonly daily: readonly DailyTotals[];
readonly metric: UsageChartMetric;
readonly onMetricChange: (metric: UsageChartMetric) => void;
readonly sinceDay: string;
readonly untilDay: string;
readonly isPast24Hours: boolean;
readonly timeZone: string;
}) {
const { merged, metric } = props;
const colors = useProviderColors();
const hasActivity = props.daily.some((period) => period.totalTokens > 0);
const hasActivity = merged.daily.some((day) => day.totalTokens > 0);
return (
<View className="gap-4 rounded-[24px] border-continuous bg-card p-4">
@@ -221,7 +173,7 @@ function ChartCard(props: {
{hasActivity ? (
<UsageDailyChart
days={props.days}
daily={props.daily}
daily={merged.daily}
metric={metric}
height={CHART_HEIGHT}
/>
@@ -232,11 +184,7 @@ function ChartCard(props: {
)}
<View className="flex-row items-center justify-between">
<Text className="text-xs text-foreground-tertiary">
{props.isPast24Hours
? formatHourShort(props.days[0] ?? "", props.timeZone)
: formatDayShort(props.sinceDay)}
</Text>
<Text className="text-xs text-foreground-tertiary">{formatDayShort(props.sinceDay)}</Text>
<View className="flex-row items-center gap-4">
{merged.providers.map((provider) => (
<View key={provider.provider} className="flex-row items-center gap-1.5">
@@ -250,11 +198,7 @@ function ChartCard(props: {
</View>
))}
</View>
<Text className="text-xs text-foreground-tertiary">
{props.isPast24Hours
? formatHourShort(props.days[props.days.length - 1] ?? "", props.timeZone)
: formatDayShort(props.untilDay)}
</Text>
<Text className="text-xs text-foreground-tertiary">{formatDayShort(props.untilDay)}</Text>
</View>
</View>
);
@@ -348,12 +292,10 @@ function ProviderSection(props: {
);
}
function TotalsSection(props: { readonly merged: MergedUsage; readonly isPast24Hours: boolean }) {
function TotalsSection(props: { readonly merged: MergedUsage }) {
const { merged } = props;
const activePeriods = (props.isPast24Hours ? merged.hourly : merged.daily).filter(
(period) => period.totalTokens > 0,
).length;
const periodAverage = activePeriods === 0 ? 0 : merged.totalTokens / activePeriods;
const activeDays = merged.daily.filter((day) => day.totalTokens > 0).length;
const dailyAverage = activeDays === 0 ? 0 : merged.totalTokens / activeDays;
const observedInput = merged.uncachedInputTokens + merged.cachedInputTokens;
const cachedShare = observedInput === 0 ? 0 : merged.cachedInputTokens / observedInput;
@@ -363,7 +305,7 @@ function TotalsSection(props: { readonly merged: MergedUsage; readonly isPast24H
<MetricCell
label="Processed tokens"
value={formatTokens(merged.totalTokens)}
detail={`${formatTokens(periodAverage)} per active ${props.isPast24Hours ? "hour" : "day"}`}
detail={`${formatTokens(dailyAverage)} per active day`}
/>
<MetricCell
label="Cache savings"
@@ -12,107 +12,12 @@ import {
} from "@t3tools/contracts";
import {
buildPendingUserInputAnswers,
buildThreadFeed,
deriveThreadFeedPresentation,
isPendingUserInputOptionSelected,
setPendingUserInputCustomAnswer,
togglePendingUserInputOptionSelection,
type ThreadFeedActivity,
type ThreadFeedEntry,
} from "./threadActivity";
const singleSelectQuestion = {
id: "runtime",
header: "Runtime",
question: "Which runtime should be used?",
options: [
{ label: "Go", description: "One binary" },
{ label: "Node.js", description: "Reuse TypeScript" },
],
multiSelect: false,
} as const;
const multiSelectQuestion = {
id: "scope",
header: "Scope",
question: "Which data should be collected?",
options: [
{ label: "Orders", description: "Receipts" },
{ label: "Listings", description: "Inventory" },
],
multiSelect: true,
} as const;
describe("pending user input answers", () => {
it("replaces single-select options and toggles multi-select options", () => {
expect(
togglePendingUserInputOptionSelection(
singleSelectQuestion,
{ selectedOptionLabels: ["Go"] },
"Node.js",
),
).toEqual({ customAnswer: "", selectedOptionLabels: ["Node.js"] });
const orders = togglePendingUserInputOptionSelection(multiSelectQuestion, undefined, "Orders");
const ordersAndListings = togglePendingUserInputOptionSelection(
multiSelectQuestion,
orders,
"Listings",
);
expect(ordersAndListings).toEqual({
customAnswer: "",
selectedOptionLabels: ["Orders", "Listings"],
});
expect(
togglePendingUserInputOptionSelection(multiSelectQuestion, ordersAndListings, "Orders"),
).toEqual({ customAnswer: "", selectedOptionLabels: ["Listings"] });
const paddedOrders = togglePendingUserInputOptionSelection(
multiSelectQuestion,
undefined,
" Orders ",
);
expect(paddedOrders).toEqual({ customAnswer: "", selectedOptionLabels: ["Orders"] });
expect(
togglePendingUserInputOptionSelection(multiSelectQuestion, paddedOrders, " Orders "),
).toEqual({ customAnswer: "" });
});
it("builds array answers for multi-select questions", () => {
expect(
buildPendingUserInputAnswers([singleSelectQuestion, multiSelectQuestion], {
runtime: { selectedOptionLabels: ["Go"] },
scope: { selectedOptionLabels: ["Orders", "Listings"] },
}),
).toEqual({
runtime: "Go",
scope: ["Orders", "Listings"],
});
});
it("clears selected options while a custom answer is active", () => {
expect(
setPendingUserInputCustomAnswer(
{ selectedOptionLabels: ["Orders", "Listings"] },
"Orders first",
),
).toEqual({ customAnswer: "Orders first" });
});
it("matches selected chips against normalized option labels", () => {
expect(
isPendingUserInputOptionSelected({ selectedOptionLabels: ["Orders"] }, " Orders "),
).toBe(true);
expect(
isPendingUserInputOptionSelected(
{ selectedOptionLabels: ["Orders"], customAnswer: "Orders first" },
" Orders ",
),
).toBe(false);
});
});
function makeActivity(
input: Partial<OrchestrationThreadActivity> &
Pick<OrchestrationThreadActivity, "id" | "kind" | "summary" | "createdAt">,
+9 -67
View File
@@ -26,7 +26,7 @@ export interface PendingUserInput {
}
export interface PendingUserInputDraftAnswer {
readonly selectedOptionLabels?: ReadonlyArray<string>;
readonly selectedOptionLabel?: string;
readonly customAnswer?: string;
}
@@ -227,32 +227,14 @@ function normalizeDraftAnswer(value: string | undefined): string | null {
return trimmed.length > 0 ? trimmed : null;
}
function normalizeSelectedOptionLabels(
value: ReadonlyArray<string> | undefined,
): ReadonlyArray<string> {
if (!Array.isArray(value)) {
return [];
}
return Array.from(
new Set(value.map((entry) => entry.trim()).filter((entry) => entry.length > 0)),
);
}
function resolvePendingUserInputAnswer(
question: UserInputQuestion,
draft: PendingUserInputDraftAnswer | undefined,
): string | ReadonlyArray<string> | null {
): string | null {
const customAnswer = normalizeDraftAnswer(draft?.customAnswer);
if (customAnswer) {
return customAnswer;
}
const selectedOptionLabels = normalizeSelectedOptionLabels(draft?.selectedOptionLabels);
if (question.multiSelect) {
return selectedOptionLabels.length > 0 ? selectedOptionLabels : null;
}
return selectedOptionLabels[0] ?? null;
return normalizeDraftAnswer(draft?.selectedOptionLabel);
}
/** Codex children settle via task.updated (idle/failed/interrupted), never
@@ -1446,62 +1428,22 @@ export function setPendingUserInputCustomAnswer(
draft: PendingUserInputDraftAnswer | undefined,
customAnswer: string,
): PendingUserInputDraftAnswer {
const selectedOptionLabels =
customAnswer.trim().length > 0
? undefined
: normalizeSelectedOptionLabels(draft?.selectedOptionLabels);
const selectedOptionLabel =
customAnswer.trim().length > 0 ? undefined : draft?.selectedOptionLabel;
return {
customAnswer,
...(selectedOptionLabels && selectedOptionLabels.length > 0 ? { selectedOptionLabels } : {}),
};
}
export function isPendingUserInputOptionSelected(
draft: PendingUserInputDraftAnswer | undefined,
optionLabel: string,
): boolean {
if (normalizeDraftAnswer(draft?.customAnswer)) {
return false;
}
return normalizeSelectedOptionLabels(draft?.selectedOptionLabels).includes(optionLabel.trim());
}
export function togglePendingUserInputOptionSelection(
question: UserInputQuestion,
draft: PendingUserInputDraftAnswer | undefined,
optionLabel: string,
): PendingUserInputDraftAnswer {
const normalizedOptionLabel = optionLabel.trim();
if (question.multiSelect) {
const selectedOptionLabels = normalizeSelectedOptionLabels(draft?.selectedOptionLabels);
const nextSelectedOptionLabels = selectedOptionLabels.includes(normalizedOptionLabel)
? selectedOptionLabels.filter((label) => label !== normalizedOptionLabel)
: [...selectedOptionLabels, normalizedOptionLabel];
return {
customAnswer: "",
...(nextSelectedOptionLabels.length > 0
? { selectedOptionLabels: nextSelectedOptionLabels }
: {}),
};
}
return {
customAnswer: "",
selectedOptionLabels: [normalizedOptionLabel],
...(selectedOptionLabel ? { selectedOptionLabel } : {}),
};
}
export function buildPendingUserInputAnswers(
questions: ReadonlyArray<UserInputQuestion>,
draftAnswers: Record<string, PendingUserInputDraftAnswer>,
): Record<string, string | ReadonlyArray<string>> | null {
const answers: Record<string, string | ReadonlyArray<string>> = {};
): Record<string, string> | null {
const answers: Record<string, string> = {};
for (const question of questions) {
const answer = resolvePendingUserInputAnswer(question, draftAnswers[question.id]);
const answer = resolvePendingUserInputAnswer(draftAnswers[question.id]);
if (!answer) {
return null;
}
@@ -17,30 +17,6 @@ describe("hasWideMarkdownBlock", () => {
expect(hasWideMarkdownBlock(" ```\ncode\n```")).toBe(true);
});
it("detects top-level and blockquoted ordered-list markers", () => {
expect(hasWideMarkdownBlock("1. One\n2. Two\n3. Three\n4. Four\n5. Five")).toBe(true);
expect(hasWideMarkdownBlock("before\n3) Three")).toBe(true);
expect(hasWideMarkdownBlock("> 1. One\n> 2. Two")).toBe(true);
expect(hasWideMarkdownBlock("> > 3) Three")).toBe(true);
});
it("detects nested ordered lists without treating indented code as a list", () => {
expect(hasWideMarkdownBlock("- Parent\n 1. Child\n 2. Child")).toBe(true);
expect(hasWideMarkdownBlock("> - Parent\n> 1. Child")).toBe(true);
expect(hasWideMarkdownBlock(" 1. indented code")).toBe(false);
expect(hasWideMarkdownBlock(" - code-like bullet\n 1. indented code")).toBe(false);
});
it("can limit ordered-list width pinning to Android", () => {
const orderedList = "1. One\n2. Two";
expect(hasWideMarkdownBlock(orderedList, { includeOrderedLists: true })).toBe(true);
expect(hasWideMarkdownBlock(orderedList, { includeOrderedLists: false })).toBe(false);
expect(hasWideMarkdownBlock("```\ncode\n```", { includeOrderedLists: false })).toBe(true);
expect(hasWideMarkdownBlock("| a | b |\n| --- | --- |", { includeOrderedLists: false })).toBe(
true,
);
});
it("detects GFM tables", () => {
expect(hasWideMarkdownBlock("| a | b |\n| --- | --- |\n| 1 | 2 |")).toBe(true);
expect(hasWideMarkdownBlock("a | b\n:-- | --:\n1 | 2")).toBe(true);
+8 -60
View File
@@ -1,10 +1,9 @@
/**
* Detects markdown that the JS renderer draws as a block requiring a definite
* user-bubble width — fenced code blocks, GFM tables, and ordered lists.
* Detects markdown that the JS renderer draws as a standalone block View
* wrapping a horizontal ScrollView — fenced code blocks and GFM tables.
*
* Fenced code blocks and tables report an intrinsic width equal to their
* widest line, which is effectively unbounded. A user bubble sizes itself
* from its content
* Those blocks report an intrinsic width equal to their widest line, which is
* effectively unbounded. A user bubble sizes itself from its content
* (`maxWidth` with no `width`), so Android lays the bubble's children out
* during the unclamped intrinsic pass — where the surrounding paragraphs
* collapse to a single line — and never repositions them once the width is
@@ -13,57 +12,12 @@
* intrinsic pass entirely, which is the same reason review-comment bubbles
* already carry an explicit width.
*
* Ordered lists hit the same Android layout bug because each item contains a
* flexing content column inside a shrink-to-fit row.
*
* A four-space ordered marker is only treated as a list when the preceding
* non-empty line is a less-indented list item. This keeps standalone indented
* code out of the heuristic while covering nested lists.
* Indented (four-space) code blocks are deliberately not detected: they are
* vanishingly rare in chat input and the check would fire on ordinary nested
* list continuations.
*/
const FENCED_CODE_BLOCK = /^ {0,3}(?:```|~~~)/m;
// Trades some precision for a simple check, favoring false positives over false
// negatives: list-shaped paragraph may get a wider bubble
const ORDERED_LIST_ITEM = /^ {0,3}\d{1,9}[.)](?:[ \t]+|$)/;
const INDENTED_ORDERED_LIST_ITEM = /^( {4,})\d{1,9}[.)](?:[ \t]+|$)/;
const ANY_LIST_ITEM = /^( *)(?:[-+*]|\d{1,9}[.)])(?:[ \t]+|$)/;
const BLOCKQUOTE_PREFIX = /^ {0,3}>[ \t]?/;
export interface WideMarkdownBlockOptions {
readonly includeOrderedLists?: boolean;
}
function stripBlockquotePrefixes(line: string): string {
let content = line;
while (BLOCKQUOTE_PREFIX.test(content)) {
content = content.replace(BLOCKQUOTE_PREFIX, "");
}
return content;
}
function hasOrderedListItem(text: string): boolean {
let previousNonEmptyLine: string | null = null;
for (const rawLine of text.split("\n")) {
const line = stripBlockquotePrefixes(rawLine);
if (ORDERED_LIST_ITEM.test(line)) {
return true;
}
const nestedMatch = INDENTED_ORDERED_LIST_ITEM.exec(line);
const parentMatch =
previousNonEmptyLine === null ? null : ANY_LIST_ITEM.exec(previousNonEmptyLine);
if (nestedMatch && parentMatch && parentMatch[1].length < nestedMatch[1].length) {
return true;
}
if (line.trim().length > 0) {
previousNonEmptyLine = line;
}
}
return false;
}
function isTableDelimiterRow(line: string): boolean {
const trimmed = line.trim();
@@ -73,16 +27,10 @@ function isTableDelimiterRow(line: string): boolean {
return /^[|\-: \t]+$/.test(trimmed);
}
export function hasWideMarkdownBlock(
text: string,
options: WideMarkdownBlockOptions = {},
): boolean {
export function hasWideMarkdownBlock(text: string): boolean {
if (FENCED_CODE_BLOCK.test(text)) {
return true;
}
if (options.includeOrderedLists !== false && hasOrderedListItem(text)) {
return true;
}
if (!text.includes("|")) {
return false;
}
+1 -11
View File
@@ -81,18 +81,8 @@ export function useUsage(input: UsageSummaryInput): UsageView {
sinceDay: input.sinceDay,
untilDay: input.untilDay,
timeZone: input.timeZone,
resolution: input.resolution,
sinceTime: input.sinceTime,
untilTime: input.untilTime,
}),
[
input.sinceDay,
input.untilDay,
input.timeZone,
input.resolution,
input.sinceTime,
input.untilTime,
],
[input.sinceDay, input.untilDay, input.timeZone],
);
const atom = usageByWindowAtom(windowKey);
const environments = useAtomValue(atom);
@@ -1,11 +1,7 @@
import { useAtomValue } from "@effect/atom-react";
import { useCallback, useMemo, useState } from "react";
import {
ApprovalRequestId,
type ProviderApprovalDecision,
type UserInputQuestion,
} from "@t3tools/contracts";
import { ApprovalRequestId, type ProviderApprovalDecision } from "@t3tools/contracts";
import { Atom } from "effect/unstable/reactivity";
import { threadEnvironment } from "../state/threads";
@@ -16,7 +12,6 @@ import {
derivePendingUserInputs,
setPendingUserInputCustomAnswer,
sortThreadActivities,
togglePendingUserInputOptionSelection,
type PendingUserInputDraftAnswer,
} from "../lib/threadActivity";
import { appAtomRegistry } from "./atom-registry";
@@ -28,21 +23,15 @@ const userInputDraftsByRequestKeyAtom = Atom.make<
Record<string, Record<string, PendingUserInputDraftAnswer>>
>({}).pipe(Atom.keepAlive, Atom.withLabel("mobile:user-input-drafts"));
function setUserInputDraftOption(
requestKey: string,
question: UserInputQuestion,
label: string,
): void {
function setUserInputDraftOption(requestKey: string, questionId: string, label: string): void {
const current = appAtomRegistry.get(userInputDraftsByRequestKeyAtom);
appAtomRegistry.set(userInputDraftsByRequestKeyAtom, {
...current,
[requestKey]: {
...current[requestKey],
[question.id]: togglePendingUserInputOptionSelection(
question,
current[requestKey]?.[question.id],
label,
),
[questionId]: {
selectedOptionLabel: label,
},
},
});
}
@@ -108,13 +97,13 @@ export function useSelectedThreadRequests() {
: null;
const onSelectUserInputOption = useCallback(
(requestId: ApprovalRequestId, question: UserInputQuestion, label: string) => {
(requestId: ApprovalRequestId, questionId: string, label: string) => {
if (!selectedThreadShell) {
return;
}
const requestKey = scopedRequestKey(selectedThreadShell.environmentId, requestId);
setUserInputDraftOption(requestKey, question, label);
setUserInputDraftOption(requestKey, questionId, label);
},
[selectedThreadShell],
);
-3
View File
@@ -58,13 +58,10 @@ export const RPC_REQUIRED_SCOPES = {
[WS_METHODS.pullRequestsActivity]: AuthOrchestrationReadScope,
[WS_METHODS.pullRequestsDiffFileContents]: AuthOrchestrationReadScope,
[WS_METHODS.pullRequestsRunAction]: AuthOrchestrationOperateScope,
[WS_METHODS.pullRequestsUpdate]: AuthOrchestrationOperateScope,
[WS_METHODS.pullRequestsComment]: AuthOrchestrationOperateScope,
[WS_METHODS.pullRequestsUpdateComment]: AuthOrchestrationOperateScope,
[WS_METHODS.pullRequestsSubmitReview]: AuthOrchestrationOperateScope,
[WS_METHODS.pullRequestsReplyToThread]: AuthOrchestrationOperateScope,
[WS_METHODS.pullRequestsSetThreadResolution]: AuthOrchestrationOperateScope,
[WS_METHODS.pullRequestsSetReaction]: AuthOrchestrationOperateScope,
// Read scope like the reads it un-caches: refreshing is part of reading, and a read-only
// client pressing refresh must not be told it may not look again.
[WS_METHODS.pullRequestsInvalidate]: AuthOrchestrationReadScope,
+7 -9
View File
@@ -26,6 +26,7 @@ import * as HttpServerResponse from "effect/unstable/http/HttpServerResponse";
import {
buildConnectAuthorizeRequestUrl,
buildConnectClerkAuthorizeUrl,
checkConnectAuthCode,
connectCallbackUrl,
} from "@t3tools/shared/connectAuth";
@@ -366,7 +367,6 @@ export const make = Effect.gen(function* () {
const login = Effect.fn("cloud.cli_token.login")(function* () {
const metadata = yield* cloudCliOAuthConfig;
const hostedAppUrl = yield* hostedAppUrlConfig;
const { verifier, challenge, state } = yield* makePkceRequest;
const callback = yield* Deferred.make<string>();
const callbackRoute = HttpRouter.add(
@@ -392,21 +392,19 @@ export const make = Effect.gen(function* () {
Layer.provide(
NodeHttpServer.layer(NodeHttp.createServer, {
host: "127.0.0.1",
port: metadata.loopbackPort,
port: 34338,
disablePreemptiveShutdown: true,
}),
),
Layer.build,
);
// The hosted /connect page establishes a Clerk session before forwarding
// the request to /oauth/authorize with the loopback redirect URI. Sending
// a signed-out browser to /oauth/authorize directly loses the authorize
// parameters across Clerk's sign-in redirect (#5051).
const authorizationUrl = buildConnectAuthorizeRequestUrl({
hostedAppUrl,
const authorizationUrl = buildConnectClerkAuthorizeUrl({
authorizationEndpoint: metadata.authorizationEndpoint,
clientId: metadata.clientId,
redirectUri: metadata.redirectUri,
scopes: metadata.scopes,
state,
challenge,
loopbackPort: metadata.loopbackPort,
});
yield* Console.log(formatLoopbackAuthorizationPrompt(authorizationUrl));
const authorization = yield* waitForLoopbackAuthorization({
+2 -1
View File
@@ -90,9 +90,9 @@ it.effect("derives direct Clerk OAuth endpoints from statically injected public
}).pipe(provideEnv({}));
assert.deepEqual(config, {
authorizationEndpoint: "https://clerk.example.test/oauth/authorize",
tokenEndpoint: "https://clerk.example.test/oauth/token",
clientId: "oauth_client_embedded",
loopbackPort: 34338,
redirectUri: "http://127.0.0.1:34338/callback",
scopes: ["openid", "profile", "email"],
});
@@ -111,6 +111,7 @@ it.effect("prefers runtime Clerk OAuth config overrides over statically injected
}),
);
assert.equal(config.authorizationEndpoint, "https://runtime.example.test/oauth/authorize");
assert.equal(config.tokenEndpoint, "https://runtime.example.test/oauth/token");
assert.equal(config.clientId, "oauth_client_runtime");
}),
+5 -15
View File
@@ -1,8 +1,4 @@
import {
connectLoopbackRedirectUri,
CONNECT_OAUTH_SCOPES,
DEFAULT_HOSTED_APP_URL,
} from "@t3tools/shared/connectAuth";
import { CONNECT_OAUTH_SCOPES, DEFAULT_HOSTED_APP_URL } from "@t3tools/shared/connectAuth";
import { clerkFrontendApiUrlFromPublishableKey } from "@t3tools/shared/relayAuth";
import { normalizeSecureRelayUrl } from "@t3tools/shared/relayUrl";
import * as Config from "effect/Config";
@@ -18,7 +14,7 @@ declare const __T3CODE_BUILD_RELAY_CLIENT_OTLP_TRACES_URL__: string | undefined;
declare const __T3CODE_BUILD_RELAY_CLIENT_OTLP_TRACES_DATASET__: string | undefined;
declare const __T3CODE_BUILD_RELAY_CLIENT_OTLP_TRACES_TOKEN__: string | undefined;
const CLOUD_CLI_OAUTH_LOOPBACK_PORT = 34338;
const CLOUD_CLI_OAUTH_REDIRECT_URI = "http://127.0.0.1:34338/callback";
const CLOUD_CLI_OAUTH_SCOPES = CONNECT_OAUTH_SCOPES;
function validateRelayUrl(value: string) {
@@ -149,16 +145,10 @@ function makePublicValueConfig(name: string, fallback: string) {
);
}
/**
* The CLI never calls Clerk's /oauth/authorize itself: the browser leg goes
* through the hosted /connect page, which builds the authorize URL after a
* Clerk session exists (see CliTokenManager.login). Only the token endpoint
* is contacted directly.
*/
export interface CloudCliOAuthConfig {
readonly authorizationEndpoint: string;
readonly tokenEndpoint: string;
readonly clientId: string;
readonly loopbackPort: number;
readonly redirectUri: string;
readonly scopes: typeof CLOUD_CLI_OAUTH_SCOPES;
}
@@ -194,10 +184,10 @@ export function makeCloudCliOAuthConfig({
Effect.map(
(clerkFrontendApiUrl) =>
({
authorizationEndpoint: `${clerkFrontendApiUrl}/oauth/authorize`,
tokenEndpoint: `${clerkFrontendApiUrl}/oauth/token`,
clientId,
loopbackPort: CLOUD_CLI_OAUTH_LOOPBACK_PORT,
redirectUri: connectLoopbackRedirectUri(CLOUD_CLI_OAUTH_LOOPBACK_PORT),
redirectUri: CLOUD_CLI_OAUTH_REDIRECT_URI,
scopes: CLOUD_CLI_OAUTH_SCOPES,
}) satisfies CloudCliOAuthConfig,
),
@@ -146,6 +146,7 @@ export const make = Effect.gen(function* () {
pullRequests: true,
threadSettlement: true,
threadSnooze: true,
threadVisits: true,
threadPinning: true,
threadPinReorder: true,
threadTitleRegeneration: true,
-54
View File
@@ -9,10 +9,8 @@ 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 Logger from "effect/Logger";
import * as Option from "effect/Option";
import * as PlatformError from "effect/PlatformError";
import * as References from "effect/References";
import * as Scope from "effect/Scope";
import { ChildProcessSpawner } from "effect/unstable/process";
import { expect } from "vite-plus/test";
@@ -1388,58 +1386,6 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
}),
);
it.effect("status logs actionable provider detail without exposing the upstream cause", () =>
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
yield* initRepo(repoDir);
yield* runGit(repoDir, ["checkout", "-b", "feature/status-rate-limited"]);
const remoteDir = yield* createBareRemote();
yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]);
yield* runGit(repoDir, ["push", "-u", "origin", "feature/status-rate-limited"]);
const upstreamCause = "GraphQL rate limit for user ID 51714798 and token secret-value";
const { manager } = yield* makeManager({
ghScenario: {
failWith: new GitHubCli.GitHubCliRateLimitError({
command: "gh",
cwd: repoDir,
cause: new Error(upstreamCause),
}),
},
});
const logs: Array<{ message: string; annotations: Record<string, unknown> }> = [];
const logger = Logger.make<unknown, void>(({ fiber, message }) => {
logs.push({
message: String(message),
annotations: { ...fiber.getRef(References.CurrentLogAnnotations) },
});
});
const status = yield* manager
.status({ cwd: repoDir })
.pipe(Effect.provide(Logger.layer([logger], { mergeWithExisting: false })));
expect(status.pr).toBeNull();
const warning = logs.find((entry) => entry.message.includes("PR lookup failed"));
expect(warning?.annotations).toMatchObject({
operation: "lookupStatusPr",
branch: "feature/status-rate-limited",
errorTag: "SourceControlProviderError",
provider: "github",
providerOperation: "listChangeRequests",
providerCommand: "gh",
errorDetail:
"GitHub API rate limit exceeded. Run `gh api rate_limit` to inspect the quota and reset time.",
});
const loggedText = [
warning?.message ?? "",
...Object.values(warning?.annotations ?? {}).map(String),
].join("\n");
expect(loggedText).not.toContain(upstreamCause);
expect(loggedText).not.toContain("secret-value");
}),
);
it.effect("status keeps the last known PR when a later lookup fails", () =>
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
-11
View File
@@ -12,7 +12,6 @@ import * as Option from "effect/Option";
import * as Order from "effect/Order";
import * as Path from "effect/Path";
import * as Ref from "effect/Ref";
import * as Schema from "effect/Schema";
import {
GitActionProgressEvent,
GitActionProgressPhase,
@@ -29,7 +28,6 @@ import {
type VcsStatusRemoteResult,
VcsStatusResult,
ModelSelection,
SourceControlProviderError,
type SourceControlWritingStyleSettings,
} from "@t3tools/contracts";
import {
@@ -115,7 +113,6 @@ const PR_LOOKUP_CACHE_TTL = Duration.minutes(2);
const PR_LOOKUP_FAILURE_BASE_TTL = Duration.seconds(20);
const PR_LOOKUP_FAILURE_MAX_TTL = Duration.minutes(15);
const PR_LOOKUP_CACHE_CAPACITY = 2_048;
const isSourceControlProviderError = Schema.is(SourceControlProviderError);
/**
* How long a failed PR lookup is cached, given the number of consecutive
@@ -1051,14 +1048,6 @@ export const make = Effect.gen(function* () {
typeof error === "object" && error !== null && "_tag" in error
? String(error._tag)
: typeof error,
...(isSourceControlProviderError(error)
? {
provider: error.provider,
providerOperation: error.operation,
providerCommand: error.command ?? "unknown",
errorDetail: error.detail,
}
: {}),
}),
Effect.andThen(resolveBranchHeadContext(cwd, details)),
Effect.map((headContext) =>
@@ -619,6 +619,7 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
settledAt: null,
snoozedUntil: null,
snoozedAt: null,
lastVisitedAt: null,
pinnedAt: null,
pinOrderKey: null,
titleRegenerationRequestId: null,
@@ -727,6 +728,21 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
return;
}
case "thread.visited": {
const existingRow = yield* projectionThreadRepository.getById({
threadId: event.payload.threadId,
});
if (Option.isNone(existingRow)) {
return;
}
yield* projectionThreadRepository.upsert({
...existingRow.value,
lastVisitedAt: event.payload.lastVisitedAt,
updatedAt: event.payload.updatedAt,
});
return;
}
case "thread.pinned": {
const existingRow = yield* projectionThreadRepository.getById({
threadId: event.payload.threadId,
@@ -323,6 +323,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
settledAt: null,
snoozedUntil: null,
snoozedAt: null,
lastVisitedAt: null,
pinnedAt: "2026-02-24T00:00:01.000Z",
pinOrderKey: "gm",
titleRegeneration: null,
@@ -442,6 +443,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
settledAt: null,
snoozedUntil: null,
snoozedAt: null,
lastVisitedAt: null,
pinnedAt: "2026-02-24T00:00:01.000Z",
pinOrderKey: "gm",
titleRegeneration: null,
@@ -426,6 +426,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
settled_at AS "settledAt",
snoozed_until AS "snoozedUntil",
snoozed_at AS "snoozedAt",
last_visited_at AS "lastVisitedAt",
pinned_at AS "pinnedAt",
pin_order_key AS "pinOrderKey",
title_regeneration_request_id AS "titleRegenerationRequestId",
@@ -462,6 +463,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
settled_at AS "settledAt",
snoozed_until AS "snoozedUntil",
snoozed_at AS "snoozedAt",
last_visited_at AS "lastVisitedAt",
pinned_at AS "pinnedAt",
pin_order_key AS "pinOrderKey",
title_regeneration_request_id AS "titleRegenerationRequestId",
@@ -500,6 +502,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
settled_at AS "settledAt",
snoozed_until AS "snoozedUntil",
snoozed_at AS "snoozedAt",
last_visited_at AS "lastVisitedAt",
pinned_at AS "pinnedAt",
pin_order_key AS "pinOrderKey",
title_regeneration_request_id AS "titleRegenerationRequestId",
@@ -942,6 +945,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
settled_at AS "settledAt",
snoozed_until AS "snoozedUntil",
snoozed_at AS "snoozedAt",
last_visited_at AS "lastVisitedAt",
pinned_at AS "pinnedAt",
pin_order_key AS "pinOrderKey",
title_regeneration_request_id AS "titleRegenerationRequestId",
@@ -1575,6 +1579,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
settledAt: row.settledAt,
snoozedUntil: row.snoozedUntil,
snoozedAt: row.snoozedAt,
lastVisitedAt: row.lastVisitedAt,
pinnedAt: row.pinnedAt,
pinOrderKey: row.pinOrderKey ?? null,
titleRegeneration: mapTitleRegeneration(row),
@@ -1782,6 +1787,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
settledAt: row.settledAt,
snoozedUntil: row.snoozedUntil,
snoozedAt: row.snoozedAt,
lastVisitedAt: row.lastVisitedAt,
pinnedAt: row.pinnedAt,
pinOrderKey: row.pinOrderKey ?? null,
titleRegeneration: mapTitleRegeneration(row),
@@ -1918,6 +1924,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
settledAt: row.settledAt,
snoozedUntil: row.snoozedUntil,
snoozedAt: row.snoozedAt,
lastVisitedAt: row.lastVisitedAt,
pinnedAt: row.pinnedAt,
pinOrderKey: row.pinOrderKey ?? null,
titleRegeneration: mapTitleRegeneration(row),
@@ -2063,6 +2070,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
settledAt: row.settledAt,
snoozedUntil: row.snoozedUntil,
snoozedAt: row.snoozedAt,
lastVisitedAt: row.lastVisitedAt,
pinnedAt: row.pinnedAt,
pinOrderKey: row.pinOrderKey ?? null,
titleRegeneration: mapTitleRegeneration(row),
@@ -2342,6 +2350,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
settledAt: threadRow.value.settledAt,
snoozedUntil: threadRow.value.snoozedUntil,
snoozedAt: threadRow.value.snoozedAt,
lastVisitedAt: threadRow.value.lastVisitedAt,
pinnedAt: threadRow.value.pinnedAt,
pinOrderKey: threadRow.value.pinOrderKey ?? null,
titleRegeneration: mapTitleRegeneration(threadRow.value),
@@ -2463,6 +2472,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
settledAt: threadRow.value.settledAt,
snoozedUntil: threadRow.value.snoozedUntil,
snoozedAt: threadRow.value.snoozedAt,
lastVisitedAt: threadRow.value.lastVisitedAt,
pinnedAt: threadRow.value.pinnedAt,
pinOrderKey: threadRow.value.pinOrderKey ?? null,
titleRegeneration: mapTitleRegeneration(threadRow.value),
+2
View File
@@ -13,6 +13,7 @@ import {
ThreadUnsettledPayload as ContractsThreadUnsettledPayloadSchema,
ThreadSnoozedPayload as ContractsThreadSnoozedPayloadSchema,
ThreadUnsnoozedPayload as ContractsThreadUnsnoozedPayloadSchema,
ThreadVisitedPayload as ContractsThreadVisitedPayloadSchema,
ThreadPinnedPayload as ContractsThreadPinnedPayloadSchema,
ThreadUnpinnedPayload as ContractsThreadUnpinnedPayloadSchema,
ThreadPinReorderedPayload as ContractsThreadPinReorderedPayloadSchema,
@@ -45,6 +46,7 @@ export const ThreadUnarchivedPayload = ContractsThreadUnarchivedPayloadSchema;
export const ThreadUnsettledPayload = ContractsThreadUnsettledPayloadSchema;
export const ThreadSnoozedPayload = ContractsThreadSnoozedPayloadSchema;
export const ThreadUnsnoozedPayload = ContractsThreadUnsnoozedPayloadSchema;
export const ThreadVisitedPayload = ContractsThreadVisitedPayloadSchema;
export const ThreadPinnedPayload = ContractsThreadPinnedPayloadSchema;
export const ThreadUnpinnedPayload = ContractsThreadUnpinnedPayloadSchema;
export const ThreadPinReorderedPayload = ContractsThreadPinReorderedPayloadSchema;
+37
View File
@@ -658,6 +658,43 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
};
}
case "thread.visit": {
// requireThread, not requireThreadNotArchived: archived threads stay
// openable, and acknowledging one must not fail.
const thread = yield* requireThread({
readModel,
command,
threadId: command.threadId,
});
// Monotonic: a visit never moves the acknowledgement backwards, so a
// raced or replayed older visit re-emits the existing value (the
// engine rejects zero-event commands) and projects as a no-op. NaN
// from an unparseable stored value fails the comparison and lets the
// fresh visit through.
const existingVisitedAt = thread.lastVisitedAt ?? null;
const lastVisitedAt =
existingVisitedAt !== null && Date.parse(existingVisitedAt) >= Date.parse(command.visitedAt)
? existingVisitedAt
: command.visitedAt;
const occurredAt = yield* nowIso;
return {
...(yield* withEventBase({
aggregateKind: "thread",
aggregateId: command.threadId,
occurredAt,
commandId: command.commandId,
})),
type: "thread.visited",
payload: {
threadId: command.threadId,
lastVisitedAt,
// A visit is passive acknowledgement: always keep the thread's
// existing updatedAt so reading never churns ordering.
updatedAt: thread.updatedAt,
},
};
}
case "thread.pin": {
const thread = yield* requireThreadNotArchived({
readModel,
@@ -0,0 +1,149 @@
import {
CommandId,
ProjectId,
ProviderInstanceId,
ThreadId,
type OrchestrationReadModel,
} from "@t3tools/contracts";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { expect, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import { decideOrchestrationCommand } from "./decider.ts";
const NOW = "2026-01-01T00:00:00.000Z";
const EARLIER_VISIT = "2025-12-30T00:00:00.000Z";
const LATER_VISIT = "2025-12-31T00:00:00.000Z";
function makeReadModel(input: {
readonly lastVisitedAt?: string | null;
readonly archivedAt?: string | null;
}): OrchestrationReadModel {
return {
snapshotSequence: 0,
projects: [],
threads: [
{
id: ThreadId.make("thread-1"),
projectId: ProjectId.make("project-1"),
title: "Thread",
modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
runtimeMode: "full-access",
interactionMode: "default",
branch: null,
worktreePath: null,
latestTurn: null,
createdAt: NOW,
updatedAt: NOW,
archivedAt: input.archivedAt ?? null,
settledOverride: null,
settledAt: null,
snoozedUntil: null,
snoozedAt: null,
lastVisitedAt: input.lastVisitedAt ?? null,
deletedAt: null,
messages: [],
proposedPlans: [],
activities: [],
checkpoints: [],
session: null,
},
],
updatedAt: NOW,
};
}
it.layer(NodeServices.layer)("visited thread decider", (it) => {
it.effect("stamps a first visit without churning updatedAt", () =>
Effect.gen(function* () {
const event = yield* decideOrchestrationCommand({
command: {
type: "thread.visit",
commandId: CommandId.make("cmd-visit"),
threadId: ThreadId.make("thread-1"),
visitedAt: LATER_VISIT,
},
readModel: makeReadModel({}),
});
const events = Array.isArray(event) ? event : [event];
expect(events).toHaveLength(1);
expect(events[0]?.type).toBe("thread.visited");
if (events[0]?.type === "thread.visited") {
expect(events[0].payload.lastVisitedAt).toBe(LATER_VISIT);
// A visit is passive acknowledgement: ordering must not move.
expect(events[0].payload.updatedAt).toBe(NOW);
}
}),
);
it.effect("advances a newer visit past an older one", () =>
Effect.gen(function* () {
const event = yield* decideOrchestrationCommand({
command: {
type: "thread.visit",
commandId: CommandId.make("cmd-visit-advance"),
threadId: ThreadId.make("thread-1"),
visitedAt: LATER_VISIT,
},
readModel: makeReadModel({ lastVisitedAt: EARLIER_VISIT }),
});
const events = Array.isArray(event) ? event : [event];
if (events[0]?.type === "thread.visited") {
expect(events[0].payload.lastVisitedAt).toBe(LATER_VISIT);
}
}),
);
it.effect("keeps the existing stamp when a raced older visit arrives", () =>
Effect.gen(function* () {
// Monotonic: a stale visit from a lagging device re-emits the current
// value instead of moving the acknowledgement backwards.
const event = yield* decideOrchestrationCommand({
command: {
type: "thread.visit",
commandId: CommandId.make("cmd-visit-stale"),
threadId: ThreadId.make("thread-1"),
visitedAt: EARLIER_VISIT,
},
readModel: makeReadModel({ lastVisitedAt: LATER_VISIT }),
});
const events = Array.isArray(event) ? event : [event];
if (events[0]?.type === "thread.visited") {
expect(events[0].payload.lastVisitedAt).toBe(LATER_VISIT);
expect(events[0].payload.updatedAt).toBe(NOW);
}
}),
);
it.effect("accepts a visit on an archived thread", () =>
Effect.gen(function* () {
// Archived threads stay openable; acknowledging one must not fail.
const event = yield* decideOrchestrationCommand({
command: {
type: "thread.visit",
commandId: CommandId.make("cmd-visit-archived"),
threadId: ThreadId.make("thread-1"),
visitedAt: LATER_VISIT,
},
readModel: makeReadModel({ archivedAt: NOW }),
});
const events = Array.isArray(event) ? event : [event];
expect(events[0]?.type).toBe("thread.visited");
}),
);
it.effect("rejects a visit for an unknown thread", () =>
Effect.gen(function* () {
const error = yield* decideOrchestrationCommand({
command: {
type: "thread.visit",
commandId: CommandId.make("cmd-visit-unknown"),
threadId: ThreadId.make("thread-unknown"),
visitedAt: LATER_VISIT,
},
readModel: makeReadModel({}),
}).pipe(Effect.flip);
expect(error._tag).toBe("OrchestrationCommandInvariantError");
}),
);
});
@@ -30,6 +30,7 @@ import {
ThreadUnarchivedPayload,
ThreadUnsettledPayload,
ThreadUnsnoozedPayload,
ThreadVisitedPayload,
ThreadRevertedPayload,
ThreadSessionSetPayload,
ThreadTurnDiffCompletedPayload,
@@ -405,6 +406,17 @@ export function projectEvent(
})),
);
case "thread.visited":
return decodeForEvent(ThreadVisitedPayload, event.payload, event.type, "payload").pipe(
Effect.map((payload) => ({
...nextBase,
threads: updateThread(nextBase.threads, payload.threadId, {
lastVisitedAt: payload.lastVisitedAt,
updatedAt: payload.updatedAt,
}),
})),
);
case "thread.pinned":
return decodeForEvent(ThreadPinnedPayload, event.payload, event.type, "payload").pipe(
Effect.map((payload) => ({
@@ -96,6 +96,7 @@ projectionRepositoriesLayer("Projection repositories", (it) => {
settledAt: null,
snoozedUntil: null,
snoozedAt: null,
lastVisitedAt: null,
pinnedAt: null,
latestUserMessageAt: null,
pendingApprovalCount: 0,
@@ -159,6 +160,7 @@ projectionRepositoriesLayer("Projection repositories", (it) => {
settledAt: "2026-03-25T00:00:00.000Z",
snoozedUntil: "2026-03-26T09:00:00.000Z",
snoozedAt: "2026-03-25T00:00:00.000Z",
lastVisitedAt: "2026-03-25T00:00:00.000Z",
pinnedAt: "2026-03-25T00:00:00.000Z",
latestUserMessageAt: null,
pendingApprovalCount: 0,
@@ -178,6 +180,7 @@ projectionRepositoriesLayer("Projection repositories", (it) => {
assert.strictEqual(row.settledAt, "2026-03-25T00:00:00.000Z");
assert.strictEqual(row.snoozedUntil, "2026-03-26T09:00:00.000Z");
assert.strictEqual(row.snoozedAt, "2026-03-25T00:00:00.000Z");
assert.strictEqual(row.lastVisitedAt, "2026-03-25T00:00:00.000Z");
assert.strictEqual(row.pinnedAt, "2026-03-25T00:00:00.000Z");
// Un-settle to the keep-active pin and wake the snooze; confirm the
@@ -188,6 +191,7 @@ projectionRepositoriesLayer("Projection repositories", (it) => {
settledAt: null,
snoozedUntil: null,
snoozedAt: null,
lastVisitedAt: null,
pinnedAt: null,
});
const repersisted = yield* threads.getById({
@@ -47,6 +47,7 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
settled_at,
snoozed_until,
snoozed_at,
last_visited_at,
pinned_at,
pin_order_key,
title_regeneration_request_id,
@@ -74,6 +75,7 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
${row.settledAt},
${row.snoozedUntil},
${row.snoozedAt},
${row.lastVisitedAt},
${row.pinnedAt},
${row.pinOrderKey ?? null},
${row.titleRegenerationRequestId ?? null},
@@ -101,6 +103,7 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
settled_at = excluded.settled_at,
snoozed_until = excluded.snoozed_until,
snoozed_at = excluded.snoozed_at,
last_visited_at = excluded.last_visited_at,
pinned_at = excluded.pinned_at,
pin_order_key = excluded.pin_order_key,
title_regeneration_request_id = excluded.title_regeneration_request_id,
@@ -135,6 +138,7 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
settled_at AS "settledAt",
snoozed_until AS "snoozedUntil",
snoozed_at AS "snoozedAt",
last_visited_at AS "lastVisitedAt",
pinned_at AS "pinnedAt",
pin_order_key AS "pinOrderKey",
title_regeneration_request_id AS "titleRegenerationRequestId",
@@ -171,6 +175,7 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
settled_at AS "settledAt",
snoozed_until AS "snoozedUntil",
snoozed_at AS "snoozedAt",
last_visited_at AS "lastVisitedAt",
pinned_at AS "pinnedAt",
pin_order_key AS "pinOrderKey",
title_regeneration_request_id AS "titleRegenerationRequestId",
@@ -53,6 +53,7 @@ import Migration0037 from "./Migrations/037_ProjectionTurnsKeysetIndex.ts";
import Migration0038 from "./Migrations/038_ProjectionThreadsPinOrderKey.ts";
import Migration0039 from "./Migrations/039_ProjectionProjectsDefaultThreadEnvMode.ts";
import Migration0040 from "./Migrations/040_ProjectionProjectFaviconPath.ts";
import Migration0041 from "./Migrations/041_ProjectionThreadsLastVisitedAt.ts";
/**
* Migration loader with all migrations defined inline.
@@ -105,6 +106,7 @@ export const migrationEntries = [
[38, "ProjectionThreadsPinOrderKey", Migration0038],
[39, "ProjectionProjectsDefaultThreadEnvMode", Migration0039],
[40, "ProjectionProjectFaviconPath", Migration0040],
[41, "ProjectionThreadsLastVisitedAt", Migration0041],
] as const;
export const migrationManifest = migrationEntries.map(([id, name]) => [id, name] as const);
@@ -0,0 +1,16 @@
import * as Effect from "effect/Effect";
import * as SqlClient from "effect/unstable/sql/SqlClient";
export default Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
const columns = yield* sql<{ readonly name: string }>`
PRAGMA table_info(projection_threads)
`;
if (!columns.some((column) => column.name === "last_visited_at")) {
yield* sql`
ALTER TABLE projection_threads
ADD COLUMN last_visited_at TEXT
`;
}
});
@@ -41,6 +41,7 @@ export const ProjectionThread = Schema.Struct({
settledAt: Schema.NullOr(IsoDateTime),
snoozedUntil: Schema.NullOr(IsoDateTime),
snoozedAt: Schema.NullOr(IsoDateTime),
lastVisitedAt: Schema.NullOr(IsoDateTime),
pinnedAt: Schema.NullOr(IsoDateTime),
pinOrderKey: Schema.optional(Schema.NullOr(Schema.String)),
titleRegenerationRequestId: Schema.optional(Schema.NullOr(CommandId)),
@@ -125,31 +125,6 @@ describe("parseModelsCliOutput", () => {
NodeAssert.ok(model.variants);
NodeAssert.equal(model.variants!["medium"] !== undefined, true);
});
it("keeps a model whose JSON body has a slash and no interior whitespace", () => {
// OpenRouter-style: the model id contains a `/` and no string value has a
// space, so the JSON body line itself matches the slug regex. It must still
// be treated as the body of the preceding slug, not a new slug.
const stdout = [
"openrouter/qwen/qwen3-coder",
JSON.stringify({
id: "qwen/qwen3-coder",
providerID: "openrouter",
name: "qwen3-coder",
status: "active",
}),
].join("\n");
const result = parseModelsCliOutput(stdout);
NodeAssert.equal(result.providers.size, 1);
NodeAssert.deepEqual([...result.connected], ["openrouter"]);
const provider = result.providers.get("openrouter")!;
NodeAssert.ok(provider);
const model = provider.models["qwen/qwen3-coder"]!;
NodeAssert.ok(model);
NodeAssert.equal(model.id, "qwen/qwen3-coder");
NodeAssert.equal(model.providerID, "openrouter");
});
});
describe("parseAgentListCliOutput", () => {
+1 -7
View File
@@ -216,13 +216,7 @@ export function parseModelsCliOutput(stdout: string): {
};
for (const line of lines) {
// A model's JSON body is a single `JSON.stringify` line starting with `{`,
// while a provider/model slug is a bare `provider/model` header. Only the
// latter can be a slug: without this guard a body line with no interior
// whitespace and a `/` in one of its values (e.g. an OpenRouter model whose
// `id` is `vendor/model`) matches SLUG_LINE_RE, so flushModel runs against
// an empty body and the model is silently dropped.
const slugMatch = line.trimStart().startsWith("{") ? null : SLUG_LINE_RE.exec(line);
const slugMatch = SLUG_LINE_RE.exec(line);
if (slugMatch) {
flushModel();
currentSlug = slugMatch[1]!;
@@ -342,40 +342,7 @@ layer("AzureDevOpsPullRequestCli.layer", (it) => {
}),
);
it.effect("stores the squash choice with an auto-completion, as a merge now does", () =>
Effect.gen(function* () {
mockedExecute.mockReturnValue(Effect.succeed(output("{}")));
const cli = yield* AzureDevOpsPullRequestCli.AzureDevOpsPullRequestCli;
yield* cli.runPullRequestAction({
cwd: "/w",
number: 42,
action: "enable-auto-merge",
mergeMethod: "squash",
});
expect(argsOfCall(0)).toEqual([
"repos",
"pr",
"update",
"--detect",
"true",
"--id",
"42",
"--auto-complete",
"true",
"--squash",
"true",
"--only-show-errors",
"--output",
"json",
]);
}),
);
it.effect.each([
{ action: "enable-auto-merge", expected: ["--auto-complete", "true", "--squash", "false"] },
{ action: "disable-auto-merge", expected: ["--auto-complete", "false"] },
{ action: "draft", expected: ["--draft", "true"] },
{ action: "ready", expected: ["--draft", "false"] },
{ action: "close", expected: ["--status", "abandoned"] },
@@ -403,79 +370,6 @@ layer("AzureDevOpsPullRequestCli.layer", (it) => {
}),
);
it.effect.each([
{ name: "a title", rewrite: { title: "Add the page" }, expected: ["--title=Add the page"] },
{
name: "a description",
rewrite: { body: "Why the page changed" },
expected: ["--description=Why the page changed"],
},
{
name: "both",
rewrite: { title: "Add the page", body: "Why the page changed" },
expected: ["--title=Add the page", "--description=Why the page changed"],
},
] as const)("rewrites $name, sending nothing it was not given", ({ rewrite, expected }) =>
Effect.gen(function* () {
mockedExecute.mockReturnValue(Effect.succeed(output("{}")));
const cli = yield* AzureDevOpsPullRequestCli.AzureDevOpsPullRequestCli;
yield* cli.updatePullRequest({ cwd: "/w", number: 42, ...rewrite });
expect(argsOfCall(0)).toEqual([
"repos",
"pr",
"update",
"--detect",
"true",
"--id",
"42",
...expected,
"--only-show-errors",
"--output",
"json",
]);
}),
);
it.effect("sends a description that starts with a dash as one value, not as a flag", () =>
Effect.gen(function* () {
mockedExecute.mockReturnValue(Effect.succeed(output("{}")));
const cli = yield* AzureDevOpsPullRequestCli.AzureDevOpsPullRequestCli;
yield* cli.updatePullRequest({
cwd: "/w",
number: 42,
body: "- rewrote the page\n- kept the rest",
});
// One argument, so the leading dash of an ordinary bullet list never reaches az as a flag,
// and the whole text stays together where `--description` would otherwise take several.
expect(argsOfCall(0)).toContain("--description=- rewrote the page\n- kept the rest");
}),
);
it.effect("rewrites through the provider, which says it takes one", () =>
Effect.gen(function* () {
mockedExecute.mockReturnValue(Effect.succeed(output("{}")));
const provider = yield* AzureDevOpsPullRequestProvider.make;
// False for a remark because nothing here can post one, so there is none to rewrite.
expect(provider.capabilities.edit).toEqual({ changeRequest: true, comment: false });
assert.isDefined(provider.updateChangeRequest);
yield* provider.updateChangeRequest({
cwd: "/w",
repository: "web",
host: "dev.azure.com",
number: 42,
title: "Add the page",
});
expect(argsOfCall(0)).toContain("--title=Add the page");
expect(argsOfCall(0)).not.toContain("--description");
}),
);
it.effect("reads the conversation through the REST API, pinned to a version", () =>
Effect.gen(function* () {
mockedExecute.mockReturnValueOnce(
@@ -159,14 +159,6 @@ export class AzureDevOpsPullRequestCli extends Context.Service<
readonly mergeMethod?: PullRequestMergeMethod;
}) => Effect.Effect<void, AzureDevOpsPullRequestCliError>;
/** Rewrites the pull request's own words, through the same command that moves it. */
readonly updatePullRequest: (input: {
readonly cwd: string;
readonly number: number;
readonly title?: string | undefined;
readonly body?: string | undefined;
}) => Effect.Effect<void, AzureDevOpsPullRequestCliError>;
/**
* Adds reviewers to a pull request, or takes them off it. `az repos pr reviewer` is the whole
* of what Azure offers here: it adds and removes named identities, and has no counterpart that
@@ -220,21 +212,12 @@ function actionArgs(
switch (action) {
case "merge":
return ["--status", "completed", "--squash", mergeMethod === "squash" ? "true" : "false"];
// Auto-complete is Azure's own name for it: the pull request stays active and Azure completes
// it once its policies pass. The squash choice is stored with it, as it is for a merge now.
case "enable-auto-merge":
return ["--auto-complete", "true", "--squash", mergeMethod === "squash" ? "true" : "false"];
case "disable-auto-merge":
return ["--auto-complete", "false"];
case "ready":
return ["--draft", "false"];
case "draft":
return ["--draft", "true"];
case "close":
return ["--status", "abandoned"];
// Never reached: this host does not declare the action, so nothing offers it.
case "update-branch":
return [];
case "reopen":
return ["--status", "active"];
}
@@ -498,29 +481,6 @@ export const make = Effect.gen(function* () {
],
})
.pipe(Effect.asVoid),
updatePullRequest: (input) =>
azure
.execute({
cwd: input.cwd,
args: [
"repos",
"pr",
"update",
...detectArgs,
"--id",
String(input.number),
// One argument rather than a flag and a value beside it: a description usually opens
// with a bullet, and az reads a dash in the next argv slot as a flag of its own.
// `--description` also takes several strings, and this keeps the whole text as one.
...(input.title === undefined ? [] : [`--title=${input.title}`]),
...(input.body === undefined ? [] : [`--description=${input.body}`]),
"--only-show-errors",
"--output",
"json",
],
})
.pipe(Effect.asVoid),
});
});
@@ -9,15 +9,7 @@ describe("azure devops viewer permissions", () => {
// and an unknown permission is granted rather than guessed away. Azure refuses the ones it
// will not allow, at the moment they are taken, in words this could not have written.
expect(AZURE_DEVOPS_VIEWER_PERMISSIONS).toEqual({
actions: [
"merge",
"ready",
"draft",
"close",
"reopen",
"enable-auto-merge",
"disable-auto-merge",
],
actions: ["merge", "ready", "draft", "close", "reopen"],
// False because the host itself cannot post one, not because this viewer may not.
comment: false,
resolve: false,
@@ -18,20 +18,11 @@ const CAPABILITIES: PullRequestCapabilities = {
// Reading a conversation is a plain REST read, but posting one is not something this can
// claim without having run it, so the composer stays hidden.
comment: false,
actions: [
"merge",
"ready",
"draft",
"close",
"reopen",
"enable-auto-merge",
"disable-auto-merge",
],
actions: ["merge", "ready", "draft", "close", "reopen"],
// Azure squashes as a completion option; it has no rebase strategy of its own.
mergeMethods: ["merge", "squash"],
// `az repos pr list` filters by status, creator, reviewer and branch, and by no text at all.
search: false,
reactions: false,
// With no patch to show there are no lines to write against, so nothing here is offered.
review: { inlineComment: false, reply: false, resolve: false, verdicts: [] },
// `az repos pr reviewer add` and `remove` name identities, and nothing anywhere in `az repos`
@@ -39,10 +30,6 @@ const CAPABILITIES: PullRequestCapabilities = {
// different service with its own permissions. So the page takes a name here rather than being
// handed a menu built out of a guess.
reviewers: { request: true, listCandidates: false },
// A new title and description travel on the same `az repos pr update` that moves a pull request.
// Rewriting a remark is false for the same reason posting one is: this cannot put a remark on
// Azure DevOps at all, so there is nothing here it could rewrite either.
edit: { changeRequest: true, comment: false },
};
/**
@@ -166,7 +153,6 @@ export const make = Effect.gen(function* () {
checks: [],
mergeCapabilities: { merge: true, squash: true, rebase: false },
viewerPermissions: AZURE_DEVOPS_VIEWER_PERMISSIONS,
autoMergeEnabled: pullRequest.autoMergeEnabled,
}),
),
),
@@ -220,16 +206,6 @@ export const make = Effect.gen(function* () {
})
.pipe(Effect.mapError(fail("runAction"))),
updateChangeRequest: (input) =>
cli
.updatePullRequest({
cwd: input.cwd,
number: input.number,
title: input.title,
body: input.body,
})
.pipe(Effect.mapError(fail("updateChangeRequest"))),
// Never called: `capabilities.reviewers.listCandidates` is false, and the service refuses the
// list without it.
listReviewerCandidates: () =>
@@ -264,8 +240,6 @@ export const make = Effect.gen(function* () {
replyToThread: () => unsupported("replyToThread"),
setThreadResolution: () => unsupported("setThreadResolution"),
setReaction: () => unsupported("setReaction"),
};
return provider;
@@ -510,74 +510,6 @@ layer("BitbucketPullRequestApi.layer", (it) => {
}),
);
it.effect("rewrites a title alone, without touching anything else", () =>
Effect.gen(function* () {
mockedRequest.mockReturnValue(Effect.succeed(response("{}")));
const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
yield* api.updateChangeRequest({ repository: "acme/web", number: 7, title: "A new title" });
const call = callAt(0);
expect(call.method).toBe("PUT");
expect(call.url).toBe("/repositories/acme/web/pullrequests/7");
// Bitbucket's PUT is a partial update, so a field left out of the body is left as it was.
// @effect-diagnostics-next-line preferSchemaOverJson:off
expect(JSON.parse(call.body ?? "")).toEqual({ title: "A new title" });
}),
);
it.effect("leaves out the half of the pull request it was not asked about", () =>
Effect.gen(function* () {
mockedRequest.mockReturnValue(Effect.succeed(response("{}")));
const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
yield* api.updateChangeRequest({ repository: "acme/web", number: 7, body: "New body." });
// @effect-diagnostics-next-line preferSchemaOverJson:off
expect(JSON.parse(callAt(0).body ?? "")).toEqual({ description: "New body." });
}),
);
it.effect("writes both fields when both were rewritten", () =>
Effect.gen(function* () {
mockedRequest.mockReturnValue(Effect.succeed(response("{}")));
const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
yield* api.updateChangeRequest({
repository: "acme/web",
number: 7,
title: "A new title",
body: "New body.",
});
// @effect-diagnostics-next-line preferSchemaOverJson:off
expect(JSON.parse(callAt(0).body ?? "")).toEqual({
title: "A new title",
description: "New body.",
});
}),
);
it.effect("rewrites a comment where it stands, whichever kind it is", () =>
Effect.gen(function* () {
mockedRequest.mockReturnValue(Effect.succeed(response("{}")));
const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
yield* api.updateComment({
repository: "acme/web",
number: 7,
commentId: "10",
body: "Edited.",
});
expect(callAt(0)).toMatchObject({
method: "PUT",
url: "/repositories/acme/web/pullrequests/7/comments/10",
body: '{"content":{"raw":"Edited."}}',
});
}),
);
it.effect("fails the read when Bitbucket answers with something unreadable", () =>
Effect.gen(function* () {
mockedRequest.mockReturnValueOnce(
@@ -222,26 +222,12 @@ export class BitbucketPullRequestApi extends Context.Service<
readonly mergeMethod?: PullRequestMergeMethod;
}) => Effect.Effect<void, BitbucketPullRequestApiError>;
readonly updateChangeRequest: (input: {
readonly repository: string;
readonly number: number;
readonly title?: string | undefined;
readonly body?: string | undefined;
}) => Effect.Effect<void, BitbucketPullRequestApiError>;
readonly comment: (input: {
readonly repository: string;
readonly number: number;
readonly body: string;
}) => Effect.Effect<void, BitbucketPullRequestApiError>;
readonly updateComment: (input: {
readonly repository: string;
readonly number: number;
readonly commentId: string;
readonly body: string;
}) => Effect.Effect<void, BitbucketPullRequestApiError>;
readonly submitReview: (input: {
readonly repository: string;
readonly number: number;
@@ -715,24 +701,6 @@ export const make = Effect.gen(function* () {
.pipe(Effect.asVoid);
}),
updateChangeRequest: (input) =>
withRepository(input.repository, (path) =>
// Only the words this call rewrites travel in the body: as `setReviewerRequest` above
// relies on, Bitbucket's PUT is a partial update, so any field left out is left as it
// was — sending `reviewers` back here would overwrite a change another user made to it
// between this call being issued and the request landing.
bitbucket
.request({
method: "PUT",
url: `${path}/pullrequests/${input.number}`,
body: JSON.stringify({
...(input.title === undefined ? {} : { title: input.title }),
...(input.body === undefined ? {} : { description: input.body }),
}),
})
.pipe(Effect.asVoid),
),
comment: (input) =>
withRepository(input.repository, (path) =>
bitbucket
@@ -745,21 +713,6 @@ export const make = Effect.gen(function* () {
.pipe(Effect.asVoid),
),
updateComment: (input) =>
withRepository(input.repository, (path) =>
bitbucket
.request({
// Bitbucket keeps a pull request's remarks and its line comments in the one
// collection, so this endpoint rewrites either kind.
method: "PUT",
url: `${path}/pullrequests/${input.number}/comments/${encodeURIComponent(
input.commentId,
)}`,
body: JSON.stringify({ content: { raw: input.body } }),
})
.pipe(Effect.asVoid),
),
submitReview: (input) =>
withRepository(input.repository, (path) =>
Effect.gen(function* () {
@@ -19,9 +19,6 @@ const CAPABILITIES: PullRequestCapabilities = {
actions: ["merge", "close"],
mergeMethods: ["merge", "squash", "rebase"],
search: true,
// Bitbucket Cloud's API exposes no reaction on a pull request or on a comment, so none is
// read and none is offered.
reactions: false,
review: {
inlineComment: true,
reply: true,
@@ -29,7 +26,6 @@ const CAPABILITIES: PullRequestCapabilities = {
verdicts: ["comment", "approve", "request-changes"],
},
reviewers: { request: true, listCandidates: true },
edit: { changeRequest: true, comment: true },
};
/**
@@ -253,31 +249,11 @@ export const make = Effect.gen(function* () {
})
.pipe(Effect.mapError(fail("runAction"))),
updateChangeRequest: (input) =>
api
.updateChangeRequest({
repository: input.repository,
number: input.number,
title: input.title,
body: input.body,
})
.pipe(Effect.mapError(fail("updateChangeRequest"))),
comment: (input) =>
api
.comment({ repository: input.repository, number: input.number, body: input.body })
.pipe(Effect.mapError(fail("comment"))),
updateComment: (input) =>
api
.updateComment({
repository: input.repository,
number: input.number,
commentId: input.commentId,
body: input.body,
})
.pipe(Effect.mapError(fail("updateComment"))),
submitReview: (input) =>
api
.submitReview({
@@ -299,17 +275,6 @@ export const make = Effect.gen(function* () {
})
.pipe(Effect.mapError(fail("replyToThread"))),
// Never called: `capabilities.reactions` is false, and the service refuses without it.
setReaction: () =>
Effect.fail(
new PullRequestProviderError({
provider: "bitbucket",
operation: "setReaction",
reason: "failed",
detail: "Bitbucket does not support reactions.",
}),
),
setThreadResolution: (input) =>
api
.setCommentResolution({
@@ -5,7 +5,6 @@ import { ChildProcessSpawner } from "effect/unstable/process";
import * as GitHubCli from "../sourceControl/GitHubCli.ts";
import * as GitHubPullRequestCli from "./GitHubPullRequestCli.ts";
import { BASE_COMPARISON_GRAPHQL_QUERY } from "./gitHubPullRequestJson.ts";
const mockedExecute = vi.fn<GitHubCli.GitHubCli["Service"]["execute"]>();
@@ -552,206 +551,6 @@ layer("GitHubPullRequestCli.layer", (it) => {
}),
);
it.effect("carries the further narrowings into the search as qualifiers", () =>
Effect.gen(function* () {
mockedExecute.mockReturnValue(Effect.succeed(output("[]")));
const cli = yield* GitHubPullRequestCli.GitHubPullRequestCli;
yield* cli.listPullRequests({
cwd: "/w",
repository: "acme/web",
host: "github.com",
state: "open",
involvement: "all",
viewer: "bilal",
limit: 10,
filters: {
draft: "hide",
review: "changes-requested",
checks: "failing",
labels: [["needs design"], ['quo"te']],
excludedLabels: ["wip"],
author: "octocat",
},
});
// Quotes around anything a reader typed, and the one character that could end a quoted
// value early dropped rather than escaped.
expect(searchOfCall(0)).toBe(
'label:"needs design" label:"quote" -label:"wip" author:"octocat" draft:false ' +
"review:changes_requested status:failure sort:updated-desc",
);
}),
);
it.effect('resolves an author filter of "me" to the viewer, not the literal word', () =>
Effect.gen(function* () {
mockedExecute.mockReturnValue(Effect.succeed(output("[]")));
const cli = yield* GitHubPullRequestCli.GitHubPullRequestCli;
yield* cli.listPullRequests({
cwd: "/w",
repository: "acme/web",
host: "github.com",
state: "open",
involvement: "all",
viewer: "bilal",
limit: 10,
filters: { author: "me" },
});
expect(searchOfCall(0)).toBe('author:"bilal" sort:updated-desc');
}),
);
it.effect("sends one label qualifier per group, its names joined the way GitHub ors them", () =>
Effect.gen(function* () {
mockedExecute.mockReturnValue(Effect.succeed(output("[]")));
const cli = yield* GitHubPullRequestCli.GitHubPullRequestCli;
yield* cli.listPullRequests({
cwd: "/w",
repository: "acme/web",
host: "github.com",
state: "open",
involvement: "all",
viewer: "bilal",
limit: 10,
filters: { labels: [["size:S", "size:XS"], ["bug"]] },
});
// One qualifier satisfied by either size, and a second one that must hold as well.
expect(searchOfCall(0)).toBe('label:"size:S","size:XS" label:"bug" sort:updated-desc');
expect(callAt(0).args).toContain('label:"size:S","size:XS" label:"bug" sort:updated-desc');
}),
);
it.effect(
"falls back for a repository the index does not cover under a checks filter, keeping only the matching rows",
() =>
Effect.gen(function* () {
mockedExecute.mockReturnValueOnce(Effect.succeed(output("[]")));
mockedExecute.mockReturnValueOnce(
Effect.succeed(
output(
pullRequests(2, 1, (number) => ({
statusCheckRollup:
number === 1
? [{ name: "lint", status: "COMPLETED", conclusion: "SUCCESS" }]
: [{ name: "test", status: "COMPLETED", conclusion: "FAILURE" }],
})),
),
),
);
const cli = yield* GitHubPullRequestCli.GitHubPullRequestCli;
const batch = yield* cli.listPullRequests({
cwd: "/w",
repository: "acme/web",
host: "github.com",
state: "open",
involvement: "all",
viewer: "bilal",
limit: 10,
filters: { checks: "passing" },
});
// The fallback's rows carry `checksState` exactly as a search's rows do, so `checks` is
// now a filter the fallback judges itself, the same as `draft`: an empty search answer
// under it is still ambiguous, and the row picked out afterwards is the one whose own
// `checksState` reads "passing".
expect(searchOfCall(1)).toBeUndefined();
assert.deepStrictEqual(
batch.items.map((item) => item.number),
[1],
);
}),
);
it.effect("fails a checks filter for a row whose checks are still pending", () =>
Effect.gen(function* () {
mockedExecute.mockReturnValueOnce(Effect.succeed(output("[]")));
mockedExecute.mockReturnValueOnce(
Effect.succeed(
output(
pullRequests(1, 1, () => ({
statusCheckRollup: [{ name: "build", status: "IN_PROGRESS" }],
})),
),
),
);
const cli = yield* GitHubPullRequestCli.GitHubPullRequestCli;
const batch = yield* cli.listPullRequests({
cwd: "/w",
repository: "acme/web",
host: "github.com",
state: "open",
involvement: "all",
viewer: "bilal",
limit: 10,
filters: { checks: "passing" },
});
// Pending equals neither "passing" nor "failing", so it satisfies neither filter value —
// the same row would also be dropped by `checks: "failing"`.
assert.deepStrictEqual(batch.items, []);
}),
);
it.effect(
"falls back for a repository the index does not cover even under a judgeable filter",
() =>
Effect.gen(function* () {
mockedExecute.mockReturnValueOnce(Effect.succeed(output("[]")));
mockedExecute.mockReturnValueOnce(
Effect.succeed(output(pullRequests(2, 1, (number) => ({ isDraft: number === 1 })))),
);
const cli = yield* GitHubPullRequestCli.GitHubPullRequestCli;
const batch = yield* cli.listPullRequests({
cwd: "/w",
repository: "acme/web",
host: "github.com",
state: "open",
involvement: "all",
viewer: "bilal",
limit: 10,
filters: { draft: "hide" },
});
// `draft` is a filter the fallback can judge over its own rows just as search judges it,
// so an empty search answer under it alone is still ambiguous between "nothing matches"
// and "this repository is not indexed" — and the fallback applies the filter itself,
// keeping only the non-draft row.
expect(searchOfCall(1)).toBeUndefined();
expect(batch.items.map((item) => item.number)).toEqual([2]);
}),
);
it.effect("carries the further narrowings into a batched search", () =>
Effect.gen(function* () {
mockedExecute.mockReturnValue(Effect.succeed(searchPage([])));
const cli = yield* GitHubPullRequestCli.GitHubPullRequestCli;
yield* cli.searchPullRequests({
cwd: "/w",
host: "github.com",
repositories: ["acme/web"],
state: "open",
involvement: "all",
viewer: "bilal",
limit: 10,
filters: { draft: "only", review: "none", labels: [["bug"]] },
});
assert.strictEqual(
searchQueryOfCall(0),
'is:pr is:open label:"bug" draft:true review:none sort:updated-desc repo:acme/web',
);
}),
);
it.effect("quotes a search, so it cannot add a qualifier or a flag of its own", () =>
Effect.gen(function* () {
mockedExecute.mockReturnValue(Effect.succeed(output("[]")));
@@ -1020,40 +819,6 @@ layer("GitHubPullRequestCli.layer", (it) => {
}),
);
it.effect("updates a stale branch with a merge commit unless asked to rebase", () =>
Effect.gen(function* () {
mockedExecute.mockReturnValue(Effect.succeed(output("")));
const cli = yield* GitHubPullRequestCli.GitHubPullRequestCli;
yield* cli.runPullRequestAction({
cwd: "/w",
repository: "acme/web",
host: "github.com",
number: 7,
action: "update-branch",
});
// GitHub's own default, and `gh`'s: a merge commit unless the rebase flag says otherwise.
expect(callAt(0).args).toEqual(["pr", "update-branch", "7", "--repo", "github.com/acme/web"]);
yield* cli.runPullRequestAction({
cwd: "/w",
repository: "acme/web",
host: "github.com",
number: 7,
action: "update-branch",
updateMethod: "rebase",
});
expect(callAt(1).args).toEqual([
"pr",
"update-branch",
"7",
"--repo",
"github.com/acme/web",
"--rebase",
]);
}),
);
it.effect("merges with the strategy it was asked for", () =>
Effect.gen(function* () {
mockedExecute.mockReturnValue(Effect.succeed(output("")));
@@ -1079,74 +844,6 @@ layer("GitHubPullRequestCli.layer", (it) => {
}),
);
it.effect("arms auto-merge with the same strategy a merge would have used", () =>
Effect.gen(function* () {
mockedExecute.mockReturnValue(Effect.succeed(output("")));
const cli = yield* GitHubPullRequestCli.GitHubPullRequestCli;
yield* cli.runPullRequestAction({
cwd: "/w",
repository: "acme/web",
host: "github.com",
number: 7,
action: "enable-auto-merge",
mergeMethod: "squash",
});
expect(callAt(0).args).toEqual([
"pr",
"merge",
"7",
"--repo",
"github.com/acme/web",
"--auto",
"--squash",
]);
// No strategy asked for is GitHub's own default, exactly as it is for a merge now.
yield* cli.runPullRequestAction({
cwd: "/w",
repository: "acme/web",
host: "github.com",
number: 7,
action: "enable-auto-merge",
});
expect(callAt(1).args).toEqual([
"pr",
"merge",
"7",
"--repo",
"github.com/acme/web",
"--auto",
"--merge",
]);
}),
);
it.effect("takes auto-merge back off without naming a strategy", () =>
Effect.gen(function* () {
mockedExecute.mockReturnValue(Effect.succeed(output("")));
const cli = yield* GitHubPullRequestCli.GitHubPullRequestCli;
yield* cli.runPullRequestAction({
cwd: "/w",
repository: "acme/web",
host: "github.com",
number: 7,
action: "disable-auto-merge",
mergeMethod: "squash",
});
expect(callAt(0).args).toEqual([
"pr",
"merge",
"7",
"--repo",
"github.com/acme/web",
"--disable-auto",
]);
}),
);
it.effect("returns a pull request to draft by undoing ready", () =>
Effect.gen(function* () {
mockedExecute.mockReturnValue(Effect.succeed(output("")));
@@ -1709,279 +1406,6 @@ layer("GitHubPullRequestCli.layer", (it) => {
}),
);
it.effect("confirms a given subject belongs to the named pull request, then reacts to it", () =>
Effect.gen(function* () {
mockedExecute.mockReturnValueOnce(
Effect.succeed(
output(
// @effect-diagnostics-next-line preferSchemaOverJson:off
JSON.stringify({
data: {
repository: { pullRequest: { id: "PR_kwDOA" } },
node: { id: "IC_1", pullRequest: { id: "PR_kwDOA" } },
},
}),
),
),
);
mockedExecute.mockReturnValueOnce(Effect.succeed(output("{}")));
const cli = yield* GitHubPullRequestCli.GitHubPullRequestCli;
yield* cli.setReaction({
cwd: "/w",
repository: "acme/web",
host: "github.com",
number: 7,
subjectId: "IC_1",
content: "heart",
reacted: true,
});
assert.strictEqual(mockedExecute.mock.calls.length, 2);
const scopeCheck = callAt(0).args;
expect(scopeCheck).toContain("owner=acme");
expect(scopeCheck).toContain("name=web");
expect(scopeCheck).toContain("number=7");
expect(scopeCheck).toContain("subjectId=IC_1");
// @effect-diagnostics-next-line preferSchemaOverJson:off
const request = JSON.parse(callAt(1).stdin ?? "") as {
query: string;
variables: Record<string, string>;
};
expect(request.query).toContain("addReaction(");
expect(request.variables).toEqual({ subjectId: "IC_1", content: "HEART" });
}),
);
it.effect("refuses a given subject that belongs to a different pull request", () =>
Effect.gen(function* () {
mockedExecute.mockReturnValueOnce(
Effect.succeed(
output(
// @effect-diagnostics-next-line preferSchemaOverJson:off
JSON.stringify({
data: {
repository: { pullRequest: { id: "PR_thisOne" } },
// A comment on pull request #99 of a different repository, named as though it
// belonged to #7 here.
node: { id: "IC_99", pullRequest: { id: "PR_someOtherOne" } },
},
}),
),
),
);
const cli = yield* GitHubPullRequestCli.GitHubPullRequestCli;
const error = yield* Effect.flip(
cli.setReaction({
cwd: "/w",
repository: "acme/web",
host: "github.com",
number: 7,
subjectId: "IC_99",
content: "heart",
reacted: true,
}),
);
assert.strictEqual(error._tag, "GitHubSubjectScopeError");
// Refused before any mutation was sent.
assert.strictEqual(mockedExecute.mock.calls.length, 1);
}),
);
it.effect("looks up the pull request's own node id when no subject was given", () =>
Effect.gen(function* () {
mockedExecute.mockReturnValueOnce(
Effect.succeed(
output(
// @effect-diagnostics-next-line preferSchemaOverJson:off
JSON.stringify({ data: { repository: { pullRequest: { id: "PR_kwDOA" } } } }),
),
),
);
mockedExecute.mockReturnValueOnce(Effect.succeed(output("{}")));
const cli = yield* GitHubPullRequestCli.GitHubPullRequestCli;
yield* cli.setReaction({
cwd: "/w",
repository: "acme/web",
host: "github.com",
number: 7,
content: "rocket",
reacted: true,
});
assert.strictEqual(mockedExecute.mock.calls.length, 2);
const lookup = callAt(0).args;
expect(lookup).toContain("owner=acme");
expect(lookup).toContain("name=web");
expect(lookup).toContain("number=7");
// @effect-diagnostics-next-line preferSchemaOverJson:off
const request = JSON.parse(callAt(1).stdin ?? "") as {
query: string;
variables: Record<string, string>;
};
expect(request.query).toContain("addReaction(");
expect(request.variables).toEqual({ subjectId: "PR_kwDOA", content: "ROCKET" });
}),
);
it.effect("takes a reaction back through the remove mutation", () =>
Effect.gen(function* () {
mockedExecute.mockReturnValueOnce(
Effect.succeed(
output(
// @effect-diagnostics-next-line preferSchemaOverJson:off
JSON.stringify({
data: {
repository: { pullRequest: { id: "PR_kwDOA" } },
node: { id: "IC_1", pullRequest: { id: "PR_kwDOA" } },
},
}),
),
),
);
mockedExecute.mockReturnValueOnce(Effect.succeed(output("{}")));
const cli = yield* GitHubPullRequestCli.GitHubPullRequestCli;
yield* cli.setReaction({
cwd: "/w",
repository: "acme/web",
host: "github.com",
number: 7,
subjectId: "IC_1",
content: "heart",
reacted: false,
});
// @effect-diagnostics-next-line preferSchemaOverJson:off
const request = JSON.parse(callAt(1).stdin ?? "") as { query: string };
expect(request.query).toContain("removeReaction(");
}),
);
it.effect("rewrites only the words a request named", () =>
Effect.gen(function* () {
mockedExecute.mockReturnValue(
Effect.succeed(
output(
// @effect-diagnostics-next-line preferSchemaOverJson:off
JSON.stringify({ data: { repository: { pullRequest: { id: "PR_kwDOA" } } } }),
),
),
);
const cli = yield* GitHubPullRequestCli.GitHubPullRequestCli;
const rewrite = (fields: { readonly title?: string; readonly body?: string }) =>
cli.updatePullRequest({
cwd: "/w",
repository: "acme/web",
host: "github.com",
number: 7,
...fields,
});
yield* rewrite({ title: "A better title" });
yield* rewrite({ body: "A better description." });
yield* rewrite({ title: "Both", body: "at once." });
// Each rewrite looks the pull request's node id up first, then mutates.
const variablesAt = (index: number) =>
(JSON.parse(callAt(index).stdin ?? "") as { variables: Record<string, string> }).variables;
expect(variablesAt(1)).toEqual({ pullRequestId: "PR_kwDOA", title: "A better title" });
expect(variablesAt(3)).toEqual({
pullRequestId: "PR_kwDOA",
body: "A better description.",
});
expect(variablesAt(5)).toEqual({
pullRequestId: "PR_kwDOA",
title: "Both",
body: "at once.",
});
// The reader's own words, so they travel the way every other body does.
expect(callAt(5).args.join(" ")).not.toContain("at once.");
}),
);
it.effect("rewrites a remark through the mutation its kind needs", () =>
Effect.gen(function* () {
mockedExecute.mockReturnValue(
Effect.succeed(
output(
// @effect-diagnostics-next-line preferSchemaOverJson:off
JSON.stringify({
data: {
repository: { pullRequest: { id: "PR_kwDOA" } },
node: { id: "IC_1", pullRequest: { id: "PR_kwDOA" } },
},
}),
),
),
);
const cli = yield* GitHubPullRequestCli.GitHubPullRequestCli;
const rewrite = (kind: "issue-comment" | "review-comment") =>
cli.updateComment({
cwd: "/w",
repository: "acme/web",
host: "github.com",
number: 7,
commentId: "IC_1",
kind,
body: "Reworded.",
});
yield* rewrite("issue-comment");
yield* rewrite("review-comment");
const parse = (index: number) =>
JSON.parse(callAt(index).stdin ?? "") as {
query: string;
variables: Record<string, string>;
};
expect(callAt(0).args).toContain("subjectId=IC_1");
expect(parse(1).query).toContain("updateIssueComment(");
expect(parse(1).variables).toEqual({ commentId: "IC_1", body: "Reworded." });
expect(parse(3).query).toContain("updatePullRequestReviewComment(");
expect(parse(3).variables).toEqual({ commentId: "IC_1", body: "Reworded." });
}),
);
it.effect("refuses a comment that belongs to a different pull request", () =>
Effect.gen(function* () {
mockedExecute.mockReturnValueOnce(
Effect.succeed(
output(
// @effect-diagnostics-next-line preferSchemaOverJson:off
JSON.stringify({
data: {
repository: { pullRequest: { id: "PR_thisOne" } },
node: { id: "IC_99", pullRequest: { id: "PR_someOtherOne" } },
},
}),
),
),
);
const cli = yield* GitHubPullRequestCli.GitHubPullRequestCli;
const error = yield* Effect.flip(
cli.updateComment({
cwd: "/w",
repository: "acme/web",
host: "github.com",
number: 7,
commentId: "IC_99",
kind: "issue-comment",
body: "Reworded.",
}),
);
assert.strictEqual(error._tag, "GitHubSubjectScopeError");
expect(error.message).toContain("updateComment");
// Refused before any mutation was sent.
assert.strictEqual(mockedExecute.mock.calls.length, 1);
}),
);
it.effect("fails the read when gh returns something unreadable", () =>
Effect.gen(function* () {
mockedExecute.mockReturnValueOnce(Effect.succeed(output('{"message":"not found"}')));
@@ -2048,7 +1472,7 @@ layer("GitHubPullRequestCli.layer", (it) => {
expect(detail.body).toBe("Core body");
expect(activity.author?.login).toBe("octocat");
expect(callAt(0).args.at(-1)).toBe(
"number,title,url,author,headRefName,baseRefName,state,isDraft,mergeable,reviewDecision,additions,deletions,createdAt,updatedAt,mergedAt,reviewRequests,labels,statusCheckRollup,body,changedFiles,closedAt,headRepositoryOwner,autoMergeRequest",
"number,title,url,author,headRefName,baseRefName,state,isDraft,mergeable,additions,deletions,createdAt,updatedAt,mergedAt,reviewRequests,labels,body,changedFiles,closedAt,statusCheckRollup",
);
expect(callAt(1).args.at(-1)).toBe("author,comments,reviews,commits");
}),
@@ -2210,58 +1634,6 @@ layer("GitHubPullRequestCli.layer", (it) => {
}),
);
it.effect("sends the base comparison's variables as gh flags, not as bare words", () =>
Effect.gen(function* () {
mockedExecute.mockReturnValue(
Effect.succeed(
output(
// @effect-diagnostics-next-line preferSchemaOverJson:off
JSON.stringify({
data: {
repository: {
pullRequest: {
viewerCanUpdateBranch: true,
baseRef: { compare: { behindBy: 4 } },
},
},
},
}),
),
),
);
const cli = yield* GitHubPullRequestCli.GitHubPullRequestCli;
const comparison = yield* cli.getPullRequestBaseComparison({
cwd: "/w",
repository: "acme/web",
host: "github.com",
number: 7,
headRef: "fork:feat/page",
});
// The tuples are flattened straight into argv, so a variable without its flag is a
// positional argument gh refuses outright.
const args = callAt(0).args;
expect(args).toEqual([
"api",
"graphql",
"--hostname",
"github.com",
"-f",
"owner=acme",
"-f",
"name=web",
"-F",
"number=7",
"-f",
"headRef=fork:feat/page",
"-f",
`query=${BASE_COMPARISON_GRAPHQL_QUERY}`,
]);
expect(comparison).toEqual({ behindBy: 4, viewerCanUpdate: true });
}),
);
it.effect("reads the viewer's role off the same call as the merge settings", () =>
Effect.gen(function* () {
mockedExecute.mockReturnValue(
@@ -3,29 +3,22 @@ import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Result from "effect/Result";
import * as Schema from "effect/Schema";
import {
resolvePullRequestAuthorFilter,
type PullRequestAction,
type PullRequestActor,
type PullRequestInvolvement,
type PullRequestListFilters,
type PullRequestListState,
type PullRequestMergeMethod,
type PullRequestOmittedFileStat,
type PullRequestReaction,
type PullRequestReactionContent,
type PullRequestReviewCommentDraft,
type PullRequestReviewVerdict,
type PullRequestReviewerCandidateList,
type PullRequestReviewerKind,
type PullRequestThreadComment,
type PullRequestUpdateMethod,
import type {
PullRequestAction,
PullRequestActor,
PullRequestInvolvement,
PullRequestListState,
PullRequestMergeMethod,
PullRequestReviewCommentDraft,
PullRequestReviewVerdict,
PullRequestReviewerCandidateList,
PullRequestReviewerKind,
PullRequestThreadComment,
} from "@t3tools/contracts";
import * as GitHubCli from "../sourceControl/GitHubCli.ts";
import {
ACTOR_AVATARS_GRAPHQL_QUERY,
ADD_REACTION_GRAPHQL_MUTATION,
buildReviewSubmissionJson,
buildReviewerRequestJson,
decodeActorAvatarsJson,
@@ -33,13 +26,10 @@ import {
decodePullRequestDetailJson,
decodePullRequestFilesJson,
decodePullRequestListJson,
decodePullRequestNodeIdJson,
decodePullRequestSearchJson,
decodePullRequestStatsJson,
decodeReactionSubjectScopeJson,
decodeRepositoryAccessJson,
decodeReviewerCandidatesJson,
decodeReviewDismissalsJson,
decodeReviewThreadCommentsJson,
decodeReviewThreadsJson,
buildPullRequestStatsGraphQlQuery,
@@ -47,29 +37,18 @@ import {
pullRequestSearchGraphQlQuery,
PULL_REQUEST_SEARCH_MAX_ROWS,
PULL_REQUEST_ACTIVITY_JSON_FIELDS,
BASE_COMPARISON_GRAPHQL_QUERY,
decodeBaseComparisonJson,
PULL_REQUEST_DETAIL_JSON_FIELDS,
PULL_REQUEST_LIST_JSON_FIELDS,
PULL_REQUEST_NODE_ID_GRAPHQL_QUERY,
REACTION_SUBJECT_PULL_REQUEST_GRAPHQL_QUERY,
REMOVE_REACTION_GRAPHQL_MUTATION,
gitHubReactionContent,
REPOSITORY_ACCESS_JSON_FIELDS,
RESOLVE_REVIEW_THREAD_GRAPHQL_MUTATION,
REVIEWER_CANDIDATES_GRAPHQL_QUERY,
REVIEW_THREAD_COMMENTS_GRAPHQL_QUERY,
REVIEW_DISMISSALS_GRAPHQL_QUERY,
REVIEW_THREAD_REPLY_GRAPHQL_MUTATION,
REVIEW_THREADS_GRAPHQL_QUERY,
reviewThreadConversation,
UNRESOLVE_REVIEW_THREAD_GRAPHQL_MUTATION,
UPDATE_ISSUE_COMMENT_GRAPHQL_MUTATION,
UPDATE_PULL_REQUEST_GRAPHQL_MUTATION,
UPDATE_REVIEW_COMMENT_GRAPHQL_MUTATION,
VIEWER_PERMISSIONS_GRAPHQL_QUERY,
decodeViewerPermissionsJson,
type GitHubBaseComparison,
type GitHubPullRequestDetail,
type GitHubPullRequestActivity,
type GitHubPullRequestListItem,
@@ -220,24 +199,6 @@ export class GitHubRepositorySelectorError extends Schema.TaggedErrorClass<GitHu
}
}
/** Not a decode failure: the reader named a subject this pull request never handed out. */
export class GitHubSubjectScopeError extends Schema.TaggedErrorClass<GitHubSubjectScopeError>()(
"GitHubSubjectScopeError",
{
command: Schema.Literal("gh"),
cwd: Schema.String,
operation: Schema.String,
},
) {
get detail(): string {
return "The named subject did not belong to the named pull request.";
}
override get message(): string {
return `GitHub CLI failed in ${this.operation}: ${this.detail}`;
}
}
export type GitHubPullRequestCliError =
| GitHubCli.GitHubCliError
| GitHubPullRequestReadError
@@ -246,7 +207,6 @@ export type GitHubPullRequestCliError =
| GitHubDiffRevisionsUnavailableError
| GitHubDiffFileContentsUnavailableError
| GitHubRepositorySelectorError
| GitHubSubjectScopeError
| GitHubViewerLoginUnavailableError;
/** A large pull request can produce a multi-megabyte patch; past this it is truncated. */
@@ -310,8 +270,6 @@ export interface GitHubPullRequestDiffSlice {
readonly truncated: boolean;
/** Where the next slice starts, or null once the patch is whole. */
readonly nextCursor: string | null;
/** GitHub's own counts for the files whose hunks it withheld from this slice. */
readonly omittedFileStats?: ReadonlyArray<PullRequestOmittedFileStat>;
}
export class GitHubPullRequestCli extends Context.Service<
@@ -333,8 +291,6 @@ export class GitHubPullRequestCli extends Context.Service<
readonly query?: string | undefined;
/** Where to carry on from, as a `updated:` qualifier on the same search. */
readonly cursor?: ProviderListCursor | undefined;
/** Further narrowings, as qualifiers on the search and as a local pass on the fallback. */
readonly filters?: PullRequestListFilters | undefined;
}) => Effect.Effect<GitHubPullRequestListBatch, GitHubPullRequestCliError>;
/**
@@ -353,7 +309,6 @@ export class GitHubPullRequestCli extends Context.Service<
readonly limit: number;
readonly query?: string | undefined;
readonly cursor?: ProviderListCursor | undefined;
readonly filters?: PullRequestListFilters | undefined;
}) => Effect.Effect<GitHubPullRequestSearchBatch, GitHubPullRequestCliError>;
/** The line counts the search leaves out, for rows already on the page. */
@@ -373,20 +328,6 @@ export class GitHubPullRequestCli extends Context.Service<
readonly number: number;
}) => Effect.Effect<GitHubPullRequestDetail, GitHubPullRequestCliError>;
/**
* How far the branch trails its base, and whether this viewer may update it. Its own read
* because the comparison needs the head ref the detail answers with — a fork's branch is not
* addressable in the base repository by name alone.
*/
readonly getPullRequestBaseComparison: (input: {
readonly cwd: string;
readonly repository: string;
readonly host: string;
readonly number: number;
/** Qualified `owner:branch`, which is the only form a fork's head resolves under. */
readonly headRef: string;
}) => Effect.Effect<GitHubBaseComparison, GitHubPullRequestCliError>;
readonly getPullRequestActivity: (input: {
readonly cwd: string;
readonly repository: string;
@@ -477,7 +418,6 @@ export class GitHubPullRequestCli extends Context.Service<
readonly number: number;
readonly action: PullRequestAction;
readonly mergeMethod?: PullRequestMergeMethod;
readonly updateMethod?: PullRequestUpdateMethod;
}) => Effect.Effect<void, GitHubPullRequestCliError>;
readonly commentOnPullRequest: (input: {
@@ -513,47 +453,6 @@ export class GitHubPullRequestCli extends Context.Service<
readonly threadId: string;
readonly resolved: boolean;
}) => Effect.Effect<void, GitHubPullRequestCliError>;
/**
* Adds a reaction to a remark, or takes it back. `subjectId` is any node GitHub calls
* reactable — a comment, a review, or the pull request itself, which is looked up here
* because nothing in the conversation names it. A given `subjectId` is confirmed to belong
* to this pull request before the mutation runs, since nothing else ties the two together.
*/
readonly setReaction: (input: {
readonly cwd: string;
readonly repository: string;
readonly host: string;
readonly number: number;
readonly subjectId?: string | undefined;
readonly content: PullRequestReactionContent;
readonly reacted: boolean;
}) => Effect.Effect<void, GitHubPullRequestCliError>;
/** Rewrites the pull request's own words, leaving whichever of the two was not given. */
readonly updatePullRequest: (input: {
readonly cwd: string;
readonly repository: string;
readonly host: string;
readonly number: number;
readonly title?: string | undefined;
readonly body?: string | undefined;
}) => Effect.Effect<void, GitHubPullRequestCliError>;
/**
* Rewrites a remark. `commentId` is trusted to be whatever node it names, so it is confirmed
* to belong to this pull request before the mutation runs, the way a reaction subject is.
* Whether the remark is the reader's to rewrite is GitHub's own answer, not one asked here.
*/
readonly updateComment: (input: {
readonly cwd: string;
readonly repository: string;
readonly host: string;
readonly number: number;
readonly commentId: string;
readonly kind: "issue-comment" | "review-comment";
readonly body: string;
}) => Effect.Effect<void, GitHubPullRequestCliError>;
}
>()("t3/pullRequest/GitHubPullRequestCli") {}
@@ -602,76 +501,6 @@ function searchPhrase(query: string): string {
return `"${query.replaceAll("\\", "\\\\").replaceAll('"', '\\"')}"`;
}
/** GitHub's own spelling of a review state, which is not the contract's. */
const REVIEW_QUALIFIERS = {
approved: "approved",
"changes-requested": "changes_requested",
"review-required": "required",
none: "none",
} as const;
/**
* The extra narrowings as GitHub search qualifiers. Values a reader typed are quoted, and the
* one character that could end the quoted value early is dropped rather than escaped: no GitHub
* label or login holds a double quote, so there is nothing to preserve and everything to lose.
*/
function qualifierValue(value: string): string {
return `"${value.replaceAll('"', "").trim()}"`;
}
function filterQualifiers(
filters: PullRequestListFilters | undefined,
viewer: string,
): ReadonlyArray<string> {
if (filters === undefined) return [];
return [
// One qualifier per group, its names joined by commas — GitHub's own OR.
...(filters.labels ?? []).flatMap((group) =>
group.length === 0 ? [] : [`label:${group.map(qualifierValue).join(",")}`],
),
...(filters.excludedLabels ?? []).map((label) => `-label:${qualifierValue(label)}`),
...(filters.author === undefined
? []
: [`author:${qualifierValue(resolvePullRequestAuthorFilter(filters.author, viewer))}`]),
...(filters.draft === undefined ? [] : [`draft:${filters.draft === "only"}`]),
...(filters.review === undefined ? [] : [`review:${REVIEW_QUALIFIERS[filters.review]}`]),
...(filters.checks === undefined
? []
: [`status:${filters.checks === "passing" ? "success" : "failure"}`]),
];
}
/**
* The same narrowings over a row that has already arrived, for the search-free fallback. Every
* listed row now carries its own `checksState`, so `checks` is judged the way `review` is: by
* equality against the row's field. Unlike `review`, `checks` has no `"none"` value to catch an
* absent state on purpose — a row with no checks configured, or whose checks are still `pending`,
* equals neither `"passing"` nor `"failing"` and so fails both, the same as a row search would
* not have surfaced for `status:success` or `status:failure`.
*/
function matchesFilters(
item: GitHubPullRequestListItem,
filters: PullRequestListFilters | undefined,
viewer: string,
): boolean {
if (filters === undefined) return true;
const labels = item.labels.map((label) => label.name.trim().toLowerCase());
const holds = (label: string) => labels.includes(label.trim().toLowerCase());
return (
(filters.draft === undefined || item.isDraft === (filters.draft === "only")) &&
(filters.review === undefined ||
(filters.review === "none"
? item.reviewDecision === null
: item.reviewDecision === filters.review)) &&
(filters.checks === undefined || item.checksState === filters.checks) &&
(filters.labels === undefined || filters.labels.every((group) => group.some(holds))) &&
(filters.excludedLabels === undefined || !filters.excludedLabels.some(holds)) &&
(filters.author === undefined ||
item.author?.login.toLowerCase() ===
resolvePullRequestAuthorFilter(filters.author, viewer).toLowerCase())
);
}
function involvementArgs(input: {
readonly state: PullRequestListState;
readonly involvement: PullRequestInvolvement;
@@ -684,7 +513,6 @@ function involvementArgs(input: {
* cannot use search at all and takes whatever order `gh pr list` answers in.
*/
readonly sorted: boolean;
readonly filters?: PullRequestListFilters | undefined;
}): ReadonlyArray<string> {
// `--state closed` includes merged pull requests, so the Closed tab additionally excludes
// them through search; `--author` and `review-requested:` are GitHub's own filters. `gh`
@@ -703,7 +531,6 @@ function involvementArgs(input: {
// sharing one instant are ordinary and the caller drops the ones it has already sent —
// asking for strictly older would lose the rest of them instead.
...(input.cursor === undefined ? [] : [`updated:<=${input.cursor.updatedBefore}`]),
...filterQualifiers(input.filters, input.viewer),
// `gh pr list` answers newest-created first, which is not the order the page reads rows in
// and not an order a continuation can carry on from: a change request opened last year and
// touched this morning belongs at the top of the list and at the front of the first slice.
@@ -723,7 +550,6 @@ function matchesUnsortedListing(
readonly state: PullRequestListState;
readonly involvement: PullRequestInvolvement;
readonly viewer: string;
readonly filters?: PullRequestListFilters | undefined;
},
): boolean {
const matchesState = input.state === "all" || item.state === input.state;
@@ -734,7 +560,7 @@ function matchesUnsortedListing(
? item.author?.login.toLowerCase() === viewer
: item.hasTeamReviewRequest ||
item.reviewRequestLogins.some((login) => login.toLowerCase() === viewer));
return matchesState && matchesInvolvement && matchesFilters(item, input.filters, input.viewer);
return matchesState && matchesInvolvement;
}
/** What a repository selector may hold before it goes into a search as itself. */
@@ -761,7 +587,6 @@ function searchQuery(input: {
readonly viewer: string;
readonly query?: string | undefined;
readonly cursor?: ProviderListCursor | undefined;
readonly filters?: PullRequestListFilters | undefined;
}): string | null {
if (input.repositories.length === 0) return null;
const repositories = input.repositories.map((repository) => repository.trim());
@@ -778,7 +603,6 @@ function searchQuery(input: {
...(query.length === 0 ? [] : [searchPhrase(query)]),
// Inclusive, and de-duplicated by the caller, for the reason the per-repository read gives.
...(input.cursor === undefined ? [] : [`updated:<=${input.cursor.updatedBefore}`]),
...filterQualifiers(input.filters, input.viewer),
// The order the page reads its rows in, and the only order a continuation can carry on from.
"sort:updated-desc",
...repositories.map((repository) => `repo:${repository}`),
@@ -797,20 +621,10 @@ function cursorVariable(cursor: string | null): readonly [string, string] {
function actionArgs(
action: PullRequestAction,
mergeMethod: PullRequestMergeMethod | undefined,
updateMethod: PullRequestUpdateMethod | undefined,
): ReadonlyArray<string> {
switch (action) {
case "merge":
return ["merge", `--${mergeMethod ?? "merge"}`];
// `--auto` arms the same command instead of running it, and still needs the strategy: GitHub
// stores the strategy with the standing instruction rather than choosing one at merge time.
case "enable-auto-merge":
return ["merge", "--auto", `--${mergeMethod ?? "merge"}`];
case "disable-auto-merge":
return ["merge", "--disable-auto"];
// `gh` updates with a merge commit unless asked to rebase, which is GitHub's own default.
case "update-branch":
return ["update-branch", ...(updateMethod === "rebase" ? ["--rebase"] : [])];
case "ready":
return ["ready"];
case "draft":
@@ -825,62 +639,6 @@ function actionArgs(
export const make = Effect.gen(function* () {
const github = yield* GitHubCli.GitHubCli;
/**
* The pull request's own node id, which is what a mutation against the pull request itself is
* addressed by: a reaction on its description, or a rewrite of its words.
*/
const pullRequestNodeId = (input: {
readonly cwd: string;
readonly repository: string;
readonly host: string;
readonly number: number;
readonly operation: string;
}) => {
const { owner, name } = parseRepositorySelector(input.repository);
return graphqlRead({
cwd: input.cwd,
host: input.host,
operation: input.operation,
variables: [
["-f", `owner=${owner}`],
["-f", `name=${name}`],
["-F", `number=${input.number}`],
],
query: PULL_REQUEST_NODE_ID_GRAPHQL_QUERY,
decode: decodePullRequestNodeIdJson,
});
};
/**
* Whether a client-given subject actually belongs to the pull request the request names. A
* subject id is trusted to be whatever node it names, and that node can hang off any pull
* request on the host — so the mutation itself would write wherever the id actually belongs,
* not wherever the request says it does, unless this confirms the two agree first.
*/
const subjectBelongsToPullRequest = (input: {
readonly cwd: string;
readonly repository: string;
readonly host: string;
readonly number: number;
readonly subjectId: string;
readonly operation: string;
}) => {
const { owner, name } = parseRepositorySelector(input.repository);
return graphqlRead({
cwd: input.cwd,
host: input.host,
operation: input.operation,
variables: [
["-f", `owner=${owner}`],
["-f", `name=${name}`],
["-F", `number=${input.number}`],
["-f", `subjectId=${input.subjectId}`],
],
query: REACTION_SUBJECT_PULL_REQUEST_GRAPHQL_QUERY,
decode: decodeReactionSubjectScopeJson,
});
};
// `gh` resolves a bare `owner/repo` against whichever host it defaults to, which is
// github.com. Naming the host makes a GitHub Enterprise repository resolve to its own
// install rather than to a same-named repository on github.com.
@@ -1038,9 +796,6 @@ export const make = Effect.gen(function* () {
patch: decoded.success.patch,
truncated: decoded.success.truncated,
nextCursor: morePages ? String(input.page + 1) : null,
...(decoded.success.omittedFileStats.length === 0
? {}
: { omittedFileStats: decoded.success.omittedFileStats }),
});
}),
);
@@ -1222,15 +977,10 @@ export const make = Effect.gen(function* () {
// repository's whole list, which is every row the reader did not search for. The fallback
// is for a repository the index does not cover, and a listing with no text to match is the
// only place an empty answer can mean that.
// Every filter is a qualifier `matchesFilters` can judge over the fallback's own rows just
// as well as search judges them over its own, so carrying them into the fallback answers
// the same read rather than a wider one. Free text is the one thing the fallback cannot
// judge locally — it lists rows, it does not search their text — so a query still rules
// the fallback out: an empty answer under one is already the answer.
const hasQuery = (input.query?.trim().length ?? 0) > 0;
const searched = (input.query?.trim().length ?? 0) > 0;
return read(true).pipe(
Effect.flatMap((batch) =>
batch.items.length === 0 && input.cursor === undefined && !hasQuery
batch.items.length === 0 && input.cursor === undefined && !searched
? read(false)
: Effect.succeed(batch),
),
@@ -1335,23 +1085,6 @@ export const make = Effect.gen(function* () {
}),
),
getPullRequestBaseComparison: (input) => {
const { owner, name } = parseRepositorySelector(input.repository);
return graphqlRead({
cwd: input.cwd,
host: input.host,
operation: "getPullRequestBaseComparison",
variables: [
["-f", `owner=${owner}`],
["-f", `name=${name}`],
["-F", `number=${input.number}`],
["-f", `headRef=${input.headRef}`],
],
query: BASE_COMPARISON_GRAPHQL_QUERY,
decode: decodeBaseComparisonJson,
});
},
getPullRequestActivity: (input) =>
github
.execute({
@@ -1483,12 +1216,8 @@ export const make = Effect.gen(function* () {
{ readonly additions: number; readonly deletions: number }
>();
let reviewers: ReadonlyArray<PullRequestActor> = [];
let reactions: GitHubReviewThreadPage["reactions"] = [];
const reactionsById = new Map<string, ReadonlyArray<PullRequestReaction>>();
let commits: GitHubReviewThreadPage["commits"] = [];
let viewer: GitHubReviewThreadPage["viewer"] = { canUpdate: true, didAuthor: false };
const dismissalsByReviewId = new Map<string, string>();
let dismissalCursor: string | null = null;
let cursor: string | null = null;
let page = 0;
do {
@@ -1500,46 +1229,14 @@ export const make = Effect.gen(function* () {
// first one already carries all of them.
if (page === 0) {
reviewers = read.reviewers;
reactions = read.reactions;
for (const [id, entry] of read.reactionsById) reactionsById.set(id, entry);
commits = read.commits;
viewer = read.viewer;
for (const [id, message] of read.dismissalsByReviewId)
dismissalsByReviewId.set(id, message);
dismissalCursor = read.nextDismissalCursor;
for (const [oid, stat] of read.commitStats) commitStats.set(oid, stat);
}
cursor = read.nextCursor;
page += 1;
} while (cursor !== null && page < REVIEW_THREAD_PAGES);
// Almost never entered: the embedded page already holds every dismissal a pull request
// ordinarily accrues. Followed so a review whose event fell past that page still finds
// its reason.
let dismissalPage = 0;
while (dismissalCursor !== null && dismissalPage < REVIEW_THREAD_PAGES) {
const read: {
readonly dismissalsByReviewId: ReadonlyMap<string, string>;
readonly nextCursor: string | null;
} = yield* graphqlRead({
cwd: input.cwd,
host: input.host,
operation: "listReviewThreadComments",
variables: [
["-f", `owner=${owner}`],
["-f", `name=${name}`],
["-F", `number=${input.number}`],
["-f", `cursor=${dismissalCursor}`],
],
query: REVIEW_DISMISSALS_GRAPHQL_QUERY,
decode: decodeReviewDismissalsJson,
});
for (const [id, message] of read.dismissalsByReviewId)
dismissalsByReviewId.set(id, message);
dismissalCursor = read.nextCursor;
dismissalPage += 1;
}
// Only the threads GitHub said were unfinished cost a request; the rest arrived whole
// with the page they were listed on.
const finished = yield* Effect.forEach(
@@ -1567,14 +1264,11 @@ export const make = Effect.gen(function* () {
const reviewThreads = finished.map((entry) => entry.thread);
return {
comments: reviewThreadConversation(reviewThreads),
dismissalsByReviewId,
reviewThreads,
// GitHub's own count of each thread, so the number the page shows is the host's even
// where a bound kept some of the words on GitHub.
commentCount: finished.reduce((total, entry) => total + entry.commentCount, 0),
truncated: cursor !== null || finished.some((entry) => entry.truncated),
reactions,
reactionsById,
reviewers,
avatarsByLogin,
commitStats,
@@ -1702,11 +1396,7 @@ export const make = Effect.gen(function* () {
},
runPullRequestAction: (input) => {
const [subcommand, ...flags] = actionArgs(
input.action,
input.mergeMethod,
input.updateMethod,
);
const [subcommand, ...flags] = actionArgs(input.action, input.mergeMethod);
return github
.execute({
cwd: input.cwd,
@@ -1777,91 +1467,6 @@ export const make = Effect.gen(function* () {
: UNRESOLVE_REVIEW_THREAD_GRAPHQL_MUTATION,
variables: { threadId: input.threadId },
}),
setReaction: (input) => {
const givenSubjectId = input.subjectId;
const subjectId =
givenSubjectId === undefined
? pullRequestNodeId({ ...input, operation: "setReaction" })
: subjectBelongsToPullRequest({
...input,
subjectId: givenSubjectId,
operation: "setReaction",
}).pipe(
Effect.flatMap((belongs) =>
belongs
? Effect.succeed(givenSubjectId)
: Effect.fail(
new GitHubSubjectScopeError({
command: "gh",
cwd: input.cwd,
operation: "setReaction",
}),
),
),
);
return subjectId.pipe(
Effect.flatMap((subjectId) =>
graphql({
cwd: input.cwd,
host: input.host,
query: input.reacted ? ADD_REACTION_GRAPHQL_MUTATION : REMOVE_REACTION_GRAPHQL_MUTATION,
variables: { subjectId, content: gitHubReactionContent(input.content) },
}),
),
);
},
updatePullRequest: (input) =>
pullRequestNodeId({ ...input, operation: "updatePullRequest" }).pipe(
Effect.flatMap((pullRequestId) =>
graphql({
cwd: input.cwd,
host: input.host,
query: UPDATE_PULL_REQUEST_GRAPHQL_MUTATION,
// A field the caller did not name is left out of the request entirely, so GitHub
// keeps the words that are there rather than being asked for an empty one.
variables: {
pullRequestId,
...(input.title === undefined ? {} : { title: input.title }),
...(input.body === undefined ? {} : { body: input.body }),
},
}),
),
),
updateComment: (input) =>
subjectBelongsToPullRequest({
cwd: input.cwd,
repository: input.repository,
host: input.host,
number: input.number,
subjectId: input.commentId,
operation: "updateComment",
}).pipe(
Effect.flatMap((belongs) =>
belongs
? Effect.succeed(input.commentId)
: Effect.fail(
new GitHubSubjectScopeError({
command: "gh",
cwd: input.cwd,
operation: "updateComment",
}),
),
),
Effect.flatMap((commentId) =>
graphql({
cwd: input.cwd,
host: input.host,
query:
input.kind === "issue-comment"
? UPDATE_ISSUE_COMMENT_GRAPHQL_MUTATION
: UPDATE_REVIEW_COMMENT_GRAPHQL_MUTATION,
variables: { commentId, body: input.body },
}),
),
),
});
});
@@ -1,7 +1,6 @@
import { describe, expect, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import type { PullRequestReaction } from "@t3tools/contracts";
import * as GitHubPullRequestCli from "./GitHubPullRequestCli.ts";
import { gitHubViewerPermissions, loginAvatarUrl, make } from "./GitHubPullRequestProvider.ts";
@@ -10,16 +9,7 @@ import type { GitHubReviewThreadComments } from "./gitHubPullRequestJson.ts";
describe("gitHubViewerPermissions", () => {
it("offers everything to a viewer who can write to the repository", () => {
expect(gitHubViewerPermissions({ canWrite: true, canUpdate: true, didAuthor: false })).toEqual({
// Arming a merge for later is the merge, so it travels with it.
actions: [
"merge",
"enable-auto-merge",
"disable-auto-merge",
"ready",
"draft",
"close",
"reopen",
],
actions: ["merge", "ready", "draft", "close", "reopen"],
comment: true,
resolve: true,
verdicts: ["comment", "approve", "request-changes"],
@@ -44,7 +34,7 @@ describe("gitHubViewerPermissions", () => {
it("keeps an author's own pull request theirs to close, with read access and no more", () => {
expect(gitHubViewerPermissions({ canWrite: false, canUpdate: true, didAuthor: true })).toEqual({
// Merging is the one thing writing is needed for, now or later; the rest an author may do.
// Merging is the one thing writing is needed for; the rest an author may do.
actions: ["ready", "draft", "close", "reopen"],
comment: true,
resolve: true,
@@ -81,20 +71,17 @@ describe("gitHubViewerPermissions", () => {
title: "Pull request 7",
url: "https://github.com/acme/web/pull/7",
author: null,
headRepositoryOwner: null,
headBranch: "feat/page",
baseBranch: "main",
state: "open",
isDraft: false,
mergeability: "mergeable",
reviewDecision: null,
additions: 1,
deletions: 1,
createdAt: "2026-07-01T00:00:00Z",
updatedAt: "2026-07-02T00:00:00Z",
reviewRequestLogins: [],
hasTeamReviewRequest: false,
checksState: null,
labels: [],
body: "",
changedFiles: 1,
@@ -117,101 +104,6 @@ describe("gitHubViewerPermissions", () => {
);
});
describe("getViewerPermissions", () => {
const openDetail = {
authorId: null,
number: 7,
title: "Pull request 7",
url: "https://github.com/acme/web/pull/7",
author: null,
headRepositoryOwner: "acme",
headBranch: "feat/page",
baseBranch: "main",
state: "open" as const,
isDraft: false,
mergeability: "mergeable" as const,
reviewDecision: null,
additions: 1,
deletions: 1,
createdAt: "2026-07-01T00:00:00Z",
updatedAt: "2026-07-02T00:00:00Z",
reviewRequestLogins: [],
hasTeamReviewRequest: false,
checksState: null,
labels: [],
body: "",
changedFiles: 1,
mergedAt: null,
closedAt: null,
checks: [],
comments: [],
commits: [],
};
const layerWithComparison = (
comparison: Effect.Effect<{
readonly behindBy: number | null;
readonly viewerCanUpdate: boolean;
}>,
) =>
Layer.mock(GitHubPullRequestCli.GitHubPullRequestCli)({
getPullRequestDetail: () => Effect.succeed(openDetail),
getPullRequestBaseComparison: () => comparison,
getViewerAccess: () => Effect.succeed({ canWrite: true, canUpdate: true, didAuthor: false }),
});
it.effect("offers update-branch when the comparison grants it", () =>
Effect.gen(function* () {
const provider = yield* make;
const permissions = yield* provider.getViewerPermissions({
cwd: "/w",
repository: "acme/web",
host: "github.com",
number: 7,
});
expect(permissions.actions).toContain("update-branch");
expect(permissions.updateMethods).toEqual(["merge", "rebase"]);
}).pipe(
Effect.provide(layerWithComparison(Effect.succeed({ behindBy: 3, viewerCanUpdate: true }))),
),
);
it.effect("withholds update-branch when the comparison cannot be read", () =>
Effect.gen(function* () {
const provider = yield* make;
const permissions = yield* provider.getViewerPermissions({
cwd: "/w",
repository: "acme/web",
host: "github.com",
number: 7,
});
expect(permissions.actions).not.toContain("update-branch");
expect(permissions.updateMethods).toBeUndefined();
// The rest of the answer survives a comparison nobody could make.
expect(permissions.actions).toContain("merge");
}).pipe(
Effect.provide(
Layer.mock(GitHubPullRequestCli.GitHubPullRequestCli)({
getPullRequestDetail: () => Effect.succeed(openDetail),
getPullRequestBaseComparison: () =>
Effect.fail(
new GitHubPullRequestCli.GitHubPullRequestReadError({
command: "gh",
cwd: "/w",
operation: "getPullRequestBaseComparison",
cause: new Error("unreadable"),
}),
),
getViewerAccess: () =>
Effect.succeed({ canWrite: true, canUpdate: true, didAuthor: false }),
}),
),
),
);
});
describe("getChangeRequest commits", () => {
const baseDetail = {
authorId: null,
@@ -230,7 +122,6 @@ describe("getChangeRequest commits", () => {
updatedAt: "2026-07-02T00:00:00Z",
reviewRequestLogins: [],
hasTeamReviewRequest: false,
checksState: null,
labels: [],
body: "",
changedFiles: 1,
@@ -242,12 +133,9 @@ describe("getChangeRequest commits", () => {
const baseThreadComments = {
comments: [],
dismissalsByReviewId: new Map<string, string>(),
reviewThreads: [],
commentCount: 0,
truncated: false,
reactions: [],
reactionsById: new Map<string, ReadonlyArray<PullRequestReaction>>(),
reviewers: [],
avatarsByLogin: new Map<string, string>(),
commitStats: new Map<string, { readonly additions: number; readonly deletions: number }>(),
@@ -312,122 +200,6 @@ describe("getChangeRequest commits", () => {
);
});
describe("getChangeRequestActivity dismissed reviews", () => {
const dismissedReview = (body: string) => ({
id: "PRR_1",
kind: "review" as const,
author: null,
body,
createdAt: "2026-07-03T00:00:00Z",
url: null,
path: null,
reviewState: "DISMISSED",
});
const threadComments: GitHubReviewThreadComments = {
comments: [],
dismissalsByReviewId: new Map([["PRR_1", "Dismissing prior approval to re-evaluate 9b66581"]]),
reviewThreads: [],
commentCount: 0,
truncated: false,
reactions: [],
reactionsById: new Map(),
reviewers: [],
avatarsByLogin: new Map(),
commitStats: new Map(),
commits: [],
viewer: { canUpdate: true, didAuthor: false },
};
const layerFor = (body: string) =>
Layer.mock(GitHubPullRequestCli.GitHubPullRequestCli)({
getPullRequestActivity: () =>
Effect.succeed({ author: null, comments: [dismissedReview(body)], commits: [] }),
listReviewThreadComments: () => Effect.succeed(threadComments),
});
const readActivity = Effect.gen(function* () {
const provider = yield* make;
return yield* provider.getChangeRequestActivity({
cwd: "/w",
repository: "acme/web",
host: "github.com",
number: 7,
});
});
it.effect("fills a marker-only dismissed review with the timeline's reason", () =>
// Macroscope's approvals carry only an HTML comment, which markdown renders as nothing —
// an empty-string check misses them and the card opens onto nothing.
readActivity.pipe(
Effect.map((activity) => {
expect(activity.comments[0]?.body).toBe("Dismissing prior approval to re-evaluate 9b66581");
}),
Effect.provide(layerFor("<!-- Macroscope (Approvability) review body marker -->")),
),
);
it.effect("keeps the words of a dismissed review that has its own", () =>
readActivity.pipe(
Effect.map((activity) => {
expect(activity.comments[0]?.body).toBe("These findings still stand.");
}),
Effect.provide(layerFor("These findings still stand.")),
),
);
});
describe("editing", () => {
const rewrites: Array<unknown> = [];
it.effect("hands a rewrite to the CLI as the request named it", () =>
Effect.gen(function* () {
const provider = yield* make;
expect(provider.capabilities.edit).toEqual({ changeRequest: true, comment: true });
yield* provider.updateChangeRequest!({
cwd: "/w",
repository: "acme/web",
host: "github.com",
number: 7,
title: "A better title",
});
yield* provider.updateComment!({
cwd: "/w",
repository: "acme/web",
host: "github.com",
number: 7,
commentId: "IC_1",
kind: "review-comment",
body: "Reworded.",
});
expect(rewrites).toEqual([
{
cwd: "/w",
repository: "acme/web",
host: "github.com",
number: 7,
title: "A better title",
},
{
cwd: "/w",
repository: "acme/web",
host: "github.com",
number: 7,
commentId: "IC_1",
kind: "review-comment",
body: "Reworded.",
},
]);
}).pipe(
Effect.provide(
Layer.mock(GitHubPullRequestCli.GitHubPullRequestCli)({
updatePullRequest: (input) => Effect.sync(() => void rewrites.push(input)),
updateComment: (input) => Effect.sync(() => void rewrites.push(input)),
}),
),
),
);
});
describe("loginAvatarUrl", () => {
it("serves a user's picture from the host they belong to", () => {
expect(loginAvatarUrl("octocat", "github.com")).toBe("https://github.com/octocat.png?size=80");
@@ -2,7 +2,6 @@ import * as Effect from "effect/Effect";
import type {
PullRequestActor,
PullRequestCapabilities,
PullRequestReaction,
PullRequestViewerPermissions,
} from "@t3tools/contracts";
@@ -18,20 +17,9 @@ import type { GitHubViewerAccess } from "./gitHubPullRequestJson.ts";
const CAPABILITIES: PullRequestCapabilities = {
diff: true,
comment: true,
actions: [
"merge",
"ready",
"draft",
"close",
"reopen",
"update-branch",
"enable-auto-merge",
"disable-auto-merge",
],
actions: ["merge", "ready", "draft", "close", "reopen"],
mergeMethods: ["merge", "squash", "rebase"],
updateMethods: ["merge", "rebase"],
search: true,
reactions: true,
review: {
inlineComment: true,
reply: true,
@@ -39,7 +27,6 @@ const CAPABILITIES: PullRequestCapabilities = {
verdicts: ["comment", "approve", "request-changes"],
},
reviewers: { request: true, listCandidates: true },
edit: { changeRequest: true, comment: true },
};
/**
@@ -62,13 +49,8 @@ const CAPABILITIES: PullRequestCapabilities = {
export function gitHubViewerPermissions(access: GitHubViewerAccess): PullRequestViewerPermissions {
return {
actions: [
// Arming a merge and taking the arming back are the merge, deferred: whoever may not
// merge here may not leave an instruction to merge later either.
...(access.canWrite ? (["merge", "enable-auto-merge", "disable-auto-merge"] as const) : []),
...(access.canWrite ? (["merge"] as const) : []),
...(access.canUpdate ? (["ready", "draft", "close", "reopen"] as const) : []),
// Whether this viewer may update the branch is GitHub's own answer, read with the
// comparison; without it the action is offered to nobody rather than to everybody.
...(access.canUpdateBranch === true ? (["update-branch"] as const) : []),
],
comment: true,
resolve: access.canWrite || access.didAuthor,
@@ -77,7 +59,6 @@ export function gitHubViewerPermissions(access: GitHubViewerAccess): PullRequest
// leaves them commenting, which is what an author has to say about their own change anyway.
verdicts: access.didAuthor ? (["comment"] as const) : CAPABILITIES.review.verdicts,
requestReviewers: access.canWrite,
...(access.canUpdateBranch === true ? { updateMethods: CAPABILITIES.updateMethods } : {}),
};
}
@@ -117,10 +98,6 @@ export function loginAvatarUrl(login: string, host: string): string | null {
return /^[a-z0-9][a-z0-9-]{0,38}$/iu.test(login) ? `https://${host}/${login}.png?size=80` : null;
}
/** True where markdown would render nothing: whitespace, or only HTML comments. */
const rendersEmpty = (body: string): boolean =>
body.replace(/<!--[\s\S]*?-->/g, "").trim().length === 0;
export const make = Effect.gen(function* () {
const cli = yield* GitHubPullRequestCli.GitHubPullRequestCli;
@@ -152,7 +129,6 @@ export const make = Effect.gen(function* () {
limit: input.limit,
query: input.query,
cursor: input.cursor,
filters: input.filters,
})
.pipe(
Effect.mapError(fail("listChangeRequests")),
@@ -196,7 +172,6 @@ export const make = Effect.gen(function* () {
limit: input.limit,
query: input.query,
cursor: input.cursor,
filters: input.filters,
})
.pipe(
Effect.mapError(fail("listChangeRequestsAcross")),
@@ -221,24 +196,7 @@ export const make = Effect.gen(function* () {
getChangeRequest: (input) =>
Effect.all(
[
cli.getPullRequestDetail(input).pipe(
Effect.flatMap((pullRequest) =>
// Only an open pull request can be behind anything worth saying so about, and only
// one whose head repository is known can be compared at all. A comparison that
// fails is left unknown: the banner is an offer, never a blocker.
pullRequest.state !== "open" || pullRequest.headRepositoryOwner === null
? Effect.succeed({ pullRequest, comparison: null })
: cli
.getPullRequestBaseComparison({
...input,
headRef: `${pullRequest.headRepositoryOwner}:${pullRequest.headBranch}`,
})
.pipe(
Effect.map((comparison) => ({ pullRequest, comparison })),
Effect.orElseSucceed(() => ({ pullRequest, comparison: null })),
),
),
),
cli.getPullRequestDetail(input),
cli.getRepositoryAccess({
cwd: input.cwd,
repository: input.repository,
@@ -252,27 +210,15 @@ export const make = Effect.gen(function* () {
).pipe(
Effect.mapError(fail("getChangeRequest")),
Effect.map(
([detail, repository, viewerAccess]): ProviderChangeRequestDetail => ({
...detail.pullRequest,
reviewers: detail.pullRequest.reviewRequestLogins.map((login) => ({
([pullRequest, repository, viewerAccess]): ProviderChangeRequestDetail => ({
...pullRequest,
reviewers: pullRequest.reviewRequestLogins.map((login) => ({
login,
name: null,
avatarUrl: null,
})),
mergeCapabilities: repository.mergeCapabilities,
viewerPermissions: gitHubViewerPermissions({
...viewerAccess,
canUpdateBranch: detail.comparison?.viewerCanUpdate === true,
}),
baseComparison:
detail.comparison === null || detail.comparison.behindBy === null
? "unknown"
: detail.comparison.behindBy > 0
? "behind"
: "up-to-date",
...(detail.comparison?.behindBy == null
? {}
: { behindBy: detail.comparison.behindBy }),
viewerPermissions: gitHubViewerPermissions(viewerAccess),
}),
),
),
@@ -286,9 +232,6 @@ export const make = Effect.gen(function* () {
cli.listReviewThreadComments(input).pipe(
Effect.orElseSucceed(() => ({
comments: [],
dismissalsByReviewId: new Map<string, string>(),
reactions: [],
reactionsById: new Map<string, ReadonlyArray<PullRequestReaction>>(),
reviewThreads: [],
commentCount: 0,
truncated: true,
@@ -310,7 +253,6 @@ export const make = Effect.gen(function* () {
([pullRequest, reviewThreads]): ProviderChangeRequestActivity => ({
author: withAvatar(pullRequest.author, reviewThreads.avatarsByLogin, input.host),
reviewers: reviewThreads.reviewers,
reactions: reviewThreads.reactions,
commits: (reviewThreads.commits.length > 0
? reviewThreads.commits
: pullRequest.commits
@@ -324,20 +266,7 @@ export const make = Effect.gen(function* () {
comments: [...pullRequest.comments, ...reviewThreads.comments]
.map((comment) => ({
...comment,
// GitHub keeps the dismissal reason on the timeline event, not on the review,
// so a dismissed review with nothing visible of its own reads its words from
// there. "Visible" and not "empty": bot reviews often carry only an HTML
// marker comment, which markdown renders as nothing.
body:
comment.kind === "review" &&
comment.reviewState?.toUpperCase() === "DISMISSED" &&
rendersEmpty(comment.body)
? (reviewThreads.dismissalsByReviewId.get(comment.id) ?? comment.body)
: comment.body,
author: withAvatar(comment.author, reviewThreads.avatarsByLogin, input.host),
// A comment out of `gh pr view --json` carries none of its own: that read
// reports no reaction at all, so they arrive from the GraphQL page by node id.
reactions: comment.reactions ?? reviewThreads.reactionsById.get(comment.id) ?? [],
}))
.toSorted((left, right) => left.createdAt.localeCompare(right.createdAt)),
// `gh pr view --json comments,reviews` follows GitHub's cursors itself, so those two
@@ -356,34 +285,9 @@ export const make = Effect.gen(function* () {
),
getViewerPermissions: (input) =>
Effect.all(
[
cli.getViewerAccess(input),
// Whether this viewer may update the branch is only on the comparison, and the
// comparison only resolves through the head ref the detail carries. A failure here
// withholds that one action rather than the whole answer, the way the detail path
// leaves the banner unknown.
cli.getPullRequestDetail(input).pipe(
Effect.flatMap((pullRequest) =>
pullRequest.state !== "open" || pullRequest.headRepositoryOwner === null
? Effect.succeed(false)
: cli
.getPullRequestBaseComparison({
...input,
headRef: `${pullRequest.headRepositoryOwner}:${pullRequest.headBranch}`,
})
.pipe(Effect.map((comparison) => comparison.viewerCanUpdate === true)),
),
Effect.orElseSucceed(() => false),
),
],
{ concurrency: 2 },
).pipe(
Effect.mapError(fail("getViewerPermissions")),
Effect.map(([access, canUpdateBranch]) =>
gitHubViewerPermissions({ ...access, canUpdateBranch }),
),
),
cli
.getViewerAccess(input)
.pipe(Effect.mapError(fail("getViewerPermissions")), Effect.map(gitHubViewerPermissions)),
getDiff: (input) => cli.getPullRequestDiff(input).pipe(Effect.mapError(fail("getDiff"))),
@@ -414,37 +318,11 @@ export const make = Effect.gen(function* () {
number: input.number,
action: input.action,
...(input.mergeMethod === undefined ? {} : { mergeMethod: input.mergeMethod }),
...(input.updateMethod === undefined ? {} : { updateMethod: input.updateMethod }),
})
.pipe(Effect.mapError(fail("runAction"))),
updateChangeRequest: (input) =>
cli
.updatePullRequest({
cwd: input.cwd,
repository: input.repository,
host: input.host,
number: input.number,
...(input.title === undefined ? {} : { title: input.title }),
...(input.body === undefined ? {} : { body: input.body }),
})
.pipe(Effect.mapError(fail("updateChangeRequest"))),
comment: (input) => cli.commentOnPullRequest(input).pipe(Effect.mapError(fail("comment"))),
updateComment: (input) =>
cli
.updateComment({
cwd: input.cwd,
repository: input.repository,
host: input.host,
number: input.number,
commentId: input.commentId,
kind: input.kind,
body: input.body,
})
.pipe(Effect.mapError(fail("updateComment"))),
submitReview: (input) => cli.submitReview(input).pipe(Effect.mapError(fail("submitReview"))),
replyToThread: (input) =>
@@ -458,19 +336,6 @@ export const make = Effect.gen(function* () {
})
.pipe(Effect.mapError(fail("replyToThread"))),
setReaction: (input) =>
cli
.setReaction({
cwd: input.cwd,
repository: input.repository,
host: input.host,
number: input.number,
...(input.subjectId === undefined ? {} : { subjectId: input.subjectId }),
content: input.content,
reacted: input.reacted,
})
.pipe(Effect.mapError(fail("setReaction"))),
setThreadResolution: (input) =>
cli
.setReviewThreadResolution({
@@ -414,69 +414,6 @@ layer("GitLabPullRequestCli.layer", (it) => {
}),
);
it.effect("arms auto-merge with the same strategy a merge would have used", () =>
Effect.gen(function* () {
mockedExecute.mockReturnValueOnce(Effect.succeed(output("")));
const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
yield* cli.runMergeRequestAction({
cwd: "/w",
repository: "acme/web",
number: 7,
action: "enable-auto-merge",
mergeMethod: "squash",
});
expect(argsOfCall(0)).toEqual([
"mr",
"merge",
"7",
"--repo",
"acme/web",
"--auto-merge=true",
"--yes",
"--squash",
]);
}),
);
it.effect("cancels an armed auto-merge through the API glab has no flag for", () =>
Effect.gen(function* () {
mockedExecute.mockReturnValueOnce(Effect.succeed(output("{}")));
const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
yield* cli.runMergeRequestAction({
cwd: "/w",
repository: "acme/platform/web",
number: 7,
action: "disable-auto-merge",
});
expect(argsOfCall(0)).toEqual([
"api",
"projects/acme%2Fplatform%2Fweb/merge_requests/7/cancel_merge_when_pipeline_succeeds",
"--method",
"POST",
]);
}),
);
it.effect("brings a stale branch up to date by rebasing it, the only way GitLab has", () =>
Effect.gen(function* () {
mockedExecute.mockReturnValueOnce(Effect.succeed(output("")));
const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
yield* cli.runMergeRequestAction({
cwd: "/w",
repository: "acme/web",
number: 7,
action: "update-branch",
});
expect(argsOfCall(0)).toEqual(["mr", "rebase", "7", "--repo", "acme/web"]);
}),
);
it.effect("moves a merge request back to draft through glab", () =>
Effect.gen(function* () {
mockedExecute.mockReturnValueOnce(Effect.succeed(output("")));
@@ -854,21 +791,6 @@ layer("GitLabPullRequestCli.layer", (it) => {
}),
);
it.effect("asks the detail read for the divergence GitLab withholds by default", () =>
Effect.gen(function* () {
mockedExecute.mockReturnValueOnce(Effect.succeed(output('{"message":"404 Not Found"}')));
const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
yield* Effect.ignore(
cli.getMergeRequestDetail({ cwd: "/w", repository: "acme/web", number: 7 }),
);
expect(argsOfCall(0)[1]).toBe(
"projects/acme%2Fweb/merge_requests/7?include_diverged_commits_count=true",
);
}),
);
it.effect("fails the read when GitLab returns something unreadable", () =>
Effect.gen(function* () {
mockedExecute.mockReturnValueOnce(Effect.succeed(output('{"message":"404 Not Found"}')));
@@ -1086,89 +1008,6 @@ layer("GitLabPullRequestCli.layer", (it) => {
}),
);
it.effect("awards an emoji through a POST naming it, not a body", () =>
Effect.gen(function* () {
mockedExecute.mockReturnValue(Effect.succeed(output("{}")));
const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
yield* cli.setReaction({
cwd: "/w",
repository: "acme/web",
number: 7,
content: "thumbs-up",
reacted: true,
});
assert.strictEqual(mockedExecute.mock.calls.length, 1);
expect(argsOfCall(0)).toEqual([
"api",
"projects/acme%2Fweb/merge_requests/7/award_emoji?name=thumbsup",
"--method",
"POST",
]);
}),
);
it.effect("removes an award by listing them and deleting the reader's own id", () =>
Effect.gen(function* () {
mockedExecute.mockReturnValueOnce(
// @effect-diagnostics-next-line preferSchemaOverJson:off
Effect.succeed(output(JSON.stringify({ username: "bilal" }))),
);
mockedExecute.mockReturnValueOnce(
Effect.succeed(
output(
// @effect-diagnostics-next-line preferSchemaOverJson:off
JSON.stringify([
{ id: 5, name: "thumbsup", user: { username: "bilal" } },
{ id: 6, name: "thumbsup", user: { username: "julius" } },
]),
),
),
);
mockedExecute.mockReturnValueOnce(Effect.succeed(output("{}")));
const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
yield* cli.setReaction({
cwd: "/w",
repository: "acme/web",
number: 7,
content: "thumbs-up",
reacted: false,
});
assert.strictEqual(mockedExecute.mock.calls.length, 3);
expect(argsOfCall(2)).toEqual([
"api",
"projects/acme%2Fweb/merge_requests/7/award_emoji/5",
"--method",
"DELETE",
]);
}),
);
it.effect("does nothing when the reader has no award of that name to take back", () =>
Effect.gen(function* () {
mockedExecute.mockReturnValueOnce(
// @effect-diagnostics-next-line preferSchemaOverJson:off
Effect.succeed(output(JSON.stringify({ username: "bilal" }))),
);
mockedExecute.mockReturnValueOnce(Effect.succeed(output("[]")));
const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
yield* cli.setReaction({
cwd: "/w",
repository: "acme/web",
number: 7,
content: "thumbs-up",
reacted: false,
});
// Nothing to delete: the reaction the caller asked to take back is already gone.
assert.strictEqual(mockedExecute.mock.calls.length, 2);
}),
);
it.effect("names a merge request with no diff revisions rather than calling it unreadable", () =>
Effect.gen(function* () {
mockedExecute.mockReturnValueOnce(
@@ -1302,99 +1141,4 @@ layer("GitLabPullRequestCli.layer", (it) => {
expect(JSON.parse(callAt(1).stdin ?? "")).toEqual({ reviewer_ids: [5] });
}),
);
it.effect("rewrites a title without touching the description", () =>
Effect.gen(function* () {
mockedExecute.mockReturnValue(Effect.succeed(output("{}")));
const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
yield* cli.updateMergeRequest({
cwd: "/w",
repository: "acme/web",
number: 7,
title: "A better title",
});
expect(argsOfCall(0)).toEqual([
"api",
"projects/acme%2Fweb/merge_requests/7",
"--method",
"PUT",
"--input",
"-",
"--header",
"Content-Type: application/json",
]);
// @effect-diagnostics-next-line preferSchemaOverJson:off
expect(JSON.parse(callAt(0).stdin ?? "")).toEqual({ title: "A better title" });
}),
);
it.effect("sends a rewritten body as GitLab's description, and nothing else", () =>
Effect.gen(function* () {
mockedExecute.mockReturnValue(Effect.succeed(output("{}")));
const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
yield* cli.updateMergeRequest({
cwd: "/w",
repository: "acme/web",
number: 7,
description: "What this changes.",
});
// A title sent as an empty string would wipe the one the merge request already has.
// @effect-diagnostics-next-line preferSchemaOverJson:off
expect(JSON.parse(callAt(0).stdin ?? "")).toEqual({ description: "What this changes." });
}),
);
it.effect("rewrites title and description together in one request", () =>
Effect.gen(function* () {
mockedExecute.mockReturnValue(Effect.succeed(output("{}")));
const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
yield* cli.updateMergeRequest({
cwd: "/w",
repository: "acme/web",
number: 7,
title: "A better title",
description: "What this changes.",
});
assert.strictEqual(mockedExecute.mock.calls.length, 1);
// @effect-diagnostics-next-line preferSchemaOverJson:off
expect(JSON.parse(callAt(0).stdin ?? "")).toEqual({
title: "A better title",
description: "What this changes.",
});
}),
);
it.effect("rewrites a note in place through the note it names", () =>
Effect.gen(function* () {
mockedExecute.mockReturnValue(Effect.succeed(output("{}")));
const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
yield* cli.updateNote({
cwd: "/w",
repository: "acme/web",
number: 7,
noteId: "42",
body: "true",
});
expect(argsOfCall(0)).toEqual([
"api",
"projects/acme%2Fweb/merge_requests/7/notes/42",
"--method",
"PUT",
"--input",
"-",
"--header",
"Content-Type: application/json",
]);
// A JSON body, so a note rewritten to a literal `true` stays text.
expect(callAt(0).stdin).toBe('{"body":"true"}');
}),
);
});
@@ -11,8 +11,6 @@ import type {
PullRequestListState,
PullRequestMergeCapabilities,
PullRequestMergeMethod,
PullRequestReaction,
PullRequestReactionContent,
PullRequestReviewCommentDraft,
PullRequestReviewThread,
PullRequestReviewVerdict,
@@ -21,8 +19,6 @@ import type {
import * as GitLabCli from "../sourceControl/GitLabCli.ts";
import {
AWARD_EMOJI_GRAPHQL_QUERY,
decodeAwardEmojiJson,
decodeCommitDiffRefsJson,
decodeCommitsJson,
decodeDiffRefsJson,
@@ -31,11 +27,9 @@ import {
decodeMergeRequestDiffsJson,
decodeMergeRequestListJson,
decodeNotesJson,
decodeOwnAwardIdJson,
decodeProjectMergeCapabilitiesJson,
decodeProjectUsersJson,
decodeViewerJson,
gitLabAwardName,
type GitLabDiffRefs,
type GitLabMergeRequestDetail,
type GitLabMergeRequestListItem,
@@ -309,15 +303,6 @@ export class GitLabPullRequestCli extends Context.Service<
readonly mergeMethod?: PullRequestMergeMethod;
}) => Effect.Effect<void, GitLabPullRequestCliError>;
/** Whichever of the two is given is sent. GitLab calls a merge request's body its description. */
readonly updateMergeRequest: (input: {
readonly cwd: string;
readonly repository: string;
readonly number: number;
readonly title?: string | undefined;
readonly description?: string | undefined;
}) => Effect.Effect<void, GitLabPullRequestCliError>;
readonly commentOnMergeRequest: (input: {
readonly cwd: string;
readonly repository: string;
@@ -325,14 +310,6 @@ export class GitLabPullRequestCli extends Context.Service<
readonly body: string;
}) => Effect.Effect<void, GitLabPullRequestCliError>;
readonly updateNote: (input: {
readonly cwd: string;
readonly repository: string;
readonly number: number;
readonly noteId: string;
readonly body: string;
}) => Effect.Effect<void, GitLabPullRequestCliError>;
readonly listDiscussions: (input: {
readonly cwd: string;
readonly repository: string;
@@ -366,32 +343,6 @@ export class GitLabPullRequestCli extends Context.Service<
readonly discussionId: string;
readonly resolved: boolean;
}) => Effect.Effect<void, GitLabPullRequestCliError>;
/** The awards on the merge request and on every note of it, keyed by the note's REST id. */
readonly listReactions: (input: {
readonly cwd: string;
readonly repository: string;
readonly number: number;
}) => Effect.Effect<
{
readonly reactions: ReadonlyArray<PullRequestReaction>;
readonly reactionsByNoteId: ReadonlyMap<string, ReadonlyArray<PullRequestReaction>>;
},
GitLabPullRequestCliError
>;
/**
* Awards an emoji, or takes the award back. `noteId` is a note of the merge request; absent
* awards the merge request itself, which is where its description's reactions live.
*/
readonly setReaction: (input: {
readonly cwd: string;
readonly repository: string;
readonly number: number;
readonly noteId?: string | undefined;
readonly content: PullRequestReactionContent;
readonly reacted: boolean;
}) => Effect.Effect<void, GitLabPullRequestCliError>;
}
>()("t3/pullRequest/GitLabPullRequestCli") {}
@@ -461,30 +412,12 @@ function actionArgs(
...(mergeMethod === "squash" ? ["--squash"] : []),
...(mergeMethod === "rebase" ? ["--rebase"] : []),
];
// The same command with the flag the other way up: here the wait is the whole point, so
// glab is told to arm the merge rather than talked out of it.
case "enable-auto-merge":
return [
"merge",
"--auto-merge=true",
"--yes",
...(mergeMethod === "squash" ? ["--squash"] : []),
...(mergeMethod === "rebase" ? ["--rebase"] : []),
];
// Never reached: taking the arming back has no `glab mr` command, so it goes to the API.
case "disable-auto-merge":
return [];
case "ready":
return ["update", "--ready"];
case "draft":
return ["update", "--draft"];
case "close":
return ["close"];
// A rebase, because GitLab has no other way to move a branch onto its target: there is no
// merge-the-target-in equivalent of GitHub's update button, which is why this host declares
// `rebase` alone and never has to read the method it was handed.
case "update-branch":
return ["rebase"];
case "reopen":
return ["reopen"];
}
@@ -886,11 +819,7 @@ export const make = Effect.gen(function* () {
}): Effect.Effect<GitLabMergeRequestDetail, GitLabPullRequestCliError> =>
api({
cwd: input.cwd,
// How far behind the target branch this one is comes only when asked for by name, and it
// is asked for here rather than on a second read because it is the same merge request.
path: `projects/${projectPath(input.repository)}/merge_requests/${input.number}?${query([
["include_diverged_commits_count", "true"],
])}`,
path: `projects/${projectPath(input.repository)}/merge_requests/${input.number}`,
}).pipe(
Effect.flatMap((result) => {
const decoded = decodeMergeRequestDetailJson(result.stdout.trim());
@@ -933,104 +862,26 @@ export const make = Effect.gen(function* () {
}),
);
/** Where an award is written: a note of the merge request, or the merge request itself. */
const awardSubjectPath = (input: {
readonly repository: string;
readonly number: number;
readonly noteId?: string | undefined;
}) => {
const mergeRequest = `projects/${projectPath(input.repository)}/merge_requests/${input.number}`;
return input.noteId === undefined
? `${mergeRequest}/award_emoji`
: `${mergeRequest}/notes/${encodeURIComponent(input.noteId)}/award_emoji`;
};
/**
* The awards on the merge request and its notes, a page of notes at a time. Bounded by the same
* count as the conversation itself: awards past the notes that were read belong to notes the
* page is not showing.
*/
const awardsPage = (input: {
readonly cwd: string;
readonly repository: string;
readonly number: number;
readonly cursor: string | null;
readonly page: number;
readonly collected: {
readonly reactions: ReadonlyArray<PullRequestReaction>;
readonly reactionsByNoteId: Map<string, ReadonlyArray<PullRequestReaction>>;
} | null;
}): Effect.Effect<
{
readonly reactions: ReadonlyArray<PullRequestReaction>;
readonly reactionsByNoteId: ReadonlyMap<string, ReadonlyArray<PullRequestReaction>>;
},
GitLabPullRequestCliError
> =>
api({
cwd: input.cwd,
path: "graphql",
method: "POST",
stdin: JSON.stringify({
query: AWARD_EMOJI_GRAPHQL_QUERY,
variables: {
fullPath: input.repository,
iid: String(input.number),
cursor: input.cursor,
},
}),
}).pipe(
Effect.flatMap((result) => {
const decoded = decodeAwardEmojiJson(result.stdout.trim());
if (!Result.isSuccess(decoded)) {
return Effect.fail(
new GitLabMergeRequestReadError({
command: "glab",
cwd: input.cwd,
operation: "listReactions",
cause: decoded.failure,
}),
);
}
const collected = input.collected ?? {
reactions: decoded.success.reactions,
reactionsByNoteId: new Map<string, ReadonlyArray<PullRequestReaction>>(),
};
for (const [id, reactions] of decoded.success.reactionsByNoteId)
collected.reactionsByNoteId.set(id, reactions);
return decoded.success.nextCursor === null || input.page >= CONVERSATION_PAGES
? Effect.succeed(collected)
: awardsPage({
...input,
cursor: decoded.success.nextCursor,
page: input.page + 1,
collected,
});
}),
);
const viewerUsername = (input: { readonly cwd: string }) =>
api({ cwd: input.cwd, path: "user" }).pipe(
Effect.flatMap((result): Effect.Effect<string, GitLabPullRequestCliError> => {
const decoded = decodeViewerJson(result.stdout.trim());
if (!Result.isSuccess(decoded)) {
return Effect.fail(
new GitLabMergeRequestReadError({
command: "glab",
cwd: input.cwd,
operation: "getViewerUsername",
cause: decoded.failure,
}),
);
}
return decoded.success === null
? Effect.fail(new GitLabViewerUnavailableError({ command: "glab", cwd: input.cwd }))
: Effect.succeed(decoded.success);
}),
);
return GitLabPullRequestCli.of({
getViewerUsername: viewerUsername,
getViewerUsername: (input) =>
api({ cwd: input.cwd, path: "user" }).pipe(
Effect.flatMap((result): Effect.Effect<string, GitLabPullRequestCliError> => {
const decoded = decodeViewerJson(result.stdout.trim());
if (!Result.isSuccess(decoded)) {
return Effect.fail(
new GitLabMergeRequestReadError({
command: "glab",
cwd: input.cwd,
operation: "getViewerUsername",
cause: decoded.failure,
}),
);
}
return decoded.success === null
? Effect.fail(new GitLabViewerUnavailableError({ command: "glab", cwd: input.cwd }))
: Effect.succeed(decoded.success);
}),
),
listMergeRequests: (input) => {
const perPage = Math.min(input.limit + 1, MAX_PAGE_SIZE);
@@ -1042,44 +893,6 @@ export const make = Effect.gen(function* () {
listNotes: (input) => notesPage({ ...input, page: 1, collected: [] }),
listReactions: (input) => awardsPage({ ...input, cursor: null, page: 1, collected: null }),
setReaction: (input) =>
Effect.gen(function* () {
const subject = awardSubjectPath(input);
if (input.reacted) {
yield* api({
cwd: input.cwd,
path: `${subject}?${query([["name", gitLabAwardName(input.content)]])}`,
method: "POST",
});
return;
}
// GitLab deletes an award by its id and takes no emoji name there, so the reader's own
// award of that name is looked up first. Nothing to delete is success: the reaction the
// caller asked to take back is already gone.
const viewer = yield* viewerUsername({ cwd: input.cwd });
const listed = yield* api({ cwd: input.cwd, path: subject });
const own = decodeOwnAwardIdJson(listed.stdout.trim(), {
content: input.content,
viewer,
});
if (!Result.isSuccess(own)) {
return yield* new GitLabMergeRequestReadError({
command: "glab",
cwd: input.cwd,
operation: "setReaction",
cause: own.failure,
});
}
if (own.success === null) return;
yield* api({
cwd: input.cwd,
path: `${subject}/${own.success}`,
method: "DELETE",
});
}),
listCommits: (input) =>
api({
cwd: input.cwd,
@@ -1240,16 +1053,6 @@ export const make = Effect.gen(function* () {
),
runMergeRequestAction: (input) => {
// `glab mr merge` arms auto-merge and never disarms it, so the one direction the CLI has
// no flag for is asked of GitLab directly through the same `api` passthrough the rest of
// this module writes with.
if (input.action === "disable-auto-merge") {
return api({
cwd: input.cwd,
path: `projects/${projectPath(input.repository)}/merge_requests/${input.number}/cancel_merge_when_pipeline_succeeds`,
method: "POST",
}).pipe(Effect.asVoid);
}
const [subcommand, ...flags] = actionArgs(input.action, input.mergeMethod);
return gitlab
.execute({
@@ -1259,20 +1062,6 @@ export const make = Effect.gen(function* () {
.pipe(Effect.asVoid);
},
updateMergeRequest: (input) =>
api({
cwd: input.cwd,
path: `projects/${projectPath(input.repository)}/merge_requests/${input.number}`,
method: "PUT",
// Only the fields the caller asked to change: GitLab leaves out what it is not sent, and
// clears what it is sent empty — so a title corrected on its own must carry no
// description at all.
stdin: JSON.stringify({
...(input.title === undefined ? {} : { title: input.title }),
...(input.description === undefined ? {} : { description: input.description }),
}),
}).pipe(Effect.asVoid),
commentOnMergeRequest: (input) =>
api({
cwd: input.cwd,
@@ -1283,16 +1072,6 @@ export const make = Effect.gen(function* () {
stdin: JSON.stringify({ body: input.body }),
}).pipe(Effect.asVoid),
updateNote: (input) =>
api({
cwd: input.cwd,
path: `projects/${projectPath(input.repository)}/merge_requests/${input.number}/notes/${encodeURIComponent(
input.noteId,
)}`,
method: "PUT",
stdin: JSON.stringify({ body: input.body }),
}).pipe(Effect.asVoid),
listDiscussions: (input) => discussionsPage({ ...input, page: 1, collected: [] }),
submitReview: (input) =>
@@ -1,36 +1,20 @@
import { assert, describe, expect, it, vi } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import { describe, expect, it } from "vite-plus/test";
import * as GitLabPullRequestCli from "./GitLabPullRequestCli.ts";
import { gitLabViewerPermissions, make } from "./GitLabPullRequestProvider.ts";
import { gitLabViewerPermissions } from "./GitLabPullRequestProvider.ts";
describe("gitLabViewerPermissions", () => {
it("offers everything to a viewer GitLab says can merge", () => {
expect(gitLabViewerPermissions({ viewerCanMerge: true })).toEqual({
// Arming a merge for later and taking the arming back answer to the same `can_merge`.
actions: [
"merge",
"ready",
"draft",
"close",
"reopen",
"update-branch",
"enable-auto-merge",
"disable-auto-merge",
],
actions: ["merge", "ready", "draft", "close", "reopen"],
comment: true,
resolve: true,
verdicts: ["comment", "approve"],
// GitLab says nothing about who may set a reviewer, and an unreported permission is granted.
requestReviewers: true,
// Rebase and nothing else: GitLab cannot merge a target branch into a source branch, so
// offering the choice would be offering something no request could carry out.
updateMethods: ["rebase"],
});
});
it("keeps merge, now and later, from a viewer GitLab says cannot", () => {
it("keeps merge from a viewer GitLab says cannot", () => {
// `user.can_merge` already accounts for the role, the approval rules and a protected target
// branch, so it is the one answer here that does not have to be inferred.
expect(gitLabViewerPermissions({ viewerCanMerge: false })).toEqual({
@@ -42,12 +26,6 @@ describe("gitLabViewerPermissions", () => {
});
});
it("names no way of updating a branch it will not let this viewer update", () => {
// The action and the strategy behind it go together: a button offered with nothing to press
// it with, or a strategy left standing next to a withheld button, is a half-refusal.
expect(gitLabViewerPermissions({ viewerCanMerge: false }).updateMethods).toBeUndefined();
});
it("treats an author with read access as any other reader, which is all GitLab says", () => {
// Its REST API names no relationship between the viewer and the merge request beyond
// `can_merge`, so the four an author keeps stay offered to everyone rather than being taken
@@ -60,138 +38,3 @@ describe("gitLabViewerPermissions", () => {
]);
});
});
describe("getChangeRequest base freshness", () => {
const detail = {
number: 7,
title: "Merge request 7",
url: "https://gitlab.com/acme/web/-/merge_requests/7",
author: null,
headBranch: "feat/page",
baseBranch: "main",
state: "open" as const,
isDraft: false,
mergeability: "mergeable" as const,
additions: 0,
deletions: 0,
createdAt: "2026-07-01T00:00:00Z",
updatedAt: "2026-07-02T00:00:00Z",
reviewRequestLogins: [],
labels: [],
body: "",
changedFiles: 1,
mergedAt: null,
closedAt: null,
reviewers: [],
checks: [],
viewerCanMerge: true,
reviewerIds: [],
};
const readWith = (divergence: { readonly divergedCommits?: number }) =>
Effect.gen(function* () {
const provider = yield* make;
return yield* provider.getChangeRequest({
cwd: "/w",
repository: "acme/web",
host: "gitlab.com",
number: 7,
});
}).pipe(
Effect.provide(
Layer.mock(GitLabPullRequestCli.GitLabPullRequestCli)({
getMergeRequestDetail: () => Effect.succeed({ ...detail, ...divergence }),
getProjectMergeCapabilities: () =>
Effect.succeed({ merge: true, squash: true, rebase: true }),
}),
),
);
it.effect("reads a counted divergence as a branch that has fallen behind", () =>
Effect.gen(function* () {
const changeRequest = yield* readWith({ divergedCommits: 3 });
expect(changeRequest.baseComparison).toBe("behind");
expect(changeRequest.behindBy).toBe(3);
}),
);
it.effect("reads a divergence of none as a branch that is current", () =>
Effect.gen(function* () {
const changeRequest = yield* readWith({ divergedCommits: 0 });
expect(changeRequest.baseComparison).toBe("up-to-date");
expect(changeRequest.behindBy).toBe(0);
}),
);
it.effect("says nothing at all where GitLab counted nothing", () =>
Effect.gen(function* () {
// An install too old to answer has to leave the page silent rather than let it claim the
// branch is current, which is the one wrong thing this banner could say.
const changeRequest = yield* readWith({});
expect(changeRequest.baseComparison).toBe("unknown");
expect(changeRequest.behindBy).toBeUndefined();
}),
);
});
describe("rewriting what has already been said", () => {
const updateMergeRequest = vi.fn(() => Effect.void);
const updateNote = vi.fn(() => Effect.void);
const providerWith = make.pipe(
Effect.provide(
Layer.mock(GitLabPullRequestCli.GitLabPullRequestCli)({ updateMergeRequest, updateNote }),
),
);
it.effect("sends only the half of the merge request the reader rewrote", () =>
Effect.gen(function* () {
const provider = yield* providerWith;
assert.isDefined(provider.updateChangeRequest);
yield* provider.updateChangeRequest({
cwd: "/w",
repository: "acme/web",
host: "gitlab.com",
number: 7,
body: "What this changes.",
});
// GitLab calls it the description, and the title stays out of the request entirely.
expect(updateMergeRequest).toHaveBeenCalledWith({
cwd: "/w",
repository: "acme/web",
number: 7,
description: "What this changes.",
});
}),
);
it.effect("rewrites a positioned comment through the same note as any other", () =>
Effect.gen(function* () {
const provider = yield* providerWith;
assert.isDefined(provider.updateComment);
yield* provider.updateComment({
cwd: "/w",
repository: "acme/web",
host: "gitlab.com",
number: 7,
commentId: "42",
kind: "review-comment",
body: "Reworded.",
});
expect(updateNote).toHaveBeenCalledWith({
cwd: "/w",
repository: "acme/web",
number: 7,
noteId: "42",
body: "Reworded.",
});
}),
);
});
@@ -1,9 +1,5 @@
import * as Effect from "effect/Effect";
import type {
PullRequestCapabilities,
PullRequestReaction,
PullRequestViewerPermissions,
} from "@t3tools/contracts";
import type { PullRequestCapabilities, PullRequestViewerPermissions } from "@t3tools/contracts";
import * as GitLabPullRequestCli from "./GitLabPullRequestCli.ts";
import {
@@ -16,24 +12,10 @@ import {
const CAPABILITIES: PullRequestCapabilities = {
diff: true,
comment: true,
actions: [
"merge",
"ready",
"draft",
"close",
"reopen",
"update-branch",
"enable-auto-merge",
"disable-auto-merge",
],
actions: ["merge", "ready", "draft", "close", "reopen"],
// GitLab offers all three, though a project settles on one; `mergeCapabilities` narrows it.
mergeMethods: ["merge", "squash", "rebase"],
// Rebase alone: GitLab moves a stale branch onto its target by replaying it, and has nothing
// that merges the target back in the way GitHub's update button can. Declaring only what it
// does is what lets a request to merge the target in be refused instead of quietly rebasing.
updateMethods: ["rebase"],
search: true,
reactions: true,
review: {
inlineComment: true,
reply: true,
@@ -43,21 +25,8 @@ const CAPABILITIES: PullRequestCapabilities = {
verdicts: ["comment", "approve"],
},
reviewers: { request: true, listCandidates: true },
edit: { changeRequest: true, comment: true },
};
/**
* The actions `user.can_merge` answers for. Rebasing writes to the source branch rather than to
* the target, so it is not literally the same permission — but GitLab reports nothing narrower,
* and someone it will not let land this change has no business rewriting its branch either.
*/
const MERGE_ACTIONS: ReadonlySet<string> = new Set([
"merge",
"update-branch",
"enable-auto-merge",
"disable-auto-merge",
]);
/**
* What the signed-in account may do here. GitLab answers exactly one of these questions per
* viewer, on the merge request itself: `user.can_merge`, which is why merging is the only thing
@@ -76,16 +45,11 @@ export function gitLabViewerPermissions(input: {
readonly viewerCanMerge: boolean;
}): PullRequestViewerPermissions {
return {
// Arming the merge and taking the arming back are the merge, deferred, so they answer to
// the same `can_merge` the merge itself does.
actions: CAPABILITIES.actions.filter(
(action) => !MERGE_ACTIONS.has(action) || input.viewerCanMerge,
),
actions: CAPABILITIES.actions.filter((action) => action !== "merge" || input.viewerCanMerge),
comment: true,
resolve: true,
verdicts: CAPABILITIES.review.verdicts,
requestReviewers: true,
...(input.viewerCanMerge ? { updateMethods: CAPABILITIES.updateMethods } : {}),
};
}
@@ -150,17 +114,6 @@ export const make = Effect.gen(function* () {
...mergeRequest,
mergeCapabilities,
viewerPermissions: gitLabViewerPermissions(mergeRequest),
// A GitLab too old to count the divergence says nothing here rather than "up to
// date": the banner is worth missing, and a wrong all-clear is not worth showing.
baseComparison:
mergeRequest.divergedCommits === undefined
? "unknown"
: mergeRequest.divergedCommits > 0
? "behind"
: "up-to-date",
...(mergeRequest.divergedCommits === undefined
? {}
: { behindBy: mergeRequest.divergedCommits }),
}),
),
),
@@ -175,37 +128,19 @@ export const make = Effect.gen(function* () {
cli
.listDiscussions(input)
.pipe(Effect.orElseSucceed(() => ({ threads: [], truncated: true }))),
// The notes endpoint carries no award of any kind, so they are read alongside it. A
// failed read costs the conversation its reactions rather than its words.
cli.listReactions(input).pipe(
Effect.orElseSucceed(() => ({
reactions: [] as ReadonlyArray<PullRequestReaction>,
reactionsByNoteId: new Map<string, ReadonlyArray<PullRequestReaction>>(),
})),
),
],
{ concurrency: 4 },
{ concurrency: 3 },
).pipe(
Effect.mapError(fail("getChangeRequestActivity")),
Effect.map(
([notes, commits, discussions, awards]): ProviderChangeRequestActivity => ({
reactions: awards.reactions,
comments: notes.comments.map((comment) => ({
...comment,
reactions: awards.reactionsByNoteId.get(comment.id) ?? [],
})),
([notes, commits, discussions]): ProviderChangeRequestActivity => ({
comments: notes.comments,
// GitLab reports no count of its own, so the walk's own total is the host's: the
// notes endpoint carries every comment on the merge request, including the ones
// written under a discussion, and it is read until GitLab runs out.
commentCount: notes.comments.length,
commentsTruncated: notes.truncated || discussions.truncated,
reviewThreads: discussions.threads.map((thread) => ({
...thread,
comments: thread.comments.map((comment) => ({
...comment,
reactions: awards.reactionsByNoteId.get(comment.id) ?? [],
})),
})),
reviewThreads: discussions.threads,
commits,
}),
),
@@ -253,32 +188,8 @@ export const make = Effect.gen(function* () {
})
.pipe(Effect.mapError(fail("runAction"))),
updateChangeRequest: (input) =>
cli
.updateMergeRequest({
cwd: input.cwd,
repository: input.repository,
number: input.number,
...(input.title === undefined ? {} : { title: input.title }),
...(input.body === undefined ? {} : { description: input.body }),
})
.pipe(Effect.mapError(fail("updateChangeRequest"))),
comment: (input) => cli.commentOnMergeRequest(input).pipe(Effect.mapError(fail("comment"))),
// The kind is not read: every comment this provider hands out, positioned or not, carries a
// plain REST note id, and one endpoint rewrites both.
updateComment: (input) =>
cli
.updateNote({
cwd: input.cwd,
repository: input.repository,
number: input.number,
noteId: input.commentId,
body: input.body,
})
.pipe(Effect.mapError(fail("updateComment"))),
submitReview: (input) => cli.submitReview(input).pipe(Effect.mapError(fail("submitReview"))),
replyToThread: (input) =>
@@ -292,18 +203,6 @@ export const make = Effect.gen(function* () {
})
.pipe(Effect.mapError(fail("replyToThread"))),
setReaction: (input) =>
cli
.setReaction({
cwd: input.cwd,
repository: input.repository,
number: input.number,
...(input.subjectId === undefined ? {} : { noteId: input.subjectId }),
content: input.content,
reacted: input.reacted,
})
.pipe(Effect.mapError(fail("setReaction"))),
setThreadResolution: (input) =>
cli
.setDiscussionResolution({
@@ -3,30 +3,22 @@ import * as Schema from "effect/Schema";
import type {
PullRequestAction,
PullRequestActor,
PullRequestBaseComparison,
PullRequestCapabilities,
PullRequestChecksState,
PullRequestCheck,
PullRequestComment,
PullRequestCommit,
PullRequestInvolvement,
PullRequestLabel,
PullRequestListFilters,
PullRequestListState,
PullRequestMergeCapabilities,
PullRequestMergeMethod,
PullRequestMergeability,
PullRequestOmittedFileStat,
PullRequestReaction,
PullRequestReactionContent,
PullRequestReviewCommentDraft,
PullRequestReviewDecision,
PullRequestReviewThread,
PullRequestReviewVerdict,
PullRequestReviewerCandidateList,
PullRequestReviewerKind,
PullRequestState,
PullRequestUpdateMethod,
PullRequestViewerPermissions,
SourceControlProviderKind,
} from "@t3tools/contracts";
@@ -72,10 +64,6 @@ export interface ProviderChangeRequest {
/** Accounts with a review requested. Team-level requests are excluded by each provider. */
readonly reviewRequestLogins: ReadonlyArray<string>;
readonly labels: ReadonlyArray<PullRequestLabel>;
/** Absent from a host that does not summarise its reviews, which is every host but GitHub. */
readonly reviewDecision?: PullRequestReviewDecision | null | undefined;
/** Absent from a host that reports no check rollup on its listings. */
readonly checksState?: PullRequestChecksState | null | undefined;
}
export interface ProviderChangeRequestPage {
@@ -152,11 +140,6 @@ export interface ProviderChangeRequestDetail extends ProviderChangeRequest {
readonly checks: ReadonlyArray<PullRequestCheck>;
readonly mergeCapabilities: PullRequestMergeCapabilities;
readonly viewerPermissions: PullRequestViewerPermissions;
/** Absent from a host that cannot compare the branch with its base, which is most of them. */
readonly baseComparison?: PullRequestBaseComparison;
readonly behindBy?: number;
/** Absent from a host that does not report whether it is armed to merge this on its own. */
readonly autoMergeEnabled?: boolean;
}
/** The conversation-shaped half of a detail, loaded after the core can already render. */
@@ -175,8 +158,6 @@ export interface ProviderChangeRequestActivity {
readonly commentsTruncated: boolean;
readonly reviewThreads: ReadonlyArray<PullRequestReviewThread>;
readonly commits: ReadonlyArray<PullRequestCommit>;
/** The change request's own reactions, from a host that has them. */
readonly reactions?: ReadonlyArray<PullRequestReaction>;
}
export interface ProviderDiffSlice {
@@ -184,8 +165,6 @@ export interface ProviderDiffSlice {
/** Something in this slice could not be shown, as opposed to there being more slices. */
readonly truncated: boolean;
readonly nextCursor: string | null;
/** The host's own counts for the files whose hunks it withheld from this slice. */
readonly omittedFileStats?: ReadonlyArray<PullRequestOmittedFileStat>;
}
export interface ProviderDiffFileContents {
@@ -237,12 +216,6 @@ export interface PullRequestProviderApi {
* asks for the first slice, which is every listing that has not been continued.
*/
readonly cursor?: ProviderListCursor | undefined;
/**
* Further narrowings, which a host applies as far as it can and ignores the rest of —
* an unnarrowed page is a wider answer rather than a wrong one, and the caller narrows
* what it gets for the fields a row carries.
*/
readonly filters?: PullRequestListFilters | undefined;
},
) => Effect.Effect<ProviderChangeRequestPage, PullRequestProviderError>;
@@ -271,7 +244,6 @@ export interface PullRequestProviderApi {
readonly limit: number;
readonly query?: string | undefined;
readonly cursor?: ProviderListCursor | undefined;
readonly filters?: PullRequestListFilters | undefined;
}) => Effect.Effect<ProviderBatchedChangeRequestPage, PullRequestProviderError>;
/**
@@ -342,23 +314,7 @@ export interface PullRequestProviderApi {
input: ProviderRepositoryRef & {
readonly number: number;
readonly action: PullRequestAction;
/** Meaningful for `merge` and `enable-auto-merge`; absent takes the host's own default. */
readonly mergeMethod?: PullRequestMergeMethod;
/** Only meaningful for `update-branch`; absent takes the host's own default. */
readonly updateMethod?: PullRequestUpdateMethod;
},
) => Effect.Effect<void, PullRequestProviderError>;
/**
* Rewrites the change request's own words. Only called when `capabilities.edit.changeRequest`
* is true, and never with both fields absent — the caller refuses that before it gets here,
* because a host asked to change nothing answers differently on each of them.
*/
readonly updateChangeRequest?: (
input: ProviderRepositoryRef & {
readonly number: number;
readonly title?: string | undefined;
readonly body?: string | undefined;
},
) => Effect.Effect<void, PullRequestProviderError>;
@@ -366,23 +322,6 @@ export interface PullRequestProviderApi {
input: ProviderRepositoryRef & { readonly number: number; readonly body: string },
) => Effect.Effect<void, PullRequestProviderError>;
/**
* Rewrites a remark somebody already posted. Only called when `capabilities.edit.comment` is
* true, with an id exactly as the conversation carried it.
*
* Whether this remark is the reader's to rewrite is the host's own answer: no read here can
* settle it, since access can be taken away between the conversation being read and the
* rewrite being sent, and a host refuses a stranger's remark with a sentence saying so.
*/
readonly updateComment?: (
input: ProviderRepositoryRef & {
readonly number: number;
readonly commentId: string;
readonly kind: "issue-comment" | "review-comment";
readonly body: string;
},
) => Effect.Effect<void, PullRequestProviderError>;
/**
* Sends a whole review at once. Only called for a verdict the host declared in
* `capabilities.review.verdicts`, and with line comments only where it declared
@@ -437,22 +376,6 @@ export interface PullRequestProviderApi {
},
) => Effect.Effect<void, PullRequestProviderError>;
/**
* Adds a reaction, or takes it back. Only called when `capabilities.reactions` is true.
*
* `subjectId` is a remark's id as the conversation carried it; absent means the change request
* itself, whose reactions sit on its description. Whatever a host needs to address either of
* them is worked out here, because the id a conversation travels with is the one the reader has.
*/
readonly setReaction: (
input: ProviderRepositoryRef & {
readonly number: number;
readonly subjectId?: string | undefined;
readonly content: PullRequestReactionContent;
readonly reacted: boolean;
},
) => Effect.Effect<void, PullRequestProviderError>;
/** Only called when `capabilities.review.resolve` is true. */
readonly setThreadResolution: (
input: ProviderRepositoryRef & {
File diff suppressed because it is too large. Load diff
+56 -399
View File
@@ -10,13 +10,11 @@ import {
PullRequestUnavailableError,
pullRequestHostOf,
pullRequestProviderRequirement,
resolvePullRequestAuthorFilter,
type OrchestrationProjectShell,
type PullRequestAction,
type PullRequestActionInput,
type PullRequestActivity,
type PullRequestCommentInput,
type PullRequestCommentUpdateInput,
type PullRequestDetail,
type PullRequestDiffFileContentsInput,
type PullRequestDiffFileContentsResult,
@@ -25,14 +23,12 @@ import {
type PullRequestDiffResult,
type PullRequestInvalidateInput,
type PullRequestListEntry,
type PullRequestListFilters,
type PullRequestListInput,
type PullRequestListProjectError,
type PullRequestListResult,
type PullRequestListStatsInput,
type PullRequestListStatsResult,
type PullRequestProviderSummary,
type PullRequestReactionInput,
type PullRequestRef,
type PullRequestReviewVerdict,
type PullRequestReviewerCandidateList,
@@ -40,14 +36,10 @@ import {
type PullRequestSubmitReviewInput,
type PullRequestThreadReplyInput,
type PullRequestThreadResolutionInput,
type PullRequestUpdateInput,
type SourceControlProviderInfo,
type SourceControlProviderKind,
} from "@t3tools/contracts";
import { detectSourceControlProviderFromRemoteUrl } from "@t3tools/shared/sourceControl";
import * as ProjectionSnapshotQuery from "../orchestration/Services/ProjectionSnapshotQuery.ts";
import * as SourceControlProviderRegistry from "../sourceControl/SourceControlProviderRegistry.ts";
import {
type ProviderChangeRequest,
type ProviderListCursor,
@@ -139,11 +131,7 @@ export class PullRequestService extends Context.Service<
input: PullRequestDiffFileContentsInput,
) => Effect.Effect<PullRequestDiffFileContentsResult, PullRequestError>;
readonly runAction: (input: PullRequestActionInput) => Effect.Effect<void, PullRequestError>;
readonly update: (input: PullRequestUpdateInput) => Effect.Effect<void, PullRequestError>;
readonly comment: (input: PullRequestCommentInput) => Effect.Effect<void, PullRequestError>;
readonly updateComment: (
input: PullRequestCommentUpdateInput,
) => Effect.Effect<void, PullRequestError>;
readonly submitReview: (
input: PullRequestSubmitReviewInput,
) => Effect.Effect<void, PullRequestError>;
@@ -153,9 +141,6 @@ export class PullRequestService extends Context.Service<
readonly setThreadResolution: (
input: PullRequestThreadResolutionInput,
) => Effect.Effect<void, PullRequestError>;
readonly setReaction: (
input: PullRequestReactionInput,
) => Effect.Effect<void, PullRequestError>;
readonly reviewerCandidates: (
input: PullRequestRef,
) => Effect.Effect<PullRequestReviewerCandidateList, PullRequestError>;
@@ -186,14 +171,8 @@ const ACTION_ACCESS_REFUSALS: Record<PullRequestAction, string> = {
"You need write access on this repository, or to have opened this change request, to return it to a draft.",
close:
"You need write access on this repository, or to have opened this change request, to close it.",
"update-branch":
"You need write access on this repository, or to have opened this change request, to update its branch.",
reopen:
"You need write access on this repository, or to have opened this change request, to reopen it.",
"enable-auto-merge":
"You need write access on this repository to have it merged for you once it is ready.",
"disable-auto-merge":
"You need write access on this repository to stop it being merged for you once it is ready.",
};
/**
@@ -367,25 +346,13 @@ function toPullRequestError(
}
/**
* The provider-native repository selector. `displayName` is the full path below the host, which
* is what nested GitLab groups need; owner/name is the two-segment fallback for identities
* recorded before that field existed.
*
* Azure DevOps is the exception: `az repos pr list --repository` takes a repository name, and
* takes the organisation and project from the checkout it detects — so the recorded
* `org/project/_git/repo` path is refused outright and the whole repository reads as
* unavailable. Its name is the last segment, which is what this hands over.
*
* One function because everything downstream is keyed by what it answers: the rows' own
* `repository`, the per-repository cursors, and the detail and diff reads a row leads to.
* The provider-native repository identity. `displayName` is the full path below the host, which
* is what nested GitLab groups and Azure project paths need; owner/name is the two-segment
* fallback for identities recorded before that field existed.
*/
export function repositoryIdentityOf(project: OrchestrationProjectShell): string | null {
function repositoryIdentityOf(project: OrchestrationProjectShell): string | null {
const identity = project.repositoryIdentity;
if (!identity) return null;
if (identity.provider === "azure-devops") {
const segments = (identity.displayName ?? "").split("/").filter((part) => part !== "_git");
return identity.name || segments.at(-1) || null;
}
if (identity.displayName) return identity.displayName;
return identity.owner && identity.name ? `${identity.owner}/${identity.name}` : null;
}
@@ -393,68 +360,9 @@ export function repositoryIdentityOf(project: OrchestrationProjectShell): string
export const make = Effect.gen(function* () {
const registry = yield* PullRequestProviderRegistry;
const projections = yield* ProjectionSnapshotQuery.ProjectionSnapshotQuery;
const sourceControlProviders = yield* SourceControlProviderRegistry.SourceControlProviderRegistry;
const refineUnknownProjectKinds = (
projects: ReadonlyArray<OrchestrationProjectShell>,
filter: Pick<PullRequestListInput, "projectId" | "host">,
) => {
type RefinementCandidate = {
readonly project: OrchestrationProjectShell;
readonly provider: SourceControlProviderInfo;
readonly remoteName: string;
readonly remoteUrl: string;
};
const refinements = new Map<string, RefinementCandidate[]>();
for (const project of projects) {
if (filter.projectId !== undefined && project.id !== filter.projectId) continue;
const identity = project.repositoryIdentity;
if (identity?.provider !== "unknown" || repositoryIdentityOf(project) === null) continue;
const host = pullRequestHostOf(identity, "unknown");
// A legacy identity has no canonical host until its provider is refined, so it must reach
// the refinement before a host filter can decide whether it belongs in the result.
if (filter.host !== undefined && host !== "unknown" && host !== filter.host.toLowerCase()) {
continue;
}
const { remoteName, remoteUrl } = identity.locator;
const provider = detectSourceControlProviderFromRemoteUrl(remoteUrl);
if (provider !== null) {
const candidates = refinements.get(provider.baseUrl);
const candidate = { project, provider, remoteName, remoteUrl };
if (candidates === undefined) refinements.set(provider.baseUrl, [candidate]);
else candidates.push(candidate);
}
}
return Effect.forEach(
refinements,
([baseUrl, candidates]) =>
Effect.firstSuccessOf(
candidates.map(({ project, provider, remoteName, remoteUrl }) =>
Effect.suspend(() =>
sourceControlProviders.resolveHandle({
cwd: project.workspaceRoot,
context: { provider, remoteName, remoteUrl },
}),
).pipe(
Effect.flatMap((handle) => {
const kind = handle.context?.provider.kind;
return kind === undefined || kind === "unknown"
? Effect.fail(undefined)
: Effect.succeed(kind);
}),
),
),
).pipe(
Effect.map((kind) => [baseUrl, kind] as const),
Effect.orElseSucceed(() => [baseUrl, "unknown"] as const),
),
{ concurrency: REPOSITORY_CONCURRENCY },
).pipe(Effect.map((resolved) => new Map(resolved)));
};
const listWorkspaceProjects = (
filter: Pick<PullRequestListInput, "projectId" | "projectIds" | "host">,
filter: Pick<PullRequestListInput, "projectId" | "host">,
): Effect.Effect<WorkspaceProjects, PullRequestError> =>
projections.getShellSnapshot().pipe(
Effect.mapError(
@@ -465,12 +373,7 @@ export const make = Effect.gen(function* () {
cause: error,
}),
),
Effect.flatMap((snapshot) =>
refineUnknownProjectKinds(snapshot.projects, filter).pipe(
Effect.map((refinedKinds) => ({ refinedKinds, snapshot })),
),
),
Effect.map(({ refinedKinds, snapshot }) => {
Effect.map((snapshot) => {
const supported: SupportedProject[] = [];
const unimplemented = new Map<
string,
@@ -480,19 +383,15 @@ export const make = Effect.gen(function* () {
const seen = new Set<string>();
for (const project of snapshot.projects) {
if (filter.projectId !== undefined && project.id !== filter.projectId) continue;
if (filter.projectIds !== undefined && !filter.projectIds.includes(project.id)) continue;
const identity = project.repositoryIdentity;
let kind = identity?.provider as SourceControlProviderKind | undefined;
const kind = project.repositoryIdentity?.provider as
| SourceControlProviderKind
| undefined;
const repository = repositoryIdentityOf(project);
if (!identity || kind === undefined || repository === null) continue;
if (kind === undefined || repository === null) continue;
// Worktrees of one repository are separate projects; reading the remote once keeps
// the page from repeating every change request per local checkout. The host is part
// of the key, so the same `owner/repo` on two hosts stays two repositories.
if (kind === "unknown") {
const provider = detectSourceControlProviderFromRemoteUrl(identity.locator.remoteUrl);
kind = provider === null ? kind : (refinedKinds.get(provider.baseUrl) ?? kind);
}
const host = pullRequestHostOf(identity, kind);
const host = pullRequestHostOf(project.repositoryIdentity, kind);
if (filter.host !== undefined && host !== filter.host.toLowerCase()) continue;
const api = registry.get(kind);
// Recorded before the de-duplication below, so the viewer lookup keeps the alternates
@@ -634,43 +533,6 @@ export const make = Effect.gen(function* () {
{ concurrency: REPOSITORY_CONCURRENCY },
);
/**
* The narrowings a row can be judged by from its own fields, applied here rather than trusted
* to the host. Only GitHub is asked to narrow a listing for itself; every other provider
* answers unnarrowed, and without this pass a draft filter or a label filter would be sent,
* accepted and quietly ignored. Idempotent for the hosts that did narrow.
*
* `checks` is absent because no listed row carries its check state: that one filter is the
* host's alone, and a row nobody narrowed stays rather than being guessed at.
*/
const matchesRowFilters = (
item: ProviderChangeRequest,
filters: PullRequestListFilters | undefined,
viewer: string,
): boolean => {
if (filters === undefined) return true;
const labels = item.labels.map((label) => label.name.trim().toLowerCase());
const holds = (label: string) => labels.includes(label.trim().toLowerCase());
return (
(filters.draft === undefined || item.isDraft === (filters.draft === "only")) &&
// Judged on the provider row rather than the entry, because the two absences mean
// different things and the entry keeps only one of them: `null` is a host that summarises
// its reviews saying there is no decision yet, which is what "none" asks for, while
// `undefined` is a host that does not summarise at all — an unjudgeable row, left alone
// the way an unreadable check state is.
(filters.review === undefined ||
item.reviewDecision === undefined ||
(filters.review === "none"
? item.reviewDecision === null
: item.reviewDecision === filters.review)) &&
(filters.labels === undefined || filters.labels.every((group) => group.some(holds))) &&
(filters.excludedLabels === undefined || !filters.excludedLabels.some(holds)) &&
(filters.author === undefined ||
item.author?.login.toLowerCase() ===
resolvePullRequestAuthorFilter(filters.author, viewer).toLowerCase())
);
};
const toEntry = (input: {
readonly project: SupportedProject;
readonly item: ProviderChangeRequest;
@@ -696,16 +558,10 @@ export const make = Effect.gen(function* () {
deletions: input.item.deletions,
createdAt: input.item.createdAt,
updatedAt: input.item.updatedAt,
...(input.item.checksState === undefined || input.item.checksState === null
? {}
: { checksState: input.item.checksState }),
viewerReviewRequested:
input.item.author?.login.toLowerCase() !== viewer &&
input.item.reviewRequestLogins.some((login) => login.toLowerCase() === viewer),
labels: input.item.labels,
...(input.item.reviewDecision === undefined || input.item.reviewDecision === null
? {}
: { reviewDecision: input.item.reviewDecision }),
};
};
@@ -829,7 +685,6 @@ export const make = Effect.gen(function* () {
// Each host matches this its own way, and one that cannot match text at all
// answers unnarrowed rather than failing.
query: input.query,
filters: input.filters,
// Only the two fields a host can act on: which rows have already been sent at the
// boundary instant is this service's business, not a provider's.
...(cursor === undefined
@@ -853,9 +708,7 @@ export const make = Effect.gen(function* () {
);
return {
key,
entries: items
.filter((item) => matchesRowFilters(item, input.filters, viewer))
.map((item) => toEntry({ project, item, viewer })),
entries: items.map((item) => toEntry({ project, item, viewer })),
errors: [],
truncated: page.truncated,
nextCursor:
@@ -913,7 +766,6 @@ export const make = Effect.gen(function* () {
viewer,
limit,
query: input.query,
filters: input.filters,
...(cursor === undefined
? {}
: { cursor: { updatedBefore: cursor.updatedBefore, delivered: cursor.delivered } }),
@@ -959,9 +811,7 @@ export const make = Effect.gen(function* () {
);
return Effect.succeed({
key: listCursorKey(project.host, project.repository),
entries: items
.filter((item) => matchesRowFilters(item, input.filters, viewer))
.map((item) => toEntry({ project, item, viewer })),
entries: items.map((item) => toEntry({ project, item, viewer })),
errors: [],
truncated: page.truncated,
nextCursor:
@@ -1019,72 +869,51 @@ export const make = Effect.gen(function* () {
};
});
/**
* Who this project's host says the reader is. Shared with the listing's own lookup — the same
* ten-minute answer per host — so a page that has already listed anything pays nothing for it,
* and a host that cannot say leaves it null rather than failing the read it decorates.
*/
const viewerOf = (project: SupportedProject): Effect.Effect<string | null> =>
resolveViewers([project], new Map()).pipe(Effect.map(([resolved]) => resolved?.viewer ?? null));
const detailUncached: PullRequestService["Service"]["detail"] = (input) =>
requireProject(input).pipe(
Effect.flatMap((project) =>
Effect.all(
[
project.api
.getChangeRequest({
cwd: project.project.workspaceRoot,
project.api
.getChangeRequest({
cwd: project.project.workspaceRoot,
repository: project.repository,
host: project.host,
number: input.number,
})
.pipe(
Effect.mapError(toPullRequestError("detail")),
Effect.map(
(changeRequest): PullRequestDetail => ({
provider: project.api.kind,
capabilities: project.api.capabilities,
projectId: project.project.id,
projectTitle: project.project.title,
workspaceRoot: project.project.workspaceRoot,
repository: project.repository,
host: project.host,
number: input.number,
})
.pipe(Effect.mapError(toPullRequestError("detail"))),
viewerOf(project),
],
{ concurrency: 2 },
).pipe(
Effect.map(
([changeRequest, viewer]): PullRequestDetail => ({
provider: project.api.kind,
capabilities: project.api.capabilities,
projectId: project.project.id,
projectTitle: project.project.title,
workspaceRoot: project.project.workspaceRoot,
repository: project.repository,
number: changeRequest.number,
title: changeRequest.title,
body: changeRequest.body,
url: changeRequest.url,
author: changeRequest.author,
state: changeRequest.state,
isDraft: changeRequest.isDraft,
mergeability: changeRequest.mergeability,
additions: changeRequest.additions,
deletions: changeRequest.deletions,
changedFiles: changeRequest.changedFiles,
headBranch: changeRequest.headBranch,
baseBranch: changeRequest.baseBranch,
createdAt: changeRequest.createdAt,
updatedAt: changeRequest.updatedAt,
mergedAt: changeRequest.mergedAt,
closedAt: changeRequest.closedAt,
reviewers: changeRequest.reviewers,
labels: changeRequest.labels,
checks: changeRequest.checks,
mergeCapabilities: changeRequest.mergeCapabilities,
viewerPermissions: changeRequest.viewerPermissions,
...(viewer === null || viewer.trim().length === 0 ? {} : { viewer }),
...(changeRequest.baseComparison === undefined
? {}
: { baseComparison: changeRequest.baseComparison }),
...(changeRequest.behindBy === undefined ? {} : { behindBy: changeRequest.behindBy }),
...(changeRequest.autoMergeEnabled === undefined
? {}
: { autoMergeEnabled: changeRequest.autoMergeEnabled }),
}),
number: changeRequest.number,
title: changeRequest.title,
body: changeRequest.body,
url: changeRequest.url,
author: changeRequest.author,
state: changeRequest.state,
isDraft: changeRequest.isDraft,
mergeability: changeRequest.mergeability,
additions: changeRequest.additions,
deletions: changeRequest.deletions,
changedFiles: changeRequest.changedFiles,
headBranch: changeRequest.headBranch,
baseBranch: changeRequest.baseBranch,
createdAt: changeRequest.createdAt,
updatedAt: changeRequest.updatedAt,
mergedAt: changeRequest.mergedAt,
closedAt: changeRequest.closedAt,
reviewers: changeRequest.reviewers,
labels: changeRequest.labels,
checks: changeRequest.checks,
mergeCapabilities: changeRequest.mergeCapabilities,
viewerPermissions: changeRequest.viewerPermissions,
}),
),
),
),
),
);
@@ -1109,7 +938,6 @@ export const make = Effect.gen(function* () {
commentsTruncated: activity.commentsTruncated,
reviewThreads: activity.reviewThreads,
commits: activity.commits,
...(activity.reactions === undefined ? {} : { reactions: activity.reactions }),
}),
),
),
@@ -1190,19 +1018,6 @@ export const make = Effect.gen(function* () {
}),
);
}
// The same for the way a stale branch is brought up to date: a host that only merges
// must not be asked to rebase and left to pick something else.
if (
input.updateMethod !== undefined &&
!(project.api.capabilities.updateMethods ?? []).includes(input.updateMethod)
) {
return Effect.fail(
new PullRequestOperationError({
operation: "runAction",
detail: `This host cannot update a branch by ${input.updateMethod}.`,
}),
);
}
// What the host can do and what this account may ask of it are two questions, and both
// have to say yes. The second is asked last, because it costs a request and the checks
// above do not.
@@ -1216,17 +1031,6 @@ export const make = Effect.gen(function* () {
}),
);
}
if (
input.updateMethod !== undefined &&
!(viewer.updateMethods ?? []).includes(input.updateMethod)
) {
return Effect.fail(
new PullRequestOperationError({
operation: "runAction",
detail: ACTION_ACCESS_REFUSALS["update-branch"],
}),
);
}
return project.api
.runAction({
cwd: project.project.workspaceRoot,
@@ -1235,7 +1039,6 @@ export const make = Effect.gen(function* () {
number: input.number,
action: input.action,
...(input.mergeMethod === undefined ? {} : { mergeMethod: input.mergeMethod }),
...(input.updateMethod === undefined ? {} : { updateMethod: input.updateMethod }),
})
.pipe(Effect.mapError(toPullRequestError("runAction")));
}),
@@ -1289,76 +1092,6 @@ export const make = Effect.gen(function* () {
}),
);
/**
* Rewriting the change request's own words, and rewriting a remark, are both left to the host to
* allow or refuse. Neither is a question a permission read answers: every host lets the person
* who wrote something rewrite it whatever access they have otherwise, and none of them reports
* that as a permission — so a check here could only guess, and a wrong guess takes the control
* away from the one person certain to be allowed.
*/
const update: PullRequestService["Service"]["update"] = (input) =>
requireProject(input).pipe(
Effect.flatMap((project): Effect.Effect<void, PullRequestError> => {
const rewrite = project.api.updateChangeRequest;
if (project.api.capabilities.edit?.changeRequest !== true || rewrite === undefined) {
return Effect.fail(
new PullRequestOperationError({
operation: "update",
detail: "This host cannot rewrite a change request.",
}),
);
}
if (input.title === undefined && input.body === undefined) {
return Effect.fail(
new PullRequestOperationError({
operation: "update",
detail: "Nothing was changed.",
}),
);
}
return rewrite({
cwd: project.project.workspaceRoot,
repository: project.repository,
host: project.host,
number: input.number,
...(input.title === undefined ? {} : { title: input.title }),
...(input.body === undefined ? {} : { body: input.body }),
}).pipe(Effect.mapError(toPullRequestError("update")));
}),
);
const updateComment: PullRequestService["Service"]["updateComment"] = (input) =>
(input.body.trim().length === 0
? Effect.fail(
new PullRequestOperationError({
operation: "updateComment",
detail: "A comment cannot be empty.",
}),
)
: requireProject(input)
).pipe(
Effect.flatMap((project): Effect.Effect<void, PullRequestError> => {
const rewrite = project.api.updateComment;
if (project.api.capabilities.edit?.comment !== true || rewrite === undefined) {
return Effect.fail(
new PullRequestOperationError({
operation: "updateComment",
detail: "This host cannot rewrite a comment.",
}),
);
}
return rewrite({
cwd: project.project.workspaceRoot,
repository: project.repository,
host: project.host,
number: input.number,
commentId: input.commentId,
kind: input.kind,
body: input.body,
}).pipe(Effect.mapError(toPullRequestError("updateComment")));
}),
);
const submitReview: PullRequestService["Service"]["submitReview"] = (input) =>
requireProject(input).pipe(
Effect.flatMap((project): Effect.Effect<void, PullRequestError> => {
@@ -1494,36 +1227,6 @@ export const make = Effect.gen(function* () {
}),
);
/**
* Reacting is gated on the host alone. Every host with reactions takes one from whoever can read
* the change request, so there is no access left to check that reading it has not already
* settled.
*/
const setReaction: PullRequestService["Service"]["setReaction"] = (input) =>
requireProject(input).pipe(
Effect.flatMap((project): Effect.Effect<void, PullRequestError> => {
if (project.api.capabilities.reactions !== true) {
return Effect.fail(
new PullRequestOperationError({
operation: "setReaction",
detail: "This host has no reactions.",
}),
);
}
return project.api
.setReaction({
cwd: project.project.workspaceRoot,
repository: project.repository,
host: project.host,
number: input.number,
...(input.subjectId === undefined ? {} : { subjectId: input.subjectId }),
content: input.content,
reacted: input.reacted,
})
.pipe(Effect.mapError(toPullRequestError("setReaction")));
}),
);
/**
* Who may be asked is only ever wanted by somebody about to ask, because the menu it fills is
* the one the request is made from. So the same permission guards both: a page that could open
@@ -1747,23 +1450,6 @@ export const make = Effect.gen(function* () {
refEpochs.set(scope, ++epochCounter);
};
/** The positional filter slot of a cache key, back as the record `listUncached` takes. */
const filtersOfKey = (
slots: ReadonlyArray<
string | ReadonlyArray<string> | ReadonlyArray<ReadonlyArray<string>> | null
>,
): PullRequestListFilters => {
const [draft, review, checks, author, labels, excludedLabels] = slots;
return {
...(typeof draft === "string" ? { draft: draft as "only" | "hide" } : {}),
...(typeof review === "string" ? { review: review as PullRequestListFilters["review"] } : {}),
...(typeof checks === "string" ? { checks: checks as PullRequestListFilters["checks"] } : {}),
...(typeof author === "string" ? { author } : {}),
...(Array.isArray(labels) ? { labels: labels as ReadonlyArray<ReadonlyArray<string>> } : {}),
...(Array.isArray(excludedLabels) ? { excludedLabels } : {}),
};
};
// Keys serialize positionally and parse back in the lookup, so the cache is the only holder
// of in-flight state: concurrent identical reads coalesce on the key into one host request.
// The continuation cursors are part of the key, entries sorted so one continuation is one
@@ -1772,24 +1458,13 @@ export const make = Effect.gen(function* () {
(key: string) => {
// The parse undoes this module's own serialization, so the shapes are known exactly;
// the cast restores the branded field types JSON cannot carry.
const [
,
state,
involvement,
filters,
projectId,
projectIds,
host,
limit,
query,
cursorEntries,
] = JSON.parse(key) as [
const [, state, involvement, projectId, host, limit, query, cursorEntries] = JSON.parse(
key,
) as [
number,
string,
string | null,
ReadonlyArray<string | ReadonlyArray<string> | null> | null,
string | null,
ReadonlyArray<string> | null,
string | null,
number | null,
string | null,
@@ -1798,9 +1473,7 @@ export const make = Effect.gen(function* () {
return listUncached({
state,
...(involvement === null ? {} : { involvement }),
...(filters === null ? {} : { filters: filtersOfKey(filters) }),
...(projectId === null ? {} : { projectId }),
...(projectIds === null ? {} : { projectIds }),
...(host === null ? {} : { host }),
...(limit === null ? {} : { limit }),
...(query === null ? {} : { query }),
@@ -1821,20 +1494,7 @@ export const make = Effect.gen(function* () {
listingsEpoch,
input.state,
input.involvement ?? null,
// Positional so two identical filter sets key alike however their record was assembled.
input.filters === undefined
? null
: [
input.filters.draft ?? null,
input.filters.review ?? null,
input.filters.checks ?? null,
input.filters.author ?? null,
input.filters.labels ?? null,
input.filters.excludedLabels ?? null,
],
input.projectId ?? null,
// Sorted so the same narrowing keys alike however the caller ordered it.
input.projectIds === undefined ? null : [...input.projectIds].sort(),
input.host ?? null,
input.limit ?? null,
input.query ?? null,
@@ -1996,13 +1656,10 @@ export const make = Effect.gen(function* () {
diff,
diffFileContents,
runAction: invalidatedByMutation(runAction),
update: invalidatedByMutation(update),
comment: invalidatedByMutation(comment),
updateComment: invalidatedByMutation(updateComment),
submitReview: invalidatedByMutation(submitReview),
replyToThread: invalidatedByMutation(replyToThread),
setThreadResolution: invalidatedByMutation(setThreadResolution),
setReaction: invalidatedByMutation(setReaction),
// The candidate list is deliberately read fresh per menu-open, so it stays uncached.
reviewerCandidates,
requestReviewers: invalidatedByMutation(requestReviewers),
@@ -144,21 +144,6 @@ describe("decodePullRequestJson", () => {
]);
});
it("reads auto-complete from whoever armed it, and its absence as nobody", () => {
const armed = expectSuccess(
decodePullRequestJson(
asJson(pullRequest({ autoCompleteSetBy: { displayName: "Bilal Hassan" } })),
),
);
expect(armed?.autoMergeEnabled).toBe(true);
// Azure leaves the field out entirely rather than sending it empty, so its absence is the
// whole of what it says about auto-complete being off.
expect(expectSuccess(decodePullRequestJson(asJson(pullRequest())))?.autoMergeEnabled).toBe(
false,
);
});
it("works out where the conversation lives from what Azure returned", () => {
const detail = expectSuccess(decodePullRequestJson(asJson(pullRequest())));
@@ -35,12 +35,6 @@ const RawPullRequestSchema = Schema.Struct({
description: Schema.optional(Schema.NullOr(Schema.String)),
status: Schema.optional(Schema.NullOr(Schema.String)),
isDraft: Schema.optional(Schema.NullOr(Schema.Boolean)),
/**
* Who armed auto-complete, which is the only thing Azure says about it: the field carries an
* identity while the pull request is set to complete on its own, and Azure leaves it out
* entirely once nobody has. So its presence is the answer, and there is no third state.
*/
autoCompleteSetBy: Schema.optional(Schema.NullOr(RawIdentitySchema)),
mergeStatus: Schema.optional(Schema.NullOr(Schema.String)),
createdBy: Schema.optional(Schema.NullOr(RawIdentitySchema)),
reviewers: Schema.optional(Schema.NullOr(Schema.Array(RawIdentitySchema))),
@@ -130,8 +124,6 @@ export interface AzureDevOpsPullRequest {
readonly reviewers: ReadonlyArray<PullRequestActor>;
/** Where this pull request's threads live, when Azure said enough to work it out. */
readonly threadsUrl: string | null;
/** Whether Azure is set to complete this on its own once its policies pass. */
readonly autoMergeEnabled: boolean;
}
function trimmed(value: string | null | undefined): string | null {
@@ -231,7 +223,6 @@ function toPullRequest(
reviewRequestLogins: reviewers.map((reviewer) => reviewer.login),
reviewers,
threadsUrl: toThreadsUrl(raw),
autoMergeEnabled: (raw.autoCompleteSetBy ?? null) !== null,
};
}
@@ -315,22 +315,6 @@ describe("decodeStatusesJson", () => {
expect(decoded.items[0]?.status).toBe(expected);
});
it("keeps two statuses that share a display name but have different keys", () => {
const decoded = expectSuccess(
decodeStatusesJson(
page([
{ key: "build", name: "Pipeline", state: "SUCCESSFUL" },
{ key: "deploy", name: "Pipeline", state: "FAILED" },
]),
),
);
expect(decoded.items.map((check) => [check.name, check.status])).toEqual([
["build / Pipeline", "success"],
["deploy / Pipeline", "failure"],
]);
});
});
describe("decodeDiffstatJson", () => {
@@ -18,8 +18,6 @@ import type {
import { TrimmedNonEmptyString } from "@t3tools/contracts";
import { decodeJsonResult } from "@t3tools/shared/schemaJson";
import { dedupeChecks } from "./pullRequestChecks.ts";
/**
* Bitbucket's enums are decoded as plain strings and normalized here, in the same tolerant
* style as the GitHub and GitLab decoders: a new pull request state or build status must not
@@ -549,33 +547,21 @@ export function decodeStatusesJson(
if (!Result.isSuccess(decoded)) {
return Result.fail(decoded.failure);
}
const checks: Array<{
readonly check: PullRequestCheck;
readonly workflowName: string | null;
readonly at: string | null;
}> = [];
const checks: PullRequestCheck[] = [];
for (const entry of decoded.success.values) {
const decodedStatus = decodeStatusEntry(entry);
if (Exit.isFailure(decodedStatus)) continue;
const status = decodedStatus.value;
const name = trimmed(status.name) ?? trimmed(status.key);
if (name === null) continue;
// Bitbucket re-uses a status key when a pipeline is run again, so the same check can appear
// twice on one page. Nothing decoded here says which copy is newer, so the later one wins,
// which is the order Bitbucket writes an update in. The key is kept as the workflow name so
// two different pipelines that display the same name are not folded into one.
checks.push({
check: {
name,
status: toBuildStatus(status.state),
description: trimmed(status.description),
url: trimmed(status.url),
},
workflowName: trimmed(status.key),
at: null,
name,
status: toBuildStatus(status.state),
description: trimmed(status.description),
url: trimmed(status.url),
});
}
return Result.succeed({ items: dedupeChecks(checks), next: trimmed(decoded.success.next) });
return Result.succeed({ items: checks, next: trimmed(decoded.success.next) });
}
export interface BitbucketDiffStat {
@@ -4,20 +4,16 @@ import { describe, expect, it } from "vite-plus/test";
import {
buildReviewSubmissionJson,
buildReviewerRequestJson,
decodeBaseComparisonJson,
decodePullRequestActivityJson,
decodePullRequestDetailJson,
decodePullRequestFilesJson,
decodePullRequestListJson,
decodePullRequestNodeIdJson,
decodePullRequestSearchJson,
decodeRepositoryAccessJson,
decodeReviewerCandidatesJson,
decodeReviewThreadCommentsJson,
decodeReviewThreadsJson,
decodeViewerPermissionsJson,
reviewThreadConversation,
REVIEW_THREADS_GRAPHQL_QUERY,
} from "./gitHubPullRequestJson.ts";
function listJson(entries: ReadonlyArray<Record<string, unknown>>): string {
@@ -71,65 +67,6 @@ describe("pull request list decoding", () => {
expect(entry?.reviewRequestLogins).toEqual(["octocat"]);
});
it("normalizes the review decision and reports nothing for one GitHub does not summarize", () => {
const batch = expectSuccess(
decodePullRequestListJson(
listJson([
{ reviewDecision: "APPROVED" },
{ reviewDecision: "CHANGES_REQUESTED" },
{ reviewDecision: "REVIEW_REQUIRED" },
{ reviewDecision: null },
]),
),
);
expect(batch.items.map((entry) => entry.reviewDecision)).toEqual([
"approved",
"changes-requested",
"review-required",
null,
]);
});
it("rolls the head commit's checks up to the one word a row has space for", () => {
const batch = expectSuccess(
decodePullRequestListJson(
listJson([
// A failure outranks a run still going, and a completed run has to be read through its
// conclusion rather than its status.
{
statusCheckRollup: [
{ name: "lint", status: "COMPLETED", conclusion: "SUCCESS" },
{ name: "build", status: "IN_PROGRESS" },
{ name: "test", status: "COMPLETED", conclusion: "FAILURE" },
],
},
{
statusCheckRollup: [
{ name: "lint", status: "COMPLETED", conclusion: "SUCCESS" },
{ name: "build", status: "QUEUED" },
],
},
{ statusCheckRollup: [{ name: "lint", status: "COMPLETED", conclusion: "SUCCESS" }] },
// A commit status reports one `state` and no `status` at all.
{ statusCheckRollup: [{ context: "ci/legacy", state: "ERROR" }] },
// Neither a pass, a failure nor a wait is no verdict rather than a green tick.
{ statusCheckRollup: [{ name: "lint", status: "COMPLETED", conclusion: "SKIPPED" }] },
{ statusCheckRollup: [] },
{},
]),
),
);
expect(batch.items.map((entry) => entry.checksState)).toEqual([
"failing",
"pending",
"passing",
"failing",
null,
null,
null,
]);
});
it("skips malformed entries but still counts them, so paging does not stop early", () => {
const raw = `[${listJson([{}]).slice(1, -1)},{"number":"not-a-number"}]`;
const batch = expectSuccess(decodePullRequestListJson(raw));
@@ -138,49 +75,6 @@ describe("pull request list decoding", () => {
});
});
describe("pull request search decoding", () => {
function searchJson(rollupStates: ReadonlyArray<string | null>): string {
return JSON.stringify({
data: {
search: {
pageInfo: { hasNextPage: false },
nodes: rollupStates.map((state, index) => ({
number: index + 1,
title: "Add the pull requests page",
url: "https://github.com/pingdotgg/t3code/pull/1",
headRefName: "feat/page",
baseRefName: "main",
createdAt: "2026-07-01T00:00:00Z",
updatedAt: "2026-07-02T00:00:00Z",
repository: { nameWithOwner: "pingdotgg/t3code" },
commits: {
nodes: [{ commit: { statusCheckRollup: state === null ? null : { state } } }],
},
})),
},
},
});
}
it("maps the rollup enum the search answers with onto the same three words", () => {
// The search asks GitHub for the verdict rather than the checks behind it, so this path sees
// one enum where the listing sees an array.
const batch = expectSuccess(
decodePullRequestSearchJson(
searchJson(["SUCCESS", "FAILURE", "ERROR", "PENDING", "EXPECTED", null]),
),
);
expect(batch.items.map((entry) => entry.checksState)).toEqual([
"passing",
"failing",
"failing",
"pending",
"pending",
null,
]);
});
});
describe("pull request detail decoding", () => {
const detailJson = JSON.stringify({
number: 7,
@@ -223,58 +117,6 @@ describe("pull request detail decoding", () => {
]);
});
it("reads an auto-merge request as armed, its null as off and its absence as neither", () => {
const raw = JSON.parse(detailJson) as Record<string, unknown>;
const armed = (entry: Record<string, unknown>) =>
expectSuccess(decodePullRequestDetailJson(JSON.stringify({ ...raw, ...entry })))
.autoMergeEnabled;
expect(
armed({ autoMergeRequest: { enabledBy: { login: "octocat" }, mergeMethod: "SQUASH" } }),
).toBe(true);
expect(armed({ autoMergeRequest: null })).toBe(false);
// `gh` not answering for the field at all is not GitHub saying the merge is unarmed.
expect(armed({})).toBeUndefined();
});
it("shows a re-running check once, as the run that is happening now", () => {
// What `statusCheckRollup` reports while a workflow is being re-run: the same check twice,
// the finished run and the one that replaced it, with no id to tell them apart.
const raw = JSON.parse(detailJson) as Record<string, unknown>;
const detail = expectSuccess(
decodePullRequestDetailJson(
JSON.stringify({
...raw,
statusCheckRollup: [
{
__typename: "CheckRun",
name: "Prepare PR size config",
workflowName: "PR Size",
status: "COMPLETED",
conclusion: "SUCCESS",
startedAt: "2026-08-11T16:06:20Z",
completedAt: "2026-08-11T16:06:25Z",
},
{
__typename: "CheckRun",
name: "Prepare PR size config",
workflowName: "PR Size",
status: "IN_PROGRESS",
conclusion: "",
startedAt: "2026-08-11T17:01:04Z",
completedAt: "0001-01-01T00:00:00Z",
},
],
}),
),
);
expect(detail.checks.map((check) => [check.name, check.status])).toEqual([
["Prepare PR size config", "pending"],
]);
expect(detail.checksState).toBe("pending");
});
it("merges reviews with comments in time order and keeps a bodyless approval", () => {
const detail = expectSuccess(decodePullRequestActivityJson(detailJson));
// r2 approved without writing anything, which is still the event worth seeing.
@@ -619,89 +461,6 @@ describe("review thread decoding", () => {
});
});
describe("reaction decoding", () => {
const commentWithGroups = (reactionGroups: ReadonlyArray<Record<string, unknown>>) =>
JSON.stringify({
data: {
node: {
comments: {
pageInfo: { hasNextPage: false, endCursor: null },
nodes: [{ id: "t1", body: "nice", createdAt: "2026-07-01T00:00:00Z", reactionGroups }],
},
},
},
});
it("keeps a named group, widens a group whose reactors were cut short, drops an unknown content and an empty group", () => {
const decoded = expectSuccess(
decodeReviewThreadCommentsJson(
commentWithGroups([
{
content: "THUMBS_UP",
viewerHasReacted: true,
reactors: { totalCount: 2, nodes: [{ login: "julius" }, { login: "bilal" }] },
},
// Not one of the eight the contract carries.
{
content: "PARTY_PARROT",
reactors: { totalCount: 1, nodes: [{ login: "hubot" }] },
},
// Nobody behind it, which GitHub still answers a group for.
{ content: "HEART", reactors: { totalCount: 0, nodes: [] } },
// More reactors than the bounded read named, and no `viewerHasReacted` at all.
{
content: "ROCKET",
reactors: { totalCount: 140, nodes: [{ login: "a" }, { login: "b" }, { login: "c" }] },
},
]),
),
);
expect(decoded.comments[0]?.reactions).toEqual([
{ content: "thumbs-up", count: 2, actors: ["julius", "bilal"], viewerHasReacted: true },
{ content: "rocket", count: 140, actors: ["a", "b", "c"], viewerHasReacted: false },
]);
});
it("leaves the viewer's own login out of actors, matched case-insensitively, while count still counts them", () => {
const decoded = expectSuccess(
decodeReviewThreadCommentsJson(
JSON.stringify({
data: {
viewer: { login: "Bilal" },
node: {
comments: {
pageInfo: { hasNextPage: false, endCursor: null },
nodes: [
{
id: "t1",
body: "nice",
createdAt: "2026-07-01T00:00:00Z",
reactionGroups: [
{
content: "HEART",
viewerHasReacted: true,
reactors: {
totalCount: 2,
nodes: [{ login: "bilal" }, { login: "julius" }],
},
},
],
},
],
},
},
},
}),
),
);
expect(decoded.comments[0]?.reactions).toEqual([
{ content: "heart", count: 2, actors: ["julius"], viewerHasReacted: true },
]);
});
});
describe("repository access decoding", () => {
const repositoryJson = (viewerPermission?: string | null) =>
JSON.stringify({
@@ -859,7 +618,6 @@ describe("review thread decoding", () => {
body: "first",
createdAt: "2026-07-01T00:00:00Z",
url: "https://github.com/acme/web/pull/1#discussion_rc1",
reactions: [],
},
{
id: "c2",
@@ -867,7 +625,6 @@ describe("review thread decoding", () => {
body: "second",
createdAt: "2026-07-01T00:00:00Z",
url: "https://github.com/acme/web/pull/1#discussion_rc2",
reactions: [],
},
],
},
@@ -919,101 +676,6 @@ describe("review thread decoding", () => {
expect(reviewThreadConversation(threads).map((comment) => comment.id)).toEqual(["c4"]);
expect(threads).toHaveLength(1);
});
it("puts an issue comment's and a review's reactions in reactionsById, and the pull request's own in reactions", () => {
const result = expectSuccess(
decodeReviewThreadsJson(
threadsJson([], {
reactionGroups: [
{
content: "HEART",
viewerHasReacted: true,
reactors: { totalCount: 1, nodes: [{ login: "bilal" }] },
},
],
comments: {
nodes: [
{
id: "c1",
reactionGroups: [
{
content: "THUMBS_UP",
reactors: { totalCount: 1, nodes: [{ login: "julius" }] },
},
],
},
],
},
reviews: {
nodes: [
{
id: "r1",
reactionGroups: [
{ content: "EYES", reactors: { totalCount: 1, nodes: [{ login: "hubot" }] } },
],
},
],
},
}),
),
);
expect(result.reactions).toEqual([
{ content: "heart", count: 1, actors: ["bilal"], viewerHasReacted: true },
]);
expect([...result.reactionsById]).toEqual([
["c1", [{ content: "thumbs-up", count: 1, actors: ["julius"], viewerHasReacted: false }]],
["r1", [{ content: "eyes", count: 1, actors: ["hubot"], viewerHasReacted: false }]],
]);
});
it("leaves the viewer's own login out of the pull request's own reactions, matched case-insensitively, while count still counts them", () => {
const result = expectSuccess(
decodeReviewThreadsJson(
JSON.stringify({
data: {
viewer: { login: "Bilal" },
repository: {
pullRequest: {
reviewThreads: { totalCount: 0, nodes: [] },
reactionGroups: [
{
content: "HEART",
viewerHasReacted: true,
reactors: { totalCount: 2, nodes: [{ login: "bilal" }, { login: "julius" }] },
},
],
},
},
},
}),
),
);
expect(result.reactions).toEqual([
{ content: "heart", count: 2, actors: ["julius"], viewerHasReacted: true },
]);
});
});
describe("decodePullRequestNodeIdJson", () => {
it("reads the pull request's own node id, which a reaction on its description is addressed by", () => {
expect(
expectSuccess(
decodePullRequestNodeIdJson(
JSON.stringify({ data: { repository: { pullRequest: { id: "PR_kwDOA" } } } }),
),
),
).toBe("PR_kwDOA");
});
});
describe("REVIEW_THREADS_GRAPHQL_QUERY", () => {
it("asks for reactionGroups on the pull request itself, its comments, its reviews and each thread's comments", () => {
expect(REVIEW_THREADS_GRAPHQL_QUERY.match(/reactionGroups/g)).toHaveLength(4);
// The reviews connection is new: only reactions were ever wanted off it.
expect(REVIEW_THREADS_GRAPHQL_QUERY).toContain("reviews(first:");
});
});
describe("reviewer candidate decoding", () => {
@@ -1295,45 +957,3 @@ describe("decodePullRequestFilesJson", () => {
expect(result.truncated).toBe(false);
});
});
describe("how far a branch trails its base", () => {
const comparison = (pullRequest: unknown) =>
JSON.stringify({ data: { repository: { pullRequest } } });
it("reads the commit count and whether this viewer may move the branch", () => {
const decoded = expectSuccess(
decodeBaseComparisonJson(
comparison({ viewerCanUpdateBranch: true, baseRef: { compare: { behindBy: 12 } } }),
),
);
expect(decoded).toEqual({ behindBy: 12, viewerCanUpdate: true });
});
it("reads a current branch as nothing to do", () => {
expect(
expectSuccess(
decodeBaseComparisonJson(
comparison({ viewerCanUpdateBranch: false, baseRef: { compare: { behindBy: 0 } } }),
),
),
).toEqual({ behindBy: 0, viewerCanUpdate: false });
});
it("answers unknown where the head could not be compared", () => {
// A pull request from a fork whose repository is gone, which GitHub answers with a null
// comparison beside a perfectly good pull request.
expect(
expectSuccess(
decodeBaseComparisonJson(comparison({ viewerCanUpdateBranch: true, baseRef: null })),
).behindBy,
).toBeNull();
expect(expectSuccess(decodeBaseComparisonJson(comparison(null)))).toEqual({
behindBy: null,
viewerCanUpdate: false,
});
});
it("refuses a body that is not the answer to this question", () => {
expect(Result.isSuccess(decodeBaseComparisonJson("{"))).toBe(false);
});
});
File diff suppressed because it is too large. Load diff
@@ -2,15 +2,12 @@ import * as Result from "effect/Result";
import { describe, expect, it } from "vite-plus/test";
import {
decodeAwardEmojiJson,
decodeCommitsJson,
decodeMergeRequestDetailJson,
decodeMergeRequestDiffsJson,
decodeMergeRequestListJson,
decodeNotesJson,
decodeOwnAwardIdJson,
decodeViewerJson,
gitLabAwardName,
} from "./gitLabMergeRequestJson.ts";
function listJson(entries: ReadonlyArray<Record<string, unknown>>): string {
@@ -180,31 +177,6 @@ describe("decodeMergeRequestDetailJson", () => {
expect(detail.changedFiles).toBe(0);
});
it("reads either auto-merge field, and says nothing where GitLab named neither", () => {
const armed = (entry: Record<string, unknown>) =>
expectSuccess(decodeMergeRequestDetailJson(detailJson(entry))).autoMergeEnabled;
expect(armed({ merge_when_pipeline_succeeds: true })).toBe(true);
// The newer name for the same fact, which older GitLab installs do not send.
expect(armed({ auto_merge_enabled: true })).toBe(true);
expect(armed({ merge_when_pipeline_succeeds: false })).toBe(false);
// Absent is GitLab not saying, which the page must not read as "not armed".
expect(armed({})).toBeUndefined();
});
it("keeps a divergence GitLab did not count apart from a divergence of none", () => {
const behind = (entry: Record<string, unknown>) =>
expectSuccess(decodeMergeRequestDetailJson(detailJson(entry))).divergedCommits;
expect(behind({ diverged_commits_count: 3 })).toBe(3);
// Counted and found level, which is the one answer that entitles the page to say so.
expect(behind({ diverged_commits_count: 0 })).toBe(0);
// An install that does not answer, and a null where the answer would have gone, are both
// silence: reading either as zero would tell a stale branch it is current.
expect(behind({})).toBeUndefined();
expect(behind({ diverged_commits_count: null })).toBeUndefined();
});
it("maps a pipeline waiting on a person to neutral, not failure", () => {
const detail = expectSuccess(
decodeMergeRequestDetailJson(detailJson({ head_pipeline: { status: "manual" } })),
@@ -481,130 +453,3 @@ describe("merge request viewer fields", () => {
).toBe(true);
});
});
describe("decodeAwardEmojiJson", () => {
it("reads MR-level awards, keys per-note awards by the REST id inside their gid, and ignores an award outside the eight", () => {
const result = expectSuccess(
decodeAwardEmojiJson(
JSON.stringify({
data: {
currentUser: { username: "bilal" },
project: {
mergeRequest: {
awardEmoji: {
nodes: [
{ name: "thumbsup", user: { username: "bilal" } },
{ name: "thumbsup", user: { username: "julius" } },
],
},
notes: {
pageInfo: { hasNextPage: false, endCursor: null },
nodes: [
{
id: "gid://gitlab/DiffNote/42",
awardEmoji: { nodes: [{ name: "heart", user: { username: "julius" } }] },
},
{
id: "gid://gitlab/Note/7",
// Not one of the eight the contract carries.
awardEmoji: {
nodes: [{ name: "partyparrot", user: { username: "bilal" } }],
},
},
],
},
},
},
},
}),
),
);
// `bilal` is `currentUser`, so the group they are in reads back as reacted, but their own
// username is left out of `actors` — the page names them "You" instead — while `count` still
// counts them; `julius` alone does not turn a group's own `viewerHasReacted` on.
expect(result.reactions).toEqual([
{ content: "thumbs-up", count: 2, actors: ["julius"], viewerHasReacted: true },
]);
// Note 7's only award named nobody the eight recognise, so it carries no reactions and is
// left out of the map rather than kept empty.
expect([...result.reactionsByNoteId]).toEqual([
["42", [{ content: "heart", count: 1, actors: ["julius"], viewerHasReacted: false }]],
]);
expect(result.nextCursor).toBeNull();
});
it("hands back a cursor when GitLab has more notes to page", () => {
const result = expectSuccess(
decodeAwardEmojiJson(
JSON.stringify({
data: {
currentUser: null,
project: {
mergeRequest: {
awardEmoji: { nodes: [] },
notes: { pageInfo: { hasNextPage: true, endCursor: "Y3Vyc29yOjE" }, nodes: [] },
},
},
},
}),
),
);
expect(result.nextCursor).toBe("Y3Vyc29yOjE");
});
it("matches the viewer's username case-insensitively, since GitLab is not consistent about case", () => {
const result = expectSuccess(
decodeAwardEmojiJson(
JSON.stringify({
data: {
currentUser: { username: "Bilal" },
project: {
mergeRequest: {
awardEmoji: {
nodes: [
{ name: "heart", user: { username: "bilal" } },
{ name: "heart", user: { username: "julius" } },
],
},
notes: { pageInfo: { hasNextPage: false, endCursor: null }, nodes: [] },
},
},
},
}),
),
);
expect(result.reactions).toEqual([
{ content: "heart", count: 2, actors: ["julius"], viewerHasReacted: true },
]);
});
});
describe("decodeOwnAwardIdJson", () => {
const awards = JSON.stringify([
{ id: 101, name: "thumbsup", user: { username: "julius" } },
{ id: 102, name: "thumbsup", user: { username: "bilal" } },
]);
it("finds the reader's own award of that name, which is the one a removal deletes", () => {
expect(
expectSuccess(decodeOwnAwardIdJson(awards, { content: "thumbs-up", viewer: "bilal" })),
).toBe(102);
});
it("returns nothing where the reader has no award of that name", () => {
expect(
expectSuccess(decodeOwnAwardIdJson(awards, { content: "heart", viewer: "bilal" })),
).toBeNull();
});
});
describe("gitLabAwardName", () => {
it("spells the contents whose GitLab award name is not their own kebab-case", () => {
expect(gitLabAwardName("thumbs-up")).toBe("thumbsup");
expect(gitLabAwardName("laugh")).toBe("laughing");
expect(gitLabAwardName("hooray")).toBe("tada");
});
});
@@ -11,8 +11,6 @@ import type {
PullRequestLabel,
PullRequestMergeability,
PullRequestMergeCapabilities,
PullRequestReaction,
PullRequestReactionContent,
PullRequestReviewThread,
PullRequestReviewerCandidate,
PullRequestState,
@@ -72,21 +70,6 @@ const RawMergeRequestSchema = Schema.Struct({
user: Schema.optional(
Schema.NullOr(Schema.Struct({ can_merge: Schema.optional(Schema.Boolean) })),
),
/**
* Whether GitLab is holding this merge request to merge it once its pipeline goes green.
* `merge_when_pipeline_succeeds` is the field every version answers with; newer ones also
* carry `auto_merge_enabled`, which is the same fact under the name GitLab settled on, so
* either one saying yes is a yes.
*/
merge_when_pipeline_succeeds: Schema.optional(Schema.NullOr(Schema.Boolean)),
auto_merge_enabled: Schema.optional(Schema.NullOr(Schema.Boolean)),
/**
* How far the target branch has moved on since this one left it, which is the same number
* GitLab's own "out of date" wording counts. It costs a walk of the two branches, so GitLab
* withholds it unless `include_diverged_commits_count` asks for it, and answers it only for a
* single merge request — a list never carries it, however it is asked for.
*/
diverged_commits_count: Schema.optional(Schema.NullOr(Schema.Int)),
});
const RawNoteSchema = Schema.Struct({
@@ -226,13 +209,6 @@ export interface GitLabMergeRequestDetail extends GitLabMergeRequestListItem {
readonly viewerCanMerge: boolean;
/** The reviewers as GitLab addresses them, which is what writing the set back takes. */
readonly reviewerIds: ReadonlyArray<number>;
/** Absent where GitLab named neither auto-merge field, which is not the same as off. */
readonly autoMergeEnabled?: boolean;
/**
* Absent where GitLab did not count, which is not the same as a branch that has nothing behind
* it: an install too old to answer must not be read as saying the branch is current.
*/
readonly divergedCommits?: number;
}
function trimmed(value: string | null | undefined): string | null {
@@ -358,10 +334,6 @@ function toListItem(
function toDetail(raw: Schema.Schema.Type<typeof RawMergeRequestSchema>): GitLabMergeRequestDetail {
const listItem = toListItem(raw);
const autoMerge =
raw.merge_when_pipeline_succeeds == null && raw.auto_merge_enabled == null
? undefined
: raw.merge_when_pipeline_succeeds === true || raw.auto_merge_enabled === true;
return {
...listItem,
body: raw.description ?? "",
@@ -378,8 +350,6 @@ function toDetail(raw: Schema.Schema.Type<typeof RawMergeRequestSchema>): GitLab
reviewerIds: (raw.reviewers ?? []).flatMap((reviewer) =>
reviewer.id === undefined ? [] : [reviewer.id],
),
...(autoMerge === undefined ? {} : { autoMergeEnabled: autoMerge }),
...(raw.diverged_commits_count == null ? {} : { divergedCommits: raw.diverged_commits_count }),
};
}
@@ -726,215 +696,3 @@ export function decodeMergeRequestDiffsJson(
rawCount: decoded.success.length,
});
}
/** GitLab's award names for the eight reactions the contract carries. */
const GITLAB_AWARD_BY_CONTENT: Readonly<Record<PullRequestReactionContent, string>> = {
"thumbs-up": "thumbsup",
"thumbs-down": "thumbsdown",
laugh: "laughing",
hooray: "tada",
confused: "confused",
heart: "heart",
rocket: "rocket",
eyes: "eyes",
};
const CONTENT_BY_GITLAB_AWARD: Readonly<Record<string, PullRequestReactionContent>> =
Object.fromEntries(
Object.entries(GITLAB_AWARD_BY_CONTENT).map(([content, name]) => [name, content]),
) as Readonly<Record<string, PullRequestReactionContent>>;
export function gitLabAwardName(content: PullRequestReactionContent): string {
return GITLAB_AWARD_BY_CONTENT[content];
}
/**
* Awards on the merge request and on every note of it, in one read. The REST notes endpoint the
* conversation comes from carries no award at all, and asking per note would be a request each.
*
* `currentUser` rides along because GitLab names who awarded but never says whether that is the
* reader — so the comparison is made here rather than paid for with a request of its own.
*/
export const AWARD_EMOJI_GRAPHQL_QUERY = `query($fullPath: ID!, $iid: String!, $cursor: String) {
currentUser { username }
project(fullPath: $fullPath) {
mergeRequest(iid: $iid) {
awardEmoji { nodes { name user { username } } }
notes(first: 100, after: $cursor) {
pageInfo { hasNextPage endCursor }
nodes { id awardEmoji { nodes { name user { username } } } }
}
}
}
}`;
const RawAwardEmojiNodesSchema = Schema.optional(
Schema.NullOr(
Schema.Struct({
nodes: Schema.optional(
Schema.NullOr(
Schema.Array(
Schema.NullOr(
Schema.Struct({
name: Schema.optional(Schema.NullOr(Schema.String)),
user: Schema.optional(
Schema.NullOr(
Schema.Struct({ username: Schema.optional(Schema.NullOr(Schema.String)) }),
),
),
}),
),
),
),
),
}),
),
);
const RawAwardEmojiPageSchema = Schema.Struct({
data: Schema.Struct({
currentUser: Schema.optional(
Schema.NullOr(Schema.Struct({ username: Schema.optional(Schema.NullOr(Schema.String)) })),
),
project: Schema.NullOr(
Schema.Struct({
mergeRequest: Schema.NullOr(
Schema.Struct({
awardEmoji: RawAwardEmojiNodesSchema,
notes: Schema.optional(
Schema.NullOr(
Schema.Struct({
pageInfo: Schema.optional(
Schema.Struct({
hasNextPage: Schema.optional(Schema.Boolean),
endCursor: Schema.optional(Schema.NullOr(Schema.String)),
}),
),
nodes: Schema.Array(
Schema.NullOr(
Schema.Struct({
id: Schema.optional(Schema.NullOr(Schema.String)),
awardEmoji: RawAwardEmojiNodesSchema,
}),
),
),
}),
),
),
}),
),
}),
),
}),
});
const decodeAwardEmojiPage = decodeJsonResult(RawAwardEmojiPageSchema);
/**
* The awards on one subject, grouped the way a reaction pill is drawn. The viewer's own username
* is left out of `actors` — the page names them "You" instead, and leaving it in would name them
* twice — but `count` still counts them along with everyone else.
*/
function toReactions(
nodes: Schema.Schema.Type<typeof RawAwardEmojiNodesSchema>,
viewer: string | null,
): ReadonlyArray<PullRequestReaction> {
const normalizedViewer = viewer?.toLowerCase() ?? null;
const groups = new Map<
PullRequestReactionContent,
{ count: number; actors: string[]; viewer: boolean }
>();
for (const node of nodes?.nodes ?? []) {
// An award outside the eight is left out rather than shown under a name the picker has no
// way to take back: GitLab accepts any emoji, and the other hosts accept none of them.
const content = CONTENT_BY_GITLAB_AWARD[trimmed(node?.name)?.toLowerCase() ?? ""];
if (content === undefined) continue;
const username = trimmed(node?.user?.username);
if (username === null) continue;
const group = groups.get(content) ?? { count: 0, actors: [], viewer: false };
group.count++;
if (normalizedViewer !== null && username.toLowerCase() === normalizedViewer) {
group.viewer = true;
} else {
group.actors.push(username);
}
groups.set(content, group);
}
return [...groups].flatMap(([content, group]) =>
group.count === 0
? []
: [{ content, count: group.count, actors: group.actors, viewerHasReacted: group.viewer }],
);
}
/** `gid://gitlab/DiffNote/42` is note 42, which is the id the REST conversation carries. */
function noteIdOf(gid: string | null | undefined): string | null {
const id = trimmed(gid)?.split("/").at(-1);
return id !== undefined && /^\d+$/.test(id) ? id : null;
}
export interface GitLabAwardEmojiPage {
/** The merge request's own awards, which are the ones on its description. */
readonly reactions: ReadonlyArray<PullRequestReaction>;
readonly reactionsByNoteId: ReadonlyMap<string, ReadonlyArray<PullRequestReaction>>;
readonly nextCursor: string | null;
}
export function decodeAwardEmojiJson(
raw: string,
): Result.Result<GitLabAwardEmojiPage, DecodeFailure> {
const decoded = decodeAwardEmojiPage(raw);
if (!Result.isSuccess(decoded)) {
return Result.fail(decoded.failure);
}
const data = decoded.success.data;
const viewer = trimmed(data.currentUser?.username);
const mergeRequest = data.project?.mergeRequest;
const reactionsByNoteId = new Map<string, ReadonlyArray<PullRequestReaction>>();
for (const node of mergeRequest?.notes?.nodes ?? []) {
const id = noteIdOf(node?.id);
if (id === null) continue;
const reactions = toReactions(node?.awardEmoji, viewer);
if (reactions.length > 0) reactionsByNoteId.set(id, reactions);
}
const pageInfo = mergeRequest?.notes?.pageInfo;
return Result.succeed({
reactions: toReactions(mergeRequest?.awardEmoji, viewer),
reactionsByNoteId,
nextCursor: pageInfo?.hasNextPage === true ? (trimmed(pageInfo.endCursor) ?? null) : null,
});
}
const RawAwardSchema = Schema.Struct({
id: Schema.Int,
name: Schema.optional(Schema.NullOr(Schema.String)),
user: Schema.optional(
Schema.NullOr(Schema.Struct({ username: Schema.optional(Schema.NullOr(Schema.String)) })),
),
});
const decodeAward = Schema.decodeUnknownExit(RawAwardSchema);
/**
* The reader's own award of one name on a subject, which is what taking a reaction back is
* addressed by: GitLab deletes an award by its id and has no way to name one by its emoji.
*/
export function decodeOwnAwardIdJson(
raw: string,
input: { readonly content: PullRequestReactionContent; readonly viewer: string },
): Result.Result<number | null, DecodeFailure> {
const decoded = decodeUnknownList(raw);
if (!Result.isSuccess(decoded)) {
return Result.fail(decoded.failure);
}
const name = gitLabAwardName(input.content);
for (const entry of decoded.success) {
const award = decodeAward(entry);
if (Exit.isFailure(award)) continue;
const value = award.value;
if (trimmed(value.name)?.toLowerCase() !== name) continue;
if (trimmed(value.user?.username) !== input.viewer) continue;
return Result.succeed(value.id);
}
return Result.succeed(null);
}
@@ -1,93 +0,0 @@
import type { PullRequestCheck, PullRequestCheckStatus } from "@t3tools/contracts";
import { describe, expect, it } from "vite-plus/test";
import { dedupeChecks } from "./pullRequestChecks.ts";
function entry(
name: string,
status: PullRequestCheckStatus,
extra: { readonly workflowName?: string | null; readonly at?: string | null } = {},
): {
readonly check: PullRequestCheck;
readonly workflowName: string | null;
readonly at: string | null;
} {
return {
check: { name, status, description: null, url: null },
workflowName: extra.workflowName ?? null,
at: extra.at ?? null,
};
}
describe("dedupeChecks", () => {
it("keeps the newest run of a check the host listed twice", () => {
const checks = dedupeChecks([
entry("Prepare PR size config", "success", {
workflowName: "PR Size",
at: "2026-08-11T16:06:25Z",
}),
entry("Prepare PR size config", "pending", {
workflowName: "PR Size",
at: "2026-08-11T17:01:04Z",
}),
]);
expect(checks.map((check) => [check.name, check.status])).toEqual([
["Prepare PR size config", "pending"],
]);
});
it("holds a check at the place it first appeared, so a re-run does not reshuffle the list", () => {
const checks = dedupeChecks([
entry("lint", "success", { workflowName: "CI", at: "2026-08-11T16:00:00Z" }),
entry("test", "success", { workflowName: "CI", at: "2026-08-11T16:00:00Z" }),
entry("lint", "failure", { workflowName: "CI", at: "2026-08-11T18:00:00Z" }),
]);
expect(checks.map((check) => [check.name, check.status])).toEqual([
["lint", "failure"],
["test", "success"],
]);
});
it("loses a run that never said when it happened to one that did, whichever came first", () => {
const undated = dedupeChecks([
entry("build", "success", { at: "2026-08-11T16:00:00Z" }),
entry("build", "pending"),
]);
const dated = dedupeChecks([
entry("build", "pending"),
entry("build", "success", { at: "2026-08-11T16:00:00Z" }),
]);
expect([undated[0]?.status, dated[0]?.status]).toEqual(["success", "success"]);
});
it("takes the last copy when neither run is dated, which is how an update is listed", () => {
const checks = dedupeChecks([entry("build", "pending"), entry("build", "failure")]);
expect(checks.map((check) => check.status)).toEqual(["failure"]);
});
it("keeps two workflows that name a job the same thing, and says which is which", () => {
const checks = dedupeChecks([
entry("build", "success", { workflowName: "CI", at: "2026-08-11T16:00:00Z" }),
entry("build", "failure", { workflowName: "Release", at: "2026-08-11T16:00:00Z" }),
]);
expect(checks.map((check) => [check.name, check.status])).toEqual([
["CI / build", "success"],
["Release / build", "failure"],
]);
});
it("leaves a colliding check with no workflow of its own unqualified", () => {
// An app-provided check run belongs to no workflow, which GitHub reports as an empty name.
const checks = dedupeChecks([
entry("build", "success", { workflowName: "", at: "2026-08-11T16:00:00Z" }),
entry("build", "failure", { workflowName: "CI", at: "2026-08-11T16:00:00Z" }),
]);
expect(checks.map((check) => check.name)).toEqual(["build", "CI / build"]);
});
});
@@ -1,55 +0,0 @@
import type { PullRequestCheck } from "@t3tools/contracts";
/** ISO-8601 timestamps in UTC compare correctly as plain text, which is all the ordering needs. */
function isAtLeastAsNew(candidate: string | null, kept: string | null): boolean {
if (candidate === null) return kept === null;
return kept === null || candidate >= kept;
}
/**
* One row per check rather than one per run of it.
*
* A host's rollup is a list of runs, not a list of checks: while a workflow is being re-run — or
* while a second run of it is already live — the same check arrives twice, and both copies reach
* the reader as what looks like a duplicate. Nothing in a check carries an id, so the name is what
* identifies it, qualified by the workflow it belongs to since two workflows are free to name a
* job the same thing.
*
* Within a group the newest run is the one worth showing: a re-run is the answer that replaces the
* one before it, and a run that never said when it happened loses to one that did. A tie goes to
* whichever came last, because a host lists a re-run after the run it repeats.
*
* The order is the host's own, held at the place each check first appeared, so a re-run landing
* mid-read replaces a row where it stands instead of reshuffling the list under the reader.
*
* Two checks that survive under the same name are then genuinely different ones, since they came
* from different workflows — each is shown as `workflow / name`, the way GitHub writes it itself.
* A survivor whose workflow the host did not name keeps its bare name rather than being qualified
* with nothing.
*/
export function dedupeChecks(
entries: ReadonlyArray<{
readonly check: PullRequestCheck;
readonly workflowName: string | null;
readonly at: string | null;
}>,
): ReadonlyArray<PullRequestCheck> {
const newestByCheck = new Map<string, (typeof entries)[number]>();
for (const entry of entries) {
const key = `${entry.workflowName ?? ""} ${entry.check.name}`;
const kept = newestByCheck.get(key);
// Re-setting a key a Map already holds keeps its first position, which is the order wanted.
if (kept === undefined || isAtLeastAsNew(entry.at, kept.at)) newestByCheck.set(key, entry);
}
const survivors = [...newestByCheck.values()];
const countsByName = new Map<string, number>();
for (const entry of survivors) {
countsByName.set(entry.check.name, (countsByName.get(entry.check.name) ?? 0) + 1);
}
return survivors.map((entry) => {
const workflowName = entry.workflowName ?? "";
return workflowName.length > 0 && (countsByName.get(entry.check.name) ?? 0) > 1
? { ...entry.check, name: `${workflowName} / ${entry.check.name}` }
: entry.check;
});
}
@@ -4,7 +4,7 @@ import {
HostProcessEnvironment,
HostProcessPlatform,
} from "@t3tools/shared/hostProcess";
import { afterEach, assert, describe, expect, it, vi } from "@effect/vitest";
import { assert, describe, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
@@ -12,36 +12,6 @@ import { ServerConfig } from "../config.ts";
import * as ResourceMonitorBinary from "./ResourceMonitorBinary.ts";
describe("ResourceMonitorBinary", () => {
afterEach(() => {
vi.restoreAllMocks();
});
it.effect("skips Linux libc detection on Windows", () =>
Effect.gen(function* () {
const getReport = vi.spyOn(process.report, "getReport").mockImplementation(() => {
throw new Error("Linux libc detection must not run on Windows");
});
const fileSystem = yield* FileSystem.FileSystem;
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
prefix: "t3-resource-monitor-binary-",
});
const binaryPath = `${baseDir}/t3-resource-monitor.exe`;
yield* fileSystem.writeFileString(binaryPath, "binary");
const service = yield* ResourceMonitorBinary.make().pipe(
Effect.provide(ServerConfig.layerTest(process.cwd(), baseDir)),
Effect.provideService(HostProcessPlatform, "win32"),
Effect.provideService(HostProcessArchitecture, "arm64"),
Effect.provideService(HostProcessEnvironment, {
T3CODE_RESOURCE_MONITOR_PATH: binaryPath,
}),
);
assert.equal(yield* service.resolve, binaryPath);
expect(getReport).not.toHaveBeenCalled();
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
);
it.effect("resolves an executable override", () =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
@@ -106,7 +106,7 @@ export function resourceMonitorPlatformKey(
export function resourceMonitorRustTarget(
platform: NodeJS.Platform,
architecture: NodeJS.Architecture,
linuxLibc?: ResourceMonitorLinuxLibc,
linuxLibc: ResourceMonitorLinuxLibc,
): string | undefined {
if (platform === "darwin") {
return architecture === "arm64"
@@ -142,7 +142,7 @@ export const make = Effect.fn("resourceTelemetry.resourceMonitorBinary.make")(fu
const platform = yield* HostProcessPlatform;
const architecture = yield* HostProcessArchitecture;
const environment = yield* HostProcessEnvironment;
const linuxLibc = platform === "linux" ? yield* ResourceMonitorHostLinuxLibc : undefined;
const linuxLibc = yield* ResourceMonitorHostLinuxLibc;
const executableName = binaryName(platform);
const platformKey = resourceMonitorPlatformKey(platform, architecture);
const rustTarget = resourceMonitorRustTarget(platform, architecture, linuxLibc);
-1
View File
@@ -435,7 +435,6 @@ const commandReadinessLayer = HttpRouter.middleware(
const PullRequestServiceLive = PullRequestService.layer.pipe(
// One registry entry per supported host; the service only knows the registry.
Layer.provide(PullRequestProviderRegistry.layer),
Layer.provide(SourceControlProviderRegistryLayerLive),
Layer.provide(VcsProcess.layer),
);
@@ -373,34 +373,4 @@ describe("GitHubCli.layer", () => {
assert.equal(error.message.includes(cause.detail), false);
}).pipe(Effect.provide(layer)),
);
it.effect("surfaces an actionable rate-limit error without exposing provider stderr", () =>
Effect.gen(function* () {
const cause = new VcsProcessExitError({
operation: "GitHubCli.execute",
command: "gh",
cwd: "/repo",
exitCode: 1,
failureKind: "rate-limited",
detail: "API rate limit exceeded.",
stderrLength: 82,
stderrTruncated: false,
});
mockRun.mockReturnValueOnce(Effect.fail(cause));
const gh = yield* GitHubCli.GitHubCli;
const error = yield* gh
.listOpenPullRequests({
cwd: "/repo",
headSelector: "feature/rate-limited",
})
.pipe(Effect.flip);
assert.strictEqual(error._tag, "GitHubCliRateLimitError");
assert.include(error.detail, "GitHub API rate limit exceeded");
assert.include(error.detail, "gh api rate_limit");
assert.strictEqual(error.cause, cause);
assert.notInclude(error.message, "user ID");
}).pipe(Effect.provide(layer)),
);
});
@@ -51,19 +51,6 @@ export class GitHubCliAuthenticationError extends Schema.TaggedErrorClass<GitHub
}
}
export class GitHubCliRateLimitError extends Schema.TaggedErrorClass<GitHubCliRateLimitError>()(
"GitHubCliRateLimitError",
gitHubCliFailureFields,
) {
get detail(): string {
return "GitHub API rate limit exceeded. Run `gh api rate_limit` to inspect the quota and reset time.";
}
override get message(): string {
return `GitHub CLI failed in execute: ${this.detail}`;
}
}
export class GitHubPullRequestNotFoundError extends Schema.TaggedErrorClass<GitHubPullRequestNotFoundError>()(
"GitHubPullRequestNotFoundError",
gitHubCliFailureFields,
@@ -151,7 +138,6 @@ export class GitHubRepositoryDecodeError extends Schema.TaggedErrorClass<GitHubR
export const GitHubCliError = Schema.Union([
GitHubCliUnavailableError,
GitHubCliAuthenticationError,
GitHubCliRateLimitError,
GitHubPullRequestNotFoundError,
GitHubCliCommandError,
GitHubPullRequestListDecodeError,
@@ -184,9 +170,6 @@ export function fromVcsError(
if (error.failureKind === "authentication") {
return new GitHubCliAuthenticationError({ ...context, cause: error });
}
if (error.failureKind === "rate-limited") {
return new GitHubCliRateLimitError({ ...context, cause: error });
}
if (error.failureKind === "not-found") {
return new GitHubPullRequestNotFoundError({ ...context, cause: error });
}
Loaded 100 of 272 files, more files were not shown because too many files have changed in this diff. Show more