mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-02 08:28:48 +01:00
## Thinking Path
> - Paperclip is the open source app people use to manage AI agents for
work.
> - Agent Chat gives each person a persistent conversation with each
agent.
> - Tasks and routines produce results outside that conversation.
> - Those runs need a safe way to bring a requested result back to the
person.
> - The server must select the agent's own chat and check the source
task's access rules.
> - This pull request adds proactive chat messages and unread
indicators.
> - People can see the result, open its source task, and reply in the
same chat.
## Linked Issues or Issue Description
**Subsystem affected**
Server, native runner tools, shared contracts, database, and UI.
**Problem or motivation**
An agent can report progress on a task or comment on an authorized task.
It cannot send a routine result to its own standing chat with the
responsible person. A morning review routine therefore cannot leave a
visible digest in that person's chat.
**Proposed solution**
Add `send_chat_message({body, idempotencyKey})` and `POST
/api/agents/me/chat/messages`. The server selects the company, agent,
and responsible person from the active run. It saves an attributed
comment and audit record in one transaction. The chat shows a
source-task link and per-person unread state.
**Alternatives considered**
A destination parameter on a generic comment tool would expose
unnecessary routing authority. A new delivery worker would add another
durable delivery path. This change uses a dedicated tool and the
existing comment and live-event paths.
**Roadmap alignment**
This extends the experimental Agent Chat capability in `ROADMAP.md`. The
existing `enableAgentChat` setting controls it. Related public work:
Refs #13282, Refs #13283, and Refs #14408. Searches for proactive chat
and unread chat found no duplicate PR.
## What Changed
- Add a focused messaging service shared by the native tool and HTTP
route. It checks current run ownership, execution mode, recipient
membership, task access, and task privacy.
- Reuse the canonical company/agent/person conversation. Save the
comment and audit record together. Keep task completion and chat
execution separate from delivery.
- Add source-task provenance and source-scoped retry keys. Identical
retries return the saved receipt. Changed content returns a conflict.
- Enforce the conversation's fixed agent at the shared comment-write
boundary. Keep normal reply cancellation and session checks.
- Add chat unread state, accessible agent dots, aggregate Chat
indicators, and visible-message read cutoffs. Refresh through existing
live events.
- Add the request-key constraint, native tool contracts, documentation,
capability maps, stories, and regression coverage.
## Verification
- Local delivery/security proof: all 38 proactive-message cases pass.
Eight credential-scope regressions and four quota regressions fail
against the prior source. The repaired delivery and canonical
cross-issue cap suites pass all 49 cases; all 31 OpenAPI tests, server
typecheck, and capability-map checks pass. The shared per-run cap covers
native and HTTP sends, mixed ordinary mutations, concurrent last-slot
contention, and retry/recovery without double charging.
- Credential tests preserve the authenticated person and authorizer;
reject bridge/test credentials and persisted skill-test runs after
task-mode changes; and recheck API-key revocation, scope, and
responsible person after destination locking. The earlier
delivery/native-authority suites passed all 74 cases before the four
quota additions.
- Four PostgreSQL contention cases cover native and HTTP sends plus
retries during a native chat mutation. All four deadlock against the
earlier source and pass with destination-before-source/run locking.
Recovery and human-reply delivery enqueue only the human comment; a
proactive digest never wakes the chat agent.
- Passed 108 companion conversation, native-authority, and OpenAPI
tests; 112 runner catalog/workflow-report tests; 47 completion-delivery
tests; and 25 project-handoff tests. Focused runner tests cover native
tool availability without generic API tools.
- All 327 affected UI tests, UI typecheck, token gates, and catalog
checks pass. The read hook retries at most three times, respects server
retry delay, coalesces only seen cutoffs, recovers on reconnect, and
cancels on scope changes.
- Real browser journeys with a deterministic process agent verify
routine-to-chat delivery, first-chat creation, unread state across
reload, the source link, secondary chat navigation, and a follow-up
reply referring to the digest. This does not qualify live GitHub
retrieval or model output quality.
- The Storybook showcase uses production components with deterministic
network fixtures. Rendered interactions pass for the landing, ordinary
read success, transient read recovery, and persistent failure after
bounded retries. Both Chat navigation variants update from two unread
chats to one while only Kodi's dot clears. Mobile and light variants
were reviewed. The existing Coordinator Recents label contrast finding
is unchanged; no Linux visual baseline archive exists.
- Current master's independent sandbox migration retains 0418.
Regenerated the feature migration as 0419 from the combined schema and
retained exactly the newest five snapshots; numbering/safety, replay,
and schema-drift checks pass.
- Workspace typecheck and build passed before PR preparation; canonical
server/UI typechecks passed again on the combined tree. Migration
`0419_slippery_impossible_man.sql` passes safety and schema drift checks
on disposable PostgreSQL, including interrupted index repair, concurrent
migrators, one-time owner read-state backfill, preserved receipts, and
two SQL replays. A default five-second local snapshot comparison timed
out; a diagnostic 30-second run passed without drift.
- Earlier failures are retained in the record: full local `pnpm
test:run` and broad shards encountered embedded-PostgreSQL startup,
timing, and provider-recovery failures. Thirteen selected
external-channel cases pass in isolation on the original and changed
sources; an unordered comment-row assertion now explicitly orders both
reads. The earlier route registry, native tool count, runner catalog,
and accessible Chat badge-name failures were fixed and passed full
remote CI on `920b3bb7db`.
- Repeated managed-skill server8 failures came from CI's newer synthetic
merge: its Cloud guard correctly rejected the old local-disk fixture.
Master independently repaired the fixture in #18385; this branch keeps
that repair unchanged. All 57 managed-skill and Cloud prerequisite cases
pass on the combined tree, and that fixture has no remaining PR diff.
- Current reviewed head `dc16f314739a6d977bed21cb1446d0e80a541578`:
Greptile 5/5 with no findings, Superagent security assessment passed,
advisory Paperclip Review 5/5 with no findings, and zero open review
threads. All 55 current-head check runs pass, with five expected skips
and the advisory review neutral at 5/5; Snyk also passes. No checks are
pending or failing. Protected squash auto-merge is enabled and is
waiting for required code-owner approval. A normal exact-head merge was
refused by the base-branch policy; no admin bypass was used. The
previous head's Superagent quota finding is fixed and covered above.
## Risks
- Chat remains company-visible. Delivery rejects a source task with
private-task, project, or ancestor restrictions.
- Read state uses a comment timestamp cutoff. The server retains
database precision and never moves a read receipt backward.
- The new unique constraint changes comment query planning. An existing
regression now uses an explicit row order. The migration builds the
unique index concurrently, then takes a brief table lock to attach it.
It uses the existing top-level migration and interrupted-index recovery
path.
- The upgrade backfills missing chat-owner read-state rows at the latest
existing agent comment. Existing read receipts remain intact. New chats
can still be unread before the human participates.
- Quota observation commits atomically with delivery. A rejected send
rolls back its attempted denial audit row and any first-chat creation;
the canonical warning remains in server logs, and previously spent quota
remains enforced. Identical/conflicting retries and receipt recovery
spend no extra slot.
- This version delivers in-app only. It adds no external-channel, push,
or email delivery.
- Local full-suite acceptance remains limited by the failures recorded
above. The feature stays behind `enableAgentChat`.
## Model Used
OpenAI Codex. PR preparation and CI work used `gpt-6.1-sol` with tool
use and code execution. The earlier implementation also used Codex, but
its exact model ID was not recorded in the visible session. The
context-window size was not provided.
## 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 (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run focused tests locally and they pass; the broad local
failures are recorded above
- [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: Paperclip <noreply@paperclip.ing>
234 lines
8.9 KiB
TypeScript
234 lines
8.9 KiB
TypeScript
import { createContext, useContext, type ReactNode } from "react";
|
|
import { NavLink } from "@/lib/router";
|
|
import { SIDEBAR_SCROLL_RESET_STATE } from "../lib/navigation-scroll";
|
|
import { cn, SIDEBAR_RAIL_HIDDEN_LABEL } from "../lib/utils";
|
|
import { useSidebar } from "../context/SidebarContext";
|
|
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
|
|
import type { LucideIcon } from "lucide-react";
|
|
import { Badge } from "@/components/ui/badge";
|
|
import { TruncatedText } from "./TruncatedText";
|
|
|
|
/**
|
|
* Forces the full-label (non-rail) presentation for any `SidebarNavItem`
|
|
* rendered beneath it, regardless of the global `useSidebar().collapsed` state.
|
|
*
|
|
* Contextual takeover routes replace the global navigation inside the same
|
|
* sidebar shell. The user's saved global collapse preference can still be
|
|
* `collapsed=true`, so this provider keeps contextual navigation readable
|
|
* without mutating that preference.
|
|
*/
|
|
const SidebarNavExpandedContext = createContext(false);
|
|
|
|
export function SidebarNavExpandedProvider({ children }: { children: ReactNode }) {
|
|
return (
|
|
<SidebarNavExpandedContext.Provider value={true}>
|
|
{children}
|
|
</SidebarNavExpandedContext.Provider>
|
|
);
|
|
}
|
|
|
|
export function useSidebarNavExpanded() {
|
|
return useContext(SidebarNavExpandedContext);
|
|
}
|
|
|
|
interface SidebarNavItemProps {
|
|
to: string;
|
|
label: string;
|
|
icon?: LucideIcon;
|
|
/**
|
|
* Pre-rendered icon element for rows whose icon isn't a plain Lucide
|
|
* component (e.g. the agent rows' `AgentIcon`). Takes precedence over `icon`;
|
|
* the caller owns its sizing/color classes.
|
|
*/
|
|
iconNode?: ReactNode;
|
|
end?: boolean;
|
|
className?: string;
|
|
labelClassName?: string;
|
|
badge?: number;
|
|
badgeTone?: "default" | "danger" | "warning";
|
|
/**
|
|
* Accessible noun for the numeric badge when collapsed to the rail, where the
|
|
* count is rendered as a dot (e.g. `badgeLabel="unread"` → "Inbox, 28 unread").
|
|
*/
|
|
badgeLabel?: string;
|
|
textBadge?: string;
|
|
textBadgeTone?: "default" | "amber";
|
|
alert?: boolean;
|
|
liveCount?: number;
|
|
/**
|
|
* Overrides NavLink's own route matching for rows whose active state is
|
|
* computed externally (agent rows match `/agents/:ref` across tab suffixes).
|
|
*/
|
|
active?: boolean;
|
|
/** Rendered after the label, before the right-aligned status cluster. */
|
|
trailing?: ReactNode;
|
|
/** Accessible text for `trailing` status content, surfaced in the collapsed rail (where `trailing` is hidden). */
|
|
trailingLabel?: string;
|
|
/** Rendered inside the right-aligned status cluster, before the live dot. */
|
|
liveAccessory?: ReactNode;
|
|
}
|
|
|
|
export function SidebarNavItem({
|
|
to,
|
|
label,
|
|
icon: Icon,
|
|
iconNode,
|
|
end,
|
|
className,
|
|
labelClassName,
|
|
badge,
|
|
badgeTone = "default",
|
|
badgeLabel,
|
|
textBadge,
|
|
textBadgeTone = "default",
|
|
alert = false,
|
|
liveCount,
|
|
active,
|
|
trailing,
|
|
trailingLabel,
|
|
liveAccessory,
|
|
}: SidebarNavItemProps) {
|
|
const { isMobile, setSidebarOpen, collapsed, peeking } = useSidebar();
|
|
// A contextual takeover forces full labels even when the saved global app
|
|
// sidebar preference is collapsed.
|
|
const forceExpanded = useSidebarNavExpanded();
|
|
// The icon-only rail presentation only applies when pinned collapsed and not
|
|
// peeking; a peek/expanded panel — or a contextual takeover — restores
|
|
// the full label + badge.
|
|
const rail = collapsed && !peeking && !forceExpanded;
|
|
|
|
const hasBadge = badge != null && badge > 0;
|
|
const hasLive = liveCount != null && liveCount > 0;
|
|
const showIconSlot = Boolean(iconNode || Icon || alert || (rail && (hasLive || hasBadge)));
|
|
|
|
// Accessible text equivalent for the collapsed dot indicator. The visible
|
|
// label is `sr-only` in the rail, so the count must be surfaced here.
|
|
const railStatusText = hasLive
|
|
? `${liveCount} live`
|
|
: hasBadge
|
|
? `${badge}${badgeLabel ? ` ${badgeLabel}` : ""}`
|
|
: alert
|
|
? "attention needed"
|
|
: undefined;
|
|
const railAriaLabel = !rail || (!railStatusText && !trailingLabel)
|
|
? undefined
|
|
: `${label}${railStatusText ? `, ${railStatusText}` : ""}${trailingLabel ? `, ${trailingLabel}` : ""}`;
|
|
|
|
const link = (
|
|
<NavLink
|
|
to={to}
|
|
state={SIDEBAR_SCROLL_RESET_STATE}
|
|
end={end}
|
|
aria-label={railAriaLabel}
|
|
onClick={() => { if (isMobile) setSidebarOpen(false); }}
|
|
className={({ isActive }) =>
|
|
cn(
|
|
// One rhythm and one inset pill highlight: mx-2 floats the row off
|
|
// the sidebar edges, rounded-lg matches the card anchor, px-2 gives
|
|
// the icon breathing room inside the pill. Rows with hover menus
|
|
// (agents/projects) reserve extra right padding via className.
|
|
"flex items-center gap-2.5 mx-2 rounded-lg px-2 py-1.5 pointer-coarse:py-1 text-(length:--text-compact) font-medium transition-colors",
|
|
(active ?? isActive)
|
|
? "bg-sidebar-accent text-sidebar-accent-foreground"
|
|
: "text-foreground/80 hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",
|
|
className,
|
|
)
|
|
}
|
|
>
|
|
{showIconSlot ? (
|
|
<span data-slot="sidebar-nav-icon" className="relative shrink-0">
|
|
{iconNode ?? (Icon ? <Icon className="h-4 w-4" /> : null)}
|
|
{alert && (
|
|
<span
|
|
data-slot="sidebar-icon-alert-badge"
|
|
className="absolute -right-0.5 -top-0.5 h-2 w-2 rounded-full bg-red-500 shadow-(--shadow-sidebar-icon-badge)"
|
|
aria-hidden="true"
|
|
/>
|
|
)}
|
|
{/* Collapsed rail: numeric badge / live count collapse to a dot on the
|
|
icon. The icon markup is untouched so it stays pixel-aligned. */}
|
|
{rail && !alert && hasLive && (
|
|
<span className="absolute -right-0.5 -top-0.5 flex h-2 w-2" aria-hidden="true">
|
|
<span className="animate-pulse absolute inline-flex h-full w-full rounded-full bg-blue-600 dark:bg-blue-400 opacity-75" />
|
|
<span className="relative inline-flex h-2 w-2 rounded-full bg-blue-600 dark:bg-blue-400 shadow-(--shadow-sidebar-icon-badge)" />
|
|
</span>
|
|
)}
|
|
{rail && !alert && !hasLive && hasBadge && (
|
|
<span
|
|
className={cn(
|
|
"absolute -right-0.5 -top-0.5 h-2 w-2 rounded-full shadow-(--shadow-sidebar-icon-badge)",
|
|
badgeTone === "danger"
|
|
? "bg-red-600"
|
|
: badgeTone === "warning"
|
|
? "bg-amber-500"
|
|
: "bg-primary",
|
|
)}
|
|
aria-hidden="true"
|
|
/>
|
|
)}
|
|
</span>
|
|
) : null}
|
|
<TruncatedText className={rail ? SIDEBAR_RAIL_HIDDEN_LABEL : cn("min-w-0 flex-1 truncate", labelClassName)}>{label}</TruncatedText>
|
|
{!rail && trailing}
|
|
{!rail && textBadge && (
|
|
<Badge variant="ghost"
|
|
className={cn(
|
|
"ml-auto px-1.5 text-(length:--text-nano) leading-none",
|
|
textBadgeTone === "amber"
|
|
? "bg-amber-100 text-amber-800 dark:bg-amber-900/30 dark:text-amber-400"
|
|
: "bg-muted text-muted-foreground",
|
|
)}
|
|
>
|
|
{textBadge}
|
|
</Badge>
|
|
)}
|
|
{!rail && (hasLive || liveAccessory) && (
|
|
<span className="ml-auto flex shrink-0 items-center gap-1.5 whitespace-nowrap">
|
|
{liveAccessory}
|
|
{hasLive && (
|
|
<>
|
|
<span className="relative flex h-2 w-2">
|
|
<span className="animate-pulse absolute inline-flex h-full w-full rounded-full bg-blue-600 dark:bg-blue-400 opacity-75" />
|
|
<span className="relative inline-flex rounded-full h-2 w-2 bg-blue-600 dark:bg-blue-400" />
|
|
</span>
|
|
<span className="text-(length:--text-micro) font-medium text-blue-600 dark:text-blue-400">{liveCount} live</span>
|
|
</>
|
|
)}
|
|
</span>
|
|
)}
|
|
{!rail && hasBadge && (
|
|
<Badge variant="ghost"
|
|
aria-label={badgeLabel ? `${badge} ${badgeLabel}` : undefined}
|
|
className={cn(
|
|
"ml-auto px-1.5 leading-none",
|
|
badgeTone === "danger"
|
|
? "bg-red-600/90 text-red-50"
|
|
: badgeTone === "warning"
|
|
? "bg-amber-500/90 text-amber-50"
|
|
: "bg-primary text-primary-foreground",
|
|
)}
|
|
>
|
|
{badge}
|
|
</Badge>
|
|
)}
|
|
</NavLink>
|
|
);
|
|
|
|
if (!rail) return link;
|
|
|
|
// The tooltip wraps a plain block element rather than the NavLink directly:
|
|
// Radix `asChild` (Slot) drops React Router's *function* className, which would
|
|
// strip `flex` off the <a> and render it as a block — the in-flow label would
|
|
// then stack under the icon and the row would grow. Anchoring the tooltip to a
|
|
// wrapper keeps the <a> rendering normally (flex), so the row stays 1:1 with
|
|
// the expanded state and the icon never moves (PAP-10676).
|
|
return (
|
|
<Tooltip>
|
|
<TooltipTrigger asChild>
|
|
<div>{link}</div>
|
|
</TooltipTrigger>
|
|
<TooltipContent side="right">{label}</TooltipContent>
|
|
</Tooltip>
|
|
);
|
|
}
|