From e2e22650854904c45aab5bdac780c347d5a09eb0 Mon Sep 17 00:00:00 2001 From: Nicky Leach Date: Fri, 4 Dec 2026 08:42:58 -0800 Subject: [PATCH] feat(plugins): tell a task side panel plugin when the person closes its tab (#23747) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## 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//api?runId=&issueId=`, 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 --- doc/plugins/PLUGIN_SPEC.md | 8 ++ packages/plugins/sdk/README.md | 13 ++ packages/shared/src/types/plugin.ts | 1 + packages/shared/src/validators/plugin.test.ts | 20 +++ packages/shared/src/validators/plugin.ts | 17 ++- .../runner-e2e/source-sdk-public-inputs.json | 6 +- .../TaskSidePanel.pluginClose.test.tsx | 121 ++++++++++++++++++ .../task-side-panel/TaskSidePanel.tsx | 4 +- ui/src/hooks/useTaskPluginPanels.ts | 8 ++ 9 files changed, 188 insertions(+), 10 deletions(-) create mode 100644 ui/src/components/task-side-panel/TaskSidePanel.pluginClose.test.tsx diff --git a/doc/plugins/PLUGIN_SPEC.md b/doc/plugins/PLUGIN_SPEC.md index 01dbef2cfb3..31975a4a0a2 100644 --- a/doc/plugins/PLUGIN_SPEC.md +++ b/doc/plugins/PLUGIN_SPEC.md @@ -416,6 +416,7 @@ export interface PaperclipPluginManifestV1 { agentEnvironmentDriver?: string; taskSidePanel?: { availabilityPath: string; + closePath?: string; /** Match runtime.activity.recorded for automatic opening; manual views need no mapping. */ activation?: { namespace: string; activityKey: string }; }; @@ -434,6 +435,13 @@ unavailable configuration hides the restricted view. A transient connection failure preserves the last known configuration. Eligibility does not depend on runtime readiness, agent lifecycle state, or automatic panel activation. +A task side panel can declare an optional `closePath` with the same path rules as +`availabilityPath`. The host sends a POST to it when the person closes the panel +tab, also when the tab is in the background. The host does not send it on a tab +switch, when the person leaves the task, or when the host removes a panel that is +no longer available. The manifest must declare the path as a board POST route +scoped to agent `:entityId`. + Rules: - `id` must be globally unique diff --git a/packages/plugins/sdk/README.md b/packages/plugins/sdk/README.md index 972707c1945..e3a14cd4172 100644 --- a/packages/plugins/sdk/README.md +++ b/packages/plugins/sdk/README.md @@ -336,6 +336,7 @@ the task is idle. An optional activity mapping also opens it automatically: ```ts taskSidePanel: { availabilityPath: "/agents/:entityId/view/availability", + closePath: "/agents/:entityId/view/close", activation: { namespace: "example.runtime", activityKey: "desktop.used" }, } ``` @@ -346,6 +347,18 @@ namespace/activity pair to installed agent detail tabs. Runner knows no plugin or UI slot. Declarations without `activation` support manual task-panel selection. Activity controls automatic opening and grants no access permission. +Core mounts only the active task panel tab, and it unmounts a plugin view in +the same way when the person switches tabs or closes the tab. To release a +resource when the person closes the tab, declare an optional `closePath`. Core +then sends a POST to that path, with `:entityId` replaced by the agent ID and +the same `runId` and `issueId` query parameters as the availability request. +When no run is active, Core leaves out `runId`. Core sends the request when the +person closes the tab, also when the tab is not the active tab. Core does not +send it when the person switches tabs or leaves the task, or when Core removes +the tab because the view is no longer available. Core does not wait for the +response and ignores failures. Declare the exact close path as a board-only +POST API route with `companyResolution: { from: "agent", param: "entityId" }`. + #### Runtime activity recording A runtime client captures Runner's opaque activity context before an eligible diff --git a/packages/shared/src/types/plugin.ts b/packages/shared/src/types/plugin.ts index 9fa76312dc7..b3476269177 100644 --- a/packages/shared/src/types/plugin.ts +++ b/packages/shared/src/types/plugin.ts @@ -517,6 +517,7 @@ export interface PluginUiSlotDeclaration { */ taskSidePanel?: { availabilityPath: string; + closePath?: string; /** Runtime activity that requests automatic opening; manual selection needs no mapping. */ activation?: { namespace: string; activityKey: string }; }; diff --git a/packages/shared/src/validators/plugin.test.ts b/packages/shared/src/validators/plugin.test.ts index 3fbbf6803e7..18ed32b80e6 100644 --- a/packages/shared/src/validators/plugin.test.ts +++ b/packages/shared/src/validators/plugin.test.ts @@ -577,6 +577,26 @@ describe("plugin task side-panel declarations", () => { it.each([[], [{ ...route, method: "POST" }], [{ ...route, auth: "agent" }], [{ ...route, companyResolution: { from: "query", key: "companyId" } }]].map(apiRoutes => ({ apiRoutes })))("requires a declared board GET route scoped to the supplied agent", ({ apiRoutes }) => { expect(pluginManifestV1Schema.safeParse({ ...manifest, apiRoutes }).success).toBe(false); }); + describe("close path", () => { + const closePath = "/agents/:entityId/view/close"; + const closing = { ...slot, taskSidePanel: { ...slot.taskSidePanel, closePath } }; + const closeRoute = { ...route, routeKey: "view.close", method: "POST", path: closePath }; + const withClose = { ...manifest, ui: { slots: [closing] }, apiRoutes: [route, closeRoute] }; + it("accepts an optional close path backed by an authorized POST route", () => { + expect(pluginManifestV1Schema.parse(withClose).ui?.slots?.[0]?.taskSidePanel?.closePath).toBe(closePath); + expect(pluginManifestV1Schema.parse(manifest).ui?.slots?.[0]?.taskSidePanel?.closePath).toBeUndefined(); + }); + it("accepts a close path that shares the availability path", () => { + const shared = { ...slot, taskSidePanel: { ...slot.taskSidePanel, closePath: slot.taskSidePanel.availabilityPath } }; + expect(pluginManifestV1Schema.safeParse({ ...manifest, ui: { slots: [shared] }, apiRoutes: [route, { ...route, routeKey: "view.close", method: "POST" }] }).success).toBe(true); + }); + it.each(["https://example.test/:entityId", "//example/:entityId", "/../:entityId", "/agents/:entityId?redirect=elsewhere", "/agents/:agentId/close", ""])("rejects unsafe or unsupported close path %j", closePath => { + expect(pluginUiSlotDeclarationSchema.safeParse({ ...slot, taskSidePanel: { ...slot.taskSidePanel, closePath } }).success).toBe(false); + }); + it.each([[route], [route, { ...closeRoute, method: "GET" }], [route, { ...closeRoute, method: "DELETE" }], [route, { ...closeRoute, auth: "agent" }], [route, { ...closeRoute, companyResolution: { from: "query", key: "companyId" } }], [route, { ...closeRoute, companyResolution: { from: "agent", param: "agentId" } }], [closeRoute]].map(apiRoutes => ({ apiRoutes })))("requires a declared board POST route scoped to the supplied agent", ({ apiRoutes }) => { + expect(pluginManifestV1Schema.safeParse({ ...withClose, apiRoutes }).success).toBe(false); + }); + }); }); diff --git a/packages/shared/src/validators/plugin.ts b/packages/shared/src/validators/plugin.ts index 10d970446d5..d1538168a6a 100644 --- a/packages/shared/src/validators/plugin.ts +++ b/packages/shared/src/validators/plugin.ts @@ -401,6 +401,8 @@ const runtimeActivityIdentifierSchema = z.string().min(1) .refine(value => Array.from(value).length <= 160, "Activity identifiers must contain at most 160 code points") .regex(/^[^\u0000-\u001f\u007f]+$/); +const taskSidePanelPathSchema = z.string().regex(/^\/(?:[a-zA-Z0-9_-]+\/)*:entityId(?:\/[a-zA-Z0-9_-]+)*$/); + export const pluginUiSlotDeclarationSchema = z.object({ type: z.enum(PLUGIN_UI_SLOT_TYPES), id: z.string().min(1), @@ -409,7 +411,8 @@ export const pluginUiSlotDeclarationSchema = z.object({ entityTypes: z.array(z.enum(PLUGIN_UI_SLOT_ENTITY_TYPES)).optional(), agentEnvironmentDriver: z.string().min(1).optional(), taskSidePanel: z.object({ - availabilityPath: z.string().regex(/^\/(?:[a-zA-Z0-9_-]+\/)*:entityId(?:\/[a-zA-Z0-9_-]+)*$/), + availabilityPath: taskSidePanelPathSchema, + closePath: taskSidePanelPathSchema.optional(), activation: z.object({ namespace: runtimeActivityIdentifierSchema, activityKey: runtimeActivityIdentifierSchema }).strict().optional(), }).strict().optional(), routePath: z.string().regex(/^[a-z0-9][a-z0-9-]*$/, { @@ -1069,10 +1072,14 @@ export const pluginManifestV1Schema = z.object({ for (const [index, slot] of (manifest.ui?.slots ?? []).entries()) { if (!slot.taskSidePanel) continue; - const route = manifest.apiRoutes?.find(route => route.path === slot.taskSidePanel!.availabilityPath && route.method === "GET"); - if (!route || route.auth !== "board" || route.transport - || route.companyResolution?.from !== "agent" || route.companyResolution.param !== "entityId") { - ctx.addIssue({ code: z.ZodIssueCode.custom, message: "taskSidePanel availability requires a declared board GET route scoped to agent :entityId", path: ["ui", "slots", index, "taskSidePanel"] }); + const required = [{ name: "availability", path: slot.taskSidePanel.availabilityPath, method: "GET" }]; + if (slot.taskSidePanel.closePath) required.push({ name: "close", path: slot.taskSidePanel.closePath, method: "POST" }); + for (const { name, path, method } of required) { + const route = manifest.apiRoutes?.find(route => route.path === path && route.method === method); + if (!route || route.auth !== "board" || route.transport + || route.companyResolution?.from !== "agent" || route.companyResolution.param !== "entityId") { + ctx.addIssue({ code: z.ZodIssueCode.custom, message: `taskSidePanel ${name} requires a declared board ${method} route scoped to agent :entityId`, path: ["ui", "slots", index, "taskSidePanel"] }); + } } } diff --git a/tests/runner-e2e/source-sdk-public-inputs.json b/tests/runner-e2e/source-sdk-public-inputs.json index 44f5b1bfde6..434446a02dc 100644 --- a/tests/runner-e2e/source-sdk-public-inputs.json +++ b/tests/runner-e2e/source-sdk-public-inputs.json @@ -466,7 +466,7 @@ "packages/shared/src/types/issue.ts": "c926a6a56874b18b3a61e22defaf9aca54172ca7", "packages/shared/src/types/live.ts": "b90e55e4de8600c6fc17d7fa8d89079d4ae655ec", "packages/shared/src/types/native-finalization.ts": "c026a73003ae232fea4f7624d561493b383df358", - "packages/shared/src/types/plugin.ts": "9fa76312dc773a6fd461c7895323e7c7c3f99fef", + "packages/shared/src/types/plugin.ts": "b347626917795b3c343d609426ee52d030b4b427", "packages/shared/src/types/project.ts": "50b9d9c51cb38d5862e287c1a47726716603f21c", "packages/shared/src/types/quota.ts": "a0686a9afb3111a4de093f66200dc0c9152e883e", "packages/shared/src/types/resource-memberships.ts": "9eab6fad50facf3e489f8c40e5bedd92e1d1faf8", @@ -552,8 +552,8 @@ "packages/shared/src/validators/native-finalization.ts": "d4e674de6ac7d36385e6f6c2172fa16ffc9b1830", "packages/shared/src/validators/onboarding-seed.ts": "de302a8400d4199053f379d9ed853522a3ac6d32", "packages/shared/src/validators/partial.ts": "fa60ec7481fc14175365e9e500c814b159f1ab53", - "packages/shared/src/validators/plugin.test.ts": "3fbbf6803e7302056386d16c56545e429fb7c7c4", - "packages/shared/src/validators/plugin.ts": "10d970446d52da15300db18102b2ebbaf684665a", + "packages/shared/src/validators/plugin.test.ts": "18ed32b80e6d1a0547188ef0320ff3228bb4dae7", + "packages/shared/src/validators/plugin.ts": "d1538168a6ad800cf537a1449aa7d457c6701d60", "packages/shared/src/validators/project.ts": "6ea168f5faf3161e6004ea47274f60634c77b219", "packages/shared/src/validators/provider-trace.ts": "b38b6200a2e51513f5dca0f8b008f2fe68175e82", "packages/shared/src/validators/resource-memberships.ts": "b124ac8a8f24b4dbb03ae82bcc87541f6b4ecdfd", diff --git a/ui/src/components/task-side-panel/TaskSidePanel.pluginClose.test.tsx b/ui/src/components/task-side-panel/TaskSidePanel.pluginClose.test.tsx new file mode 100644 index 00000000000..36cf76463e3 --- /dev/null +++ b/ui/src/components/task-side-panel/TaskSidePanel.pluginClose.test.tsx @@ -0,0 +1,121 @@ +// @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 }) =>
{slot.displayName}
})); +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; + +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( + undefined} /> + )); +} +function button(label: string) { + const element = container.querySelector(`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"); + 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); +}); diff --git a/ui/src/components/task-side-panel/TaskSidePanel.tsx b/ui/src/components/task-side-panel/TaskSidePanel.tsx index 41f873b61df..3cfb4736428 100644 --- a/ui/src/components/task-side-panel/TaskSidePanel.tsx +++ b/ui/src/components/task-side-panel/TaskSidePanel.tsx @@ -5,7 +5,7 @@ import { TaskAttachmentPanel } from "./TaskAttachmentPanel"; import { focusPlanPane, scheduleTaskPaneScroll } from "./task-pane-focus"; import { useQueryView } from "@/components/QueryView"; import { useTaskBrowsers } from "@/hooks/useTaskBrowsers"; -import { taskPluginPanelActivationKey, taskPluginPanelId, type TaskPluginPanel } from "@/hooks/useTaskPluginPanels"; +import { notifyTaskPluginPanelClosed, taskPluginPanelActivationKey, taskPluginPanelId, type TaskPluginPanel } from "@/hooks/useTaskPluginPanels"; import { PluginSlotMount } from "@/plugins/slots"; import { TaskBrowserPanel } from "./TaskBrowserPanel"; import { @@ -616,7 +616,7 @@ function TaskSidePanelForScope({ const tab = controller.tabs.find((candidate) => candidate.id === tabId); if (tab?.payload.kind === "plugin-panel") { const panel = pluginPanels.find(panel => taskPluginPanelId(panel) === tabId); - if (panel) dismissedPluginPanels.add(pluginPanelKey(panel)); + if (panel) { dismissedPluginPanels.add(pluginPanelKey(panel)); notifyTaskPluginPanelClosed(panel, issue.id); } } controller.closeTab(tabId); if (tabId === controller.activeTabId && (tab?.payload.kind === "workspace-file" || tab?.payload.kind === "files-browser")) { diff --git a/ui/src/hooks/useTaskPluginPanels.ts b/ui/src/hooks/useTaskPluginPanels.ts index e8456365492..a160d6631a9 100644 --- a/ui/src/hooks/useTaskPluginPanels.ts +++ b/ui/src/hooks/useTaskPluginPanels.ts @@ -29,6 +29,14 @@ export function taskPluginPanelActivationKey(panel: TaskPluginPanel, accountScop 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();