Compare commits

..
Author SHA1 Message Date
Cursor AgentandJulius Marminge bd8657af44 Avoid provider pill transition bookkeeping renders
Co-authored-by: Julius Marminge <[email protected]>
2026-07-08 16:16:12 +00:00
Cursor AgentandJulius Marminge f34cfbb7c4 Optimize provider update pill renders
Co-authored-by: Julius Marminge <[email protected]>
2026-07-08 16:15:10 +00:00
121 changed files with 1964 additions and 5496 deletions

No files matched your search

@@ -43,15 +43,6 @@ Review changed TypeScript and directly affected call sites for the conventions b
- Keep implementation-specific names when an abstract port module contains one of several possible implementations, for example `makeCloudflaredRelayClient` and `layerCloudflared` in `RelayClient.ts`.
- `infra/relay/src/db.ts` is an intentional exception: an inline `Layer.succeed(RelayDb, db)` is acceptable without generic `make`/`layer` exports.
## Dependency acquisition and runtime boundaries
- Production service construction must acquire Effect service dependencies from the environment with `yield* Foo.Foo`, and its `make`/`layer` types must expose those requirements. Flag factories or constructors that accept `Foo["Service"]` (or a plain object whose methods return `Effect`) when that value is an implementation dependency owned by the service. Passing service instances explicitly is acceptable in tests and integration harnesses; passing pure configuration, immutable domain values, or deliberate callback strategies is not service injection.
- Do not hide dependencies in module globals, closures over singleton services, or `Layer.succeed` implementations that call runtime-backed or imperative APIs. Trace helpers used by a supposedly synchronous layer far enough to verify that asynchronous services are represented in the Effect environment.
- `ManagedRuntime.make`, `runPromise`, and `runPromiseExit` belong at explicit application/framework boundaries such as React, native callback, CLI, or HTTP adapters. Flag their use in domain services, repositories, persistence implementations, and service constructors. A clearly named imperative adapter may bridge an Effect service into a Promise API, but it must not become a dependency of another Effect service.
- Do not create per-feature managed runtimes or Atom runtimes to smuggle the same owned resource into multiple consumers. Compose the resource once in an application-owned layer/runtime and provide its context to integration runtimes.
- When acquisition can fail but a caller must retain fallback behavior, keep the failure typed in Effect rather than bypassing the layer through an imperative runtime. Model unavailability in service operations or with an explicit optional-service layer so downstream recovery remains visible and testable.
- During review, search touched code and affected call sites for service-instance parameters, `Layer.succeed`, `ManagedRuntime.make`, and `.runPromise`/`.runPromiseExit`. Verify that each occurrence is a legitimate test seam, pure value injection, or application boundary—not fake dependency injection or a hidden runtime.
## Errors and predicates
- Define service failures with `Schema.TaggedErrorClass` and structured attributes. Derive `message` from those attributes rather than storing an unstructured message as the only data.
+1 -35
View File
@@ -63,16 +63,6 @@ function resolveAppVariant(value: string | undefined): AppVariant {
const variant = VARIANT_CONFIG[APP_VARIANT];
const dmSansFonts = {
regular: "@expo-google-fonts/dm-sans/400Regular/DMSans_400Regular.ttf",
medium: "@expo-google-fonts/dm-sans/500Medium/DMSans_500Medium.ttf",
bold: "@expo-google-fonts/dm-sans/700Bold/DMSans_700Bold.ttf",
} as const;
// These aliases match the fonts' PostScript names on iOS. Register the same
// names on Android so React Native and the native composer use one set of
// family names without waiting for runtime font loading.
const config: ExpoConfig = {
name: variant.appName,
slug: "t3-code",
@@ -131,32 +121,8 @@ const config: ExpoConfig = {
favicon: "./assets/favicon.png",
},
plugins: [
[
"expo-font",
{
ios: {
fonts: [dmSansFonts.regular, dmSansFonts.medium, dmSansFonts.bold],
},
android: {
fonts: [
{
fontFamily: "DMSans-Regular",
fontDefinitions: [{ path: dmSansFonts.regular, weight: 400 }],
},
{
fontFamily: "DMSans-Medium",
fontDefinitions: [{ path: dmSansFonts.medium, weight: 500 }],
},
{
fontFamily: "DMSans-Bold",
fontDefinitions: [{ path: dmSansFonts.bold, weight: 700 }],
},
],
},
},
],
"expo-font",
"expo-secure-store",
"expo-sqlite",
["@clerk/expo", { theme: "./clerk-theme.json" }],
"expo-web-browser",
[
+4 -8
View File
@@ -8,8 +8,7 @@
"development": {
"corepack": true,
"env": {
"APP_VARIANT": "development",
"NODE_OPTIONS": "--max-old-space-size=4096"
"APP_VARIANT": "development"
},
"channel": "development",
"developmentClient": true,
@@ -18,8 +17,7 @@
"preview": {
"corepack": true,
"env": {
"APP_VARIANT": "preview",
"NODE_OPTIONS": "--max-old-space-size=4096"
"APP_VARIANT": "preview"
},
"channel": "preview",
"environment": "preview",
@@ -29,8 +27,7 @@
"corepack": true,
"env": {
"APP_VARIANT": "preview",
"MOBILE_VERSION_POLICY": "fingerprint",
"NODE_OPTIONS": "--max-old-space-size=4096"
"MOBILE_VERSION_POLICY": "fingerprint"
},
"channel": "preview",
"environment": "preview",
@@ -43,8 +40,7 @@
"production": {
"corepack": true,
"env": {
"APP_VARIANT": "production",
"NODE_OPTIONS": "--max-old-space-size=4096"
"APP_VARIANT": "production"
},
"channel": "production",
"environment": "production",
+6 -9
View File
@@ -51,7 +51,6 @@
/* Inputs */
--color-input: #ffffff;
--color-input-border: rgba(0, 0, 0, 0.1);
--color-sidebar-search: rgba(118, 118, 128, 0.12);
--color-placeholder: #a3a3a3;
/* Icons */
@@ -145,7 +144,6 @@
/* Inputs */
--color-input: #141414;
--color-input-border: rgba(255, 255, 255, 0.08);
--color-sidebar-search: rgba(118, 118, 128, 0.24);
--color-placeholder: #8e8e93;
/* Icons */
@@ -196,10 +194,9 @@
/* ─── Typography ────────────────────────────────────────────────────── */
@theme {
/* Keep these native family names aligned with app.config.ts. */
--font-sans: "DMSans-Regular";
--font-medium: "DMSans-Medium";
--font-bold: "DMSans-Bold";
--font-sans: "DMSans_400Regular";
--font-medium: "DMSans_500Medium";
--font-bold: "DMSans_700Bold";
/* Keep this scale aligned with src/lib/typography.ts for native style props. */
--text-3xs: 11px;
@@ -224,14 +221,14 @@
/* ─── Custom utilities ──────────────────────────────────────────────── */
@utility font-t3-medium {
font-family: var(--font-medium);
font-family: "DMSans_500Medium";
}
@utility font-t3-bold {
font-family: var(--font-bold);
font-family: "DMSans_700Bold";
}
@utility font-t3-extrabold {
font-family: var(--font-bold);
font-family: "DMSans_700Bold";
font-weight: 800;
}
@@ -300,7 +300,7 @@ public final class T3ComposerEditorView: ExpoView, UITextViewDelegate {
skillText: "#a21caf",
fileTint: "#737373"
)
private var fontFamily = "DMSans-Regular"
private var fontFamily = "DMSans_400Regular"
private var fontSize: CGFloat = 14
private var lineHeight: CGFloat = 20
private var contentInsetVertical: CGFloat = 0
@@ -608,7 +608,7 @@ public final class T3ComposerEditorView: ExpoView, UITextViewDelegate {
iconImage: UIImage?,
style: ComposerChipStyle
) -> UIImage {
let font = UIFont(name: "DMSans-Medium", size: max(12, fontSize - 2))
let font = UIFont(name: "DMSans_500Medium", size: max(12, fontSize - 2))
?? UIFont.systemFont(ofSize: max(12, fontSize - 2), weight: .medium)
let fallbackIcon = UIImage(
systemName: iconName,
-3
View File
@@ -6,7 +6,6 @@
"scripts": {
"dev": "expo start --clear",
"dev:client": "APP_VARIANT=development expo start --dev-client --scheme t3code-dev --clear",
"dev:client:preview": "eas env:exec preview 'EXPO_NO_DOTENV=1 APP_VARIANT=preview expo start --dev-client --scheme t3code-preview --clear --lan'",
"start": "expo start",
"start:dev": "APP_VARIANT=development expo start",
"start:preview": "APP_VARIANT=preview expo start",
@@ -80,7 +79,6 @@
"expo-font": "~56.0.7",
"expo-glass-effect": "~56.0.4",
"expo-haptics": "~56.0.3",
"expo-image": "~56.0.11",
"expo-image-picker": "~56.0.18",
"expo-linking": "~56.0.14",
"expo-network": "~56.0.5",
@@ -88,7 +86,6 @@
"expo-paste-input": "^0.1.15",
"expo-secure-store": "~56.0.4",
"expo-splash-screen": "~56.0.10",
"expo-sqlite": "~56.0.5",
"expo-symbols": "~56.0.6",
"expo-updates": "~56.0.19",
"expo-web-browser": "~56.0.5",
+14 -3
View File
@@ -1,6 +1,11 @@
import {
DMSans_400Regular,
DMSans_500Medium,
DMSans_700Bold,
useFonts,
} from "@expo-google-fonts/dm-sans";
import * as Linking from "expo-linking";
import * as SplashScreen from "expo-splash-screen";
import { useEffect } from "react";
import { StatusBar, useColorScheme } from "react-native";
import { GestureHandlerRootView } from "react-native-gesture-handler";
import { KeyboardProvider } from "react-native-keyboard-controller";
@@ -8,6 +13,7 @@ import { SafeAreaProvider } from "react-native-safe-area-context";
import { createStaticNavigation, DarkTheme, DefaultTheme } from "@react-navigation/native";
import { RegistryContext } from "@effect/atom-react";
import { useEffect } from "react";
import { CloudAuthProvider } from "./features/cloud/CloudAuthProvider";
import { AppearancePreferencesProvider } from "./features/settings/appearance/AppearancePreferencesProvider";
import { RootStack } from "./Stack";
@@ -23,12 +29,17 @@ const appLinking = {
const Navigation = createStaticNavigation(RootStack);
export default function App() {
const [fontsLoaded] = useFonts({
DMSans_400Regular,
DMSans_500Medium,
DMSans_700Bold,
});
const colorScheme = useColorScheme();
const statusBarBg = useThemeColor("--color-status-bar");
useEffect(() => {
SplashScreen.hide();
}, []);
if (fontsLoaded) SplashScreen.hide();
}, [fontsLoaded]);
return (
<RegistryContext.Provider value={appAtomRegistry}>
-8
View File
@@ -41,7 +41,6 @@ import { NewTaskDraftRouteScreen } from "./features/threads/NewTaskDraftRouteScr
import { NewTaskFlowProvider } from "./features/threads/new-task-flow-provider";
import { NewTaskRouteScreen } from "./features/threads/NewTaskRouteScreen";
import { SettingsAppearanceRouteScreen } from "./features/settings/SettingsAppearanceRouteScreen";
import { SettingsClientStorageRouteScreen } from "./features/settings/SettingsClientStorageRouteScreen";
import { SettingsAuthRouteScreen } from "./features/settings/SettingsAuthRouteScreen";
import { SettingsEnvironmentsRouteScreen } from "./features/settings/SettingsEnvironmentsRouteScreen";
import { SettingsRouteScreen } from "./features/settings/SettingsRouteScreen";
@@ -148,13 +147,6 @@ const SettingsSheetStack = createNativeStackNavigator({
title: "Appearance",
},
}),
SettingsClientStorage: createNativeStackScreen({
screen: SettingsClientStorageRouteScreen,
linking: "client-storage",
options: {
title: "Client Storage",
},
}),
SettingsAuth: createNativeStackScreen({
screen: SettingsAuthRouteScreen,
linking: "auth",
+11 -3
View File
@@ -4,6 +4,7 @@ import {
type TextInputProps as RNTextInputProps,
type TextProps as RNTextProps,
} from "react-native";
import { useThemeColor } from "../lib/useThemeColor";
import { cn } from "../lib/cn";
@@ -17,7 +18,7 @@ export function AppText({ className, ...props }: AppTextProps) {
return <RNText className={cn("font-sans text-foreground", className)} {...props} />;
}
export type AppTextInputProps = Omit<RNTextInputProps, "placeholderTextColor"> & {
export type AppTextInputProps = RNTextInputProps & {
readonly className?: string;
readonly ref?: React.Ref<RNTextInput>;
};
@@ -26,7 +27,14 @@ export type AppTextInputProps = Omit<RNTextInputProps, "placeholderTextColor"> &
* Thin wrapper around RN TextInput with default input styling.
* Uses Uniwind className — no manual style parsing.
*/
export function AppTextInput({ className, ref, ...props }: AppTextInputProps) {
export function AppTextInput({
className,
placeholderTextColor,
ref,
...props
}: AppTextInputProps) {
const placeholderColor = useThemeColor("--color-placeholder");
return (
<RNTextInput
ref={ref}
@@ -34,7 +42,7 @@ export function AppTextInput({ className, ref, ...props }: AppTextInputProps) {
"min-h-13.5 rounded-2xl border border-input-border bg-input px-3.5 py-3 font-sans text-base text-foreground",
className,
)}
placeholderTextColorClassName="accent-placeholder"
placeholderTextColor={placeholderTextColor ?? placeholderColor}
{...props}
/>
);
+7 -2
View File
@@ -22,9 +22,14 @@ export function BrandMark(props: { readonly compact?: boolean; readonly stageLab
/>
<View className="gap-1">
<View className="flex-row items-center gap-2">
<Text className="text-lg font-t3-bold tracking-[-0.4px] text-foreground">T3 Code</Text>
<Text className="text-lg font-t3-bold text-foreground" style={{ letterSpacing: -0.4 }}>
T3 Code
</Text>
<View className="rounded-full bg-subtle px-2 py-1">
<Text className="text-3xs font-t3-bold tracking-[1.1px] uppercase text-foreground-muted">
<Text
className="text-3xs font-t3-bold uppercase text-foreground-muted"
style={{ letterSpacing: 1.1 }}
>
{stageLabel}
</Text>
</View>
@@ -39,14 +39,14 @@ export function ComposerAttachmentStrip(props: ComposerAttachmentStripProps) {
horizontal
showsHorizontalScrollIndicator={false}
keyboardShouldPersistTaps="always"
className="grow-0"
style={{ flexGrow: 0 }}
>
<View className="flex-row gap-2.5">
<View style={{ flexDirection: "row", gap: 10 }}>
{props.attachments.map((image) => (
<View
key={image.id}
className="relative"
style={{
position: "relative",
paddingTop: removeButtonGutter,
paddingRight: removeButtonGutter,
}}
@@ -66,10 +66,16 @@ export function ComposerAttachmentStrip(props: ComposerAttachmentStripProps) {
/>
</Pressable>
<Pressable
className="absolute h-[22px] w-[22px] items-center justify-center rounded-[11px] bg-black/55"
style={{
position: "absolute",
top: removeButtonPlacement === "gutter" ? 0 : 4,
right: removeButtonPlacement === "gutter" ? 0 : 4,
width: 22,
height: 22,
borderRadius: 11,
backgroundColor: "rgba(0,0,0,0.55)",
alignItems: "center",
justifyContent: "center",
}}
hitSlop={6}
onPress={() => props.onRemove(image.id)}
@@ -31,9 +31,11 @@ export function ComposerToolbarRow(props: {
}) {
return (
<View
className="flex-row items-center gap-1.5"
style={[
{
alignItems: "center",
flexDirection: "row",
gap: 6,
paddingBottom: props.paddingBottom ?? 8,
paddingHorizontal: props.paddingHorizontal ?? 6,
paddingTop: props.paddingTop ?? 8,
@@ -87,7 +89,7 @@ export function ComposerToolbarScroller(props: {
}, []);
return (
<View className="relative min-w-0 flex-1">
<View className="min-w-0 flex-1" style={{ position: "relative" }}>
<ScrollView
horizontal
keyboardShouldPersistTaps="always"
@@ -39,12 +39,22 @@ export function GlassSafeAreaView({
style={{ borderRadius: 0, backgroundColor: "transparent" }}
>
<View
className="flex-row items-center gap-2.5 px-5 pb-4"
style={{ paddingTop: headerPaddingTop }}
style={{
flexDirection: "row",
alignItems: "center",
paddingHorizontal: 20,
paddingTop: headerPaddingTop,
paddingBottom: 16,
gap: 10,
}}
>
<View className="items-start justify-center">{leftSlot}</View>
<View className="flex-1 items-center justify-center overflow-hidden">{centerSlot}</View>
<View className="items-end justify-center">{rightSlot}</View>
<View style={{ alignItems: "flex-start", justifyContent: "center" }}>{leftSlot}</View>
<View
style={{ flex: 1, alignItems: "center", justifyContent: "center", overflow: "hidden" }}
>
{centerSlot}
</View>
<View style={{ alignItems: "flex-end", justifyContent: "center" }}>{rightSlot}</View>
</View>
</GlassSurface>
</View>
+1 -1
View File
@@ -10,7 +10,7 @@ import {
} from "react-native";
import { useThemeColor } from "../lib/useThemeColor";
export interface GlassSurfaceProps extends Omit<ViewProps, "className"> {
export interface GlassSurfaceProps extends ViewProps {
readonly children: ReactNode;
readonly glassEffectStyle?: "clear" | "regular" | "none";
readonly tintColor?: ColorValue;
@@ -1,7 +1,6 @@
import { SymbolView } from "expo-symbols";
import { Image } from "expo-image";
import { useState } from "react";
import { View } from "react-native";
import { Image, View } from "react-native";
import type { EnvironmentId } from "@t3tools/contracts";
import { useThemeColor } from "../lib/useThemeColor";
import { useAssetUrl } from "../state/assets";
@@ -79,7 +78,7 @@ function ProjectFaviconImage(props: {
borderRadius: props.size * 0.16,
...(showImage ? {} : { position: "absolute" as const, opacity: 0 }),
}}
contentFit="contain"
resizeMode="contain"
onLoad={() => {
if (props.faviconUrl) loadedFaviconUrls.add(props.faviconUrl);
setStatus("loaded");
+26 -25
View File
@@ -10,7 +10,6 @@ import * as Ref from "effect/Ref";
import * as Schema from "effect/Schema";
import * as Semaphore from "effect/Semaphore";
import * as MobileSecureStorage from "../persistence/mobile-secure-storage";
import { migrateLegacyConnectionCatalog } from "./migration";
export const CONNECTION_CATALOG_KEY = "t3code.connection-catalog.v1";
@@ -23,22 +22,23 @@ function catalogError(operation: string, cause: unknown) {
});
}
const ConnectionCatalogDocumentJson = Schema.fromJsonString(ConnectionCatalogDocument);
const decodeConnectionCatalogDocument = Schema.decodeEffect(ConnectionCatalogDocumentJson);
const encodeConnectionCatalogDocument = Schema.encodeEffect(ConnectionCatalogDocumentJson);
const decodeCatalog = Effect.fn("mobile.connectionStorage.decodeCatalog")(function* (raw: string) {
return yield* decodeConnectionCatalogDocument(raw).pipe(
Effect.mapError((cause) => catalogError("decode", cause)),
);
const parsed = yield* Effect.try({
try: () => JSON.parse(raw) as unknown,
catch: (cause) => catalogError("decode", cause),
});
return yield* Effect.fromResult(
Schema.decodeUnknownResult(ConnectionCatalogDocument)(parsed),
).pipe(Effect.mapError((cause) => catalogError("decode", cause)));
});
const encodeCatalog = Effect.fn("mobile.connectionStorage.encodeCatalog")(function* (
catalog: ConnectionCatalogDocumentType,
) {
return yield* encodeConnectionCatalogDocument(catalog).pipe(
Effect.mapError((cause) => catalogError("encode", cause)),
);
const encoded = yield* Effect.fromResult(
Schema.encodeUnknownResult(ConnectionCatalogDocument)(catalog),
).pipe(Effect.mapError((cause) => catalogError("encode", cause)));
return JSON.stringify(encoded);
});
interface CatalogStore {
@@ -48,19 +48,20 @@ interface CatalogStore {
) => Effect.Effect<void, ConnectionTransientError>;
}
export const make = Effect.fn("mobile.connectionStorage.makeCatalogStore")(function* () {
const storage = yield* MobileSecureStorage.MobileSecureStorage;
const getItem = (key: string) =>
storage.getItem(key).pipe(Effect.mapError((cause) => catalogError("load", cause)));
const setItem = (key: string, value: string) =>
storage.setItem(key, value).pipe(Effect.mapError((cause) => catalogError("save", cause)));
const deleteItem = (key: string) =>
storage.removeItem(key).pipe(Effect.mapError((cause) => catalogError("delete", cause)));
export interface SecureCatalogStorage {
readonly getItem: (key: string) => Effect.Effect<string | null, ConnectionTransientError>;
readonly setItem: (key: string, value: string) => Effect.Effect<void, ConnectionTransientError>;
readonly deleteItem: (key: string) => Effect.Effect<void, ConnectionTransientError>;
}
export const makeCatalogStore = Effect.fn("mobile.connectionStorage.makeCatalogStore")(function* (
storage: SecureCatalogStorage,
) {
const state = yield* Ref.make<Option.Option<ConnectionCatalogDocumentType>>(Option.none());
const lock = yield* Semaphore.make(1);
const loadLegacyCatalog = Effect.fn("mobile.connectionStorage.loadLegacyCatalog")(function* () {
const legacyRaw = yield* getItem(LEGACY_CONNECTIONS_KEY);
const legacyRaw = yield* storage.getItem(LEGACY_CONNECTIONS_KEY);
const catalog =
legacyRaw === null || legacyRaw.trim() === ""
? EMPTY_CONNECTION_CATALOG_DOCUMENT
@@ -74,8 +75,8 @@ export const make = Effect.fn("mobile.connectionStorage.makeCatalogStore")(funct
);
if (legacyRaw !== null && legacyRaw.trim() !== "") {
const encoded = yield* encodeCatalog(catalog);
yield* setItem(CONNECTION_CATALOG_KEY, encoded);
yield* deleteItem(LEGACY_CONNECTIONS_KEY);
yield* storage.setItem(CONNECTION_CATALOG_KEY, encoded);
yield* storage.deleteItem(LEGACY_CONNECTIONS_KEY);
}
return catalog;
});
@@ -85,13 +86,13 @@ export const make = Effect.fn("mobile.connectionStorage.makeCatalogStore")(funct
if (Option.isSome(cached)) {
return cached.value;
}
const raw = yield* getItem(CONNECTION_CATALOG_KEY);
const raw = yield* storage.getItem(CONNECTION_CATALOG_KEY);
let catalog: ConnectionCatalogDocumentType;
if (raw !== null && raw.trim() !== "") {
catalog = yield* decodeCatalog(raw).pipe(
Effect.catch((error) =>
Effect.logWarning("Discarding corrupt mobile connection catalog", error).pipe(
Effect.andThen(deleteItem(CONNECTION_CATALOG_KEY)),
Effect.andThen(storage.deleteItem(CONNECTION_CATALOG_KEY)),
Effect.andThen(loadLegacyCatalog()),
),
),
@@ -110,7 +111,7 @@ export const make = Effect.fn("mobile.connectionStorage.makeCatalogStore")(funct
Effect.gen(function* () {
const next = transform(yield* loadUnlocked());
const encoded = yield* encodeCatalog(next);
yield* setItem(CONNECTION_CATALOG_KEY, encoded);
yield* storage.setItem(CONNECTION_CATALOG_KEY, encoded);
yield* Ref.set(state, Option.some(next));
}),
);
@@ -1,97 +0,0 @@
import { EnvironmentId, type VcsListRefsResult } from "@t3tools/contracts";
import { describe, expect, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
import { type ClientCacheKind, MobileDatabase } from "../persistence/mobile-database";
import { make } from "./environment-cache-store";
const ENVIRONMENT_ID = EnvironmentId.make("environment-1");
const REFS: VcsListRefsResult = {
refs: [
{
name: "main",
current: true,
isDefault: true,
worktreePath: "/repo",
},
],
isRepo: true,
hasPrimaryRemote: true,
nextCursor: null,
totalCount: 1,
};
function cacheId(environmentId: EnvironmentId, kind: ClientCacheKind, cacheKey: string) {
return `${environmentId}:${kind}:${cacheKey}`;
}
function makeDatabase() {
const values = new Map<string, string>();
const removed: Array<string> = [];
const database = MobileDatabase.of({
loadCache: (environmentId, kind, cacheKey) =>
Effect.succeed(Option.fromUndefinedOr(values.get(cacheId(environmentId, kind, cacheKey)))),
saveCache: (environmentId, kind, cacheKey, _schemaVersion, payload) =>
Effect.sync(() => {
values.set(cacheId(environmentId, kind, cacheKey), payload);
}),
removeCache: (environmentId, kind, cacheKey) =>
Effect.sync(() => {
const id = cacheId(environmentId, kind, cacheKey);
removed.push(id);
values.delete(id);
}),
clearEnvironmentCache: (environmentId) =>
Effect.sync(() => {
for (const key of values.keys()) {
if (key.startsWith(`${environmentId}:`)) values.delete(key);
}
}),
clearAllCaches: Effect.sync(() => values.clear()),
inspectCaches: Effect.succeed([]),
loadPreferencesJson: Effect.succeed(Option.none()),
savePreferencesJson: () => Effect.void,
});
return { database, removed, values };
}
describe("mobile SQLite environment cache store", () => {
it.effect("round-trips schema-validated VCS refs", () =>
Effect.gen(function* () {
const memory = makeDatabase();
const store = yield* make().pipe(Effect.provideService(MobileDatabase, memory.database));
yield* store.saveVcsRefs(ENVIRONMENT_ID, "/repo", REFS);
expect(yield* store.loadVcsRefs(ENVIRONMENT_ID, "/repo")).toEqual(Option.some(REFS));
}),
);
it.effect("deletes a corrupt cache record and treats it as a miss", () =>
Effect.gen(function* () {
const memory = makeDatabase();
const store = yield* make().pipe(Effect.provideService(MobileDatabase, memory.database));
const id = cacheId(ENVIRONMENT_ID, "vcs-refs", "/repo");
memory.values.set(id, "{not-json");
expect(yield* store.loadVcsRefs(ENVIRONMENT_ID, "/repo")).toEqual(Option.none());
expect(memory.removed).toEqual([id]);
}),
);
it.effect("clears one environment without touching another", () =>
Effect.gen(function* () {
const memory = makeDatabase();
const store = yield* make().pipe(Effect.provideService(MobileDatabase, memory.database));
const otherEnvironmentId = EnvironmentId.make("environment-2");
yield* store.saveVcsRefs(ENVIRONMENT_ID, "/repo", REFS);
yield* store.saveVcsRefs(otherEnvironmentId, "/repo", REFS);
yield* store.clear(ENVIRONMENT_ID);
expect(yield* store.loadVcsRefs(ENVIRONMENT_ID, "/repo")).toEqual(Option.none());
expect(yield* store.loadVcsRefs(otherEnvironmentId, "/repo")).toEqual(Option.some(REFS));
}),
);
});
@@ -1,234 +0,0 @@
import {
ConnectionPersistenceError,
EnvironmentCacheStore,
} from "@t3tools/client-runtime/platform";
import {
type EnvironmentId,
OrchestrationShellSnapshot,
OrchestrationThreadDetailSnapshot,
ServerConfig,
VcsListRefsResult,
} from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
import * as MobileDatabase from "../persistence/mobile-database";
const SHELL_SNAPSHOT_CACHE_SCHEMA_VERSION = 1;
const THREAD_SNAPSHOT_CACHE_SCHEMA_VERSION = 2;
const SERVER_CONFIG_CACHE_SCHEMA_VERSION = 1;
const VCS_REFS_CACHE_SCHEMA_VERSION = 1;
const StoredShellSnapshot = Schema.Struct({
schemaVersion: Schema.Literal(SHELL_SNAPSHOT_CACHE_SCHEMA_VERSION),
environmentId: Schema.String,
snapshot: OrchestrationShellSnapshot,
});
const StoredThreadSnapshot = Schema.Struct({
schemaVersion: Schema.Literal(THREAD_SNAPSHOT_CACHE_SCHEMA_VERSION),
environmentId: Schema.String,
threadId: Schema.String,
snapshot: OrchestrationThreadDetailSnapshot,
});
const StoredServerConfig = Schema.Struct({
schemaVersion: Schema.Literal(SERVER_CONFIG_CACHE_SCHEMA_VERSION),
environmentId: Schema.String,
config: ServerConfig,
});
const StoredVcsRefs = Schema.Struct({
schemaVersion: Schema.Literal(VCS_REFS_CACHE_SCHEMA_VERSION),
environmentId: Schema.String,
cwd: Schema.String,
refs: VcsListRefsResult,
});
const decodeStoredShellSnapshot = Schema.decodeUnknownEffect(
Schema.fromJsonString(StoredShellSnapshot),
);
const encodeStoredShellSnapshot = Schema.encodeEffect(Schema.fromJsonString(StoredShellSnapshot));
const decodeStoredThreadSnapshot = Schema.decodeUnknownEffect(
Schema.fromJsonString(StoredThreadSnapshot),
);
const encodeStoredThreadSnapshot = Schema.encodeEffect(Schema.fromJsonString(StoredThreadSnapshot));
const decodeStoredServerConfig = Schema.decodeUnknownEffect(
Schema.fromJsonString(StoredServerConfig),
);
const encodeStoredServerConfig = Schema.encodeEffect(Schema.fromJsonString(StoredServerConfig));
const decodeStoredVcsRefs = Schema.decodeUnknownEffect(Schema.fromJsonString(StoredVcsRefs));
const encodeStoredVcsRefs = Schema.encodeEffect(Schema.fromJsonString(StoredVcsRefs));
type CacheOperation = ConnectionPersistenceError["operation"];
function persistenceError(operation: CacheOperation, cause: unknown) {
return new ConnectionPersistenceError({
operation,
message: `Could not ${operation.replaceAll("-", " ")}: ${String(cause)}`,
});
}
function mapDatabaseError(operation: CacheOperation) {
return (error: MobileDatabase.MobileDatabaseError) => persistenceError(operation, error);
}
function loadDecodedCache<A, B>(input: {
readonly database: MobileDatabase.MobileDatabase["Service"];
readonly environmentId: EnvironmentId;
readonly kind: MobileDatabase.ClientCacheKind;
readonly cacheKey: string;
readonly operation: CacheOperation;
readonly decode: (raw: string) => Effect.Effect<A, unknown>;
readonly select: (value: A) => Option.Option<B>;
}): Effect.Effect<Option.Option<B>, ConnectionPersistenceError> {
return input.database.loadCache(input.environmentId, input.kind, input.cacheKey).pipe(
Effect.mapError(mapDatabaseError(input.operation)),
Effect.flatMap(
Option.match({
onNone: () => Effect.succeed(Option.none<B>()),
onSome: (raw) =>
input.decode(raw).pipe(
Effect.map(input.select),
Effect.catch((cause) =>
Effect.logWarning("Discarding corrupt mobile client cache record.", {
environmentId: input.environmentId,
kind: input.kind,
cacheKey: input.cacheKey,
cause: String(cause),
}).pipe(
Effect.andThen(
input.database
.removeCache(input.environmentId, input.kind, input.cacheKey)
.pipe(Effect.catch(() => Effect.void)),
),
Effect.as(Option.none<B>()),
),
),
),
}),
),
);
}
export const make = Effect.fn("MobileEnvironmentCacheStore.make")(function* () {
const database = yield* MobileDatabase.MobileDatabase;
return EnvironmentCacheStore.of({
loadShell: Effect.fn("MobileEnvironmentCache.loadShell")((environmentId) =>
loadDecodedCache({
database,
environmentId,
kind: "shell",
cacheKey: "snapshot",
operation: "load-shell",
decode: decodeStoredShellSnapshot,
select: (stored) =>
stored.environmentId === environmentId ? Option.some(stored.snapshot) : Option.none(),
}),
),
saveShell: Effect.fn("MobileEnvironmentCache.saveShell")(function* (environmentId, snapshot) {
const payload = yield* encodeStoredShellSnapshot({
schemaVersion: SHELL_SNAPSHOT_CACHE_SCHEMA_VERSION,
environmentId,
snapshot,
}).pipe(Effect.mapError((cause) => persistenceError("save-shell", cause)));
yield* database
.saveCache(environmentId, "shell", "snapshot", SHELL_SNAPSHOT_CACHE_SCHEMA_VERSION, payload)
.pipe(Effect.mapError(mapDatabaseError("save-shell")));
}),
loadThread: Effect.fn("MobileEnvironmentCache.loadThread")((environmentId, threadId) =>
loadDecodedCache({
database,
environmentId,
kind: "thread",
cacheKey: threadId,
operation: "load-thread",
decode: decodeStoredThreadSnapshot,
select: (stored) =>
stored.environmentId === environmentId && stored.threadId === threadId
? Option.some(stored.snapshot)
: Option.none(),
}),
),
saveThread: Effect.fn("MobileEnvironmentCache.saveThread")(function* (environmentId, snapshot) {
const threadId = snapshot.thread.id;
const payload = yield* encodeStoredThreadSnapshot({
schemaVersion: THREAD_SNAPSHOT_CACHE_SCHEMA_VERSION,
environmentId,
threadId,
snapshot,
}).pipe(Effect.mapError((cause) => persistenceError("save-thread", cause)));
yield* database
.saveCache(environmentId, "thread", threadId, THREAD_SNAPSHOT_CACHE_SCHEMA_VERSION, payload)
.pipe(Effect.mapError(mapDatabaseError("save-thread")));
}),
removeThread: Effect.fn("MobileEnvironmentCache.removeThread")((environmentId, threadId) =>
database
.removeCache(environmentId, "thread", threadId)
.pipe(Effect.mapError(mapDatabaseError("remove-thread"))),
),
loadServerConfig: Effect.fn("MobileEnvironmentCache.loadServerConfig")((environmentId) =>
loadDecodedCache({
database,
environmentId,
kind: "server-config",
cacheKey: "config",
operation: "load-server-config",
decode: decodeStoredServerConfig,
select: (stored) =>
stored.environmentId === environmentId ? Option.some(stored.config) : Option.none(),
}),
),
saveServerConfig: Effect.fn("MobileEnvironmentCache.saveServerConfig")(
function* (environmentId, config) {
const payload = yield* encodeStoredServerConfig({
schemaVersion: SERVER_CONFIG_CACHE_SCHEMA_VERSION,
environmentId,
config,
}).pipe(Effect.mapError((cause) => persistenceError("save-server-config", cause)));
yield* database
.saveCache(
environmentId,
"server-config",
"config",
SERVER_CONFIG_CACHE_SCHEMA_VERSION,
payload,
)
.pipe(Effect.mapError(mapDatabaseError("save-server-config")));
},
),
loadVcsRefs: Effect.fn("MobileEnvironmentCache.loadVcsRefs")((environmentId, cwd) =>
loadDecodedCache({
database,
environmentId,
kind: "vcs-refs",
cacheKey: cwd,
operation: "load-vcs-refs",
decode: decodeStoredVcsRefs,
select: (stored) =>
stored.environmentId === environmentId && stored.cwd === cwd
? Option.some(stored.refs)
: Option.none(),
}),
),
saveVcsRefs: Effect.fn("MobileEnvironmentCache.saveVcsRefs")(
function* (environmentId, cwd, refs) {
const payload = yield* encodeStoredVcsRefs({
schemaVersion: VCS_REFS_CACHE_SCHEMA_VERSION,
environmentId,
cwd,
refs,
}).pipe(Effect.mapError((cause) => persistenceError("save-vcs-refs", cause)));
yield* database
.saveCache(environmentId, "vcs-refs", cwd, VCS_REFS_CACHE_SCHEMA_VERSION, payload)
.pipe(Effect.mapError(mapDatabaseError("save-vcs-refs")));
},
),
clear: Effect.fn("MobileEnvironmentCache.clear")((environmentId) =>
database
.clearEnvironmentCache(environmentId)
.pipe(Effect.mapError(mapDatabaseError("clear-environment"))),
),
});
});
export const layer = Layer.effect(EnvironmentCacheStore, make());
+80 -95
View File
@@ -25,8 +25,7 @@ import * as Network from "expo-network";
import { AppState } from "react-native";
import { authClientMetadata } from "../lib/authClientMetadata";
import * as Runtime from "../lib/runtime";
import * as MobileStorage from "../persistence/mobile-storage";
import { loadOrCreateAgentAwarenessDeviceId } from "../lib/storage";
import { appAtomRegistry } from "../state/atom-registry";
import { clearThreadOutboxEnvironment } from "../state/thread-outbox";
import { clearComposerDraftsEnvironment } from "../state/use-composer-drafts";
@@ -84,87 +83,82 @@ const wakeupsLayer = Wakeups.layer({
),
});
const capabilitiesLayer = Layer.effectContext(
Effect.gen(function* () {
const storage = yield* MobileStorage.MobileStorage;
return Context.make(
CloudSession,
CloudSession.of({
clerkToken: Effect.gen(function* () {
const session = appAtomRegistry.get(managedRelaySessionAtom);
if (session === null) {
return yield* new ConnectionBlockedError({
reason: "authentication",
detail: "Sign in to T3 Connect to connect this environment.",
});
}
const token = yield* session.readClerkToken().pipe(
Effect.mapError(
(error) =>
new ConnectionTransientError({
reason: "network",
detail: error.message,
}),
),
);
if (token === null) {
return yield* new ConnectionBlockedError({
reason: "authentication",
detail: "The T3 Connect session is unavailable.",
});
}
return token;
}),
}),
).pipe(
Context.add(
PrimaryEnvironmentAuth,
PrimaryEnvironmentAuth.of({ bearerToken: Effect.succeed(Option.none()) }),
),
Context.add(
RelayDeviceIdentity,
RelayDeviceIdentity.of({
deviceId: storage.loadOrCreateAgentAwarenessDeviceId.pipe(
Effect.mapError(
(cause) =>
new ConnectionTransientError({
reason: "remote-unavailable",
detail: `Could not load the mobile device identity: ${String(cause)}`,
}),
),
Effect.map(Option.some),
const capabilitiesLayer = Layer.succeedContext(
Context.make(
CloudSession,
CloudSession.of({
clerkToken: Effect.gen(function* () {
const session = appAtomRegistry.get(managedRelaySessionAtom);
if (session === null) {
return yield* new ConnectionBlockedError({
reason: "authentication",
detail: "Sign in to T3 Connect to connect this environment.",
});
}
const token = yield* session.readClerkToken().pipe(
Effect.mapError(
(error) =>
new ConnectionTransientError({
reason: "network",
detail: error.message,
}),
),
}),
),
Context.add(
ClientPresentation,
ClientPresentation.of({
metadata: authClientMetadata(),
scopes: AuthStandardClientScopes,
}),
),
Context.add(
SshEnvironmentGateway,
SshEnvironmentGateway.of({
provision: () =>
Effect.fail(
new ConnectionBlockedError({
reason: "unsupported",
detail: "SSH environments are only available in the desktop app.",
}),
),
prepare: () =>
Effect.fail(
new ConnectionBlockedError({
reason: "unsupported",
detail: "SSH environments are only available in the desktop app.",
}),
),
disconnect: () => Effect.void,
}),
),
);
}),
);
if (token === null) {
return yield* new ConnectionBlockedError({
reason: "authentication",
detail: "The T3 Connect session is unavailable.",
});
}
return token;
}),
}),
).pipe(
Context.add(
PrimaryEnvironmentAuth,
PrimaryEnvironmentAuth.of({ bearerToken: Effect.succeed(Option.none()) }),
),
Context.add(
RelayDeviceIdentity,
RelayDeviceIdentity.of({
deviceId: Effect.tryPromise({
try: () => loadOrCreateAgentAwarenessDeviceId(),
catch: (cause) =>
new ConnectionTransientError({
reason: "remote-unavailable",
detail: `Could not load the mobile device identity: ${String(cause)}`,
}),
}).pipe(Effect.map(Option.some)),
}),
),
Context.add(
ClientPresentation,
ClientPresentation.of({
metadata: authClientMetadata(),
scopes: AuthStandardClientScopes,
}),
),
Context.add(
SshEnvironmentGateway,
SshEnvironmentGateway.of({
provision: () =>
Effect.fail(
new ConnectionBlockedError({
reason: "unsupported",
detail: "SSH environments are only available in the desktop app.",
}),
),
prepare: () =>
Effect.fail(
new ConnectionBlockedError({
reason: "unsupported",
detail: "SSH environments are only available in the desktop app.",
}),
),
disconnect: () => Effect.void,
}),
),
),
);
const platformConnectionSourceLayer = Layer.succeed(
@@ -174,13 +168,6 @@ const platformConnectionSourceLayer = Layer.succeed(
}),
);
const providedConnectionStorageLayer = connectionStorageLayer.pipe(
Layer.provide(Runtime.runtimeContextLayer),
);
const providedCapabilitiesLayer = capabilitiesLayer.pipe(
Layer.provide(Runtime.runtimeContextLayer),
);
const environmentOwnedDataCleanupLayer = Layer.succeed(
EnvironmentOwnedDataCleanup,
EnvironmentOwnedDataCleanup.of({
@@ -203,11 +190,10 @@ const environmentOwnedDataCleanupLayer = Layer.succeed(
);
type ConnectionPlatformLayerSource =
| typeof providedConnectionStorageLayer
| typeof Runtime.runtimeContextLayer
| typeof connectionStorageLayer
| typeof connectivityLayer
| typeof wakeupsLayer
| typeof providedCapabilitiesLayer
| typeof capabilitiesLayer
| typeof platformConnectionSourceLayer
| typeof environmentOwnedDataCleanupLayer;
@@ -216,11 +202,10 @@ export const connectionPlatformLayer: Layer.Layer<
Layer.Error<ConnectionPlatformLayerSource>,
Layer.Services<ConnectionPlatformLayerSource>
> = Layer.mergeAll(
providedConnectionStorageLayer,
Runtime.runtimeContextLayer,
connectionStorageLayer,
connectivityLayer,
wakeupsLayer,
providedCapabilitiesLayer,
capabilitiesLayer,
platformConnectionSourceLayer,
environmentOwnedDataCleanupLayer,
);
+12 -25
View File
@@ -1,35 +1,28 @@
import { describe, expect, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import { vi } from "vite-plus/test";
vi.mock("react-native", () => ({
Platform: { OS: "ios" },
}));
vi.mock("expo-secure-store", () => ({
deleteItemAsync: vi.fn(),
getItemAsync: vi.fn(),
setItemAsync: vi.fn(),
}));
import { CONNECTION_CATALOG_KEY, LEGACY_CONNECTIONS_KEY, make } from "./catalog-store";
import { MobileSecureStorage } from "../persistence/mobile-secure-storage";
import {
CONNECTION_CATALOG_KEY,
LEGACY_CONNECTIONS_KEY,
makeCatalogStore,
type SecureCatalogStorage,
} from "./catalog-store";
function makeStorage(initial: Readonly<Record<string, string>>) {
const values = new Map(Object.entries(initial));
const deleted: Array<string> = [];
const storage = MobileSecureStorage.of({
const storage: SecureCatalogStorage = {
getItem: (key) => Effect.sync(() => values.get(key) ?? null),
setItem: (key, value) =>
Effect.sync(() => {
values.set(key, value);
}),
removeItem: (key) =>
deleteItem: (key) =>
Effect.sync(() => {
deleted.push(key);
values.delete(key);
}),
});
};
return { deleted, storage, values };
}
@@ -39,9 +32,7 @@ describe("mobile connection catalog storage", () => {
const memory = makeStorage({
[CONNECTION_CATALOG_KEY]: "{not-json",
});
const catalog = yield* make().pipe(
Effect.provideService(MobileSecureStorage, memory.storage),
);
const catalog = yield* makeCatalogStore(memory.storage);
expect((yield* catalog.read).targets).toEqual([]);
expect(memory.deleted).toEqual([CONNECTION_CATALOG_KEY]);
@@ -53,9 +44,7 @@ describe("mobile connection catalog storage", () => {
const memory = makeStorage({
[LEGACY_CONNECTIONS_KEY]: JSON.stringify({ connections: [{ invalid: true }] }),
});
const catalog = yield* make().pipe(
Effect.provideService(MobileSecureStorage, memory.storage),
);
const catalog = yield* makeCatalogStore(memory.storage);
expect((yield* catalog.read).targets).toEqual([]);
expect(memory.deleted).toEqual([LEGACY_CONNECTIONS_KEY]);
@@ -82,9 +71,7 @@ describe("mobile connection catalog storage", () => {
],
}),
});
const catalog = yield* make().pipe(
Effect.provideService(MobileSecureStorage, memory.storage),
);
const catalog = yield* makeCatalogStore(memory.storage);
expect((yield* catalog.read).targets).toHaveLength(1);
expect(memory.deleted).toEqual([CONNECTION_CATALOG_KEY, LEGACY_CONNECTIONS_KEY]);
+299 -2
View File
@@ -2,6 +2,7 @@ import {
ConnectionPersistenceError,
ConnectionRegistrationStore,
ConnectionTargetStore,
EnvironmentCacheStore,
registerConnectionInCatalog,
removeConnectionFromCatalog,
removeCatalogValue,
@@ -13,11 +14,111 @@ import {
CredentialStore,
ProfileStore,
} from "@t3tools/client-runtime/connection";
import {
EnvironmentId,
OrchestrationShellSnapshot,
OrchestrationThreadDetailSnapshot,
ThreadId,
} from "@t3tools/contracts";
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as CatalogStore from "./catalog-store";
import * as Schema from "effect/Schema";
import * as SecureStore from "expo-secure-store";
import { makeCatalogStore, type SecureCatalogStorage } from "./catalog-store";
const SHELL_SNAPSHOT_CACHE_SCHEMA_VERSION = 1;
const SHELL_SNAPSHOT_CACHE_DIRECTORY = "connection-shell-snapshots";
const LEGACY_SHELL_SNAPSHOT_CACHE_DIRECTORY = "shell-snapshots";
// v2 stores the snapshot sequence alongside the thread so a warm cache can
// resume via `afterSequence` instead of re-downloading the full thread body.
// Older v1 entries (no sequence) fail to decode and are treated as a cold cache.
const THREAD_SNAPSHOT_CACHE_SCHEMA_VERSION = 2;
const THREAD_SNAPSHOT_CACHE_DIRECTORY = "connection-thread-snapshots";
const StoredShellSnapshot = Schema.Struct({
schemaVersion: Schema.Literal(SHELL_SNAPSHOT_CACHE_SCHEMA_VERSION),
environmentId: EnvironmentId,
snapshot: OrchestrationShellSnapshot,
});
const StoredThreadSnapshot = Schema.Struct({
schemaVersion: Schema.Literal(THREAD_SNAPSHOT_CACHE_SCHEMA_VERSION),
environmentId: EnvironmentId,
threadId: ThreadId,
snapshot: OrchestrationThreadDetailSnapshot,
});
const LegacyStoredShellSnapshot = Schema.Struct({
schemaVersion: Schema.Literal(1),
environmentId: EnvironmentId,
snapshotReceivedAt: Schema.String,
snapshot: OrchestrationShellSnapshot,
});
function catalogError(operation: string, cause: unknown) {
return new ConnectionTransientError({
reason: "remote-unavailable",
detail: `Could not ${operation} the local connection catalog: ${String(cause)}`,
});
}
function shellPersistenceError(
operation:
| "load-shell"
| "save-shell"
| "load-thread"
| "save-thread"
| "remove-thread"
| "clear-environment",
cause: unknown,
) {
return new ConnectionPersistenceError({
operation,
message: `Could not ${operation.replaceAll("-", " ")}: ${String(cause)}`,
});
}
function threadSnapshotFileName(threadId: ThreadId): string {
return `${encodeURIComponent(threadId)}.json`;
}
const threadSnapshotDirectory = Effect.fn("mobile.connectionStorage.threadSnapshotDirectory")(
function* (
environmentId: EnvironmentId,
operation: "load-thread" | "save-thread" | "remove-thread" | "clear-environment",
) {
return yield* Effect.tryPromise({
try: async () => {
const { Directory, Paths } = await import("expo-file-system");
const directory = new Directory(
Paths.document,
THREAD_SNAPSHOT_CACHE_DIRECTORY,
encodeURIComponent(environmentId),
);
if (operation !== "clear-environment") {
directory.create({ idempotent: true, intermediates: true });
}
return directory;
},
catch: (cause) => shellPersistenceError(operation, cause),
});
},
);
const threadSnapshotFile = Effect.fn("mobile.connectionStorage.threadSnapshotFile")(function* (
environmentId: EnvironmentId,
threadId: ThreadId,
operation: "load-thread" | "save-thread" | "remove-thread",
) {
const { File } = yield* Effect.promise(() => import("expo-file-system"));
return new File(
yield* threadSnapshotDirectory(environmentId, operation),
threadSnapshotFileName(threadId),
);
});
function targetPersistenceError(
operation: "list-targets" | "register-connection" | "remove-connection",
@@ -29,9 +130,59 @@ function targetPersistenceError(
});
}
const secureCatalogStorage: SecureCatalogStorage = {
getItem: (key) =>
Effect.tryPromise({
try: () => SecureStore.getItemAsync(key),
catch: (cause) => catalogError("load", cause),
}),
setItem: (key, value) =>
Effect.tryPromise({
try: () => SecureStore.setItemAsync(key, value),
catch: (cause) => catalogError("save", cause),
}),
deleteItem: (key) =>
Effect.tryPromise({
try: () => SecureStore.deleteItemAsync(key),
catch: (cause) => catalogError("delete", cause),
}),
};
function shellSnapshotFileName(environmentId: EnvironmentId): string {
return `${encodeURIComponent(environmentId)}.json`;
}
const shellSnapshotFileInDirectory = Effect.fn(
"mobile.connectionStorage.shellSnapshotFileInDirectory",
)(function* (
environmentId: EnvironmentId,
operation: "load-shell" | "save-shell" | "clear-environment",
directoryName: string,
) {
return yield* Effect.tryPromise({
try: async () => {
const { Directory, File, Paths } = await import("expo-file-system");
const directory = new Directory(Paths.document, directoryName);
directory.create({ idempotent: true, intermediates: true });
return new File(directory, shellSnapshotFileName(environmentId));
},
catch: (cause) => shellPersistenceError(operation, cause),
});
});
const shellSnapshotFile = (
environmentId: EnvironmentId,
operation: "load-shell" | "save-shell" | "clear-environment",
) => shellSnapshotFileInDirectory(environmentId, operation, SHELL_SNAPSHOT_CACHE_DIRECTORY);
const legacyShellSnapshotFile = (
environmentId: EnvironmentId,
operation: "load-shell" | "clear-environment",
) => shellSnapshotFileInDirectory(environmentId, operation, LEGACY_SHELL_SNAPSHOT_CACHE_DIRECTORY);
export const connectionStorageLayer = Layer.effectContext(
Effect.gen(function* () {
const catalog = yield* CatalogStore.make();
const catalog = yield* makeCatalogStore(secureCatalogStorage);
const targetStore = ConnectionTargetStore.of({
list: catalog.read.pipe(
@@ -128,11 +279,157 @@ export const connectionStorageLayer = Layer.effectContext(
),
})),
});
const cacheStore = EnvironmentCacheStore.of({
loadShell: (environmentId) =>
Effect.gen(function* () {
const file = yield* shellSnapshotFile(environmentId, "load-shell");
if (file.exists) {
const raw = yield* Effect.tryPromise({
try: () => file.text(),
catch: (cause) => shellPersistenceError("load-shell", cause),
});
const parsed = yield* Effect.try({
try: () => JSON.parse(raw) as unknown,
catch: (cause) => shellPersistenceError("load-shell", cause),
});
const stored = yield* Effect.fromResult(
Schema.decodeUnknownResult(StoredShellSnapshot)(parsed),
).pipe(Effect.mapError((cause) => shellPersistenceError("load-shell", cause)));
return stored.environmentId === environmentId
? Option.some(stored.snapshot)
: Option.none();
}
const legacyFile = yield* legacyShellSnapshotFile(environmentId, "load-shell");
if (!legacyFile.exists) {
return Option.none();
}
const legacyRaw = yield* Effect.tryPromise({
try: () => legacyFile.text(),
catch: (cause) => shellPersistenceError("load-shell", cause),
});
const legacyParsed = yield* Effect.try({
try: () => JSON.parse(legacyRaw) as unknown,
catch: (cause) => shellPersistenceError("load-shell", cause),
});
const legacyStored = yield* Effect.fromResult(
Schema.decodeUnknownResult(LegacyStoredShellSnapshot)(legacyParsed),
).pipe(Effect.mapError((cause) => shellPersistenceError("load-shell", cause)));
return legacyStored.environmentId === environmentId
? Option.some(legacyStored.snapshot)
: Option.none();
}),
saveShell: (environmentId, snapshot) =>
Effect.gen(function* () {
const file = yield* shellSnapshotFile(environmentId, "save-shell");
const stored = {
schemaVersion: SHELL_SNAPSHOT_CACHE_SCHEMA_VERSION,
environmentId,
snapshot,
} as const;
const encoded = yield* Effect.fromResult(
Schema.encodeUnknownResult(StoredShellSnapshot)(stored),
).pipe(Effect.mapError((cause) => shellPersistenceError("save-shell", cause)));
yield* Effect.try({
try: () => {
if (!file.exists) {
file.create({ intermediates: true, overwrite: true });
}
file.write(JSON.stringify(encoded));
},
catch: (cause) => shellPersistenceError("save-shell", cause),
});
}),
loadThread: (environmentId, threadId) =>
Effect.gen(function* () {
const file = yield* threadSnapshotFile(environmentId, threadId, "load-thread");
if (!file.exists) {
return Option.none();
}
const raw = yield* Effect.tryPromise({
try: () => file.text(),
catch: (cause) => shellPersistenceError("load-thread", cause),
});
const parsed = yield* Effect.try({
try: () => JSON.parse(raw) as unknown,
catch: (cause) => shellPersistenceError("load-thread", cause),
});
const stored = yield* Effect.fromResult(
Schema.decodeUnknownResult(StoredThreadSnapshot)(parsed),
).pipe(Effect.mapError((cause) => shellPersistenceError("load-thread", cause)));
return stored.environmentId === environmentId && stored.threadId === threadId
? Option.some(stored.snapshot)
: Option.none();
}),
saveThread: (environmentId, snapshot) =>
Effect.gen(function* () {
const file = yield* threadSnapshotFile(environmentId, snapshot.thread.id, "save-thread");
const encoded = yield* Effect.fromResult(
Schema.encodeUnknownResult(StoredThreadSnapshot)({
schemaVersion: THREAD_SNAPSHOT_CACHE_SCHEMA_VERSION,
environmentId,
threadId: snapshot.thread.id,
snapshot,
}),
).pipe(Effect.mapError((cause) => shellPersistenceError("save-thread", cause)));
yield* Effect.try({
try: () => {
if (!file.exists) {
file.create({ intermediates: true, overwrite: true });
}
file.write(JSON.stringify(encoded));
},
catch: (cause) => shellPersistenceError("save-thread", cause),
});
}),
removeThread: (environmentId, threadId) =>
Effect.gen(function* () {
const file = yield* threadSnapshotFile(environmentId, threadId, "remove-thread");
if (file.exists) {
file.delete();
}
}).pipe(
Effect.mapError((cause) =>
cause._tag === "ConnectionPersistenceError"
? cause
: shellPersistenceError("remove-thread", cause),
),
),
clear: (environmentId) =>
Effect.gen(function* () {
const file = yield* shellSnapshotFile(environmentId, "clear-environment");
if (file.exists) {
yield* Effect.try({
try: () => file.delete(),
catch: (cause) => shellPersistenceError("clear-environment", cause),
});
}
const legacyFile = yield* legacyShellSnapshotFile(environmentId, "clear-environment");
if (legacyFile.exists) {
yield* Effect.try({
try: () => legacyFile.delete(),
catch: (cause) => shellPersistenceError("clear-environment", cause),
});
}
const threadDirectory = yield* threadSnapshotDirectory(
environmentId,
"clear-environment",
);
if (threadDirectory.exists) {
yield* Effect.try({
try: () => threadDirectory.delete(),
catch: (cause) => shellPersistenceError("clear-environment", cause),
});
}
}),
});
return Context.make(ConnectionTargetStore, targetStore).pipe(
Context.add(ConnectionRegistrationStore, registrationStore),
Context.add(ProfileStore.ConnectionProfileStore, profileStore),
Context.add(CredentialStore.ConnectionCredentialStore, credentialStore),
Context.add(TokenStore.RemoteDpopAccessTokenStore, remoteTokenStore),
Context.add(EnvironmentCacheStore, cacheStore),
);
}),
);
@@ -7,30 +7,21 @@ import * as Layer from "effect/Layer";
import { HttpClient } from "effect/unstable/http";
import type { SavedRemoteConnection } from "../../lib/connection";
import { MobileStorage } from "../../persistence/mobile-storage";
import {
CloudEnvironmentLinkError,
linkEnvironmentToCloudWithPreference,
} from "../cloud/linkEnvironment";
import { savePreferencesPatch } from "../../lib/storage";
import { linkEnvironmentToCloud } from "../cloud/linkEnvironment";
import { setLiveActivityUpdatesEnabled } from "./liveActivityPreferences";
import { updateAgentAwarenessRegistrationPreferences } from "./remoteRegistration";
import { refreshAgentAwarenessRegistration } from "./remoteRegistration";
vi.mock("expo-secure-store", () => ({
deleteItemAsync: vi.fn(),
getItemAsync: vi.fn(),
setItemAsync: vi.fn(),
}));
vi.mock("react-native", () => ({
Platform: { OS: "ios" },
vi.mock("../../lib/storage", () => ({
savePreferencesPatch: vi.fn(() => Promise.resolve()),
}));
vi.mock("../cloud/linkEnvironment", () => ({
linkEnvironmentToCloudWithPreference: vi.fn(() => Effect.void),
linkEnvironmentToCloud: vi.fn(() => Effect.void),
}));
vi.mock("./remoteRegistration", () => ({
updateAgentAwarenessRegistrationPreferences: vi.fn(() => Effect.void),
refreshAgentAwarenessRegistration: vi.fn(() => Effect.void),
}));
const connection: SavedRemoteConnection = {
@@ -49,19 +40,6 @@ const testLayer = Layer.mergeAll(
HttpClient.HttpClient,
HttpClient.make(() => Effect.die("unexpected HTTP request")),
),
Layer.succeed(
MobileStorage,
MobileStorage.of({
loadSavedConnections: Effect.succeed([]),
saveConnection: () => Effect.void,
clearSavedConnection: () => Effect.void,
loadOrCreateAgentAwarenessDeviceId: Effect.succeed("device-1"),
loadAgentAwarenessDeviceId: Effect.succeed("device-1"),
loadAgentAwarenessRegistrationRecord: Effect.succeed(null),
saveAgentAwarenessRegistrationRecord: () => Effect.void,
clearAgentAwarenessRegistrationRecord: Effect.void,
}),
),
);
describe("liveActivityPreferences", () => {
@@ -73,18 +51,15 @@ describe("liveActivityPreferences", () => {
Effect.gen(function* () {
yield* setLiveActivityUpdatesEnabled({
enabled: false,
previousEnabled: true,
clerkToken: "clerk-token",
connections: [connection],
});
expect(updateAgentAwarenessRegistrationPreferences).toHaveBeenCalledWith({
liveActivitiesEnabled: false,
});
expect(linkEnvironmentToCloudWithPreference).toHaveBeenCalledWith({
expect(savePreferencesPatch).toHaveBeenCalledWith({ liveActivitiesEnabled: false });
expect(refreshAgentAwarenessRegistration).toHaveBeenCalledTimes(1);
expect(linkEnvironmentToCloud).toHaveBeenCalledWith({
clerkToken: "clerk-token",
connection,
liveActivitiesEnabled: false,
});
}).pipe(Effect.provide(testLayer)),
);
@@ -93,18 +68,15 @@ describe("liveActivityPreferences", () => {
Effect.gen(function* () {
yield* setLiveActivityUpdatesEnabled({
enabled: true,
previousEnabled: false,
clerkToken: "clerk-token",
connections: [connection],
});
expect(updateAgentAwarenessRegistrationPreferences).toHaveBeenCalledWith({
liveActivitiesEnabled: true,
});
expect(linkEnvironmentToCloudWithPreference).toHaveBeenCalledWith({
expect(savePreferencesPatch).toHaveBeenCalledWith({ liveActivitiesEnabled: true });
expect(refreshAgentAwarenessRegistration).toHaveBeenCalledTimes(1);
expect(linkEnvironmentToCloud).toHaveBeenCalledWith({
clerkToken: "clerk-token",
connection,
liveActivitiesEnabled: true,
});
}).pipe(Effect.provide(testLayer)),
);
@@ -113,15 +85,13 @@ describe("liveActivityPreferences", () => {
Effect.gen(function* () {
yield* setLiveActivityUpdatesEnabled({
enabled: false,
previousEnabled: true,
clerkToken: null,
connections: [connection],
});
expect(updateAgentAwarenessRegistrationPreferences).toHaveBeenCalledWith({
liveActivitiesEnabled: false,
});
expect(linkEnvironmentToCloudWithPreference).not.toHaveBeenCalled();
expect(savePreferencesPatch).toHaveBeenCalledWith({ liveActivitiesEnabled: false });
expect(refreshAgentAwarenessRegistration).toHaveBeenCalledTimes(1);
expect(linkEnvironmentToCloud).not.toHaveBeenCalled();
}).pipe(Effect.provide(testLayer)),
);
@@ -134,51 +104,14 @@ describe("liveActivityPreferences", () => {
return Effect.gen(function* () {
yield* setLiveActivityUpdatesEnabled({
enabled: true,
previousEnabled: false,
clerkToken: "clerk-token",
connections: [connection, managedConnection],
});
expect(linkEnvironmentToCloudWithPreference).toHaveBeenCalledTimes(1);
expect(linkEnvironmentToCloudWithPreference).toHaveBeenCalledWith({
expect(linkEnvironmentToCloud).toHaveBeenCalledTimes(1);
expect(linkEnvironmentToCloud).toHaveBeenCalledWith({
clerkToken: "clerk-token",
connection,
liveActivitiesEnabled: true,
});
}).pipe(Effect.provide(testLayer));
});
it.effect("restores relay preferences when an environment update fails", () => {
vi.mocked(linkEnvironmentToCloudWithPreference).mockImplementationOnce(() =>
Effect.fail(new CloudEnvironmentLinkError({ message: "environment update failed" })),
);
return Effect.gen(function* () {
const exit = yield* Effect.exit(
setLiveActivityUpdatesEnabled({
enabled: false,
previousEnabled: true,
clerkToken: "clerk-token",
connections: [connection],
}),
);
expect(exit._tag).toBe("Failure");
expect(updateAgentAwarenessRegistrationPreferences).toHaveBeenNthCalledWith(1, {
liveActivitiesEnabled: false,
});
expect(updateAgentAwarenessRegistrationPreferences).toHaveBeenNthCalledWith(2, {
liveActivitiesEnabled: true,
});
expect(linkEnvironmentToCloudWithPreference).toHaveBeenNthCalledWith(1, {
clerkToken: "clerk-token",
connection,
liveActivitiesEnabled: false,
});
expect(linkEnvironmentToCloudWithPreference).toHaveBeenNthCalledWith(2, {
clerkToken: "clerk-token",
connection,
liveActivitiesEnabled: true,
});
}).pipe(Effect.provide(testLayer));
});
@@ -1,73 +1,47 @@
import * as Effect from "effect/Effect";
import * as Schema from "effect/Schema";
import { HttpClient } from "effect/unstable/http";
import { ManagedRelay } from "@t3tools/client-runtime/relay";
import type { SavedRemoteConnection } from "../../lib/connection";
import { linkEnvironmentToCloudWithPreference } from "../cloud/linkEnvironment";
import { updateAgentAwarenessRegistrationPreferences } from "./remoteRegistration";
import { savePreferencesPatch } from "../../lib/storage";
import { linkEnvironmentToCloud } from "../cloud/linkEnvironment";
import { refreshAgentAwarenessRegistration } from "./remoteRegistration";
export const setLiveActivityUpdatesEnabled = Effect.fn("setLiveActivityUpdatesEnabled")(
function* (input: {
readonly enabled: boolean;
readonly previousEnabled: boolean;
readonly clerkToken: string | null;
readonly connections: ReadonlyArray<SavedRemoteConnection>;
}) {
const linkedConnections = input.connections.filter(
(connection) => connection.bearerToken !== null,
);
const updateRelayPreference = Effect.fn("updateRelayPreference")(function* (enabled: boolean) {
yield* updateAgentAwarenessRegistrationPreferences({
liveActivitiesEnabled: enabled,
});
const clerkToken = input.clerkToken;
if (!clerkToken) return;
yield* Effect.forEach(
linkedConnections,
(connection) =>
linkEnvironmentToCloudWithPreference({
clerkToken,
connection,
liveActivitiesEnabled: enabled,
}),
{ concurrency: "unbounded" },
);
});
const restoreRelayPreference = Effect.fn("restoreRelayPreference")(function* () {
yield* updateAgentAwarenessRegistrationPreferences({
liveActivitiesEnabled: input.previousEnabled,
}).pipe(
Effect.catchCause((cause) =>
Effect.logWarning("Could not restore Live Activity device preference.", cause),
),
);
const clerkToken = input.clerkToken;
if (!clerkToken) return;
yield* Effect.forEach(
linkedConnections,
(connection) =>
linkEnvironmentToCloudWithPreference({
clerkToken,
connection,
liveActivitiesEnabled: input.previousEnabled,
}).pipe(
Effect.catchCause((cause) =>
Effect.logWarning(
`Could not restore Live Activity preference for environment ${connection.environmentId}.`,
cause,
),
),
),
{ concurrency: "unbounded" },
);
});
yield* updateRelayPreference(input.enabled).pipe(
Effect.onError(() => restoreRelayPreference()),
);
export class LiveActivityPreferenceSaveError extends Schema.TaggedErrorClass<LiveActivityPreferenceSaveError>()(
"LiveActivityPreferenceSaveError",
{
enabled: Schema.Boolean,
cause: Schema.Defect(),
},
);
) {
override get message(): string {
return `Failed to save the Live Activity updates setting (enabled: ${this.enabled}).`;
}
}
export function setLiveActivityUpdatesEnabled(input: {
readonly enabled: boolean;
readonly clerkToken: string | null;
readonly connections: ReadonlyArray<SavedRemoteConnection>;
}): Effect.Effect<void, unknown, HttpClient.HttpClient | ManagedRelay.ManagedRelayClient> {
return Effect.gen(function* () {
yield* Effect.tryPromise({
try: () => savePreferencesPatch({ liveActivitiesEnabled: input.enabled }),
catch: (cause) => new LiveActivityPreferenceSaveError({ enabled: input.enabled, cause }),
});
yield* refreshAgentAwarenessRegistration();
const clerkToken = input.clerkToken;
if (!clerkToken) {
return;
}
yield* Effect.forEach(
input.connections.filter((connection) => connection.bearerToken !== null),
(connection) => linkEnvironmentToCloud({ clerkToken, connection }),
{ concurrency: "unbounded" },
);
});
}
@@ -1,6 +1,6 @@
import type { RelayDeviceRegistrationRequest } from "@t3tools/contracts/relay";
import type { Preferences } from "../../persistence/mobile-preferences";
import type { Preferences } from "../../lib/storage";
// Development builds are Xcode-signed and receive sandbox APNs tokens;
// preview and production builds are distribution-signed and use production
@@ -21,13 +21,12 @@ import {
loadAgentAwarenessRegistrationRecord,
loadOrCreateAgentAwarenessDeviceId,
saveAgentAwarenessRegistrationRecord,
} from "../../persistence/imperative";
} from "../../lib/storage";
import { makeRelayDeviceRegistrationRequest, resolveApsEnvironment } from "./registrationPayload";
import {
AgentAwarenessOperationError,
__resetAgentAwarenessRemoteRegistrationForTest,
getAgentAwarenessRegistrationStatus,
mergeAgentAwarenessRegistrationPreferences,
refreshActiveLiveActivityRemoteRegistration,
refreshAgentAwarenessRegistration,
normalizeAgentAwarenessRelayBaseUrl,
@@ -143,7 +142,7 @@ vi.mock("../../lib/runtime", () => ({
},
}));
vi.mock("../../persistence/imperative", () => ({
vi.mock("../../lib/storage", () => ({
loadAgentAwarenessDeviceId: vi.fn(() => Promise.resolve("device-1")),
loadOrCreateAgentAwarenessDeviceId: vi.fn(() => Promise.resolve("device-1")),
loadPreferences: vi.fn(() => Promise.resolve({ liveActivitiesEnabled: false })),
@@ -325,15 +324,6 @@ describe("makeRelayDeviceRegistrationRequest", () => {
expect(normalizeAgentAwarenessRelayBaseUrl(" ")).toBeNull();
});
it("overrides persisted preferences for an in-flight registration", () => {
expect(
mergeAgentAwarenessRegistrationPreferences(
{ liveActivitiesEnabled: false, baseFontSize: 18 },
{ liveActivitiesEnabled: true },
),
).toEqual({ liveActivitiesEnabled: true, baseFontSize: 18 });
});
it.effect("registers at most one listener while a Live Activity push token is pending", () => {
registerAgentAwarenessConnection(savedConnection());
const addPushTokenListener = vi.fn();
@@ -20,7 +20,6 @@ import {
import type { SavedRemoteConnection } from "../../lib/connection";
import { runtime } from "../../lib/runtime";
import type { Preferences } from "../../persistence/mobile-preferences";
import {
clearAgentAwarenessRegistrationRecord,
loadAgentAwarenessDeviceId,
@@ -28,7 +27,7 @@ import {
loadOrCreateAgentAwarenessDeviceId,
loadPreferences,
saveAgentAwarenessRegistrationRecord,
} from "../../persistence/imperative";
} from "../../lib/storage";
import AgentActivity, { type AgentActivityProps } from "../../widgets/AgentActivity";
import { resolveCloudPublicConfig } from "../cloud/publicConfig";
import { makeRelayDeviceRegistrationRequest, resolveApsEnvironment } from "./registrationPayload";
@@ -125,17 +124,6 @@ interface DeviceRegistrationInput {
readonly observedPushToken?: string;
}
interface RegisterDeviceInput extends DeviceRegistrationInput {
readonly preferencesOverride?: Partial<Preferences>;
}
export function mergeAgentAwarenessRegistrationPreferences(
stored: Preferences,
override: Partial<Preferences> | undefined,
): Preferences {
return { ...stored, ...override };
}
export function normalizeAgentAwarenessRelayBaseUrl(
value: string | null | undefined,
): string | null {
@@ -667,7 +655,7 @@ function enqueueDeviceRegistration(input: DeviceRegistrationInput, context: stri
}
function registerDevice(
input: RegisterDeviceInput = {},
input: DeviceRegistrationInput = {},
expectedGeneration = deviceRegistrationGeneration,
): Effect.Effect<void, unknown, ManagedRelay.ManagedRelayClient> {
return Effect.gen(function* () {
@@ -677,7 +665,7 @@ function registerDevice(
}
logRegistrationDebug("device registration loading local state", { expectedGeneration });
const [deviceId, storedPreferences] = yield* Effect.all([
const [deviceId, preferences] = yield* Effect.all([
Effect.tryPromise({
try: () => loadOrCreateAgentAwarenessDeviceId(),
catch: (cause) =>
@@ -695,10 +683,6 @@ function registerDevice(
}),
}),
]);
const preferences = mergeAgentAwarenessRegistrationPreferences(
storedPreferences,
input.preferencesOverride,
);
const pushTokenRegistration = yield* nativePushTokenRegistration(input?.observedPushToken);
logRegistrationDebug("device registration local state ready", {
expectedGeneration,
@@ -836,21 +820,6 @@ export function refreshAgentAwarenessRegistration(): Effect.Effect<
);
}
export function updateAgentAwarenessRegistrationPreferences(
preferencesOverride: Partial<Preferences>,
): Effect.Effect<void, unknown, ManagedRelay.ManagedRelayClient> {
return registerDevice({ preferencesOverride }).pipe(
Effect.tapError((error) =>
Effect.sync(() => {
if (registrationStatus !== "registered") {
setRegistrationStatus("failed");
}
logRegistrationError("device preference registration refresh failed", error);
}),
),
);
}
export function __resetAgentAwarenessRemoteRegistrationForTest(): void {
environmentConnections.clear();
pushTokenSubscription?.remove();
@@ -244,8 +244,9 @@ function ProjectGroupLabel(props: {
workspaceRoot={props.project.workspaceRoot}
/>
<Text
className="flex-1 text-xs font-t3-medium tracking-[0.5px] uppercase text-foreground-muted"
className="flex-1 text-xs font-t3-medium uppercase text-foreground-muted"
numberOfLines={1}
style={{ letterSpacing: 0.5 }}
>
{props.project.title}
</Text>
@@ -330,7 +331,10 @@ function ArchivedThreadRow(props: {
>
{props.thread.title}
</Text>
<Text className="min-w-[30px] text-right text-xs tabular-nums text-foreground-tertiary">
<Text
className="text-xs text-foreground-tertiary"
style={{ fontVariant: ["tabular-nums"], minWidth: 30, textAlign: "right" }}
>
{timestamp}
</Text>
</View>
@@ -343,8 +347,9 @@ function ArchivedThreadRow(props: {
type="monochrome"
/>
<Text
className="min-w-0 flex-1 font-mono text-2xs text-foreground-tertiary"
className="min-w-0 flex-1 text-2xs text-foreground-tertiary"
numberOfLines={1}
style={{ fontFamily: "monospace" }}
>
{subtitle.join(" · ")}
</Text>
@@ -1,12 +1,13 @@
import { useWaitlist } from "@clerk/expo";
import { ActivityIndicator, Pressable, Text, TextInput, View } from "react-native";
import { ActivityIndicator, Pressable, StyleSheet, Text, TextInput, View } from "react-native";
import { useState } from "react";
import { cn } from "../../lib/cn";
import { useThemeColor } from "../../lib/useThemeColor";
import { CloudWaitlistJoinRejectedError, joinCloudWaitlist } from "./cloudWaitlistJoin";
export function CloudWaitlistEnrollment(props: { readonly onSignIn: () => void }) {
const { errors, fetchStatus, waitlist } = useWaitlist();
const colors = useCloudWaitlistColors();
const [emailAddress, setEmailAddress] = useState("");
const [requestError, setRequestError] = useState<string | null>(null);
const isSubmitting = fetchStatus === "fetching";
@@ -33,7 +34,7 @@ export function CloudWaitlistEnrollment(props: { readonly onSignIn: () => void }
if (waitlist.id) {
return (
<View className="gap-[18px]">
<View style={styles.content}>
<Text className="text-center font-t3-bold text-xl text-foreground">
You are on the waitlist
</Text>
@@ -46,22 +47,19 @@ export function CloudWaitlistEnrollment(props: { readonly onSignIn: () => void }
}
return (
<View className="gap-[18px]">
<View style={styles.content}>
<Text className="font-sans text-base text-foreground-secondary">
Enter your email and we will let you know when access is ready.
</Text>
<View className="gap-2">
<View style={styles.field}>
<Text className="font-t3-bold text-sm text-foreground-secondary">Email address</Text>
<TextInput
accessibilityLabel="Email address"
autoCapitalize="none"
autoComplete="email"
autoCorrect={false}
className={cn(
"min-h-[54px] rounded-2xl border border-input-border bg-input px-4 py-3.5 font-sans text-lg text-foreground border-continuous",
(fieldError || requestError) && "border-danger-foreground",
)}
className="font-sans text-lg text-foreground"
keyboardType="email-address"
onChangeText={(value) => {
setEmailAddress(value);
@@ -69,8 +67,16 @@ export function CloudWaitlistEnrollment(props: { readonly onSignIn: () => void }
}}
onSubmitEditing={() => void joinWaitlist()}
placeholder="Enter your email address"
placeholderTextColorClassName="accent-placeholder"
placeholderTextColor={colors.placeholder}
returnKeyType="join"
style={[
styles.input,
{
backgroundColor: colors.input,
borderColor:
fieldError || requestError ? colors.dangerForeground : colors.inputBorder,
},
]}
textContentType="emailAddress"
value={emailAddress}
/>
@@ -93,11 +99,15 @@ export function CloudWaitlistEnrollment(props: { readonly onSignIn: () => void }
}}
disabled={isSubmitting || emailAddress.trim().length === 0}
onPress={() => void joinWaitlist()}
className="min-h-[54px] flex-row items-center justify-center gap-2 rounded-full bg-primary px-5 py-3 disabled:opacity-[0.45]"
style={[
styles.primaryButton,
{
backgroundColor: colors.primary,
opacity: isSubmitting || emailAddress.trim().length === 0 ? 0.45 : 1,
},
]}
>
{isSubmitting ? (
<ActivityIndicator colorClassName="accent-primary-foreground" size="small" />
) : null}
{isSubmitting ? <ActivityIndicator color={colors.primaryForeground} size="small" /> : null}
<Text className="font-t3-bold text-base text-primary-foreground">
{isSubmitting ? "Joining" : "Join the waitlist"}
</Text>
@@ -110,7 +120,7 @@ export function CloudWaitlistEnrollment(props: { readonly onSignIn: () => void }
function SignInAction(props: { readonly onPress: () => void }) {
return (
<View className="flex-row items-center justify-center gap-1 pt-1">
<View style={styles.signInRow}>
<Text className="font-sans text-base text-foreground-secondary">Already have access?</Text>
<Pressable accessibilityRole="button" hitSlop={8} onPress={props.onPress}>
<Text className="font-t3-bold text-base text-foreground">Sign in</Text>
@@ -118,3 +128,48 @@ function SignInAction(props: { readonly onPress: () => void }) {
</View>
);
}
function useCloudWaitlistColors() {
return {
dangerForeground: String(useThemeColor("--color-danger-foreground")),
input: String(useThemeColor("--color-input")),
inputBorder: String(useThemeColor("--color-input-border")),
placeholder: String(useThemeColor("--color-placeholder")),
primary: String(useThemeColor("--color-primary")),
primaryForeground: String(useThemeColor("--color-primary-foreground")),
};
}
const styles = StyleSheet.create({
content: {
gap: 18,
},
field: {
gap: 8,
},
input: {
borderCurve: "continuous",
borderRadius: 16,
borderWidth: 1,
minHeight: 54,
paddingHorizontal: 16,
paddingVertical: 14,
},
primaryButton: {
alignItems: "center",
borderRadius: 999,
flexDirection: "row",
gap: 8,
justifyContent: "center",
minHeight: 54,
paddingHorizontal: 20,
paddingVertical: 12,
},
signInRow: {
alignItems: "center",
flexDirection: "row",
gap: 4,
justifyContent: "center",
paddingTop: 4,
},
});
@@ -88,7 +88,7 @@ function ConfiguredConnectOnboardingRouteScreen() {
alwaysBounceVertical
contentInsetAdjustmentBehavior="automatic"
showsVerticalScrollIndicator={false}
className="flex-1"
style={{ flex: 1 }}
contentInset={{ bottom: Math.max(insets.bottom, 18) + 18 }}
contentContainerStyle={{
gap: 16,
@@ -1,7 +1,7 @@
import { loadPreferences, updatePreferences } from "../../persistence/imperative";
import { loadPreferences, updatePreferences } from "../../lib/storage";
// Lives apart from connectOnboarding.ts so CloudAuthProvider (which imports
// the request signal) never pulls the persistence adapter into its
// 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". */
@@ -7,13 +7,10 @@ import { RelayMobileClientId } from "@t3tools/contracts/relay";
import { ManagedRelay } from "@t3tools/client-runtime/relay";
import { remoteHttpClientLayer } from "@t3tools/client-runtime/rpc";
import { HttpClient } from "effect/unstable/http";
import { MobilePreferencesStore } from "../../persistence/mobile-preferences";
import { MobileStorage } from "../../persistence/mobile-storage";
import {
cloudEnvironmentsPendingStatus,
linkEnvironmentToCloud,
linkEnvironmentToCloudWithPreference,
connectCloudEnvironment,
listCloudEnvironments,
listCloudEnvironmentsWithStatus,
@@ -39,14 +36,11 @@ vi.mock("react-native", () => ({
},
}));
vi.mock("expo-secure-store", () => ({
deleteItemAsync: vi.fn(),
getItemAsync: vi.fn(),
setItemAsync: vi.fn(),
vi.mock("../../lib/storage", () => ({
loadOrCreateAgentAwarenessDeviceId: vi.fn(() => Promise.resolve("device-1")),
loadPreferences: vi.fn(() => Promise.resolve({})),
}));
const loadPreferences = vi.fn(() => Effect.succeed({}));
const savedConnection = {
environmentId: EnvironmentId.make("env-1"),
environmentLabel: "Desktop",
@@ -75,27 +69,6 @@ function cloudClientLayer() {
const httpClientLayer = remoteHttpClientLayer((input, init) => globalThis.fetch(input, init));
return Layer.mergeAll(
httpClientLayer,
Layer.succeed(
MobilePreferencesStore,
MobilePreferencesStore.of({
load: loadPreferences(),
savePatch: (patch) => Effect.succeed(patch),
update: () => Effect.succeed({}),
}),
),
Layer.succeed(
MobileStorage,
MobileStorage.of({
loadSavedConnections: Effect.succeed([]),
saveConnection: () => Effect.void,
clearSavedConnection: () => Effect.void,
loadOrCreateAgentAwarenessDeviceId: Effect.succeed("device-1"),
loadAgentAwarenessDeviceId: Effect.succeed("device-1"),
loadAgentAwarenessRegistrationRecord: Effect.succeed(null),
saveAgentAwarenessRegistrationRecord: () => Effect.void,
clearAgentAwarenessRegistrationRecord: Effect.void,
}),
),
ManagedRelay.layer({
relayUrl: "https://relay.example.test",
clientId: RelayMobileClientId,
@@ -107,11 +80,7 @@ const withCloudServices = <A, E>(
effect: Effect.Effect<
A,
E,
| HttpClient.HttpClient
| ManagedRelay.ManagedRelayClient
| ManagedRelay.ManagedRelayDpopSigner
| MobilePreferencesStore
| MobileStorage
HttpClient.HttpClient | ManagedRelay.ManagedRelayClient | ManagedRelay.ManagedRelayDpopSigner
>,
) => effect.pipe(Effect.provide(cloudClientLayer()));
@@ -177,7 +146,6 @@ describe("mobile cloud link environment client", () => {
beforeEach(() => {
vi.restoreAllMocks();
createProofMock.mockClear();
loadPreferences.mockClear();
});
it("normalizes configured relay base URLs before building DPoP-bound requests", () => {
@@ -737,7 +705,10 @@ describe("mobile cloud link environment client", () => {
it.effect("preserves disabled Live Activity preferences when linking an environment", () =>
Effect.gen(function* () {
loadPreferences.mockReturnValueOnce(Effect.succeed({ liveActivitiesEnabled: false }));
const storage = yield* Effect.promise(() => import("../../lib/storage"));
vi.mocked(storage.loadPreferences).mockResolvedValueOnce({
liveActivitiesEnabled: false,
});
const bodies: Array<unknown> = [];
const fetchMock = vi.fn((url: string | URL, init?: RequestInit) => {
if (init?.body) {
@@ -790,45 +761,6 @@ describe("mobile cloud link environment client", () => {
}),
);
it.effect("uses an explicit Live Activity preference when persisted state is unavailable", () =>
Effect.gen(function* () {
loadPreferences.mockReturnValueOnce(Effect.die("persisted preferences must not be read"));
const bodies: Array<Record<string, unknown>> = [];
const fetchMock = vi.fn((url: string | URL, init?: RequestInit) => {
if (init?.body) {
// @effect-diagnostics-next-line preferSchemaOverJson:off
bodies.push(JSON.parse(requestBodyText(init.body)) as Record<string, unknown>);
}
if (String(url).endsWith("/v1/client/environment-link-challenges")) {
return Promise.resolve(Response.json(validLinkChallengeResponse()));
}
if (String(url).endsWith("/api/connect/link-proof")) {
return Promise.resolve(Response.json(validLinkProof()));
}
if (String(url).endsWith("/v1/client/environment-links")) {
return Promise.resolve(Response.json(validLinkResponse()));
}
return Promise.resolve(
Response.json({ ok: true, endpointRuntimeStatus: { status: "configured" } }),
);
});
vi.stubGlobal("fetch", fetchMock);
yield* withCloudServices(
linkEnvironmentToCloudWithPreference({
clerkToken: "clerk-token",
connection: savedConnection,
liveActivitiesEnabled: true,
}),
);
expect(bodies.filter((body) => "liveActivitiesEnabled" in body)).toEqual([
expect.objectContaining({ liveActivitiesEnabled: true }),
expect.objectContaining({ liveActivitiesEnabled: true }),
]);
}),
);
it.effect(
"does not persist cloud connect bootstrap credentials in saved connection records",
() =>
@@ -30,8 +30,7 @@ import { makeEnvironmentHttpApiClient } from "@t3tools/client-runtime/rpc";
import { authClientMetadata } from "../../lib/authClientMetadata";
import type { SavedRemoteConnection } from "../../lib/connection";
import * as MobilePreferences from "../../persistence/mobile-preferences";
import * as MobileStorage from "../../persistence/mobile-storage";
import { loadOrCreateAgentAwarenessDeviceId, loadPreferences } from "../../lib/storage";
import { resolveCloudPublicConfig } from "./publicConfig";
const RELAY_STATUS_AND_CONNECT_SCOPES = [
@@ -257,19 +256,14 @@ function ensureConnectEndpointMatchesEnvironment(input: {
return Effect.void;
}
interface LinkEnvironmentToCloudInput {
export function linkEnvironmentToCloud(input: {
readonly connection: SavedRemoteConnection;
readonly clerkToken: string;
}
type LinkEnvironmentToCloudRequirements =
| HttpClient.HttpClient
| ManagedRelay.ManagedRelayClient
| MobileStorage.MobileStorage;
export function linkEnvironmentToCloudWithPreference(
input: LinkEnvironmentToCloudInput & { readonly liveActivitiesEnabled: boolean },
): Effect.Effect<void, CloudEnvironmentLinkError, LinkEnvironmentToCloudRequirements> {
}): Effect.Effect<
void,
CloudEnvironmentLinkError,
HttpClient.HttpClient | ManagedRelay.ManagedRelayClient
> {
return Effect.gen(function* () {
if (!input.connection.bearerToken) {
return yield* new CloudEnvironmentLinkError({
@@ -279,11 +273,15 @@ export function linkEnvironmentToCloudWithPreference(
const localBearerToken = input.connection.bearerToken;
const relayUrl = yield* requireRelayUrl();
const relayClient = yield* ManagedRelay.ManagedRelayClient;
const storage = yield* MobileStorage.MobileStorage;
const deviceId = yield* storage.loadOrCreateAgentAwarenessDeviceId.pipe(
Effect.mapError(cloudEnvironmentLinkError("Could not load the mobile device id.")),
);
const liveActivitiesEnabled = input.liveActivitiesEnabled;
const deviceId = yield* Effect.tryPromise({
try: () => loadOrCreateAgentAwarenessDeviceId(),
catch: cloudEnvironmentLinkError("Could not load the mobile device id."),
});
const preferences = yield* Effect.tryPromise({
try: () => loadPreferences(),
catch: cloudEnvironmentLinkError("Could not load mobile notification preferences."),
});
const liveActivitiesEnabled = preferences.liveActivitiesEnabled !== false;
const challenge = yield* relayClient
.createEnvironmentLinkChallenge({
clerkToken: input.clerkToken,
@@ -352,25 +350,6 @@ export function linkEnvironmentToCloudWithPreference(
});
}
export function linkEnvironmentToCloud(
input: LinkEnvironmentToCloudInput,
): Effect.Effect<
void,
CloudEnvironmentLinkError,
LinkEnvironmentToCloudRequirements | MobilePreferences.MobilePreferencesStore
> {
return MobilePreferences.MobilePreferencesStore.pipe(
Effect.flatMap((preferencesStore) => preferencesStore.load),
Effect.mapError(cloudEnvironmentLinkError("Could not load mobile notification preferences.")),
Effect.flatMap((preferences) =>
linkEnvironmentToCloudWithPreference({
...input,
liveActivitiesEnabled: preferences.liveActivitiesEnabled !== false,
}),
),
);
}
export function listCloudEnvironments(input: {
readonly clerkToken: string;
}): Effect.Effect<
@@ -481,10 +460,10 @@ export function listCloudEnvironmentsWithStatus(input: {
const loadAgentAwarenessDeviceId = Effect.fn("mobile.cloud.loadAgentAwarenessDeviceId")(
function* () {
const storage = yield* MobileStorage.MobileStorage;
return yield* storage.loadOrCreateAgentAwarenessDeviceId.pipe(
Effect.mapError(cloudEnvironmentLinkError("Could not load the mobile device id.")),
);
return yield* Effect.tryPromise({
try: () => loadOrCreateAgentAwarenessDeviceId(),
catch: cloudEnvironmentLinkError("Could not load the mobile device id."),
});
},
);
@@ -578,10 +557,7 @@ export function connectCloudEnvironment(input: {
}): Effect.Effect<
SavedRemoteConnection,
CloudEnvironmentLinkError,
| HttpClient.HttpClient
| ManagedRelay.ManagedRelayClient
| ManagedRelay.ManagedRelayDpopSigner
| MobileStorage.MobileStorage
HttpClient.HttpClient | ManagedRelay.ManagedRelayClient | ManagedRelay.ManagedRelayDpopSigner
> {
return connectRelayManagedEnvironment({
clerkToken: input.clerkToken,
@@ -596,10 +572,7 @@ export function refreshCloudEnvironmentConnection(input: {
}): Effect.Effect<
SavedRemoteConnection,
CloudEnvironmentLinkError,
| HttpClient.HttpClient
| ManagedRelay.ManagedRelayClient
| ManagedRelay.ManagedRelayDpopSigner
| MobileStorage.MobileStorage
HttpClient.HttpClient | ManagedRelay.ManagedRelayClient | ManagedRelay.ManagedRelayDpopSigner
> {
return connectRelayManagedEnvironment({
clerkToken: input.clerkToken,
@@ -297,8 +297,9 @@ function CloudEnvironmentRowShell(props: {
{props.connectionError ? (
<Text
aria-hidden
className={cn("absolute left-0 right-0 text-xs", statusClassName)}
onTextLayout={onMeasuredErrorTextLayout}
className={cn("absolute inset-x-0 -z-[1] text-xs opacity-0", statusClassName)}
style={{ opacity: 0, zIndex: -1 }}
>
{measuredErrorText}
</Text>
@@ -320,7 +321,7 @@ function CloudEnvironmentRowShell(props: {
<Text
accessibilityHint="Copies the trace ID"
accessibilityRole="button"
className={cn("text-xs underline decoration-dotted", statusClassName)}
className={cn("text-xs underline", statusClassName)}
onLongPress={(event) => {
event.stopPropagation();
copyTextWithHaptic(errorTraceId, { target: "connection-trace-id" });
@@ -328,6 +329,7 @@ function CloudEnvironmentRowShell(props: {
onPress={(event) => {
event.stopPropagation();
}}
style={{ textDecorationStyle: "dotted" }}
>
{errorTraceId}
</Text>
@@ -38,6 +38,7 @@ export function ConnectionEnvironmentRow(props: {
const [url, setUrl] = useState(props.environment.displayUrl);
const mutedColor = useThemeColor("--color-icon-subtle");
const placeholderColor = useThemeColor("--color-placeholder");
const primaryFg = useThemeColor("--color-primary-foreground");
const dangerFg = useThemeColor("--color-danger-foreground");
const statusLabel = connectionStatusLabel(props.environment);
@@ -97,7 +98,7 @@ export function ConnectionEnvironmentRow(props: {
<Text
accessibilityHint="Copies the trace ID"
accessibilityRole="button"
className="underline decoration-dotted"
className="underline"
onLongPress={(event) => {
event.stopPropagation();
copyTextWithHaptic(statusTraceId, { target: "connection-trace-id" });
@@ -105,6 +106,7 @@ export function ConnectionEnvironmentRow(props: {
onPress={(event) => {
event.stopPropagation();
}}
style={{ textDecorationStyle: "dotted" }}
>
{statusTraceId}
</Text>
@@ -138,13 +140,17 @@ export function ConnectionEnvironmentRow(props: {
) : (
<>
<View className="gap-1.5">
<Text className="text-2xs font-t3-bold tracking-[0.8px] uppercase text-foreground-muted">
<Text
className="text-2xs font-t3-bold uppercase text-foreground-muted"
style={{ letterSpacing: 0.8 }}
>
Label
</Text>
<TextInput
autoCapitalize="words"
autoCorrect={false}
placeholder="My MacBook"
placeholderTextColor={placeholderColor}
value={label}
onChangeText={setLabel}
className="rounded-[14px] border border-input-border bg-input px-4 py-3 text-base text-foreground"
@@ -152,7 +158,10 @@ export function ConnectionEnvironmentRow(props: {
</View>
<View className="gap-1.5">
<Text className="text-2xs font-t3-bold tracking-[0.8px] uppercase text-foreground-muted">
<Text
className="text-2xs font-t3-bold uppercase text-foreground-muted"
style={{ letterSpacing: 0.8 }}
>
URL
</Text>
<TextInput
@@ -160,6 +169,7 @@ export function ConnectionEnvironmentRow(props: {
autoCorrect={false}
keyboardType="url"
placeholder="192.168.1.100:8080"
placeholderTextColor={placeholderColor}
value={url}
onChangeText={setUrl}
className="rounded-[14px] border border-input-border bg-input px-4 py-3 text-base text-foreground"
@@ -175,7 +185,10 @@ export function ConnectionEnvironmentRow(props: {
onPress={handleSave}
>
<SymbolView name="checkmark" size={13} tintColor={primaryFg} type="monochrome" />
<Text className="text-xs font-t3-bold tracking-[0.8px] uppercase text-primary-foreground">
<Text
className="text-xs font-t3-bold uppercase text-primary-foreground"
style={{ letterSpacing: 0.8 }}
>
Save
</Text>
</Pressable>
@@ -37,11 +37,33 @@ export function ConnectionSheetButton(props: {
}) {
const tone = props.tone ?? "secondary";
const primaryBg = useThemeColor("--color-primary");
const primaryFg = useThemeColor("--color-primary-foreground");
const dangerBg = useThemeColor("--color-danger");
const dangerBorderColor = useThemeColor("--color-danger-border");
const dangerFg = useThemeColor("--color-danger-foreground");
const secondaryBg = useThemeColor("--color-secondary");
const secondaryFg = useThemeColor("--color-secondary-foreground");
const borderColor = useThemeColor("--color-border");
const textColor = tone === "primary" ? primaryFg : tone === "danger" ? dangerFg : secondaryFg;
const colors =
tone === "primary"
? {
backgroundColor: primaryBg,
borderColor: "transparent",
textColor: primaryFg,
}
: tone === "danger"
? {
backgroundColor: dangerBg,
borderColor: dangerBorderColor,
textColor: dangerFg,
}
: {
backgroundColor: secondaryBg,
borderColor: borderColor,
textColor: secondaryFg,
};
const primaryShadow =
tone === "primary"
@@ -62,32 +84,28 @@ export function ConnectionSheetButton(props: {
props.compact
? "min-h-[42px] flex-row items-center justify-center gap-1.5 rounded-[14px] px-3.5 py-2.5"
: "min-h-[48px] flex-row items-center justify-center gap-2 rounded-[16px] px-4 py-3",
"disabled:opacity-50",
tone === "primary"
? "bg-primary"
: tone === "danger"
? "border border-danger-border bg-danger"
: "border border-border bg-secondary",
)}
disabled={props.disabled}
onPress={props.onPress}
style={primaryShadow}
style={[
{
backgroundColor: colors.backgroundColor,
borderWidth: tone === "primary" ? 0 : 1,
borderColor: colors.borderColor,
opacity: props.disabled ? 0.5 : 1,
},
primaryShadow,
]}
>
<SymbolView
name={props.icon}
size={props.compact ? 13 : 14}
tintColor={textColor}
tintColor={colors.textColor}
type="monochrome"
/>
<Text
className={cn(
"text-xs font-t3-bold tracking-[0.8px] uppercase",
tone === "primary"
? "text-primary-foreground"
: tone === "danger"
? "text-danger-foreground"
: "text-secondary-foreground",
)}
className="text-xs font-t3-bold uppercase"
style={{ color: colors.textColor, letterSpacing: 0.8 }}
>
{props.label}
</Text>
@@ -38,6 +38,7 @@ export function ConnectionsNewRouteScreen({
const [scannerLocked, setScannerLocked] = useState(false);
const headerIconColor = useThemeColor("--color-icon");
const placeholderColor = useThemeColor("--color-placeholder");
const connectDisabled = isSubmitting || hostInput.trim().length === 0;
@@ -157,7 +158,7 @@ export function ConnectionsNewRouteScreen({
<ScrollView
contentInsetAdjustmentBehavior="automatic"
showsVerticalScrollIndicator={false}
className="flex-1"
style={{ flex: 1 }}
contentInset={{ bottom: Math.max(insets.bottom, 18) + 18 }}
contentContainerStyle={{
paddingHorizontal: 20,
@@ -167,7 +168,10 @@ export function ConnectionsNewRouteScreen({
<View collapsable={false} className="gap-5">
{showScanner ? (
cameraPermission?.granted ? (
<View className="overflow-hidden rounded-[24px] border-continuous">
<View
className="overflow-hidden rounded-[24px]"
style={{ borderCurve: "continuous" }}
>
<CameraView
barcodeScannerSettings={{ barcodeTypes: ["qr"] }}
onBarcodeScanned={handleQrScan}
@@ -175,7 +179,10 @@ export function ConnectionsNewRouteScreen({
/>
</View>
) : (
<View className="items-center gap-3 rounded-[24px] border-continuous bg-card px-5 py-8">
<View
className="items-center gap-3 rounded-[24px] bg-card px-5 py-8"
style={{ borderCurve: "continuous" }}
>
<Text className="text-center text-sm leading-normal text-foreground-muted">
Camera permission is required to scan a QR code.
</Text>
@@ -193,7 +200,10 @@ export function ConnectionsNewRouteScreen({
) : (
<View collapsable={false} className="gap-4 rounded-[24px] bg-card p-4">
<View collapsable={false} className="gap-1.5">
<Text className="text-2xs font-t3-bold tracking-[0.8px] uppercase text-foreground-muted">
<Text
className="text-2xs font-t3-bold uppercase text-foreground-muted"
style={{ letterSpacing: 0.8 }}
>
Host
</Text>
<TextInput
@@ -201,6 +211,7 @@ export function ConnectionsNewRouteScreen({
autoCorrect={false}
keyboardType="url"
placeholder="192.168.1.100:8080"
placeholderTextColor={placeholderColor}
value={hostInput}
onChangeText={handleHostChange}
className="rounded-[14px] border border-input-border bg-input px-4 py-3.5 text-base text-foreground"
@@ -208,13 +219,17 @@ export function ConnectionsNewRouteScreen({
</View>
<View collapsable={false} className="gap-1.5">
<Text className="text-2xs font-t3-bold tracking-[0.8px] uppercase text-foreground-muted">
<Text
className="text-2xs font-t3-bold uppercase text-foreground-muted"
style={{ letterSpacing: 0.8 }}
>
Pairing code
</Text>
<TextInput
autoCapitalize="none"
autoCorrect={false}
placeholder="abc-123-xyz"
placeholderTextColor={placeholderColor}
value={codeInput}
onChangeText={handleCodeChange}
className="rounded-[14px] border border-input-border bg-input px-4 py-3.5 text-base text-foreground"
@@ -42,7 +42,7 @@ export function ConnectionsRouteScreen() {
<ScrollView
contentInsetAdjustmentBehavior="automatic"
showsVerticalScrollIndicator={false}
className="flex-1"
style={{ flex: 1 }}
contentInset={{ bottom: Math.max(insets.bottom, 18) + 18 }}
contentContainerStyle={{
paddingHorizontal: 20,
@@ -55,7 +55,10 @@ export function ConnectionsRouteScreen() {
<View
key={environment.environmentId}
collapsable={false}
className={cn(index !== 0 && "border-t border-border")}
style={{
borderTopWidth: index === 0 ? 0 : 1,
}}
className={cn(index !== 0 && "border-border")}
>
<ConnectionEnvironmentRow
environment={environment}
@@ -8,7 +8,6 @@ import {
import { RefreshControl, ScrollView, Text as NativeText, View } from "react-native";
import { tryOpenExternalUrl } from "../../lib/openExternalUrl";
import { useFontFamily } from "../../lib/useFontFamily";
import {
resolveMarkdownFontSizes,
resolveNativeMarkdownTypography,
@@ -46,15 +45,11 @@ function useMarkdownPreviewStyles(): MarkdownPreviewStyles {
const codeBackground = String(useThemeColor("--color-md-code-bg"));
const codeText = String(useThemeColor("--color-md-code-text"));
const horizontalRule = String(useThemeColor("--color-md-hr"));
const regularFontFamily = useFontFamily("regular");
const mediumFontFamily = useFontFamily("medium");
const boldFontFamily = useFontFamily("bold");
return useMemo(() => {
const renderers: CustomRenderers = {
link: ({ href, children }) => (
<NativeText
className="font-t3-medium"
onPress={() => {
if (href) {
void tryOpenExternalUrl(href, "markdown-link");
@@ -62,6 +57,7 @@ function useMarkdownPreviewStyles(): MarkdownPreviewStyles {
}}
style={{
color: link,
fontFamily: "DMSans_500Medium",
textDecorationLine: "none",
}}
>
@@ -90,21 +86,21 @@ function useMarkdownPreviewStyles(): MarkdownPreviewStyles {
styles: {
text: {
color: body,
fontFamily: regularFontFamily,
fontFamily: "DMSans_400Regular",
fontSize: markdownFontSizes.m,
lineHeight: markdownFontSizes.bodyLineHeight,
},
heading: {
color: strong,
fontFamily: boldFontFamily,
fontFamily: "DMSans_700Bold",
},
strong: {
color: strong,
fontFamily: boldFontFamily,
fontFamily: "DMSans_700Bold",
},
link: {
color: link,
fontFamily: mediumFontFamily,
fontFamily: "DMSans_500Medium",
},
blockquote: {
backgroundColor: blockquoteBackground,
@@ -145,9 +141,9 @@ function useMarkdownPreviewStyles(): MarkdownPreviewStyles {
fontSize: nativeMarkdownTypography.fontSize,
lineHeight: nativeMarkdownTypography.lineHeight,
headingFontSizes: nativeMarkdownTypography.headingFontSizes,
fontFamily: regularFontFamily,
headingFontFamily: boldFontFamily,
boldFontFamily,
fontFamily: "DMSans_400Regular",
headingFontFamily: "DMSans_700Bold",
boldFontFamily: "DMSans_700Bold",
},
};
}, [
@@ -159,11 +155,8 @@ function useMarkdownPreviewStyles(): MarkdownPreviewStyles {
horizontalRule,
link,
markdownFontSizes,
mediumFontFamily,
nativeMarkdownTypography,
regularFontFamily,
strong,
boldFontFamily,
]);
}
@@ -246,7 +246,7 @@ export function FileTreeBrowser(props: {
// flex-1 Views is ignored, which is why the tree rendered under the header with no blur.
return (
<FlatList
className="flex-1"
style={{ flex: 1 }}
data={visibleNodes}
keyExtractor={(item) => item.node.path}
contentInsetAdjustmentBehavior={Platform.OS === "ios" ? "automatic" : "never"}
@@ -224,7 +224,14 @@ function FilesToolbarBottomFade() {
pointerEvents="none"
accessibilityElementsHidden
importantForAccessibility="no-hide-descendants"
className="absolute inset-x-0 bottom-0 z-[1] h-28"
style={{
bottom: 0,
height: 112,
left: 0,
position: "absolute",
right: 0,
zIndex: 1,
}}
>
<Svg width="100%" height="100%">
<Defs>
+12 -42
View File
@@ -12,8 +12,6 @@ import type {
SidebarProjectGroupingMode,
SidebarThreadSortOrder,
} from "@t3tools/contracts";
import { useAtomSet, useAtomValue } from "@effect/atom-react";
import { AsyncResult } from "effect/unstable/reactivity";
import { useCallback, useMemo, useRef, useState } from "react";
import { ActivityIndicator, Platform, View } from "react-native";
import type { SwipeableMethods } from "react-native-gesture-handler/ReanimatedSwipeable";
@@ -24,7 +22,6 @@ import { EmptyState } from "../../components/EmptyState";
import type { WorkspaceState } from "../../state/workspaceModel";
import type { SavedRemoteConnection } from "../../lib/connection";
import { scopedProjectKey } from "../../lib/scopedEntities";
import { mobilePreferencesAtom, updateMobilePreferencesAtom } from "../../state/preferences";
import type { PendingNewTask } from "../../state/use-pending-new-tasks";
import {
PendingTaskListRow,
@@ -157,48 +154,21 @@ export function HomeScreen(props: HomeScreenProps) {
const [groupDisplayStates, setGroupDisplayStates] = useState<
ReadonlyMap<string, HomeGroupDisplayState>
>(() => new Map());
const preferencesResult = useAtomValue(mobilePreferencesAtom);
const savePreferences = useAtomSet(updateMobilePreferencesAtom);
const openSwipeableRef = useRef<SwipeableMethods | null>(null);
const listRef = useRef<LegendListRef | null>(null);
const insets = useSafeAreaInsets();
const accentColor = useThemeColor("--color-icon-muted");
const effectiveGroupDisplayStates = useMemo(() => {
const next = new Map(groupDisplayStates);
if (!AsyncResult.isSuccess(preferencesResult)) {
const updateGroupDisplay = useCallback((key: string, action: HomeGroupDisplayAction) => {
setGroupDisplayStates((previous) => {
const next = new Map(previous);
next.set(
key,
nextGroupDisplayState(previous.get(key) ?? DEFAULT_GROUP_DISPLAY_STATE, action),
);
return next;
}
for (const key of preferencesResult.value.collapsedProjectGroups ?? []) {
const existing = next.get(key);
next.set(key, {
...(existing ?? DEFAULT_GROUP_DISPLAY_STATE),
collapsed: true,
});
}
return next;
}, [groupDisplayStates, preferencesResult]);
const effectiveGroupDisplayStatesRef = useRef(effectiveGroupDisplayStates);
effectiveGroupDisplayStatesRef.current = effectiveGroupDisplayStates;
const updateGroupDisplay = useCallback(
(key: string, action: HomeGroupDisplayAction) => {
const next = new Map(effectiveGroupDisplayStatesRef.current);
next.set(key, nextGroupDisplayState(next.get(key) ?? DEFAULT_GROUP_DISPLAY_STATE, action));
effectiveGroupDisplayStatesRef.current = next;
setGroupDisplayStates(next);
if (action === "toggle-collapsed") {
const collapsedProjectGroups: string[] = [];
for (const [groupKey, state] of next) {
if (state.collapsed) {
collapsedProjectGroups.push(groupKey);
}
}
savePreferences({ collapsedProjectGroups });
}
},
[savePreferences],
);
});
}, []);
const handleSwipeableWillOpen = useCallback((methods: SwipeableMethods) => {
if (openSwipeableRef.current !== methods) {
@@ -249,10 +219,10 @@ export function HomeScreen(props: HomeScreenProps) {
() =>
buildHomeListLayout({
groups: projectGroups,
displayStates: effectiveGroupDisplayStates,
displayStates: groupDisplayStates,
showAllThreads: hasSearchQuery,
}),
[projectGroups, effectiveGroupDisplayStates, hasSearchQuery],
[projectGroups, groupDisplayStates, hasSearchQuery],
);
const projectCwdByKey = useMemo(() => {
@@ -412,7 +382,7 @@ export function HomeScreen(props: HomeScreenProps) {
{Platform.OS === "ios" ? null : <HomeTopContentSpacer topInset={insets.top} />}
{shouldShowConnectionStatus && Platform.OS === "ios" ? (
<View className="pb-4">
<View style={{ paddingBottom: 16 }}>
<WorkspaceConnectionStatus
state={props.catalogState}
onPress={props.onOpenEnvironments}
@@ -476,17 +476,16 @@ export function AdaptiveWorkspaceLayout(props: {
return (
<HomeListOptionsProvider>
<AdaptiveWorkspaceContext.Provider value={contextValue}>
<View testID="adaptive-workspace-layout" className="flex-1 flex-row">
<View testID="adaptive-workspace-layout" style={{ flex: 1, flexDirection: "row" }}>
{shouldRenderPrimarySidebar && layout.listPaneWidth !== null ? (
<Animated.View
className="self-stretch overflow-hidden"
accessibilityElementsHidden={!panes.primarySidebarVisible}
collapsable={false}
importantForAccessibility={
panes.primarySidebarVisible ? "auto" : "no-hide-descendants"
}
pointerEvents={panes.primarySidebarVisible ? "auto" : "none"}
style={sidebarAnimatedStyle}
style={[{ alignSelf: "stretch", overflow: "hidden" }, sidebarAnimatedStyle]}
>
<ThreadNavigationSidebar
width={layout.listPaneWidth}
@@ -502,7 +501,7 @@ export function AdaptiveWorkspaceLayout(props: {
/>
</Animated.View>
) : null}
<View className="flex-1 overflow-hidden bg-screen" collapsable={false}>
<View className="bg-screen" collapsable={false} style={{ flex: 1, overflow: "hidden" }}>
<View
collapsable={false}
style={
@@ -129,14 +129,13 @@ export function WorkspaceInspectorPane(props: {
) : null}
{inspectorSupported ? (
<Animated.View
className="shrink-0 overflow-hidden"
accessibilityElementsHidden={!inspectorVisible}
collapsable={false}
importantForAccessibility={inspectorVisible ? "auto" : "no-hide-descendants"}
pointerEvents={inspectorVisible ? "auto" : "none"}
style={inspectorStyle}
style={[{ flexShrink: 0, overflow: "hidden" }, inspectorStyle]}
>
<Animated.View className="flex-1" style={inspectorContentStyle}>
<Animated.View style={[{ flex: 1 }, inspectorContentStyle]}>
{props.renderInspector?.()}
</Animated.View>
</Animated.View>
@@ -69,7 +69,6 @@ export function WorkspacePaneDivider(props: WorkspacePaneDividerProps) {
return (
<GestureDetector gesture={resizeGesture}>
<Pressable
className="relative z-[100] -mx-[22px] w-11 self-stretch cursor-pointer justify-center"
accessibilityActions={[
{ name: "increment", label: "Make pane wider" },
{ name: "decrement", label: "Make pane narrower" },
@@ -83,6 +82,7 @@ export function WorkspacePaneDivider(props: WorkspacePaneDividerProps) {
onAccessibilityAction={handleAccessibilityAction}
onHoverIn={() => setHovered(true)}
onHoverOut={() => setHovered(false)}
style={styles.hitTarget}
>
<View style={[styles.line, (hovered || dragging) && styles.activeLine]} />
</Pressable>
@@ -91,6 +91,15 @@ export function WorkspacePaneDivider(props: WorkspacePaneDividerProps) {
}
const styles = StyleSheet.create({
hitTarget: {
alignSelf: "stretch",
cursor: "pointer",
justifyContent: "center",
marginHorizontal: -22,
position: "relative",
width: 44,
zIndex: 100,
},
line: {
alignSelf: "center",
backgroundColor:
@@ -31,7 +31,6 @@ import * as Arr from "effect/Array";
import * as Cause from "effect/Cause";
import * as Order from "effect/Order";
import { AsyncResult } from "effect/unstable/reactivity";
import { cn } from "../../lib/cn";
import { useProjects, useServerConfigs } from "../../state/entities";
import { filesystemEnvironment } from "../../state/filesystem";
@@ -100,7 +99,10 @@ function sourceFromParam(value: string | string[] | undefined): AddProjectRemote
function SectionTitle(props: { readonly children: string }) {
return (
<Text className="px-1 text-2xs font-t3-bold tracking-[0.7px] uppercase text-foreground-muted">
<Text
className="px-1 text-2xs font-t3-bold uppercase text-foreground-muted"
style={{ letterSpacing: 0.7 }}
>
{props.children}
</Text>
);
@@ -146,17 +148,19 @@ function ListRow(props: {
readonly right?: ReactNode;
readonly onPress?: () => void;
}) {
const borderColor = useThemeColor("--color-border-subtle");
const chevronColor = useThemeColor("--color-chevron");
return (
<Pressable
disabled={props.disabled}
onPress={props.onPress}
className={cn(
"bg-card px-3.5 py-2.5 active:opacity-70",
!props.isFirst && "border-t border-border-subtle",
props.disabled && "opacity-[0.45]",
)}
className="bg-card px-3.5 py-2.5 active:opacity-70"
style={{
opacity: props.disabled ? 0.45 : 1,
borderTopWidth: props.isFirst ? 0 : 1,
borderTopColor: borderColor,
}}
>
<View className="flex-row items-center gap-3">
<View
@@ -144,11 +144,15 @@ export function ReviewCommentComposerSheet(props: ReviewCommentComposerSheetProp
}
return (
<View className="flex-1">
<KeyboardAvoidingView automaticOffset behavior="padding" className="flex-1">
<View style={{ flex: 1 }}>
<KeyboardAvoidingView automaticOffset behavior="padding" style={{ flex: 1 }}>
<View
className="flex-1 px-5 pt-2"
style={{ paddingBottom: target ? 0 : Math.max(insets.bottom, 18) }}
style={{
flex: 1,
paddingHorizontal: 20,
paddingTop: 8,
paddingBottom: target ? 0 : Math.max(insets.bottom, 18),
}}
>
<View className="flex-row items-center justify-between py-2">
<Pressable
@@ -249,7 +253,8 @@ export function ReviewCommentComposerSheet(props: ReviewCommentComposerSheetProp
textAlignVertical="top"
value={commentText}
onChangeText={setCommentText}
className="h-full min-h-0 flex-1 border-0 bg-transparent px-0 py-0 font-sans text-base"
className="h-full flex-1 border-0 bg-transparent px-0 py-0 font-sans text-base"
style={{ flex: 1, minHeight: 0 }}
/>
</TextInputWrapper>
</View>
@@ -655,7 +655,7 @@ export function ReviewSheet(props: ReviewSheetProps) {
<View className="flex-1 bg-sheet">
{showConnectionNotice ? (
<View className="flex-1" style={{ paddingTop: topContentInset }}>
<View style={{ flex: 1, paddingTop: topContentInset }}>
<EnvironmentConnectionNotice
environmentLabel={environment.presentation?.entry.target.label ?? "Environment"}
connection={
@@ -722,7 +722,7 @@ export function ReviewSheet(props: ReviewSheetProps) {
bottom: Math.max(insets.bottom, 18) + 18,
}}
showsVerticalScrollIndicator={false}
className="flex-1"
style={{ flex: 1 }}
>
{listHeader}
{!selectedSection ? (
@@ -48,8 +48,8 @@ export function ReviewChangeBar(props: {
<View>
{Array.from({ length: Math.ceil(height / 2) }, (_, index) => (
<View key={index}>
<View className="h-px w-[5px] bg-rose-400" />
<View className="h-px" />
<View className="w-[5px] bg-rose-400" style={{ height: 1 }} />
<View style={{ height: 1 }} />
</View>
))}
</View>
@@ -13,10 +13,12 @@ export function SettingsAppearanceRouteScreen() {
<ScrollView
contentInsetAdjustmentBehavior="automatic"
showsVerticalScrollIndicator={false}
className="flex-1"
contentContainerClassName="gap-6 px-5 pt-4"
style={{ flex: 1 }}
contentContainerStyle={{
gap: 24,
paddingBottom: Math.max(insets.bottom, 18) + 18,
paddingHorizontal: 20,
paddingTop: 16,
}}
>
<TextAppearanceSection />
@@ -1,215 +0,0 @@
import { useAtomSet, useAtomValue } from "@effect/atom-react";
import { AsyncResult } from "effect/unstable/reactivity";
import { SymbolView } from "expo-symbols";
import { useMemo } from "react";
import { ActivityIndicator, Alert, Pressable, ScrollView, View } from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { AppText as Text } from "../../components/AppText";
import { useThemeColor } from "../../lib/useThemeColor";
import {
clearClientCacheAtom,
clientCacheSummaryAtom,
type EnvironmentClientCacheSummary,
} from "../../state/client-cache-state";
import { useSavedRemoteConnections } from "../../state/use-remote-environment-registry";
import { SettingsSection } from "./components/SettingsSection";
export function SettingsClientStorageRouteScreen() {
const insets = useSafeAreaInsets();
const iconColor = useThemeColor("--color-icon");
const dangerForegroundColor = useThemeColor("--color-danger-foreground");
const summaryResult = useAtomValue(clientCacheSummaryAtom);
const clearResult = useAtomValue(clearClientCacheAtom);
const clearCache = useAtomSet(clearClientCacheAtom);
const { savedConnectionsById } = useSavedRemoteConnections();
const isClearing = clearResult.waiting;
const summary = AsyncResult.isSuccess(summaryResult) ? summaryResult.value : null;
const environmentSummaries = useMemo(
() =>
[...(summary?.environments ?? [])].sort((left, right) => {
const leftLabel = savedConnectionsById[left.environmentId]?.environmentLabel ?? "";
const rightLabel = savedConnectionsById[right.environmentId]?.environmentLabel ?? "";
return leftLabel.localeCompare(rightLabel);
}),
[savedConnectionsById, summary?.environments],
);
const confirmClearEnvironment = (environment: EnvironmentClientCacheSummary) => {
const label =
savedConnectionsById[environment.environmentId]?.environmentLabel ??
environment.environmentId;
Alert.alert(
`Clear cache for ${label}?`,
"This removes offline threads, server metadata, and cached branches for this environment. The saved connection and credentials stay intact.",
[
{ text: "Cancel", style: "cancel" },
{
text: "Clear Cache",
style: "destructive",
onPress: () =>
clearCache({ type: "environment", environmentId: environment.environmentId }),
},
],
);
};
const confirmClearAll = () => {
Alert.alert(
"Clear all client caches?",
"This removes offline data for every environment. Connections, credentials, account data, and app preferences stay intact.",
[
{ text: "Cancel", style: "cancel" },
{
text: "Clear All Caches",
style: "destructive",
onPress: () => clearCache({ type: "all" }),
},
],
);
};
return (
<View collapsable={false} className="flex-1 bg-sheet">
<ScrollView
contentInsetAdjustmentBehavior="automatic"
contentInset={{ bottom: Math.max(insets.bottom, 18) }}
showsVerticalScrollIndicator={false}
className="flex-1"
contentContainerClassName="gap-6 px-5 pt-4 pb-[18px]"
>
<SettingsSection title="Environment caches">
{AsyncResult.isFailure(summaryResult) ? (
<View className="items-center gap-2 px-6 py-8">
<SymbolView
name="exclamationmark.triangle"
size={28}
tintColor={dangerForegroundColor}
type="monochrome"
weight="regular"
/>
<Text className="text-center text-base text-foreground">Storage unavailable</Text>
<Text className="text-center text-sm text-foreground-muted">
Restart the app and try again.
</Text>
</View>
) : !summary ? (
<View className="items-center gap-3 px-6 py-8">
<ActivityIndicator />
<Text className="text-center text-sm text-foreground-muted">
Inspecting cached data…
</Text>
</View>
) : environmentSummaries.length > 0 ? (
environmentSummaries.map((environment, index) => (
<CacheEnvironmentRow
key={environment.environmentId}
environment={environment}
environmentLabel={
savedConnectionsById[environment.environmentId]?.environmentLabel ??
environment.environmentId
}
disabled={isClearing}
first={index === 0}
onClear={() => confirmClearEnvironment(environment)}
/>
))
) : (
<View className="items-center gap-2 px-6 py-8">
<SymbolView
name="checkmark.circle"
size={28}
tintColor={iconColor}
type="monochrome"
weight="regular"
/>
<Text className="text-center text-base text-foreground">No cached data</Text>
<Text className="text-center text-sm text-foreground-muted">
Offline cache records will appear here after environments are used.
</Text>
</View>
)}
</SettingsSection>
<View className="gap-3">
<SettingsSection title="Actions">
<Pressable
accessibilityRole="button"
disabled={isClearing || !summary || summary.recordCount === 0}
onPress={confirmClearAll}
className="flex-row items-center gap-4 p-4 disabled:opacity-40"
>
<SymbolView
name="trash"
size={22}
tintColor={dangerForegroundColor}
type="monochrome"
weight="regular"
/>
<Text className="flex-1 text-lg tabular-nums text-danger-foreground">
{summary ? `Clear ${formatBytes(summary.payloadBytes)}` : "Clear caches"}
</Text>
{isClearing ? <ActivityIndicator color={dangerForegroundColor} /> : null}
</Pressable>
</SettingsSection>
<Text className="px-2 text-sm leading-normal text-foreground-muted">
Clearing caches never removes environment connections, credentials, account data, or
appearance preferences.
</Text>
{AsyncResult.isFailure(summaryResult) || AsyncResult.isFailure(clearResult) ? (
<Text selectable className="px-2 text-sm text-danger-foreground">
Client storage is temporarily unavailable. Try again after restarting the app.
</Text>
) : null}
</View>
</ScrollView>
</View>
);
}
function CacheEnvironmentRow(props: {
readonly environment: EnvironmentClientCacheSummary;
readonly environmentLabel: string;
readonly disabled: boolean;
readonly first: boolean;
readonly onClear: () => void;
}) {
const iconColor = useThemeColor("--color-icon");
return (
<View
className={
props.first
? "flex-row items-center gap-3 p-4"
: "border-t border-border flex-row items-center gap-3 p-4"
}
>
<SymbolView
name="desktopcomputer"
size={22}
tintColor={iconColor}
type="monochrome"
weight="regular"
/>
<Text className="min-w-0 flex-1 text-base text-foreground" numberOfLines={1}>
{props.environmentLabel}
</Text>
<Pressable
accessibilityLabel={`Clear cache for ${props.environmentLabel}`}
accessibilityRole="button"
disabled={props.disabled}
onPress={props.onClear}
className="rounded-full px-3 py-2 disabled:opacity-40"
>
<Text className="font-t3-medium tabular-nums text-danger-foreground" numberOfLines={1}>
Clear {formatBytes(props.environment.payloadBytes)}
</Text>
</Pressable>
</View>
);
}
function formatBytes(bytes: number): string {
if (bytes < 1024) return `${bytes} B`;
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(bytes < 10 * 1024 ? 1 : 0)} KB`;
return `${(bytes / (1024 * 1024)).toFixed(bytes < 10 * 1024 * 1024 ? 1 : 0)} MB`;
}
@@ -50,10 +50,11 @@ export function SettingsEnvironmentsRouteScreen() {
<ScrollView
contentInsetAdjustmentBehavior="automatic"
showsVerticalScrollIndicator={false}
className="flex-1"
contentContainerClassName="px-5 pt-4"
style={{ flex: 1 }}
contentContainerStyle={{
paddingBottom: Math.max(insets.bottom, 18) + 18,
paddingHorizontal: 20,
paddingTop: 16,
}}
>
{hasLocalEnvironments ? (
@@ -62,7 +63,10 @@ export function SettingsEnvironmentsRouteScreen() {
<View
key={environment.environmentId}
collapsable={false}
className={cn(index !== 0 && "border-t border-border")}
style={{
borderTopWidth: index === 0 ? 0 : 1,
}}
className={cn(index !== 0 && "border-border")}
>
<ConnectionEnvironmentRow
environment={environment}
@@ -1,5 +1,4 @@
import { useAuth, useUser } from "@clerk/expo";
import { useAtomSet, useAtomValue } from "@effect/atom-react";
import Constants from "expo-constants";
import * as Notifications from "expo-notifications";
import * as Updates from "expo-updates";
@@ -7,7 +6,6 @@ import { useNavigation } from "@react-navigation/native";
import { NativeStackScreenOptions } from "../../native/StackHeader";
import { SymbolView } from "expo-symbols";
import * as Effect from "effect/Effect";
import { AsyncResult } from "effect/unstable/reactivity";
import { useCallback, useEffect, useMemo, useState, useSyncExternalStore } from "react";
import { Alert, Linking, Platform, ScrollView, View } from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context";
@@ -33,8 +31,8 @@ import { hasCloudPublicConfig, resolveRelayClerkTokenOptions } from "../cloud/pu
import { withNativeGlassHeaderItem } from "../layout/native-glass-header-items";
import { WorkspaceSidebarToolbar } from "../layout/workspace-sidebar-toolbar";
import { runtime } from "../../lib/runtime";
import { loadPreferences } from "../../lib/storage";
import { useThemeColor } from "../../lib/useThemeColor";
import { mobilePreferencesAtom, updateMobilePreferencesAtom } from "../../state/preferences";
import { useSavedRemoteConnections } from "../../state/use-remote-environment-registry";
import { SettingsRow } from "./components/SettingsRow";
import { SettingsSection } from "./components/SettingsSection";
@@ -94,10 +92,12 @@ function LocalSettingsRouteScreen() {
<ScrollView
contentInsetAdjustmentBehavior="automatic"
showsVerticalScrollIndicator={false}
className="flex-1"
contentContainerClassName="gap-6 px-5 pt-4"
style={{ flex: 1 }}
contentContainerStyle={{
gap: 24,
paddingBottom: Math.max(insets.bottom, 18) + 18,
paddingHorizontal: 20,
paddingTop: 16,
}}
>
<SettingsSection title="Configuration">
@@ -122,8 +122,6 @@ function LocalSettingsRouteScreen() {
}
function ConfiguredSettingsRouteScreen() {
const preferencesResult = useAtomValue(mobilePreferencesAtom);
const savePreferences = useAtomSet(updateMobilePreferencesAtom);
const insets = useSafeAreaInsets();
const navigation = useNavigation();
const { expand: expandClerkSheet } = useClerkSettingsSheetDetent();
@@ -133,9 +131,6 @@ function ConfiguredSettingsRouteScreen() {
const [notificationStatus, setNotificationStatus] = useState<NotificationStatus>("checking");
const [liveActivityStatus, setLiveActivityStatus] = useState<LiveActivityStatus>("checking");
const deviceRegistered = useDeviceRegistered();
const liveActivitiesPreferenceEnabled = AsyncResult.isSuccess(preferencesResult)
? preferencesResult.value.liveActivitiesEnabled !== false
: true;
const connections = useMemo(() => Object.values(savedConnectionsById), [savedConnectionsById]);
const environmentCount = connections.length;
@@ -172,19 +167,16 @@ function ConfiguredSettingsRouteScreen() {
setLiveActivityStatus("signed-out");
return;
}
if (!AsyncResult.isSuccess(preferencesResult)) {
if (AsyncResult.isFailure(preferencesResult)) {
reportAtomCommandResult(preferencesResult, { label: "live activity preference load" });
void (async () => {
const result = await settlePromise(() => loadPreferences());
if (result._tag === "Failure") {
reportAtomCommandResult(result, { label: "live activity preference load" });
setLiveActivityStatus("enabled");
} else {
setLiveActivityStatus("checking");
return;
}
return;
}
setLiveActivityStatus(
preferencesResult.value.liveActivitiesEnabled === false ? "disabled" : "enabled",
);
}, [isLoaded, isSignedIn, preferencesResult]);
setLiveActivityStatus(result.value.liveActivitiesEnabled === false ? "disabled" : "enabled");
})();
}, [isLoaded, isSignedIn]);
const requestNotifications = useCallback(async () => {
const result = await settleAsyncResult(() =>
@@ -287,7 +279,6 @@ function ConfiguredSettingsRouteScreen() {
runtime.runPromiseExit(
setLiveActivityUpdatesEnabled({
enabled: true,
previousEnabled: liveActivitiesPreferenceEnabled,
clerkToken: tokenResult.value,
connections,
}),
@@ -305,7 +296,6 @@ function ConfiguredSettingsRouteScreen() {
return;
}
savePreferences({ liveActivitiesEnabled: true });
refreshManagedRelayEnvironments();
setLiveActivityStatus("enabled");
// The environment link can succeed while this device's own registration
@@ -324,15 +314,7 @@ function ConfiguredSettingsRouteScreen() {
"This device could not be registered with T3 Connect, so Live Activities won't appear yet. They'll start once registration succeeds.",
);
}
}, [
connections,
environmentCount,
getToken,
isSignedIn,
liveActivitiesPreferenceEnabled,
promptSignIn,
savePreferences,
]);
}, [connections, environmentCount, getToken, isSignedIn, promptSignIn]);
const handleDeviceNotificationsChange = useCallback(
(enabled: boolean) => {
@@ -376,20 +358,17 @@ function ConfiguredSettingsRouteScreen() {
runtime.runPromiseExit(
setLiveActivityUpdatesEnabled({
enabled: false,
previousEnabled: liveActivitiesPreferenceEnabled,
clerkToken: token,
connections,
}),
),
);
if (updateResult._tag === "Failure") {
setLiveActivityStatus("enabled");
reportAtomCommandResult(updateResult, {
label: "live activity disable",
});
return;
}
savePreferences({ liveActivitiesEnabled: false });
refreshManagedRelayEnvironments();
})();
return;
@@ -402,15 +381,7 @@ function ConfiguredSettingsRouteScreen() {
void linkEnvironments();
},
[
connections,
getToken,
isSignedIn,
linkEnvironments,
liveActivitiesPreferenceEnabled,
promptSignIn,
savePreferences,
],
[connections, getToken, isSignedIn, linkEnvironments, promptSignIn],
);
const openAccount = useCallback(() => {
@@ -428,10 +399,12 @@ function ConfiguredSettingsRouteScreen() {
<ScrollView
contentInsetAdjustmentBehavior="automatic"
showsVerticalScrollIndicator={false}
className="flex-1"
contentContainerClassName="gap-6 px-5 pt-4"
style={{ flex: 1 }}
contentContainerStyle={{
gap: 24,
paddingBottom: Math.max(insets.bottom, 18) + 18,
paddingHorizontal: 20,
paddingTop: 16,
}}
>
<View className="gap-3">
@@ -515,7 +488,6 @@ function AppSettingsSection() {
return (
<SettingsSection title="App">
<SettingsRow icon="internaldrive" label="Client Storage" target="SettingsClientStorage" />
<View className="flex-row items-center gap-4 p-4">
<SymbolView
name="info.circle"
@@ -1,7 +1,12 @@
import { createContext, use, useCallback, useEffect, useMemo, type ReactNode } from "react";
import { useAtomSet, useAtomValue } from "@effect/atom-react";
import { AsyncResult } from "effect/unstable/reactivity";
import {
createContext,
useCallback,
useContext,
useEffect,
useMemo,
useState,
type ReactNode,
} from "react";
import { Uniwind } from "uniwind";
@@ -12,7 +17,7 @@ import {
type AppearancePreferences,
type ResolvedAppearance,
} from "../../../lib/appearancePreferences";
import { mobilePreferencesAtom, updateMobilePreferencesAtom } from "../../../state/preferences";
import { loadPreferences, savePreferencesPatch } from "../../../lib/storage";
import { cacheTerminalFontSize } from "../../terminal/terminalUiState";
interface AppearancePreferencesContextValue {
@@ -47,28 +52,55 @@ function applyTextScaleVariables(baseFontSize: number) {
}
export function AppearancePreferencesProvider(props: { readonly children: ReactNode }) {
const preferencesResult = useAtomValue(mobilePreferencesAtom);
const savePreferences = useAtomSet(updateMobilePreferencesAtom);
const preferences = useMemo(
() =>
resolveAppearancePreferences(
AsyncResult.isSuccess(preferencesResult) ? preferencesResult.value : null,
),
[preferencesResult],
const [preferences, setPreferences] = useState<AppearancePreferences>(() =>
resolveAppearancePreferences(null),
);
const isReady = AsyncResult.isSuccess(preferencesResult) && !preferencesResult.waiting;
const [isReady, setIsReady] = useState(false);
useEffect(() => {
let cancelled = false;
void loadPreferences()
.then((stored) => {
if (cancelled) {
return;
}
const resolved = resolveAppearancePreferences(stored);
setPreferences(resolved);
cacheTerminalFontSize(resolveAppearance(resolved).terminalFontSize);
setIsReady(true);
})
.catch(() => {
if (cancelled) {
return;
}
setIsReady(true);
});
return () => {
cancelled = true;
};
}, []);
useEffect(() => {
applyTextScaleVariables(preferences.baseFontSize);
cacheTerminalFontSize(resolveAppearance(preferences).terminalFontSize);
}, [preferences]);
}, [preferences.baseFontSize]);
const updatePreferences = useCallback(
(patch: Partial<AppearancePreferences>) => {
savePreferences(patch);
},
[savePreferences],
);
const updatePreferences = useCallback((patch: Partial<AppearancePreferences>) => {
setPreferences((current) => {
const next = resolveAppearancePreferences({ ...current, ...patch });
cacheTerminalFontSize(resolveAppearance(next).terminalFontSize);
void savePreferencesPatch({
baseFontSize: next.baseFontSize,
terminalFontSize: next.terminalFontSize,
codeFontSize: next.codeFontSize,
codeWordBreak: next.codeWordBreak,
}).catch(() => undefined);
return next;
});
}, []);
const setBaseFontSize = useCallback(
(value: number) => {
@@ -118,7 +150,7 @@ export function AppearancePreferencesProvider(props: { readonly children: ReactN
}
export function useAppearancePreferences(): AppearancePreferencesContextValue {
const context = use(AppearancePreferencesContext);
const context = useContext(AppearancePreferencesContext);
if (!context) {
throw new Error("useAppearancePreferences must be used within AppearancePreferencesProvider");
}
@@ -136,7 +136,7 @@ export function FontSizeSliderRow(props: {
};
return (
<View className={disabled ? "gap-1 p-4 opacity-[0.45]" : "gap-1 p-4"}>
<View className="gap-1 p-4" style={{ opacity: disabled ? 0.45 : 1 }}>
<View className="flex-row items-center gap-4">
<SymbolView
name={props.icon}
@@ -22,11 +22,8 @@ export function SettingsRow(props: {
const chevron = useThemeColor("--color-chevron");
const content = (
<View
className={
props.disabled
? "flex-row items-center gap-4 p-4 opacity-[0.45]"
: "flex-row items-center gap-4 p-4"
}
className="flex-row items-center gap-4 p-4"
style={{ opacity: props.disabled ? 0.45 : 1 }}
>
<SymbolView name={props.icon} size={22} tintColor={icon} type="monochrome" weight="regular" />
<Text className="shrink-0 text-lg text-foreground" numberOfLines={1}>
@@ -7,7 +7,10 @@ export function SettingsSection(props: { readonly title: string; readonly childr
return (
<View className="gap-2">
<Text className="px-2 text-sm font-t3-medium text-foreground-muted">{props.title}</Text>
<View className="overflow-hidden rounded-[28px] border-continuous bg-card">
<View
className="overflow-hidden rounded-[28px] bg-card"
style={{ borderCurve: "continuous" }}
>
{props.children}
</View>
</View>
@@ -20,11 +20,8 @@ export function SettingsSwitchRow(props: {
return (
<View
className={
props.disabled
? "flex-row items-center gap-4 p-4 opacity-[0.45]"
: "flex-row items-center gap-4 p-4"
}
className="flex-row items-center gap-4 p-4"
style={{ opacity: props.disabled ? 0.45 : 1 }}
>
<SymbolView name={props.icon} size={22} tintColor={icon} type="monochrome" weight="regular" />
<Text className="flex-1 text-lg text-foreground">{props.label}</Text>
@@ -1,5 +1 @@
export type SettingsSheetTarget =
| "SettingsEnvironments"
| "SettingsArchive"
| "SettingsAppearance"
| "SettingsClientStorage";
export type SettingsSheetTarget = "SettingsEnvironments" | "SettingsArchive" | "SettingsAppearance";
@@ -82,9 +82,9 @@ const FallbackTerminalSurface = memo(function FallbackTerminalSurface(props: Ter
return (
<View
className="flex-1"
style={[
{
flex: 1,
backgroundColor: theme.background,
borderRadius: 8,
overflow: "hidden",
@@ -93,18 +93,19 @@ const FallbackTerminalSurface = memo(function FallbackTerminalSurface(props: Ter
]}
onLayout={handleLayout}
>
<View className="flex-1 px-2.5 py-2">
<View style={{ flex: 1, paddingHorizontal: 10, paddingVertical: 8 }}>
<Text
className="pb-2 text-2xs"
className="text-2xs"
style={{
color: theme.mutedForeground,
paddingBottom: 8,
}}
>
{statusLabel}
</Text>
<ScrollView
className="flex-1"
contentContainerClassName="pb-3"
style={{ flex: 1 }}
contentContainerStyle={{ paddingBottom: 12 }}
showsVerticalScrollIndicator={false}
>
<Text
@@ -121,9 +122,13 @@ const FallbackTerminalSurface = memo(function FallbackTerminalSurface(props: Ter
</ScrollView>
</View>
<View
className="flex-row items-center gap-2 border-t p-2"
style={{
borderTopWidth: 1,
borderTopColor: theme.border,
flexDirection: "row",
alignItems: "center",
gap: 8,
padding: 8,
}}
>
<TextInput
@@ -160,7 +165,13 @@ const FallbackTerminalSurface = memo(function FallbackTerminalSurface(props: Ter
})}
onPress={() => props.onInput("\u0003")}
>
<Text className="text-2xs font-t3-bold" style={{ color: theme.foreground }}>
<Text
className="text-2xs"
style={{
color: theme.foreground,
fontFamily: "DMSans_700Bold",
}}
>
Ctrl-C
</Text>
</Pressable>
@@ -929,7 +929,7 @@ export function ThreadTerminalRouteScreen(props: ThreadTerminalRouteScreenProps)
</NativeHeaderToolbar>
) : null}
<View className="flex-1" style={{ backgroundColor: terminalTheme.background }}>
<View style={{ flex: 1, backgroundColor: terminalTheme.background }}>
{!isEnvironmentReady ? (
<EnvironmentConnectionNotice
environmentLabel={
@@ -949,7 +949,7 @@ export function ThreadTerminalRouteScreen(props: ThreadTerminalRouteScreenProps)
/>
) : (
<>
<View className="flex-1" style={{ paddingBottom: terminalBottomInset }}>
<View style={{ flex: 1, paddingBottom: terminalBottomInset }}>
<TerminalSurface
buffer={terminalSurfaceBuffer}
fontSize={fontSize}
@@ -968,10 +968,10 @@ export function ThreadTerminalRouteScreen(props: ThreadTerminalRouteScreenProps)
offset={{ closed: 0, opened: 0 }}
>
<View
className="border-t"
style={{
backgroundColor: terminalTheme.background,
borderTopColor: terminalTheme.border,
borderTopWidth: 1,
minHeight: TERMINAL_ACCESSORY_HEIGHT,
}}
>
@@ -154,11 +154,23 @@ const CommandRow = memo(function CommandRow(props: {
) : iconName ? (
<SymbolView name={iconName} size={14} tintColor={iconColor} type="monochrome" />
) : null}
<Text className="shrink-0 text-base font-t3-medium text-foreground" numberOfLines={1}>
<Text
className="text-base font-t3-medium text-foreground"
numberOfLines={1}
style={{ flexShrink: 0 }}
>
{props.item.label}
</Text>
{props.item.description ? (
<Text className="min-w-0 flex-1 text-xs text-zinc-400" numberOfLines={1}>
<Text
className="text-xs"
numberOfLines={1}
style={{
flex: 1,
minWidth: 0,
color: "#a1a1aa",
}}
>
{props.item.description}
</Text>
) : null}
@@ -175,15 +187,18 @@ export const ComposerCommandPopover = memo(function ComposerCommandPopover(
return (
<PopoverSurface isDarkMode={isDarkMode}>
{label ? (
<View className="px-3.5 pt-2.5 pb-1">
<Text className="text-3xs font-t3-bold tracking-[0.8px] uppercase text-foreground-muted">
<View style={{ paddingHorizontal: 14, paddingTop: 10, paddingBottom: 4 }}>
<Text
className="text-3xs font-t3-bold text-foreground-muted"
style={{ letterSpacing: 0.8, textTransform: "uppercase" }}
>
{label}
</Text>
</View>
) : null}
{props.items.length > 0 ? (
<ScrollView
className="max-h-[180px]"
style={{ maxHeight: 180 }}
keyboardShouldPersistTaps="always"
showsVerticalScrollIndicator={false}
>
@@ -197,7 +212,7 @@ export const ComposerCommandPopover = memo(function ComposerCommandPopover(
))}
</ScrollView>
) : (
<View className="px-3.5 py-2.5">
<View style={{ paddingHorizontal: 14, paddingVertical: 10 }}>
<Text className="text-xs text-foreground-tertiary">
{emptyText(props.triggerKind, props.isLoading)}
</Text>
@@ -47,8 +47,7 @@ export function GitActionProgressOverlay(props: {
<Animated.View
entering={FadeIn.duration(200)}
exiting={FadeOut.duration(150)}
className="absolute inset-x-3 z-[100]"
style={{ top: insets.top + 48 }}
style={{ top: insets.top + 48, left: 12, right: 12, position: "absolute", zIndex: 100 }}
pointerEvents="box-none"
>
<Pressable onPress={handlePress}>
@@ -4,6 +4,7 @@ import { useCallback, useEffect, useMemo, useRef } from "react";
import { Alert, InteractionManager, View, useColorScheme } from "react-native";
import { KeyboardAvoidingView, useKeyboardState } from "react-native-keyboard-controller";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { useThemeColor } from "../../lib/useThemeColor";
import { EnvironmentId } from "@t3tools/contracts";
import {
@@ -111,6 +112,7 @@ export function NewTaskDraftScreen(props: {
};
}, [props.pendingTaskId, cancelEditingPendingTask]);
const borderColor = useThemeColor("--color-border");
const headlineText = useScaledTextRole("headline");
const sheetFadeOpaque = colorScheme === "dark" ? "rgba(14,14,14,0.98)" : "rgba(242,242,247,0.98)";
const sheetFadeTransparent = colorScheme === "dark" ? "rgba(14,14,14,0)" : "rgba(242,242,247,0)";
@@ -598,8 +600,8 @@ export function NewTaskDraftScreen(props: {
<View className="flex-1 bg-sheet">
<NativeStackScreenOptions options={{ title: selectedProject.title }} />
<KeyboardAvoidingView automaticOffset behavior="padding" className="flex-1">
<View className="min-h-0 flex-1 px-5 pt-2">
<KeyboardAvoidingView automaticOffset behavior="padding" style={{ flex: 1 }}>
<View style={{ flex: 1, minHeight: 0, paddingHorizontal: 20, paddingTop: 8 }}>
<ComposerEditor
ref={promptInputRef}
autoFocus
@@ -615,9 +617,15 @@ export function NewTaskDraftScreen(props: {
/>
</View>
<View className="border-t border-border" style={{ paddingBottom: controlsBottomPadding }}>
<View
style={{
borderTopWidth: 1,
borderTopColor: borderColor,
paddingBottom: controlsBottomPadding,
}}
>
{flow.attachments.length > 0 ? (
<View className="px-4 pt-3">
<View style={{ paddingHorizontal: 16, paddingTop: 12 }}>
<ComposerAttachmentStrip
attachments={flow.attachments}
onRemove={flow.removeAttachment}
@@ -6,7 +6,6 @@ import { useMemo } from "react";
import { ActivityIndicator, Pressable, ScrollView, View } from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { useThemeColor } from "../../lib/useThemeColor";
import { cn } from "../../lib/cn";
import { AppText as Text } from "../../components/AppText";
import { ProjectFavicon } from "../../components/ProjectFavicon";
@@ -80,6 +79,7 @@ export function NewTaskRouteScreen() {
const insets = useSafeAreaInsets();
const chevronColor = useThemeColor("--color-chevron");
const accentColor = useThemeColor("--color-icon-muted");
const borderSubtleColor = useThemeColor("--color-border-subtle");
const repositoryGroups = useMemo(
() => groupProjectsByRepository({ projects, threads }),
[projects, threads],
@@ -130,7 +130,7 @@ export function NewTaskRouteScreen() {
<ScrollView
contentInsetAdjustmentBehavior="automatic"
showsVerticalScrollIndicator={false}
className="flex-1"
style={{ flex: 1 }}
contentInset={{ bottom: Math.max(insets.bottom, 18) + 18 }}
contentContainerStyle={{
paddingHorizontal: 20,
@@ -175,6 +175,7 @@ export function NewTaskRouteScreen() {
return (
<Pressable
key={item.key}
className="bg-card"
onPress={() =>
navigation.navigate("NewTaskSheet", {
screen: "NewTaskDraft",
@@ -185,12 +186,16 @@ export function NewTaskRouteScreen() {
},
})
}
className={cn(
"bg-card px-4 py-3.5",
!isFirst && "border-t border-border-subtle",
isFirst && "rounded-t-[24px]",
isLast && "rounded-b-[24px]",
)}
style={{
paddingHorizontal: 16,
paddingVertical: 14,
borderTopWidth: isFirst ? 0 : 1,
borderTopColor: borderSubtleColor,
borderTopLeftRadius: isFirst ? 24 : 0,
borderTopRightRadius: isFirst ? 24 : 0,
borderBottomLeftRadius: isLast ? 24 : 0,
borderBottomRightRadius: isLast ? 24 : 0,
}}
>
<View className="flex-row items-center justify-between gap-3">
<View className="h-7 w-7 items-center justify-center">
@@ -688,9 +688,9 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
return (
<Animated.View
className="px-4"
layout={COMPOSER_LAYOUT_TRANSITION}
style={{
paddingHorizontal: 16,
paddingTop: isExpanded ? 8 : 6,
paddingBottom: (props.bottomInset ?? 0) + (isExpanded ? 8 : 6),
experimental_backgroundImage: isDarkMode
@@ -699,12 +699,21 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
}}
>
<Animated.View
className="relative w-full self-center"
className="w-full"
layout={COMPOSER_LAYOUT_TRANSITION}
style={{ maxWidth: props.contentMaxWidth }}
style={{ alignSelf: "center", maxWidth: props.contentMaxWidth, position: "relative" }}
>
{composerTrigger && composerMenuItems.length > 0 ? (
<View className="absolute inset-x-0 bottom-full z-10 mb-2">
<View
style={{
position: "absolute",
bottom: "100%",
left: 0,
right: 0,
marginBottom: 8,
zIndex: 10,
}}
>
<ComposerCommandPopover
items={composerMenuItems}
triggerKind={composerTrigger.kind}
@@ -745,9 +754,9 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
{/* Attachment strip — inside the card, above the text input */}
{isExpanded ? (
<Animated.View
className={props.draftAttachments.length > 0 ? "pb-2.5" : undefined}
entering={FadeIn.duration(160)}
exiting={FadeOut.duration(120)}
style={{ paddingBottom: props.draftAttachments.length > 0 ? 10 : 0 }}
>
<ComposerAttachmentStrip
attachments={props.draftAttachments}
@@ -757,7 +766,7 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
</Animated.View>
) : null}
<View className={isExpanded ? undefined : "min-w-0 flex-1"}>
<View style={isExpanded ? undefined : { flex: 1, minWidth: 0 }}>
<ComposerEditor
ref={inputRef}
multiline
@@ -788,22 +797,37 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
textStyle={{
...bodyText,
color: foregroundColor,
fontFamily: "DMSans_400Regular",
}}
/>
</View>
{!isExpanded && props.draftAttachments.length > 0 ? (
<View className="flex-row gap-1 pl-1">
<View style={{ flexDirection: "row", gap: 4, paddingLeft: 4 }}>
{props.draftAttachments.slice(0, 3).map((image) => (
<Pressable key={image.id} onPress={() => onPressImage(image.previewUri)}>
<Image
source={{ uri: image.previewUri }}
className="size-[30px] rounded-lg bg-subtle"
className="bg-subtle"
style={{
width: 30,
height: 30,
borderRadius: 8,
}}
resizeMode="cover"
/>
</Pressable>
))}
{props.draftAttachments.length > 3 ? (
<View className="size-[30px] items-center justify-center rounded-lg bg-subtle-strong">
<View
className="bg-subtle-strong"
style={{
width: 30,
height: 30,
borderRadius: 8,
alignItems: "center",
justifyContent: "center",
}}
>
<Text className="text-foreground-muted text-2xs font-t3-bold">
+{props.draftAttachments.length - 3}
</Text>
@@ -886,7 +910,7 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
{/* Queue count */}
{props.queueCount > 0 ? (
<Animated.View entering={FadeIn.duration(180)} exiting={FadeOut.duration(120)}>
<Text className="pt-2 text-xs text-foreground-muted">
<Text className="text-xs text-foreground-muted" style={{ paddingTop: 8 }}>
{props.queueCount} queued message{props.queueCount === 1 ? "" : "s"} will send
automatically.
</Text>
@@ -193,9 +193,10 @@ const WorkingDurationPill = memo(function WorkingDurationPill(props: {
return (
<Animated.View
className="shrink-0 px-4 pb-2 pt-2"
className="px-4 pb-2 pt-2"
entering={FadeInDown.duration(200)}
exiting={FadeOut.duration(140)}
style={{ flexShrink: 0 }}
>
<View className="self-start rounded-full border border-neutral-200/80 bg-neutral-50/90 px-3 py-2 dark:border-white/[0.08] dark:bg-white/[0.04]">
<View className="flex-row items-center gap-2">
@@ -389,7 +390,7 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
<View className="flex-1">
{showContent ? (
<View
className="flex-1"
style={{ flex: 1 }}
onTouchStart={handleFeedTouchStart}
onTouchMove={handleFeedTouchMove}
onTouchEnd={handleFeedTouchEnd}
@@ -418,7 +419,7 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
/>
</View>
) : (
<View className="flex-1" />
<View style={{ flex: 1 }} />
)}
{/* Floating composer — sticks to keyboard via KeyboardStickyView */}
@@ -430,11 +431,10 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
{/* No paddingTop here: the overlay's measured height becomes the
list's bottom inset, so any padding above the pill/composer
pushes the resting content floor up by the same amount. */}
<View ref={composerOverlayRef} onLayout={onComposerLayout} className="w-full">
<View ref={composerOverlayRef} onLayout={onComposerLayout} style={{ width: "100%" }}>
<Animated.View
className="w-full self-center"
layout={LinearTransition.duration(220)}
style={{ maxWidth: contentMaxWidth }}
style={{ alignSelf: "center", maxWidth: contentMaxWidth, width: "100%" }}
>
{props.activeWorkStartedAt ? (
<WorkingDurationPill startedAt={props.activeWorkStartedAt} />
@@ -442,9 +442,10 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
{props.activePendingApproval || props.activePendingUserInput ? (
<Animated.View
className="shrink-0 gap-3 px-4 pb-3"
className="gap-3 px-4 pb-3"
entering={FadeInDown.duration(220)}
exiting={FadeOut.duration(140)}
style={{ flexShrink: 0 }}
>
{props.activePendingApproval ? (
<PendingApprovalCard
+53 -44
View File
@@ -52,7 +52,6 @@ import Animated, {
type SharedValue,
} from "react-native-reanimated";
import { useThemeColor } from "../../lib/useThemeColor";
import { useFontFamily } from "../../lib/useFontFamily";
import { copyTextWithHaptic } from "../../lib/copyTextWithHaptic";
import {
hasNativeSelectableMarkdownText,
@@ -235,6 +234,10 @@ const markdownLinkStyles = StyleSheet.create({
favicon: {
borderRadius: 3,
},
file: {
fontFamily: "DMSans_700Bold",
fontWeight: "700",
},
});
const MarkdownExternalLink = memo(function MarkdownExternalLink(props: {
@@ -247,12 +250,12 @@ const MarkdownExternalLink = memo(function MarkdownExternalLink(props: {
return (
<NativeText
className="font-sans"
onPress={() => {
void Linking.openURL(props.href);
}}
style={{
color: props.color,
fontFamily: "DMSans_400Regular",
textDecorationLine: "none",
}}
>
@@ -311,8 +314,6 @@ function useMarkdownStyles(onLinkPress: (href: string) => void): MarkdownStyleSe
);
const colors = MARKDOWN_COLORS[colorScheme === "dark" ? "dark" : "light"];
const inlineSkillForeground = String(useThemeColor("--color-inline-skill-foreground"));
const regularFontFamily = useFontFamily("regular");
const boldFontFamily = useFontFamily("bold");
return useMemo(() => {
const markdownBodyColor = colors.body;
@@ -364,8 +365,8 @@ function useMarkdownStyles(onLinkPress: (href: string) => void): MarkdownStyleSe
h6: markdownFontSizes.h6,
},
fontFamilies: {
regular: regularFontFamily,
heading: boldFontFamily,
regular: "DMSans_400Regular",
heading: "DMSans_700Bold",
mono: "ui-monospace",
},
headingWeight: "700",
@@ -387,7 +388,7 @@ function useMarkdownStyles(onLinkPress: (href: string) => void): MarkdownStyleSe
bold: {
fontWeight: "700",
color: markdownStrongColor,
fontFamily: boldFontFamily,
fontFamily: "DMSans_700Bold",
},
italic: { fontStyle: "italic" },
link: {
@@ -403,7 +404,7 @@ function useMarkdownStyles(onLinkPress: (href: string) => void): MarkdownStyleSe
marginVertical: 10,
},
heading: {
fontFamily: boldFontFamily,
fontFamily: "DMSans_700Bold",
color: markdownStrongColor,
marginTop: 18,
marginBottom: 8,
@@ -427,9 +428,8 @@ function useMarkdownStyles(onLinkPress: (href: string) => void): MarkdownStyleSe
if (presentation.kind === "file") {
return (
<NativeText
className="font-t3-bold"
onPress={() => onLinkPress(href)}
style={{ color: inlineTextColor }}
style={[markdownLinkStyles.file, { color: inlineTextColor }]}
>
<Image
source={markdownFileIconSource(presentation.icon)}
@@ -453,7 +453,6 @@ function useMarkdownStyles(onLinkPress: (href: string) => void): MarkdownStyleSe
const linkHref = presentation.href;
return (
<NativeText
className="underline"
onPress={
linkHref
? () => {
@@ -461,14 +460,17 @@ function useMarkdownStyles(onLinkPress: (href: string) => void): MarkdownStyleSe
}
: undefined
}
style={{ color: markdownLinkColor }}
style={{
color: markdownLinkColor,
textDecorationLine: "underline",
}}
>
{children}
</NativeText>
);
},
list: ({ node, Renderer, ordered = false, start = 1 }) => (
<View className="mt-0.5 mb-2">
<View style={{ marginTop: 2, marginBottom: 8 }}>
{node.children?.map((child, index) => {
const childKey = `${child.type}:${child.beg ?? "unknown"}:${child.end ?? "unknown"}`;
if (child.type === "task_list_item") {
@@ -477,13 +479,20 @@ function useMarkdownStyles(onLinkPress: (href: string) => void): MarkdownStyleSe
);
}
return (
<View className="mb-[3px] flex-row items-start" key={childKey}>
<View
key={childKey}
style={{
flexDirection: "row",
alignItems: "flex-start",
marginBottom: 3,
}}
>
<NativeText
className="font-sans"
style={{
width: ordered ? 22 : 12,
marginRight: 5,
color: inlineTextColor,
fontFamily: "DMSans_400Regular",
fontSize: markdownFontSizes.m,
lineHeight: markdownFontSizes.bodyLineHeight,
textAlign: ordered ? "right" : "center",
@@ -491,7 +500,7 @@ function useMarkdownStyles(onLinkPress: (href: string) => void): MarkdownStyleSe
>
{ordered ? `${start + index}.` : "•"}
</NativeText>
<View className="min-w-0 flex-1">
<View style={{ flex: 1, minWidth: 0 }}>
<Renderer node={child} depth={1} inListItem parentIsText={false} />
</View>
</View>
@@ -503,9 +512,9 @@ function useMarkdownStyles(onLinkPress: (href: string) => void): MarkdownStyleSe
const value = content ?? "";
return (
<NativeText
className="font-mono"
style={{
color: inlineCodeTextColor,
fontFamily: "ui-monospace",
fontSize: markdownFontSizes.codeBlockFontSize,
lineHeight: markdownFontSizes.bodyLineHeight,
}}
@@ -521,24 +530,31 @@ function useMarkdownStyles(onLinkPress: (href: string) => void): MarkdownStyleSe
: {}),
code_block: ({ content, language }) => (
<View
className="my-3 overflow-hidden rounded-[10px] border"
style={{
backgroundColor: blockBackgroundColor,
borderRadius: 10,
borderWidth: 1,
borderColor: markdownHrColor,
marginVertical: 12,
overflow: "hidden",
}}
>
{language ? (
<View
className="border-b px-3.5 py-2"
style={{
borderBottomWidth: 1,
borderBottomColor: markdownHrColor,
paddingHorizontal: 14,
paddingVertical: 8,
}}
>
<NativeText
className="font-mono uppercase opacity-70"
style={{
color: markdownBodyColor,
fontFamily: "ui-monospace",
fontSize: markdownFontSizes.codeBlockFontSize,
opacity: 0.7,
textTransform: "uppercase",
}}
>
{language}
@@ -549,13 +565,13 @@ function useMarkdownStyles(onLinkPress: (href: string) => void): MarkdownStyleSe
horizontal
showsHorizontalScrollIndicator={false}
bounces={false}
contentContainerClassName="px-3.5 py-3"
contentContainerStyle={{ paddingHorizontal: 14, paddingVertical: 12 }}
>
<NativeText
selectable
className="font-mono"
style={{
color: blockTextColor,
fontFamily: "ui-monospace",
fontSize: markdownFontSizes.codeBlockFontSize,
lineHeight: markdownFontSizes.codeBlockLineHeight,
}}
@@ -585,7 +601,7 @@ function useMarkdownStyles(onLinkPress: (href: string) => void): MarkdownStyleSe
bold: {
fontWeight: "700",
color: markdownUserBodyColor,
fontFamily: boldFontFamily,
fontFamily: "DMSans_700Bold",
},
heading: {
...baseStyles.heading,
@@ -639,9 +655,9 @@ function useMarkdownStyles(onLinkPress: (href: string) => void): MarkdownStyleSe
fontSize: nativeMarkdownTypography.fontSize,
lineHeight: nativeMarkdownTypography.lineHeight,
headingFontSizes: nativeMarkdownTypography.headingFontSizes,
fontFamily: regularFontFamily,
headingFontFamily: boldFontFamily,
boldFontFamily,
fontFamily: "DMSans_400Regular",
headingFontFamily: "DMSans_700Bold",
boldFontFamily: "DMSans_700Bold",
},
},
assistant: {
@@ -670,21 +686,13 @@ function useMarkdownStyles(onLinkPress: (href: string) => void): MarkdownStyleSe
fontSize: nativeMarkdownTypography.fontSize,
lineHeight: nativeMarkdownTypography.lineHeight,
headingFontSizes: nativeMarkdownTypography.headingFontSizes,
fontFamily: regularFontFamily,
headingFontFamily: boldFontFamily,
boldFontFamily,
fontFamily: "DMSans_400Regular",
headingFontFamily: "DMSans_700Bold",
boldFontFamily: "DMSans_700Bold",
},
},
};
}, [
boldFontFamily,
colors,
inlineSkillForeground,
markdownFontSizes,
nativeMarkdownTypography,
onLinkPress,
regularFontFamily,
]);
}, [colors, inlineSkillForeground, markdownFontSizes, nativeMarkdownTypography, onLinkPress]);
}
function renderFeedEntry(
@@ -1011,10 +1019,11 @@ const ReviewCommentCard = memo(function ReviewCommentCard(props: {
return (
<View
className="w-full overflow-hidden rounded-[16px] border border-continuous"
className="w-full overflow-hidden rounded-[16px] border"
style={{
backgroundColor: props.colors.background,
borderColor: props.colors.border,
borderCurve: "continuous",
}}
>
<View
@@ -1022,8 +1031,8 @@ const ReviewCommentCard = memo(function ReviewCommentCard(props: {
style={{ borderColor: props.colors.border }}
>
<View
className="size-6 items-center justify-center rounded-[7px] border-continuous"
style={{ backgroundColor: props.colors.mutedBackground }}
className="size-6 items-center justify-center rounded-[7px]"
style={{ backgroundColor: props.colors.mutedBackground, borderCurve: "continuous" }}
>
<SymbolView
name="doc.text"
@@ -1076,9 +1085,9 @@ const ReviewCommentCard = memo(function ReviewCommentCard(props: {
>
<NativeText
selectable
className="font-mono"
style={{
color: props.colors.text,
fontFamily: "ui-monospace",
fontSize: codeSurface.fontSize,
lineHeight: codeSurface.rowHeight,
}}
@@ -1550,8 +1559,8 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
return (
<>
<View className="flex-1" onLayout={handleViewportLayout}>
<View className="flex-1">
<View style={{ flex: 1 }} onLayout={handleViewportLayout}>
<View style={{ flex: 1 }}>
<KeyboardAwareLegendList
ref={props.listRef}
// The empty↔filled key remounts the list when messages first
@@ -97,6 +97,8 @@ function SidebarHeaderButtonGroup(props: {
const SIDEBAR_STICKY_HEADER_HEIGHT = 106;
const SIDEBAR_STICKY_HEADER_FADE_HEIGHT = 44;
const IOS_SEARCH_FILL_DARK = "rgba(118, 118, 128, 0.24)";
const IOS_SEARCH_FILL_LIGHT = "rgba(118, 118, 128, 0.12)";
const SIDEBAR_HEADER_WASH_OPACITY = {
dark: [0.22, 0.14, 0.04],
light: [0.46, 0.3, 0.08],
@@ -138,13 +140,15 @@ function NativeSidebarContainer(props: ThreadNavigationSidebarProps) {
return (
<View
testID="thread-navigation-sidebar"
className="flex-1"
style={{
width: props.width,
backgroundColor,
borderRightColor: borderColor,
borderRightWidth: StyleSheet.hairlineWidth,
}}
style={[
styles.container,
{
width: props.width,
backgroundColor,
borderRightColor: borderColor,
borderRightWidth: StyleSheet.hairlineWidth,
},
]}
>
<SidebarNavigationShell>
<ThreadNavigationSidebarPane {...props} nativeChrome />
@@ -334,8 +338,11 @@ function ThreadNavigationSidebarPane(
const backgroundColor = useThemeColor("--color-drawer");
const borderColor = useThemeColor("--color-border");
const foregroundColor = useThemeColor("--color-foreground");
const mutedColor = useThemeColor("--color-foreground-muted");
const placeholderColor = useThemeColor("--color-placeholder");
const searchBackgroundColor =
colorScheme === "dark" ? IOS_SEARCH_FILL_DARK : IOS_SEARCH_FILL_LIGHT;
const headerFadeColor = String(backgroundColor);
const headerWashOpacity = SIDEBAR_HEADER_WASH_OPACITY[colorScheme];
const [measuredHeaderHeight, setMeasuredHeaderHeight] = useState<number | null>(null);
@@ -525,7 +532,7 @@ function ThreadNavigationSidebarPane(
[filterIcon, filterMenu, props.onOpenSettings],
);
const listEmpty = (
<Text className="px-2 py-4 text-sm text-foreground-muted">
<Text className="px-2 py-4 text-sm" style={{ color: mutedColor }}>
{catalogState.isLoadingConnections
? "Loading threads…"
: props.searchQuery.trim().length > 0
@@ -559,7 +566,7 @@ function ThreadNavigationSidebarPane(
unstable_headerRightItems: () => nativeHeaderItems,
}}
/>
<View className="flex-1">
<View style={styles.container}>
<SwipeableScrollGateProvider enabled={swipeEnabled}>
<GestureDetector gesture={sidebarScrollGesture}>
<LegendList
@@ -589,7 +596,7 @@ function ThreadNavigationSidebarPane(
style={styles.threadList}
ListHeaderComponent={
showsConnectionStatus ? (
<View className="px-1.5 pt-0.5 pb-2">
<View style={styles.connectionStatusNative}>
<WorkspaceConnectionStatus
onPress={props.onOpenEnvironmentSettings}
state={catalogState}
@@ -610,15 +617,17 @@ function ThreadNavigationSidebarPane(
return (
<View
testID="thread-navigation-sidebar"
className="flex-1"
style={{
width: props.width,
backgroundColor,
borderRightColor: borderColor,
borderRightWidth: StyleSheet.hairlineWidth,
}}
style={[
styles.container,
{
width: props.width,
backgroundColor,
borderRightColor: borderColor,
borderRightWidth: StyleSheet.hairlineWidth,
},
]}
>
<View className="flex-1" style={{ paddingBottom: insets.bottom }}>
<View style={{ flex: 1, paddingBottom: insets.bottom }}>
<SwipeableScrollGateProvider enabled={swipeEnabled}>
<GestureDetector gesture={sidebarScrollGesture}>
<LegendList
@@ -651,17 +660,25 @@ function ThreadNavigationSidebarPane(
</View>
<View
className="absolute inset-x-0 top-0 z-[4]"
onLayout={handleStickyHeaderLayout}
pointerEvents="box-none"
style={{ paddingTop: insets.top }}
style={[
styles.stickyHeader,
{
paddingTop: insets.top,
},
]}
>
<View
className="absolute inset-x-0 top-0"
pointerEvents="none"
accessibilityElementsHidden
importantForAccessibility="no-hide-descendants"
style={{ height: stickyHeaderHeight + SIDEBAR_STICKY_HEADER_FADE_HEIGHT }}
style={[
styles.stickyHeaderWash,
{
height: stickyHeaderHeight + SIDEBAR_STICKY_HEADER_FADE_HEIGHT,
},
]}
>
<Svg width="100%" height="100%">
<Defs>
@@ -687,8 +704,12 @@ function ThreadNavigationSidebarPane(
<Rect width="100%" height="100%" fill="url(#sidebar-header-wash)" />
</Svg>
</View>
<View className="h-[50px] flex-row items-end gap-0.5 pr-2 pl-5">
<Text className="flex-1 text-[34px] font-t3-bold text-foreground" numberOfLines={1}>
<View style={styles.header}>
<Text
className="flex-1 text-[34px] font-t3-bold"
numberOfLines={1}
style={{ color: foregroundColor }}
>
Threads
</Text>
<SidebarHeaderButtonGroup colorScheme={colorScheme}>
@@ -703,7 +724,14 @@ function ThreadNavigationSidebarPane(
</SidebarHeaderButtonGroup>
</View>
<View className="mx-4 mt-[9px] h-[38px] flex-row items-center gap-1.5 rounded-xl bg-sidebar-search pr-2.5 pl-[11px]">
<View
style={[
styles.searchField,
{
backgroundColor: searchBackgroundColor,
},
]}
>
<SymbolView name="magnifyingglass" size={15} tintColor={mutedColor} type="monochrome" />
<TextInput
ref={searchInputRef}
@@ -715,13 +743,14 @@ function ThreadNavigationSidebarPane(
placeholder="Search"
placeholderTextColor={placeholderColor}
returnKeyType="search"
className="h-[34px] flex-1 px-0 py-0 font-sans text-base text-foreground"
className="text-base"
style={[styles.searchInput, { color: foregroundColor }]}
value={props.searchQuery}
/>
</View>
{showsConnectionStatus ? (
<View className="px-3.5 pt-2.5">
<View style={styles.connectionStatus}>
<WorkspaceConnectionStatus
onPress={props.onOpenEnvironmentSettings}
state={catalogState}
@@ -735,12 +764,63 @@ function ThreadNavigationSidebarPane(
}
const styles = StyleSheet.create({
container: {
flex: 1,
},
stickyHeader: {
left: 0,
position: "absolute",
right: 0,
top: 0,
zIndex: 4,
},
stickyHeaderWash: {
left: 0,
position: "absolute",
right: 0,
top: 0,
},
header: {
height: 50,
paddingLeft: 20,
paddingRight: 8,
flexDirection: "row",
alignItems: "flex-end",
gap: 2,
},
headerButtonGroup: {
alignItems: "center",
borderRadius: 22,
flexDirection: "row",
overflow: "hidden",
},
connectionStatus: {
paddingTop: 10,
paddingHorizontal: 14,
},
connectionStatusNative: {
paddingBottom: 8,
paddingHorizontal: 6,
paddingTop: 2,
},
searchField: {
height: 38,
marginTop: 9,
marginHorizontal: 16,
paddingLeft: 11,
paddingRight: 10,
borderRadius: 12,
flexDirection: "row",
alignItems: "center",
gap: 6,
},
searchInput: {
flex: 1,
height: 34,
paddingVertical: 0,
paddingHorizontal: 0,
fontFamily: "DMSans_400Regular",
},
threadList: {
flex: 1,
},
@@ -3,9 +3,9 @@ import { useNavigation, type StaticScreenProps } from "@react-navigation/native"
import { useState } from "react";
import { Pressable, ScrollView, View } from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { useThemeColor } from "../../../lib/useThemeColor";
import { AppText as Text, AppTextInput as TextInput } from "../../../components/AppText";
import { cn } from "../../../lib/cn";
import { useEnvironmentQuery } from "../../../state/query";
import { useThreadSelection } from "../../../state/use-thread-selection";
import { useSelectedThreadGitActions } from "../../../state/use-selected-thread-git-actions";
@@ -27,6 +27,12 @@ export function GitBranchesSheet(_props: GitBranchesSheetProps) {
const gitState = useSelectedThreadGitState();
const gitActions = useSelectedThreadGitActions();
const borderColor = useThemeColor("--color-border");
const inputBorderColor = useThemeColor("--color-input-border");
const inputBg = useThemeColor("--color-input");
const foregroundColor = useThemeColor("--color-foreground");
const subtleStrongColor = useThemeColor("--color-subtle-strong");
const gitStatus = useEnvironmentQuery(
selectedThread !== null && selectedThreadCwd !== null
? vcsEnvironment.status({
@@ -67,14 +73,23 @@ export function GitBranchesSheet(_props: GitBranchesSheetProps) {
}}
>
<View className="gap-2 rounded-[18px] border border-border bg-card px-4 py-4">
<Text className="text-foreground-secondary text-2xs font-t3-bold tracking-[1px] uppercase">
<Text
className="text-foreground-secondary text-2xs font-t3-bold uppercase"
style={{ letterSpacing: 1 }}
>
New branch
</Text>
<TextInput
value={newBranchName}
onChangeText={setNewBranchName}
placeholder="feature/mobile-polish"
className="rounded-[18px]"
className="rounded-[18px] px-3.5 py-3 font-sans text-base"
style={{
borderWidth: 1,
borderColor: inputBorderColor,
backgroundColor: inputBg,
color: foregroundColor,
}}
/>
<SheetActionButton
icon="plus"
@@ -93,20 +108,35 @@ export function GitBranchesSheet(_props: GitBranchesSheetProps) {
</View>
<View className="gap-2 rounded-[18px] border border-border bg-card px-4 py-4">
<Text className="text-foreground-secondary text-2xs font-t3-bold tracking-[1px] uppercase">
<Text
className="text-foreground-secondary text-2xs font-t3-bold uppercase"
style={{ letterSpacing: 1 }}
>
New worktree
</Text>
<TextInput
value={worktreeBaseBranch}
onChangeText={setWorktreeBaseBranch}
placeholder="main"
className="rounded-[18px]"
className="rounded-[18px] px-3.5 py-3 font-sans text-base"
style={{
borderWidth: 1,
borderColor: inputBorderColor,
backgroundColor: inputBg,
color: foregroundColor,
}}
/>
<TextInput
value={worktreeBranchName}
onChangeText={setWorktreeBranchName}
placeholder="feature/mobile-thread"
className="rounded-[18px]"
className="rounded-[18px] px-3.5 py-3 font-sans text-base"
style={{
borderWidth: 1,
borderColor: inputBorderColor,
backgroundColor: inputBg,
color: foregroundColor,
}}
/>
<SheetActionButton
icon="square.split.2x1"
@@ -128,7 +158,10 @@ export function GitBranchesSheet(_props: GitBranchesSheetProps) {
</View>
<View className="gap-2">
<Text className="text-foreground-secondary text-2xs font-t3-bold tracking-[1px] uppercase">
<Text
className="text-foreground-secondary text-2xs font-t3-bold uppercase"
style={{ letterSpacing: 1 }}
>
Existing branches
</Text>
{branchesLoading ? (
@@ -152,11 +185,12 @@ export function GitBranchesSheet(_props: GitBranchesSheetProps) {
return (
<Pressable
key={branch.name}
className={cn(
"gap-1 rounded-[18px] border px-4 py-3 disabled:opacity-[0.45]",
branch.current ? "border-subtle-strong" : "border-border",
)}
className="gap-1 rounded-[18px] border px-4 py-3"
disabled={busy || disabled}
style={{
borderColor: branch.current ? subtleStrongColor : borderColor,
opacity: busy || disabled ? 0.45 : 1,
}}
onPress={() => {
void gitActions.onCheckoutSelectedThreadBranch(branch.name).then(() => {
navigation.goBack();
@@ -1,10 +1,10 @@
import { useNavigation, type StaticScreenProps } from "@react-navigation/native";
import { useCallback, useState } from "react";
import { Pressable, ScrollView, View } from "react-native";
import { Pressable, ScrollView, View, useColorScheme } from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { useThemeColor } from "../../../lib/useThemeColor";
import { AppText as Text, AppTextInput as TextInput } from "../../../components/AppText";
import { cn } from "../../../lib/cn";
import { useEnvironmentQuery } from "../../../state/query";
import { useThreadSelection } from "../../../state/use-thread-selection";
import { useSelectedThreadGitActions } from "../../../state/use-selected-thread-git-actions";
@@ -21,11 +21,18 @@ type GitCommitSheetProps = StaticScreenProps<{
export function GitCommitSheet(_props: GitCommitSheetProps) {
const navigation = useNavigation();
const insets = useSafeAreaInsets();
const isDarkMode = useColorScheme() === "dark";
const { selectedThread } = useThreadSelection();
const { selectedThreadCwd } = useSelectedThreadWorktree();
const gitState = useSelectedThreadGitState();
const gitActions = useSelectedThreadGitActions();
const borderColor = useThemeColor("--color-border");
const borderSubtleColor = useThemeColor("--color-border-subtle");
const inputBorderColor = useThemeColor("--color-input-border");
const inputBg = useThemeColor("--color-input");
const foregroundColor = useThemeColor("--color-foreground");
const gitStatus = useEnvironmentQuery(
selectedThread !== null && selectedThreadCwd !== null
? vcsEnvironment.status({
@@ -83,7 +90,10 @@ export function GitCommitSheet(_props: GitCommitSheetProps) {
</Text>
</View>
{isDefaultRef ? (
<Text className="text-xs leading-normal text-amber-700 dark:text-amber-400">
<Text
className="text-xs leading-normal"
style={{ color: isDarkMode ? "#fbbf24" : "#b45309" }}
>
Warning: this is the default branch.
</Text>
) : null}
@@ -128,8 +138,12 @@ export function GitCommitSheet(_props: GitCommitSheetProps) {
<Text className="text-foreground flex-1 text-sm font-medium" numberOfLines={1}>
{file.path}
</Text>
<Text className="text-xs font-t3-bold text-emerald-500">+{file.insertions}</Text>
<Text className="text-xs font-t3-bold text-rose-500">-{file.deletions}</Text>
<Text className="text-xs font-t3-bold" style={{ color: "#10b981" }}>
+{file.insertions}
</Text>
<Text className="text-xs font-t3-bold" style={{ color: "#f43f5e" }}>
-{file.deletions}
</Text>
</View>
))}
{selectedFiles.length > selectedFilePreview.length ? (
@@ -145,10 +159,10 @@ export function GitCommitSheet(_props: GitCommitSheetProps) {
return (
<Pressable
key={file.path}
className={cn(
"rounded-[18px] border px-4 py-3",
included ? "border-border" : "border-border-subtle",
)}
className="rounded-[18px] border px-4 py-3"
style={{
borderColor: included ? borderColor : borderSubtleColor,
}}
onPress={() => {
setExcludedFiles((current) => {
const next = new Set(current);
@@ -179,10 +193,12 @@ export function GitCommitSheet(_props: GitCommitSheetProps) {
) : null}
</View>
<View className="items-end gap-1">
<Text className="text-xs font-t3-bold text-emerald-500">
<Text className="text-xs font-t3-bold" style={{ color: "#10b981" }}>
+{file.insertions}
</Text>
<Text className="text-xs font-t3-bold text-rose-500">-{file.deletions}</Text>
<Text className="text-xs font-t3-bold" style={{ color: "#f43f5e" }}>
-{file.deletions}
</Text>
</View>
</View>
</Pressable>
@@ -200,7 +216,14 @@ export function GitCommitSheet(_props: GitCommitSheetProps) {
onChangeText={setDialogCommitMessage}
placeholder="Leave empty to auto-generate"
textAlignVertical="top"
className="min-h-[128px] rounded-[20px] px-4 py-3.5"
className="min-h-[128px] rounded-[20px] px-4 py-3.5 font-sans text-base"
style={{
minHeight: 128,
borderWidth: 1,
borderColor: inputBorderColor,
backgroundColor: inputBg,
color: foregroundColor,
}}
/>
</View>
@@ -101,10 +101,13 @@ export function GitConfirmSheet(props: GitConfirmSheetProps) {
return (
<View collapsable={false} className="flex-1 bg-sheet">
<View className="min-h-4 pt-2" />
<View style={{ minHeight: 16, paddingTop: 8 }} />
<View className="items-center gap-1 px-5 pb-3 pt-4">
<Text className="text-xs font-t3-bold tracking-[1px] uppercase text-foreground-muted">
<Text
className="text-xs font-t3-bold uppercase text-foreground-muted"
style={{ letterSpacing: 1 }}
>
Confirm
</Text>
<Text className="text-center text-3xl font-t3-bold">
@@ -115,7 +118,10 @@ export function GitConfirmSheet(props: GitConfirmSheetProps) {
</Text>
</View>
<View className="gap-3 px-5 pt-2" style={{ paddingBottom: Math.max(insets.bottom, 18) + 8 }}>
<View
className="gap-3 px-5"
style={{ paddingBottom: Math.max(insets.bottom, 18) + 8, paddingTop: 8 }}
>
<SheetActionButton
icon="arrow.right.circle"
label={copy?.continueLabel ?? "Continue"}
@@ -47,6 +47,7 @@ export function GitOverviewSheet(props: GitOverviewSheetProps) {
const gitActions = useSelectedThreadGitActions();
const iconColor = useThemeColor("--color-icon");
const borderColor = useThemeColor("--color-border");
const foregroundColor = String(useThemeColor("--color-foreground"));
const sheetColor = String(useThemeColor("--color-sheet"));
@@ -204,9 +205,9 @@ export function GitOverviewSheet(props: GitOverviewSheetProps) {
const content = (
<ScrollView
className="flex-1 bg-screen"
contentInsetAdjustmentBehavior={Platform.OS === "ios" ? "automatic" : "never"}
showsVerticalScrollIndicator={false}
style={{ flex: 1, backgroundColor: sheetColor }}
contentInset={{ bottom: Math.max(insets.bottom, 18) + 18 }}
contentContainerStyle={{
paddingHorizontal: isInspector ? 12 : 20,
@@ -226,7 +227,9 @@ export function GitOverviewSheet(props: GitOverviewSheetProps) {
>
{sheetMenuItems.map(({ item, disabledReason }, index) => (
<View key={`${item.id}-${item.label}`}>
{index > 0 ? <View className="ml-12 h-px bg-border" /> : null}
{index > 0 ? (
<View className="ml-12 h-px" style={{ backgroundColor: borderColor }} />
) : null}
<SheetListRow
icon={menuItemIconName(item.icon)}
title={item.label}
@@ -238,7 +241,7 @@ export function GitOverviewSheet(props: GitOverviewSheetProps) {
))}
{behindCount > 0 ? (
<>
<View className="ml-12 h-px bg-border" />
<View className="ml-12 h-px" style={{ backgroundColor: borderColor }} />
<SheetListRow
icon="arrow.down.circle"
title="Pull latest"
@@ -248,7 +251,7 @@ export function GitOverviewSheet(props: GitOverviewSheetProps) {
/>
</>
) : null}
<View className="ml-12 h-px bg-border" />
<View className="ml-12 h-px" style={{ backgroundColor: borderColor }} />
<SheetListRow
icon="text.bubble"
title="Review changes"
@@ -256,7 +259,7 @@ export function GitOverviewSheet(props: GitOverviewSheetProps) {
disabled={busy || !isRepo}
onPress={() => navigation.navigate("ThreadReview", { environmentId, threadId })}
/>
<View className="ml-12 h-px bg-border" />
<View className="ml-12 h-px" style={{ backgroundColor: borderColor }} />
<SheetListRow
icon="point.topleft.down.curvedto.point.bottomright.up"
title="Branches & worktrees"
@@ -362,11 +365,8 @@ export function GitOverviewSheet(props: GitOverviewSheetProps) {
}
>
<Pressable
className={
busy
? "absolute right-3 top-4 z-[1] h-9 w-9 items-center justify-center rounded-full bg-subtle opacity-[0.45]"
: "absolute right-3 top-4 z-[1] h-9 w-9 items-center justify-center rounded-full bg-subtle"
}
className="absolute right-3 top-4 h-9 w-9 items-center justify-center rounded-full bg-subtle"
style={{ zIndex: 1, opacity: busy ? 0.45 : 1 }}
disabled={busy}
onPress={() => void gitActions.refreshSelectedThreadGitStatus()}
>
@@ -378,7 +378,10 @@ export function GitOverviewSheet(props: GitOverviewSheetProps) {
weight="medium"
/>
</Pressable>
<Text className="text-xs font-t3-bold tracking-[1px] uppercase text-foreground-muted">
<Text
className="text-xs font-t3-bold uppercase text-foreground-muted"
style={{ letterSpacing: 1 }}
>
{isInspector ? "Repository" : "Branch"}
</Text>
<Text className={isInspector ? "pr-10 text-xl font-t3-bold" : "text-3xl font-t3-bold"}>
@@ -3,7 +3,6 @@ import type { ComponentProps } from "react";
import { Pressable, View } from "react-native";
import { useThemeColor } from "../../../lib/useThemeColor";
import { AppText as Text } from "../../../components/AppText";
import { cn } from "../../../lib/cn";
/* ─── Shared sheet components ──────────────────────────────────────── */
@@ -14,36 +13,51 @@ export function SheetActionButton(props: {
readonly tone?: "primary" | "secondary" | "danger";
readonly onPress: () => void;
}) {
const primaryBg = useThemeColor("--color-primary");
const primaryFg = useThemeColor("--color-primary-foreground");
const dangerBg = useThemeColor("--color-danger");
const dangerBorder = useThemeColor("--color-danger-border");
const dangerFg = useThemeColor("--color-danger-foreground");
const secondaryBg = useThemeColor("--color-secondary");
const secondaryBorder = useThemeColor("--color-secondary-border");
const secondaryFg = useThemeColor("--color-secondary-foreground");
const tone = props.tone ?? "secondary";
const textColor = tone === "primary" ? primaryFg : tone === "danger" ? dangerFg : secondaryFg;
const colors =
tone === "primary"
? {
backgroundColor: primaryBg,
borderColor: "transparent",
textColor: primaryFg,
}
: tone === "danger"
? {
backgroundColor: dangerBg,
borderColor: dangerBorder,
textColor: dangerFg,
}
: {
backgroundColor: secondaryBg,
borderColor: secondaryBorder,
textColor: secondaryFg,
};
return (
<Pressable
className={cn(
"min-h-[48px] flex-1 flex-row items-center justify-center gap-2 rounded-[18px] px-4 py-3 disabled:opacity-[0.45]",
tone === "primary"
? "bg-primary"
: tone === "danger"
? "border border-danger-border bg-danger"
: "border border-secondary-border bg-secondary",
)}
className="min-h-[48px] flex-1 flex-row items-center justify-center gap-2 rounded-[18px] px-4 py-3"
disabled={props.disabled}
style={{
backgroundColor: colors.backgroundColor,
borderWidth: tone === "primary" ? 0 : 1,
borderColor: colors.borderColor,
opacity: props.disabled ? 0.45 : 1,
}}
onPress={props.onPress}
>
<SymbolView name={props.icon} size={16} tintColor={textColor} type="monochrome" />
<SymbolView name={props.icon} size={16} tintColor={colors.textColor} type="monochrome" />
<Text
className={cn(
"text-xs font-t3-bold tracking-[0.9px] uppercase",
tone === "primary"
? "text-primary-foreground"
: tone === "danger"
? "text-danger-foreground"
: "text-secondary-foreground",
)}
className="text-xs font-t3-bold uppercase"
style={{ color: colors.textColor, letterSpacing: 0.9 }}
>
{props.label}
</Text>
@@ -54,7 +68,10 @@ export function SheetActionButton(props: {
export function MetaCard(props: { readonly label: string; readonly value: string }) {
return (
<View className="rounded-[18px] border border-border bg-card px-4 py-3">
<Text className="text-foreground-muted text-2xs font-t3-bold tracking-[0.9px] uppercase">
<Text
className="text-foreground-muted text-2xs font-t3-bold uppercase"
style={{ letterSpacing: 0.9 }}
>
{props.label}
</Text>
<Text selectable className="text-foreground text-sm font-medium" numberOfLines={1}>
@@ -76,8 +93,9 @@ export function SheetListRow(props: {
return (
<Pressable
className="flex-row items-center gap-3 px-1 py-3 disabled:opacity-[0.45]"
className="flex-row items-center gap-3 px-1 py-3"
disabled={props.disabled}
style={{ opacity: props.disabled ? 0.45 : 1 }}
onPress={props.onPress}
>
<View className="bg-subtle h-9 w-9 items-center justify-center rounded-full">
@@ -22,17 +22,16 @@ export function SidebarFilterButton(props: {
return (
<Pressable
className="h-11 w-[50px] cursor-pointer items-center justify-center rounded-[22px]"
accessibilityLabel={props.accessibilityLabel}
accessibilityRole="button"
hitSlop={4}
style={({ pressed }) => [
styles.button,
props.grouped
? { backgroundColor: pressed ? pressedBackgroundColor : "transparent", borderWidth: 0 }
: {
backgroundColor: pressed ? pressedBackgroundColor : idleBackgroundColor,
borderColor,
borderWidth: StyleSheet.hairlineWidth,
},
]}
>
@@ -40,3 +39,17 @@ export function SidebarFilterButton(props: {
</Pressable>
);
}
const styles = StyleSheet.create({
button: {
// Match the native glass UIBarButtonItem group metrics (~50pt slots,
// 44pt bar height, label-colored ~20pt glyphs).
width: 50,
height: 44,
borderRadius: 22,
borderWidth: StyleSheet.hairlineWidth,
alignItems: "center",
justifyContent: "center",
cursor: "pointer",
},
});
@@ -24,18 +24,17 @@ function FallbackHeaderButton(props: {
return (
<Pressable
className="h-11 w-[50px] items-center justify-center rounded-[22px]"
accessibilityLabel={props.accessibilityLabel}
accessibilityRole="button"
hitSlop={4}
onPress={props.onPress}
style={({ pressed }) => [
styles.button,
props.grouped
? { backgroundColor: pressed ? pressedBackgroundColor : "transparent", borderWidth: 0 }
: {
backgroundColor: pressed ? pressedBackgroundColor : idleBackgroundColor,
borderColor,
borderWidth: StyleSheet.hairlineWidth,
},
]}
>
@@ -46,7 +45,7 @@ function FallbackHeaderButton(props: {
export function SidebarHeaderActions(props: SidebarHeaderActionsProps) {
return (
<View className="flex-row items-center gap-0.5">
<View style={styles.actions}>
<FallbackHeaderButton
accessibilityLabel="Open settings"
grouped={props.grouped}
@@ -56,3 +55,20 @@ export function SidebarHeaderActions(props: SidebarHeaderActionsProps) {
</View>
);
}
const styles = StyleSheet.create({
actions: {
flexDirection: "row",
alignItems: "center",
gap: 2,
},
button: {
// Match the native glass UIBarButtonItem group metrics.
width: 50,
height: 44,
borderRadius: 22,
borderWidth: StyleSheet.hairlineWidth,
alignItems: "center",
justifyContent: "center",
},
});
@@ -75,7 +75,7 @@ export function ThreadInspectorContentStack(props: {
const Route = props.Route;
return (
<View className="flex-1">
<View style={{ flex: 1 }}>
<InspectorContentPane
mounted={mountedModes.has("files") || props.mode === "files"}
visible={props.mode === "files"}
@@ -6,18 +6,16 @@ import type {
import type { MenuAction } from "@react-native-menu/menu";
import { SymbolView } from "expo-symbols";
import { memo, useCallback, useMemo, type ComponentProps } from "react";
import { Pressable, useColorScheme, useWindowDimensions, View } from "react-native";
import { Pressable, useWindowDimensions, View } from "react-native";
import type { SwipeableMethods } from "react-native-gesture-handler/ReanimatedSwipeable";
import Svg, { Circle, Path } from "react-native-svg";
import { AppText as Text } from "../../components/AppText";
import { ControlPillMenu } from "../../components/ControlPill";
import { ProjectFavicon } from "../../components/ProjectFavicon";
import { cn } from "../../lib/cn";
import { relativeTime } from "../../lib/time";
import { useThemeColor } from "../../lib/useThemeColor";
import type { PendingNewTask } from "../../state/use-pending-new-tasks";
import { useThreadPr, type ThreadPr } from "../../state/use-thread-pr";
import { useThreadPr } from "../../state/use-thread-pr";
import type { HomeGroupDisplayAction } from "../home/homeListItems";
import { ThreadSwipeable } from "../home/thread-swipe-actions";
import { resolveThreadStatus } from "./threadPresentation";
@@ -34,41 +32,6 @@ export type ThreadListVariant = "compact" | "sidebar";
export const THREAD_LIST_COMPACT_INSET = 20;
const SIDEBAR_ROW_RADIUS = 12;
function pullRequestTintColor(
state: ThreadPr["state"],
colorScheme: ReturnType<typeof useColorScheme>,
) {
const dark = colorScheme === "dark";
switch (state) {
case "open":
return dark ? "#34d399" : "#059669";
case "merged":
return dark ? "#a78bfa" : "#7c3aed";
case "closed":
return dark ? "#a1a1aa" : "#71717a";
}
}
function PullRequestIcon(props: { readonly size: number; readonly color: string }) {
return (
<Svg
width={props.size}
height={props.size}
viewBox="0 0 24 24"
fill="none"
stroke={props.color}
strokeWidth={2}
strokeLinecap="round"
strokeLinejoin="round"
>
<Circle cx={18} cy={18} r={3} />
<Circle cx={6} cy={6} r={3} />
<Path d="M13 6h3a2 2 0 0 1 2 2v7" />
<Path d="M6 9v12" />
</Svg>
);
}
/* ─── Project group header ───────────────────────────────────────────── */
export const ThreadListGroupHeader = memo(function ThreadListGroupHeader(props: {
@@ -138,9 +101,10 @@ export const ThreadListGroupHeader = memo(function ThreadListGroupHeader(props:
<Text
className={
compact
? "flex-shrink text-base font-t3-bold tracking-[0.2px] text-foreground-muted"
: "flex-shrink text-sm font-t3-bold tracking-[0.2px] text-foreground-muted"
? "flex-shrink text-base font-t3-bold text-foreground-muted"
: "flex-shrink text-sm font-t3-bold text-foreground-muted"
}
style={{ letterSpacing: 0.2 }}
numberOfLines={1}
>
{props.title}
@@ -272,6 +236,7 @@ export const PendingTaskListRow = memo(function PendingTaskListRow(props: {
const compact = props.variant === "compact";
const separatorColor = useThemeColor("--color-separator");
const iconSubtleColor = useThemeColor("--color-icon-subtle");
const foregroundColor = useThemeColor("--color-foreground");
const mutedColor = useThemeColor("--color-foreground-muted");
const pressedBackgroundColor = useThemeColor("--color-subtle");
@@ -289,14 +254,17 @@ export const PendingTaskListRow = memo(function PendingTaskListRow(props: {
);
const statusPill = (
<View className="rounded-full bg-zinc-500/12 px-1.5 py-0.5 dark:bg-zinc-500/16">
<View
className="bg-zinc-500/12 dark:bg-zinc-500/16"
style={{ borderRadius: 99, paddingHorizontal: 6, paddingVertical: 2 }}
>
<Text className="text-3xs font-t3-bold text-zinc-600 dark:text-zinc-300">Pending</Text>
</View>
);
const subtitleRow =
subtitleParts.length > 0 ? (
<View className="mt-px flex-row items-center gap-1.5">
<View className="flex-row items-center gap-1.5" style={{ marginTop: 1 }}>
<SymbolView
name="tray.and.arrow.up"
size={10}
@@ -304,12 +272,9 @@ export const PendingTaskListRow = memo(function PendingTaskListRow(props: {
type="monochrome"
/>
<Text
className={
compact
? "shrink text-sm text-foreground-muted"
: "shrink text-xs text-foreground-muted"
}
className={compact ? "text-sm text-foreground-muted" : "text-xs"}
numberOfLines={1}
style={compact ? { flexShrink: 1 } : { flexShrink: 1, color: mutedColor }}
>
{subtitleParts.join(" · ")}
</Text>
@@ -346,7 +311,12 @@ export const PendingTaskListRow = memo(function PendingTaskListRow(props: {
</Text>
<View className="flex-row items-center gap-2">
{statusPill}
<Text className="text-base tabular-nums text-foreground-tertiary">{timestamp}</Text>
<Text
className="text-base text-foreground-tertiary"
style={{ fontVariant: ["tabular-nums"] }}
>
{timestamp}
</Text>
<SymbolView
name="chevron.right"
size={13}
@@ -375,14 +345,22 @@ export const PendingTaskListRow = memo(function PendingTaskListRow(props: {
paddingVertical: 10,
})}
>
<View className="gap-[3px]">
<View style={{ gap: 3 }}>
<View className="flex-row items-center justify-between gap-2">
<Text className="flex-1 text-base font-t3-medium text-foreground" numberOfLines={1}>
<Text
className="flex-1 text-base font-t3-medium"
numberOfLines={1}
style={{ color: foregroundColor }}
>
{pendingTask.title}
</Text>
<View className="flex-row items-center gap-2">
{statusPill}
<Text className="text-xs tabular-nums text-foreground-muted" numberOfLines={1}>
<Text
className="text-xs"
numberOfLines={1}
style={{ color: mutedColor, fontVariant: ["tabular-nums"] }}
>
{timestamp}
</Text>
</View>
@@ -430,7 +408,6 @@ export const ThreadListRow = memo(function ThreadListRow(props: {
>["simultaneousWithExternalGesture"];
}) {
const { width: windowWidth } = useWindowDimensions();
const colorScheme = useColorScheme();
const compact = props.variant === "compact";
const selected = props.selected === true;
// Recycling-safe: resets when the list container is reused for another
@@ -441,8 +418,12 @@ export const ThreadListRow = memo(function ThreadListRow(props: {
const iconSubtleColor = useThemeColor("--color-icon-subtle");
const screenColor = useThemeColor("--color-screen");
const drawerColor = useThemeColor("--color-drawer");
const foregroundColor = useThemeColor("--color-foreground");
const mutedColor = useThemeColor("--color-foreground-muted");
const pressedBackgroundColor = useThemeColor("--color-subtle");
const selectedBackgroundColor = useThemeColor("--color-user-bubble");
const selectedForegroundColor = useThemeColor("--color-user-bubble-foreground");
const selectedMutedColor = useThemeColor("--color-user-bubble-foreground-muted");
const { thread, onSelectThread, onArchiveThread, onDeleteThread } = props;
const status = resolveThreadStatus(thread);
@@ -450,12 +431,13 @@ export const ThreadListRow = memo(function ThreadListRow(props: {
const timestamp = relativeTime(
thread.latestUserMessageAt ?? thread.updatedAt ?? thread.createdAt,
);
const threadAccessibilityLabel = pr ? `${thread.title}, ${pr.accessibilityLabel}` : thread.title;
const subtitleParts = [props.environmentLabel, thread.branch].filter((part): part is string =>
Boolean(part),
);
const backgroundColor = compact ? screenColor : drawerColor;
const effectiveForeground = selected ? selectedForegroundColor : foregroundColor;
const effectiveMuted = selected ? selectedMutedColor : mutedColor;
const effectivePressedBackground = selected ? "rgba(255,255,255,0.16)" : pressedBackgroundColor;
const effectiveStatus =
selected && status
@@ -482,7 +464,10 @@ export const ThreadListRow = memo(function ThreadListRow(props: {
);
const statusPill = effectiveStatus ? (
<View className={`${effectiveStatus.pillClassName} rounded-full px-1.5 py-0.5`}>
<View
className={effectiveStatus.pillClassName}
style={{ borderRadius: 99, paddingHorizontal: 6, paddingVertical: 2 }}
>
<Text className={`text-3xs font-t3-bold ${effectiveStatus.textClassName}`}>
{effectiveStatus.label}
</Text>
@@ -491,36 +476,32 @@ export const ThreadListRow = memo(function ThreadListRow(props: {
const subtitleRow =
subtitleParts.length > 0 || pr !== null ? (
<View className="mt-px flex-row items-center gap-1.5">
<View className="flex-row items-center gap-1.5" style={{ marginTop: 1 }}>
{subtitleParts.length > 0 ? (
<>
<SymbolView
name="arrow.triangle.branch"
size={10}
tintColor={compact ? iconSubtleColor : effectiveMuted}
type="monochrome"
/>
<Text
className={cn(
"shrink",
compact ? "text-sm text-foreground-muted" : "text-xs",
!compact &&
(selected ? "text-user-bubble-foreground-muted" : "text-foreground-muted"),
)}
className={compact ? "text-sm text-foreground-muted" : "text-xs"}
numberOfLines={1}
style={compact ? { flexShrink: 1 } : { flexShrink: 1, color: effectiveMuted }}
>
{subtitleParts.join(" · ")}
</Text>
</>
) : null}
{pr !== null ? (
<View className="flex-row items-center gap-0.5">
<PullRequestIcon
size={compact ? 13 : 11}
color={selected ? "#ffffff" : pullRequestTintColor(pr.state, colorScheme)}
/>
<Text
className={`${compact ? "text-sm" : "text-xs"} font-t3-medium ${
selected ? "text-white" : pr.textClassName
}`}
>
{pr.label}
</Text>
</View>
<Text
className={`${compact ? "text-sm" : "text-xs"} font-t3-medium ${
selected ? "text-white" : pr.textClassName
}`}
>
{pr.label}
</Text>
) : null}
</View>
) : null;
@@ -529,7 +510,7 @@ export const ThreadListRow = memo(function ThreadListRow(props: {
compact ? (
<Pressable
accessibilityHint="Swipe left for archive and delete actions"
accessibilityLabel={threadAccessibilityLabel}
accessibilityLabel={thread.title}
accessibilityRole="button"
className="bg-screen"
onPress={() => {
@@ -559,7 +540,12 @@ export const ThreadListRow = memo(function ThreadListRow(props: {
</Text>
<View className="flex-row items-center gap-2">
{statusPill}
<Text className="text-base tabular-nums text-foreground-tertiary">{timestamp}</Text>
<Text
className="text-base text-foreground-tertiary"
style={{ fontVariant: ["tabular-nums"] }}
>
{timestamp}
</Text>
<SymbolView
name="chevron.right"
size={13}
@@ -575,7 +561,7 @@ export const ThreadListRow = memo(function ThreadListRow(props: {
) : (
<Pressable
accessibilityHint="Opens the thread"
accessibilityLabel={threadAccessibilityLabel}
accessibilityLabel={thread.title}
accessibilityRole="button"
accessibilityState={{ selected }}
onHoverIn={() => setHovered(true)}
@@ -598,25 +584,21 @@ export const ThreadListRow = memo(function ThreadListRow(props: {
paddingVertical: 10,
})}
>
<View className="gap-[3px]">
<View style={{ gap: 3 }}>
<View className="flex-row items-center justify-between gap-2">
<Text
className={cn(
"flex-1 text-base font-t3-medium",
selected ? "text-user-bubble-foreground" : "text-foreground",
)}
className="flex-1 text-base font-t3-medium"
numberOfLines={1}
style={{ color: effectiveForeground }}
>
{thread.title}
</Text>
<View className="flex-row items-center gap-2">
{statusPill}
<Text
className={cn(
"text-xs tabular-nums",
selected ? "text-user-bubble-foreground-muted" : "text-foreground-muted",
)}
className="text-xs"
numberOfLines={1}
style={{ color: effectiveMuted, fontVariant: ["tabular-nums"] }}
>
{timestamp}
</Text>
@@ -206,12 +206,13 @@ export function ThreadWorkLog(props: {
nestedScrollEnabled
directionalLockEnabled
showsVerticalScrollIndicator
className="max-h-60"
style={{ maxHeight: 240 }}
contentContainerStyle={{ paddingRight: 8 }}
>
<Text
selectable
className="font-mono text-2xs leading-normal text-foreground-muted"
className="text-2xs leading-normal text-foreground-muted"
style={{ fontFamily: "ui-monospace" }}
>
{row.fullDetail}
</Text>
-3
View File
@@ -8,7 +8,6 @@ import { cryptoLayer } from "../features/cloud/dpop";
import { managedRelayClientLayer } from "../features/cloud/managedRelayLayer";
import { resolveCloudPublicConfig } from "../features/cloud/publicConfig";
import { tracingLayer } from "../features/observability/tracing";
import * as Persistence from "../persistence/layer";
function configuredRelayUrl(): string {
return resolveCloudPublicConfig().relay.url ?? "http://relay.invalid";
@@ -21,7 +20,6 @@ type RuntimeLayerSource =
| typeof Socket.layerWebSocketConstructorGlobal
| typeof cryptoLayer
| typeof httpClientLayer
| typeof Persistence.layer
| typeof tracingLayer;
const runtimeLayer = Layer.merge(
@@ -31,7 +29,6 @@ const runtimeLayer = Layer.merge(
Layer.provideMerge(cryptoLayer),
Layer.provideMerge(httpClientLayer),
Layer.provideMerge(tracingLayer.pipe(Layer.provide(httpClientLayer))),
Layer.provideMerge(Persistence.layer),
);
export const runtime: ManagedRuntime.ManagedRuntime<
+8 -148
View File
@@ -3,103 +3,34 @@ import { beforeEach, describe, expect, it, vi } from "vite-plus/test";
const mocks = vi.hoisted(() => {
const values = new Map<string, string>();
let preferencesJson: string | null = null;
let preferencesUpdatedAt = 0;
let loadPreferencesFails = false;
let savePreferencesFails = false;
return {
clear: () => {
values.clear();
preferencesJson = null;
preferencesUpdatedAt = 0;
loadPreferencesFails = false;
savePreferencesFails = false;
},
getStoredValue: (key: string) => values.get(key) ?? null,
getPreferencesJson: () => preferencesJson,
setPreferencesJson: (value: string, updatedAt: number) => {
preferencesJson = value;
preferencesUpdatedAt = updatedAt;
},
setDatabaseFailures: (load: boolean, save: boolean) => {
loadPreferencesFails = load;
savePreferencesFails = save;
},
clear: () => values.clear(),
getItemAsync: vi.fn((key: string) => Promise.resolve(values.get(key) ?? null)),
setItemAsync: vi.fn((key: string, value: string) => {
values.set(key, value);
return Promise.resolve();
}),
deleteItemAsync: vi.fn((key: string) => {
values.delete(key);
return Promise.resolve();
}),
database: {
closeAsync: vi.fn(() => Promise.resolve()),
execAsync: vi.fn(() => Promise.resolve()),
withExclusiveTransactionAsync: vi.fn(
(run: (transaction: { execAsync: () => Promise<void> }) => Promise<void>) =>
run({ execAsync: () => Promise.resolve() }),
),
getFirstAsync: vi.fn((sql: string) => {
if (sql.includes("PRAGMA user_version")) {
return Promise.resolve({ user_version: 1 });
}
if (loadPreferencesFails) {
return Promise.reject(new Error("database unavailable"));
}
return Promise.resolve(
preferencesJson === null
? null
: { payload: preferencesJson, updatedAt: preferencesUpdatedAt },
);
}),
runAsync: vi.fn((_sql: string, payload?: unknown, updatedAt?: unknown) => {
if (savePreferencesFails) {
return Promise.reject(new Error("database unavailable"));
}
if (typeof payload === "string") {
preferencesJson = payload;
}
if (typeof updatedAt === "number") {
preferencesUpdatedAt = updatedAt;
}
return Promise.resolve();
}),
},
};
});
vi.mock("expo-secure-store", () => ({
deleteItemAsync: mocks.deleteItemAsync,
getItemAsync: mocks.getItemAsync,
setItemAsync: mocks.setItemAsync,
}));
vi.mock("expo-sqlite", () => ({
openDatabaseAsync: vi.fn(() => Promise.resolve(mocks.database)),
}));
vi.mock("expo-crypto", () => ({
getRandomBytes: vi.fn(() => new Uint8Array(16)),
}));
vi.mock("expo-constants", () => ({
default: { expoConfig: { extra: {} } },
}));
vi.mock("react-native", () => ({
Platform: {
OS: "ios",
},
}));
import {
loadPreferences,
loadSavedConnections,
saveConnection,
savePreferencesPatch,
} from "../persistence/imperative";
vi.mock("./runtime", () => ({
runtime: {
runPromise: vi.fn(),
},
}));
import { loadSavedConnections, saveConnection } from "./storage";
import { toStableSavedRemoteConnection } from "./connection";
const managedConnection = {
@@ -169,75 +100,4 @@ describe("mobile connection storage", () => {
warn.mockRestore();
});
it("loads legacy preferences when SQLite is unavailable", async () => {
mocks.setDatabaseFailures(true, true);
await mocks.setItemAsync("t3code.preferences", JSON.stringify({ baseFontSize: 17 }));
await expect(loadPreferences()).resolves.toEqual({ baseFontSize: 17 });
});
it("falls back to secure storage when SQLite cannot save preferences", async () => {
mocks.setDatabaseFailures(true, true);
await expect(savePreferencesPatch({ baseFontSize: 19 })).resolves.toEqual({ baseFontSize: 19 });
const fallback = JSON.parse(mocks.getStoredValue("t3code.preferences.fallback") ?? "") as {
readonly payload: string;
readonly updatedAt: number;
};
expect(JSON.parse(fallback.payload)).toEqual({ baseFontSize: 19 });
expect(fallback.updatedAt).toEqual(expect.any(Number));
});
it("reconciles fallback preferences after SQLite recovers", async () => {
mocks.setPreferencesJson(JSON.stringify({ baseFontSize: 15 }), 10);
await mocks.setItemAsync(
"t3code.preferences.fallback",
JSON.stringify({
payload: JSON.stringify({ baseFontSize: 19 }),
updatedAt: 20,
}),
);
await expect(loadPreferences()).resolves.toEqual({ baseFontSize: 19 });
expect(JSON.parse(mocks.getPreferencesJson() ?? "")).toEqual({ baseFontSize: 19 });
expect(mocks.getStoredValue("t3code.preferences.fallback")).toBeNull();
});
it("ignores a stale fallback when its previous deletion failed", async () => {
mocks.setPreferencesJson(JSON.stringify({ baseFontSize: 21 }), 30);
await mocks.setItemAsync(
"t3code.preferences.fallback",
JSON.stringify({
payload: JSON.stringify({ baseFontSize: 19 }),
updatedAt: 20,
}),
);
await expect(loadPreferences()).resolves.toEqual({ baseFontSize: 21 });
expect(JSON.parse(mocks.getPreferencesJson() ?? "")).toEqual({ baseFontSize: 21 });
expect(mocks.getStoredValue("t3code.preferences.fallback")).toBeNull();
});
it("ignores an invalid fallback even when it has a newer timestamp", async () => {
mocks.setPreferencesJson(JSON.stringify({ baseFontSize: 21 }), 30);
await mocks.setItemAsync(
"t3code.preferences.fallback",
JSON.stringify({ payload: "{", updatedAt: 40 }),
);
const warn = vi.spyOn(console, "warn").mockImplementation(() => undefined);
await expect(loadPreferences()).resolves.toEqual({ baseFontSize: 21 });
expect(JSON.parse(mocks.getPreferencesJson() ?? "")).toEqual({ baseFontSize: 21 });
expect(mocks.getStoredValue("t3code.preferences.fallback")).toBeNull();
warn.mockRestore();
});
it("keeps SQLite authoritative when stale legacy preferences remain", async () => {
mocks.setPreferencesJson(JSON.stringify({ baseFontSize: 21 }), 30);
await mocks.setItemAsync("t3code.preferences", JSON.stringify({ baseFontSize: 19 }));
await expect(loadPreferences()).resolves.toEqual({ baseFontSize: 21 });
expect(JSON.parse(mocks.getPreferencesJson() ?? "")).toEqual({ baseFontSize: 21 });
});
});
+291
View File
@@ -0,0 +1,291 @@
import * as Arr from "effect/Array";
import { pipe } from "effect/Function";
import * as Schema from "effect/Schema";
import * as SecureStore from "expo-secure-store";
import { EnvironmentId } from "@t3tools/contracts";
import {
isRelayManagedConnection,
type SavedRemoteConnection,
toStableSavedRemoteConnection,
} from "./connection";
const CONNECTIONS_KEY = "t3code.connections";
const PREFERENCES_KEY = "t3code.preferences";
const AGENT_AWARENESS_DEVICE_ID_KEY = "t3code.agent-awareness.device-id";
const AGENT_AWARENESS_REGISTRATION_KEY = "t3code.agent-awareness.registration";
const MobileStorageKey = Schema.Literals([
CONNECTIONS_KEY,
PREFERENCES_KEY,
AGENT_AWARENESS_DEVICE_ID_KEY,
AGENT_AWARENESS_REGISTRATION_KEY,
]);
type MobileStorageKeyValue = typeof MobileStorageKey.Type;
export class MobileSecureStorageError extends Schema.TaggedErrorClass<MobileSecureStorageError>()(
"MobileSecureStorageError",
{
operation: Schema.Literals(["read", "write", "generate-device-id"]),
key: MobileStorageKey,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Mobile secure storage operation ${this.operation} failed for key ${this.key}.`;
}
}
export class MobileStorageDecodeError extends Schema.TaggedErrorClass<MobileStorageDecodeError>()(
"MobileStorageDecodeError",
{
key: MobileStorageKey,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to decode mobile storage value for key ${this.key}.`;
}
}
export class MobileStorageEncodeError extends Schema.TaggedErrorClass<MobileStorageEncodeError>()(
"MobileStorageEncodeError",
{
key: MobileStorageKey,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to encode mobile storage value for key ${this.key}.`;
}
}
export interface Preferences {
readonly liveActivitiesEnabled?: boolean;
readonly baseFontSize?: number;
/** Terminal font size override; null/absent means derived from baseFontSize. */
readonly terminalFontSize?: number | null;
/** Legacy key predating baseFontSize; read once for migration. */
readonly markdownFontSize?: number;
/** 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> {
try {
return await SecureStore.getItemAsync(key);
} catch (cause) {
throw new MobileSecureStorageError({ operation: "read", key, cause });
}
}
async function writeStorageItem(key: MobileStorageKeyValue, value: string): Promise<void> {
try {
await SecureStore.setItemAsync(key, value);
} catch (cause) {
throw new MobileSecureStorageError({ operation: "write", key, cause });
}
}
async function readJsonStorageItem<T>(key: MobileStorageKeyValue): Promise<T | null> {
const raw = (await readStorageItem(key)) ?? "";
if (!raw.trim()) {
return null;
}
try {
return JSON.parse(raw) as T;
} catch (cause) {
console.warn(
"[mobile-storage] ignored invalid JSON",
new MobileStorageDecodeError({ key, cause }),
);
return null;
}
}
async function writeJsonStorageItem(key: MobileStorageKeyValue, value: unknown) {
let encoded: string;
try {
encoded = JSON.stringify(value);
} catch (cause) {
throw new MobileStorageEncodeError({ key, cause });
}
await writeStorageItem(key, encoded);
}
export async function loadSavedConnections(): Promise<ReadonlyArray<SavedRemoteConnection>> {
const parsed = await readJsonStorageItem<{
readonly connections?: ReadonlyArray<SavedRemoteConnection>;
}>(CONNECTIONS_KEY);
if (!parsed) {
return [];
}
return pipe(
parsed.connections ?? [],
Arr.filter(
(c) => !!c.environmentId && (!!c.bearerToken?.trim() || isRelayManagedConnection(c)),
),
);
}
export async function saveConnection(connection: SavedRemoteConnection): Promise<void> {
const current = await loadSavedConnections();
const stableConnection = toStableSavedRemoteConnection(connection);
const next = current.some((entry) => entry.environmentId === connection.environmentId)
? pipe(
current,
Arr.map((entry) =>
entry.environmentId === connection.environmentId ? stableConnection : entry,
),
)
: pipe(current, Arr.append(stableConnection));
await writeJsonStorageItem(CONNECTIONS_KEY, { connections: next });
}
export async function clearSavedConnection(environmentId: EnvironmentId): Promise<void> {
const current = await loadSavedConnections();
const next = pipe(
current,
Arr.filter((entry) => entry.environmentId !== environmentId),
);
await writeJsonStorageItem(CONNECTIONS_KEY, { connections: next });
}
export async function loadPreferences(): Promise<Preferences> {
const parsed = await readJsonStorageItem<Preferences>(PREFERENCES_KEY);
if (!parsed || typeof parsed !== "object") {
return {};
}
const preferences: {
liveActivitiesEnabled?: boolean;
baseFontSize?: number;
terminalFontSize?: number | null;
markdownFontSize?: number;
codeFontSize?: number | null;
codeWordBreak?: boolean;
connectOnboardingOptOutAccounts?: ReadonlyArray<string>;
} = {};
if (typeof parsed.liveActivitiesEnabled === "boolean") {
preferences.liveActivitiesEnabled = parsed.liveActivitiesEnabled;
}
if (typeof parsed.baseFontSize === "number") {
preferences.baseFontSize = parsed.baseFontSize;
}
if (typeof parsed.terminalFontSize === "number" || parsed.terminalFontSize === null) {
preferences.terminalFontSize = parsed.terminalFontSize;
}
if (typeof parsed.markdownFontSize === "number") {
preferences.markdownFontSize = parsed.markdownFontSize;
}
if (typeof parsed.codeFontSize === "number" || parsed.codeFontSize === null) {
preferences.codeFontSize = parsed.codeFontSize;
}
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> {
return updatePreferences(() => patch);
}
export async function loadOrCreateAgentAwarenessDeviceId(): Promise<string> {
const existing = await readStorageItem(AGENT_AWARENESS_DEVICE_ID_KEY);
if (existing?.trim()) {
return existing;
}
const deviceId = await import("./uuid")
.then(({ uuidv4 }) => uuidv4())
.catch((cause) => {
throw new MobileSecureStorageError({
operation: "generate-device-id",
key: AGENT_AWARENESS_DEVICE_ID_KEY,
cause,
});
});
await writeStorageItem(AGENT_AWARENESS_DEVICE_ID_KEY, deviceId);
return deviceId;
}
export async function loadAgentAwarenessDeviceId(): Promise<string | null> {
const existing = await readStorageItem(AGENT_AWARENESS_DEVICE_ID_KEY);
return existing?.trim() ? existing : null;
}
export interface AgentAwarenessRegistrationRecord {
readonly identity: string;
readonly signature: string;
// Last push-to-start token the relay accepted. Registrations triggered
// without a token event merge it back in so token absence never reads as a
// change (which would defeat the register-once skip every launch).
readonly pushToStartToken?: string;
}
// Remembers the account identity and payload signature the relay last accepted
// so the app does not re-register on every launch while nothing has changed.
// Cleared only on sign-out.
export async function loadAgentAwarenessRegistrationRecord(): Promise<AgentAwarenessRegistrationRecord | null> {
const parsed = await readJsonStorageItem<AgentAwarenessRegistrationRecord>(
AGENT_AWARENESS_REGISTRATION_KEY,
);
if (
!parsed ||
typeof parsed !== "object" ||
typeof parsed.identity !== "string" ||
typeof parsed.signature !== "string"
) {
return null;
}
return {
identity: parsed.identity,
signature: parsed.signature,
...(typeof parsed.pushToStartToken === "string" && parsed.pushToStartToken
? { pushToStartToken: parsed.pushToStartToken }
: {}),
};
}
export async function saveAgentAwarenessRegistrationRecord(
record: AgentAwarenessRegistrationRecord,
): Promise<void> {
await writeJsonStorageItem(AGENT_AWARENESS_REGISTRATION_KEY, record);
}
export async function clearAgentAwarenessRegistrationRecord(): Promise<void> {
await writeStorageItem(AGENT_AWARENESS_REGISTRATION_KEY, "");
}
-15
View File
@@ -1,15 +0,0 @@
import { useCSSVariable } from "uniwind";
const FONT_FAMILY_VARIABLES = {
regular: "--font-sans",
medium: "--font-medium",
bold: "--font-bold",
} as const;
/**
* Resolves a font family for APIs that require a style object or native prop.
* Prefer Uniwind font classes when the target component accepts `className`.
*/
export function useFontFamily(weight: keyof typeof FONT_FAMILY_VARIABLES): string {
return useCSSVariable(FONT_FAMILY_VARIABLES[weight]) as string;
}
@@ -15,7 +15,6 @@ import { Image, StyleSheet } from "react-native";
import { markdownFileIconSource } from "@t3tools/mobile-markdown-text/file-icons";
import { resolveMarkdownFileIcon } from "@t3tools/mobile-markdown-text/links";
import { useThemeColor } from "../lib/useThemeColor";
import { useFontFamily } from "../lib/useFontFamily";
import { useScaledTextRole } from "../features/settings/appearance/useScaledTextRole";
import {
acknowledgeComposerNativeEvent,
@@ -118,7 +117,6 @@ export function ComposerEditor({
const skillBorder = useThemeColor("--color-inline-skill-border");
const skillText = useThemeColor("--color-inline-skill-foreground");
const fileTint = useThemeColor("--color-icon-muted");
const fontFamily = useFontFamily("regular");
useImperativeHandle(
ref,
@@ -228,7 +226,9 @@ export function ComposerEditor({
themeJson={themeJson}
placeholder={props.placeholder ?? ""}
fontFamily={
typeof resolvedTextStyle.fontFamily === "string" ? resolvedTextStyle.fontFamily : fontFamily
typeof resolvedTextStyle.fontFamily === "string"
? resolvedTextStyle.fontFamily
: "DMSans_400Regular"
}
fontSize={
typeof resolvedTextStyle.fontSize === "number"
+1 -3
View File
@@ -3,7 +3,6 @@ import { useImperativeHandle, useRef } from "react";
import { TextInput, type TextInput as RNTextInput } from "react-native";
import { useThemeColor } from "../lib/useThemeColor";
import { useFontFamily } from "../lib/useFontFamily";
import { useScaledTextRole } from "../features/settings/appearance/useScaledTextRole";
import { useNativePaste } from "../lib/useNativePaste";
import type { ComposerEditorProps } from "./T3ComposerEditor.types";
@@ -22,7 +21,6 @@ export function ComposerEditor({
const bodyText = useScaledTextRole("body");
const foregroundColor = useThemeColor("--color-foreground");
const placeholderColor = useThemeColor("--color-placeholder");
const fontFamily = useFontFamily("regular");
const handlePaste = useNativePaste((uris) => onPasteImages?.(uris));
useImperativeHandle(
@@ -50,7 +48,7 @@ export function ComposerEditor({
flex: 1,
minHeight: 0,
color: foregroundColor,
fontFamily,
fontFamily: "DMSans_400Regular",
...bodyText,
paddingVertical: contentInsetVertical,
},
@@ -9,5 +9,5 @@ export function T3KeyboardCommands(
readonly onCommand: (command: HardwareKeyboardCommand) => void;
}>,
) {
return <View className="flex-1">{props.children}</View>;
return <View style={{ flex: 1 }}>{props.children}</View>;
}
-47
View File
@@ -1,47 +0,0 @@
import * as Effect from "effect/Effect";
import { runtime } from "../lib/runtime";
import * as MobilePreferences from "./mobile-preferences";
import * as MobileStorage from "./mobile-storage";
export type { Preferences } from "./mobile-preferences";
export type { AgentAwarenessRegistrationRecord } from "./mobile-storage";
export { MobilePreferencesLoadError, MobilePreferencesSaveError } from "./mobile-preferences";
export {
MobileDeviceIdGenerationError,
MobileStorageDecodeError,
MobileStorageEncodeError,
} from "./mobile-storage";
export { MobileSecureStorageError } from "./mobile-secure-storage";
const runStorage = <A, E>(
use: (storage: MobileStorage.MobileStorage["Service"]) => Effect.Effect<A, E>,
) => runtime.runPromise(MobileStorage.MobileStorage.pipe(Effect.flatMap(use)));
const runPreferences = <A, E>(
use: (store: MobilePreferences.MobilePreferencesStore["Service"]) => Effect.Effect<A, E>,
) => runtime.runPromise(MobilePreferences.MobilePreferencesStore.pipe(Effect.flatMap(use)));
export const loadSavedConnections = () => runStorage((storage) => storage.loadSavedConnections);
export const saveConnection = (
connection: Parameters<MobileStorage.MobileStorage["Service"]["saveConnection"]>[0],
) => runStorage((storage) => storage.saveConnection(connection));
export const loadPreferences = () => runPreferences((store) => store.load);
export const savePreferencesPatch = (patch: Partial<MobilePreferences.Preferences>) =>
runPreferences((store) => store.savePatch(patch));
export const updatePreferences = (
transform: (current: MobilePreferences.Preferences) => Partial<MobilePreferences.Preferences>,
) => runPreferences((store) => store.update(transform));
export const loadOrCreateAgentAwarenessDeviceId = () =>
runStorage((storage) => storage.loadOrCreateAgentAwarenessDeviceId);
export const loadAgentAwarenessDeviceId = () =>
runStorage((storage) => storage.loadAgentAwarenessDeviceId);
export const loadAgentAwarenessRegistrationRecord = () =>
runStorage((storage) => storage.loadAgentAwarenessRegistrationRecord);
export const saveAgentAwarenessRegistrationRecord = (
record: MobileStorage.AgentAwarenessRegistrationRecord,
) => runStorage((storage) => storage.saveAgentAwarenessRegistrationRecord(record));
export const clearAgentAwarenessRegistrationRecord = () =>
runStorage((storage) => storage.clearAgentAwarenessRegistrationRecord);
-16
View File
@@ -1,16 +0,0 @@
import * as Layer from "effect/Layer";
import * as EnvironmentCacheStore from "../connection/environment-cache-store";
import * as MobileDatabase from "./mobile-database";
import * as MobilePreferences from "./mobile-preferences";
import * as MobileSecureStorage from "./mobile-secure-storage";
import * as MobileStorage from "./mobile-storage";
const baseLayer = Layer.merge(MobileDatabase.layer, MobileSecureStorage.layer);
const dependentLayer = Layer.mergeAll(
MobilePreferences.layer,
MobileStorage.layer,
EnvironmentCacheStore.layer,
).pipe(Layer.provide(baseLayer));
export const layer = Layer.merge(baseLayer, dependentLayer);
@@ -1,71 +0,0 @@
import { describe, expect, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import { vi } from "vite-plus/test";
const openDatabaseAsync = vi.hoisted(() => vi.fn());
vi.mock("expo-sqlite", () => ({ openDatabaseAsync }));
import { decodeLegacyCacheRecord, make } from "./mobile-database";
describe("mobile database legacy cache migration", () => {
it.effect("keeps acquisition failures typed on database operations", () =>
Effect.scoped(
Effect.gen(function* () {
openDatabaseAsync.mockRejectedValueOnce(new Error("SQLite unavailable"));
const database = yield* make;
const result = yield* Effect.result(database.loadPreferencesJson);
expect(result).toMatchObject({
_tag: "Failure",
failure: { _tag: "MobileDatabaseError", operation: "open" },
});
}),
),
);
it("maps legacy thread records to their SQLite identity", () => {
const payload = JSON.stringify({
schemaVersion: 2,
environmentId: "environment-1",
threadId: "thread-1",
snapshot: {},
});
expect(decodeLegacyCacheRecord("connection-thread-snapshots", payload)).toEqual({
environmentId: "environment-1",
kind: "thread",
cacheKey: "thread-1",
schemaVersion: 2,
payload,
});
});
it("preserves the old shell payload for schema decoding after migration", () => {
const payload = JSON.stringify({
schemaVersion: 1,
environmentId: "environment-1",
snapshotReceivedAt: "2026-07-01T00:00:00.000Z",
snapshot: {},
});
expect(decodeLegacyCacheRecord("shell-snapshots", payload)).toEqual({
environmentId: "environment-1",
kind: "shell",
cacheKey: "snapshot",
schemaVersion: 1,
payload,
});
});
it("skips malformed legacy records", () => {
expect(decodeLegacyCacheRecord("connection-vcs-refs", "{not-json")).toBeNull();
expect(
decodeLegacyCacheRecord(
"connection-vcs-refs",
JSON.stringify({ schemaVersion: 1, environmentId: "environment-1" }),
),
).toBeNull();
});
});
@@ -1,409 +0,0 @@
import type { EnvironmentId } from "@t3tools/contracts";
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
import type { SQLiteDatabase } from "expo-sqlite";
const DATABASE_NAME = "t3code-client.db";
const DATABASE_SCHEMA_VERSION = 1;
const LEGACY_CACHE_DIRECTORIES = [
"connection-shell-snapshots",
"shell-snapshots",
"connection-thread-snapshots",
"connection-server-configs",
"connection-vcs-refs",
] as const;
export const ClientCacheKind = Schema.Literals(["shell", "thread", "server-config", "vcs-refs"]);
export type ClientCacheKind = typeof ClientCacheKind.Type;
export interface ClientCacheSummaryRow {
readonly environmentId: EnvironmentId;
readonly kind: ClientCacheKind;
readonly recordCount: number;
readonly payloadBytes: number;
}
export interface StoredPreferencesJson {
readonly payload: string;
readonly updatedAt: number;
}
const ClientCacheSummaryRows = Schema.Array(
Schema.Struct({
environmentId: Schema.String,
kind: ClientCacheKind,
recordCount: Schema.Number,
payloadBytes: Schema.Number,
}),
);
const MobileDatabaseOperation = Schema.Literals([
"open",
"migrate",
"load-cache",
"save-cache",
"remove-cache",
"clear-environment-cache",
"clear-all-caches",
"inspect-caches",
"load-preferences",
"save-preferences",
]);
export class MobileDatabaseError extends Schema.TaggedErrorClass<MobileDatabaseError>()(
"MobileDatabaseError",
{
operation: MobileDatabaseOperation,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Mobile database operation failed: ${this.operation}.`;
}
}
function databaseError(operation: typeof MobileDatabaseOperation.Type) {
return (cause: unknown) => new MobileDatabaseError({ operation, cause });
}
interface LegacyCacheRecord {
readonly environmentId: string;
readonly kind: ClientCacheKind;
readonly cacheKey: string;
readonly schemaVersion: number;
readonly payload: string;
}
function objectRecord(value: unknown): Record<string, unknown> | null {
return typeof value === "object" && value !== null ? (value as Record<string, unknown>) : null;
}
export function decodeLegacyCacheRecord(
directoryName: (typeof LEGACY_CACHE_DIRECTORIES)[number],
payload: string,
): LegacyCacheRecord | null {
let parsed: Record<string, unknown> | null;
try {
parsed = objectRecord(JSON.parse(payload));
} catch {
return null;
}
if (
parsed === null ||
typeof parsed.environmentId !== "string" ||
typeof parsed.schemaVersion !== "number"
) {
return null;
}
switch (directoryName) {
case "connection-shell-snapshots":
case "shell-snapshots":
return {
environmentId: parsed.environmentId,
kind: "shell",
cacheKey: "snapshot",
schemaVersion: parsed.schemaVersion,
payload,
};
case "connection-thread-snapshots":
return typeof parsed.threadId === "string"
? {
environmentId: parsed.environmentId,
kind: "thread",
cacheKey: parsed.threadId,
schemaVersion: parsed.schemaVersion,
payload,
}
: null;
case "connection-server-configs":
return {
environmentId: parsed.environmentId,
kind: "server-config",
cacheKey: "config",
schemaVersion: parsed.schemaVersion,
payload,
};
case "connection-vcs-refs":
return typeof parsed.cwd === "string"
? {
environmentId: parsed.environmentId,
kind: "vcs-refs",
cacheKey: parsed.cwd,
schemaVersion: parsed.schemaVersion,
payload,
}
: null;
}
}
async function migrateLegacyFileCaches(database: SQLiteDatabase): Promise<boolean> {
try {
const { Directory, File, Paths } = await import("expo-file-system");
let complete = true;
const listFiles = (
directory: InstanceType<typeof Directory>,
): Array<InstanceType<typeof File>> =>
directory.list().flatMap((entry) => (entry instanceof File ? [entry] : listFiles(entry)));
for (const directoryName of LEGACY_CACHE_DIRECTORIES) {
try {
const directory = new Directory(Paths.document, directoryName);
if (!directory.exists) continue;
for (const file of listFiles(directory)) {
const payload = await file.text();
const record = decodeLegacyCacheRecord(directoryName, payload);
if (record === null) continue;
await database.runAsync(
`INSERT INTO client_cache
(environment_id, kind, cache_key, schema_version, payload, updated_at)
VALUES (?, ?, ?, ?, ?, ?)
ON CONFLICT (environment_id, kind, cache_key) DO NOTHING`,
record.environmentId,
record.kind,
record.cacheKey,
record.schemaVersion,
record.payload,
Date.now(),
);
}
directory.delete();
} catch (cause) {
complete = false;
console.warn(`[mobile-database] could not migrate legacy cache ${directoryName}`, cause);
}
}
return complete;
} catch (cause) {
console.warn("[mobile-database] could not load legacy cache migration", cause);
return false;
}
}
export class MobileDatabase extends Context.Service<
MobileDatabase,
{
readonly loadCache: (
environmentId: EnvironmentId,
kind: ClientCacheKind,
cacheKey: string,
) => Effect.Effect<Option.Option<string>, MobileDatabaseError>;
readonly saveCache: (
environmentId: EnvironmentId,
kind: ClientCacheKind,
cacheKey: string,
schemaVersion: number,
payload: string,
) => Effect.Effect<void, MobileDatabaseError>;
readonly removeCache: (
environmentId: EnvironmentId,
kind: ClientCacheKind,
cacheKey: string,
) => Effect.Effect<void, MobileDatabaseError>;
readonly clearEnvironmentCache: (
environmentId: EnvironmentId,
) => Effect.Effect<void, MobileDatabaseError>;
readonly clearAllCaches: Effect.Effect<void, MobileDatabaseError>;
readonly inspectCaches: Effect.Effect<
ReadonlyArray<ClientCacheSummaryRow>,
MobileDatabaseError
>;
readonly loadPreferencesJson: Effect.Effect<
Option.Option<StoredPreferencesJson>,
MobileDatabaseError
>;
readonly savePreferencesJson: (
payload: string,
updatedAt: number,
) => Effect.Effect<void, MobileDatabaseError>;
}
>()("@t3tools/mobile/persistence/MobileDatabase") {}
const makeAvailable = Effect.gen(function* () {
const database = yield* Effect.acquireRelease(
Effect.tryPromise({
try: async () => {
const SQLite = await import("expo-sqlite");
return SQLite.openDatabaseAsync(DATABASE_NAME);
},
catch: databaseError("open"),
}),
(openDatabase) => Effect.promise(() => openDatabase.closeAsync()).pipe(Effect.ignore),
);
yield* Effect.tryPromise({
try: async () => {
await database.execAsync("PRAGMA journal_mode = WAL; PRAGMA foreign_keys = ON;");
const schema = await database.getFirstAsync<{ readonly user_version: number }>(
"PRAGMA user_version",
);
await database.withExclusiveTransactionAsync(async (transaction) => {
await transaction.execAsync(`
CREATE TABLE IF NOT EXISTS client_cache (
environment_id TEXT NOT NULL,
kind TEXT NOT NULL,
cache_key TEXT NOT NULL,
schema_version INTEGER NOT NULL,
payload TEXT NOT NULL,
updated_at INTEGER NOT NULL,
PRIMARY KEY (environment_id, kind, cache_key)
) WITHOUT ROWID;
CREATE INDEX IF NOT EXISTS client_cache_environment_updated
ON client_cache (environment_id, updated_at DESC);
CREATE TABLE IF NOT EXISTS client_preferences (
singleton INTEGER PRIMARY KEY NOT NULL CHECK (singleton = 1),
payload TEXT NOT NULL,
updated_at INTEGER NOT NULL
);
`);
});
if ((schema?.user_version ?? 0) < DATABASE_SCHEMA_VERSION) {
const migrated = await migrateLegacyFileCaches(database);
if (migrated) {
await database.execAsync(`PRAGMA user_version = ${DATABASE_SCHEMA_VERSION};`);
}
}
},
catch: databaseError("migrate"),
});
return MobileDatabase.of({
loadCache: Effect.fn("MobileDatabase.loadCache")((environmentId, kind, cacheKey) =>
Effect.tryPromise({
try: () =>
database.getFirstAsync<{ readonly payload: string }>(
`SELECT payload
FROM client_cache
WHERE environment_id = ? AND kind = ? AND cache_key = ?`,
environmentId,
kind,
cacheKey,
),
catch: databaseError("load-cache"),
}).pipe(Effect.map((row) => Option.fromNullishOr(row?.payload))),
),
saveCache: Effect.fn("MobileDatabase.saveCache")(
(environmentId, kind, cacheKey, schemaVersion, payload) =>
Effect.tryPromise({
try: () =>
database.runAsync(
`INSERT INTO client_cache
(environment_id, kind, cache_key, schema_version, payload, updated_at)
VALUES (?, ?, ?, ?, ?, ?)
ON CONFLICT (environment_id, kind, cache_key) DO UPDATE SET
schema_version = excluded.schema_version,
payload = excluded.payload,
updated_at = excluded.updated_at`,
environmentId,
kind,
cacheKey,
schemaVersion,
payload,
Date.now(),
),
catch: databaseError("save-cache"),
}).pipe(Effect.asVoid),
),
removeCache: Effect.fn("MobileDatabase.removeCache")((environmentId, kind, cacheKey) =>
Effect.tryPromise({
try: () =>
database.runAsync(
`DELETE FROM client_cache
WHERE environment_id = ? AND kind = ? AND cache_key = ?`,
environmentId,
kind,
cacheKey,
),
catch: databaseError("remove-cache"),
}).pipe(Effect.asVoid),
),
clearEnvironmentCache: Effect.fn("MobileDatabase.clearEnvironmentCache")((environmentId) =>
Effect.tryPromise({
try: () =>
database.runAsync("DELETE FROM client_cache WHERE environment_id = ?", environmentId),
catch: databaseError("clear-environment-cache"),
}).pipe(Effect.asVoid),
),
clearAllCaches: Effect.tryPromise({
try: () => database.runAsync("DELETE FROM client_cache"),
catch: databaseError("clear-all-caches"),
}).pipe(Effect.asVoid),
inspectCaches: Effect.tryPromise({
try: () =>
database.getAllAsync<unknown>(`
SELECT
environment_id AS environmentId,
kind,
COUNT(*) AS recordCount,
COALESCE(SUM(LENGTH(CAST(payload AS BLOB))), 0) AS payloadBytes
FROM client_cache
GROUP BY environment_id, kind
ORDER BY environment_id, kind
`),
catch: databaseError("inspect-caches"),
}).pipe(
Effect.flatMap(Schema.decodeUnknownEffect(ClientCacheSummaryRows)),
Effect.mapError(databaseError("inspect-caches")),
Effect.map(
(rows): ReadonlyArray<ClientCacheSummaryRow> =>
rows.map((row) => ({
environmentId: row.environmentId as EnvironmentId,
kind: row.kind,
recordCount: row.recordCount,
payloadBytes: row.payloadBytes,
})),
),
),
loadPreferencesJson: Effect.tryPromise({
try: () =>
database.getFirstAsync<StoredPreferencesJson>(
`SELECT payload, updated_at AS updatedAt
FROM client_preferences
WHERE singleton = 1`,
),
catch: databaseError("load-preferences"),
}).pipe(Effect.map(Option.fromNullishOr)),
savePreferencesJson: Effect.fn("MobileDatabase.savePreferencesJson")((payload, updatedAt) =>
Effect.tryPromise({
try: () =>
database.runAsync(
`INSERT INTO client_preferences (singleton, payload, updated_at)
VALUES (1, ?, ?)
ON CONFLICT (singleton) DO UPDATE SET
payload = excluded.payload,
updated_at = excluded.updated_at`,
payload,
updatedAt,
),
catch: databaseError("save-preferences"),
}).pipe(Effect.asVoid),
),
});
});
function makeUnavailable(error: MobileDatabaseError): MobileDatabase["Service"] {
const fail = Effect.fail(error);
return MobileDatabase.of({
loadCache: () => fail,
saveCache: () => fail,
removeCache: () => fail,
clearEnvironmentCache: () => fail,
clearAllCaches: fail,
inspectCaches: fail,
loadPreferencesJson: fail,
savePreferencesJson: () => fail,
});
}
export const make = Effect.result(makeAvailable).pipe(
Effect.map((result) =>
result._tag === "Success" ? result.success : makeUnavailable(result.failure),
),
);
export const layer = Layer.effect(MobileDatabase, make);
@@ -1,305 +0,0 @@
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Ref from "effect/Ref";
import * as Schema from "effect/Schema";
import * as Semaphore from "effect/Semaphore";
import * as MobileDatabase from "./mobile-database";
import * as MobileSecureStorage from "./mobile-secure-storage";
import { MobileStorageDecodeError, MobileStorageEncodeError } from "./mobile-storage";
const PREFERENCES_KEY = "t3code.preferences";
const PREFERENCES_FALLBACK_KEY = "t3code.preferences.fallback";
export interface Preferences {
readonly liveActivitiesEnabled?: boolean;
readonly baseFontSize?: number;
readonly terminalFontSize?: number | null;
readonly markdownFontSize?: number;
readonly codeFontSize?: number | null;
readonly codeWordBreak?: boolean;
readonly connectOnboardingOptOutAccounts?: ReadonlyArray<string>;
readonly collapsedProjectGroups?: readonly string[];
}
export class MobilePreferencesLoadError extends Schema.TaggedErrorClass<MobilePreferencesLoadError>()(
"MobilePreferencesLoadError",
{ cause: Schema.Defect() },
) {
override get message(): string {
return "Failed to load mobile preferences.";
}
}
export class MobilePreferencesSaveError extends Schema.TaggedErrorClass<MobilePreferencesSaveError>()(
"MobilePreferencesSaveError",
{ cause: Schema.Defect() },
) {
override get message(): string {
return "Failed to save mobile preferences.";
}
}
interface PreferencesFallback {
readonly payload: string;
readonly updatedAt: number;
readonly preferences: Preferences;
}
export class MobilePreferencesStore extends Context.Service<
MobilePreferencesStore,
{
readonly load: Effect.Effect<Preferences, MobilePreferencesLoadError>;
readonly savePatch: (
patch: Partial<Preferences>,
) => Effect.Effect<Preferences, MobilePreferencesSaveError>;
readonly update: (
transform: (current: Preferences) => Partial<Preferences>,
) => Effect.Effect<Preferences, MobilePreferencesSaveError>;
}
>()("@t3tools/mobile/persistence/MobilePreferencesStore") {}
function sanitizePreferences(parsed: Preferences): Preferences {
const preferences: {
liveActivitiesEnabled?: boolean;
baseFontSize?: number;
terminalFontSize?: number | null;
markdownFontSize?: number;
codeFontSize?: number | null;
codeWordBreak?: boolean;
connectOnboardingOptOutAccounts?: ReadonlyArray<string>;
collapsedProjectGroups?: readonly string[];
} = {};
if (typeof parsed.liveActivitiesEnabled === "boolean") {
preferences.liveActivitiesEnabled = parsed.liveActivitiesEnabled;
}
if (typeof parsed.baseFontSize === "number") preferences.baseFontSize = parsed.baseFontSize;
if (typeof parsed.terminalFontSize === "number" || parsed.terminalFontSize === null) {
preferences.terminalFontSize = parsed.terminalFontSize;
}
if (typeof parsed.markdownFontSize === "number") {
preferences.markdownFontSize = parsed.markdownFontSize;
}
if (typeof parsed.codeFontSize === "number" || parsed.codeFontSize === null) {
preferences.codeFontSize = parsed.codeFontSize;
}
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",
);
}
if (Array.isArray(parsed.collapsedProjectGroups)) {
preferences.collapsedProjectGroups = parsed.collapsedProjectGroups.filter(
(key): key is string => typeof key === "string",
);
}
return preferences;
}
export const make = Effect.fn("MobilePreferencesStore.make")(function* () {
const database = yield* MobileDatabase.MobileDatabase;
const secureStorage = yield* MobileSecureStorage.MobileSecureStorage;
const lock = yield* Semaphore.make(1);
const lastUpdatedAt = yield* Ref.make(0);
const parsePayload = (raw: string | null): Preferences | null => {
if (raw === null || !raw.trim()) return null;
let parsed: unknown;
try {
parsed = JSON.parse(raw);
} catch (cause) {
console.warn(
"[mobile-storage] ignored invalid JSON",
new MobileStorageDecodeError({ key: PREFERENCES_KEY, cause }),
);
return null;
}
return typeof parsed === "object" && parsed !== null && !Array.isArray(parsed)
? (parsed as Preferences)
: null;
};
const parseFallback = (raw: string | null): PreferencesFallback | null => {
if (raw === null || !raw.trim()) return null;
let parsed: unknown;
try {
parsed = JSON.parse(raw);
} catch (cause) {
console.warn(
"[mobile-storage] ignored invalid JSON",
new MobileStorageDecodeError({ key: PREFERENCES_FALLBACK_KEY, cause }),
);
return null;
}
if (
typeof parsed !== "object" ||
parsed === null ||
!("payload" in parsed) ||
typeof parsed.payload !== "string" ||
!("updatedAt" in parsed) ||
typeof parsed.updatedAt !== "number"
) {
return null;
}
const preferences = parsePayload(parsed.payload);
return preferences === null
? null
: { payload: parsed.payload, updatedAt: parsed.updatedAt, preferences };
};
const encode = Effect.fn("MobilePreferencesStore.encode")(function* (
key: string,
value: unknown,
) {
return yield* Effect.try({
try: () => JSON.stringify(value),
catch: (cause) => new MobileStorageEncodeError({ key, cause }),
});
});
const nextUpdatedAt = Ref.modify(lastUpdatedAt, (last) => {
const next = Math.max(Date.now(), last + 1);
return [next, next] as const;
});
const saveJson = Effect.fn("MobilePreferencesStore.saveJson")(function* (
payload: string,
updatedAt?: number,
) {
const timestamp = updatedAt ?? (yield* nextUpdatedAt);
yield* Ref.update(lastUpdatedAt, (last) => Math.max(last, timestamp));
const databaseResult = yield* Effect.result(database.savePreferencesJson(payload, timestamp));
if (databaseResult._tag === "Failure") {
yield* Effect.logWarning("Database unavailable; saving preferences to secure storage.").pipe(
Effect.annotateLogs({ cause: databaseResult.failure }),
);
const fallback = yield* encode(PREFERENCES_FALLBACK_KEY, { payload, updatedAt: timestamp });
yield* secureStorage.setItem(PREFERENCES_FALLBACK_KEY, fallback);
return;
}
yield* secureStorage
.removeItem(PREFERENCES_FALLBACK_KEY)
.pipe(
Effect.catch((error) =>
Effect.logWarning("Could not remove the mobile preferences fallback.").pipe(
Effect.annotateLogs({ error }),
),
),
);
});
const loadUnlocked = Effect.gen(function* () {
const databaseResult = yield* Effect.result(database.loadPreferencesJson);
const databaseAvailable = databaseResult._tag === "Success";
const storedJson = databaseAvailable
? databaseResult.success
: Option.none<MobileDatabase.StoredPreferencesJson>();
if (databaseResult._tag === "Failure") {
yield* Effect.logWarning("Database unavailable; loading fallback preferences.").pipe(
Effect.annotateLogs({ cause: databaseResult.failure }),
);
}
const fallbackResult = yield* Effect.result(secureStorage.getItem(PREFERENCES_FALLBACK_KEY));
let fallbackJson: string | null = null;
if (fallbackResult._tag === "Success") {
fallbackJson = fallbackResult.success;
} else if (Option.isNone(storedJson)) {
return yield* fallbackResult.failure;
} else {
yield* Effect.logWarning("Could not inspect the mobile preferences fallback.").pipe(
Effect.annotateLogs({ error: fallbackResult.failure }),
);
}
const fallback = parseFallback(fallbackJson);
const storedPreferences = Option.isSome(storedJson)
? parsePayload(storedJson.value.payload)
: null;
const fallbackIsNewer =
fallback !== null &&
(storedPreferences === null ||
(Option.isSome(storedJson) && fallback.updatedAt > storedJson.value.updatedAt));
let parsed: Preferences | null = null;
if (fallbackIsNewer) {
parsed = fallback.preferences;
yield* Ref.update(lastUpdatedAt, (last) => Math.max(last, fallback.updatedAt));
if (databaseAvailable) yield* saveJson(fallback.payload, fallback.updatedAt);
} else if (storedPreferences !== null && Option.isSome(storedJson)) {
parsed = storedPreferences;
yield* Ref.update(lastUpdatedAt, (last) => Math.max(last, storedJson.value.updatedAt));
if (fallbackJson !== null) {
yield* secureStorage
.removeItem(PREFERENCES_FALLBACK_KEY)
.pipe(
Effect.catch((error) =>
Effect.logWarning("Could not remove a stale mobile preferences fallback.").pipe(
Effect.annotateLogs({ error }),
),
),
);
}
}
if (parsed === null) {
const legacyJson = yield* secureStorage.getItem(PREFERENCES_KEY);
const legacyPreferences = parsePayload(legacyJson);
parsed = legacyPreferences;
if (legacyJson !== null && legacyPreferences !== null && databaseAvailable) {
yield* saveJson(legacyJson);
yield* secureStorage
.removeItem(PREFERENCES_KEY)
.pipe(
Effect.catch((error) =>
Effect.logWarning("Could not remove migrated mobile preferences.").pipe(
Effect.annotateLogs({ error }),
),
),
);
}
}
return parsed === null ? {} : sanitizePreferences(parsed);
});
const load = lock
.withPermits(1)(loadUnlocked)
.pipe(Effect.mapError((cause) => new MobilePreferencesLoadError({ cause })));
const update = Effect.fn("MobilePreferencesStore.update")((transform) =>
lock
.withPermits(1)(
Effect.gen(function* () {
const current = yield* loadUnlocked;
const patch = yield* Effect.try({
try: () => transform(current),
catch: (cause) => new MobilePreferencesSaveError({ cause }),
});
const next: Preferences = { ...current, ...patch };
const payload = yield* encode(PREFERENCES_KEY, next);
yield* saveJson(payload);
return next;
}),
)
.pipe(
Effect.mapError((cause) =>
cause instanceof MobilePreferencesSaveError
? cause
: new MobilePreferencesSaveError({ cause }),
),
),
);
return MobilePreferencesStore.of({
load,
update,
savePatch: (patch) => update(() => patch),
});
});
export const layer = Layer.effect(MobilePreferencesStore, make());
@@ -1,52 +0,0 @@
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Schema from "effect/Schema";
import * as SecureStore from "expo-secure-store";
const MobileSecureStorageOperation = Schema.Literals(["read", "write", "delete"]);
export class MobileSecureStorageError extends Schema.TaggedErrorClass<MobileSecureStorageError>()(
"MobileSecureStorageError",
{
operation: MobileSecureStorageOperation,
key: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Mobile secure storage operation ${this.operation} failed for key ${this.key}.`;
}
}
export class MobileSecureStorage extends Context.Service<
MobileSecureStorage,
{
readonly getItem: (key: string) => Effect.Effect<string | null, MobileSecureStorageError>;
readonly setItem: (key: string, value: string) => Effect.Effect<void, MobileSecureStorageError>;
readonly removeItem: (key: string) => Effect.Effect<void, MobileSecureStorageError>;
}
>()("@t3tools/mobile/persistence/MobileSecureStorage") {}
export const make = MobileSecureStorage.of({
getItem: Effect.fn("MobileSecureStorage.getItem")((key) =>
Effect.tryPromise({
try: () => SecureStore.getItemAsync(key),
catch: (cause) => new MobileSecureStorageError({ operation: "read", key, cause }),
}),
),
setItem: Effect.fn("MobileSecureStorage.setItem")((key, value) =>
Effect.tryPromise({
try: () => SecureStore.setItemAsync(key, value),
catch: (cause) => new MobileSecureStorageError({ operation: "write", key, cause }),
}),
),
removeItem: Effect.fn("MobileSecureStorage.removeItem")((key) =>
Effect.tryPromise({
try: () => SecureStore.deleteItemAsync(key),
catch: (cause) => new MobileSecureStorageError({ operation: "delete", key, cause }),
}),
),
});
export const layer = Layer.succeed(MobileSecureStorage, make);
@@ -1,227 +0,0 @@
import { EnvironmentId } from "@t3tools/contracts";
import * as Arr from "effect/Array";
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import { pipe } from "effect/Function";
import * as Layer from "effect/Layer";
import * as Schema from "effect/Schema";
import {
isRelayManagedConnection,
type SavedRemoteConnection,
toStableSavedRemoteConnection,
} from "../lib/connection";
import * as MobileSecureStorage from "./mobile-secure-storage";
const CONNECTIONS_KEY = "t3code.connections";
const AGENT_AWARENESS_DEVICE_ID_KEY = "t3code.agent-awareness.device-id";
const AGENT_AWARENESS_REGISTRATION_KEY = "t3code.agent-awareness.registration";
export class MobileStorageDecodeError extends Schema.TaggedErrorClass<MobileStorageDecodeError>()(
"MobileStorageDecodeError",
{
key: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to decode mobile storage value for key ${this.key}.`;
}
}
export class MobileStorageEncodeError extends Schema.TaggedErrorClass<MobileStorageEncodeError>()(
"MobileStorageEncodeError",
{
key: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to encode mobile storage value for key ${this.key}.`;
}
}
export class MobileDeviceIdGenerationError extends Schema.TaggedErrorClass<MobileDeviceIdGenerationError>()(
"MobileDeviceIdGenerationError",
{ cause: Schema.Defect() },
) {
override get message(): string {
return "Failed to generate the mobile agent-awareness device id.";
}
}
export interface AgentAwarenessRegistrationRecord {
readonly identity: string;
readonly signature: string;
readonly pushToStartToken?: string;
}
export class MobileStorage extends Context.Service<
MobileStorage,
{
readonly loadSavedConnections: Effect.Effect<
ReadonlyArray<SavedRemoteConnection>,
MobileSecureStorage.MobileSecureStorageError
>;
readonly saveConnection: (
connection: SavedRemoteConnection,
) => Effect.Effect<
void,
MobileSecureStorage.MobileSecureStorageError | MobileStorageEncodeError
>;
readonly clearSavedConnection: (
environmentId: EnvironmentId,
) => Effect.Effect<
void,
MobileSecureStorage.MobileSecureStorageError | MobileStorageEncodeError
>;
readonly loadOrCreateAgentAwarenessDeviceId: Effect.Effect<
string,
MobileSecureStorage.MobileSecureStorageError | MobileDeviceIdGenerationError
>;
readonly loadAgentAwarenessDeviceId: Effect.Effect<
string | null,
MobileSecureStorage.MobileSecureStorageError
>;
readonly loadAgentAwarenessRegistrationRecord: Effect.Effect<
AgentAwarenessRegistrationRecord | null,
MobileSecureStorage.MobileSecureStorageError
>;
readonly saveAgentAwarenessRegistrationRecord: (
record: AgentAwarenessRegistrationRecord,
) => Effect.Effect<
void,
MobileSecureStorage.MobileSecureStorageError | MobileStorageEncodeError
>;
readonly clearAgentAwarenessRegistrationRecord: Effect.Effect<
void,
MobileSecureStorage.MobileSecureStorageError
>;
}
>()("@t3tools/mobile/persistence/MobileStorage") {}
export const make = Effect.fn("MobileStorage.make")(function* () {
const secureStorage = yield* MobileSecureStorage.MobileSecureStorage;
const parseJson = <A>(key: string, raw: string): A | null => {
if (!raw.trim()) return null;
try {
return JSON.parse(raw) as A;
} catch (cause) {
console.warn(
"[mobile-storage] ignored invalid JSON",
new MobileStorageDecodeError({ key, cause }),
);
return null;
}
};
const readJson = Effect.fn("MobileStorage.readJson")(function* <A>(key: string) {
const raw = (yield* secureStorage.getItem(key)) ?? "";
return parseJson<A>(key, raw);
});
const writeJson = Effect.fn("MobileStorage.writeJson")(function* (key: string, value: unknown) {
const encoded = yield* Effect.try({
try: () => JSON.stringify(value),
catch: (cause) => new MobileStorageEncodeError({ key, cause }),
});
yield* secureStorage.setItem(key, encoded);
});
const loadSavedConnections = readJson<{
readonly connections?: ReadonlyArray<SavedRemoteConnection>;
}>(CONNECTIONS_KEY).pipe(
Effect.map((parsed) =>
pipe(
parsed?.connections ?? [],
Arr.filter(
(connection) =>
!!connection.environmentId &&
(!!connection.bearerToken?.trim() || isRelayManagedConnection(connection)),
),
),
),
);
const saveConnection = Effect.fn("MobileStorage.saveConnection")(function* (
connection: SavedRemoteConnection,
) {
const current = yield* loadSavedConnections;
const stableConnection = toStableSavedRemoteConnection(connection);
const next = current.some((entry) => entry.environmentId === connection.environmentId)
? pipe(
current,
Arr.map((entry) =>
entry.environmentId === connection.environmentId ? stableConnection : entry,
),
)
: pipe(current, Arr.append(stableConnection));
yield* writeJson(CONNECTIONS_KEY, { connections: next });
});
const clearSavedConnection = Effect.fn("MobileStorage.clearSavedConnection")(function* (
environmentId: EnvironmentId,
) {
const current = yield* loadSavedConnections;
const next = pipe(
current,
Arr.filter((entry) => entry.environmentId !== environmentId),
);
yield* writeJson(CONNECTIONS_KEY, { connections: next });
});
const loadOrCreateAgentAwarenessDeviceId = Effect.gen(function* () {
const existing = yield* secureStorage.getItem(AGENT_AWARENESS_DEVICE_ID_KEY);
if (existing?.trim()) return existing;
const deviceId = yield* Effect.tryPromise({
try: () => import("../lib/uuid").then(({ uuidv4 }) => uuidv4()),
catch: (cause) => new MobileDeviceIdGenerationError({ cause }),
});
yield* secureStorage.setItem(AGENT_AWARENESS_DEVICE_ID_KEY, deviceId);
return deviceId;
});
const loadAgentAwarenessDeviceId = secureStorage
.getItem(AGENT_AWARENESS_DEVICE_ID_KEY)
.pipe(Effect.map((existing) => (existing?.trim() ? existing : null)));
const loadAgentAwarenessRegistrationRecord = readJson<AgentAwarenessRegistrationRecord>(
AGENT_AWARENESS_REGISTRATION_KEY,
).pipe(
Effect.map((parsed) => {
if (
!parsed ||
typeof parsed !== "object" ||
typeof parsed.identity !== "string" ||
typeof parsed.signature !== "string"
) {
return null;
}
return {
identity: parsed.identity,
signature: parsed.signature,
...(typeof parsed.pushToStartToken === "string" && parsed.pushToStartToken
? { pushToStartToken: parsed.pushToStartToken }
: {}),
};
}),
);
return MobileStorage.of({
loadSavedConnections,
saveConnection,
clearSavedConnection,
loadOrCreateAgentAwarenessDeviceId,
loadAgentAwarenessDeviceId,
loadAgentAwarenessRegistrationRecord,
saveAgentAwarenessRegistrationRecord: (record) =>
writeJson(AGENT_AWARENESS_REGISTRATION_KEY, record),
clearAgentAwarenessRegistrationRecord: secureStorage.setItem(
AGENT_AWARENESS_REGISTRATION_KEY,
"",
),
});
});
export const layer = Layer.effect(MobileStorage, make());
@@ -1,87 +0,0 @@
import type { EnvironmentId } from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import { Atom } from "effect/unstable/reactivity";
import { type ClientCacheKind, MobileDatabase } from "../persistence/mobile-database";
import * as Runtime from "../lib/runtime";
export interface EnvironmentClientCacheSummary {
readonly environmentId: EnvironmentId;
readonly recordCount: number;
readonly payloadBytes: number;
readonly kinds: Readonly<Partial<Record<ClientCacheKind, number>>>;
}
export interface ClientCacheSummary {
readonly recordCount: number;
readonly payloadBytes: number;
readonly environments: ReadonlyArray<EnvironmentClientCacheSummary>;
}
export type ClientCacheClearScope =
| { readonly type: "all" }
| { readonly type: "environment"; readonly environmentId: EnvironmentId };
function aggregateCacheSummary(
rows: ReadonlyArray<{
readonly environmentId: EnvironmentId;
readonly kind: ClientCacheKind;
readonly recordCount: number;
readonly payloadBytes: number;
}>,
): ClientCacheSummary {
const environments = new Map<EnvironmentId, EnvironmentClientCacheSummary>();
let recordCount = 0;
let payloadBytes = 0;
for (const row of rows) {
recordCount += row.recordCount;
payloadBytes += row.payloadBytes;
const current = environments.get(row.environmentId) ?? {
environmentId: row.environmentId,
recordCount: 0,
payloadBytes: 0,
kinds: {},
};
environments.set(row.environmentId, {
environmentId: row.environmentId,
recordCount: current.recordCount + row.recordCount,
payloadBytes: current.payloadBytes + row.payloadBytes,
kinds: { ...current.kinds, [row.kind]: row.recordCount },
});
}
return {
recordCount,
payloadBytes,
environments: [...environments.values()],
};
}
const clientCacheRuntime = Atom.runtime(Runtime.runtimeContextLayer);
export const clientCacheSummaryAtom = clientCacheRuntime
.atom(
MobileDatabase.pipe(
Effect.flatMap((database) => database.inspectCaches),
Effect.map(aggregateCacheSummary),
),
)
.pipe(Atom.withLabel("mobile:client-cache:summary"));
export const clearClientCacheAtom = clientCacheRuntime
.fn((scope: ClientCacheClearScope, get) =>
MobileDatabase.pipe(
Effect.flatMap((database) =>
scope.type === "all"
? database.clearAllCaches
: database.clearEnvironmentCache(scope.environmentId),
),
Effect.tap(() =>
Effect.sync(() => {
get.refresh(clientCacheSummaryAtom);
}),
),
),
)
.pipe(Atom.withLabel("mobile:client-cache:clear"));
-272
View File
@@ -1,272 +0,0 @@
import { describe, expect, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import { AsyncResult, Atom, AtomRegistry } from "effect/unstable/reactivity";
import { vi } from "vite-plus/test";
vi.mock("expo-secure-store", () => ({
getItemAsync: vi.fn(),
setItemAsync: vi.fn(),
}));
vi.mock("react-native", () => ({
Platform: { OS: "ios" },
}));
vi.mock("../lib/runtime", async () => {
const Layer = await import("effect/Layer");
return {
runtime: { runPromise: vi.fn() },
runtimeContextLayer: Layer.empty,
};
});
import type { Preferences } from "../persistence/mobile-preferences";
import {
createMobilePreferencesState,
MobilePreferencesLoadError,
MobilePreferencesSaveError,
MobilePreferencesStore,
} from "./preferences";
function deferred<A>() {
let resolve!: (value: A) => void;
const promise = new Promise<A>((resume) => {
resolve = resume;
});
return { promise, resolve } as const;
}
function makePreferencesState(
service: Omit<MobilePreferencesStore["Service"], "update"> &
Partial<Pick<MobilePreferencesStore["Service"], "update">>,
) {
const completeService = MobilePreferencesStore.of({
...service,
update:
service.update ??
((transform) =>
service.load.pipe(
Effect.flatMap((current) => service.savePatch(transform(current))),
Effect.mapError((cause) =>
cause._tag === "MobilePreferencesSaveError"
? cause
: new MobilePreferencesSaveError({ cause }),
),
)),
});
return createMobilePreferencesState(
Atom.runtime(Layer.succeed(MobilePreferencesStore, completeService)),
);
}
describe("mobile preferences state", () => {
it.effect("shares one preference load across consumers", () =>
Effect.gen(function* () {
const load = vi.fn(() => Promise.resolve<Preferences>({ baseFontSize: 17 }));
const state = makePreferencesState({
load: Effect.promise(load),
savePatch: (patch) => Effect.succeed(patch),
});
const registry = AtomRegistry.make();
const unmountFirst = registry.mount(state.preferencesAtom);
const unmountSecond = registry.mount(state.preferencesAtom);
expect(
yield* AtomRegistry.getResult(registry, state.preferencesAtom, {
suspendOnWaiting: true,
}),
).toEqual({ baseFontSize: 17 });
expect(load).toHaveBeenCalledTimes(1);
unmountSecond();
unmountFirst();
registry.dispose();
}),
);
it.effect("preserves an optimistic patch when the initial load finishes later", () =>
Effect.gen(function* () {
const pendingLoad = deferred<Preferences>();
const savePatch = vi.fn((patch: Partial<Preferences>) => Effect.succeed(patch));
const state = makePreferencesState({
load: Effect.promise(() => pendingLoad.promise),
savePatch,
});
const registry = AtomRegistry.make();
const unmountPreferences = registry.mount(state.preferencesAtom);
const unmountUpdate = registry.mount(state.updatePreferencesAtom);
registry.set(state.updatePreferencesAtom, {
collapsedProjectGroups: ["project:new"],
});
pendingLoad.resolve({
baseFontSize: 18,
collapsedProjectGroups: ["project:old"],
});
const preferences = yield* AtomRegistry.getResult(registry, state.preferencesAtom, {
suspendOnWaiting: true,
});
expect(preferences).toEqual({
baseFontSize: 18,
collapsedProjectGroups: ["project:new"],
});
expect(savePatch).toHaveBeenCalledWith({
collapsedProjectGroups: ["project:new"],
});
expect(AsyncResult.isFailure(registry.get(state.updatePreferencesAtom))).toBe(false);
unmountUpdate();
unmountPreferences();
registry.dispose();
}),
);
it.effect("falls back to empty preferences when secure storage cannot be read", () =>
Effect.gen(function* () {
const state = makePreferencesState({
load: Effect.fail(
new MobilePreferencesLoadError({
cause: new Error("secure storage unavailable"),
}),
),
savePatch: (patch) => Effect.succeed(patch),
});
const registry = AtomRegistry.make();
const unmount = registry.mount(state.preferencesAtom);
expect(
yield* AtomRegistry.getResult(registry, state.preferencesAtom, {
suspendOnWaiting: true,
}),
).toEqual({});
unmount();
registry.dispose();
}),
);
it.effect("does not roll back a newer optimistic write with the same value", () =>
Effect.gen(function* () {
let saveCount = 0;
const state = makePreferencesState({
load: Effect.succeed({ baseFontSize: 16, codeFontSize: 13 }),
savePatch: (patch) => {
saveCount += 1;
return saveCount === 1
? Effect.fail(new MobilePreferencesSaveError({ cause: new Error("write failed") }))
: Effect.succeed(patch);
},
});
const registry = AtomRegistry.make();
const unmountPreferences = registry.mount(state.preferencesAtom);
const unmountUpdate = registry.mount(state.updatePreferencesAtom);
yield* AtomRegistry.getResult(registry, state.preferencesAtom, {
suspendOnWaiting: true,
});
registry.set(state.updatePreferencesAtom, { baseFontSize: 18 });
registry.set(state.updatePreferencesAtom, { baseFontSize: 18, codeFontSize: 15 });
yield* Effect.promise(() =>
vi.waitFor(() => {
expect(AsyncResult.isFailure(registry.get(state.updatePreferencesAtom))).toBe(false);
expect(Option.getOrThrow(AsyncResult.value(registry.get(state.preferencesAtom)))).toEqual(
{
baseFontSize: 18,
codeFontSize: 15,
},
);
}),
);
unmountUpdate();
unmountPreferences();
registry.dispose();
}),
);
it.effect("rolls back an optimistic field when its save fails", () =>
Effect.gen(function* () {
const state = makePreferencesState({
load: Effect.succeed({ baseFontSize: 16 }),
savePatch: () =>
Effect.fail(new MobilePreferencesSaveError({ cause: new Error("write failed") })),
});
const registry = AtomRegistry.make();
const unmountPreferences = registry.mount(state.preferencesAtom);
const unmountUpdate = registry.mount(state.updatePreferencesAtom);
yield* AtomRegistry.getResult(registry, state.preferencesAtom, {
suspendOnWaiting: true,
});
registry.set(state.updatePreferencesAtom, { baseFontSize: 18 });
yield* Effect.promise(() =>
vi.waitFor(() => {
expect(Option.getOrThrow(AsyncResult.value(registry.get(state.preferencesAtom)))).toEqual(
{
baseFontSize: 16,
},
);
}),
);
unmountUpdate();
unmountPreferences();
registry.dispose();
}),
);
it.effect("rolls back to the last confirmed value after a later save fails", () =>
Effect.gen(function* () {
let saveCount = 0;
const state = makePreferencesState({
load: Effect.succeed({ baseFontSize: 16 }),
savePatch: () => {
saveCount += 1;
return saveCount === 1
? Effect.succeed({ baseFontSize: 14 })
: Effect.fail(new MobilePreferencesSaveError({ cause: new Error("write failed") }));
},
});
const registry = AtomRegistry.make();
const unmountPreferences = registry.mount(state.preferencesAtom);
const unmountUpdate = registry.mount(state.updatePreferencesAtom);
yield* AtomRegistry.getResult(registry, state.preferencesAtom, {
suspendOnWaiting: true,
});
registry.set(state.updatePreferencesAtom, { baseFontSize: 14 });
yield* Effect.promise(() =>
vi.waitFor(() => {
expect(saveCount).toBe(1);
expect(registry.get(state.updatePreferencesAtom).waiting).toBe(false);
expect(Option.getOrThrow(AsyncResult.value(registry.get(state.preferencesAtom)))).toEqual(
{
baseFontSize: 14,
},
);
}),
);
registry.set(state.updatePreferencesAtom, { baseFontSize: 18 });
yield* Effect.promise(() =>
vi.waitFor(() => {
expect(saveCount).toBe(2);
expect(Option.getOrThrow(AsyncResult.value(registry.get(state.preferencesAtom)))).toEqual(
{
baseFontSize: 14,
},
);
}),
);
unmountUpdate();
unmountPreferences();
registry.dispose();
}),
);
});
-124
View File
@@ -1,124 +0,0 @@
import * as Effect from "effect/Effect";
import { AsyncResult, Atom } from "effect/unstable/reactivity";
import { MobilePreferencesStore, type Preferences } from "../persistence/mobile-preferences";
import * as Runtime from "../lib/runtime";
export {
MobilePreferencesLoadError,
MobilePreferencesSaveError,
MobilePreferencesStore,
} from "../persistence/mobile-preferences";
interface OptimisticPreferences {
readonly values: Partial<Preferences>;
readonly versions: Partial<Record<keyof Preferences, number>>;
}
/**
* Owns the device preference blob for the lifetime of the app registry.
* Optimistic patches are kept separately so writes made while persistence is
* still loading cannot be replaced by the eventual read result.
*/
export function createMobilePreferencesState(runtime: Atom.AtomRuntime<MobilePreferencesStore>) {
const storedPreferencesAtom = runtime
.atom(
MobilePreferencesStore.pipe(
Effect.flatMap((store) => store.load),
Effect.catch((error) =>
Effect.logWarning("Could not load mobile preferences.", error).pipe(
Effect.as<Preferences>({}),
),
),
),
)
.pipe(Atom.keepAlive, Atom.withLabel("mobile:preferences:stored"));
const optimisticPatchAtom = Atom.make<OptimisticPreferences>({ values: {}, versions: {} }).pipe(
Atom.keepAlive,
Atom.withLabel("mobile:preferences:optimistic-patch"),
);
const confirmedPreferencesAtom = Atom.make<Preferences>({}).pipe(
Atom.keepAlive,
Atom.withLabel("mobile:preferences:confirmed"),
);
let nextPatchVersion = 0;
const preferencesAtom = Atom.make((get) => {
const stored = get(storedPreferencesAtom);
const confirmed = get(confirmedPreferencesAtom);
const optimistic = get(optimisticPatchAtom);
return AsyncResult.map(stored, (preferences) => ({
...preferences,
...confirmed,
...optimistic.values,
}));
}).pipe(Atom.keepAlive, Atom.withLabel("mobile:preferences"));
const updatePreferencesAtom = runtime
.fn(
(patch: Partial<Preferences>, get) => {
const version = ++nextPatchVersion;
const current = get(optimisticPatchAtom);
const versions = { ...current.versions };
for (const key of Object.keys(patch) as Array<keyof Preferences>) {
versions[key] = version;
}
get.set(optimisticPatchAtom, {
values: { ...current.values, ...patch },
versions,
});
return MobilePreferencesStore.pipe(
Effect.flatMap((store) => store.savePatch(patch)),
Effect.tap((saved) =>
Effect.sync(() => {
get.set(confirmedPreferencesAtom, saved);
const optimistic = get(optimisticPatchAtom);
const values = { ...optimistic.values } as Record<string, unknown>;
const currentVersions = { ...optimistic.versions } as Record<string, unknown>;
for (const key of Object.keys(patch) as Array<keyof Preferences>) {
if (optimistic.versions[key] === version) {
delete values[key];
delete currentVersions[key];
}
}
get.set(optimisticPatchAtom, {
values: values as Partial<Preferences>,
versions: currentVersions as Partial<Record<keyof Preferences, number>>,
});
}),
),
Effect.tapError(() =>
Effect.sync(() => {
const optimistic = get(optimisticPatchAtom);
const values = { ...optimistic.values } as Record<string, unknown>;
const currentVersions = { ...optimistic.versions } as Record<string, unknown>;
for (const key of Object.keys(patch) as Array<keyof Preferences>) {
if (optimistic.versions[key] === version) {
delete values[key];
delete currentVersions[key];
}
}
get.set(optimisticPatchAtom, {
values: values as Partial<Preferences>,
versions: currentVersions as Partial<Record<keyof Preferences, number>>,
});
}),
),
);
},
// The storage layer serializes preference read-modify-write operations.
// Keep every invocation alive so one preference update cannot interrupt
// another update to a different field in the shared blob.
{ concurrent: true },
)
.pipe(Atom.keepAlive, Atom.withLabel("mobile:preferences:update"));
return { preferencesAtom, updatePreferencesAtom } as const;
}
const mobilePreferencesRuntime = Atom.runtime(Runtime.runtimeContextLayer);
export const mobilePreferencesState = createMobilePreferencesState(mobilePreferencesRuntime);
export const mobilePreferencesAtom = mobilePreferencesState.preferencesAtom;
export const updateMobilePreferencesAtom = mobilePreferencesState.updatePreferencesAtom;
@@ -1,36 +0,0 @@
import type { VcsStatusResult } from "@t3tools/contracts";
import { resolveChangeRequestPresentation } from "@t3tools/shared/sourceControl";
export type ThreadPr = NonNullable<VcsStatusResult["pr"]>;
export interface ThreadPrPresentation {
readonly number: number;
readonly state: ThreadPr["state"];
readonly url: string;
/** Compact pull request number label, e.g. "3774". */
readonly label: string;
/** Full, provider-aware label for assistive technologies. */
readonly accessibilityLabel: string;
readonly textClassName: string;
}
const PR_STATE_TEXT_CLASS: Record<ThreadPr["state"], string> = {
open: "text-emerald-600 dark:text-emerald-400",
merged: "text-violet-600 dark:text-violet-400",
closed: "text-zinc-500 dark:text-zinc-400",
};
export function presentThreadPr(
pr: ThreadPr,
provider: VcsStatusResult["sourceControlProvider"] | null | undefined,
): ThreadPrPresentation {
const presentation = resolveChangeRequestPresentation(provider);
return {
number: pr.number,
state: pr.state,
url: pr.url,
label: String(pr.number),
accessibilityLabel: `#${pr.number} ${presentation.longName} ${pr.state}`,
textClassName: PR_STATE_TEXT_CLASS[pr.state],
};
}
@@ -1,36 +0,0 @@
import type { VcsStatusResult } from "@t3tools/contracts";
import { describe, expect, it } from "vite-plus/test";
import { presentThreadPr } from "./thread-pr-presentation";
const pullRequest: NonNullable<VcsStatusResult["pr"]> = {
number: 3774,
title: "Desktop-style pull request indicator",
url: "https://github.com/t3tools/t3code/pull/3774",
baseRef: "main",
headRef: "codex/desktop-style-pr-indicator",
state: "merged",
};
describe("presentThreadPr", () => {
it("uses the compact pull request number label without a hash prefix", () => {
expect(presentThreadPr(pullRequest, undefined)).toMatchObject({
label: "3774",
accessibilityLabel: "#3774 pull request merged",
textClassName: "text-violet-600 dark:text-violet-400",
});
});
it("uses merge-request terminology for GitLab", () => {
expect(
presentThreadPr(pullRequest, {
kind: "gitlab",
name: "GitLab",
baseUrl: "https://gitlab.com",
}),
).toMatchObject({
label: "3774",
accessibilityLabel: "#3774 merge request merged",
});
});
});
+32 -6
View File
@@ -1,14 +1,40 @@
import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
import type { VcsStatusResult } from "@t3tools/contracts";
import { resolveChangeRequestPresentation } from "@t3tools/shared/sourceControl";
import { useEnvironmentQuery } from "./query";
import { presentThreadPr, type ThreadPrPresentation } from "./thread-pr-presentation";
import { vcsEnvironment } from "./vcs";
export {
presentThreadPr,
type ThreadPr,
type ThreadPrPresentation,
} from "./thread-pr-presentation";
export type ThreadPr = NonNullable<VcsStatusResult["pr"]>;
export interface ThreadPrPresentation {
readonly number: number;
readonly state: ThreadPr["state"];
readonly url: string;
/** Compact chip label, e.g. "PR open" / "MR merged". */
readonly label: string;
readonly textClassName: string;
}
const PR_STATE_TEXT_CLASS: Record<ThreadPr["state"], string> = {
open: "text-emerald-600 dark:text-emerald-400",
merged: "text-violet-600 dark:text-violet-400",
closed: "text-zinc-500 dark:text-zinc-400",
};
export function presentThreadPr(
pr: ThreadPr,
provider: VcsStatusResult["sourceControlProvider"] | null | undefined,
): ThreadPrPresentation {
const shortName = resolveChangeRequestPresentation(provider).shortName;
return {
number: pr.number,
state: pr.state,
url: pr.url,
label: `${shortName} ${pr.state}`,
textClassName: PR_STATE_TEXT_CLASS[pr.state],
};
}
/**
* Live PR status for a thread's branch. Subscriptions are deduplicated per
@@ -477,112 +477,6 @@ 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;
+2 -8
View File
@@ -313,17 +313,11 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
}
case "thread.meta.update": {
const thread = yield* requireThread({
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({
@@ -339,7 +333,7 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
...(command.modelSelection !== undefined
? { modelSelection: command.modelSelection }
: {}),
...(branch !== undefined ? { branch } : {}),
...(command.branch !== undefined ? { branch: command.branch } : {}),
...(command.worktreePath !== undefined ? { worktreePath: command.worktreePath } : {}),
updatedAt: occurredAt,
},
Loaded 100 of 121 files, more files were not shown because too many files have changed in this diff. Show more