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