mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-05 06:03:51 +01:00
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - Plugins can show an agent detail tab in the task side panel, next to a task > - The board mounts only the active side panel tab, and it unmounts a plugin view in the same way when the person switches tabs and when the person closes the tab > - Thus a plugin that shows a live view in a task panel tab cannot know when the person is done with it, and it cannot release the view > - A component callback does not solve this, because a background tab is not mounted when the person clicks its close control > - This pull request adds an optional declarative `taskSidePanel.closePath`, symmetric with the existing `availabilityPath` > - The benefit is that a plugin can release a live view when the person closes its tab, and plugins that do not declare the path see no change ## Linked Issues or Issue Description Refs #17796 (added plugin panels in task side panels). Related: #23609. **Subsystem affected** Plugin UI slots: `detailTab` slots with a `taskSidePanel` declaration, and the task side panel in the board UI. **Problem or motivation** A plugin panel in the task side panel gets no signal when the person closes its tab. The board unmounts the view on a close and on a tab switch in the same way, so the plugin cannot tell the two apart. A plugin that holds a live view for the panel cannot release it when the person closes the tab. **Proposed solution** Add an optional `closePath` to `taskSidePanel`. When the person closes the tab, the board sends a fire-and-forget POST to that plugin route, with the same agent, run and task as the availability request. The manifest must declare the path as a board POST route scoped to agent `:entityId`. **Alternatives considered** A callback on the mounted plugin component. It does not work for a background tab, because only the active tab is mounted. **Roadmap alignment** This extends the plugin system. It adds no product-specific behaviour to the control plane. ## What Changed - `taskSidePanel` accepts an optional `closePath`. It uses the same path rules as `availabilityPath`: a plugin-relative path with one `:entityId` segment. - Manifest validation requires a declared `POST` API route at `closePath` with `auth: "board"`, no transport, and `companyResolution: { from: "agent", param: "entityId" }`. These are the same rules as the `GET` availability route. - When the person closes a plugin panel tab in the task side panel, the board sends `POST /plugins/<pluginId>/api<closePath>?runId=<run>&issueId=<task>`, with `:entityId` replaced by the panel's agent. The board leaves out `runId` when the task has no active run. This applies to the active tab and to background tabs. - The board does not wait for the request. A failed request does not block the close, and the board logs a console warning. - The board sends no request on a tab switch, when the panel unmounts, when the person leaves the task, or when the board removes a panel that is no longer available. - A slot without `closePath` behaves as before. - The plugin SDK README and the plugin spec document the new field. A plugin declares: ```ts ui: { slots: [{ type: "detailTab", id: "screen", displayName: "Live view", exportName: "LiveView", entityTypes: ["agent"], taskSidePanel: { availabilityPath: "/agents/:entityId/view/availability", closePath: "/agents/:entityId/view/close", }, }] }, apiRoutes: [ { routeKey: "view.availability", method: "GET", path: "/agents/:entityId/view/availability", auth: "board", capability: "api.routes.register", companyResolution: { from: "agent", param: "entityId" } }, { routeKey: "view.close", method: "POST", path: "/agents/:entityId/view/close", auth: "board", capability: "api.routes.register", companyResolution: { from: "agent", param: "entityId" } }, ], ``` ## Verification - `packages/shared`: `npx vitest run src/validators/plugin.test.ts` passes (85 tests). New cases accept a valid close route and a close path equal to the availability path. They reject unsafe paths, a missing POST route, the wrong method (`GET`, `DELETE`), non-board auth, a non-agent company resolution, and the wrong agent parameter. - `ui`: `npx vitest run src/components/task-side-panel/TaskSidePanel.pluginClose.test.tsx` passes (6 tests). The tests render the task side panel and check that a close of the active tab and of a background tab sends exactly one POST to the correct URL. They also check that a tab switch, an unmount, a removal of an unavailable panel, and a slot without `closePath` send nothing, and that an idle task omits `runId` and a failed request still closes the tab. - Red check: with the board call removed, the three close tests fail. - `ui`: `npx vitest run src/hooks/useTaskPluginPanels.test.tsx` passes (56 tests). - `tsc --noEmit` passes for `packages/shared` and for `ui` source files. ## Risks - Low risk. The field is optional, and slots without it keep their current behaviour. - A plugin receives a close POST only for a person's close of the tab. The plugin must treat the request as a hint, because the request can fail or arrive late. - Existing manifests continue to validate. The availability route error message has the same text as before. > For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and discuss it in `#dev` before opening the PR. Feature PRs that overlap with planned core work may need to be redirected — check the roadmap first. See `CONTRIBUTING.md`. ## Model Used - Claude Opus 5.5 (Anthropic), model ID `claude-opus-5-5`, run in Claude Code with tool use (file edits, shell, test runs) and extended reasoning. ## 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 - [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 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
159 lines
10 KiB
TypeScript
159 lines
10 KiB
TypeScript
import { queryViewKind } from "@/components/QueryView";
|
|
import { useEffect, useMemo } from "react";
|
|
import { useQueries, useQuery, useQueryClient } from "@tanstack/react-query";
|
|
import type { Issue } from "@paperclipai/shared";
|
|
import { api, ApiError } from "@/api/client";
|
|
import { heartbeatsApi } from "@/api/heartbeats";
|
|
import { useTaskRunLiveUpdates, useTranscriptLiveStream } from "@/context/LiveUpdatesProvider";
|
|
import { createLiveQueryRecovery } from "@/lib/live-query-recovery";
|
|
import { QueryNotReadyError } from "@/lib/query-client";
|
|
import { queryKeys } from "@/lib/queryKeys";
|
|
import { useAgentEnvironmentSlots } from "@/plugins/useAgentEnvironmentSlots";
|
|
import { usePluginSlots, type ResolvedPluginSlot } from "@/plugins/slots";
|
|
import { readFromIssueChatBootstrap } from "@/lib/issue-chat-bootstrap";
|
|
|
|
export interface TaskPluginPanel {
|
|
entityId: string;
|
|
runId?: string;
|
|
autoOpen: boolean;
|
|
slot: ResolvedPluginSlot;
|
|
}
|
|
|
|
const EMPTY_PANELS: TaskPluginPanel[] = [];
|
|
|
|
export function taskPluginPanelId(panel: TaskPluginPanel) {
|
|
return `plugin:${panel.slot.pluginKey}:${panel.slot.id}:${panel.entityId}`;
|
|
}
|
|
|
|
export function taskPluginPanelActivationKey(panel: TaskPluginPanel, accountScope: string, issue: Pick<Issue, "companyId" | "id">) {
|
|
return JSON.stringify([accountScope, issue.companyId, issue.id, panel.runId, taskPluginPanelId(panel)]);
|
|
}
|
|
|
|
export function notifyTaskPluginPanelClosed(panel: TaskPluginPanel, issueId: string) {
|
|
const closePath = panel.slot.taskSidePanel?.closePath;
|
|
if (!closePath) return;
|
|
const query = new URLSearchParams({ ...(panel.runId ? { runId: panel.runId } : {}), issueId });
|
|
void api.post(`/plugins/${encodeURIComponent(panel.slot.pluginId)}/api${closePath.replace(":entityId", encodeURIComponent(panel.entityId))}?${query}`, {})
|
|
.catch((error: unknown) => console.warn("Plugin panel close notification failed", error));
|
|
}
|
|
|
|
/** Plugins own their views; activity controls automatic opening. */
|
|
export function useTaskPluginPanels(issue: Issue | null | undefined, enabled = true): { panels: TaskPluginPanel[]; isLoading: boolean } {
|
|
const queryClient = useQueryClient();
|
|
const savedTask = enabled && !!issue && !issue.id.startsWith("chat:");
|
|
const { slots: declaredSlots, errorMessage, isLoading } = usePluginSlots({
|
|
slotTypes: ["detailTab"], entityType: "agent", taskSidePanel: true,
|
|
companyId: issue?.companyId, enabled: savedTask,
|
|
});
|
|
const declaredPanels = useMemo(() => declaredSlots.filter(slot => slot.taskSidePanel), [declaredSlots]);
|
|
const connected = useTaskRunLiveUpdates({
|
|
companyId: savedTask && declaredPanels.length > 0 && !errorMessage ? issue?.companyId : null,
|
|
issueId: issue?.id, issueQueryRef: issue?.id ?? "pending", assigneeAgentId: issue?.assigneeAgentId,
|
|
});
|
|
const { data: runs, isError: runsError, isPending: runsPending } = useQuery({
|
|
queryKey: queryKeys.issues.liveRuns(issue?.id ?? "pending"),
|
|
queryFn: () => readFromIssueChatBootstrap(queryClient, queryKeys.issues.liveRuns(issue!.id), issue!.id, (item) => item.liveRuns, () => heartbeatsApi.liveRunsForIssue(issue!.id)),
|
|
enabled: savedTask && declaredPanels.length > 0 && !errorMessage,
|
|
refetchInterval: connected ? false : 3000,
|
|
retry: (failures: number, error: Error) => failures < 2 && !(error instanceof ApiError && error.status >= 400 && error.status < 500),
|
|
retryDelay: 1000,
|
|
});
|
|
const run = runs?.find(run => run.status === "running"
|
|
&& (!issue?.executionRunId || run.id === issue.executionRunId));
|
|
const agentId = (!runsError && run?.agentId) || issue?.assigneeAgentId;
|
|
const { slots: panels, isLoading: environmentLoading } = useAgentEnvironmentSlots(
|
|
declaredPanels, savedTask && !errorMessage ? agentId : null, issue?.companyId,
|
|
);
|
|
const slots = useMemo(() => panels.filter(slot => slot.taskSidePanel?.activation), [panels]);
|
|
const active = savedTask && slots.length > 0 && !!run && !runsError && !errorMessage;
|
|
const declarations = slots.map(slot => [slot.pluginKey, slot.id, slot.pluginVersion,
|
|
slot.taskSidePanel!.activation!.namespace, slot.taskSidePanel!.activation!.activityKey]);
|
|
const activationScope = JSON.stringify(declarations);
|
|
const activationKey = ["task-plugin-panel-activations", issue?.companyId, issue?.id, run?.id, run?.agentId, activationScope];
|
|
// Keep unchanged declarations active while a new declaration scope loads.
|
|
const retained = new Map<string, { pluginKey: string; slotId: string }>();
|
|
for (const [key, panels] of queryClient.getQueriesData<Array<{ pluginKey: string; slotId: string }>>({ queryKey: activationKey.slice(0, 5) })) {
|
|
if (typeof key[5] !== "string" || queryClient.getQueryState(key)?.status !== "success") continue;
|
|
const unchanged = (JSON.parse(key[5]) as string[][]).filter(previous =>
|
|
declarations.some(current => current.every((part, index) => part === previous[index])));
|
|
for (const panel of panels ?? []) if (unchanged.some(declaration => declaration[0] === panel.pluginKey && declaration[1] === panel.slotId)) {
|
|
retained.set(JSON.stringify([panel.pluginKey, panel.slotId]), panel);
|
|
}
|
|
}
|
|
const { data: recordedActivations = [], isError: activationsError } = useQuery({
|
|
queryKey: activationKey,
|
|
queryFn: ({ signal }) => heartbeatsApi.taskPanelActivations(run!.id, { signal, cache: "no-store" }),
|
|
initialData: () => retained.size ? [...retained.values()] : undefined,
|
|
initialDataUpdatedAt: 0,
|
|
// Run activations only grow; merge history and live hints when committing cache data.
|
|
structuralSharing: (previous, incoming) => {
|
|
const merged = new Map(retained);
|
|
for (const panel of [...((previous ?? []) as Array<{ pluginKey: string; slotId: string }>), ...(incoming as Array<{ pluginKey: string; slotId: string }>)]) {
|
|
merged.set(JSON.stringify([panel.pluginKey, panel.slotId]), panel);
|
|
}
|
|
return [...merged.values()];
|
|
},
|
|
staleTime: 0,
|
|
enabled: active,
|
|
retry: (failures: number, error: Error) => failures < 2 && !(error instanceof ApiError && error.status >= 400 && error.status < 500),
|
|
retryDelay: 1000,
|
|
});
|
|
const activations = [...recordedActivations, ...retained.values()];
|
|
const stream = useTranscriptLiveStream(active ? [run!.id] : [], { companyId: issue?.companyId, enabled: active }, event => {
|
|
if (!active || !run || event.companyId !== issue?.companyId || event.payload.runId !== run.id
|
|
|| event.payload.agentId !== run.agentId || event.payload.issueId !== issue?.id
|
|
|| event.type !== "heartbeat.run.event" || event.payload.eventType !== "runtime.activity.recorded") return;
|
|
const native = event.payload.payload as { prpEvent?: { eventType?: string; sourceKind?: string; payload?: unknown } } | null;
|
|
if (native?.prpEvent?.eventType !== "runtime.activity.recorded" || native.prpEvent.sourceKind !== "runner") return;
|
|
const activity = native.prpEvent.payload as { namespace?: unknown; activityKey?: unknown } | null;
|
|
if (!activity || Object.keys(activity).length !== 2 || typeof activity.namespace !== "string" || typeof activity.activityKey !== "string") return;
|
|
const panels = slots.filter(slot => slot.taskSidePanel?.activation?.namespace === activity.namespace
|
|
&& slot.taskSidePanel?.activation?.activityKey === activity.activityKey)
|
|
.map(slot => ({ pluginKey: slot.pluginKey, slotId: slot.id }));
|
|
if (!panels.length) return;
|
|
queryClient.setQueryData<Array<{ pluginKey: string; slotId: string }>>(activationKey, previous => {
|
|
const missing = panels.filter(panel => !previous?.some(item => item.pluginKey === panel.pluginKey && item.slotId === panel.slotId));
|
|
return missing.length ? [...(previous ?? []), ...missing] : previous;
|
|
});
|
|
for (const panel of panels) void queryClient.invalidateQueries({
|
|
queryKey: ["task-plugin-panel", issue?.companyId, issue?.id, run.id, run.agentId, panel.pluginKey, panel.slotId],
|
|
predicate: ({ state }) => state.status === "error" && state.fetchStatus === "idle"
|
|
&& !(state.error instanceof ApiError && state.error.status >= 400 && state.error.status < 500),
|
|
});
|
|
});
|
|
useEffect(() => {
|
|
if (!active || !stream.healthy) return;
|
|
let current = true;
|
|
void queryClient.invalidateQueries({ queryKey: ["task-plugin-panel", issue?.companyId, issue?.id, run?.id, run?.agentId] });
|
|
// A pre-subscription history read must settle before the recovery read.
|
|
createLiveQueryRecovery(queryClient, () => current, { queryKey: activationKey, exact: true })();
|
|
return () => { current = false; };
|
|
}, [active, stream.healthy, stream.epoch, queryClient, issue?.companyId, issue?.id, run?.id, run?.agentId, activationScope]);
|
|
const availability = useQueries({ queries: slots.map(slot => ({
|
|
queryKey: ["task-plugin-panel", issue?.companyId, issue?.id, run?.id, run?.agentId, slot.pluginKey, slot.id, slot.pluginVersion, slot.pluginId, slot.taskSidePanel!.availabilityPath],
|
|
queryFn: async ({ signal }: { signal: AbortSignal }) => {
|
|
const result = await api.get<{ available: boolean }>(
|
|
`/plugins/${encodeURIComponent(slot.pluginId)}/api${slot.taskSidePanel!.availabilityPath.replace(":entityId", encodeURIComponent(run!.agentId))}?runId=${encodeURIComponent(run!.id)}&issueId=${encodeURIComponent(issue!.id)}`,
|
|
{ signal, cache: "no-store" },
|
|
);
|
|
if (result.available !== true) throw new QueryNotReadyError("Plugin panel is not ready");
|
|
return result;
|
|
},
|
|
enabled: active && !activationsError && activations.some(panel => panel.pluginKey === slot.pluginKey && panel.slotId === slot.id),
|
|
retry: (failures: number, error: Error) => failures < 2 && !(error instanceof ApiError && error.status >= 400 && error.status < 500),
|
|
retryDelay: 1000,
|
|
})) });
|
|
const available = availability.map((result, index) => !activationsError && queryViewKind(result) !== "error" && result.data?.available === true
|
|
&& activations.some(panel => panel.pluginKey === slots[index]?.pluginKey && panel.slotId === slots[index]?.id));
|
|
const availableKey = available.join(",");
|
|
const manualPanels = useMemo(() => savedTask && !errorMessage && agentId ? panels.map(slot => ({
|
|
entityId: agentId,
|
|
...(!runsError && run ? { runId: run.id } : {}),
|
|
autoOpen: active && available[slots.indexOf(slot)] === true,
|
|
slot,
|
|
})) : EMPTY_PANELS,
|
|
[savedTask, errorMessage, agentId, panels, run?.id, runsError, active, slots, availableKey]);
|
|
return { panels: manualPanels, isLoading: savedTask && !errorMessage
|
|
&& (isLoading || environmentLoading || (declaredPanels.length > 0 && runsPending)) };
|
|
}
|