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

LinkedThreadPane.tsx

278 lines10.9 KB

1import { isLinkedThreadWorking, linkedThreadFailure } from "@t3tools/client-runtime/linked-thread";
2import type { ScopedThreadRef } from "@t3tools/contracts";
3import { T, useGT, useMessages, Var } from "gt-react";
4import { EyeIcon, PlugIcon } from "lucide-react";
5import { useEffect, useEffectEvent, useState, type ReactNode } from "react";
6​
7import { useStableCallback } from "../../hooks/useStableCallback";
8import { type LinkedThreadSurface, linkedThreadTitle } from "../../linkedThreadSurface";
9import { useEnvironment } from "../../state/environments";
10import {
11 linkedThreadItemSource,
12 useConnectLinkedEnvironment,
13 useLinkedThreadView,
14} from "../../state/linkedThreadView";
15import { Alert, AlertAction, AlertDescription, AlertTitle } from "../ui/alert";
16import { Button } from "../ui/button";
17import { ComposerBannerStack, type ComposerBannerStackItem } from "./ComposerBannerStack";
18import { ComposerSurface } from "./ComposerSurface";
19import {
20 ReadOnlyComposerBar,
21 ReadOnlyComposerLead,
22 ReadOnlyComposerStatus,
23} from "./ReadOnlyComposerBar";
24import { Spinner } from "../ui/spinner";
25import { toastManager } from "../ui/toast";
26import type { MessagesTimelineHistoryControls } from "./MessagesTimeline";
27import { ReadOnlyThreadTimeline } from "./ReadOnlyThreadTimeline";
28​
29/**
30 * Stands where a composer would: the thread takes no messages from here. `action` is the one way
31 * forward it offers, and `notice` what came of it.
32 */
33function LinkedThreadComposer(props: {
34 /** The linked environment the thread is on. */
35 readonly label: string;
36 /** The environment that reads it. */
37 readonly via: string;
38 readonly working: boolean;
39 readonly action?: ReactNode;
40 readonly notice?: ComposerBannerStackItem | null;
41}) {
42 const { label, via } = props;
43 const gt = useGT();
44 return (
45 <div className="chat-composer-lane flex shrink-0 flex-col gap-1 pt-1.5 pb-4 sm:pt-2 sm:pb-5">
46 {props.notice ? <ComposerBannerStack items={[props.notice]} detached /> : null}
47 <ComposerSurface.Shell>
48 <ComposerSurface.Host>
49 <div className="relative z-10">
50 <ReadOnlyComposerBar actions={props.action}>
51 <ReadOnlyComposerLead>
52 <EyeIcon aria-hidden className="size-4 shrink-0 text-muted-foreground" />
53 <span className="min-w-0 truncate font-medium text-foreground">
54 <T>Read-only</T>
55 </span>
56 </ReadOnlyComposerLead>
57 <ReadOnlyComposerStatus role="status">
58 {props.working
59 ? gt`On ${{ label }} via ${{ via }} · Working`
60 : gt`On ${{ label }} via ${{ via }}`}
61 </ReadOnlyComposerStatus>
62 </ReadOnlyComposerBar>
63 </div>
64 </ComposerSurface.Host>
65 </ComposerSurface.Shell>
66 </div>
67 );
69​
70/** Environments an unasked connect was tried for; a failed one waits for the button after that. */
71const autoConnectTried = new Set<string>();
72​
73const NO_ATTACHMENT_URLS: ReadonlyMap<string, string> = new Map();
74const noAttachmentUrls = () => NO_ATTACHMENT_URLS;
75const ignore = () => {};
76​
77/**
78 * A linked environment's thread, streamed through the environment this client is connected to
79 * and drawn by the timeline every thread uses. The client never connects to the linked one, so
80 * the view only reads: what would need that connection is absent. Key it by its surface id.
81 */
82export function LinkedThread(props: {
83 /** The thread whose panel shows it as a tab, or null on the main screen. */
84 readonly panelRef: ScopedThreadRef | null;
85 readonly surface: LinkedThreadSurface;
86 /** Whether it is showing; the stream runs only while it is. */
87 readonly visible: boolean;
88 /** What sits above the timeline on the main screen; a tab already names the thread. */
89 readonly renderHeader?: (title: string) => ReactNode;
90 /** Connect once without being asked; what it cannot do alone is left to the button. */
91 readonly autoConnect?: boolean;
92}) {
93 const { surface, panelRef } = props;
94 const gt = useGT();
95 const m = useMessages();
96 const via = useEnvironment(surface.viaEnvironmentId)?.label ?? gt`this environment`;
97 const { view, error, retry } = useLinkedThreadView(panelRef, surface, props.visible);
98 const [turnItemSource] = useState(() => linkedThreadItemSource(surface));
99 const label = surface.label;
100 const projection = view?.thread.projection ?? null;
101 const connection = useConnectLinkedEnvironment(panelRef, surface);
102 const connectState = connection.state;
103 const connecting = connectState.phase === "connecting";
104 const autoConnect = useEffectEvent(() => {
105 if (props.autoConnect !== true || autoConnectTried.has(surface.environmentId)) return;
106 autoConnectTried.add(surface.environmentId);
107 void connection.connect({ unasked: true });
108 });
109 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- pairing starts a network exchange with another machine, once when a moved thread opens
110 useEffect(() => autoConnect(), []);
111 const connect = async () => {
112 const outcome = await connection.connect();
113 if (outcome.type === "connected") {
114 toastManager.add({
115 type: "success",
116 title: gt`Connected to ${{ label }}`,
117 description: gt`This device is paired with it and can use its threads.`,
118 });
119 }
120 };
121 const connectNotice: ComposerBannerStackItem | null =
122 connectState.phase === "connecting"
123 ? {
124 id: "connecting",
125 variant: "info",
126 icon: <Spinner size="sm" />,
127 title: gt`Connecting to ${{ label }}…`,
128 }
129 : connectState.phase === "unreachable"
130 ? {
131 id: "unreachable",
132 variant: "warning",
133 icon: <PlugIcon />,
134 title: gt`${{ label: connectState.label }} is not reachable from this device`,
135 description: gt`Join a network it is on, such as its Tailscale network, and try again. You can keep reading here.`,
136 }
137 : connectState.phase === "manual"
138 ? {
139 id: "manual",
140 variant: "info",
141 icon: <PlugIcon />,
142 title: gt`${{ label: connectState.prefill.label }} needs a pairing code`,
143 description: gt`Create one on it, then add it to this device as an environment.`,
144 actions: (
145 <Button
146 size="xs"
147 variant="ghost"
148 onClick={() => connection.addWithCode(connectState.prefill)}
149 >
150 <T>Enter code</T>
151 </Button>
152 ),
153 }
154 : null;
155 const connectAction = (
156 <Button size="sm" variant="outline" disabled={connecting} onClick={() => void connect()}>
157 <PlugIcon aria-hidden />
158 <span className="@max-[320px]/composer-surface:sr-only">
159 <T>Connect to interact</T>
160 </span>
161 </Button>
162 );
163 const failure = error === null ? null : linkedThreadFailure(error, { via, label }, m);
164 const retryAction = failure?.retryable ? (
165 <AlertAction>
166 <Button size="sm" variant="outline" onClick={retry}>
167 <T>Try again</T>
168 </Button>
169 </AlertAction>
170 ) : null;
171 // A file or visual lives on the linked environment, which this client has no way to ask.
172 const renderHtmlRender = useStableCallback(() => (
173 <p className="chat-content-lane text-xs text-muted-foreground">
174 {gt`Open this thread on ${{ label }} to see this visual.`}
175 </p>
176 ));
177 const working = projection !== null && isLinkedThreadWorking(projection);
178 const historyControls: MessagesTimelineHistoryControls | undefined =
179 view === null || view.thread.historyCursor === null
180 ? undefined
181 : {
182 hasMoreHistory: true,
183 loading: view.history.loading,
184 error: view.history.failed ? gt`Could not load earlier turns. Try again.` : null,
185 onLoadEarlier: view.loadEarlier,
186 };
187 return (
188 // `data-chat-canvas` gives the timeline the side gutters it has in a thread's own chat.
189 <div
190 data-chat-canvas
191 className="flex h-full min-h-0 flex-col [--chat-lane-inset-end:0px] [--chat-lane-inset-start:0px] [--chat-timeline-gutter:0px]"
192 >
193 {props.renderHeader?.(
194 linkedThreadTitle(
195 { title: projection?.thread.title || surface.title },
196 gt`Thread on ${{ label }}`,
197 ),
198 )}
199 {projection === null ? (
200 <>
201 <div className="chat-composer-lane min-h-0 flex-1 overflow-y-auto py-3">
202 <div className="chat-content-lane">
203 {failure === null ? (
204 <div className="flex items-center gap-2 text-sm text-muted-foreground">
205 <Spinner size="sm" />
206 <T>
207 Reading from <Var>{label}</Var>…
208 </T>
209 </div>
210 ) : (
211 <Alert variant="error">
212 <AlertTitle>{failure.title}</AlertTitle>
213 <AlertDescription>{failure.detail}</AlertDescription>
214 {retryAction}
215 </Alert>
216 )}
217 </div>
218 </div>
219 <LinkedThreadComposer
220 label={label}
221 via={via}
222 working={false}
223 notice={connectNotice}
224 action={connectAction}
225 />
226 </>
227 ) : (
228 <ReadOnlyThreadTimeline
229 // No ":" so the timeline finds no environment thread behind the key.
230 threadKey={`linked-${encodeURIComponent(surface.id)}`}
231 projection={projection}
232 historyControls={historyControls}
233 turnItemSource={turnItemSource}
234 attachmentUrls={noAttachmentUrls}
235 onImageExpand={ignore}
236 onFileOpen={ignore}
237 renderHtmlRender={renderHtmlRender}
238 >
239 {() => (
240 <>
241 {failure === null ? null : (
242 <div className="chat-composer-lane shrink-0 pb-2">
243 <div className="chat-content-lane">
244 <Alert variant="warning">
245 <AlertTitle>{failure.title}</AlertTitle>
246 <AlertDescription>
247 {failure.detail} <T>Showing what was read before.</T>
248 </AlertDescription>
249 {retryAction}
250 </Alert>
251 </div>
252 </div>
253 )}
254 <LinkedThreadComposer
255 label={label}
256 via={via}
257 working={working}
258 notice={connectNotice}
259 action={connectAction}
260 />
261 </>
262 )}
263 </ReadOnlyThreadTimeline>
264 )}
265 </div>
266 );
268​
269/** A linked environment's thread as a right panel tab. Key it by its surface id. */
270export function LinkedThreadPane(props: {
271 /** The thread whose panel shows the tab. */
272 readonly panelRef: ScopedThreadRef;
273 readonly surface: LinkedThreadSurface;
274 /** Whether the tab is showing. */
275 readonly visible: boolean;
276}) {
277 return <LinkedThread panelRef={props.panelRef} surface={props.surface} visible={props.visible} />;