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();