The open-source app everyone uses to manage agents at work
TypeScript acpxagent-orchestrationagent-skillsagentic-aiai-agentsai-engineeringai-governanceai-toolsautonomous-agentsclaudeclaude-codeclaude-skillscodexhermesllmmcpmulti-agentopenclawproject-managementworkflow-automation
fix: show notification actors and avatars, and hide self-actions (#15695)
Dotta41fec8c8921f
diff --git a/docs/pr-screenshots/pr-15695/README.md b/docs/pr-screenshots/pr-15695/README.mdnew file mode 100644index 0000000000..5763108aa8--- /dev/null+++ b/docs/pr-screenshots/pr-15695/README.md@@ -0,0 +1,8 @@+# Notification avatar review++These Chromium screenshots render the production `ToastProvider` and `ToastViewport` with the app stylesheet. Both themes show a person notification and an agent notification. The person uses the existing Storybook sample profile image. The agent uses the existing `ceo-cliptoon.png` fixture through a mocked custom-avatar asset response.++These are isolated UI renders with synthetic task and actor data, not screenshots of a production account. The capture waits for both avatar images to load before taking each screenshot. The authenticated WebSocket path is covered separately in `server/src/__tests__/live-events-toast.test.ts`.++- [Light theme](notification-avatars-light.png)+- [Dark theme](notification-avatars-dark.png)diff --git a/docs/pr-screenshots/pr-15695/notification-avatars-dark.png b/docs/pr-screenshots/pr-15695/notification-avatars-dark.pngnew file mode 100644index 0000000000..3d14f42f7fBinary files /dev/null and b/docs/pr-screenshots/pr-15695/notification-avatars-dark.png differdiff --git a/docs/pr-screenshots/pr-15695/notification-avatars-light.png b/docs/pr-screenshots/pr-15695/notification-avatars-light.pngnew file mode 100644index 0000000000..1f7ef68a4cBinary files /dev/null and b/docs/pr-screenshots/pr-15695/notification-avatars-light.png differdiff --git a/server/src/__tests__/live-events-toast.test.ts b/server/src/__tests__/live-events-toast.test.tsnew file mode 100644index 0000000000..5cddd929a9--- /dev/null+++ b/server/src/__tests__/live-events-toast.test.ts@@ -0,0 +1,98 @@+import { createServer } from "node:http";+import { once } from "node:events";+import { getTableName, type SQL } from "drizzle-orm";+import { PgDialect } from "drizzle-orm/pg-core";+import { activityToastIdentity } from "../realtime/activity-toast-identity.js";+import { WebSocket } from "ws";+import { describe, expect, it, vi } from "vitest";+import { setupLiveEventsWebSocketServer } from "../realtime/live-events-ws.js";+import { publishLiveEvent } from "../services/live-events.js";++vi.mock("../services/authorization.js", () => ({+ authorizationService: () => ({ decide: async ({ resource }: { resource: { issueId: string } }) => ({ allowed: resource.issueId !== "hidden" }) }),+}));+vi.mock("../services/heartbeat-run-privacy.js", () => ({ canActorReadHeartbeatRun: async () => false }));+function database(onPredicate: (kind: "where" | "join", condition: SQL) => void = () => {}) {+ return { select: (fields: Record<string, unknown>) => {+ let table = "";+ const query = {+ from: (value: Parameters<typeof getTableName>[0]) => { table = getTableName(value); return query; },+ innerJoin: (_table: unknown, condition: SQL) => { onPredicate("join", condition); return query; },+ where: (condition: SQL) => { onPredicate("where", condition); return query; },+ limit: async () => {+ if (table === "issues") return [{ id: "task" }];+ if (table === "company_memberships") return fields.name ? [{ name: "Alex Example", image: "/alex.png" }] : [{ id: "membership" }];+ if (table === "agents") return [{ name: "Coder", appearance: { schemaVersion: 1, characterVersion: "cap-v1", paletteId: "bubblegum-sky" } }];+ return [];+ },+ };+ return query;+ } };+}+describe("authenticated activity notifications", () => {+ it("keeps actor identity after authorization and excludes hidden tasks and private details", async () => {+ const server = createServer();+ setupLiveEventsWebSocketServer(server, database() as never, { deploymentMode: "authenticated",+ resolveCloudActor: async () => ({ userId: "viewer", companyIds: ["company"] }) });+ server.listen(0, "127.0.0.1");+ await once(server, "listening");+ const socket = new WebSocket(`ws://127.0.0.1:${(server.address() as { port: number }).port}/api/companies/company/events/ws`);+ try {+ await once(socket, "open");+ const messages: Array<{ payload: Record<string, unknown> }> = [];+ socket.on("message", (data) => messages.push(JSON.parse(data.toString())));+ const activity = (entityId: string, actorType = "user") => publishLiveEvent({ companyId: "company", type: "activity.logged", payload: {+ action: "issue.created", entityType: "issue", entityId, actorType, actorId: actorType === "user" ? "viewer" : "agent",+ details: { bodySnippet: "private comment", secret: "not for the socket" },+ } });+ activity("hidden");+ const first = once(socket, "message");+ activity("visible");+ await first;+ expect(messages).toHaveLength(1);+ expect(messages[0].payload).toEqual({ action: "issue.created", entityType: "issue", entityId: "visible", actorType: "user", actorId: "viewer", actorName: "Alex Example", actorImage: "/alex.png" });+ const second = once(socket, "message");+ activity("visible", "agent");+ await second;+ expect(messages[1].payload).toMatchObject({ actorName: "Coder", actorType: "agent", actorId: "agent", actorAppearance: { paletteId: "bubblegum-sky" } });+ expect(messages[1].payload).not.toHaveProperty("details");+ } finally {+ socket.terminate();+ await new Promise<void>((resolve) => server.close(() => resolve()));+ }+ });+});+++describe("activity profile query boundaries", () => {+ it("requires the exact company, human actor, and active membership before reading a person profile", async () => {+ const predicates: { kind: string; sql: string; params: unknown[] }[] = [];+ const db = database((kind, condition) => {+ const { sql, params } = new PgDialect().sqlToQuery(condition);+ predicates.push({ kind, sql, params });+ });+ await activityToastIdentity(db as never, "company-A", {+ action: "issue.created", actorType: "user", actorId: "person-A",+ });+ expect(predicates).toEqual([+ { kind: "join", sql: '"user"."id" = "company_memberships"."principal_id"', params: [] },+ { kind: "where", sql: '("company_memberships"."company_id" = $1 and "company_memberships"."principal_type" = $2 and "company_memberships"."principal_id" = $3 and "company_memberships"."status" = $4)',+ params: ["company-A", "user", "person-A", "active"] },+ ]);+ });++ it("requires both the exact company and agent ID before reading an agent profile", async () => {+ const predicates: { kind: string; sql: string; params: unknown[] }[] = [];+ const db = database((kind, condition) => {+ const { sql, params } = new PgDialect().sqlToQuery(condition);+ predicates.push({ kind, sql, params });+ });+ await activityToastIdentity(db as never, "company-A", {+ action: "issue.created", actorType: "agent", actorId: "agent-A",+ });+ expect(predicates).toEqual([+ { kind: "where", sql: '("agents"."company_id" = $1 and "agents"."id" = $2)',+ params: ["company-A", "agent-A"] },+ ]);+ });+});diff --git a/server/src/realtime/activity-toast-identity.ts b/server/src/realtime/activity-toast-identity.tsnew file mode 100644index 0000000000..414f46e199--- /dev/null+++ b/server/src/realtime/activity-toast-identity.ts@@ -0,0 +1,40 @@+import { and, eq } from "drizzle-orm";+import { agents, authUsers, companyMemberships, type Db } from "@paperclipai/db";++const TOAST_ACTIONS = new Set(["issue.created", "issue.updated", "issue.comment_added"]);++/** Called only after the viewer can read the activity's task. Never copy details. */+export async function activityToastIdentity(+ db: Db,+ companyId: string,+ payload: Record<string, unknown>,+) {+ const actorType = typeof payload.actorType === "string" ? payload.actorType : null;+ const actorId = typeof payload.actorId === "string" ? payload.actorId : null;+ const identity = { actorType, actorId };+ if (!actorId || !TOAST_ACTIONS.has(String(payload.action))) return identity;++ if (actorType === "agent") {+ const [agent] = await db+ .select({ name: agents.name, appearance: agents.appearance })+ .from(agents)+ .where(and(eq(agents.companyId, companyId), eq(agents.id, actorId)))+ .limit(1);+ return { ...identity, actorName: agent?.name, actorAppearance: agent?.appearance };+ }+ if (actorType === "user") {+ const [user] = await db+ .select({ name: authUsers.name, image: authUsers.image })+ .from(companyMemberships)+ .innerJoin(authUsers, eq(authUsers.id, companyMemberships.principalId))+ .where(and(+ eq(companyMemberships.companyId, companyId),+ eq(companyMemberships.principalType, "user"),+ eq(companyMemberships.principalId, actorId),+ eq(companyMemberships.status, "active"),+ ))+ .limit(1);+ return { ...identity, actorName: user?.name, actorImage: user?.image };+ }+ return identity;+}diff --git a/server/src/realtime/live-events-ws.ts b/server/src/realtime/live-events-ws.tsindex 67e836a0cf..9351d54d1e 100644--- a/server/src/realtime/live-events-ws.ts+++ b/server/src/realtime/live-events-ws.ts@@ -8,6 +8,7 @@ import { agentApiKeys, companyMemberships, instanceUserRoles, heartbeatRuns, issimport type { DeploymentMode, LiveEvent } from "@paperclipai/shared";import type { BetterAuthSessionResult } from "../auth/better-auth.js";import { logger } from "../middleware/logger.js";+import { activityToastIdentity } from "./activity-toast-identity.js";import { subscribeCompanyLiveEvents } from "../services/live-events.js";import { trackIdleWork } from "../services/task-admission.js";@@ -273,7 +274,13 @@ export function setupLiveEventsWebSocketServer(const access = authorizationService(db);async function visibleEvent(event: LiveEvent): Promise<LiveEvent | null> {- if (context!.actor.source === "local_implicit") return event;+ if (context!.actor.source === "local_implicit") {+ if (event.type === "activity.logged" && event.payload.entityType === "issue") {+ return { ...event, payload: { ...event.payload,+ ...await activityToastIdentity(db, event.companyId, event.payload) } };+ }+ return event;+ }if (context!.apiKeyId) {const active = await db.select({ id: agentApiKeys.id }).from(agentApiKeys).where(and(eq(agentApiKeys.id, context!.apiKeyId), isNull(agentApiKeys.revokedAt))).limit(1);@@ -313,6 +320,8 @@ export function setupLiveEventsWebSocketServer(// clients obtain details through viewer-filtered HTTP reads.if (event.type === "activity.logged") return { ...event, payload: {action: payload.action, entityType: payload.entityType, entityId: payload.entityId,+ // The task read check above authorizes attribution, but not arbitrary details.+ ...(issueId ? await activityToastIdentity(db, event.companyId, payload) : {}),} };if (event.type === "agent.status") return { ...event, payload: { agentId: payload.agentId, status: payload.status } };if (event.type === "external_object.updated") return { ...event, payload: { externalObjectId: payload.externalObjectId } };diff --git a/ui/src/components/ToastViewport.test.tsx b/ui/src/components/ToastViewport.test.tsxnew file mode 100644index 0000000000..cdf0babd01--- /dev/null+++ b/ui/src/components/ToastViewport.test.tsx@@ -0,0 +1,27 @@+// @vitest-environment jsdom+import { act, useEffect } from "react";+import { createRoot } from "react-dom/client";+import { describe, expect, it, vi } from "vitest";+import { ToastProvider, useToastActions, type ToastInput } from "../context/ToastContext";+import { ToastViewport } from "./ToastViewport";++vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);+vi.stubGlobal("requestAnimationFrame", (callback: () => void) => setTimeout(callback, 0));+vi.stubGlobal("cancelAnimationFrame", clearTimeout);+function Notify({ toast }: { toast: ToastInput }) {+ const { pushToast } = useToastActions();+ useEffect(() => { pushToast(toast); }, [pushToast, toast]);+ return <ToastViewport />;+}+describe("notification avatars", () => {+ it.each(["user", "agent"] as const)("carries the %s identity through the provider to the viewport", (type) => {+ const container = document.createElement("div");+ const root = createRoot(container);+ try {+ act(() => root.render(<ToastProvider><Notify toast={{ title: "Alex Example created a task", actor: { type, id: "actor-1", name: "Alex Example" } }} /></ToastProvider>));+ expect(container.textContent).toContain("Alex Example created a task");+ if (type === "user") expect(container.querySelector('[data-slot="avatar-fallback"]')?.textContent).toBe("AE");+ else expect(container.querySelector('[data-slot="agent-avatar"] img')?.getAttribute("src")).toContain("/api/agent-avatars/");+ } finally { act(() => root.unmount()); }+ });+});diff --git a/ui/src/components/ToastViewport.tsx b/ui/src/components/ToastViewport.tsxindex 23a53bda24..9205814af0 100644--- a/ui/src/components/ToastViewport.tsx+++ b/ui/src/components/ToastViewport.tsx@@ -1,3 +1,6 @@+import { AgentAvatar } from "./AgentAvatar";+import { deriveInitials } from "./Identity";+import { Avatar, AvatarFallback, AvatarImage } from "./ui/avatar";import { useEffect, useState } from "react";import { Link } from "@/lib/router";import { X } from "lucide-react";@@ -48,7 +51,16 @@ function AnimatedToast({)}><div className="flex items-start gap-3 px-3 py-2.5">- <span className={cn("mt-1 h-2 w-2 shrink-0 rounded-full", toneDotClasses[toast.tone])} />+ {toast.actor?.type === "agent" ? (+ <AgentAvatar agent={{ id: toast.actor.id, name: toast.actor.name, appearance: toast.actor.appearance }} size={24} />+ ) : toast.actor?.type === "user" ? (+ <Avatar size="sm" aria-hidden="true">+ {toast.actor.image && <AvatarImage src={toast.actor.image} alt="" />}+ <AvatarFallback>{deriveInitials(toast.actor.name)}</AvatarFallback>+ </Avatar>+ ) : (+ <span className={cn("mt-1 h-2 w-2 shrink-0 rounded-full", toneDotClasses[toast.tone])} />+ )}<div className="min-w-0 flex-1"><p className="text-sm font-semibold leading-5">{toast.title}</p>{toast.body && (diff --git a/ui/src/context/LiveUpdatesProvider.test.ts b/ui/src/context/LiveUpdatesProvider.test.tsindex 059ede5b0f..0e35df6486 100644--- a/ui/src/context/LiveUpdatesProvider.test.ts+++ b/ui/src/context/LiveUpdatesProvider.test.ts@@ -1644,3 +1644,30 @@ describe("task subtree notification context", () => {expect(__liveUpdatesTestUtils.shouldSuppressRunStatusToastForVisibleIssue(queryClient as never, "/PAP/agents/alex/runs/child-run", { runId: "child-run" }, { isForegrounded: true })).toBe(true);});});++describe("activity toast attribution", () => {+ const build = __liveUpdatesTestUtils.buildActivityToast;+ const payload = { action: "issue.created", entityType: "issue", entityId: "task-1", actorType: "user", actorId: "user-1", actorName: "Alex Example", actorImage: "/alex.png" };+ it.each(["issue.created", "issue.updated", "issue.comment_added"])("hides the viewer's own %s", (action) => {+ expect(build(new QueryClient(), "company", { ...payload, action }, { userId: "user-1", agentId: null })).toBeNull();+ });+ it("hides an agent's own action", () => {+ expect(build(new QueryClient(), "company", { ...payload, actorType: "agent", actorId: "agent-1" }, { userId: null, agentId: "agent-1" })).toBeNull();+ });+ it("uses the real name and photo with an empty directory cache", () => {+ const toast = build(new QueryClient(), "company", payload, { userId: "other-user", agentId: null });+ expect(toast?.title).toBe("Alex Example created Task task-1");+ expect(toast?.actor).toMatchObject({ type: "user", name: "Alex Example", image: "/alex.png" });+ });+ it("uses the agent's custom avatar with an empty agent cache", () => {+ const appearance = { schemaVersion: 1, characterVersion: "cap-v1", paletteId: "bubblegum-sky", customAvatarAssetId: "11111111-1111-4111-8111-111111111111" };+ const toast = build(new QueryClient(), "company", { ...payload, actorType: "agent", actorId: "agent-1", actorName: "Coder", actorAppearance: appearance }, { userId: "user-1", agentId: null });+ expect(toast?.title).toBe("Coder created Task task-1");+ expect(toast?.actor?.appearance).toEqual(appearance);+ });+ it("keeps system activity distinct from people", () => {+ const toast = build(new QueryClient(), "company", { ...payload, actorType: "system", actorName: undefined }, { userId: "user-1", agentId: null });+ expect(toast?.title).toBe("System created Task task-1");+ expect(toast?.actor).toBeUndefined();+ });+});diff --git a/ui/src/context/LiveUpdatesProvider.tsx b/ui/src/context/LiveUpdatesProvider.tsxindex 62260aad93..21f4c278b2 100644--- a/ui/src/context/LiveUpdatesProvider.tsx+++ b/ui/src/context/LiveUpdatesProvider.tsx@@ -1,3 +1,4 @@+import { resolveAgentAppearance } from "@paperclipai/shared";import { getPageVisibility, usePageVisibility } from "../lib/page-visibility";import {createContext,@@ -37,7 +38,7 @@ import { authApi } from "../api/auth";import type { CompanyListResult } from "../api/companies-query";import { healthApi } from "../api/health";import { useCompany } from "./CompanyContext";-import type { ToastInput } from "./ToastContext";+import type { ToastActor, ToastInput } from "./ToastContext";import { useToastActions } from "./ToastContext";import { upsertIssueCommentInPages } from "../lib/optimistic-issue-comments";import {@@ -186,9 +187,10 @@ function resolveActorLabel(}if (actorType === "system") return "System";if (actorType === "user" && actorId) {- return resolveUserName(queryClient, companyId, actorId) ?? "Board";+ return resolveUserName(queryClient, companyId, actorId) ??+ (actorId === "board" || actorId === "local-board" ? "Board" : `User ${shortId(actorId)}`);}- return "Someone";+ return actorType === "plugin" ? "Plugin" : "Unknown actor";}interface IssueToastContext {@@ -939,7 +941,21 @@ function buildActivityToast(entityId,details,);- const actor = resolveActorLabel(queryClient, companyId, actorType, actorId);+ const actor = readString(readString(payload.actorName)?.trim()) ?? resolveActorLabel(queryClient, companyId, actorType, actorId);+ const cachedAgent = actorType === "agent" && actorId+ ? queryClient.getQueryData<Agent[]>(queryKeys.agents.list(companyId))?.find((a) => a.id === actorId)+ ?? queryClient.getQueryData<Agent>(queryKeys.agents.detail(actorId))+ : undefined;+ const cachedUser = actorType === "user" && actorId+ ? queryClient.getQueryData<CompanyUserDirectoryResponse>(queryKeys.access.companyUserDirectory(companyId))+ ?.users.find((u) => u.principalId === actorId)?.user+ : undefined;+ const toastActor: ToastActor | undefined = actorId && (actorType === "user" || actorType === "agent")+ ? { type: actorType, id: actorId, name: actor,+ image: payload.actorImage !== undefined ? readString(payload.actorImage) : cachedUser?.image,+ appearance: actorType === "agent"+ ? resolveAgentAppearance(payload.actorAppearance !== undefined ? payload.actorAppearance : cachedAgent?.appearance, actorId) : undefined }+ : undefined;const isSelfActivity =(actorType === "user" &&!!currentActor.userId &&@@ -951,6 +967,7 @@ function buildActivityToast(if (action === "issue.created") {return {+ actor: toastActor,title: `${actor} created ${issue.ref}`,body: issue.title ? truncate(issue.title, 96) : undefined,tone: "success",@@ -973,6 +990,7 @@ function buildActivityToast(? truncate(issue.title, 96): issue.label;return {+ actor: toastActor,title: `${actor} updated ${issue.ref}`,body: truncate(body, 100),tone: "info",@@ -1006,6 +1024,7 @@ function buildActivityToast(: reopenedLabel: (issue.title ?? undefined);return {+ actor: toastActor,title,body: body ? truncate(body, 96) : undefined,tone: "info",@@ -1838,6 +1857,7 @@ function closeSocketQuietly(}export const __liveUpdatesTestUtils = {+ buildActivityToast,applyRunLifecycleToCompanyLiveRuns,buildAgentStatusToast,buildRunStatusToast,@@ -1883,7 +1903,8 @@ export function LiveUpdatesProvider({ children }: { children: ReactNode }) {retry: false,});const { data: health } = useQuery({ queryKey: queryKeys.health, queryFn: healthApi.get });- const currentUserId = session?.user?.id ?? session?.session?.userId ?? null;+ const currentUserId = session?.user?.id ?? session?.session?.userId ??+ (health?.deploymentMode === "local_trusted" ? "local-board" : null);const socketAuthKey = session?.session?.id ?? currentUserId ?? "signed_out";const liveCompanyId = resolveLiveCompanyId(selectedCompanyId, selectedCompany?.id ?? null);const canConnectSocket = canUseLiveSession(sessionStatus, session != null, health?.deploymentMode) && liveCompanyId !== null;diff --git a/ui/src/context/ToastContext.tsx b/ui/src/context/ToastContext.tsxindex b5d577e184..d9841e011f 100644--- a/ui/src/context/ToastContext.tsx+++ b/ui/src/context/ToastContext.tsx@@ -1,3 +1,4 @@+import type { AgentAppearance } from "@paperclipai/shared";import {createContext,useCallback,@@ -19,6 +20,14 @@ export interface ToastAction {onClick?: () => void;}+export type ToastActor = {+ type: "user" | "agent";+ id: string;+ name: string;+ image?: string | null;+ appearance?: AgentAppearance | null;+};+export interface ToastInput {id?: string;dedupeKey?: string;@@ -27,6 +36,7 @@ export interface ToastInput {tone?: ToastTone;ttlMs?: number;action?: ToastAction;+ actor?: ToastActor;}export interface ToastItem {@@ -36,6 +46,7 @@ export interface ToastItem {tone: ToastTone;ttlMs: number;action?: ToastAction;+ actor?: ToastActor;createdAt: number;}@@ -134,6 +145,7 @@ export function ToastProvider({ children }: { children: ReactNode }) {tone,ttlMs,action: input.action,+ actor: input.actor,createdAt: now,};