| 1 | import { BellOff, ChevronDown, Compass, Hash, Lock, Pin, PinOff, Plus, Search } from "lucide-react"; |
| 2 | import { ContextMenu } from "radix-ui"; |
| 3 | import { type ReactNode, useEffect, useState } from "react"; |
| 4 | import { Link, NavLink, useFetcher, useLocation, useNavigate } from "react-router"; |
| 5 | |
| 6 | import type { ChatSidebarEntry, WorkspaceAgent } from "@g1t/contracts"; |
| 7 | |
| 8 | import { conversationCache } from "./conversation-cache"; |
| 9 | import { CreateChannelButton, NewMessageButton, useChatData, useChatSend, useChatSidebar } from "./actions"; |
| 10 | import { MemberAvatar, StatusDot, statusLabel } from "./marks"; |
| 11 | import { AgentAvatar } from "../agent-avatar"; |
| 12 | import { isOrchestrator } from "../orchestrator"; |
| 13 | import { Hint } from "../ui/hint"; |
| 14 | import { Skeleton } from "../ui/skeleton"; |
| 15 | import { type ChatFilter, agentDmOf, channelPath, filterEntries, sections } from "../../lib/chat"; |
| 16 | import { feedConnected } from "../../lib/notify-client"; |
| 17 | import { FALLBACK_REFRESH_MS } from "../../lib/notify-store"; |
| 18 | |
| 19 | /** How often the sidebar asks again while the tab is shown and the feed socket is down. */ |
| 20 | const REFRESH_MS = FALLBACK_REFRESH_MS; |
| 21 | |
| 22 | const ROW = |
| 23 | "group/row flex h-8 items-center gap-2 rounded-md pr-1.5 pl-2 text-[0.8125rem] transition-colors max-md:h-11 max-md:text-[0.9375rem] max-md:active:bg-raised"; |
| 24 | |
| 25 | /** Unread on a row: lavender for a mention, quiet for the rest. */ |
| 26 | function Count({ entry }: { entry: ChatSidebarEntry | undefined }) { |
| 27 | if (!entry || entry.muted) return null; |
| 28 | const count = entry.mentions > 0 ? entry.mentions : entry.unread; |
| 29 | if (count <= 0) return null; |
| 30 | return ( |
| 31 | <span |
| 32 | className={`min-w-5 shrink-0 rounded-full group-hover/row:invisible px-1.5 text-center text-[0.6875rem] leading-[1.125rem] font-semibold tabular-nums ${ |
| 33 | entry.mentions > 0 ? "bg-accent text-bg" : "bg-line-strong text-fg" |
| 34 | }`} |
| 35 | > |
| 36 | {count} |
| 37 | </span> |
| 38 | ); |
| 39 | } |
| 40 | |
| 41 | /** |
| 42 | * Chat mode's sidebar: what you pinned, the channels, the workspace's |
| 43 | * agents (g1t first, each opening your conversation with it), then direct |
| 44 | * messages with people. All, Unread and Mentions filter every section. It |
| 45 | * refreshes itself while the tab is shown, so unread counts move without |
| 46 | * a reload. |
| 47 | */ |
| 48 | export function ChatSidebar({ slug, heading = true }: { slug: string; heading?: boolean }) { |
| 49 | const data = useChatData(); |
| 50 | const { sidebar, refresh } = useChatSidebar(); |
| 51 | const send = useChatSend(slug); |
| 52 | const [filter, setFilter] = useState<ChatFilter>("all"); |
| 53 | const [query, setQuery] = useState(""); |
| 54 | const [opening, setOpening] = useState<string | null>(null); |
| 55 | const navigate = useNavigate(); |
| 56 | const { pathname } = useLocation(); |
| 57 | |
| 58 | useEffect(() => { |
| 59 | if (!data) return; |
| 60 | // Notify: counts arrive live over the feed socket; this asks again only while it is down. |
| 61 | const tick = () => { |
| 62 | if (document.visibilityState === "visible" && !feedConnected()) refresh(); |
| 63 | }; |
| 64 | const timer = setInterval(tick, REFRESH_MS); |
| 65 | document.addEventListener("visibilitychange", tick); |
| 66 | return () => { |
| 67 | clearInterval(timer); |
| 68 | document.removeEventListener("visibilitychange", tick); |
| 69 | }; |
| 70 | }, [data, refresh]); |
| 71 | |
| 72 | // Pins show at once and go back if the service refuses. |
| 73 | const [pins, setPins] = useState<Map<string, boolean>>(new Map()); |
| 74 | useEffect(() => setPins(new Map()), [sidebar]); |
| 75 | const entries = (sidebar?.entries ?? []).map((e) => (pins.has(e.channel.id) ? { ...e, starred: pins.get(e.channel.id)! } : e)); |
| 76 | const shown = filterEntries(entries, filter, query); |
| 77 | const { pinned, channels, dms } = sections(shown); |
| 78 | const { agentDms } = sections(entries); |
| 79 | const loading = !data; |
| 80 | const owner = data?.role === "owner"; |
| 81 | |
| 82 | // Every agent, g1t first; filtered as the conversations are. |
| 83 | const q = query.trim().toLowerCase().replace(/^@/, ""); |
| 84 | const agents = [...(data?.agents ?? [])] |
| 85 | .sort((a, b) => Number(isOrchestrator(b)) - Number(isOrchestrator(a)) || a.display_name.localeCompare(b.display_name)) |
| 86 | .filter((agent) => { |
| 87 | const dm = agentDms.get(agent.id); |
| 88 | if (filter === "unread" && !(dm && !dm.muted && (dm.unread > 0 || dm.mentions > 0))) return false; |
| 89 | if (filter === "mentions" && !(dm && dm.mentions > 0)) return false; |
| 90 | return !q || agent.handle.includes(q) || agent.display_name.toLowerCase().includes(q) || agent.role.toLowerCase().includes(q); |
| 91 | }); |
| 92 | |
| 93 | /** The direct message with an agent: opened, or made on first use. */ |
| 94 | const openAgent = async (agent: WorkspaceAgent, pin = false) => { |
| 95 | const had = agentDms.get(agent.id); |
| 96 | if (had && !pin) return navigate(channelPath(slug, had.channel)); |
| 97 | setOpening(agent.id); |
| 98 | const opened = had ? { ok: true as const, value: { channel: had.channel, to: channelPath(slug, had.channel) } } : await send<{ channel: ChatSidebarEntry["channel"]; to: string }>({ intent: "dm", members: [`agent:${agent.id}`] }); |
| 99 | if (opened.ok && pin) await send({ intent: "preferences", channel_id: opened.value.channel.id, starred: !had?.starred }); |
| 100 | setOpening(null); |
| 101 | if (opened.ok && !pin) navigate(opened.value.to); |
| 102 | if (pin) refresh(); |
| 103 | }; |
| 104 | const togglePin = async (entry: ChatSidebarEntry) => { |
| 105 | const next = !entry.starred; |
| 106 | setPins((now) => new Map(now).set(entry.channel.id, next)); |
| 107 | const done = await send({ intent: "preferences", channel_id: entry.channel.id, starred: next }); |
| 108 | if (!done.ok) |
| 109 | setPins((now) => { |
| 110 | const back = new Map(now); |
| 111 | back.delete(entry.channel.id); |
| 112 | return back; |
| 113 | }); |
| 114 | }; |
| 115 | |
| 116 | const conversation = (entry: ChatSidebarEntry) => ( |
| 117 | <ConversationRow key={entry.channel.id} entry={entry} slug={slug} pathname={pathname} agents={data?.agents ?? []} onPin={() => void togglePin(entry)} /> |
| 118 | ); |
| 119 | |
| 120 | return ( |
| 121 | <div className="flex h-full flex-col"> |
| 122 | {heading && ( |
| 123 | <div className="flex h-14 shrink-0 items-center justify-between border-b border-line pr-2.5 pl-4"> |
| 124 | <h2 className="text-[0.9375rem] font-semibold">Chat</h2> |
| 125 | <NewMessageButton slug={slug} /> |
| 126 | </div> |
| 127 | )} |
| 128 | <div className="space-y-2.5 px-2.5 pt-3"> |
| 129 | <label className="flex h-8 items-center gap-2 rounded-md bg-surface px-2.5 text-[0.8125rem] ring-1 ring-line transition-shadow focus-within:ring-accent-dim/70"> |
| 130 | <Search size={14} className="shrink-0 text-faint" /> |
| 131 | <input |
| 132 | value={query} |
| 133 | onChange={(event) => setQuery(event.target.value)} |
| 134 | onKeyDown={(event) => { |
| 135 | if (event.key === "Enter") { |
| 136 | const first = [...pinned, ...channels, ...dms][0]; |
| 137 | if (first) { |
| 138 | navigate(channelPath(slug, first.channel)); |
| 139 | setQuery(""); |
| 140 | } else if (agents[0]) void openAgent(agents[0]); |
| 141 | } else if (event.key === "Escape") setQuery(""); |
| 142 | }} |
| 143 | placeholder="Jump to channel or person" |
| 144 | aria-label="Jump to channel or person" |
| 145 | autoComplete="off" |
| 146 | data-1p-ignore |
| 147 | className="min-w-0 grow bg-transparent text-fg outline-none placeholder:text-faint" |
| 148 | /> |
| 149 | </label> |
| 150 | <div role="radiogroup" aria-label="Show" className="grid grid-cols-3 rounded-md bg-surface p-0.5 ring-1 ring-line"> |
| 151 | {(["all", "unread", "mentions"] as const).map((key) => ( |
| 152 | <button |
| 153 | key={key} |
| 154 | type="button" |
| 155 | role="radio" |
| 156 | aria-checked={filter === key} |
| 157 | onClick={() => setFilter(key)} |
| 158 | className={`h-6 rounded-[5px] text-xs font-medium capitalize transition-colors ${ |
| 159 | filter === key ? "bg-raised text-fg shadow-sm ring-1 ring-line-strong" : "text-muted hover:text-fg" |
| 160 | }`} |
| 161 | > |
| 162 | {key} |
| 163 | </button> |
| 164 | ))} |
| 165 | </div> |
| 166 | </div> |
| 167 | {/* A phone's list (no heading): room at the end so the compose button never covers the last row. */} |
| 168 | <nav |
| 169 | aria-label="Conversations" |
| 170 | className={`min-h-0 grow overflow-y-auto px-2.5 pt-3 [scrollbar-width:thin] ${heading ? "pb-4" : "pb-[calc(5.5rem+env(safe-area-inset-bottom))]"}`} |
| 171 | > |
| 172 | {loading ? ( |
| 173 | <SidebarSkeleton /> |
| 174 | ) : !sidebar ? ( |
| 175 | <p className="px-2 py-3 text-xs leading-relaxed text-faint">Chat didn't answer. Your conversations will show here once it does.</p> |
| 176 | ) : ( |
| 177 | <> |
| 178 | {pinned.length > 0 && <Section title="Pinned">{pinned.map(conversation)}</Section>} |
| 179 | <Section title="Channels" action={<CreateChannelButton slug={slug} />}> |
| 180 | {channels.map(conversation)} |
| 181 | {channels.length === 0 && filter === "all" && !query && <Empty>No channels yet.</Empty>} |
| 182 | </Section> |
| 183 | <Section |
| 184 | title="Agents" |
| 185 | action={ |
| 186 | owner ? ( |
| 187 | <Hint label="New agent"> |
| 188 | <Link |
| 189 | to={`/${slug}/-/agents/new`} |
| 190 | aria-label="New agent" |
| 191 | className="flex size-7 items-center justify-center rounded-md text-faint transition-colors hover:bg-raised hover:text-fg" |
| 192 | > |
| 193 | <Plus size={14} /> |
| 194 | </Link> |
| 195 | </Hint> |
| 196 | ) : null |
| 197 | } |
| 198 | > |
| 199 | {agents.map((agent) => ( |
| 200 | <AgentRow |
| 201 | key={agent.id} |
| 202 | agent={agent} |
| 203 | dm={agentDms.get(agent.id)} |
| 204 | current={(() => { |
| 205 | const dm = agentDms.get(agent.id); |
| 206 | return dm != null && pathname === channelPath(slug, dm.channel); |
| 207 | })()} |
| 208 | busy={opening === agent.id} |
| 209 | onOpen={() => void openAgent(agent)} |
| 210 | onPin={() => void openAgent(agent, true)} |
| 211 | /> |
| 212 | ))} |
| 213 | {agents.length === 0 && filter === "all" && !query && <Empty>No agents yet.</Empty>} |
| 214 | </Section> |
| 215 | <Section title="Direct messages" action={<NewMessageButton slug={slug} />}> |
| 216 | {dms.map(conversation)} |
| 217 | {dms.length === 0 && filter === "all" && !query && <Empty>Message a teammate.</Empty>} |
| 218 | </Section> |
| 219 | {shown.length === 0 && agents.length === 0 && (filter !== "all" || query) && ( |
| 220 | <p className="px-2 py-2 text-xs text-faint">{query ? "Nothing matches." : filter === "unread" ? "You're all caught up." : "No mentions."}</p> |
| 221 | )} |
| 222 | <NavLink |
| 223 | to={`/${slug}/-/chat/browse`} |
| 224 | className={({ isActive }) => |
| 225 | `mt-3 flex h-8 items-center gap-2.5 rounded-md px-2 text-[0.8125rem] transition-colors ${isActive ? "bg-raised text-fg" : "text-muted hover:bg-raised/60 hover:text-fg"}` |
| 226 | } |
| 227 | > |
| 228 | <Compass size={15} className="text-faint" /> |
| 229 | Browse all channels |
| 230 | <span className="ml-auto text-xs text-faint tabular-nums">{(sidebar.browsable ?? 0) + entries.filter((e) => e.channel.kind === "channel").length}</span> |
| 231 | </NavLink> |
| 232 | </> |
| 233 | )} |
| 234 | </nav> |
| 235 | </div> |
| 236 | ); |
| 237 | } |
| 238 | |
| 239 | function Section({ title, action, children }: { title: string; action?: ReactNode; children: ReactNode }) { |
| 240 | const [open, setOpen] = useState(true); |
| 241 | return ( |
| 242 | <section className="mb-3"> |
| 243 | <div className="group/head flex h-7 items-center justify-between pr-0.5 pl-1"> |
| 244 | <button |
| 245 | type="button" |
| 246 | onClick={() => setOpen(!open)} |
| 247 | aria-expanded={open} |
| 248 | className="flex items-center gap-1 rounded px-1 text-xs font-medium text-faint transition-colors hover:text-muted" |
| 249 | > |
| 250 | <ChevronDown size={12} className={`transition-transform ${open ? "" : "-rotate-90"}`} /> |
| 251 | {title} |
| 252 | </button> |
| 253 | <span className="opacity-70 transition-opacity group-hover/head:opacity-100">{action}</span> |
| 254 | </div> |
| 255 | {open && <ul className="space-y-px">{children}</ul>} |
| 256 | </section> |
| 257 | ); |
| 258 | } |
| 259 | |
| 260 | function Empty({ children }: { children: ReactNode }) { |
| 261 | return <li className="px-2 py-1 text-xs text-faint">{children}</li>; |
| 262 | } |
| 263 | |
| 264 | /** Pin or unpin, on hover or focus; the same as the context menu's first item. */ |
| 265 | function PinButton({ pinned, onPin, label }: { pinned: boolean; onPin: () => void; label: string }) { |
| 266 | return ( |
| 267 | <Hint label={pinned ? "Unpin" : "Pin to the top"}> |
| 268 | <button |
| 269 | type="button" |
| 270 | aria-label={`${pinned ? "Unpin" : "Pin"} ${label}`} |
| 271 | onClick={(event) => { |
| 272 | event.preventDefault(); |
| 273 | event.stopPropagation(); |
| 274 | onPin(); |
| 275 | }} |
| 276 | className="absolute top-1/2 right-1 hidden size-6 -translate-y-1/2 items-center justify-center rounded bg-raised text-faint group-hover/row:flex group-focus-within/row:flex hover:bg-line hover:text-fg [@media(hover:none)]:hidden" |
| 277 | > |
| 278 | {pinned ? <PinOff size={13} /> : <Pin size={13} />} |
| 279 | </button> |
| 280 | </Hint> |
| 281 | ); |
| 282 | } |
| 283 | |
| 284 | /** Right-click on a row: pin it, or open it. */ |
| 285 | function RowMenu({ pinned, onPin, to, children }: { pinned: boolean; onPin: () => void; to?: string; children: ReactNode }) { |
| 286 | const navigate = useNavigate(); |
| 287 | const item = |
| 288 | "flex cursor-default items-center gap-2 rounded-md px-2 py-1.5 text-[0.8125rem] text-fg/90 outline-none select-none data-highlighted:bg-line data-highlighted:text-fg [&_svg]:size-4 [&_svg]:text-muted"; |
| 289 | return ( |
| 290 | <ContextMenu.Root> |
| 291 | <ContextMenu.Trigger asChild>{children}</ContextMenu.Trigger> |
| 292 | <ContextMenu.Portal> |
| 293 | <ContextMenu.Content className="z-50 min-w-44 rounded-lg border border-line-strong bg-raised p-1 shadow-xl shadow-black/40 data-[state=open]:animate-pop-in"> |
| 294 | <ContextMenu.Item className={item} onSelect={onPin}> |
| 295 | {pinned ? <PinOff /> : <Pin />} |
| 296 | {pinned ? "Unpin" : "Pin to the top"} |
| 297 | </ContextMenu.Item> |
| 298 | {to && ( |
| 299 | <ContextMenu.Item className={item} onSelect={() => navigate(to)}> |
| 300 | <Hash /> |
| 301 | Open |
| 302 | </ContextMenu.Item> |
| 303 | )} |
| 304 | </ContextMenu.Content> |
| 305 | </ContextMenu.Portal> |
| 306 | </ContextMenu.Root> |
| 307 | ); |
| 308 | } |
| 309 | |
| 310 | /** |
| 311 | * Reads a conversation ahead, on hover, focus or the start of a touch, so |
| 312 | * opening it draws at once (its route's `clientLoader` keeps it). |
| 313 | */ |
| 314 | function usePrefetchConversation(to: string) { |
| 315 | const fetcher = useFetcher(); |
| 316 | const load = () => { |
| 317 | if (fetcher.state === "idle" && fetcher.data === undefined && !conversationCache.has(to)) fetcher.load(to); |
| 318 | }; |
| 319 | return { onPointerEnter: load, onFocus: load, onTouchStart: load }; |
| 320 | } |
| 321 | |
| 322 | /** One channel or direct message: its mark, its name, its unread count, and a pin. */ |
| 323 | function ConversationRow({ |
| 324 | entry, |
| 325 | slug, |
| 326 | pathname, |
| 327 | agents, |
| 328 | onPin, |
| 329 | }: { |
| 330 | entry: ChatSidebarEntry; |
| 331 | slug: string; |
| 332 | pathname: string; |
| 333 | agents: WorkspaceAgent[]; |
| 334 | onPin: () => void; |
| 335 | }) { |
| 336 | const to = channelPath(slug, entry.channel); |
| 337 | const current = pathname === to || pathname.startsWith(`${to}/`); |
| 338 | const prefetch = usePrefetchConversation(to); |
| 339 | const unread = !entry.muted && (entry.unread > 0 || entry.mentions > 0); |
| 340 | const agentId = agentDmOf(entry); |
| 341 | const agent = agentId ? agents.find((a) => a.id === agentId) : null; |
| 342 | const other = entry.others[0]; |
| 343 | const icon = agent ? ( |
| 344 | <AgentAvatar agent={{ ...agent, builtin: isOrchestrator(agent) }} size={18} /> |
| 345 | ) : entry.channel.kind === "dm" && other ? ( |
| 346 | <MemberAvatar member={other} size={18} /> |
| 347 | ) : entry.channel.private ? ( |
| 348 | <Lock size={14} /> |
| 349 | ) : ( |
| 350 | <Hash size={15} /> |
| 351 | ); |
| 352 | return ( |
| 353 | <li className="group/row relative"> |
| 354 | <RowMenu pinned={entry.starred} onPin={onPin} to={to}> |
| 355 | <NavLink |
| 356 | to={to} |
| 357 | {...prefetch} |
| 358 | aria-current={current ? "page" : undefined} |
| 359 | className={`${ROW} ${ |
| 360 | current ? "bg-raised text-fg" : unread ? "text-fg hover:bg-raised/60" : entry.muted ? "text-faint hover:bg-raised/60 hover:text-muted" : "text-muted hover:bg-raised/60 hover:text-fg" |
| 361 | }`} |
| 362 | > |
| 363 | <span className={`flex w-[18px] shrink-0 justify-center ${current || unread ? "text-muted" : "text-faint"}`}>{icon}</span> |
| 364 | <span className={`min-w-0 grow truncate ${unread ? "font-semibold" : current ? "font-medium" : ""}`}>{entry.title}</span> |
| 365 | {entry.muted && <BellOff size={12} className="shrink-0 text-faint" aria-label="Muted" />} |
| 366 | <Count entry={entry} /> |
| 367 | </NavLink> |
| 368 | </RowMenu> |
| 369 | <PinButton pinned={entry.starred} onPin={onPin} label={entry.title} /> |
| 370 | </li> |
| 371 | ); |
| 372 | } |
| 373 | |
| 374 | /** One agent: its face, its name and status, and unread from your conversation with it. */ |
| 375 | function AgentRow({ |
| 376 | agent, |
| 377 | dm, |
| 378 | current, |
| 379 | busy, |
| 380 | onOpen, |
| 381 | onPin, |
| 382 | }: { |
| 383 | agent: WorkspaceAgent; |
| 384 | dm: ChatSidebarEntry | undefined; |
| 385 | current: boolean; |
| 386 | busy: boolean; |
| 387 | onOpen: () => void; |
| 388 | onPin: () => void; |
| 389 | }) { |
| 390 | const g1t = isOrchestrator(agent); |
| 391 | const unread = dm != null && !dm.muted && (dm.unread > 0 || dm.mentions > 0); |
| 392 | return ( |
| 393 | <li className="group/row relative"> |
| 394 | <RowMenu pinned={dm?.starred ?? false} onPin={onPin}> |
| 395 | <button |
| 396 | type="button" |
| 397 | onClick={onOpen} |
| 398 | aria-current={current ? "page" : undefined} |
| 399 | aria-busy={busy || undefined} |
| 400 | className={`${ROW} w-full text-left ${current ? "bg-raised text-fg" : unread ? "text-fg hover:bg-raised/60" : "text-muted hover:bg-raised/60 hover:text-fg"} ${busy ? "opacity-60" : ""}`} |
| 401 | > |
| 402 | <span className="relative flex w-[18px] shrink-0 justify-center"> |
| 403 | <AgentAvatar agent={{ ...agent, builtin: g1t }} size={18} /> |
| 404 | </span> |
| 405 | <span className={`min-w-0 grow truncate ${unread ? "font-semibold" : current ? "font-medium" : ""}`}> |
| 406 | {agent.display_name} |
| 407 | <span className="ml-1.5 text-[0.6875rem] font-normal text-faint">{g1t ? "orchestrator" : agent.title}</span> |
| 408 | </span> |
| 409 | {!g1t && ( |
| 410 | <Hint label={statusLabel(agent.status)}> |
| 411 | <span className="flex size-4 shrink-0 items-center justify-center"> |
| 412 | <StatusDot status={agent.status} /> |
| 413 | </span> |
| 414 | </Hint> |
| 415 | )} |
| 416 | <Count entry={dm} /> |
| 417 | </button> |
| 418 | </RowMenu> |
| 419 | <PinButton pinned={dm?.starred ?? false} onPin={onPin} label={agent.display_name} /> |
| 420 | </li> |
| 421 | ); |
| 422 | } |
| 423 | |
| 424 | function SidebarSkeleton() { |
| 425 | return ( |
| 426 | <div className="space-y-2 px-2 pt-1" aria-busy="true"> |
| 427 | <Skeleton className="h-3 w-16" /> |
| 428 | {[70, 52, 84, 60].map((w) => ( |
| 429 | <div key={w} className="flex h-6 items-center gap-2"> |
| 430 | <Skeleton className="size-4 rounded" /> |
| 431 | <Skeleton className="h-3" style={{ width: `${w}%` }} /> |
| 432 | </div> |
| 433 | ))} |
| 434 | <Skeleton className="mt-4 h-3 w-24" /> |
| 435 | {[64, 48, 72].map((w) => ( |
| 436 | <div key={w} className="flex h-6 items-center gap-2"> |
| 437 | <Skeleton className="size-4 rounded-full" /> |
| 438 | <Skeleton className="h-3" style={{ width: `${w}%` }} /> |
| 439 | </div> |
| 440 | ))} |
| 441 | </div> |
| 442 | ); |
| 443 | } |