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