diff --git a/apps/mobile/index.ts b/apps/mobile/index.ts index 738722323725a..9367ade408e95 100644 --- a/apps/mobile/index.ts +++ b/apps/mobile/index.ts @@ -9,8 +9,6 @@ import { LogBox } from "react-native"; import { featureFlags } from "react-native-screens"; import App from "./src/App"; -// Kin: dev-only inbox log, gated on EXPO_PUBLIC_KIN_DEV_LOG=1. -import "./src/features/chats/state/kinDevLogEntry"; // Enables iOS FormSheet sizing for nested native stacks in non-fitToContents sheets. featureFlags.experiment.synchronousScreenUpdatesEnabled = true; diff --git a/apps/mobile/src/Stack.tsx b/apps/mobile/src/Stack.tsx index ef79ef182cc57..8f10e048f5b35 100644 --- a/apps/mobile/src/Stack.tsx +++ b/apps/mobile/src/Stack.tsx @@ -58,6 +58,7 @@ import { DevicePreviewRouteScreen } from "./features/devices/DevicePreviewRouteS import { BrowserPreviewRouteScreen } from "./features/browser/BrowserPreviewRouteScreen"; import { GitBranchesSheet } from "./features/threads/git/GitBranchesSheet"; import { GitCommitSheet } from "./features/threads/git/GitCommitSheet"; +import { KIN_SCREENS } from "./features/chats/routes"; import { GitConfirmSheet } from "./features/threads/git/GitConfirmSheet"; import { GitOverviewSheet } from "./features/threads/git/GitOverviewSheet"; import { ThreadPullRequestsSheet } from "./features/threads/ThreadPullRequestsSheet"; @@ -698,6 +699,7 @@ const RootStackConfig = createWorkspaceStackNavigator({ options: sheetRoute({ detent: 0.55, maxDetent: 0.7, androidFit: true }), }), ...SETTINGS_SCREENS, + ...KIN_SCREENS, SettingsLegal: createNativeStackScreen({ screen: SettingsLegalRouteScreen, linking: "settings/legal", diff --git a/apps/mobile/src/features/chats/KinChatScreen.tsx b/apps/mobile/src/features/chats/KinChatScreen.tsx new file mode 100644 index 0000000000000..59ba89f596729 --- /dev/null +++ b/apps/mobile/src/features/chats/KinChatScreen.tsx @@ -0,0 +1,671 @@ +import { useAtomValue } from "@effect/atom-react"; +import { + LegendList, + type LegendListRef, + type OnViewableItemsChangedInfo, + type ViewabilityConfigCallbackPairs, +} from "@legendapp/list/react-native"; +import { + StackActions, + useIsFocused, + useNavigation, + type StaticScreenProps, +} from "@react-navigation/native"; +import { + EnvironmentId, + KinChatId, + type KinChatHistoryInput, + type KinChatHistoryResult, + type KinMessage, +} from "@t3tools/contracts"; +import * as Exit from "effect/Exit"; +import * as Option from "effect/Option"; +import * as Schema from "effect/Schema"; +import { Atom, type AsyncResult } from "effect/reactivity"; +import { useEffect, useRef, useState } from "react"; +import { View } from "react-native"; +import { useSafeAreaInsets } from "react-native-safe-area-context"; + +import { AppBar } from "../../components/ui/AppBar"; +import { Button } from "../../components/ui/Button"; +import { ControlPill } from "../../components/ui/ControlPill"; +import { EmptyState } from "../../components/ui/EmptyState"; +import { ErrorBanner } from "../../components/ui/ErrorBanner"; +import { LoadingStrip } from "../../components/ui/LoadingStrip"; +import { Notice } from "../../components/ui/Notice"; +import { ScreenContent } from "../../components/ui/ScreenContent"; +import { useBarOverlap, useContentTopInset } from "../../components/ui/useBarInset"; +import { useReduceMotionEnabled } from "../../lib/appState"; +import { useLocalDayStartMs } from "../../lib/clock"; +import { NativeScrollView } from "../../native/NativeScrollViewMarker"; +import { useOpenPullRequest } from "../../native/useOpenPullRequest"; +import { appAtomRegistry } from "../../state/atom-registry"; +import { useMarkdownPreviewStyles } from "../files/FileMarkdownPreview"; +import { KinFoldLine } from "./components/KinFoldLine"; +import { KinDayLine, KinMessageBubble, KinSystemLine } from "./components/KinMessageBubble"; +import { + buildKinFeedRows, + initialKinPaging, + kinActivePaging, + kinChatScreenState, + kinChatStatusLine, + kinEarlierPage, + kinFeedViewer, + kinMarkReadRearms, + kinRowSeq, + kinSeqToMarkRead, + kinUnseenCount, + latestKinSeq, + mergeKinFeed, + type KinChatScreenState, + type KinFeedRow, + type KinFeedViewer, + type KinPaging, +} from "./state/kinChatFeed"; +import { kinClient, type KinSynced } from "./state/kinClient"; +import { + initialKinFeedFollow, + kinFollowsEnd, + resolveKinFeedFollow, + type KinFeedFollowEvent, +} from "./state/kinFeedFollow"; +import { + applyKinChatHistory, + emptyKinChat, + KIN_CACHED_MESSAGE_LIMIT, + type KinChatState, + type KinInboxState, +} from "./state/kinInboxModel"; +import { kinChatTitle, kinDirectAgentName } from "./state/kinScreenState"; +import { useKinHostAt } from "./state/useKinHost"; + +type KinChatParams = { + readonly environmentId: string; + readonly orgId: string; + readonly chatId: string; +}; + +type KinFixtures = typeof import("./state/kinChatFixtures"); + +export function KinChatScreen({ route }: StaticScreenProps) { + // `KIN_FIXTURE_CHAT_ID`; required inside the `__DEV__` branch so release builds drop it. + if (__DEV__ && route.params.chatId === "dev-fixture") { + return ; + } + const environmentId = decodeEnvironmentId(route.params.environmentId); + if (Option.isNone(environmentId)) { + return ( + {}} + readHistory={null} + /> + ); + } + return ( + + ); +} + +type ChatResult = AsyncResult.AsyncResult, unknown> | null; +type InboxResult = AsyncResult.AsyncResult, unknown> | null; +const noChatAtom: Atom.Atom = Atom.make(null); +const noInboxAtom: Atom.Atom = Atom.make(null); + +const decodeChatId = Schema.decodeUnknownOption(KinChatId); +const decodeEnvironmentId = Schema.decodeUnknownOption(EnvironmentId); + +function KinLiveChat(props: { + readonly environmentId: EnvironmentId; + readonly orgId: string; + readonly chatId: string; +}) { + // The route's host, not the saved one: every Kin host uses the same org id. + const host = useKinHostAt(props.environmentId); + const chatId = Option.getOrNull(decodeChatId(props.chatId)); + const environmentId = host._tag === "host" ? host.environmentId : null; + const chatAtom: Atom.Atom = + environmentId === null || chatId === null + ? noChatAtom + : kinClient.chat({ environmentId, input: { chatId } }); + const inboxAtom: Atom.Atom = + environmentId === null ? noInboxAtom : kinClient.inbox({ environmentId, input: {} }); + const chatResult = useAtomValue(chatAtom); + const inbox = useAtomValue(inboxAtom); + const state: KinChatScreenState = + chatId === null ? { _tag: "gone", reason: "not_found" } : kinChatScreenState(host, chatResult); + const viewer = kinFeedViewer( + host._tag === "host" && host.probe._tag === "ready" ? host.probe.orgs : null, + props.orgId, + ); + const summary = + inbox?._tag === "Success" + ? inbox.value.value.chats.find((chat) => chat.chatId === chatId) + : undefined; + + const retry = () => { + if (environmentId === null) return; + if (state._tag === "error" && state.retry === "orgs") { + appAtomRegistry.refresh(kinClient.orgs({ environmentId, input: {} })); + } else if (state._tag === "error" || (state._tag === "ready" && state.error !== null)) { + appAtomRegistry.refresh(chatAtom); + } + }; + + return ( + + kinClient.markRead + .run(appAtomRegistry, { environmentId, input: { chatId, seq } }) + .then((result) => result._tag === "Success") + } + state={state} + viewer={viewer} + onRetry={retry} + readHistory={ + state._tag === "ready" && state.connected + ? (input) => kinClient.readHistoryPage(state.environmentId, input) + : null + } + /> + ); +} + +let fixtureMessages: ReadonlyArray | null = null; +const readFixtureMessages = (fixtures: KinFixtures) => + (fixtureMessages ??= fixtures.makeKinFixtureMessages(500)); + +/** Dev only: 500 local messages, the latest 50 live, older ones paged in by "Load earlier". */ +function KinFixtureChat({ fixtures }: { readonly fixtures: KinFixtures }) { + const getFixtureMessages = () => readFixtureMessages(fixtures); + const chat: KinSynced = { + value: { ...emptyKinChat, messages: getFixtureMessages().slice(-KIN_CACHED_MESSAGE_LIMIT) }, + live: true, + savedAt: null, + }; + return ( + {}} + readHistory={(input) => + Promise.resolve(Exit.succeed(fixtures.readKinFixtureHistory(getFixtureMessages(), input))) + } + /> + ); +} + +type ReadHistory = ( + input: KinChatHistoryInput, +) => Promise>; + +type MarkRead = (seq: number) => Promise; + +function KinChatPage(props: { + readonly chatId: KinChatId; + readonly title: string; + /** The agent a direct chat is with, for the empty chat's copy; null when unknown. */ + readonly agentName: string | null; + /** The inbox's unread count for this chat; null until the inbox loads. */ + readonly unread: number | null; + /** Null where nothing can be marked, such as the dev fixture. */ + readonly markRead: MarkRead | null; + readonly state: KinChatScreenState; + readonly viewer: KinFeedViewer; + readonly onRetry: () => void; + /** Null while older pages can't be read, such as offline. */ + readonly readHistory: ReadHistory | null; +}) { + const navigation = useNavigation(); + const topInset = useContentTopInset(); + const { state } = props; + const subtitle = state._tag === "ready" ? kinChatStatusLine(state.chat.value.widgets) : null; + return ( + + navigation.goBack()} /> + + {state._tag === "ready" ? ( + + ) : ( + + )} + + {state._tag === "loading" ? ( + + + + ) : null} + + ); +} + +function KinChatStateView(props: { + readonly state: Exclude; + readonly onRetry: () => void; +}) { + const navigation = useNavigation(); + const { state } = props; + const body = (() => { + switch (state._tag) { + case "loading": + return null; + case "offline": + return ( + + ); + case "noHost": + return ( + navigation.navigate("SettingsEnvironments")} + /> + ); + case "unpaired": + return ( + navigation.navigate("SettingsEnvironments")} + /> + ); + case "unauthorized": + return ( + + ); + case "noIdentity": + return ( + + ); + case "gone": + return ( + navigation.dispatch(StackActions.popTo("KinChats"))} + /> + ); + case "error": + return ( + + + +