Skip to content

Where people and agents ship software together. The open-source git platform for the whole job: issues, agents, checks and deploys to the edge.

g1t.sh
503 linesCodeBlameRaw
1import { ArrowUp, MessageSquare, RotateCcw, Settings2, Square } from "lucide-react";
2import { type FormEvent, type KeyboardEvent, useCallback, useEffect, useMemo, useRef, useState } from "react";
3import { Link, useLocation } from "react-router";
4
5import { type AskSetup, type ChatLiveEvent, type ChatMessage, type Result } from "@g1t/contracts";
6
7import { askPage, askWhere } from "../lib/ask";
8import { browserTimeZone } from "../lib/time-zone";
9import { anyAnswering, applyLive, fromG1t, suggestions } from "../lib/g1t-chat";
10import { Conversation, ConversationContent, ConversationEmptyState, ConversationScrollButton } from "./ai-elements/conversation";
11import { Message, MessageContent } from "./ai-elements/message";
12import type { ResponseContext } from "./ai-elements/response";
13import { Suggestion, Suggestions } from "./ai-elements/suggestion";
14import { AskedFrom, G1tAnswer } from "./chat/answer";
15import { useChatLive } from "./chat/live";
16import { MarkGlyph } from "./logo";
17import { Alert, AlertDescription, AlertTitle } from "./ui/alert";
18import { Button } from "./ui/button";
19import { Hint } from "./ui/hint";
20import { Kbd } from "./ui/kbd";
21import { SheetClose, SheetContent, SheetDescription, SheetHeader, SheetTitle } from "./ui/sheet";
22import { Skeleton } from "./ui/skeleton";
23import { Textarea } from "./ui/textarea";
24
25/**
26 * Ask g1t: a conversation with g1t about your work, from the top bar. It
27 * is your direct message with @g1t in Chat: the same messages, the same
28 * answers, whichever you write in. The answers come from the AI provider
29 * and model an owner chose for the workspace (Integrations → Your AI
30 * providers → Ask g1t), on the workspace's own key: g1t hosts no model.
31 *
32 * Each question carries the page you are on, which g1t is told. The chat
33 * service has g1t answer, and the answer streams into the direct message
34 * over its live socket, so it shows here and in Chat at once. The panel
35 * shows the current conversation, since the latest "New conversation";
36 * everything before it stays in Chat.
37 */
38
39type Setup = AskSetup & { owner: boolean };
40type SetupAnswer = { ok: boolean; value?: AskSetup; error?: { message: string }; owner: boolean };
41type Shown = ChatMessage & { pending?: boolean; failed?: boolean };
42
43const channelKey = (slug: string) => `g1t:ask-dm:${slug}`;
44
45function rememberedChannel(slug: string): string | null {
46 try {
47 return sessionStorage.getItem(channelKey(slug));
48 } catch {
49 return null;
50 }
51}
52
53function rememberChannel(slug: string, id: string) {
54 try {
55 sessionStorage.setItem(channelKey(slug), id);
56 } catch {
57 // Not kept: it is asked for again next time.
58 }
59}
60
61async function chatApi<T>(slug: string, body: Record<string, unknown>): Promise<Result<T>> {
62 try {
63 const response = await fetch(`/${slug}/-/chat/api`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body) });
64 return (await response.json()) as Result<T>;
65 } catch {
66 return { ok: false, error: { code: "conflict", message: "g1t could not be reached. Check your connection and try again." } };
67 }
68}
69
70/** Oldest first, the newest message from each id. */
71function byId(list: Shown[]): Shown[] {
72 return [...new Map(list.map((m) => [m.id, m])).values()].sort((a, b) => (a.id < b.id ? -1 : a.id > b.id ? 1 : 0));
73}
74
75/**
76 * The viewer's direct message with @g1t, as the panel shows it. It belongs
77 * to the top bar's button, not the panel, so what was said stays while the
78 * panel is closed; the answer itself is kept by chat either way.
79 */
80function useG1tConversation(slug: string, open: boolean) {
81 const [channelId, setChannelId] = useState<string | null>(null);
82 const [messages, setMessages] = useState<Shown[]>([]);
83 const [loaded, setLoaded] = useState(false);
84 const [problem, setProblem] = useState<string | null>(null);
85 const opening = useRef<Promise<string | null> | null>(null);
86
87 const channel = useCallback(async (): Promise<string | null> => {
88 if (channelId) return channelId;
89 opening.current ??= (async () => {
90 const remembered = rememberedChannel(slug);
91 if (remembered) return remembered;
92 const opened = await chatApi<{ channel: { id: string } }>(slug, { intent: "g1t_dm" });
93 if (!opened.ok) {
94 setProblem(opened.error.message);
95 return null;
96 }
97 rememberChannel(slug, opened.value.channel.id);
98 return opened.value.channel.id;
99 })().finally(() => {
100 opening.current = null;
101 });
102 const id = await opening.current;
103 if (id) setChannelId(id);
104 return id;
105 }, [channelId, slug]);
106
107 const load = useCallback(async () => {
108 const id = await channel();
109 if (!id) return;
110 try {
111 const response = await fetch(`/${slug}/-/chat/api?channel=${encodeURIComponent(id)}&limit=60`, { headers: { accept: "application/json" } });
112 const page = (await response.json()) as Result<{ messages: ChatMessage[] }>;
113 if (page.ok) {
114 setMessages((now) => byId([...now.filter((m) => m.pending), ...page.value.messages.filter((m) => !m.deleted_at && !m.thread_root)]));
115 setProblem(null);
116 } else if (page.error.code === "not_found") {
117 // Kept from another session that no longer has it: open it again.
118 try {
119 sessionStorage.removeItem(channelKey(slug));
120 } catch {
121 // Nothing kept.
122 }
123 setChannelId(null);
124 } else setProblem(page.error.message);
125 } catch {
126 setProblem("g1t could not be reached. Check your connection and try again.");
127 }
128 setLoaded(true);
129 }, [channel, slug]);
130
131 useEffect(() => {
132 if (open) void load();
133 }, [open, load]);
134
135 const onEvent = useCallback((event: ChatLiveEvent) => {
136 if (!channelId) return;
137 setMessages((now) => applyLive(now, event, channelId) as Shown[]);
138 }, [channelId]);
139
140 // Read up to the newest message while the panel is open and in view, as
141 // the conversation in Chat does: it is the same direct message, so what
142 // was read here is not left unread there.
143 const lastRead = useRef<string | null>(null);
144 useEffect(() => {
145 if (!open || !channelId) return;
146 const markRead = () => {
147 if (document.visibilityState !== "visible") return;
148 const newest = [...messages].reverse().find((m) => !m.pending);
149 if (!newest || newest.id === lastRead.current) return;
150 lastRead.current = newest.id;
151 void chatApi(slug, { intent: "read", channel_id: channelId, id: newest.id });
152 window.dispatchEvent(new CustomEvent("g1t:chat-read", { detail: channelId }));
153 };
154 const timer = setTimeout(markRead, 400);
155 document.addEventListener("visibilitychange", markRead);
156 window.addEventListener("focus", markRead);
157 return () => {
158 clearTimeout(timer);
159 document.removeEventListener("visibilitychange", markRead);
160 window.removeEventListener("focus", markRead);
161 };
162 }, [open, channelId, messages, slug]);
163
164 const ask = useCallback(
165 async (text: string, pathname: string) => {
166 const body = text.trim();
167 if (!body) return;
168 const id = await channel();
169 if (!id) return;
170 const pendingId = `~pending-${Date.now().toString(36)}`;
171 const pending: Shown = {
172 id: pendingId,
173 channel_id: id,
174 author: { kind: "user", id: "", name: "", display_name: "", avatar: null, role: null },
175 kind: "text",
176 body,
177 card: null,
178 thread_root: null,
179 reply_count: 0,
180 last_reply_at: null,
181 created_at: new Date().toISOString(),
182 edited_at: null,
183 deleted_at: null,
184 pending: true,
185 };
186 setMessages((now) => [...now, pending]);
187 const saved = await chatApi<ChatMessage>(slug, { intent: "post", channel_id: id, body, page: { ...askPage(pathname), time_zone: browserTimeZone() } });
188 setMessages((now) => (saved.ok ? byId([...now.filter((m) => m.id !== pendingId), saved.value]) : now.map((m) => (m.id === pendingId ? { ...m, failed: true } : m))));
189 // The answer arrives over the socket; should it have opened late, ask once more.
190 if (saved.ok) setTimeout(() => void load(), 1_500);
191 },
192 [channel, slug, load],
193 );
194
195 const act = useCallback(
196 async (intent: "g1t_stop" | "g1t_reset" | "g1t_retry") => {
197 const id = await channel();
198 if (!id) return;
199 const done = await chatApi<ChatMessage | null>(slug, { intent, channel_id: id });
200 if (!done.ok) setProblem(done.error.message);
201 else if (intent === "g1t_reset" && done.value) setMessages((now) => byId([...now, done.value as ChatMessage]));
202 },
203 [channel, slug],
204 );
205
206 return { channelId, messages, loaded, problem, ask, act, load, onEvent };
207}
208
209type G1tConversation = ReturnType<typeof useG1tConversation>;
210
211/**
212 * The Ask panel's sheet (components/ask-button.tsx loads it the first time
213 * the top bar's Ask opens, so pages don't carry it until then): the
214 * conversation, kept while the panel is closed.
215 */
216export function AskSheet({ slug, open }: { slug: string; open: boolean }) {
217 const conversation = useG1tConversation(slug, open);
218 const busy = anyAnswering(conversation.messages);
219 return (
220 <SheetContent
221 side="right"
222 className="sm:max-w-xl"
223 // Esc stops an answer still coming first; pressed again, it closes the panel.
224 onEscapeKeyDown={(event) => {
225 if (!busy) return;
226 event.preventDefault();
227 void conversation.act("g1t_stop");
228 }}
229 >
230 <AskPanel slug={slug} open={open} conversation={conversation} />
231 </SheetContent>
232 );
233}
234
235/** The live socket of the direct message, while the panel is open. */
236function LiveSocket({ slug, channelId, onEvent, onReconnect }: { slug: string; channelId: string; onEvent: (event: ChatLiveEvent) => void; onReconnect: () => void }) {
237 useChatLive(slug, channelId, onEvent, onReconnect);
238 return null;
239}
240
241function AskPanel({ slug, open, conversation }: { slug: string; open: boolean; conversation: G1tConversation }) {
242 const { pathname } = useLocation();
243 const { channelId, messages, loaded, problem, ask, act, load, onEvent } = conversation;
244 const [setup, setSetup] = useState<Setup | null>(null);
245 const [setupError, setSetupError] = useState<string | null>(null);
246 const [draft, setDraft] = useState("");
247 const input = useRef<HTMLTextAreaElement>(null);
248
249 // What Ask answers with, each time it opens: an owner may have changed it.
250 useEffect(() => {
251 if (!open) return;
252 let live = true;
253 fetch(`/${slug}/-/ask`, { headers: { accept: "application/json" } })
254 .then((response) => (response.ok ? (response.json() as Promise<SetupAnswer>) : Promise.reject(new Error(String(response.status)))))
255 .then((answer) => {
256 if (!live) return;
257 if (answer.ok && answer.value) {
258 setSetup({ ...answer.value, owner: answer.owner });
259 setSetupError(null);
260 } else setSetupError(answer.error?.message ?? "Ask could not be loaded.");
261 })
262 .catch(() => live && setSetupError("Ask could not be loaded. Try again in a moment."));
263 return () => {
264 live = false;
265 };
266 }, [open, slug]);
267
268 useEffect(() => {
269 if (open) requestAnimationFrame(() => input.current?.focus());
270 }, [open]);
271
272 // ⌘K or Ctrl+K, while the panel is open, goes to its box rather than the command palette.
273 useEffect(() => {
274 if (!open) return;
275 const onKey = (event: globalThis.KeyboardEvent) => {
276 if ((event.metaKey || event.ctrlKey) && event.key.toLowerCase() === "k") {
277 event.preventDefault();
278 event.stopImmediatePropagation();
279 input.current?.focus();
280 }
281 };
282 window.addEventListener("keydown", onKey, { capture: true });
283 return () => window.removeEventListener("keydown", onKey, { capture: true });
284 }, [open]);
285
286 // The current conversation: what came after the latest "New conversation".
287 const shown = useMemo(() => {
288 let start = 0;
289 messages.forEach((m, index) => {
290 if (m.reset && fromG1t(m)) start = index + 1;
291 });
292 return messages.slice(start);
293 }, [messages]);
294 const earlier = shown.length < messages.length;
295 const busy = anyAnswering(messages);
296 const ready = setup != null && setup.problem == null;
297 const where = askPage(pathname);
298 const lastAnswer = [...shown].reverse().find((m) => !m.pending);
299 const context = useMemo<ResponseContext>(() => ({ slug, repo: where.repo ?? null }), [slug, where.repo?.namespace, where.repo?.name]);
300
301 const send = (text: string) => {
302 if (!ready || busy || !text.trim()) return;
303 setDraft("");
304 void ask(text, pathname);
305 };
306 const submit = (event: FormEvent) => {
307 event.preventDefault();
308 send(draft);
309 };
310 const onKeyDown = (event: KeyboardEvent<HTMLTextAreaElement>) => {
311 if (event.key === "Enter" && !event.shiftKey && !event.nativeEvent.isComposing) {
312 event.preventDefault();
313 send(draft);
314 }
315 };
316 const fresh = () => {
317 void act("g1t_reset");
318 input.current?.focus();
319 };
320
321 return (
322 <>
323 {open && channelId && <LiveSocket slug={slug} channelId={channelId} onEvent={onEvent} onReconnect={() => void load()} />}
324 <SheetHeader className="gap-1 border-b border-line pb-3">
325 <SheetTitle className="flex items-center gap-2">
326 <MarkGlyph className="h-3.5" />
327 Ask g1t
328 </SheetTitle>
329 <SheetDescription className="sr-only">A conversation with g1t about your work in {slug}. It is your direct message with g1t in Chat.</SheetDescription>
330 <div className="flex min-h-7 flex-wrap items-center gap-2 text-xs text-muted">
331 {setup == null && !setupError ? (
332 <Skeleton className="h-4 w-40" />
333 ) : ready ? (
334 <span className="min-w-0 truncate">
335 Answers with {setup.connection_name} · <span className="font-mono">{setup.model}</span>
336 </span>
337 ) : (
338 <span>Not set up yet</span>
339 )}
340 <span className="ml-auto flex items-center gap-0.5">
341 {setup?.owner && (
342 <Hint label="Choose the provider and model">
343 <Button asChild variant="ghost" size="icon-xs" aria-label="Choose the provider and model">
344 <Link to={`/${slug}/-/integrations/models#ask`}>
345 <Settings2 size={14} />
346 </Link>
347 </Button>
348 </Hint>
349 )}
350 {channelId && (
351 <Hint label="Open this conversation in Chat">
352 <Button asChild variant="ghost" size="icon-xs" aria-label="Open in Chat">
353 <Link to={`/${slug}/-/chat/dm/${channelId}`}>
354 <MessageSquare size={14} />
355 </Link>
356 </Button>
357 </Hint>
358 )}
359 <Hint label="New conversation: g1t reads only what comes next">
360 <Button variant="ghost" size="xs" onClick={fresh} disabled={shown.length === 0}>
361 <RotateCcw size={13} />
362 New conversation
363 </Button>
364 </Hint>
365 </span>
366 </div>
367 </SheetHeader>
368
369 <Conversation aria-busy={busy}>
370 <ConversationContent>
371 {setupError && (
372 <Alert tone="danger">
373 <AlertDescription className="text-danger">{setupError}</AlertDescription>
374 </Alert>
375 )}
376 {problem && (
377 <Alert tone="danger">
378 <AlertDescription className="text-danger">{problem}</AlertDescription>
379 </Alert>
380 )}
381 {setup && setup.problem && <NotSetUp slug={slug} setup={setup} />}
382 {earlier && channelId && (
383 <p className="text-center text-xs text-faint">
384 Earlier conversations are in{" "}
385 <Link to={`/${slug}/-/chat/dm/${channelId}`} className="text-accent hover:underline">
386 your direct message with g1t
387 </Link>
388 .
389 </p>
390 )}
391 {!loaded && open ? (
392 <div className="space-y-3" aria-busy="true">
393 <Skeleton className="ml-auto h-9 w-2/3 rounded-2xl" />
394 <Skeleton className="h-4 w-11/12" />
395 <Skeleton className="h-4 w-3/4" />
396 </div>
397 ) : shown.length === 0 && ready ? (
398 <ConversationEmptyState className="pt-16">
399 <MarkGlyph className="h-7" />
400 <div className="space-y-1">
401 <h3 className="text-base font-semibold text-fg">Ask about your work</h3>
402 <p className="max-w-sm text-sm text-muted">
403 {where.repo
404 ? `g1t is told you're in ${where.repo.namespace}/${where.repo.name}${where.issue ? `, on issue #${where.issue}` : where.pull ? `, on pull request #${where.pull}` : ""}.`
405 : "g1t is told which page you're on, and reads the issue or pull request in front of you."}
406 </p>
407 </div>
408 <Suggestions className="mt-3 max-w-md justify-center">
409 {suggestions(where).map((text) => (
410 <Suggestion key={text} suggestion={text} onPick={send} />
411 ))}
412 </Suggestions>
413 </ConversationEmptyState>
414 ) : (
415 shown.map((m) =>
416 fromG1t(m) ? (
417 m.reset ? null : (
418 <Message key={m.id} from="assistant">
419 <G1tAnswer message={m} context={context} onRetry={!busy && lastAnswer?.id === m.id ? () => void act("g1t_retry") : undefined} />
420 </Message>
421 )
422 ) : (
423 <Message key={m.id} from="user">
424 <MessageContent className={m.pending && !m.failed ? "opacity-70" : undefined}>{m.body}</MessageContent>
425 <AskedFrom page={m.page} />
426 {m.failed && <span className="text-xs text-danger">Not sent. Ask again.</span>}
427 </Message>
428 ),
429 )
430 )}
431 </ConversationContent>
432 <ConversationScrollButton />
433 </Conversation>
434
435 <form onSubmit={submit} className="border-t border-line px-4 pt-3 pb-3">
436 <div className="rounded-xl border border-line bg-bg transition-shadow focus-within:border-accent-dim focus-within:ring-2 focus-within:ring-accent/25">
437 <label htmlFor="ask-g1t" className="sr-only">
438 Ask g1t
439 </label>
440 <Textarea
441 id="ask-g1t"
442 ref={input}
443 value={draft}
444 onChange={(event) => setDraft(event.target.value)}
445 onKeyDown={onKeyDown}
446 rows={2}
447 maxLength={16_000}
448 disabled={!ready}
449 placeholder={ready ? "Ask about this page, a repository, or your work" : "Ask is not set up yet"}
450 className="max-h-48 min-h-14 resize-none border-0 bg-transparent px-3 pt-2.5 pb-1 shadow-none focus-visible:ring-0"
451 />
452 <div className="flex items-center gap-2 px-2 pb-2">
453 <span className="truncate pl-1 text-xs text-faint">{askWhere(where)}</span>
454 <span className="ml-auto" />
455 {busy ? (
456 <Hint label="Stop the answer (Esc)">
457 <Button type="button" variant="outline" size="icon-sm" onClick={() => void act("g1t_stop")} aria-label="Stop">
458 <Square size={12} className="fill-current" />
459 </Button>
460 </Hint>
461 ) : (
462 <Hint label="Send (Enter)">
463 <Button type="submit" variant="accent" size="icon-sm" disabled={!ready || !draft.trim()} aria-label="Send">
464 <ArrowUp size={15} />
465 </Button>
466 </Hint>
467 )}
468 </div>
469 </div>
470 <p className="mt-2 px-1 text-[0.6875rem] leading-relaxed text-faint">
471 Answers come from your workspace&apos;s own AI provider and can be wrong. Kept in your direct message with g1t.{" "}
472 <span className="whitespace-nowrap max-sm:hidden">
473 <Kbd>Shift</Kbd> <Kbd>Enter</Kbd> for a new line.
474 </span>
475 </p>
476 </form>
477 </>
478 );
479}
480
481function NotSetUp({ slug, setup }: { slug: string; setup: Setup }) {
482 return (
483 <Alert tone="info">
484 <AlertTitle>Ask needs one of your workspace&apos;s AI providers</AlertTitle>
485 <AlertDescription>
486 <p>{setup.problem}</p>
487 <p className="mt-2">
488 Ask answers with an AI provider your workspace connects, on its own key: g1t hosts no model for it.{" "}
489 {setup.owner ? (
490 // Following it closes the panel, so the page it opens is not behind it.
491 <SheetClose asChild>
492 <Link to={`/${slug}/-/integrations/models#ask`} className="text-accent hover:underline">
493 Connect a provider and choose it for Ask
494 </Link>
495 </SheetClose>
496 ) : (
497 <>Ask an owner of {slug} to connect one and choose it for Ask.</>
498 )}
499 </p>
500 </AlertDescription>
501 </Alert>
502 );
503}