Open History to see the last commit
1import type { ProviderAuthResponse } from "@t3tools/contracts";
2import { useEffect, useRef, useState } from "react";
3import { GhosttyTerminalSurface } from "../../terminal/ghostty/surface";
4import { ensureLocalApi } from "../../localApi";
5import { terminalThemeFromApp } from "../ThreadTerminalDrawer";
6
7/** Loaded only for an interactive login. PTY input is serialized by the parent. */
8export default function ProviderAuthTerminal({
9 output,
10 outputOffset,
11 onResponse,
12}: {
13 readonly output: string;
14 readonly outputOffset?: number | undefined;
15 readonly onResponse: (response: Extract<ProviderAuthResponse, { type: "terminal" }>) => void;
16}) {
17 const mount = useRef<HTMLDivElement>(null);
18 const surface = useRef<GhosttyTerminalSurface | null>(null);
19 const latest = useRef({ output, offset: outputOffset ?? output.length, onResponse });
20 const written = useRef(0);
21 const [error, setError] = useState<string | null>(null);
22 useEffect(() => {
23 latest.current = { output, offset: outputOffset ?? output.length, onResponse };
24 const terminal = surface.current;
25 if (!terminal) return;
26 const delta = latest.current.offset - written.current;
27 if (delta > 0 && delta <= output.length) terminal.write(output.slice(-delta));
28 else if (delta !== 0) terminal.resetAndWrite(output);
29 written.current = latest.current.offset;
30 }, [output, outputOffset, onResponse]);
31 useEffect(() => {
32 const element = mount.current;
33 if (!element) return;
34 let disposed = false;
35 void GhosttyTerminalSurface.create(element, {
36 theme: terminalThemeFromApp(element),
37 font: { size: 13 },
38 onData: (data) => latest.current.onResponse({ type: "terminal", data }),
39 onResize: (cols, rows) =>
40 latest.current.onResponse({ type: "terminal", data: "", size: { cols, rows } }),
41 onSelectionChange: () => {},
42 beforeKey: (event) => event.key !== "Tab",
43 onLinkActivate: (url) => {
44 if (/^https?:\/\//i.test(url))
45 void ensureLocalApi()
46 .shell.openExternal(url)
47 .catch(() => setError("Could not open the provider link."));
48 },
49 })
50 .then((terminal) => {
51 if (disposed) {
52 terminal.dispose();
53 return;
54 }
55 surface.current = terminal;
56 terminal.write(latest.current.output);
57 written.current = latest.current.offset;
58 })
59 .catch(() => setError("Could not load the sign-in terminal. Cancel and retry sign-in."));
60 return () => {
61 disposed = true;
62 surface.current?.dispose();
63 surface.current = null;
64 };
65 }, []);
66 return (
67 <>
68 <div
69 ref={mount}
70 aria-label="Provider sign-in terminal"
71 className="relative h-64 overflow-hidden rounded-md border border-border"
72 />
73 {error ? (
74 <p role="alert" className="text-destructive">
75 {error}
76 </p>
77 ) : null}
78 </>
79 );
80}