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

HostedPromptLinkLanding.tsx

208 lines7.2 KB

1import {
2 type LinkedPrompt,
3 promptLinkAppPath,
4 promptLinkDeepLink,
5} from "@t3tools/shared/promptLinks";
6import { parseNewThreadLink, parseThreadLinkPrompt } from "@t3tools/shared/promptLinksCopy";
7import { useLocation } from "@tanstack/react-router";
8import * as Schema from "effect/Schema";
9import { msg, T, useGT, useMessages } from "gt-react";
10import { type ReactNode, useEffect, useRef, useState } from "react";
11​
12import type { MessageResolver } from "../../i18n/messages";
13​
14import { DESKTOP_DOWNLOAD_URL } from "~/branding";
15import { useLocalStorage } from "~/hooks/useLocalStorage";
16import { isHostedStaticApp } from "~/hostedPairing";
17import { useEnvironments } from "~/state/environments";
18​
19import { Alert, AlertDescription, AlertTitle } from "../ui/alert";
20import { Button } from "../ui/button";
21import { Checkbox } from "../ui/checkbox";
22import { StandalonePage, StandalonePageHeader } from "../ui/standalone-page";
23​
24const OPENER_STORAGE_KEY = "t3code:prompt-link-opener";
25const Opener = Schema.NullOr(Schema.Literals(["app", "browser"]));
26​
27interface LinkSummary {
28 readonly title: string;
29 readonly description: string;
30 readonly prompt: LinkedPrompt | null;
31 readonly details: ReadonlyArray<string>;
33​
34function summarize(
35 appPath: string,
36 resolve: MessageResolver,
37): { ok: true; value: LinkSummary } | { ok: false; error: string } {
38 const PROMPT_HEADER = {
39 title: resolve(msg("Open this prompt")),
40 description: resolve(msg("It opens as a draft. Nothing runs until you press Send.")),
41 };
42 const url = new URL(appPath, window.location.origin);
43 if (url.pathname !== "/new") {
44 const prompt = parseThreadLinkPrompt(url.search, resolve);
45 if (!prompt.ok) return prompt;
46 return {
47 ok: true,
48 value:
49 prompt.value === null
50 ? {
51 title: resolve(msg("Open this thread")),
52 description: resolve(
53 msg("It opens in T3 Code if you're connected to the machine it runs on."),
54 ),
55 prompt: null,
56 details: [],
57 }
58 : {
59 ...PROMPT_HEADER,
60 prompt: prompt.value,
61 details: [resolve(msg("Opens one of your threads."))],
62 },
63 };
64 }
65 const link = parseNewThreadLink(url.search, resolve);
66 if (!link.ok) return link;
67 if (link.value.kind === "pull-request") {
68 const { owner, name, number } = link.value.pullRequest;
69 return {
70 ok: true,
71 value: {
72 ...PROMPT_HEADER,
73 prompt: link.value.prompt,
74 details: [
75 resolve(msg("Pull request {pullRequest}", { pullRequest: `${owner}/${name}#${number}` })),
76 ],
77 },
78 };
79 }
80 const { repository, provider, model } = link.value;
81 return {
82 ok: true,
83 value: {
84 ...PROMPT_HEADER,
85 prompt: link.value.prompt,
86 details: [
87 repository
88 ? resolve(
89 msg("Repository {repository}", {
90 repository: `${repository.owner}/${repository.name}`,
91 }),
92 )
93 : resolve(msg("No project")),
94 ...(provider
95 ? [resolve(msg("Model {model}", { model: model ? `${provider} ${model}` : provider }))]
96 : []),
97 ],
98 },
99 };
101​
102export function useHostedPromptLinkLanding(enabled: boolean): ReactNode | null {
103 const href = useLocation({ select: (location) => location.href });
104 const { environments, isReady } = useEnvironments();
105 const [opener, setOpener] = useLocalStorage(OPENER_STORAGE_KEY, null, Opener);
106 const [continuedHref, setContinuedHref] = useState<string | null>(null);
107 const appPath =
108 enabled && isHostedStaticApp()
109 ? promptLinkAppPath(new URL(href, window.location.origin).href, window.location.origin)
110 : null;
111 if (appPath === null || continuedHref === href) return null;
112 const canContinue = isReady && environments.length > 0;
113 if (opener === "browser") {
114 if (canContinue) return null;
115 if (!isReady) return <></>;
116 }
117 return (
118 <HostedPromptLinkLanding
119 appPath={appPath}
120 canContinue={canContinue}
121 openInAppRemembered={opener === "app"}
122 onChoose={(choice, remember) => {
123 if (remember) setOpener(choice);
124 if (choice === "browser") setContinuedHref(href);
125 }}
126 />
127 );
129​
130function HostedPromptLinkLanding({
131 appPath,
132 canContinue,
133 openInAppRemembered,
134 onChoose,
135}: {
136 readonly appPath: string;
137 readonly canContinue: boolean;
138 readonly openInAppRemembered: boolean;
139 readonly onChoose: (choice: "app" | "browser", remember: boolean) => void;
140}) {
141 const gt = useGT();
142 const m = useMessages();
143 const summary = summarize(appPath, m);
144 const [remember, setRemember] = useState(false);
145 const deepLink = promptLinkDeepLink(appPath);
146 const onPhone = /android|iphone|ipad/i.test(navigator.userAgent);
147 const autoOpenedRef = useRef(false);
148​
149 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- redirects window.location to the app deep link once when the user chose to always open in the app
150 useEffect(() => {
151 if (!openInAppRemembered || !summary.ok || autoOpenedRef.current) return;
152 autoOpenedRef.current = true;
153 window.location.href = deepLink;
154 }, [deepLink, openInAppRemembered, summary.ok]);
155​
156 if (!summary.ok) {
157 return (
158 <StandalonePage>
159 <StandalonePageHeader title={gt("Could not open the link")} description={summary.error} />
160 </StandalonePage>
161 );
162 }
163​
164 const { title, description, prompt, details } = summary.value;
165 return (
166 <StandalonePage>
167 <StandalonePageHeader title={title} description={description} />
168 {prompt !== null && prompt.hiddenCharacters > 0 ? (
169 <Alert className="mt-5" variant="error">
170 <AlertTitle>
171 <T>This prompt had hidden characters, it may be malicious</T>
172 </AlertTitle>
173 <AlertDescription>
174 {gt(
175 "{count, plural, one {T3 Code removed {count} hidden character. Read the prompt before you send it.} other {T3 Code removed {count} hidden characters. Read the prompt before you send it.}}",
176 { count: prompt.hiddenCharacters },
177 )}
178 </AlertDescription>
179 </Alert>
180 ) : null}
181 {prompt !== null ? (
182 <pre className="mt-5 max-h-72 overflow-auto rounded-lg border border-border bg-background p-3 text-sm whitespace-pre-wrap">
183 {prompt.text}
184 </pre>
185 ) : null}
186 {details.length > 0 ? (
187 <p className="mt-3 text-xs text-muted-foreground">{details.join(" · ")}</p>
188 ) : null}
189 <div className="mt-6 flex flex-wrap gap-2">
190 <Button render={<a href={deepLink} />} onClick={() => onChoose("app", remember)}>
191 {onPhone ? gt("Open in app") : gt("Open in desktop app")}
192 </Button>
193 {canContinue ? (
194 <Button variant="outline" onClick={() => onChoose("browser", remember)}>
195 <T>Continue here</T>
196 </Button>
197 ) : null}
198 <Button variant="ghost" render={<a href={DESKTOP_DOWNLOAD_URL} />}>
199 <T>Get T3 Code</T>
200 </Button>
201 </div>
202 <label className="mt-4 flex items-center gap-2 text-sm text-muted-foreground">
203 <Checkbox checked={remember} onCheckedChange={(checked) => setRemember(checked === true)} />
204 <T>Remember my choice</T>
205 </label>
206 </StandalonePage>
207 );