Compare commits

...
Author SHA1 Message Date
Theo BrowneandClaude Fable 5 e5d5249680 refactor: trim redundant optimizations from the perf PR (#3928)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-07-13 16:21:24 -07:00
Theo BrowneandClaude Fable 5 6b2f3f8ae8 fix: address review bot findings on hover prewarm, Shiki cache, activity fan-out
- Sidebar hover prewarm: match Element instead of HTMLElement so resting on
  a row's SVG icons (status pill, PR badge) still resolves to the row's
  prewarm key instead of cancelling the hover.
- Shiki negative cache: bound it (100 entries) since fence labels are
  arbitrary text; evict failed loads from the promise cache so transient
  failures stay retryable; stop adding render-time codeToHtml throws to the
  negative cache so one pathological block can't disable highlighting for a
  supported language.
- Activity projection: skip the thread-row upsert entirely for non-summary
  activity kinds (not just the history rebuild) and skip the corresponding
  shell re-broadcast in ws.ts — high-volume command/output/progress streams
  no longer churn updatedAt or fan out per-event shell upserts.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-07-11 17:28:19 -07:00
Theo BrowneandClaude Fable 5 05e623fee9 refactor: drop createDebouncedStorage now superseded by the JSON variant
The composer store was its only production consumer; port its tests to
createDebouncedJsonStorage.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-07-11 17:01:44 -07:00
Theo BrowneandClaude Fable 5 bc23ec5073 perf: fix sustained-CPU hot paths from the July 2026 web performance audit
Addresses the audit's findings with minimal, desktop-first changes (no
payload deferral, no streaming-path work since streaming is off by default):

- Sidebar: replace the 10-thread bulk detail prewarm with a single
  hover-based prewarm; at idle one shell stream + at most one detail stream
- Server replay: thread catch-up reads only the thread's aggregate stream
  via the (aggregate_kind, stream_id, sequence) index instead of scanning
  the global log; shell catch-up is bounded (500 events) with a shell
  snapshot fallback for stale cursors
- Shell summaries: thread.message-sent updates latestUserMessageAt
  incrementally; activity-appended triggers the history-wide summary
  rebuild only for approval/user-input activity kinds; streaming assistant
  chunks no longer fan out per-chunk shell upserts
- Client runtime: O(1) activity appends when order is preserved; skip
  IndexedDB full-snapshot encodes while a turn is running (settle event and
  scope finalizer persist the final state)
- Timeline derivation: share one ordered activities view across the four
  derivations (identity-cached, O(n) sorted check); k-way merge for the
  combined timeline instead of concat+sort
- Composer drafts: debounce JSON serialization itself, and cache per-draft
  partialization by object identity so typing doesn't re-clone every
  retained draft
- Shiki: negative-cache languages without grammars (sh, yaml) so those
  fences stop retrying and throwing on every render
- Bootstrap polling: one shared change-detecting poller instead of one
  2s interval per consumer; minimap only writes data-in-view on change

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-07-09 04:09:08 -07:00
Julius Marmingeandcodex 3201e00ad4 [codex] Preserve worktree metadata during branch sync (#3822)
Co-authored-by: codex <[email protected]>
2026-07-09 09:01:23 +02:00
Julius Marmingeandcodex e9127658a6 [codex] Upgrade Clerk stack (#3821)
Co-authored-by: codex <[email protected]>
2026-07-09 07:54:28 +02:00
Patricio Gómez Meneses 18a41388eb Fix desktop native optional dependency packaging (#3816) 2026-07-09 03:55:33 +00:00
Rowan 0c66565854 fix(release): bump electron-builder so pnpm 11 deduped deps land in the asar (#3790) 2026-07-08 04:38:45 -07:00
Julius Marminge e775bc6228 Upgrade Clerk toolchain to latest versions (#3785) 2026-07-08 04:30:07 -07:00
Julius MarmingeandCursor Agent 03ac1f0cd9 fix(release): stage pnpm 11 allowBuilds for desktop installs (#3781)
Co-authored-by: Cursor Agent <[email protected]>
2026-07-07 15:55:18 -07:00
Julius MarmingeandCursor Agent 7778a1cea7 Use rounded depth logo for production splash screen (#3780)
Co-authored-by: Cursor Agent <[email protected]>
2026-07-07 22:49:50 +00:00
Julius MarmingeandClaude Fable 5 dad0889766 Revert "Revert "Add T3 Connect onboarding for mobile and web"" (#3777)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-07-07 14:17:18 -07:00
b9cc8d6ef1 Set up Cursor Cloud dev environment (web + Android toolchain) (#3755)
Co-authored-by: Cursor Agent <[email protected]>
Co-authored-by: Theo Browne <[email protected]>
2026-07-07 13:18:58 -07:00
Julius MarmingeandClaude Fable 5 0e0040832c Expose Clerk Google sign-in env vars to Expo (#3772)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-07-07 12:45:40 -07:00
Julius Marminge cd8b9fc8b3 Revert "Add T3 Connect onboarding for mobile and web" (#3776) 2026-07-07 12:40:12 -07:00
Julius Marminge fa6073e2e1 Add T3 Connect onboarding for mobile and web (#3765) 2026-07-07 12:39:56 -07:00
Julius Marminge 4eb1b57933 Lead with the outcome when no agents are active in the Live Activity (#3768) 2026-07-07 09:12:52 -07:00
Julius Marminge 4414f922fe Clear VCS presentation state on finish (#3764) 2026-07-07 08:54:27 -07:00
Julius Marminge 6e42231cb1 Extend Done display to 15 minutes and show up to 5 Live Activity banner rows (#3761) 2026-07-07 02:00:36 -07:00
Julius Marminge bdf5aed665 Fix Expo widget asset wiring order (#3763) 2026-07-07 02:00:10 -07:00
Julius Marminge 0b62e2eb11 Use variant-specific splash icons in mobile app (#3762) 2026-07-07 01:59:13 -07:00
Julius Marminge f9727d0853 Prevent Add Project sheet from collapsing on relayout (#3759) 2026-07-07 01:58:29 -07:00
81 changed files with 3791 additions and 1604 deletions

No files matched your search

+72
View File
@@ -0,0 +1,72 @@
---
description: Cursor Cloud environment setup and run notes for T3 Code (Cursor-specific; not for other editors/CI)
alwaysApply: true
---
# Cursor Cloud specific instructions
These notes apply only to Cursor Cloud agents (kept out of the shared `AGENTS.md` since T3 Code is
developed in many places). They cover the pre-provisioned VM environment and non-obvious run caveats.
## Toolchain
Pre-installed and wired into login shells (`~/.bashrc`/`~/.profile`): Node 24 (via nvm), the global
`vp` (Vite+) CLI, and its bundled pnpm. `vp` is the package manager + task runner for this repo
(`vp i`, `vp check`, `vp run typecheck`, `vp test`, `vp run --filter <pkg> <script>`).
- Node gotcha: the base image also ships an older Node on `/exec-daemon` that wins on `PATH` in
non-login shells. Run commands in a login shell (`bash -lc '...'`) or prepend
`$HOME/.nvm/versions/node/v24.13.1/bin` so Node 24 (`engines.node: ^24.13.1`) is used.
- `vp check` also runs the formatter (not just lint); markdown edits must be formatter-clean. Run
`vp check --fix` before committing.
## Running the web app
- `npm run dev` (from repo root) starts contracts (watch), web (Vite, port 5733), and the server
(`node --watch`, port 13773) together, auto-wiring `VITE_HTTP_URL`/`VITE_WS_URL`. Use
`npm run dev:server` / `npm run dev:web` for one side. If base ports are taken it auto-offsets to
the next free pair, so read the actual ports from stdout. Avoid production `build`/`start` in dev.
- Auth/pairing: the server is unauthenticated by default and prints a pairing URL to stdout on startup
(e.g. `http://localhost:5733/pair#token=XXXX`). Open that URL in the browser to pair before the web
UI can talk to the server. Server state (SQLite, auth, projects) lives under `~/.t3`
(`T3CODE_HOME`); multiple `npm run dev` instances bind different ports but share that same DB.
- Agent providers are external CLIs (`codex`, `claude`, `cursor-agent`, `opencode`) probed on `PATH`.
Without one installed the UI loads but no agent can run. Claude Code
(`npm i -g @anthropic-ai/claude-code`) works headlessly using `ANTHROPIC_API_KEY` from the
environment (the server forwards `process.env` to the child; no interactive `claude auth login`
needed). Provider probing runs at startup and refreshes roughly every 5 minutes — restart the dev
server to pick up a newly installed provider CLI immediately.
## Android native builds (apps/mobile)
The Android toolchain is pre-installed and wired into login shells: OpenJDK 17
(`JAVA_HOME=/usr/lib/jvm/java-17-openjdk-amd64`; the base image's default `java` is 21, so builds must
use `JAVA_HOME`), and the Android SDK at `$HOME/Android/Sdk` (`ANDROID_HOME`/`ANDROID_SDK_ROOT`) with
platform-tools, `platforms;android-36`, `build-tools;36.0.0`, `ndk;27.1.12297006`, and `cmake;3.22.1`.
Gradle auto-downloads any additional pinned SDK packages on demand.
- Generate the native project first: from `apps/mobile`,
`EXPO_NO_GIT_STATUS=1 APP_VARIANT=development npx expo prebuild --clean --platform android`
(the `android/` folder is generated, not committed). RN 0.85 defaults: compileSdk/targetSdk 36,
minSdk 24, NDK `27.1.12297006` (see `react-native/gradle/libs.versions.toml`).
- Build with Gradle from `apps/mobile/android`, e.g. `./gradlew :app:assembleDebug`. First build is
slow (Kotlin + C++/NDK codegen). Limit ABIs to speed things up, e.g.
`-PreactNativeArchitectures=arm64-v8a`. Verified working end-to-end on a native module:
`./gradlew :react-native-worklets:assembleDebug` compiles Kotlin + C++ and emits an AAR + `.so`s.
- No emulator: this VM has no `/dev/kvm` (nested virtualization), so a hardware-accelerated Android
emulator will not run. Use a physical device (`adb`) or EAS cloud builds (`vp run eas:android:*`) to
actually run the app. The full IDE GUI is unnecessary here — the SDK/NDK/Gradle toolchain that
Android Studio bundles is what is installed.
- Known blocker for the full-app `:app:assembleDebug` (pre-existing, app-level — not the environment):
`:react-native-screens:compileDebugKotlin` fails because `patches/[email protected]`
adds new codegen props (`subtitle`, `largeSubtitle`, `navigationItemStyle`,
`headerCenterBarButtonItems`, `headerToolbarItems`) to the JS spec + iOS native code but includes no
Android Kotlin setters, so the generated `ScreenStackHeaderConfigManagerInterface` is unimplemented.
The mobile README documents only iOS for local builds and routes Android through EAS. Fixing local
Android app builds requires an app/patch change (add the Android Kotlin setters), which is out of
scope for environment setup.
## Known flaky tests (unrelated to setup)
- `apps/server/src/git/GitManager.test.ts` (cross-repo PR metadata, can time out at 12s).
- `apps/server/src/provider/Layers/ProviderRegistry.test.ts` (codex binaryPath re-probe ordering).
+4 -1
View File
@@ -57,7 +57,10 @@ jobs:
with:
eas-version: latest
token: ${{ secrets.EXPO_TOKEN }}
packager: pnpm
# npm, not pnpm: this only installs eas-cli into the action's own
# tool dir, and pnpm 11 hard-fails that install on dtrace-provider's
# ignored build script (no allowBuilds config outside the repo).
packager: npm
- name: Pull preview environment variables
if: steps.expo-token.outputs.present == 'true'
+4 -1
View File
@@ -80,7 +80,10 @@ jobs:
with:
eas-version: latest
token: ${{ secrets.EXPO_TOKEN }}
packager: pnpm
# npm, not pnpm: this only installs eas-cli into the action's own
# tool dir, and pnpm 11 hard-fails that install on dtrace-provider's
# ignored build script (no allowBuilds config outside the repo).
packager: npm
- name: Pull production environment variables
if: steps.expo-token.outputs.present == 'true'
+1 -1
View File
@@ -31,7 +31,7 @@
"@effect/vitest": "catalog:",
"@types/node": "catalog:",
"cross-env": "^10.1.0",
"electron-builder": "26.8.1",
"electron-builder": "26.15.6",
"tailwindcss": "^4.0.0",
"vite-plus": "catalog:"
},
+21 -5
View File
@@ -15,6 +15,7 @@ const VARIANT_CONFIG: Record<
readonly appName: string;
readonly scheme: string;
readonly iosIcon: string;
readonly splashIcon: string;
readonly iosBundleIdentifier: string;
readonly androidPackage: string;
readonly relyingParty?: string;
@@ -24,6 +25,7 @@ const VARIANT_CONFIG: Record<
appName: "T3 Code Dev",
scheme: "t3code-dev",
iosIcon: "./assets/icon-composer-dev.icon",
splashIcon: "./assets/splash-icon-dev.png",
iosBundleIdentifier: "com.t3tools.t3code.dev",
androidPackage: "com.t3tools.t3code.dev",
relyingParty: "clerk.t3.codes",
@@ -32,6 +34,7 @@ const VARIANT_CONFIG: Record<
appName: "T3 Code Preview",
scheme: "t3code-preview",
iosIcon: "./assets/icon-composer-prod.icon",
splashIcon: "./assets/splash-icon-prod.png",
iosBundleIdentifier: "com.t3tools.t3code.preview",
androidPackage: "com.t3tools.t3code.preview",
relyingParty: "clerk.t3.codes",
@@ -40,6 +43,7 @@ const VARIANT_CONFIG: Record<
appName: "T3 Code",
scheme: "t3code",
iosIcon: "./assets/icon-composer-prod.icon",
splashIcon: "./assets/splash-icon-prod.png",
iosBundleIdentifier: "com.t3tools.t3code",
androidPackage: "com.t3tools.t3code",
relyingParty: "clerk.t3.codes",
@@ -131,12 +135,12 @@ const config: ExpoConfig = {
[
"expo-splash-screen",
{
image: "./assets/splash-icon.png",
image: variant.splashIcon,
resizeMode: "contain",
backgroundColor: "#ffffff",
imageWidth: 220,
dark: {
image: "./assets/splash-icon.png",
image: variant.splashIcon,
backgroundColor: "#0a0a0a",
},
},
@@ -155,6 +159,12 @@ const config: ExpoConfig = {
},
],
"./plugins/withIosCocoaPodsUuidCache.cjs",
// Must be listed BEFORE expo-widgets: same-type mods run last-registered-
// first, so registering earlier makes this plugin's mods run AFTER
// expo-widgets' — its dangerous mod wipes ios/ExpoWidgetsTarget/ (which
// would delete the asset catalog) and its xcodeproj mod creates the widget
// target (which must exist before the compile phase can be attached).
"./plugins/withWidgetLogoAsset.cjs",
[
"expo-widgets",
{
@@ -174,9 +184,6 @@ const config: ExpoConfig = {
],
},
],
// Must run after expo-widgets so the widget target exists when it wires in
// the branded logo asset catalog.
"./plugins/withWidgetLogoAsset.cjs",
"./plugins/withIosSceneLifecycle.cjs",
"./plugins/withAndroidCleartextTraffic.cjs",
],
@@ -189,6 +196,15 @@ const config: ExpoConfig = {
publishableKey: repoEnv.EXPO_PUBLIC_CLERK_PUBLISHABLE_KEY ?? null,
jwtTemplate: repoEnv.EXPO_PUBLIC_CLERK_JWT_TEMPLATE ?? null,
},
// Native Google sign-in credentials. @clerk/expo reads these from `extra`
// under their exact env-var names (not nested), and its config plugin reads
// the iOS URL scheme at prebuild to register it in Info.plist.
// Unset values must be omitted (not null): the public manifest serializes
// null to {}, which is truthy and would defeat Clerk's fallback checks.
EXPO_PUBLIC_CLERK_GOOGLE_WEB_CLIENT_ID: repoEnv.EXPO_PUBLIC_CLERK_GOOGLE_WEB_CLIENT_ID,
EXPO_PUBLIC_CLERK_GOOGLE_IOS_CLIENT_ID: repoEnv.EXPO_PUBLIC_CLERK_GOOGLE_IOS_CLIENT_ID,
EXPO_PUBLIC_CLERK_GOOGLE_ANDROID_CLIENT_ID: repoEnv.EXPO_PUBLIC_CLERK_GOOGLE_ANDROID_CLIENT_ID,
EXPO_PUBLIC_CLERK_GOOGLE_IOS_URL_SCHEME: repoEnv.EXPO_PUBLIC_CLERK_GOOGLE_IOS_URL_SCHEME,
observability: {
tracesUrl: repoEnv.EXPO_PUBLIC_OTLP_TRACES_URL ?? "https://api.axiom.co/v1/traces",
tracesDataset: repoEnv.EXPO_PUBLIC_OTLP_TRACES_DATASET ?? null,
File renamed without changes.

Before

Width:  |  Height:  |  Size: 2.0 MiB

After

Width:  |  Height:  |  Size: 2.0 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 302 KiB

@@ -9,8 +9,10 @@
// drops the compiled Assets.car into the extension bundle. Marked
// alwaysOutOfDate so the build system always runs it.
//
// Idempotent across re-runs. Returns true when it added the phase, false when it
// was already present or the target was not found.
// Idempotent across re-runs. Returns true when it added the phase, false when
// it was already present. Throws when the target does not exist — that means
// this ran before expo-widgets created the target (plugin ordering bug) and
// silently skipping would ship a widget without its assets.
const PHASE_NAME = "Compile Widget Assets";
@@ -20,8 +22,8 @@ const ACTOOL_SCRIPT = [
"set -e",
'CATALOG="${SRCROOT}/ExpoWidgetsTarget/Assets.xcassets"',
'if [ ! -d "$CATALOG" ]; then',
' echo "warning: widget asset catalog not found at $CATALOG"',
" exit 0",
' echo "error: widget asset catalog not found at $CATALOG (expo-widgets wiped it? check plugin ordering in app.config.ts)"',
" exit 1",
"fi",
'DEST="${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}"',
'mkdir -p "$DEST"',
@@ -51,7 +53,13 @@ function findByName(map, name) {
function addWidgetAssetCatalog(proj, opts) {
const objects = proj.hash.project.objects;
const target = findByName(objects.PBXNativeTarget, opts.targetName);
if (!target) return false;
if (!target) {
throw new Error(
`addWidgetAssetCatalog: target "${opts.targetName}" not found — ` +
"withWidgetLogoAsset must be registered before expo-widgets so its " +
"xcodeproj mod runs after the widget target is created.",
);
}
const phases = target.value.buildPhases || [];
const existing = objects.PBXShellScriptBuildPhase || {};
+9 -3
View File
@@ -5,9 +5,15 @@
// expo-widgets generates ExpoWidgetsTarget without a Resources build phase and
// has no asset support, so this plugin (a) writes an SVG template image set into
// the generated widget asset catalog and (b) wires that catalog into the widget
// target with a dedicated Resources build phase. Both steps are idempotent and
// survive `expo prebuild --clean`. Must be listed AFTER "expo-widgets" in the
// plugins array so the widget target exists when this runs.
// target with an actool build phase.
//
// ORDERING: must be listed BEFORE "expo-widgets" in the plugins array. Expo
// chains same-type mods so the last-registered runs FIRST; registering this
// plugin earlier makes its mods run AFTER expo-widgets' mods. That matters
// twice: expo-widgets' dangerous mod rmSync's ios/ExpoWidgetsTarget/ (deleting
// any catalog written before it), and its xcodeproj mod is what creates the
// widget target. Listed after expo-widgets, both steps silently no-op on a
// fresh prebuild — which is how prod build 8 shipped without the logo.
const path = require("path");
const fs = require("fs");
@@ -26,5 +26,5 @@ if (added) {
fs.writeFileSync(pbxprojPath, proj.writeSync());
console.log("Added widget asset-compile phase to ExpoWidgetsTarget.");
} else {
console.log("No change: phase already present or target not found.");
console.log("No change: phase already present.");
}
+19
View File
@@ -17,6 +17,8 @@ import { AppText as Text } from "./components/AppText";
import { ArchivedThreadsRouteScreen } from "./features/archive/ArchivedThreadsRouteScreen";
import { useAgentNotificationNavigation } from "./features/agent-awareness/notificationNavigation";
import { ClerkSettingsSheetDetentProvider } from "./features/cloud/ClerkSettingsSheetDetent";
import { ConnectOnboardingRouteScreen } from "./features/cloud/ConnectOnboardingRouteScreen";
import { useConnectOnboardingNavigation } from "./features/cloud/connectOnboardingNavigation";
import { ThreadFilesTreeScreen, ThreadFileScreen } from "./features/files/ThreadFilesRouteScreen";
import { AdaptiveWorkspaceLayout } from "./features/layout/AdaptiveWorkspaceLayout";
import { HardwareKeyboardCommandProvider } from "./features/keyboard/HardwareKeyboardCommandProvider";
@@ -220,6 +222,7 @@ const NewTaskSheetStack = createNativeStackNavigator({
// influence the adaptive workspace layout: opening Settings over Home should
// not flip the sidebar in or change the active thread.
const WORKSPACE_OVERLAY_ROUTES = new Set([
"ConnectOnboarding",
"Connections",
"ConnectionsNew",
"GitBranches",
@@ -251,6 +254,8 @@ function RootStackLayout(props: {
}) {
useAgentNotificationNavigation();
useThreadOutboxDrain();
// Presents the T3 Connect onboarding sheet after an in-session sign-in.
useConnectOnboardingNavigation();
// Full pathname (sheets included) for keyboard-command scoping; the
// workspace layout only reacts to the underlying non-overlay route.
const path = getPathFromState(props.state, navigationPathConfig);
@@ -412,6 +417,20 @@ export const RootStack = createNativeStackNavigator({
sheetGrabberVisible: true,
},
}),
ConnectOnboarding: createNativeStackScreen({
screen: ConnectOnboardingRouteScreen,
linking: "connect-onboarding",
options: {
// Root screenOptions hide headers; formSheets that want the native
// title bar opt back in with the sheet header preset.
...SHEET_SOLID_HEADER_OPTIONS,
title: "Set up T3 Connect",
gestureEnabled: true,
presentation: "formSheet",
sheetAllowedDetents: [0.6, 0.95],
sheetGrabberVisible: true,
},
}),
Connections: createNativeStackScreen({
screen: ConnectionsRouteScreen,
linking: "connections",
+2 -2
View File
@@ -92,7 +92,7 @@ const capabilitiesLayer = Layer.succeedContext(
if (session === null) {
return yield* new ConnectionBlockedError({
reason: "authentication",
detail: "Sign in to T3 Cloud to connect this environment.",
detail: "Sign in to T3 Connect to connect this environment.",
});
}
const token = yield* session.readClerkToken().pipe(
@@ -107,7 +107,7 @@ const capabilitiesLayer = Layer.succeedContext(
if (token === null) {
return yield* new ConnectionBlockedError({
reason: "authentication",
detail: "The T3 Cloud session is unavailable.",
detail: "The T3 Connect session is unavailable.",
});
}
return token;
@@ -18,6 +18,7 @@ import {
setAgentAwarenessRelayTokenProvider,
unregisterAgentAwarenessDeviceForCurrentUser,
} from "../agent-awareness/remoteRegistration";
import { clearConnectOnboardingRequest, requestConnectOnboarding } from "./connectOnboarding";
import { resolveCloudPublicConfig, resolveRelayClerkTokenOptions } from "./publicConfig";
function resetManagedRelayTokenCache() {
@@ -67,6 +68,19 @@ function CloudAuthBridge(props: { readonly children: ReactNode }) {
const nextAccount = isSignedIn && userId ? userId : null;
observedAccountRef.current = nextAccount;
// Every sign-in or account switch that completes during this session (a
// cold start observes undefined → account and must not re-prompt) requests
// the T3 Connect onboarding sheet — account transitions clear the
// connected environments, so each new session starts with no devices to
// reach. The request itself is issued after the cleanup transition inside
// activateSession, so the sheet never lists the previous account's
// environments; sign-out drops any not-yet-presented request instead.
const isAccountTransition =
previousObservedAccount !== undefined && previousObservedAccount !== nextAccount;
if (isAccountTransition && nextAccount === null) {
clearConnectOnboardingRequest();
}
const queueAccountCleanup = (
previous: {
readonly userId: string;
@@ -114,6 +128,9 @@ function CloudAuthBridge(props: { readonly children: ReactNode }) {
}
previousTokenProviderRef.current = { userId, provider: tokenProvider };
activateCloudRelayAccount(userId, tokenProvider);
if (isAccountTransition) {
requestConnectOnboarding(userId);
}
};
const activateAfterTransition = (transition: Promise<void>) => {
void (async () => {
@@ -39,7 +39,7 @@ export function CloudWaitlistEnrollment(props: { readonly onSignIn: () => void }
You are on the waitlist
</Text>
<Text className="text-center font-sans text-base text-foreground-secondary">
We will email you when your T3 Cloud access is ready.
We will email you when your T3 Connect access is ready.
</Text>
<SignInAction onPress={props.onSignIn} />
</View>
@@ -0,0 +1,129 @@
import { NativeHeaderToolbar } from "../../native/StackHeader";
import { useAuth } from "@clerk/expo";
import { StackActions, useNavigation } from "@react-navigation/native";
import { useCallback, useEffect, useState } from "react";
import { Pressable, RefreshControl, ScrollView, View } from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { reportAtomCommandResult, settlePromise } from "@t3tools/client-runtime/state/runtime";
import { AppText as Text } from "../../components/AppText";
import { useRemoteConnections } from "../../state/use-remote-environment-registry";
import { CloudEnvironmentRows } from "../connection/CloudEnvironmentRows";
import { splitEnvironmentSections } from "../connection/environmentSections";
import { useConnectionController } from "../connection/useConnectionController";
import { optOutOfConnectOnboarding } from "./connectOnboardingOptOut";
import { hasCloudPublicConfig } from "./publicConfig";
/**
* Post-sign-in onboarding sheet for T3 Connect. Mobile never publishes
* environments itself — it consumes ones published elsewhere — so this simply
* surfaces the account's T3 Connect environments right after sign-in so every
* device can be connected in one go. It shows on every sign-in: sign-out
* clears the connected environments, so each new session starts from zero.
*/
export function ConnectOnboardingRouteScreen() {
const navigation = useNavigation();
// The route is deep-linkable; without cloud config the sheet would present
// empty with no chrome to dismiss it, so bail back out instead.
useEffect(() => {
if (hasCloudPublicConfig()) {
return;
}
if (navigation.canGoBack()) {
navigation.goBack();
} else {
navigation.dispatch(StackActions.replace("Home"));
}
}, [navigation]);
return hasCloudPublicConfig() ? <ConfiguredConnectOnboardingRouteScreen /> : null;
}
function ConfiguredConnectOnboardingRouteScreen() {
const navigation = useNavigation();
const insets = useSafeAreaInsets();
const { isSignedIn, userId } = useAuth({ treatPendingAsSignedOut: false });
const { connectedEnvironments, onReconnectEnvironment } = useRemoteConnections();
const { refreshRelayEnvironments } = useConnectionController();
const { connectedCloudEnvironments } = splitEnvironmentSections({
connectedEnvironments,
cloudEnvironments: null,
});
// Pull-to-refresh tracks its own spinner instead of discovery's refreshing
// flag, so background refreshes (e.g. the sign-in one) don't yank the
// content down.
const [isPullRefreshing, setIsPullRefreshing] = useState(false);
const handlePullRefresh = useCallback(() => {
void (async () => {
setIsPullRefreshing(true);
await refreshRelayEnvironments();
setIsPullRefreshing(false);
})();
}, [refreshRelayEnvironments]);
const handleClose = useCallback(() => {
navigation.goBack();
}, [navigation]);
// Persist before dismissing so a quick sign-out/sign-in cannot race ahead
// of the preference write; the write is a local secure-store update.
const handleDontShowAgain = useCallback(() => {
void (async () => {
if (userId) {
const result = await settlePromise(() => optOutOfConnectOnboarding(userId));
reportAtomCommandResult(result, { label: "connect onboarding opt-out" });
}
navigation.goBack();
})();
}, [navigation, userId]);
return (
<View collapsable={false} className="flex-1 bg-sheet">
<NativeHeaderToolbar placement="right">
<NativeHeaderToolbar.Button icon="xmark" onPress={handleClose} separateBackground />
</NativeHeaderToolbar>
<ScrollView
alwaysBounceVertical
contentInsetAdjustmentBehavior="automatic"
showsVerticalScrollIndicator={false}
style={{ flex: 1 }}
contentInset={{ bottom: Math.max(insets.bottom, 18) + 18 }}
contentContainerStyle={{
gap: 16,
paddingHorizontal: 20,
paddingTop: 16,
}}
refreshControl={
<RefreshControl refreshing={isPullRefreshing} onRefresh={handlePullRefresh} />
}
>
{isSignedIn ? (
<CloudEnvironmentRows
connectedCloudEnvironments={connectedCloudEnvironments}
onReconnectEnvironment={onReconnectEnvironment}
showHeader={false}
/>
) : (
<View collapsable={false} className="rounded-[24px] bg-card p-5">
<Text className="text-sm leading-normal text-foreground-muted">
Sign in to your T3 account to set up T3 Connect.
</Text>
</View>
)}
{userId ? (
<Pressable
accessibilityRole="button"
hitSlop={8}
onPress={handleDontShowAgain}
className="items-center py-1 active:opacity-70"
>
<Text className="text-xs text-foreground-muted">{"Don't show this again"}</Text>
</Pressable>
) : null}
</ScrollView>
</View>
);
}
@@ -0,0 +1,24 @@
import { Atom } from "effect/unstable/reactivity";
import { appAtomRegistry } from "../../state/atom-registry";
// Signals RootStackLayout (inside the navigation tree) that an in-session
// sign-in just completed. Holds the account id so a sign-out between the
// request and the navigation cannot present the sheet for the wrong account.
export const connectOnboardingRequestAtom = Atom.make<string | null>(null).pipe(
Atom.keepAlive,
Atom.withLabel("mobile:connect-onboarding-request"),
);
/**
* Requests the onboarding sheet for the given account. Sign-out clears the
* connected environments, so onboarding runs on every in-session sign-in —
* each new session starts with no connected devices.
*/
export function requestConnectOnboarding(accountId: string): void {
appAtomRegistry.set(connectOnboardingRequestAtom, accountId);
}
export function clearConnectOnboardingRequest(): void {
appAtomRegistry.set(connectOnboardingRequestAtom, null);
}
@@ -0,0 +1,49 @@
import { useAtomValue } from "@effect/atom-react";
import { useNavigation } from "@react-navigation/native";
import { useEffect } from "react";
import { appAtomRegistry } from "../../state/atom-registry";
import { clearConnectOnboardingRequest, connectOnboardingRequestAtom } from "./connectOnboarding";
import { isConnectOnboardingOptedOut } from "./connectOnboardingOptOut";
// Sign-in happens inside the Settings sheet; give its detent/session-state
// transitions a beat to settle before presenting another formSheet on top.
const PRESENT_ONBOARDING_DELAY_MS = 600;
/**
* Consumes the onboarding request inside the navigation tree (RootStackLayout)
* and presents the onboarding formSheet. Lives apart from connectOnboarding.ts
* so non-navigation consumers (CloudAuthProvider) do not pull
* @react-navigation into their module graph.
*/
export function useConnectOnboardingNavigation(): void {
const navigation = useNavigation();
const requestedAccountId = useAtomValue(connectOnboardingRequestAtom);
useEffect(() => {
if (requestedAccountId === null) {
return;
}
let cancelled = false;
const timer = setTimeout(() => {
void (async () => {
// A failed preference read prefers showing the sheet.
const optedOut = await isConnectOnboardingOptedOut(requestedAccountId).catch(() => false);
// The cancelled flag covers effect re-runs, but a sign-out can clear
// the request atom moments before this render commits — re-check the
// atom so a stale request never presents the sheet.
if (cancelled || appAtomRegistry.get(connectOnboardingRequestAtom) !== requestedAccountId) {
return;
}
clearConnectOnboardingRequest();
if (!optedOut) {
navigation.navigate("ConnectOnboarding");
}
})();
}, PRESENT_ONBOARDING_DELAY_MS);
return () => {
cancelled = true;
clearTimeout(timer);
};
}, [navigation, requestedAccountId]);
}
@@ -0,0 +1,21 @@
import { loadPreferences, updatePreferences } from "../../lib/storage";
// Lives apart from connectOnboarding.ts so CloudAuthProvider (which imports
// the request signal) never pulls lib/storage — expo-secure-store — into its
// module graph; that breaks CloudAuthProvider.test.ts suite loading.
/** Whether the account chose "Don't show this again". */
export async function isConnectOnboardingOptedOut(accountId: string): Promise<boolean> {
const preferences = await loadPreferences();
return preferences.connectOnboardingOptOutAccounts?.includes(accountId) ?? false;
}
/** Persists "Don't show this again" for the account. */
export async function optOutOfConnectOnboarding(accountId: string): Promise<void> {
await updatePreferences((current) => {
const optedOut = current.connectOnboardingOptOutAccounts ?? [];
return optedOut.includes(accountId)
? {}
: { connectOnboardingOptOutAccounts: [...optedOut, accountId] };
});
}
@@ -0,0 +1,379 @@
import { useAuth } from "@clerk/expo";
import { SymbolView } from "expo-symbols";
import {
connectionStatusText,
type EnvironmentConnectionPhase,
} from "@t3tools/client-runtime/connection";
import type { EnvironmentId } from "@t3tools/contracts";
import { useCallback, useState } from "react";
import {
ActivityIndicator,
Pressable,
Switch,
type NativeSyntheticEvent,
type TextLayoutEventData,
View,
} from "react-native";
import { AppText as Text } from "../../components/AppText";
import { cn } from "../../lib/cn";
import { copyTextWithHaptic } from "../../lib/copyTextWithHaptic";
import { useThemeColor } from "../../lib/useThemeColor";
import type { ConnectedEnvironmentSummary } from "../../state/remote-runtime-types";
import { availableCloudEnvironmentPresentation } from "../cloud/cloudEnvironmentPresentation";
import { ConnectionStatusDot } from "./ConnectionStatusDot";
import { type RelayEnvironmentView, useConnectionController } from "./useConnectionController";
/**
* "T3 Connect" section: every environment published to the signed-in account,
* with connect switches, availability status, refresh, and loading/error
* states. Shared between the Settings environments screen and the T3 Connect
* onboarding sheet.
*/
export function CloudEnvironmentRows(props: {
readonly connectedCloudEnvironments: ReadonlyArray<ConnectedEnvironmentSummary>;
readonly onReconnectEnvironment: (environmentId: EnvironmentId) => void;
/**
* Hide the "T3 Connect" section title + refresh button for hosts that
* provide their own chrome (the onboarding sheet's native header and
* pull-to-refresh).
*/
readonly showHeader?: boolean;
}) {
const { isSignedIn } = useAuth({ treatPendingAsSignedOut: false });
const controller = useConnectionController();
const iconColor = useThemeColor("--color-icon");
const availableCloudEnvironments = controller.availableRelayEnvironments;
const [expandedErrorId, setExpandedErrorId] = useState<string | null>(null);
const hasCloudRows =
props.connectedCloudEnvironments.length > 0 || availableCloudEnvironments.length > 0;
const handleConnectCloudEnvironment = useCallback(
(entry: RelayEnvironmentView) => controller.connectRelayEnvironment(entry.environment),
[controller],
);
const handleDisconnectCloudEnvironment = useCallback(
(environmentId: EnvironmentId) => controller.removeEnvironment(environmentId),
[controller],
);
const handleToggleCloudError = useCallback((environmentId: string) => {
setExpandedErrorId((current) => (current === environmentId ? null : environmentId));
}, []);
const showHeader = props.showHeader ?? true;
if (!isSignedIn) return null;
return (
<View collapsable={false} className={cn("gap-3", showHeader && "mt-5")}>
{showHeader ? (
<View className="flex-row items-center justify-between px-1">
<Text className="text-sm font-t3-bold uppercase text-foreground-muted">T3 Connect</Text>
<Pressable
accessibilityRole="button"
disabled={controller.relayDiscovery.isRefreshing}
onPress={() => {
void controller.refreshRelayEnvironments();
}}
className="h-9 w-9 items-center justify-center rounded-full bg-subtle active:opacity-70 disabled:opacity-50"
>
{controller.relayDiscovery.isRefreshing ? (
<ActivityIndicator color={iconColor} size="small" />
) : (
<SymbolView
name="arrow.clockwise"
size={14}
tintColor={iconColor}
type="monochrome"
/>
)}
</Pressable>
</View>
) : null}
{hasCloudRows ? (
<View collapsable={false} className="overflow-hidden rounded-[24px] bg-card">
{props.connectedCloudEnvironments.map((environment, index) => (
<ConnectedCloudEnvironmentRow
key={environment.environmentId}
environment={environment}
borderTop={index !== 0}
onConnect={() => props.onReconnectEnvironment(environment.environmentId)}
onDisconnect={() => handleDisconnectCloudEnvironment(environment.environmentId)}
errorExpanded={expandedErrorId === environment.environmentId}
onToggleError={() => handleToggleCloudError(environment.environmentId)}
/>
))}
{availableCloudEnvironments.map((environment, index) => (
<CloudEnvironmentRow
key={environment.environment.environmentId}
environment={environment}
borderTop={props.connectedCloudEnvironments.length > 0 || index !== 0}
onConnect={() => handleConnectCloudEnvironment(environment)}
errorExpanded={expandedErrorId === environment.environment.environmentId}
onToggleError={() => handleToggleCloudError(environment.environment.environmentId)}
/>
))}
</View>
) : controller.relayDiscovery.isRefreshing ? (
<View collapsable={false} className="items-center gap-3 rounded-[24px] bg-card p-6">
<ActivityIndicator color={iconColor} />
<Text className="text-center text-sm leading-normal text-foreground-muted">
Loading linked cloud environments.
</Text>
</View>
) : controller.relayDiscovery.error ? null : (
<View collapsable={false} className="rounded-[24px] bg-card p-5">
<Text className="text-sm leading-normal text-foreground-muted">
No additional linked cloud environments.
</Text>
</View>
)}
{/* Rendered alongside any connected rows — a failed discovery must not
hide behind an otherwise-healthy list. */}
{controller.relayDiscovery.error && !controller.relayDiscovery.isRefreshing ? (
<View collapsable={false} className="gap-3 rounded-[24px] bg-card p-5">
<Text className="text-base font-t3-bold text-foreground">
Could not load T3 Connect environments
</Text>
<Text className="text-sm text-foreground-muted">{controller.relayDiscovery.error}</Text>
{controller.relayDiscovery.errorTraceId ? (
<CopyTraceIdButton traceId={controller.relayDiscovery.errorTraceId} />
) : null}
<Pressable
accessibilityRole="button"
onPress={() => {
void controller.refreshRelayEnvironments();
}}
className="self-start rounded-full bg-subtle px-3.5 py-2 active:opacity-70"
>
<Text className="text-xs font-t3-bold text-foreground">Try again</Text>
</Pressable>
</View>
) : null}
</View>
);
}
function ConnectedCloudEnvironmentRow(props: {
readonly environment: ConnectedEnvironmentSummary;
readonly borderTop: boolean;
readonly errorExpanded: boolean;
readonly onConnect: () => void;
readonly onDisconnect: () => void;
readonly onToggleError: () => void;
}) {
return (
<CloudEnvironmentRowShell
borderTop={props.borderTop}
connectionError={props.environment.connectionError}
connectionErrorTraceId={props.environment.connectionErrorTraceId}
connectionState={props.environment.connectionState}
errorExpanded={props.errorExpanded}
label={props.environment.environmentLabel}
onValueChange={(enabled) => {
if (enabled) {
props.onConnect();
return;
}
props.onDisconnect();
}}
onToggleError={props.onToggleError}
value={props.environment.connectionState !== "available"}
/>
);
}
function CloudEnvironmentRow(props: {
readonly environment: RelayEnvironmentView;
readonly borderTop: boolean;
readonly errorExpanded: boolean;
readonly onConnect: () => void;
readonly onToggleError: () => void;
}) {
const presentation = availableCloudEnvironmentPresentation({
isStatusPending: props.environment.availability === "checking",
status: props.environment.status,
statusError: props.environment.error,
statusErrorTraceId: props.environment.traceId,
});
return (
<CloudEnvironmentRowShell
borderTop={props.borderTop}
connectionError={presentation.connectionError}
connectionErrorTraceId={presentation.connectionErrorTraceId}
connectionState={presentation.connectionState}
errorExpanded={props.errorExpanded}
label={props.environment.environment.label}
onValueChange={(enabled) => {
if (enabled) {
props.onConnect();
}
}}
onToggleError={props.onToggleError}
statusText={presentation.statusText}
value={false}
/>
);
}
function CloudEnvironmentRowShell(props: {
readonly borderTop: boolean;
readonly connectionError: string | null;
readonly connectionErrorTraceId: string | null;
readonly connectionState: EnvironmentConnectionPhase;
readonly disabled?: boolean;
readonly errorExpanded: boolean;
readonly label: string;
readonly onToggleError: () => void;
readonly onValueChange: (enabled: boolean) => void;
readonly statusText?: string;
readonly value: boolean;
}) {
const activeTrack = String(useThemeColor("--color-switch-active"));
const track = String(useThemeColor("--color-secondary-border"));
const chevron = useThemeColor("--color-chevron");
const isRetrying =
props.connectionState === "connecting" || props.connectionState === "reconnecting";
const shouldPulse = isRetrying;
const statusText =
props.statusText ??
connectionStatusText({
phase: props.connectionState,
error: props.connectionError,
traceId: props.connectionErrorTraceId,
});
const statusClassName = props.connectionError
? "text-rose-500 dark:text-rose-400"
: "text-foreground-muted";
const [errorMeasurement, setErrorMeasurement] = useState<{
readonly text: string;
readonly lineCount: number;
} | null>(null);
const errorTraceId = props.connectionErrorTraceId;
const measuredErrorText = errorTraceId ? `${statusText} Trace ID: ${errorTraceId}` : statusText;
const errorLineCount =
errorMeasurement?.text === measuredErrorText ? errorMeasurement.lineCount : 0;
const errorCanExpand = props.connectionError !== null && errorLineCount > 1;
const isErrorExpanded = errorCanExpand && props.errorExpanded;
const StatusContainer = errorCanExpand ? Pressable : View;
const onMeasuredErrorTextLayout = useCallback(
(event: NativeSyntheticEvent<TextLayoutEventData>) => {
if (!props.connectionError) {
return;
}
const nextLineCount = event.nativeEvent.lines.length;
setErrorMeasurement((currentMeasurement) =>
currentMeasurement?.text === measuredErrorText &&
currentMeasurement.lineCount === nextLineCount
? currentMeasurement
: { text: measuredErrorText, lineCount: nextLineCount },
);
},
[measuredErrorText, props.connectionError],
);
return (
<View
collapsable={false}
className={cn(
"flex-row items-center gap-3 bg-card px-4 py-3.5",
props.borderTop && "border-t border-border",
)}
>
<View className="min-w-0 flex-1 gap-0.5">
<View className="min-w-0 flex-row items-center gap-2">
<ConnectionStatusDot state={props.connectionState} pulse={shouldPulse} size={7} />
<Text
className="min-w-0 flex-shrink text-base font-t3-bold leading-snug text-foreground"
numberOfLines={1}
>
{props.label}
</Text>
</View>
{props.connectionError ? (
<Text
aria-hidden
className={cn("absolute left-0 right-0 text-xs", statusClassName)}
onTextLayout={onMeasuredErrorTextLayout}
style={{ opacity: 0, zIndex: -1 }}
>
{measuredErrorText}
</Text>
) : null}
<StatusContainer
{...(errorCanExpand
? { accessibilityRole: "button" as const, onPress: props.onToggleError }
: {})}
className="min-w-0 flex-row items-start gap-1"
>
<Text
className={cn("min-w-0 flex-1 text-xs", statusClassName)}
numberOfLines={isErrorExpanded ? undefined : 1}
>
{statusText}
{errorTraceId ? (
<>
{" Trace ID: "}
<Text
accessibilityHint="Copies the trace ID"
accessibilityRole="button"
className={cn("text-xs underline", statusClassName)}
onLongPress={(event) => {
event.stopPropagation();
copyTextWithHaptic(errorTraceId, { target: "connection-trace-id" });
}}
onPress={(event) => {
event.stopPropagation();
}}
style={{ textDecorationStyle: "dotted" }}
>
{errorTraceId}
</Text>
</>
) : null}
</Text>
{errorCanExpand ? (
<SymbolView
name="chevron.down"
size={10}
tintColor={chevron}
type="monochrome"
style={{
marginTop: 3,
transform: [{ rotate: isErrorExpanded ? "180deg" : "0deg" }],
}}
/>
) : null}
</StatusContainer>
</View>
<Switch
disabled={props.disabled}
ios_backgroundColor={track}
onValueChange={props.onValueChange}
trackColor={{ false: track, true: activeTrack }}
value={props.value}
/>
</View>
);
}
function CopyTraceIdButton(props: { readonly traceId: string }) {
const iconColor = useThemeColor("--color-icon");
return (
<Pressable
accessibilityRole="button"
onPress={() => {
copyTextWithHaptic(props.traceId, { target: "connection-trace-id" });
}}
className="self-start flex-row items-center gap-1.5 rounded-full bg-subtle px-3 py-2 active:opacity-70"
>
<SymbolView name="doc.on.doc" size={12} tintColor={iconColor} type="monochrome" />
<Text className="text-xs font-t3-bold text-foreground">Copy trace ID</Text>
</Pressable>
);
}
@@ -135,7 +135,7 @@ export function ConnectionEnvironmentRow(props: {
>
{props.environment.isRelayManaged ? (
<Text className="text-sm text-foreground-muted">
Managed by T3 Cloud. Tunnel details update automatically.
Managed by T3 Connect. Tunnel details update automatically.
</Text>
) : (
<>
@@ -35,7 +35,7 @@ function cloudEnvironment(environmentId: string): RelayClientEnvironmentRecord {
}
describe("mobile environment settings sections", () => {
it("keeps saved relay-managed connections under T3 Cloud", () => {
it("keeps saved relay-managed connections under T3 Connect", () => {
const local = connectedEnvironment({
environmentId: "environment-local",
isRelayManaged: false,
@@ -112,7 +112,12 @@ function AddProjectShell(props: { readonly children: ReactNode }) {
const insets = useSafeAreaInsets();
return (
<View className="flex-1 bg-sheet">
// collapsable={false} is load-bearing: if this wrapper is flattened, the
// ScrollView lands directly under RNSSafeAreaView and RNS's formSheet
// scroll-view frame correction mistakes this full-height wrapper for a
// "header" sibling, coercing the ScrollView to zero height (blank sheet
// as soon as the sheet re-lays-out, e.g. when the keyboard opens).
<View collapsable={false} className="flex-1 bg-sheet">
<ScrollView
keyboardShouldPersistTaps="handled"
contentInsetAdjustmentBehavior="automatic"
@@ -1,38 +1,18 @@
import { useAuth } from "@clerk/expo";
import { NativeHeaderToolbar } from "../../native/StackHeader";
import { useNavigation } from "@react-navigation/native";
import { SymbolView } from "expo-symbols";
import {
connectionStatusText,
type EnvironmentConnectionPhase,
} from "@t3tools/client-runtime/connection";
import type { EnvironmentId } from "@t3tools/contracts";
import { useCallback, useState } from "react";
import {
ActivityIndicator,
Pressable,
ScrollView,
Switch,
type NativeSyntheticEvent,
type TextLayoutEventData,
View,
} from "react-native";
import { ScrollView, View } from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { AppText as Text } from "../../components/AppText";
import {
type RelayEnvironmentView,
useConnectionController,
} from "../connection/useConnectionController";
import { hasCloudPublicConfig } from "../cloud/publicConfig";
import { availableCloudEnvironmentPresentation } from "../cloud/cloudEnvironmentPresentation";
import { CloudEnvironmentRows } from "../connection/CloudEnvironmentRows";
import { ConnectionEnvironmentRow } from "../connection/ConnectionEnvironmentRow";
import { ConnectionStatusDot } from "../connection/ConnectionStatusDot";
import { splitEnvironmentSections } from "../connection/environmentSections";
import { cn } from "../../lib/cn";
import { copyTextWithHaptic } from "../../lib/copyTextWithHaptic";
import { useThemeColor } from "../../lib/useThemeColor";
import type { ConnectedEnvironmentSummary } from "../../state/remote-runtime-types";
import { useRemoteConnections } from "../../state/use-remote-environment-registry";
export function SettingsEnvironmentsRouteScreen() {
@@ -117,7 +97,7 @@ export function SettingsEnvironmentsRouteScreen() {
)}
{hasCloudPublicConfig() ? (
<ConfiguredCloudEnvironmentRows
<CloudEnvironmentRows
connectedCloudEnvironments={connectedCloudEnvironments}
onReconnectEnvironment={onReconnectEnvironment}
/>
@@ -126,323 +106,3 @@ export function SettingsEnvironmentsRouteScreen() {
</View>
);
}
function ConfiguredCloudEnvironmentRows(props: {
readonly connectedCloudEnvironments: ReadonlyArray<ConnectedEnvironmentSummary>;
readonly onReconnectEnvironment: (environmentId: EnvironmentId) => void;
}) {
const { isSignedIn } = useAuth({ treatPendingAsSignedOut: false });
const controller = useConnectionController();
const iconColor = useThemeColor("--color-icon");
const availableCloudEnvironments = controller.availableRelayEnvironments;
const [expandedErrorId, setExpandedErrorId] = useState<string | null>(null);
const hasCloudRows =
props.connectedCloudEnvironments.length > 0 || availableCloudEnvironments.length > 0;
const handleConnectCloudEnvironment = useCallback(
(entry: RelayEnvironmentView) => controller.connectRelayEnvironment(entry.environment),
[controller],
);
const handleDisconnectCloudEnvironment = useCallback(
(environmentId: EnvironmentId) => controller.removeEnvironment(environmentId),
[controller],
);
const handleToggleCloudError = useCallback((environmentId: string) => {
setExpandedErrorId((current) => (current === environmentId ? null : environmentId));
}, []);
if (!isSignedIn) return null;
return (
<View collapsable={false} className="mt-5 gap-3">
<View className="flex-row items-center justify-between px-1">
<Text className="text-sm font-t3-bold uppercase text-foreground-muted">T3 Cloud</Text>
<Pressable
accessibilityRole="button"
disabled={controller.relayDiscovery.isRefreshing}
onPress={() => {
void controller.refreshRelayEnvironments();
}}
className="h-9 w-9 items-center justify-center rounded-full bg-subtle active:opacity-70 disabled:opacity-50"
>
{controller.relayDiscovery.isRefreshing ? (
<ActivityIndicator color={iconColor} size="small" />
) : (
<SymbolView name="arrow.clockwise" size={14} tintColor={iconColor} type="monochrome" />
)}
</Pressable>
</View>
{hasCloudRows ? (
<View collapsable={false} className="overflow-hidden rounded-[24px] bg-card">
{props.connectedCloudEnvironments.map((environment, index) => (
<ConnectedCloudEnvironmentRow
key={environment.environmentId}
environment={environment}
borderTop={index !== 0}
onConnect={() => props.onReconnectEnvironment(environment.environmentId)}
onDisconnect={() => handleDisconnectCloudEnvironment(environment.environmentId)}
errorExpanded={expandedErrorId === environment.environmentId}
onToggleError={() => handleToggleCloudError(environment.environmentId)}
/>
))}
{availableCloudEnvironments.map((environment, index) => (
<CloudEnvironmentRow
key={environment.environment.environmentId}
environment={environment}
borderTop={props.connectedCloudEnvironments.length > 0 || index !== 0}
onConnect={() => handleConnectCloudEnvironment(environment)}
errorExpanded={expandedErrorId === environment.environment.environmentId}
onToggleError={() => handleToggleCloudError(environment.environment.environmentId)}
/>
))}
</View>
) : controller.relayDiscovery.isRefreshing ? (
<View collapsable={false} className="items-center gap-3 rounded-[24px] bg-card p-6">
<ActivityIndicator color={iconColor} />
<Text className="text-center text-sm leading-normal text-foreground-muted">
Loading linked cloud environments.
</Text>
</View>
) : controller.relayDiscovery.error ? (
<View collapsable={false} className="gap-3 rounded-[24px] bg-card p-5">
<Text className="text-base font-t3-bold text-foreground">
Could not load T3 Cloud environments
</Text>
<Text className="text-sm text-foreground-muted">{controller.relayDiscovery.error}</Text>
{controller.relayDiscovery.errorTraceId ? (
<CopyTraceIdButton traceId={controller.relayDiscovery.errorTraceId} />
) : null}
</View>
) : (
<View collapsable={false} className="rounded-[24px] bg-card p-5">
<Text className="text-sm leading-normal text-foreground-muted">
No additional linked cloud environments.
</Text>
</View>
)}
</View>
);
}
function ConnectedCloudEnvironmentRow(props: {
readonly environment: ConnectedEnvironmentSummary;
readonly borderTop: boolean;
readonly errorExpanded: boolean;
readonly onConnect: () => void;
readonly onDisconnect: () => void;
readonly onToggleError: () => void;
}) {
return (
<CloudEnvironmentRowShell
borderTop={props.borderTop}
connectionError={props.environment.connectionError}
connectionErrorTraceId={props.environment.connectionErrorTraceId}
connectionState={props.environment.connectionState}
errorExpanded={props.errorExpanded}
label={props.environment.environmentLabel}
onValueChange={(enabled) => {
if (enabled) {
props.onConnect();
return;
}
props.onDisconnect();
}}
onToggleError={props.onToggleError}
value={props.environment.connectionState !== "available"}
/>
);
}
function CloudEnvironmentRow(props: {
readonly environment: RelayEnvironmentView;
readonly borderTop: boolean;
readonly errorExpanded: boolean;
readonly onConnect: () => void;
readonly onToggleError: () => void;
}) {
const presentation = availableCloudEnvironmentPresentation({
isStatusPending: props.environment.availability === "checking",
status: props.environment.status,
statusError: props.environment.error,
statusErrorTraceId: props.environment.traceId,
});
return (
<CloudEnvironmentRowShell
borderTop={props.borderTop}
connectionError={presentation.connectionError}
connectionErrorTraceId={presentation.connectionErrorTraceId}
connectionState={presentation.connectionState}
errorExpanded={props.errorExpanded}
label={props.environment.environment.label}
onValueChange={(enabled) => {
if (enabled) {
props.onConnect();
}
}}
onToggleError={props.onToggleError}
statusText={presentation.statusText}
value={false}
/>
);
}
function CloudEnvironmentRowShell(props: {
readonly borderTop: boolean;
readonly connectionError: string | null;
readonly connectionErrorTraceId: string | null;
readonly connectionState: EnvironmentConnectionPhase;
readonly disabled?: boolean;
readonly errorExpanded: boolean;
readonly label: string;
readonly onToggleError: () => void;
readonly onValueChange: (enabled: boolean) => void;
readonly statusText?: string;
readonly value: boolean;
}) {
const activeTrack = String(useThemeColor("--color-switch-active"));
const track = String(useThemeColor("--color-secondary-border"));
const chevron = useThemeColor("--color-chevron");
const isRetrying =
props.connectionState === "connecting" || props.connectionState === "reconnecting";
const shouldPulse = isRetrying;
const statusText =
props.statusText ??
connectionStatusText({
phase: props.connectionState,
error: props.connectionError,
traceId: props.connectionErrorTraceId,
});
const statusClassName = props.connectionError
? "text-rose-500 dark:text-rose-400"
: "text-foreground-muted";
const [errorMeasurement, setErrorMeasurement] = useState<{
readonly text: string;
readonly lineCount: number;
} | null>(null);
const errorTraceId = props.connectionErrorTraceId;
const measuredErrorText = errorTraceId ? `${statusText} Trace ID: ${errorTraceId}` : statusText;
const errorLineCount =
errorMeasurement?.text === measuredErrorText ? errorMeasurement.lineCount : 0;
const errorCanExpand = props.connectionError !== null && errorLineCount > 1;
const isErrorExpanded = errorCanExpand && props.errorExpanded;
const StatusContainer = errorCanExpand ? Pressable : View;
const onMeasuredErrorTextLayout = useCallback(
(event: NativeSyntheticEvent<TextLayoutEventData>) => {
if (!props.connectionError) {
return;
}
const nextLineCount = event.nativeEvent.lines.length;
setErrorMeasurement((currentMeasurement) =>
currentMeasurement?.text === measuredErrorText &&
currentMeasurement.lineCount === nextLineCount
? currentMeasurement
: { text: measuredErrorText, lineCount: nextLineCount },
);
},
[measuredErrorText, props.connectionError],
);
return (
<View
collapsable={false}
className={cn(
"flex-row items-center gap-3 bg-card px-4 py-3.5",
props.borderTop && "border-t border-border",
)}
>
<View className="min-w-0 flex-1 gap-0.5">
<View className="min-w-0 flex-row items-center gap-2">
<ConnectionStatusDot state={props.connectionState} pulse={shouldPulse} size={7} />
<Text
className="min-w-0 flex-shrink text-base font-t3-bold leading-snug text-foreground"
numberOfLines={1}
>
{props.label}
</Text>
</View>
{props.connectionError ? (
<Text
aria-hidden
className={cn("absolute left-0 right-0 text-xs", statusClassName)}
onTextLayout={onMeasuredErrorTextLayout}
style={{ opacity: 0, zIndex: -1 }}
>
{measuredErrorText}
</Text>
) : null}
<StatusContainer
{...(errorCanExpand
? { accessibilityRole: "button" as const, onPress: props.onToggleError }
: {})}
className="min-w-0 flex-row items-start gap-1"
>
<Text
className={cn("min-w-0 flex-1 text-xs", statusClassName)}
numberOfLines={isErrorExpanded ? undefined : 1}
>
{statusText}
{errorTraceId ? (
<>
{" Trace ID: "}
<Text
accessibilityHint="Copies the trace ID"
accessibilityRole="button"
className={cn("text-xs underline", statusClassName)}
onLongPress={(event) => {
event.stopPropagation();
copyTextWithHaptic(errorTraceId, { target: "connection-trace-id" });
}}
onPress={(event) => {
event.stopPropagation();
}}
style={{ textDecorationStyle: "dotted" }}
>
{errorTraceId}
</Text>
</>
) : null}
</Text>
{errorCanExpand ? (
<SymbolView
name="chevron.down"
size={10}
tintColor={chevron}
type="monochrome"
style={{
marginTop: 3,
transform: [{ rotate: isErrorExpanded ? "180deg" : "0deg" }],
}}
/>
) : null}
</StatusContainer>
</View>
<Switch
disabled={props.disabled}
ios_backgroundColor={track}
onValueChange={props.onValueChange}
trackColor={{ false: track, true: activeTrack }}
value={props.value}
/>
</View>
);
}
function CopyTraceIdButton(props: { readonly traceId: string }) {
const iconColor = useThemeColor("--color-icon");
return (
<Pressable
accessibilityRole="button"
onPress={() => {
copyTextWithHaptic(props.traceId, { target: "connection-trace-id" });
}}
className="self-start flex-row items-center gap-1.5 rounded-full bg-subtle px-3 py-2 active:opacity-70"
>
<SymbolView name="doc.on.doc" size={12} tintColor={iconColor} type="monochrome" />
<Text className="text-xs font-t3-bold text-foreground">Copy trace ID</Text>
</Pressable>
);
}
@@ -240,8 +240,8 @@ function ConfiguredSettingsRouteScreen() {
const promptSignIn = useCallback(() => {
Alert.alert(
"Request T3 Cloud access",
"Live Activity updates require approved T3 Cloud access so relay can deliver updates to this device.",
"Request T3 Connect access",
"Live Activity updates require approved T3 Connect access so relay can deliver updates to this device.",
[
{ text: "Cancel", style: "cancel" },
{
+29 -7
View File
@@ -69,6 +69,8 @@ export interface Preferences {
/** Code/diff font size override; null/absent means derived from baseFontSize. */
readonly codeFontSize?: number | null;
readonly codeWordBreak?: boolean;
/** Cloud account ids that opted out of the T3 Connect onboarding sheet. */
readonly connectOnboardingOptOutAccounts?: ReadonlyArray<string>;
}
async function readStorageItem(key: MobileStorageKeyValue): Promise<string | null> {
@@ -167,6 +169,7 @@ export async function loadPreferences(): Promise<Preferences> {
markdownFontSize?: number;
codeFontSize?: number | null;
codeWordBreak?: boolean;
connectOnboardingOptOutAccounts?: ReadonlyArray<string>;
} = {};
if (typeof parsed.liveActivitiesEnabled === "boolean") {
@@ -187,18 +190,37 @@ export async function loadPreferences(): Promise<Preferences> {
if (typeof parsed.codeWordBreak === "boolean") {
preferences.codeWordBreak = parsed.codeWordBreak;
}
if (Array.isArray(parsed.connectOnboardingOptOutAccounts)) {
preferences.connectOnboardingOptOutAccounts = parsed.connectOnboardingOptOutAccounts.filter(
(account): account is string => typeof account === "string",
);
}
return preferences;
}
// Preference writes are read-modify-write over one JSON blob; concurrent
// writers would drop each other's fields, so all writes are serialized here.
let preferencesWriteQueue: Promise<unknown> = Promise.resolve();
export async function updatePreferences(
update: (current: Preferences) => Partial<Preferences>,
): Promise<Preferences> {
const task = preferencesWriteQueue.then(async () => {
const current = await loadPreferences();
const next: Preferences = {
...current,
...update(current),
};
await writeJsonStorageItem(PREFERENCES_KEY, next);
return next;
});
preferencesWriteQueue = task.catch(() => undefined);
return task;
}
export async function savePreferencesPatch(patch: Partial<Preferences>): Promise<Preferences> {
const current = await loadPreferences();
const next: Preferences = {
...current,
...patch,
};
await writeJsonStorageItem(PREFERENCES_KEY, next);
return next;
return updatePreferences(() => patch);
}
export async function loadOrCreateAgentAwarenessDeviceId(): Promise<string> {
@@ -199,6 +199,70 @@ describe("AgentActivity widget layout", () => {
).not.toContain("widgetURL");
});
it("leads with the outcome instead of a zero count when nothing is active", () => {
const layout = AgentActivity(
{
...props,
subtitle: "Agent work completed",
activeCount: 0,
activities: [makeRow({ phase: "completed", status: "Done" })],
},
environment as never,
);
const banner = JSON.stringify(layout.banner);
expect(banner).toContain("Agent work completed");
expect(banner).not.toContain("0 active");
expect(banner).toContain("#6ee7b7"); // emerald-300 header tint
expect(JSON.stringify(layout.compactTrailing)).toContain("Done");
expect(JSON.stringify(layout.compactTrailing)).not.toContain("0 active");
expect(JSON.stringify(layout.expandedLeading)).toContain("Done");
expect(JSON.stringify(layout.minimal)).toContain("checkmark.circle.fill");
expect(JSON.stringify(layout.bannerSmall)).toContain("Done");
});
it("reads Failed when the finished work ended in failure", () => {
const layout = AgentActivity(
{
...props,
subtitle: "Agent work failed",
activeCount: 0,
activities: [makeRow({ phase: "failed", status: "Failed" })],
},
environment as never,
);
const banner = JSON.stringify(layout.banner);
expect(banner).toContain("Agent work failed");
expect(banner).toContain("#fca5a5"); // red-300 header tint
expect(JSON.stringify(layout.compactTrailing)).toContain("Failed");
expect(JSON.stringify(layout.expandedLeading)).toContain("Failed");
expect(JSON.stringify(layout.minimal)).toContain("xmark.octagon.fill");
});
it("lets a failure dominate mixed finished outcomes across every presentation", () => {
const layout = AgentActivity(
{
...props,
// The server subtitle keys off the newest terminal row (completed
// here); the layout must still read Failed everywhere so the header
// text never disagrees with the tint, count slots, or minimal glyph.
subtitle: "Agent work completed",
activeCount: 0,
activities: [
makeRow({ phase: "completed", status: "Done" }),
makeRow({ threadId: "thread-2", phase: "failed", status: "Failed" }),
],
},
environment as never,
);
const banner = JSON.stringify(layout.banner);
expect(banner).toContain("Agent work failed");
expect(banner).not.toContain("Agent work completed");
expect(banner).toContain("#fca5a5"); // red-300 header tint
expect(JSON.stringify(layout.compactTrailing)).toContain("Failed");
expect(JSON.stringify(layout.expandedLeading)).toContain("Failed");
expect(JSON.stringify(layout.minimal)).toContain("xmark.octagon.fill");
});
it("renders up to five rows in the banner", () => {
const layout = AgentActivity(
{
+21 -8
View File
@@ -123,16 +123,28 @@ export function AgentActivity(
? phaseTint(failedRow.phase)
: tint;
// With nothing active the aggregate only carries recently finished work, so
// "0 active agents" (and a lone "0" in the expanded island) read as broken.
// Lead with the outcome instead. The outcome is derived here from the rows
// rather than taken from the server subtitle (which keys off the newest
// terminal row): every presentation — header text, tint, count slots,
// minimal glyph — must agree, and a failure anywhere should dominate a
// newer success.
const allDone = props.activeCount === 0;
const doneLabel = failedRow ? "Failed" : "Done";
const outcomeLabel = failedRow ? "Agent work failed" : "Agent work completed";
// Header copy: "5 active agents" + (", 1 needs attention"). The banner renders
// the two parts in-line so the attention half can carry the accent color;
// `summary` is the short form for tight spots (expanded center, watch card).
const agentWord = props.activeCount === 1 ? "agent" : "agents";
const agentsLabel = `${props.activeCount} active ${agentWord}`;
const agentsLabel = allDone ? outcomeLabel : `${props.activeCount} active ${agentWord}`;
const attentionSuffix =
attentionRows.length > 0
? `${attentionRows.length} need${attentionRows.length === 1 ? "s" : ""} attention`
: "";
const summary = attentionSuffix || `${props.activeCount} active`;
const activeLabel = allDone ? doneLabel : `${props.activeCount} active`;
const summary = attentionSuffix || activeLabel;
// Any registered scheme variant routes back to this app; taps are delivered
// to the widget's containing app, so the prod scheme is safe for all builds.
@@ -142,8 +154,6 @@ export function AgentActivity(
? `t3code://${deepLinkRow.deepLink.slice(1)}`
: null;
const activeLabel = `${props.activeCount} active`;
// A scannable status glyph per phase — reads faster than colored words and
// ties the compact / expanded / banner / watch presentations together.
type SFName = NonNullable<ComponentProps<typeof Image>["systemName"]>;
@@ -245,7 +255,9 @@ export function AgentActivity(
<Text
modifiers={[
font({ weight: "semibold", size: 13 }),
foregroundStyle(primaryForeground),
// The all-done header carries the outcome tint (emerald /
// red) the way the Done/Failed status labels do.
foregroundStyle(allDone ? headerTint : primaryForeground),
lineLimit(1),
]}
>
@@ -322,16 +334,17 @@ export function AgentActivity(
</Text>
),
// The shared/minimal form is a ~22pt circle — a single signal reads there,
// the wordmark does not. Show the blocking phase glyph, else the mark.
// the wordmark does not. Show the blocking/outcome phase glyph, else the
// mark (all-done shows the hero row's checkmark/cross).
minimal:
attentionRow || failedRow
(attentionRow || failedRow || allDone) && heroRow
? renderGlyph(phaseSymbol(heroRow.phase), 13, phaseTint(heroRow.phase))
: renderLogo(11, tint),
expandedLeading: (
<HStack spacing={5} alignment="center" modifiers={[padding({ leading: 4, vertical: 4 })]}>
{renderLogo(15, tint)}
<Text modifiers={[font({ weight: "bold", size: 13 }), foregroundStyle(tint)]}>
{`${props.activeCount}`}
{allDone ? doneLabel : `${props.activeCount}`}
</Text>
</HStack>
),
@@ -102,6 +102,7 @@ describe("OrchestrationEngine", () => {
return savedEvent;
}),
readFromSequence: () => Stream.empty,
readAggregateFromSequence: () => Stream.empty,
readAll: () =>
Stream.fail(
new PersistenceSqlError({
@@ -477,6 +478,112 @@ describe("OrchestrationEngine", () => {
await system.dispose();
});
it("does not regress a generated branch to a stale temporary worktree branch", async () => {
const system = await createOrchestrationSystem();
const { engine } = system;
const createdAt = now();
await system.run(
engine.dispatch({
type: "project.create",
commandId: CommandId.make("cmd-branch-race-project-create"),
projectId: asProjectId("project-branch-race"),
title: "Branch Race Project",
workspaceRoot: "/tmp/project-branch-race",
defaultModelSelection: {
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5-codex",
},
createdAt,
}),
);
await system.run(
engine.dispatch({
type: "thread.create",
commandId: CommandId.make("cmd-branch-race-thread-create"),
threadId: ThreadId.make("thread-branch-race"),
projectId: asProjectId("project-branch-race"),
title: "Branch Race Thread",
modelSelection: {
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5-codex",
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
branch: "t3code/generated-branch-name",
worktreePath: "/tmp/project-branch-race-worktree",
createdAt,
}),
);
await system.run(
engine.dispatch({
type: "thread.meta.update",
commandId: CommandId.make("cmd-stale-temporary-branch-sync"),
threadId: ThreadId.make("thread-branch-race"),
branch: "t3code/1234abcd",
expectedBranch: "t3code/1234abcd",
}),
);
const snapshot = await system.readModel();
expect(snapshot.threads[0]?.branch).toBe("t3code/generated-branch-name");
await system.dispose();
});
it("allows authoritative worktree bootstrap to assign a temporary branch", async () => {
const system = await createOrchestrationSystem();
const { engine } = system;
const createdAt = now();
await system.run(
engine.dispatch({
type: "project.create",
commandId: CommandId.make("cmd-worktree-bootstrap-project-create"),
projectId: asProjectId("project-worktree-bootstrap"),
title: "Worktree Bootstrap Project",
workspaceRoot: "/tmp/project-worktree-bootstrap",
defaultModelSelection: {
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5-codex",
},
createdAt,
}),
);
await system.run(
engine.dispatch({
type: "thread.create",
commandId: CommandId.make("cmd-worktree-bootstrap-thread-create"),
threadId: ThreadId.make("thread-worktree-bootstrap"),
projectId: asProjectId("project-worktree-bootstrap"),
title: "Worktree Bootstrap Thread",
modelSelection: {
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5-codex",
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
branch: "main",
worktreePath: null,
createdAt,
}),
);
await system.run(
engine.dispatch({
type: "thread.meta.update",
commandId: CommandId.make("cmd-authoritative-worktree-bootstrap"),
threadId: ThreadId.make("thread-worktree-bootstrap"),
branch: "t3code/1234abcd",
worktreePath: "/tmp/project-worktree-bootstrap-worktree",
}),
);
const snapshot = await system.readModel();
expect(snapshot.threads[0]?.branch).toBe("t3code/1234abcd");
expect(snapshot.threads[0]?.worktreePath).toBe("/tmp/project-worktree-bootstrap-worktree");
await system.dispose();
});
it("records command ack duration using the first committed event type", async () => {
const system = await createOrchestrationSystem();
const { engine } = system;
@@ -666,6 +773,16 @@ describe("OrchestrationEngine", () => {
readFromSequence(sequenceExclusive) {
return Stream.fromIterable(events.filter((event) => event.sequence > sequenceExclusive));
},
readAggregateFromSequence(aggregateKind, aggregateId, sequenceExclusive) {
return Stream.fromIterable(
events.filter(
(event) =>
event.aggregateKind === aggregateKind &&
event.aggregateId === aggregateId &&
event.sequence > sequenceExclusive,
),
);
},
readAll() {
return Stream.fromIterable(events);
},
@@ -898,6 +1015,16 @@ describe("OrchestrationEngine", () => {
readFromSequence(sequenceExclusive) {
return Stream.fromIterable(events.filter((event) => event.sequence > sequenceExclusive));
},
readAggregateFromSequence(aggregateKind, aggregateId, sequenceExclusive) {
return Stream.fromIterable(
events.filter(
(event) =>
event.aggregateKind === aggregateKind &&
event.aggregateId === aggregateId &&
event.sequence > sequenceExclusive,
),
);
},
readAll() {
return Stream.fromIterable(events);
},
@@ -309,6 +309,14 @@ const makeOrchestrationEngine = Effect.gen(function* () {
const readEvents: OrchestrationEngineShape["readEvents"] = (fromSequenceExclusive, limit) =>
eventStore.readFromSequence(fromSequenceExclusive, limit);
const readAggregateEvents: OrchestrationEngineShape["readAggregateEvents"] = (
aggregateKind,
aggregateId,
fromSequenceExclusive,
limit,
) =>
eventStore.readAggregateFromSequence(aggregateKind, aggregateId, fromSequenceExclusive, limit);
const dispatch: OrchestrationEngineShape["dispatch"] = (command) =>
Effect.gen(function* () {
const result = yield* Deferred.make<{ sequence: number }, OrchestrationDispatchError>();
@@ -322,6 +330,7 @@ const makeOrchestrationEngine = Effect.gen(function* () {
return {
readEvents,
readAggregateEvents,
dispatch,
// Each access creates a fresh PubSub subscription so that multiple
// consumers (wsServer, ProviderRuntimeIngestion, CheckpointReactor, etc.)
@@ -2013,6 +2013,107 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => {
}),
);
it.effect("updates shell summary fields incrementally for message events", () =>
Effect.gen(function* () {
const projectionPipeline = yield* OrchestrationProjectionPipeline;
const eventStore = yield* OrchestrationEventStore;
const sql = yield* SqlClient.SqlClient;
const appendAndProject = (event: Parameters<typeof eventStore.append>[0]) =>
eventStore
.append(event)
.pipe(Effect.flatMap((savedEvent) => projectionPipeline.projectEvent(savedEvent)));
yield* appendAndProject({
type: "thread.created",
eventId: EventId.make("evt-incremental-1"),
aggregateKind: "thread",
aggregateId: ThreadId.make("thread-incremental"),
occurredAt: "2026-02-26T14:00:00.000Z",
commandId: CommandId.make("cmd-incremental-1"),
causationEventId: null,
correlationId: CorrelationId.make("cmd-incremental-1"),
metadata: {},
payload: {
threadId: ThreadId.make("thread-incremental"),
projectId: ProjectId.make("project-incremental"),
title: "Thread Incremental",
modelSelection: {
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5-codex",
},
runtimeMode: "full-access",
interactionMode: "default",
branch: null,
worktreePath: null,
createdAt: "2026-02-26T14:00:00.000Z",
updatedAt: "2026-02-26T14:00:00.000Z",
},
});
yield* appendAndProject({
type: "thread.message-sent",
eventId: EventId.make("evt-incremental-2"),
aggregateKind: "thread",
aggregateId: ThreadId.make("thread-incremental"),
occurredAt: "2026-02-26T14:00:01.000Z",
commandId: CommandId.make("cmd-incremental-2"),
causationEventId: null,
correlationId: CorrelationId.make("cmd-incremental-2"),
metadata: {},
payload: {
threadId: ThreadId.make("thread-incremental"),
messageId: MessageId.make("message-incremental-user"),
role: "user",
text: "Do the thing",
turnId: null,
streaming: false,
createdAt: "2026-02-26T14:00:01.000Z",
updatedAt: "2026-02-26T14:00:01.000Z",
},
});
// A streaming assistant chunk must not move updatedAt (no shell fan-out).
yield* appendAndProject({
type: "thread.message-sent",
eventId: EventId.make("evt-incremental-3"),
aggregateKind: "thread",
aggregateId: ThreadId.make("thread-incremental"),
occurredAt: "2026-02-26T14:00:02.000Z",
commandId: CommandId.make("cmd-incremental-3"),
causationEventId: null,
correlationId: CorrelationId.make("cmd-incremental-3"),
metadata: {},
payload: {
threadId: ThreadId.make("thread-incremental"),
messageId: MessageId.make("message-incremental-assistant"),
role: "assistant",
text: "Work",
turnId: null,
streaming: true,
createdAt: "2026-02-26T14:00:02.000Z",
updatedAt: "2026-02-26T14:00:02.000Z",
},
});
const threadRows = yield* sql<{
readonly latestUserMessageAt: string | null;
readonly updatedAt: string;
}>`
SELECT
latest_user_message_at AS "latestUserMessageAt",
updated_at AS "updatedAt"
FROM projection_threads
WHERE thread_id = 'thread-incremental'
`;
assert.deepEqual(threadRows, [
{
latestUserMessageAt: "2026-02-26T14:00:01.000Z",
updatedAt: "2026-02-26T14:00:01.000Z",
},
]);
}),
);
it.effect("ignores non-stale provider approval response failures", () =>
Effect.gen(function* () {
const projectionPipeline = yield* OrchestrationProjectionPipeline;
@@ -176,6 +176,20 @@ function derivePendingUserInputCountFromActivities(
return openRequestIds.size;
}
// Activity kinds that can change the shell summary's pending-approval or
// pending-user-input counters. All other activity kinds (command output,
// file edits, streaming progress, ...) leave the summary untouched, so they
// must not trigger the history-wide summary rebuild — and the shell stream
// (ws.ts toShellStreamEvent) skips re-broadcasting the thread row for them.
export const SHELL_SUMMARY_ACTIVITY_KINDS: ReadonlySet<string> = new Set([
"approval.requested",
"approval.resolved",
"provider.approval.respond.failed",
"user-input.requested",
"user-input.resolved",
"provider.user-input.respond.failed",
]);
function deriveHasActionableProposedPlan(input: {
readonly latestTurnId: string | null;
readonly proposedPlans: ReadonlyArray<ProjectionThreadProposedPlan>;
@@ -713,9 +727,61 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
return;
}
case "thread.message-sent":
case "thread.message-sent": {
const existingRow = yield* projectionThreadRepository.getById({
threadId: event.payload.threadId,
});
if (Option.isNone(existingRow)) {
return;
}
// A message can only move latestUserMessageAt forward; the other
// summary fields depend on activities/plans/approvals, which this
// event cannot touch. Update incrementally instead of re-reading the
// whole message/plan/activity/approval history per (streamed) chunk.
const latestUserMessageAt =
event.payload.role === "user" &&
(existingRow.value.latestUserMessageAt === null ||
event.payload.createdAt > existingRow.value.latestUserMessageAt)
? event.payload.createdAt
: existingRow.value.latestUserMessageAt;
yield* projectionThreadRepository.upsert({
...existingRow.value,
latestUserMessageAt,
// Streaming assistant chunks arrive many times per second and
// change no shell-visible field; leaving updatedAt untouched lets
// the shell stream skip per-chunk upsert fan-out (toShellStreamEvent).
updatedAt:
event.payload.streaming && event.payload.role === "assistant"
? existingRow.value.updatedAt
: event.occurredAt,
});
return;
}
case "thread.activity-appended": {
// Non-summary activities (command output, file edits, progress, ...)
// change no shell-visible field: the sidebar timestamp prefers
// latestUserMessageAt and status pills derive from session/approval
// state. Skip the row churn entirely so high-volume activity streams
// don't bump updatedAt (and fan out shell upserts) per event.
if (!SHELL_SUMMARY_ACTIVITY_KINDS.has(event.payload.activity.kind)) {
return;
}
const existingRow = yield* projectionThreadRepository.getById({
threadId: event.payload.threadId,
});
if (Option.isNone(existingRow)) {
return;
}
yield* projectionThreadRepository.upsert({
...existingRow.value,
updatedAt: event.occurredAt,
});
yield* refreshThreadShellSummary(event.payload.threadId);
return;
}
case "thread.proposed-plan-upserted":
case "thread.activity-appended":
case "thread.approval-response-requested":
case "thread.user-input-response-requested": {
const existingRow = yield* projectionThreadRepository.getById({
@@ -37,6 +37,18 @@ export interface OrchestrationEngineShape {
limit?: number,
) => Stream.Stream<OrchestrationEvent, OrchestrationEventStoreError, never>;
/**
* Replay a single aggregate's persisted events from an exclusive sequence
* cursor. Reads via the aggregate stream index, so per-thread catch-up does
* not scan the global event range after the cursor.
*/
readonly readAggregateEvents: (
aggregateKind: OrchestrationEvent["aggregateKind"],
aggregateId: string,
fromSequenceExclusive: number,
limit?: number,
) => Stream.Stream<OrchestrationEvent, OrchestrationEventStoreError, never>;
/**
* Dispatch a validated orchestration command.
*
+8 -2
View File
@@ -313,11 +313,17 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
}
case "thread.meta.update": {
yield* requireThread({
const thread = yield* requireThread({
readModel,
command,
threadId: command.threadId,
});
const branch =
command.branch !== undefined &&
command.expectedBranch !== undefined &&
thread.branch !== command.expectedBranch
? thread.branch
: command.branch;
const occurredAt = yield* nowIso;
return {
...(yield* withEventBase({
@@ -333,7 +339,7 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
...(command.modelSelection !== undefined
? { modelSelection: command.modelSelection }
: {}),
...(command.branch !== undefined ? { branch: command.branch } : {}),
...(branch !== undefined ? { branch } : {}),
...(command.worktreePath !== undefined ? { worktreePath: command.worktreePath } : {}),
updatedAt: occurredAt,
},
@@ -69,6 +69,51 @@ layer("OrchestrationEventStore", (it) => {
}),
);
it.effect("replays only the requested aggregate's events after the cursor", () =>
Effect.gen(function* () {
const eventStore = yield* OrchestrationEventStore;
const now = "2026-01-01T00:00:00.000Z";
const appendProjectCreated = (suffix: string) =>
eventStore.append({
type: "project.created",
eventId: EventId.make(`evt-aggregate-${suffix}`),
aggregateKind: "project",
aggregateId: ProjectId.make(`project-${suffix}`),
occurredAt: now,
commandId: CommandId.make(`cmd-aggregate-${suffix}`),
causationEventId: null,
correlationId: null,
metadata: {},
payload: {
projectId: ProjectId.make(`project-${suffix}`),
title: `Project ${suffix}`,
workspaceRoot: `/tmp/project-${suffix}`,
defaultModelSelection: null,
scripts: [],
createdAt: now,
updatedAt: now,
},
});
const first = yield* appendProjectCreated("a");
yield* appendProjectCreated("b");
const replayed = yield* Stream.runCollect(
eventStore.readAggregateFromSequence("project", first.aggregateId, 0),
).pipe(Effect.map((chunk) => Array.from(chunk)));
assert.deepStrictEqual(
replayed.map((event) => event.aggregateId),
[first.aggregateId],
);
const afterCursor = yield* Stream.runCollect(
eventStore.readAggregateFromSequence("project", first.aggregateId, first.sequence),
).pipe(Effect.map((chunk) => Array.from(chunk)));
assert.deepStrictEqual(afterCursor, []);
}),
);
it.effect("fails with PersistenceDecodeError when stored json is invalid", () =>
Effect.gen(function* () {
const eventStore = yield* OrchestrationEventStore;
@@ -64,6 +64,12 @@ const ReadFromSequenceRequestSchema = Schema.Struct({
sequenceExclusive: NonNegativeInt,
limit: Schema.Number,
});
const ReadAggregateFromSequenceRequestSchema = Schema.Struct({
aggregateKind: OrchestrationAggregateKind,
aggregateId: Schema.String,
sequenceExclusive: NonNegativeInt,
limit: Schema.Number,
});
const DEFAULT_READ_FROM_SEQUENCE_LIMIT = 1_000;
const READ_PAGE_SIZE = 500;
@@ -181,6 +187,32 @@ const makeEventStore = Effect.gen(function* () {
`,
});
const readAggregateEventRowsFromSequence = SqlSchema.findAll({
Request: ReadAggregateFromSequenceRequestSchema,
Result: OrchestrationEventPersistedRowSchema,
execute: (request) =>
sql`
SELECT
sequence,
event_id AS "eventId",
event_type AS "type",
aggregate_kind AS "aggregateKind",
stream_id AS "aggregateId",
occurred_at AS "occurredAt",
command_id AS "commandId",
causation_event_id AS "causationEventId",
correlation_id AS "correlationId",
payload_json AS "payload",
metadata_json AS "metadata"
FROM orchestration_events
WHERE aggregate_kind = ${request.aggregateKind}
AND stream_id = ${request.aggregateId}
AND sequence > ${request.sequenceExclusive}
ORDER BY sequence ASC
LIMIT ${request.limit}
`,
});
const append: OrchestrationEventStoreShape["append"] = (event) =>
appendEventRow({
eventId: event.eventId,
@@ -208,10 +240,18 @@ const makeEventStore = Effect.gen(function* () {
),
);
const readFromSequence: OrchestrationEventStoreShape["readFromSequence"] = (
sequenceExclusive,
limit = DEFAULT_READ_FROM_SEQUENCE_LIMIT,
) => {
const readPagedEvents = <E>(
operation: string,
readRows: (
cursor: number,
pageLimit: number,
) => Effect.Effect<
ReadonlyArray<Schema.Schema.Type<typeof OrchestrationEventPersistedRowSchema>>,
E
>,
sequenceExclusive: number,
limit: number,
): Stream.Stream<OrchestrationEvent, OrchestrationEventStoreError> => {
const normalizedLimit = Math.max(0, Math.floor(limit));
if (normalizedLimit === 0) {
return Stream.empty;
@@ -221,22 +261,14 @@ const makeEventStore = Effect.gen(function* () {
remaining: number,
): Stream.Stream<OrchestrationEvent, OrchestrationEventStoreError> =>
Stream.fromEffect(
readEventRowsFromSequence({
sequenceExclusive: cursor,
limit: Math.min(remaining, READ_PAGE_SIZE),
}).pipe(
readRows(cursor, Math.min(remaining, READ_PAGE_SIZE)).pipe(
Effect.mapError(
toPersistenceSqlOrDecodeError(
"OrchestrationEventStore.readFromSequence:query",
"OrchestrationEventStore.readFromSequence:decodeRows",
),
toPersistenceSqlOrDecodeError(`${operation}:query`, `${operation}:decodeRows`),
),
Effect.flatMap((rows) =>
Effect.forEach(rows, (row) =>
decodeEvent(row).pipe(
Effect.mapError(
toPersistenceDecodeError("OrchestrationEventStore.readFromSequence:rowToEvent"),
),
Effect.mapError(toPersistenceDecodeError(`${operation}:rowToEvent`)),
),
),
),
@@ -260,9 +292,41 @@ const makeEventStore = Effect.gen(function* () {
return readPage(sequenceExclusive, normalizedLimit);
};
const readFromSequence: OrchestrationEventStoreShape["readFromSequence"] = (
sequenceExclusive,
limit = DEFAULT_READ_FROM_SEQUENCE_LIMIT,
) =>
readPagedEvents(
"OrchestrationEventStore.readFromSequence",
(cursor, pageLimit) =>
readEventRowsFromSequence({ sequenceExclusive: cursor, limit: pageLimit }),
sequenceExclusive,
limit,
);
const readAggregateFromSequence: OrchestrationEventStoreShape["readAggregateFromSequence"] = (
aggregateKind,
aggregateId,
sequenceExclusive,
limit = Number.MAX_SAFE_INTEGER,
) =>
readPagedEvents(
"OrchestrationEventStore.readAggregateFromSequence",
(cursor, pageLimit) =>
readAggregateEventRowsFromSequence({
aggregateKind,
aggregateId,
sequenceExclusive: cursor,
limit: pageLimit,
}),
sequenceExclusive,
limit,
);
return {
append,
readFromSequence,
readAggregateFromSequence,
readAll: () => readFromSequence(0, Number.MAX_SAFE_INTEGER),
} satisfies OrchestrationEventStoreShape;
});
@@ -46,6 +46,26 @@ export interface OrchestrationEventStoreShape {
limit?: number,
) => Stream.Stream<OrchestrationEvent, OrchestrationEventStoreError>;
/**
* Replay a single aggregate's events after the provided sequence.
*
* @param aggregateKind - Aggregate kind of the stream.
* @param aggregateId - Aggregate id of the stream.
* @param sequenceExclusive - Sequence cursor (exclusive).
* @param limit - Maximum number of events to emit.
* @returns Stream containing ordered events for that aggregate only.
*
* The filter runs in SQL against the (aggregate_kind, stream_id, sequence)
* index, so the cost scales with the aggregate's own events rather than the
* global event range after the cursor.
*/
readonly readAggregateFromSequence: (
aggregateKind: OrchestrationEvent["aggregateKind"],
aggregateId: string,
sequenceExclusive: number,
limit?: number,
) => Stream.Stream<OrchestrationEvent, OrchestrationEventStoreError>;
/**
* Read all events from the beginning of the stream.
*
@@ -459,6 +459,7 @@ describe.sequential("signRelayAgentActivityPublishProof", () => {
const orchestrationEngine = {
readEvents: () => Stream.empty,
readAggregateEvents: () => Stream.empty,
dispatch: () => Effect.succeed({ sequence: 1 }),
streamDomainEvents: Stream.fromQueue(events),
} satisfies OrchestrationEngineShape;
@@ -648,6 +649,7 @@ describe.sequential("signRelayAgentActivityPublishProof", () => {
}),
Layer.succeed(OrchestrationEngineService, {
readEvents: () => Stream.empty,
readAggregateEvents: () => Stream.empty,
dispatch: () => Effect.succeed({ sequence: 1 }),
streamDomainEvents: Stream.fromQueue(events),
} satisfies OrchestrationEngineShape),
+1
View File
@@ -675,6 +675,7 @@ const buildAppUnderTest = (options?: {
Layer.provide(
Layer.mock(OrchestrationEngine.OrchestrationEngineService)({
readEvents: () => Stream.empty,
readAggregateEvents: () => Stream.empty,
dispatch: () => Effect.succeed({ sequence: 0 }),
streamDomainEvents: Stream.empty,
...options?.layers?.orchestrationEngine,
@@ -163,6 +163,7 @@ it.effect("resolveAutoBootstrapWelcomeTargets returns existing project and threa
}),
Effect.provideService(OrchestrationEngine.OrchestrationEngineService, {
readEvents: () => Stream.empty,
readAggregateEvents: () => Stream.empty,
dispatch: (command) =>
Ref.update(dispatchCalls, (calls) => [...calls, command.type]).pipe(
Effect.as({ sequence: 1 }),
@@ -206,6 +207,7 @@ it.effect("resolveAutoBootstrapWelcomeTargets creates a project and thread when
}),
Effect.provideService(OrchestrationEngine.OrchestrationEngineService, {
readEvents: () => Stream.empty,
readAggregateEvents: () => Stream.empty,
dispatch: (command) =>
Ref.update(dispatchCalls, (calls) => [...calls, command.type]).pipe(
Effect.as({ sequence: 1 }),
@@ -255,6 +257,7 @@ it.effect("resolveAutoBootstrapWelcomeTargets preserves typed UUID generation fa
}),
Effect.provideService(OrchestrationEngine.OrchestrationEngineService, {
readEvents: () => Stream.empty,
readAggregateEvents: () => Stream.empty,
dispatch: (command) =>
Ref.update(dispatchCalls, (calls) => [...calls, command.type]).pipe(
Effect.as({ sequence: 1 }),
+66 -18
View File
@@ -68,6 +68,7 @@ import * as ServerConfig from "./config.ts";
import * as Keybindings from "./keybindings.ts";
import * as ExternalLauncher from "./process/externalLauncher.ts";
import { normalizeDispatchCommand } from "./orchestration/Normalizer.ts";
import { SHELL_SUMMARY_ACTIVITY_KINDS } from "./orchestration/Layers/ProjectionPipeline.ts";
import * as OrchestrationEngine from "./orchestration/Services/OrchestrationEngine.ts";
import * as ProjectionSnapshotQuery from "./orchestration/Services/ProjectionSnapshotQuery.ts";
import {
@@ -276,6 +277,11 @@ function isThreadDetailEvent(event: OrchestrationEvent): event is Extract<
const PROVIDER_STATUS_DEBOUNCE_MS = 200;
// Shell catch-up replays the global event stream (shell relevance is only known
// after reading), so a stale cursor must not scan an unbounded gap. Past this
// many events it is cheaper to re-send the projection-backed shell snapshot.
const MAX_SHELL_CATCH_UP_EVENTS = 500;
const RPC_REQUIRED_SCOPE = new Map<string, AuthEnvironmentScope>([
[ORCHESTRATION_WS_METHODS.dispatchCommand, AuthOrchestrationOperateScope],
[ORCHESTRATION_WS_METHODS.getTurnDiff, AuthOrchestrationReadScope],
@@ -662,6 +668,25 @@ const makeWsRpcLayer = (
if (event.aggregateKind !== "thread") {
return Effect.succeed(Option.none());
}
// Streaming assistant chunks change no shell-visible field (the
// projection leaves updatedAt untouched for them), so don't read
// and re-broadcast the thread shell row once per token.
if (
event.type === "thread.message-sent" &&
event.payload.streaming &&
event.payload.role === "assistant"
) {
return Effect.succeed(Option.none());
}
// Same for high-volume activity kinds (command output, file edits,
// progress): the projection skips the thread row for them, so a
// shell broadcast would be a no-op re-send of unchanged data.
if (
event.type === "thread.activity-appended" &&
!SHELL_SUMMARY_ACTIVITY_KINDS.has(event.payload.activity.kind)
) {
return Effect.succeed(Option.none());
}
return projectionSnapshotQuery
.getThreadShellById(ThreadId.make(event.aggregateId))
.pipe(
@@ -1079,8 +1104,13 @@ const makeWsRpcLayer = (
// 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.
// on the client.
//
// Shell events are filtered out of the global event stream after
// reading, so a stale cursor would otherwise scan every event
// appended since it. The catch-up read is therefore bounded: past
// the bound it is cheaper to re-send the projection-backed shell
// snapshot than to replay (and per-event enrich) the whole gap.
if (input.afterSequence !== undefined) {
const afterSequence = input.afterSequence;
return Stream.unwrap(
@@ -1089,22 +1119,41 @@ const makeWsRpcLayer = (
yield* Effect.forkScoped(
liveStream.pipe(Stream.runForEach((item) => Queue.offer(liveBuffer, item))),
);
const catchUpStream = orchestrationEngine
.readEvents(afterSequence, Number.MAX_SAFE_INTEGER)
.pipe(
const catchUpEvents = yield* Stream.runCollect(
orchestrationEngine.readEvents(afterSequence, MAX_SHELL_CATCH_UP_EVENTS + 1),
).pipe(
Effect.map((events) => Array.from(events)),
Effect.mapError(
(cause) =>
new OrchestrationGetSnapshotError({
message: "Failed to replay orchestration shell events",
cause,
}),
),
);
if (catchUpEvents.length <= MAX_SHELL_CATCH_UP_EVENTS) {
const catchUpStream = Stream.fromIterable(catchUpEvents).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));
return Stream.concat(catchUpStream, Stream.fromQueue(liveBuffer));
}
const snapshot = yield* projectionSnapshotQuery.getShellSnapshot().pipe(
Effect.mapError(
(cause) =>
new OrchestrationGetSnapshotError({
message: "Failed to load orchestration shell snapshot",
cause,
}),
),
);
return Stream.concat(
Stream.make({ kind: "snapshot" as const, snapshot }),
Stream.fromQueue(liveBuffer),
);
}),
);
}
@@ -1179,10 +1228,9 @@ const makeWsRpcLayer = (
// 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.
// The catch-up read targets this thread's aggregate stream (via
// the aggregate stream index), so a stale cursor replays only this
// thread's events instead of scanning the global range after it.
if (input.afterSequence !== undefined) {
const afterSequence = input.afterSequence;
return Stream.unwrap(
@@ -1192,7 +1240,7 @@ const makeWsRpcLayer = (
liveStream.pipe(Stream.runForEach((item) => Queue.offer(liveBuffer, item))),
);
const catchUpStream = orchestrationEngine
.readEvents(afterSequence, Number.MAX_SAFE_INTEGER)
.readAggregateEvents("thread", input.threadId, afterSequence)
.pipe(
Stream.filter(isThisThreadDetailEvent),
Stream.map((event) => ({ kind: "event" as const, event })),
+18
View File
@@ -0,0 +1,18 @@
import * as Schema from "effect/Schema";
/**
* Accounts that opted out of the post-sign-in T3 Connect onboarding wizard
* ("Don't show this again"). The wizard otherwise shows on every sign-in,
* since sign-out clears the connected environments.
*/
export const CONNECT_ONBOARDING_OPT_OUT_STORAGE_KEY = "t3code:connect-onboarding-opt-out:v1";
export const ConnectOnboardingOptOutSchema = Schema.Struct({
optOutAccounts: Schema.Array(Schema.String),
});
export type ConnectOnboardingOptOutState = typeof ConnectOnboardingOptOutSchema.Type;
export const EMPTY_CONNECT_ONBOARDING_OPT_OUT_STATE: ConnectOnboardingOptOutState = {
optOutAccounts: [],
};
@@ -0,0 +1,163 @@
import { useAuth } from "@clerk/react";
import { findErrorTraceId } from "@t3tools/client-runtime/errors";
import {
isAtomCommandInterrupted,
settlePromise,
squashAtomCommandFailure,
} from "@t3tools/client-runtime/state/runtime";
import { useState } from "react";
import { toastManager } from "../components/ui/toast";
import { relayEnvironmentDiscovery } from "../state/relay";
import { useAtomCommand } from "../state/use-atom-command";
import {
linkPrimaryEnvironment as linkPrimaryEnvironmentAtom,
unlinkPrimaryEnvironment as unlinkPrimaryEnvironmentAtom,
updatePrimaryEnvironmentPreferences as updatePrimaryEnvironmentPreferencesAtom,
} from "./linkEnvironmentAtoms";
import { usePrimaryCloudLinkState } from "./primaryCloudLinkState";
import { resolveRelayClerkTokenOptions } from "./publicConfig";
export interface CloudLinkDesiredState {
readonly managedTunnel: boolean;
readonly publish: boolean;
}
/**
* Drives the primary environment's T3 Connect link. T3 Connect (managed
* tunnel) and agent-activity publishing are independent capabilities backed by
* a single relay link, so consumers express the full desired state and
* `reconcileCloudState` applies it: unlink when neither is wanted, otherwise
* (re)link with the mode the managed-tunnel bit implies and set the publish
* preference. Re-linking only happens when the managed-tunnel mode actually
* changes, so flipping publish alone is cheap.
*/
export function useCloudLinkController() {
const { getToken, isSignedIn } = useAuth();
const refreshRelayEnvironments = useAtomCommand(relayEnvironmentDiscovery.refresh, {
reportFailure: false,
});
const linkPrimaryEnvironment = useAtomCommand(linkPrimaryEnvironmentAtom, {
reportFailure: false,
});
const unlinkPrimaryEnvironment = useAtomCommand(unlinkPrimaryEnvironmentAtom, {
reportFailure: false,
});
const updatePrimaryEnvironmentPreferences = useAtomCommand(
updatePrimaryEnvironmentPreferencesAtom,
{ reportFailure: false },
);
const primaryCloudLinkState = usePrimaryCloudLinkState();
const [operationError, setOperationError] = useState<string | null>(null);
const reportUpdateFailure = (cause: unknown) => {
const message = cause instanceof Error ? cause.message : "Could not update T3 Connect access.";
const traceId = findErrorTraceId(cause);
console.error("[t3-connect] Could not update T3 Connect", { message, traceId, cause });
setOperationError(traceId ? `${message} Trace ID: ${traceId}` : message);
toastManager.add({
type: "error",
title: "Could not update T3 Connect",
description: message,
data: traceId
? {
secondaryActionProps: {
children: "Copy trace ID",
onClick: () => void navigator.clipboard?.writeText(traceId),
},
}
: undefined,
});
};
// Older environment servers predate the managedTunnelActive field; for them a
// link always implies a managed tunnel, so fall back to `linked`.
const managedTunnelActive =
primaryCloudLinkState.data?.managedTunnelActive ?? primaryCloudLinkState.data?.linked ?? false;
const publishAgentActivity = primaryCloudLinkState.data?.publishAgentActivity ?? false;
const linked = primaryCloudLinkState.data?.linked ?? false;
const reconcileCloudState = async (desired: CloudLinkDesiredState): Promise<boolean> => {
setOperationError(null);
const target = primaryCloudLinkState.target;
if (!target) {
reportUpdateFailure(new Error("Local environment is not ready yet."));
return false;
}
const tokenResult = await settlePromise(() => getToken(resolveRelayClerkTokenOptions()));
const wantsLink = desired.managedTunnel || desired.publish;
// A failure after this point may follow a partially applied mutation (e.g.
// the link succeeded but the preference update did not), so every exit —
// success or failure — refreshes the rendered state to whatever the server
// actually holds now.
if (!wantsLink) {
// Unlink works without a relay token — a failed token read must not
// leave the user unable to turn T3 Connect off.
const unlinkResult = await unlinkPrimaryEnvironment({
target,
clerkToken: tokenResult._tag === "Success" ? (tokenResult.value ?? null) : null,
});
if (unlinkResult._tag === "Failure") {
if (!isAtomCommandInterrupted(unlinkResult)) {
reportUpdateFailure(squashAtomCommandFailure(unlinkResult));
}
primaryCloudLinkState.refresh();
return false;
}
} else {
if (tokenResult._tag === "Failure") {
reportUpdateFailure(squashAtomCommandFailure(tokenResult));
return false;
}
const clerkToken = tokenResult.value;
if (!clerkToken) {
reportUpdateFailure(new Error("Sign in to T3 Connect before enabling this."));
return false;
}
if (!linked || managedTunnelActive !== desired.managedTunnel) {
const linkResult = await linkPrimaryEnvironment({
target,
clerkToken,
mode: desired.managedTunnel ? "managed" : "publish_only",
});
if (linkResult._tag === "Failure") {
if (!isAtomCommandInterrupted(linkResult)) {
reportUpdateFailure(squashAtomCommandFailure(linkResult));
}
primaryCloudLinkState.refresh();
return false;
}
}
const prefResult = await updatePrimaryEnvironmentPreferences({
target,
publishAgentActivity: desired.publish,
});
if (prefResult._tag === "Failure") {
if (!isAtomCommandInterrupted(prefResult)) {
reportUpdateFailure(squashAtomCommandFailure(prefResult));
}
primaryCloudLinkState.refresh();
return false;
}
}
primaryCloudLinkState.refresh();
const refreshResult = await refreshRelayEnvironments();
if (refreshResult._tag === "Failure" && !isAtomCommandInterrupted(refreshResult)) {
reportUpdateFailure(squashAtomCommandFailure(refreshResult));
return false;
}
return true;
};
return {
isSignedIn,
linkState: primaryCloudLinkState,
linked,
managedTunnelActive,
publishAgentActivity,
operationError,
reconcileCloudState,
};
}
+23 -4
View File
@@ -140,6 +140,12 @@ const highlightedCodeCache = new LRUCache<string>(
MAX_HIGHLIGHT_CACHE_MEMORY_BYTES,
);
const highlighterPromiseCache = new Map<string, Promise<DiffsHighlighter>>();
// Languages Shiki has no grammar for (e.g. `sh` fences). Without this negative
// cache every render of such a block retries the grammar load and throws again.
// Fence labels are arbitrary text, so cap both caches: past the cap, unknown
// languages just retry (the pre-cache behavior) instead of growing memory.
const fallbackHighlightLanguages = new Set<string>();
const MAX_FALLBACK_HIGHLIGHT_LANGUAGES = 100;
function findTaskListMarkerOffset(markdown: string, listItemStart: number): number | null {
const firstLineEnd = markdown.indexOf("\n", listItemStart);
@@ -273,6 +279,9 @@ function estimateHighlightedSize(html: string, code: string): number {
}
function getHighlighterPromise(language: string): Promise<DiffsHighlighter> {
if (fallbackHighlightLanguages.has(language)) {
return getHighlighterPromise("text");
}
const cached = highlighterPromiseCache.get(language);
if (cached) return cached;
@@ -281,12 +290,19 @@ function getHighlighterPromise(language: string): Promise<DiffsHighlighter> {
langs: [language as SupportedLanguages],
preferredHighlighter: "shiki-js",
}).catch((err) => {
// Failed loads never stay in the promise cache: unsupported languages are
// remembered in the (bounded) negative cache instead, and transient
// failures for real languages stay retryable.
highlighterPromiseCache.delete(language);
if (language === "text") {
// "text" itself failed — Shiki cannot initialize at all, surface the error
throw err;
}
// Language not supported by Shiki — fall back to "text"
// Language not supported by Shiki — remember that and fall back to "text"
// so blocks with that language stop retrying the grammar load per render.
if (fallbackHighlightLanguages.size < MAX_FALLBACK_HIGHLIGHT_LANGUAGES) {
fallbackHighlightLanguages.add(language);
}
return getHighlighterPromise("text");
});
highlighterPromiseCache.set(language, promise);
@@ -684,15 +700,18 @@ function UncachedShikiCodeBlock({
}: UncachedShikiCodeBlockProps) {
const highlighter = use(getHighlighterPromise(language));
const highlightedHtml = useMemo(() => {
const effectiveLanguage = fallbackHighlightLanguages.has(language) ? "text" : language;
try {
return highlighter.codeToHtml(code, { lang: language, theme: themeName });
return highlighter.codeToHtml(code, { lang: effectiveLanguage, theme: themeName });
} catch (error) {
// Log highlighting failures for debugging while falling back to plain text
// Log highlighting failures for debugging while falling back to plain
// text. Render-time throws can be content-specific, so they don't join
// the negative cache — one pathological block must not disable
// highlighting for the whole language. Retries are bounded by the memo.
console.warn(
`Code highlighting failed for language "${language}", falling back to plain text.`,
error instanceof Error ? error.message : error,
);
// If highlighting fails for this language, render as plain text
return highlighter.codeToHtml(code, { lang: "text", theme: themeName });
}
}, [code, highlighter, language, themeName]);
@@ -0,0 +1,56 @@
import { cn } from "~/lib/utils";
import { Tooltip, TooltipPopup, TooltipTrigger } from "~/components/ui/tooltip";
type ConnectionStatusDotProps = {
tooltipText?: string | null;
dotClassName: string;
pingClassName?: string | null;
};
export function ConnectionStatusDot({
tooltipText,
dotClassName,
pingClassName,
}: ConnectionStatusDotProps) {
const dotContent = (
<>
{pingClassName ? (
<span
className={cn(
"absolute inline-flex h-full w-full animate-ping rounded-full",
pingClassName,
)}
/>
) : null}
<span className={cn("relative inline-flex size-2 rounded-full", dotClassName)} />
</>
);
if (!tooltipText) {
return (
<span className="relative flex size-3 shrink-0 items-center justify-center">
{dotContent}
</span>
);
}
const dot = (
<button
type="button"
title={tooltipText}
aria-label={tooltipText}
className="relative flex size-3 shrink-0 cursor-help items-center justify-center rounded-full outline-hidden"
>
{dotContent}
</button>
);
return (
<Tooltip>
<TooltipTrigger render={dot} />
<TooltipPopup side="top" className="max-w-80 whitespace-pre-wrap leading-tight">
{tooltipText}
</TooltipPopup>
</Tooltip>
);
}
@@ -9,6 +9,7 @@ import {
resolveLiveThreadBranchUpdate,
resolveQuickAction,
resolveThreadBranchUpdate,
resolveThreadBranchMetadataPatch,
} from "./GitActionsControl.logic";
function status(overrides: Partial<VcsStatusResult> = {}): VcsStatusResult {
@@ -1111,6 +1112,18 @@ describe("resolveLiveThreadBranchUpdate", () => {
});
});
describe("resolveThreadBranchMetadataPatch", () => {
it("does not overwrite worktree metadata while reconciling a branch", () => {
assert.deepEqual(
resolveThreadBranchMetadataPatch("feature/current-ref", "feature/previous-ref"),
{
branch: "feature/current-ref",
expectedBranch: "feature/previous-ref",
},
);
});
});
describe("resolveAutoFeatureBranchName", () => {
it("uses semantic preferred ref names when available", () => {
const ref = resolveAutoFeatureBranchName(["main", "feature/other"], "fix toast copy");
@@ -373,6 +373,16 @@ export function resolveThreadBranchUpdate(
};
}
export function resolveThreadBranchMetadataPatch(
branch: string | null,
expectedBranch: string | null,
): {
branch: string | null;
expectedBranch: string | null;
} {
return { branch, expectedBranch };
}
export function resolveLiveThreadBranchUpdate(input: {
threadBranch: string | null;
gitStatus: VcsStatusResult | null;
@@ -45,6 +45,7 @@ import {
requiresDefaultBranchConfirmation,
resolveDefaultBranchActionDialogCopy,
resolveLiveThreadBranchUpdate,
resolveThreadBranchMetadataPatch,
resolveQuickAction,
resolveThreadBranchUpdate,
} from "./GitActionsControl.logic";
@@ -1033,13 +1034,11 @@ export default function GitActionsControl({
return;
}
const worktreePath = activeServerThread.worktreePath;
void updateThreadMetadata({
environmentId: activeThreadRef.environmentId,
input: {
threadId: activeThreadRef.threadId,
branch,
worktreePath,
...resolveThreadBranchMetadataPatch(branch, activeServerThread.branch),
},
});
+72 -8
View File
@@ -1,7 +1,7 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
import {
createSidebarHoverPrewarmController,
createThreadJumpHintVisibilityController,
getSidebarThreadIdsToPrewarm,
getVisibleSidebarThreadIds,
resolveAdjacentThreadId,
getFallbackThreadIdAfterDelete,
@@ -19,6 +19,7 @@ import {
resolveThreadStatusPill,
shouldClearThreadSelectionOnMouseDown,
sortProjectsForSidebar,
SIDEBAR_THREAD_HOVER_PREWARM_DELAY_MS,
THREAD_JUMP_HINT_SHOW_DELAY_MS,
} from "./Sidebar.logic";
import {
@@ -181,17 +182,80 @@ describe("createThreadJumpHintVisibilityController", () => {
});
});
describe("getSidebarThreadIdsToPrewarm", () => {
it("returns only the first visible thread ids up to the prewarm limit", () => {
expect(getSidebarThreadIdsToPrewarm(["t1", "t2", "t3"], 2)).toEqual(["t1", "t2"]);
describe("createSidebarHoverPrewarmController", () => {
beforeEach(() => {
vi.useFakeTimers();
});
it("returns all visible thread ids when they fit within the limit", () => {
expect(getSidebarThreadIdsToPrewarm(["t1", "t2"], 10)).toEqual(["t1", "t2"]);
afterEach(() => {
vi.useRealTimers();
});
it("returns no thread ids when the limit is zero", () => {
expect(getSidebarThreadIdsToPrewarm(["t1", "t2"], 0)).toEqual([]);
const makeController = () => {
const targets: Array<string | null> = [];
const controller = createSidebarHoverPrewarmController({
delayMs: SIDEBAR_THREAD_HOVER_PREWARM_DELAY_MS,
onPrewarmTargetChange: (threadKey) => {
targets.push(threadKey);
},
});
return { controller, targets };
};
it("prewarms a row only after the pointer rests on it", () => {
const { controller, targets } = makeController();
controller.hover("t1");
vi.advanceTimersByTime(SIDEBAR_THREAD_HOVER_PREWARM_DELAY_MS - 1);
expect(targets).toEqual([]);
vi.advanceTimersByTime(1);
expect(targets).toEqual(["t1"]);
});
it("prewarms at most one thread while sweeping across rows", () => {
const { controller, targets } = makeController();
controller.hover("t1");
vi.advanceTimersByTime(SIDEBAR_THREAD_HOVER_PREWARM_DELAY_MS / 2);
controller.hover("t2");
vi.advanceTimersByTime(SIDEBAR_THREAD_HOVER_PREWARM_DELAY_MS / 2);
controller.hover("t3");
vi.advanceTimersByTime(SIDEBAR_THREAD_HOVER_PREWARM_DELAY_MS);
expect(targets).toEqual(["t3"]);
});
it("keeps an established prewarm when re-entering the same row", () => {
const { controller, targets } = makeController();
controller.hover("t1");
vi.advanceTimersByTime(SIDEBAR_THREAD_HOVER_PREWARM_DELAY_MS);
controller.hover("t1");
vi.advanceTimersByTime(SIDEBAR_THREAD_HOVER_PREWARM_DELAY_MS);
expect(targets).toEqual(["t1"]);
});
it("releases the prewarm target when the pointer leaves thread rows", () => {
const { controller, targets } = makeController();
controller.hover("t1");
vi.advanceTimersByTime(SIDEBAR_THREAD_HOVER_PREWARM_DELAY_MS);
controller.hover(null);
expect(targets).toEqual(["t1", null]);
});
it("cancels a pending prewarm when the pointer leaves early", () => {
const { controller, targets } = makeController();
controller.hover("t1");
vi.advanceTimersByTime(SIDEBAR_THREAD_HOVER_PREWARM_DELAY_MS / 2);
controller.hover(null);
vi.advanceTimersByTime(SIDEBAR_THREAD_HOVER_PREWARM_DELAY_MS);
expect(targets).toEqual([]);
});
});
+61 -8
View File
@@ -13,9 +13,9 @@ import { resolveServerBackedAppStageLabel } from "../branding.logic";
export const THREAD_SELECTION_SAFE_SELECTOR = "[data-thread-item], [data-thread-selection-safe]";
export const THREAD_JUMP_HINT_SHOW_DELAY_MS = 100;
// Visible sidebar rows are prewarmed into the thread-detail cache so opening a
// nearby thread usually reuses an already-hot subscription.
export const SIDEBAR_THREAD_PREWARM_LIMIT = 10;
// A pointer resting on a row signals intent to open it; sweeping past rows must
// not open a detail subscription per row.
export const SIDEBAR_THREAD_HOVER_PREWARM_DELAY_MS = 120;
export type SidebarNewThreadEnvMode = "local" | "worktree";
type SidebarProject = {
id: string;
@@ -283,11 +283,64 @@ export function getVisibleSidebarThreadIds<TThreadId>(
);
}
export function getSidebarThreadIdsToPrewarm<TThreadId>(
visibleThreadIds: readonly TThreadId[],
limit = SIDEBAR_THREAD_PREWARM_LIMIT,
): TThreadId[] {
return visibleThreadIds.slice(0, Math.max(0, limit));
export interface SidebarHoverPrewarmController {
hover: (threadKey: string | null) => void;
dispose: () => void;
}
// Prewarms at most one thread at a time: the row the pointer has rested on.
// The route mounts the active thread's detail subscription itself, so this is
// the only sidebar-driven detail stream.
export function createSidebarHoverPrewarmController(input: {
delayMs: number;
onPrewarmTargetChange: (threadKey: string | null) => void;
}): SidebarHoverPrewarmController {
let target: string | null = null;
let pendingKey: string | null = null;
let timeoutId: ReturnType<typeof setTimeout> | null = null;
const clearPending = () => {
if (timeoutId === null) {
return;
}
clearTimeout(timeoutId);
timeoutId = null;
pendingKey = null;
};
return {
hover: (threadKey) => {
if (threadKey === null) {
clearPending();
if (target !== null) {
target = null;
input.onPrewarmTargetChange(null);
}
return;
}
if (threadKey === target) {
clearPending();
return;
}
if (threadKey === pendingKey) {
return;
}
clearPending();
pendingKey = threadKey;
timeoutId = setTimeout(() => {
timeoutId = null;
pendingKey = null;
target = threadKey;
input.onPrewarmTargetChange(threadKey);
}, input.delayMs);
},
dispose: () => {
clearPending();
},
};
}
export function resolveAdjacentThreadId<T>(input: {
+38 -16
View File
@@ -184,7 +184,8 @@ import {
import { useThreadSelectionStore } from "../threadSelectionStore";
import { useOpenAddProjectCommandPalette } from "../commandPaletteContext";
import {
getSidebarThreadIdsToPrewarm,
createSidebarHoverPrewarmController,
SIDEBAR_THREAD_HOVER_PREWARM_DELAY_MS,
resolveAdjacentThreadId,
isContextMenuPointerDown,
isTrailingDoubleClick,
@@ -248,6 +249,40 @@ function SidebarThreadDetailPrewarmer({ threadRef }: { readonly threadRef: Scope
return null;
}
// Self-contained so hover changes re-render only this component, never the
// sidebar tree. Delegated `pointerover` avoids threading a hover callback
// through the memoized row tree.
function SidebarHoverThreadPrewarmer() {
const [prewarmThreadKey, setPrewarmThreadKey] = useState<string | null>(null);
useEffect(() => {
const controller = createSidebarHoverPrewarmController({
delayMs: SIDEBAR_THREAD_HOVER_PREWARM_DELAY_MS,
onPrewarmTargetChange: setPrewarmThreadKey,
});
const onPointerOver = (event: globalThis.PointerEvent) => {
// Element, not HTMLElement: row icons are SVG and must still resolve to
// their row's key instead of cancelling the hover.
const target = event.target instanceof Element ? event.target : null;
controller.hover(
target?.closest("[data-thread-prewarm-key]")?.getAttribute("data-thread-prewarm-key") ??
null,
);
};
window.addEventListener("pointerover", onPointerOver, { passive: true });
return () => {
window.removeEventListener("pointerover", onPointerOver);
controller.dispose();
};
}, []);
const prewarmThreadRef = useMemo(
() => (prewarmThreadKey === null ? null : parseScopedThreadKey(prewarmThreadKey)),
[prewarmThreadKey],
);
return prewarmThreadRef ? <SidebarThreadDetailPrewarmer threadRef={prewarmThreadRef} /> : null;
}
function clampSidebarThreadPreviewCount(value: number): SidebarThreadPreviewCount {
return Math.min(
MAX_SIDEBAR_THREAD_PREVIEW_COUNT,
@@ -673,6 +708,7 @@ export const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThr
<SidebarMenuSubItem
className="w-full"
data-thread-item
data-thread-prewarm-key={threadKey}
onMouseLeave={handleMouseLeave}
onBlurCapture={handleBlurCapture}
>
@@ -3491,18 +3527,6 @@ export default function Sidebar() {
? threadJumpLabelByKey
: EMPTY_THREAD_JUMP_LABELS;
const orderedSidebarThreadKeys = visibleSidebarThreadKeys;
const prewarmedSidebarThreadKeys = useMemo(
() => getSidebarThreadIdsToPrewarm(visibleSidebarThreadKeys),
[visibleSidebarThreadKeys],
);
const prewarmedSidebarThreadRefs = useMemo(
() =>
prewarmedSidebarThreadKeys.flatMap((threadKey) => {
const ref = parseScopedThreadKey(threadKey);
return ref ? [ref] : [];
}),
[prewarmedSidebarThreadKeys],
);
useEffect(() => {
updateThreadJumpHintsVisibility(shouldShowThreadJumpHintsNow);
@@ -3695,9 +3719,7 @@ export default function Sidebar() {
return (
<>
{prewarmedSidebarThreadRefs.map((threadRef) => (
<SidebarThreadDetailPrewarmer key={scopedThreadKey(threadRef)} threadRef={threadRef} />
))}
<SidebarHoverThreadPrewarmer />
<SidebarChromeHeader isElectron={isElectron} />
{isOnSettings ? (
@@ -373,7 +373,13 @@ export const MessagesTimeline = memo(function MessagesTimeline({
rowTop < scrollBottom &&
rowTop + Math.max(1, rowHeight ?? 1) > scrollTop;
strip.dataset.inView = inView ? "true" : "false";
// Scroll fires per frame; unconditional writes would dirty every strip's
// attributes each frame even though only rows crossing the viewport edge
// change.
const nextInView = inView ? "true" : "false";
if (strip.dataset.inView !== nextInView) {
strip.dataset.inView = nextInView;
}
}
}, [listRef, minimapItems, minimapStripMap, onIsAtEndChange]);
@@ -0,0 +1,227 @@
import { findErrorTraceId } from "@t3tools/client-runtime/errors";
import {
RelayConnectionRegistration,
RelayConnectionTarget,
} from "@t3tools/client-runtime/connection";
import {
isAtomCommandInterrupted,
squashAtomCommandFailure,
} from "@t3tools/client-runtime/state/runtime";
import type { EnvironmentId } from "@t3tools/contracts";
import type { RelayClientEnvironmentRecord } from "@t3tools/contracts/relay";
import * as Option from "effect/Option";
import { type ReactNode, useCallback, useEffect, useMemo, useState } from "react";
import { environmentCatalog } from "~/connection/catalog";
import { cn } from "~/lib/utils";
import { relayEnvironmentDiscovery } from "~/state/relay";
import { useRelayEnvironmentDiscovery } from "~/state/environments";
import { useAtomCommand } from "~/state/use-atom-command";
import { ConnectionStatusDot } from "../ConnectionStatusDot";
import { ITEM_ROW_CLASSNAME, ITEM_ROW_INNER_CLASSNAME } from "../settings/itemRows";
import { Button } from "../ui/button";
import { Skeleton } from "../ui/skeleton";
import { toastManager } from "../ui/toast";
export function RemoteEnvironmentRowsSkeleton() {
return (
<div className={ITEM_ROW_CLASSNAME}>
<div className={ITEM_ROW_INNER_CLASSNAME}>
<div className="min-w-0 flex-1 space-y-2">
<Skeleton className="h-4 w-32 rounded-full" />
<Skeleton className="h-3 w-20 rounded-full" />
</div>
<Skeleton className="h-7 w-16 rounded-md" />
</div>
</div>
);
}
/**
* The user's T3 Connect environments from relay discovery, each with a
* Connect button. The primary environment is always excluded; already-saved
* environments are hidden unless `showSavedAsConnected` renders them as
* connected instead (used by onboarding, where the full device mesh should be
* visible).
*/
export function CloudEnvironmentConnectRows({
primaryEnvironmentId,
savedEnvironmentIds,
showSavedAsConnected = false,
empty = null,
}: {
readonly primaryEnvironmentId: EnvironmentId | null;
readonly savedEnvironmentIds: ReadonlyArray<EnvironmentId>;
readonly showSavedAsConnected?: boolean;
readonly empty?: ReactNode;
}) {
const environmentsState = useRelayEnvironmentDiscovery();
const registerEnvironment = useAtomCommand(environmentCatalog.register, {
reportFailure: false,
});
const refreshRelayEnvironments = useAtomCommand(relayEnvironmentDiscovery.refresh, {
reportFailure: false,
});
const connectRelayEnvironment = useCallback(
(environment: RelayClientEnvironmentRecord) =>
registerEnvironment(
new RelayConnectionRegistration({
target: new RelayConnectionTarget({
environmentId: environment.environmentId,
label: environment.label,
}),
}),
),
[registerEnvironment],
);
const [connectingEnvironmentId, setConnectingEnvironmentId] = useState<EnvironmentId | null>(
null,
);
const savedIds = useMemo(() => new Set(savedEnvironmentIds), [savedEnvironmentIds]);
useEffect(() => {
void refreshRelayEnvironments();
}, [refreshRelayEnvironments]);
const connectEnvironment = async (environment: RelayClientEnvironmentRecord) => {
setConnectingEnvironmentId(environment.environmentId);
const result = await connectRelayEnvironment(environment);
setConnectingEnvironmentId(null);
if (result._tag === "Success") {
toastManager.add({
type: "success",
title: "Environment connected",
description: `${environment.label} is available through T3 Connect.`,
});
return;
}
if (isAtomCommandInterrupted(result)) {
return;
}
const cause = squashAtomCommandFailure(result);
const message =
cause instanceof Error ? cause.message : "Could not connect the T3 Connect environment.";
const traceId = findErrorTraceId(cause);
console.error("[t3-connect] Could not connect environment", { message, traceId, cause });
toastManager.add({
type: "error",
title: "Could not connect environment",
description: message,
data: traceId
? {
secondaryActionProps: {
children: "Copy trace ID",
onClick: () => void navigator.clipboard?.writeText(traceId),
},
}
: undefined,
});
};
const visibleEnvironments = [...environmentsState.environments.values()].filter(
({ environment }) =>
environment.environmentId !== primaryEnvironmentId &&
(showSavedAsConnected || !savedIds.has(environment.environmentId)),
);
const standalone = showSavedAsConnected || savedEnvironmentIds.length === 0;
if (
standalone &&
visibleEnvironments.length === 0 &&
environmentsState.refreshing &&
environmentsState.environments.size === 0
) {
return <RemoteEnvironmentRowsSkeleton />;
}
if (standalone && visibleEnvironments.length === 0) {
// A failed or offline discovery is not "no environments" — misreporting it
// as empty would read as the user's devices having disappeared.
const discoveryProblem = environmentsState.offline
? "You appear to be offline."
: (Option.getOrNull(environmentsState.error)?.message ?? null);
if (discoveryProblem !== null && !environmentsState.refreshing) {
return (
<div className={ITEM_ROW_CLASSNAME}>
<p className="text-sm font-medium text-destructive">
Could not load T3 Connect environments
</p>
<p className="mt-1 text-xs text-muted-foreground">{discoveryProblem}</p>
<Button
size="sm"
variant="outline"
className="mt-3"
onClick={() => void refreshRelayEnvironments()}
>
Try again
</Button>
</div>
);
}
return empty;
}
return visibleEnvironments.map(({ environment, availability, error }) => {
const alreadyConnected = savedIds.has(environment.environmentId);
return (
<div key={environment.environmentId} className={ITEM_ROW_CLASSNAME}>
<div className={ITEM_ROW_INNER_CLASSNAME}>
<div className="min-w-0">
<div className="flex items-center gap-2">
<ConnectionStatusDot
dotClassName={
availability === "online"
? "bg-success"
: availability === "error"
? "bg-destructive"
: availability === "checking"
? "bg-warning"
: "bg-muted-foreground/35"
}
pingClassName={availability === "checking" ? "bg-warning/60 duration-2000" : null}
tooltipText={
availability === "online"
? "Relay online"
: availability === "offline"
? "Relay offline"
: availability === "checking"
? "Checking relay status"
: (Option.getOrNull(error)?.message ?? "Relay status unavailable")
}
/>
<p className="truncate text-sm font-medium">{environment.label}</p>
</div>
<p
className={cn(
"mt-1 truncate text-xs",
availability === "error" ? "text-destructive" : "text-muted-foreground",
)}
>
{availability === "online"
? "Available · Relay online"
: availability === "offline"
? "Available · Relay offline"
: availability === "checking"
? "Available · Checking relay status…"
: (Option.getOrNull(error)?.message ?? "Available · Relay status unavailable")}
</p>
</div>
{alreadyConnected ? (
<Button size="sm" variant="outline" disabled>
Connected
</Button>
) : (
<Button
size="sm"
disabled={connectingEnvironmentId !== null}
onClick={() => void connectEnvironment(environment)}
>
{connectingEnvironmentId === environment.environmentId ? "Connecting…" : "Connect"}
</Button>
)}
</div>
</div>
);
});
}
@@ -0,0 +1,437 @@
import { useAuth } from "@clerk/react";
import { AuthAdministrativeScopes, AuthRelayWriteScope } from "@t3tools/contracts";
import { CheckIcon } from "lucide-react";
import { useEffect, useMemo, useRef, useState } from "react";
import {
CONNECT_ONBOARDING_OPT_OUT_STORAGE_KEY,
ConnectOnboardingOptOutSchema,
EMPTY_CONNECT_ONBOARDING_OPT_OUT_STATE,
} from "~/cloud/connectOnboarding";
import { hasCloudPublicConfig } from "~/cloud/publicConfig";
import { useCloudLinkController } from "~/cloud/useCloudLinkController";
import { usePrimarySessionState } from "~/environments/primary";
import { useLocalStorage } from "~/hooks/useLocalStorage";
import { cn } from "~/lib/utils";
import { useEnvironments, usePrimaryEnvironment } from "~/state/environments";
import { CloudEnvironmentConnectRows } from "./CloudEnvironmentConnectList";
import { Button } from "../ui/button";
import { Checkbox } from "../ui/checkbox";
import {
Dialog,
DialogDescription,
DialogFooter,
DialogHeader,
DialogPanel,
DialogPopup,
DialogTitle,
} from "../ui/dialog";
import { Switch } from "../ui/switch";
import { toastManager } from "../ui/toast";
/**
* Post-sign-in onboarding wizard for T3 Connect. Opens on every in-session
* sign-in — sign-out removes the connected relay environments, so each new
* session starts with no devices to reach. It first prompts to publish this
* environment (managed tunnel + agent activity, both defaulting on) when the
* current session is authorized to manage the relay link, then lists the
* account's T3 Connect environments so every device can be connected right
* away. A cold load with a restored session does not count as a sign-in.
*/
export function ConnectOnboardingDialog() {
if (!hasCloudPublicConfig()) return null;
return <ConfiguredConnectOnboardingDialog />;
}
type OnboardingStep = "publish" | "devices";
function ConfiguredConnectOnboardingDialog() {
// Mirrors ManagedRelayAuthProvider: a pending Clerk session must not read as
// signed-out, or its later activation would look like a fresh sign-in.
const { isLoaded, isSignedIn, userId } = useAuth({ treatPendingAsSignedOut: false });
const [optOutState, setOptOutState] = useLocalStorage(
CONNECT_ONBOARDING_OPT_OUT_STORAGE_KEY,
EMPTY_CONNECT_ONBOARDING_OPT_OUT_STATE,
ConnectOnboardingOptOutSchema,
);
const desktopBridge = window.desktopBridge;
const primarySessionState = usePrimarySessionState();
const currentSessionScopes = desktopBridge
? AuthAdministrativeScopes
: primarySessionState.data?.authenticated
? (primarySessionState.data.scopes ?? null)
: null;
const canManageRelay = currentSessionScopes?.includes(AuthRelayWriteScope) ?? false;
// The publish step is only offered when we know the answer; opening the
// wizard before the session state resolves would let the step set change
// mid-flight. A failed session read still opens the wizard — it just means
// no publish step.
const sessionScopesKnown =
Boolean(desktopBridge) ||
primarySessionState.data !== null ||
primarySessionState.error !== null;
const controller = useCloudLinkController();
const showPublishStep = canManageRelay && controller.linkState.target !== null;
const steps: ReadonlyArray<OnboardingStep> = showPublishStep
? ["publish", "devices"]
: ["devices"];
const [requestedAccount, setRequestedAccount] = useState<string | null>(null);
const [openForAccount, setOpenForAccount] = useState<string | null>(null);
const [step, setStep] = useState<OnboardingStep>("devices");
const [exposeEnvironment, setExposeEnvironment] = useState(true);
const [publishAgentActivity, setPublishAgentActivity] = useState(true);
const [dontShowAgain, setDontShowAgain] = useState(false);
const [isApplying, setIsApplying] = useState(false);
const prefilledFromLinkStateRef = useRef(false);
const observedAccountRef = useRef<string | null | undefined>(undefined);
const optOutAccounts = optOutState.optOutAccounts;
// Every sign-in or account switch that completes during this session
// requests the wizard — account transitions clear the connected relay
// environments, so each new session starts with no devices to reach. A cold
// load observes undefined → account and must not re-prompt.
useEffect(() => {
if (!isLoaded) return;
// A loaded-but-incomplete snapshot (signed in, user id not yet populated)
// must not be recorded as signed-out — the next render would then look
// like a fresh sign-in on a cold load.
if (isSignedIn && !userId) return;
const previousAccount = observedAccountRef.current;
const nextAccount = isSignedIn && userId ? userId : null;
observedAccountRef.current = nextAccount;
if (previousAccount !== undefined && previousAccount !== nextAccount && nextAccount !== null) {
setRequestedAccount(nextAccount);
}
}, [isLoaded, isSignedIn, userId]);
// A manageable session implies a primary environment, so when the scopes
// allow publishing, wait for the connection target too — otherwise the
// wizard could open on the devices step moments before the publish step
// becomes available and freeze there.
const publishStepDecided = !canManageRelay || controller.linkState.target !== null;
// Open once the session scopes resolve so the step set is stable. Accounts
// that chose "Don't show this again" are skipped.
useEffect(() => {
if (requestedAccount === null || openForAccount !== null) return;
if (optOutAccounts.includes(requestedAccount)) {
setRequestedAccount(null);
return;
}
if (!sessionScopesKnown || !publishStepDecided) return;
setRequestedAccount(null);
prefilledFromLinkStateRef.current = false;
setExposeEnvironment(true);
setPublishAgentActivity(true);
setDontShowAgain(false);
setStep(canManageRelay && controller.linkState.target !== null ? "publish" : "devices");
setOpenForAccount(requestedAccount);
}, [
canManageRelay,
controller.linkState.target,
openForAccount,
optOutAccounts,
publishStepDecided,
requestedAccount,
sessionScopesKnown,
]);
// Signing out (or switching accounts) mid-wizard invalidates everything the
// wizard would do — close it and let the sign-in trigger re-evaluate.
useEffect(() => {
if (openForAccount !== null && (!isSignedIn || userId !== openForAccount)) {
setOpenForAccount(null);
}
if (requestedAccount !== null && (!isSignedIn || userId !== requestedAccount)) {
setRequestedAccount(null);
}
}, [isSignedIn, openForAccount, requestedAccount, userId]);
// Toggles default on, but an environment that is already linked should show
// its actual configuration instead of silently proposing to rewrite it.
// Only when the link belongs to the account being onboarded, though — after
// an account switch the cached link state can still describe the previous
// account's setup.
const linkStateData = controller.linkState.data;
useEffect(() => {
if (openForAccount === null || prefilledFromLinkStateRef.current || linkStateData === null) {
return;
}
prefilledFromLinkStateRef.current = true;
if (linkStateData.linked && linkStateData.cloudUserId === openForAccount) {
setExposeEnvironment(linkStateData.managedTunnelActive ?? linkStateData.linked);
setPublishAgentActivity(linkStateData.publishAgentActivity);
}
}, [linkStateData, openForAccount]);
const complete = () => {
// Keep the wizard up while a link request is in flight so its outcome
// (and any failure) stays visible.
if (isApplying) return;
const account = openForAccount;
setOpenForAccount(null);
if (account !== null && dontShowAgain) {
setOptOutState((state) =>
state.optOutAccounts.includes(account)
? state
: { optOutAccounts: [...state.optOutAccounts, account] },
);
}
};
const applyPublishSelection = async () => {
// The wizard only ever enables — with both toggles off there is nothing to
// apply, and an existing link must not be torn down from onboarding.
if (!exposeEnvironment && !publishAgentActivity) {
setStep("devices");
return;
}
setIsApplying(true);
const ok = await controller.reconcileCloudState({
managedTunnel: exposeEnvironment,
publish: publishAgentActivity,
});
setIsApplying(false);
if (!ok) return;
toastManager.add({
type: "success",
title: "T3 Connect enabled",
description: exposeEnvironment
? "This environment is available to your other devices through T3 Connect."
: "This environment publishes agent activity to your mobile clients.",
});
setStep("devices");
};
return (
<Dialog
open={openForAccount !== null}
onOpenChange={(open) => {
// Keep the dialog up while a link request is in flight so its outcome
// (and any failure) stays visible.
if (!open && !isApplying) complete();
}}
>
<DialogPopup className="max-w-xl">
<DialogHeader>
<DialogTitle>Set up T3 Connect</DialogTitle>
<DialogDescription>
Mesh your devices together — publish this environment and connect the rest, all in one
place.
</DialogDescription>
{steps.length > 1 ? (
<OnboardingStepper
steps={steps}
currentStep={step}
disabled={isApplying}
onStepSelect={setStep}
/>
) : null}
</DialogHeader>
<DialogPanel>
{step === "publish" ? (
<PublishStep
exposeEnvironment={exposeEnvironment}
publishAgentActivity={publishAgentActivity}
disabled={isApplying}
operationError={controller.operationError}
onExposeEnvironmentChange={setExposeEnvironment}
onPublishAgentActivityChange={setPublishAgentActivity}
/>
) : (
<DevicesStep />
)}
</DialogPanel>
<DialogFooter variant="bare" className="sm:justify-between">
<label className="flex cursor-pointer items-center gap-2 self-start text-xs text-muted-foreground sm:self-center">
<Checkbox
checked={dontShowAgain}
onCheckedChange={(checked) => setDontShowAgain(checked === true)}
/>
Don&apos;t show this again
</label>
<div className="flex flex-col-reverse gap-2 sm:flex-row">
{step === "publish" ? (
<>
<Button variant="ghost" disabled={isApplying} onClick={() => setStep("devices")}>
Not now
</Button>
<Button
disabled={
isApplying || (controller.linkState.isPending && linkStateData === null)
}
onClick={() => void applyPublishSelection()}
>
{isApplying ? "Enabling…" : "Continue"}
</Button>
</>
) : (
<Button disabled={isApplying} onClick={complete}>
Done
</Button>
)}
</div>
</DialogFooter>
</DialogPopup>
</Dialog>
);
}
const STEP_LABELS: Record<OnboardingStep, string> = {
publish: "Publish",
devices: "Connect devices",
};
function OnboardingStepper({
steps,
currentStep,
disabled,
onStepSelect,
}: {
readonly steps: ReadonlyArray<OnboardingStep>;
readonly currentStep: OnboardingStep;
readonly disabled: boolean;
readonly onStepSelect: (step: OnboardingStep) => void;
}) {
const currentIndex = steps.indexOf(currentStep);
return (
<div className="grid grid-cols-2 gap-2">
{steps.map((step, index) => (
<button
key={step}
type="button"
disabled={disabled}
className={cn(
"grid min-w-0 grid-cols-[1rem_minmax(0,1fr)] gap-x-2 rounded-lg border px-3 py-2 text-left",
index === currentIndex
? "border-primary bg-primary/10 ring-1 ring-primary/25"
: index < currentIndex
? "border-border bg-background"
: "border-border bg-muted/40",
)}
onClick={() => onStepSelect(step)}
>
<span
className={cn(
"row-span-2 mt-0.5 grid size-4 place-items-center rounded-full border",
index < currentIndex
? "border-primary bg-primary text-primary-foreground"
: index === currentIndex
? "border-primary bg-background"
: "border-muted-foreground/35 bg-background",
)}
aria-hidden
>
{index < currentIndex ? <CheckIcon className="size-3" /> : null}
</span>
<span className="text-[10px] font-medium uppercase text-muted-foreground">
Step {index + 1}
</span>
<span className="truncate text-xs font-semibold text-foreground">
{STEP_LABELS[step]}
</span>
</button>
))}
</div>
);
}
function PublishStep({
exposeEnvironment,
publishAgentActivity,
disabled,
operationError,
onExposeEnvironmentChange,
onPublishAgentActivityChange,
}: {
readonly exposeEnvironment: boolean;
readonly publishAgentActivity: boolean;
readonly disabled: boolean;
readonly operationError: string | null;
readonly onExposeEnvironmentChange: (enabled: boolean) => void;
readonly onPublishAgentActivityChange: (enabled: boolean) => void;
}) {
return (
<div className="space-y-3">
<div className="rounded-lg border">
<OnboardingToggleRow
title="Publish this environment"
description="Make this environment available to your other devices through T3 Connect."
checked={exposeEnvironment}
disabled={disabled}
onCheckedChange={onExposeEnvironmentChange}
/>
<OnboardingToggleRow
title="Publish agent activity"
description="Send activity from this environment to your mobile clients for push notifications and Live Activities."
checked={publishAgentActivity}
disabled={disabled}
onCheckedChange={onPublishAgentActivityChange}
/>
</div>
{operationError ? <p className="text-xs text-destructive">{operationError}</p> : null}
</div>
);
}
function OnboardingToggleRow({
title,
description,
checked,
disabled,
onCheckedChange,
}: {
readonly title: string;
readonly description: string;
readonly checked: boolean;
readonly disabled: boolean;
readonly onCheckedChange: (enabled: boolean) => void;
}) {
return (
<div className="flex items-start justify-between gap-4 border-t border-border/60 px-4 py-3 first:border-t-0">
<div className="min-w-0">
<p className="text-sm font-medium">{title}</p>
<p className="mt-1 text-xs text-muted-foreground">{description}</p>
</div>
<Switch
aria-label={title}
checked={checked}
disabled={disabled}
onCheckedChange={onCheckedChange}
/>
</div>
);
}
function DevicesStep() {
const { environments } = useEnvironments();
const primaryEnvironment = usePrimaryEnvironment();
const savedEnvironmentIds = useMemo(
() =>
environments
.filter((environment) => environment.entry.target._tag !== "PrimaryConnectionTarget")
.map((environment) => environment.environmentId),
[environments],
);
return (
<div className="overflow-hidden rounded-lg border">
<CloudEnvironmentConnectRows
primaryEnvironmentId={primaryEnvironment?.environmentId ?? null}
savedEnvironmentIds={savedEnvironmentIds}
showSavedAsConnected
empty={
<p className="px-4 py-6 text-center text-sm text-muted-foreground">
No other environments are published to your account yet. Publish one from another device
and it will show up here.
</p>
}
/>
</div>
);
}
@@ -7,8 +7,7 @@ import {
TerminalIcon,
TriangleAlertIcon,
} from "lucide-react";
import { useAuth } from "@clerk/react";
import { type ReactNode, memo, useCallback, useEffect, useMemo, useState } from "react";
import { type ReactNode, memo, useCallback, useMemo, useState } from "react";
import {
AuthAccessReadScope,
AuthAccessWriteScope,
@@ -30,18 +29,11 @@ import {
type DesktopWslState,
type EnvironmentId,
} from "@t3tools/contracts";
import {
connectionStatusText,
RelayConnectionRegistration,
RelayConnectionTarget,
} from "@t3tools/client-runtime/connection";
import { findErrorTraceId } from "@t3tools/client-runtime/errors";
import { connectionStatusText } from "@t3tools/client-runtime/connection";
import {
isAtomCommandInterrupted,
settlePromise,
squashAtomCommandFailure,
} from "@t3tools/client-runtime/state/runtime";
import type { RelayClientEnvironmentRecord } from "@t3tools/contracts/relay";
import * as DateTime from "effect/DateTime";
import * as Option from "effect/Option";
@@ -50,7 +42,6 @@ import { cn } from "../../lib/utils";
import { formatElapsedDurationLabel, formatExpiresInLabel } from "../../timestampFormat";
import { resolveDesktopPairingUrl, resolveHostedPairingUrl } from "./pairingUrls";
import { applyWslEnableSelection } from "./ConnectionsSettings.logic";
import { resolveRelayClerkTokenOptions } from "../../cloud/publicConfig";
import {
SettingsPageContainer,
SettingsRow,
@@ -82,7 +73,6 @@ import {
} from "../ui/alert-dialog";
import { Popover, PopoverPopup, PopoverTrigger } from "../ui/popover";
import { QRCodeSvg } from "../ui/qr-code";
import { Skeleton } from "../ui/skeleton";
import { Spinner } from "../ui/spinner";
import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "../ui/select";
import { Switch } from "../ui/switch";
@@ -117,13 +107,8 @@ import {
import { isDesktopLocalConnectionTarget } from "~/connection/desktopLocal";
import { useUiStateStore } from "~/uiStateStore";
import { resolveServerConfigVersionMismatch } from "~/versionSkew";
import { usePrimaryCloudLinkState } from "~/cloud/primaryCloudLinkState";
import { hasCloudPublicConfig } from "~/cloud/publicConfig";
import {
linkPrimaryEnvironment as linkPrimaryEnvironmentAtom,
unlinkPrimaryEnvironment as unlinkPrimaryEnvironmentAtom,
updatePrimaryEnvironmentPreferences as updatePrimaryEnvironmentPreferencesAtom,
} from "~/cloud/linkEnvironmentAtoms";
import { useCloudLinkController } from "~/cloud/useCloudLinkController";
import { authEnvironment } from "~/state/auth";
import { environmentCatalog } from "~/connection/catalog";
import {
@@ -141,10 +126,11 @@ import {
type EnvironmentPresentation,
useEnvironments,
usePrimaryEnvironment,
useRelayEnvironmentDiscovery,
} from "~/state/environments";
import { relayEnvironmentDiscovery } from "~/state/relay";
import { useAtomCommand } from "../../state/use-atom-command";
import { ConnectionStatusDot } from "../ConnectionStatusDot";
import { CloudEnvironmentConnectRows } from "../cloud/CloudEnvironmentConnectList";
import { ITEM_ROW_CLASSNAME, ITEM_ROW_INNER_CLASSNAME } from "./itemRows";
const DEFAULT_TAILSCALE_SERVE_PORT = 443;
const EMPTY_ADVERTISED_ENDPOINTS: ReadonlyArray<AdvertisedEndpoint> = [];
@@ -260,60 +246,6 @@ function AccessScopeSummary({
);
}
type ConnectionStatusDotProps = {
tooltipText?: string | null;
dotClassName: string;
pingClassName?: string | null;
};
function ConnectionStatusDot({
tooltipText,
dotClassName,
pingClassName,
}: ConnectionStatusDotProps) {
const dotContent = (
<>
{pingClassName ? (
<span
className={cn(
"absolute inline-flex h-full w-full animate-ping rounded-full",
pingClassName,
)}
/>
) : null}
<span className={cn("relative inline-flex size-2 rounded-full", dotClassName)} />
</>
);
if (!tooltipText) {
return (
<span className="relative flex size-3 shrink-0 items-center justify-center">
{dotContent}
</span>
);
}
const dot = (
<button
type="button"
title={tooltipText}
aria-label={tooltipText}
className="relative flex size-3 shrink-0 cursor-help items-center justify-center rounded-full outline-hidden"
>
{dotContent}
</button>
);
return (
<Tooltip>
<TooltipTrigger render={dot} />
<TooltipPopup side="top" className="max-w-80 whitespace-pre-wrap leading-tight">
{tooltipText}
</TooltipPopup>
</Tooltip>
);
}
function formatDesktopSshTarget(target: DesktopSshEnvironmentTarget): string {
const authority = target.username ? `${target.username}@${target.hostname}` : target.hostname;
return target.port ? `${authority}:${target.port}` : authority;
@@ -437,13 +369,8 @@ function formatDesktopSshConnectionError(error: unknown): string {
return withoutTaggedErrorPrefix.trim() || fallback;
}
/** Direct row in the card – same pattern as the Provider / ACP-agent list rows. */
const ITEM_ROW_CLASSNAME = "border-t border-border/60 px-4 py-4 first:border-t-0 sm:px-5";
const ENDPOINT_ROW_CLASSNAME = "border-t border-border/60 px-4 py-2.5 first:border-t-0 sm:px-5";
const ITEM_ROW_INNER_CLASSNAME =
"flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between";
type AccessSectionPresentation = "current" | "endpoint-rail";
function accessRowClassName(_presentation: AccessSectionPresentation) {
@@ -1629,51 +1556,17 @@ function CloudLinkSwitch({
}
function ConfiguredCloudLinkRow({ canManageRelay }: { readonly canManageRelay: boolean }) {
const { getToken, isSignedIn } = useAuth();
const refreshRelayEnvironments = useAtomCommand(relayEnvironmentDiscovery.refresh, {
reportFailure: false,
});
const linkPrimaryEnvironment = useAtomCommand(linkPrimaryEnvironmentAtom, {
reportFailure: false,
});
const unlinkPrimaryEnvironment = useAtomCommand(unlinkPrimaryEnvironmentAtom, {
reportFailure: false,
});
const updatePrimaryEnvironmentPreferences = useAtomCommand(
updatePrimaryEnvironmentPreferencesAtom,
{ reportFailure: false },
);
const primaryCloudLinkState = usePrimaryCloudLinkState();
const [operationError, setOperationError] = useState<string | null>(null);
const {
isSignedIn,
linkState: primaryCloudLinkState,
managedTunnelActive,
publishAgentActivity,
operationError,
reconcileCloudState,
} = useCloudLinkController();
const [isUpdating, setIsUpdating] = useState(false);
const [isUpdatingPreference, setIsUpdatingPreference] = useState(false);
const reportUpdateFailure = (cause: unknown) => {
const message = cause instanceof Error ? cause.message : "Could not update T3 Connect access.";
const traceId = findErrorTraceId(cause);
console.error("[t3-connect] Could not update T3 Connect", { message, traceId, cause });
setOperationError(traceId ? `${message} Trace ID: ${traceId}` : message);
toastManager.add({
type: "error",
title: "Could not update T3 Connect",
description: message,
data: traceId
? {
secondaryActionProps: {
children: "Copy trace ID",
onClick: () => void navigator.clipboard?.writeText(traceId),
},
}
: undefined,
});
};
// Older environment servers predate the managedTunnelActive field; for them a
// link always implies a managed tunnel, so fall back to `linked`.
const managedTunnelActive =
primaryCloudLinkState.data?.managedTunnelActive ?? primaryCloudLinkState.data?.linked ?? false;
const publishAgentActivity = primaryCloudLinkState.data?.publishAgentActivity ?? false;
const linked = primaryCloudLinkState.data?.linked ?? false;
const disabledReason = !isSignedIn
? "Sign in to T3 Connect to manage this environment."
: !canManageRelay
@@ -1681,86 +1574,6 @@ function ConfiguredCloudLinkRow({ canManageRelay }: { readonly canManageRelay: b
: null;
const isBusy = isUpdating || isUpdatingPreference;
// T3 Connect (managed tunnel) and publishing are independent capabilities
// backed by a single relay link. Reconcile the whole desired state: unlink
// when neither is wanted, otherwise (re)link with the mode the managed-tunnel
// bit implies and set the publish preference. Re-linking only happens when the
// managed-tunnel mode actually changes, so flipping publish alone is cheap.
const reconcileCloudState = async (desired: {
readonly managedTunnel: boolean;
readonly publish: boolean;
}): Promise<boolean> => {
setOperationError(null);
const target = primaryCloudLinkState.target;
if (!target) {
reportUpdateFailure(new Error("Local environment is not ready yet."));
return false;
}
const tokenResult = await settlePromise(() => getToken(resolveRelayClerkTokenOptions()));
if (tokenResult._tag === "Failure") {
reportUpdateFailure(squashAtomCommandFailure(tokenResult));
return false;
}
const clerkToken = tokenResult.value;
const wantsLink = desired.managedTunnel || desired.publish;
// A failure after this point may follow a partially applied mutation (e.g.
// the link succeeded but the preference update did not), so every exit —
// success or failure — refreshes the rendered state to whatever the server
// actually holds now.
if (!wantsLink) {
const unlinkResult = await unlinkPrimaryEnvironment({
target,
clerkToken: clerkToken ?? null,
});
if (unlinkResult._tag === "Failure") {
if (!isAtomCommandInterrupted(unlinkResult)) {
reportUpdateFailure(squashAtomCommandFailure(unlinkResult));
}
primaryCloudLinkState.refresh();
return false;
}
} else {
if (!clerkToken) {
reportUpdateFailure(new Error("Sign in to T3 Connect before enabling this."));
return false;
}
if (!linked || managedTunnelActive !== desired.managedTunnel) {
const linkResult = await linkPrimaryEnvironment({
target,
clerkToken,
mode: desired.managedTunnel ? "managed" : "publish_only",
});
if (linkResult._tag === "Failure") {
if (!isAtomCommandInterrupted(linkResult)) {
reportUpdateFailure(squashAtomCommandFailure(linkResult));
}
primaryCloudLinkState.refresh();
return false;
}
}
const prefResult = await updatePrimaryEnvironmentPreferences({
target,
publishAgentActivity: desired.publish,
});
if (prefResult._tag === "Failure") {
if (!isAtomCommandInterrupted(prefResult)) {
reportUpdateFailure(squashAtomCommandFailure(prefResult));
}
primaryCloudLinkState.refresh();
return false;
}
}
primaryCloudLinkState.refresh();
const refreshResult = await refreshRelayEnvironments();
if (refreshResult._tag === "Failure" && !isAtomCommandInterrupted(refreshResult)) {
reportUpdateFailure(squashAtomCommandFailure(refreshResult));
return false;
}
return true;
};
const updateManagedTunnel = async (enabled: boolean) => {
setIsUpdating(true);
const ok = await reconcileCloudState({ managedTunnel: enabled, publish: publishAgentActivity });
@@ -1857,163 +1670,6 @@ function EmptyRemoteEnvironments({ cloudEnabled = true }: { readonly cloudEnable
);
}
function RemoteEnvironmentRowsSkeleton() {
return (
<div className={ITEM_ROW_CLASSNAME}>
<div className={ITEM_ROW_INNER_CLASSNAME}>
<div className="min-w-0 flex-1 space-y-2">
<Skeleton className="h-4 w-32 rounded-full" />
<Skeleton className="h-3 w-20 rounded-full" />
</div>
<Skeleton className="h-7 w-16 rounded-md" />
</div>
</div>
);
}
function ConfiguredCloudRemoteEnvironmentRows({
primaryEnvironmentId,
savedEnvironmentIds,
}: {
readonly primaryEnvironmentId: EnvironmentId | null;
readonly savedEnvironmentIds: ReadonlyArray<EnvironmentId>;
}) {
const environmentsState = useRelayEnvironmentDiscovery();
const registerEnvironment = useAtomCommand(environmentCatalog.register, {
reportFailure: false,
});
const refreshRelayEnvironments = useAtomCommand(relayEnvironmentDiscovery.refresh, {
reportFailure: false,
});
const connectRelayEnvironment = useCallback(
(environment: RelayClientEnvironmentRecord) =>
registerEnvironment(
new RelayConnectionRegistration({
target: new RelayConnectionTarget({
environmentId: environment.environmentId,
label: environment.label,
}),
}),
),
[registerEnvironment],
);
const [connectingEnvironmentId, setConnectingEnvironmentId] = useState<EnvironmentId | null>(
null,
);
const savedIds = useMemo(() => new Set(savedEnvironmentIds), [savedEnvironmentIds]);
useEffect(() => {
void refreshRelayEnvironments();
}, [refreshRelayEnvironments]);
const connectEnvironment = async (environment: RelayClientEnvironmentRecord) => {
setConnectingEnvironmentId(environment.environmentId);
const result = await connectRelayEnvironment(environment);
setConnectingEnvironmentId(null);
if (result._tag === "Success") {
toastManager.add({
type: "success",
title: "Environment connected",
description: `${environment.label} is available through T3 Connect.`,
});
return;
}
if (isAtomCommandInterrupted(result)) {
return;
}
const cause = squashAtomCommandFailure(result);
const message =
cause instanceof Error ? cause.message : "Could not connect the T3 Connect environment.";
const traceId = findErrorTraceId(cause);
console.error("[t3-connect] Could not connect environment", { message, traceId, cause });
toastManager.add({
type: "error",
title: "Could not connect environment",
description: message,
data: traceId
? {
secondaryActionProps: {
children: "Copy trace ID",
onClick: () => void navigator.clipboard?.writeText(traceId),
},
}
: undefined,
});
};
const connectableEnvironments = [...environmentsState.environments.values()].filter(
({ environment }) =>
environment.environmentId !== primaryEnvironmentId &&
!savedIds.has(environment.environmentId),
);
if (
savedEnvironmentIds.length === 0 &&
environmentsState.refreshing &&
environmentsState.environments.size === 0
) {
return <RemoteEnvironmentRowsSkeleton />;
}
if (savedEnvironmentIds.length === 0 && connectableEnvironments.length === 0) {
return <EmptyRemoteEnvironments />;
}
return connectableEnvironments.map(({ environment, availability, error }) => (
<div key={environment.environmentId} className={ITEM_ROW_CLASSNAME}>
<div className={ITEM_ROW_INNER_CLASSNAME}>
<div className="min-w-0">
<div className="flex items-center gap-2">
<ConnectionStatusDot
dotClassName={
availability === "online"
? "bg-success"
: availability === "error"
? "bg-destructive"
: availability === "checking"
? "bg-warning"
: "bg-muted-foreground/35"
}
pingClassName={availability === "checking" ? "bg-warning/60 duration-2000" : null}
tooltipText={
availability === "online"
? "Relay online"
: availability === "offline"
? "Relay offline"
: availability === "checking"
? "Checking relay status"
: (Option.getOrNull(error)?.message ?? "Relay status unavailable")
}
/>
<p className="truncate text-sm font-medium">{environment.label}</p>
</div>
<p
className={cn(
"mt-1 truncate text-xs",
availability === "error" ? "text-destructive" : "text-muted-foreground",
)}
>
{availability === "online"
? "Available · Relay online"
: availability === "offline"
? "Available · Relay offline"
: availability === "checking"
? "Available · Checking relay status…"
: (Option.getOrNull(error)?.message ?? "Available · Relay status unavailable")}
</p>
</div>
<Button
size="sm"
disabled={connectingEnvironmentId !== null}
onClick={() => void connectEnvironment(environment)}
>
{connectingEnvironmentId === environment.environmentId ? "Connecting…" : "Connect"}
</Button>
</div>
</div>
));
}
function CloudRemoteEnvironmentRows({
primaryEnvironmentId,
savedEnvironmentIds,
@@ -2022,9 +1678,10 @@ function CloudRemoteEnvironmentRows({
readonly savedEnvironmentIds: ReadonlyArray<EnvironmentId>;
}) {
return hasCloudPublicConfig() ? (
<ConfiguredCloudRemoteEnvironmentRows
<CloudEnvironmentConnectRows
primaryEnvironmentId={primaryEnvironmentId}
savedEnvironmentIds={savedEnvironmentIds}
empty={<EmptyRemoteEnvironments />}
/>
) : savedEnvironmentIds.length === 0 ? (
<EmptyRemoteEnvironments cloudEnabled={false} />
@@ -0,0 +1,5 @@
/** Direct row in the card – same pattern as the Provider / ACP-agent list rows. */
export const ITEM_ROW_CLASSNAME = "border-t border-border/60 px-4 py-4 first:border-t-0 sm:px-5";
export const ITEM_ROW_INNER_CLASSNAME =
"flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between";
+39 -28
View File
@@ -75,7 +75,7 @@ import {
insertInlineTerminalContextPlaceholder,
type TerminalContextDraft,
} from "./lib/terminalContext";
import { createDebouncedStorage } from "./lib/storage";
import { createDebouncedJsonStorage } from "./lib/storage";
function makeImage(input: {
id: string;
@@ -1648,7 +1648,7 @@ describe("composerDraftStore runtime and interaction settings", () => {
});
// ---------------------------------------------------------------------------
// createDebouncedStorage
// createDebouncedJsonStorage
// ---------------------------------------------------------------------------
function createMockStorage() {
@@ -1664,7 +1664,11 @@ function createMockStorage() {
};
}
describe("createDebouncedStorage", () => {
describe("createDebouncedJsonStorage", () => {
const v1 = { state: { value: "v1" }, version: 1 };
const v2 = { state: { value: "v2" }, version: 1 };
const v3 = { state: { value: "v3" }, version: 1 };
beforeEach(() => {
vi.useFakeTimers();
});
@@ -1673,47 +1677,54 @@ describe("createDebouncedStorage", () => {
vi.useRealTimers();
});
it("delegates getItem immediately", () => {
it("parses getItem results immediately", () => {
const base = createMockStorage();
base.getItem.mockReturnValueOnce("value");
const storage = createDebouncedStorage(base);
base.getItem.mockReturnValueOnce(JSON.stringify(v1));
const storage = createDebouncedJsonStorage(base);
expect(storage.getItem("key")).toBe("value");
expect(storage.getItem("key")).toEqual(v1);
expect(base.getItem).toHaveBeenCalledWith("key");
});
it("does not write to base storage until the debounce fires", () => {
it("returns null from getItem when nothing is stored", () => {
const base = createMockStorage();
const storage = createDebouncedStorage(base);
const storage = createDebouncedJsonStorage(base);
storage.setItem("key", "v1");
expect(storage.getItem("key")).toBeNull();
});
it("does not serialize or write until the debounce fires", () => {
const base = createMockStorage();
const storage = createDebouncedJsonStorage(base);
storage.setItem("key", v1);
expect(base.setItem).not.toHaveBeenCalled();
vi.advanceTimersByTime(299);
expect(base.setItem).not.toHaveBeenCalled();
vi.advanceTimersByTime(1);
expect(base.setItem).toHaveBeenCalledWith("key", "v1");
expect(base.setItem).toHaveBeenCalledWith("key", JSON.stringify(v1));
});
it("only writes the last value when setItem is called rapidly", () => {
const base = createMockStorage();
const storage = createDebouncedStorage(base);
const storage = createDebouncedJsonStorage(base);
storage.setItem("key", "v1");
storage.setItem("key", "v2");
storage.setItem("key", "v3");
storage.setItem("key", v1);
storage.setItem("key", v2);
storage.setItem("key", v3);
vi.advanceTimersByTime(300);
expect(base.setItem).toHaveBeenCalledTimes(1);
expect(base.setItem).toHaveBeenCalledWith("key", "v3");
expect(base.setItem).toHaveBeenCalledWith("key", JSON.stringify(v3));
});
it("removeItem cancels a pending setItem write", () => {
const base = createMockStorage();
const storage = createDebouncedStorage(base);
const storage = createDebouncedJsonStorage(base);
storage.setItem("key", "v1");
storage.setItem("key", v1);
storage.removeItem("key");
vi.advanceTimersByTime(300);
@@ -1723,13 +1734,13 @@ describe("createDebouncedStorage", () => {
it("flush writes the pending value immediately", () => {
const base = createMockStorage();
const storage = createDebouncedStorage(base);
const storage = createDebouncedJsonStorage(base);
storage.setItem("key", "v1");
storage.setItem("key", v1);
expect(base.setItem).not.toHaveBeenCalled();
storage.flush();
expect(base.setItem).toHaveBeenCalledWith("key", "v1");
expect(base.setItem).toHaveBeenCalledWith("key", JSON.stringify(v1));
// Timer should be cancelled; no duplicate write.
vi.advanceTimersByTime(300);
@@ -1738,7 +1749,7 @@ describe("createDebouncedStorage", () => {
it("flush is a no-op when nothing is pending", () => {
const base = createMockStorage();
const storage = createDebouncedStorage(base);
const storage = createDebouncedJsonStorage(base);
storage.flush();
expect(base.setItem).not.toHaveBeenCalled();
@@ -1746,9 +1757,9 @@ describe("createDebouncedStorage", () => {
it("flush after removeItem is a no-op", () => {
const base = createMockStorage();
const storage = createDebouncedStorage(base);
const storage = createDebouncedJsonStorage(base);
storage.setItem("key", "v1");
storage.setItem("key", v1);
storage.removeItem("key");
storage.flush();
@@ -1757,14 +1768,14 @@ describe("createDebouncedStorage", () => {
it("setItem works normally after removeItem cancels a pending write", () => {
const base = createMockStorage();
const storage = createDebouncedStorage(base);
const storage = createDebouncedJsonStorage(base);
storage.setItem("key", "v1");
storage.setItem("key", v1);
storage.removeItem("key");
storage.setItem("key", "v2");
storage.setItem("key", v2);
vi.advanceTimersByTime(300);
expect(base.setItem).toHaveBeenCalledTimes(1);
expect(base.setItem).toHaveBeenCalledWith("key", "v2");
expect(base.setItem).toHaveBeenCalledWith("key", JSON.stringify(v2));
});
});
+82 -75
View File
@@ -46,9 +46,9 @@ import {
newElementContextId,
} from "./lib/elementContext";
import { create } from "zustand";
import { createJSONStorage, persist } from "zustand/middleware";
import { persist } from "zustand/middleware";
import { useShallow } from "zustand/react/shallow";
import { createDebouncedStorage, createMemoryStorage } from "./lib/storage";
import { createDebouncedJsonStorage, createMemoryStorage } from "./lib/storage";
import { getDefaultServerModel } from "./providerModels";
import { UnifiedSettings } from "@t3tools/contracts/settings";
import { ReviewCommentContextSchema, type ReviewCommentContext } from "./reviewCommentContext";
@@ -66,7 +66,7 @@ export type DraftId = typeof DraftId.Type;
const COMPOSER_PERSIST_DEBOUNCE_MS = 300;
const composerDebouncedStorage = createDebouncedStorage(
const composerDebouncedStorage = createDebouncedJsonStorage<PersistedComposerDraftStoreState>(
typeof localStorage !== "undefined" ? localStorage : createMemoryStorage(),
COMPOSER_PERSIST_DEBOUNCE_MS,
);
@@ -1825,78 +1825,11 @@ function partializeComposerDraftStoreState(
if (typeof threadKey !== "string" || threadKey.length === 0) {
continue;
}
const hasModelData =
Object.keys(draft.modelSelectionByProvider).length > 0 || draft.activeProvider !== null;
if (
draft.prompt.length === 0 &&
draft.persistedAttachments.length === 0 &&
draft.terminalContexts.length === 0 &&
draft.elementContexts.length === 0 &&
draft.previewAnnotations.length === 0 &&
draft.reviewComments.length === 0 &&
!hasModelData &&
draft.runtimeMode === null &&
draft.interactionMode === null
) {
continue;
const persisted = partializeComposerThreadDraft(draft);
if (persisted !== null) {
persistedDraftsByThreadKey[threadKey] =
persisted as DeepMutable<PersistedComposerThreadDraftState>;
}
const persistedDraft: DeepMutable<PersistedComposerThreadDraftState> = {
prompt: draft.prompt,
attachments: draft.persistedAttachments,
...(draft.terminalContexts.length > 0
? {
terminalContexts: draft.terminalContexts.map((context) => ({
id: context.id,
threadId: context.threadId,
createdAt: context.createdAt,
terminalId: context.terminalId,
terminalLabel: context.terminalLabel,
lineStart: context.lineStart,
lineEnd: context.lineEnd,
})),
}
: {}),
...(draft.elementContexts.length > 0
? {
elementContexts: draft.elementContexts.map((context) => ({
id: context.id,
threadId: context.threadId,
pickedAt: context.pickedAt,
pageUrl: context.pageUrl,
pageTitle: context.pageTitle,
tagName: context.tagName,
selector: context.selector,
htmlPreview: context.htmlPreview,
componentName: context.componentName,
source: context.source,
styles: context.styles,
})),
}
: {}),
...(draft.previewAnnotations.length > 0
? {
previewAnnotations: draft.previewAnnotations.map(
(annotation) => ({ ...annotation }) as DeepMutable<PreviewAnnotationPayload>,
),
}
: {}),
...(draft.reviewComments.length > 0
? {
reviewComments: draft.reviewComments.map((comment) => ({ ...comment })),
}
: {}),
...(hasModelData
? {
modelSelectionByProvider: compactModelSelectionByProvider(
draft.modelSelectionByProvider,
),
activeProvider: draft.activeProvider,
}
: {}),
...(draft.runtimeMode ? { runtimeMode: draft.runtimeMode } : {}),
...(draft.interactionMode ? { interactionMode: draft.interactionMode } : {}),
};
persistedDraftsByThreadKey[threadKey] = persistedDraft;
}
return {
draftsByThreadKey: persistedDraftsByThreadKey,
@@ -1910,6 +1843,80 @@ function partializeComposerDraftStoreState(
};
}
function partializeComposerThreadDraft(
draft: ComposerThreadDraftState,
): PersistedComposerThreadDraftState | null {
const hasModelData =
Object.keys(draft.modelSelectionByProvider).length > 0 || draft.activeProvider !== null;
if (
draft.prompt.length === 0 &&
draft.persistedAttachments.length === 0 &&
draft.terminalContexts.length === 0 &&
draft.elementContexts.length === 0 &&
draft.previewAnnotations.length === 0 &&
draft.reviewComments.length === 0 &&
!hasModelData &&
draft.runtimeMode === null &&
draft.interactionMode === null
) {
return null;
}
return {
prompt: draft.prompt,
attachments: draft.persistedAttachments,
...(draft.terminalContexts.length > 0
? {
terminalContexts: draft.terminalContexts.map((context) => ({
id: context.id,
threadId: context.threadId,
createdAt: context.createdAt,
terminalId: context.terminalId,
terminalLabel: context.terminalLabel,
lineStart: context.lineStart,
lineEnd: context.lineEnd,
})),
}
: {}),
...(draft.elementContexts.length > 0
? {
elementContexts: draft.elementContexts.map((context) => ({
id: context.id,
threadId: context.threadId,
pickedAt: context.pickedAt,
pageUrl: context.pageUrl,
pageTitle: context.pageTitle,
tagName: context.tagName,
selector: context.selector,
htmlPreview: context.htmlPreview,
componentName: context.componentName,
source: context.source,
styles: context.styles,
})),
}
: {}),
...(draft.previewAnnotations.length > 0
? {
previewAnnotations: draft.previewAnnotations.map(
(annotation) => ({ ...annotation }) as DeepMutable<PreviewAnnotationPayload>,
),
}
: {}),
...(draft.reviewComments.length > 0
? {
reviewComments: draft.reviewComments.map((comment) => ({ ...comment })),
}
: {}),
...(hasModelData
? {
modelSelectionByProvider: compactModelSelectionByProvider(draft.modelSelectionByProvider),
activeProvider: draft.activeProvider,
}
: {}),
...(draft.runtimeMode ? { runtimeMode: draft.runtimeMode } : {}),
...(draft.interactionMode ? { interactionMode: draft.interactionMode } : {}),
};
}
function normalizeCurrentPersistedComposerDraftStoreState(
persistedState: unknown,
): PersistedComposerDraftStoreState {
@@ -3341,7 +3348,7 @@ const composerDraftStore = create<ComposerDraftStoreState>()(
{
name: COMPOSER_DRAFT_STORAGE_KEY,
version: COMPOSER_DRAFT_STORAGE_VERSION,
storage: createJSONStorage(() => composerDebouncedStorage),
storage: composerDebouncedStorage,
migrate: migratePersistedComposerDraftStoreState,
partialize: partializeComposerDraftStoreState,
merge: (persistedState, currentState) => {
+2 -2
View File
@@ -182,7 +182,7 @@ const capabilitiesLayer = Layer.effectContext(
if (session === null) {
return yield* new ConnectionBlockedError({
reason: "authentication",
detail: "Sign in to T3 Cloud to connect this environment.",
detail: "Sign in to T3 Connect to connect this environment.",
});
}
const token = yield* session.readClerkToken().pipe(
@@ -197,7 +197,7 @@ const capabilitiesLayer = Layer.effectContext(
if (token === null) {
return yield* new ConnectionBlockedError({
reason: "authentication",
detail: "The T3 Cloud session is unavailable.",
detail: "The T3 Connect session is unavailable.",
});
}
return token;
@@ -5,12 +5,33 @@ import { readDesktopSecondaryBootstraps } from "./desktopLocal";
const DESKTOP_LOCAL_BOOTSTRAP_POLL_MS = 2_000;
function bootstrapsEqual(
left: ReadonlyArray<DesktopEnvironmentBootstrap>,
right: ReadonlyArray<DesktopEnvironmentBootstrap>,
): boolean {
if (left.length !== right.length) {
return false;
}
return left.every((entry, index) => {
const other = right[index];
return (
other !== undefined &&
entry.id === other.id &&
entry.label === other.label &&
entry.runningDistro === other.runningDistro &&
entry.httpBaseUrl === other.httpBaseUrl &&
entry.wsBaseUrl === other.wsBaseUrl &&
entry.bootstrapToken === other.bootstrapToken
);
});
}
/**
* Reactively track the desktop's secondary local backends (e.g. a parallel WSL
* backend). The bridge exposes no change event, so we re-read on an interval;
* failed reads retain the latest successful snapshot, while a successful empty
* read clears it. Use this instead of polling the bridge ad hoc so every
* renderer consumer reads the same topology.
* backend). The bridge exposes no change event, so each hook instance re-reads
* on its own interval; a poll returns a fresh array, so the previous reference
* is kept when the topology is unchanged to avoid re-rendering the consumer
* every tick. Use this instead of polling the bridge ad hoc.
*/
export function useDesktopLocalBootstraps(): ReadonlyArray<DesktopEnvironmentBootstrap> {
const [bootstraps, setBootstraps] = useState<ReadonlyArray<DesktopEnvironmentBootstrap>>(
@@ -18,7 +39,10 @@ export function useDesktopLocalBootstraps(): ReadonlyArray<DesktopEnvironmentBoo
);
useEffect(() => {
const read = () => setBootstraps(readDesktopSecondaryBootstraps());
const read = () => {
const next = readDesktopSecondaryBootstraps();
setBootstraps((previous) => (bootstrapsEqual(previous, next) ? previous : next));
};
read();
const interval = setInterval(read, DESKTOP_LOCAL_BOOTSTRAP_POLL_MS);
return () => clearInterval(interval);
+21 -9
View File
@@ -1,4 +1,5 @@
import { Debouncer } from "@tanstack/react-pacer";
import type { PersistStorage, StorageValue } from "zustand/middleware";
export interface StateStorage<R = unknown> {
getItem: (name: string) => string | null | Promise<string | null>;
@@ -6,10 +7,6 @@ export interface StateStorage<R = unknown> {
removeItem: (name: string) => R;
}
export interface DebouncedStorage<R = unknown> extends StateStorage<R> {
flush: () => void;
}
export function createMemoryStorage(): StateStorage {
const store = new Map<string, string>();
return {
@@ -39,20 +36,35 @@ export function resolveStorage(storage: Partial<StateStorage> | null | undefined
return isStateStorage(storage) ? storage : createMemoryStorage();
}
export function createDebouncedStorage(
export interface DebouncedPersistStorage<S> extends PersistStorage<S> {
flush: () => void;
}
/**
* A zustand `PersistStorage` that debounces the JSON serialization as well as
* the storage write. `createJSONStorage` + a debounced `StateStorage` only
* delays the write — the full state is still stringified on every store
* update; here it happens once per debounce window instead.
*/
export function createDebouncedJsonStorage<S>(
baseStorage: Partial<StateStorage> | null | undefined,
debounceMs: number = 300,
): DebouncedStorage {
): DebouncedPersistStorage<S> {
const resolvedStorage = resolveStorage(baseStorage);
const debouncedSetItem = new Debouncer(
(name: string, value: string) => {
resolvedStorage.setItem(name, value);
(name: string, value: StorageValue<S>) => {
resolvedStorage.setItem(name, JSON.stringify(value));
},
{ wait: debounceMs },
);
return {
getItem: (name) => resolvedStorage.getItem(name),
getItem: (name) => {
const raw = resolvedStorage.getItem(name);
const parse = (value: string | null): StorageValue<S> | null =>
value === null ? null : (JSON.parse(value) as StorageValue<S>);
return raw instanceof Promise ? raw.then(parse) : parse(raw);
},
setItem: (name, value) => {
debouncedSetItem.maybeExecute(name, value);
},
+2
View File
@@ -14,6 +14,7 @@ import { APP_BASE_NAME, APP_DISPLAY_NAME, APP_STAGE_LABEL } from "../branding";
import { resolveServerBackedAppDisplayName } from "../branding.logic";
import { AppSidebarLayout } from "../components/AppSidebarLayout";
import { CommandPalette } from "../components/CommandPalette";
import { ConnectOnboardingDialog } from "../components/cloud/ConnectOnboardingDialog";
import { RelayClientInstallDialog } from "../components/cloud/RelayClientInstallDialog";
import { SshPasswordPromptDialog } from "../components/desktop/SshPasswordPromptDialog";
import { ProviderUpdateLaunchNotification } from "../components/ProviderUpdateLaunchNotification";
@@ -128,6 +129,7 @@ function RootRouteView() {
<DocumentTitleSync />
{primaryEnvironmentAuthenticated ? <AuthenticatedTracingBootstrap /> : null}
<RelayClientInstallDialog />
<ConnectOnboardingDialog />
<SshPasswordPromptDialog />
<SlowRpcRequestToastCoordinator />
<HostedStaticEnvironmentBootstrap />
+33 -4
View File
@@ -356,7 +356,7 @@ export function derivePendingApprovals(
activities: ReadonlyArray<OrchestrationThreadActivity>,
): PendingApproval[] {
const openByRequestId = new Map<ApprovalRequestId, PendingApproval>();
const ordered = [...activities].toSorted(compareActivitiesByOrder);
const ordered = orderActivities(activities);
for (const activity of ordered) {
const payload =
@@ -462,7 +462,7 @@ export function derivePendingUserInputs(
activities: ReadonlyArray<OrchestrationThreadActivity>,
): PendingUserInput[] {
const openByRequestId = new Map<ApprovalRequestId, PendingUserInput>();
const ordered = [...activities].toSorted(compareActivitiesByOrder);
const ordered = orderActivities(activities);
for (const activity of ordered) {
const payload =
@@ -511,7 +511,7 @@ export function deriveActivePlanState(
activities: ReadonlyArray<OrchestrationThreadActivity>,
latestTurnId: TurnId | undefined,
): ActivePlanState | null {
const ordered = [...activities].toSorted(compareActivitiesByOrder);
const ordered = orderActivities(activities);
const allPlanActivities = ordered.filter((activity) => activity.kind === "turn.plan.updated");
// Prefer plan from the current turn; fall back to the most recent plan from any turn
// so that TodoWrite tasks persist across follow-up messages.
@@ -627,7 +627,7 @@ export function hasActionableProposedPlan(
export function deriveWorkLogEntries(
activities: ReadonlyArray<OrchestrationThreadActivity>,
): WorkLogEntry[] {
const ordered = [...activities].toSorted(compareActivitiesByOrder);
const ordered = orderActivities(activities);
const entries: DerivedWorkLogEntry[] = [];
for (const activity of ordered) {
if (activity.kind === "tool.started") continue;
@@ -1296,6 +1296,35 @@ function extractChangedFiles(payload: Record<string, unknown> | null): string[]
return changedFiles;
}
// Several independent derivations (work log, pending approvals, pending user
// inputs, active plan) order the same activities array per render. The reducer
// appends in order, so the input is almost always already sorted — detect that
// in O(n) and share the result per array identity instead of copying and
// re-sorting the whole history in each derivation.
const orderedActivitiesCache = new WeakMap<
ReadonlyArray<OrchestrationThreadActivity>,
ReadonlyArray<OrchestrationThreadActivity>
>();
function orderActivities(
activities: ReadonlyArray<OrchestrationThreadActivity>,
): ReadonlyArray<OrchestrationThreadActivity> {
const cached = orderedActivitiesCache.get(activities);
if (cached) {
return cached;
}
let isSorted = true;
for (let index = 1; index < activities.length; index += 1) {
if (compareActivitiesByOrder(activities[index - 1]!, activities[index]!) > 0) {
isSorted = false;
break;
}
}
const ordered = isSorted ? activities : [...activities].toSorted(compareActivitiesByOrder);
orderedActivitiesCache.set(activities, ordered);
return ordered;
}
function compareActivitiesByOrder(
left: OrchestrationThreadActivity,
right: OrchestrationThreadActivity,
@@ -736,7 +736,7 @@ describe("makeAggregateState", () => {
...state,
threadId: "thread-done" as RelayAgentActivityState["threadId"],
phase: "completed",
updatedAt: "1970-01-01T00:50:00.000Z",
updatedAt: "1970-01-01T00:44:00.000Z",
};
const aggregate = AgentActivityPublisher.makeAggregateState({
activeStates: [active, staleCompleted],
@@ -769,7 +769,7 @@ describe("makeAggregateState", () => {
});
expect(
AgentActivityPublisher.makeAggregateState({
activeStates: [{ ...lingeringCompleted, updatedAt: "1970-01-01T00:50:00.000Z" }],
activeStates: [{ ...lingeringCompleted, updatedAt: "1970-01-01T00:44:00.000Z" }],
terminalState: null,
nowMs: hourMs,
}),
@@ -789,16 +789,25 @@ describe("makeAggregateState", () => {
updatedAt: "1970-01-01T00:59:00.000Z",
};
const aggregate = AgentActivityPublisher.makeAggregateState({
activeStates: [mkActive("a-1"), mkActive("a-2"), mkActive("a-3"), justCompleted],
activeStates: [
mkActive("a-1"),
mkActive("a-2"),
mkActive("a-3"),
mkActive("a-4"),
mkActive("a-5"),
justCompleted,
],
terminalState: null,
nowMs: hourMs,
});
expect(aggregate?.activeCount).toBe(3);
expect(aggregate?.activeCount).toBe(5);
expect(aggregate?.activities).toMatchObject([
{ threadId: "a-1" },
{ threadId: "a-2" },
{ threadId: "a-3" },
{ threadId: "a-4" },
{ threadId: "a-5" },
]);
});
});
@@ -13,6 +13,7 @@ import * as Option from "effect/Option";
import {
isExpiredAgentActivityState,
isTerminalPhase,
MAX_ACTIVITY_ROWS,
sanitizeAgentActivityAggregateState,
} from "./agentActivityPayloads.ts";
@@ -228,7 +229,7 @@ function terminalAggregateState(state: RelayAgentActivityState): RelayAgentActiv
// How long a finished thread keeps its Done/Failed row in the aggregate while
// other agents are still active. Long enough to be seen on the lock screen,
// short enough that the activity list stays about live work.
export const TERMINAL_AGENT_ACTIVITY_DISPLAY_TTL_MS = 5 * 60 * 1_000;
export const TERMINAL_AGENT_ACTIVITY_DISPLAY_TTL_MS = 15 * 60 * 1_000;
function isRecentTerminalState(state: RelayAgentActivityState, nowMs: number): boolean {
if (!isTerminalPhase(state)) {
@@ -273,7 +274,7 @@ export function makeAggregateState(input: {
subtitle: newest.phase === "failed" ? "Agent work failed" : "Agent work completed",
activeCount: 0,
updatedAt: newest.updatedAt,
activities: recentTerminal.slice(0, 3).map(aggregateRowForState),
activities: recentTerminal.slice(0, MAX_ACTIVITY_ROWS).map(aggregateRowForState),
});
}
// Recently finished threads ride along after the active ones (display slots
@@ -282,7 +283,10 @@ export function makeAggregateState(input: {
const recentTerminalStates = input.activeStates
.filter((state) => isRecentTerminalState(state, input.nowMs))
.sort((a, b) => b.updatedAt.localeCompare(a.updatedAt));
const displayedStates = [...activeStates.slice(0, 3), ...recentTerminalStates].slice(0, 3);
const displayedStates = [
...activeStates.slice(0, MAX_ACTIVITY_ROWS),
...recentTerminalStates,
].slice(0, MAX_ACTIVITY_ROWS);
const updatedAt = [...activeStates, ...recentTerminalStates].reduce((latest, state) =>
state.updatedAt.localeCompare(latest.updatedAt) > 0 ? state : latest,
).updatedAt;
@@ -373,7 +373,7 @@ describe("ApnsDeliveries", () => {
...aggregate,
title: longTitle,
subtitle: longTitle,
activities: [0, 1, 2, 3].map((index) =>
activities: [0, 1, 2, 3, 4, 5].map((index) =>
Object.assign({}, aggregate.activities[0]!, {
projectTitle: longTitle,
threadTitle: longTitle,
@@ -396,7 +396,7 @@ describe("ApnsDeliveries", () => {
const payloadAggregate = queuedJobs[0]?.payload.aggregate;
expect(payloadAggregate?.title.length).toBeLessThanOrEqual(120);
expect(payloadAggregate?.subtitle.length).toBeLessThanOrEqual(120);
expect(payloadAggregate?.activities).toHaveLength(3);
expect(payloadAggregate?.activities).toHaveLength(5);
expect(payloadAggregate?.activities[0]?.projectTitle.length).toBeLessThanOrEqual(120);
expect(payloadAggregate?.activities[0]?.status.length).toBeLessThanOrEqual(40);
expect(payloadAggregate?.activities[0]?.deepLink).toBe("/");
@@ -43,7 +43,9 @@ export function isExpiredAgentActivityState(
const MAX_SUMMARY_TEXT_LENGTH = 120;
const MAX_STATUS_TEXT_LENGTH = 40;
const MAX_DEEP_LINK_LENGTH = 512;
const MAX_ACTIVITY_ROWS = 3;
// The Live Activity banner (lock screen / Notification Center) renders up to
// five rows; the expanded Dynamic Island shows the top three of these.
export const MAX_ACTIVITY_ROWS = 5;
function truncateText(value: string, maxLength: number): string {
const trimmed = value.trim();
+1 -1
View File
@@ -48,7 +48,7 @@
"engines": {
"node": "^24.13.1"
},
"packageManager": "pnpm@10.24.0",
"packageManager": "pnpm@11.10.0",
"msw": {
"workerDirectory": [
"apps/web/public"
@@ -342,6 +342,55 @@ describe("RelayEnvironmentDiscovery", () => {
}),
);
it.effect("refreshes proactively when credentials change before any manual refresh", () =>
Effect.gen(function* () {
const harness = yield* makeHarness();
yield* Effect.gen(function* () {
const discovery = yield* RelayEnvironmentDiscovery.RelayEnvironmentDiscovery;
const requests = yield* Ref.get(harness.statusRequests);
for (const environment of environments) {
yield* Deferred.succeed(
requests.get(environment.environmentId)!,
status(environment, "online"),
);
}
// Let the scoped wakeup subscription start before emitting, mirroring
// a real sign-in which always happens long after service start.
yield* Effect.yieldNow;
// Sign-in activates the session and emits credentials-changed; the
// list must populate without any screen having asked for a refresh.
yield* harness.wake("credentials-changed");
const populated = yield* SubscriptionRef.changes(discovery.state).pipe(
Stream.filter(
(state) => state.environments.size === environments.length && !state.refreshing,
),
Stream.runHead,
Effect.map(Option.getOrThrow),
);
expect(Option.isNone(populated.error)).toBe(true);
expect(yield* Ref.get(harness.listCalls)).toBe(1);
}).pipe(Effect.provide(harness.layer), Effect.scoped);
}),
);
it.effect("settles to a clean empty state when refreshed while signed out", () =>
Effect.gen(function* () {
const harness = yield* makeHarness();
yield* Effect.gen(function* () {
const discovery = yield* RelayEnvironmentDiscovery.RelayEnvironmentDiscovery;
yield* Ref.set(harness.clerkToken, null);
yield* discovery.refresh;
const state = yield* SubscriptionRef.get(discovery.state);
expect(state.environments.size).toBe(0);
expect(state.refreshing).toBe(false);
expect(Option.isNone(state.error)).toBe(true);
}).pipe(Effect.provide(harness.layer));
}),
);
it.effect("does not republish stale rows after sign-out invalidates an in-flight refresh", () =>
Effect.gen(function* () {
const harness = yield* makeHarness();
+26 -5
View File
@@ -222,7 +222,27 @@ export const make = Effect.fn("RelayEnvironmentDiscovery.make")(function* () {
error: Option.none(),
});
const clerkToken = yield* session.clerkToken;
// Signed out is the idle state, not a failure: the proactive refresh on
// credentials-changed also runs on sign-out and must settle back to a
// clean empty list. Only the session-level "no credentials" error is
// benign — relay-side auth failures (expired/invalid tokens) happen
// after this point and must surface as errors.
const tokenResult = yield* Effect.result(session.clerkToken);
if (tokenResult._tag === "Failure") {
const failure = tokenResult.failure;
if (failure._tag === "ConnectionBlockedError" && failure.reason === "authentication") {
if ((yield* Ref.get(accountGeneration)) !== generation) {
return;
}
yield* SubscriptionRef.update(state, (current) => ({
...current,
refreshing: false,
}));
return;
}
return yield* Effect.fail(failure);
}
const clerkToken = tokenResult.success;
if ((yield* Ref.get(accountGeneration)) !== generation) {
return;
}
@@ -311,11 +331,12 @@ export const make = Effect.fn("RelayEnvironmentDiscovery.make")(function* () {
yield* Ref.update(accountGeneration, (current) => current + 1);
yield* Ref.set(activeAccountId, Option.none());
yield* Ref.set(offlineReportFingerprints, new Map());
const shouldRefresh = yield* Ref.get(hasRefreshed);
yield* SubscriptionRef.set(state, EMPTY_RELAY_ENVIRONMENT_DISCOVERY_STATE);
if (shouldRefresh) {
yield* refresh.pipe(Effect.forkScoped);
}
// Refresh proactively — this wakeup fires when a session activates
// (sign-in or cold start), and the list should be populated before
// any screen asks for it. A signed-out refresh settles back to the
// clean empty state.
yield* refresh.pipe(Effect.forkScoped);
})
: Effect.void,
),
@@ -123,7 +123,7 @@ export function createManagedRelaySession(input: ManagedRelaySessionInput): Mana
try: () => readCachedClerkToken(nowMillis),
catch: (cause) =>
new ManagedRelaySessionError({
message: "Could not obtain the T3 Cloud session token.",
message: "Could not obtain the T3 Connect session token.",
cause,
}),
});
@@ -181,7 +181,7 @@ function readSessionClerkToken(
? Effect.succeed(token)
: Effect.fail(
new ManagedRelaySessionError({
message: "The T3 Cloud session token is unavailable.",
message: "The T3 Connect session token is unavailable.",
}),
),
),
@@ -226,7 +226,7 @@ function requireClerkToken(
if (!session || session.accountId !== accountId) {
return Effect.fail(
new ManagedRelaySessionError({
message: "Sign in to T3 Cloud before loading relay data.",
message: "Sign in to T3 Connect before loading relay data.",
}),
);
}
@@ -296,7 +296,7 @@ export function readManagedRelaySnapshotState<A>(
let errorTraceId: string | null = null;
if (result._tag === "Failure") {
const cause = Cause.squash(result.cause);
error = cause instanceof Error ? cause.message : "Could not load T3 Cloud data.";
error = cause instanceof Error ? cause.message : "Could not load T3 Connect data.";
errorTraceId = findErrorTraceId(cause);
}
return {
@@ -457,12 +457,21 @@ export function applyThreadDetailEvent(
// ── Activities ──────────────────────────────────────────────────
case "thread.activity-appended": {
const activities = pipe(
thread.activities,
Arr.filter((activity) => activity.id !== event.payload.activity.id),
Arr.append(event.payload.activity),
Arr.sort(activityOrder),
);
const activity = event.payload.activity;
// Live activities arrive in order and are new: keep the sorted invariant
// with a single append instead of filter+append+sort over the (possibly
// very long) history on every event.
const lastActivity = thread.activities.at(-1);
const activities =
(lastActivity === undefined || activityOrder(lastActivity, activity) <= 0) &&
!thread.activities.some((entry) => entry.id === activity.id)
? Arr.append(thread.activities, activity)
: pipe(
thread.activities,
Arr.filter((entry) => entry.id !== activity.id),
Arr.append(activity),
Arr.sort(activityOrder),
);
return {
kind: "updated",
@@ -5,6 +5,7 @@ import {
ProjectId,
ProviderInstanceId,
ThreadId,
TurnId,
type OrchestrationThread,
type OrchestrationThreadDetailSnapshot,
type OrchestrationThreadStreamItem,
@@ -304,6 +305,67 @@ describe("EnvironmentThreads", () => {
}),
);
it.effect("skips snapshot persistence while the session is running a turn", () =>
Effect.gen(function* () {
const harness = yield* makeHarness({ cached: BASE_THREAD });
yield* Queue.offer(harness.inputs, snapshot(BASE_THREAD));
const sessionSet = (
status: "running" | "idle",
sequence: number,
): OrchestrationThreadStreamItem => ({
kind: "event",
event: {
eventId: EventId.make(`event-session-${sequence}`),
sequence,
occurredAt: "2026-04-01T01:00:00.000Z",
commandId: null,
causationEventId: null,
correlationId: null,
metadata: {},
aggregateKind: "thread",
aggregateId: THREAD_ID,
type: "thread.session-set",
payload: {
threadId: THREAD_ID,
session: {
threadId: THREAD_ID,
status,
providerName: null,
runtimeMode: "full-access",
activeTurnId: status === "running" ? TurnId.make("turn-1") : null,
lastError: null,
updatedAt: "2026-04-01T01:00:00.000Z",
},
},
},
});
yield* Queue.offer(harness.inputs, sessionSet("running", 2));
yield* Queue.offer(harness.inputs, titleUpdated("Streaming title", 3));
yield* awaitThreadState(
harness.observed,
(value) => Option.isSome(value.data) && value.data.value.title === "Streaming title",
);
yield* TestClock.adjust("500 millis");
yield* Effect.yieldNow;
const savedWhileRunning = yield* Ref.get(harness.savedThreads);
expect(savedWhileRunning.some((saved) => saved.thread.title === "Streaming title")).toBe(
false,
);
yield* Queue.offer(harness.inputs, sessionSet("idle", 4));
yield* awaitThreadState(
harness.observed,
(value) => Option.isSome(value.data) && value.data.value.session?.status === "idle",
);
yield* TestClock.adjust("500 millis");
yield* Effect.yieldNow;
const savedAfterSettle = yield* Ref.get(harness.savedThreads);
expect(savedAfterSettle.at(-1)?.thread.title).toBe("Streaming title");
expect(savedAfterSettle.at(-1)?.snapshotSequence).toBe(4);
}),
);
it.effect("seeds the thread from the HTTP snapshot and resumes live events", () =>
Effect.gen(function* () {
const httpThread: OrchestrationThread = { ...BASE_THREAD, title: "HTTP title" };
+8 -1
View File
@@ -129,7 +129,14 @@ export const makeEnvironmentThreadState = Effect.fn("EnvironmentThreadState.make
error: Option.none(),
});
// Persist the thread together with the sequence it reflects so the next warm
// cache can resume from exactly here.
// cache can resume from exactly here. While a turn is actively running,
// events arrive many times per second and each snapshot encode covers the
// whole thread history — skip those; the session leaving "running" (and the
// scope finalizer) persists the settled state, and a stale cache only means
// resuming via a slightly longer `afterSequence` replay.
if (thread.session?.status === "running") {
return;
}
const snapshotSequence = yield* SubscriptionRef.get(lastSequence);
yield* Queue.offer(persistence, { snapshotSequence, thread });
});
@@ -155,6 +155,46 @@ describe("vcsActionState", () => {
});
});
it("clears running presentation state once the action finishes", () => {
const initial = beginVcsActionState({
operation: "run_change_request",
label: "Running source control action",
actionId,
});
const pushing = applyVcsActionProgressEvent(
initial,
progress({
actionId,
action,
cwd,
kind: "phase_started",
phase: "push",
label: "Pushing...",
}),
);
const finished = applyVcsActionProgressEvent(
pushing,
progress({
actionId,
action,
cwd,
kind: "action_finished",
result,
}),
);
expect(finished).toMatchObject({
isRunning: false,
operation: "run_change_request",
actionId,
action,
currentLabel: null,
currentPhaseLabel: null,
lastOutputLine: null,
error: null,
});
});
it("retains a terminal action error for presentation", () => {
const initial = beginVcsActionState({
operation: "run_change_request",
@@ -386,12 +386,10 @@ export function applyVcsActionProgressEvent(
};
case "action_finished":
return {
...current,
isRunning: false,
...EMPTY_VCS_ACTION_STATE,
actionId: event.actionId,
action: event.action,
operation: "run_change_request",
error: null,
};
case "action_failed":
return {
+1
View File
@@ -552,6 +552,7 @@ const ThreadMetaUpdateCommand = Schema.Struct({
title: Schema.optional(TrimmedNonEmptyString),
modelSelection: Schema.optional(ModelSelection),
branch: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)),
expectedBranch: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)),
worktreePath: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)),
});
+40 -1
View File
@@ -1,3 +1,42 @@
diff --git a/android/src/main/java/com/swmansion/rnscreens/ScreenStackHeaderConfigViewManager.kt b/android/src/main/java/com/swmansion/rnscreens/ScreenStackHeaderConfigViewManager.kt
index 03d8d9f3a5c403c93282d53cbacf1a339e877e85..54d5eabc6c8a408e711a5be97286fdbb8ab1c461 100644
--- a/android/src/main/java/com/swmansion/rnscreens/ScreenStackHeaderConfigViewManager.kt
+++ b/android/src/main/java/com/swmansion/rnscreens/ScreenStackHeaderConfigViewManager.kt
@@ -103,6 +103,34 @@ class ScreenStackHeaderConfigViewManager :
config.setTitle(title)
}
+ // The t3 patch adds these iOS glass-chrome props to the native spec; they have
+ // no Android implementation, but the codegen-generated interface requires the
+ // setters to exist. No-ops keep the Android build compiling.
+ override fun setSubtitle(
+ config: ScreenStackHeaderConfig,
+ subtitle: String?,
+ ) = Unit
+
+ override fun setLargeSubtitle(
+ config: ScreenStackHeaderConfig,
+ largeSubtitle: String?,
+ ) = Unit
+
+ override fun setNavigationItemStyle(
+ config: ScreenStackHeaderConfig,
+ navigationItemStyle: String?,
+ ) = Unit
+
+ override fun setHeaderCenterBarButtonItems(
+ config: ScreenStackHeaderConfig,
+ headerCenterBarButtonItems: ReadableArray?,
+ ) = Unit
+
+ override fun setHeaderToolbarItems(
+ config: ScreenStackHeaderConfig,
+ headerToolbarItems: ReadableArray?,
+ ) = Unit
+
override fun setTitleFontFamily(
config: ScreenStackHeaderConfig,
titleFontFamily: String?,
diff --git a/ios/RNSBarButtonItem.h b/ios/RNSBarButtonItem.h
index ea5325ea8d17b1ddfa790ff8dab48ce83142d4d3..acd2fd7ceb7162ed300abc4d3c9f0c24f4d63898 100644
--- a/ios/RNSBarButtonItem.h
@@ -1067,7 +1106,7 @@ index b7568ecfebd4f4420f2a8d3fec5184d7fc728dd1..41ca1f273f0175929e73105faa463978
onPressHeaderBarButtonMenuItem?: CT.DirectEventHandler<OnPressHeaderBarButtonMenuItemEvent> | undefined;
synchronousShadowStateUpdatesEnabled?: CT.WithDefault<boolean, false>;
diff --git a/lib/typescript/types.d.ts b/lib/typescript/types.d.ts
index 3b384e03891e38e936f370372a682d73440e7ec2..1e3a966806c8b8b312f75fb367f758efe49dde9d 100644
index 3b384e03891e38e936f370372a682d73440e7ec2..861ffed850e90f27916c427853b503dbe6ee9840 100644
--- a/lib/typescript/types.d.ts
+++ b/lib/typescript/types.d.ts
@@ -10,6 +10,7 @@ export type SearchBarCommands = {
+542 -564
View File
File diff suppressed because it is too large. Load diff
+30 -15
View File
@@ -5,14 +5,31 @@ packages:
- packages/*
- scripts
# Successor to onlyBuiltDependencies/ignoredBuiltDependencies (pnpm 11).
# true = allowed to run build scripts; false mirrors the pnpm 10 behavior
# where anything outside onlyBuiltDependencies was silently not built.
allowBuilds:
browser-tabs-lock: false
bufferutil: false
core-js: false
electron: true
electron-winstaller: false
esbuild: true
msgpackr-extract: true
msw: false
node-pty: true
sharp: true
utf-8-validate: false
workerd: false
catalog:
"@clerk/backend": 3.8.4
"@clerk/clerk-js": 6.22.0
"@clerk/electron": 0.0.5
"@clerk/backend": 3.11.2
"@clerk/clerk-js": 6.25.1
"@clerk/electron": 0.0.11
"@clerk/electron-passkeys": 0.0.3
"@clerk/expo": 3.6.2
"@clerk/react": 6.11.1
"@clerk/shared": 4.22.0
"@clerk/expo": 3.7.2
"@clerk/react": 6.12.1
"@clerk/shared": 4.25.1
"@effect/atom-react": 4.0.0-beta.78
"@effect/openapi-generator": 4.0.0-beta.78
"@effect/platform-bun": 4.0.0-beta.78
@@ -34,15 +51,13 @@ catalog:
vite-plus: 0.2.2
yaml: ^2.9.0
ignoredBuiltDependencies:
- msw
onlyBuiltDependencies:
- electron
- esbuild
- msgpackr-extract
- node-pty
- sharp
minimumReleaseAgeExclude:
- "@clerk/[email protected]"
- "@clerk/[email protected]"
- "@clerk/[email protected]"
- "@clerk/[email protected]"
- "@clerk/[email protected]"
- "@clerk/[email protected]"
overrides:
"@clerk/backend": "catalog:"
+83 -14
View File
@@ -11,7 +11,7 @@ import { ChildProcessSpawner } from "effect/unstable/process";
import {
BuildCommandFailedError,
createStageWorkspaceConfig,
createStagePnpmConfig,
createStagePatchedDependencies,
createBuildConfig,
DESKTOP_ASAR_UNPACK,
InvalidMacPasskeyRpDomainError,
@@ -33,6 +33,7 @@ import {
resolveGitHubPublishConfig,
resolveMockUpdateServerPort,
resolveMockUpdateServerUrl,
resolvePackageManagerUserAgent,
stageLinuxIconSize,
STAGE_INSTALL_ARGS,
} from "./build-desktop-artifact.ts";
@@ -168,7 +169,7 @@ it.layer(NodeServices.layer)("build-desktop-artifact", (it) => {
it("carries only staged dependency patch metadata into staged desktop installs", () => {
assert.deepStrictEqual(
createStagePnpmConfig(
createStagePatchedDependencies(
{
"@expo/[email protected]": "patches/@expo%[email protected]",
"@ff-labs/[email protected]": "patches/@[email protected]",
@@ -183,50 +184,55 @@ it.layer(NodeServices.layer)("build-desktop-artifact", (it) => {
},
),
{
patchedDependencies: {
"@ff-labs/[email protected]": "patches/@[email protected].patch",
"@pierre/[email protected]": "patches/@pierre%[email protected].patch",
"[email protected]": "patches/[email protected]",
},
"@ff-labs/[email protected]": "patches/@[email protected]",
"@pierre/[email protected]": "patches/@pierre%[email protected].patch",
"[email protected]": "patches/[email protected].patch",
},
);
assert.equal(
createStagePnpmConfig(
assert.deepStrictEqual(
createStagePatchedDependencies(
{
"@expo/[email protected]": "patches/@expo%[email protected]",
},
{ effect: "4.0.0-beta.73" },
),
undefined,
{},
);
});
it("installs optional native dependencies for the target desktop architecture", () => {
assert.deepStrictEqual(STAGE_INSTALL_ARGS, ["install", "--prod"]);
assert.deepStrictEqual(createStageWorkspaceConfig("mac", "x64"), {
assert.deepStrictEqual(createStageWorkspaceConfig({ platform: "mac", arch: "x64" }), {
supportedArchitectures: {
os: ["darwin"],
cpu: ["x64"],
},
});
assert.deepStrictEqual(createStageWorkspaceConfig({ platform: "linux", arch: "x64" }), {
supportedArchitectures: {
os: ["linux"],
cpu: ["x64"],
libc: ["glibc"],
},
});
// Windows artifacts also bundle the same-architecture WSL (Linux, glibc) backend, so the
// staged install must fetch its native optional deps (e.g. ffi-rs) too.
assert.deepStrictEqual(createStageWorkspaceConfig("win", "x64"), {
assert.deepStrictEqual(createStageWorkspaceConfig({ platform: "win", arch: "x64" }), {
supportedArchitectures: {
os: ["win32", "linux"],
cpu: ["x64"],
libc: ["glibc"],
},
});
assert.deepStrictEqual(createStageWorkspaceConfig("win", "arm64"), {
assert.deepStrictEqual(createStageWorkspaceConfig({ platform: "win", arch: "arm64" }), {
supportedArchitectures: {
os: ["win32", "linux"],
cpu: ["arm64"],
libc: ["glibc"],
},
});
assert.deepStrictEqual(createStageWorkspaceConfig("mac", "universal"), {
assert.deepStrictEqual(createStageWorkspaceConfig({ platform: "mac", arch: "universal" }), {
supportedArchitectures: {
os: ["darwin"],
cpu: ["arm64", "x64"],
@@ -234,6 +240,63 @@ it.layer(NodeServices.layer)("build-desktop-artifact", (it) => {
});
});
it("stages pnpm 11 allowBuilds and patchedDependencies in the workspace yaml", () => {
assert.deepStrictEqual(
createStageWorkspaceConfig({
platform: "linux",
arch: "x64",
allowBuilds: {
electron: true,
"node-pty": true,
"browser-tabs-lock": false,
},
patchedDependencies: {
"[email protected]": "patches/[email protected]",
},
overrides: {
effect: "4.0.0-beta.73",
},
}),
{
supportedArchitectures: {
os: ["linux"],
cpu: ["x64"],
libc: ["glibc"],
},
allowBuilds: {
electron: true,
"node-pty": true,
"browser-tabs-lock": false,
},
patchedDependencies: {
"[email protected]": "patches/[email protected]",
},
overrides: {
effect: "4.0.0-beta.73",
},
},
);
// Empty maps must not be written — pnpm would still require reviewed
// packages if allowBuilds is present but incomplete, and omitting empty
// patchedDependencies keeps the stage yaml minimal.
assert.deepStrictEqual(
createStageWorkspaceConfig({
platform: "mac",
arch: "arm64",
allowBuilds: {},
patchedDependencies: {},
overrides: {},
}),
{
supportedArchitectures: {
os: ["darwin"],
cpu: ["arm64"],
},
},
);
});
it("unpacks the fff shared library for filesystem and FFI access", () => {
assert.deepStrictEqual(DESKTOP_ASAR_UNPACK, ["node_modules/@ff-labs/fff-bin-*/**/*"]);
});
@@ -475,6 +538,12 @@ it.layer(NodeServices.layer)("build-desktop-artifact", (it) => {
assert.equal(resolveMockUpdateServerUrl(4123), "http://localhost:4123");
});
it("derives the electron-builder package manager user agent from packageManager", () => {
assert.equal(resolvePackageManagerUserAgent("[email protected]"), "pnpm/11.10.0");
assert.equal(resolvePackageManagerUserAgent(" [email protected] "), "yarn/4.9.2");
assert.equal(resolvePackageManagerUserAgent("pnpm"), "pnpm");
});
it.effect("normalizes mock update server ports from env-style strings", () =>
Effect.gen(function* () {
assert.equal(yield* resolveMockUpdateServerPort(undefined), undefined);
+74 -38
View File
@@ -40,6 +40,7 @@ const WorkspaceConfig = Schema.Struct({
catalog: Schema.optional(Schema.Record(Schema.String, Schema.String)),
overrides: Schema.optional(Schema.Record(Schema.String, Schema.String)),
patchedDependencies: Schema.optional(Schema.Record(Schema.String, Schema.String)),
allowBuilds: Schema.optional(Schema.Record(Schema.String, Schema.Boolean)),
});
type WorkspaceConfig = typeof WorkspaceConfig.Type;
@@ -49,7 +50,14 @@ const StageWorkspaceConfig = Schema.Struct({
cpu: Schema.Array(Schema.String),
libc: Schema.optional(Schema.Array(Schema.String)),
}),
// pnpm 11 only reads these from pnpm-workspace.yaml (not package.json#pnpm).
// Without allowBuilds the staged `vp install --prod` fails with
// ERR_PNPM_IGNORED_BUILDS for packages that have lifecycle scripts.
allowBuilds: Schema.optional(Schema.Record(Schema.String, Schema.Boolean)),
patchedDependencies: Schema.optional(Schema.Record(Schema.String, Schema.String)),
overrides: Schema.optional(Schema.Record(Schema.String, Schema.String)),
});
type StageWorkspaceConfig = typeof StageWorkspaceConfig.Type;
const RepoRoot = Effect.service(Path.Path).pipe(
Effect.flatMap((path) => path.fromFileUrl(new URL("..", import.meta.url))),
@@ -563,10 +571,6 @@ interface StagePackageJson {
readonly devDependencies: {
readonly electron: string;
};
readonly overrides: Record<string, unknown>;
readonly pnpm?: {
readonly patchedDependencies?: Record<string, string>;
};
}
export const STAGE_INSTALL_ARGS = ["install", "--prod"] as const;
@@ -876,47 +880,57 @@ const stageClerkPasskeyNativeBinaries = Effect.fn("stageClerkPasskeyNativeBinari
}
});
export function createStageWorkspaceConfig(
platform: typeof BuildPlatform.Type,
arch: typeof BuildArch.Type,
): typeof StageWorkspaceConfig.Type {
export function createStageWorkspaceConfig(input: {
readonly platform: typeof BuildPlatform.Type;
readonly arch: typeof BuildArch.Type;
readonly allowBuilds?: Record<string, boolean>;
readonly patchedDependencies?: Record<string, string>;
readonly overrides?: Record<string, string>;
}): StageWorkspaceConfig {
const { platform, arch, allowBuilds, patchedDependencies, overrides } = input;
const hostOs = platform === "mac" ? "darwin" : platform === "win" ? "win32" : "linux";
const hostCpu = arch === "universal" ? ["arm64", "x64"] : [arch];
// Windows artifacts also bundle the same-architecture WSL Linux backend, which loads
// Linux-native optional deps at runtime (e.g. @yuuang/ffi-rs-linux-x64-gnu).
// Pull the Linux (glibc) variants in addition to the host platform's so
// they ship in the asar; without them the WSL backend crash-loops on require
// ("Cannot find module '@yuuang/ffi-rs-linux-x64-gnu'").
if (platform === "win") {
return {
supportedArchitectures: {
os: Array.from(new Set([hostOs, "linux"])),
cpu: hostCpu,
libc: ["glibc"],
},
};
}
// Linux AppImages and Windows WSL backends both execute a Linux/glibc Node
// process that loads Linux-native optional deps at runtime (e.g.
// @yuuang/ffi-rs-linux-x64-gnu). Keep libc explicit so pnpm includes those
// optional packages in the staged production install.
const supportedArchitectures =
platform === "linux"
? {
os: [hostOs],
cpu: hostCpu,
libc: ["glibc"],
}
: platform === "win"
? {
os: Array.from(new Set([hostOs, "linux"])),
cpu: hostCpu,
libc: ["glibc"],
}
: {
os: [hostOs],
cpu: hostCpu,
};
return {
supportedArchitectures: {
os: [hostOs],
cpu: hostCpu,
},
supportedArchitectures,
...(allowBuilds && Object.keys(allowBuilds).length > 0 ? { allowBuilds } : {}),
...(patchedDependencies && Object.keys(patchedDependencies).length > 0
? { patchedDependencies }
: {}),
...(overrides && Object.keys(overrides).length > 0 ? { overrides } : {}),
};
}
export function createStagePnpmConfig(
export function createStagePatchedDependencies(
patchedDependencies: Record<string, string>,
dependencies: Record<string, unknown>,
): StagePackageJson["pnpm"] | undefined {
const stagePatchedDependencies = Object.fromEntries(
): Record<string, string> {
return Object.fromEntries(
Object.entries(patchedDependencies).filter(([patchKey]) =>
Object.hasOwn(dependencies, getPatchedDependencyPackageName(patchKey)),
),
);
return Object.keys(stagePatchedDependencies).length > 0
? { patchedDependencies: stagePatchedDependencies }
: undefined;
}
function getPatchedDependencyPackageName(patchKey: string): string {
@@ -1330,6 +1344,19 @@ export function resolveMockUpdateServerUrl(mockUpdateServerPort: number | undefi
return `http://localhost:${mockUpdateServerPort ?? 3000}`;
}
// Electron Builder detects pnpm from npm_config_user_agent, whose value uses
// user-agent syntax (pnpm/11.10.0) rather than packageManager syntax
// ([email protected]).
export function resolvePackageManagerUserAgent(packageManager: string): string {
const trimmed = packageManager.trim();
const versionSeparator = trimmed.lastIndexOf("@");
if (versionSeparator <= 0 || versionSeparator === trimmed.length - 1) {
return trimmed;
}
return `${trimmed.slice(0, versionSeparator)}/${trimmed.slice(versionSeparator + 1)}`;
}
export function resolveDesktopProductName(version: string): string {
return resolveDesktopUpdateChannel(version) === "nightly"
? "T3 Code (Nightly)"
@@ -1540,6 +1567,7 @@ const buildDesktopArtifact = Effect.fn("buildDesktopArtifact")(function* (
const workspaceCatalog = workspaceConfig.catalog ?? {};
const workspaceOverrides = workspaceConfig.overrides ?? {};
const workspacePatchedDependencies = workspaceConfig.patchedDependencies ?? {};
const workspaceAllowBuilds = workspaceConfig.allowBuilds ?? {};
const platformConfig = PLATFORM_CONFIG[options.platform];
if (!platformConfig) {
@@ -1709,7 +1737,10 @@ const buildDesktopArtifact = Effect.fn("buildDesktopArtifact")(function* (
)
: {}),
};
const stagePnpmConfig = createStagePnpmConfig(workspacePatchedDependencies, stageDependencies);
const stagePatchedDependencies = createStagePatchedDependencies(
workspacePatchedDependencies,
stageDependencies,
);
const stagePackageJson: StagePackageJson = {
name: "t3code",
version: appVersion,
@@ -1738,20 +1769,24 @@ const buildDesktopArtifact = Effect.fn("buildDesktopArtifact")(function* (
devDependencies: {
electron: electronVersion,
},
overrides: resolvedOverrides,
...(stagePnpmConfig ? { pnpm: stagePnpmConfig } : {}),
};
const stagePackageJsonString = yield* encodeJsonString(stagePackageJson);
yield* fs.writeFileString(path.join(stageAppDir, "package.json"), `${stagePackageJsonString}\n`);
const stageWorkspaceConfig = createStageWorkspaceConfig(options.platform, options.arch);
const stageWorkspaceConfig = createStageWorkspaceConfig({
platform: options.platform,
arch: options.arch,
allowBuilds: workspaceAllowBuilds,
patchedDependencies: stagePatchedDependencies,
overrides: resolvedOverrides,
});
const stageWorkspaceConfigString = yield* encodeStageWorkspaceConfig(stageWorkspaceConfig);
yield* fs.writeFileString(
path.join(stageAppDir, "pnpm-workspace.yaml"),
stageWorkspaceConfigString,
);
if (Object.keys(workspacePatchedDependencies).length > 0) {
if (Object.keys(stagePatchedDependencies).length > 0) {
yield* fs.copy(path.join(repoRoot, "patches"), path.join(stageAppDir, "patches"));
}
@@ -1782,6 +1817,7 @@ const buildDesktopArtifact = Effect.fn("buildDesktopArtifact")(function* (
const buildEnv: NodeJS.ProcessEnv = {
...process.env,
};
buildEnv.npm_config_user_agent = resolvePackageManagerUserAgent(rootPackageJson.packageManager);
for (const [key, value] of Object.entries(buildEnv)) {
if (value === "") {
delete buildEnv[key];