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
548 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/**
227 * The Ask panel's sheet (components/ask-button.tsx loads it the first time
228 * the top bar's Ask opens, so pages don't carry it until then): the
229 * conversation, kept while the panel is closed.
230 */
231export function AskSheet({ slug, open }: { slug: string; open: boolean }) {
232 const conversation = useG1tConversation(slug, open);
233 const busy = anyAnswering(conversation.messages);
234 return (
235 <SheetContent
236 side="right"
237 className="sm:max-w-xl"
238 // Esc stops an answer still coming first; pressed again, it closes the panel.
239 onEscapeKeyDown={(event) => {
240 if (!busy) return;
241 event.preventDefault();
242 void conversation.act("g1t_stop");
243 }}
244 >
245 <AskPanel slug={slug} open={open} conversation={conversation} />
246 </SheetContent>
247 );
248}
249
250/** The live socket of the direct message, while the panel is open. */
251function LiveSocket({ slug, channelId, onEvent, onReconnect }: { slug: string; channelId: string; onEvent: (event: ChatLiveEvent) => void; onReconnect: () => void }) {
252 useChatLive(slug, channelId, onEvent, onReconnect);
253 return null;
254}
255
256function AskPanel({ slug, open, conversation }: { slug: string; open: boolean; conversation: G1tConversation }) {
257 const { pathname } = useLocation();
258 const { channelId, messages, loaded, problem, ask, act, clear, load, onEvent } = conversation;
259 const [clearing, setClearing] = useState(false);
260 const [setup, setSetup] = useState<Setup | null>(null);
261 const [setupError, setSetupError] = useState<string | null>(null);
262 const [draft, setDraft] = useState("");
263 const input = useRef<HTMLTextAreaElement>(null);
264
265 // What Ask answers with, each time it opens: an owner may have changed it.
266 useEffect(() => {
267 if (!open) return;
268 let live = true;
269 fetch(`/${slug}/-/ask`, { headers: { accept: "application/json" } })
270 .then((response) => (response.ok ? (response.json() as Promise<SetupAnswer>) : Promise.reject(new Error(String(response.status)))))
271 .then((answer) => {
272 if (!live) return;
273 if (answer.ok && answer.value) {
274 setSetup({ ...answer.value, owner: answer.owner });
275 setSetupError(null);
276 } else setSetupError(answer.error?.message ?? "Ask could not be loaded.");
277 })
278 .catch(() => live && setSetupError("Ask could not be loaded. Try again in a moment."));
279 return () => {
280 live = false;
281 };
282 }, [open, slug]);
283
284 useEffect(() => {
285 if (open) requestAnimationFrame(() => input.current?.focus());
286 }, [open]);
287
288 // ⌘K or Ctrl+K, while the panel is open, goes to its box rather than the command palette.
289 useEffect(() => {
290 if (!open) return;
291 const onKey = (event: globalThis.KeyboardEvent) => {
292 if ((event.metaKey || event.ctrlKey) && event.key.toLowerCase() === "k") {
293 event.preventDefault();
294 event.stopImmediatePropagation();
295 input.current?.focus();
296 }
297 };
298 window.addEventListener("keydown", onKey, { capture: true });
299 return () => window.removeEventListener("keydown", onKey, { capture: true });
300 }, [open]);
301
302 // The current conversation: what came after the latest "New conversation".
303 const shown = useMemo(() => {
304 let start = 0;
305 messages.forEach((m, index) => {
306 if (m.reset && fromG1t(m)) start = index + 1;
307 });
308 return messages.slice(start);
309 }, [messages]);
310 const earlier = shown.length < messages.length;
311 const busy = anyAnswering(messages);
312 const ready = setup != null && setup.problem == null;
313 const where = askPage(pathname);
314 const lastAnswer = [...shown].reverse().find((m) => !m.pending);
315 const context = useMemo<ResponseContext>(() => ({ slug, repo: where.repo ?? null }), [slug, where.repo?.namespace, where.repo?.name]);
316
317 const send = (text: string) => {
318 // `/clear` asks to clear the conversation; it is never sent to g1t.
319 if (isClearCommand(text)) {
320 setDraft("");
321 setClearing(true);
322 return;
323 }
324 if (!ready || busy || !text.trim()) return;
325 setDraft("");
326 void ask(text, pathname);
327 };
328 const submit = (event: FormEvent) => {
329 event.preventDefault();
330 send(draft);
331 };
332 const onKeyDown = (event: KeyboardEvent<HTMLTextAreaElement>) => {
333 if (event.key === "Enter" && !event.shiftKey && !event.nativeEvent.isComposing) {
334 event.preventDefault();
335 send(draft);
336 }
337 };
338 const fresh = () => {
339 void act("g1t_reset");
340 input.current?.focus();
341 };
342
343 return (
344 <>
345 {open && channelId && <LiveSocket slug={slug} channelId={channelId} onEvent={onEvent} onReconnect={() => void load()} />}
346 <SheetHeader className="gap-1 border-b border-line pb-3">
347 <SheetTitle className="flex items-center gap-2">
348 <MarkGlyph className="h-3.5" />
349 Ask g1t
350 </SheetTitle>
351 <SheetDescription className="sr-only">A conversation with g1t about your work in {slug}. It is your direct message with g1t in Chat.</SheetDescription>
352 <div className="flex min-h-7 flex-wrap items-center gap-2 text-xs text-muted">
353 {setup == null && !setupError ? (
354 <Skeleton className="h-4 w-40" />
355 ) : ready ? (
356 <span className="min-w-0 truncate">
357 Answers with {setup.connection_name} · <span className="font-mono">{modelLabel(setup)}</span>
358 </span>
359 ) : (
360 <span>Not set up yet</span>
361 )}
362 <span className="ml-auto flex items-center gap-0.5">
363 {setup?.owner && (
364 <Hint label="Choose the provider and model">
365 <Button asChild variant="ghost" size="icon-xs" aria-label="Choose the provider and model">
366 <Link to={`/${slug}/-/integrations/models#ask`}>
367 <Settings2 size={14} />
368 </Link>
369 </Button>
370 </Hint>
371 )}
372 {channelId && (
373 <Hint label="Open this conversation in Chat">
374 <Button asChild variant="ghost" size="icon-xs" aria-label="Open in Chat">
375 <Link to={`/${slug}/-/chat/dm/${channelId}`}>
376 <MessageSquare size={14} />
377 </Link>
378 </Button>
379 </Hint>
380 )}
381 <Hint label="New conversation: g1t reads only what comes next">
382 <Button variant="ghost" size="xs" onClick={fresh} disabled={shown.length === 0}>
383 <RotateCcw size={13} />
384 New conversation
385 </Button>
386 </Hint>
387 <DropdownMenu>
388 <Hint label="More">
389 <DropdownMenuTrigger asChild>
390 <Button variant="ghost" size="icon-xs" aria-label="More">
391 <Ellipsis size={14} />
392 </Button>
393 </DropdownMenuTrigger>
394 </Hint>
395 <DropdownMenuContent align="end">
396 <DropdownMenuItem variant="destructive" disabled={messages.length === 0} onSelect={() => setClearing(true)}>
397 <Trash2 />
398 Clear conversation…
399 </DropdownMenuItem>
400 </DropdownMenuContent>
401 </DropdownMenu>
402 </span>
403 </div>
404 </SheetHeader>
405
406 <Conversation aria-busy={busy}>
407 <ConversationContent>
408 {setupError && (
409 <Alert tone="danger">
410 <AlertDescription className="text-danger">{setupError}</AlertDescription>
411 </Alert>
412 )}
413 {problem && (
414 <Alert tone="danger">
415 <AlertDescription className="text-danger">{problem}</AlertDescription>
416 </Alert>
417 )}
418 {setup && setup.problem && <NotSetUp slug={slug} setup={setup} />}
419 {earlier && channelId && (
420 <p className="text-center text-xs text-faint">
421 Earlier conversations are in{" "}
422 <Link to={`/${slug}/-/chat/dm/${channelId}`} className="text-accent hover:underline">
423 your direct message with g1t
424 </Link>
425 .
426 </p>
427 )}
428 {!loaded && open ? (
429 <div className="space-y-3" aria-busy="true">
430 <Skeleton className="ml-auto h-9 w-2/3 rounded-2xl" />
431 <Skeleton className="h-4 w-11/12" />
432 <Skeleton className="h-4 w-3/4" />
433 </div>
434 ) : shown.length === 0 && ready ? (
435 <ConversationEmptyState className="pt-16">
436 <MarkGlyph className="h-7" />
437 <div className="space-y-1">
438 <h3 className="text-base font-semibold text-fg">Ask about your work</h3>
439 <p className="max-w-sm text-sm text-muted">
440 {where.repo
441 ? `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}` : ""}.`
442 : "g1t is told which page you're on, and reads the issue or pull request in front of you."}
443 </p>
444 </div>
445 <Suggestions className="mt-3 max-w-md justify-center">
446 {suggestions(where).map((text) => (
447 <Suggestion key={text} suggestion={text} onPick={send} />
448 ))}
449 </Suggestions>
450 </ConversationEmptyState>
451 ) : (
452 shown.map((m) =>
453 fromG1t(m) ? (
454 m.reset ? null : (
455 <Message key={m.id} from="assistant">
456 <G1tAnswer message={m} context={context} onRetry={!busy && lastAnswer?.id === m.id ? () => void act("g1t_retry") : undefined} />
457 </Message>
458 )
459 ) : (
460 <Message key={m.id} from="user">
461 <MessageContent className={m.pending && !m.failed ? "opacity-70" : undefined}>{m.body}</MessageContent>
462 <AskedFrom page={m.page} />
463 {m.failed && <span className="text-xs text-danger">Not sent. Ask again.</span>}
464 </Message>
465 ),
466 )
467 )}
468 </ConversationContent>
469 <ConversationScrollButton />
470 </Conversation>
471
472 <form onSubmit={submit} className="border-t border-line px-4 pt-3 pb-3">
473 <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">
474 <label htmlFor="ask-g1t" className="sr-only">
475 Ask g1t
476 </label>
477 <Textarea
478 id="ask-g1t"
479 ref={input}
480 value={draft}
481 onChange={(event) => setDraft(event.target.value)}
482 onKeyDown={onKeyDown}
483 rows={2}
484 maxLength={16_000}
485 disabled={!ready}
486 placeholder={ready ? "Ask about this page, a repository, or your work" : "Ask is not set up yet"}
487 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"
488 />
489 <div className="flex items-center gap-2 px-2 pb-2">
490 <span className="truncate pl-1 text-xs text-faint">{askWhere(where)}</span>
491 <span className="ml-auto" />
492 {busy ? (
493 <Hint label="Stop the answer (Esc)">
494 <Button type="button" variant="outline" size="icon-sm" onClick={() => void act("g1t_stop")} aria-label="Stop">
495 <Square size={12} className="fill-current" />
496 </Button>
497 </Hint>
498 ) : (
499 <Hint label="Send (Enter)">
500 <Button type="submit" variant="accent" size="icon-sm" disabled={!ready || !draft.trim()} aria-label="Send">
501 <ArrowUp size={15} />
502 </Button>
503 </Hint>
504 )}
505 </div>
506 </div>
507 <p className="mt-2 px-1 text-[0.6875rem] leading-relaxed text-faint">
508 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.{" "}
509 <span className="whitespace-nowrap max-sm:hidden">
510 <Kbd>Shift</Kbd> <Kbd>Enter</Kbd> for a new line.
511 </span>
512 </p>
513 </form>
514 <ClearG1tDialog
515 open={clearing}
516 onOpenChange={(next) => {
517 setClearing(next);
518 if (!next) requestAnimationFrame(() => input.current?.focus());
519 }}
520 onClear={clear}
521 />
522 </>
523 );
524}
525
526function NotSetUp({ slug, setup }: { slug: string; setup: Setup }) {
527 return (
528 <Alert tone="info">
529 <AlertTitle>Ask needs one of your workspace&apos;s AI providers</AlertTitle>
530 <AlertDescription>
531 <p>{setup.problem}</p>
532 <p className="mt-2">
533 Ask answers with an AI provider your workspace connects, on its own key: g1t hosts no model for it.{" "}
534 {setup.owner ? (
535 // Following it closes the panel, so the page it opens is not behind it.
536 <SheetClose asChild>
537 <Link to={`/${slug}/-/integrations/models#ask`} className="text-accent hover:underline">
538 Connect a provider and choose it for Ask
539 </Link>
540 </SheetClose>
541 ) : (
542 <>Ask an owner of {slug} to connect one and choose it for Ask.</>
543 )}
544 </p>
545 </AlertDescription>
546 </Alert>
547 );
548}