Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

LinkedThreadSheet.tsx

459 lines17.1 KB

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 : 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 );
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 */
149function 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 );
179​
180function 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 );
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 */
209function 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 );
239​
240const subscribeAppState = (onChange: () => void) => {
241 const subscription = AppState.addEventListener("change", onChange);
242 return () => subscription.remove();
243};
244const 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 */
251export 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 showHistoryError =
290 view !== null && view.thread.historyCursor !== null && view.history.failed;
291 const lastLayoutHadHistoryError = useRef(false);
292 const working = projection !== null && isLinkedThreadWorking(projection);
293 const connection = useConnectLinkedEnvironment(target);
294 const connectState = connection.state;
295 const openThread = useOpenLinkedThread();
296 const shown = useRef(true);
297 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- records unmount, so a connect that resolves after the view is gone navigates nowhere
298 useEffect(() => {
299 shown.current = true;
300 return () => {
301 shown.current = false;
302 };
303 }, []);
304 const connect = async () => {
305 const outcome = await connection.connect();
306 if (outcome.type === "unreachable" || !shown.current) return;
307 // The read-only view gives way either way: the thread opens where the app is now connected,
308 // or the add-environment screen takes its place. In the inspector the thread replaces it there.
309 if (outcome.type === "connected") {
310 if (!inInspector) navigation.goBack();
311 openThread({ environmentId: target.environmentId, threadId: target.threadId });
312 return;
313 }
314 if (inInspector) navigation.navigate("ConnectionsNew", { linked: target.environmentId });
315 else {
316 navigation.dispatch(StackActions.replace("ConnectionsNew", { linked: target.environmentId }));
317 }
318 };
319 return (
320 <View collapsable={false} className={inInspector ? "flex-1 bg-screen" : "flex-1 bg-sheet"}>
321 <ThreadInspectorHeader
322 {...presentation}
323 title={projection?.thread.title || target.title || gt("Thread on {label}", { label })}
324 />
325 <ScreenContent>
326 <ScrollView
327 ref={scroll}
328 nestedScrollEnabled
329 className="flex-1"
330 contentInsetAdjustmentBehavior="automatic"
331 contentContainerClassName="gap-3 px-5 pb-3 pt-3"
332 // An earlier page lands above what is being read without moving it.
333 maintainVisibleContentPosition={{ minIndexForVisible: 0 }}
334 scrollEventThrottle={64}
335 onScroll={({ nativeEvent }) => {
336 const { contentOffset, contentSize, layoutMeasurement } = nativeEvent;
337 atEnd.current = contentSize.height - layoutMeasurement.height - contentOffset.y < 80;
338 }}
339 onContentSizeChange={() => {
340 // A page error can resize the top of a short feed whose reader is also near the end.
341 const historyErrorChanged = lastLayoutHadHistoryError.current !== showHistoryError;
342 lastLayoutHadHistoryError.current = showHistoryError;
343 if (atEnd.current && !historyErrorChanged) {
344 scroll.current?.scrollToEnd({ animated: false });
345 }
346 }}
347 >
348 {view === null || projection === null ? (
349 failure === null ? (
350 <View className="flex-row items-center gap-2 pt-6">
351 <AppActivityIndicator size="small" />
352 <Text className="text-sm text-foreground-muted">
353 {gt("Reading from {label}…", { label })}
354 </Text>
355 </View>
356 ) : (
357 <FailureCard failure={failure} stale={false} onRetry={retry} />
358 )
359 ) : (
360 <>
361 {view.thread.historyCursor !== null ? (
362 <View className="flex-row flex-wrap justify-center">
363 <Button
364 size="compact"
365 tone="text"
366 label={gt("Load earlier")}
367 loading={view.history.loading}
368 disabled={view.history.loading}
369 onPress={view.loadEarlier}
370 />
371 {showHistoryError ? (
372 <Text
373 accessibilityLiveRegion="polite"
374 accessibilityRole="alert"
375 className="w-full text-center text-xs text-danger-foreground"
376 >
377 {gt("Could not load earlier turns. Try again.")}
378 </Text>
379 ) : null}
380 </View>
381 ) : null}
382 {feed.length === 0 ? (
383 <Text className="text-sm text-foreground-muted">
384 <T>Nothing in this thread yet.</T>
385 </Text>
386 ) : null}
387 {feed.map((entry) => (
388 <LinkedThreadEntry key={entry.id} entry={entry} target={target} />
389 ))}
390 {failure === null ? null : <FailureCard failure={failure} stale onRetry={retry} />}
391 </>
392 )}
393 </ScrollView>
394 <View
395 className="gap-2 px-3 pt-1.5"
396 style={{ paddingBottom: Math.max(insets.bottom, 10) + 6 }}
397 >
398 <LinkedThreadComposer
399 label={label}
400 via={via}
401 working={working}
402 action={
403 <Button
404 tone="secondary"
405 label={gt("Connect to interact")}
406 loading={connectState.phase === "connecting"}
407 onPress={() => void connect()}
408 />
409 }
410 notice={
411 connectState.phase === "connecting" ? (
412 <Text
413 accessibilityLiveRegion="polite"
414 className="px-2 text-xs text-foreground-muted"
415 >
416 {gt("Connecting to {environment}...", { environment: label })}
417 </Text>
418 ) : connectState.phase === "unreachable" ? (
419 <View
420 accessibilityLiveRegion="polite"
421 className="gap-1 rounded-2xl border border-danger-border bg-danger px-3.5 py-3"
422 >
423 <Text className="font-t3-medium text-sm text-danger-foreground">
424 {gt("{label} is not reachable from this device", {
425 label: connectState.label,
426 })}
427 </Text>
428 <Text className="text-sm text-danger-foreground">
429 <T>
430 Join a network it is on, such as its Tailscale network, and try again. You can
431 keep reading here.
432 </T>
433 </Text>
434 </View>
435 ) : null
436 }
437 />
438 </View>
439 </ScreenContent>
440 </View>
441 );
443​
444/** The read-only view as its own screen: a sheet, or the whole screen when maximized from the inspector. */
445export function LinkedThreadSheet({ route }: StaticScreenProps<LinkedThreadRouteParams>) {
446 const { viaEnvironmentId, environmentId, threadId, label, title } = route.params;
447 return (
448 <LinkedThreadView
449 key={`${viaEnvironmentId}:${environmentId}:${threadId}`}
450 target={{
451 viaEnvironmentId: EnvironmentId.make(viaEnvironmentId),
452 environmentId: EnvironmentId.make(environmentId),
453 threadId: ThreadId.make(threadId),
454 label,
455 title: title ?? null,
456 }}
457 />
458 );