paperclip/ui/src/lib/activity-format.ts
Dotta b9a80dcf22
feat: implement multi-user access and invite flows (#3784)
## Thinking Path

> - Paperclip is the control plane for autonomous AI companies.
> - V1 needs to stay local-first while also supporting shared,
authenticated deployments.
> - Human operators need real identities, company membership, invite
flows, profile surfaces, and company-scoped access controls.
> - Agents and operators also need the existing issue, inbox, workspace,
approval, and plugin flows to keep working under those authenticated
boundaries.
> - This branch accumulated the multi-user implementation, follow-up QA
fixes, workspace/runtime refinements, invite UX improvements,
release-branch conflict resolution, and review hardening.
> - This pull request consolidates that branch onto the current `master`
branch as a single reviewable PR.
> - The benefit is a complete multi-user implementation path with tests
and docs carried forward without dropping existing branch work.

## What Changed

- Added authenticated human-user access surfaces: auth/session routes,
company user directory, profile settings, company access/member
management, join requests, and invite management.
- Added invite creation, invite landing, onboarding, logo/branding,
invite grants, deduped join requests, and authenticated multi-user E2E
coverage.
- Tightened company-scoped and instance-admin authorization across
board, plugin, adapter, access, issue, and workspace routes.
- Added profile-image URL validation hardening, avatar preservation on
name-only profile updates, and join-request uniqueness migration cleanup
for pending human requests.
- Added an atomic member role/status/grants update path so Company
Access saves no longer leave partially updated permissions.
- Improved issue chat, inbox, assignee identity rendering,
sidebar/account/company navigation, workspace routing, and execution
workspace reuse behavior for multi-user operation.
- Added and updated server/UI tests covering auth, invites, membership,
issue workspace inheritance, plugin authz, inbox/chat behavior, and
multi-user flows.
- Merged current `public-gh/master` into this branch, resolved all
conflicts, and verified no `pnpm-lock.yaml` change is included in this
PR diff.

## Verification

- `pnpm exec vitest run server/src/__tests__/issues-service.test.ts
ui/src/components/IssueChatThread.test.tsx ui/src/pages/Inbox.test.tsx`
- `pnpm run preflight:workspace-links && pnpm exec vitest run
server/src/__tests__/plugin-routes-authz.test.ts`
- `pnpm exec vitest run server/src/__tests__/plugin-routes-authz.test.ts
server/src/__tests__/workspace-runtime-service-authz.test.ts
server/src/__tests__/access-validators.test.ts`
- `pnpm exec vitest run
server/src/__tests__/authz-company-access.test.ts
server/src/__tests__/routines-routes.test.ts
server/src/__tests__/sidebar-preferences-routes.test.ts
server/src/__tests__/approval-routes-idempotency.test.ts
server/src/__tests__/openclaw-invite-prompt-route.test.ts
server/src/__tests__/agent-cross-tenant-authz-routes.test.ts
server/src/__tests__/routines-e2e.test.ts`
- `pnpm exec vitest run server/src/__tests__/auth-routes.test.ts
ui/src/pages/CompanyAccess.test.tsx`
- `pnpm --filter @paperclipai/shared typecheck && pnpm --filter
@paperclipai/db typecheck && pnpm --filter @paperclipai/server
typecheck`
- `pnpm --filter @paperclipai/shared typecheck && pnpm --filter
@paperclipai/server typecheck`
- `pnpm --filter @paperclipai/ui typecheck`
- `pnpm db:generate`
- `npx playwright test --config tests/e2e/playwright.config.ts --list`
- Confirmed branch has no uncommitted changes and is `0` commits behind
`public-gh/master` before PR creation.
- Confirmed no `pnpm-lock.yaml` change is staged or present in the PR
diff.

## Risks

- High review surface area: this PR contains the accumulated multi-user
branch plus follow-up fixes, so reviewers should focus especially on
company-boundary enforcement and authenticated-vs-local deployment
behavior.
- UI behavior changed across invites, inbox, issue chat, access
settings, and sidebar navigation; no browser screenshots are included in
this branch-consolidation PR.
- Plugin install, upgrade, and lifecycle/config mutations now require
instance-admin access, which is intentional but may change expectations
for non-admin board users.
- A join-request dedupe migration rejects duplicate pending human
requests before creating unique indexes; deployments with unusual
historical duplicates should review the migration behavior.
- Company member role/status/grant saves now use a new combined
endpoint; older separate endpoints remain for compatibility.
- Full production build was not run locally in this heartbeat; CI should
cover the full matrix.

## Model Used

- OpenAI Codex coding agent, GPT-5-based model, CLI/tool-use
environment. Exact deployed model identifier and context window were not
exposed by the runtime.

## 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 run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] If this change affects the UI, I have included before/after
screenshots
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [x] I will address all Greptile and reviewer comments before
requesting merge

Note on screenshots: this is a branch-consolidation PR for an
already-developed multi-user branch, and no browser screenshots were
captured during this heartbeat.

---------

Co-authored-by: dotta <dotta@example.com>
Co-authored-by: Paperclip <noreply@paperclip.ing>
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-17 09:44:19 -05:00

309 lines
11 KiB
TypeScript

import type { Agent } from "@paperclipai/shared";
import type { CompanyUserProfile } from "./company-members";
type ActivityDetails = Record<string, unknown> | null | undefined;
type ActivityParticipant = {
type: "agent" | "user";
agentId?: string | null;
userId?: string | null;
};
type ActivityIssueReference = {
id?: string | null;
identifier?: string | null;
title?: string | null;
};
interface ActivityFormatOptions {
agentMap?: Map<string, Agent>;
userProfileMap?: Map<string, CompanyUserProfile>;
currentUserId?: string | null;
}
const ACTIVITY_ROW_VERBS: Record<string, string> = {
"issue.created": "created",
"issue.updated": "updated",
"issue.checked_out": "checked out",
"issue.released": "released",
"issue.comment_added": "commented on",
"issue.comment_cancelled": "cancelled a queued comment on",
"issue.attachment_added": "attached file to",
"issue.attachment_removed": "removed attachment from",
"issue.document_created": "created document for",
"issue.document_updated": "updated document on",
"issue.document_deleted": "deleted document from",
"issue.commented": "commented on",
"issue.deleted": "deleted",
"agent.created": "created",
"agent.updated": "updated",
"agent.paused": "paused",
"agent.resumed": "resumed",
"agent.terminated": "terminated",
"agent.key_created": "created API key for",
"agent.budget_updated": "updated budget for",
"agent.runtime_session_reset": "reset session for",
"heartbeat.invoked": "invoked heartbeat for",
"heartbeat.cancelled": "cancelled heartbeat for",
"approval.created": "requested approval",
"approval.approved": "approved",
"approval.rejected": "rejected",
"project.created": "created",
"project.updated": "updated",
"project.deleted": "deleted",
"goal.created": "created",
"goal.updated": "updated",
"goal.deleted": "deleted",
"cost.reported": "reported cost for",
"cost.recorded": "recorded cost for",
"company.created": "created company",
"company.updated": "updated company",
"company.archived": "archived",
"company.budget_updated": "updated budget for",
};
const ISSUE_ACTIVITY_LABELS: Record<string, string> = {
"issue.created": "created the issue",
"issue.updated": "updated the issue",
"issue.checked_out": "checked out the issue",
"issue.released": "released the issue",
"issue.comment_added": "added a comment",
"issue.comment_cancelled": "cancelled a queued comment",
"issue.feedback_vote_saved": "saved feedback on an AI output",
"issue.attachment_added": "added an attachment",
"issue.attachment_removed": "removed an attachment",
"issue.document_created": "created a document",
"issue.document_updated": "updated a document",
"issue.document_deleted": "deleted a document",
"issue.deleted": "deleted the issue",
"agent.created": "created an agent",
"agent.updated": "updated the agent",
"agent.paused": "paused the agent",
"agent.resumed": "resumed the agent",
"agent.terminated": "terminated the agent",
"heartbeat.invoked": "invoked a heartbeat",
"heartbeat.cancelled": "cancelled a heartbeat",
"approval.created": "requested approval",
"approval.approved": "approved",
"approval.rejected": "rejected",
};
function asRecord(value: unknown): Record<string, unknown> | null {
if (!value || typeof value !== "object" || Array.isArray(value)) return null;
return value as Record<string, unknown>;
}
function humanizeValue(value: unknown): string {
if (typeof value !== "string") return String(value ?? "none");
return value.replace(/_/g, " ");
}
function isActivityParticipant(value: unknown): value is ActivityParticipant {
const record = asRecord(value);
if (!record) return false;
return record.type === "agent" || record.type === "user";
}
function isActivityIssueReference(value: unknown): value is ActivityIssueReference {
return asRecord(value) !== null;
}
function readParticipants(details: ActivityDetails, key: string): ActivityParticipant[] {
const value = details?.[key];
if (!Array.isArray(value)) return [];
return value.filter(isActivityParticipant);
}
function readIssueReferences(details: ActivityDetails, key: string): ActivityIssueReference[] {
const value = details?.[key];
if (!Array.isArray(value)) return [];
return value.filter(isActivityIssueReference);
}
function formatUserLabel(userId: string | null | undefined, options: ActivityFormatOptions = {}): string {
if (!userId || userId === "local-board") return "Board";
if (options.currentUserId && userId === options.currentUserId) return "You";
const profile = options.userProfileMap?.get(userId);
if (profile) return profile.label;
return `user ${userId.slice(0, 5)}`;
}
function formatParticipantLabel(participant: ActivityParticipant, options: ActivityFormatOptions): string {
if (participant.type === "agent") {
const agentId = participant.agentId ?? "";
return options.agentMap?.get(agentId)?.name ?? "agent";
}
return formatUserLabel(participant.userId, options);
}
function formatIssueReferenceLabel(reference: ActivityIssueReference): string {
if (reference.identifier) return reference.identifier;
if (reference.title) return reference.title;
if (reference.id) return reference.id.slice(0, 8);
return "issue";
}
function formatChangedEntityLabel(
singular: string,
plural: string,
labels: string[],
): string {
if (labels.length <= 0) return plural;
if (labels.length === 1) return `${singular} ${labels[0]}`;
return `${labels.length} ${plural}`;
}
function formatIssueUpdatedVerb(details: ActivityDetails): string | null {
if (!details) return null;
const previous = asRecord(details._previous) ?? {};
if (details.status !== undefined) {
const from = previous.status;
return from
? `changed status from ${humanizeValue(from)} to ${humanizeValue(details.status)} on`
: `changed status to ${humanizeValue(details.status)} on`;
}
if (details.priority !== undefined) {
const from = previous.priority;
return from
? `changed priority from ${humanizeValue(from)} to ${humanizeValue(details.priority)} on`
: `changed priority to ${humanizeValue(details.priority)} on`;
}
return null;
}
function formatAssigneeName(details: ActivityDetails, options: ActivityFormatOptions): string | null {
if (!details) return null;
const agentId = details.assigneeAgentId;
const userId = details.assigneeUserId;
if (typeof agentId === "string" && agentId) {
return options.agentMap?.get(agentId)?.name ?? "agent";
}
if (typeof userId === "string" && userId) {
return formatUserLabel(userId, options);
}
return null;
}
function formatIssueUpdatedAction(details: ActivityDetails, options: ActivityFormatOptions = {}): string | null {
if (!details) return null;
const previous = asRecord(details._previous) ?? {};
const parts: string[] = [];
if (details.status !== undefined) {
const from = previous.status;
parts.push(
from
? `changed the status from ${humanizeValue(from)} to ${humanizeValue(details.status)}`
: `changed the status to ${humanizeValue(details.status)}`,
);
}
if (details.priority !== undefined) {
const from = previous.priority;
parts.push(
from
? `changed the priority from ${humanizeValue(from)} to ${humanizeValue(details.priority)}`
: `changed the priority to ${humanizeValue(details.priority)}`,
);
}
if (details.assigneeAgentId !== undefined || details.assigneeUserId !== undefined) {
const assigneeName = formatAssigneeName(details, options);
parts.push(assigneeName ? `assigned the issue to ${assigneeName}` : "unassigned the issue");
}
if (details.title !== undefined) parts.push("updated the title");
if (details.description !== undefined) parts.push("updated the description");
return parts.length > 0 ? parts.join(", ") : null;
}
function formatStructuredIssueChange(input: {
action: string;
details: ActivityDetails;
options: ActivityFormatOptions;
forIssueDetail: boolean;
}): string | null {
const details = input.details;
if (!details) return null;
if (input.action === "issue.blockers_updated") {
const added = readIssueReferences(details, "addedBlockedByIssues").map(formatIssueReferenceLabel);
const removed = readIssueReferences(details, "removedBlockedByIssues").map(formatIssueReferenceLabel);
if (added.length > 0 && removed.length === 0) {
const changed = formatChangedEntityLabel("blocker", "blockers", added);
return input.forIssueDetail ? `added ${changed}` : `added ${changed} to`;
}
if (removed.length > 0 && added.length === 0) {
const changed = formatChangedEntityLabel("blocker", "blockers", removed);
return input.forIssueDetail ? `removed ${changed}` : `removed ${changed} from`;
}
return input.forIssueDetail ? "updated blockers" : "updated blockers on";
}
if (input.action === "issue.reviewers_updated" || input.action === "issue.approvers_updated") {
const added = readParticipants(details, "addedParticipants").map((participant) => formatParticipantLabel(participant, input.options));
const removed = readParticipants(details, "removedParticipants").map((participant) => formatParticipantLabel(participant, input.options));
const singular = input.action === "issue.reviewers_updated" ? "reviewer" : "approver";
const plural = input.action === "issue.reviewers_updated" ? "reviewers" : "approvers";
if (added.length > 0 && removed.length === 0) {
const changed = formatChangedEntityLabel(singular, plural, added);
return input.forIssueDetail ? `added ${changed}` : `added ${changed} to`;
}
if (removed.length > 0 && added.length === 0) {
const changed = formatChangedEntityLabel(singular, plural, removed);
return input.forIssueDetail ? `removed ${changed}` : `removed ${changed} from`;
}
return input.forIssueDetail ? `updated ${plural}` : `updated ${plural} on`;
}
return null;
}
export function formatActivityVerb(
action: string,
details?: Record<string, unknown> | null,
options: ActivityFormatOptions = {},
): string {
if (action === "issue.updated") {
const issueUpdatedVerb = formatIssueUpdatedVerb(details);
if (issueUpdatedVerb) return issueUpdatedVerb;
}
const structuredChange = formatStructuredIssueChange({
action,
details,
options,
forIssueDetail: false,
});
if (structuredChange) return structuredChange;
return ACTIVITY_ROW_VERBS[action] ?? action.replace(/[._]/g, " ");
}
export function formatIssueActivityAction(
action: string,
details?: Record<string, unknown> | null,
options: ActivityFormatOptions = {},
): string {
if (action === "issue.updated") {
const issueUpdatedAction = formatIssueUpdatedAction(details, options);
if (issueUpdatedAction) return issueUpdatedAction;
}
const structuredChange = formatStructuredIssueChange({
action,
details,
options,
forIssueDetail: true,
});
if (structuredChange) return structuredChange;
if (
(action === "issue.document_created" || action === "issue.document_updated" || action === "issue.document_deleted") &&
details
) {
const key = typeof details.key === "string" ? details.key : "document";
const title = typeof details.title === "string" && details.title ? ` (${details.title})` : "";
return `${ISSUE_ACTIVITY_LABELS[action] ?? action} ${key}${title}`;
}
return ISSUE_ACTIVITY_LABELS[action] ?? action.replace(/[._]/g, " ");
}