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