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

ThreadAgentsSheet.tsx

197 lines6.7 KB

1import { useAtomValue } from "@effect/atom-react";
2import type { ThreadTurnSubagents } from "@t3tools/client-runtime/state/thread-subagents";
3import {
4 isOrchestrationV2WorkActive,
5 type EnvironmentId,
6 type OrchestrationV2Subagent,
7 type ThreadId,
8} from "@t3tools/contracts";
9import { deriveSubagentElapsedMs, formatDuration } from "@t3tools/shared/orchestrationTiming";
10import { StackActions, useNavigation, type StaticScreenProps } from "@react-navigation/native";
11import * as DateTime from "effect/DateTime";
12import * as Haptics from "expo-haptics";
13import { useEffect, useState } from "react";
14import { Platform, Pressable, ScrollView, View } from "react-native";
15import { Screen, ScreenStack, ScreenStackHeaderConfig } from "react-native-screens";
16import { useSafeAreaInsets } from "react-native-safe-area-context";
17​
18import { AndroidSheetHeader } from "../../components/AndroidScreenHeader";
19import { AppText as Text } from "../../components/AppText";
20import { useUniwindTheme } from "../../lib/useUniwindTheme";
21import { environmentThreadDetails } from "../../state/threads";
22import { nativeHeaderScrollEdgeEffects } from "../../native/StackHeader";
23import { SubagentRow } from "./SubagentRow";
24​
25const HEADER_SCROLL_EDGE_EFFECTS = nativeHeaderScrollEdgeEffects(Platform.OS, Platform.Version);
26​
27type AgentsTarget = { readonly environmentId: EnvironmentId; readonly threadId: ThreadId };
28​
29export function useThreadTurnSubagents(target: AgentsTarget): ThreadTurnSubagents | null {
30 return useAtomValue(environmentThreadDetails.turnSubagentsAtom(target));
32​
33export function ThreadAgentsSheet({ route }: StaticScreenProps<AgentsTarget>) {
34 const target = route.params;
35 const navigation = useNavigation();
36 const insets = useSafeAreaInsets();
37 const theme = useUniwindTheme();
38 const turn = useThreadTurnSubagents(target);
39 const subagents = turn?.subagents ?? [];
40 const hasLiveAgent = (turn?.liveCount ?? 0) > 0;
41​
42 const openChildThread = (childThreadId: ThreadId) => {
43 void Haptics.selectionAsync();
44 // Replace rather than push: the sheet is a leaf, and the child thread
45 // belongs in the workspace stack where Home's back button expects it.
46 navigation.dispatch(
47 StackActions.replace("Thread", {
48 environmentId: target.environmentId,
49 threadId: childThreadId,
50 }),
51 );
52 };
53​
54 const content = (
55 <ScrollView
56 className="flex-1"
57 // The iOS header is translucent and floats over this view; UIKit has to
58 // inset the content or the first row sits underneath the title.
59 contentInsetAdjustmentBehavior={Platform.OS === "ios" ? "automatic" : "never"}
60 contentContainerClassName="px-5 pb-6"
61 contentContainerStyle={{ paddingBottom: Math.max(insets.bottom, 16) + 8 }}
62 >
63 {subagents.length === 0 ? (
64 <Text className="pt-6 text-center text-sm text-foreground-muted">
65 No agents in this turn.
66 </Text>
67 ) : (
68 subagents.map((subagent) => (
69 <AgentRow
70 key={subagent.id}
71 subagent={subagent}
72 environmentId={target.environmentId}
73 tickSeconds={hasLiveAgent}
74 onOpen={openChildThread}
75 />
76 ))
77 )}
78 </ScrollView>
79 );
80​
81 if (Platform.OS === "ios") {
82 // A plain formSheet screen never renders a stack header, so it comes from
83 // a nested native stack inside the sheet (same shape as the git sheet).
84 return (
85 <View collapsable={false} className="flex-1 bg-sheet">
86 <ScreenStack style={{ flex: 1 }}>
87 <Screen
88 activityState={2}
89 enabled
90 isNativeStack
91 screenId="thread-agents-sheet-native"
92 scrollEdgeEffects={HEADER_SCROLL_EDGE_EFFECTS}
93 style={{ backgroundColor: theme["--color-sheet"], flex: 1 }}
94 >
95 {content}
96 <ScreenStackHeaderConfig
97 backgroundColor="rgba(0,0,0,0)"
98 color={theme["--color-foreground"]}
99 hideBackButton
100 hideShadow={false}
101 title="Agents"
102 titleColor={theme["--color-foreground"]}
103 titleFontSize={18}
104 titleFontWeight="800"
105 translucent
106 />
107 </Screen>
108 </ScreenStack>
109 </View>
110 );
111 }
112​
113 return (
114 <View collapsable={false} className="flex-1 bg-sheet">
115 <AndroidSheetHeader title="Agents" onBack={() => navigation.goBack()} />
116 {content}
117 </View>
118 );
120​
121function AgentRow(props: {
122 readonly environmentId: EnvironmentId;
123 readonly subagent: OrchestrationV2Subagent;
124 readonly tickSeconds: boolean;
125 readonly onOpen: (childThreadId: ThreadId) => void;
126}) {
127 const { subagent } = props;
128 const childThreadId = subagent.childThreadId;
129​
130 const row = (
131 <View className="border-b border-border py-3.5">
132 <SubagentRow
133 environmentId={props.environmentId}
134 subagent={subagent}
135 elapsed={<AgentElapsed subagent={subagent} tickSeconds={props.tickSeconds} />}
136 />
137 </View>
138 );
139​
140 if (childThreadId === null) {
141 return (
142 <View
143 accessible
144 accessibilityHint="Provider-managed agent. Its work appears in the transcript."
145 >
146 {row}
147 </View>
148 );
149 }
150​
151 return (
152 <Pressable
153 accessibilityRole="link"
154 accessibilityHint="Opens this agent's thread"
155 onPress={() => props.onOpen(childThreadId)}
156 className="active:opacity-70"
157 >
158 {row}
159 </Pressable>
160 );
162​
163function AgentElapsed(props: {
164 readonly subagent: OrchestrationV2Subagent;
165 readonly tickSeconds: boolean;
166}) {
167 const elapsed = useSubagentElapsed(props.subagent, props.tickSeconds);
168 return elapsed === null ? null : (
169 <Text className="shrink-0 text-xs tabular-nums text-foreground-muted">{elapsed}</Text>
170 );
172​
173/**
174 * Elapsed time for one agent. Only live work ticks, inside AgentElapsed,
175 * so the timer never repaints the metadata or a settled sheet.
176 */
177function useSubagentElapsed(
178 subagent: Pick<OrchestrationV2Subagent, "status" | "startedAt" | "completedAt">,
179 tickSeconds: boolean,
180): string | null {
181 const [nowMs, setNowMs] = useState(() => Date.now());
182 const running = isOrchestrationV2WorkActive(subagent.status);
183 useEffect(() => {
184 if (!tickSeconds || !running) return;
185 const intervalId = setInterval(() => setNowMs(Date.now()), 1_000);
186 return () => clearInterval(intervalId);
187 }, [running, tickSeconds]);
188 const elapsedMs = deriveSubagentElapsedMs(
189 {
190 status: subagent.status,
191 startedAt: subagent.startedAt === null ? null : DateTime.formatIso(subagent.startedAt),
192 completedAt: subagent.completedAt === null ? null : DateTime.formatIso(subagent.completedAt),
193 },
194 nowMs,
195 );
196 return elapsedMs === null || elapsedMs === 0 ? null : formatDuration(elapsedMs);