feat(plugins): add sidebar workspace actions to New Task (#2607)

Co-authored-by: ayattara <alassane.yattara@savoirfairelinux.com>
Co-authored-by: Carlos Florencio <carlosmflorencio@gmail.com>
This commit is contained in:
Alassane
2026-08-15 12:00:02 -04:00
committed by GitHub
parent fe991d0b77
commit 31e07fab34
17 changed files with 659 additions and 78 deletions
@@ -356,6 +356,29 @@
);
}
function WorkspaceActionsSlot(props) {
var slotProps = props.slotProps || {};
return jsx(
"button",
{
type: "button",
"data-testid": "e2e-sidebar-workspace-actions",
"data-workspace-id": slotProps.workspaceId,
"data-workspace-label": slotProps.workspaceLabel || "",
"data-presentation": slotProps.presentation || "unknown",
"aria-label": "Fixture workspace action",
className:
slotProps.presentation === "mobile"
? "flex h-11 w-11 cursor-pointer items-center justify-center rounded-md border"
: "flex h-6 w-6 cursor-pointer items-center justify-center rounded-md border",
onClick: function (event) {
event.currentTarget.setAttribute("data-clicked", "true");
},
},
"W",
);
}
function StatusSlot(props) {
var slotProps = props.slotProps || {};
var id = slotProps.placement === "left" ? "hello-status-left" : "hello-status-right";
@@ -602,6 +625,7 @@
registry.registerComponent("new-session-input-actions", ComposerAction);
registry.registerComponent("task-card-indicators", CardIndicator);
registry.registerComponent("task-card-tags", CardTags);
registry.registerComponent("sidebar-workspace-actions", WorkspaceActionsSlot);
registry.registerTaskMenuAction({
id: "enhance-notes",
label: "Enhance notes",
@@ -153,6 +153,106 @@ func TestUserStateGETFromDifferentUserReturns404(t *testing.T) {
}
}
// TestUserStateWorkspaceScopeIsolatesUsersAndScopes covers the workspace
// scope the way TestUserStateGETFromDifferentUserReturns404 covers the task
// scope. Workspace-scoped entries only became a shipping surface with the
// sidebar-workspace-actions slot (kandev-plugin-notes' per-workspace note),
// and that note's UI promises "only you can see this note" — so the negative
// is asserted for every verb, not just GET: a second user must not read,
// overwrite, delete, or enumerate the first user's workspace note.
//
// The same subtest also pins scope separation on an identical raw id:
// task/X and workspace/X are different entries, which is what lets the
// plugin key one cache by "<scope>:<id>" without conflating the two.
func TestUserStateWorkspaceScopeIsolatesUsersAndScopes(t *testing.T) {
router, svc, _ := newUserStateTestRouter(t)
installUserStatePlugin(t, svc, "kandev-plugin-notes", true)
const (
wsPath = "/api/plugins/kandev-plugin-notes/user-state/workspace/ws_1/note"
wsList = "/api/plugins/kandev-plugin-notes/user-state/workspace/ws_1"
taskPath = "/api/plugins/kandev-plugin-notes/user-state/task/ws_1/note"
)
rec := userStateReq(router, http.MethodPut, wsPath, "user_1", `{"value":"alice's workspace note"}`)
if rec.Code != http.StatusOK {
t.Fatalf("PUT status = %d, want 200, body=%s", rec.Code, rec.Body.String())
}
if rec = userStateReq(router, http.MethodPut, taskPath, "user_1", `{"value":"task-scoped"}`); rec.Code != http.StatusOK {
t.Fatalf("PUT task scope status = %d, want 200, body=%s", rec.Code, rec.Body.String())
}
// user_2 must not read it.
if rec = userStateReq(router, http.MethodGet, wsPath, "user_2", ""); rec.Code != http.StatusNotFound {
t.Fatalf("GET (different user) status = %d, want 404, body=%s", rec.Code, rec.Body.String())
}
// user_2 must not enumerate it.
rec = userStateReq(router, http.MethodGet, wsList, "user_2", "")
if rec.Code != http.StatusOK {
t.Fatalf("LIST (different user) status = %d, want 200, body=%s", rec.Code, rec.Body.String())
}
var user2List struct {
Entries []state.UserStateEntry `json:"entries"`
}
if err := json.Unmarshal(rec.Body.Bytes(), &user2List); err != nil {
t.Fatalf("unmarshal LIST (different user): %v", err)
}
if len(user2List.Entries) != 0 {
t.Fatalf("LIST (different user) returned entries: %+v", user2List.Entries)
}
assertUserStateValue(t, router, taskPath, "user_1", `"task-scoped"`)
rec = userStateReq(router, http.MethodGet, wsList, "user_1", "")
if rec.Code != http.StatusOK {
t.Fatalf("LIST (workspace scope) status = %d, want 200, body=%s", rec.Code, rec.Body.String())
}
var workspaceList struct {
Entries []state.UserStateEntry `json:"entries"`
}
if err := json.Unmarshal(rec.Body.Bytes(), &workspaceList); err != nil {
t.Fatalf("unmarshal LIST (workspace scope): %v", err)
}
if len(workspaceList.Entries) != 1 || workspaceList.Entries[0].Key != "note" {
t.Fatalf("LIST (workspace scope) entries = %+v, want only note", workspaceList.Entries)
}
// user_2 writing the same path must not disturb user_1's value, and
// user_2 deleting it must not delete user_1's.
if rec = userStateReq(router, http.MethodPut, wsPath, "user_2", `{"value":"bob's own"}`); rec.Code != http.StatusOK {
t.Fatalf("PUT (different user) status = %d, want 200, body=%s", rec.Code, rec.Body.String())
}
if rec = userStateReq(router, http.MethodDelete, wsPath, "user_2", ""); rec.Code != http.StatusOK {
t.Fatalf("DELETE (different user) status = %d, want 200, body=%s", rec.Code, rec.Body.String())
}
assertUserStateValue(t, router, wsPath, "user_1", `"alice's workspace note"`)
assertUserStateValue(t, router, taskPath, "user_1", `"task-scoped"`)
// task/ws_1 and workspace/ws_1 are distinct entries for the same user.
if rec = userStateReq(router, http.MethodDelete, wsPath, "user_1", ""); rec.Code != http.StatusOK {
t.Fatalf("DELETE workspace scope status = %d, want 200, body=%s", rec.Code, rec.Body.String())
}
assertUserStateValue(t, router, taskPath, "user_1", `"task-scoped"`)
}
// assertUserStateValue fails unless userID's entry at path holds want.
func assertUserStateValue(t *testing.T, router *gin.Engine, path, userID, want string) {
t.Helper()
rec := userStateReq(router, http.MethodGet, path, userID, "")
if rec.Code != http.StatusOK {
t.Fatalf("GET %s status = %d, want 200, body=%s", path, rec.Code, rec.Body.String())
}
var resp struct {
Value json.RawMessage `json:"value"`
}
if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil {
t.Fatalf("unmarshal %s: %v", path, err)
}
if string(resp.Value) != want {
t.Fatalf("GET %s value = %s, want %s", path, resp.Value, want)
}
}
// TestUserStateWithoutCapabilityReturns403 pins AC17.
func TestUserStateWithoutCapabilityReturns403(t *testing.T) {
router, svc, _ := newUserStateTestRouter(t)
+1 -1
View File
@@ -91,7 +91,6 @@ For rebasing or finishing PRs written against the old Next.js runtime, follow [`
Use subscription hooks only; the WS client auto-deduplicates.
**Task overview vs. session detail:** Shared task rows read `Task.statusSummary` and `task.status_summary.updated`; rich streams stay session-detail-only. Extend the bounded projection per the [spec](../../docs/specs/platform/bounded-task-status-delivery.md) and [ADR](../../docs/decisions/2026-08-01-separate-task-summary-session-stream-traffic.md).
**Branch-scoped task state:** For live worktree/session state plus `task_prs`, key by `(repository, checked-out branch)`, not task/repository alone. `branch_switched` invalidates prior status/commits; reject late results with a generation/identity guard and preserve siblings. Historical PRs affect Changes only when `repository_id` and normalized `head_branch` match; Review/PR history may still show them. Test single/multi-repo cases and desktop/mobile Changes behavior.
**HTTP/WS cache races:** When HTTP hydrates a cache also updated by WebSockets, guard responses with per-scope revision and request/workspace generation; discard or refresh stale responses and cover deferred responses. `useEnsureTaskSession` re-fires `session.ensure` when an open task page sees zero sessions after a prior ensure, so deleting the last session from that page spawns a replacement; test zero-session states through the backend/API instead.
@@ -287,6 +286,7 @@ plugin leaks a stale registration.
- **Kanban card contributions:** `registerTaskMenuAction({ group: "edit", ... })` turns the flat
`Edit` item into an `Edit` submenu (`kanban-card-edit-submenu.tsx`);
`registerComponent("task-card-indicators", ...)` renders beside `PRTaskIcon` via `<PluginSlot/>`; `task-card-tags` renders in its own row below the badges (for contributions too wide for the title-row indicators spot, e.g. tag chips).
- **Sidebar workspace actions:** `registerComponent("sidebar-workspace-actions", ...)` renders after Quick Terminal/Quick Chat in the desktop sidebar's New Task row and in the shared phone navigation sheet, forwarding `SidebarWorkspaceActionsSlotProps` with `presentation: "desktop" | "mobile"`; mobile plugin controls own a 44px touch target and accessible name.
- **`host.storage`:** authenticated per-user key/value storage (`lib/plugins/host-api.ts`), backed by
`/api/plugins/{id}/user-state/...` (`docs/decisions/2026-08-01-per-user-plugin-storage.md`).
`subscribe` (`lib/plugins/user-state-sync.ts`) wraps `registerWsHandler` with own-plugin filtering
@@ -1,6 +1,7 @@
import { describe, it, expect, beforeEach, afterEach, vi } from "vitest";
import { act, cleanup, fireEvent, render, screen } from "@testing-library/react";
import { TooltipProvider } from "@kandev/ui/tooltip";
import type { JSX } from "react";
const mocks = vi.hoisted(() => ({
routerPush: vi.fn(),
@@ -21,10 +22,13 @@ function renderItem(collapsed: boolean) {
);
}
const WORKSPACE_ID = "ws-1";
const WORKSPACE_NAME = "Default Workspace";
const state = {
workspaces: {
activeId: "ws-1" as string | null,
items: [{ id: "ws-1", name: "Default Workspace" }],
activeId: WORKSPACE_ID as string | null,
items: [{ id: WORKSPACE_ID, name: WORKSPACE_NAME }],
},
appSidebar: { improveDialogOpen: false },
kanban: {
@@ -40,6 +44,22 @@ const QUICK_CHAT_TEST_ID = "sidebar-quick-chat-shortcut";
let officeEnabled = false;
let pathname = "/";
// sidebar-workspace-actions plugin slot registrations (A1-A5). Empty by
// default so the existing dialog-routing/row-action tests above are
// unaffected; individual tests below set this before rendering.
let workspaceActionsRegistrations: Array<{
registrationId: string;
pluginId: string;
Component: (props: { slotProps?: unknown }) => JSX.Element;
}> = [];
vi.mock("@/lib/plugins/registry", () => ({
usePluginRegistry: () => ({
getSlotRegistrations: (name: string) =>
name === "sidebar-workspace-actions" ? workspaceActionsRegistrations : [],
}),
}));
vi.mock("@/components/state-provider", () => ({
useAppStore: (selector: (s: typeof state) => unknown) => selector(state),
}));
@@ -95,14 +115,14 @@ const REGULAR_DIALOG_TESTID = "regular-task-create-dialog";
function setImproveWorkspaceActive() {
state.workspaces.activeId = "ws-improve";
state.workspaces.items = [
{ id: "ws-1", name: "Default Workspace" },
{ id: WORKSPACE_ID, name: WORKSPACE_NAME },
{ id: "ws-improve", name: "Improve Kandev" },
];
}
function resetTestState() {
state.workspaces.activeId = "ws-1";
state.workspaces.items = [{ id: "ws-1", name: "Default Workspace" }];
state.workspaces.activeId = WORKSPACE_ID;
state.workspaces.items = [{ id: WORKSPACE_ID, name: WORKSPACE_NAME }];
state.appSidebar.improveDialogOpen = false;
state.kanban.workflowId = "wf-1";
state.kanban.steps = [{ id: "s1", title: "Todo" }];
@@ -116,6 +136,7 @@ function resetTestState() {
mocks.dialogWillNavigate = false;
officeEnabled = false;
pathname = "/";
workspaceActionsRegistrations = [];
}
beforeEach(resetTestState);
@@ -255,6 +276,103 @@ describe("AppSidebarNewTaskItem row actions", () => {
});
});
describe("AppSidebarNewTaskItem sidebar-workspace-actions plugin slot", () => {
const PLUGIN_TEST_ID = "plugin-workspace-action";
const INSET_TEST_ID = "create-task-button";
function registerPlugin(Component: (props: { slotProps?: unknown }) => JSX.Element) {
workspaceActionsRegistrations = [{ registrationId: "reg-1", pluginId: "plugin-1", Component }];
}
function registerPlugins(components: Array<(props: { slotProps?: unknown }) => JSX.Element>) {
workspaceActionsRegistrations = components.map((Component, index) => ({
registrationId: `reg-${index + 1}`,
pluginId: `plugin-${index + 1}`,
Component,
}));
}
it("A1: renders a registered component after Quick Terminal and Quick Chat", () => {
registerPlugin(() => <button type="button" data-testid={PLUGIN_TEST_ID} />);
renderItem(false);
const terminal = screen.getByTestId(QUICK_TERMINAL_TEST_ID);
const quickChat = screen.getByTestId(QUICK_CHAT_TEST_ID);
const plugin = screen.getByTestId(PLUGIN_TEST_ID);
const pluginSlot = plugin.parentElement;
expect(pluginSlot?.getAttribute("data-plugin-slot")).toBe("sidebar-workspace-actions");
expect(terminal.nextElementSibling).toBe(quickChat);
expect(quickChat.nextElementSibling).toBe(pluginSlot);
});
it("A2: forwards the active workspace id and label as slotProps", () => {
let captured: unknown;
registerPlugin(({ slotProps }) => {
captured = slotProps;
return <button type="button" data-testid={PLUGIN_TEST_ID} />;
});
renderItem(false);
expect(captured).toEqual({
workspaceId: WORKSPACE_ID,
workspaceLabel: WORKSPACE_NAME,
presentation: "desktop",
});
});
it("A3: keeps the label and action cluster in one flow layout", () => {
renderItem(false);
const createTask = screen.getByTestId(INSET_TEST_ID);
expect(createTask.className).toContain("flex-1");
expect(createTask.parentElement?.className).toContain("items-center");
});
it("A3: keeps multiple plugin actions from overlapping the task label", () => {
registerPlugins([
() => <button type="button" data-testid={`${PLUGIN_TEST_ID}-one`} />,
() => <button type="button" data-testid={`${PLUGIN_TEST_ID}-two`} />,
]);
renderItem(false);
const quickChat = screen.getByTestId(QUICK_CHAT_TEST_ID);
const firstPlugin = screen.getByTestId(`${PLUGIN_TEST_ID}-one`);
const secondPlugin = screen.getByTestId(`${PLUGIN_TEST_ID}-two`);
const pluginSlot = firstPlugin.parentElement;
expect(pluginSlot).toBe(secondPlugin.parentElement);
expect(quickChat.nextElementSibling).toBe(pluginSlot);
expect(firstPlugin.nextElementSibling).toBe(secondPlugin);
});
it("A4: renders no plugin markup when the sidebar is collapsed or no workspace is active", () => {
registerPlugin(() => <button type="button" data-testid={PLUGIN_TEST_ID} />);
renderItem(true);
expect(screen.queryByTestId(PLUGIN_TEST_ID)).toBeNull();
cleanup();
state.workspaces.activeId = null;
renderItem(false);
expect(screen.queryByTestId(PLUGIN_TEST_ID)).toBeNull();
});
it("A5: a throwing plugin component leaves Quick Terminal and Quick Chat functional", () => {
registerPlugin(() => {
throw new Error("boom");
});
const consoleError = vi.spyOn(console, "error").mockImplementation(() => {});
renderItem(false);
expect(screen.queryByTestId(PLUGIN_TEST_ID)).toBeNull();
const terminal = screen.getByTestId(QUICK_TERMINAL_TEST_ID);
terminal.click();
expect(mocks.openQuickTerminal).toHaveBeenCalledOnce();
screen.getByTestId(QUICK_CHAT_TEST_ID).click();
expect(mocks.openQuickChat).toHaveBeenCalledOnce();
consoleError.mockRestore();
});
});
describe("AppSidebarNewTaskItem creation success", () => {
it("focuses the created task after regular sidebar task creation succeeds", () => {
renderItem(false);
@@ -16,6 +16,7 @@ import { IMPROVE_KANDEV_WORKSPACE_NAME } from "@/components/improve-kandev-dialo
import { linkToTask } from "@/lib/links";
import type { Task } from "@/lib/types/http";
import { subscribeNewTaskCreationRequests } from "@/lib/desktop/new-task-request";
import { AppSidebarWorkspaceActions } from "./app-sidebar-workspace-actions";
// The Office "New issue" dialog only renders on `/office` routes, but this item
// lives in the global sidebar (every page). Lazy-load it so its office-only
@@ -37,7 +38,6 @@ function useNewTaskCreationRequest(workspaceId: string | null, openDialog: () =>
}, [workspaceId, openDialog]);
}
const ROW_ACTION_INSET_CLASS = "pr-16";
type RowActionButtonProps = {
icon: TablerIcon;
label: string;
@@ -180,7 +180,6 @@ export function AppSidebarNewTaskItem({ collapsed }: AppSidebarNewTaskItemProps)
useNewTaskCreationRequest(workspaceId, handleOpenNewTask);
const canOpenRowActions = !collapsed && !!workspaceId;
const actionInsetClass = canOpenRowActions ? ROW_ACTION_INSET_CLASS : undefined;
const handleRegularTaskCreated = useCallback(
(
task: Task,
@@ -201,7 +200,7 @@ export function AppSidebarNewTaskItem({ collapsed }: AppSidebarNewTaskItemProps)
return (
<>
<div className="relative">
<div className="flex min-w-0 items-center gap-1">
<AppSidebarNavItem
icon={IconSquarePlus}
label={t("sidebar:newTask")}
@@ -209,10 +208,10 @@ export function AppSidebarNewTaskItem({ collapsed }: AppSidebarNewTaskItemProps)
collapsed={collapsed}
disabled={!workspaceId}
testId="create-task-button"
className={actionInsetClass}
className={!collapsed ? "min-w-0 flex-1" : undefined}
/>
{canOpenRowActions && (
<div className="absolute right-1.5 top-1/2 -translate-y-1/2 flex items-center gap-1 sidebar-fade-in">
<div className="flex shrink-0 items-center gap-1 sidebar-fade-in">
<RowActionButton
icon={IconTerminal2}
label={t("sidebar:quickTerminal")}
@@ -225,6 +224,11 @@ export function AppSidebarNewTaskItem({ collapsed }: AppSidebarNewTaskItemProps)
testId="sidebar-quick-chat-shortcut"
onClick={handleOpenQuickChat}
/>
<AppSidebarWorkspaceActions
workspaceId={workspaceId}
workspaceLabel={activeWorkspace?.name}
presentation="desktop"
/>
</div>
)}
</div>
@@ -0,0 +1,81 @@
"use client";
import { useMemo } from "react";
import { useTranslation } from "react-i18next";
import { PluginSlot } from "@/components/plugins/plugin-slot";
import { useAppStore } from "@/components/state-provider";
import type { SidebarWorkspaceActionsSlotProps } from "@/lib/plugins/types";
import { usePluginRegistry } from "@/lib/plugins/registry";
import { cn } from "@/lib/utils";
/**
* Props forwarded to every plugin component registered for the
* `sidebar-workspace-actions` slot (`registry.registerComponent("sidebar-workspace-actions",
* Component)`) — the sidebar's New Task row action cluster or its mobile
* navigation counterpart, alongside the built-in Quick Terminal and Quick
* Chat actions. The host keeps the workspace context and presentation shape
* stable across both surfaces, so a plugin never needs its own subscription
* just to know the active workspace.
*/
export function AppSidebarWorkspaceActions(props: {
workspaceId: string;
workspaceLabel?: string;
presentation: SidebarWorkspaceActionsSlotProps["presentation"];
}) {
const { workspaceId, workspaceLabel, presentation } = props;
const registry = usePluginRegistry();
const hasRegistrations = registry.getSlotRegistrations("sidebar-workspace-actions").length > 0;
const slotProps = useMemo<SidebarWorkspaceActionsSlotProps>(
() => ({ workspaceId, workspaceLabel, presentation }),
[presentation, workspaceId, workspaceLabel],
);
if (!hasRegistrations) return null;
return (
<div
className={cn(
"flex shrink-0 items-center",
presentation === "mobile"
? "gap-2 [&_a]:min-h-11 [&_a]:min-w-11 [&_button]:min-h-11 [&_button]:min-w-11"
: "gap-1",
)}
data-plugin-slot="sidebar-workspace-actions"
data-presentation={presentation}
>
<PluginSlot name="sidebar-workspace-actions" slotProps={slotProps} />
</div>
);
}
/**
* Shared phone navigation entry point for workspace-scoped plugin actions.
* The same slot is mounted in the kanban drawer and at the top of the shared
* app navigation sheet on other phone surfaces.
*/
export function MobileWorkspaceActionsSection({
workspaceId: providedWorkspaceId,
}: {
workspaceId?: string;
}) {
const { t } = useTranslation();
const activeWorkspaceId = useAppStore((state) => state.workspaces?.activeId ?? null);
const registry = usePluginRegistry();
const workspaceId = providedWorkspaceId ?? activeWorkspaceId;
if (!workspaceId || registry.getSlotRegistrations("sidebar-workspace-actions").length === 0) {
return null;
}
return (
<div
className="flex flex-col gap-3"
data-testid="mobile-workspace-actions"
role="group"
aria-label={t("common:workspace")}
>
<AppSidebarWorkspaceActions workspaceId={workspaceId} presentation="mobile" />
</div>
);
}
@@ -6,6 +6,7 @@ import { Checkbox } from "@kandev/ui/checkbox";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@kandev/ui/select";
import { ToggleGroup, ToggleGroupItem } from "@kandev/ui/toggle-group";
import { IconLayoutKanban, IconList, IconTimeline } from "@tabler/icons-react";
import { MobileWorkspaceActionsSection } from "@/components/app-sidebar/app-sidebar-workspace-actions";
import { AppSidebarWorkspacePicker } from "@/components/app-sidebar/app-sidebar-workspace-picker";
import {
AppNavSections,
@@ -351,6 +352,7 @@ function ResponsiveMenuSurface({
}
function MobileMenuContent({
workspaceId,
searchQuery,
onSearchChange,
isSearchLoading,
@@ -362,7 +364,7 @@ function MobileMenuContent({
navControls,
}: Pick<
MobileMenuSheetProps,
"searchQuery" | "onSearchChange" | "isSearchLoading" | "onOpenChange"
"workspaceId" | "searchQuery" | "onSearchChange" | "isSearchLoading" | "onOpenChange"
> & {
viewValue: string;
onViewChange: (value: string) => void;
@@ -390,6 +392,7 @@ function MobileMenuContent({
<AppNavSections
onNavigate={() => onOpenChange(false)}
omitSections={["primary"]}
workspaceActions={<MobileWorkspaceActionsSection workspaceId={workspaceId} />}
controls={navControls}
/>
</div>
@@ -417,6 +420,7 @@ export function MobileMenuSheet({
onOpenChange={onOpenChange}
contentRef={contentRef}
onOpenAutoFocus={focusMenu}
workspaceId={workspaceId}
searchQuery={searchQuery}
onSearchChange={onSearchChange}
isSearchLoading={isSearchLoading}
@@ -431,7 +435,7 @@ export function MobileMenuSheet({
function MobileMenuRender(
props: Pick<
MobileMenuSheetProps,
"open" | "onOpenChange" | "searchQuery" | "onSearchChange" | "isSearchLoading"
"open" | "onOpenChange" | "workspaceId" | "searchQuery" | "onSearchChange" | "isSearchLoading"
> & {
isMobile: boolean;
contentRef: RefObject<HTMLDivElement | null>;
@@ -100,6 +100,8 @@ type AppNavSectionsProps = {
* both rendered gave two identically labelled rows going to different places.
*/
omitDestinations?: string[];
/** Optional workspace-scoped plugin actions for the current phone surface. */
workspaceActions?: ReactNode;
controls: AppNavDialogControls;
};
@@ -113,11 +115,13 @@ export function AppNavSections({
onNavigate,
omitSections = [],
omitDestinations = [],
workspaceActions,
controls,
}: AppNavSectionsProps) {
const omit = new Set(omitSections);
return (
<>
{workspaceActions}
{!omit.has("primary") && (
<PrimaryNavSection onNavigate={onNavigate} omitDestinations={omitDestinations} />
)}
@@ -1,5 +1,6 @@
import { cleanup, fireEvent, render, screen } from "@testing-library/react";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import type { JSX } from "react";
import { AppNavSheet } from "./app-nav-sheet";
import { AppNavSections, useAppNavDialogs } from "./app-nav-sections";
@@ -20,6 +21,11 @@ const state = {
let healthHasIssues = false;
let statusSeverity: "none" | "unstable" | "lost" = "none";
let workspaceActionsRegistrations: Array<{
registrationId: string;
pluginId: string;
Component: (props: { slotProps?: unknown }) => JSX.Element;
}> = [];
vi.mock("@/lib/routing/client-router", () => ({
useRouter: () => ({ push: mocks.routerPush }),
@@ -35,7 +41,11 @@ vi.mock("@/hooks/use-in-office", () => ({
}));
vi.mock("@/lib/plugins/registry", () => ({
usePluginRegistry: () => ({ getNavRegistrations: () => [] }),
usePluginRegistry: () => ({
getNavRegistrations: () => [],
getSlotRegistrations: (name: string) =>
name === "sidebar-workspace-actions" ? workspaceActionsRegistrations : [],
}),
}));
vi.mock("@/hooks/use-nav-availability", () => ({
@@ -107,6 +117,7 @@ describe("AppNavSheet", () => {
beforeEach(() => {
healthHasIssues = false;
resolvedTheme = "light";
workspaceActionsRegistrations = [];
vi.clearAllMocks();
});
afterEach(cleanup);
@@ -139,12 +150,33 @@ describe("AppNavSheet", () => {
"/?home=overview&workspaceId=ws-1",
);
});
it("exposes workspace actions through the shared phone navigation sheet", () => {
let captured: unknown;
workspaceActionsRegistrations = [
{
registrationId: "workspace-action",
pluginId: "plugin-1",
Component: ({ slotProps }) => {
captured = slotProps;
return <button type="button" data-testid="mobile-workspace-action" />;
},
},
];
render(<AppNavSheet />);
fireEvent.click(screen.getByTestId("app-nav-trigger"));
expect(screen.getByTestId("mobile-workspace-action")).not.toBeNull();
expect(captured).toEqual({ workspaceId: "ws-1", presentation: "mobile" });
});
});
describe("AppNavSections", () => {
beforeEach(() => {
healthHasIssues = false;
statusSeverity = "none";
workspaceActionsRegistrations = [];
vi.clearAllMocks();
});
afterEach(cleanup);
@@ -210,6 +242,7 @@ describe("AppNavSections theme toggle", () => {
beforeEach(() => {
healthHasIssues = false;
resolvedTheme = "light";
workspaceActionsRegistrations = [];
vi.clearAllMocks();
});
afterEach(cleanup);
@@ -3,6 +3,7 @@
import { useState, type MouseEvent, type ReactNode } from "react";
import { useTranslation } from "react-i18next";
import { Sheet, SheetContent, SheetHeader, SheetTitle, SheetTrigger } from "@kandev/ui/sheet";
import { MobileWorkspaceActionsSection } from "@/components/app-sidebar/app-sidebar-workspace-actions";
import { AppNavSections, useAppNavDialogs } from "./app-nav-sections";
import { AppNavTrigger } from "./app-nav-trigger";
@@ -58,6 +59,7 @@ export function AppNavSheet({ pageNav, omitDestinations }: AppNavSheetProps) {
<AppNavSections
onNavigate={close}
omitDestinations={omitDestinations}
workspaceActions={<MobileWorkspaceActionsSection />}
controls={controls}
/>
</nav>
@@ -0,0 +1,45 @@
/**
* Mobile parity for the `sidebar-workspace-actions` slot. The desktop sidebar
* is hidden below `md`, so the shared phone navigation sheet must expose the
* same workspace action with a touch-sized target.
*/
import { expect, test } from "../../fixtures/test-base";
import { installFixturePlugin, PLUGIN_ID } from "../../helpers/plugin-fixture";
import { MobileKanbanPage } from "../../pages/mobile-kanban-page";
const SLOT_TEST_ID = "e2e-sidebar-workspace-actions";
test.describe("Mobile plugin workspace actions", () => {
test.afterEach(async ({ apiClient }) => {
await apiClient.rawRequest("DELETE", `/api/plugins/${PLUGIN_ID}`).catch(() => undefined);
});
test("exposes the workspace action in the phone navigation sheet", async ({
testPage,
seedData,
}) => {
test.setTimeout(60_000);
await installFixturePlugin(testPage);
const kanban = new MobileKanbanPage(testPage);
await kanban.goto();
await kanban.mobileMenuButton.click();
const sheet = testPage.getByRole("dialog");
const slot = sheet.getByTestId(SLOT_TEST_ID);
await expect(slot).toBeVisible({ timeout: 15_000 });
await expect(slot).toHaveAttribute("data-workspace-id", seedData.workspaceId);
await expect(slot).toHaveAttribute("data-presentation", "mobile");
const box = await slot.boundingBox();
expect(box).not.toBeNull();
expect(box!.width).toBeGreaterThanOrEqual(44);
expect(box!.height).toBeGreaterThanOrEqual(44);
await slot.tap();
await expect(slot).toHaveAttribute("data-clicked", "true");
expect(await testPage.evaluate(() => document.documentElement.scrollWidth)).toBe(
await testPage.evaluate(() => document.documentElement.clientWidth),
);
});
});
@@ -0,0 +1,94 @@
/**
* E2E: the `sidebar-workspace-actions` slot (docs/plans/plugins/PLUGIN-API.md),
* rendered in the sidebar's New Task row action cluster after the built-in
* Quick Terminal and Quick Chat icons.
*
* Uses the same real `plugin-fixture` gRPC plugin package as
* `plugin-task-panel.spec.ts` — see that file's header for how
* apps/backend/.build/kandev-plugin-e2e-1.0.0.tar.gz is built
* (`make -C apps/backend e2e-plugin-package`). The fixture's `ui/bundle.js`
* registers a `sidebar-workspace-actions` slot component — see
* apps/backend/cmd/plugin-fixture/fixture-package/ui/bundle.js.
*/
import { expect, test } from "../../fixtures/test-base";
import { installFixturePlugin, PLUGIN_ID } from "../../helpers/plugin-fixture";
import type { ApiClient } from "../../helpers/api-client";
const SLOT_TEST_ID = "e2e-sidebar-workspace-actions";
const QUICK_TERMINAL_TEST_ID = "sidebar-quick-terminal-shortcut";
const QUICK_CHAT_TEST_ID = "sidebar-quick-chat-shortcut";
async function uninstallViaApi(apiClient: ApiClient): Promise<void> {
await apiClient.rawRequest("DELETE", `/api/plugins/${PLUGIN_ID}`).catch(() => undefined);
}
test.describe("Plugins — sidebar-workspace-actions slot", () => {
test.afterEach(async ({ apiClient }) => {
await uninstallViaApi(apiClient);
});
test("renders the plugin's component after Quick Terminal and Quick Chat, with the active workspace id (A1/A2)", async ({
testPage,
seedData,
}) => {
test.setTimeout(60_000);
await installFixturePlugin(testPage);
await testPage.goto("/");
const slot = testPage.getByTestId(SLOT_TEST_ID);
await expect(slot).toBeVisible({ timeout: 15_000 });
await expect(slot).toHaveAttribute("data-workspace-id", seedData.workspaceId);
await expect(slot).toHaveAttribute("data-presentation", "desktop");
// A1: after both built-in icons, not before either of them.
const terminal = testPage.getByTestId(QUICK_TERMINAL_TEST_ID);
const quickChat = testPage.getByTestId(QUICK_CHAT_TEST_ID);
await expect(terminal).toBeVisible();
await expect(quickChat).toBeVisible();
const order = await testPage.evaluate(
([terminalId, chatId, slotId]) => {
const byTestId = (id: string) => document.querySelector(`[data-testid="${id}"]`);
const terminalEl = byTestId(terminalId);
const chatEl = byTestId(chatId);
const slotEl = byTestId(slotId);
if (!terminalEl || !chatEl || !slotEl) return null;
const position = terminalEl.compareDocumentPosition(chatEl);
const chatAfterTerminal = Boolean(position & Node.DOCUMENT_POSITION_FOLLOWING);
const slotPosition = chatEl.compareDocumentPosition(slotEl);
const slotAfterChat = Boolean(slotPosition & Node.DOCUMENT_POSITION_FOLLOWING);
return { chatAfterTerminal, slotAfterChat };
},
[QUICK_TERMINAL_TEST_ID, QUICK_CHAT_TEST_ID, SLOT_TEST_ID] as const,
);
expect(order).toEqual({ chatAfterTerminal: true, slotAfterChat: true });
});
test("no sidebar-workspace-actions markup renders when the plugin isn't installed (A1)", async ({
testPage,
}) => {
await testPage.goto("/");
await expect(testPage.getByTestId(QUICK_CHAT_TEST_ID)).toBeVisible({ timeout: 15_000 });
await expect(testPage.getByTestId(SLOT_TEST_ID)).toHaveCount(0);
});
test("disabling the plugin removes the slot markup without a reload (A1)", async ({
testPage,
}) => {
test.setTimeout(60_000);
await installFixturePlugin(testPage);
const pluginRow = testPage.getByTestId(`plugin-row-${PLUGIN_ID}`);
await testPage.goto("/");
await expect(testPage.getByTestId(SLOT_TEST_ID)).toBeVisible({ timeout: 15_000 });
await testPage.goto("/settings/plugins");
await pluginRow.getByRole("button", { name: "Disable" }).click();
await expect(pluginRow.getByText("Disabled", { exact: true })).toBeVisible({ timeout: 10_000 });
await testPage.goto("/");
await expect(testPage.getByTestId(QUICK_CHAT_TEST_ID)).toBeVisible({ timeout: 15_000 });
await expect(testPage.getByTestId(SLOT_TEST_ID)).toHaveCount(0);
});
});
@@ -16,7 +16,6 @@ import { installFixturePlugin, PLUGIN_ID } from "../../helpers/plugin-fixture";
import { SessionPage } from "../../pages/session-page";
import { KanbanPage } from "../../pages/kanban-page";
import type { ApiClient } from "../../helpers/api-client";
import { dwell } from "../../helpers/causal-waits";
const PANEL_ID = "notes";
@@ -266,59 +265,77 @@ test.describe("Plugins — task panel / kanban Edit submenu / card indicator", (
workflow_step_id: seedData.startStepId,
});
const notePath = `/api/plugins/${PLUGIN_ID}/user-state/task/${seedTask.id}/note`;
const notePathPattern = `**${notePath}`;
let firstRequestSeen = false;
let releaseFirst: () => void = () => {};
const firstHeld = new Promise<void>((resolve) => {
releaseFirst = resolve;
// Hold only the first mount read. A production E2E bundle does not replay
// effects through React Strict Mode, while a development bundle may issue
// a second read. Letting later reads continue keeps the causal stale-read
// setup valid in both modes without waiting for a dev-only request.
let firstReadHeld = false;
let releaseInitialReads: () => void = () => {};
const initialReadsHeld = new Promise<void>((resolve) => {
releaseInitialReads = resolve;
});
let signalFirstRequestStarted: () => void = () => {};
const firstRequestStarted = new Promise<void>((resolve) => {
signalFirstRequestStarted = resolve;
});
const initialRequestHandlers: Promise<void>[] = [];
await testPage.route(`**${notePath}`, async (route) => {
if (route.request().method() !== "GET" || firstRequestSeen) {
await testPage.route(notePathPattern, async (route) => {
if (route.request().method() !== "GET" || firstReadHeld) {
return route.continue();
}
firstRequestSeen = true;
await firstHeld;
// Fulfilled with canned stale content instead of passed through, so
// its body is deterministically the pre-update value even though the
// real store has since moved on.
return route.fulfill({
status: 200,
contentType: "application/json",
body: JSON.stringify({ value: "first note", updatedAt: new Date(0).toISOString() }),
firstReadHeld = true;
const handler = (async () => {
signalFirstRequestStarted();
await initialReadsHeld;
// Fulfilled with canned stale content instead of passed through, so
// its body is deterministically the pre-update value even though the
// real store has since moved on.
await route.fulfill({
status: 200,
contentType: "application/json",
body: JSON.stringify({ value: "first note", updatedAt: new Date(0).toISOString() }),
});
})();
initialRequestHandlers.push(handler);
return handler;
});
try {
await testPage.goto(`/t/${seedTask.id}`);
const session = new SessionPage(testPage);
await session.waitForLoad();
await session.addPanelButton().click();
await session.addPanelPluginItem(PLUGIN_ID, PANEL_ID).click();
// Wait until the first mount GET is held before issuing the newer write.
await firstRequestStarted;
// Subsequent reads are the real subscription refreshes. The sibling
// write now triggers one that resolves with the newer store value.
const res = await apiClient.rawRequest("PUT", notePath, {
value: "second note",
writerId: "e2e-sibling-surface",
});
});
expect(res.status).toBe(200);
await testPage.goto(`/t/${seedTask.id}`);
const session = new SessionPage(testPage);
await session.waitForLoad();
await session.addPanelButton().click();
await session.addPanelPluginItem(PLUGIN_ID, PANEL_ID).click();
const notesEditor = testPage.getByTestId("e2e-notes-panel");
await expect(notesEditor).toHaveValue("second note", { timeout: 10_000 });
// The mount's GET is held — the panel stays on its loading state, but
// its subscription (set up in the same effect) is already live.
await expect(testPage.getByTestId("e2e-notes-panel-loading")).toBeVisible();
// A sibling surface's write lands; its notification triggers a second,
// unheld refresh that resolves quickly with the real current value.
const res = await apiClient.rawRequest("PUT", notePath, {
value: "second note",
writerId: "e2e-sibling-surface",
});
expect(res.status).toBe(200);
const notesEditor = testPage.getByTestId("e2e-notes-panel");
await expect(notesEditor).toHaveValue("second note", { timeout: 10_000 });
// Now let the stale first read land — it must not revert the panel.
releaseFirst();
await dwell(
testPage,
500,
"negative-assertion",
"asserts the stale first read never reverts the panel; a value that must not be written renders nothing, so the check needs time for the late response to land and do damage",
);
await expect(notesEditor).toHaveValue("second note");
// Now let the stale mount reads land — neither may revert the panel.
// Awaiting the handlers themselves (rather than a fixed dwell) is the
// real causal signal that the stale responses have been processed.
releaseInitialReads();
await Promise.all(initialRequestHandlers);
await expect(notesEditor).toHaveValue("second note");
} finally {
releaseInitialReads();
await Promise.all(initialRequestHandlers);
await testPage.unroute(notePathPattern);
}
});
test("task-card-indicators slot renders the plugin's indicator on the kanban card (AC13)", async ({
+17 -3
View File
@@ -115,11 +115,15 @@ export interface IntegrationSettingsRegistration {
* another plugin's page and authors don't gate on the current id themselves.
* "task-card-indicators" (small icon/badge rendered beside the PR status icon
* on every kanban card — receives `{ taskId, workspaceId, workflowStepId }`
* as `slotProps`), and "task-card-tags" (its own row on every kanban card,
* as `slotProps`), "task-card-tags" (its own row on every kanban card,
* rendered below the badges row — for contributions too wide for the cramped
* title-row `task-card-indicators` spot, e.g. a row of tag chips — receives
* `TaskCardTagsSlotProps` as `slotProps`). Not a closed union — hosts may
* register additional slot names.
* `TaskCardTagsSlotProps` as `slotProps`), and "sidebar-workspace-actions"
* (icon-button cluster in the sidebar's New Task row, after the built-in
* Quick Terminal and Quick Chat actions, with the same action group exposed
* through mobile navigation — receives `SidebarWorkspaceActionsSlotProps`
* as `slotProps`). Not a closed union — hosts may register additional slot
* names.
*/
export type PluginSlotName = string;
@@ -144,6 +148,16 @@ export type TaskCardTagsSlotProps = {
workflowStepId: string | null;
};
/** Context the host forwards to every `sidebar-workspace-actions` component. */
export type SidebarWorkspaceActionsSlotProps = {
/** Active workspace for the current navigation surface. */
workspaceId: string;
/** Human-readable label of that workspace, when known. */
workspaceLabel?: string;
/** Desktop sidebar cluster or phone navigation action group. */
presentation: "desktop" | "mobile";
};
/** Component registered for a named slot; receives host-provided `slotProps`. */
export type SlotComponent = ReactType.ComponentType<{ slotProps?: unknown }>;
+8 -1
View File
@@ -629,7 +629,8 @@ interface PluginRegistry {
// "settings-nav", "chat-input-actions", "task-create-input-actions",
// "new-session-input-actions", "chat-top-bar",
// "main-top-bar", "app-status-bar-left", "app-status-bar-right",
// "plugin-settings", "task-card-indicators", and "task-card-tags".
// "plugin-settings", "task-card-indicators", "task-card-tags", and
// "sidebar-workspace-actions".
// "task-card-indicators" renders a small icon/badge beside the PR status
// icon on every kanban card and forwards
// `{ taskId, workspaceId, workflowStepId }` as `slotProps`. Not a closed
@@ -653,6 +654,12 @@ interface PluginRegistry {
// controls) and forwards `{ workspaceId, workspaceLabel, currentPage }`. It is
// the app-wide, task-agnostic counterpart to "chat-top-bar", so it carries no
// task/session ids.
// "sidebar-workspace-actions" renders icon buttons after the built-in Quick
// Terminal and Quick Chat actions in the desktop sidebar's New Task row and
// in the shared phone navigation sheet. It forwards
// `SidebarWorkspaceActionsSlotProps` as `slotProps`, with `presentation` set
// to "desktop" or "mobile". The mobile presentation must use a touch target
// of at least 44px in its active dimension.
// Resolving a session id to an agent/ACP transcript id (e.g. to key
// tokscale cost data on a session) is the plugin's job, done server-side in
// the plugin backend via the Host data API; the host only propagates ids.
+21 -14
View File
@@ -433,20 +433,21 @@ display-only until Kandev calls the plugin again to authorize it for submission.
registerComponent currently has these mounted slots. The source type is open
to strings, but an unmounted name renders nowhere.
| Slot | Mounted location | slotProps |
| ------------------------- | -------------------------------------------------------- | ---------------------------------------------------------------- |
| task-sidebar | Bottom of task-detail sidebar | none |
| settings-nav | Settings navigation tree | none |
| chat-input-actions | Task or Quick Chat composer toolbar | PluginComposerSlotProps |
| task-create-input-actions | Task creation composer toolbar | PluginComposerSlotProps |
| new-session-input-actions | New-session composer toolbar | PluginComposerSlotProps |
| chat-top-bar | Session top bar | { taskId, taskTitle?, workspaceId, activeSessionId, sessionIds } |
| main-top-bar | Home/Kanban/Tasks top bar | { workspaceId, workspaceLabel?, currentPage } |
| app-status-bar-left | Left side of desktop status bar or mobile status drawer | AppStatusBarSlotProps |
| app-status-bar-right | Right side of desktop status bar or mobile status drawer | AppStatusBarSlotProps |
| plugin-settings | Top of this plugin's Settings > Plugins page | { pluginId, status }; owner-scoped to the plugin being viewed |
| task-card-indicators | Kanban card, beside the PR status icon | { taskId, workspaceId, workflowStepId } |
| task-card-tags | Kanban card, its own row below the badges row | { taskId, workspaceId, workflowStepId } |
| Slot | Mounted location | slotProps |
| ------------------------- | --------------------------------------------------------- | ---------------------------------------------------------------- |
| task-sidebar | Bottom of task-detail sidebar | none |
| settings-nav | Settings navigation tree | none |
| chat-input-actions | Task or Quick Chat composer toolbar | PluginComposerSlotProps |
| task-create-input-actions | Task creation composer toolbar | PluginComposerSlotProps |
| new-session-input-actions | New-session composer toolbar | PluginComposerSlotProps |
| chat-top-bar | Session top bar | { taskId, taskTitle?, workspaceId, activeSessionId, sessionIds } |
| main-top-bar | Home/Kanban/Tasks top bar | { workspaceId, workspaceLabel?, currentPage } |
| app-status-bar-left | Left side of desktop status bar or mobile status drawer | AppStatusBarSlotProps |
| app-status-bar-right | Right side of desktop status bar or mobile status drawer | AppStatusBarSlotProps |
| plugin-settings | Top of this plugin's Settings > Plugins page | { pluginId, status }; owner-scoped to the plugin being viewed |
| task-card-indicators | Kanban card, beside the PR status icon | { taskId, workspaceId, workflowStepId } |
| task-card-tags | Kanban card, its own row below the badges row | { taskId, workspaceId, workflowStepId } |
| sidebar-workspace-actions | Desktop New Task row or phone navigation action group, after Quick Terminal and Quick Chat | SidebarWorkspaceActionsSlotProps |
AppStatusBarSlotProps is { placement, presentation, density, pathname,
activeWorkspaceId, activeTaskId, activeSessionId }. Desktop presentation is a
@@ -454,6 +455,12 @@ compact 24px bar; mobile presentation is an in-flow drawer, so render a
touch-usable row. Status items can be reordered by the host; plugins do not get
an ordering API.
`SidebarWorkspaceActionsSlotProps` is `{ workspaceId, workspaceLabel?,
presentation }`. The host uses `presentation: "desktop"` for the compact
sidebar cluster and `presentation: "mobile"` for the phone navigation sheet.
Mobile actions must keep their own buttons or links at least 44px in the active
dimension and provide an accessible name.
`PluginComposerSlotProps` is `{ surface, presentation, taskId, taskTitle?,
activeSessionId, sessionIds, disabled, submittable, disabledReason?, composer }`.
The `composer` capability provides `insertText`, `focus`, and asynchronous
+27
View File
@@ -758,6 +758,12 @@ C)` renders `C` beside the PR status icon on every kanban card, receiving
kanban card (below the badges row), receiving the same
`{ taskId, workspaceId, workflowStepId }` shape — for a contribution too wide
for the cramped title-row `task-card-indicators` spot, e.g. a row of tag chips.
- **Sidebar workspace actions:** `registerComponent("sidebar-workspace-actions", C)`
renders `C` after Quick Terminal/Quick Chat in the desktop sidebar's New Task
row and in the shared phone navigation sheet, forwarding
`{ workspaceId, workspaceLabel?, presentation }`. The host uses
`presentation: "desktop"` or `"mobile"`; mobile actions must expose a
touch-sized, accessible control.
- **`host.storage`:** authenticated, per-user key/value storage
(`get`/`set`/`delete`/`list`/`subscribe`), backed by the `plugin_user_state`
table (separate from the plugin-backend-only `plugin_state` table — no gRPC/proto
@@ -1099,6 +1105,27 @@ complete.
slot components (e.g. `"task-card-indicators"`) still render, isolated by
the existing per-registration error boundary.
- **GIVEN** a plugin registers a component for `"sidebar-workspace-actions"`,
**WHEN** the sidebar's New Task row renders with the rail expanded and a
workspace active, **THEN** that component mounts in the row's action
cluster after the built-in Quick Terminal and Quick Chat icons, receiving
`{ workspaceId, workspaceLabel, presentation: "desktop" }` for the active
workspace, and the flex row keeps the label and every registered action
reachable without overlap.
**GIVEN** no plugin is registered for the slot, **WHEN** the row renders,
**THEN** no plugin action markup or extra row spacing appears. **GIVEN** the
desktop rail is collapsed or no workspace is active, **WHEN** the desktop
row renders, **THEN** no `"sidebar-workspace-actions"` markup renders,
matching the built-in icons' own visibility. **GIVEN** a
`"sidebar-workspace-actions"`
component throws during render, **WHEN** the row renders, **THEN** Quick
Terminal and Quick Chat still render and function, isolated by the existing
per-registration error boundary.
**GIVEN** the same plugin is active on a phone, **WHEN** the shared navigation
sheet opens, **THEN** the component mounts with
`presentation: "mobile"` and its control remains reachable with a 44px
touch target.
## Out of scope
- **Remote / operator-hosted plugin tier.** The earlier `base_url` registration model,