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.

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