Files
PaperClipAI/ui/src/components/task-side-panel/TaskSidePanel.pluginClose.test.tsx
T
Nicky LeachandClaude Opus 5.5 e2e2265085 feat(plugins): tell a task side panel plugin when the person closes its tab (#23747)
## 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>
2026-12-04 08:42:58 -08:00

122 lines
6.7 KiB
TypeScript

// @vitest-environment jsdom
import { act } from "react";
import { createRoot, type Root } from "react-dom/client";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import type { Issue } from "@paperclipai/shared";
import { afterEach, beforeEach, expect, it, vi, type MockInstance } from "vitest";
import { api } from "@/api/client";
import type { TaskPluginPanel } from "@/hooks/useTaskPluginPanels";
import { taskPanelPluginTab, writeTaskSidePanelState } from "@/lib/task-side-panel-state";
import type { ResolvedPluginSlot } from "@/plugins/slots";
import { TooltipProvider } from "@/components/ui/tooltip";
import { TaskSidePanel } from "./TaskSidePanel";
(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
vi.mock("@/lib/router", () => ({ useLocation: () => ({ pathname: "/task", search: "", hash: "", state: null }), useNavigate: () => vi.fn() }));
vi.mock("@/plugins/slots", () => ({ PluginSlotMount: ({ slot }: { slot: ResolvedPluginSlot }) => <div data-testid="plugin-view">{slot.displayName}</div> }));
vi.mock("@/hooks/useAgentChatEnabled", () => ({ useAgentChatEnabled: () => ({ enabled: false }) }));
vi.mock("@/hooks/useCoordinatorWorkspaceEnabled", () => ({ useCoordinatorWorkspaceEnabled: () => ({ enabled: false }) }));
vi.mock("@/hooks/useTaskBrowsers", () => ({ useTaskBrowsers: () => ({ data: [] }) }));
vi.mock("@/hooks/useIssueDocuments", () => ({ useIssueDocuments: () => ({ data: [] }) }));
vi.mock("@/hooks/useIssuePlanDocument", () => ({ useIssuePlanDocument: () => ({ data: null }) }));
const issue = { id: "task", companyId: "company", identifier: "TASK-1", title: "Task" } as Issue;
function panel(pluginId: string, displayName: string, closePath?: string, runId: string | null = "run"): TaskPluginPanel {
const slot = { type: "detailTab", id: "screen", displayName, exportName: "View", entityTypes: ["agent"], pluginId, pluginKey: `example.${pluginId}`, pluginDisplayName: displayName, pluginVersion: "1.0.0",
taskSidePanel: { availabilityPath: "/agents/:entityId/view/availability", ...(closePath ? { closePath } : {}) } } as ResolvedPluginSlot;
return { entityId: "agent", ...(runId ? { runId } : {}), autoOpen: false, slot };
}
const live = panel("live-view", "Live view", "/agents/:entityId/view/close");
const other = panel("other-view", "Other view", "/views/:entityId/release");
let root: Root, container: HTMLDivElement, client: QueryClient, post: MockInstance<typeof api.post>;
function seed(panels: TaskPluginPanel[], activeTabId: string) {
writeTaskSidePanelState("account", issue.companyId, issue.id, { state: { tabs: panels.map(taskPanelPluginTab), activeTabId }, launcherOpen: false, userInteracted: true, autoPlanHandled: true, updatedAt: Date.now() });
}
async function render(pluginPanels: TaskPluginPanel[]) {
await act(async () => root.render(<QueryClientProvider client={client}><TooltipProvider>
<TaskSidePanel issue={issue} accountScope="account" pluginPanels={pluginPanels} fileTabsEnabled={false} streamlinedTabs onUpdate={() => undefined} />
</TooltipProvider></QueryClientProvider>));
}
function button(label: string) {
const element = container.querySelector<HTMLButtonElement>(`button[aria-label="${label}"]`);
if (!element) throw new Error(`Missing ${label}`);
return element;
}
async function click(label: string) {
await act(async () => button(label).click());
}
beforeEach(() => {
window.localStorage.clear();
vi.stubGlobal("ResizeObserver", class { observe() {} unobserve() {} disconnect() {} });
Element.prototype.scrollTo = () => undefined;
client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
container = document.createElement("div"); document.body.append(container); root = createRoot(container);
vi.spyOn(api, "get").mockResolvedValue([]);
post = vi.spyOn(api, "post").mockResolvedValue({});
});
afterEach(async () => {
await act(async () => root.unmount()); client.clear(); container.remove(); vi.restoreAllMocks(); vi.unstubAllGlobals();
});
it("tells the plugin once when the person closes the active panel tab", async () => {
seed([live, other], "plugin:example.live-view:screen:agent");
await render([live, other]);
expect(container.querySelector("[data-testid=plugin-view]")?.textContent).toBe("Live view");
await click("Close Live view");
expect(post).toHaveBeenCalledTimes(1);
expect(post).toHaveBeenCalledWith("/plugins/live-view/api/agents/agent/view/close?runId=run&issueId=task", {});
});
it("tells the plugin when the person closes a background panel tab that is not mounted", async () => {
seed([live, other], "plugin:example.live-view:screen:agent");
await render([live, other]);
expect(container.textContent).not.toContain("Other view</div>");
await click("Close Other view");
expect(post).toHaveBeenCalledTimes(1);
expect(post).toHaveBeenCalledWith("/plugins/other-view/api/views/agent/release?runId=run&issueId=task", {});
expect(container.querySelector("[data-testid=plugin-view]")?.textContent).toBe("Live view");
});
it("sends nothing when the person switches tabs or leaves the task", async () => {
seed([live, other], "plugin:example.live-view:screen:agent");
await render([live, other]);
await click("Other view");
expect(container.querySelector("[data-testid=plugin-view]")?.textContent).toBe("Other view");
await click("Live view");
await act(async () => root.unmount());
root = createRoot(container);
expect(post).not.toHaveBeenCalled();
});
it("sends nothing when Core removes a panel that stopped being available", async () => {
seed([live, other], "plugin:example.live-view:screen:agent");
await render([live, other]);
await render([other]);
expect(container.textContent).not.toContain("Live view");
expect(post).not.toHaveBeenCalled();
});
it("sends nothing for a panel without a close route", async () => {
const plain = panel("plain-view", "Plain view");
seed([plain], "plugin:example.plain-view:screen:agent");
await render([plain]);
await click("Close Plain view");
expect(post).not.toHaveBeenCalled();
expect(container.querySelector("[data-testid=plugin-view]")).toBeNull();
});
it("omits the run for an idle task and closes the tab even when the request fails", async () => {
const idle = panel("live-view", "Live view", "/agents/:entityId/view/close", null);
seed([idle], "plugin:example.live-view:screen:agent");
post.mockRejectedValue(new Error("offline"));
const warn = vi.spyOn(console, "warn").mockImplementation(() => undefined);
await render([idle]);
await click("Close Live view");
await act(async () => undefined);
expect(post).toHaveBeenCalledExactlyOnceWith("/plugins/live-view/api/agents/agent/view/close?issueId=task", {});
expect(container.querySelector("[data-testid=plugin-view]")).toBeNull();
expect(warn).toHaveBeenCalledTimes(1);
});