Expand plugin host surface (#5205)

## Thinking Path

> - Paperclip orchestrates AI agents for zero-human companies
> - The plugin system is the extension boundary for optional product
capabilities
> - Rich plugins need more than a worker entrypoint: they need scoped
database storage, local project folders, managed agents/routines, host
navigation, and reusable UI components
> - The LLM Wiki work exposed those missing host surfaces while keeping
plugin code outside the core control plane
> - This pull request expands the core plugin host, SDK, server APIs,
and UI bridge so plugins can declare and use those surfaces
> - The benefit is that future plugins can integrate with Paperclip
through documented, validated contracts instead of bespoke server or UI
imports

## What Changed

- Added plugin-managed database namespaces and migration tracking,
including Drizzle schema/migration files and SQL validation for
namespace isolation.
- Added server support for plugin local folders, managed agents, managed
routines, scoped plugin APIs, and plugin operation visibility.
- Expanded shared plugin manifest/types/validators and SDK
host/testing/UI exports for richer plugin surfaces.
- Added reusable UI pieces for file trees, managed routines, resizable
sidebars, route sidebars, and plugin bridge initialization.
- Updated plugin docs and example plugins to use the expanded host and
SDK surface.

## Verification

- `pnpm install --frozen-lockfile`
- `pnpm run preflight:workspace-links && pnpm exec vitest run
packages/shared/src/validators/plugin.test.ts
server/src/__tests__/plugin-database.test.ts
server/src/__tests__/plugin-local-folders.test.ts
server/src/__tests__/plugin-managed-agents.test.ts
server/src/__tests__/plugin-managed-routines.test.ts
server/src/__tests__/plugin-orchestration-apis.test.ts
ui/src/api/plugins.test.ts ui/src/components/FileTree.test.tsx
ui/src/components/ResizableSidebarPane.test.tsx
ui/src/pages/PluginPage.test.tsx ui/src/plugins/bridge.test.ts` passed:
11 files, 67 tests.
- Confirmed this PR changes 89 files and does not include
`pnpm-lock.yaml` or `.github/workflows/*`.

## Risks

- Medium: this expands plugin host contracts across db/shared/server/ui
and includes a new core migration (`0076_useful_elektra.sql`).
- The plugin database namespace validator is intentionally restrictive;
plugin authors may need follow-up affordances for SQL patterns that
remain blocked.
- Merge this before the LLM Wiki plugin PR so the plugin can resolve the
new SDK and host APIs.

> 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

- OpenAI Codex, GPT-5 coding agent, tool-enabled shell/git/GitHub
workflow. Context window size was not exposed by the runtime.

## 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 run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] If this change affects the UI, I have included before/after
screenshots
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [x] I will address all Greptile and reviewer comments before
requesting merge

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
This commit is contained in:
Dotta 2026-05-05 07:42:57 -05:00 committed by GitHub
parent d6bee62f02
commit 3c73ed26b5
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
89 changed files with 27516 additions and 914 deletions

View file

@ -7,7 +7,6 @@ import { queryKeys } from "@/lib/queryKeys";
import { useCompany } from "@/context/CompanyContext";
import { useSidebar } from "@/context/SidebarContext";
import { SidebarNavItem } from "./SidebarNavItem";
import { SidebarCompanyMenu } from "./SidebarCompanyMenu";
export function CompanySettingsSidebar() {
const { selectedCompany, selectedCompanyId } = useCompany();
@ -32,11 +31,8 @@ export function CompanySettingsSidebar() {
});
return (
<aside className="w-60 h-full min-h-0 border-r border-border bg-background flex flex-col">
<div className="flex items-center gap-1 px-3 h-12 shrink-0">
<SidebarCompanyMenu />
</div>
<div className="flex flex-col gap-1 px-3 pb-3 shrink-0">
<aside className="w-full h-full min-h-0 border-r border-border bg-background flex flex-col">
<div className="flex flex-col gap-1 px-3 py-3 shrink-0">
<Link
to="/dashboard"
onClick={() => {

View file

@ -0,0 +1,190 @@
// @vitest-environment jsdom
import { act } from "react";
import { createRoot, type Root } from "react-dom/client";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { FileTree, buildFileTree } from "./FileTree";
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(globalThis as any).IS_REACT_ACT_ENVIRONMENT = true;
describe("FileTree", () => {
let container: HTMLDivElement;
let root: Root;
beforeEach(() => {
container = document.createElement("div");
document.body.appendChild(container);
root = createRoot(container);
});
afterEach(() => {
act(() => {
root.unmount();
});
container.remove();
});
function row(path: string) {
return container.querySelector(`[data-file-tree-path="${path}"]`) as HTMLDivElement | null;
}
it("selects file rows and expands directory rows", () => {
const onSelectFile = vi.fn();
const onToggleDir = vi.fn();
const nodes = buildFileTree({
"README.md": "",
"docs/guide.md": "",
});
act(() => {
root.render(
<FileTree
nodes={nodes}
selectedFile="README.md"
expandedDirs={new Set(["docs"])}
onSelectFile={onSelectFile}
onToggleDir={onToggleDir}
/>,
);
});
expect(row("README.md")?.getAttribute("aria-selected")).toBe("true");
act(() => {
row("docs/guide.md")?.click();
});
expect(onSelectFile).toHaveBeenCalledWith("docs/guide.md");
act(() => {
row("docs")?.click();
});
expect(onToggleDir).toHaveBeenCalledWith("docs");
});
it("marks partially selected directories as indeterminate", () => {
const nodes = buildFileTree({
"docs/a.md": "",
"docs/b.md": "",
});
act(() => {
root.render(
<FileTree
nodes={nodes}
selectedFile={null}
expandedDirs={new Set(["docs"])}
checkedFiles={new Set(["docs/a.md"])}
onSelectFile={() => {}}
onToggleDir={() => {}}
onToggleCheck={() => {}}
/>,
);
});
const input = row("docs")?.querySelector("input[type='checkbox']") as HTMLInputElement | null;
expect(input?.checked).toBe(false);
expect(input?.indeterminate).toBe(true);
expect(row("docs")?.getAttribute("aria-checked")).toBe("mixed");
});
it("renders file badges and host-only file extras", () => {
const nodes = buildFileTree({
"wiki/very-long-page-slug.md": "",
});
act(() => {
root.render(
<FileTree
nodes={nodes}
selectedFile={null}
expandedDirs={new Set(["wiki"])}
onSelectFile={() => {}}
onToggleDir={() => {}}
fileBadges={{
"wiki/very-long-page-slug.md": {
label: "fresh",
status: "ok",
tooltip: "Synced",
},
}}
renderFileExtra={(node) => (
node.kind === "file" ? <span data-testid="file-extra">{node.name.length} chars</span> : null
)}
/>,
);
});
expect(container.textContent).toContain("fresh");
expect(container.querySelector("[title='Synced']")).not.toBeNull();
expect(container.querySelector("[data-testid='file-extra']")?.textContent).toBe("22 chars");
});
it("wraps long labels by default and can opt back into truncation", () => {
const nodes = buildFileTree({
"wiki/extremely-long-page-slug-that-wraps-on-mobile.md": "",
});
act(() => {
root.render(
<FileTree
nodes={nodes}
selectedFile={null}
expandedDirs={new Set(["wiki"])}
onSelectFile={() => {}}
onToggleDir={() => {}}
/>,
);
});
expect(row("wiki/extremely-long-page-slug-that-wraps-on-mobile.md")?.innerHTML).toContain("break-all");
act(() => {
root.render(
<FileTree
nodes={nodes}
selectedFile={null}
expandedDirs={new Set(["wiki"])}
onSelectFile={() => {}}
onToggleDir={() => {}}
wrapLabels={false}
/>,
);
});
expect(row("wiki/extremely-long-page-slug-that-wraps-on-mobile.md")?.innerHTML).toContain("truncate");
});
it("supports tree keyboard expansion and checkbox toggling", () => {
const onToggleDir = vi.fn();
const onToggleCheck = vi.fn();
const nodes = buildFileTree({
"docs/a.md": "",
});
act(() => {
root.render(
<FileTree
nodes={nodes}
selectedFile={null}
expandedDirs={new Set()}
onSelectFile={() => {}}
onToggleDir={onToggleDir}
onToggleCheck={onToggleCheck}
/>,
);
});
const docsRow = row("docs");
act(() => {
docsRow?.focus();
docsRow?.dispatchEvent(new KeyboardEvent("keydown", { key: "ArrowRight", bubbles: true }));
});
expect(onToggleDir).toHaveBeenCalledWith("docs");
act(() => {
docsRow?.dispatchEvent(new KeyboardEvent("keydown", { key: " ", bubbles: true }));
});
expect(onToggleCheck).toHaveBeenCalledWith("docs", "dir");
});
});

View file

@ -0,0 +1,500 @@
import type { KeyboardEvent, ReactNode } from "react";
import { useMemo, useRef, useState } from "react";
import { cn } from "../lib/utils";
import {
ChevronDown,
ChevronRight,
FileCode2,
FileText,
Folder,
FolderOpen,
} from "lucide-react";
import { statusBadge, statusBadgeDefault } from "../lib/status-colors";
import { Button } from "./ui/button";
import { Skeleton } from "./ui/skeleton";
// -- Tree types --------------------------------------------------------------
export type FileTreeNode = {
name: string;
path: string;
kind: "dir" | "file";
children: FileTreeNode[];
/** Optional per-node metadata (e.g. import action) */
action?: string | null;
};
export type FileTreeBadgeVariant = "ok" | "warning" | "error" | "info" | "pending";
export type FileTreeBadge = {
label: string;
status: FileTreeBadgeVariant;
tooltip?: string;
};
export type FileTreeTone = "default" | "warning" | "error" | "muted";
export type FileTreeEmptyState = {
title?: string;
description?: string;
};
export type FileTreeErrorState = {
message: string;
retry?: () => void;
};
type VisibleFileTreeNode = {
node: FileTreeNode;
depth: number;
};
const TREE_BASE_INDENT = 16;
const TREE_STEP_INDENT = 24;
const TREE_ROW_HEIGHT_CLASS = "min-h-9";
const fileTreeToneClass: Record<FileTreeTone, string | undefined> = {
default: undefined,
warning: "bg-amber-500/5 text-amber-700 dark:text-amber-300",
error: "bg-destructive/5 text-destructive",
muted: "opacity-50",
};
// -- Helpers -----------------------------------------------------------------
export function buildFileTree(
files: Record<string, unknown>,
actionMap?: Map<string, string>,
): FileTreeNode[] {
const root: FileTreeNode = { name: "", path: "", kind: "dir", children: [] };
for (const filePath of Object.keys(files)) {
const segments = filePath.split("/").filter(Boolean);
let current = root;
let currentPath = "";
for (let i = 0; i < segments.length; i++) {
const segment = segments[i];
currentPath = currentPath ? `${currentPath}/${segment}` : segment;
const isLeaf = i === segments.length - 1;
let next = current.children.find((c) => c.name === segment);
if (!next) {
next = {
name: segment,
path: currentPath,
kind: isLeaf ? "file" : "dir",
children: [],
action: isLeaf ? (actionMap?.get(filePath) ?? null) : null,
};
current.children.push(next);
}
current = next;
}
}
function sortNode(node: FileTreeNode) {
node.children.sort((a, b) => {
// Files before directories so PROJECT.md appears above tasks/
if (a.kind !== b.kind) return a.kind === "file" ? -1 : 1;
return a.name.localeCompare(b.name);
});
node.children.forEach(sortNode);
}
sortNode(root);
return root.children;
}
export function countFiles(nodes: FileTreeNode[]): number {
let count = 0;
for (const node of nodes) {
if (node.kind === "file") count++;
else count += countFiles(node.children);
}
return count;
}
export function collectAllPaths(
nodes: FileTreeNode[],
type: "file" | "dir" | "all" = "all",
): Set<string> {
const paths = new Set<string>();
for (const node of nodes) {
if (type === "all" || node.kind === type) paths.add(node.path);
for (const p of collectAllPaths(node.children, type)) paths.add(p);
}
return paths;
}
function fileIcon(name: string) {
if (name.endsWith(".yaml") || name.endsWith(".yml")) return FileCode2;
return FileText;
}
function flattenVisibleNodes(
nodes: FileTreeNode[],
expandedDirs: Set<string>,
depth = 0,
): VisibleFileTreeNode[] {
const flattened: VisibleFileTreeNode[] = [];
for (const node of nodes) {
flattened.push({ node, depth });
if (node.kind === "dir" && expandedDirs.has(node.path)) {
flattened.push(...flattenVisibleNodes(node.children, expandedDirs, depth + 1));
}
}
return flattened;
}
function checkboxState(node: FileTreeNode, checkedFiles: Set<string>) {
if (node.kind === "file") {
return {
allChecked: checkedFiles.has(node.path),
someChecked: false,
};
}
const childFiles = collectAllPaths(node.children, "file");
const childFilePaths = [...childFiles];
const allChecked = childFilePaths.length > 0 && childFilePaths.every((p) => checkedFiles.has(p));
const someChecked = childFilePaths.some((p) => checkedFiles.has(p));
return { allChecked, someChecked: someChecked && !allChecked };
}
// -- Frontmatter helpers -----------------------------------------------------
export type FrontmatterData = Record<string, string | string[]>;
export function parseFrontmatter(content: string): { data: FrontmatterData; body: string } | null {
const match = content.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/);
if (!match) return null;
const data: FrontmatterData = {};
const rawYaml = match[1];
const body = match[2];
let currentKey: string | null = null;
let currentList: string[] | null = null;
for (const line of rawYaml.split("\n")) {
const trimmed = line.trim();
if (!trimmed || trimmed.startsWith("#")) continue;
if (trimmed.startsWith("- ") && currentKey) {
if (!currentList) currentList = [];
currentList.push(trimmed.slice(2).trim().replace(/^["']|["']$/g, ""));
continue;
}
if (currentKey && currentList) {
data[currentKey] = currentList;
currentList = null;
currentKey = null;
}
const kvMatch = trimmed.match(/^([a-zA-Z_][\w-]*)\s*:\s*(.*)$/);
if (kvMatch) {
const key = kvMatch[1];
const val = kvMatch[2].trim().replace(/^["']|["']$/g, "");
if (val === "null") {
currentKey = null;
continue;
}
if (val) {
data[key] = val;
currentKey = null;
} else {
currentKey = key;
}
}
}
if (currentKey && currentList) {
data[currentKey] = currentList;
}
return Object.keys(data).length > 0 ? { data, body } : null;
}
export const FRONTMATTER_FIELD_LABELS: Record<string, string> = {
name: "Name",
title: "Title",
kind: "Kind",
reportsTo: "Reports to",
skills: "Skills",
status: "Status",
description: "Description",
priority: "Priority",
assignee: "Assignee",
project: "Project",
recurring: "Recurring",
targetDate: "Target date",
};
// -- File tree component -----------------------------------------------------
export type FileTreeProps = {
nodes: FileTreeNode[];
selectedFile: string | null;
expandedDirs: Set<string>;
checkedFiles?: Set<string>;
onToggleDir: (path: string) => void;
onSelectFile: (path: string) => void;
onToggleCheck?: (path: string, kind: "file" | "dir") => void;
/** Serializable badge metadata keyed by path. This is safe to expose through plugin UI contracts. */
fileBadges?: Record<string, FileTreeBadge | undefined>;
/** Closed row tone metadata keyed by path. This avoids raw host class names in public contracts. */
fileTones?: Record<string, FileTreeTone | undefined>;
/** Internal-only escape hatch for current host call sites that need richer row content. */
renderFileExtra?: (node: FileTreeNode, checked: boolean) => ReactNode;
/** @deprecated Use fileTones for public surfaces. Kept for compatibility with host-only callers. */
fileRowClassName?: (node: FileTreeNode, checked: boolean) => string | undefined;
showCheckboxes?: boolean;
/** Allow long file and directory names to wrap instead of forcing horizontal overflow. */
wrapLabels?: boolean;
loading?: boolean;
error?: FileTreeErrorState | null;
empty?: FileTreeEmptyState;
ariaLabel?: string;
};
export function FileTree({
nodes,
selectedFile,
expandedDirs,
checkedFiles,
onToggleDir,
onSelectFile,
onToggleCheck,
fileBadges,
fileTones,
renderFileExtra,
fileRowClassName,
showCheckboxes = true,
wrapLabels = true,
loading = false,
error,
empty,
ariaLabel = "Files",
}: FileTreeProps) {
const effectiveCheckedFiles = checkedFiles ?? new Set<string>();
const visibleNodes = useMemo(
() => flattenVisibleNodes(nodes, expandedDirs),
[expandedDirs, nodes],
);
const [focusedPath, setFocusedPath] = useState<string | null>(null);
const rowRefs = useRef(new Map<string, HTMLDivElement>());
function focusPath(path: string) {
setFocusedPath(path);
window.requestAnimationFrame(() => {
rowRefs.current.get(path)?.focus();
});
}
function toggleNode(node: FileTreeNode) {
if (node.kind === "dir") onToggleDir(node.path);
else onSelectFile(node.path);
}
function handleRowKeyDown(event: KeyboardEvent<HTMLDivElement>, index: number, node: FileTreeNode) {
switch (event.key) {
case "ArrowDown": {
event.preventDefault();
const next = visibleNodes[Math.min(index + 1, visibleNodes.length - 1)];
if (next) focusPath(next.node.path);
break;
}
case "ArrowUp": {
event.preventDefault();
const previous = visibleNodes[Math.max(index - 1, 0)];
if (previous) focusPath(previous.node.path);
break;
}
case "ArrowRight":
if (node.kind === "dir" && !expandedDirs.has(node.path)) {
event.preventDefault();
onToggleDir(node.path);
}
break;
case "ArrowLeft":
if (node.kind === "dir" && expandedDirs.has(node.path)) {
event.preventDefault();
onToggleDir(node.path);
}
break;
case "Enter":
event.preventDefault();
toggleNode(node);
break;
case " ":
if (showCheckboxes && onToggleCheck) {
event.preventDefault();
onToggleCheck(node.path, node.kind);
}
break;
}
}
if (loading) {
return (
<div aria-busy="true" aria-label={ariaLabel} role="tree" className="py-1">
{[0, 1, 2, 3].map((row) => (
<div key={row} className={cn("flex items-center gap-2 px-4", TREE_ROW_HEIGHT_CLASS)}>
<Skeleton className="h-4 w-4 shrink-0 rounded-sm" />
<Skeleton className={cn("h-3.5", row === 1 ? "w-3/5" : "w-4/5")} />
</div>
))}
</div>
);
}
if (error) {
return (
<div aria-label={ariaLabel} role="tree" className="p-3">
<div
role="treeitem"
aria-level={1}
className="flex min-h-9 items-center justify-between gap-3 rounded-md border border-destructive/30 bg-destructive/5 px-3 py-2 text-sm"
>
<div className="flex min-w-0 items-center gap-2">
<span
className={cn(
"inline-flex shrink-0 items-center rounded-full px-2.5 py-0.5 text-xs font-medium whitespace-nowrap",
statusBadge.error ?? statusBadgeDefault,
)}
>
error
</span>
<span className="min-w-0 text-destructive">{error.message}</span>
</div>
{error.retry && (
<Button type="button" size="xs" variant="outline" onClick={error.retry}>
Retry
</Button>
)}
</div>
</div>
);
}
if (nodes.length === 0) {
return (
<div aria-label={ariaLabel} role="tree" className="p-3">
<div className="rounded-md border border-dashed border-border px-4 py-8 text-center">
<div className="text-sm font-medium">{empty?.title ?? "No files"}</div>
<div className="mt-1 text-xs text-muted-foreground">
{empty?.description ?? "Files will appear here when they are available."}
</div>
</div>
</div>
);
}
return (
<div aria-label={ariaLabel} role="tree">
{visibleNodes.map(({ node, depth }, index) => {
const expanded = node.kind === "dir" && expandedDirs.has(node.path);
const { allChecked, someChecked } = checkboxState(node, effectiveCheckedFiles);
const badge = fileBadges?.[node.path];
const tone = fileTones?.[node.path] ?? "default";
const extraClassName = node.kind === "file" ? fileRowClassName?.(node, allChecked) : undefined;
const FileIcon = node.kind === "file" ? fileIcon(node.name) : null;
const isSelected = node.kind === "file" && node.path === selectedFile;
return (
<div
key={node.path}
ref={(element) => {
if (element) rowRefs.current.set(node.path, element);
else rowRefs.current.delete(node.path);
}}
role="treeitem"
aria-level={depth + 1}
aria-expanded={node.kind === "dir" ? expanded : undefined}
aria-selected={node.kind === "file" ? isSelected : undefined}
aria-checked={showCheckboxes ? (someChecked ? "mixed" : allChecked) : undefined}
tabIndex={(focusedPath ?? visibleNodes[0]?.node.path) === node.path ? 0 : -1}
className={cn(
node.kind === "dir"
? showCheckboxes
? "group grid w-full grid-cols-[auto_minmax(0,1fr)_2.25rem] items-center gap-x-1 pr-3 text-left text-sm text-muted-foreground hover:bg-accent/30 hover:text-foreground"
: "group grid w-full grid-cols-[minmax(0,1fr)_2.25rem] items-center gap-x-1 pr-3 text-left text-sm text-muted-foreground hover:bg-accent/30 hover:text-foreground max-[480px]:grid-cols-[minmax(0,1fr)]"
: "group flex w-full items-center gap-1 pr-3 text-left text-sm text-muted-foreground hover:bg-accent/30 hover:text-foreground cursor-pointer",
TREE_ROW_HEIGHT_CLASS,
isSelected && "text-foreground bg-accent/20",
fileTreeToneClass[tone],
extraClassName,
"outline-none focus-visible:ring-2 focus-visible:ring-ring/50 focus-visible:ring-inset",
)}
style={{
paddingInlineStart: `${TREE_BASE_INDENT + depth * TREE_STEP_INDENT - 8}px`,
}}
onFocus={() => setFocusedPath(node.path)}
onClick={() => toggleNode(node)}
onKeyDown={(event) => handleRowKeyDown(event, index, node)}
data-file-tree-path={node.path}
>
{showCheckboxes && (
<label className="flex items-center pl-2" onClick={(event) => event.stopPropagation()}>
<input
type="checkbox"
checked={allChecked}
ref={(element) => {
if (element) element.indeterminate = someChecked;
}}
onChange={() => onToggleCheck?.(node.path, node.kind)}
className="mr-2 accent-foreground"
/>
</label>
)}
<span className="flex min-w-0 flex-1 items-center gap-2 py-1 text-left">
<span className="flex h-4 w-4 shrink-0 items-center justify-center">
{node.kind === "dir" ? (
expanded ? (
<FolderOpen className="h-3.5 w-3.5" />
) : (
<Folder className="h-3.5 w-3.5" />
)
) : FileIcon ? (
<FileIcon className="h-3.5 w-3.5" />
) : null}
</span>
<span className={cn("min-w-0", wrapLabels ? "break-all leading-4" : "truncate")}>
{node.name}
</span>
</span>
{badge && (
<span
className={cn(
"ml-3 shrink-0 rounded-full px-2 py-0.5 text-[10px] font-medium uppercase tracking-wide",
statusBadge[badge.status] ?? statusBadgeDefault,
)}
title={badge.tooltip}
>
{badge.label}
</span>
)}
{node.kind === "file" && renderFileExtra?.(node, allChecked)}
{node.kind === "dir" && (
<button
type="button"
className="flex h-9 w-9 items-center justify-center self-center rounded-sm text-muted-foreground opacity-70 transition-[background-color,color,opacity] hover:bg-accent hover:text-foreground group-hover:opacity-100 focus-visible:ring-2 focus-visible:ring-ring/50 max-[480px]:hidden"
onClick={(event) => {
event.stopPropagation();
onToggleDir(node.path);
}}
aria-label={expanded ? `Collapse ${node.name}` : `Expand ${node.name}`}
>
{expanded ? (
<ChevronDown className="h-3.5 w-3.5" />
) : (
<ChevronRight className="h-3.5 w-3.5" />
)}
</button>
)}
</div>
);
})}
</div>
);
}

View file

@ -5,7 +5,6 @@ import { pluginsApi } from "@/api/plugins";
import { queryKeys } from "@/lib/queryKeys";
import { SIDEBAR_SCROLL_RESET_STATE } from "@/lib/navigation-scroll";
import { SidebarNavItem } from "./SidebarNavItem";
import { SidebarCompanyMenu } from "./SidebarCompanyMenu";
export function InstanceSidebar() {
const { data: plugins } = useQuery({
@ -14,13 +13,12 @@ export function InstanceSidebar() {
});
return (
<aside className="w-60 h-full min-h-0 border-r border-border bg-background flex flex-col">
<div className="flex items-center gap-1 px-3 h-12 shrink-0">
<SidebarCompanyMenu />
</div>
<div className="flex items-center gap-2 px-5 pb-3 shrink-0">
<Settings className="h-4 w-4 text-muted-foreground shrink-0" />
<span className="flex-1 truncate text-sm font-bold text-foreground">Instance Settings</span>
<aside className="w-full h-full min-h-0 border-r border-border bg-background flex flex-col">
<div className="flex items-center gap-2 px-3 h-12 shrink-0">
<Settings className="h-4 w-4 text-muted-foreground shrink-0 ml-1" />
<span className="flex-1 text-sm font-bold text-foreground truncate">
Instance Settings
</span>
</div>
<nav className="flex-1 min-h-0 overflow-y-auto scrollbar-auto-hide flex flex-col gap-4 px-3 py-2">

View file

@ -17,6 +17,16 @@ const mockInstanceSettingsApi = vi.hoisted(() => ({
const mockNavigate = vi.hoisted(() => vi.fn());
const mockSetSelectedCompanyId = vi.hoisted(() => vi.fn());
const mockSetSidebarOpen = vi.hoisted(() => vi.fn());
const mockCompanyState = vi.hoisted(() => ({
companies: [{ id: "company-1", issuePrefix: "PAP", name: "Paperclip" }],
selectedCompany: { id: "company-1", issuePrefix: "PAP", name: "Paperclip" },
selectedCompanyId: "company-1",
}));
const mockPluginSlots = vi.hoisted(() => ({
slots: [] as Array<Record<string, unknown>>,
}));
const mockUsePluginSlots = vi.hoisted(() => vi.fn());
const mockPluginSlotContexts = vi.hoisted(() => [] as Array<Record<string, unknown>>);
let currentPathname = "/PAP/dashboard";
vi.mock("@/lib/router", () => ({
@ -24,7 +34,10 @@ vi.mock("@/lib/router", () => ({
useLocation: () => ({ pathname: currentPathname, search: "", hash: "", state: null }),
useNavigate: () => mockNavigate,
useNavigationType: () => "PUSH",
useParams: () => ({ companyPrefix: "PAP" }),
useParams: () => {
const firstSegment = currentPathname.split("/").filter(Boolean)[0];
return { companyPrefix: firstSegment === "instance" ? undefined : firstSegment ?? "PAP" };
},
}));
vi.mock("./CompanyRail", () => ({
@ -95,6 +108,33 @@ vi.mock("./SidebarAccountMenu", () => ({
SidebarAccountMenu: () => <div>Account menu</div>,
}));
vi.mock("../plugins/slots", async () => {
const actual = await vi.importActual<typeof import("../plugins/slots")>("../plugins/slots");
return {
resolveRouteSidebarSlot: actual.resolveRouteSidebarSlot,
usePluginSlots: (params: Record<string, unknown>) => {
mockUsePluginSlots(params);
return {
slots: mockPluginSlots.slots,
isLoading: false,
errorMessage: null,
};
},
PluginSlotMount: ({
slot,
context,
className,
}: {
slot: { displayName: string };
context: Record<string, unknown>;
className?: string;
}) => {
mockPluginSlotContexts.push(context);
return <div data-plugin-slot-class={className}>Plugin route sidebar: {slot.displayName}</div>;
},
};
});
vi.mock("../context/DialogContext", () => ({
useDialog: () => ({
openNewIssue: vi.fn(),
@ -114,10 +154,10 @@ vi.mock("../context/PanelContext", () => ({
vi.mock("../context/CompanyContext", () => ({
useCompany: () => ({
companies: [{ id: "company-1", issuePrefix: "PAP", name: "Paperclip" }],
companies: mockCompanyState.companies,
loading: false,
selectedCompany: { id: "company-1", issuePrefix: "PAP", name: "Paperclip" },
selectedCompanyId: "company-1",
selectedCompany: mockCompanyState.selectedCompany,
selectedCompanyId: mockCompanyState.selectedCompanyId,
selectionSource: "manual",
setSelectedCompanyId: mockSetSelectedCompanyId,
}),
@ -179,6 +219,9 @@ describe("Layout", () => {
container = document.createElement("div");
document.body.appendChild(container);
currentPathname = "/PAP/dashboard";
mockCompanyState.companies = [{ id: "company-1", issuePrefix: "PAP", name: "Paperclip" }];
mockCompanyState.selectedCompany = { id: "company-1", issuePrefix: "PAP", name: "Paperclip" };
mockCompanyState.selectedCompanyId = "company-1";
mockHealthApi.get.mockResolvedValue({
status: "ok",
deploymentMode: "authenticated",
@ -188,6 +231,8 @@ describe("Layout", () => {
mockInstanceSettingsApi.getGeneral.mockResolvedValue({
keyboardShortcuts: false,
});
mockPluginSlots.slots = [];
mockPluginSlotContexts.length = 0;
});
afterEach(() => {
@ -227,6 +272,30 @@ describe("Layout", () => {
it("renders the company settings sidebar on company settings routes", async () => {
currentPathname = "/PAP/company/settings/access";
mockPluginSlots.slots = [
{
type: "page",
id: "company-page",
displayName: "Company Page",
exportName: "CompanyPage",
routePath: "company",
pluginId: "plugin-1",
pluginKey: "fake-plugin",
pluginDisplayName: "Fake Plugin",
pluginVersion: "1.0.0",
},
{
type: "routeSidebar",
id: "company-sidebar",
displayName: "Company Route Sidebar",
exportName: "CompanySidebar",
routePath: "company",
pluginId: "plugin-1",
pluginKey: "fake-plugin",
pluginDisplayName: "Fake Plugin",
pluginVersion: "1.0.0",
},
];
const root = createRoot(container);
const queryClient = new QueryClient({
defaultOptions: { queries: { retry: false } },
@ -245,6 +314,213 @@ describe("Layout", () => {
expect(container.textContent).toContain("Company settings sidebar");
expect(container.textContent).not.toContain("Instance sidebar");
expect(container.textContent).not.toContain("Main company nav");
expect(container.textContent).not.toContain("Plugin route sidebar");
await act(async () => {
root.unmount();
});
});
it("renders the instance settings sidebar on instance settings routes", async () => {
currentPathname = "/instance/settings/general";
const root = createRoot(container);
const queryClient = new QueryClient({
defaultOptions: { queries: { retry: false } },
});
await act(async () => {
root.render(
<QueryClientProvider client={queryClient}>
<Layout />
</QueryClientProvider>,
);
});
await flushReact();
await flushReact();
expect(container.textContent).toContain("Instance sidebar");
expect(container.textContent).not.toContain("Company settings sidebar");
expect(container.textContent).not.toContain("Main company nav");
expect(container.textContent).not.toContain("Plugin route sidebar");
await act(async () => {
root.unmount();
});
});
it("renders a route-scoped plugin sidebar for a matching plugin page route", async () => {
currentPathname = "/PAP/wiki";
mockPluginSlots.slots = [
{
type: "page",
id: "wiki-page",
displayName: "Wiki Page",
exportName: "WikiPage",
routePath: "wiki",
pluginId: "plugin-1",
pluginKey: "wiki-plugin",
pluginDisplayName: "Wiki Plugin",
pluginVersion: "1.0.0",
},
{
type: "routeSidebar",
id: "wiki-route-sidebar",
displayName: "Wiki Sidebar",
exportName: "WikiSidebar",
routePath: "wiki",
pluginId: "plugin-1",
pluginKey: "wiki-plugin",
pluginDisplayName: "Wiki Plugin",
pluginVersion: "1.0.0",
},
];
const root = createRoot(container);
const queryClient = new QueryClient({
defaultOptions: { queries: { retry: false } },
});
await act(async () => {
root.render(
<QueryClientProvider client={queryClient}>
<Layout />
</QueryClientProvider>,
);
});
await flushReact();
await flushReact();
expect(container.textContent).toContain("Plugin route sidebar: Wiki Sidebar");
expect(container.querySelector("[data-plugin-slot-class='h-full w-full']")).not.toBeNull();
expect(container.textContent).not.toContain("Main company nav");
expect(container.textContent).not.toContain("Company settings sidebar");
expect(container.textContent).not.toContain("Instance sidebar");
await act(async () => {
root.unmount();
});
});
it("uses the route company context for plugin route sidebars on the first render", async () => {
currentPathname = "/ALT/wiki";
mockCompanyState.companies = [
{ id: "company-1", issuePrefix: "PAP", name: "Paperclip" },
{ id: "company-2", issuePrefix: "ALT", name: "Alternate" },
];
mockCompanyState.selectedCompany = { id: "company-1", issuePrefix: "PAP", name: "Paperclip" };
mockCompanyState.selectedCompanyId = "company-1";
mockPluginSlots.slots = [
{
type: "page",
id: "wiki-page",
displayName: "Wiki Page",
exportName: "WikiPage",
routePath: "wiki",
pluginId: "plugin-1",
pluginKey: "wiki-plugin",
pluginDisplayName: "Wiki Plugin",
pluginVersion: "1.0.0",
},
{
type: "routeSidebar",
id: "wiki-route-sidebar",
displayName: "Wiki Sidebar",
exportName: "WikiSidebar",
routePath: "wiki",
pluginId: "plugin-1",
pluginKey: "wiki-plugin",
pluginDisplayName: "Wiki Plugin",
pluginVersion: "1.0.0",
},
];
const root = createRoot(container);
const queryClient = new QueryClient({
defaultOptions: { queries: { retry: false } },
});
await act(async () => {
root.render(
<QueryClientProvider client={queryClient}>
<Layout />
</QueryClientProvider>,
);
});
await flushReact();
await flushReact();
expect(mockUsePluginSlots).toHaveBeenCalledWith(
expect.objectContaining({
companyId: "company-2",
enabled: true,
}),
);
expect(mockPluginSlotContexts).toContainEqual({
companyId: "company-2",
companyPrefix: "ALT",
});
expect(mockPluginSlotContexts).not.toContainEqual({
companyId: "company-1",
companyPrefix: "PAP",
});
await act(async () => {
root.unmount();
});
});
it("keeps the normal company sidebar when a plugin page route is ambiguous", async () => {
currentPathname = "/PAP/wiki";
mockPluginSlots.slots = [
{
type: "page",
id: "wiki-page-a",
displayName: "Wiki Page A",
exportName: "WikiPageA",
routePath: "wiki",
pluginId: "plugin-1",
pluginKey: "wiki-plugin-a",
pluginDisplayName: "Wiki Plugin A",
pluginVersion: "1.0.0",
},
{
type: "page",
id: "wiki-page-b",
displayName: "Wiki Page B",
exportName: "WikiPageB",
routePath: "wiki",
pluginId: "plugin-2",
pluginKey: "wiki-plugin-b",
pluginDisplayName: "Wiki Plugin B",
pluginVersion: "1.0.0",
},
{
type: "routeSidebar",
id: "wiki-route-sidebar",
displayName: "Wiki Sidebar",
exportName: "WikiSidebar",
routePath: "wiki",
pluginId: "plugin-1",
pluginKey: "wiki-plugin-a",
pluginDisplayName: "Wiki Plugin A",
pluginVersion: "1.0.0",
},
];
const root = createRoot(container);
const queryClient = new QueryClient({
defaultOptions: { queries: { retry: false } },
});
await act(async () => {
root.render(
<QueryClientProvider client={queryClient}>
<Layout />
</QueryClientProvider>,
);
});
await flushReact();
await flushReact();
expect(container.textContent).toContain("Main company nav");
expect(container.textContent).not.toContain("Plugin route sidebar");
await act(async () => {
root.unmount();

View file

@ -1,6 +1,7 @@
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { useQuery } from "@tanstack/react-query";
import { Outlet, useLocation, useNavigate, useNavigationType, useParams } from "@/lib/router";
import { CompanyRail } from "./CompanyRail";
import { Sidebar } from "./Sidebar";
import { InstanceSidebar } from "./InstanceSidebar";
import { CompanySettingsSidebar } from "./CompanySettingsSidebar";
@ -16,6 +17,7 @@ import { ToastViewport } from "./ToastViewport";
import { MobileBottomNav } from "./MobileBottomNav";
import { WorktreeBanner } from "./WorktreeBanner";
import { DevRestartBanner } from "./DevRestartBanner";
import { ResizableSidebarPane } from "./ResizableSidebarPane";
import { SidebarAccountMenu } from "./SidebarAccountMenu";
import { useDialogActions } from "../context/DialogContext";
import { GeneralSettingsProvider } from "../context/GeneralSettingsContext";
@ -39,9 +41,18 @@ import { queryKeys } from "../lib/queryKeys";
import { scheduleMainContentFocus } from "../lib/main-content-focus";
import { cn } from "../lib/utils";
import { NotFoundPage } from "../pages/NotFound";
import { PluginSlotMount, resolveRouteSidebarSlot, usePluginSlots } from "../plugins/slots";
const INSTANCE_SETTINGS_MEMORY_KEY = "paperclip.lastInstanceSettingsPath";
function getCompanyRouteSegment(pathname: string, companyPrefix: string | undefined): string | null {
if (!companyPrefix) return null;
const segments = pathname.split("/").filter(Boolean);
if (segments.length < 2) return null;
if (segments[0]?.toUpperCase() !== companyPrefix.toUpperCase()) return null;
return segments[1]?.toLowerCase() ?? null;
}
function readRememberedInstanceSettingsPath(): string {
if (typeof window === "undefined") return DEFAULT_INSTANCE_SETTINGS_PATH;
try {
@ -83,6 +94,38 @@ export function Layout() {
}, [companies, companyPrefix]);
const hasUnknownCompanyPrefix =
Boolean(companyPrefix) && !companiesLoading && companies.length > 0 && !matchedCompany;
const pluginRoutePath = useMemo(
() => getCompanyRouteSegment(location.pathname, companyPrefix),
[companyPrefix, location.pathname],
);
const routeSidebarCompanyId = matchedCompany?.id ?? null;
const routeSidebarCompanyPrefix = matchedCompany?.issuePrefix ?? null;
const { slots: routeSidebarSlots } = usePluginSlots({
slotTypes: ["page", "routeSidebar"],
companyId: routeSidebarCompanyId,
enabled: Boolean(routeSidebarCompanyId && pluginRoutePath),
});
const routeSidebarSlot = useMemo(
() => resolveRouteSidebarSlot(routeSidebarSlots, pluginRoutePath),
[pluginRoutePath, routeSidebarSlots],
);
const sidebarContext = useMemo(
() => ({
companyId: routeSidebarCompanyId,
companyPrefix: routeSidebarCompanyPrefix,
}),
[routeSidebarCompanyId, routeSidebarCompanyPrefix],
);
const companySidebar = routeSidebarSlot ? (
<PluginSlotMount
slot={routeSidebarSlot}
context={sidebarContext}
className="h-full w-full"
missingBehavior="placeholder"
/>
) : (
<Sidebar />
);
const { data: health } = useQuery({
queryKey: queryKeys.health,
queryFn: () => healthApi.get(),
@ -335,13 +378,16 @@ export function Layout() {
)}
>
<div className="flex flex-1 min-h-0 overflow-hidden">
{isInstanceSettingsRoute ? (
<InstanceSidebar />
) : isCompanySettingsRoute ? (
<CompanySettingsSidebar />
) : (
<Sidebar />
)}
<CompanyRail />
<div className="w-60 shrink-0 overflow-hidden">
{isInstanceSettingsRoute ? (
<InstanceSidebar />
) : isCompanySettingsRoute ? (
<CompanySettingsSidebar />
) : (
companySidebar
)}
</div>
</div>
<SidebarAccountMenu
deploymentMode={health?.deploymentMode}
@ -352,20 +398,16 @@ export function Layout() {
) : (
<div className="flex h-full flex-col shrink-0">
<div className="flex flex-1 min-h-0">
<div
className={cn(
"overflow-hidden transition-[width] duration-100 ease-out",
sidebarOpen ? "w-60" : "w-0"
)}
>
<CompanyRail />
<ResizableSidebarPane open={sidebarOpen} resizable className="h-full shrink-0">
{isInstanceSettingsRoute ? (
<InstanceSidebar />
) : isCompanySettingsRoute ? (
<CompanySettingsSidebar />
) : (
<Sidebar />
companySidebar
)}
</div>
</ResizableSidebarPane>
</div>
<SidebarAccountMenu
deploymentMode={health?.deploymentMode}

View file

@ -0,0 +1,180 @@
import { Button } from "@/components/ui/button";
import {
RoutineListRow,
type RoutineListAgentSummary,
type RoutineListProjectSummary,
type RoutineListRowItem,
} from "@/components/RoutineList";
export type ManagedRoutinesListAgent = {
id: string;
name: string;
icon?: string | null;
};
export type ManagedRoutinesListProject = {
id: string;
name: string;
color?: string | null;
};
export type ManagedRoutineMissingRef = {
resourceKind: string;
resourceKey: string;
};
export type ManagedRoutinesListItem = {
key: string;
title: string;
status: string;
routineId?: string | null;
href?: string | null;
resourceKey?: string | null;
projectId?: string | null;
assigneeAgentId?: string | null;
cronExpression?: string | null;
lastRunAt?: Date | string | null;
lastRunStatus?: string | null;
managedByPluginDisplayName?: string | null;
missingRefs?: ManagedRoutineMissingRef[];
};
export type ManagedRoutinesListProps = {
routines: ManagedRoutinesListItem[];
agents?: ManagedRoutinesListAgent[];
projects?: ManagedRoutinesListProject[];
pluginDisplayName?: string | null;
emptyMessage?: string;
runningRoutineKey?: string | null;
statusMutationRoutineKey?: string | null;
reconcilingRoutineKey?: string | null;
resettingRoutineKey?: string | null;
onRunNow?: (routine: ManagedRoutinesListItem) => void;
onToggleEnabled?: (routine: ManagedRoutinesListItem, enabled: boolean) => void;
onReconcile?: (routine: ManagedRoutinesListItem) => void;
onReset?: (routine: ManagedRoutinesListItem) => void;
};
function managedRoutineToRow(routine: ManagedRoutinesListItem): RoutineListRowItem {
return {
id: routine.key,
title: routine.title,
status: routine.status,
projectId: routine.projectId ?? null,
assigneeAgentId: routine.assigneeAgentId ?? null,
lastRun: routine.lastRunAt || routine.lastRunStatus
? {
triggeredAt: routine.lastRunAt ?? null,
status: routine.lastRunStatus ?? null,
}
: null,
};
}
export function ManagedRoutinesList({
routines,
agents = [],
projects = [],
pluginDisplayName = null,
emptyMessage = "No managed routines.",
runningRoutineKey = null,
statusMutationRoutineKey = null,
reconcilingRoutineKey = null,
resettingRoutineKey = null,
onRunNow,
onToggleEnabled,
onReconcile,
onReset,
}: ManagedRoutinesListProps) {
const agentById = new Map<string, RoutineListAgentSummary>(
agents.map((agent) => [agent.id, { name: agent.name, icon: agent.icon }]),
);
const projectById = new Map<string, RoutineListProjectSummary>(
projects.map((project) => [project.id, { name: project.name, color: project.color }]),
);
if (routines.length === 0) {
return (
<div className="rounded-lg border border-border px-3 py-8 text-center text-sm text-muted-foreground">
{emptyMessage}
</div>
);
}
return (
<div className="rounded-lg border border-border">
{routines.map((routine) => {
const row = managedRoutineToRow(routine);
const href = routine.href ?? (routine.routineId ? `/routines/${routine.routineId}` : "/routines");
const missingRefs = routine.missingRefs ?? [];
const canUseRoutine = Boolean(routine.routineId && routine.resourceKey && missingRefs.length === 0);
const managedBy = routine.managedByPluginDisplayName ?? pluginDisplayName;
const hasRepairActions = Boolean(onReconcile || onReset);
return (
<div key={routine.key} className="last:[&_a]:border-b-0">
<RoutineListRow
routine={row}
projectById={projectById}
agentById={agentById}
runningRoutineId={runningRoutineKey}
statusMutationRoutineId={statusMutationRoutineKey}
href={href}
configureLabel="Configure"
managedByLabel={managedBy ? `Managed by ${managedBy}` : null}
runNowButton
hideArchiveAction
disableRunNow={!canUseRoutine}
disableToggle={!canUseRoutine}
secondaryDetails={
<span className="flex flex-wrap items-center gap-x-3 gap-y-1">
{routine.resourceKey ? <span>{routine.resourceKey}</span> : null}
{routine.cronExpression ? <span>Schedule {routine.cronExpression}</span> : null}
</span>
}
onRunNow={() => onRunNow?.(routine)}
onToggleEnabled={() => onToggleEnabled?.(routine, row.status === "active")}
/>
{hasRepairActions ? (
<div
className="flex flex-wrap items-center justify-between gap-2 border-b border-border px-3 pb-3 text-xs text-muted-foreground last:border-b-0"
onClick={(event) => {
event.preventDefault();
event.stopPropagation();
}}
>
<span>
{missingRefs.length
? `Missing ${missingRefs.map((ref) => `${ref.resourceKind}:${ref.resourceKey}`).join(", ")}`
: "Routine defaults can be repaired."}
</span>
<span className="flex items-center gap-2">
{onReconcile ? (
<Button
size="sm"
variant="ghost"
disabled={reconcilingRoutineKey === routine.key}
onClick={() => onReconcile(routine)}
>
{reconcilingRoutineKey === routine.key ? "Reconciling..." : "Reconcile"}
</Button>
) : null}
{onReset ? (
<Button
size="sm"
variant="ghost"
disabled={resettingRoutineKey === routine.key}
onClick={() => onReset(routine)}
>
{resettingRoutineKey === routine.key ? "Resetting..." : "Reset"}
</Button>
) : null}
</span>
</div>
) : null}
</div>
);
})}
</div>
);
}

View file

@ -1,6 +1,6 @@
// @vitest-environment node
import type { ReactNode } from "react";
import type { ComponentProps, ReactNode } from "react";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { describe, expect, it, vi } from "vitest";
import { renderToStaticMarkup } from "react-dom/server";
@ -33,7 +33,11 @@ vi.mock("../api/issues", () => ({
issuesApi: mockIssuesApi,
}));
function renderMarkdown(children: string, seededIssues: Array<{ identifier: string; status: string; title?: string }> = []) {
function renderMarkdown(
children: string,
seededIssues: Array<{ identifier: string; status: string; title?: string }> = [],
props: Partial<ComponentProps<typeof MarkdownBody>> = {},
) {
const queryClient = new QueryClient({
defaultOptions: {
queries: {
@ -54,7 +58,7 @@ function renderMarkdown(children: string, seededIssues: Array<{ identifier: stri
return renderToStaticMarkup(
<QueryClientProvider client={queryClient}>
<ThemeProvider>
<MarkdownBody>{children}</MarkdownBody>
<MarkdownBody {...props}>{children}</MarkdownBody>
</ThemeProvider>
</QueryClientProvider>,
);
@ -279,6 +283,64 @@ describe("MarkdownBody", () => {
expect(html).toContain('href="PAP-1271"');
});
it("leaves wiki links as text unless explicitly enabled", () => {
const html = renderMarkdown("See [[wiki/entities/paperclip]].");
expect(html).toContain("[[wiki/entities/paperclip]]");
expect(html).not.toContain('href="/wiki/page/wiki/entities/paperclip.md"');
});
it("renders wiki links with a custom resolver when enabled", () => {
const html = renderMarkdown(
"See [[wiki/entities/paperclip|Paperclip]] and [[wiki/entities/dotta-b]].",
[],
{
enableWikiLinks: true,
resolveWikiLinkHref: (target) => `/wiki/page/${target.endsWith(".md") ? target : `${target}.md`}`,
},
);
expect(html).toContain('href="/wiki/page/wiki/entities/paperclip.md"');
expect(html).toContain('data-paperclip-wiki-link="true"');
expect(html).toContain('data-paperclip-wiki-target="wiki/entities/paperclip"');
expect(html).toContain(">Paperclip</a>");
expect(html).toContain('href="/wiki/page/wiki/entities/dotta-b.md"');
expect(html).toContain(">wiki/entities/dotta-b</a>");
expect(html).not.toContain("[[wiki/entities/paperclip");
});
it("keeps wiki links as text when the custom resolver rejects them", () => {
const html = renderMarkdown(
"See [[wiki/entities/paperclip]].",
[],
{
enableWikiLinks: true,
wikiLinkRoot: "/wiki/page",
resolveWikiLinkHref: () => null,
},
);
expect(html).toContain("[[wiki/entities/paperclip]]");
expect(html).not.toContain('data-paperclip-wiki-link="true"');
expect(html).not.toContain('href="/wiki/page/wiki/entities/paperclip"');
});
it("does not render wiki links inside code spans or code blocks", () => {
const html = renderMarkdown(
"Inline `[[wiki/entities/paperclip]]`.\n\n```md\n[[wiki/entities/dotta-b]]\n```",
[],
{
enableWikiLinks: true,
wikiLinkRoot: "/wiki/page",
},
);
expect(html).toContain("[[wiki/entities/paperclip]]");
expect(html).toContain("[[wiki/entities/dotta-b]]");
expect(html).not.toContain('href="/wiki/page/wiki/entities/paperclip"');
expect(html).not.toContain('href="/wiki/page/wiki/entities/dotta-b"');
});
it("applies wrap-friendly styles to long inline content", () => {
const html = renderMarkdown("averyveryveryveryveryveryveryveryveryverylongtoken");

View file

@ -19,6 +19,12 @@ interface MarkdownBodyProps {
style?: React.CSSProperties;
softBreaks?: boolean;
linkIssueReferences?: boolean;
/** Opt into Obsidian-style [[target]] / [[target|label]] wikilinks. */
enableWikiLinks?: boolean;
/** Base href used for wikilinks when no resolver is supplied. */
wikiLinkRoot?: string;
/** Optional href resolver for wikilinks. Return null to leave a token as plain text. */
resolveWikiLinkHref?: (target: string, label: string) => string | null | undefined;
/** Optional resolver for relative image paths (e.g. within export packages) */
resolveImageSrc?: (src: string) => string | null;
/** Called when a user clicks an inline image */
@ -111,6 +117,160 @@ function safeMarkdownUrlTransform(url: string): string {
return parseMentionChipHref(url) ? url : defaultUrlTransform(url);
}
type MarkdownAstNode = {
type?: string;
value?: string;
children?: MarkdownAstNode[];
url?: string;
title?: string | null;
data?: {
hProperties?: Record<string, string>;
};
};
type ParsedWikiLink = {
target: string;
label: string;
};
const WIKI_LINK_PATTERN = /\[\[([^\]\r\n]+)\]\]/g;
const WIKI_LINK_SKIP_PARENT_TYPES = new Set([
"definition",
"image",
"imageReference",
"link",
"linkReference",
]);
function parseWikiLinkBody(body: string): ParsedWikiLink | null {
const [rawTarget, ...rawLabelParts] = body.split("|");
const target = rawTarget?.trim() ?? "";
const label = rawLabelParts.length > 0 ? rawLabelParts.join("|").trim() : target;
if (!target || target.includes("[") || target.includes("]")) return null;
return {
target,
label: label || target,
};
}
function encodeWikiLinkTarget(target: string): string | null {
const trimmed = target.trim();
if (!trimmed || /^[a-z][a-z\d+.-]*:/i.test(trimmed) || trimmed.startsWith("//")) return null;
const hashIndex = trimmed.indexOf("#");
const rawPath = (hashIndex >= 0 ? trimmed.slice(0, hashIndex) : trimmed)
.trim()
.replace(/^\/+/, "");
if (
!rawPath ||
rawPath.includes("\\") ||
rawPath.split("/").some((segment) => !segment || segment === "." || segment === "..")
) {
return null;
}
const encodedPath = rawPath.split("/").map((segment) => encodeURIComponent(segment)).join("/");
const rawHash = hashIndex >= 0 ? trimmed.slice(hashIndex + 1).trim() : "";
return rawHash ? `${encodedPath}#${encodeURIComponent(rawHash)}` : encodedPath;
}
function defaultWikiLinkHref(target: string, wikiLinkRoot?: string): string | null {
const encodedTarget = encodeWikiLinkTarget(target);
if (!encodedTarget) return null;
const root = wikiLinkRoot?.trim().replace(/\/+$/, "") ?? "";
return root ? `${root}/${encodedTarget}` : encodedTarget;
}
function createWikiLinkNode(href: string, wikiLink: ParsedWikiLink): MarkdownAstNode {
return {
type: "link",
url: href,
title: null,
data: {
hProperties: {
"data-paperclip-wiki-link": "true",
"data-paperclip-wiki-target": wikiLink.target,
},
},
children: [{ type: "text", value: wikiLink.label }],
};
}
function splitTextByWikiLinks(
value: string,
options: {
wikiLinkRoot?: string;
resolveWikiLinkHref?: (target: string, label: string) => string | null | undefined;
},
): MarkdownAstNode[] {
const nodes: MarkdownAstNode[] = [];
let lastIndex = 0;
for (const match of value.matchAll(WIKI_LINK_PATTERN)) {
const raw = match[0] ?? "";
const body = match[1] ?? "";
const start = match.index ?? 0;
if (start > lastIndex) {
nodes.push({ type: "text", value: value.slice(lastIndex, start) });
}
const wikiLink = parseWikiLinkBody(body);
let resolvedHref: string | null = null;
if (wikiLink) {
if (options.resolveWikiLinkHref) {
const customHref = options.resolveWikiLinkHref(wikiLink.target, wikiLink.label);
resolvedHref = customHref === undefined
? defaultWikiLinkHref(wikiLink.target, options.wikiLinkRoot)
: customHref;
} else {
resolvedHref = defaultWikiLinkHref(wikiLink.target, options.wikiLinkRoot);
}
}
if (wikiLink && resolvedHref) {
nodes.push(createWikiLinkNode(resolvedHref, wikiLink));
} else {
nodes.push({ type: "text", value: raw });
}
lastIndex = start + raw.length;
}
if (lastIndex < value.length) {
nodes.push({ type: "text", value: value.slice(lastIndex) });
}
return nodes;
}
function transformWikiLinkChildren(
node: MarkdownAstNode,
options: {
wikiLinkRoot?: string;
resolveWikiLinkHref?: (target: string, label: string) => string | null | undefined;
},
) {
if (!node.children || WIKI_LINK_SKIP_PARENT_TYPES.has(node.type ?? "")) return;
node.children = node.children.flatMap((child) => {
if (child.type === "text" && typeof child.value === "string" && child.value.includes("[[")) {
return splitTextByWikiLinks(child.value, options);
}
transformWikiLinkChildren(child, options);
return child;
});
}
function createRemarkWikiLinks(options: {
wikiLinkRoot?: string;
resolveWikiLinkHref?: (target: string, label: string) => string | null | undefined;
}) {
return function remarkWikiLinks() {
return (tree: MarkdownAstNode) => {
transformWikiLinkChildren(tree, options);
};
};
}
function isGitHubUrl(href: string | null | undefined): boolean {
if (!href) return false;
try {
@ -321,11 +481,17 @@ export function MarkdownBody({
style,
softBreaks = true,
linkIssueReferences = true,
enableWikiLinks = false,
wikiLinkRoot,
resolveWikiLinkHref,
resolveImageSrc,
onImageClick,
}: MarkdownBodyProps) {
const { theme } = useTheme();
const remarkPlugins: NonNullable<Options["remarkPlugins"]> = [remarkGfm];
if (enableWikiLinks) {
remarkPlugins.push(createRemarkWikiLinks({ wikiLinkRoot, resolveWikiLinkHref }));
}
if (linkIssueReferences) {
remarkPlugins.push(remarkLinkIssueReferences);
}
@ -370,7 +536,22 @@ export function MarkdownBody({
{codeChildren}
</code>
),
a: ({ href, style: linkStyle, children: linkChildren }) => {
a: ({ node: _node, href, style: linkStyle, children: linkChildren, ...anchorProps }) => {
const dataProps = anchorProps as Record<string, unknown>;
const isWikiLink = dataProps["data-paperclip-wiki-link"] === "true";
if (isWikiLink && href && !/^[a-z][a-z\d+.-]*:/i.test(href) && !href.startsWith("//")) {
return (
<Link
to={href}
{...anchorProps}
rel="noreferrer"
style={mergeWrapStyle(linkStyle as React.CSSProperties | undefined)}
>
{linkChildren}
</Link>
);
}
const issueRef = linkIssueReferences ? parseIssueReferenceFromHref(href) : null;
if (issueRef) {
return (

View file

@ -1,326 +1,24 @@
import type { ReactNode } from "react";
import { cn } from "../lib/utils";
import {
ChevronDown,
ChevronRight,
FileCode2,
FileText,
Folder,
FolderOpen,
} from "lucide-react";
import { FileTree } from "./FileTree";
import type { FileTreeProps } from "./FileTree";
// ── Tree types ────────────────────────────────────────────────────────
export type FileTreeNode = {
name: string;
path: string;
kind: "dir" | "file";
children: FileTreeNode[];
/** Optional per-node metadata (e.g. import action) */
action?: string | null;
};
const TREE_BASE_INDENT = 16;
const TREE_STEP_INDENT = 24;
const TREE_ROW_HEIGHT_CLASS = "min-h-9";
// ── Helpers ───────────────────────────────────────────────────────────
export function buildFileTree(
files: Record<string, unknown>,
actionMap?: Map<string, string>,
): FileTreeNode[] {
const root: FileTreeNode = { name: "", path: "", kind: "dir", children: [] };
for (const filePath of Object.keys(files)) {
const segments = filePath.split("/").filter(Boolean);
let current = root;
let currentPath = "";
for (let i = 0; i < segments.length; i++) {
const segment = segments[i];
currentPath = currentPath ? `${currentPath}/${segment}` : segment;
const isLeaf = i === segments.length - 1;
let next = current.children.find((c) => c.name === segment);
if (!next) {
next = {
name: segment,
path: currentPath,
kind: isLeaf ? "file" : "dir",
children: [],
action: isLeaf ? (actionMap?.get(filePath) ?? null) : null,
};
current.children.push(next);
}
current = next;
}
}
function sortNode(node: FileTreeNode) {
node.children.sort((a, b) => {
// Files before directories so PROJECT.md appears above tasks/
if (a.kind !== b.kind) return a.kind === "file" ? -1 : 1;
return a.name.localeCompare(b.name);
});
node.children.forEach(sortNode);
}
sortNode(root);
return root.children;
export function PackageFileTree({ wrapLabels = false, ...props }: FileTreeProps) {
return <FileTree {...props} wrapLabels={wrapLabels} />;
}
export function countFiles(nodes: FileTreeNode[]): number {
let count = 0;
for (const node of nodes) {
if (node.kind === "file") count++;
else count += countFiles(node.children);
}
return count;
}
export function collectAllPaths(
nodes: FileTreeNode[],
type: "file" | "dir" | "all" = "all",
): Set<string> {
const paths = new Set<string>();
for (const node of nodes) {
if (type === "all" || node.kind === type) paths.add(node.path);
for (const p of collectAllPaths(node.children, type)) paths.add(p);
}
return paths;
}
function fileIcon(name: string) {
if (name.endsWith(".yaml") || name.endsWith(".yml")) return FileCode2;
return FileText;
}
// ── Frontmatter helpers ───────────────────────────────────────────────
export type FrontmatterData = Record<string, string | string[]>;
export function parseFrontmatter(content: string): { data: FrontmatterData; body: string } | null {
const match = content.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/);
if (!match) return null;
const data: FrontmatterData = {};
const rawYaml = match[1];
const body = match[2];
let currentKey: string | null = null;
let currentList: string[] | null = null;
for (const line of rawYaml.split("\n")) {
const trimmed = line.trim();
if (!trimmed || trimmed.startsWith("#")) continue;
if (trimmed.startsWith("- ") && currentKey) {
if (!currentList) currentList = [];
currentList.push(trimmed.slice(2).trim().replace(/^["']|["']$/g, ""));
continue;
}
if (currentKey && currentList) {
data[currentKey] = currentList;
currentList = null;
currentKey = null;
}
const kvMatch = trimmed.match(/^([a-zA-Z_][\w-]*)\s*:\s*(.*)$/);
if (kvMatch) {
const key = kvMatch[1];
const val = kvMatch[2].trim().replace(/^["']|["']$/g, "");
if (val === "null") {
currentKey = null;
continue;
}
if (val) {
data[key] = val;
currentKey = null;
} else {
currentKey = key;
}
}
}
if (currentKey && currentList) {
data[currentKey] = currentList;
}
return Object.keys(data).length > 0 ? { data, body } : null;
}
export const FRONTMATTER_FIELD_LABELS: Record<string, string> = {
name: "Name",
title: "Title",
kind: "Kind",
reportsTo: "Reports to",
skills: "Skills",
status: "Status",
description: "Description",
priority: "Priority",
assignee: "Assignee",
project: "Project",
recurring: "Recurring",
targetDate: "Target date",
};
// ── File tree component ───────────────────────────────────────────────
export function PackageFileTree({
nodes,
selectedFile,
expandedDirs,
checkedFiles,
onToggleDir,
onSelectFile,
onToggleCheck,
renderFileExtra,
fileRowClassName,
showCheckboxes = true,
wrapLabels = false,
depth = 0,
}: {
nodes: FileTreeNode[];
selectedFile: string | null;
expandedDirs: Set<string>;
checkedFiles?: Set<string>;
onToggleDir: (path: string) => void;
onSelectFile: (path: string) => void;
onToggleCheck?: (path: string, kind: "file" | "dir") => void;
/** Optional extra content rendered at the end of each file row (e.g. action badge) */
renderFileExtra?: (node: FileTreeNode, checked: boolean) => ReactNode;
/** Optional additional className for file rows */
fileRowClassName?: (node: FileTreeNode, checked: boolean) => string | undefined;
showCheckboxes?: boolean;
/** Allow long file and directory names to wrap instead of forcing horizontal overflow. */
wrapLabels?: boolean;
depth?: number;
}) {
const effectiveCheckedFiles = checkedFiles ?? new Set<string>();
return (
<div>
{nodes.map((node) => {
const expanded = node.kind === "dir" && expandedDirs.has(node.path);
if (node.kind === "dir") {
const childFiles = collectAllPaths(node.children, "file");
const allChecked = [...childFiles].every((p) => effectiveCheckedFiles.has(p));
const someChecked = [...childFiles].some((p) => effectiveCheckedFiles.has(p));
return (
<div key={node.path}>
<div
className={cn(
showCheckboxes
? "group grid w-full grid-cols-[auto_minmax(0,1fr)_2.25rem] items-center gap-x-1 pr-3 text-left text-sm text-muted-foreground hover:bg-accent/30 hover:text-foreground"
: "group grid w-full grid-cols-[minmax(0,1fr)_2.25rem] items-center gap-x-1 pr-3 text-left text-sm text-muted-foreground hover:bg-accent/30 hover:text-foreground",
TREE_ROW_HEIGHT_CLASS,
)}
style={{
paddingInlineStart: `${TREE_BASE_INDENT + depth * TREE_STEP_INDENT - 8}px`,
}}
>
{showCheckboxes && (
<label className="flex items-center pl-2">
<input
type="checkbox"
checked={allChecked}
ref={(el) => { if (el) el.indeterminate = someChecked && !allChecked; }}
onChange={() => onToggleCheck?.(node.path, "dir")}
className="mr-2 accent-foreground"
/>
</label>
)}
<button
type="button"
className="flex min-w-0 items-center gap-2 py-1 text-left"
onClick={() => onToggleDir(node.path)}
>
<span className="flex h-4 w-4 shrink-0 items-center justify-center">
{expanded ? (
<FolderOpen className="h-3.5 w-3.5" />
) : (
<Folder className="h-3.5 w-3.5" />
)}
</span>
<span className={cn("min-w-0", wrapLabels ? "break-all leading-4" : "truncate")}>
{node.name}
</span>
</button>
<button
type="button"
className="flex h-9 w-9 items-center justify-center self-center rounded-sm text-muted-foreground opacity-70 transition-[background-color,color,opacity] hover:bg-accent hover:text-foreground group-hover:opacity-100"
onClick={() => onToggleDir(node.path)}
>
{expanded ? (
<ChevronDown className="h-3.5 w-3.5" />
) : (
<ChevronRight className="h-3.5 w-3.5" />
)}
</button>
</div>
{expanded && (
<PackageFileTree
nodes={node.children}
selectedFile={selectedFile}
expandedDirs={expandedDirs}
checkedFiles={effectiveCheckedFiles}
onToggleDir={onToggleDir}
onSelectFile={onSelectFile}
onToggleCheck={onToggleCheck}
renderFileExtra={renderFileExtra}
fileRowClassName={fileRowClassName}
showCheckboxes={showCheckboxes}
wrapLabels={wrapLabels}
depth={depth + 1}
/>
)}
</div>
);
}
const FileIcon = fileIcon(node.name);
const checked = effectiveCheckedFiles.has(node.path);
const extraClassName = fileRowClassName?.(node, checked);
return (
<div
key={node.path}
className={cn(
"flex w-full items-center gap-1 pr-3 text-left text-sm text-muted-foreground hover:bg-accent/30 hover:text-foreground cursor-pointer",
TREE_ROW_HEIGHT_CLASS,
node.path === selectedFile && "text-foreground bg-accent/20",
extraClassName,
)}
style={{
paddingInlineStart: `${TREE_BASE_INDENT + depth * TREE_STEP_INDENT - 8}px`,
}}
onClick={() => onSelectFile(node.path)}
>
{showCheckboxes && (
<label className="flex items-center pl-2">
<input
type="checkbox"
checked={checked}
onChange={() => onToggleCheck?.(node.path, "file")}
className="mr-2 accent-foreground"
/>
</label>
)}
<button
type="button"
className="flex min-w-0 flex-1 items-center gap-2 py-1 text-left"
onClick={() => onSelectFile(node.path)}
>
<span className="flex h-4 w-4 shrink-0 items-center justify-center">
<FileIcon className="h-3.5 w-3.5" />
</span>
<span className={cn("min-w-0", wrapLabels ? "break-all leading-4" : "truncate")}>
{node.name}
</span>
</button>
{renderFileExtra?.(node, checked)}
</div>
);
})}
</div>
);
}
export {
FRONTMATTER_FIELD_LABELS,
buildFileTree,
collectAllPaths,
countFiles,
parseFrontmatter,
} from "./FileTree";
export type {
FileTreeBadge,
FileTreeBadgeVariant,
FileTreeEmptyState,
FileTreeErrorState,
FileTreeNode,
FileTreeProps,
FileTreeTone,
FrontmatterData,
} from "./FileTree";

View file

@ -0,0 +1,121 @@
// @vitest-environment jsdom
import { act } from "react";
import { createRoot, type Root } from "react-dom/client";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { ResizableSidebarPane } from "./ResizableSidebarPane";
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(globalThis as any).IS_REACT_ACT_ENVIRONMENT = true;
function pointerEvent(type: string, clientX: number) {
const event = new MouseEvent(type, { bubbles: true, clientX });
Object.defineProperty(event, "pointerId", { value: 1 });
return event;
}
describe("ResizableSidebarPane", () => {
let container: HTMLDivElement;
let root: Root;
beforeEach(() => {
window.localStorage.clear();
container = document.createElement("div");
document.body.appendChild(container);
root = createRoot(container);
});
afterEach(() => {
act(() => {
root.unmount();
});
container.remove();
window.localStorage.clear();
});
function pane() {
return container.firstElementChild as HTMLDivElement;
}
function handle() {
return container.querySelector('[role="separator"]') as HTMLDivElement | null;
}
it("uses a persisted width when open", () => {
window.localStorage.setItem("test.sidebar.width", "320");
act(() => {
root.render(
<ResizableSidebarPane open resizable storageKey="test.sidebar.width">
<div>Sidebar</div>
</ResizableSidebarPane>,
);
});
expect(pane().style.width).toBe("320px");
expect(handle()?.getAttribute("aria-valuenow")).toBe("320");
});
it("resizes by dragging and persists the new width", () => {
act(() => {
root.render(
<ResizableSidebarPane open resizable storageKey="test.sidebar.width">
<div>Sidebar</div>
</ResizableSidebarPane>,
);
});
const separator = handle();
expect(separator).not.toBeNull();
separator!.setPointerCapture = vi.fn();
act(() => {
separator!.dispatchEvent(pointerEvent("pointerdown", 240));
separator!.dispatchEvent(pointerEvent("pointermove", 320));
separator!.dispatchEvent(pointerEvent("pointerup", 320));
});
expect(pane().style.width).toBe("320px");
expect(window.localStorage.getItem("test.sidebar.width")).toBe("320");
});
it("supports keyboard resizing and clamps to the configured bounds", () => {
act(() => {
root.render(
<ResizableSidebarPane open resizable storageKey="test.sidebar.width">
<div>Sidebar</div>
</ResizableSidebarPane>,
);
});
const separator = handle();
act(() => {
separator?.dispatchEvent(new KeyboardEvent("keydown", { key: "ArrowRight", bubbles: true }));
});
expect(pane().style.width).toBe("256px");
expect(window.localStorage.getItem("test.sidebar.width")).toBe("256");
act(() => {
separator?.dispatchEvent(new KeyboardEvent("keydown", { key: "Home", bubbles: true }));
});
expect(pane().style.width).toBe("208px");
act(() => {
separator?.dispatchEvent(new KeyboardEvent("keydown", { key: "End", bubbles: true }));
});
expect(pane().style.width).toBe("420px");
});
it("can render without a resize handle", () => {
act(() => {
root.render(
<ResizableSidebarPane open resizable={false}>
<div>Sidebar</div>
</ResizableSidebarPane>,
);
});
expect(handle()).toBeNull();
expect(pane().style.width).toBe("240px");
});
});

View file

@ -0,0 +1,176 @@
import {
useCallback,
useEffect,
useMemo,
useRef,
useState,
type KeyboardEvent,
type PointerEvent,
type ReactNode,
} from "react";
import { cn } from "@/lib/utils";
const DEFAULT_SIDEBAR_WIDTH = 240;
const MIN_SIDEBAR_WIDTH = 208;
const MAX_SIDEBAR_WIDTH = 420;
const SIDEBAR_WIDTH_STEP = 16;
function clampSidebarWidth(width: number) {
return Math.min(MAX_SIDEBAR_WIDTH, Math.max(MIN_SIDEBAR_WIDTH, width));
}
function readStoredSidebarWidth(storageKey: string) {
if (typeof window === "undefined") return DEFAULT_SIDEBAR_WIDTH;
try {
const stored = window.localStorage.getItem(storageKey);
if (!stored) return DEFAULT_SIDEBAR_WIDTH;
const parsed = Number.parseInt(stored, 10);
if (!Number.isFinite(parsed)) return DEFAULT_SIDEBAR_WIDTH;
return clampSidebarWidth(parsed);
} catch {
return DEFAULT_SIDEBAR_WIDTH;
}
}
function writeStoredSidebarWidth(storageKey: string, width: number) {
if (typeof window === "undefined") return;
try {
window.localStorage.setItem(storageKey, String(clampSidebarWidth(width)));
} catch {
// Storage can be unavailable in private contexts; resizing should still work.
}
}
type ResizableSidebarPaneProps = {
children: ReactNode;
open: boolean;
resizable?: boolean;
storageKey?: string;
className?: string;
};
export function ResizableSidebarPane({
children,
open,
resizable = false,
storageKey = "paperclip.sidebar.width",
className,
}: ResizableSidebarPaneProps) {
const [width, setWidth] = useState(() => readStoredSidebarWidth(storageKey));
const [isResizing, setIsResizing] = useState(false);
const widthRef = useRef(width);
const dragState = useRef<{ startX: number; startWidth: number } | null>(null);
useEffect(() => {
const storedWidth = readStoredSidebarWidth(storageKey);
widthRef.current = storedWidth;
setWidth(storedWidth);
}, [storageKey]);
const visibleWidth = open ? width : 0;
const paneStyle = useMemo(
() => ({ width: `${visibleWidth}px` }),
[visibleWidth],
);
const commitWidth = useCallback(
(nextWidth: number) => {
const clamped = clampSidebarWidth(nextWidth);
widthRef.current = clamped;
setWidth(clamped);
writeStoredSidebarWidth(storageKey, clamped);
},
[storageKey],
);
const handlePointerDown = useCallback(
(event: PointerEvent<HTMLDivElement>) => {
if (!open || !resizable) return;
event.preventDefault();
event.currentTarget.setPointerCapture(event.pointerId);
dragState.current = { startX: event.clientX, startWidth: widthRef.current };
setIsResizing(true);
},
[open, resizable],
);
const handlePointerMove = useCallback(
(event: PointerEvent<HTMLDivElement>) => {
if (!dragState.current) return;
const nextWidth = dragState.current.startWidth + event.clientX - dragState.current.startX;
const clamped = clampSidebarWidth(nextWidth);
widthRef.current = clamped;
setWidth(clamped);
},
[],
);
const endResize = useCallback(() => {
if (!dragState.current) return;
dragState.current = null;
setIsResizing(false);
writeStoredSidebarWidth(storageKey, widthRef.current);
}, [storageKey]);
const handleKeyDown = useCallback(
(event: KeyboardEvent<HTMLDivElement>) => {
if (!open || !resizable) return;
if (event.key === "ArrowLeft") {
event.preventDefault();
commitWidth(width - SIDEBAR_WIDTH_STEP);
} else if (event.key === "ArrowRight") {
event.preventDefault();
commitWidth(width + SIDEBAR_WIDTH_STEP);
} else if (event.key === "Home") {
event.preventDefault();
commitWidth(MIN_SIDEBAR_WIDTH);
} else if (event.key === "End") {
event.preventDefault();
commitWidth(MAX_SIDEBAR_WIDTH);
}
},
[commitWidth, open, resizable, width],
);
return (
<div
className={cn(
"relative overflow-hidden",
!isResizing && "transition-[width] duration-100 ease-out",
className,
)}
style={paneStyle}
>
{children}
{resizable && open ? (
<div
role="separator"
aria-label="Resize sidebar"
aria-orientation="vertical"
aria-valuemin={MIN_SIDEBAR_WIDTH}
aria-valuemax={MAX_SIDEBAR_WIDTH}
aria-valuenow={width}
tabIndex={0}
className={cn(
"absolute inset-y-0 right-0 z-20 w-3 cursor-col-resize touch-none outline-none",
"before:absolute before:inset-y-0 before:left-1/2 before:w-px before:-translate-x-1/2 before:bg-transparent before:transition-colors",
"hover:before:bg-border focus-visible:before:bg-ring",
isResizing && "before:bg-ring",
)}
onPointerDown={handlePointerDown}
onPointerMove={handlePointerMove}
onPointerUp={endResize}
onPointerCancel={endResize}
onLostPointerCapture={endResize}
onKeyDown={handleKeyDown}
/>
) : null}
</div>
);
}

View file

@ -0,0 +1,196 @@
import type { ReactNode } from "react";
import { MoreHorizontal, Play } from "lucide-react";
import { Link } from "@/lib/router";
import { AgentIcon } from "@/components/AgentIconPicker";
import { Button } from "@/components/ui/button";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuSeparator,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { ToggleSwitch } from "@/components/ui/toggle-switch";
export type RoutineListProjectSummary = {
name: string;
color?: string | null;
};
export type RoutineListAgentSummary = {
name: string;
icon?: string | null;
};
export type RoutineListRowItem = {
id: string;
title: string;
status: string;
projectId: string | null;
assigneeAgentId: string | null;
lastRun?: {
triggeredAt?: Date | string | null;
status?: string | null;
} | null;
};
export function formatLastRunTimestamp(value: Date | string | null | undefined) {
if (!value) return "Never";
return new Date(value).toLocaleString();
}
export function formatRoutineRunStatus(value: string | null | undefined) {
if (!value) return null;
return value.replaceAll("_", " ");
}
export function nextRoutineStatus(currentStatus: string, enabled: boolean) {
if (currentStatus === "archived" && enabled) return "active";
return enabled ? "active" : "paused";
}
export function RoutineListRow<TRoutine extends RoutineListRowItem>({
routine,
projectById,
agentById,
runningRoutineId,
statusMutationRoutineId,
href,
configureLabel = "Edit",
managedByLabel,
secondaryDetails,
runNowButton = false,
disableRunNow = false,
disableToggle = false,
hideArchiveAction = false,
onRunNow,
onToggleEnabled,
onToggleArchived,
}: {
routine: TRoutine;
projectById: Map<string, RoutineListProjectSummary>;
agentById: Map<string, RoutineListAgentSummary>;
runningRoutineId: string | null;
statusMutationRoutineId: string | null;
href: string;
configureLabel?: string;
managedByLabel?: string | null;
secondaryDetails?: ReactNode;
runNowButton?: boolean;
disableRunNow?: boolean;
disableToggle?: boolean;
hideArchiveAction?: boolean;
onRunNow: (routine: TRoutine) => void;
onToggleEnabled: (routine: TRoutine, enabled: boolean) => void;
onToggleArchived?: (routine: TRoutine) => void;
}) {
const enabled = routine.status === "active";
const isArchived = routine.status === "archived";
const isStatusPending = statusMutationRoutineId === routine.id;
const project = routine.projectId ? projectById.get(routine.projectId) ?? null : null;
const agent = routine.assigneeAgentId ? agentById.get(routine.assigneeAgentId) ?? null : null;
const isDraft = !isArchived && !routine.assigneeAgentId;
const runDisabled = runningRoutineId === routine.id || isArchived || disableRunNow;
return (
<Link
to={href}
className="group flex flex-col gap-3 border-b border-border px-3 py-3 transition-colors hover:bg-accent/50 last:border-b-0 sm:flex-row sm:items-center no-underline text-inherit"
>
<div className="min-w-0 flex-1 space-y-1.5">
<div className="flex flex-wrap items-center gap-2">
<span className="truncate text-sm font-medium">{routine.title}</span>
{(isArchived || routine.status === "paused" || isDraft) ? (
<span className="text-xs text-muted-foreground">
{isArchived ? "archived" : isDraft ? "draft" : "paused"}
</span>
) : null}
{managedByLabel ? (
<span className="text-xs text-muted-foreground">{managedByLabel}</span>
) : null}
</div>
<div className="flex flex-wrap items-center gap-x-4 gap-y-1 text-xs text-muted-foreground">
<span className="flex items-center gap-2">
<span
className="h-2.5 w-2.5 shrink-0 rounded-sm"
style={{ backgroundColor: project?.color ?? "#64748b" }}
/>
<span>{routine.projectId ? (project?.name ?? "Unknown project") : "No project"}</span>
</span>
<span className="flex items-center gap-2">
{agent?.icon ? <AgentIcon icon={agent.icon} className="h-3.5 w-3.5 shrink-0" /> : null}
<span>{routine.assigneeAgentId ? (agent?.name ?? "Unknown agent") : "No default agent"}</span>
</span>
<span>
{formatLastRunTimestamp(routine.lastRun?.triggeredAt)}
{routine.lastRun ? ` · ${formatRoutineRunStatus(routine.lastRun.status)}` : ""}
</span>
</div>
{secondaryDetails ? (
<div className="text-xs text-muted-foreground">{secondaryDetails}</div>
) : null}
</div>
<div className="flex items-center gap-3" onClick={(event) => { event.preventDefault(); event.stopPropagation(); }}>
{runNowButton ? (
<Button
variant="ghost"
size="sm"
disabled={runDisabled}
onClick={() => onRunNow(routine)}
>
<Play className="h-3.5 w-3.5" />
{runningRoutineId === routine.id ? "Running..." : "Run now"}
</Button>
) : null}
<div className="flex items-center gap-3">
<ToggleSwitch
size="lg"
checked={enabled}
onCheckedChange={() => onToggleEnabled(routine, enabled)}
disabled={isStatusPending || isArchived || disableToggle}
aria-label={enabled ? `Disable ${routine.title}` : `Enable ${routine.title}`}
/>
<span className="w-12 text-xs text-muted-foreground">
{isArchived ? "Archived" : isDraft ? "Draft" : enabled ? "On" : "Off"}
</span>
</div>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="ghost" size="icon-sm" aria-label={`More actions for ${routine.title}`}>
<MoreHorizontal className="h-4 w-4" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<DropdownMenuItem asChild>
<Link to={href}>{configureLabel}</Link>
</DropdownMenuItem>
<DropdownMenuItem
disabled={runDisabled}
onClick={() => onRunNow(routine)}
>
{runningRoutineId === routine.id ? "Running..." : "Run now"}
</DropdownMenuItem>
<DropdownMenuSeparator />
<DropdownMenuItem
onClick={() => onToggleEnabled(routine, enabled)}
disabled={isStatusPending || isArchived || disableToggle}
>
{enabled ? "Pause" : "Enable"}
</DropdownMenuItem>
{!hideArchiveAction && onToggleArchived ? (
<DropdownMenuItem
onClick={() => onToggleArchived(routine)}
disabled={isStatusPending}
>
{routine.status === "archived" ? "Restore" : "Archive"}
</DropdownMenuItem>
) : null}
</DropdownMenuContent>
</DropdownMenu>
</div>
</Link>
);
}

View file

@ -55,7 +55,7 @@ export function Sidebar() {
};
return (
<aside className="w-60 h-full min-h-0 border-r border-border bg-background flex flex-col">
<aside className="w-full h-full min-h-0 border-r border-border bg-background flex flex-col">
{/* Top bar: Company name (bold) + Search — aligned with top sections (no visible border) */}
<div className="flex items-center gap-1 px-3 h-12 shrink-0">
<SidebarCompanyMenu />