no idea how this works

This commit is contained in:
2026-03-16 16:48:38 -04:00
parent 55a8c9432e
commit 7c45451212
12 changed files with 588 additions and 113 deletions

View File

@@ -0,0 +1,71 @@
/**
* Tests for permissions plugin constants and worker handlers
*/
import { describe, it, expect, beforeEach, vi } from 'vitest';
import {
PERMISSION_KEYS,
type PermissionKey,
PERMISSION_LABELS,
DEFAULT_PAGE_LIMIT,
MAX_PAGE_LIMIT,
SIDEBAR_PREVIEW_LIMIT
} from '../constants';
describe('Constants', () => {
describe('PERMISSION_KEYS', () => {
it('should contain exactly 6 permission keys', () => {
expect(PERMISSION_KEYS).toHaveLength(6);
});
it('should contain expected permission keys', () => {
expect(PERMISSION_KEYS).toContain('agents:create');
expect(PERMISSION_KEYS).toContain('users:invite');
expect(PERMISSION_KEYS).toContain('users:manage_permissions');
expect(PERMISSION_KEYS).toContain('tasks:assign');
expect(PERMISSION_KEYS).toContain('tasks:assign_scope');
expect(PERMISSION_KEYS).toContain('joins:approve');
});
it('should be typed as readonly tuple', () => {
const keys: Readonly<readonly PermissionKey[]> = PERMISSION_KEYS;
expect(keys).toBeDefined();
});
});
describe('PERMISSION_LABELS', () => {
it('should have a label for each permission key', () => {
PERMISSION_KEYS.forEach(key => {
expect(PERMISSION_LABELS[key]).toBeDefined();
expect(PERMISSION_LABELS[key]).toBeTruthy();
});
});
it('should have human-readable labels', () => {
expect(PERMISSION_LABELS['agents:create']).toBe('Create Agents');
expect(PERMISSION_LABELS['users:invite']).toBe('Invite Users');
expect(PERMISSION_LABELS['users:manage_permissions']).toBe('Manage Permissions');
expect(PERMISSION_LABELS['tasks:assign']).toBe('Assign Tasks');
expect(PERMISSION_LABELS['tasks:assign_scope']).toBe('Task Assignment Scope');
expect(PERMISSION_LABELS['joins:approve']).toBe('Approve Join Requests');
});
});
describe('Pagination Constants', () => {
it('should have reasonable default page limit', () => {
expect(DEFAULT_PAGE_LIMIT).toBe(50);
expect(DEFAULT_PAGE_LIMIT).toBeGreaterThan(0);
expect(DEFAULT_PAGE_LIMIT).toBeLessThanOrEqual(MAX_PAGE_LIMIT);
});
it('should have max page limit greater than default', () => {
expect(MAX_PAGE_LIMIT).toBe(200);
expect(MAX_PAGE_LIMIT).toBeGreaterThan(DEFAULT_PAGE_LIMIT);
});
it('should have sidebar preview limit', () => {
expect(SIDEBAR_PREVIEW_LIMIT).toBe(5);
expect(SIDEBAR_PREVIEW_LIMIT).toBeLessThan(DEFAULT_PAGE_LIMIT);
});
});
});

View File

@@ -0,0 +1,108 @@
/**
* Tests for permissions plugin input validation
*/
import { describe, it, expect } from 'vitest';
import { PERMISSION_KEYS, DEFAULT_PAGE_LIMIT, MAX_PAGE_LIMIT } from '../constants';
describe('Input Validation', () => {
describe('Permission key validation', () => {
it('should accept valid permission keys', () => {
const validKeys = [
'agents:create',
'users:invite',
'users:manage_permissions',
'tasks:assign',
'tasks:assign_scope',
'joins:approve'
];
validKeys.forEach(key => {
expect(PERMISSION_KEYS).toContain(key as any);
});
});
it('should reject invalid permission keys', () => {
const invalidKeys = [
'invalid:key',
'agents:delete',
'',
'AGENTS:CREATE'
];
invalidKeys.forEach(key => {
expect(PERMISSION_KEYS).not.toContain(key as any);
});
});
});
describe('Pagination limit validation', () => {
function validateLimit(input: number | string | undefined): number {
const rawValue = typeof input === 'string' ? parseInt(input, 10) : input;
const numericValue = Number(rawValue) || DEFAULT_PAGE_LIMIT;
return Math.min(Math.max(1, numericValue), MAX_PAGE_LIMIT);
}
it('should use default limit when not specified', () => {
expect(validateLimit(undefined)).toBe(DEFAULT_PAGE_LIMIT);
expect(validateLimit(0)).toBe(DEFAULT_PAGE_LIMIT);
expect(validateLimit(NaN)).toBe(DEFAULT_PAGE_LIMIT);
});
it('should cap at max limit', () => {
expect(validateLimit(250)).toBe(MAX_PAGE_LIMIT);
expect(validateLimit(1000)).toBe(MAX_PAGE_LIMIT);
expect(validateLimit('500')).toBe(MAX_PAGE_LIMIT);
});
it('should minimum to 1', () => {
expect(validateLimit(-10)).toBe(1);
expect(validateLimit(0.5)).toBe(1);
});
it('should accept valid limits', () => {
expect(validateLimit(25)).toBe(25);
expect(validateLimit(100)).toBe(100);
expect(validateLimit(MAX_PAGE_LIMIT)).toBe(MAX_PAGE_LIMIT);
});
});
describe('Agent ID validation', () => {
function isValidAgentId(id: unknown): id is string {
return typeof id === 'string' && id.length > 0;
}
it('should accept valid agent IDs', () => {
expect(isValidAgentId('agent-123')).toBe(true);
expect(isValidAgentId('d20f6f1c-1f24-4405-a122-2f93e0d6c94a')).toBe(true);
expect(isValidAgentId('a')).toBe(true);
});
it('should reject invalid agent IDs', () => {
expect(isValidAgentId('')).toBe(false);
expect(isValidAgentId(123)).toBe(false);
expect(isValidAgentId(null)).toBe(false);
expect(isValidAgentId(undefined)).toBe(false);
expect(isValidAgentId({})).toBe(false);
});
});
describe('Boolean validation', () => {
function isValidBoolean(value: unknown): value is boolean {
return typeof value === 'boolean';
}
it('should accept true and false', () => {
expect(isValidBoolean(true)).toBe(true);
expect(isValidBoolean(false)).toBe(true);
});
it('should reject non-boolean values', () => {
expect(isValidBoolean('true')).toBe(false);
expect(isValidBoolean(1)).toBe(false);
expect(isValidBoolean(0)).toBe(false);
expect(isValidBoolean(null)).toBe(false);
expect(isValidBoolean(undefined)).toBe(false);
});
});
});

View File

@@ -0,0 +1,26 @@
// Shared permission keys for agent permissions plugin
export const PERMISSION_KEYS = [
"agents:create",
"users:invite",
"users:manage_permissions",
"tasks:assign",
"tasks:assign_scope",
"joins:approve"
] as const;
export type PermissionKey = typeof PERMISSION_KEYS[number];
export const PERMISSION_LABELS: Record<PermissionKey, string> = {
"agents:create": "Create Agents",
"users:invite": "Invite Users",
"users:manage_permissions": "Manage Permissions",
"tasks:assign": "Assign Tasks",
"tasks:assign_scope": "Task Assignment Scope",
"joins:approve": "Approve Join Requests"
};
// Pagination constants
export const DEFAULT_PAGE_LIMIT = 50;
export const MAX_PAGE_LIMIT = 200;
export const SIDEBAR_PREVIEW_LIMIT = 5;

View File

@@ -1,47 +1,38 @@
import { useState } from "react";
import { usePluginData, usePluginAction } from "@paperclipai/plugin-sdk/ui";
import type { PluginDetailTabProps } from "@paperclipai/plugin-sdk/ui";
const PERMISSION_KEYS = [
"agents:create",
"users:invite",
"users:manage_permissions",
"tasks:assign",
"tasks:assign_scope",
"joins:approve"
] as const;
const PERMISSION_LABELS: Record<string, string> = {
"agents:create": "Create Agents",
"users:invite": "Invite Users",
"users:manage_permissions": "Manage Permissions",
"tasks:assign": "Assign Tasks",
"tasks:assign_scope": "Task Assignment Scope",
"joins:approve": "Approve Join Requests"
};
import { PERMISSION_KEYS, PERMISSION_LABELS, type PermissionKey } from "../constants";
export function AgentPermissionsTab({ context }: PluginDetailTabProps) {
const { entityId: agentId } = context;
const { data, loading, error, refresh } = usePluginData<{
agentId: string;
permissions: Record<string, boolean>;
permissions: Record<PermissionKey, boolean>;
}>("agent-permissions", { agentId });
const togglePermission = usePluginAction("toggle-agent-permission");
const [updating, setUpdating] = useState<string | null>(null);
const [updating, setUpdating] = useState<PermissionKey | null>(null);
const [lastError, setLastError] = useState<Error | null>(null);
if (loading) return <div style={{ padding: "1rem" }}>Loading permissions...</div>;
if (error) return <div style={{ padding: "1rem", color: "#c00" }}>Error: {error.message}</div>;
if (error) return (
<div role="alert" style={{ padding: "1rem", color: "#c00" }}>
<strong>Error:</strong> {error.message}
</div>
);
if (!data) return <div style={{ padding: "1rem" }}>No permissions data available</div>;
async function handleToggle(permissionKey: string, currentEnabled: boolean) {
async function handleToggle(permissionKey: PermissionKey, currentEnabled: boolean) {
setLastError(null);
setUpdating(permissionKey);
try {
await togglePermission({ agentId, permissionKey, enabled: !currentEnabled });
await refresh();
} catch (err) {
console.error("Failed to toggle permission:", err);
const error = err instanceof Error ? err : new Error(String(err));
setLastError(error);
console.error("Failed to toggle permission:", error);
} finally {
setUpdating(null);
}
@@ -49,40 +40,74 @@ export function AgentPermissionsTab({ context }: PluginDetailTabProps) {
return (
<div style={{ padding: "1rem", maxWidth: "600px" }}>
<h2 style={{ marginBottom: "1.5rem", fontSize: "1.25rem", fontWeight: 600 }}>Agent Permissions</h2>
<h2 id="permissions-heading" style={{ marginBottom: "1.5rem", fontSize: "1.25rem", fontWeight: 600 }}>Agent Permissions</h2>
<p style={{ color: "#666", marginBottom: "1.5rem" }}>
Control what actions this agent can perform.
</p>
<div style={{ display: "flex", flexDirection: "column", gap: "0.75rem" }}>
{PERMISSION_KEYS.map((key) => {
const enabled = data.permissions[key] ?? false;
const isUpdating = updating === key;
return (
<label key={key} style={{
display: "flex",
alignItems: "center",
gap: "0.75rem",
cursor: isUpdating ? "wait" : "pointer",
padding: "0.5rem",
borderRadius: "4px",
backgroundColor: isUpdating ? "#f5f5f5" : "transparent",
transition: "background-color 0.2s"
}}>
<input
type="checkbox"
checked={enabled}
onChange={() => handleToggle(key, enabled)}
disabled={updating !== null}
style={{ width: "18px", height: "18px", cursor: isUpdating ? "wait" : "pointer" }}
/>
<span style={{ fontWeight: 500 }}>{PERMISSION_LABELS[key] || key}</span>
{isUpdating && <span style={{ color: "#888", fontSize: "0.875rem" }}>updating...</span>}
</label>
);
})}
</div>
{lastError && (
<div
role="alert"
aria-live="polite"
style={{
padding: "0.75rem",
marginBottom: "1rem",
backgroundColor: "#fee",
border: "1px solid #fcc",
borderRadius: "4px",
color: "#c00"
}}
>
<strong>Failed to update:</strong> {lastError.message}
</div>
)}
<fieldset style={{ border: "none", padding: 0, margin: 0 }}>
<legend style={{ display: "none" }}>Permission toggles</legend>
<div style={{ display: "flex", flexDirection: "column", gap: "0.75rem" }}>
{PERMISSION_KEYS.map((key) => {
const enabled = data.permissions[key] ?? false;
const isUpdating = updating === key;
return (
<label
key={key}
htmlFor={`perm-${key}`}
style={{
display: "flex",
alignItems: "center",
gap: "0.75rem",
cursor: isUpdating ? "wait" : "pointer",
padding: "0.5rem",
borderRadius: "4px",
backgroundColor: isUpdating ? "#f5f5f5" : "transparent",
transition: "background-color 0.2s"
}}
>
<input
id={`perm-${key}`}
type="checkbox"
checked={enabled}
onChange={() => handleToggle(key, enabled)}
disabled={updating !== null}
aria-describedby={isUpdating ? `loading-${key}` : undefined}
style={{ width: "18px", height: "18px", cursor: isUpdating ? "wait" : "pointer" }}
/>
<span style={{ fontWeight: 500 }}>{PERMISSION_LABELS[key]}</span>
{isUpdating && (
<span
id={`loading-${key}`}
style={{ color: "#888", fontSize: "0.875rem" }}
role="status"
>
updating...
</span>
)}
</label>
);
})}
</div>
</fieldset>
</div>
);
}

View File

@@ -1,17 +1,26 @@
import { usePluginData } from "@paperclipai/plugin-sdk/ui";
import type { PluginSidebarProps } from "@paperclipai/plugin-sdk/ui";
import { SIDEBAR_PREVIEW_LIMIT, type PermissionKey } from "../constants";
interface AgentPermissionsSummary {
agentId: string;
agentName: string;
permissions: Record<string, boolean>;
permissions: Record<PermissionKey, boolean>;
}
export function PermissionsNav({ context }: PluginSidebarProps) {
export function PermissionsNav(_props: PluginSidebarProps) {
const { data: agentsData, loading, error } = usePluginData<AgentPermissionsSummary[]>("all-agents-permissions");
if (loading) return <div style={{ padding: "1rem" }}>Loading...</div>;
if (error) return <div style={{ padding: "1rem", color: "#c00" }}>Error: {error.message}</div>;
if (loading) return (
<div role="status" style={{ padding: "1rem" }}>
Loading permissions...
</div>
);
if (error) return (
<div role="alert" style={{ padding: "1rem", color: "#c00" }}>
<strong>Error:</strong> {error.message}
</div>
);
if (!agentsData || agentsData.length === 0) {
return (
<div style={{ padding: "1rem" }}>
@@ -27,28 +36,31 @@ export function PermissionsNav({ context }: PluginSidebarProps) {
return (
<div style={{ padding: "1rem" }}>
<h3 style={{ fontSize: "1rem", fontWeight: 600, marginBottom: "0.75rem" }}>Permissions</h3>
<p style={{ color: "#666", fontSize: "0.75rem", marginBottom: "1rem" }}>
<h3 id="permissions-nav-heading" style={{ fontSize: "1rem", fontWeight: 600, marginBottom: "0.75rem" }}>Permissions</h3>
<p aria-labelledby="permissions-nav-heading" style={{ color: "#666", fontSize: "0.75rem", marginBottom: "1rem" }}>
{agentsWithPermissions.length} agent(s) with custom permissions
</p>
<div style={{ display: "flex", flexDirection: "column", gap: "0.5rem" }}>
{agentsData.slice(0, 5).map(agent => {
<ul style={{ display: "flex", flexDirection: "column", gap: "0.5rem", padding: 0, margin: 0, listStyle: "none" }}>
{agentsData.slice(0, SIDEBAR_PREVIEW_LIMIT).map(agent => {
const permCount = Object.values(agent.permissions).filter(Boolean).length;
return (
<div key={agent.agentId} style={{
fontSize: "0.875rem",
padding: "0.5rem",
backgroundColor: "#f9f9f9",
borderRadius: "4px"
}}>
<li
key={agent.agentId}
style={{
fontSize: "0.875rem",
padding: "0.5rem",
backgroundColor: "#f9f9f9",
borderRadius: "4px"
}}
>
<div style={{ fontWeight: 500 }}>{agent.agentName}</div>
<div style={{ color: "#888", fontSize: "0.75rem" }}>
{permCount} permission(s) granted
</div>
</div>
</li>
);
})}
</div>
</ul>
</div>
);
}

View File

@@ -1,15 +1,10 @@
import { definePlugin, runWorker } from "@paperclipai/plugin-sdk";
const PERMISSION_KEYS = [
"agents:create",
"users:invite",
"users:manage_permissions",
"tasks:assign",
"tasks:assign_scope",
"joins:approve"
] as const;
type PermissionKey = typeof PERMISSION_KEYS[number];
import {
PERMISSION_KEYS,
type PermissionKey,
DEFAULT_PAGE_LIMIT,
MAX_PAGE_LIMIT
} from "./constants";
interface AgentPermissions {
agentId: string;
@@ -51,6 +46,17 @@ const plugin = definePlugin({
enabled: boolean;
};
// Input validation
if (!agentId || typeof agentId !== 'string') {
throw new Error('Invalid agentId: must be a non-empty string');
}
if (!PERMISSION_KEYS.includes(permissionKey)) {
throw new Error(`Invalid permission key: ${permissionKey}`);
}
if (typeof enabled !== 'boolean') {
throw new Error('Invalid enabled: must be a boolean');
}
const allPerms = (await ctx.state.get(
{ scopeKind: "instance", stateKey: "agent_permissions" }
) as AgentPermissionsMap) ?? {};
@@ -68,9 +74,14 @@ const plugin = definePlugin({
ctx.data.register("all-agents-permissions", async (params) => {
const companyId = typeof params.companyId === "string" ? params.companyId : "";
const limit = Math.min(
Math.max(1, Number(params.limit) || DEFAULT_PAGE_LIMIT),
MAX_PAGE_LIMIT
);
const offset = Math.max(0, Number(params.offset) || 0);
const agents = companyId
? await ctx.agents.list({ companyId, limit: 100, offset: 0 })
? await ctx.agents.list({ companyId, limit, offset })
: [];
const allPerms = (await ctx.state.get(