The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import { |
| 2 | StackActions, |
| 3 | useIsFocused, |
| 4 | useNavigation, |
| 5 | type StaticScreenProps, |
| 6 | } from "@react-navigation/native"; |
| 7 | import { |
| 8 | isLinkedThreadWorking, |
| 9 | linkedThreadFailure, |
| 10 | type LinkedThreadFailure, |
| 11 | type LinkedThreadTarget, |
| 12 | } from "@t3tools/client-runtime/linked-thread"; |
| 13 | import { |
| 14 | toolCallLines, |
| 15 | turnItemDetailRevision, |
| 16 | turnItemOutputText, |
| 17 | } from "@t3tools/client-runtime/work-log/item-detail"; |
| 18 | import { EnvironmentId, ThreadId } from "@t3tools/contracts"; |
| 19 | import { T, useGT, useLocale, useMessages } from "gt-react-native"; |
| 20 | import { useEffect, useRef, useState, useSyncExternalStore } from "react"; |
| 21 | import type * as React from "react"; |
| 22 | import { AppState, Pressable, ScrollView, View } from "react-native"; |
| 23 | import { useSafeAreaInsets } from "react-native-safe-area-context"; |
| 24 | |
| 25 | import { AppActivityIndicator } from "../../components/ui/AppActivityIndicator"; |
| 26 | import { AppText as Text } from "../../components/ui/AppText"; |
| 27 | import { Button } from "../../components/ui/Button"; |
| 28 | import { ScreenContent } from "../../components/ui/ScreenContent"; |
| 29 | import { SelectableMarkdownText } from "../../native/SelectableMarkdownText"; |
| 30 | import { useEnvironments } from "../../state/environments"; |
| 31 | import { |
| 32 | buildThreadFeed, |
| 33 | createThreadFeedCache, |
| 34 | formatItemFullDetail, |
| 35 | type ThreadFeedActivity, |
| 36 | type ThreadFeedEntry, |
| 37 | } from "../../lib/threadActivity"; |
| 38 | import { useConnectLinkedEnvironment, useLinkedThreadView } from "../../state/linkedThread"; |
| 39 | import { peerLinkEnvironment } from "../../state/peerLinks"; |
| 40 | import { useEnvironmentQuery } from "../../state/query"; |
| 41 | import { useMarkdownPreviewStyles } from "../files/FileMarkdownPreview"; |
| 42 | import type { LinkedThreadRouteParams } from "./linkedThreadRoute"; |
| 43 | import { ReadOnlyComposerBar } from "./ReadOnlyComposerBar"; |
| 44 | import { ThreadInspectorHeader, type ThreadInspectorPresentation } from "./thread-inspector-header"; |
| 45 | import { useOpenLinkedThread } from "./useOpenLinkedThread"; |
| 46 | |
| 47 | function ActivityRow(props: { |
| 48 | readonly activity: ThreadFeedActivity; |
| 49 | readonly target: LinkedThreadTarget; |
| 50 | }) { |
| 51 | const { activity, target } = props; |
| 52 | const gt = useGT(); |
| 53 | const [open, setOpen] = useState(false); |
| 54 | const row = activity.projectedItem; |
| 55 | // The stream leaves long output out; an open row reads its item in full through the link. |
| 56 | const fetched = useEnvironmentQuery( |
| 57 | open && activity.fetchesDetail |
| 58 | ? peerLinkEnvironment.threadItem({ |
| 59 | environmentId: target.viaEnvironmentId, |
| 60 | input: { |
| 61 | environmentId: target.environmentId, |
| 62 | threadId: row.sourceThreadId, |
| 63 | itemId: row.sourceItemId, |
| 64 | revision: turnItemDetailRevision(row.item), |
| 65 | }, |
| 66 | }) |
| 67 | : null, |
| 68 | ); |
| 69 | const fetchedItem = fetched.data?.item ?? null; |
| 70 | const shownItem = fetchedItem ?? row.item; |
| 71 | // A command or tool call reads as what was called, as on the thread screen; only an item with |
| 72 | // no call to show falls back to its full detail. |
| 73 | const call = !open |
| 74 | ? null |
| 75 | : shownItem.type === "command_execution" |
| 76 | ? toolCallLines({ command: shownItem.input }) |
| 77 | : shownItem.type === "dynamic_tool" |
| 78 | ? toolCallLines({ args: shownItem.input }) |
| 79 | : null; |
| 80 | const callText = call |
| 81 | ? (call.command ?? |
| 82 | call.args?.map(([key, value]) => `${key}: ${value}`).join("\n") ?? |
| 83 | call.argsText) |
| 84 | : null; |
| 85 | const body = !open |
| 86 | ? null |
| 87 | : call |
| 88 | ? callText |
| 89 | : fetchedItem |
| 90 | ? formatItemFullDetail(row, fetchedItem) |
| 91 | : (activity.getFullDetail() ?? activity.detail); |
| 92 | const output = !open |
| 93 | ? null |
| 94 | : !activity.fetchesDetail |
| 95 | ? turnItemOutputText(row.item) |
| 96 | : fetchedItem |
| 97 | ? (turnItemOutputText(fetchedItem) ?? gt("No output.")) |
| 98 | : fetched.error |
| 99 | ? gt("Couldn't load output: {error}", { error: fetched.error }) |
| 100 | : fetched.data |
| 101 | ? gt("Output is no longer available.") |
| 102 | : gt("Loading output…"); |
| 103 | return ( |
| 104 | <Pressable |
| 105 | accessibilityRole="button" |
| 106 | accessibilityState={{ expanded: open }} |
| 107 | disabled={!activity.canExpand} |
| 108 | onPress={() => setOpen(!open)} |
| 109 | className="active:opacity-70" |
| 110 | > |
| 111 | <Text |
| 112 | numberOfLines={open ? undefined : 1} |
| 113 | className={`font-mono text-xs ${activity.status === "failure" ? "text-danger-foreground" : "text-foreground-muted"}`} |
| 114 | > |
| 115 | {activity.summary} |
| 116 | </Text> |
| 117 | {body ? ( |
| 118 | <View className="mt-1 rounded-lg bg-subtle p-2"> |
| 119 | <Text selectable className="font-mono text-xs text-foreground-muted"> |
| 120 | {body} |
| 121 | </Text> |
| 122 | </View> |
| 123 | ) : null} |
| 124 | {output ? ( |
| 125 | <View className="mt-1 rounded-lg bg-subtle p-2"> |
| 126 | <Text selectable className="font-mono text-xs text-foreground-muted"> |
| 127 | {output} |
| 128 | </Text> |
| 129 | </View> |
| 130 | ) : null} |
| 131 | {open && fetched.error ? ( |
| 132 | <View className="mt-1.5 self-start"> |
| 133 | <Button |
| 134 | size="compact" |
| 135 | tone="secondary" |
| 136 | label={gt("Try again")} |
| 137 | onPress={fetched.refresh} |
| 138 | /> |
| 139 | </View> |
| 140 | ) : null} |
| 141 | </Pressable> |
| 142 | ); |
| 143 | } |
| 144 | |
| 145 | /** |
| 146 | * One entry of the thread's feed, as the thread screen's own feed model has it. Only reading |
| 147 | * rows are drawn: what needs the thread's environment (files, visuals, apps) is left out. |
| 148 | */ |
| 149 | function LinkedThreadEntry(props: { |
| 150 | readonly entry: ThreadFeedEntry; |
| 151 | readonly target: LinkedThreadTarget; |
| 152 | }) { |
| 153 | const { entry } = props; |
| 154 | const styles = useMarkdownPreviewStyles(); |
| 155 | if (entry.type === "activity-group") { |
| 156 | return ( |
| 157 | <View className="gap-1.5"> |
| 158 | {entry.activities.map((activity) => ( |
| 159 | <ActivityRow key={activity.id} activity={activity} target={props.target} /> |
| 160 | ))} |
| 161 | </View> |
| 162 | ); |
| 163 | } |
| 164 | // A message the agent sent with a tool reads as its own words, as on the thread screen. |
| 165 | if (entry.type === "sent-message") { |
| 166 | return <SelectableMarkdownText markdown={entry.text} textStyle={styles.nativeTextStyle} />; |
| 167 | } |
| 168 | if (entry.type !== "message" || entry.message.text.trim() === "") return null; |
| 169 | return entry.message.role === "user" ? ( |
| 170 | <View className="max-w-[88%] self-end rounded-2xl bg-user-bubble px-3.5 py-2.5"> |
| 171 | <Text selectable className="text-sm text-user-bubble-foreground"> |
| 172 | {entry.message.text} |
| 173 | </Text> |
| 174 | </View> |
| 175 | ) : ( |
| 176 | <SelectableMarkdownText markdown={entry.message.text} textStyle={styles.nativeTextStyle} /> |
| 177 | ); |
| 178 | } |
| 179 | |
| 180 | function FailureCard(props: { |
| 181 | readonly failure: LinkedThreadFailure; |
| 182 | readonly stale: boolean; |
| 183 | readonly onRetry: () => void; |
| 184 | }) { |
| 185 | const gt = useGT(); |
| 186 | return ( |
| 187 | <View |
| 188 | accessibilityLiveRegion="polite" |
| 189 | className="gap-1 rounded-2xl border border-danger-border bg-danger px-3.5 py-3" |
| 190 | > |
| 191 | <Text className="font-t3-medium text-sm text-danger-foreground">{props.failure.title}</Text> |
| 192 | <Text className="text-sm text-danger-foreground"> |
| 193 | {props.failure.detail} |
| 194 | {props.stale ? ` ${gt("Showing what was read before.")}` : ""} |
| 195 | </Text> |
| 196 | {props.failure.retryable ? ( |
| 197 | <View className="mt-2 self-start"> |
| 198 | <Button size="compact" tone="secondary" label={gt("Try again")} onPress={props.onRetry} /> |
| 199 | </View> |
| 200 | ) : null} |
| 201 | </View> |
| 202 | ); |
| 203 | } |
| 204 | |
| 205 | /** |
| 206 | * Stands where a composer would: the thread takes no messages from here. `action` is the one way |
| 207 | * forward it offers, and `notice` what came of it. |
| 208 | */ |
| 209 | function LinkedThreadComposer(props: { |
| 210 | /** The linked environment the thread is on. */ |
| 211 | readonly label: string; |
| 212 | /** The environment that reads it. */ |
| 213 | readonly via: string; |
| 214 | readonly working: boolean; |
| 215 | readonly action?: React.ReactNode; |
| 216 | readonly notice?: React.ReactNode; |
| 217 | }) { |
| 218 | const { label, via } = props; |
| 219 | const gt = useGT(); |
| 220 | return ( |
| 221 | <> |
| 222 | {props.notice} |
| 223 | <ReadOnlyComposerBar> |
| 224 | <View accessible className="min-w-0 flex-1 gap-0.5"> |
| 225 | <Text numberOfLines={1} className="font-t3-bold text-sm text-foreground"> |
| 226 | <T>Read-only</T> |
| 227 | </Text> |
| 228 | <Text numberOfLines={1} className="font-sans text-xs text-foreground-secondary"> |
| 229 | {props.working |
| 230 | ? gt("On {label} via {via} · Working", { label, via }) |
| 231 | : gt("On {label} via {via}", { label, via })} |
| 232 | </Text> |
| 233 | </View> |
| 234 | {props.action} |
| 235 | </ReadOnlyComposerBar> |
| 236 | </> |
| 237 | ); |
| 238 | } |
| 239 | |
| 240 | const subscribeAppState = (onChange: () => void) => { |
| 241 | const subscription = AppState.addEventListener("change", onChange); |
| 242 | return () => subscription.remove(); |
| 243 | }; |
| 244 | const appIsActive = () => AppState.currentState === "active"; |
| 245 | |
| 246 | /** |
| 247 | * A linked environment's thread, read through the environment this app is connected to. The app |
| 248 | * never connects to the linked one, so the view only reads. It shows in the inspector, where |
| 249 | * `presentation` maximizes it, or as its own screen, where `presentation` closes it. |
| 250 | */ |
| 251 | export function LinkedThreadView(props: { |
| 252 | readonly target: LinkedThreadTarget; |
| 253 | /** Closes the screen by going back when absent. */ |
| 254 | readonly presentation?: ThreadInspectorPresentation; |
| 255 | }) { |
| 256 | const { target } = props; |
| 257 | const gt = useGT(); |
| 258 | const m = useMessages(); |
| 259 | const locale = useLocale(); |
| 260 | const navigation = useNavigation(); |
| 261 | const presentation = props.presentation ?? { onClose: () => navigation.goBack() }; |
| 262 | const inInspector = "onMaximize" in presentation; |
| 263 | const insets = useSafeAreaInsets(); |
| 264 | const via = |
| 265 | useEnvironments().environments.find( |
| 266 | (environment) => environment.environmentId === target.viaEnvironmentId, |
| 267 | )?.label ?? gt("this environment"); |
| 268 | // The stream runs only while this screen is the one being looked at. |
| 269 | const focused = useIsFocused(); |
| 270 | const appActive = useSyncExternalStore(subscribeAppState, appIsActive); |
| 271 | const { view, error, retry } = useLinkedThreadView(target, focused && appActive); |
| 272 | const projection = view?.thread.projection ?? null; |
| 273 | const label = target.label; |
| 274 | const failure = error === null ? null : linkedThreadFailure(error, { via, label }, m); |
| 275 | const [feedCache] = useState(() => createThreadFeedCache()); |
| 276 | const feed = |
| 277 | projection === null |
| 278 | ? [] |
| 279 | : buildThreadFeed(projection.visibleTurnItems, { |
| 280 | attempts: projection.attempts, |
| 281 | nodes: projection.nodes, |
| 282 | cache: feedCache, |
| 283 | resolve: m, |
| 284 | locale, |
| 285 | }); |
| 286 | const scroll = useRef<React.ComponentRef<typeof ScrollView>>(null); |
| 287 | // Follows new items only while the reader is already at the end. |
| 288 | const atEnd = useRef(true); |
| 289 | const working = projection !== null && isLinkedThreadWorking(projection); |
| 290 | const connection = useConnectLinkedEnvironment(target); |
| 291 | const connectState = connection.state; |
| 292 | const openThread = useOpenLinkedThread(); |
| 293 | const shown = useRef(true); |
| 294 | // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- records unmount, so a connect that resolves after the view is gone navigates nowhere |
| 295 | useEffect(() => { |
| 296 | shown.current = true; |
| 297 | return () => { |
| 298 | shown.current = false; |
| 299 | }; |
| 300 | }, []); |
| 301 | const connect = async () => { |
| 302 | const outcome = await connection.connect(); |
| 303 | if (outcome.type === "unreachable" || !shown.current) return; |
| 304 | // The read-only view gives way either way: the thread opens where the app is now connected, |
| 305 | // or the add-environment screen takes its place. In the inspector the thread replaces it there. |
| 306 | if (outcome.type === "connected") { |
| 307 | if (!inInspector) navigation.goBack(); |
| 308 | openThread({ environmentId: target.environmentId, threadId: target.threadId }); |
| 309 | return; |
| 310 | } |
| 311 | if (inInspector) navigation.navigate("ConnectionsNew", { linked: target.environmentId }); |
| 312 | else { |
| 313 | navigation.dispatch(StackActions.replace("ConnectionsNew", { linked: target.environmentId })); |
| 314 | } |
| 315 | }; |
| 316 | return ( |
| 317 | <View collapsable={false} className={inInspector ? "flex-1 bg-screen" : "flex-1 bg-sheet"}> |
| 318 | <ThreadInspectorHeader |
| 319 | {...presentation} |
| 320 | title={projection?.thread.title || target.title || gt("Thread on {label}", { label })} |
| 321 | /> |
| 322 | <ScreenContent> |
| 323 | <ScrollView |
| 324 | ref={scroll} |
| 325 | nestedScrollEnabled |
| 326 | className="flex-1" |
| 327 | contentInsetAdjustmentBehavior="automatic" |
| 328 | contentContainerClassName="gap-3 px-5 pb-3 pt-3" |
| 329 | // An earlier page lands above what is being read without moving it. |
| 330 | maintainVisibleContentPosition={{ minIndexForVisible: 0 }} |
| 331 | scrollEventThrottle={64} |
| 332 | onScroll={({ nativeEvent }) => { |
| 333 | const { contentOffset, contentSize, layoutMeasurement } = nativeEvent; |
| 334 | atEnd.current = contentSize.height - layoutMeasurement.height - contentOffset.y < 80; |
| 335 | }} |
| 336 | onContentSizeChange={() => { |
| 337 | if (atEnd.current) scroll.current?.scrollToEnd({ animated: false }); |
| 338 | }} |
| 339 | > |
| 340 | {view === null || projection === null ? ( |
| 341 | failure === null ? ( |
| 342 | <View className="flex-row items-center gap-2 pt-6"> |
| 343 | <AppActivityIndicator size="small" /> |
| 344 | <Text className="text-sm text-foreground-muted"> |
| 345 | {gt("Reading from {label}…", { label })} |
| 346 | </Text> |
| 347 | </View> |
| 348 | ) : ( |
| 349 | <FailureCard failure={failure} stale={false} onRetry={retry} /> |
| 350 | ) |
| 351 | ) : ( |
| 352 | <> |
| 353 | {view.thread.historyCursor !== null ? ( |
| 354 | <View className="self-center"> |
| 355 | <Button |
| 356 | size="compact" |
| 357 | tone="text" |
| 358 | label={gt("Load earlier")} |
| 359 | loading={view.history.loading} |
| 360 | disabled={view.history.loading} |
| 361 | onPress={view.loadEarlier} |
| 362 | /> |
| 363 | </View> |
| 364 | ) : null} |
| 365 | {feed.length === 0 ? ( |
| 366 | <Text className="text-sm text-foreground-muted"> |
| 367 | <T>Nothing in this thread yet.</T> |
| 368 | </Text> |
| 369 | ) : null} |
| 370 | {feed.map((entry) => ( |
| 371 | <LinkedThreadEntry key={entry.id} entry={entry} target={target} /> |
| 372 | ))} |
| 373 | {failure === null ? null : <FailureCard failure={failure} stale onRetry={retry} />} |
| 374 | </> |
| 375 | )} |
| 376 | </ScrollView> |
| 377 | <View |
| 378 | className="gap-2 px-3 pt-1.5" |
| 379 | style={{ paddingBottom: Math.max(insets.bottom, 10) + 6 }} |
| 380 | > |
| 381 | <LinkedThreadComposer |
| 382 | label={label} |
| 383 | via={via} |
| 384 | working={working} |
| 385 | action={ |
| 386 | <Button |
| 387 | tone="secondary" |
| 388 | label={gt("Connect to interact")} |
| 389 | loading={connectState.phase === "connecting"} |
| 390 | onPress={() => void connect()} |
| 391 | /> |
| 392 | } |
| 393 | notice={ |
| 394 | connectState.phase === "connecting" ? ( |
| 395 | <Text |
| 396 | accessibilityLiveRegion="polite" |
| 397 | className="px-2 text-xs text-foreground-muted" |
| 398 | > |
| 399 | {gt("Connecting to {environment}...", { environment: label })} |
| 400 | </Text> |
| 401 | ) : connectState.phase === "unreachable" ? ( |
| 402 | <View |
| 403 | accessibilityLiveRegion="polite" |
| 404 | className="gap-1 rounded-2xl border border-danger-border bg-danger px-3.5 py-3" |
| 405 | > |
| 406 | <Text className="font-t3-medium text-sm text-danger-foreground"> |
| 407 | {gt("{label} is not reachable from this device", { |
| 408 | label: connectState.label, |
| 409 | })} |
| 410 | </Text> |
| 411 | <Text className="text-sm text-danger-foreground"> |
| 412 | <T> |
| 413 | Join a network it is on, such as its Tailscale network, and try again. You can |
| 414 | keep reading here. |
| 415 | </T> |
| 416 | </Text> |
| 417 | </View> |
| 418 | ) : null |
| 419 | } |
| 420 | /> |
| 421 | </View> |
| 422 | </ScreenContent> |
| 423 | </View> |
| 424 | ); |
| 425 | } |
| 426 | |
| 427 | /** The read-only view as its own screen: a sheet, or the whole screen when maximized from the inspector. */ |
| 428 | export function LinkedThreadSheet({ route }: StaticScreenProps<LinkedThreadRouteParams>) { |
| 429 | const { viaEnvironmentId, environmentId, threadId, label, title } = route.params; |
| 430 | return ( |
| 431 | <LinkedThreadView |
| 432 | key={`${viaEnvironmentId}:${environmentId}:${threadId}`} |
| 433 | target={{ |
| 434 | viaEnvironmentId: EnvironmentId.make(viaEnvironmentId), |
| 435 | environmentId: EnvironmentId.make(environmentId), |
| 436 | threadId: ThreadId.make(threadId), |
| 437 | label, |
| 438 | title: title ?? null, |
| 439 | }} |
| 440 | /> |
| 441 | ); |
| 442 | } |