Compare commits

..
Author SHA1 Message Date
Cursor Agent b4d9649137 Add retry button to T3 Connect discovery error card 2026-07-07 19:41:23 +00:00
Julius Marminge 593aa69833 Polish connect onboarding sheet
- Restore native sheet header and close affordance
- Add pull-to-refresh and simplify onboarding actions
- Reuse cloud rows without the section header in onboarding
2026-07-07 12:33:02 -07:00
Julius Marminge 4f648f1e11 Simplify Connect onboarding to sign-in only
- Remove device publishing flow from onboarding
- Add per-account "Don't show this again" opt-out
- Update mobile and web copy to T3 Connect
2026-07-07 11:07:31 -07:00
Julius Marminge 53ab016efd Add T3 Connect onboarding flow
- Present an onboarding sheet after in-session sign-in
- Let users publish local environments and connect cloud environments
- Persist onboarding completion per account across mobile sessions
2026-07-07 02:03:05 -07:00
40 changed files with 838 additions and 1341 deletions

No files matched your search

-72
View File
@@ -1,72 +0,0 @@
---
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).
+1 -4
View File
@@ -57,10 +57,7 @@ jobs:
with:
eas-version: latest
token: ${{ secrets.EXPO_TOKEN }}
# 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
packager: pnpm
- name: Pull preview environment variables
if: steps.expo-token.outputs.present == 'true'
+1 -4
View File
@@ -80,10 +80,7 @@ jobs:
with:
eas-version: latest
token: ${{ secrets.EXPO_TOKEN }}
# 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
packager: pnpm
- 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.15.6",
"electron-builder": "26.8.1",
"tailwindcss": "^4.0.0",
"vite-plus": "catalog:"
},
+5 -21
View File
@@ -15,7 +15,6 @@ 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;
@@ -25,7 +24,6 @@ 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",
@@ -34,7 +32,6 @@ 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",
@@ -43,7 +40,6 @@ 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",
@@ -135,12 +131,12 @@ const config: ExpoConfig = {
[
"expo-splash-screen",
{
image: variant.splashIcon,
image: "./assets/splash-icon.png",
resizeMode: "contain",
backgroundColor: "#ffffff",
imageWidth: 220,
dark: {
image: variant.splashIcon,
image: "./assets/splash-icon.png",
backgroundColor: "#0a0a0a",
},
},
@@ -159,12 +155,6 @@ 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",
{
@@ -184,6 +174,9 @@ 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",
],
@@ -196,15 +189,6 @@ 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,
Binary file not shown.

Before

Width:  |  Height:  |  Size: 302 KiB

File renamed without changes.

Before

Width:  |  Height:  |  Size: 2.0 MiB

After

Width:  |  Height:  |  Size: 2.0 MiB

@@ -9,10 +9,8 @@
// 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. 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.
// Idempotent across re-runs. Returns true when it added the phase, false when it
// was already present or the target was not found.
const PHASE_NAME = "Compile Widget Assets";
@@ -22,8 +20,8 @@ const ACTOOL_SCRIPT = [
"set -e",
'CATALOG="${SRCROOT}/ExpoWidgetsTarget/Assets.xcassets"',
'if [ ! -d "$CATALOG" ]; then',
' echo "error: widget asset catalog not found at $CATALOG (expo-widgets wiped it? check plugin ordering in app.config.ts)"',
" exit 1",
' echo "warning: widget asset catalog not found at $CATALOG"',
" exit 0",
"fi",
'DEST="${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}"',
'mkdir -p "$DEST"',
@@ -53,13 +51,7 @@ function findByName(map, name) {
function addWidgetAssetCatalog(proj, opts) {
const objects = proj.hash.project.objects;
const target = findByName(objects.PBXNativeTarget, opts.targetName);
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.",
);
}
if (!target) return false;
const phases = target.value.buildPhases || [];
const existing = objects.PBXShellScriptBuildPhase || {};
+3 -9
View File
@@ -5,15 +5,9 @@
// 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 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.
// 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.
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.");
console.log("No change: phase already present or target not found.");
}
@@ -18,7 +18,7 @@ import {
setAgentAwarenessRelayTokenProvider,
unregisterAgentAwarenessDeviceForCurrentUser,
} from "../agent-awareness/remoteRegistration";
import { clearConnectOnboardingRequest, requestConnectOnboarding } from "./connectOnboarding";
import { requestConnectOnboarding } from "./connectOnboarding";
import { resolveCloudPublicConfig, resolveRelayClerkTokenOptions } from "./publicConfig";
function resetManagedRelayTokenCache() {
@@ -68,17 +68,12 @@ 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();
// Every sign-in that completes during this session (a cold start observes
// undefined → account and must not re-prompt) requests the T3 Connect
// onboarding sheet — sign-out clears the connected environments, so each
// new session starts with no devices to reach.
if (previousObservedAccount === null && nextAccount !== null) {
requestConnectOnboarding(nextAccount);
}
const queueAccountCleanup = (
@@ -128,9 +123,6 @@ 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 () => {
@@ -1,7 +1,7 @@
import { NativeHeaderToolbar } from "../../native/StackHeader";
import { useAuth } from "@clerk/expo";
import { StackActions, useNavigation } from "@react-navigation/native";
import { useCallback, useEffect, useState } from "react";
import { useNavigation } from "@react-navigation/native";
import { useCallback, useState } from "react";
import { Pressable, RefreshControl, ScrollView, View } from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context";
@@ -22,21 +22,6 @@ import { hasCloudPublicConfig } from "./publicConfig";
* 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;
}
@@ -67,16 +52,14 @@ function ConfiguredConnectOnboardingRouteScreen() {
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) {
if (userId) {
void (async () => {
const result = await settlePromise(() => optOutOfConnectOnboarding(userId));
reportAtomCommandResult(result, { label: "connect onboarding opt-out" });
}
navigation.goBack();
})();
})();
}
navigation.goBack();
}, [navigation, userId]);
return (
@@ -85,7 +68,6 @@ function ConfiguredConnectOnboardingRouteScreen() {
<NativeHeaderToolbar.Button icon="xmark" onPress={handleClose} separateBackground />
</NativeHeaderToolbar>
<ScrollView
alwaysBounceVertical
contentInsetAdjustmentBehavior="automatic"
showsVerticalScrollIndicator={false}
style={{ flex: 1 }}
@@ -2,7 +2,6 @@ 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";
@@ -29,10 +28,7 @@ export function useConnectOnboardingNavigation(): void {
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) {
if (cancelled) {
return;
}
clearConnectOnboardingRequest();
@@ -1,4 +1,4 @@
import { loadPreferences, updatePreferences } from "../../lib/storage";
import { loadPreferences, savePreferencesPatch } from "../../lib/storage";
// Lives apart from connectOnboarding.ts so CloudAuthProvider (which imports
// the request signal) never pulls lib/storage — expo-secure-store — into its
@@ -12,10 +12,10 @@ export async function isConnectOnboardingOptedOut(accountId: string): Promise<bo
/** 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] };
});
const preferences = await loadPreferences();
const optedOut = preferences.connectOnboardingOptOutAccounts ?? [];
if (optedOut.includes(accountId)) {
return;
}
await savePreferencesPatch({ connectOnboardingOptOutAccounts: [...optedOut, accountId] });
}
@@ -124,36 +124,40 @@ export function CloudEnvironmentRows(props: {
Loading linked cloud environments.
</Text>
</View>
) : controller.relayDiscovery.error ? null : (
) : 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 Connect environments
</Text>
<Text className="text-sm text-foreground-muted">{controller.relayDiscovery.error}</Text>
<View className="flex-row items-center gap-2">
<Pressable
accessibilityRole="button"
onPress={() => {
void controller.refreshRelayEnvironments();
}}
className="flex-row items-center gap-1.5 rounded-full bg-subtle px-3 py-2 active:opacity-70"
>
<SymbolView
name="arrow.clockwise"
size={12}
tintColor={iconColor}
type="monochrome"
/>
<Text className="text-xs font-t3-bold text-foreground">Try again</Text>
</Pressable>
{controller.relayDiscovery.errorTraceId ? (
<CopyTraceIdButton traceId={controller.relayDiscovery.errorTraceId} />
) : null}
</View>
</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>
)}
{/* 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>
);
}
@@ -112,12 +112,7 @@ function AddProjectShell(props: { readonly children: ReactNode }) {
const insets = useSafeAreaInsets();
return (
// 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">
<View className="flex-1 bg-sheet">
<ScrollView
keyboardShouldPersistTaps="handled"
contentInsetAdjustmentBehavior="automatic"
+7 -21
View File
@@ -199,28 +199,14 @@ export async function loadPreferences(): Promise<Preferences> {
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> {
return updatePreferences(() => patch);
const current = await loadPreferences();
const next: Preferences = {
...current,
...patch,
};
await writeJsonStorageItem(PREFERENCES_KEY, next);
return next;
}
export async function loadOrCreateAgentAwarenessDeviceId(): Promise<string> {
@@ -199,70 +199,6 @@ 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(
{
+8 -21
View File
@@ -123,28 +123,16 @@ 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 = allDone ? outcomeLabel : `${props.activeCount} active ${agentWord}`;
const agentsLabel = `${props.activeCount} active ${agentWord}`;
const attentionSuffix =
attentionRows.length > 0
? `${attentionRows.length} need${attentionRows.length === 1 ? "s" : ""} attention`
: "";
const activeLabel = allDone ? doneLabel : `${props.activeCount} active`;
const summary = attentionSuffix || activeLabel;
const summary = attentionSuffix || `${props.activeCount} active`;
// 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.
@@ -154,6 +142,8 @@ 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"]>;
@@ -255,9 +245,7 @@ export function AgentActivity(
<Text
modifiers={[
font({ weight: "semibold", size: 13 }),
// The all-done header carries the outcome tint (emerald /
// red) the way the Done/Failed status labels do.
foregroundStyle(allDone ? headerTint : primaryForeground),
foregroundStyle(primaryForeground),
lineLimit(1),
]}
>
@@ -334,17 +322,16 @@ export function AgentActivity(
</Text>
),
// The shared/minimal form is a ~22pt circle — a single signal reads there,
// the wordmark does not. Show the blocking/outcome phase glyph, else the
// mark (all-done shows the hero row's checkmark/cross).
// the wordmark does not. Show the blocking phase glyph, else the mark.
minimal:
(attentionRow || failedRow || allDone) && heroRow
attentionRow || failedRow
? 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)]}>
{allDone ? doneLabel : `${props.activeCount}`}
{`${props.activeCount}`}
</Text>
</HStack>
),
@@ -59,7 +59,6 @@ describe("TraceDiagnostics", () => {
durationMs: 50,
}),
"not-json",
'{"name":"missing span fields","durationMs":"not-a-number"}',
].join("\n"),
},
{
@@ -124,7 +123,7 @@ describe("TraceDiagnostics", () => {
}),
"1970-01-01T00:00:05.025Z",
);
assert.equal(diagnostics.parseErrorCount, 2);
assert.equal(diagnostics.parseErrorCount, 1);
assert.equal(diagnostics.failureCount, 2);
assert.equal(diagnostics.interruptionCount, 1);
assert.equal(diagnostics.slowSpanCount, 1);
+55 -59
View File
@@ -16,19 +16,17 @@ import * as Option from "effect/Option";
import * as PlatformError from "effect/PlatformError";
import * as Result from "effect/Result";
import * as Schema from "effect/Schema";
import { decodeJsonResult } from "@t3tools/shared/schemaJson";
const TraceRecordLineSchema = Schema.Struct({
name: Schema.String,
traceId: Schema.String,
spanId: Schema.String,
startTimeUnixNano: Schema.optional(Schema.NullOr(Schema.String)),
endTimeUnixNano: Schema.String,
durationMs: Schema.Finite,
exit: Schema.optional(Schema.Unknown),
events: Schema.optional(Schema.Unknown),
});
const decodeTraceRecordLine = decodeJsonResult(TraceRecordLineSchema);
interface TraceRecordLike {
readonly name?: unknown;
readonly traceId?: unknown;
readonly spanId?: unknown;
readonly startTimeUnixNano?: unknown;
readonly endTimeUnixNano?: unknown;
readonly durationMs?: unknown;
readonly exit?: unknown;
readonly events?: unknown;
}
interface TraceEventLike {
readonly name?: unknown;
@@ -92,36 +90,37 @@ function toRotatedTracePaths(traceFilePath: string, maxFiles: number): ReadonlyA
return [...backups, traceFilePath];
}
function isRecordObject(value: unknown): value is Readonly<Record<string, unknown>> {
function isRecordObject(value: unknown): value is TraceRecordLike {
return typeof value === "object" && value !== null;
}
function toStringValue(value: unknown): Option.Option<string> {
return typeof value === "string" && value.trim().length > 0 ? Option.some(value) : Option.none();
function toStringValue(value: unknown): string | null {
return typeof value === "string" && value.trim().length > 0 ? value : null;
}
function unixNanoToDateTime(value: unknown): Option.Option<DateTime.Utc> {
const text = Option.getOrUndefined(toStringValue(value));
if (text === undefined) return Option.none();
function toNumberValue(value: unknown): number | null {
return typeof value === "number" && Number.isFinite(value) ? value : null;
}
function unixNanoToDateTime(value: unknown): DateTime.Utc | null {
const text = toStringValue(value);
if (!text) return null;
try {
const millis = Number(BigInt(text) / 1_000_000n);
return DateTime.make(millis);
return Option.getOrNull(DateTime.make(millis));
} catch {
return Option.none();
return null;
}
}
function readExitTag(exit: unknown): Option.Option<string> {
if (!isRecordObject(exit) || !("_tag" in exit)) return Option.none();
function readExitTag(exit: unknown): string | null {
if (!isRecordObject(exit) || !("_tag" in exit)) return null;
return toStringValue(exit._tag);
}
function readExitCause(exit: unknown): string {
if (!isRecordObject(exit) || !("cause" in exit)) return "Failure";
return Option.getOrElse(
Option.map(toStringValue(exit.cause), (cause) => cause.trim()),
() => "Failure",
);
return toStringValue(exit.cause)?.trim() ?? "Failure";
}
function isTraceEvent(value: unknown): value is TraceEventLike {
@@ -212,8 +211,8 @@ export function aggregateTraceDiagnostics(
let failureCount = 0;
let interruptionCount = 0;
let slowSpanCount = 0;
let firstSpanAt = Option.none<DateTime.Utc>();
let lastSpanAt = Option.none<DateTime.Utc>();
let firstSpanAt: DateTime.Utc | null = null;
let lastSpanAt: DateTime.Utc | null = null;
const spansByName = new Map<
string,
@@ -230,40 +229,40 @@ export function aggregateTraceDiagnostics(
for (const line of lines) {
if (line.trim().length === 0) continue;
const decoded = decodeTraceRecordLine(line);
if (Result.isFailure(decoded)) {
let parsed: unknown;
try {
parsed = JSON.parse(line);
} catch {
parseErrorCount += 1;
continue;
}
const parsed = decoded.success;
const requiredFields = Option.all({
name: toStringValue(parsed.name),
traceId: toStringValue(parsed.traceId),
spanId: toStringValue(parsed.spanId),
durationMs: Option.some(parsed.durationMs),
endedAt: unixNanoToDateTime(parsed.endTimeUnixNano),
});
if (!isRecordObject(parsed)) {
parseErrorCount += 1;
continue;
}
const name = toStringValue(parsed.name);
const traceId = toStringValue(parsed.traceId);
const spanId = toStringValue(parsed.spanId);
const durationMs = toNumberValue(parsed.durationMs);
const endedAt = unixNanoToDateTime(parsed.endTimeUnixNano);
const startedAt = unixNanoToDateTime(parsed.startTimeUnixNano);
if (Option.isNone(requiredFields)) {
if (!name || !traceId || !spanId || durationMs === null || !endedAt) {
parseErrorCount += 1;
continue;
}
const { durationMs, endedAt, name, spanId, traceId } = requiredFields.value;
recordCount += 1;
if (
Option.isSome(startedAt) &&
(Option.isNone(firstSpanAt) || DateTime.isLessThan(startedAt.value, firstSpanAt.value))
) {
firstSpanAt = startedAt;
}
if (Option.isNone(lastSpanAt) || DateTime.isGreaterThan(endedAt, lastSpanAt.value)) {
lastSpanAt = Option.some(endedAt);
}
firstSpanAt =
startedAt && (firstSpanAt === null || DateTime.isLessThan(startedAt, firstSpanAt))
? startedAt
: firstSpanAt;
lastSpanAt =
lastSpanAt === null || DateTime.isGreaterThan(endedAt, lastSpanAt) ? endedAt : lastSpanAt;
const exitTag = Option.getOrUndefined(readExitTag(parsed.exit));
const exitTag = readExitTag(parsed.exit);
const isFailure = exitTag === "Failure";
const isInterrupted = exitTag === "Interrupted";
if (isFailure) failureCount += 1;
@@ -308,8 +307,8 @@ export function aggregateTraceDiagnostics(
for (const rawEvent of parsed.events) {
if (!isTraceEvent(rawEvent)) continue;
const attributes = readEventAttributes(rawEvent);
const level = Option.getOrUndefined(toStringValue(attributes["effect.logLevel"]));
if (level === undefined) continue;
const level = toStringValue(attributes["effect.logLevel"]);
if (!level) continue;
logLevelCounts[level] = (logLevelCounts[level] ?? 0) + 1;
const normalizedLevel = level.toLowerCase();
@@ -322,11 +321,8 @@ export function aggregateTraceDiagnostics(
continue;
}
const seenAt = Option.getOrElse(unixNanoToDateTime(rawEvent.timeUnixNano), () => endedAt);
const message = Option.getOrElse(
Option.map(toStringValue(rawEvent.name), (name) => name.trim()),
() => "Log event",
);
const seenAt = unixNanoToDateTime(rawEvent.timeUnixNano) ?? endedAt;
const message = toStringValue(rawEvent.name)?.trim() ?? "Log event";
latestWarningAndErrorLogs.push({
spanName: name,
level,
@@ -358,8 +354,8 @@ export function aggregateTraceDiagnostics(
readAt,
recordCount,
parseErrorCount,
firstSpanAt,
lastSpanAt,
firstSpanAt: Option.fromNullishOr(firstSpanAt),
lastSpanAt: Option.fromNullishOr(lastSpanAt),
failureCount,
interruptionCount,
slowSpanThresholdMs,
@@ -208,28 +208,6 @@ describe("GitHubCli.layer", () => {
}).pipe(Effect.provide(layer)),
);
it.effect("surfaces tagged decode errors for invalid pull request output", () =>
Effect.gen(function* () {
mockRun.mockReturnValueOnce(Effect.succeed(processOutput("not-json")));
const gh = yield* GitHubCli.GitHubCli;
const error = yield* gh
.getPullRequest({
cwd: "/repo",
reference: "#42",
})
.pipe(Effect.flip);
assert.strictEqual(error._tag, "GitHubPullRequestDecodeError");
assert.strictEqual(error.command, "gh");
assert.strictEqual(error.cwd, "/repo");
assert.strictEqual(
error.message,
"GitHub CLI failed in getPullRequest: GitHub CLI returned invalid pull request JSON.",
);
}).pipe(Effect.provide(layer)),
);
it.effect("reads repository clone URLs", () =>
Effect.gen(function* () {
mockRun.mockReturnValueOnce(
+35 -24
View File
@@ -2,6 +2,7 @@ import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as PlatformError from "effect/PlatformError";
import * as Result from "effect/Result";
import * as Schema from "effect/Schema";
import {
@@ -12,8 +13,8 @@ import {
import * as VcsProcess from "../vcs/VcsProcess.ts";
import {
decodeGitHubPullRequestJsonEffect,
decodeGitHubPullRequestListJsonEffect,
decodeGitHubPullRequestJson,
decodeGitHubPullRequestListJson,
} from "./gitHubPullRequests.ts";
const DEFAULT_TIMEOUT_MS = 30_000;
@@ -338,18 +339,22 @@ export const make = Effect.gen(function* () {
Effect.flatMap((raw) =>
raw.length === 0
? Effect.succeed([])
: decodeGitHubPullRequestListJsonEffect(raw).pipe(
Effect.map((decoded) =>
decoded.map(({ updatedAt: _updatedAt, ...summary }) => summary),
),
Effect.mapError(
(cause) =>
new GitHubPullRequestListDecodeError({
command: "gh",
cwd: input.cwd,
cause,
}),
),
: Effect.sync(() => decodeGitHubPullRequestListJson(raw)).pipe(
Effect.flatMap((decoded) => {
if (!Result.isSuccess(decoded)) {
return Effect.fail(
new GitHubPullRequestListDecodeError({
command: "gh",
cwd: input.cwd,
cause: decoded.failure,
}),
);
}
return Effect.succeed(
decoded.success.map(({ updatedAt: _updatedAt, ...summary }) => summary),
);
}),
),
),
),
@@ -366,16 +371,22 @@ export const make = Effect.gen(function* () {
}).pipe(
Effect.map((result) => result.stdout.trim()),
Effect.flatMap((raw) =>
decodeGitHubPullRequestJsonEffect(raw).pipe(
Effect.map(({ updatedAt: _updatedAt, ...summary }) => summary),
Effect.mapError(
(cause) =>
new GitHubPullRequestDecodeError({
command: "gh",
cwd: input.cwd,
cause,
}),
),
Effect.sync(() => decodeGitHubPullRequestJson(raw)).pipe(
Effect.flatMap((decoded) => {
if (!Result.isSuccess(decoded)) {
return Effect.fail(
new GitHubPullRequestDecodeError({
command: "gh",
cwd: input.cwd,
cause: decoded.failure,
}),
);
}
return Effect.succeed(
(({ updatedAt: _updatedAt, ...summary }) => summary)(decoded.success),
);
}),
),
),
),
@@ -1,6 +1,5 @@
import * as Cause from "effect/Cause";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
import * as Option from "effect/Option";
import * as Result from "effect/Result";
@@ -98,13 +97,6 @@ function normalizeGitHubPullRequestRecord(
const decodeGitHubPullRequestList = decodeJsonResult(Schema.Array(Schema.Unknown));
const decodeGitHubPullRequest = decodeJsonResult(GitHubPullRequestSchema);
const decodeGitHubPullRequestEntry = Schema.decodeUnknownExit(GitHubPullRequestSchema);
const decodeGitHubPullRequestListEffect = Schema.decodeEffect(
Schema.fromJsonString(Schema.Array(Schema.Unknown)),
);
const decodeGitHubPullRequestEffect = Schema.decodeEffect(
Schema.fromJsonString(GitHubPullRequestSchema),
);
const decodeGitHubPullRequestEntryEffect = Schema.decodeUnknownEffect(GitHubPullRequestSchema);
export const formatGitHubJsonDecodeError = formatSchemaError;
@@ -138,24 +130,3 @@ export function decodeGitHubPullRequestJson(
}
return Result.fail(result.failure);
}
export function decodeGitHubPullRequestListJsonEffect(
raw: string,
): Effect.Effect<ReadonlyArray<NormalizedGitHubPullRequestRecord>, Schema.SchemaError> {
return Effect.gen(function* () {
const entries = yield* decodeGitHubPullRequestListEffect(raw);
const decoded = yield* Effect.forEach(entries, (entry) =>
decodeGitHubPullRequestEntryEffect(entry).pipe(
Effect.map(normalizeGitHubPullRequestRecord),
Effect.option,
),
);
return decoded.flatMap((entry) => (Option.isSome(entry) ? [entry.value] : []));
});
}
export function decodeGitHubPullRequestJsonEffect(
raw: string,
): Effect.Effect<NormalizedGitHubPullRequestRecord, Schema.SchemaError> {
return decodeGitHubPullRequestEffect(raw).pipe(Effect.map(normalizeGitHubPullRequestRecord));
}
+6 -8
View File
@@ -85,6 +85,11 @@ export function useCloudLinkController() {
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.
@@ -92,11 +97,9 @@ export function useCloudLinkController() {
// 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,
clerkToken: clerkToken ?? null,
});
if (unlinkResult._tag === "Failure") {
if (!isAtomCommandInterrupted(unlinkResult)) {
@@ -106,11 +109,6 @@ export function useCloudLinkController() {
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;
@@ -136,29 +136,6 @@ export function CloudEnvironmentConnectRows({
}
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;
}
@@ -47,9 +47,7 @@ export function ConnectOnboardingDialog() {
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 { isLoaded, isSignedIn, userId } = useAuth();
const [optOutState, setOptOutState] = useLocalStorage(
CONNECT_ONBOARDING_OPT_OUT_STORAGE_KEY,
EMPTY_CONNECT_ONBOARDING_OPT_OUT_STATE,
@@ -91,30 +89,19 @@ function ConfiguredConnectOnboardingDialog() {
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.
// Every sign-in that completes during this session requests the wizard. A
// cold load observes undefined → account and must not re-prompt — only a
// null → account transition is a sign-in.
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) {
if (previousAccount === null && 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(() => {
@@ -123,7 +110,7 @@ function ConfiguredConnectOnboardingDialog() {
setRequestedAccount(null);
return;
}
if (!sessionScopesKnown || !publishStepDecided) return;
if (!sessionScopesKnown) return;
setRequestedAccount(null);
prefilledFromLinkStateRef.current = false;
setExposeEnvironment(true);
@@ -136,7 +123,6 @@ function ConfiguredConnectOnboardingDialog() {
controller.linkState.target,
openForAccount,
optOutAccounts,
publishStepDecided,
requestedAccount,
sessionScopesKnown,
]);
@@ -154,25 +140,19 @@ function ConfiguredConnectOnboardingDialog() {
// 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) {
if (linkStateData.linked) {
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) {
@@ -212,9 +192,7 @@ function ConfiguredConnectOnboardingDialog() {
<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();
if (!open) complete();
}}
>
<DialogPopup className="max-w-xl">
@@ -225,12 +203,7 @@ function ConfiguredConnectOnboardingDialog() {
place.
</DialogDescription>
{steps.length > 1 ? (
<OnboardingStepper
steps={steps}
currentStep={step}
disabled={isApplying}
onStepSelect={setStep}
/>
<OnboardingStepper steps={steps} currentStep={step} onStepSelect={setStep} />
) : null}
</DialogHeader>
<DialogPanel>
@@ -271,9 +244,7 @@ function ConfiguredConnectOnboardingDialog() {
</Button>
</>
) : (
<Button disabled={isApplying} onClick={complete}>
Done
</Button>
<Button onClick={complete}>Done</Button>
)}
</div>
</DialogFooter>
@@ -290,12 +261,10 @@ const STEP_LABELS: Record<OnboardingStep, string> = {
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);
@@ -305,7 +274,6 @@ function OnboardingStepper({
<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
@@ -736,7 +736,7 @@ describe("makeAggregateState", () => {
...state,
threadId: "thread-done" as RelayAgentActivityState["threadId"],
phase: "completed",
updatedAt: "1970-01-01T00:44:00.000Z",
updatedAt: "1970-01-01T00:50:00.000Z",
};
const aggregate = AgentActivityPublisher.makeAggregateState({
activeStates: [active, staleCompleted],
@@ -769,7 +769,7 @@ describe("makeAggregateState", () => {
});
expect(
AgentActivityPublisher.makeAggregateState({
activeStates: [{ ...lingeringCompleted, updatedAt: "1970-01-01T00:44:00.000Z" }],
activeStates: [{ ...lingeringCompleted, updatedAt: "1970-01-01T00:50:00.000Z" }],
terminalState: null,
nowMs: hourMs,
}),
@@ -789,25 +789,16 @@ describe("makeAggregateState", () => {
updatedAt: "1970-01-01T00:59:00.000Z",
};
const aggregate = AgentActivityPublisher.makeAggregateState({
activeStates: [
mkActive("a-1"),
mkActive("a-2"),
mkActive("a-3"),
mkActive("a-4"),
mkActive("a-5"),
justCompleted,
],
activeStates: [mkActive("a-1"), mkActive("a-2"), mkActive("a-3"), justCompleted],
terminalState: null,
nowMs: hourMs,
});
expect(aggregate?.activeCount).toBe(5);
expect(aggregate?.activeCount).toBe(3);
expect(aggregate?.activities).toMatchObject([
{ threadId: "a-1" },
{ threadId: "a-2" },
{ threadId: "a-3" },
{ threadId: "a-4" },
{ threadId: "a-5" },
]);
});
});
@@ -13,7 +13,6 @@ import * as Option from "effect/Option";
import {
isExpiredAgentActivityState,
isTerminalPhase,
MAX_ACTIVITY_ROWS,
sanitizeAgentActivityAggregateState,
} from "./agentActivityPayloads.ts";
@@ -229,7 +228,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 = 15 * 60 * 1_000;
export const TERMINAL_AGENT_ACTIVITY_DISPLAY_TTL_MS = 5 * 60 * 1_000;
function isRecentTerminalState(state: RelayAgentActivityState, nowMs: number): boolean {
if (!isTerminalPhase(state)) {
@@ -274,7 +273,7 @@ export function makeAggregateState(input: {
subtitle: newest.phase === "failed" ? "Agent work failed" : "Agent work completed",
activeCount: 0,
updatedAt: newest.updatedAt,
activities: recentTerminal.slice(0, MAX_ACTIVITY_ROWS).map(aggregateRowForState),
activities: recentTerminal.slice(0, 3).map(aggregateRowForState),
});
}
// Recently finished threads ride along after the active ones (display slots
@@ -283,10 +282,7 @@ 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, MAX_ACTIVITY_ROWS),
...recentTerminalStates,
].slice(0, MAX_ACTIVITY_ROWS);
const displayedStates = [...activeStates.slice(0, 3), ...recentTerminalStates].slice(0, 3);
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, 4, 5].map((index) =>
activities: [0, 1, 2, 3].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(5);
expect(payloadAggregate?.activities).toHaveLength(3);
expect(payloadAggregate?.activities[0]?.projectTitle.length).toBeLessThanOrEqual(120);
expect(payloadAggregate?.activities[0]?.status.length).toBeLessThanOrEqual(40);
expect(payloadAggregate?.activities[0]?.deepLink).toBe("/");
@@ -43,9 +43,7 @@ export function isExpiredAgentActivityState(
const MAX_SUMMARY_TEXT_LENGTH = 120;
const MAX_STATUS_TEXT_LENGTH = 40;
const MAX_DEEP_LINK_LENGTH = 512;
// 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;
const MAX_ACTIVITY_ROWS = 3;
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@11.10.0",
"packageManager": "pnpm@10.24.0",
"msw": {
"workerDirectory": [
"apps/web/public"
+7 -22
View File
@@ -222,27 +222,7 @@ export const make = Effect.fn("RelayEnvironmentDiscovery.make")(function* () {
error: Option.none(),
});
// 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;
const clerkToken = yield* session.clerkToken;
if ((yield* Ref.get(accountGeneration)) !== generation) {
return;
}
@@ -299,10 +279,15 @@ export const make = Effect.fn("RelayEnvironmentDiscovery.make")(function* () {
if ((yield* Ref.get(accountGeneration)) !== generation) {
return;
}
// 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.
const signedOut =
error._tag === "ConnectionBlockedError" && error.reason === "authentication";
yield* SubscriptionRef.update(state, (current) => ({
...current,
refreshing: false,
error: Option.some(error),
error: signedOut ? Option.none() : Option.some(error),
}));
}),
),
@@ -155,46 +155,6 @@ 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,10 +386,12 @@ export function applyVcsActionProgressEvent(
};
case "action_finished":
return {
...EMPTY_VCS_ACTION_STATE,
...current,
isRunning: false,
actionId: event.actionId,
action: event.action,
operation: "run_change_request",
error: null,
};
case "action_failed":
return {
+1 -40
View File
@@ -1,42 +1,3 @@
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
@@ -1106,7 +1067,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..861ffed850e90f27916c427853b503dbe6ee9840 100644
index 3b384e03891e38e936f370372a682d73440e7ec2..1e3a966806c8b8b312f75fb367f758efe49dde9d 100644
--- a/lib/typescript/types.d.ts
+++ b/lib/typescript/types.d.ts
@@ -10,6 +10,7 @@ export type SearchBarCommands = {
+564 -542
View File
File diff suppressed because it is too large. Load diff
+15 -30
View File
@@ -5,31 +5,14 @@ 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.11.1
"@clerk/clerk-js": 6.25.0
"@clerk/electron": 0.0.10
"@clerk/backend": 3.8.4
"@clerk/clerk-js": 6.22.0
"@clerk/electron": 0.0.5
"@clerk/electron-passkeys": 0.0.3
"@clerk/expo": 3.7.1
"@clerk/react": 6.12.0
"@clerk/shared": 4.25.0
"@clerk/expo": 3.6.2
"@clerk/react": 6.11.1
"@clerk/shared": 4.22.0
"@effect/atom-react": 4.0.0-beta.78
"@effect/openapi-generator": 4.0.0-beta.78
"@effect/platform-bun": 4.0.0-beta.78
@@ -51,13 +34,15 @@ catalog:
vite-plus: 0.2.2
yaml: ^2.9.0
minimumReleaseAgeExclude:
- "@clerk/[email protected]"
- "@clerk/[email protected]"
- "@clerk/[email protected]"
- "@clerk/[email protected]"
- "@clerk/[email protected]"
- "@clerk/[email protected]"
ignoredBuiltDependencies:
- msw
onlyBuiltDependencies:
- electron
- esbuild
- msgpackr-extract
- node-pty
- sharp
overrides:
"@clerk/backend": "catalog:"
+14 -68
View File
@@ -11,7 +11,7 @@ import { ChildProcessSpawner } from "effect/unstable/process";
import {
BuildCommandFailedError,
createStageWorkspaceConfig,
createStagePatchedDependencies,
createStagePnpmConfig,
createBuildConfig,
DESKTOP_ASAR_UNPACK,
InvalidMacPasskeyRpDomainError,
@@ -168,7 +168,7 @@ it.layer(NodeServices.layer)("build-desktop-artifact", (it) => {
it("carries only staged dependency patch metadata into staged desktop installs", () => {
assert.deepStrictEqual(
createStagePatchedDependencies(
createStagePnpmConfig(
{
"@expo/[email protected]": "patches/@expo%[email protected]",
"@ff-labs/[email protected]": "patches/@[email protected]",
@@ -183,26 +183,28 @@ it.layer(NodeServices.layer)("build-desktop-artifact", (it) => {
},
),
{
"@ff-labs/[email protected]": "patches/@[email protected]",
"@pierre/[email protected]": "patches/@pierre%[email protected].patch",
"[email protected]": "patches/[email protected].patch",
patchedDependencies: {
"@ff-labs/[email protected]": "patches/@[email protected].patch",
"@pierre/[email protected]": "patches/@pierre%[email protected].patch",
"[email protected]": "patches/[email protected]",
},
},
);
assert.deepStrictEqual(
createStagePatchedDependencies(
assert.equal(
createStagePnpmConfig(
{
"@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({ platform: "mac", arch: "x64" }), {
assert.deepStrictEqual(createStageWorkspaceConfig("mac", "x64"), {
supportedArchitectures: {
os: ["darwin"],
cpu: ["x64"],
@@ -210,21 +212,21 @@ it.layer(NodeServices.layer)("build-desktop-artifact", (it) => {
});
// 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({ platform: "win", arch: "x64" }), {
assert.deepStrictEqual(createStageWorkspaceConfig("win", "x64"), {
supportedArchitectures: {
os: ["win32", "linux"],
cpu: ["x64"],
libc: ["glibc"],
},
});
assert.deepStrictEqual(createStageWorkspaceConfig({ platform: "win", arch: "arm64" }), {
assert.deepStrictEqual(createStageWorkspaceConfig("win", "arm64"), {
supportedArchitectures: {
os: ["win32", "linux"],
cpu: ["arm64"],
libc: ["glibc"],
},
});
assert.deepStrictEqual(createStageWorkspaceConfig({ platform: "mac", arch: "universal" }), {
assert.deepStrictEqual(createStageWorkspaceConfig("mac", "universal"), {
supportedArchitectures: {
os: ["darwin"],
cpu: ["arm64", "x64"],
@@ -232,62 +234,6 @@ 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"],
},
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-*/**/*"]);
});
+33 -50
View File
@@ -40,7 +40,6 @@ 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;
@@ -50,14 +49,7 @@ 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))),
@@ -571,6 +563,10 @@ 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;
@@ -880,14 +876,10 @@ const stageClerkPasskeyNativeBinaries = Effect.fn("stageClerkPasskeyNativeBinari
}
});
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;
export function createStageWorkspaceConfig(
platform: typeof BuildPlatform.Type,
arch: typeof BuildArch.Type,
): typeof StageWorkspaceConfig.Type {
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
@@ -895,37 +887,36 @@ export function createStageWorkspaceConfig(input: {
// 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'").
const supportedArchitectures =
platform === "win"
? {
os: Array.from(new Set([hostOs, "linux"])),
cpu: hostCpu,
libc: ["glibc"],
}
: {
os: [hostOs],
cpu: hostCpu,
};
if (platform === "win") {
return {
supportedArchitectures: {
os: Array.from(new Set([hostOs, "linux"])),
cpu: hostCpu,
libc: ["glibc"],
},
};
}
return {
supportedArchitectures,
...(allowBuilds && Object.keys(allowBuilds).length > 0 ? { allowBuilds } : {}),
...(patchedDependencies && Object.keys(patchedDependencies).length > 0
? { patchedDependencies }
: {}),
...(overrides && Object.keys(overrides).length > 0 ? { overrides } : {}),
supportedArchitectures: {
os: [hostOs],
cpu: hostCpu,
},
};
}
export function createStagePatchedDependencies(
export function createStagePnpmConfig(
patchedDependencies: Record<string, string>,
dependencies: Record<string, unknown>,
): Record<string, string> {
return Object.fromEntries(
): StagePackageJson["pnpm"] | undefined {
const stagePatchedDependencies = 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 {
@@ -1549,7 +1540,6 @@ 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) {
@@ -1719,10 +1709,7 @@ const buildDesktopArtifact = Effect.fn("buildDesktopArtifact")(function* (
)
: {}),
};
const stagePatchedDependencies = createStagePatchedDependencies(
workspacePatchedDependencies,
stageDependencies,
);
const stagePnpmConfig = createStagePnpmConfig(workspacePatchedDependencies, stageDependencies);
const stagePackageJson: StagePackageJson = {
name: "t3code",
version: appVersion,
@@ -1751,24 +1738,20 @@ 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({
platform: options.platform,
arch: options.arch,
allowBuilds: workspaceAllowBuilds,
patchedDependencies: stagePatchedDependencies,
overrides: resolvedOverrides,
});
const stageWorkspaceConfig = createStageWorkspaceConfig(options.platform, options.arch);
const stageWorkspaceConfigString = yield* encodeStageWorkspaceConfig(stageWorkspaceConfig);
yield* fs.writeFileString(
path.join(stageAppDir, "pnpm-workspace.yaml"),
stageWorkspaceConfigString,
);
if (Object.keys(stagePatchedDependencies).length > 0) {
if (Object.keys(workspacePatchedDependencies).length > 0) {
yield* fs.copy(path.join(repoRoot, "patches"), path.join(stageAppDir, "patches"));
}