Files
PaperClipAI/ui/src/components/responsibilities/AddExistingWorkPicker.tsx
T
575ef12575 feat(responsibilities): file company skills under responsibilities (#22275)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - A responsibility shows the skills of the agents doing its work.
People cannot say which skills a responsibility needs.
> - The maintainer chose to file skills under responsibilities like
projects, tasks and routines.
> - Agents also need to set a skill's catalog details without rewriting
its SKILL.md.
> - This pull request lets people and agents file, move and remove
company skills under a responsibility, and adds `update_skill_details`.
> - The benefit is that a responsibility lists the skills it needs,
beside the skills its agents already hold.

## Linked Issues or Issue Description

Refs #22253, #22261 and #22274; this pull request is stacked on them.

**Subsystem affected**

Database (`responsibility_links`), shared types and validators, server
responsibility service and routes, Dashboard versions, native runner
tools, and the responsibility page UI.

**Problem or motivation**

Skills under a responsibility are only computed from the agents doing
its work. A person cannot record that "Hiring needs interviewing", and
an agent cannot file a skill when it maps work for a person.

**Proposed solution**

Add a nullable `skill_id` to `responsibility_links` and allow it as the
one target of a link. Show filed and computed skills together. Let the
file, unfile, lookup and link routes and tools take skills. Keep filed
skills in Dashboard versions so undo covers them. Add a small live tool
for a skill's tagline and categories.

**Alternatives considered**

Keeping skills computed only, and giving the skill to the agent that
runs the responsibility, was the other option. It was not chosen.
Extending `update_skill` would change its scenario contract, whose mock
needs `markdown`, so the details tool is separate.

## What Changed

- Review fixes: the default responsibility view's Skills "+" adds an
existing skill, removes a filed one, or opens an agent's skills page. A
newest Dashboard version without a skill list is upgraded in place, so
the first skill filed after it is undone. Undo files again, or removes,
only skills the restoring person can see. A read scope without a skill
condition sees no filed skill. `update_skill_details` with only
`skillId` is a no-op, as its schema allows.

- Migration `0499`: add `responsibility_links.skill_id` (FK to
`company_skills`, on delete cascade). Widen the single-target check to
four targets. Add a unique `(responsibility_id, skill_id)` index and a
`skill_id` index. The migration is idempotent and online-compatible (NOT
VALID then VALIDATE, and the indexes are built CONCURRENTLY). It is
listed in `MIGRATIONS_WITH_TOP_LEVEL_STATEMENTS`.
- Shared: `ResponsibilityLink.skillId`;
`ResponsibilitySkillSummary.linkId` and `computed`; `skillId` in the
link and lookup schemas; `skill` in `RESPONSIBILITY_FILE_ITEM_KINDS`;
optional `skillIds` in Dashboard snapshot links.
- Server: filing checks the reader's skill visibility
(`skillAccessService`). The detail merges filed and computed skills into
one card each. Lookup accepts `skillId`. Dashboard capture, restore and
summary include filed skills. A version without `skillIds` leaves filed
skills as they are when it is restored.
- Tools: `file_under_responsibility`, `remove_from_responsibility` and
`find_responsibilities_for` accept `kind: "skill"`. `get_responsibility`
returns `linkId` and `computed` for each skill. Add
`update_skill_details` (tagline and categories).
- UI: the responsibility page has "Add existing skill". A filed skill
shows "Filed here" and a remove button. Computed skills keep their
holders.

## Verification

- Server: the `responsibilit*` tests (new: file, find, move and unfile a
skill; one card for a skill that is both filed and computed; undo of a
filed skill from the Dashboard history), `skill-tools.test.ts` (new
`update_skill_details` cases), `responsibility-tools`, `routine-tools`,
`routines-routes`, `paperclip-runner-tool-authority`, `runner-api` and
`openapi-routes`: 24 files, 2723 tests passed.
- UI: responsibility page and component tests (16 files, 158 tests,
including a new filed-skill test) pass. `pnpm --filter @paperclipai/ui
typecheck` passed.
- `@paperclipai/db` `check:migrations` passes and reports the override.
The snapshot drift test passes. `tsc` passes for `db`, `shared` and the
server layers.
- Runner: catalog and semantic-tool tests (317) pass. All generator
checks pass.

## Risks

- The migration changes a check constraint on `responsibility_links`.
The replacement accepts every row that the old check accepted. It is
swapped as NOT VALID and then validated. The previous release never sets
`skill_id`.
- Deleting a company skill removes its links (cascade).
- Filed skills follow the reader's skill visibility. A skill the reader
may not see is not listed.

## Model Used

Claude Opus 5.5 (`claude-opus-5-5`) in Claude Code, with tool use and
code execution.

## 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 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
- [ ] All Paperclip CI gates are green
- [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-11-19 09:30:49 -06:00

220 lines
8.3 KiB
TypeScript

import { useEffect, useMemo, useState, type ReactNode } from "react";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import type { LinkResponsibility } from "@paperclipai/shared";
import { Plus } from "lucide-react";
import { ApiError } from "@/api/client";
import { describeError } from "@/api/errors";
import { QueryErrorState, useQueryView } from "@/components/QueryView";
import { companySkillsApi } from "@/api/companySkills";
import { issuesApi } from "@/api/issues";
import { responsibilitiesApi, type ResponsibilityLinkResult } from "@/api/responsibilities";
import { routinesApi } from "@/api/routines";
import { Button } from "@/components/ui/button";
import { Command, CommandEmpty, CommandInput, CommandItem, CommandList } from "@/components/ui/command";
import { Popover, PopoverAnchor, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import { companyProjectsQuery } from "@/lib/company-projects-query";
import { queryKeys } from "@/lib/queryKeys";
export type ResponsibilityWorkKind = "project" | "task" | "routine" | "skill";
const TASK_SEARCH_LIMIT = 20;
const TASK_SEARCH_DEBOUNCE_MS = 200;
const NOUN: Record<ResponsibilityWorkKind, string> = { project: "project", task: "task", routine: "routine", skill: "skill" };
interface PickerOption {
id: string;
label: string;
detail?: string | null;
}
/**
* Readable copy for a refused link. Filing is additive (an item can sit under
* several responsibilities), so a 404 means the item is gone or out of reach.
*/
export function describeLinkError(error: unknown, kind: ResponsibilityWorkKind): string {
if (error instanceof ApiError && error.status === 404) {
return `That ${NOUN[kind]} is no longer available to you. It may have been deleted or made private.`;
}
return describeError(error).body;
}
function linkBody(kind: ResponsibilityWorkKind, id: string): LinkResponsibility {
if (kind === "project") return { projectId: id };
if (kind === "task") return { issueId: id };
if (kind === "skill") return { skillId: id };
return { routineId: id };
}
function useDebounced<T>(value: T, delayMs: number): T {
const [debounced, setDebounced] = useState(value);
useEffect(() => {
const timer = window.setTimeout(() => setDebounced(value), delayMs);
return () => window.clearTimeout(timer);
}, [value, delayMs]);
return debounced;
}
/**
* "Add existing…": search the company's projects, tasks, routines or skills
* and file one under the responsibility (it stays wherever else it is filed). Lists
* load only while the picker is open; tasks are searched on the server. Items
* already directly under this responsibility are left out.
*
* By default it opens from its own "Add existing" button. With `anchor` (and
* `open`/`onOpenChange`), another control opens it, and it sits under that.
*/
export function AddExistingWorkPicker({
companyId,
responsibilityId,
kind,
linkedIds,
onLinked,
open: controlledOpen,
onOpenChange,
anchor,
}: {
companyId: string;
responsibilityId: string;
kind: ResponsibilityWorkKind;
/** Ids already linked directly to this responsibility. */
linkedIds: ReadonlySet<string>;
onLinked?: (result: ResponsibilityLinkResult) => void;
open?: boolean;
onOpenChange?: (open: boolean) => void;
/** What the picker opens under, in place of its own button. */
anchor?: ReactNode;
}) {
const queryClient = useQueryClient();
const [ownOpen, setOwnOpen] = useState(false);
const open = controlledOpen ?? ownOpen;
const setOpen = (next: boolean) => {
if (controlledOpen === undefined) setOwnOpen(next);
onOpenChange?.(next);
};
const [query, setQuery] = useState("");
const taskQuery = useDebounced(query.trim(), TASK_SEARCH_DEBOUNCE_MS);
const projects = useQuery({ ...companyProjectsQuery(companyId), enabled: open && kind === "project" });
const routines = useQuery({
queryKey: queryKeys.routines.list(companyId),
queryFn: () => routinesApi.list(companyId),
enabled: open && kind === "routine",
});
const skills = useQuery({
queryKey: queryKeys.companySkills.list(companyId),
queryFn: () => companySkillsApi.list(companyId),
enabled: open && kind === "skill",
});
const tasks = useQuery({
queryKey: queryKeys.issues.search(companyId, taskQuery, undefined, TASK_SEARCH_LIMIT),
queryFn: () => issuesApi.list(companyId, { q: taskQuery || undefined, limit: TASK_SEARCH_LIMIT }),
enabled: open && kind === "task",
});
const options = useMemo<PickerOption[]>(() => {
if (kind === "project") {
return (projects.data ?? []).map((project) => ({ id: project.id, label: project.name }));
}
if (kind === "routine") {
return (routines.data ?? []).map((routine) => ({ id: routine.id, label: routine.title }));
}
if (kind === "skill") {
return (skills.data ?? []).map((skill) => ({ id: skill.id, label: skill.name }));
}
return (tasks.data ?? []).map((task) => ({ id: task.id, label: task.title, detail: task.identifier }));
}, [kind, projects.data, routines.data, skills.data, tasks.data]);
const available = useMemo(() => options.filter((option) => !linkedIds.has(option.id)), [options, linkedIds]);
const source = kind === "project" ? projects : kind === "routine" ? routines : kind === "skill" ? skills : tasks;
const sourceView = useQueryView<unknown>({
data: source.data,
error: source.error,
status: source.status,
fetchStatus: source.fetchStatus,
failureReason: source.failureReason,
refetch: source.refetch,
});
const link = useMutation({
mutationFn: (id: string) => responsibilitiesApi.link(responsibilityId, linkBody(kind, id)),
onSuccess: (result) => {
setOpen(false);
setQuery("");
onLinked?.(result);
void queryClient.invalidateQueries({ queryKey: queryKeys.responsibilities.all });
},
});
const resetLink = link.reset;
useEffect(() => {
if (open) resetLink();
}, [open, resetLink]);
return (
<Popover open={open} onOpenChange={setOpen}>
{anchor ? (
<PopoverAnchor asChild>
<span className="inline-flex">{anchor}</span>
</PopoverAnchor>
) : (
<PopoverTrigger asChild>
<Button size="sm" variant="ghost">
<Plus aria-hidden="true" />
Add existing {NOUN[kind]}
</Button>
</PopoverTrigger>
)}
<PopoverContent align="end" className="w-80 p-0">
<Command shouldFilter={kind !== "task"}>
<CommandInput
value={query}
onValueChange={setQuery}
placeholder={`Search ${NOUN[kind]}s…`}
aria-label={`Search ${NOUN[kind]}s`}
/>
<CommandList>
{sourceView.kind === "error" ? (
<div className="px-3 py-4">
<QueryErrorState
error={sourceView.error}
size="inline"
action={`load ${NOUN[kind]}s`}
onRetry={sourceView.retry}
retrying={sourceView.isFetching}
/>
</div>
) : !sourceView.data ? (
<p className="px-3 py-4 text-sm text-muted-foreground" role="status">Loading…</p>
) : (
<>
<CommandEmpty>
{options.length > 0 && available.length === 0
? `Every matching ${NOUN[kind]} is already here.`
: `No ${NOUN[kind]}s found.`}
</CommandEmpty>
{available.map((option) => (
<CommandItem
key={option.id}
value={`${option.label} ${option.detail ?? ""} ${option.id}`}
disabled={link.isPending}
onSelect={() => link.mutate(option.id)}
>
{option.detail ? <span className="font-mono text-xs text-muted-foreground">{option.detail}</span> : null}
<span className="truncate">{option.label}</span>
</CommandItem>
))}
</>
)}
</CommandList>
{link.error ? (
<p role="alert" className="border-t border-border px-3 py-2 text-sm text-destructive">
{describeLinkError(link.error, kind)}
</p>
) : null}
</Command>
</PopoverContent>
</Popover>
);
}