Compare commits

..
Author SHA1 Message Date
Julius Marminge e9b6980ced Add device-login tip to T3 Connect auth prompt
- Update the OAuth console message to mention `t3 connect login --device`
- Improve guidance for headless and remote machines
2026-07-06 23:32:24 -07:00
Julius Marminge 87c028fd05 Harden device login flow against transient relay failures
- Retry device authorization issuance on unique-code collisions
- Validate relay device/login payload sizes up front
- Keep polling and cleanup resilient to transient transport failures
2026-07-06 23:20:46 -07:00
Julius Marminge ebaeee9339 Harden device login flow and relay config
- Preserve device auth timeout errors and guard against stale lookup results
- Add relay device authorization schema and tighten stage-specific base URL defaults
2026-07-06 22:49:07 -07:00
Julius Marminge aa17397149 Document device-code login relay configuration
- Describe the new `t3 connect login --device` flow
- Add `T3CODE_APP_BASE_URL` guidance for relay stages
- Update relay README and Clerk setup docs
2026-07-06 22:29:31 -07:00
Julius Marminge e369795c4f Preserve device login return URL
- Open Clerk sign-in with the current page as the forced redirect URL
- Keep the device authorization flow returning users to where they started
2026-07-06 22:23:50 -07:00
Julius Marminge 560646c97e Add device login flow for T3 Connect
- Add device-code CLI login for headless machines
- Add relay and web approval/callback surfaces
- Update shared relay contracts and tests
2026-07-06 22:19:54 -07:00
Julius MarmingeandClaude Fable 5 32e7844837 Fix mobile legend anchor under automatic iOS insets (#3684)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-07-05 22:50:33 -07:00
Julius MarmingeandClaude Opus 4.8 482d56233d Load thread snapshots over HTTP before live sync (#3719)
Co-authored-by: Claude Opus 4.8 <[email protected]>
2026-07-05 22:00:13 -07:00
Theo BrowneandClaude Fable 5 6009720844 Add repo-root favicon.svg so t3 code shows its own icon (#3683)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-07-04 15:05:45 -07:00
Theo BrowneandClaude Opus 4.8 e26e55f389 fix(mobile): combined test branch — scroll, back-swipe, thread lists, computer switching (#3687)
Co-authored-by: Claude Opus 4.8 <[email protected]>
2026-07-04 14:28:51 -07:00
80 changed files with 6446 additions and 267 deletions

No files matched your search

+110
View File
@@ -0,0 +1,110 @@
name: Mobile EAS Production
# Production builds and OTA updates run from CI (Linux) — never from a laptop.
# Under the fingerprint runtime-version policy the fingerprint must be computed
# in the same OS/pnpm as the EAS build; a macOS `eas build` computes a different
# fingerprint (platform-specific deps + pnpm version) and errors. On this Linux
# runner, with corepack pinning pnpm 10.24 in eas.json, local == build.
on:
workflow_dispatch:
inputs:
mode:
description: "build (+ auto-submit to TestFlight) or update (OTA)"
required: true
type: choice
default: build
options:
- build
- update
platform:
description: "Target platform"
required: true
type: choice
default: ios
options:
- ios
- android
- all
message:
description: "OTA update message (mode=update only)"
required: false
type: string
jobs:
production:
name: EAS Production ${{ inputs.mode }}
runs-on: blacksmith-8vcpu-ubuntu-2404
permissions:
contents: read
env:
APP_VARIANT: production
NODE_OPTIONS: --max-old-space-size=8192
steps:
- id: expo-token
name: Check for EXPO_TOKEN
env:
EXPO_TOKEN: ${{ secrets.EXPO_TOKEN }}
run: |
if [ -n "$EXPO_TOKEN" ]; then
echo "present=true" >> "$GITHUB_OUTPUT"
else
echo "present=false" >> "$GITHUB_OUTPUT"
echo "EXPO_TOKEN is not available; skipping EAS production job."
fi
- name: Checkout
if: steps.expo-token.outputs.present == 'true'
uses: actions/checkout@v6
with:
fetch-depth: 0
- name: Setup Vite+
if: steps.expo-token.outputs.present == 'true'
uses: voidzero-dev/setup-vp@v1
with:
node-version-file: package.json
cache: true
run-install: true
- name: Expose pnpm
if: steps.expo-token.outputs.present == 'true'
run: |
pnpm_version="$(node --print "require('./package.json').packageManager.split('@').pop()")"
vp_pnpm_bin="$HOME/.vite-plus/package_manager/pnpm/$pnpm_version/pnpm/bin"
echo "$vp_pnpm_bin" >> "$GITHUB_PATH"
"$vp_pnpm_bin/pnpm" --version
- name: Setup EAS
if: steps.expo-token.outputs.present == 'true'
uses: expo/expo-github-action@v8
with:
eas-version: latest
token: ${{ secrets.EXPO_TOKEN }}
packager: pnpm
- name: Pull production environment variables
if: steps.expo-token.outputs.present == 'true'
working-directory: apps/mobile
env:
EXPO_TOKEN: ${{ secrets.EXPO_TOKEN }}
run: eas env:pull production --non-interactive
- name: Build and submit
if: steps.expo-token.outputs.present == 'true' && inputs.mode == 'build'
working-directory: apps/mobile
env:
EXPO_TOKEN: ${{ secrets.EXPO_TOKEN }}
run: eas build --platform ${{ inputs.platform }} --profile production --auto-submit --non-interactive --no-wait
- name: Publish OTA update
if: steps.expo-token.outputs.present == 'true' && inputs.mode == 'update'
working-directory: apps/mobile
env:
EXPO_TOKEN: ${{ secrets.EXPO_TOKEN }}
run: |
eas update \
--channel production \
--environment production \
--platform ${{ inputs.platform }} \
--message "${{ inputs.message || format('Production OTA ({0})', github.sha) }}" \
--non-interactive
+5 -1
View File
@@ -66,7 +66,11 @@ const config: ExpoConfig = {
scheme: variant.scheme,
version: "0.1.0",
runtimeVersion: {
policy: process.env.MOBILE_VERSION_POLICY ?? "appVersion",
// Fingerprint (not appVersion) so an OTA only reaches binaries whose native
// project — native deps, config plugins, AND patches/ — matches the update.
// With appVersion, every 0.1.0 build shares a runtime version, so a JS update
// could land on a binary missing the native changes it needs and crash.
policy: process.env.MOBILE_VERSION_POLICY ?? "fingerprint",
},
orientation: "portrait",
icon: "./assets/icon.png",
+8 -1
View File
@@ -6,6 +6,7 @@
},
"build": {
"development": {
"corepack": true,
"env": {
"APP_VARIANT": "development"
},
@@ -14,6 +15,7 @@
"distribution": "internal"
},
"preview": {
"corepack": true,
"env": {
"APP_VARIANT": "preview"
},
@@ -22,6 +24,7 @@
"distribution": "internal"
},
"preview:dev": {
"corepack": true,
"env": {
"APP_VARIANT": "preview",
"MOBILE_VERSION_POLICY": "fingerprint"
@@ -35,6 +38,7 @@
}
},
"production": {
"corepack": true,
"env": {
"APP_VARIANT": "production"
},
@@ -46,7 +50,10 @@
"submit": {
"production": {
"ios": {
"ascAppId": "6761315631"
"ascAppId": "6787819824"
},
"android": {
"track": "internal"
}
}
}
+6 -1
View File
@@ -1,4 +1,6 @@
import { Connection } from "@t3tools/client-runtime/connection";
import { shellSnapshotLoaderLayer } from "@t3tools/client-runtime/state/shell";
import { threadSnapshotLoaderLayer } from "@t3tools/client-runtime/state/threads";
import * as Layer from "effect/Layer";
import { Atom } from "effect/unstable/reactivity";
@@ -9,12 +11,15 @@ const providedConnectionPlatformLayer = connectionPlatformLayer.pipe(
Layer.provide(runtimeContextLayer),
);
const snapshotLoaderLayer = Layer.merge(threadSnapshotLoaderLayer, shellSnapshotLoaderLayer);
type ConnectionLayerSource =
| typeof Connection.layer
| typeof snapshotLoaderLayer
| typeof runtimeContextLayer
| typeof connectionPlatformLayer;
const connectionLayer = Connection.layer.pipe(
const connectionLayer = Layer.merge(Connection.layer, snapshotLoaderLayer).pipe(
Layer.provideMerge(Layer.mergeAll(runtimeContextLayer, providedConnectionPlatformLayer)),
);
+11 -8
View File
@@ -16,8 +16,8 @@ import {
} from "@t3tools/client-runtime/connection";
import {
EnvironmentId,
OrchestrationThread,
OrchestrationShellSnapshot,
OrchestrationThreadDetailSnapshot,
ThreadId,
} from "@t3tools/contracts";
import * as Context from "effect/Context";
@@ -32,7 +32,10 @@ import { makeCatalogStore, type SecureCatalogStorage } from "./catalog-store";
const SHELL_SNAPSHOT_CACHE_SCHEMA_VERSION = 1;
const SHELL_SNAPSHOT_CACHE_DIRECTORY = "connection-shell-snapshots";
const LEGACY_SHELL_SNAPSHOT_CACHE_DIRECTORY = "shell-snapshots";
const THREAD_SNAPSHOT_CACHE_SCHEMA_VERSION = 1;
// v2 stores the snapshot sequence alongside the thread so a warm cache can
// resume via `afterSequence` instead of re-downloading the full thread body.
// Older v1 entries (no sequence) fail to decode and are treated as a cold cache.
const THREAD_SNAPSHOT_CACHE_SCHEMA_VERSION = 2;
const THREAD_SNAPSHOT_CACHE_DIRECTORY = "connection-thread-snapshots";
const StoredShellSnapshot = Schema.Struct({
@@ -45,7 +48,7 @@ const StoredThreadSnapshot = Schema.Struct({
schemaVersion: Schema.Literal(THREAD_SNAPSHOT_CACHE_SCHEMA_VERSION),
environmentId: EnvironmentId,
threadId: ThreadId,
thread: OrchestrationThread,
snapshot: OrchestrationThreadDetailSnapshot,
});
const LegacyStoredShellSnapshot = Schema.Struct({
@@ -355,18 +358,18 @@ export const connectionStorageLayer = Layer.effectContext(
Schema.decodeUnknownResult(StoredThreadSnapshot)(parsed),
).pipe(Effect.mapError((cause) => shellPersistenceError("load-thread", cause)));
return stored.environmentId === environmentId && stored.threadId === threadId
? Option.some(stored.thread)
? Option.some(stored.snapshot)
: Option.none();
}),
saveThread: (environmentId, thread) =>
saveThread: (environmentId, snapshot) =>
Effect.gen(function* () {
const file = yield* threadSnapshotFile(environmentId, thread.id, "save-thread");
const file = yield* threadSnapshotFile(environmentId, snapshot.thread.id, "save-thread");
const encoded = yield* Effect.fromResult(
Schema.encodeUnknownResult(StoredThreadSnapshot)({
schemaVersion: THREAD_SNAPSHOT_CACHE_SCHEMA_VERSION,
environmentId,
threadId: thread.id,
thread,
threadId: snapshot.thread.id,
snapshot,
}),
).pipe(Effect.mapError((cause) => shellPersistenceError("save-thread", cause)));
yield* Effect.try({
@@ -148,6 +148,10 @@ function relayProtectedErrorMessage(error: RelayProtectedErrorType): string {
return `Relay rejected the agent activity publish proof (${error.reason}).`;
case "RelayInternalError":
return `Relay encountered an internal error (${error.reason}).`;
case "RelayDeviceTokenPollError":
return `Relay rejected the device authorization poll (${error.code}).`;
case "RelayDeviceAuthorizationNotFoundError":
return "Relay could not find the device authorization.";
}
}
@@ -216,15 +216,12 @@ export function buildHomeThreadGroups(input: {
: sortedThreads;
// Sorted newest-first, so the first thread whose project is a group member
// marks the machine the user last worked on. Derived from the FULL history
// (not the search-filtered subset) so the target is stable across queries.
const lastActiveProject = Arr.findFirst(
sortThreads(group.threads, input.threadSortOrder),
(thread) =>
group.projects.some(
(project) =>
project.environmentId === thread.environmentId && project.id === thread.projectId,
),
// marks the machine the user last worked on.
const lastActiveProject = Arr.findFirst(sortedThreads, (thread) =>
group.projects.some(
(project) =>
project.environmentId === thread.environmentId && project.id === thread.projectId,
),
).pipe(
Option.flatMap((thread) =>
Arr.findFirst(
@@ -1,5 +1,7 @@
import { useAuth, useUser } from "@clerk/expo";
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 "expo-symbols";
@@ -422,6 +424,23 @@ function ConfiguredSettingsRouteScreen() {
function AppSettingsSection() {
const icon = useThemeColor("--color-icon");
const version = Constants.expoConfig?.version ?? "0.0.0";
// Fall back to "production" to match resolveAppVariant in app.config.ts, so a
// missing variant never mislabels a production build as development.
const variant = (Constants.expoConfig?.extra?.appVariant as string | undefined) ?? "production";
const variantLabel = variant === "production" ? "" : capitalize(variant);
const versionLabel = variantLabel ? `${version} · ${variantLabel}` : version;
// Which JS is actually running: the bundle shipped in the binary, or an OTA
// update downloaded on top of it. Surfacing this makes "am I even on the
// right build?" answerable at a glance.
const bundleLabel = Updates.isEnabled
? Updates.isEmbeddedLaunch
? "Embedded"
: Updates.updateId
? `OTA ${Updates.updateId.slice(0, 7)}`
: null
: null;
return (
<SettingsSection title="App">
<View className="flex-row items-center gap-4 p-4">
@@ -433,12 +452,21 @@ function AppSettingsSection() {
weight="regular"
/>
<Text className="flex-1 text-lg text-foreground">Version</Text>
<Text className="text-lg text-foreground-muted">Alpha</Text>
<View className="items-end">
<Text className="text-lg text-foreground-muted">{versionLabel}</Text>
{bundleLabel ? (
<Text className="text-xs text-foreground-muted/70">{bundleLabel}</Text>
) : null}
</View>
</View>
</SettingsSection>
);
}
function capitalize(value: string): string {
return value.length > 0 ? value.charAt(0).toUpperCase() + value.slice(1) : value;
}
function ArchivedThreadsSettingsSection() {
return (
<SettingsSection title="Threads">
@@ -25,6 +25,7 @@ import {
type ViewStyle,
} from "react-native";
import ImageViewing from "react-native-image-viewing";
import Animated, { FadeIn, FadeOut, LinearTransition } from "react-native-reanimated";
import { useThemeColor } from "../../lib/useThemeColor";
import { scopedThreadKey } from "../../lib/scopedEntities";
@@ -112,6 +113,10 @@ export interface ThreadComposerProps {
* The pill / card container — renders as LiquidGlassView on supported
* iOS 26+ devices (progressive blur, native morph), opaque View otherwise.
*/
// One timing for every piece of the expanded↔compact morph so the surface,
// toolbar, and siblings move together instead of popping between layouts.
const COMPOSER_LAYOUT_TRANSITION = LinearTransition.duration(220);
function ComposerSurface(props: {
readonly children: ReactNode;
readonly style: ViewStyle;
@@ -130,7 +135,7 @@ function ComposerSurface(props: {
if (isLiquidGlassSupported) {
return (
<View style={shadowStyle}>
<Animated.View layout={COMPOSER_LAYOUT_TRANSITION} style={shadowStyle}>
<LiquidGlassView
effect="regular"
interactive
@@ -139,12 +144,12 @@ function ComposerSurface(props: {
>
{props.children}
</LiquidGlassView>
</View>
</Animated.View>
);
}
return (
<View style={shadowStyle}>
<Animated.View layout={COMPOSER_LAYOUT_TRANSITION} style={shadowStyle}>
<View
style={[
props.style,
@@ -157,7 +162,7 @@ function ComposerSurface(props: {
>
{props.children}
</View>
</View>
</Animated.View>
);
}
@@ -669,7 +674,8 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
}
return (
<View
<Animated.View
layout={COMPOSER_LAYOUT_TRANSITION}
style={{
paddingHorizontal: 16,
paddingTop: isExpanded ? 8 : 6,
@@ -679,8 +685,9 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
: "linear-gradient(to bottom, rgba(255,255,255,0) 0%, rgba(255,255,255,0.6) 55%, rgba(255,255,255,0.9) 100%)",
}}
>
<View
<Animated.View
className="w-full"
layout={COMPOSER_LAYOUT_TRANSITION}
style={{ alignSelf: "center", maxWidth: props.contentMaxWidth, position: "relative" }}
>
{composerTrigger && composerMenuItems.length > 0 ? (
@@ -733,13 +740,17 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
>
{/* Attachment strip — inside the card, above the text input */}
{isExpanded ? (
<View style={{ paddingBottom: props.draftAttachments.length > 0 ? 10 : 0 }}>
<Animated.View
entering={FadeIn.duration(160)}
exiting={FadeOut.duration(120)}
style={{ paddingBottom: props.draftAttachments.length > 0 ? 10 : 0 }}
>
<ComposerAttachmentStrip
attachments={props.draftAttachments}
onRemove={props.onRemoveDraftImage}
onPressImage={onPressImage}
/>
</View>
</Animated.View>
) : null}
<View style={isExpanded ? undefined : { flex: 1, minWidth: 0 }}>
@@ -812,81 +823,87 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
</View>
) : null}
{!isExpanded ? (
showStopAction ? (
<ControlPill icon="stop.fill" variant="danger" onPress={props.onStopThread} />
) : (
<ControlPill
icon="arrow.up"
variant="primary"
disabled={!canSend}
onPress={handleSend}
/>
)
<Animated.View entering={FadeIn.duration(180)} exiting={FadeOut.duration(100)}>
{showStopAction ? (
<ControlPill icon="stop.fill" variant="danger" onPress={props.onStopThread} />
) : (
<ControlPill
icon="arrow.up"
variant="primary"
disabled={!canSend}
onPress={handleSend}
/>
)}
</Animated.View>
) : null}
</ComposerSurface>
{/* Toolbar row — matches draft page layout (expanded only) */}
{isExpanded ? (
<ComposerToolbarRow paddingBottom={8} paddingHorizontal={0} paddingTop={8}>
<ComposerToolbarScroller
fadeOpaque={toolbarFadeOpaque}
fadeTransparent={toolbarFadeTransparent}
>
<ComposerToolbarButton
icon="plus"
onPress={() => void props.onPickDraftImages()}
showChevron={false}
/>
<ControlPillMenu
actions={modelMenuActions}
onPressAction={({ nativeEvent }) => handleModelMenuAction(nativeEvent.event)}
<Animated.View entering={FadeIn.duration(160)} exiting={FadeOut.duration(120)}>
<ComposerToolbarRow paddingBottom={8} paddingHorizontal={0} paddingTop={8}>
<ComposerToolbarScroller
fadeOpaque={toolbarFadeOpaque}
fadeTransparent={toolbarFadeTransparent}
>
<ComposerToolbarTrigger
accessibilityLabel="Model"
iconNode={
<ProviderIcon provider={currentModelOption?.providerDriver} size={16} />
}
label={currentModelOption?.label ?? currentModelSelection.model}
/>
</ControlPillMenu>
<ControlPillMenu
actions={optionsMenuActions}
onPressAction={({ nativeEvent }) => handleOptionsMenuAction(nativeEvent.event)}
>
<ComposerToolbarTrigger
accessibilityLabel="Configuration"
icon="slider.horizontal.3"
label={configurationLabel}
/>
</ControlPillMenu>
{showStopAction ? (
<ComposerToolbarButton
icon="stop.fill"
variant="danger"
onPress={props.onStopThread}
icon="plus"
onPress={() => void props.onPickDraftImages()}
showChevron={false}
/>
) : null}
</ComposerToolbarScroller>
<ComposerToolbarButton
accessibilityLabel={sendLabel}
icon="arrow.up"
variant="primary"
disabled={!canSend}
onPress={handleSend}
showChevron={false}
/>
</ComposerToolbarRow>
<ControlPillMenu
actions={modelMenuActions}
onPressAction={({ nativeEvent }) => handleModelMenuAction(nativeEvent.event)}
>
<ComposerToolbarTrigger
accessibilityLabel="Model"
iconNode={
<ProviderIcon provider={currentModelOption?.providerDriver} size={16} />
}
label={currentModelOption?.label ?? currentModelSelection.model}
/>
</ControlPillMenu>
<ControlPillMenu
actions={optionsMenuActions}
onPressAction={({ nativeEvent }) => handleOptionsMenuAction(nativeEvent.event)}
>
<ComposerToolbarTrigger
accessibilityLabel="Configuration"
icon="slider.horizontal.3"
label={configurationLabel}
/>
</ControlPillMenu>
{showStopAction ? (
<ComposerToolbarButton
icon="stop.fill"
variant="danger"
onPress={props.onStopThread}
showChevron={false}
/>
) : null}
</ComposerToolbarScroller>
<ComposerToolbarButton
accessibilityLabel={sendLabel}
icon="arrow.up"
variant="primary"
disabled={!canSend}
onPress={handleSend}
showChevron={false}
/>
</ComposerToolbarRow>
</Animated.View>
) : null}
{/* Queue count */}
{props.queueCount > 0 ? (
<Text className="text-xs text-foreground-muted" style={{ paddingTop: 8 }}>
{props.queueCount} queued message{props.queueCount === 1 ? "" : "s"} will send
automatically.
</Text>
<Animated.View entering={FadeIn.duration(180)} exiting={FadeOut.duration(120)}>
<Text className="text-xs text-foreground-muted" style={{ paddingTop: 8 }}>
{props.queueCount} queued message{props.queueCount === 1 ? "" : "s"} will send
automatically.
</Text>
</Animated.View>
) : null}
</View>
</Animated.View>
<ImageViewing
images={previewImageUri ? [{ uri: previewImageUri }] : []}
@@ -896,6 +913,6 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
swipeToCloseEnabled
doubleTapToZoomEnabled
/>
</View>
</Animated.View>
);
});
@@ -17,8 +17,9 @@ import type {
import { formatElapsed } from "@t3tools/shared/orchestrationTiming";
import * as Haptics from "expo-haptics";
import { memo, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
import { View, type GestureResponderEvent } from "react-native";
import { Platform, View, type GestureResponderEvent } from "react-native";
import { KeyboardController, KeyboardStickyView } from "react-native-keyboard-controller";
import Animated, { FadeInDown, FadeOut, LinearTransition } from "react-native-reanimated";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { AppText as Text } from "../../components/AppText";
@@ -170,7 +171,11 @@ function useStreamingHaptics(threadId: ThreadId, feed: ReadonlyArray<ThreadFeedE
}, [threadId, feed]);
}
const WORKING_INDICATOR_HEIGHT = 44;
// Pre-measurement estimate for the working pill's slot (the real height is
// measured via onComposerLayout since the pill lives inside the composer
// overlay). Matches the rendered pill: pt-2 + pb-2 (16) wrapping a bordered
// px-3/py-2 row (~36), so ~52 — keep it in sync with WorkingDurationPill.
const WORKING_INDICATOR_HEIGHT = 52;
const WorkingDurationPill = memo(function WorkingDurationPill(props: {
readonly startedAt: string;
@@ -187,7 +192,12 @@ const WorkingDurationPill = memo(function WorkingDurationPill(props: {
const durationLabel = formatElapsed(props.startedAt, new Date(nowMs).toISOString()) ?? "0s";
return (
<View className="px-4 pb-2" style={{ flexShrink: 0 }}>
<Animated.View
className="px-4 pb-2 pt-2"
entering={FadeInDown.duration(200)}
exiting={FadeOut.duration(140)}
style={{ flexShrink: 0 }}
>
<View className="self-start rounded-full border border-neutral-200/80 bg-neutral-50/90 px-3 py-2 dark:border-white/[0.08] dark:bg-white/[0.04]">
<View className="flex-row items-center gap-2">
<View className="flex-row items-center gap-1">
@@ -200,7 +210,7 @@ const WorkingDurationPill = memo(function WorkingDurationPill(props: {
</Text>
</View>
</View>
</View>
</Animated.View>
);
});
@@ -238,11 +248,21 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
const composerChrome = composerExpanded ? COMPOSER_EXPANDED_CHROME : COMPOSER_COLLAPSED_CHROME;
const composerOverlapHeight = composerChrome + composerBottomInset;
const activeWorkIndicatorHeight = props.activeWorkStartedAt ? WORKING_INDICATOR_HEIGHT : 0;
const estimatedOverlayHeight = composerOverlapHeight + activeWorkIndicatorHeight + 8;
const estimatedOverlayHeight = composerOverlapHeight + activeWorkIndicatorHeight;
// The overlay's measured height includes the home-indicator inset (the
// composer pads it), but contentInsetAdjustmentBehavior="automatic" makes
// UIKit add the safe-area bottom to the content inset AGAIN — leaving a
// dead strip between the resting content and the composer. Report the
// overlay height minus the safe area; UIKit adds it back, and ThreadFeed
// hands LegendList the same delta via contentInsetEndStaticAdjustment so
// its end-scroll math matches the real resting position.
const nativeInsetOvercount =
props.usesAutomaticContentInsets === true && Platform.OS === "ios" ? insets.bottom : 0;
const { contentInsetEndAdjustment, onComposerLayout } = useKeyboardChatComposerInset(
listRef,
composerOverlayRef,
estimatedOverlayHeight,
Math.max(0, estimatedOverlayHeight - nativeInsetOvercount),
-nativeInsetOvercount,
);
const { freeze, scrollMessageToEnd } = useKeyboardScrollToEnd({ listRef });
const showContent = props.showContent ?? true;
@@ -408,18 +428,25 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
style={{ position: "absolute", bottom: 0, left: 0, right: 0 }}
offset={{ closed: 0, opened: 0 }}
>
<View
ref={composerOverlayRef}
onLayout={onComposerLayout}
style={{ width: "100%", paddingTop: 8 }}
>
<View style={{ alignSelf: "center", maxWidth: contentMaxWidth, width: "100%" }}>
{/* No paddingTop here: the overlay's measured height becomes the
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} style={{ width: "100%" }}>
<Animated.View
layout={LinearTransition.duration(220)}
style={{ alignSelf: "center", maxWidth: contentMaxWidth, width: "100%" }}
>
{props.activeWorkStartedAt ? (
<WorkingDurationPill startedAt={props.activeWorkStartedAt} />
) : null}
{props.activePendingApproval || props.activePendingUserInput ? (
<View className="gap-3 px-4 pb-3" style={{ flexShrink: 0 }}>
<Animated.View
className="gap-3 px-4 pb-3"
entering={FadeInDown.duration(220)}
exiting={FadeOut.duration(140)}
style={{ flexShrink: 0 }}
>
{props.activePendingApproval ? (
<PendingApprovalCard
approval={props.activePendingApproval}
@@ -438,9 +465,9 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
onSubmit={props.onSubmitUserInput}
/>
) : null}
</View>
</Animated.View>
) : null}
</View>
</Animated.View>
<ThreadComposer
editorRef={composerEditorRef}
+111 -11
View File
@@ -4,11 +4,14 @@ import { type LegendListRef } from "@legendapp/list/react-native";
import type { EnvironmentId, MessageId, ThreadId, TurnId } from "@t3tools/contracts";
import { CHAT_LIST_ANCHOR_OFFSET, resolveChatListAnchoredEndSpace } from "@t3tools/shared/chatList";
import { SymbolView } from "expo-symbols";
import { HeaderHeightContext } from "@react-navigation/elements";
import { useNavigation } from "@react-navigation/native";
import {
memo,
useCallback,
useContext,
useEffect,
useLayoutEffect,
useMemo,
useRef,
useState,
@@ -41,7 +44,13 @@ import {
import { TouchableOpacity } from "react-native-gesture-handler";
import ImageViewing from "react-native-image-viewing";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { type SharedValue } from "react-native-reanimated";
import Animated, {
FadeIn,
FadeInUp,
FadeOut,
LinearTransition,
type SharedValue,
} from "react-native-reanimated";
import { useThemeColor } from "../../lib/useThemeColor";
import { copyTextWithHaptic } from "../../lib/copyTextWithHaptic";
import {
@@ -96,6 +105,19 @@ function formatMessageTime(input: string): string {
return MESSAGE_TIME_FORMATTER.format(timestamp);
}
// Rows shift when content above them grows (streaming text, work-log folds);
// animating the container position turns those jumps into slides.
const FEED_ITEM_LAYOUT_TRANSITION = LinearTransition.duration(180);
// Entering animations must only play for rows born just now — LegendList
// remounts rows when they scroll back into view, and replaying an entrance for
// old content would be its own kind of jank.
const FRESH_ENTRY_WINDOW_MS = 3_000;
function isFreshTimestamp(input: string): boolean {
const timestamp = Date.parse(input);
return Number.isFinite(timestamp) && Date.now() - timestamp < FRESH_ENTRY_WINDOW_MS;
}
export interface ThreadFeedProps {
readonly environmentId: EnvironmentId;
readonly threadId: ThreadId;
@@ -749,8 +771,12 @@ function renderFeedEntry(
!message.streaming;
if (isUser) {
const enterAnimated = isFreshTimestamp(message.createdAt);
return (
<View className="mb-5 items-end">
<Animated.View
className="mb-5 items-end"
{...(enterAnimated ? { entering: FadeInUp.duration(220) } : {})}
>
<View
className="min-w-0 gap-2 rounded-[20px] px-3.5 py-2.5"
style={{
@@ -794,7 +820,7 @@ function renderFeedEntry(
/>
) : null}
</View>
</View>
</Animated.View>
);
}
@@ -804,8 +830,12 @@ function renderFeedEntry(
return null;
}
const enterAnimated = isFreshTimestamp(message.createdAt);
return (
<View className={cn(showAssistantMeta ? "mb-5 px-1" : "mb-2 px-1")}>
<Animated.View
className={cn(showAssistantMeta ? "mb-5 px-1" : "mb-2 px-1")}
{...(enterAnimated ? { entering: FadeIn.duration(220) } : {})}
>
{message.text.trim().length > 0 ? (
hasNativeSelectableMarkdownText() ? (
<SelectableMarkdownText
@@ -850,7 +880,7 @@ function renderFeedEntry(
</Text>
</View>
) : null}
</View>
</Animated.View>
);
}
@@ -1146,6 +1176,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
const [viewportWidth, setViewportWidth] = useState(() =>
props.layoutVariant === "split" ? 0 : windowWidth,
);
const [viewportHeight, setViewportHeight] = useState(0);
const [disclosureToggleSettling, setDisclosureToggleSettling] = useState(false);
const [interactionState, setInteractionState] = useState<{
readonly copiedRowId: string | null;
@@ -1177,6 +1208,17 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
const bottomContentInset = props.contentBottomInset ?? 18;
const usesNativeAutomaticInsets =
props.usesAutomaticContentInsets === true && Platform.OS === "ios";
// With automatic insets the header inset lives in UIKit's adjustedContentInset,
// which LegendList's JS anchoring math cannot see — it measures the anchored
// end space from the scroll view's frame top. Fold the header height back into
// the anchor offset or a just-sent message anchors underneath the header and
// the oversized end space keeps maintainScrollAtEnd snapping away from earlier
// messages. Read the context directly (useHeaderHeight throws outside a
// header-providing screen) and fall back to the standard iOS bar height.
const navigationHeaderHeight = useContext(HeaderHeightContext);
const anchorTopInset = usesNativeAutomaticInsets
? navigationHeaderHeight || insets.top + 44
: topContentInset;
const iconSubtleColor = useThemeColor("--color-icon-subtle");
const userBubbleColor = useThemeColor("--color-user-bubble");
@@ -1242,13 +1284,19 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
);
const handleScroll = useCallback(
(event: NativeSyntheticEvent<NativeScrollEvent>) => {
reportHeaderMaterialVisibility(event.nativeEvent.contentOffset.y + topContentInset > 6);
// anchorTopInset, not topContentInset: under automatic insets the list
// rests at contentOffset.y = -headerHeight (the inset lives only in
// 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);
},
[reportHeaderMaterialVisibility, topContentInset],
[reportHeaderMaterialVisibility, anchorTopInset],
);
const handleViewportLayout = useCallback((event: LayoutChangeEvent) => {
const nextWidth = Math.round(event.nativeEvent.layout.width);
const nextHeight = Math.round(event.nativeEvent.layout.height);
setViewportWidth((current) => (Math.abs(current - nextWidth) > 1 ? nextWidth : current));
setViewportHeight((current) => (Math.abs(current - nextHeight) > 1 ? nextHeight : current));
}, []);
useEffect(() => {
@@ -1275,15 +1323,30 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
[expandedTurnIds, expandedWorkGroupIds, props.feed, props.latestTurn],
);
// The empty↔filled key below remounts the list, which resets its imperative
// content-inset override — and useKeyboardChatComposerInset (mounted above
// the remount boundary) deduplicates by height, so it never re-reports the
// composer inset to the fresh instance. Without this, the remounted list's
// initial scroll-to-end computes with a zero end inset and rests one
// composer-height short of the end. Layout effect: it must land before the
// list's first positioning tick or the one-shot initial scroll misses it.
const listMountKey = `${props.threadId}:${props.feed.length === 0 ? "empty" : "filled"}`;
useLayoutEffect(() => {
const bottom = props.contentInsetEndAdjustment.value;
if (bottom > 0) {
props.listRef.current?.reportContentInset({ bottom });
}
}, [listMountKey, props.contentInsetEndAdjustment, props.listRef]);
const anchoredEndSpace = useMemo(
() =>
resolveChatListAnchoredEndSpace(
presentedFeed,
props.anchorMessageId,
(entry) => (entry.type === "message" ? entry.id : null),
{ anchorOffset: topContentInset + CHAT_LIST_ANCHOR_OFFSET },
{ anchorOffset: anchorTopInset + CHAT_LIST_ANCHOR_OFFSET },
),
[presentedFeed, props.anchorMessageId, topContentInset],
[presentedFeed, props.anchorMessageId, anchorTopInset],
);
const terminalAssistantMessageIds = useMemo(() => {
const terminalIdsByTurn = new Map<TurnId, string>();
@@ -1506,7 +1569,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
// an already-attached list under a transparent header can pin
// short content at offset 0 (one header-height too high). A fresh
// mount positions during attach, where UIKit applies the inset.
key={`${props.threadId}:${props.feed.length === 0 ? "empty" : "filled"}`}
key={listMountKey}
style={{ flex: 1 }}
// RN 0.81+ drops touches inside the contentInset area
// (facebook/react-native#54123); the anchored end space after a send
@@ -1527,13 +1590,35 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
}
: { scrollIndicatorInsets: { top: topContentInset, bottom: 0 } })}
{...(anchoredEndSpace ? { anchoredEndSpace } : {})}
itemLayoutAnimation={FEED_ITEM_LAYOUT_TRANSITION}
// Patched LegendList prop (patches/@[email protected]):
// lets its scroll math clamp programmatic scrolls to -headerInset
// instead of 0, so initialScrollAtEnd/maintainScrollAtEnd on short
// content rest below the transparent header rather than at frame top.
contentInsetStartAdjustment={usesNativeAutomaticInsets ? anchorTopInset : 0}
contentInsetEndAdjustment={props.contentInsetEndAdjustment}
// UIKit's automatic behavior adds the safe-area bottom on top of the
// raw contentInset the keyboard integration writes. The detail screen
// under-reports the composer inset by this amount (see
// ThreadDetailScreen); this tells LegendList's scroll math about the
// extra so programmatic end scrolls land at the true resting offset.
contentInsetEndStaticAdjustment={usesNativeAutomaticInsets ? insets.bottom : 0}
// The keyboard integration's offset math (end pinning, max scroll)
// must add the same UIKit-added extra, or its keyboard-open end
// targets land one safe-area short of the true resting offset.
adjustedInsetCompensation={usesNativeAutomaticInsets ? insets.bottom : 0}
freeze={props.freeze}
// Animated: on send, the optimistic message's dataChange fires
// maintainScrollAtEnd before any render-cycle suppression could
// engage — an instant snap there teleports the feed to the anchor
// instead of scrolling to it. Keeping it enabled (animated) during
// anchor scrolls also lets it correct a scroll that landed on a
// stale end target once the anchor row finishes measuring.
maintainScrollAtEnd={
disclosureToggleSettling
? false
: {
animated: false,
animated: true,
on: {
dataChange: true,
itemLayout: true,
@@ -1552,6 +1637,21 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
keyboardShouldPersistTaps="always"
keyboardDismissMode="none"
keyboardLiftBehavior="whenAtEnd"
// Seed the list's scroll math with the real viewport before its own
// onLayout: the empty→filled remount can then tell at mount that
// short content underflows the viewport and skip programmatic
// positioning entirely (any offset write during screen attach races
// UIKit's adjustedContentInset application and lands high or low).
{...(viewportHeight > 0 && viewportWidth > 0
? { estimatedListSize: { height: viewportHeight, width: viewportWidth } }
: {})}
// RN's native scrollTo command clamps targets to a floor of
// -contentInset.top using the RAW inset — under automatic insets the
// header inset only exists in adjustedContentInset, so scrolls to
// negative offsets (content top below the transparent header) get
// clamped to 0. This prop disables that clamp; UIKit still bounces
// user overscroll back to the adjusted rest position.
scrollToOverflowEnabled
estimatedItemSize={180}
initialScrollAtEnd
onScroll={handleScroll}
@@ -5,6 +5,7 @@ import { LayoutAnimation, Pressable, ScrollView, useColorScheme, View } from "re
import { AppText as Text } from "../../components/AppText";
import { cn } from "../../lib/cn";
import type { ThreadFeedActivity } from "../../lib/threadActivity";
import Animated, { FadeIn } from "react-native-reanimated";
const WORK_LOG_LAYOUT_ANIMATION = {
duration: 180,
@@ -68,6 +69,14 @@ function workRowSymbolName(icon: ThreadFeedActivity["icon"]): SFSymbol {
}
}
// Entering fades only for rows created moments ago: rows remount whenever the
// list scrolls them back into view, and old rows must not replay an entrance.
const FRESH_ROW_WINDOW_MS = 3_000;
function isFreshRow(createdAt: string): boolean {
const timestamp = Date.parse(createdAt);
return Number.isFinite(timestamp) && Date.now() - timestamp < FRESH_ROW_WINDOW_MS;
}
export function ThreadWorkLog(props: {
readonly activities: ReadonlyArray<ThreadFeedActivity>;
readonly copiedRowId: string | null;
@@ -104,7 +113,10 @@ export function ThreadWorkLog(props: {
const iconIsDestructive = row.icon === "alert" || row.icon === "warning";
return (
<View key={row.id}>
<Animated.View
key={row.id}
{...(isFreshRow(row.createdAt) ? { entering: FadeIn.duration(200) } : {})}
>
<Pressable
accessibilityRole={canExpand ? "button" : undefined}
accessibilityLabel={displayText}
@@ -207,7 +219,7 @@ export function ThreadWorkLog(props: {
</ScrollView>
</View>
) : null}
</View>
</Animated.View>
);
})}
</View>
+10
View File
@@ -16,6 +16,8 @@ import {
EnvironmentOperationForbiddenError,
EnvironmentRequestInvalidError,
type EnvironmentRequestInvalidReason,
EnvironmentResourceNotFoundError,
type EnvironmentResourceNotFoundReason,
EnvironmentScopeRequiredError,
EnvironmentAuthenticatedAuth,
EnvironmentAuthenticatedPrincipal,
@@ -137,6 +139,14 @@ function failEnvironmentOperationForbidden(reason: "current_session_revoke_not_a
);
}
export function failEnvironmentNotFound(reason: EnvironmentResourceNotFoundReason) {
return currentEnvironmentTraceId.pipe(
Effect.flatMap((traceId) =>
Effect.fail(new EnvironmentResourceNotFoundError({ code: "not_found", reason, traceId })),
),
);
}
export function failEnvironmentInternal(reason: EnvironmentInternalErrorReason, error?: unknown) {
return Effect.gen(function* () {
const traceId = yield* currentEnvironmentTraceId;
@@ -107,6 +107,7 @@ describe("CheckpointDiffQuery.layer", () => {
}),
getThreadShellById: () => Effect.succeed(Option.none()),
getThreadDetailById: () => Effect.succeed(Option.none()),
getThreadDetailSnapshot: () => Effect.succeed(Option.none()),
}),
),
);
@@ -199,6 +200,7 @@ describe("CheckpointDiffQuery.layer", () => {
getFullThreadDiffContext: () => Effect.die("unused"),
getThreadShellById: () => Effect.succeed(Option.none()),
getThreadDetailById: () => Effect.succeed(Option.none()),
getThreadDetailSnapshot: () => Effect.succeed(Option.none()),
}),
),
);
@@ -281,6 +283,7 @@ describe("CheckpointDiffQuery.layer", () => {
getFullThreadDiffContext: () => Effect.die("unused"),
getThreadShellById: () => Effect.succeed(Option.none()),
getThreadDetailById: () => Effect.succeed(Option.none()),
getThreadDetailSnapshot: () => Effect.succeed(Option.none()),
}),
),
);
@@ -348,6 +351,7 @@ describe("CheckpointDiffQuery.layer", () => {
getFullThreadDiffContext: () => Effect.die("unused"),
getThreadShellById: () => Effect.succeed(Option.none()),
getThreadDetailById: () => Effect.succeed(Option.none()),
getThreadDetailSnapshot: () => Effect.succeed(Option.none()),
}),
),
);
@@ -400,6 +404,7 @@ describe("CheckpointDiffQuery.layer", () => {
getFullThreadDiffContext: () => Effect.succeed(Option.none()),
getThreadShellById: () => Effect.succeed(Option.none()),
getThreadDetailById: () => Effect.succeed(Option.none()),
getThreadDetailSnapshot: () => Effect.succeed(Option.none()),
}),
),
);
+9 -1
View File
@@ -350,8 +350,16 @@ const runCloudCommand = <A, E>(
return yield* run.pipe(Effect.provide(runtimeLayer));
});
const deviceLoginFlag = Flag.boolean("device").pipe(
Flag.withDescription(
"Sign in with a device code approved from another browser (for SSH and headless machines).",
),
Flag.withDefault(false),
);
const connectLoginCommand = Command.make("login", {
...projectLocationFlags,
device: deviceLoginFlag,
}).pipe(
Command.withDescription("Authorize the T3 Connect CLI without enabling remote access."),
Command.withHandler((flags) =>
@@ -359,7 +367,7 @@ const connectLoginCommand = Command.make("login", {
flags,
Effect.gen(function* () {
const tokens = yield* CliTokenManager.CloudCliTokenManager;
yield* tokens.get;
yield* flags.device ? tokens.getWithDeviceLogin : tokens.get;
yield* Console.log("Signed in to T3 Connect.");
}),
),
+168 -5
View File
@@ -21,12 +21,25 @@ import * as HttpRouter from "effect/unstable/http/HttpRouter";
import * as HttpServerRequest from "effect/unstable/http/HttpServerRequest";
import * as HttpServerResponse from "effect/unstable/http/HttpServerResponse";
import {
RelayDeviceAuthorizationGrantType,
RelayDeviceAuthorizationResponse,
RelayDeviceTokenPollCode,
RelayDeviceTokenResponse,
} from "@t3tools/contracts/relay";
import {
HostProcessArchitecture,
HostProcessHostname,
HostProcessPlatform,
} from "@t3tools/shared/hostProcess";
import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
import { cloudCliOAuthConfig, type CloudCliOAuthConfig } from "./publicConfig.ts";
import { cloudCliOAuthConfig, relayUrlConfig, type CloudCliOAuthConfig } from "./publicConfig.ts";
const CLOUD_CLI_OAUTH_TOKEN_SECRET = "cloud-cli-oauth-token";
const CLOUD_CLI_OAUTH_CALLBACK_TIMEOUT = Duration.minutes(10);
const CLOUD_CLI_OAUTH_REFRESH_EARLY_MS = Duration.toMillis(Duration.minutes(5));
const CLOUD_CLI_DEVICE_POLL_MAX_TRANSPORT_FAILURES = 5;
const PersistedToken = Schema.Struct({
accessToken: Schema.String,
@@ -46,6 +59,10 @@ const OAuthTokenResponse = Schema.Struct({
token_type: Schema.String,
});
const DeviceTokenPollErrorBody = Schema.Struct({
code: RelayDeviceTokenPollCode,
});
export class CloudCliCredentialRemovalError extends Schema.TaggedErrorClass<CloudCliCredentialRemovalError>()(
"CloudCliCredentialRemovalError",
{ cause: Schema.Defect() },
@@ -104,6 +121,7 @@ export class CloudCliTokenManager extends Context.Service<
CloudCliTokenManager,
{
readonly get: Effect.Effect<PersistedToken, CloudCliTokenManagerError>;
readonly getWithDeviceLogin: Effect.Effect<PersistedToken, CloudCliTokenManagerError>;
readonly getExisting: Effect.Effect<Option.Option<PersistedToken>, CloudCliTokenManagerError>;
readonly hasCredential: Effect.Effect<boolean, CloudCliTokenManagerError>;
readonly clear: Effect.Effect<void, CloudCliTokenManagerError>;
@@ -115,6 +133,19 @@ const wrapError =
<A, E, R>(effect: Effect.Effect<A, E, R>): Effect.Effect<A, WrappedError, R> =>
effect.pipe(Effect.mapError(makeError));
const isCloudCliTokenManagerError = Schema.is(CloudCliTokenManagerError);
// Keeps already-typed manager errors (e.g. the authorization timeout) intact
// instead of collapsing them into a generic authorization failure.
const wrapUnknownError =
<WrappedError extends CloudCliTokenManagerError>(makeError: (cause: unknown) => WrappedError) =>
<A, E, R>(
effect: Effect.Effect<A, E, R>,
): Effect.Effect<A, WrappedError | CloudCliTokenManagerError, R> =>
effect.pipe(
Effect.mapError((cause) => (isCloudCliTokenManagerError(cause) ? cause : makeError(cause))),
);
function stringToBytes(value: string): Uint8Array {
return new TextEncoder().encode(value);
}
@@ -125,7 +156,9 @@ function bytesToString(value: Uint8Array): string {
export const make = Effect.gen(function* () {
const crypto = yield* Crypto.Crypto;
const httpClient = (yield* HttpClient.HttpClient).pipe(HttpClient.filterStatusOk);
// Device-token polling reads structured 400 bodies, so it needs the unfiltered client.
const rawHttpClient = yield* HttpClient.HttpClient;
const httpClient = rawHttpClient.pipe(HttpClient.filterStatusOk);
const secrets = yield* ServerSecretStore.ServerSecretStore;
const semaphore = yield* Semaphore.make(1);
const persist = Effect.fn("cloud.cli_token.persist")(function* (token: PersistedToken) {
@@ -222,7 +255,14 @@ export const make = Effect.gen(function* () {
authorizationUrl.searchParams.set("state", state);
authorizationUrl.searchParams.set("code_challenge", challenge);
authorizationUrl.searchParams.set("code_challenge_method", "S256");
yield* Console.log(`Open this URL to authorize T3 Connect:\n${authorizationUrl.toString()}\n`);
yield* Console.log(
[
`Open this URL to authorize T3 Connect:\n${authorizationUrl.toString()}`,
"",
"Tip: on a headless or remote machine (SSH, VPS), run `t3 connect login --device` instead.",
"",
].join("\n"),
);
const code = yield* Deferred.await(callback).pipe(
Effect.timeout(CLOUD_CLI_OAUTH_CALLBACK_TIMEOUT),
Effect.catchTag("TimeoutError", (cause) =>
@@ -242,6 +282,121 @@ export const make = Effect.gen(function* () {
});
});
const loginDevice = Effect.fn("cloud.cli_token.login_device")(function* () {
const metadata = yield* cloudCliOAuthConfig;
const relayUrl = yield* relayUrlConfig;
const verifier = Encoding.encodeBase64Url(yield* crypto.randomBytes(32));
const challenge = Encoding.encodeBase64Url(
yield* crypto.digest("SHA-256", new TextEncoder().encode(verifier)),
);
const hostname = yield* HostProcessHostname;
const platform = yield* HostProcessPlatform;
const architecture = yield* HostProcessArchitecture;
const authorization = yield* HttpClientRequest.post(`${relayUrl}/v1/device/authorization`).pipe(
HttpClientRequest.bodyUrlParams({
client_id: metadata.clientId,
scope: metadata.scopes.join(" "),
code_challenge: challenge,
code_challenge_method: "S256",
device_name: hostname,
device_platform: `${platform} (${architecture}) node-v${process.versions.node}`,
}),
httpClient.execute,
Effect.flatMap(HttpClientResponse.schemaBodyJson(RelayDeviceAuthorizationResponse)),
);
yield* Console.log(
[
`To authorize T3 Connect, open ${authorization.verification_uri} on another device and enter this code:`,
"",
` ${authorization.user_code}`,
"",
"Or open this link directly:",
authorization.verification_uri_complete,
"",
"Waiting for approval...",
].join("\n"),
);
let pollInterval = Duration.seconds(authorization.interval);
// Approval can take minutes; a flaky network or a relay blip mid-wait
// must not abort the whole login, so only repeated transport failures do.
let consecutiveTransportFailures = 0;
const failTransportOrContinue = (cause: unknown) => {
consecutiveTransportFailures += 1;
return consecutiveTransportFailures >= CLOUD_CLI_DEVICE_POLL_MAX_TRANSPORT_FAILURES
? Effect.fail(new CloudCliAuthorizationError({ cause }))
: Effect.succeed(Option.none<HttpClientResponse.HttpClientResponse>());
};
const poll = Effect.gen(function* () {
while (true) {
yield* Effect.sleep(pollInterval);
const response = yield* rawHttpClient
.execute(
HttpClientRequest.post(`${relayUrl}/v1/device/token`).pipe(
HttpClientRequest.bodyUrlParams({
grant_type: RelayDeviceAuthorizationGrantType,
device_code: authorization.device_code,
client_id: metadata.clientId,
}),
),
)
.pipe(Effect.map(Option.some), Effect.catch(failTransportOrContinue));
if (Option.isNone(response)) {
continue;
}
if (response.value.status === 200) {
return yield* HttpClientResponse.schemaBodyJson(RelayDeviceTokenResponse)(response.value);
}
if (response.value.status !== 400) {
// Gateway errors and other unexpected statuses are transient.
yield* failTransportOrContinue(
`Relay device token poll returned status ${response.value.status}.`,
);
continue;
}
consecutiveTransportFailures = 0;
const body = yield* HttpClientResponse.schemaBodyJson(DeviceTokenPollErrorBody)(
response.value,
).pipe(Effect.mapError((cause) => new CloudCliAuthorizationError({ cause })));
switch (body.code) {
case "authorization_pending":
continue;
case "slow_down":
pollInterval = Duration.sum(pollInterval, Duration.seconds(5));
continue;
case "access_denied":
return yield* new CloudCliAuthorizationError({
cause: "The device authorization request was denied.",
});
case "expired_token":
return yield* new CloudCliAuthorizationTimeoutError({
cause:
"The device authorization request expired or was already redeemed before this device could complete it.",
});
}
}
});
// The relay owns the authoritative expiry (it answers expired_token), so
// the local timeout is a backstop padded past the final scheduled poll.
const grant = yield* poll.pipe(
Effect.timeout(Duration.seconds(authorization.expires_in + authorization.interval + 5)),
Effect.catchTag("TimeoutError", (cause) =>
Effect.fail(new CloudCliAuthorizationTimeoutError({ cause })),
),
);
return yield* exchangeToken(metadata, {
grant_type: "authorization_code",
code: grant.authorization_code,
redirect_uri: grant.redirect_uri,
client_id: metadata.clientId,
code_verifier: verifier,
});
});
const getExistingNoLock = Effect.fn("cloud.cli_token.get_existing_no_lock")(function* () {
const token = yield* read();
if (Option.isNone(token)) return token;
@@ -267,10 +422,18 @@ export const make = Effect.gen(function* () {
return Option.isSome(token)
? token.value
: yield* Effect.scoped(login()).pipe(Effect.flatMap(persist));
}).pipe(wrapError((cause) => new CloudCliAuthorizationError({ cause }))),
}).pipe(wrapUnknownError((cause) => new CloudCliAuthorizationError({ cause }))),
);
const getWithDeviceLogin = semaphore.withPermits(1)(
Effect.gen(function* () {
const token = yield* getExistingNoLock();
return Option.isSome(token)
? token.value
: yield* loginDevice().pipe(Effect.flatMap(persist));
}).pipe(wrapUnknownError((cause) => new CloudCliAuthorizationError({ cause }))),
);
return CloudCliTokenManager.of({ get, getExisting, hasCredential, clear });
return CloudCliTokenManager.of({ get, getWithDeviceLogin, getExisting, hasCredential, clear });
});
export const layer = Layer.effect(CloudCliTokenManager, make);
+1
View File
@@ -192,6 +192,7 @@ describe("reconcileDesiredCloudLink", () => {
CliTokenManager.CloudCliTokenManager,
CliTokenManager.CloudCliTokenManager.of({
get: unusedSecretStoreOperation(),
getWithDeviceLogin: unusedSecretStoreOperation(),
getExisting: Effect.succeed(Option.none()),
hasCredential: unusedSecretStoreOperation(),
clear: unusedSecretStoreOperation(),
@@ -200,6 +200,7 @@ describe("OrchestrationEngine", () => {
getFullThreadDiffContext: () => Effect.succeed(Option.none()),
getThreadShellById: () => Effect.succeed(Option.none()),
getThreadDetailById: () => Effect.succeed(Option.none()),
getThreadDetailSnapshot: () => Effect.succeed(Option.none()),
}),
),
Layer.provide(
@@ -306,8 +306,8 @@ const makeOrchestrationEngine = Effect.gen(function* () {
Effect.annotateLogs({ sequence: commandReadModel.snapshotSequence }),
);
const readEvents: OrchestrationEngineShape["readEvents"] = (fromSequenceExclusive) =>
eventStore.readFromSequence(fromSequenceExclusive);
const readEvents: OrchestrationEngineShape["readEvents"] = (fromSequenceExclusive, limit) =>
eventStore.readFromSequence(fromSequenceExclusive, limit);
const dispatch: OrchestrationEngineShape["dispatch"] = (command) =>
Effect.gen(function* () {
@@ -9,6 +9,7 @@ import {
OrchestrationReadModel,
OrchestrationShellSnapshot,
OrchestrationThread,
OrchestrationThreadDetailSnapshot,
ProjectScript,
TurnId,
type OrchestrationCheckpointSummary,
@@ -2033,6 +2034,35 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
);
});
const getThreadDetailSnapshot: ProjectionSnapshotQueryShape["getThreadDetailSnapshot"] = (
threadId,
) =>
// Read the thread detail and the snapshot sequence within a single
// transaction so the sequence is consistent with the returned state; a
// projector update landing between two separate reads could otherwise return
// a sequence ahead of the thread detail, causing the client to resume from
// too far and drop events.
sql
.withTransaction(
Effect.gen(function* () {
const thread = yield* getThreadDetailById(threadId);
if (Option.isNone(thread)) {
return Option.none<OrchestrationThreadDetailSnapshot>();
}
const { snapshotSequence } = yield* getSnapshotSequence();
return Option.some({ snapshotSequence, thread: thread.value });
}),
)
.pipe(
Effect.mapError((error) =>
isPersistenceError(error)
? error
: toPersistenceSqlError("ProjectionSnapshotQuery.getThreadDetailSnapshot:transaction")(
error,
),
),
);
return {
getCommandReadModel,
getSnapshot,
@@ -2047,6 +2077,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
getFullThreadDiffContext,
getThreadShellById,
getThreadDetailById,
getThreadDetailSnapshot,
} satisfies ProjectionSnapshotQueryShape;
});
@@ -26,10 +26,15 @@ export interface OrchestrationEngineShape {
* Replay persisted orchestration events from an exclusive sequence cursor.
*
* @param fromSequenceExclusive - Sequence cursor (exclusive).
* @param limit - Maximum number of events to read. Defaults to the event
* store's page-bounded default; pass a higher value when the caller must
* read every event after the cursor (e.g. per-thread catch-up that filters
* a small subset out of a potentially larger global range).
* @returns Stream containing ordered events.
*/
readonly readEvents: (
fromSequenceExclusive: number,
limit?: number,
) => Stream.Stream<OrchestrationEvent, OrchestrationEventStoreError, never>;
/**
@@ -14,6 +14,7 @@ import type {
OrchestrationReadModel,
OrchestrationShellSnapshot,
OrchestrationThread,
OrchestrationThreadDetailSnapshot,
OrchestrationThreadShell,
ProjectId,
ThreadId,
@@ -157,6 +158,16 @@ export interface ProjectionSnapshotQueryShape {
readonly getThreadDetailById: (
threadId: ThreadId,
) => Effect.Effect<Option.Option<OrchestrationThread>, ProjectionRepositoryError>;
/**
* Read a single active thread detail together with the projection snapshot
* sequence in one consistent transaction, so the returned `snapshotSequence`
* exactly matches the state reflected in `thread` (no interleaving projector
* update between the two reads).
*/
readonly getThreadDetailSnapshot: (
threadId: ThreadId,
) => Effect.Effect<Option.Option<OrchestrationThreadDetailSnapshot>, ProjectionRepositoryError>;
}
/**
+34
View File
@@ -4,6 +4,7 @@ import {
EnvironmentHttpApi,
} from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
import * as HttpApiBuilder from "effect/unstable/httpapi/HttpApiBuilder";
import { normalizeDispatchCommand } from "./Normalizer.ts";
@@ -11,6 +12,7 @@ import {
annotateEnvironmentRequest,
failEnvironmentInternal,
failEnvironmentInvalidRequest,
failEnvironmentNotFound,
requireEnvironmentScope,
} from "../auth/http.ts";
import { OrchestrationEngineService } from "./Services/OrchestrationEngine.ts";
@@ -38,6 +40,38 @@ export const orchestrationHttpApiLayer = HttpApiBuilder.group(
);
}),
)
.handle(
"shellSnapshot",
Effect.fn("environment.orchestration.shellSnapshot")(function* (args) {
yield* annotateEnvironmentRequest(args.endpoint.name);
yield* requireEnvironmentScope(AuthOrchestrationReadScope);
return yield* projectionSnapshotQuery
.getShellSnapshot()
.pipe(
Effect.catch((cause) =>
failEnvironmentInternal("orchestration_snapshot_failed", cause),
),
);
}),
)
.handle(
"threadSnapshot",
Effect.fn("environment.orchestration.threadSnapshot")(function* (args) {
yield* annotateEnvironmentRequest(args.endpoint.name);
yield* requireEnvironmentScope(AuthOrchestrationReadScope);
const snapshot = yield* projectionSnapshotQuery
.getThreadDetailSnapshot(args.params.threadId)
.pipe(
Effect.catch((cause) =>
failEnvironmentInternal("orchestration_thread_snapshot_failed", cause),
),
);
if (Option.isNone(snapshot)) {
return yield* failEnvironmentNotFound("thread_not_found");
}
return snapshot.value;
}),
)
.handle(
"dispatch",
Effect.fn("environment.orchestration.dispatch")(function* (args) {
@@ -43,6 +43,7 @@ const makeProjectionSnapshotQueryLayer = (project: OrchestrationProject) =>
getFullThreadDiffContext: () => Effect.die("unused"),
getThreadShellById: () => Effect.die("unused"),
getThreadDetailById: () => Effect.die("unused"),
getThreadDetailSnapshot: () => Effect.die("unused"),
});
const makeTerminalManagerLayer = (
@@ -209,6 +209,7 @@ describe("ProviderSessionReaper", () => {
: Option.none(),
),
getThreadDetailById: () => Effect.die("unused"),
getThreadDetailSnapshot: () => Effect.die("unused"),
}),
),
Layer.provideMerge(NodeServices.layer),
+1
View File
@@ -702,6 +702,7 @@ const buildAppUnderTest = (options?: {
getProjectShellById: () => Effect.succeed(Option.none()),
getThreadShellById: () => Effect.succeed(Option.none()),
getThreadDetailById: () => Effect.succeed(Option.none()),
getThreadDetailSnapshot: () => Effect.succeed(Option.none()),
getCounts: () => Effect.succeed({ projectCount: 0, threadCount: 0 }),
getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()),
getFirstActiveThreadIdByProjectId: () => Effect.succeed(Option.none()),
@@ -96,6 +96,7 @@ it.effect("launchStartupHeartbeat does not block the caller while counts are loa
getFullThreadDiffContext: () => Effect.succeed(Option.none()),
getThreadShellById: () => Effect.succeed(Option.none()),
getThreadDetailById: () => Effect.succeed(Option.none()),
getThreadDetailSnapshot: () => Effect.succeed(Option.none()),
}),
Effect.provideService(AnalyticsService.AnalyticsService, {
record: () => Effect.void,
@@ -158,6 +159,7 @@ it.effect("resolveAutoBootstrapWelcomeTargets returns existing project and threa
getFullThreadDiffContext: () => Effect.succeed(Option.none()),
getThreadShellById: () => Effect.die("unused"),
getThreadDetailById: () => Effect.die("unused"),
getThreadDetailSnapshot: () => Effect.die("unused"),
}),
Effect.provideService(OrchestrationEngine.OrchestrationEngineService, {
readEvents: () => Stream.empty,
@@ -200,6 +202,7 @@ it.effect("resolveAutoBootstrapWelcomeTargets creates a project and thread when
getFullThreadDiffContext: () => Effect.succeed(Option.none()),
getThreadShellById: () => Effect.die("unused"),
getThreadDetailById: () => Effect.die("unused"),
getThreadDetailSnapshot: () => Effect.die("unused"),
}),
Effect.provideService(OrchestrationEngine.OrchestrationEngineService, {
readEvents: () => Stream.empty,
@@ -248,6 +251,7 @@ it.effect("resolveAutoBootstrapWelcomeTargets preserves typed UUID generation fa
getFullThreadDiffContext: () => Effect.succeed(Option.none()),
getThreadShellById: () => Effect.die("unused"),
getThreadDetailById: () => Effect.die("unused"),
getThreadDetailSnapshot: () => Effect.die("unused"),
}),
Effect.provideService(OrchestrationEngine.OrchestrationEngineService, {
readEvents: () => Stream.empty,
+109 -40
View File
@@ -30,6 +30,8 @@ import {
OrchestrationDispatchCommandError,
type OrchestrationEvent,
type OrchestrationShellStreamEvent,
type OrchestrationShellStreamItem,
type OrchestrationThreadStreamItem,
OrchestrationGetFullThreadDiffError,
OrchestrationGetSnapshotError,
OrchestrationGetTurnDiffError,
@@ -1059,10 +1061,54 @@ const makeWsRpcLayer = (
),
{ "rpc.aggregate": "orchestration" },
),
[ORCHESTRATION_WS_METHODS.subscribeShell]: (_input) =>
[ORCHESTRATION_WS_METHODS.subscribeShell]: (input) =>
observeRpcStreamEffect(
ORCHESTRATION_WS_METHODS.subscribeShell,
Effect.gen(function* () {
const liveStream = orchestrationEngine.streamDomainEvents.pipe(
Stream.mapEffect(toShellStreamEvent),
Stream.flatMap((event) =>
Option.isSome(event) ? Stream.succeed(event.value) : Stream.empty,
),
);
// When the client already holds a shell snapshot (cached, or loaded
// over HTTP) it passes that snapshot's sequence, and we resume by
// replaying shell events after it instead of re-sending the whole
// projects/threads list over the socket. As in the thread path, the
// live subscription is attached (into a scope-bound buffer) before
// draining the catch-up replay so no event published during the
// replay window is lost; overlapping events are deduped by sequence
// on the client. The full range is read (not the store's default
// page limit) since the shell filter runs after reading.
if (input.afterSequence !== undefined) {
const afterSequence = input.afterSequence;
return Stream.unwrap(
Effect.gen(function* () {
const liveBuffer = yield* Queue.unbounded<OrchestrationShellStreamItem>();
yield* Effect.forkScoped(
liveStream.pipe(Stream.runForEach((item) => Queue.offer(liveBuffer, item))),
);
const catchUpStream = orchestrationEngine
.readEvents(afterSequence, Number.MAX_SAFE_INTEGER)
.pipe(
Stream.mapEffect(toShellStreamEvent),
Stream.flatMap((event) =>
Option.isSome(event) ? Stream.succeed(event.value) : Stream.empty,
),
Stream.mapError(
(cause) =>
new OrchestrationGetSnapshotError({
message: "Failed to replay orchestration shell events",
cause,
}),
),
);
return Stream.concat(catchUpStream, Stream.fromQueue(liveBuffer));
}),
);
}
const snapshot = yield* projectionSnapshotQuery.getShellSnapshot().pipe(
Effect.tapError((cause) =>
Effect.logError("orchestration shell snapshot load failed", { cause }),
@@ -1076,13 +1122,6 @@ const makeWsRpcLayer = (
),
);
const liveStream = orchestrationEngine.streamDomainEvents.pipe(
Stream.mapEffect(toShellStreamEvent),
Stream.flatMap((event) =>
Option.isSome(event) ? Stream.succeed(event.value) : Stream.empty,
),
);
return Stream.concat(
Stream.make({
kind: "snapshot" as const,
@@ -1114,8 +1153,65 @@ const makeWsRpcLayer = (
observeRpcStreamEffect(
ORCHESTRATION_WS_METHODS.subscribeThread,
Effect.gen(function* () {
const [threadDetail, snapshotSequence] = yield* Effect.all([
projectionSnapshotQuery.getThreadDetailById(input.threadId).pipe(
const isThisThreadDetailEvent = (event: OrchestrationEvent) =>
event.aggregateKind === "thread" &&
event.aggregateId === input.threadId &&
isThreadDetailEvent(event);
const liveStream = orchestrationEngine.streamDomainEvents.pipe(
Stream.filter(isThisThreadDetailEvent),
Stream.map((event) => ({
kind: "event" as const,
event,
})),
);
// When the client already loaded the snapshot over HTTP it passes
// that snapshot's sequence, and we resume the live subscription by
// replaying persisted events after it instead of re-sending the
// (potentially multi-KB) snapshot frame over the socket.
//
// The live PubSub subscription must be attached *before* draining
// the catch-up replay, otherwise events published during the replay
// window are dropped (they are past the persisted tail the replay
// read, but the live stream is not yet subscribed). So fork the
// live stream into a buffer bound to this stream's scope, then emit
// catch-up followed by the buffered/ongoing live events. Overlapping
// events are deduped by sequence on the client.
//
// Read the full range after the cursor (not the store's default
// page-bounded limit): the range is normally tiny (a fresh HTTP
// snapshot sequence) and the per-thread filter runs after reading,
// so a global cap could otherwise omit this thread's events.
if (input.afterSequence !== undefined) {
const afterSequence = input.afterSequence;
return Stream.unwrap(
Effect.gen(function* () {
const liveBuffer = yield* Queue.unbounded<OrchestrationThreadStreamItem>();
yield* Effect.forkScoped(
liveStream.pipe(Stream.runForEach((item) => Queue.offer(liveBuffer, item))),
);
const catchUpStream = orchestrationEngine
.readEvents(afterSequence, Number.MAX_SAFE_INTEGER)
.pipe(
Stream.filter(isThisThreadDetailEvent),
Stream.map((event) => ({ kind: "event" as const, event })),
Stream.mapError(
(cause) =>
new OrchestrationGetSnapshotError({
message: `Failed to replay thread ${input.threadId} events`,
cause,
}),
),
);
return Stream.concat(catchUpStream, Stream.fromQueue(liveBuffer));
}),
);
}
const snapshot = yield* projectionSnapshotQuery
.getThreadDetailSnapshot(input.threadId)
.pipe(
Effect.mapError(
(cause) =>
new OrchestrationGetSnapshotError({
@@ -1123,46 +1219,19 @@ const makeWsRpcLayer = (
cause,
}),
),
),
projectionSnapshotQuery.getSnapshotSequence().pipe(
Effect.map(({ snapshotSequence }) => snapshotSequence),
Effect.mapError(
(cause) =>
new OrchestrationGetSnapshotError({
message: "Failed to load orchestration snapshot sequence",
cause,
}),
),
),
]);
);
if (Option.isNone(threadDetail)) {
if (Option.isNone(snapshot)) {
return yield* new OrchestrationGetSnapshotError({
message: `Thread ${input.threadId} was not found`,
cause: input.threadId,
});
}
const liveStream = orchestrationEngine.streamDomainEvents.pipe(
Stream.filter(
(event) =>
event.aggregateKind === "thread" &&
event.aggregateId === input.threadId &&
isThreadDetailEvent(event),
),
Stream.map((event) => ({
kind: "event" as const,
event,
})),
);
return Stream.concat(
Stream.make({
kind: "snapshot" as const,
snapshot: {
snapshotSequence,
thread: threadDetail.value,
},
snapshot: snapshot.value,
}),
liveStream,
);
+86
View File
@@ -0,0 +1,86 @@
import { ManagedRelay } from "@t3tools/client-runtime/relay";
import type {
RelayDeviceApprovalResponse,
RelayDeviceAuthorizationDetails,
RelayOkResponse,
} from "@t3tools/contracts/relay";
import * as Effect from "effect/Effect";
import { runtime } from "../lib/runtime";
export type DeviceAuthorizationResult<A> =
| { readonly _tag: "success"; readonly value: A }
| { readonly _tag: "not-found" }
| { readonly _tag: "failed"; readonly message: string };
function mapFailure(error: ManagedRelay.ManagedRelayClientError): DeviceAuthorizationResult<never> {
if (
error._tag === "ManagedRelayRequestFailedError" &&
error.relayError?._tag === "RelayDeviceAuthorizationNotFoundError"
) {
return { _tag: "not-found" };
}
return { _tag: "failed", message: error.message };
}
function runDeviceAuthorizationRequest<A>(
run: (
client: ManagedRelay.ManagedRelayClient["Service"],
) => Effect.Effect<A, ManagedRelay.ManagedRelayClientError>,
): Promise<DeviceAuthorizationResult<A>> {
return runtime.runPromise(
ManagedRelay.ManagedRelayClient.pipe(
Effect.flatMap(run),
Effect.map((value) => ({ _tag: "success", value }) as DeviceAuthorizationResult<A>),
Effect.catch((error) => Effect.succeed(mapFailure(error))),
),
);
}
export function getDeviceAuthorization(
clerkToken: string,
userCode: string,
): Promise<DeviceAuthorizationResult<RelayDeviceAuthorizationDetails>> {
return runDeviceAuthorizationRequest((client) =>
client.getDeviceAuthorization({ clerkToken, userCode }),
);
}
export function approveDeviceAuthorization(
clerkToken: string,
userCode: string,
): Promise<DeviceAuthorizationResult<RelayDeviceApprovalResponse>> {
return runDeviceAuthorizationRequest((client) =>
client.approveDeviceAuthorization({ clerkToken, userCode }),
);
}
export function denyDeviceAuthorization(
clerkToken: string,
userCode: string,
): Promise<DeviceAuthorizationResult<RelayOkResponse>> {
return runDeviceAuthorizationRequest((client) =>
client.denyDeviceAuthorization({ clerkToken, userCode }),
);
}
export function completeDeviceAuthorization(
clerkToken: string,
input: { readonly state: string; readonly code: string },
): Promise<DeviceAuthorizationResult<RelayOkResponse>> {
return runDeviceAuthorizationRequest((client) =>
client.completeDeviceAuthorization({ clerkToken, payload: input }),
);
}
export function formatDeviceUserCodeInput(raw: string): string {
const normalized = raw
.toUpperCase()
.replaceAll(/[^A-Z0-9]/gu, "")
.slice(0, 8);
return normalized.length > 4 ? `${normalized.slice(0, 4)}-${normalized.slice(4)}` : normalized;
}
export function isCompleteDeviceUserCode(value: string): boolean {
return /^[A-Z0-9]{4}-[A-Z0-9]{4}$/u.test(value);
}
+4
View File
@@ -160,6 +160,10 @@ function relayProtectedErrorMessage(error: RelayProtectedErrorType): string {
return `Relay rejected the agent activity publish proof (${error.reason}).`;
case "RelayInternalError":
return `Relay encountered an internal error (${error.reason}).`;
case "RelayDeviceTokenPollError":
return `Relay rejected the device authorization poll (${error.code}).`;
case "RelayDeviceAuthorizationNotFoundError":
return "Relay could not find the device authorization.";
}
}
@@ -0,0 +1,489 @@
import { useAuth, useClerk } from "@clerk/react";
import type { RelayDeviceAuthorizationDetails } from "@t3tools/contracts/relay";
import React, { useCallback, useEffect, useRef, useState } from "react";
import { APP_DISPLAY_NAME } from "../../branding";
import {
approveDeviceAuthorization,
completeDeviceAuthorization,
denyDeviceAuthorization,
formatDeviceUserCodeInput,
getDeviceAuthorization,
isCompleteDeviceUserCode,
} from "../../cloud/deviceAuthorization";
import { hasCloudPublicConfig, resolveRelayClerkTokenOptions } from "../../cloud/publicConfig";
import { Button } from "../ui/button";
import { Input } from "../ui/input";
function DeviceSurfaceShell({ children }: { readonly children: React.ReactNode }) {
return (
<div className="relative flex min-h-screen items-center justify-center overflow-hidden bg-background px-4 py-10 text-foreground sm:px-6">
<div className="pointer-events-none absolute inset-0 opacity-80">
<div className="absolute inset-x-0 top-0 h-44 bg-[radial-gradient(44rem_16rem_at_top,color-mix(in_srgb,var(--color-sky-500)_14%,transparent),transparent)]" />
<div className="absolute inset-y-0 left-0 w-72 bg-[radial-gradient(28rem_18rem_at_left,color-mix(in_srgb,var(--color-violet-500)_10%,transparent),transparent)]" />
<div className="absolute inset-0 bg-[linear-gradient(145deg,color-mix(in_srgb,var(--background)_90%,var(--color-black))_0%,var(--background)_55%)]" />
</div>
<section className="relative w-full max-w-xl rounded-2xl border border-border/80 bg-card/90 p-6 shadow-2xl shadow-black/20 backdrop-blur-md sm:p-8">
<p className="text-[11px] font-semibold tracking-[0.18em] text-muted-foreground uppercase">
{APP_DISPLAY_NAME}
</p>
{children}
</section>
</div>
);
}
function DeviceSurfaceMessage({
title,
message,
children,
}: {
readonly title: string;
readonly message: string;
readonly children?: React.ReactNode;
}) {
return (
<DeviceSurfaceShell>
<h1 className="mt-3 text-2xl font-semibold tracking-tight sm:text-3xl">{title}</h1>
<p className="mt-2 text-sm leading-relaxed text-muted-foreground">{message}</p>
{children}
</DeviceSurfaceShell>
);
}
function SignInGate({
title,
message,
children,
}: {
readonly title: string;
readonly message: string;
readonly children: React.ReactNode;
}) {
const { isLoaded, isSignedIn } = useAuth({ treatPendingAsSignedOut: false });
const clerk = useClerk();
if (!isLoaded) {
return <DeviceSurfaceMessage title={title} message="Checking your session." />;
}
if (!isSignedIn) {
return (
<DeviceSurfaceMessage title={title} message={message}>
<div className="mt-6">
<Button
size="sm"
onClick={() => clerk.openSignIn({ forceRedirectUrl: window.location.href })}
>
Sign in to continue
</Button>
</div>
</DeviceSurfaceMessage>
);
}
return children;
}
function useClerkTokenReader(): () => Promise<string | null> {
const { getToken } = useAuth({ treatPendingAsSignedOut: false });
return useCallback(
async () => (await getToken(resolveRelayClerkTokenOptions())) ?? null,
[getToken],
);
}
const GENERIC_FAILURE_MESSAGE =
"The device authorization service could not be reached. Try again in a moment.";
const NOT_FOUND_MESSAGE =
"That code was not recognized. It may have expired or already been used — run `t3 connect login --device` again to get a fresh code.";
type DeviceApprovalStep =
| { readonly step: "enter" }
| { readonly step: "looking-up" }
| { readonly step: "review"; readonly details: RelayDeviceAuthorizationDetails }
| { readonly step: "approving"; readonly details: RelayDeviceAuthorizationDetails }
| { readonly step: "denied" }
| { readonly step: "redirecting" };
export function DeviceAuthorizationSurface({
initialUserCode,
}: {
readonly initialUserCode?: string;
}) {
if (!hasCloudPublicConfig()) {
return (
<DeviceSurfaceMessage
title="Device authorization unavailable"
message="T3 Connect is not configured for this app, so there is nothing to authorize here."
/>
);
}
return (
<SignInGate
title="Authorize device"
message="Sign in to your T3 Connect account to authorize the device that requested access."
>
<ConfiguredDeviceAuthorizationSurface
{...(initialUserCode !== undefined ? { initialUserCode } : {})}
/>
</SignInGate>
);
}
function ConfiguredDeviceAuthorizationSurface({
initialUserCode,
}: {
readonly initialUserCode?: string;
}) {
const readClerkToken = useClerkTokenReader();
const [userCode, setUserCode] = useState(() => formatDeviceUserCodeInput(initialUserCode ?? ""));
const [state, setState] = useState<DeviceApprovalStep>({ step: "enter" });
const [errorMessage, setErrorMessage] = useState("");
const autoLookupAttemptedRef = useRef(false);
const lookupRequestSeqRef = useRef(0);
const lookup = useCallback(
async (code: string) => {
// A newer lookup supersedes any in-flight one; stale results must not
// reach setState or the review step could show the wrong device.
const requestSeq = ++lookupRequestSeqRef.current;
setErrorMessage("");
setState({ step: "looking-up" });
const clerkToken = await readClerkToken();
if (lookupRequestSeqRef.current !== requestSeq) {
return;
}
if (!clerkToken) {
setState({ step: "enter" });
setErrorMessage("Your session expired. Sign in again to continue.");
return;
}
const result = await getDeviceAuthorization(clerkToken, code);
if (lookupRequestSeqRef.current !== requestSeq) {
return;
}
if (result._tag === "success") {
if (result.value.status !== "pending") {
setState({ step: "enter" });
setErrorMessage(NOT_FOUND_MESSAGE);
return;
}
setState({ step: "review", details: result.value });
return;
}
setState({ step: "enter" });
setErrorMessage(result._tag === "not-found" ? NOT_FOUND_MESSAGE : GENERIC_FAILURE_MESSAGE);
},
[readClerkToken],
);
useEffect(() => {
if (autoLookupAttemptedRef.current) {
return;
}
autoLookupAttemptedRef.current = true;
const initial = formatDeviceUserCodeInput(initialUserCode ?? "");
if (isCompleteDeviceUserCode(initial)) {
void lookup(initial);
}
}, [initialUserCode, lookup]);
const approve = useCallback(
async (details: RelayDeviceAuthorizationDetails) => {
setErrorMessage("");
setState({ step: "approving", details });
const clerkToken = await readClerkToken();
if (!clerkToken) {
setState({ step: "review", details });
setErrorMessage("Your session expired. Sign in again to continue.");
return;
}
const result = await approveDeviceAuthorization(clerkToken, details.userCode);
if (result._tag === "success") {
setState({ step: "redirecting" });
window.location.assign(result.value.authorizationUrl);
return;
}
if (result._tag === "not-found") {
setState({ step: "enter" });
setErrorMessage(NOT_FOUND_MESSAGE);
return;
}
setState({ step: "review", details });
setErrorMessage(GENERIC_FAILURE_MESSAGE);
},
[readClerkToken],
);
const deny = useCallback(
async (details: RelayDeviceAuthorizationDetails) => {
setErrorMessage("");
const clerkToken = await readClerkToken();
if (!clerkToken) {
setErrorMessage("Your session expired. Sign in again to continue.");
return;
}
const result = await denyDeviceAuthorization(clerkToken, details.userCode);
if (result._tag === "success" || result._tag === "not-found") {
setState({ step: "denied" });
return;
}
setErrorMessage(GENERIC_FAILURE_MESSAGE);
},
[readClerkToken],
);
if (state.step === "denied") {
return (
<DeviceSurfaceMessage
title="Request denied"
message="The device was not authorized. You can close this window."
/>
);
}
if (state.step === "redirecting") {
return (
<DeviceSurfaceMessage
title="Finishing authorization"
message="Confirming access with the sign-in service."
/>
);
}
if (state.step === "review" || state.step === "approving") {
const { details } = state;
const approving = state.step === "approving";
return (
<DeviceSurfaceShell>
<h1 className="mt-3 text-2xl font-semibold tracking-tight sm:text-3xl">Authorize device</h1>
<p className="mt-2 text-sm leading-relaxed text-muted-foreground">
A device is asking to sign in to your T3 Connect account with this code:
</p>
<p className="mt-4 text-center font-mono text-3xl font-semibold tracking-[0.2em]">
{details.userCode}
</p>
<dl className="mt-5 space-y-2 rounded-lg border border-border/70 bg-background/55 px-3 py-3 text-xs leading-relaxed text-muted-foreground">
<DeviceDetailRow label="Device">
{details.deviceName ?? "Unknown device"}
{details.devicePlatform ? ` · ${details.devicePlatform}` : ""}
{details.clientVersion ? ` · ${details.clientVersion}` : ""}
</DeviceDetailRow>
{details.requestIp ? (
<DeviceDetailRow label="Address">
{details.requestIp}
{details.requestLocation ? ` (${details.requestLocation})` : ""}
</DeviceDetailRow>
) : null}
<DeviceDetailRow label="Requested">
{formatTimestamp(details.requestedAt)}
</DeviceDetailRow>
</dl>
{errorMessage ? <DeviceSurfaceError message={errorMessage} /> : null}
<div className="mt-6 flex flex-wrap gap-2">
<Button disabled={approving} size="sm" onClick={() => void approve(details)}>
{approving ? "Authorizing..." : "Allow"}
</Button>
<Button
disabled={approving}
size="sm"
variant="outline"
onClick={() => void deny(details)}
>
Deny
</Button>
</div>
<p className="mt-5 text-xs leading-relaxed text-muted-foreground">
Do not click Allow unless you started this login attempt yourself with{" "}
<span className="font-mono">t3 connect login --device</span>. Anyone with this code can
request access to your account.
</p>
</DeviceSurfaceShell>
);
}
const lookingUp = state.step === "looking-up";
return (
<DeviceSurfaceShell>
<h1 className="mt-3 text-2xl font-semibold tracking-tight sm:text-3xl">Authorize device</h1>
<p className="mt-2 text-sm leading-relaxed text-muted-foreground">
Enter the code shown in your terminal to authorize the device requesting access to your T3
Connect account.
</p>
<form
className="mt-6 space-y-4"
onSubmit={(event) => {
event.preventDefault();
if (isCompleteDeviceUserCode(userCode)) {
void lookup(userCode);
}
}}
>
<Input
aria-label="Device code"
autoCapitalize="characters"
autoComplete="off"
autoCorrect="off"
autoFocus
className="text-center font-mono text-xl tracking-[0.25em] uppercase"
disabled={lookingUp}
nativeInput
onChange={(event) => setUserCode(formatDeviceUserCodeInput(event.currentTarget.value))}
placeholder="XXXX-XXXX"
spellCheck={false}
value={userCode}
/>
{errorMessage ? <DeviceSurfaceError message={errorMessage} /> : null}
<Button disabled={lookingUp || !isCompleteDeviceUserCode(userCode)} size="sm" type="submit">
{lookingUp ? "Checking..." : "Continue"}
</Button>
</form>
</DeviceSurfaceShell>
);
}
function DeviceDetailRow({
label,
children,
}: {
readonly label: string;
readonly children: React.ReactNode;
}) {
return (
<div className="flex gap-3">
<dt className="w-20 shrink-0 font-medium text-foreground/70">{label}</dt>
<dd className="text-foreground/85">{children}</dd>
</div>
);
}
function DeviceSurfaceError({ message }: { readonly message: string }) {
return (
<div className="rounded-lg border border-destructive/30 bg-destructive/6 px-3 py-2 text-sm text-destructive">
{message}
</div>
);
}
function formatTimestamp(value: string): string {
const parsed = new Date(value);
return Number.isNaN(parsed.getTime()) ? value : parsed.toLocaleString();
}
export function DeviceAuthorizationCallbackSurface({
code,
state,
authorizationError,
}: {
readonly code?: string;
readonly state?: string;
readonly authorizationError?: string;
}) {
if (!hasCloudPublicConfig()) {
return (
<DeviceSurfaceMessage
title="Device authorization unavailable"
message="T3 Connect is not configured for this app, so there is nothing to authorize here."
/>
);
}
if (authorizationError) {
return (
<DeviceSurfaceMessage
title="Authorization not completed"
message="The sign-in service did not grant access to the device. You can close this window, or run `t3 connect login --device` again to retry."
/>
);
}
if (!code || !state) {
return (
<DeviceSurfaceMessage
title="Authorization not completed"
message="This page is missing its authorization details. Start again from your terminal with `t3 connect login --device`."
/>
);
}
return (
<SignInGate
title="Finish device authorization"
message="Sign in to finish authorizing the device."
>
<ConfiguredDeviceAuthorizationCallbackSurface code={code} state={state} />
</SignInGate>
);
}
function ConfiguredDeviceAuthorizationCallbackSurface({
code,
state,
}: {
readonly code: string;
readonly state: string;
}) {
const readClerkToken = useClerkTokenReader();
const [status, setStatus] = useState<"completing" | "done" | "not-found" | "failed">(
"completing",
);
const completionAttemptedRef = useRef(false);
useEffect(() => {
if (completionAttemptedRef.current) {
return;
}
completionAttemptedRef.current = true;
void (async () => {
const clerkToken = await readClerkToken();
if (!clerkToken) {
setStatus("failed");
return;
}
const result = await completeDeviceAuthorization(clerkToken, { state, code });
setStatus(
result._tag === "success" ? "done" : result._tag === "not-found" ? "not-found" : "failed",
);
})();
}, [code, readClerkToken, state]);
if (status === "completing") {
return (
<DeviceSurfaceMessage
title="Finishing device authorization"
message="Handing the authorization back to your device."
/>
);
}
if (status === "done") {
return (
<DeviceSurfaceMessage
title="Device authorized"
message="You can close this window and return to your terminal — it signs in automatically within a few seconds."
/>
);
}
return (
<DeviceSurfaceMessage
title="Authorization not completed"
message={
status === "not-found"
? NOT_FOUND_MESSAGE
: "The device authorization could not be completed. Run `t3 connect login --device` again to retry."
}
/>
);
}
+6 -1
View File
@@ -1,4 +1,6 @@
import { Connection } from "@t3tools/client-runtime/connection";
import { shellSnapshotLoaderLayer } from "@t3tools/client-runtime/state/shell";
import { threadSnapshotLoaderLayer } from "@t3tools/client-runtime/state/threads";
import * as Layer from "effect/Layer";
import { Atom } from "effect/unstable/reactivity";
@@ -9,12 +11,15 @@ const providedConnectionPlatformLayer = connectionPlatformLayer.pipe(
Layer.provide(runtimeContextLayer),
);
const snapshotLoaderLayer = Layer.merge(threadSnapshotLoaderLayer, shellSnapshotLoaderLayer);
type ConnectionLayerSource =
| typeof Connection.layer
| typeof snapshotLoaderLayer
| typeof runtimeContextLayer
| typeof connectionPlatformLayer;
const connectionLayer = Connection.layer.pipe(
const connectionLayer = Layer.merge(Connection.layer, snapshotLoaderLayer).pipe(
Layer.provideMerge(Layer.mergeAll(runtimeContextLayer, providedConnectionPlatformLayer)),
);
+12 -9
View File
@@ -20,7 +20,7 @@ import {
import {
EnvironmentId,
OrchestrationShellSnapshot,
OrchestrationThread,
OrchestrationThreadDetailSnapshot,
ThreadId,
} from "@t3tools/contracts";
import * as Context from "effect/Context";
@@ -45,11 +45,14 @@ const StoredShellSnapshot = Schema.Struct({
snapshot: OrchestrationShellSnapshot,
});
const StoredShellSnapshotJson = Schema.fromJsonString(StoredShellSnapshot);
// v2 stores the snapshot sequence alongside the thread so a warm cache can
// resume via `afterSequence` instead of re-downloading the full thread body.
// Older v1 entries (no sequence) fail to decode and are treated as a cold cache.
const StoredThreadSnapshot = Schema.Struct({
schemaVersion: Schema.Literal(1),
schemaVersion: Schema.Literal(2),
environmentId: EnvironmentId,
threadId: ThreadId,
thread: OrchestrationThread,
snapshot: OrchestrationThreadDetailSnapshot,
});
const StoredThreadSnapshotJson = Schema.fromJsonString(StoredThreadSnapshot);
const ConnectionCatalogDocumentJson = Schema.fromJsonString(ConnectionCatalogDocument);
@@ -473,7 +476,7 @@ export const connectionStorageLayer = Layer.effectContext(
Effect.mapError((cause) => persistenceError("load-thread", cause)),
Effect.map((stored) =>
stored.environmentId === environmentId && stored.threadId === threadId
? Option.some(stored.thread)
? Option.some(stored.snapshot)
: Option.none(),
),
);
@@ -484,18 +487,18 @@ export const connectionStorageLayer = Layer.effectContext(
: persistenceError("load-thread", cause),
),
),
saveThread: (environmentId, thread) =>
saveThread: (environmentId, snapshot) =>
Effect.gen(function* () {
const encoded = yield* encodeStoredThreadSnapshot({
schemaVersion: 1,
schemaVersion: 2,
environmentId,
threadId: thread.id,
thread,
threadId: snapshot.thread.id,
snapshot,
}).pipe(Effect.mapError((cause) => persistenceError("save-thread", cause)));
yield* writeDatabaseValue(
database,
THREAD_STORE_NAME,
threadCacheKey(environmentId, thread.id),
threadCacheKey(environmentId, snapshot.thread.id),
encoded,
);
}).pipe(
@@ -221,6 +221,8 @@ function readEnvironmentHttpErrorStatus(error: EnvironmentHttpCommonErrorType):
case "EnvironmentScopeRequiredError":
case "EnvironmentOperationForbiddenError":
return 403;
case "EnvironmentResourceNotFoundError":
return 404;
case "EnvironmentInternalError":
return 500;
}
+42
View File
@@ -20,6 +20,8 @@ import { Route as SettingsGeneralRouteImport } from './routes/settings.general'
import { Route as SettingsDiagnosticsRouteImport } from './routes/settings.diagnostics'
import { Route as SettingsConnectionsRouteImport } from './routes/settings.connections'
import { Route as SettingsArchivedRouteImport } from './routes/settings.archived'
import { Route as OauthDeviceRouteImport } from './routes/oauth.device'
import { Route as OauthDeviceCallbackRouteImport } from './routes/oauth.device_.callback'
import { Route as ChatDraftDraftIdRouteImport } from './routes/_chat.draft.$draftId'
import { Route as ChatEnvironmentIdThreadIdRouteImport } from './routes/_chat.$environmentId.$threadId'
@@ -77,6 +79,16 @@ const SettingsArchivedRoute = SettingsArchivedRouteImport.update({
path: '/archived',
getParentRoute: () => SettingsRoute,
} as any)
const OauthDeviceRoute = OauthDeviceRouteImport.update({
id: '/oauth/device',
path: '/oauth/device',
getParentRoute: () => rootRouteImport,
} as any)
const OauthDeviceCallbackRoute = OauthDeviceCallbackRouteImport.update({
id: '/oauth/device_/callback',
path: '/oauth/device/callback',
getParentRoute: () => rootRouteImport,
} as any)
const ChatDraftDraftIdRoute = ChatDraftDraftIdRouteImport.update({
id: '/draft/$draftId',
path: '/draft/$draftId',
@@ -93,6 +105,7 @@ export interface FileRoutesByFullPath {
'/': typeof ChatIndexRoute
'/pair': typeof PairRoute
'/settings': typeof SettingsRouteWithChildren
'/oauth/device': typeof OauthDeviceRoute
'/settings/archived': typeof SettingsArchivedRoute
'/settings/connections': typeof SettingsConnectionsRoute
'/settings/diagnostics': typeof SettingsDiagnosticsRoute
@@ -102,10 +115,12 @@ export interface FileRoutesByFullPath {
'/settings/source-control': typeof SettingsSourceControlRoute
'/$environmentId/$threadId': typeof ChatEnvironmentIdThreadIdRoute
'/draft/$draftId': typeof ChatDraftDraftIdRoute
'/oauth/device/callback': typeof OauthDeviceCallbackRoute
}
export interface FileRoutesByTo {
'/pair': typeof PairRoute
'/settings': typeof SettingsRouteWithChildren
'/oauth/device': typeof OauthDeviceRoute
'/settings/archived': typeof SettingsArchivedRoute
'/settings/connections': typeof SettingsConnectionsRoute
'/settings/diagnostics': typeof SettingsDiagnosticsRoute
@@ -116,12 +131,14 @@ export interface FileRoutesByTo {
'/': typeof ChatIndexRoute
'/$environmentId/$threadId': typeof ChatEnvironmentIdThreadIdRoute
'/draft/$draftId': typeof ChatDraftDraftIdRoute
'/oauth/device/callback': typeof OauthDeviceCallbackRoute
}
export interface FileRoutesById {
__root__: typeof rootRouteImport
'/_chat': typeof ChatRouteWithChildren
'/pair': typeof PairRoute
'/settings': typeof SettingsRouteWithChildren
'/oauth/device': typeof OauthDeviceRoute
'/settings/archived': typeof SettingsArchivedRoute
'/settings/connections': typeof SettingsConnectionsRoute
'/settings/diagnostics': typeof SettingsDiagnosticsRoute
@@ -132,6 +149,7 @@ export interface FileRoutesById {
'/_chat/': typeof ChatIndexRoute
'/_chat/$environmentId/$threadId': typeof ChatEnvironmentIdThreadIdRoute
'/_chat/draft/$draftId': typeof ChatDraftDraftIdRoute
'/oauth/device_/callback': typeof OauthDeviceCallbackRoute
}
export interface FileRouteTypes {
fileRoutesByFullPath: FileRoutesByFullPath
@@ -139,6 +157,7 @@ export interface FileRouteTypes {
| '/'
| '/pair'
| '/settings'
| '/oauth/device'
| '/settings/archived'
| '/settings/connections'
| '/settings/diagnostics'
@@ -148,10 +167,12 @@ export interface FileRouteTypes {
| '/settings/source-control'
| '/$environmentId/$threadId'
| '/draft/$draftId'
| '/oauth/device/callback'
fileRoutesByTo: FileRoutesByTo
to:
| '/pair'
| '/settings'
| '/oauth/device'
| '/settings/archived'
| '/settings/connections'
| '/settings/diagnostics'
@@ -162,11 +183,13 @@ export interface FileRouteTypes {
| '/'
| '/$environmentId/$threadId'
| '/draft/$draftId'
| '/oauth/device/callback'
id:
| '__root__'
| '/_chat'
| '/pair'
| '/settings'
| '/oauth/device'
| '/settings/archived'
| '/settings/connections'
| '/settings/diagnostics'
@@ -177,12 +200,15 @@ export interface FileRouteTypes {
| '/_chat/'
| '/_chat/$environmentId/$threadId'
| '/_chat/draft/$draftId'
| '/oauth/device_/callback'
fileRoutesById: FileRoutesById
}
export interface RootRouteChildren {
ChatRoute: typeof ChatRouteWithChildren
PairRoute: typeof PairRoute
SettingsRoute: typeof SettingsRouteWithChildren
OauthDeviceRoute: typeof OauthDeviceRoute
OauthDeviceCallbackRoute: typeof OauthDeviceCallbackRoute
}
declare module '@tanstack/react-router' {
@@ -264,6 +290,20 @@ declare module '@tanstack/react-router' {
preLoaderRoute: typeof SettingsArchivedRouteImport
parentRoute: typeof SettingsRoute
}
'/oauth/device': {
id: '/oauth/device'
path: '/oauth/device'
fullPath: '/oauth/device'
preLoaderRoute: typeof OauthDeviceRouteImport
parentRoute: typeof rootRouteImport
}
'/oauth/device_/callback': {
id: '/oauth/device_/callback'
path: '/oauth/device/callback'
fullPath: '/oauth/device/callback'
preLoaderRoute: typeof OauthDeviceCallbackRouteImport
parentRoute: typeof rootRouteImport
}
'/_chat/draft/$draftId': {
id: '/_chat/draft/$draftId'
path: '/draft/$draftId'
@@ -323,6 +363,8 @@ const rootRouteChildren: RootRouteChildren = {
ChatRoute: ChatRouteWithChildren,
PairRoute: PairRoute,
SettingsRoute: SettingsRouteWithChildren,
OauthDeviceRoute: OauthDeviceRoute,
OauthDeviceCallbackRoute: OauthDeviceCallbackRoute,
}
export const routeTree = rootRouteImport
._addFileChildren(rootRouteChildren)
+1 -1
View File
@@ -96,7 +96,7 @@ function RootRouteView() {
};
}, [pathname]);
if (pathname === "/pair") {
if (pathname === "/pair" || pathname.startsWith("/oauth/device")) {
return (
<>
<DocumentTitleSync />
+15
View File
@@ -0,0 +1,15 @@
import { createFileRoute } from "@tanstack/react-router";
import { DeviceAuthorizationSurface } from "../components/auth/DeviceAuthorizationSurface";
export const Route = createFileRoute("/oauth/device")({
validateSearch: (search: Record<string, unknown>) => ({
user_code: typeof search.user_code === "string" ? search.user_code : undefined,
}),
component: DeviceAuthorizationRouteView,
});
function DeviceAuthorizationRouteView() {
const { user_code } = Route.useSearch();
return <DeviceAuthorizationSurface {...(user_code ? { initialUserCode: user_code } : {})} />;
}
@@ -0,0 +1,23 @@
import { createFileRoute } from "@tanstack/react-router";
import { DeviceAuthorizationCallbackSurface } from "../components/auth/DeviceAuthorizationSurface";
export const Route = createFileRoute("/oauth/device_/callback")({
validateSearch: (search: Record<string, unknown>) => ({
code: typeof search.code === "string" ? search.code : undefined,
state: typeof search.state === "string" ? search.state : undefined,
error: typeof search.error === "string" ? search.error : undefined,
}),
component: DeviceAuthorizationCallbackRouteView,
});
function DeviceAuthorizationCallbackRouteView() {
const { code, state, error } = Route.useSearch();
return (
<DeviceAuthorizationCallbackSurface
{...(code ? { code } : {})}
{...(state ? { state } : {})}
{...(error ? { authorizationError: error } : {})}
/>
);
}
+28 -12
View File
@@ -42,7 +42,10 @@ deployments.
For a hosted relay deployment, copy `infra/relay/.env.example` to `infra/relay/.env`. The relay
deployment reads `RELAY_DOMAIN`, `RELAY_API_ZONE_NAME`, `RELAY_TUNNEL_ZONE_NAME`,
`CLERK_PUBLISHABLE_KEY`, and `CLERK_JWT_AUDIENCE` through Effect `Config`. There are no checked-in
`CLERK_PUBLISHABLE_KEY`, and `CLERK_JWT_AUDIENCE` through Effect `Config`, plus
`T3CODE_APP_BASE_URL` (web app origin for device-code login; `prod` defaults to
`https://app.t3.codes`, and every other stage must set it explicitly to a web app build that
targets the same stage relay and Clerk instance). Other than that default, there are no checked-in
deployment defaults.
`vp run --filter t3code-relay deploy` invokes Alchemy from the relay directory, so Alchemy loads
`infra/relay/.env`. After a successful deployment, the wrapper updates the repository-root `.env`
@@ -63,19 +66,30 @@ In **Clerk Dashboard > OAuth applications**:
1. Create an OAuth application for the T3 CLI.
2. Enable the **Public** option so authorization-code exchange uses PKCE.
3. Add `http://127.0.0.1:34338/callback` as an allowed redirect URI.
4. Enable the `openid`, `profile`, and `email` scopes.
5. Set `T3CODE_CLERK_CLI_OAUTH_CLIENT_ID` in the repository-root `.env` file and release build
3. Add `http://127.0.0.1:34338/callback` as an allowed redirect URI. This serves the default
loopback login flow.
4. Add `<app origin>/oauth/device/callback` as an additional allowed redirect URI for device-code
login (`t3 connect login --device`). The app origin must match the relay stage's
`T3CODE_APP_BASE_URL` (production: `https://app.t3.codes/oauth/device/callback`). For local
web-app testing against a development Clerk instance, also add the dev-server variant such as
`http://localhost:5733/oauth/device/callback`.
5. Enable the `openid`, `profile`, and `email` scopes.
6. Set `T3CODE_CLERK_CLI_OAUTH_CLIENT_ID` in the repository-root `.env` file and release build
environment to the generated public client ID.
The CLI derives Clerk's frontend API URL from the publishable key and calls Clerk's
`/oauth/authorize` and `/oauth/token` endpoints directly. The relay is not involved in the OAuth
handshake; it only validates the issued Clerk bearer token when the CLI manages an environment link.
`/oauth/authorize` and `/oauth/token` endpoints directly. In the default loopback flow the relay is
not involved in the OAuth handshake; it only validates the issued Clerk bearer token when the CLI
manages an environment link. In the device flow the relay additionally brokers the pending
authorization (it stores the PKCE challenge and hands the Clerk authorization code back to the
polling CLI), but the token exchange still happens directly between the CLI and Clerk, so both
flows store the same credential.
The CLI supports these headless operations:
```sh
t3 connect login
t3 connect login --device
t3 connect link
t3 connect status
t3 connect unlink
@@ -84,7 +98,11 @@ t3 serve
```
`t3 connect login` opens the Clerk authorization flow and stores the CLI credential without enabling
cloud exposure. `t3 connect link` installs the pinned managed `cloudflared` binary when needed,
cloud exposure. `t3 connect login --device` uses a device-code flow instead: the CLI prints a short
code and a link to `<T3CODE_APP_BASE_URL>/oauth/device`, where a signed-in user reviews the
requesting device and approves or denies it while the CLI polls the relay for the result. Use it on
VPSes, containers, and other machines where the loopback browser flow is impractical.
`t3 connect link` installs the pinned managed `cloudflared` binary when needed,
authorizes when needed, and records durable intent to expose the environment. It works without a
running T3 server. The next `t3 serve` or `t3 start` reconciles the relay link and launches the
managed tunnel. `t3 connect unlink` records disabled intent immediately, stops a reachable running
@@ -92,16 +110,14 @@ connector, and attempts to revoke the relay-side environment record. It retains
authorization so `t3 connect link` can re-enable exposure without another browser flow. `t3 connect
logout` performs the same cleanup and removes the stored CLI authorization.
The current OAuth callback listener binds to loopback port `34338`. When running the CLI over SSH,
forward that port before running `t3 connect login` or `t3 connect link`:
The default loopback callback listener binds to port `34338`. When running the CLI over SSH, either
use `t3 connect login --device` (recommended — no port forwarding required) or forward that port
before running `t3 connect login` or `t3 connect link`:
```sh
ssh -L 34338:127.0.0.1:34338 <host>
```
A relay-hosted callback broker can remove this port-forward requirement later without changing the
stored PKCE token model.
## JWT Template
In **Clerk Dashboard > JWT templates**, create a template with:
+4
View File
@@ -0,0 +1,4 @@
<svg width="128" height="128" viewBox="0 0 128 128" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M0 10C0 4.47715 4.47715 0 10 0H118C123.523 0 128 4.47715 128 10V118C128 123.523 123.523 128 118 128H10C4.47715 128 0 123.523 0 118V10Z" fill="black"/>
<path d="M33.4509 93V47.56H15.5309V37H64.3309V47.56H46.4109V93H33.4509ZM86.7253 93.96C82.832 93.96 78.9653 93.4533 75.1253 92.44C71.2853 91.3733 68.032 89.88 65.3653 87.96L70.4053 78.04C72.5386 79.5867 75.0186 80.8133 77.8453 81.72C80.672 82.6267 83.5253 83.08 86.4053 83.08C89.6586 83.08 92.2186 82.44 94.0853 81.16C95.952 79.88 96.8853 78.12 96.8853 75.88C96.8853 73.7467 96.0586 72.0667 94.4053 70.84C92.752 69.6133 90.0853 69 86.4053 69H80.4853V60.44L96.0853 42.76L97.5253 47.4H68.1653V37H107.365V45.4L91.8453 63.08L85.2853 59.32H89.0453C95.9253 59.32 101.125 60.8667 104.645 63.96C108.165 67.0533 109.925 71.0267 109.925 75.88C109.925 79.0267 109.099 81.9867 107.445 84.76C105.792 87.48 103.259 89.6933 99.8453 91.4C96.432 93.1067 92.0586 93.96 86.7253 93.96Z" fill="white"/>
</svg>

After

Width:  |  Height:  |  Size: 1.0 KiB

+10
View File
@@ -9,6 +9,16 @@ RELAY_TUNNEL_ZONE_NAME=tunnels.example.com
# Set this only when the derived relay hostname should not be used.
# RELAY_DOMAIN=relay.example.com
# Hosted web app origin for device-code login
# `t3 connect login --device` sends users to <origin>/oauth/device and the
# approval flow returns through <origin>/oauth/device/callback, so the origin
# must serve a web app built against this relay stage and its Clerk instance,
# and the callback URL must be an allowed redirect URI on the Clerk CLI OAuth
# application. The `prod` stage defaults to https://app.t3.codes; every other
# stage must set this explicitly to its own app build (for local testing,
# e.g. http://localhost:5733) or the deploy fails.
# T3CODE_APP_BASE_URL=http://localhost:5733
# Required: Clerk
# Get the keys from the Clerk Dashboard under API keys. Set the JWT audience to
# the `aud` claim configured on the `t3-relay` JWT template.
+6 -1
View File
@@ -19,6 +19,8 @@ The relay currently owns:
- Linking T3 Code environments to a cloud account.
- Provisioning and tracking managed environment endpoints.
- Issuing short-lived credentials used to connect clients to linked environments.
- Brokering OAuth device authorization for headless CLI logins (`t3 connect login --device`),
including the pending-authorization records approved at `app.t3.codes/oauth/device`.
- Listing linked environments and registered mobile devices for an account.
- Registering mobile notification preferences and APNs tokens.
- Receiving published agent activity and delivering notifications or Live Activity updates.
@@ -85,7 +87,10 @@ vp run --filter t3code-relay deploy
The stack provisions the Cloudflare Worker and queues, managed endpoint resources, database
connectivity, and relay tracing resources. Copy [`infra/relay/.env.example`](./.env.example) to
`infra/relay/.env` and fill in the deployment-specific values before deploying. Alchemy loads that
file from the relay directory. Runtime secrets include Clerk and APNs credentials. Production adopts
file from the relay directory. Runtime secrets include Clerk and APNs credentials.
`T3CODE_APP_BASE_URL` selects the web app origin used by device-code login; `prod` defaults to
`https://app.t3.codes`, and every other stage must set it explicitly — see the comment in
`.env.example`. Production adopts
the configured API and tunnel DNS zones as retained Cloudflare resources. Personal stages reference
the production-owned zones.
@@ -0,0 +1,29 @@
CREATE TABLE "relay_device_authorizations" (
"device_code_hash" varchar(64) PRIMARY KEY,
"user_code" varchar(16) NOT NULL,
"client_id" varchar(191) NOT NULL,
"scope" text NOT NULL,
"code_challenge" varchar(128) NOT NULL,
"status" varchar(16) NOT NULL,
"user_id" varchar(255),
"callback_state" varchar(64),
"redirect_uri" text,
"authorization_code" text,
"device_name" text,
"device_platform" varchar(128),
"client_version" varchar(64),
"request_ip" varchar(64),
"request_location" varchar(191),
"poll_interval_seconds" integer NOT NULL,
"last_polled_at" varchar(64),
"expires_at" varchar(64) NOT NULL,
"created_at" varchar(64) NOT NULL,
"updated_at" varchar(64) NOT NULL
);
--> statement-breakpoint
CREATE UNIQUE INDEX "idx_relay_device_authorizations_user_code" ON "relay_device_authorizations" ("user_code");
--> statement-breakpoint
CREATE UNIQUE INDEX "idx_relay_device_authorizations_callback_state" ON "relay_device_authorizations" ("callback_state");
--> statement-breakpoint
CREATE INDEX "idx_relay_device_authorizations_expires_at" ON "relay_device_authorizations" ("expires_at");
File diff suppressed because it is too large. Load diff
+2
View File
@@ -18,6 +18,8 @@ export class RelayConfiguration extends Context.Service<
RelayConfiguration,
{
readonly relayIssuer: string;
/** Origin of the hosted web app that serves the device-authorization approval page. */
readonly appBaseUrl: string;
readonly apns: ApnsCredentials;
readonly clerkSecretKey: Redacted.Redacted<string>;
readonly clerkPublishableKey: string;
@@ -31,6 +31,7 @@ import * as ApnsClient from "./ApnsClient.ts";
const config = RelayConfiguration.RelayConfiguration.of({
relayIssuer: "https://relay.example.test",
appBaseUrl: "https://app.example.test",
apns: {
environment: "sandbox",
teamId: "team-id",
@@ -10,6 +10,7 @@ import * as ApnsDeliveryQueue from "./ApnsDeliveryQueue.ts";
const config: RelayConfiguration.RelayConfiguration["Service"] = {
relayIssuer: "https://relay.example.com",
appBaseUrl: "https://app.example.test",
apns: {
teamId: "team-1",
keyId: "key-1",
@@ -123,6 +123,7 @@ function makeDeliveryAttempts(
const config = RelayConfiguration.RelayConfiguration.of({
relayIssuer: "https://relay.example.test",
appBaseUrl: "https://app.example.test",
apns: {
environment: "sandbox",
teamId: "team-id",
@@ -0,0 +1,297 @@
import * as Context from "effect/Context";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Schema from "effect/Schema";
import { and, eq, gt, isNull, lt, ne, or } from "drizzle-orm";
import * as RelayDb from "../db.ts";
import { relayDeviceAuthorizations } from "../persistence/schema.ts";
export class DeviceAuthorizationPersistenceError extends Schema.TaggedErrorClass<DeviceAuthorizationPersistenceError>()(
"DeviceAuthorizationPersistenceError",
{
operation: Schema.Literals([
"create",
"find-by-user-code",
"find-by-device-code",
"begin-approval",
"complete-approval",
"deny",
"stamp-polled",
"take-approved",
"delete",
"prune-expired",
]),
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to persist device authorization state during '${this.operation}'`;
}
}
export type DeviceAuthorizationRecord = typeof relayDeviceAuthorizations.$inferSelect;
export class DeviceAuthorizations extends Context.Service<
DeviceAuthorizations,
{
readonly create: (input: {
readonly deviceCodeHash: string;
readonly userCode: string;
readonly clientId: string;
readonly scope: string;
readonly codeChallenge: string;
readonly deviceName: string | null;
readonly devicePlatform: string | null;
readonly clientVersion: string | null;
readonly requestIp: string | null;
readonly requestLocation: string | null;
readonly pollIntervalSeconds: number;
readonly expiresAt: DateTime.DateTime;
}) => Effect.Effect<void, DeviceAuthorizationPersistenceError>;
readonly findByUserCode: (
userCode: string,
) => Effect.Effect<DeviceAuthorizationRecord | null, DeviceAuthorizationPersistenceError>;
readonly findByDeviceCodeHash: (
deviceCodeHash: string,
) => Effect.Effect<DeviceAuthorizationRecord | null, DeviceAuthorizationPersistenceError>;
readonly beginApproval: (input: {
readonly userCode: string;
readonly callbackState: string;
readonly redirectUri: string;
readonly now: DateTime.DateTime;
}) => Effect.Effect<DeviceAuthorizationRecord | null, DeviceAuthorizationPersistenceError>;
readonly completeApproval: (input: {
readonly callbackState: string;
readonly authorizationCode: string;
readonly userId: string;
readonly now: DateTime.DateTime;
}) => Effect.Effect<DeviceAuthorizationRecord | null, DeviceAuthorizationPersistenceError>;
readonly deny: (input: {
readonly userCode: string;
readonly userId: string;
readonly now: DateTime.DateTime;
}) => Effect.Effect<DeviceAuthorizationRecord | null, DeviceAuthorizationPersistenceError>;
readonly stampPolled: (input: {
readonly deviceCodeHash: string;
readonly now: DateTime.DateTime;
}) => Effect.Effect<void, DeviceAuthorizationPersistenceError>;
readonly takeApproved: (
deviceCodeHash: string,
) => Effect.Effect<DeviceAuthorizationRecord | null, DeviceAuthorizationPersistenceError>;
readonly deleteByDeviceCodeHash: (
deviceCodeHash: string,
) => Effect.Effect<void, DeviceAuthorizationPersistenceError>;
readonly pruneExpired: Effect.Effect<void, DeviceAuthorizationPersistenceError>;
}
>()("t3code-relay/auth/DeviceAuthorizations") {}
const persistenceError =
(operation: DeviceAuthorizationPersistenceError["operation"]) => (cause: unknown) =>
new DeviceAuthorizationPersistenceError({ operation, cause });
const make = Effect.gen(function* () {
const db = yield* RelayDb.RelayDb;
const firstOrNull = (rows: ReadonlyArray<DeviceAuthorizationRecord>) => rows[0] ?? null;
const create: DeviceAuthorizations["Service"]["create"] = Effect.fn(
"relay.device_authorizations.create",
)(function* (input) {
const now = DateTime.formatIso(yield* DateTime.now);
yield* db
.insert(relayDeviceAuthorizations)
.values({
deviceCodeHash: input.deviceCodeHash,
userCode: input.userCode,
clientId: input.clientId,
scope: input.scope,
codeChallenge: input.codeChallenge,
status: "pending",
deviceName: input.deviceName,
devicePlatform: input.devicePlatform,
clientVersion: input.clientVersion,
requestIp: input.requestIp,
requestLocation: input.requestLocation,
pollIntervalSeconds: input.pollIntervalSeconds,
expiresAt: DateTime.formatIso(input.expiresAt),
createdAt: now,
updatedAt: now,
})
.pipe(Effect.mapError(persistenceError("create")));
});
const findByUserCode: DeviceAuthorizations["Service"]["findByUserCode"] = Effect.fn(
"relay.device_authorizations.find_by_user_code",
)(function* (userCode) {
return firstOrNull(
yield* db
.select()
.from(relayDeviceAuthorizations)
.where(eq(relayDeviceAuthorizations.userCode, userCode))
.limit(1)
.pipe(Effect.mapError(persistenceError("find-by-user-code"))),
);
});
const findByDeviceCodeHash: DeviceAuthorizations["Service"]["findByDeviceCodeHash"] = Effect.fn(
"relay.device_authorizations.find_by_device_code",
)(function* (deviceCodeHash) {
return firstOrNull(
yield* db
.select()
.from(relayDeviceAuthorizations)
.where(eq(relayDeviceAuthorizations.deviceCodeHash, deviceCodeHash))
.limit(1)
.pipe(Effect.mapError(persistenceError("find-by-device-code"))),
);
});
const beginApproval: DeviceAuthorizations["Service"]["beginApproval"] = Effect.fn(
"relay.device_authorizations.begin_approval",
)(function* (input) {
const now = DateTime.formatIso(input.now);
// Claims only rows without a callback state; repeated approvals must
// reuse the first issued state so an in-flight Clerk redirect stays valid.
return firstOrNull(
yield* db
.update(relayDeviceAuthorizations)
.set({
callbackState: input.callbackState,
redirectUri: input.redirectUri,
updatedAt: now,
})
.where(
and(
eq(relayDeviceAuthorizations.userCode, input.userCode),
eq(relayDeviceAuthorizations.status, "pending"),
gt(relayDeviceAuthorizations.expiresAt, now),
isNull(relayDeviceAuthorizations.callbackState),
),
)
.returning()
.pipe(Effect.mapError(persistenceError("begin-approval"))),
);
});
const completeApproval: DeviceAuthorizations["Service"]["completeApproval"] = Effect.fn(
"relay.device_authorizations.complete_approval",
)(function* (input) {
const now = DateTime.formatIso(input.now);
return firstOrNull(
yield* db
.update(relayDeviceAuthorizations)
.set({
status: "approved",
authorizationCode: input.authorizationCode,
userId: input.userId,
updatedAt: now,
})
.where(
and(
eq(relayDeviceAuthorizations.callbackState, input.callbackState),
eq(relayDeviceAuthorizations.status, "pending"),
gt(relayDeviceAuthorizations.expiresAt, now),
),
)
.returning()
.pipe(Effect.mapError(persistenceError("complete-approval"))),
);
});
const deny: DeviceAuthorizations["Service"]["deny"] = Effect.fn(
"relay.device_authorizations.deny",
)(function* (input) {
const now = DateTime.formatIso(input.now);
return firstOrNull(
yield* db
.update(relayDeviceAuthorizations)
.set({
status: "denied",
userId: input.userId,
updatedAt: now,
})
.where(
and(
eq(relayDeviceAuthorizations.userCode, input.userCode),
eq(relayDeviceAuthorizations.status, "pending"),
gt(relayDeviceAuthorizations.expiresAt, now),
),
)
.returning()
.pipe(Effect.mapError(persistenceError("deny"))),
);
});
const stampPolled: DeviceAuthorizations["Service"]["stampPolled"] = Effect.fn(
"relay.device_authorizations.stamp_polled",
)(function* (input) {
yield* db
.update(relayDeviceAuthorizations)
.set({ lastPolledAt: DateTime.formatIso(input.now) })
.where(eq(relayDeviceAuthorizations.deviceCodeHash, input.deviceCodeHash))
.pipe(Effect.mapError(persistenceError("stamp-polled")));
});
const takeApproved: DeviceAuthorizations["Service"]["takeApproved"] = Effect.fn(
"relay.device_authorizations.take_approved",
)(function* (deviceCodeHash) {
return firstOrNull(
yield* db
.delete(relayDeviceAuthorizations)
.where(
and(
eq(relayDeviceAuthorizations.deviceCodeHash, deviceCodeHash),
eq(relayDeviceAuthorizations.status, "approved"),
),
)
.returning()
.pipe(Effect.mapError(persistenceError("take-approved"))),
);
});
const deleteByDeviceCodeHash: DeviceAuthorizations["Service"]["deleteByDeviceCodeHash"] =
Effect.fn("relay.device_authorizations.delete")(function* (deviceCodeHash) {
yield* db
.delete(relayDeviceAuthorizations)
.where(eq(relayDeviceAuthorizations.deviceCodeHash, deviceCodeHash))
.pipe(Effect.mapError(persistenceError("delete")));
});
const pruneExpired: DeviceAuthorizations["Service"]["pruneExpired"] = Effect.gen(function* () {
const now = yield* DateTime.now;
const cutoff = DateTime.formatIso(now);
// Approved-but-unredeemed rows get a grace window so a completion near
// the expiry boundary can still be picked up by the next CLI poll.
const approvedCutoff = DateTime.formatIso(DateTime.subtract(now, { minutes: 10 }));
yield* Effect.annotateCurrentSpan({ "relay.device_authorization_prune.before": cutoff });
yield* db
.delete(relayDeviceAuthorizations)
.where(
or(
and(
lt(relayDeviceAuthorizations.expiresAt, cutoff),
ne(relayDeviceAuthorizations.status, "approved"),
),
lt(relayDeviceAuthorizations.expiresAt, approvedCutoff),
),
)
.pipe(Effect.mapError(persistenceError("prune-expired")));
}).pipe(Effect.withSpan("relay.device_authorizations.prune_expired"));
return DeviceAuthorizations.of({
create,
findByUserCode,
findByDeviceCodeHash,
beginApproval,
completeApproval,
deny,
stampPolled,
takeApproved,
deleteByDeviceCodeHash,
pruneExpired,
});
});
export const layer = Layer.effect(DeviceAuthorizations, make);
+1
View File
@@ -16,6 +16,7 @@ const keyPair = NodeCrypto.generateKeyPairSync("ed25519", {
const config = RelayConfiguration.RelayConfiguration.of({
relayIssuer: "https://relay.example.test/",
appBaseUrl: "https://app.example.test",
apns: {
environment: "sandbox",
teamId: "team-id",
@@ -63,6 +63,7 @@ function requestBodyText(request: HttpClientRequest.HttpClientRequest): string {
const settings = RelayConfiguration.RelayConfiguration.of({
relayIssuer: "https://relay.example.test",
appBaseUrl: "https://app.example.test",
apns: {
environment: "sandbox",
teamId: "team-id",
@@ -30,6 +30,7 @@ const environmentKeyPair = NodeCrypto.generateKeyPairSync("ed25519", {
});
const config = RelayConfiguration.RelayConfiguration.of({
relayIssuer: "https://relay.example.test",
appBaseUrl: "https://app.example.test",
apns: {
environment: "sandbox",
teamId: "team-id",
@@ -25,6 +25,7 @@ const keyPair = NodeCrypto.generateKeyPairSync("ed25519", {
});
const config = RelayConfiguration.RelayConfiguration.of({
relayIssuer: "https://relay.example.test",
appBaseUrl: "https://app.example.test",
apns: {
environment: "sandbox",
teamId: "team-id",
@@ -12,6 +12,7 @@ import * as ManagedEndpointProvider from "./ManagedEndpointProvider.ts";
const config = RelayConfiguration.RelayConfiguration.of({
relayIssuer: "https://relay.example.test",
appBaseUrl: "https://app.example.test",
apns: {
environment: "sandbox",
teamId: "team-id",
+1
View File
@@ -32,6 +32,7 @@ vi.mock("@clerk/backend", () => ({
const relaySettings: RelayConfiguration.RelayConfiguration["Service"] = {
relayIssuer: "https://relay.example.test",
appBaseUrl: "https://app.example.test",
apns: {
teamId: "apns-team",
keyId: "apns-key",
+285
View File
@@ -5,6 +5,7 @@ import * as Context from "effect/Context";
import * as DateTime from "effect/DateTime";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Encoding from "effect/Encoding";
import * as Layer from "effect/Layer";
import * as Record from "effect/Record";
import * as Redacted from "effect/Redacted";
@@ -34,6 +35,9 @@ import {
RelayMobileRegistrationScope,
RelayAuthInvalidError,
type RelayAuthInvalidReason,
RelayDeviceAuthorizationNotFoundError,
RelayDeviceTokenPollError,
type RelayDeviceTokenPollCode,
RelayEnvironmentAuth,
RelayEnvironmentConnectNotAuthorizedError,
RelayEnvironmentEndpointTimedOutError,
@@ -47,9 +51,11 @@ import {
type RelayDpopAccessTokenScope,
RelayInternalError,
} from "@t3tools/contracts/relay";
import { clerkFrontendApiUrlFromPublishableKey } from "@t3tools/shared/relayAuth";
import { normalizeRelayIssuer } from "@t3tools/shared/relayJwt";
import * as DeliveryAttempts from "../agentActivity/DeliveryAttempts.ts";
import * as DeviceAuthorizations from "../auth/DeviceAuthorizations.ts";
import * as AgentActivityRows from "../agentActivity/AgentActivityRows.ts";
import * as Devices from "../agentActivity/Devices.ts";
import * as DpopProofs from "../auth/DpopProofs.ts";
@@ -623,6 +629,284 @@ export const tokenApi = HttpApiBuilder.group(
}),
);
const RELAY_DEVICE_AUTHORIZATION_TTL = Duration.minutes(15);
const RELAY_DEVICE_POLL_INTERVAL_SECONDS = 5;
// Consonant-only alphabet: no accidental words, no ambiguous I/O/0/1.
const RELAY_DEVICE_USER_CODE_ALPHABET = "BCDFGHJKLMNPQRSTVWXZ";
const RELAY_DEVICE_USER_CODE_LENGTH = 8;
function normalizeDeviceUserCode(userCode: string): string {
return userCode.toUpperCase().replaceAll(/[^A-Z0-9]/gu, "");
}
function formatDeviceUserCode(userCode: string): string {
return userCode.length === RELAY_DEVICE_USER_CODE_LENGTH
? `${userCode.slice(0, 4)}-${userCode.slice(4)}`
: userCode;
}
function deviceUserCodeFromBytes(bytes: Uint8Array): string {
let code = "";
for (let index = 0; index < RELAY_DEVICE_USER_CODE_LENGTH; index++) {
code +=
RELAY_DEVICE_USER_CODE_ALPHABET[(bytes[index] ?? 0) % RELAY_DEVICE_USER_CODE_ALPHABET.length];
}
return code;
}
function trimTrailingSlash(value: string): string {
return value.replace(/\/+$/u, "");
}
function hashDeviceCode(crypto: Crypto.Crypto, deviceCode: string) {
return crypto.digest("SHA-256", new TextEncoder().encode(deviceCode)).pipe(
Effect.map(Encoding.encodeHex),
Effect.catch(() => relayInternalErrorResponse("internal_error")),
);
}
function deviceAuthorizationDetails(record: DeviceAuthorizations.DeviceAuthorizationRecord) {
return {
userCode: formatDeviceUserCode(record.userCode),
status: record.status,
scope: record.scope,
deviceName: record.deviceName,
devicePlatform: record.devicePlatform,
clientVersion: record.clientVersion,
requestIp: record.requestIp,
requestLocation: record.requestLocation,
requestedAt: record.createdAt,
expiresAt: record.expiresAt,
};
}
const relayDeviceTokenPollError = Effect.fnUntraced(function* (code: RelayDeviceTokenPollCode) {
const traceId = yield* currentTraceId;
yield* Effect.annotateCurrentSpan({ "relay.device_authorization.poll_result": code });
return yield* new RelayDeviceTokenPollError({ code, traceId });
});
const relayDeviceAuthorizationNotFoundError = Effect.fnUntraced(function* () {
const traceId = yield* currentTraceId;
return yield* new RelayDeviceAuthorizationNotFoundError({
code: "device_authorization_not_found",
traceId,
});
});
export const deviceApi = HttpApiBuilder.group(
RelayApi,
"device",
Effect.fnUntraced(function* (handlers) {
const config = yield* RelayConfiguration.RelayConfiguration;
const crypto = yield* Crypto.Crypto;
const deviceAuthorizations = yield* DeviceAuthorizations.DeviceAuthorizations;
const appBaseUrl = trimTrailingSlash(config.appBaseUrl);
return handlers
.handle(
"authorizeDevice",
Effect.fn("relay.api.device.authorizeDevice")(function* (args) {
yield* appendRelayCredentialResponseHeaders;
const request = yield* HttpServerRequest.HttpServerRequest;
yield* Effect.annotateCurrentSpan({
"relay.oauth.client_id": args.payload.client_id,
});
// A fresh code pair is generated per attempt so a user-code
// collision on the unique index retries instead of failing the
// login request.
const issueAuthorization = Effect.gen(function* () {
const randomBytes = yield* crypto
.randomBytes(32 + RELAY_DEVICE_USER_CODE_LENGTH)
.pipe(Effect.catch(() => relayInternalErrorResponse("internal_error")));
const deviceCode = Encoding.encodeBase64Url(randomBytes.slice(0, 32));
const deviceCodeHash = yield* hashDeviceCode(crypto, deviceCode);
const userCode = deviceUserCodeFromBytes(randomBytes.slice(32));
const now = yield* DateTime.now;
const expiresAt = DateTime.addDuration(now, RELAY_DEVICE_AUTHORIZATION_TTL);
yield* deviceAuthorizations.create({
deviceCodeHash,
userCode,
clientId: args.payload.client_id,
scope: args.payload.scope,
codeChallenge: args.payload.code_challenge,
deviceName: args.payload.device_name ?? null,
devicePlatform: args.payload.device_platform ?? null,
clientVersion: args.payload.client_version ?? null,
requestIp: request.headers["cf-connecting-ip"] ?? null,
requestLocation: request.headers["cf-ipcountry"] ?? null,
pollIntervalSeconds: RELAY_DEVICE_POLL_INTERVAL_SECONDS,
expiresAt,
});
return { deviceCode, userCode };
});
const issued = yield* issueAuthorization.pipe(
Effect.retry({
times: 2,
while: (error) => error._tag === "DeviceAuthorizationPersistenceError",
}),
);
const formattedUserCode = formatDeviceUserCode(issued.userCode);
return {
device_code: issued.deviceCode,
user_code: formattedUserCode,
verification_uri: `${appBaseUrl}/oauth/device`,
verification_uri_complete: `${appBaseUrl}/oauth/device?user_code=${formattedUserCode}`,
expires_in: Duration.toSeconds(RELAY_DEVICE_AUTHORIZATION_TTL),
interval: RELAY_DEVICE_POLL_INTERVAL_SECONDS,
};
}, mapRelayCommonApiErrors("not_authorized")),
)
.handle(
"redeemDeviceCode",
Effect.fn("relay.api.device.redeemDeviceCode")(function* (args) {
yield* appendRelayCredentialResponseHeaders;
const deviceCodeHash = yield* hashDeviceCode(crypto, args.payload.device_code);
const record = yield* deviceAuthorizations.findByDeviceCodeHash(deviceCodeHash);
if (record === null || record.clientId !== args.payload.client_id) {
return yield* relayDeviceTokenPollError("expired_token");
}
const now = yield* DateTime.now;
// Approved rows stay redeemable past expiry (until pruning) so a
// completion near the deadline is not lost to the next poll.
if (record.status === "approved") {
const granted = yield* deviceAuthorizations.takeApproved(deviceCodeHash);
if (granted?.authorizationCode && granted.redirectUri) {
return {
authorization_code: granted.authorizationCode,
redirect_uri: granted.redirectUri,
};
}
return yield* relayDeviceTokenPollError("expired_token");
}
if (record.status === "denied") {
yield* deviceAuthorizations.deleteByDeviceCodeHash(deviceCodeHash);
return yield* relayDeviceTokenPollError("access_denied");
}
if (record.expiresAt <= DateTime.formatIso(now)) {
yield* deviceAuthorizations.deleteByDeviceCodeHash(deviceCodeHash);
return yield* relayDeviceTokenPollError("expired_token");
}
const polledTooFast =
record.lastPolledAt !== null &&
Date.parse(record.lastPolledAt) + (record.pollIntervalSeconds - 1) * 1_000 >
now.epochMilliseconds;
yield* deviceAuthorizations.stampPolled({ deviceCodeHash, now });
return yield* relayDeviceTokenPollError(
polledTooFast ? "slow_down" : "authorization_pending",
);
}, mapRelayCommonApiErrors("not_authorized")),
);
}),
);
export const deviceApprovalApi = HttpApiBuilder.group(
RelayApi,
"deviceApproval",
Effect.fnUntraced(function* (handlers) {
const config = yield* RelayConfiguration.RelayConfiguration;
const crypto = yield* Crypto.Crypto;
const deviceAuthorizations = yield* DeviceAuthorizations.DeviceAuthorizations;
const appBaseUrl = trimTrailingSlash(config.appBaseUrl);
return handlers
.handle(
"getDeviceAuthorization",
Effect.fn("relay.api.device_approval.getDeviceAuthorization")(function* (args) {
yield* appendRelayCredentialResponseHeaders;
const record = yield* deviceAuthorizations.findByUserCode(
normalizeDeviceUserCode(args.params.userCode),
);
const now = DateTime.formatIso(yield* DateTime.now);
if (record === null || record.expiresAt <= now) {
return yield* relayDeviceAuthorizationNotFoundError();
}
return deviceAuthorizationDetails(record);
}, mapRelayCommonApiErrors("not_authorized")),
)
.handle(
"approveDeviceAuthorization",
Effect.fn("relay.api.device_approval.approveDeviceAuthorization")(function* (args) {
yield* appendRelayCredentialResponseHeaders;
const { userId } = yield* RelayClientPrincipal;
yield* Effect.annotateCurrentSpan({ "user.id": userId });
const userCode = normalizeDeviceUserCode(args.params.userCode);
const requestedState = yield* crypto.randomUUIDv4.pipe(
Effect.catch(() => relayInternalErrorResponse("internal_error")),
);
const now = yield* DateTime.now;
// beginApproval only claims rows without a callback state. A reload
// or second tab reuses the already-issued state so the first Clerk
// redirect still completes.
const claimed = yield* deviceAuthorizations.beginApproval({
userCode,
callbackState: requestedState,
redirectUri: `${appBaseUrl}/oauth/device/callback`,
now,
});
const record = claimed ?? (yield* deviceAuthorizations.findByUserCode(userCode));
if (
record === null ||
record.status !== "pending" ||
record.expiresAt <= DateTime.formatIso(now) ||
record.callbackState === null ||
record.redirectUri === null
) {
return yield* relayDeviceAuthorizationNotFoundError();
}
const clerkFrontendApiUrl = yield* Effect.try({
try: () => clerkFrontendApiUrlFromPublishableKey(config.clerkPublishableKey),
catch: (cause) => new ClerkTokenVerificationFailed({ cause }),
}).pipe(Effect.catch(() => relayInternalErrorResponse("internal_error")));
const authorizationUrl = new URL(`${clerkFrontendApiUrl}/oauth/authorize`);
authorizationUrl.searchParams.set("client_id", record.clientId);
authorizationUrl.searchParams.set("redirect_uri", record.redirectUri);
authorizationUrl.searchParams.set("response_type", "code");
authorizationUrl.searchParams.set("scope", record.scope);
authorizationUrl.searchParams.set("state", record.callbackState);
authorizationUrl.searchParams.set("code_challenge", record.codeChallenge);
authorizationUrl.searchParams.set("code_challenge_method", "S256");
return { authorizationUrl: authorizationUrl.toString() };
}, mapRelayCommonApiErrors("not_authorized")),
)
.handle(
"completeDeviceAuthorization",
Effect.fn("relay.api.device_approval.completeDeviceAuthorization")(function* (args) {
yield* appendRelayCredentialResponseHeaders;
const { userId } = yield* RelayClientPrincipal;
yield* Effect.annotateCurrentSpan({ "user.id": userId });
const now = yield* DateTime.now;
const record = yield* deviceAuthorizations.completeApproval({
callbackState: args.payload.state,
authorizationCode: args.payload.code,
userId,
now,
});
if (record === null) {
return yield* relayDeviceAuthorizationNotFoundError();
}
return { ok: true };
}, mapRelayCommonApiErrors("not_authorized")),
)
.handle(
"denyDeviceAuthorization",
Effect.fn("relay.api.device_approval.denyDeviceAuthorization")(function* (args) {
yield* appendRelayCredentialResponseHeaders;
const { userId } = yield* RelayClientPrincipal;
yield* Effect.annotateCurrentSpan({ "user.id": userId });
const now = yield* DateTime.now;
const record = yield* deviceAuthorizations.deny({
userCode: normalizeDeviceUserCode(args.params.userCode),
userId,
now,
});
if (record === null) {
return yield* relayDeviceAuthorizationNotFoundError();
}
return { ok: true };
}, mapRelayCommonApiErrors("not_authorized")),
);
}),
);
export const dpopClientApi = HttpApiBuilder.group(
RelayApi,
"dpopClient",
@@ -893,6 +1177,7 @@ const RelayCommonPersistenceError = Schema.Union([
EnvironmentCredentials.EnvironmentCredentialAuthenticatePersistenceError,
EnvironmentCredentials.EnvironmentCredentialRevokePersistenceError,
DpopProofs.DpopProofReplayPersistenceError,
DeviceAuthorizations.DeviceAuthorizationPersistenceError,
LiveActivities.LiveActivityTargetListPersistenceError,
AgentActivityRows.AgentActivityRowUpsertPersistenceError,
AgentActivityRows.AgentActivityRowDeletePersistenceError,
+31
View File
@@ -168,6 +168,37 @@ export const relayDeliveryAttempts = pgTable(
],
);
export const relayDeviceAuthorizations = pgTable(
"relay_device_authorizations",
{
deviceCodeHash: varchar("device_code_hash", { length: 64 }).primaryKey(),
userCode: varchar("user_code", { length: 16 }).notNull(),
clientId: varchar("client_id", { length: 191 }).notNull(),
scope: text("scope").notNull(),
codeChallenge: varchar("code_challenge", { length: 128 }).notNull(),
status: varchar("status", { length: 16 }).notNull().$type<"pending" | "approved" | "denied">(),
userId: varchar("user_id", { length: 255 }),
callbackState: varchar("callback_state", { length: 64 }),
redirectUri: text("redirect_uri"),
authorizationCode: text("authorization_code"),
deviceName: text("device_name"),
devicePlatform: varchar("device_platform", { length: 128 }),
clientVersion: varchar("client_version", { length: 64 }),
requestIp: varchar("request_ip", { length: 64 }),
requestLocation: varchar("request_location", { length: 191 }),
pollIntervalSeconds: integer("poll_interval_seconds").notNull(),
lastPolledAt: varchar("last_polled_at", { length: 64 }),
expiresAt: varchar("expires_at", { length: 64 }).notNull(),
createdAt: varchar("created_at", { length: 64 }).notNull(),
updatedAt: varchar("updated_at", { length: 64 }).notNull(),
},
(table) => [
uniqueIndex("idx_relay_device_authorizations_user_code").on(table.userCode),
uniqueIndex("idx_relay_device_authorizations_callback_state").on(table.callbackState),
index("idx_relay_device_authorizations_expires_at").on(table.expiresAt),
],
);
export const relayDpopProofs = pgTable(
"relay_dpop_proofs",
{
+35 -6
View File
@@ -4,6 +4,7 @@ import * as Drizzle from "alchemy/Drizzle";
import * as Config from "effect/Config";
import * as Crypto from "effect/Crypto";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
import * as Layer from "effect/Layer";
import * as Stream from "effect/Stream";
import * as Etag from "effect/unstable/http/Etag";
@@ -16,6 +17,8 @@ import { RelayApi } from "@t3tools/contracts/relay";
import {
clientApi,
deviceApi,
deviceApprovalApi,
dpopClientApi,
healthApi,
metadataApi,
@@ -36,6 +39,7 @@ import { makeRelayTraceLayer, RelayObservability } from "./observability.ts";
import * as DeliveryAttempts from "./agentActivity/DeliveryAttempts.ts";
import * as AgentActivityRows from "./agentActivity/AgentActivityRows.ts";
import * as Devices from "./agentActivity/Devices.ts";
import * as DeviceAuthorizations from "./auth/DeviceAuthorizations.ts";
import * as DpopProofs from "./auth/DpopProofs.ts";
import * as RelayTokens from "./auth/RelayTokens.ts";
import * as EnvironmentCredentials from "./environments/EnvironmentCredentials.ts";
@@ -79,6 +83,8 @@ const relayApiLayer = Layer.mergeAll(
mobileApi,
clientApi,
tokenApi,
deviceApi,
deviceApprovalApi,
dpopClientApi,
serverApi,
);
@@ -135,6 +141,11 @@ export default class Api extends Cloudflare.Worker<Api>()(
const clerkSecretKey = yield* Config.redacted("CLERK_SECRET_KEY");
const clerkPublishableKey = yield* Config.string("CLERK_PUBLISHABLE_KEY");
const clerkJwtAudience = yield* Config.string("CLERK_JWT_AUDIENCE");
// The default only fits prod: a stage relay needs a web app build that
// targets that same stage, so non-prod deploys must set the URL explicitly.
const appBaseUrl = yield* stage === "prod"
? Config.string("T3CODE_APP_BASE_URL").pipe(Config.withDefault("https://app.t3.codes"))
: Config.string("T3CODE_APP_BASE_URL");
const cloudMintPrivateKey = yield* cloudMintKeyPair.privateKey;
const cloudMintPublicKey = yield* cloudMintKeyPair.publicKey;
@@ -155,6 +166,7 @@ export default class Api extends Cloudflare.Worker<Api>()(
const loadSettings = Effect.gen(function* () {
return RelayConfiguration.RelayConfiguration.of({
relayIssuer: relayPublicOrigin,
appBaseUrl,
apns: {
environment,
teamId: apnsTeamId,
@@ -194,7 +206,7 @@ export default class Api extends Cloudflare.Worker<Api>()(
alchemyRuntimeContext,
),
),
Layer.provideMerge(DpopProofs.layer),
Layer.provideMerge(Layer.mergeAll(DpopProofs.layer, DeviceAuthorizations.layer)),
Layer.provideMerge(ApnsDeliveries.layer),
Layer.provideMerge(ApnsClient.layer),
Layer.provideMerge(
@@ -239,12 +251,29 @@ export default class Api extends Cloudflare.Worker<Api>()(
),
);
// Each prune runs to completion even when the other fails; a failure in
// one must not leave the other's expired rows behind for a whole cycle.
yield* Cloudflare.cron("*/5 * * * *").subscribe(() =>
DpopProofs.DpopProofReplay.pipe(
Effect.flatMap((dpopProofs) => dpopProofs.pruneExpired),
Effect.withSpan("relay.cron.prune_expired_dpop_proofs"),
Effect.provide(runtimeLayer),
),
Effect.gen(function* () {
const dpopPruneExit = yield* Effect.exit(
DpopProofs.DpopProofReplay.pipe(
Effect.flatMap((dpopProofs) => dpopProofs.pruneExpired),
Effect.withSpan("relay.cron.prune_expired_dpop_proofs"),
),
);
const devicePruneExit = yield* Effect.exit(
DeviceAuthorizations.DeviceAuthorizations.pipe(
Effect.flatMap((deviceAuthorizations) => deviceAuthorizations.pruneExpired),
Effect.withSpan("relay.cron.prune_expired_device_authorizations"),
),
);
if (Exit.isFailure(dpopPruneExit)) {
return yield* Effect.failCause(dpopPruneExit.cause);
}
if (Exit.isFailure(devicePruneExit)) {
return yield* Effect.failCause(devicePruneExit.cause);
}
}).pipe(Effect.provide(runtimeLayer)),
);
const fetch = Layer.merge(
@@ -70,6 +70,15 @@ function relayProtectedError(error: RelayProtectedError): ConnectionAttemptError
detail: error.message,
traceId: error.traceId,
});
case "RelayDeviceTokenPollError":
case "RelayDeviceAuthorizationNotFoundError":
// Device-authorization errors never occur while connecting to an
// environment; map them defensively as configuration problems.
return new ConnectionBlockedError({
reason: "configuration",
detail: error.message,
traceId: error.traceId,
});
}
}
@@ -132,6 +141,15 @@ export function mapRemoteEnvironmentError(
detail: "The environment rejected the authentication request.",
traceId: error.traceId,
});
case "EnvironmentResourceNotFoundError":
// Not expected during connection authorization, but the shared request
// error type now includes it (used by resource fetches like the thread
// snapshot). Treat it as a configuration issue with the endpoint.
return new ConnectionBlockedError({
reason: "configuration",
detail: "The environment endpoint could not be found.",
traceId: error.traceId,
});
case "RemoteEnvironmentAuthTimeoutError":
return new ConnectionTransientError({
reason: "timeout",
@@ -84,6 +84,10 @@ function relayClient(
registerDevice: () => unsupported("registerDevice"),
unregisterDevice: () => unsupported("unregisterDevice"),
registerLiveActivity: () => unsupported("registerLiveActivity"),
getDeviceAuthorization: () => unsupported("getDeviceAuthorization"),
approveDeviceAuthorization: () => unsupported("approveDeviceAuthorization"),
completeDeviceAuthorization: () => unsupported("completeDeviceAuthorization"),
denyDeviceAuthorization: () => unsupported("denyDeviceAuthorization"),
resetTokenCache: Effect.void,
});
}
@@ -1,7 +1,7 @@
import {
type EnvironmentId,
type OrchestrationThread,
type OrchestrationShellSnapshot,
type OrchestrationThreadDetailSnapshot,
type ThreadId,
} from "@t3tools/contracts";
import * as Context from "effect/Context";
@@ -60,10 +60,13 @@ export class EnvironmentCacheStore extends Context.Service<
readonly loadThread: (
environmentId: EnvironmentId,
threadId: ThreadId,
) => Effect.Effect<Option.Option<OrchestrationThread>, ConnectionPersistenceError>;
) => Effect.Effect<
Option.Option<OrchestrationThreadDetailSnapshot>,
ConnectionPersistenceError
>;
readonly saveThread: (
environmentId: EnvironmentId,
thread: OrchestrationThread,
snapshot: OrchestrationThreadDetailSnapshot,
) => Effect.Effect<void, ConnectionPersistenceError>;
readonly removeThread: (
environmentId: EnvironmentId,
@@ -112,6 +112,10 @@ const makeHarness = Effect.fn("RelayDiscoveryTest.makeHarness")(function* () {
registerDevice: () => Effect.die("unused"),
unregisterDevice: () => Effect.die("unused"),
registerLiveActivity: () => Effect.die("unused"),
getDeviceAuthorization: () => Effect.die("unused"),
approveDeviceAuthorization: () => Effect.die("unused"),
completeDeviceAuthorization: () => Effect.die("unused"),
denyDeviceAuthorization: () => Effect.die("unused"),
resetTokenCache: Effect.void,
} satisfies ManagedRelay.ManagedRelayClient["Service"]);
const connectivity = Connectivity.Connectivity.of({
@@ -272,6 +276,10 @@ describe("RelayEnvironmentDiscovery", () => {
registerDevice: () => Effect.die("unused"),
unregisterDevice: () => Effect.die("unused"),
registerLiveActivity: () => Effect.die("unused"),
getDeviceAuthorization: () => Effect.die("unused"),
approveDeviceAuthorization: () => Effect.die("unused"),
completeDeviceAuthorization: () => Effect.die("unused"),
denyDeviceAuthorization: () => Effect.die("unused"),
resetTokenCache: Effect.void,
} satisfies ManagedRelay.ManagedRelayClient["Service"]);
const layer = RelayEnvironmentDiscovery.layer.pipe(
@@ -4,6 +4,9 @@ import {
type RelayClientEnvironmentRecord,
type RelayClientDeviceRecord,
RelayConnectEnvironmentEndpoint,
type RelayDeviceApprovalResponse,
type RelayDeviceAuthorizationDetails,
type RelayDeviceCompletionRequest,
type RelayDeviceRegistrationRequest,
RelayDpopAccessTokenScope,
RelayDpopTokenExchangeGrantType,
@@ -92,6 +95,10 @@ export const ManagedRelayRequestAction = Schema.Literals([
"register relay mobile device",
"unregister relay mobile device",
"register relay live activity",
"get relay device authorization",
"approve relay device authorization",
"complete relay device authorization",
"deny relay device authorization",
]);
export type ManagedRelayRequestAction = typeof ManagedRelayRequestAction.Type;
@@ -107,6 +114,10 @@ export const ManagedRelayRequestActivity = Schema.Literals([
"Relay mobile device registration",
"Relay mobile device unregistration",
"Relay Live Activity registration",
"Relay device authorization lookup",
"Relay device authorization approval",
"Relay device authorization completion",
"Relay device authorization denial",
]);
export type ManagedRelayRequestActivity = typeof ManagedRelayRequestActivity.Type;
@@ -286,6 +297,22 @@ export class ManagedRelayClient extends Context.Service<
readonly clerkToken: string;
readonly payload: RelayLiveActivityRegistrationRequest;
}) => Effect.Effect<RelayOkResponse, ManagedRelayClientError>;
readonly getDeviceAuthorization: (input: {
readonly clerkToken: string;
readonly userCode: string;
}) => Effect.Effect<RelayDeviceAuthorizationDetails, ManagedRelayClientError>;
readonly approveDeviceAuthorization: (input: {
readonly clerkToken: string;
readonly userCode: string;
}) => Effect.Effect<RelayDeviceApprovalResponse, ManagedRelayClientError>;
readonly completeDeviceAuthorization: (input: {
readonly clerkToken: string;
readonly payload: RelayDeviceCompletionRequest;
}) => Effect.Effect<RelayOkResponse, ManagedRelayClientError>;
readonly denyDeviceAuthorization: (input: {
readonly clerkToken: string;
readonly userCode: string;
}) => Effect.Effect<RelayOkResponse, ManagedRelayClientError>;
readonly resetTokenCache: Effect.Effect<void>;
}
>()("@t3tools/client-runtime/relay/managedRelay/ManagedRelayClient") {}
@@ -399,6 +426,14 @@ function disabledManagedRelayClient(relayUrl: string): ManagedRelayClient["Servi
registerDevice: unavailable("clientRuntime.managedRelay.registerDevice"),
unregisterDevice: unavailable("clientRuntime.managedRelay.unregisterDevice"),
registerLiveActivity: unavailable("clientRuntime.managedRelay.registerLiveActivity"),
getDeviceAuthorization: unavailable("clientRuntime.managedRelay.getDeviceAuthorization"),
approveDeviceAuthorization: unavailable(
"clientRuntime.managedRelay.approveDeviceAuthorization",
),
completeDeviceAuthorization: unavailable(
"clientRuntime.managedRelay.completeDeviceAuthorization",
),
denyDeviceAuthorization: unavailable("clientRuntime.managedRelay.denyDeviceAuthorization"),
resetTokenCache: Effect.void.pipe(
Effect.withSpan("clientRuntime.managedRelay.resetTokenCache"),
),
@@ -867,6 +902,66 @@ export const make = Effect.fn("ManagedRelayClient.make")(function* (
Effect.withSpan("clientRuntime.managedRelay.registerLiveActivity"),
withRelayClientTracing,
),
getDeviceAuthorization: Effect.fnUntraced(
function* (input) {
return yield* client.deviceApproval
.getDeviceAuthorization({
headers: bearerHeaders(input.clerkToken),
params: { userCode: input.userCode },
})
.pipe(
Effect.mapError(relayRequestError("get relay device authorization")),
timeoutRelayRequest("Relay device authorization lookup"),
);
},
Effect.withSpan("clientRuntime.managedRelay.getDeviceAuthorization"),
withRelayClientTracing,
),
approveDeviceAuthorization: Effect.fnUntraced(
function* (input) {
return yield* client.deviceApproval
.approveDeviceAuthorization({
headers: bearerHeaders(input.clerkToken),
params: { userCode: input.userCode },
})
.pipe(
Effect.mapError(relayRequestError("approve relay device authorization")),
timeoutRelayRequest("Relay device authorization approval"),
);
},
Effect.withSpan("clientRuntime.managedRelay.approveDeviceAuthorization"),
withRelayClientTracing,
),
completeDeviceAuthorization: Effect.fnUntraced(
function* (input) {
return yield* client.deviceApproval
.completeDeviceAuthorization({
headers: bearerHeaders(input.clerkToken),
payload: input.payload,
})
.pipe(
Effect.mapError(relayRequestError("complete relay device authorization")),
timeoutRelayRequest("Relay device authorization completion"),
);
},
Effect.withSpan("clientRuntime.managedRelay.completeDeviceAuthorization"),
withRelayClientTracing,
),
denyDeviceAuthorization: Effect.fnUntraced(
function* (input) {
return yield* client.deviceApproval
.denyDeviceAuthorization({
headers: bearerHeaders(input.clerkToken),
params: { userCode: input.userCode },
})
.pipe(
Effect.mapError(relayRequestError("deny relay device authorization")),
timeoutRelayRequest("Relay device authorization denial"),
);
},
Effect.withSpan("clientRuntime.managedRelay.denyDeviceAuthorization"),
withRelayClientTracing,
),
resetTokenCache: SynchronizedRef.set(cachedTokens, []).pipe(
Effect.andThen(options.accessTokenStore ? options.accessTokenStore.clear : Effect.void),
Effect.withSpan("clientRuntime.managedRelay.resetTokenCache"),
@@ -83,6 +83,10 @@ function createManager(
registerDevice: () => Effect.die("unused"),
unregisterDevice: () => Effect.die("unused"),
registerLiveActivity: () => Effect.die("unused"),
getDeviceAuthorization: () => Effect.die("unused"),
approveDeviceAuthorization: () => Effect.die("unused"),
completeDeviceAuthorization: () => Effect.die("unused"),
denyDeviceAuthorization: () => Effect.die("unused"),
resetTokenCache: Effect.void,
...overrides,
});
+2
View File
@@ -5,6 +5,7 @@ import {
type EnvironmentInternalError,
type EnvironmentOperationForbiddenError,
type EnvironmentRequestInvalidError,
type EnvironmentResourceNotFoundError,
type EnvironmentScopeRequiredError,
} from "@t3tools/contracts";
import { httpHeaderRedactionLayer } from "@t3tools/shared/httpObservability";
@@ -70,6 +71,7 @@ export type RemoteEnvironmentRequestError =
| EnvironmentAuthInvalidError
| EnvironmentScopeRequiredError
| EnvironmentOperationForbiddenError
| EnvironmentResourceNotFoundError
| EnvironmentInternalError
| RemoteEnvironmentAuthFetchError
| RemoteEnvironmentAuthInvalidJsonError
@@ -0,0 +1,73 @@
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
import { FetchHttpClient, type HttpMethod } from "effect/unstable/http";
import type { PreparedHttpAuthorization } from "../connection/model.ts";
import type { ManagedRelayDpopSigner } from "../relay/managedRelay.ts";
import { RemoteEnvironmentAuthFetchError } from "../rpc/http.ts";
export interface EnvironmentHttpAuthHeaders {
readonly authorization?: string;
readonly dpop?: string;
}
/**
* Primary/local environments with no bearer or DPoP credential authenticate the
* browser via a session cookie. A cross-origin `fetch` does not send cookies by
* default, so those requests must opt into credentialed mode; bearer/DPoP
* connections carry their credential in a header and need no cookies. Applied
* per-request via `FetchHttpClient.RequestInit`, which the fetch client reads
* from the fiber context at request time.
*/
export const withEnvironmentCredentials = <A, E, R>(
authorization: PreparedHttpAuthorization | null,
request: Effect.Effect<A, E, R>,
): Effect.Effect<A, E, R> =>
authorization === null
? request.pipe(Effect.provideService(FetchHttpClient.RequestInit, { credentials: "include" }))
: request;
/**
* Build the authorization headers for an authenticated environment HTTP
* request, matching the credential the connection was prepared with:
* - primary/local connections carry no credential,
* - bearer connections send a static `Bearer` token,
* - relay connections send a `DPoP` access token with a freshly signed proof
* bound to this request's method and URL.
*
* The DPoP signer is passed in (not resolved from context) and is only required
* for relay/DPoP connections, so bearer/primary connections work even when no
* signer is available.
*/
export const buildEnvironmentAuthHeaders = (
authorization: PreparedHttpAuthorization | null,
method: HttpMethod.HttpMethod,
url: string,
signer: Option.Option<ManagedRelayDpopSigner["Service"]>,
): Effect.Effect<EnvironmentHttpAuthHeaders, RemoteEnvironmentAuthFetchError> =>
Effect.gen(function* () {
if (authorization === null) {
return {};
}
if (authorization._tag === "Bearer") {
return { authorization: `Bearer ${authorization.token}` };
}
if (Option.isNone(signer)) {
return yield* new RemoteEnvironmentAuthFetchError({
message: "No DPoP signer is available to authorize the environment request.",
cause: authorization._tag,
});
}
const proof = yield* signer.value
.createProof({ method, url, accessToken: authorization.accessToken })
.pipe(
Effect.mapError(
(cause) =>
new RemoteEnvironmentAuthFetchError({
message: "Could not create the environment request authorization proof.",
cause,
}),
),
);
return { authorization: `DPoP ${authorization.accessToken}`, dpop: proof };
});
@@ -20,7 +20,7 @@ import * as EnvironmentSupervisor from "../connection/supervisor.ts";
import * as Persistence from "../platform/persistence.ts";
import * as RpcSession from "../rpc/session.ts";
import type { WsRpcProtocolClient } from "../rpc/protocol.ts";
import { makeEnvironmentShellState } from "./shell.ts";
import { makeEnvironmentShellState, ShellSnapshotLoader } from "./shell.ts";
const TARGET = new PrimaryConnectionTarget({
environmentId: EnvironmentId.make("environment-1"),
@@ -29,6 +29,15 @@ const TARGET = new PrimaryConnectionTarget({
wsBaseUrl: "wss://environment.example.test",
});
const PREPARED: PreparedConnection = {
environmentId: TARGET.environmentId,
label: TARGET.label,
httpBaseUrl: TARGET.httpBaseUrl,
socketUrl: TARGET.wsBaseUrl,
httpAuthorization: null,
target: TARGET,
};
const LIVE_SHELL_SNAPSHOT: OrchestrationShellSnapshot = {
snapshotSequence: 1,
projects: [],
@@ -61,7 +70,7 @@ describe("environment shell synchronization", () => {
target: TARGET,
state: supervisorState,
session: activeSession,
prepared: yield* SubscriptionRef.make(Option.none<PreparedConnection>()),
prepared: yield* SubscriptionRef.make(Option.some(PREPARED)),
connect: Effect.void,
disconnect: Effect.void,
retryNow: Effect.void,
@@ -74,9 +83,15 @@ describe("environment shell synchronization", () => {
removeThread: () => Effect.void,
clear: () => Effect.void,
});
// Cold cache with no HTTP snapshot available → falls back to the
// socket-embedded snapshot.
const snapshotLoader = ShellSnapshotLoader.of({
load: () => Effect.succeed(Option.none()),
});
const shellState = yield* makeEnvironmentShellState().pipe(
Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
Effect.provideService(Persistence.EnvironmentCacheStore, cache),
Effect.provideService(ShellSnapshotLoader, snapshotLoader),
);
yield* SubscriptionRef.set(supervisorState, {
@@ -117,4 +132,65 @@ describe("environment shell synchronization", () => {
expect(Option.getOrThrow(state.snapshot)).toEqual(LIVE_SHELL_SNAPSHOT);
}),
);
it.effect("resumes a warm shell cache via afterSequence without an HTTP fetch", () =>
Effect.gen(function* () {
const cachedSnapshot: OrchestrationShellSnapshot = {
snapshotSequence: 5,
projects: [],
threads: [],
updatedAt: "2026-06-06T00:00:00.000Z",
};
const events = yield* Queue.unbounded<OrchestrationShellStreamItem>();
const capturedAfterSequence = yield* SubscriptionRef.make<number | undefined>(undefined);
const loaderCalls = yield* SubscriptionRef.make(0);
const client = {
[ORCHESTRATION_WS_METHODS.subscribeShell]: (input: { readonly afterSequence?: number }) =>
Stream.unwrap(
SubscriptionRef.set(capturedAfterSequence, input.afterSequence).pipe(
Effect.as(Stream.fromQueue(events)),
),
),
} as unknown as WsRpcProtocolClient;
const supervisorState = yield* SubscriptionRef.make(AVAILABLE_CONNECTION_STATE);
const activeSession = yield* SubscriptionRef.make<Option.Option<RpcSession.RpcSession>>(
Option.some(session(client)),
);
const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
target: TARGET,
state: supervisorState,
session: activeSession,
prepared: yield* SubscriptionRef.make(Option.some(PREPARED)),
connect: Effect.void,
disconnect: Effect.void,
retryNow: Effect.void,
} satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]);
const cache = Persistence.EnvironmentCacheStore.of({
loadShell: () => Effect.succeed(Option.some(cachedSnapshot)),
saveShell: () => Effect.void,
loadThread: () => Effect.succeed(Option.none()),
saveThread: () => Effect.void,
removeThread: () => Effect.void,
clear: () => Effect.void,
});
const snapshotLoader = ShellSnapshotLoader.of({
load: () =>
SubscriptionRef.update(loaderCalls, (count) => count + 1).pipe(Effect.as(Option.none())),
});
yield* makeEnvironmentShellState().pipe(
Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
Effect.provideService(Persistence.EnvironmentCacheStore, cache),
Effect.provideService(ShellSnapshotLoader, snapshotLoader),
);
// Wait until the subscription is established from the warm cache.
yield* SubscriptionRef.changes(capturedAfterSequence).pipe(
Stream.filter((value) => value !== undefined),
Stream.runHead,
);
expect(yield* SubscriptionRef.get(capturedAfterSequence)).toBe(5);
expect(yield* SubscriptionRef.get(loaderCalls)).toBe(0);
}),
);
});
+46 -8
View File
@@ -19,6 +19,7 @@ import { EnvironmentSupervisor } from "../connection/supervisor.ts";
import { safeErrorLogAttributes } from "../errors/safeLog.ts";
import { EnvironmentCacheStore } from "../platform/persistence.ts";
import { subscribe } from "../rpc/client.ts";
import { ShellSnapshotLoader } from "./shellSnapshotHttp.ts";
import { applyShellStreamEvent } from "./shellReducer.ts";
import type { EnvironmentCatalogState } from "./connections.ts";
import { followStreamInEnvironment } from "./runtime.ts";
@@ -48,6 +49,7 @@ const SHELL_SYNCHRONIZATION_ERROR_MESSAGE = "Could not synchronize environment d
export const makeEnvironmentShellState = Effect.fn("EnvironmentShellState.make")(function* () {
const supervisor = yield* EnvironmentSupervisor;
const cache = yield* EnvironmentCacheStore;
const snapshotLoader = yield* ShellSnapshotLoader;
const environmentId = supervisor.target.environmentId;
const cachedSnapshot = yield* cache.loadShell(environmentId).pipe(
Effect.catch((error) =>
@@ -147,13 +149,45 @@ export const makeEnvironmentShellState = Effect.fn("EnvironmentShellState.make")
yield* Queue.offer(persistence, nextSnapshot);
});
yield* subscribe(
ORCHESTRATION_WS_METHODS.subscribeShell,
{},
{
onExpectedFailure: (cause) => setStreamError(Cause.squash(cause)),
},
).pipe(Stream.runForEach(applyItem), Effect.forkScoped);
yield* Effect.forkScoped(
Effect.gen(function* () {
// Establish the base shell snapshot to resume from, minimizing bytes over
// the wire:
// - Warm cache: reuse the cached snapshot (zero network) and resume via
// `afterSequence` so we only receive shell events since the cached
// sequence.
// - Cold cache: load the full shell snapshot over HTTP (gzip-compressible,
// and off the socket), then resume via `afterSequence`.
// If no base can be established we fall back to the socket-embedded
// snapshot so the shell still synchronizes. Overlapping/replayed events are
// deduped by sequence in applyItem.
const base = Option.isSome(cachedSnapshot)
? cachedSnapshot
: yield* Effect.gen(function* () {
const prepared = yield* SubscriptionRef.changes(supervisor.prepared).pipe(
Stream.filter(Option.isSome),
Stream.map((current) => current.value),
Stream.runHead,
);
return Option.isSome(prepared)
? yield* snapshotLoader.load(prepared.value)
: Option.none<OrchestrationShellSnapshot>();
});
if (Option.isSome(base)) {
yield* applyItem({ kind: "snapshot", snapshot: base.value });
}
const subscribeInput = Option.match(base, {
onNone: () => ({}),
onSome: (snapshot) => ({ afterSequence: snapshot.snapshotSequence }),
});
yield* subscribe(ORCHESTRATION_WS_METHODS.subscribeShell, subscribeInput, {
onExpectedFailure: (cause) => setStreamError(Cause.squash(cause)),
}).pipe(Stream.runForEach(applyItem));
}),
);
yield* SubscriptionRef.changes(supervisor.state).pipe(
Stream.runForEach((connectionState) => {
switch (connectionProjectionPhase(connectionState)) {
@@ -293,7 +327,10 @@ export function createEnvironmentServerConfigsAtom(input: {
}
export function createEnvironmentShellAtoms<R, E>(
runtime: Atom.AtomRuntime<EnvironmentRegistry | EnvironmentCacheStore | R, E>,
runtime: Atom.AtomRuntime<
EnvironmentRegistry | EnvironmentCacheStore | ShellSnapshotLoader | R,
E
>,
) {
const stateAtom = Atom.family((environmentId: EnvironmentId) =>
runtime.atom(shellStateChanges(environmentId), {
@@ -316,4 +353,5 @@ export function createEnvironmentShellAtoms<R, E>(
export * from "./models.ts";
export * from "./shellCommands.ts";
export * from "./shellReducer.ts";
export * from "./shellSnapshotHttp.ts";
export * from "./snapshots.ts";
@@ -0,0 +1,92 @@
import type { OrchestrationShellSnapshot } from "@t3tools/contracts";
import * as Cause from "effect/Cause";
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import { HttpClient } from "effect/unstable/http";
import type { PreparedConnection } from "../connection/model.ts";
import { environmentEndpointUrl } from "../environment/endpoint.ts";
import { ManagedRelayDpopSigner } from "../relay/managedRelay.ts";
import { executeEnvironmentHttpRequest, makeEnvironmentHttpApiClient } from "../rpc/http.ts";
import { buildEnvironmentAuthHeaders, withEnvironmentCredentials } from "./environmentHttpAuth.ts";
// Bounded so a pathologically slow endpoint cannot block the (cheaper) socket
// fallback for long. The cached shell renders while this runs.
const DEFAULT_SHELL_SNAPSHOT_TIMEOUT_MS = 6_000;
/**
* Load the environment shell snapshot (projects + thread shells) over HTTP
* instead of as the WebSocket subscription's first frame. The response is
* gzip-compressible by the transport and keeps the (potentially large) list off
* the socket.
*/
export const fetchEnvironmentShellSnapshot = Effect.fn(
"clientRuntime.state.fetchEnvironmentShellSnapshot",
)(function* (input: {
readonly prepared: PreparedConnection;
readonly signer: Option.Option<ManagedRelayDpopSigner["Service"]>;
readonly timeoutMs?: number;
}) {
const requestUrl = environmentEndpointUrl(input.prepared.httpBaseUrl, "/api/orchestration/shell");
const client = yield* makeEnvironmentHttpApiClient(input.prepared.httpBaseUrl);
const headers = yield* buildEnvironmentAuthHeaders(
input.prepared.httpAuthorization,
"GET",
requestUrl,
input.signer,
);
return yield* executeEnvironmentHttpRequest(
requestUrl,
input.timeoutMs ?? DEFAULT_SHELL_SNAPSHOT_TIMEOUT_MS,
withEnvironmentCredentials(
input.prepared.httpAuthorization,
client.orchestration.shellSnapshot({ headers }),
),
);
});
/**
* Loads the environment shell snapshot over HTTP, returning `Option.none()` when
* it cannot be loaded (so the caller falls back to the socket-embedded snapshot).
* Decouples the shell state machine from the underlying HTTP + DPoP details and
* keeps them out of test contexts.
*/
export class ShellSnapshotLoader extends Context.Service<
ShellSnapshotLoader,
{
readonly load: (
prepared: PreparedConnection,
) => Effect.Effect<Option.Option<OrchestrationShellSnapshot>>;
}
>()("@t3tools/client-runtime/state/shellSnapshotHttp/ShellSnapshotLoader") {}
export const shellSnapshotLoaderLayer: Layer.Layer<
ShellSnapshotLoader,
never,
HttpClient.HttpClient
> = Layer.effect(
ShellSnapshotLoader,
Effect.gen(function* () {
const httpClient = yield* HttpClient.HttpClient;
// Resolve the DPoP signer optionally: it is only needed for relay/DPoP
// connections, so the loader must not hard-require it.
const signer = yield* Effect.serviceOption(ManagedRelayDpopSigner);
return ShellSnapshotLoader.of({
load: (prepared: PreparedConnection) =>
fetchEnvironmentShellSnapshot({ prepared, signer }).pipe(
Effect.map(Option.some<OrchestrationShellSnapshot>),
Effect.provideService(HttpClient.HttpClient, httpClient),
Effect.catchCause((cause) =>
Effect.logWarning(
"Could not load the environment shell snapshot over HTTP; using the socket snapshot instead.",
).pipe(
Effect.annotateLogs({ cause: Cause.pretty(cause) }),
Effect.as(Option.none<OrchestrationShellSnapshot>()),
),
),
),
});
}),
);
@@ -0,0 +1,120 @@
import type { OrchestrationThreadDetailSnapshot, ThreadId } from "@t3tools/contracts";
import * as Cause from "effect/Cause";
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import { HttpClient } from "effect/unstable/http";
import type { PreparedConnection } from "../connection/model.ts";
import { environmentEndpointUrl } from "../environment/endpoint.ts";
import { ManagedRelayDpopSigner } from "../relay/managedRelay.ts";
import {
executeEnvironmentHttpRequest,
makeEnvironmentHttpApiClient,
type RemoteEnvironmentRequestError,
} from "../rpc/http.ts";
import { buildEnvironmentAuthHeaders, withEnvironmentCredentials } from "./environmentHttpAuth.ts";
// Bounded so a pathologically slow endpoint cannot block the (cheaper) socket
// fallback for long. The cached thread renders while this runs, so the wait only
// delays the transition to live data on the first open, not the initial paint.
const DEFAULT_THREAD_SNAPSHOT_TIMEOUT_MS = 6_000;
/**
* Load a thread's detail snapshot over HTTP instead of embedding it in the
* WebSocket subscription's first frame. The response is gzip-compressible by
* the transport and keeps the (potentially multi-KB) snapshot off the socket.
*/
export const fetchEnvironmentThreadSnapshot = Effect.fn(
"clientRuntime.state.fetchEnvironmentThreadSnapshot",
)(function* (input: {
readonly prepared: PreparedConnection;
readonly threadId: ThreadId;
readonly signer: Option.Option<ManagedRelayDpopSigner["Service"]>;
readonly timeoutMs?: number;
}) {
const requestUrl = environmentEndpointUrl(
input.prepared.httpBaseUrl,
`/api/orchestration/threads/${input.threadId}`,
);
const client = yield* makeEnvironmentHttpApiClient(input.prepared.httpBaseUrl);
const headers = yield* buildEnvironmentAuthHeaders(
input.prepared.httpAuthorization,
"GET",
requestUrl,
input.signer,
);
return yield* executeEnvironmentHttpRequest(
requestUrl,
input.timeoutMs ?? DEFAULT_THREAD_SNAPSHOT_TIMEOUT_MS,
withEnvironmentCredentials(
input.prepared.httpAuthorization,
client.orchestration.threadSnapshot({
params: { threadId: input.threadId },
headers,
}),
),
);
});
export type FetchEnvironmentThreadSnapshotError = RemoteEnvironmentRequestError;
/**
* Loads a thread's detail snapshot over HTTP, returning `Option.none()` when it
* cannot be loaded (so the caller falls back to the socket-embedded snapshot).
* Decouples the thread state machine from the underlying HTTP + DPoP details and
* keeps them out of test contexts.
*/
export class ThreadSnapshotLoader extends Context.Service<
ThreadSnapshotLoader,
{
readonly load: (
prepared: PreparedConnection,
threadId: ThreadId,
) => Effect.Effect<Option.Option<OrchestrationThreadDetailSnapshot>>;
}
>()("@t3tools/client-runtime/state/threadSnapshotHttp/ThreadSnapshotLoader") {}
export const threadSnapshotLoaderLayer: Layer.Layer<
ThreadSnapshotLoader,
never,
HttpClient.HttpClient
> = Layer.effect(
ThreadSnapshotLoader,
Effect.gen(function* () {
const httpClient = yield* HttpClient.HttpClient;
// Resolve the DPoP signer optionally: it is only needed for relay/DPoP
// connections, so the loader must not hard-require it (bearer/primary
// connections work without one).
const signer = yield* Effect.serviceOption(ManagedRelayDpopSigner);
return ThreadSnapshotLoader.of({
load: (prepared: PreparedConnection, threadId: ThreadId) =>
fetchEnvironmentThreadSnapshot({ prepared, threadId, signer }).pipe(
Effect.map(Option.some<OrchestrationThreadDetailSnapshot>),
Effect.provideService(HttpClient.HttpClient, httpClient),
// A genuinely missing thread (404) is expected — the socket
// subscription is the source of truth for thread existence and will
// surface the deletion — so don't treat it as an error worth warning
// about; just defer to the socket path.
Effect.catchTags({
EnvironmentResourceNotFoundError: () =>
Effect.logDebug(
"Thread snapshot not found over HTTP; deferring to the socket subscription.",
).pipe(
Effect.annotateLogs({ threadId }),
Effect.as(Option.none<OrchestrationThreadDetailSnapshot>()),
),
}),
Effect.catchCause((cause) =>
Effect.logWarning(
"Could not load the thread snapshot over HTTP; using the socket snapshot instead.",
).pipe(
Effect.annotateLogs({ threadId, cause: Cause.pretty(cause) }),
Effect.as(Option.none<OrchestrationThreadDetailSnapshot>()),
),
),
),
});
}),
);
@@ -6,12 +6,12 @@ import { Atom } from "effect/unstable/reactivity";
import type { EnvironmentRegistry } from "../connection/registry.ts";
import type { EnvironmentCacheStore } from "../platform/persistence.ts";
import { THREAD_STATE_IDLE_TTL_MS } from "./threadRetention.ts";
import { createEnvironmentThreadStateAtoms } from "./threads.ts";
import { createEnvironmentThreadStateAtoms, type ThreadSnapshotLoader } from "./threads.ts";
describe("createEnvironmentThreadStateAtoms", () => {
it("retains thread state across short subscriber gaps", () => {
const runtime = Atom.runtime(Layer.empty) as unknown as Atom.AtomRuntime<
EnvironmentRegistry | EnvironmentCacheStore,
EnvironmentRegistry | EnvironmentCacheStore | ThreadSnapshotLoader,
never
>;
const threads = createEnvironmentThreadStateAtoms(runtime);
@@ -6,6 +6,7 @@ import {
ProviderInstanceId,
ThreadId,
type OrchestrationThread,
type OrchestrationThreadDetailSnapshot,
type OrchestrationThreadStreamItem,
} from "@t3tools/contracts";
import { describe, expect, it } from "@effect/vitest";
@@ -30,6 +31,7 @@ import * as RpcSession from "../rpc/session.ts";
import {
EMPTY_ENVIRONMENT_THREAD_STATE,
makeEnvironmentThreadState,
ThreadSnapshotLoader,
type EnvironmentThreadState,
} from "./threads.ts";
@@ -40,6 +42,15 @@ const TARGET = new PrimaryConnectionTarget({
wsBaseUrl: "wss://environment.example.test",
});
const THREAD_ID = ThreadId.make("thread-1");
const CACHED_SNAPSHOT_SEQUENCE = 7;
const PREPARED: PreparedConnection = {
environmentId: TARGET.environmentId,
label: TARGET.label,
httpBaseUrl: TARGET.httpBaseUrl,
socketUrl: TARGET.wsBaseUrl,
httpAuthorization: null,
target: TARGET,
};
const BASE_THREAD: OrchestrationThread = {
id: THREAD_ID,
projectId: ProjectId.make("project-1"),
@@ -89,13 +100,16 @@ function awaitThreadState(
const makeHarness = Effect.fn("TestEnvironmentThreads.makeHarness")(function* (options?: {
readonly cached?: OrchestrationThread;
readonly httpSnapshot?: Option.Option<OrchestrationThreadDetailSnapshot>;
}) {
const inputs = yield* Queue.unbounded<TestThreadInput>();
const observed = yield* Queue.unbounded<EnvironmentThreadState>();
const latest = yield* Ref.make<EnvironmentThreadState>(EMPTY_ENVIRONMENT_THREAD_STATE);
const retryCount = yield* Ref.make(0);
const subscriptionCount = yield* Ref.make(0);
const savedThreads = yield* Ref.make<ReadonlyArray<OrchestrationThread>>([]);
const loaderCalls = yield* Ref.make(0);
const lastSubscribeAfterSequence = yield* Ref.make<number | undefined>(undefined);
const savedThreads = yield* Ref.make<ReadonlyArray<OrchestrationThreadDetailSnapshot>>([]);
const removedThreads = yield* Ref.make<ReadonlyArray<ThreadId>>([]);
const supervisorState = yield* SubscriptionRef.make<SupervisorConnectionState>(
AVAILABLE_CONNECTION_STATE,
@@ -107,17 +121,30 @@ const makeHarness = Effect.fn("TestEnvironmentThreads.makeHarness")(function* (o
),
);
const client = {
[ORCHESTRATION_WS_METHODS.subscribeThread]: () =>
[ORCHESTRATION_WS_METHODS.subscribeThread]: (input: { readonly afterSequence?: number }) =>
Stream.unwrap(
Ref.updateAndGet(subscriptionCount, (count) => count + 1).pipe(
Effect.map(() => streamFrom(inputs)),
Effect.andThen(Ref.set(lastSubscribeAfterSequence, input.afterSequence)),
Effect.as(streamFrom(inputs)),
),
),
} as unknown as WsRpcProtocolClient;
const supervisorSession = yield* SubscriptionRef.make<Option.Option<RpcSession.RpcSession>>(
Option.some(testSession(client)),
);
const prepared = yield* SubscriptionRef.make<Option.Option<PreparedConnection>>(Option.none());
const prepared = yield* SubscriptionRef.make<Option.Option<PreparedConnection>>(
Option.some(PREPARED),
);
const snapshotLoader = ThreadSnapshotLoader.of({
load: (_prepared, threadId) =>
Ref.update(loaderCalls, (count) => count + 1).pipe(
Effect.as(
threadId === THREAD_ID
? (options?.httpSnapshot ?? Option.none<OrchestrationThreadDetailSnapshot>())
: Option.none<OrchestrationThreadDetailSnapshot>(),
),
),
});
const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
target: TARGET,
state: supervisorState,
@@ -133,7 +160,10 @@ const makeHarness = Effect.fn("TestEnvironmentThreads.makeHarness")(function* (o
loadThread: (_environmentId, threadId) =>
Effect.succeed(
threadId === THREAD_ID && options?.cached !== undefined
? Option.some(options.cached)
? Option.some({
snapshotSequence: CACHED_SNAPSHOT_SEQUENCE,
thread: options.cached,
})
: Option.none(),
),
saveThread: (_environmentId, thread) =>
@@ -145,6 +175,7 @@ const makeHarness = Effect.fn("TestEnvironmentThreads.makeHarness")(function* (o
const threadState = yield* makeEnvironmentThreadState(THREAD_ID).pipe(
Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
Effect.provideService(Persistence.EnvironmentCacheStore, cache),
Effect.provideService(ThreadSnapshotLoader, snapshotLoader),
);
yield* SubscriptionRef.changes(threadState).pipe(
Stream.runForEach((state) =>
@@ -159,6 +190,8 @@ const makeHarness = Effect.fn("TestEnvironmentThreads.makeHarness")(function* (o
latest,
retryCount,
subscriptionCount,
loaderCalls,
lastSubscribeAfterSequence,
supervisorState,
supervisorSession,
savedThreads,
@@ -217,19 +250,38 @@ const deleted = (): OrchestrationThreadStreamItem => ({
});
describe("EnvironmentThreads", () => {
it.effect("publishes cached data before a live snapshot arrives", () =>
it.effect("publishes cached data immediately from a warm cache", () =>
Effect.gen(function* () {
const harness = yield* makeHarness({ cached: BASE_THREAD });
const state = yield* awaitThreadState(
harness.observed,
(value) => value.status === "cached" && Option.isSome(value.data),
);
const state = yield* awaitThreadState(harness.observed, (value) => Option.isSome(value.data));
expect(Option.getOrThrow(state.data)).toEqual(BASE_THREAD);
expect(Option.isNone(state.error)).toBe(true);
}),
);
it.effect("resumes a warm cache via afterSequence without an HTTP fetch", () =>
Effect.gen(function* () {
const harness = yield* makeHarness({ cached: BASE_THREAD });
// The warm cache reaches live from the cached data, and a live event
// applies on top of it.
yield* Queue.offer(harness.inputs, titleUpdated("Live title", CACHED_SNAPSHOT_SEQUENCE + 1));
yield* awaitThreadState(
harness.observed,
(value) =>
value.status === "live" &&
Option.isSome(value.data) &&
value.data.value.title === "Live title",
);
// The subscription resumed from the cached sequence and never fetched the
// full snapshot over HTTP.
expect(yield* Ref.get(harness.lastSubscribeAfterSequence)).toBe(CACHED_SNAPSHOT_SEQUENCE);
expect(yield* Ref.get(harness.loaderCalls)).toBe(0);
}),
);
it.effect("reduces live events and persists the latest thread", () =>
Effect.gen(function* () {
const harness = yield* makeHarness({ cached: BASE_THREAD });
@@ -247,7 +299,34 @@ describe("EnvironmentThreads", () => {
yield* Effect.yieldNow;
expect(Option.getOrThrow(state.data).title).toBe("Live title");
expect((yield* Ref.get(harness.savedThreads)).at(-1)?.title).toBe("Live title");
expect((yield* Ref.get(harness.savedThreads)).at(-1)?.thread.title).toBe("Live title");
expect((yield* Ref.get(harness.savedThreads)).at(-1)?.snapshotSequence).toBe(2);
}),
);
it.effect("seeds the thread from the HTTP snapshot and resumes live events", () =>
Effect.gen(function* () {
const httpThread: OrchestrationThread = { ...BASE_THREAD, title: "HTTP title" };
const harness = yield* makeHarness({
httpSnapshot: Option.some({ snapshotSequence: 1, thread: httpThread }),
});
// No socket snapshot is pushed; only a live event arrives over the socket.
// It can only be applied if the HTTP snapshot already seeded the thread.
yield* Queue.offer(harness.inputs, titleUpdated("Live title", 2));
const state = yield* awaitThreadState(
harness.observed,
(value) =>
value.status === "live" &&
Option.isSome(value.data) &&
value.data.value.title === "Live title",
);
expect(Option.getOrThrow(state.data).title).toBe("Live title");
// Cold cache: the full snapshot was loaded over HTTP and the socket
// resumed from that snapshot's sequence.
expect(yield* Ref.get(harness.loaderCalls)).toBeGreaterThanOrEqual(1);
expect(yield* Ref.get(harness.lastSubscribeAfterSequence)).toBe(1);
}),
);
+69 -20
View File
@@ -2,6 +2,7 @@ import {
ORCHESTRATION_WS_METHODS,
type EnvironmentId as EnvironmentIdType,
type OrchestrationThread,
type OrchestrationThreadDetailSnapshot,
type OrchestrationThreadStreamItem,
type ThreadId as ThreadIdType,
} from "@t3tools/contracts";
@@ -18,6 +19,7 @@ import { connectionProjectionPhase } from "../connection/model.ts";
import { EnvironmentSupervisor } from "../connection/supervisor.ts";
import { EnvironmentCacheStore } from "../platform/persistence.ts";
import { subscribe } from "../rpc/client.ts";
import { ThreadSnapshotLoader } from "./threadSnapshotHttp.ts";
import { parseThreadKey, threadKey } from "./entities.ts";
import { applyThreadDetailEvent } from "./threadReducer.ts";
import { THREAD_STATE_IDLE_TTL_MS } from "./threadRetention.ts";
@@ -44,6 +46,7 @@ export const makeEnvironmentThreadState = Effect.fn("EnvironmentThreadState.make
) {
const supervisor = yield* EnvironmentSupervisor;
const cache = yield* EnvironmentCacheStore;
const snapshotLoader = yield* ThreadSnapshotLoader;
const environmentId = supervisor.target.environmentId;
const cached = yield* cache.loadThread(environmentId, threadId).pipe(
Effect.catch((error) =>
@@ -53,22 +56,27 @@ export const makeEnvironmentThreadState = Effect.fn("EnvironmentThreadState.make
threadId,
error: error.message,
}),
Effect.as(Option.none<OrchestrationThread>()),
Effect.as(Option.none<OrchestrationThreadDetailSnapshot>()),
),
),
);
const cachedThread = Option.map(cached, (snapshot) => snapshot.thread);
const state = yield* SubscriptionRef.make<EnvironmentThreadState>({
data: cached,
status: statusWithoutLiveData(cached),
data: cachedThread,
status: statusWithoutLiveData(cachedThread),
error: Option.none(),
});
const lastSequence = yield* SubscriptionRef.make(0);
const persistence = yield* Queue.sliding<OrchestrationThread>(1);
// Seed the resume cursor from the cached snapshot so a warm cache can catch up
// via `afterSequence` instead of re-downloading the full thread body.
const lastSequence = yield* SubscriptionRef.make(
Option.match(cached, { onNone: () => 0, onSome: (snapshot) => snapshot.snapshotSequence }),
);
const persistence = yield* Queue.sliding<OrchestrationThreadDetailSnapshot>(1);
const persist = Effect.fn("EnvironmentThreadState.persist")(function* (
thread: OrchestrationThread,
snapshot: OrchestrationThreadDetailSnapshot,
) {
yield* cache.saveThread(environmentId, thread).pipe(
yield* cache.saveThread(environmentId, snapshot).pipe(
Effect.catch((error) =>
Effect.logWarning("Could not persist the thread cache.").pipe(
Effect.annotateLogs({
@@ -120,7 +128,10 @@ export const makeEnvironmentThreadState = Effect.fn("EnvironmentThreadState.make
status: "live",
error: Option.none(),
});
yield* Queue.offer(persistence, thread);
// Persist the thread together with the sequence it reflects so the next warm
// cache can resume from exactly here.
const snapshotSequence = yield* SubscriptionRef.get(lastSequence);
yield* Queue.offer(persistence, { snapshotSequence, thread });
});
const setDeleted = Effect.fn("EnvironmentThreadState.setDeleted")(function* () {
@@ -187,21 +198,55 @@ export const makeEnvironmentThreadState = Effect.fn("EnvironmentThreadState.make
);
yield* setSynchronizing;
yield* subscribe(
ORCHESTRATION_WS_METHODS.subscribeThread,
{ threadId },
{
onExpectedFailure: setStreamError,
retryExpectedFailureAfter: "250 millis",
},
).pipe(Stream.runForEach(applyItem), Effect.forkScoped);
yield* Effect.forkScoped(
Effect.gen(function* () {
// Establish the base snapshot to resume from, minimizing bytes over the
// wire:
// - Warm cache: reuse the cached snapshot (zero network) and resume via
// `afterSequence` so we only receive events since the cached sequence.
// - Cold cache: load the full snapshot over HTTP (gzip-compressible, and
// off the socket), then resume via `afterSequence`.
// If no base can be established we fall back to the socket-embedded
// snapshot so the thread still synchronizes. Overlapping/replayed events
// are deduped by sequence in applyItem.
const base = Option.isSome(cached)
? cached
: yield* Effect.gen(function* () {
// Cold cache only: wait for a prepared connection so we can
// authenticate the HTTP request; this mirrors the socket path, which
// likewise waits for a live session.
const prepared = yield* SubscriptionRef.changes(supervisor.prepared).pipe(
Stream.filter(Option.isSome),
Stream.map((current) => current.value),
Stream.runHead,
);
return Option.isSome(prepared)
? yield* snapshotLoader.load(prepared.value, threadId)
: Option.none<OrchestrationThreadDetailSnapshot>();
});
if (Option.isSome(base)) {
yield* applyItem({ kind: "snapshot", snapshot: base.value });
}
const subscribeInput = Option.match(base, {
onNone: () => ({ threadId }),
onSome: (snapshot) => ({ threadId, afterSequence: snapshot.snapshotSequence }),
});
yield* subscribe(ORCHESTRATION_WS_METHODS.subscribeThread, subscribeInput, {
onExpectedFailure: setStreamError,
retryExpectedFailureAfter: "250 millis",
}).pipe(Stream.runForEach(applyItem));
}),
);
yield* Effect.addFinalizer(() =>
SubscriptionRef.get(state).pipe(
Effect.flatMap((current) =>
Effect.all([SubscriptionRef.get(state), SubscriptionRef.get(lastSequence)]).pipe(
Effect.flatMap(([current, snapshotSequence]) =>
Option.match(current.data, {
onNone: () => Effect.void,
onSome: persist,
onSome: (thread) => persist({ snapshotSequence, thread }),
}),
),
),
@@ -218,7 +263,10 @@ export function threadStateChanges(environmentId: EnvironmentIdType, threadId: T
}
export function createEnvironmentThreadStateAtoms<R, E>(
runtime: Atom.AtomRuntime<EnvironmentRegistry | EnvironmentCacheStore | R, E>,
runtime: Atom.AtomRuntime<
EnvironmentRegistry | EnvironmentCacheStore | ThreadSnapshotLoader | R,
E
>,
) {
const family = Atom.family((key: string) => {
const { environmentId, threadId } = parseThreadKey(key);
@@ -240,6 +288,7 @@ export function createEnvironmentThreadStateAtoms<R, E>(
export * from "./archivedThreads.ts";
export * from "./checkpointDiff.ts";
export * from "./threadSnapshotHttp.ts";
export * from "./composerPathSearch.ts";
export * from "./threadCommands.ts";
export * from "./threadDetail.ts";
+46 -1
View File
@@ -24,12 +24,14 @@ import {
AuthWebSocketTicketResult,
ServerAuthSessionMethod,
} from "./auth.ts";
import { AuthSessionId, TrimmedNonEmptyString } from "./baseSchemas.ts";
import { AuthSessionId, ThreadId, TrimmedNonEmptyString } from "./baseSchemas.ts";
import { ExecutionEnvironmentDescriptor } from "./environment.ts";
import {
ClientOrchestrationCommand,
DispatchResult,
OrchestrationReadModel,
OrchestrationShellSnapshot,
OrchestrationThreadDetailSnapshot,
} from "./orchestration.ts";
import {
RelayCloudEnvironmentHealthRequest,
@@ -80,6 +82,7 @@ export const EnvironmentInternalErrorReason = Schema.Literals([
"client_sessions_load_failed",
"client_session_revoke_failed",
"orchestration_snapshot_failed",
"orchestration_thread_snapshot_failed",
"orchestration_dispatch_failed",
"internal_error",
]);
@@ -155,11 +158,29 @@ export class EnvironmentInternalError extends Schema.TaggedErrorClass<Environmen
}
}
export const EnvironmentResourceNotFoundReason = Schema.Literals(["thread_not_found"]);
export type EnvironmentResourceNotFoundReason = typeof EnvironmentResourceNotFoundReason.Type;
export class EnvironmentResourceNotFoundError extends Schema.TaggedErrorClass<EnvironmentResourceNotFoundError>()(
"EnvironmentResourceNotFoundError",
{
code: Schema.Literal("not_found"),
reason: EnvironmentResourceNotFoundReason,
traceId: TrimmedNonEmptyString,
},
{ httpApiStatus: 404 },
) {
[HttpServerRespondable.symbol]() {
return HttpServerResponse.schemaJson(EnvironmentResourceNotFoundError)(this, { status: 404 });
}
}
export const EnvironmentHttpCommonError = Schema.Union([
EnvironmentRequestInvalidError,
EnvironmentAuthInvalidError,
EnvironmentScopeRequiredError,
EnvironmentOperationForbiddenError,
EnvironmentResourceNotFoundError,
EnvironmentInternalError,
]);
export type EnvironmentHttpCommonError = typeof EnvironmentHttpCommonError.Type;
@@ -269,6 +290,11 @@ const EnvironmentOrchestrationSnapshotErrors = [
EnvironmentScopeRequiredError,
EnvironmentInternalError,
] as const;
const EnvironmentOrchestrationThreadSnapshotErrors = [
EnvironmentScopeRequiredError,
EnvironmentResourceNotFoundError,
EnvironmentInternalError,
] as const;
const EnvironmentOrchestrationDispatchErrors = [
EnvironmentRequestInvalidError,
EnvironmentScopeRequiredError,
@@ -422,6 +448,10 @@ export class EnvironmentAuthHttpApi extends HttpApiGroup.make("auth")
}).middleware(EnvironmentAuthenticatedAuth),
) {}
const EnvironmentOrchestrationThreadSnapshotParams = Schema.Struct({
threadId: ThreadId,
});
export class EnvironmentOrchestrationHttpApi extends HttpApiGroup.make("orchestration")
.add(
HttpApiEndpoint.get("snapshot", "/api/orchestration/snapshot", {
@@ -430,6 +460,21 @@ export class EnvironmentOrchestrationHttpApi extends HttpApiGroup.make("orchestr
error: EnvironmentOrchestrationSnapshotErrors,
}).middleware(EnvironmentAuthenticatedAuth),
)
.add(
HttpApiEndpoint.get("shellSnapshot", "/api/orchestration/shell", {
headers: OptionalBearerHeaders,
success: OrchestrationShellSnapshot,
error: EnvironmentOrchestrationSnapshotErrors,
}).middleware(EnvironmentAuthenticatedAuth),
)
.add(
HttpApiEndpoint.get("threadSnapshot", "/api/orchestration/threads/:threadId", {
headers: OptionalBearerHeaders,
params: EnvironmentOrchestrationThreadSnapshotParams,
success: OrchestrationThreadDetailSnapshot,
error: EnvironmentOrchestrationThreadSnapshotErrors,
}).middleware(EnvironmentAuthenticatedAuth),
)
.add(
HttpApiEndpoint.post("dispatch", "/api/orchestration/dispatch", {
headers: OptionalBearerHeaders,
+22 -1
View File
@@ -451,8 +451,29 @@ export const OrchestrationShellStreamItem = Schema.Union([
]);
export type OrchestrationShellStreamItem = typeof OrchestrationShellStreamItem.Type;
export const OrchestrationSubscribeShellInput = Schema.Struct({
/**
* When provided, the server skips the initial full shell snapshot and instead
* replays shell events after this sequence before streaming live events.
* Clients that already hold a cached (or HTTP-loaded) shell snapshot pass its
* sequence here so the subscription resumes without re-sending the entire
* projects/threads list (overlapping events are deduped by sequence on the
* client).
*/
afterSequence: Schema.optionalKey(NonNegativeInt),
});
export type OrchestrationSubscribeShellInput = typeof OrchestrationSubscribeShellInput.Type;
export const OrchestrationSubscribeThreadInput = Schema.Struct({
threadId: ThreadId,
/**
* When provided, the server skips the initial snapshot frame and instead
* replays events after this sequence before streaming live events. Clients
* that load the snapshot over HTTP pass the snapshot's sequence here so the
* live subscription resumes without a gap (overlapping events are deduped by
* sequence on the client).
*/
afterSequence: Schema.optionalKey(NonNegativeInt),
});
export type OrchestrationSubscribeThreadInput = typeof OrchestrationSubscribeThreadInput.Type;
@@ -1244,7 +1265,7 @@ export const OrchestrationRpcSchemas = {
output: OrchestrationThreadStreamItem,
},
subscribeShell: {
input: Schema.Struct({}),
input: OrchestrationSubscribeShellInput,
output: OrchestrationShellStreamItem,
},
} as const;
+215
View File
@@ -457,6 +457,40 @@ export class RelayAgentActivityPublishProofInvalidError extends Schema.TaggedErr
}
}
export const RelayDeviceTokenPollCode = Schema.Literals([
"authorization_pending",
"slow_down",
"access_denied",
"expired_token",
]);
export type RelayDeviceTokenPollCode = typeof RelayDeviceTokenPollCode.Type;
export class RelayDeviceTokenPollError extends Schema.TaggedErrorClass<RelayDeviceTokenPollError>()(
"RelayDeviceTokenPollError",
{
code: RelayDeviceTokenPollCode,
traceId: TrimmedNonEmptyString,
},
{ httpApiStatus: 400 },
) {
override get message(): string {
return `Relay device authorization is not redeemable: ${this.code}`;
}
}
export class RelayDeviceAuthorizationNotFoundError extends Schema.TaggedErrorClass<RelayDeviceAuthorizationNotFoundError>()(
"RelayDeviceAuthorizationNotFoundError",
{
code: Schema.Literal("device_authorization_not_found"),
traceId: TrimmedNonEmptyString,
},
{ httpApiStatus: 404 },
) {
override get message(): string {
return "Relay device authorization was not found, already handled, or expired.";
}
}
export class RelayInternalError extends Schema.TaggedErrorClass<RelayInternalError>()(
"RelayInternalError",
{
@@ -473,6 +507,8 @@ export class RelayInternalError extends Schema.TaggedErrorClass<RelayInternalErr
export const RelayProtectedError = Schema.Union([
RelayAuthInvalidError,
RelayDeviceTokenPollError,
RelayDeviceAuthorizationNotFoundError,
RelayEnvironmentLinkProofExpiredError,
RelayEnvironmentLinkProofInvalidError,
RelayEnvironmentConnectNotAuthorizedError,
@@ -654,6 +690,116 @@ export const RelayDpopAccessTokenResponse = Schema.Struct({
});
export type RelayDpopAccessTokenResponse = typeof RelayDpopAccessTokenResponse.Type;
export const RelayDeviceAuthorizationGrantType =
"urn:ietf:params:oauth:grant-type:device_code" as const;
// Bounds mirror the relay_device_authorizations column widths so overlong
// input fails request validation instead of surfacing as a persistence error.
const RelayDeviceClientId = TrimmedNonEmptyString.check(Schema.isMaxLength(191));
const RelayDeviceScope = TrimmedNonEmptyString.check(Schema.isMaxLength(256));
const RelayDeviceCodeChallenge = TrimmedNonEmptyString.check(Schema.isMaxLength(128));
export const RelayDeviceAuthorizationRequest = Schema.Struct({
client_id: RelayDeviceClientId.annotate({
description: "Clerk OAuth client id of the CLI requesting device authorization.",
}),
scope: RelayDeviceScope.annotate({
description: "Space-separated OAuth scopes requested from Clerk.",
}),
code_challenge: RelayDeviceCodeChallenge.annotate({
description: "PKCE code challenge generated by the device.",
}),
code_challenge_method: Schema.Literal("S256"),
device_name: Schema.optional(
TrimmedNonEmptyString.check(Schema.isMaxLength(191)).annotate({
description: "Human-readable device name shown on the approval page.",
}),
),
device_platform: Schema.optional(
TrimmedNonEmptyString.check(Schema.isMaxLength(128)).annotate({
description: "Platform descriptor shown on the approval page.",
}),
),
client_version: Schema.optional(
TrimmedNonEmptyString.check(Schema.isMaxLength(64)).annotate({
description: "CLI version shown on the approval page.",
}),
),
})
.annotate({ description: "Starts an OAuth device authorization for a browserless client." })
.pipe(HttpApiSchema.asFormUrlEncoded());
export type RelayDeviceAuthorizationRequest = typeof RelayDeviceAuthorizationRequest.Type;
export const RelayDeviceAuthorizationResponse = Schema.Struct({
device_code: TrimmedNonEmptyString,
user_code: TrimmedNonEmptyString,
verification_uri: TrimmedNonEmptyString,
verification_uri_complete: TrimmedNonEmptyString,
expires_in: Schema.Int.check(Schema.isGreaterThan(0)),
interval: Schema.Int.check(Schema.isGreaterThan(0)),
});
export type RelayDeviceAuthorizationResponse = typeof RelayDeviceAuthorizationResponse.Type;
export const RelayDeviceTokenRequest = Schema.Struct({
grant_type: Schema.Literal(RelayDeviceAuthorizationGrantType),
device_code: TrimmedNonEmptyString.check(Schema.isMaxLength(128)),
client_id: RelayDeviceClientId,
})
.annotate({ description: "Polls a pending device authorization for its granted code." })
.pipe(HttpApiSchema.asFormUrlEncoded());
export type RelayDeviceTokenRequest = typeof RelayDeviceTokenRequest.Type;
export const RelayDeviceTokenResponse = Schema.Struct({
authorization_code: TrimmedNonEmptyString.annotate({
description:
"Clerk authorization code bound to the device's PKCE challenge. The device exchanges it directly at the Clerk token endpoint.",
}),
redirect_uri: TrimmedNonEmptyString.annotate({
description: "Redirect URI used in the brokered authorization; echo it in the token exchange.",
}),
});
export type RelayDeviceTokenResponse = typeof RelayDeviceTokenResponse.Type;
export const RelayDeviceAuthorizationStatus = Schema.Literals(["pending", "approved", "denied"]);
export type RelayDeviceAuthorizationStatus = typeof RelayDeviceAuthorizationStatus.Type;
export const RelayDeviceAuthorizationDetails = Schema.Struct({
userCode: TrimmedNonEmptyString,
status: RelayDeviceAuthorizationStatus,
scope: TrimmedNonEmptyString,
deviceName: Schema.NullOr(Schema.String),
devicePlatform: Schema.NullOr(Schema.String),
clientVersion: Schema.NullOr(Schema.String),
requestIp: Schema.NullOr(Schema.String),
requestLocation: Schema.NullOr(Schema.String),
requestedAt: TrimmedNonEmptyString,
expiresAt: TrimmedNonEmptyString,
});
export type RelayDeviceAuthorizationDetails = typeof RelayDeviceAuthorizationDetails.Type;
export const RelayDeviceAuthorizationParams = Schema.Struct({
userCode: TrimmedNonEmptyString.check(Schema.isMaxLength(32)),
});
export type RelayDeviceAuthorizationParams = typeof RelayDeviceAuthorizationParams.Type;
export const RelayDeviceApprovalResponse = Schema.Struct({
authorizationUrl: TrimmedNonEmptyString.annotate({
description:
"Clerk authorize URL the approving browser must visit to mint the device's authorization code.",
}),
});
export type RelayDeviceApprovalResponse = typeof RelayDeviceApprovalResponse.Type;
export const RelayDeviceCompletionRequest = Schema.Struct({
state: TrimmedNonEmptyString.check(Schema.isMaxLength(64)).annotate({
description: "Opaque state returned by the approval step and echoed by Clerk.",
}),
code: TrimmedNonEmptyString.check(Schema.isMaxLength(512)).annotate({
description: "Authorization code issued by Clerk for the approved device.",
}),
});
export type RelayDeviceCompletionRequest = typeof RelayDeviceCompletionRequest.Type;
export const RelayBearerRequestHeaders = Schema.Struct({
authorization: TrimmedNonEmptyString,
});
@@ -942,6 +1088,73 @@ export const RelayTokenGroup = HttpApiGroup.make("token")
.add(RelayExchangeDpopAccessTokenEndpoint)
.annotate(OpenApi.Description, "OAuth token exchange for DPoP-bound client access.");
const RelayDeviceTokenErrors = [RelayDeviceTokenPollError, RelayInternalError] as const;
const RelayDeviceApprovalErrors = [
RelayAuthInvalidError,
RelayDeviceAuthorizationNotFoundError,
RelayInternalError,
] as const;
export const RelayDeviceGroup = HttpApiGroup.make("device")
.add(
HttpApiEndpoint.post("authorizeDevice", "/v1/device/authorization", {
payload: RelayDeviceAuthorizationRequest,
success: RelayDeviceAuthorizationResponse,
error: RelayInternalError,
}).annotate(OpenApi.Summary, "Start a device authorization"),
HttpApiEndpoint.post("redeemDeviceCode", "/v1/device/token", {
payload: RelayDeviceTokenRequest,
success: RelayDeviceTokenResponse,
error: RelayDeviceTokenErrors,
}).annotate(OpenApi.Summary, "Poll a device authorization for its granted code"),
)
.annotate(
OpenApi.Description,
"OAuth device authorization for browserless CLIs, brokered through the Clerk authorization-code flow.",
);
export const RelayDeviceApprovalGroup = HttpApiGroup.make("deviceApproval")
.add(
HttpApiEndpoint.get("getDeviceAuthorization", "/v1/client/device-authorizations/:userCode", {
headers: RelayBearerRequestHeaders,
params: RelayDeviceAuthorizationParams,
success: RelayDeviceAuthorizationDetails,
error: RelayDeviceApprovalErrors,
}).annotate(OpenApi.Summary, "Look up a pending device authorization by user code"),
HttpApiEndpoint.post(
"approveDeviceAuthorization",
"/v1/client/device-authorizations/:userCode/approve",
{
headers: RelayBearerRequestHeaders,
params: RelayDeviceAuthorizationParams,
success: RelayDeviceApprovalResponse,
error: RelayDeviceApprovalErrors,
},
).annotate(OpenApi.Summary, "Approve a device authorization"),
HttpApiEndpoint.post(
"completeDeviceAuthorization",
"/v1/client/device-authorizations/complete",
{
headers: RelayBearerRequestHeaders,
payload: RelayDeviceCompletionRequest,
success: RelayOkResponse,
error: RelayDeviceApprovalErrors,
},
).annotate(OpenApi.Summary, "Attach the Clerk authorization code to an approved device"),
HttpApiEndpoint.post(
"denyDeviceAuthorization",
"/v1/client/device-authorizations/:userCode/deny",
{
headers: RelayBearerRequestHeaders,
params: RelayDeviceAuthorizationParams,
success: RelayOkResponse,
error: RelayDeviceApprovalErrors,
},
).annotate(OpenApi.Summary, "Deny a device authorization"),
)
.annotate(OpenApi.Description, "Signed-in approval surface for pending device authorizations.")
.middleware(RelayClientAuth);
export const RelayConnectEnvironmentEndpoint = HttpApiEndpoint.post(
"connectEnvironment",
"/v1/environments/:environmentId/connect",
@@ -1000,6 +1213,8 @@ export const RelayApi = HttpApi.make("RelayApi")
RelayMobileGroup,
RelayClientGroup,
RelayTokenGroup,
RelayDeviceGroup,
RelayDeviceApprovalGroup,
RelayDpopClientGroup,
RelayServerGroup,
)
+922
View File
@@ -0,0 +1,922 @@
diff --git a/keyboard.d.ts b/keyboard.d.ts
index 5a115ea..2c65d31 100644
--- a/keyboard.d.ts
+++ b/keyboard.d.ts
@@ -269,7 +269,7 @@ type KeyboardChatComposerInsetListRef = {
type KeyboardChatComposerRef = {
current: Pick<View, "measure"> | null;
};
-declare function useKeyboardChatComposerInset(listRef: KeyboardChatComposerInsetListRef, composerRef: KeyboardChatComposerRef, initialHeight?: number): {
+declare function useKeyboardChatComposerInset(listRef: KeyboardChatComposerInsetListRef, composerRef: KeyboardChatComposerRef, initialHeight?: number, heightAdjustment?: number): {
contentInsetEndAdjustment: SharedValue<number>;
onComposerLayout: (event: LayoutChangeEvent) => void;
};
@@ -278,8 +278,10 @@ declare function useKeyboardScrollToEnd({ freeze: freezeProp, listRef }: UseKeyb
scrollMessageToEnd: ({ animated, closeKeyboard }: ScrollMessageToEndOptions) => Promise<void>;
};
declare const KeyboardAwareLegendList: <ItemT>(props: Omit<AnimatedLegendListProps<ItemT>, "anchoredEndSpace" | "contentInsetEndAdjustment" | "renderScrollComponent"> & KeyboardChatScrollViewPropsUnique & {
+ adjustedInsetCompensation?: number;
anchoredEndSpace?: AnchoredEndSpaceConfig;
contentInsetEndAdjustment?: SharedValue<number>;
+ contentInsetEndStaticAdjustment?: number;
keyboardOffset?: number;
} & React.RefAttributes<LegendListRef>) => React.ReactElement | null;
diff --git a/keyboard.js b/keyboard.js
index 736286a..8218172 100644
--- a/keyboard.js
+++ b/keyboard.js
@@ -33,19 +33,19 @@ if (typeof __DEV__ !== "undefined" && __DEV__ && !reactNativeKeyboardController.
"[legend-list] KeyboardAwareLegendList requires a recent react-native-keyboard-controller with KeyboardChatScrollView. Please upgrade react-native-keyboard-controller to at least 1.21.7."
);
}
-function useKeyboardChatComposerInset(listRef, composerRef, initialHeight = 0) {
+function useKeyboardChatComposerInset(listRef, composerRef, initialHeight = 0, heightAdjustment = 0) {
const contentInsetEndAdjustment = reactNativeReanimated.useSharedValue(initialHeight);
const lastHeightRef = React.useRef(void 0);
const reportHeight = React.useCallback(
- (height) => {
+ (rawHeight) => {
+ const height = Math.max(0, rawHeight + heightAdjustment);
var _a;
if (Number.isFinite(height) && height !== lastHeightRef.current) {
lastHeightRef.current = height;
contentInsetEndAdjustment.value = height;
- (_a = listRef.current) == null ? void 0 : _a.reportContentInset({ bottom: height });
}
},
- [contentInsetEndAdjustment, listRef]
+ [contentInsetEndAdjustment, heightAdjustment, listRef]
);
React.useLayoutEffect(() => {
var _a;
@@ -84,9 +84,11 @@ function useKeyboardScrollToEnd({ freeze: freezeProp, listRef }) {
}
var KeyboardAwareLegendList = typedForwardRef(function KeyboardAwareLegendList2(props, forwardedRef) {
const {
+ adjustedInsetCompensation,
anchoredEndSpace,
applyWorkaroundForContentInsetHitTestBug,
contentInsetEndAdjustment,
+ contentInsetEndStaticAdjustment,
freeze,
keyboardLiftBehavior,
keyboardOffset,
@@ -109,11 +111,15 @@ var KeyboardAwareLegendList = typedForwardRef(function KeyboardAwareLegendList2(
includeInEndInset: true,
onSizeChanged: (size) => {
var _a;
- blankSpace.value = size;
+ // The anchored blank is sized against the ADJUSTED viewport, but the
+ // scroll component writes it as a raw contentInset that UIKit tops up
+ // with the safe-area bottom — write it net of that or the end rest
+ // (and the anchored message) sinks one safe-area under the header.
+ blankSpace.value = size > 0 ? Math.max(0, size - (adjustedInsetCompensation || 0)) : 0;
(_a = anchoredEndSpace.onSizeChanged) == null ? void 0 : _a.call(anchoredEndSpace, size);
}
};
- }, [anchoredEndSpace, blankSpace]);
+ }, [adjustedInsetCompensation, anchoredEndSpace, blankSpace]);
const onContentInsetChange = React.useCallback((insets) => {
var _a;
(_a = refLegendList.current) == null ? void 0 : _a.reportContentInset(insets);
@@ -124,6 +130,7 @@ var KeyboardAwareLegendList = typedForwardRef(function KeyboardAwareLegendList2(
reactNativeKeyboardController.KeyboardChatScrollView,
{
...scrollProps,
+ adjustedInsetCompensation,
applyWorkaroundForContentInsetHitTestBug,
blankSpace,
extraContentPadding: contentInsetEndAdjustment,
@@ -135,6 +142,7 @@ var KeyboardAwareLegendList = typedForwardRef(function KeyboardAwareLegendList2(
);
},
[
+ adjustedInsetCompensation,
applyWorkaroundForContentInsetHitTestBug,
blankSpace,
contentInsetEndAdjustment,
@@ -149,6 +157,7 @@ var KeyboardAwareLegendList = typedForwardRef(function KeyboardAwareLegendList2(
AnimatedLegendListInternal,
{
anchoredEndSpace: anchoredEndSpaceWithBlankSpace,
+ contentInsetEndAdjustment: contentInsetEndStaticAdjustment,
ref: combinedRef,
renderScrollComponent: memoList,
...rest
diff --git a/keyboard.mjs b/keyboard.mjs
index c1dd270..cb0d142 100644
--- a/keyboard.mjs
+++ b/keyboard.mjs
@@ -12,19 +12,19 @@ if (typeof __DEV__ !== "undefined" && __DEV__ && !KeyboardChatScrollView) {
"[legend-list] KeyboardAwareLegendList requires a recent react-native-keyboard-controller with KeyboardChatScrollView. Please upgrade react-native-keyboard-controller to at least 1.21.7."
);
}
-function useKeyboardChatComposerInset(listRef, composerRef, initialHeight = 0) {
+function useKeyboardChatComposerInset(listRef, composerRef, initialHeight = 0, heightAdjustment = 0) {
const contentInsetEndAdjustment = useSharedValue(initialHeight);
const lastHeightRef = useRef(void 0);
const reportHeight = useCallback(
- (height) => {
+ (rawHeight) => {
+ const height = Math.max(0, rawHeight + heightAdjustment);
var _a;
if (Number.isFinite(height) && height !== lastHeightRef.current) {
lastHeightRef.current = height;
contentInsetEndAdjustment.value = height;
- (_a = listRef.current) == null ? void 0 : _a.reportContentInset({ bottom: height });
}
},
- [contentInsetEndAdjustment, listRef]
+ [contentInsetEndAdjustment, heightAdjustment, listRef]
);
useLayoutEffect(() => {
var _a;
@@ -63,9 +63,11 @@ function useKeyboardScrollToEnd({ freeze: freezeProp, listRef }) {
}
var KeyboardAwareLegendList = typedForwardRef(function KeyboardAwareLegendList2(props, forwardedRef) {
const {
+ adjustedInsetCompensation,
anchoredEndSpace,
applyWorkaroundForContentInsetHitTestBug,
contentInsetEndAdjustment,
+ contentInsetEndStaticAdjustment,
freeze,
keyboardLiftBehavior,
keyboardOffset,
@@ -88,11 +90,15 @@ var KeyboardAwareLegendList = typedForwardRef(function KeyboardAwareLegendList2(
includeInEndInset: true,
onSizeChanged: (size) => {
var _a;
- blankSpace.value = size;
+ // The anchored blank is sized against the ADJUSTED viewport, but the
+ // scroll component writes it as a raw contentInset that UIKit tops up
+ // with the safe-area bottom — write it net of that or the end rest
+ // (and the anchored message) sinks one safe-area under the header.
+ blankSpace.value = size > 0 ? Math.max(0, size - (adjustedInsetCompensation || 0)) : 0;
(_a = anchoredEndSpace.onSizeChanged) == null ? void 0 : _a.call(anchoredEndSpace, size);
}
};
- }, [anchoredEndSpace, blankSpace]);
+ }, [adjustedInsetCompensation, anchoredEndSpace, blankSpace]);
const onContentInsetChange = useCallback((insets) => {
var _a;
(_a = refLegendList.current) == null ? void 0 : _a.reportContentInset(insets);
@@ -103,6 +109,7 @@ var KeyboardAwareLegendList = typedForwardRef(function KeyboardAwareLegendList2(
KeyboardChatScrollView,
{
...scrollProps,
+ adjustedInsetCompensation,
applyWorkaroundForContentInsetHitTestBug,
blankSpace,
extraContentPadding: contentInsetEndAdjustment,
@@ -114,6 +121,7 @@ var KeyboardAwareLegendList = typedForwardRef(function KeyboardAwareLegendList2(
);
},
[
+ adjustedInsetCompensation,
applyWorkaroundForContentInsetHitTestBug,
blankSpace,
contentInsetEndAdjustment,
@@ -128,6 +136,7 @@ var KeyboardAwareLegendList = typedForwardRef(function KeyboardAwareLegendList2(
AnimatedLegendListInternal,
{
anchoredEndSpace: anchoredEndSpaceWithBlankSpace,
+ contentInsetEndAdjustment: contentInsetEndStaticAdjustment,
ref: combinedRef,
renderScrollComponent: memoList,
...rest
diff --git a/react-native.d.ts b/react-native.d.ts
index 72d3f59..435a5fc 100644
--- a/react-native.d.ts
+++ b/react-native.d.ts
@@ -284,6 +284,12 @@ interface LegendListSpecificProps<ItemT, TItemType extends string | undefined> {
* The adjustment is also rendered as real content padding so the browser scroll range includes it.
*/
contentInsetEndAdjustment?: number;
+ /**
+ * Width/height of a leading content inset applied natively outside the list's knowledge
+ * (e.g. iOS contentInsetAdjustmentBehavior="automatic" under a transparent header).
+ * Programmatic scrolls clamp to -adjustment instead of 0 so content can rest below the header.
+ */
+ contentInsetStartAdjustment?: number;
/**
* Number of columns to render items in.
* @default 1
diff --git a/react-native.js b/react-native.js
index 8d4ff89..18f0d62 100644
--- a/react-native.js
+++ b/react-native.js
@@ -1195,7 +1195,7 @@ function setInitialRenderState(ctx, {
if (didInitialScroll) {
state.didFinishInitialScroll = true;
}
- const isReadyToRender = Boolean(state.didContainersLayout && state.didFinishInitialScroll);
+ const isReadyToRender = Boolean(state.didContainersLayout && state.didFinishInitialScroll && !state.insetEndRevealHold);
if (isReadyToRender && !peek$(ctx, "readyToRender")) {
set$(ctx, "readyToRender", true);
setAdaptiveRender(ctx, "normal");
@@ -1480,18 +1480,23 @@ function calculateOffsetWithOffsetPosition(ctx, offsetParam, params) {
}
// src/core/clampScrollOffset.ts
+function getContentInsetStartAdjustment(ctx) {
+ const adjustment = ctx.state.props.contentInsetStartAdjustment;
+ return typeof adjustment === "number" && Number.isFinite(adjustment) ? Math.max(0, adjustment) : 0;
+}
function clampScrollOffset(ctx, offset, scrollTarget) {
const state = ctx.state;
const contentSize = getContentSize(ctx);
+ const minOffset = -getContentInsetStartAdjustment(ctx);
let clampedOffset = offset;
if (Number.isFinite(contentSize) && Number.isFinite(state.scrollLength) && (Platform.OS !== "android" || state.lastLayout)) {
- const baseMaxOffset = Math.max(0, contentSize - state.scrollLength);
+ const baseMaxOffset = Math.max(minOffset, contentSize - state.scrollLength);
const viewOffset = scrollTarget == null ? void 0 : scrollTarget.viewOffset;
const extraEndOffset = typeof viewOffset === "number" && viewOffset < 0 ? -viewOffset : 0;
const maxOffset = baseMaxOffset + extraEndOffset;
clampedOffset = Math.min(offset, maxOffset);
}
- clampedOffset = Math.max(0, clampedOffset);
+ clampedOffset = Math.max(minOffset, clampedOffset);
return clampedOffset;
}
@@ -1626,10 +1631,10 @@ function checkFinishedScrollFrame(ctx) {
finishScrollTo(ctx);
}
}
-function scrollToFallbackOffset(ctx, offset) {
+function scrollToFallbackOffset(ctx, offset, animated) {
var _a3;
(_a3 = ctx.state.refScroller.current) == null ? void 0 : _a3.scrollTo({
- animated: false,
+ animated: !!animated,
x: ctx.state.props.horizontal ? offset : 0,
y: ctx.state.props.horizontal ? 0 : offset
});
@@ -1676,7 +1681,10 @@ function checkFinishedScrollFallback(ctx) {
});
scheduleFallbackCheck(SILENT_INITIAL_SCROLL_RETRY_DELAY_MS);
} else if (shouldRetryUnalignedEndScroll) {
- scrollToFallbackOffset(ctx, completionState.clampedTargetOffset);
+ const isActivelyAnimatingToEnd = !!isStillScrollingTo.animated && Date.now() - state.scrollTime < 100;
+ if (!isActivelyAnimatingToEnd) {
+ scrollToFallbackOffset(ctx, completionState.clampedTargetOffset, !!isStillScrollingTo.animated);
+ }
scheduleFallbackCheck(100);
} else if (shouldFinishZeroTarget || shouldFinishAfterObservedScroll || canFinishInitialScrollWithoutNativeProgress || canFinishAfterSilentNativeDispatch || numChecks > maxChecks) {
finishScrollTo(ctx);
@@ -1737,9 +1745,18 @@ function doMaintainScrollAtEnd(ctx) {
}
state.pendingMaintainScrollAtEnd = false;
if (shouldMaintainScrollAtEnd) {
+ const maintainAnchoredEndSpace = state.props.anchoredEndSpace;
+ const maintainAnchorIndex = maintainAnchoredEndSpace == null ? void 0 : maintainAnchoredEndSpace.anchorIndex;
+ if (maintainAnchorIndex !== void 0 && maintainAnchorIndex >= 0 && maintainAnchorIndex < state.props.data.length && !areKnownOrFixedItemSizesAvailable(ctx, maintainAnchorIndex, state.props.data.length - 1)) {
+ return false;
+ }
const contentSize = getContentSize(ctx);
+ const maintainInsetStartAdjustment = getContentInsetStartAdjustment(ctx);
if (contentSize < state.scrollLength) {
- state.scroll = 0;
+ state.scroll = -maintainInsetStartAdjustment;
+ if (maintainInsetStartAdjustment > 0) {
+ return true;
+ }
}
if (!state.maintainingScrollAtEnd) {
const pendingState = maintainScrollAtEnd.animated ? "pending-animated" : "pending-instant";
@@ -1759,9 +1776,18 @@ function doMaintainScrollAtEnd(ctx) {
y: 0
});
} else {
- scroller == null ? void 0 : scroller.scrollToEnd({
- animated: maintainScrollAtEnd.animated
- });
+ const insetStartAdjustment = getContentInsetStartAdjustment(ctx);
+ if (insetStartAdjustment > 0) {
+ scroller == null ? void 0 : scroller.scrollTo({
+ animated: maintainScrollAtEnd.animated,
+ x: 0,
+ y: Math.max(-insetStartAdjustment, getContentSize(ctx) - state.scrollLength)
+ });
+ } else {
+ scroller == null ? void 0 : scroller.scrollToEnd({
+ animated: maintainScrollAtEnd.animated
+ });
+ }
}
setTimeout(
() => {
@@ -1888,7 +1914,9 @@ function getPredictedNativeClamp(state, unresolvedAmount, totalSize) {
if (Math.abs(unresolvedAmount) <= MVCP_POSITION_EPSILON) {
return 0;
}
- const maxScroll = Math.max(0, totalSize - state.scrollLength);
+ const insetStartAdjustment = state.props.contentInsetStartAdjustment;
+ const minScroll = typeof insetStartAdjustment === "number" && Number.isFinite(insetStartAdjustment) ? -Math.max(0, insetStartAdjustment) : 0;
+ const maxScroll = Math.max(minScroll, totalSize - state.scrollLength);
const clampDelta = maxScroll - state.scroll;
if (unresolvedAmount < 0) {
return Math.max(unresolvedAmount, Math.min(0, clampDelta));
@@ -1950,7 +1978,7 @@ function resolvePendingNativeMVCPAdjust(ctx, newScroll) {
settlePendingNativeMVCPAdjust(ctx, remainingAfterManual, nativeDelta);
return true;
}
- const expectedNativeClampScroll = Math.max(0, getContentSize(ctx) - state.scrollLength);
+ const expectedNativeClampScroll = Math.max(-getContentInsetStartAdjustment(ctx), getContentSize(ctx) - state.scrollLength);
const distanceToClamp = Math.abs(newScroll - expectedNativeClampScroll);
const isAtExpectedNativeClamp = distanceToClamp <= NATIVE_END_CLAMP_EPSILON;
if (isAtExpectedNativeClamp) {
@@ -2083,7 +2111,7 @@ function prepareMVCP(ctx, dataChanged) {
if (diff > 0) {
diff = Math.max(0, totalSize - state.scroll - state.scrollLength);
} else {
- const maxScroll = Math.max(0, totalSize - state.scrollLength);
+ const maxScroll = Math.max(-getContentInsetStartAdjustment(ctx), totalSize - state.scrollLength);
state.scroll = maxScroll;
state.scrollPending = maxScroll;
diff = 0;
@@ -2374,8 +2402,121 @@ function scrollToIndex(ctx, {
}
// src/core/initialScroll.ts
+var INSET_END_SETTLE_WATCHDOG_FRAMES = 150;
+var INSET_END_SETTLE_WATCHDOG_STABLE_FRAMES = 20;
+var INSET_END_REVEAL_STABLE_FRAMES = 3;
+var INSET_END_REVEAL_MAX_HOLD_FRAMES = 40;
+function startInsetEndSettleWatchdog(ctx) {
+ const state = ctx.state;
+ if (state.insetEndSettleWatchdogActive) {
+ return;
+ }
+ state.insetEndSettleWatchdogActive = true;
+ state.didUserDrag = false;
+ // Hold the readyToRender opacity gate until the end landing is stable, so
+ // the estimated-to-measured settle chase happens before first VISIBLE
+ // paint instead of in front of the user. Capped so slow measurement can
+ // never hide content for long.
+ state.insetEndRevealHold = true;
+ let frames = 0;
+ let settledFrames = 0;
+ let revealStableFrames = 0;
+ const releaseRevealHold = () => {
+ if (state.insetEndRevealHold) {
+ state.insetEndRevealHold = false;
+ setInitialRenderState(ctx, {});
+ }
+ };
+ // Revealing flips adaptive rendering to "normal", which re-renders rows and
+ // can move the end target one more time — do that upgrade while still
+ // hidden (phase 1), then require stability again before revealing (phase 2)
+ // so the first visible frame is the settled one.
+ let revealPhase = 1;
+ const onRevealStability = () => {
+ var _a3;
+ if (!state.insetEndRevealHold) {
+ return;
+ }
+ if (revealPhase === 1) {
+ revealPhase = 2;
+ revealStableFrames = 0;
+ setAdaptiveRender(ctx, "normal");
+ (_a3 = state.triggerCalculateItemsInView) == null ? void 0 : _a3.call(state);
+ return;
+ }
+ releaseRevealHold();
+ };
+ const tick = () => {
+ // The user owns the scroll from their first drag — a re-pin here would
+ // pin the list under their finger.
+ if (frames++ >= INSET_END_SETTLE_WATCHDOG_FRAMES || settledFrames >= INSET_END_SETTLE_WATCHDOG_STABLE_FRAMES || state.didUserDrag || !ctx.state || ctx.state !== state) {
+ state.insetEndSettleWatchdogActive = false;
+ releaseRevealHold();
+ return;
+ }
+ if (frames >= INSET_END_REVEAL_MAX_HOLD_FRAMES) {
+ releaseRevealHold();
+ }
+ const insetStartAdjustment = getContentInsetStartAdjustment(ctx);
+ const contentSize = getContentSize(ctx);
+ const scrollLength = state.scrollLength;
+ if (insetStartAdjustment > 0 && scrollLength > 0 && Number.isFinite(contentSize) && contentSize > scrollLength && !state.scrollingTo && !state.maintainingScrollAtEnd) {
+ const endOffset = Math.max(-insetStartAdjustment, contentSize - scrollLength);
+ const distance = endOffset - state.scroll;
+ // Estimated row sizes converging to measured ones can strand the initial
+ // end landing when the library's own end-anchor bookkeeping gives up.
+ // While still near the end (never fighting a user who scrolled away),
+ // re-pin to the current true end until sizes stop changing.
+ if (Math.abs(distance) > 2 && Math.abs(distance) <= scrollLength * 0.5) {
+ settledFrames = 0;
+ revealStableFrames = 0;
+ const scroller = state.refScroller.current;
+ if (scroller) {
+ scroller.scrollTo({ animated: false, x: 0, y: endOffset });
+ }
+ } else {
+ settledFrames++;
+ revealStableFrames++;
+ if (revealStableFrames >= INSET_END_REVEAL_STABLE_FRAMES) {
+ onRevealStability();
+ }
+ }
+ } else {
+ // Conditions that make re-pinning unnecessary (underflow, in-flight
+ // programmatic scroll) count toward stability for the reveal.
+ revealStableFrames++;
+ if (revealStableFrames >= INSET_END_REVEAL_STABLE_FRAMES) {
+ onRevealStability();
+ }
+ }
+ requestAnimationFrame(tick);
+ };
+ requestAnimationFrame(tick);
+}
function dispatchInitialScroll(ctx, params) {
const { forceScroll, resolvedOffset, target, waitForCompletionFrame } = params;
+ const insetStartAdjustment = getContentInsetStartAdjustment(ctx);
+ if (insetStartAdjustment > 0 && ctx.state.props.data.length > 0) {
+ if (ctx.state.scrollLength <= 0) {
+ // The scroll length is unknown, so the resolved target is meaningless;
+ // the initial-scroll machinery re-advances after layout.
+ return;
+ }
+ if (resolvedOffset <= -insetStartAdjustment + 1 && !ctx.state.didDispatchInsetInitialScroll) {
+ // Content underflows the viewport and nothing has scrolled yet: the
+ // untouched native rest position (UIKit's adjustedContentInset) IS the
+ // end position. Dispatching a negative scroll here would race UIKit's
+ // inset application during screen attach, so just finish the session.
+ finishInitialScroll(ctx, {
+ resolvedOffset
+ });
+ return;
+ }
+ ctx.state.didDispatchInsetInitialScroll = true;
+ if (target.viewPosition === 1) {
+ startInsetEndSettleWatchdog(ctx);
+ }
+ }
const requestedIndex = target.index;
const index = requestedIndex !== void 0 ? clampScrollIndex(requestedIndex, ctx.state.props.data.length) : void 0;
const itemSize = getItemSizeAtIndex(ctx, index);
@@ -2804,7 +2945,9 @@ function clearFinishedBootstrapInitialScrollTargetIfMovedAway(ctx) {
return;
}
if (didFinishedInitialScrollMoveAwayFromTarget(ctx, initialScroll)) {
- const shouldKeepEndTargetAlive = isRetargetableBottomAlignedInitialScrollTarget(initialScroll) && peek$(ctx, "isAtEnd");
+ const endTargetDistanceFromEnd = getContentSize(ctx) - state.scroll - state.scrollLength - getContentInsetEnd(ctx);
+ const isNearEndForInsetList = getContentInsetStartAdjustment(ctx) > 0 && Number.isFinite(endTargetDistanceFromEnd) && endTargetDistanceFromEnd <= state.scrollLength * 0.5;
+ const shouldKeepEndTargetAlive = isRetargetableBottomAlignedInitialScrollTarget(initialScroll) && (peek$(ctx, "isAtEnd") || isNearEndForInsetList);
if (!shouldKeepEndTargetAlive) {
if (shouldPreserveInitialScrollForFooterLayout(initialScroll)) {
clearPendingInitialScrollFooterLayout(ctx, {
@@ -4646,7 +4789,8 @@ function maybeUpdateAnchoredEndSpace(ctx) {
}
contentBelowAnchor += footerSize + stylePaddingBottom;
isReady = !hasUnknownTailSize;
- nextSize = hasUnknownTailSize ? previousSize || 0 : Math.max(0, state.scrollLength - contentBelowAnchor - anchorOffset);
+ const knownSizeBound = Math.max(0, state.scrollLength - contentBelowAnchor - anchorOffset);
+ nextSize = hasUnknownTailSize ? Math.min(previousSize || 0, knownSizeBound) : knownSizeBound;
} else if (anchorIndex >= 0) {
isReady = false;
}
@@ -4664,6 +4808,12 @@ function maybeUpdateAnchoredEndSpace(ctx) {
updateScroll(ctx, state.scroll, true);
}
(_b = anchoredEndSpace == null ? void 0 : anchoredEndSpace.onReady) == null ? void 0 : _b.call(anchoredEndSpace, { anchorIndex: nextAnchorIndex, anchorKey: nextAnchorKey, size: nextSize });
+ } else if (!isReady && didSizeChange && nextSize < (previousSize || 0)) {
+ set$(ctx, "anchoredEndSpaceSize", nextSize);
+ (_a3 = anchoredEndSpace == null ? void 0 : anchoredEndSpace.onSizeChanged) == null ? void 0 : _a3.call(anchoredEndSpace, nextSize);
+ if (anchoredEndSpace == null ? void 0 : anchoredEndSpace.includeInEndInset) {
+ updateScroll(ctx, state.scroll, true);
+ }
}
return nextSize;
}
@@ -6462,6 +6612,7 @@ var LegendListInner = typedForwardRef(function LegendListInner2(props, forwarded
dataVersion,
drawDistance = 250,
contentInsetEndAdjustment,
+ contentInsetStartAdjustment,
estimatedItemSize = 100,
estimatedListSize,
extraData,
@@ -6492,6 +6643,7 @@ var LegendListInner = typedForwardRef(function LegendListInner2(props, forwarded
onLayout: onLayoutProp,
onLoad,
onMomentumScrollEnd,
+ onScrollBeginDrag,
onRefresh,
onScroll: onScrollProp,
onStartReached,
@@ -6710,6 +6862,7 @@ var LegendListInner = typedForwardRef(function LegendListInner2(props, forwarded
contentContainerAlignItems: contentContainerStyle.alignItems,
contentInset,
contentInsetEndAdjustment: contentInsetEndAdjustmentResolved,
+ contentInsetStartAdjustment,
data: dataProp,
dataVersion,
drawDistance,
@@ -6789,6 +6942,13 @@ var LegendListInner = typedForwardRef(function LegendListInner2(props, forwarded
return void 0;
}
const resolvedOffset = (_a4 = initialScroll.contentOffset) != null ? _a4 : resolveInitialScrollOffset(ctx, initialScroll);
+ if (getContentInsetStartAdjustment(ctx) > 0) {
+ // With a native leading inset (transparent header + automatic insets),
+ // any mount-time contentOffset races UIKit's adjustedContentInset
+ // application. The gated initial-scroll dispatch positions the list once
+ // real sizes are known instead.
+ return void 0;
+ }
return usesBootstrapInitialScroll && ((_b2 = state.initialScrollSession) == null ? void 0 : _b2.kind) === "bootstrap" && Platform.OS === "web" ? void 0 : resolvedOffset;
}, [usesBootstrapInitialScroll]);
React2.useLayoutEffect(() => {
@@ -6995,6 +7155,12 @@ var LegendListInner = typedForwardRef(function LegendListInner2(props, forwarded
onMomentumScrollEnd(event);
}
},
+ onScrollBeginDrag: (event) => {
+ ctx.state.didUserDrag = true;
+ if (onScrollBeginDrag) {
+ onScrollBeginDrag(event);
+ }
+ },
onScroll: (event) => onScroll(ctx, event)
}),
[]
@@ -7019,6 +7185,7 @@ var LegendListInner = typedForwardRef(function LegendListInner2(props, forwarded
onLayout,
onLayoutFooter,
onMomentumScrollEnd: fns.onMomentumScrollEnd,
+ onScrollBeginDrag: fns.onScrollBeginDrag,
onScroll: onScrollHandler,
recycleItems,
refreshControl: refreshControlElement ? stylePaddingTopState > 0 ? React2__namespace.cloneElement(refreshControlElement, {
diff --git a/react-native.mjs b/react-native.mjs
index 2e96ca7..6e8913e 100644
--- a/react-native.mjs
+++ b/react-native.mjs
@@ -1174,7 +1174,7 @@ function setInitialRenderState(ctx, {
if (didInitialScroll) {
state.didFinishInitialScroll = true;
}
- const isReadyToRender = Boolean(state.didContainersLayout && state.didFinishInitialScroll);
+ const isReadyToRender = Boolean(state.didContainersLayout && state.didFinishInitialScroll && !state.insetEndRevealHold);
if (isReadyToRender && !peek$(ctx, "readyToRender")) {
set$(ctx, "readyToRender", true);
setAdaptiveRender(ctx, "normal");
@@ -1459,18 +1459,23 @@ function calculateOffsetWithOffsetPosition(ctx, offsetParam, params) {
}
// src/core/clampScrollOffset.ts
+function getContentInsetStartAdjustment(ctx) {
+ const adjustment = ctx.state.props.contentInsetStartAdjustment;
+ return typeof adjustment === "number" && Number.isFinite(adjustment) ? Math.max(0, adjustment) : 0;
+}
function clampScrollOffset(ctx, offset, scrollTarget) {
const state = ctx.state;
const contentSize = getContentSize(ctx);
+ const minOffset = -getContentInsetStartAdjustment(ctx);
let clampedOffset = offset;
if (Number.isFinite(contentSize) && Number.isFinite(state.scrollLength) && (Platform.OS !== "android" || state.lastLayout)) {
- const baseMaxOffset = Math.max(0, contentSize - state.scrollLength);
+ const baseMaxOffset = Math.max(minOffset, contentSize - state.scrollLength);
const viewOffset = scrollTarget == null ? void 0 : scrollTarget.viewOffset;
const extraEndOffset = typeof viewOffset === "number" && viewOffset < 0 ? -viewOffset : 0;
const maxOffset = baseMaxOffset + extraEndOffset;
clampedOffset = Math.min(offset, maxOffset);
}
- clampedOffset = Math.max(0, clampedOffset);
+ clampedOffset = Math.max(minOffset, clampedOffset);
return clampedOffset;
}
@@ -1605,10 +1610,10 @@ function checkFinishedScrollFrame(ctx) {
finishScrollTo(ctx);
}
}
-function scrollToFallbackOffset(ctx, offset) {
+function scrollToFallbackOffset(ctx, offset, animated) {
var _a3;
(_a3 = ctx.state.refScroller.current) == null ? void 0 : _a3.scrollTo({
- animated: false,
+ animated: !!animated,
x: ctx.state.props.horizontal ? offset : 0,
y: ctx.state.props.horizontal ? 0 : offset
});
@@ -1655,7 +1660,10 @@ function checkFinishedScrollFallback(ctx) {
});
scheduleFallbackCheck(SILENT_INITIAL_SCROLL_RETRY_DELAY_MS);
} else if (shouldRetryUnalignedEndScroll) {
- scrollToFallbackOffset(ctx, completionState.clampedTargetOffset);
+ const isActivelyAnimatingToEnd = !!isStillScrollingTo.animated && Date.now() - state.scrollTime < 100;
+ if (!isActivelyAnimatingToEnd) {
+ scrollToFallbackOffset(ctx, completionState.clampedTargetOffset, !!isStillScrollingTo.animated);
+ }
scheduleFallbackCheck(100);
} else if (shouldFinishZeroTarget || shouldFinishAfterObservedScroll || canFinishInitialScrollWithoutNativeProgress || canFinishAfterSilentNativeDispatch || numChecks > maxChecks) {
finishScrollTo(ctx);
@@ -1716,9 +1724,18 @@ function doMaintainScrollAtEnd(ctx) {
}
state.pendingMaintainScrollAtEnd = false;
if (shouldMaintainScrollAtEnd) {
+ const maintainAnchoredEndSpace = state.props.anchoredEndSpace;
+ const maintainAnchorIndex = maintainAnchoredEndSpace == null ? void 0 : maintainAnchoredEndSpace.anchorIndex;
+ if (maintainAnchorIndex !== void 0 && maintainAnchorIndex >= 0 && maintainAnchorIndex < state.props.data.length && !areKnownOrFixedItemSizesAvailable(ctx, maintainAnchorIndex, state.props.data.length - 1)) {
+ return false;
+ }
const contentSize = getContentSize(ctx);
+ const maintainInsetStartAdjustment = getContentInsetStartAdjustment(ctx);
if (contentSize < state.scrollLength) {
- state.scroll = 0;
+ state.scroll = -maintainInsetStartAdjustment;
+ if (maintainInsetStartAdjustment > 0) {
+ return true;
+ }
}
if (!state.maintainingScrollAtEnd) {
const pendingState = maintainScrollAtEnd.animated ? "pending-animated" : "pending-instant";
@@ -1738,9 +1755,18 @@ function doMaintainScrollAtEnd(ctx) {
y: 0
});
} else {
- scroller == null ? void 0 : scroller.scrollToEnd({
- animated: maintainScrollAtEnd.animated
- });
+ const insetStartAdjustment = getContentInsetStartAdjustment(ctx);
+ if (insetStartAdjustment > 0) {
+ scroller == null ? void 0 : scroller.scrollTo({
+ animated: maintainScrollAtEnd.animated,
+ x: 0,
+ y: Math.max(-insetStartAdjustment, getContentSize(ctx) - state.scrollLength)
+ });
+ } else {
+ scroller == null ? void 0 : scroller.scrollToEnd({
+ animated: maintainScrollAtEnd.animated
+ });
+ }
}
setTimeout(
() => {
@@ -1867,7 +1893,9 @@ function getPredictedNativeClamp(state, unresolvedAmount, totalSize) {
if (Math.abs(unresolvedAmount) <= MVCP_POSITION_EPSILON) {
return 0;
}
- const maxScroll = Math.max(0, totalSize - state.scrollLength);
+ const insetStartAdjustment = state.props.contentInsetStartAdjustment;
+ const minScroll = typeof insetStartAdjustment === "number" && Number.isFinite(insetStartAdjustment) ? -Math.max(0, insetStartAdjustment) : 0;
+ const maxScroll = Math.max(minScroll, totalSize - state.scrollLength);
const clampDelta = maxScroll - state.scroll;
if (unresolvedAmount < 0) {
return Math.max(unresolvedAmount, Math.min(0, clampDelta));
@@ -1929,7 +1957,7 @@ function resolvePendingNativeMVCPAdjust(ctx, newScroll) {
settlePendingNativeMVCPAdjust(ctx, remainingAfterManual, nativeDelta);
return true;
}
- const expectedNativeClampScroll = Math.max(0, getContentSize(ctx) - state.scrollLength);
+ const expectedNativeClampScroll = Math.max(-getContentInsetStartAdjustment(ctx), getContentSize(ctx) - state.scrollLength);
const distanceToClamp = Math.abs(newScroll - expectedNativeClampScroll);
const isAtExpectedNativeClamp = distanceToClamp <= NATIVE_END_CLAMP_EPSILON;
if (isAtExpectedNativeClamp) {
@@ -2062,7 +2090,7 @@ function prepareMVCP(ctx, dataChanged) {
if (diff > 0) {
diff = Math.max(0, totalSize - state.scroll - state.scrollLength);
} else {
- const maxScroll = Math.max(0, totalSize - state.scrollLength);
+ const maxScroll = Math.max(-getContentInsetStartAdjustment(ctx), totalSize - state.scrollLength);
state.scroll = maxScroll;
state.scrollPending = maxScroll;
diff = 0;
@@ -2353,8 +2381,121 @@ function scrollToIndex(ctx, {
}
// src/core/initialScroll.ts
+var INSET_END_SETTLE_WATCHDOG_FRAMES = 150;
+var INSET_END_SETTLE_WATCHDOG_STABLE_FRAMES = 20;
+var INSET_END_REVEAL_STABLE_FRAMES = 3;
+var INSET_END_REVEAL_MAX_HOLD_FRAMES = 40;
+function startInsetEndSettleWatchdog(ctx) {
+ const state = ctx.state;
+ if (state.insetEndSettleWatchdogActive) {
+ return;
+ }
+ state.insetEndSettleWatchdogActive = true;
+ state.didUserDrag = false;
+ // Hold the readyToRender opacity gate until the end landing is stable, so
+ // the estimated-to-measured settle chase happens before first VISIBLE
+ // paint instead of in front of the user. Capped so slow measurement can
+ // never hide content for long.
+ state.insetEndRevealHold = true;
+ let frames = 0;
+ let settledFrames = 0;
+ let revealStableFrames = 0;
+ const releaseRevealHold = () => {
+ if (state.insetEndRevealHold) {
+ state.insetEndRevealHold = false;
+ setInitialRenderState(ctx, {});
+ }
+ };
+ // Revealing flips adaptive rendering to "normal", which re-renders rows and
+ // can move the end target one more time — do that upgrade while still
+ // hidden (phase 1), then require stability again before revealing (phase 2)
+ // so the first visible frame is the settled one.
+ let revealPhase = 1;
+ const onRevealStability = () => {
+ var _a3;
+ if (!state.insetEndRevealHold) {
+ return;
+ }
+ if (revealPhase === 1) {
+ revealPhase = 2;
+ revealStableFrames = 0;
+ setAdaptiveRender(ctx, "normal");
+ (_a3 = state.triggerCalculateItemsInView) == null ? void 0 : _a3.call(state);
+ return;
+ }
+ releaseRevealHold();
+ };
+ const tick = () => {
+ // The user owns the scroll from their first drag — a re-pin here would
+ // pin the list under their finger.
+ if (frames++ >= INSET_END_SETTLE_WATCHDOG_FRAMES || settledFrames >= INSET_END_SETTLE_WATCHDOG_STABLE_FRAMES || state.didUserDrag || !ctx.state || ctx.state !== state) {
+ state.insetEndSettleWatchdogActive = false;
+ releaseRevealHold();
+ return;
+ }
+ if (frames >= INSET_END_REVEAL_MAX_HOLD_FRAMES) {
+ releaseRevealHold();
+ }
+ const insetStartAdjustment = getContentInsetStartAdjustment(ctx);
+ const contentSize = getContentSize(ctx);
+ const scrollLength = state.scrollLength;
+ if (insetStartAdjustment > 0 && scrollLength > 0 && Number.isFinite(contentSize) && contentSize > scrollLength && !state.scrollingTo && !state.maintainingScrollAtEnd) {
+ const endOffset = Math.max(-insetStartAdjustment, contentSize - scrollLength);
+ const distance = endOffset - state.scroll;
+ // Estimated row sizes converging to measured ones can strand the initial
+ // end landing when the library's own end-anchor bookkeeping gives up.
+ // While still near the end (never fighting a user who scrolled away),
+ // re-pin to the current true end until sizes stop changing.
+ if (Math.abs(distance) > 2 && Math.abs(distance) <= scrollLength * 0.5) {
+ settledFrames = 0;
+ revealStableFrames = 0;
+ const scroller = state.refScroller.current;
+ if (scroller) {
+ scroller.scrollTo({ animated: false, x: 0, y: endOffset });
+ }
+ } else {
+ settledFrames++;
+ revealStableFrames++;
+ if (revealStableFrames >= INSET_END_REVEAL_STABLE_FRAMES) {
+ onRevealStability();
+ }
+ }
+ } else {
+ // Conditions that make re-pinning unnecessary (underflow, in-flight
+ // programmatic scroll) count toward stability for the reveal.
+ revealStableFrames++;
+ if (revealStableFrames >= INSET_END_REVEAL_STABLE_FRAMES) {
+ onRevealStability();
+ }
+ }
+ requestAnimationFrame(tick);
+ };
+ requestAnimationFrame(tick);
+}
function dispatchInitialScroll(ctx, params) {
const { forceScroll, resolvedOffset, target, waitForCompletionFrame } = params;
+ const insetStartAdjustment = getContentInsetStartAdjustment(ctx);
+ if (insetStartAdjustment > 0 && ctx.state.props.data.length > 0) {
+ if (ctx.state.scrollLength <= 0) {
+ // The scroll length is unknown, so the resolved target is meaningless;
+ // the initial-scroll machinery re-advances after layout.
+ return;
+ }
+ if (resolvedOffset <= -insetStartAdjustment + 1 && !ctx.state.didDispatchInsetInitialScroll) {
+ // Content underflows the viewport and nothing has scrolled yet: the
+ // untouched native rest position (UIKit's adjustedContentInset) IS the
+ // end position. Dispatching a negative scroll here would race UIKit's
+ // inset application during screen attach, so just finish the session.
+ finishInitialScroll(ctx, {
+ resolvedOffset
+ });
+ return;
+ }
+ ctx.state.didDispatchInsetInitialScroll = true;
+ if (target.viewPosition === 1) {
+ startInsetEndSettleWatchdog(ctx);
+ }
+ }
const requestedIndex = target.index;
const index = requestedIndex !== void 0 ? clampScrollIndex(requestedIndex, ctx.state.props.data.length) : void 0;
const itemSize = getItemSizeAtIndex(ctx, index);
@@ -2783,7 +2924,9 @@ function clearFinishedBootstrapInitialScrollTargetIfMovedAway(ctx) {
return;
}
if (didFinishedInitialScrollMoveAwayFromTarget(ctx, initialScroll)) {
- const shouldKeepEndTargetAlive = isRetargetableBottomAlignedInitialScrollTarget(initialScroll) && peek$(ctx, "isAtEnd");
+ const endTargetDistanceFromEnd = getContentSize(ctx) - state.scroll - state.scrollLength - getContentInsetEnd(ctx);
+ const isNearEndForInsetList = getContentInsetStartAdjustment(ctx) > 0 && Number.isFinite(endTargetDistanceFromEnd) && endTargetDistanceFromEnd <= state.scrollLength * 0.5;
+ const shouldKeepEndTargetAlive = isRetargetableBottomAlignedInitialScrollTarget(initialScroll) && (peek$(ctx, "isAtEnd") || isNearEndForInsetList);
if (!shouldKeepEndTargetAlive) {
if (shouldPreserveInitialScrollForFooterLayout(initialScroll)) {
clearPendingInitialScrollFooterLayout(ctx, {
@@ -4625,7 +4768,8 @@ function maybeUpdateAnchoredEndSpace(ctx) {
}
contentBelowAnchor += footerSize + stylePaddingBottom;
isReady = !hasUnknownTailSize;
- nextSize = hasUnknownTailSize ? previousSize || 0 : Math.max(0, state.scrollLength - contentBelowAnchor - anchorOffset);
+ const knownSizeBound = Math.max(0, state.scrollLength - contentBelowAnchor - anchorOffset);
+ nextSize = hasUnknownTailSize ? Math.min(previousSize || 0, knownSizeBound) : knownSizeBound;
} else if (anchorIndex >= 0) {
isReady = false;
}
@@ -4643,6 +4787,12 @@ function maybeUpdateAnchoredEndSpace(ctx) {
updateScroll(ctx, state.scroll, true);
}
(_b = anchoredEndSpace == null ? void 0 : anchoredEndSpace.onReady) == null ? void 0 : _b.call(anchoredEndSpace, { anchorIndex: nextAnchorIndex, anchorKey: nextAnchorKey, size: nextSize });
+ } else if (!isReady && didSizeChange && nextSize < (previousSize || 0)) {
+ set$(ctx, "anchoredEndSpaceSize", nextSize);
+ (_a3 = anchoredEndSpace == null ? void 0 : anchoredEndSpace.onSizeChanged) == null ? void 0 : _a3.call(anchoredEndSpace, nextSize);
+ if (anchoredEndSpace == null ? void 0 : anchoredEndSpace.includeInEndInset) {
+ updateScroll(ctx, state.scroll, true);
+ }
}
return nextSize;
}
@@ -6441,6 +6591,7 @@ var LegendListInner = typedForwardRef(function LegendListInner2(props, forwarded
dataVersion,
drawDistance = 250,
contentInsetEndAdjustment,
+ contentInsetStartAdjustment,
estimatedItemSize = 100,
estimatedListSize,
extraData,
@@ -6471,6 +6622,7 @@ var LegendListInner = typedForwardRef(function LegendListInner2(props, forwarded
onLayout: onLayoutProp,
onLoad,
onMomentumScrollEnd,
+ onScrollBeginDrag,
onRefresh,
onScroll: onScrollProp,
onStartReached,
@@ -6689,6 +6841,7 @@ var LegendListInner = typedForwardRef(function LegendListInner2(props, forwarded
contentContainerAlignItems: contentContainerStyle.alignItems,
contentInset,
contentInsetEndAdjustment: contentInsetEndAdjustmentResolved,
+ contentInsetStartAdjustment,
data: dataProp,
dataVersion,
drawDistance,
@@ -6768,6 +6921,13 @@ var LegendListInner = typedForwardRef(function LegendListInner2(props, forwarded
return void 0;
}
const resolvedOffset = (_a4 = initialScroll.contentOffset) != null ? _a4 : resolveInitialScrollOffset(ctx, initialScroll);
+ if (getContentInsetStartAdjustment(ctx) > 0) {
+ // With a native leading inset (transparent header + automatic insets),
+ // any mount-time contentOffset races UIKit's adjustedContentInset
+ // application. The gated initial-scroll dispatch positions the list once
+ // real sizes are known instead.
+ return void 0;
+ }
return usesBootstrapInitialScroll && ((_b2 = state.initialScrollSession) == null ? void 0 : _b2.kind) === "bootstrap" && Platform.OS === "web" ? void 0 : resolvedOffset;
}, [usesBootstrapInitialScroll]);
useLayoutEffect(() => {
@@ -6974,6 +7134,12 @@ var LegendListInner = typedForwardRef(function LegendListInner2(props, forwarded
onMomentumScrollEnd(event);
}
},
+ onScrollBeginDrag: (event) => {
+ ctx.state.didUserDrag = true;
+ if (onScrollBeginDrag) {
+ onScrollBeginDrag(event);
+ }
+ },
onScroll: (event) => onScroll(ctx, event)
}),
[]
@@ -6998,6 +7164,7 @@ var LegendListInner = typedForwardRef(function LegendListInner2(props, forwarded
onLayout,
onLayoutFooter,
onMomentumScrollEnd: fns.onMomentumScrollEnd,
+ onScrollBeginDrag: fns.onScrollBeginDrag,
onScroll: onScrollHandler,
recycleItems,
refreshControl: refreshControlElement ? stylePaddingTopState > 0 ? React2.cloneElement(refreshControlElement, {
diff --git a/reanimated.d.ts b/reanimated.d.ts
index 7e2d11f..d5b0d66 100644
--- a/reanimated.d.ts
+++ b/reanimated.d.ts
@@ -285,6 +285,12 @@ interface LegendListSpecificProps<ItemT, TItemType extends string | undefined> {
* The adjustment is also rendered as real content padding so the browser scroll range includes it.
*/
contentInsetEndAdjustment?: number;
+ /**
+ * Width/height of a leading content inset applied natively outside the list's knowledge
+ * (e.g. iOS contentInsetAdjustmentBehavior="automatic" under a transparent header).
+ * Programmatic scrolls clamp to -adjustment instead of 0 so content can rest below the header.
+ */
+ contentInsetStartAdjustment?: number;
/**
* Number of columns to render items in.
* @default 1
+483
View File
@@ -0,0 +1,483 @@
diff --git a/lib/commonjs/components/KeyboardChatScrollView/index.js b/lib/commonjs/components/KeyboardChatScrollView/index.js
index db8cfb1d289f91563f13c4dd842c783c99facc32..940e1dd80c6c9dfc42eab916445be414372ce52e 100644
--- a/lib/commonjs/components/KeyboardChatScrollView/index.js
+++ b/lib/commonjs/components/KeyboardChatScrollView/index.js
@@ -26,9 +26,11 @@ const KeyboardChatScrollView = /*#__PURE__*/(0, _react.forwardRef)(({
offset = 0,
extraContentPadding = ZERO_CONTENT_PADDING,
blankSpace = ZERO_BLANK_SPACE,
+ adjustedInsetCompensation = 0,
applyWorkaroundForContentInsetHitTestBug = false,
onLayout: onLayoutProp,
onContentSizeChange: onContentSizeChangeProp,
+ onContentInsetChange,
onEndVisible,
...rest
}, ref) => {
@@ -50,13 +52,15 @@ const KeyboardChatScrollView = /*#__PURE__*/(0, _react.forwardRef)(({
freeze: freezeSV,
offset,
blankSpace,
- extraContentPadding
+ extraContentPadding,
+ adjustedInsetCompensation
});
(0, _useExtraContentPadding.useExtraContentPadding)({
scrollViewRef,
extraContentPadding,
keyboardPadding: padding,
blankSpace,
+ adjustedInsetCompensation,
scroll,
layout,
size,
@@ -82,10 +86,21 @@ const KeyboardChatScrollView = /*#__PURE__*/(0, _react.forwardRef)(({
// a bug for you, please open an issue.
const totalPadding = (0, _reactNativeReanimated.useDerivedValue)(() => Math.min(layout.value.height, Math.max(blankSpace.value, padding.value + extraContentPadding.value)));
+ // Mirror the effective bottom padding (keyboard + composer + blank floor)
+ // to the consumer - a virtualized list needs it in its own scroll math or
+ // its end/maintain targets point at the under-the-keyboard resting offset.
+ (0, _reactNativeReanimated.useAnimatedReaction)(() => totalPadding.value, (current, previous) => {
+ if (onContentInsetChange && current !== previous) {
+ (0, _reactNativeReanimated.runOnJS)(onContentInsetChange)({
+ bottom: current
+ });
+ }
+ }, [onContentInsetChange]);
+
// Scroll indicator inset = keyboard + extraContentPadding (excludes blankSpace).
// Apps that render into the unsafe area can supply a negative
// scrollIndicatorInsets adjustment at the application layer.
- const indicatorPadding = (0, _reactNativeReanimated.useDerivedValue)(() => padding.value + extraContentPadding.value);
+ const indicatorPadding = (0, _reactNativeReanimated.useDerivedValue)(() => padding.value);
const onLayout = (0, _react.useCallback)(e => {
onLayoutInternal(e);
onLayoutProp === null || onLayoutProp === void 0 || onLayoutProp(e);
diff --git a/lib/commonjs/components/KeyboardChatScrollView/useChatKeyboard/index.ios.js b/lib/commonjs/components/KeyboardChatScrollView/useChatKeyboard/index.ios.js
index 2073da84b8b2be291aa3181700c2b18a75d0fc56..f43f2efdc4f0eda0460720839544dc6e7f4a54e0 100644
--- a/lib/commonjs/components/KeyboardChatScrollView/useChatKeyboard/index.ios.js
+++ b/lib/commonjs/components/KeyboardChatScrollView/useChatKeyboard/index.ios.js
@@ -32,7 +32,8 @@ function useChatKeyboard(scrollViewRef, options) {
freeze,
offset,
blankSpace,
- extraContentPadding
+ extraContentPadding,
+ adjustedInsetCompensation
} = options;
const padding = (0, _reactNativeReanimated.useSharedValue)(0);
const currentHeight = (0, _reactNativeReanimated.useSharedValue)(0);
@@ -66,7 +67,7 @@ function useChatKeyboard(scrollViewRef, options) {
const visiblePadding = visibleFraction * blankSpace.value;
const minimumPaddingAbsorbed = Math.max(0, visiblePadding - extraContentPadding.value);
const scrollEffective = (0, _helpers.getScrollEffective)(effective, minimumPaddingAbsorbed);
- const actualTotalPadding = Math.max(blankSpace.value, effective + extraContentPadding.value);
+ const actualTotalPadding = Math.max(blankSpace.value, effective + extraContentPadding.value) + adjustedInsetCompensation;
// persistent mode: when keyboard shrinks, clamp to valid range
if (keyboardLiftBehavior === "persistent" && effective < padding.value) {
@@ -134,7 +135,7 @@ function useChatKeyboard(scrollViewRef, options) {
const effective = (0, _helpers.getEffectiveHeight)(e.height, targetKeyboardHeight.value, offset);
padding.value = effective;
}
- }, [inverted, keyboardLiftBehavior, offset, extraContentPadding]);
+ }, [inverted, keyboardLiftBehavior, offset, extraContentPadding, adjustedInsetCompensation]);
return {
padding,
currentHeight,
diff --git a/lib/commonjs/components/KeyboardChatScrollView/useExtraContentPadding/index.js b/lib/commonjs/components/KeyboardChatScrollView/useExtraContentPadding/index.js
index 0d50bdfeb7bbc5c14a31ed344f8a690e4fd340b3..22ca193257ab0068f732c088b09145dabf39a05e 100644
--- a/lib/commonjs/components/KeyboardChatScrollView/useExtraContentPadding/index.js
+++ b/lib/commonjs/components/KeyboardChatScrollView/useExtraContentPadding/index.js
@@ -29,6 +29,7 @@ function useExtraContentPadding(options) {
extraContentPadding,
keyboardPadding,
blankSpace,
+ adjustedInsetCompensation,
scroll,
layout,
size,
@@ -68,8 +69,8 @@ function useExtraContentPadding(options) {
}
// Compute effective delta considering blankSpace floor
- const previousTotal = Math.max(blankSpace.value, keyboardPadding.value + previous);
- const currentTotal = Math.max(blankSpace.value, keyboardPadding.value + current);
+ const previousTotal = Math.max(blankSpace.value, keyboardPadding.value + previous) + adjustedInsetCompensation;
+ const currentTotal = Math.max(blankSpace.value, keyboardPadding.value + current) + adjustedInsetCompensation;
const effectiveDelta = currentTotal - previousTotal;
if (effectiveDelta === 0) {
// blankSpace absorbed the change
@@ -92,6 +93,6 @@ function useExtraContentPadding(options) {
const target = Math.min(scroll.value + effectiveDelta, maxScroll);
scrollToTarget(target);
}
- }, [inverted, keyboardLiftBehavior]);
+ }, [inverted, keyboardLiftBehavior, adjustedInsetCompensation]);
}
//# sourceMappingURL=index.js.map
\ No newline at end of file
diff --git a/lib/module/components/KeyboardChatScrollView/index.js b/lib/module/components/KeyboardChatScrollView/index.js
index 612dd8bd9bd6cc3e30a5acac937ea3383eb1b630..ac79433fdf0b36f89525b9840447a116da63d58c 100644
--- a/lib/module/components/KeyboardChatScrollView/index.js
+++ b/lib/module/components/KeyboardChatScrollView/index.js
@@ -1,7 +1,7 @@
function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
import React, { forwardRef, useCallback, useMemo } from "react";
import { StyleSheet } from "react-native";
-import { makeMutable, useAnimatedRef, useAnimatedStyle, useDerivedValue } from "react-native-reanimated";
+import { makeMutable, runOnJS, useAnimatedReaction, useAnimatedRef, useAnimatedStyle, useDerivedValue } from "react-native-reanimated";
import Reanimated from "react-native-reanimated";
import useCombinedRef from "../hooks/useCombinedRef";
import ScrollViewWithBottomPadding from "../ScrollViewWithBottomPadding";
@@ -19,9 +19,11 @@ const KeyboardChatScrollView = /*#__PURE__*/forwardRef(({
offset = 0,
extraContentPadding = ZERO_CONTENT_PADDING,
blankSpace = ZERO_BLANK_SPACE,
+ adjustedInsetCompensation = 0,
applyWorkaroundForContentInsetHitTestBug = false,
onLayout: onLayoutProp,
onContentSizeChange: onContentSizeChangeProp,
+ onContentInsetChange,
onEndVisible,
...rest
}, ref) => {
@@ -43,13 +45,15 @@ const KeyboardChatScrollView = /*#__PURE__*/forwardRef(({
freeze: freezeSV,
offset,
blankSpace,
- extraContentPadding
+ extraContentPadding,
+ adjustedInsetCompensation
});
useExtraContentPadding({
scrollViewRef,
extraContentPadding,
keyboardPadding: padding,
blankSpace,
+ adjustedInsetCompensation,
scroll,
layout,
size,
@@ -75,10 +79,21 @@ const KeyboardChatScrollView = /*#__PURE__*/forwardRef(({
// a bug for you, please open an issue.
const totalPadding = useDerivedValue(() => Math.min(layout.value.height, Math.max(blankSpace.value, padding.value + extraContentPadding.value)));
+ // Mirror the effective bottom padding (keyboard + composer + blank floor)
+ // to the consumer - a virtualized list needs it in its own scroll math or
+ // its end/maintain targets point at the under-the-keyboard resting offset.
+ useAnimatedReaction(() => totalPadding.value, (current, previous) => {
+ if (onContentInsetChange && current !== previous) {
+ runOnJS(onContentInsetChange)({
+ bottom: current
+ });
+ }
+ }, [onContentInsetChange]);
+
// Scroll indicator inset = keyboard + extraContentPadding (excludes blankSpace).
// Apps that render into the unsafe area can supply a negative
// scrollIndicatorInsets adjustment at the application layer.
- const indicatorPadding = useDerivedValue(() => padding.value + extraContentPadding.value);
+ const indicatorPadding = useDerivedValue(() => padding.value);
const onLayout = useCallback(e => {
onLayoutInternal(e);
onLayoutProp === null || onLayoutProp === void 0 || onLayoutProp(e);
diff --git a/lib/module/components/KeyboardChatScrollView/useChatKeyboard/index.ios.js b/lib/module/components/KeyboardChatScrollView/useChatKeyboard/index.ios.js
index 52943c3a7d6a68fe2094dc1d112c07e6b9d890e4..c8685c18a53ad078c24fc3e3b6572669b2b63397 100644
--- a/lib/module/components/KeyboardChatScrollView/useChatKeyboard/index.ios.js
+++ b/lib/module/components/KeyboardChatScrollView/useChatKeyboard/index.ios.js
@@ -25,7 +25,8 @@ function useChatKeyboard(scrollViewRef, options) {
freeze,
offset,
blankSpace,
- extraContentPadding
+ extraContentPadding,
+ adjustedInsetCompensation
} = options;
const padding = useSharedValue(0);
const currentHeight = useSharedValue(0);
@@ -59,7 +60,7 @@ function useChatKeyboard(scrollViewRef, options) {
const visiblePadding = visibleFraction * blankSpace.value;
const minimumPaddingAbsorbed = Math.max(0, visiblePadding - extraContentPadding.value);
const scrollEffective = getScrollEffective(effective, minimumPaddingAbsorbed);
- const actualTotalPadding = Math.max(blankSpace.value, effective + extraContentPadding.value);
+ const actualTotalPadding = Math.max(blankSpace.value, effective + extraContentPadding.value) + adjustedInsetCompensation;
// persistent mode: when keyboard shrinks, clamp to valid range
if (keyboardLiftBehavior === "persistent" && effective < padding.value) {
@@ -127,7 +128,7 @@ function useChatKeyboard(scrollViewRef, options) {
const effective = getEffectiveHeight(e.height, targetKeyboardHeight.value, offset);
padding.value = effective;
}
- }, [inverted, keyboardLiftBehavior, offset, extraContentPadding]);
+ }, [inverted, keyboardLiftBehavior, offset, extraContentPadding, adjustedInsetCompensation]);
return {
padding,
currentHeight,
diff --git a/lib/module/components/KeyboardChatScrollView/useExtraContentPadding/index.js b/lib/module/components/KeyboardChatScrollView/useExtraContentPadding/index.js
index 1afa50987a8d2a5fe3f36b20945efe804d48a873..e2966d89d4329a7dc1233ff060cab6f365f745d6 100644
--- a/lib/module/components/KeyboardChatScrollView/useExtraContentPadding/index.js
+++ b/lib/module/components/KeyboardChatScrollView/useExtraContentPadding/index.js
@@ -23,6 +23,7 @@ function useExtraContentPadding(options) {
extraContentPadding,
keyboardPadding,
blankSpace,
+ adjustedInsetCompensation,
scroll,
layout,
size,
@@ -62,8 +63,8 @@ function useExtraContentPadding(options) {
}
// Compute effective delta considering blankSpace floor
- const previousTotal = Math.max(blankSpace.value, keyboardPadding.value + previous);
- const currentTotal = Math.max(blankSpace.value, keyboardPadding.value + current);
+ const previousTotal = Math.max(blankSpace.value, keyboardPadding.value + previous) + adjustedInsetCompensation;
+ const currentTotal = Math.max(blankSpace.value, keyboardPadding.value + current) + adjustedInsetCompensation;
const effectiveDelta = currentTotal - previousTotal;
if (effectiveDelta === 0) {
// blankSpace absorbed the change
@@ -86,7 +87,7 @@ function useExtraContentPadding(options) {
const target = Math.min(scroll.value + effectiveDelta, maxScroll);
scrollToTarget(target);
}
- }, [inverted, keyboardLiftBehavior]);
+ }, [inverted, keyboardLiftBehavior, adjustedInsetCompensation]);
}
export { useExtraContentPadding };
//# sourceMappingURL=index.js.map
\ No newline at end of file
diff --git a/lib/typescript/components/KeyboardChatScrollView/types.d.ts b/lib/typescript/components/KeyboardChatScrollView/types.d.ts
index a036b431f03efb9d5379527c17db6fce62bfee09..6ca6fdf60fc9fae1e28a86cf24e21beed99b3a76 100644
--- a/lib/typescript/components/KeyboardChatScrollView/types.d.ts
+++ b/lib/typescript/components/KeyboardChatScrollView/types.d.ts
@@ -86,6 +86,8 @@ export type KeyboardChatScrollViewProps = {
* Default is `undefined` (equivalent to `0` — no minimum floor).
*/
blankSpace?: SharedValue<number>;
+ /** Extra bottom inset UIKit adds beyond the raw contentInset (safe area). Offset math only. */
+ adjustedInsetCompensation?: number;
/**
* Fires whenever the effective content inset changes — the static `contentInset`
* prop combined with the dynamic keyboard-driven padding.
diff --git a/lib/typescript/components/KeyboardChatScrollView/useChatKeyboard/types.d.ts b/lib/typescript/components/KeyboardChatScrollView/useChatKeyboard/types.d.ts
index aff9b5a8dbc2464546396437eaf6c5ae955b9f29..67edbe1a1eac27b5a571611979753ebf3134bc8b 100644
--- a/lib/typescript/components/KeyboardChatScrollView/useChatKeyboard/types.d.ts
+++ b/lib/typescript/components/KeyboardChatScrollView/useChatKeyboard/types.d.ts
@@ -9,6 +9,8 @@ type UseChatKeyboardOptions = {
blankSpace: SharedValue<number>;
/** Extra content padding shared value — needed on iOS to correctly clamp contentOffset. */
extraContentPadding: SharedValue<number>;
+ /** Safe-area extra beyond raw contentInset. Offset math only. */
+ adjustedInsetCompensation: number;
};
type UseChatKeyboardReturn = {
/** Extra scrollable space (= keyboard height). Used as contentInset on iOS, contentInsetBottom/contentInsetTop on Android. */
diff --git a/lib/typescript/components/KeyboardChatScrollView/useExtraContentPadding/index.d.ts b/lib/typescript/components/KeyboardChatScrollView/useExtraContentPadding/index.d.ts
index ec73f70544a062fbecfc1d8be92d839d3e0bea6f..6fe16cd0b1200a2f4d4d8eeb9b555747186dbfe0 100644
--- a/lib/typescript/components/KeyboardChatScrollView/useExtraContentPadding/index.d.ts
+++ b/lib/typescript/components/KeyboardChatScrollView/useExtraContentPadding/index.d.ts
@@ -8,6 +8,8 @@ type UseExtraContentPaddingOptions = {
keyboardPadding: SharedValue<number>;
/** Minimum inset floor — used to absorb keyboard and extraContentPadding changes. */
blankSpace: SharedValue<number>;
+ /** Safe-area extra beyond raw contentInset. Offset math only. */
+ adjustedInsetCompensation: number;
/** Current vertical scroll offset. */
scroll: SharedValue<number>;
/** Visible viewport dimensions. */
diff --git a/src/components/KeyboardChatScrollView/index.tsx b/src/components/KeyboardChatScrollView/index.tsx
index 03f5f74e9aaaabc75db1c01643a655ee4fdfa5f2..d657002ebbce53c47e3a713c0921c35dca6056f3 100644
--- a/src/components/KeyboardChatScrollView/index.tsx
+++ b/src/components/KeyboardChatScrollView/index.tsx
@@ -2,6 +2,8 @@ import React, { forwardRef, useCallback, useMemo } from "react";
import { StyleSheet } from "react-native";
import {
makeMutable,
+ runOnJS,
+ useAnimatedReaction,
useAnimatedRef,
useAnimatedStyle,
useDerivedValue,
@@ -35,9 +37,11 @@ const KeyboardChatScrollView = forwardRef<
offset = 0,
extraContentPadding = ZERO_CONTENT_PADDING,
blankSpace = ZERO_BLANK_SPACE,
+ adjustedInsetCompensation = 0,
applyWorkaroundForContentInsetHitTestBug = false,
onLayout: onLayoutProp,
onContentSizeChange: onContentSizeChangeProp,
+ onContentInsetChange,
onEndVisible,
...rest
},
@@ -64,6 +68,7 @@ const KeyboardChatScrollView = forwardRef<
offset,
blankSpace,
extraContentPadding,
+ adjustedInsetCompensation,
});
useExtraContentPadding({
@@ -71,6 +76,7 @@ const KeyboardChatScrollView = forwardRef<
extraContentPadding,
keyboardPadding: padding,
blankSpace,
+ adjustedInsetCompensation,
scroll,
layout,
size,
@@ -102,13 +108,25 @@ const KeyboardChatScrollView = forwardRef<
),
);
- // Scroll indicator inset = keyboard + extraContentPadding (excludes blankSpace).
- // Apps that render into the unsafe area can supply a negative
- // scrollIndicatorInsets adjustment at the application layer.
- const indicatorPadding = useDerivedValue(
- () => padding.value + extraContentPadding.value,
+ // Mirror the effective bottom padding (keyboard + composer + blank floor)
+ // to the consumer — a virtualized list needs it in its own scroll math or
+ // its end/maintain targets point at the under-the-keyboard resting offset.
+ useAnimatedReaction(
+ () => totalPadding.value,
+ (current, previous) => {
+ if (onContentInsetChange && current !== previous) {
+ runOnJS(onContentInsetChange)({ bottom: current });
+ }
+ },
+ [onContentInsetChange],
);
+ // Scroll indicator inset = keyboard only (excludes extraContentPadding and
+ // blankSpace): with a floating composer the indicator track should run the
+ // full height of the scroll view, behind the composer, like iOS Messages.
+ // The keyboard still lifts it so it never disappears under the keyboard.
+ const indicatorPadding = useDerivedValue(() => padding.value);
+
const onLayout = useCallback(
(e: LayoutChangeEvent) => {
onLayoutInternal(e);
diff --git a/src/components/KeyboardChatScrollView/types.ts b/src/components/KeyboardChatScrollView/types.ts
index dd222b57bc7a71729524670bad3812f30920bd73..40249a4357991b7a9c69b87214db2ceb6ff4ba7d 100644
--- a/src/components/KeyboardChatScrollView/types.ts
+++ b/src/components/KeyboardChatScrollView/types.ts
@@ -90,6 +90,15 @@ export type KeyboardChatScrollViewProps = {
* Default is `undefined` (equivalent to `0` — no minimum floor).
*/
blankSpace?: SharedValue<number>;
+ /**
+ * Extra bottom inset UIKit adds on top of the raw `contentInset` this
+ * component writes (e.g. the home-indicator safe area under
+ * `contentInsetAdjustmentBehavior="automatic"`). Used ONLY in scroll-offset
+ * math (max scroll / end pinning) — never written into `contentInset`.
+ *
+ * Default is `0`.
+ */
+ adjustedInsetCompensation?: number;
/**
* Fires whenever the effective content inset changes — the static `contentInset`
* prop combined with the dynamic keyboard-driven padding.
diff --git a/src/components/KeyboardChatScrollView/useChatKeyboard/index.ios.ts b/src/components/KeyboardChatScrollView/useChatKeyboard/index.ios.ts
index 560df54bae1a8c41a2e9ac0e2a8d2fd9b843968a..a0cb412692cf47fee372a01132e6a670b59bcd66 100644
--- a/src/components/KeyboardChatScrollView/useChatKeyboard/index.ios.ts
+++ b/src/components/KeyboardChatScrollView/useChatKeyboard/index.ios.ts
@@ -43,6 +43,7 @@ function useChatKeyboard(
offset,
blankSpace,
extraContentPadding,
+ adjustedInsetCompensation,
} = options;
const padding = useSharedValue(0);
@@ -104,10 +105,12 @@ function useChatKeyboard(
effective,
minimumPaddingAbsorbed,
);
- const actualTotalPadding = Math.max(
- blankSpace.value,
- effective + extraContentPadding.value,
- );
+ // UIKit adds adjustedInsetCompensation (safe area) on top of the raw
+ // inset; include it here so end/max-scroll targets match the real
+ // resting offsets.
+ const actualTotalPadding =
+ Math.max(blankSpace.value, effective + extraContentPadding.value) +
+ adjustedInsetCompensation;
// persistent mode: when keyboard shrinks, clamp to valid range
if (
@@ -242,7 +245,7 @@ function useChatKeyboard(
padding.value = effective;
},
},
- [inverted, keyboardLiftBehavior, offset, extraContentPadding],
+ [inverted, keyboardLiftBehavior, offset, extraContentPadding, adjustedInsetCompensation],
);
return {
diff --git a/src/components/KeyboardChatScrollView/useChatKeyboard/types.ts b/src/components/KeyboardChatScrollView/useChatKeyboard/types.ts
index 02abf5cd9490900826678175462b234e07e30e92..3f261fa8f1913a79fa1de2004bbac20415a89acc 100644
--- a/src/components/KeyboardChatScrollView/useChatKeyboard/types.ts
+++ b/src/components/KeyboardChatScrollView/useChatKeyboard/types.ts
@@ -11,6 +11,8 @@ type UseChatKeyboardOptions = {
blankSpace: SharedValue<number>;
/** Extra content padding shared value — needed on iOS to correctly clamp contentOffset. */
extraContentPadding: SharedValue<number>;
+ /** Extra bottom inset UIKit adds beyond the raw contentInset (safe area). Offset math only. */
+ adjustedInsetCompensation: number;
};
type UseChatKeyboardReturn = {
diff --git a/src/components/KeyboardChatScrollView/useExtraContentPadding/index.ts b/src/components/KeyboardChatScrollView/useExtraContentPadding/index.ts
index 833acbe78f1b1245251ddd3431d6546decdd0ade..49d679446b03199217faa16a503d8d15e83a29b9 100644
--- a/src/components/KeyboardChatScrollView/useExtraContentPadding/index.ts
+++ b/src/components/KeyboardChatScrollView/useExtraContentPadding/index.ts
@@ -16,6 +16,8 @@ type UseExtraContentPaddingOptions = {
keyboardPadding: SharedValue<number>;
/** Minimum inset floor — used to absorb keyboard and extraContentPadding changes. */
blankSpace: SharedValue<number>;
+ /** Extra bottom inset UIKit adds beyond the raw contentInset (safe area). Offset math only. */
+ adjustedInsetCompensation: number;
/** Current vertical scroll offset. */
scroll: SharedValue<number>;
/** Visible viewport dimensions. */
@@ -49,6 +51,7 @@ function useExtraContentPadding(options: UseExtraContentPaddingOptions): void {
extraContentPadding,
keyboardPadding,
blankSpace,
+ adjustedInsetCompensation,
scroll,
layout,
size,
@@ -97,14 +100,12 @@ function useExtraContentPadding(options: UseExtraContentPaddingOptions): void {
}
// Compute effective delta considering blankSpace floor
- const previousTotal = Math.max(
- blankSpace.value,
- keyboardPadding.value + previous,
- );
- const currentTotal = Math.max(
- blankSpace.value,
- keyboardPadding.value + current,
- );
+ const previousTotal =
+ Math.max(blankSpace.value, keyboardPadding.value + previous) +
+ adjustedInsetCompensation;
+ const currentTotal =
+ Math.max(blankSpace.value, keyboardPadding.value + current) +
+ adjustedInsetCompensation;
const effectiveDelta = currentTotal - previousTotal;
if (effectiveDelta === 0) {
@@ -146,7 +147,7 @@ function useExtraContentPadding(options: UseExtraContentPaddingOptions): void {
scrollToTarget(target);
}
},
- [inverted, keyboardLiftBehavior],
+ [inverted, keyboardLiftBehavior, adjustedInsetCompensation],
);
}
+12 -6
View File
@@ -76,6 +76,9 @@ patchedDependencies:
'@ff-labs/[email protected]':
hash: 2b16019ce7ab61aec6478dd02f79ef468cc1d5c51e9d00764f7d2ab8167210c8
path: patches/@[email protected]
'@legendapp/[email protected]':
hash: 45e4cbcbeeca1b628b8480869374d7cbc77e3fbfa97ee0107a0d72c3c4a5d7f3
path: patches/@[email protected]
'@pierre/[email protected]':
hash: 7cb6da88544119adda056b2f46f43956f99326227732da0b345081e285a6c53a
path: patches/@pierre%[email protected]
@@ -94,6 +97,9 @@ patchedDependencies:
[email protected]:
hash: 808eb26f9e57cf4945efd3985af4d9c764da6f91f4c9764433cc868602bbf4d3
path: patches/[email protected]
[email protected]:
hash: 20be72c84d74253acdcfefbc6defe36dc396944f1a44cab2bdd0e3cd572ae008
path: patches/[email protected]
[email protected]:
hash: 825622aae63a8fb5b904f3c77908a0e216261d727ea171709f2c0b6088422675
path: patches/[email protected]
@@ -226,7 +232,7 @@ importers:
version: 56.0.18(19413efe5eaad64848598eedfe3a0fd3)
'@legendapp/list':
specifier: 3.2.0
version: 3.2.0([email protected]([email protected]))([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected])
version: 3.2.0(patch_hash=45e4cbcbeeca1b628b8480869374d7cbc77e3fbfa97ee0107a0d72c3c4a5d7f3)([email protected]([email protected]))([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected])
'@noble/curves':
specifier: 'catalog:'
version: 1.9.1
@@ -379,7 +385,7 @@ importers:
version: 0.2.2([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected])
react-native-keyboard-controller:
specifier: 1.21.13
version: 1.21.13([email protected]([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected]))([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected]))([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected])
version: 1.21.13(patch_hash=20be72c84d74253acdcfefbc6defe36dc396944f1a44cab2bdd0e3cd572ae008)([email protected]([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected]))([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected]))([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected])
react-native-nitro-markdown:
specifier: ^0.5.0
version: 0.5.8([email protected](patch_hash=825622aae63a8fb5b904f3c77908a0e216261d727ea171709f2c0b6088422675)([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected]))([email protected]([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected]))([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected])
@@ -537,7 +543,7 @@ importers:
version: 0.9.0
'@legendapp/list':
specifier: 3.2.0
version: 3.2.0([email protected]([email protected]))([email protected])
version: 3.2.0(patch_hash=45e4cbcbeeca1b628b8480869374d7cbc77e3fbfa97ee0107a0d72c3c4a5d7f3)([email protected]([email protected]))([email protected])
'@lexical/react':
specifier: ^0.41.0
version: 0.41.0([email protected]([email protected]))([email protected])([email protected])
@@ -12654,7 +12660,7 @@ snapshots:
dependencies:
jsbi: 4.3.2
'@legendapp/[email protected]([email protected]([email protected]))([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected])':
'@legendapp/[email protected](patch_hash=45e4cbcbeeca1b628b8480869374d7cbc77e3fbfa97ee0107a0d72c3c4a5d7f3)([email protected]([email protected]))([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected])':
dependencies:
react: 19.2.3
use-sync-external-store: 1.6.0([email protected])
@@ -12662,7 +12668,7 @@ snapshots:
react-dom: 19.2.3([email protected])
react-native: 0.85.3(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])([email protected])([email protected])
'@legendapp/[email protected]([email protected]([email protected]))([email protected])':
'@legendapp/[email protected](patch_hash=45e4cbcbeeca1b628b8480869374d7cbc77e3fbfa97ee0107a0d72c3c4a5d7f3)([email protected]([email protected]))([email protected])':
dependencies:
react: 19.2.6
use-sync-external-store: 1.6.0([email protected])
@@ -18950,7 +18956,7 @@ snapshots:
react: 19.2.3
react-native: 0.85.3(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])([email protected])([email protected])
[email protected]([email protected]([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected]))([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected]))([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected]):
[email protected](patch_hash=20be72c84d74253acdcfefbc6defe36dc396944f1a44cab2bdd0e3cd572ae008)([email protected]([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected]))([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected]))([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected]):
dependencies:
react: 19.2.3
react-native: 0.85.3(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])([email protected])([email protected])
+7 -16
View File
@@ -5,20 +5,6 @@ packages:
- packages/*
- scripts
# Install both Windows and Linux native binaries so the WSL (Linux) backend
# can load platform-gated optional deps (e.g. @yuuang/ffi-rs-linux-x64-gnu)
# out of the same node_modules the Windows desktop uses.
supportedArchitectures:
os:
- current
- linux
cpu:
- current
- x64
libc:
- current
- glibc
catalog:
"@clerk/backend": 3.8.4
"@clerk/clerk-js": 6.22.0
@@ -84,8 +70,6 @@ overrides:
"@pierre/diffs>@shikijs/transformers": ^4.2.0
"@types/node": "catalog:"
effect: "catalog:"
# Pin to the version our patch targets; expo-modules-core's ~56.0.10 range
# otherwise floats to newer releases on fresh resolves (ERR_PNPM_UNUSED_PATCH).
expo-modules-jsi: 56.0.10
vite: "catalog:"
yaml: "catalog:"
@@ -105,12 +89,14 @@ patchedDependencies:
"@effect/[email protected]": patches/@[email protected]
"@expo/[email protected]": patches/@expo%[email protected]
"@ff-labs/[email protected]": patches/@[email protected]
"@legendapp/[email protected]": patches/@[email protected]
"@pierre/[email protected]": patches/@pierre%[email protected]
"@react-native-menu/[email protected]": patches/@[email protected]
"@react-navigation/[email protected]": patches/@react-navigation%[email protected]
[email protected]: patches/[email protected]
[email protected]: patches/[email protected]
[email protected]: patches/[email protected]
[email protected]: patches/[email protected]
[email protected]: patches/[email protected]
[email protected]: patches/[email protected]
@@ -119,3 +105,8 @@ peerDependencyRules:
- vite
allowedVersions:
vite: "*"
supportedArchitectures:
cpu: [current, x64]
libc: [current, glibc]
os: [current, linux]