mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-20 09:50:48 +01:00
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - Agent Chat lets people discuss work and review the plans and documents it produces. > - A document link in Chat promises to open the sidebar. It currently moves the reader to Tasks. > - Readers need to see the document and the conversation together, even when the window is narrow. > - This pull request opens the document in Chat, frees space for reading, and gives readers a link to the source task. > - Readers can review the saved revision in context and open the task when they need its details. ## Linked Issues or Issue Description Refs #11226 for the document sidebar that this change builds on. **What happened?** Opening a saved plan from Agent Chat changed the route to Tasks. The document could show the same title twice. At narrow desktop widths, the chat list left too little space for the conversation beside the document. A task opened by UUID could still show a Chat header. **Expected behavior** The sidebar shows the saved revision beside the current conversation. It shows a matching title once. The chat list collapses when space is tight. The source link opens the standard task header with status, name, and ID. **Steps to reproduce** 1. Open an Agent Chat with a saved plan and select its sidebar link. 2. Use a narrow desktop window and inspect the conversation and plan. 3. Open the task that owns the plan and inspect the breadcrumb. **Paperclip version or commit** Reproduced on source commit `8285a81280`. **Deployment mode** Local trusted development instance with synthetic data. ## What Changed - Open sidebar document links on the current Chat route. Keep the requested revision and document owner, including links inside another task’s preview. Provide an **Open source task** link. - Show one title when the document title matches the opening Markdown heading. - Collapse the desktop chat list when an artifact tab would leave less than 420 px for the conversation. Keep **Browse chats** in the header with access to saved chat history. Restore the list when there is room. - Use the task breadcrumb on task URLs, with the short UUID for a conversation-backed task without a number. ## Verification - Ran 618 focused Vitest tests across 18 UI files on the published revision `2ff6c9e931`. All passed. - Ran `pnpm --filter @paperclipai/ui typecheck`. It passed. - Checked the synthetic demo in Chromium. Opened the plan in Chat, checked the title, resized the window, and followed **Open source task** to check its breadcrumb. Also verified a link inside a preview owned by another task. - Reproduced the chat navigation failure from the CI trace. The same Playwright test passed locally after limiting collapse to artifact tabs. - GitHub CI passed on `2ff6c9e931`, including build, typecheck, and all browser shards. The remaining jobs passed on a retry after runner shutdowns and a server handover test failure. The handover suite also passed locally (19 tests). [GitHub CI](https://github.com/paperclipai/paperclip/actions/runs/44423540581/attempts/2) - `pnpm verify` selected broader CI coverage because `doc/PRODUCT.md` changed. The full local suite was not run. ## Risks The chat list changes visibility when an artifact tab is active and the available width crosses the threshold. The list stays mounted to keep its search text. Document tabs use the existing read API and check the owning company. This change adds no database migration or API contract change. ## Model Used OpenAI Codex (GPT-6), with repository tools, shell execution, and Chromium. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either linked existing issues or described the issue in-PR following the relevant issue template - [x] I have used public GitHub references for linked work - [x] My branch name describes the change and contains no internal Paperclip ticket ID - [x] I have run focused tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge --------- Co-authored-by: Scott Tong <1504818+scotttong@users.noreply.github.com> Co-authored-by: Paperclip <noreply@paperclip.ing>
145 lines
10 KiB
TypeScript
145 lines
10 KiB
TypeScript
import { useId, useMemo, useRef, useState, type ReactNode } from "react";
|
||
import { PanelLeftOpen, Plus, Search, Users, X } from "lucide-react";
|
||
import { SortablePinnedList, SortablePinnedRow } from "./PinnedNavigationList";
|
||
import { Badge } from "./ui/badge";
|
||
import type { Agent } from "@paperclipai/shared";
|
||
import { AgentChatPicker } from "@/components/AgentChatPicker";
|
||
import { AgentAvatar } from "@/components/AgentAvatar";
|
||
import { Button } from "@/components/ui/button";
|
||
import { Input } from "@/components/ui/input";
|
||
import { Link, useNavigate } from "@/lib/router";
|
||
import { agentRouteRef, cn } from "@/lib/utils";
|
||
|
||
export interface AgentConversationSidebarProps {
|
||
agents: Agent[];
|
||
compact?: boolean;
|
||
/** Agents with a saved conversation; defaults to every listed agent. */
|
||
existingChatAgentIds?: readonly string[];
|
||
availableAgents?: Agent[];
|
||
activeId?: string;
|
||
previews?: Record<string, string>;
|
||
unreadAgentIds?: readonly string[];
|
||
unreadMessageCounts?: ReadonlyMap<string, number>;
|
||
loading?: boolean;
|
||
error?: Error | null;
|
||
onRetry?: () => void;
|
||
initialSearch?: string;
|
||
onSelect?: (agent: Agent, signal?: AbortSignal) => void | Promise<void>;
|
||
onBrowse?: () => void;
|
||
onAddChat?: (agent: Agent, signal?: AbortSignal) => void | Promise<void>;
|
||
historyLoading?: boolean;
|
||
historyError?: Error | null;
|
||
onRetryHistory?: () => void;
|
||
onCreateAgent?: () => void;
|
||
renderAgentAction?: (agent: Agent) => ReactNode;
|
||
pinnedAgentIds?: readonly string[];
|
||
onReorderPins?: (ids: string[]) => void;
|
||
}
|
||
|
||
const NO_PINNED_AGENTS: readonly string[] = [];
|
||
const contactRowClassName = "agent-pin-row agent-contact-pin-row group/agent-pin relative rounded-md";
|
||
|
||
/** Searchable navigation for one conversation per agent. */
|
||
export function AgentConversationSidebar({ agents, compact = false, existingChatAgentIds, availableAgents = agents, activeId, previews = {}, unreadAgentIds = [], unreadMessageCounts, loading = false, error, onRetry, initialSearch = "", onSelect, onBrowse, onAddChat, historyLoading, historyError, onRetryHistory, onCreateAgent, renderAgentAction, pinnedAgentIds = NO_PINNED_AGENTS, onReorderPins }: AgentConversationSidebarProps) {
|
||
const navigate = useNavigate();
|
||
const [pickerOpen, setPickerOpen] = useState(false);
|
||
const [search, setSearch] = useState(initialSearch);
|
||
const searchRef = useRef<HTMLInputElement>(null);
|
||
const headingId = useId();
|
||
const unreadIds = useMemo(() => new Set(unreadAgentIds), [unreadAgentIds]);
|
||
const pinnedIds = useMemo(() => new Set(pinnedAgentIds), [pinnedAgentIds]);
|
||
const picker = <AgentChatPicker agents={compact ? agents : availableAgents} open={pickerOpen} onOpenChange={setPickerOpen}
|
||
trigger={compact ? <Button variant="ghost" size="icon-sm" className="text-muted-foreground" aria-label="Browse chats" title="Browse chats">
|
||
<PanelLeftOpen className="size-4" aria-hidden />
|
||
</Button> : undefined}
|
||
unreadMessageCounts={unreadMessageCounts}
|
||
existingChatAgentIds={existingChatAgentIds ?? agents.map(agent => agent.id)} loading={loading} error={error} onRetry={onRetry}
|
||
renderAgentIcon={agent => <AgentAvatar agent={agent} size={32} />}
|
||
onSelect={async (agent, signal) => {
|
||
if (onAddChat) await onAddChat(agent, signal);
|
||
else if (onSelect) await onSelect(agent, signal);
|
||
else navigate(`/chats/${encodeURIComponent(agentRouteRef(agent))}`);
|
||
if (!signal?.aborted) setSearch("");
|
||
}} />;
|
||
if (compact) return picker;
|
||
const query = search.trim().toLocaleLowerCase();
|
||
const matching = agents.filter(agent => `${agent.name} ${agent.title ?? ""} ${agent.role}`.toLocaleLowerCase().includes(query));
|
||
const byId = new Map(matching.map(agent => [agent.id, agent]));
|
||
const pins = pinnedAgentIds.flatMap(id => {
|
||
const agent = byId.get(id);
|
||
return agent ? [agent] : [];
|
||
});
|
||
const visible = [...pins, ...matching.filter(agent => !pinnedIds.has(agent.id))];
|
||
const visiblePinnedIds = pins.map(agent => agent.id);
|
||
function focusSearch() {
|
||
setSearch("");
|
||
searchRef.current?.focus();
|
||
}
|
||
return <aside aria-labelledby={headingId} className="flex h-full min-h-0 flex-col border-r border-border bg-background">
|
||
<h2 id={headingId} className="sr-only">Chat contacts</h2>
|
||
<div className="flex shrink-0 items-center gap-2 px-3 pb-3 pt-5">
|
||
<div className="relative min-w-0 flex-1">
|
||
<Search aria-hidden="true" className="pointer-events-none absolute left-3 top-1/2 size-3.5 -translate-y-1/2 text-muted-foreground" />
|
||
<Input ref={searchRef} aria-label="Search chats" placeholder="Search chats" value={search} onChange={event => setSearch(event.target.value)}
|
||
onKeyDown={event => { if (event.key === "Escape") { event.stopPropagation(); setSearch(""); } }}
|
||
className="h-9 pl-8 pr-8 text-xs md:text-xs" />
|
||
{search && <Button variant="ghost" size="icon-xs" aria-label="Clear search" className="absolute right-1 top-1/2 -translate-y-1/2" onClick={focusSearch}><X className="size-3" /></Button>}
|
||
</div>
|
||
</div>
|
||
<div className="flex min-h-0 flex-1 flex-col gap-2 overflow-y-auto px-3 pb-3 scrollbar-auto-hide">
|
||
<span role="status" className="sr-only">{loading ? "Loading agents" : `${visible.length} ${visible.length === 1 ? "agent" : "agents"}`}</span>
|
||
{historyLoading && <p role="status" className="px-2 text-xs text-muted-foreground">Loading chat history…</p>}
|
||
{historyError && <div role="alert" className="flex flex-col items-start gap-2 px-2 py-3">
|
||
<p className="text-xs text-muted-foreground">Some chat history couldn’t load.</p>
|
||
<Button variant="outline" size="sm" onClick={onRetryHistory}>Retry chat history</Button>
|
||
</div>}
|
||
{error ? <div role="alert" className="flex flex-col items-start gap-2 px-2 py-6"><p className="text-sm">Couldn’t load your chats.</p><Button variant="outline" size="sm" onClick={onRetry}>Try again</Button></div> : loading ? <div aria-hidden="true" className="flex flex-col gap-1">
|
||
{[0, 1, 2, 3].map(index => <div key={index} className="flex items-center gap-3 rounded-md px-2 py-3 motion-safe:animate-pulse">
|
||
<div className="size-8 shrink-0 rounded-lg bg-muted" />
|
||
<div className="flex flex-1 flex-col gap-2"><div className="h-3 w-2/3 rounded-sm bg-muted" /><div className="h-2 w-full rounded-sm bg-muted" /></div>
|
||
</div>)}
|
||
</div> : visible.length ? <nav aria-label="Agent conversations" className="flex flex-col gap-1">
|
||
<SortablePinnedList keys={visiblePinnedIds} onReorder={onReorderPins}>
|
||
{visible.map(agent => {
|
||
const unreadCount = unreadMessageCounts?.get(agent.id) ?? 0;
|
||
const hasUnread = unreadCount > 0 || unreadIds.has(agent.id);
|
||
const canReorder = pinnedIds.has(agent.id) && !!onReorderPins;
|
||
const content = <><Link to={`/chats/${encodeURIComponent(agent.status === "terminated" ? agent.id : agentRouteRef(agent))}`}
|
||
aria-current={activeId === agent.id ? "page" : undefined}
|
||
title={`${agent.name}${agent.title ? ` · ${agent.title}` : ""}`}
|
||
onClick={event => { if (onSelect) { event.preventDefault(); onSelect(agent); } }}
|
||
className={cn("agent-contact-row flex min-w-0 items-center gap-3 rounded-md px-2.5 py-3 text-left transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring", renderAgentAction && hasUnread && "pr-12", canReorder && "pr-20", activeId === agent.id ? "bg-accent text-accent-foreground" : "group-hover/agent-pin:bg-accent/60 group-focus-within/agent-pin:bg-accent/60")}>
|
||
<AgentAvatar agent={agent} size={40} />
|
||
<span className="agent-pin-text flex min-w-0 flex-1 flex-col gap-0.5">
|
||
<span className="truncate text-sm font-medium">{agent.name}</span>
|
||
<span className="truncate text-xs text-muted-foreground">{agent.status === "terminated" ? "Terminated" : agent.title ?? agent.role}</span>
|
||
</span>
|
||
{unreadCount > 0 ? <Badge variant="ghost" aria-label={`${unreadCount} unread ${unreadCount === 1 ? "message" : "messages"} from ${agent.name}`} className="shrink-0 bg-primary font-mono tabular-nums text-primary-foreground">{unreadCount}</Badge>
|
||
: unreadIds.has(agent.id) && <span role="img" aria-label={`Unread messages from ${agent.name}`} className="size-2 shrink-0 rounded-full bg-primary" />}
|
||
</Link>{renderAgentAction?.(agent)}</>;
|
||
return <SortablePinnedRow key={agent.id} id={agent.id} label={agent.name} disabled={!canReorder} className={contactRowClassName}
|
||
data-selected={activeId === agent.id || undefined} data-has-unread={hasUnread || undefined}
|
||
handleClassName="agent-chat-pin right-2 size-8 focus-visible:outline-none group-hover/agent-pin:opacity-100 group-focus-within/agent-pin:opacity-100" handleIconClassName="size-4">{content}</SortablePinnedRow>;
|
||
})}
|
||
</SortablePinnedList>
|
||
</nav> : !agents.length && (historyLoading || historyError) ? null : <div className="flex flex-col items-start gap-2 px-2 py-6">
|
||
<p className="text-sm font-medium">{agents.length ? "No agents found" : "No chats yet"}</p>
|
||
<p className="text-xs leading-relaxed text-muted-foreground">{agents.length ? "Try another name or role." : "Choose an agent to start a conversation."}</p>
|
||
{!agents.length && <Button variant="outline" size="sm" onClick={() => setPickerOpen(true)}>Choose an agent</Button>}
|
||
{agents.length > 0 && <Button variant="outline" size="sm" onClick={focusSearch}>Clear search</Button>}
|
||
</div>}
|
||
{onCreateAgent && !loading && !error && <button type="button" onClick={onCreateAgent}
|
||
className="flex min-w-0 items-center gap-3 rounded-md px-2.5 py-3 text-left hover:bg-accent/60 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring">
|
||
<span aria-hidden className="flex size-10 shrink-0 items-center justify-center"><span className="agent-contact-create flex size-8 items-center justify-center bg-muted"><Plus className="size-5 text-foreground" /></span></span>
|
||
<span className="text-sm font-medium">Create a new agent</span>
|
||
</button>}
|
||
</div>
|
||
{onBrowse && <div className="shrink-0 px-3 py-4">
|
||
<Button variant="ghost" size="sm" className="w-full justify-start gap-2 px-2 text-muted-foreground" onClick={onBrowse}>
|
||
<Users className="size-4" />Browse all agents
|
||
</Button>
|
||
</div>}
|
||
{picker}
|
||
</aside>;
|
||
}
|