feat(plugins): let plugin panels read and arrange a workspace's layout

useWorkspaceLayout gives a plugin a handle on a workspace's panes and tabs:
open, focus, move and close tabs, close panes, show the Explorer, and read the
layout reactively.

A tab is named as a registered panel plus params, so the SDK holds no list of
tab kinds. Built-in panels declare their public id and params on the panel
manifest, and "paseo" becomes a reserved plugin ID so "paseo/<panel>" cannot be
claimed.

The app side is a facade over the layout store and workspace-tabs, so a plugin's
open, move and close behave as the same action in the UI.
This commit is contained in:
Mohamed Boudra
2026-11-29 14:23:25 +01:00
parent 8d5fecb595
commit bf6d881ece
30 changed files with 2533 additions and 272 deletions
+3 -14
View File
@@ -3,9 +3,12 @@ import { useTranslation } from "react-i18next";
import { i18n } from "@/i18n/i18next";
import { useProviderIcon } from "@/components/provider-icons";
import type { PanelDescriptor } from "@/panels/panel-registry";
import { resolveAgentLabel } from "@/panels/tab-labels";
import { useSessionStore, selectAgentTurnPresentation, type Agent } from "@/stores/session-store";
import { deriveSidebarStateBucket } from "@/utils/sidebar-agent-state";
export { resolveAgentLabel };
function formatProviderLabel(provider: Agent["provider"]): string {
if (!provider) {
return "Agent";
@@ -17,20 +20,6 @@ function formatProviderLabel(provider: Agent["provider"]): string {
.join(" ");
}
export function resolveAgentLabel(title: string | null | undefined): string | null {
if (typeof title !== "string") {
return null;
}
const normalized = title.trim();
if (!normalized) {
return null;
}
if (normalized.toLowerCase() === "new agent") {
return null;
}
return normalized;
}
export function useAgentDescriptor(
target: { kind: "agent"; agentId: string },
context: { serverId: string },
+2 -15
View File
@@ -5,23 +5,10 @@ import invariant from "tiny-invariant";
import { BrowserPane } from "@/desktop/browser/pane";
import { usePaneContext, usePaneFocus } from "@/panels/pane-context";
import { definePanel, type PanelDescriptor, type PanelIconProps } from "@/panels/panel-registry";
import { browserTabLabel } from "@/panels/tab-labels";
import { useBrowserStore } from "@/desktop/browser/store";
import { useWorkspaceDirectory } from "@/stores/session-store-hooks";
function getBrowserLabel(input: { title: string; url: string }): string {
const title = input.title.trim();
if (title) {
return title;
}
try {
const parsed = new URL(input.url);
return parsed.hostname || input.url;
} catch {
return input.url;
}
}
function createBrowserTabIcon(faviconUrl: string | null) {
return function BrowserTabIcon({ size, color }: PanelIconProps) {
const source = useMemo(() => (faviconUrl ? { uri: faviconUrl } : undefined), []);
@@ -42,7 +29,7 @@ function useBrowserPanelDescriptor(target: {
const browser = useBrowserStore((state) => state.browsersById[target.browserId] ?? null);
const url = browser?.url ?? "https://example.com";
const icon = createBrowserTabIcon(browser?.faviconUrl ?? null);
const label = getBrowserLabel({ title: browser?.title ?? "", url });
const label = browserTabLabel({ title: browser?.title ?? "", url });
return {
label,
@@ -0,0 +1,135 @@
/** One workspace's file tree state, driven from inside and outside React. */
import {
loadExplorerDirectory,
type DirectoryListingResult,
} from "@/file-explorer/directory-listings";
import { clearFileFilter } from "@/file-explorer/filter";
import { useExplorerRevealStore } from "@/file-explorer/reveal-request";
import { revealExplorerEntry } from "@/file-explorer/tree";
import { i18n } from "@/i18n/i18next";
import { usePanelStore } from "@/stores/panel-store";
import { useSessionStore, type AgentFileExplorerState } from "@/stores/session-store";
export interface FileExplorerWorkspaceScope {
workspaceId?: string | null;
workspaceRoot?: string | null;
}
/** The tree being driven: its host, its state key, and the directory it lists. */
export interface WorkspaceFileTree {
serverId: string;
stateKey: string;
workspaceRoot: string | null;
}
function createExplorerState(): AgentFileExplorerState {
return {
listingGeneration: 0,
directories: new Map(),
isLoading: false,
lastError: null,
pendingRequest: null,
currentPath: ".",
history: ["."],
lastVisitedPath: ".",
selectedEntryPath: null,
};
}
export function normalizeWorkspaceValue(value: string | null | undefined): string | null {
if (typeof value !== "string") {
return null;
}
const trimmed = value.trim();
return trimmed.length > 0 ? trimmed : null;
}
export function buildWorkspaceExplorerStateKey(scope: FileExplorerWorkspaceScope): string | null {
const normalizedWorkspaceId = normalizeWorkspaceValue(scope.workspaceId);
if (normalizedWorkspaceId) {
return `workspace:${normalizedWorkspaceId}`;
}
const normalizedWorkspaceRoot = normalizeWorkspaceValue(scope.workspaceRoot);
if (!normalizedWorkspaceRoot) {
return null;
}
return `root:${normalizedWorkspaceRoot}`;
}
export function updateWorkspaceExplorerState(
tree: Pick<WorkspaceFileTree, "serverId" | "stateKey">,
updater: (prev: AgentFileExplorerState) => AgentFileExplorerState,
): AgentFileExplorerState | null {
let updated: AgentFileExplorerState | null = null;
useSessionStore.getState().setFileExplorer(tree.serverId, (prev) => {
const next = new Map(prev);
const current = next.get(tree.stateKey) ?? createExplorerState();
updated = updater(current);
next.set(tree.stateKey, updated);
return next;
});
return updated;
}
export function listWorkspaceExplorerDirectory(
tree: WorkspaceFileTree,
path: string,
options?: { recordHistory?: boolean; setCurrentPath?: boolean },
): Promise<DirectoryListingResult> {
const normalizedPath = path && path.length > 0 ? path : ".";
return loadExplorerDirectory({
path: normalizedPath,
options,
updateState: (updater) => updateWorkspaceExplorerState(tree, updater),
fallbackError: i18n.t("workspace.fileExplorer.errors.failedToListDirectory"),
listDirectory: async () => {
if (!tree.workspaceRoot) {
throw new Error(i18n.t("workspace.fileExplorer.states.unavailable"));
}
const client = useSessionStore.getState().sessions[tree.serverId]?.client;
if (!client) throw new Error(i18n.t("workspace.terminal.hostDisconnected"));
return client.listDirectory(tree.workspaceRoot, normalizedPath);
},
});
}
export function showWorkspaceExplorerHiddenFiles(): void {
const panel = usePanelStore.getState();
if (!panel.explorerShowHiddenFiles) panel.toggleExplorerShowHiddenFiles();
}
export function expandWorkspaceExplorerPaths(stateKey: string, paths: string[]): void {
usePanelStore
.getState()
.setExpandedPathsForWorkspace(stateKey, (current) =>
Array.from(new Set([...current, ...paths])),
);
}
/** Selects an entry the tree has expanded to, and asks the tree to scroll to it. */
export function showWorkspaceExplorerEntry(
tree: Pick<WorkspaceFileTree, "serverId" | "stateKey">,
entryPath: string,
): void {
updateWorkspaceExplorerState(tree, (state) => ({ ...state, selectedEntryPath: entryPath }));
useExplorerRevealStore.getState().request(tree.stateKey, entryPath);
}
/** Expands to an entry, selects it, and asks the tree to scroll to it. */
export async function revealWorkspaceExplorerEntry(
tree: WorkspaceFileTree,
entryPath: string,
): Promise<boolean> {
const found = await revealExplorerEntry({
entryPath,
requestDirectoryListing: (path) =>
listWorkspaceExplorerDirectory(tree, path, { recordHistory: false, setCurrentPath: false }),
showHiddenFiles: showWorkspaceExplorerHiddenFiles,
expandPaths: (paths) => expandWorkspaceExplorerPaths(tree.stateKey, paths),
});
if (found) {
clearFileFilter(tree.stateKey);
showWorkspaceExplorerEntry(tree, entryPath);
}
return found;
}
@@ -1,61 +1,32 @@
import { useCallback, useMemo } from "react";
import { useTranslation } from "react-i18next";
import { useSessionStore, type AgentFileExplorerState } from "@/stores/session-store";
import { usePanelStore } from "@/stores/panel-store";
import { revealExplorerDirectory, revealExplorerEntry } from "@/file-explorer/tree";
import { useExplorerRevealStore } from "@/file-explorer/reveal-request";
import { revealExplorerDirectory } from "@/file-explorer/tree";
import { clearFileFilter } from "@/file-explorer/filter";
import {
loadExplorerDirectory,
type DirectoryListingResult,
invalidateExplorerDirectoryListings,
} from "@/file-explorer/directory-listings";
import {
buildWorkspaceExplorerStateKey,
expandWorkspaceExplorerPaths,
listWorkspaceExplorerDirectory,
normalizeWorkspaceValue,
revealWorkspaceExplorerEntry,
showWorkspaceExplorerEntry,
showWorkspaceExplorerHiddenFiles,
updateWorkspaceExplorerState,
type FileExplorerWorkspaceScope,
type WorkspaceFileTree,
} from "@/file-explorer/workspace-tree";
import { parentExplorerPath } from "@/utils/explorer-paths";
function createExplorerState(): AgentFileExplorerState {
return {
listingGeneration: 0,
directories: new Map(),
isLoading: false,
lastError: null,
pendingRequest: null,
currentPath: ".",
history: ["."],
lastVisitedPath: ".",
selectedEntryPath: null,
};
}
export interface FileExplorerWorkspaceScope {
workspaceId?: string | null;
workspaceRoot?: string | null;
}
function normalizeWorkspaceValue(value: string | null | undefined): string | null {
if (typeof value !== "string") {
return null;
}
const trimmed = value.trim();
return trimmed.length > 0 ? trimmed : null;
}
export function buildWorkspaceExplorerStateKey(scope: FileExplorerWorkspaceScope): string | null {
const normalizedWorkspaceId = normalizeWorkspaceValue(scope.workspaceId);
if (normalizedWorkspaceId) {
return `workspace:${normalizedWorkspaceId}`;
}
const normalizedWorkspaceRoot = normalizeWorkspaceValue(scope.workspaceRoot);
if (!normalizedWorkspaceRoot) {
return null;
}
return `root:${normalizedWorkspaceRoot}`;
}
export { buildWorkspaceExplorerStateKey, type FileExplorerWorkspaceScope };
export function useFileExplorerActions(params: { serverId: string } & FileExplorerWorkspaceScope) {
const { t } = useTranslation();
const { serverId, workspaceId, workspaceRoot } = params;
const client = useSessionStore((state) => state.sessions[serverId]?.client ?? null);
const setFileExplorer = useSessionStore((state) => state.setFileExplorer);
const normalizedWorkspaceRoot = useMemo(
() => normalizeWorkspaceValue(workspaceRoot),
[workspaceRoot],
@@ -69,66 +40,28 @@ export function useFileExplorerActions(params: { serverId: string } & FileExplor
[workspaceId, normalizedWorkspaceRoot],
);
const tree = useMemo<WorkspaceFileTree | null>(
() =>
workspaceStateKey
? { serverId, stateKey: workspaceStateKey, workspaceRoot: normalizedWorkspaceRoot }
: null,
[normalizedWorkspaceRoot, serverId, workspaceStateKey],
);
const updateExplorerState = useCallback(
(
updater: (prev: AgentFileExplorerState) => AgentFileExplorerState,
): AgentFileExplorerState | null => {
if (!workspaceStateKey) {
return null;
}
let updated: AgentFileExplorerState | null = null;
setFileExplorer(serverId, (prev) => {
const next = new Map(prev);
const current = next.get(workspaceStateKey) ?? createExplorerState();
updated = updater(current);
next.set(workspaceStateKey, updated);
return next;
});
return updated;
},
[serverId, setFileExplorer, workspaceStateKey],
): AgentFileExplorerState | null => (tree ? updateWorkspaceExplorerState(tree, updater) : null),
[tree],
);
const requestDirectoryListing = useCallback(
async (
path: string,
options?: { recordHistory?: boolean; setCurrentPath?: boolean },
): Promise<DirectoryListingResult> => {
if (!workspaceStateKey) {
return null;
}
const normalizedPath = path && path.length > 0 ? path : ".";
return loadExplorerDirectory({
path: normalizedPath,
options,
updateState: updateExplorerState,
fallbackError: t("workspace.fileExplorer.errors.failedToListDirectory"),
listDirectory: async () => {
if (!normalizedWorkspaceRoot)
throw new Error(t("workspace.fileExplorer.states.unavailable"));
if (!client) throw new Error(t("workspace.terminal.hostDisconnected"));
return client.listDirectory(normalizedWorkspaceRoot, normalizedPath);
},
});
},
[client, normalizedWorkspaceRoot, t, updateExplorerState, workspaceStateKey],
);
const showHiddenFiles = useCallback(() => {
const panel = usePanelStore.getState();
if (!panel.explorerShowHiddenFiles) panel.toggleExplorerShowHiddenFiles();
}, []);
const expandPaths = useCallback(
(paths: string[]) => {
if (!workspaceStateKey) return;
usePanelStore
.getState()
.setExpandedPathsForWorkspace(workspaceStateKey, (current) =>
Array.from(new Set([...current, ...paths])),
);
},
[workspaceStateKey],
): Promise<DirectoryListingResult> =>
tree ? listWorkspaceExplorerDirectory(tree, path, options) : null,
[tree],
);
const selectExplorerEntry = useCallback(
@@ -141,50 +74,27 @@ export function useFileExplorerActions(params: { serverId: string } & FileExplor
[updateExplorerState],
);
/** Selects an entry the tree has expanded to, and asks the tree to scroll to it. */
const showEntry = useCallback(
(entryPath: string) => {
if (!workspaceStateKey) return;
selectExplorerEntry(entryPath);
useExplorerRevealStore.getState().request(workspaceStateKey, entryPath);
},
[selectExplorerEntry, workspaceStateKey],
);
/** Expands to a directory and into it. `select` also selects it and scrolls the tree to it. */
const revealDirectory = useCallback(
async (directoryPath: string, { select = false }: { select?: boolean } = {}) => {
if (!workspaceStateKey) return;
if (!tree) return;
const listed = await revealExplorerDirectory({
directoryPath,
requestDirectoryListing,
showHiddenFiles,
expandPaths,
showHiddenFiles: showWorkspaceExplorerHiddenFiles,
expandPaths: (paths) => expandWorkspaceExplorerPaths(tree.stateKey, paths),
});
clearFileFilter(workspaceStateKey);
if (listed && select) showEntry(directoryPath);
clearFileFilter(tree.stateKey);
if (listed && select) showWorkspaceExplorerEntry(tree, directoryPath);
},
[expandPaths, requestDirectoryListing, showEntry, showHiddenFiles, workspaceStateKey],
[requestDirectoryListing, tree],
);
/** Expands to an entry, selects it, and asks the tree to scroll to it. */
const revealEntry = useCallback(
async (entryPath: string): Promise<boolean> => {
if (!workspaceStateKey) return false;
const found = await revealExplorerEntry({
entryPath,
requestDirectoryListing: (path) =>
requestDirectoryListing(path, { recordHistory: false, setCurrentPath: false }),
showHiddenFiles,
expandPaths,
});
if (found) {
clearFileFilter(workspaceStateKey);
showEntry(entryPath);
}
return found;
},
[expandPaths, requestDirectoryListing, showEntry, showHiddenFiles, workspaceStateKey],
async (entryPath: string): Promise<boolean> =>
tree ? revealWorkspaceExplorerEntry(tree, entryPath) : false,
[tree],
);
const requestFileDownloadToken = useCallback(
+2 -1
View File
@@ -16,6 +16,7 @@ import { useChangesPreferences } from "@/hooks/use-changes-preferences";
import { useAppSettings } from "@/hooks/use-settings";
import { usePaneContext } from "@/panels/pane-context";
import { definePanel, type PanelDescriptor, type PanelPresentation } from "@/panels/panel-registry";
import { commitDiffTabLabel } from "@/panels/tab-labels";
import { useAddFileToChat } from "@/panels/use-add-file-to-chat";
import { useWorkspaceDirectory } from "@/stores/session-store-hooks";
import type { WorkspaceTabTarget } from "@/workspace-tabs/model";
@@ -228,7 +229,7 @@ function useCommitDiffPanelDescriptor(
): PanelDescriptor {
const { t } = useTranslation();
return {
label: target.sha.slice(0, 7),
label: commitDiffTabLabel(target.sha),
subtitle: t("panels.diff.commitSubtitle"),
tooltip: target.sha,
titleState: "ready",
@@ -1,6 +1,7 @@
import type { ComponentType } from "react";
import { i18n } from "@/i18n/i18next";
import type { PanelDescriptor, PanelIconProps } from "@/panels/panel-registry";
import { draftTabLabel } from "@/panels/tab-labels";
export function buildDraftPanelDescriptor(input: {
isCreating: boolean;
@@ -9,7 +10,7 @@ export function buildDraftPanelDescriptor(input: {
}): PanelDescriptor {
const { icon, isCreating, pendingPrompt } = input;
const newAgentLabel = i18n.t("panels.draft.newAgent");
const creatingLabel = pendingPrompt?.trim() || newAgentLabel;
const creatingLabel = draftTabLabel({ isCreating, pendingPrompt, newAgentLabel });
if (isCreating) {
return {
label: creatingLabel,
+2 -1
View File
@@ -5,6 +5,7 @@ import { useTranslation } from "react-i18next";
import { FilePane } from "@/file-pane/pane";
import { usePaneContext } from "@/panels/pane-context";
import { definePanel } from "@/panels/panel-registry";
import { fileTabLabel } from "@/panels/tab-labels";
import { useWorkspaceDirectory } from "@/stores/session-store-hooks";
import { createMaterialFileIcon } from "@/components/material-file-icon";
@@ -16,7 +17,7 @@ const CENTERED_PADDED_STYLE = {
} as const;
function useFilePanelDescriptor(target: { kind: "file"; path: string }) {
const fileName = target.path.split("/").findLast(Boolean) ?? target.path;
const fileName = fileTabLabel(target.path);
const icon = useMemo(() => createMaterialFileIcon(fileName), [fileName]);
return {
label: fileName,
@@ -60,16 +60,21 @@ export function setPanelInstanceAttributes(
for (const listener of allListeners) listener();
}
/** Calls back when any panel's attributes change. */
export function subscribeAllPanelInstanceAttributes(listener: () => void): () => void {
allListeners.add(listener);
return () => {
allListeners.delete(listener);
};
}
export function useModifiedPanelTabIds(input: {
serverId: string;
workspaceId: string;
tabIds: string[];
}): Set<string> {
const revision = useSyncExternalStore(
useCallback((listener: () => void) => {
allListeners.add(listener);
return () => allListeners.delete(listener);
}, []),
subscribeAllPanelInstanceAttributes,
() => attributesRevision,
() => attributesRevision,
);
+173
View File
@@ -1,3 +1,7 @@
import type { PluginPanelTargetParams } from "@getpaseo/plugin/client";
import { z } from "zod";
import { isAbsolutePath } from "@/utils/path";
import { normalizeWorkspaceTabTarget } from "@/workspace-tabs/identity";
import type { WorkspaceTabTarget } from "@/workspace-tabs/model";
/** Where a tab renders: a split pane, the Explorer dock, or the compact workspace sheet. */
@@ -22,6 +26,26 @@ type CompactSheetRule<K extends WorkspaceTabTarget["kind"]> =
facts: PanelTargetFacts,
) => CompactSheetPolicy | null);
/** What opening a panel by its public identity asks the workspace to do. */
export interface PanelOpenRequest {
target: WorkspaceTabTarget;
/** A workspace-relative path the panel expands to and selects once it shows. */
revealPath?: string;
}
/**
* How plugins name a kind and spell one instance of it. Ids and param names are a published
* contract: add optional params, never rename, narrow or require one.
*/
export interface PanelPublicIdentity<
K extends WorkspaceTabTarget["kind"] = WorkspaceTabTarget["kind"],
> {
publicId: `paseo/${string}`;
toParams(target: Extract<WorkspaceTabTarget, { kind: K }>): PluginPanelTargetParams;
/** Null for params this panel does not accept. */
fromParams(params: PluginPanelTargetParams): PanelOpenRequest | null;
}
export interface PanelManifest<K extends WorkspaceTabTarget["kind"] = WorkspaceTabTarget["kind"]> {
kind: K;
/** The sheet is never listed: a kind renders there exactly when it has a `compactSheet` rule. */
@@ -34,101 +58,219 @@ export interface PanelManifest<K extends WorkspaceTabTarget["kind"] = WorkspaceT
*/
compactSheet: CompactSheetRule<K>;
resourceKey(target: Extract<WorkspaceTabTarget, { kind: K }>): string;
/** One instance, such as an agent's chat or a terminal, never has a second tab. */
oneTabPerInstance: boolean;
/** Null for a kind plugins cannot open. */
public: PanelPublicIdentity<K> | null;
}
type PanelManifestByKind = {
[K in WorkspaceTabTarget["kind"]]: PanelManifest<K>;
};
function publicPanel<K extends WorkspaceTabTarget["kind"], Params>(input: {
publicId: `paseo/${string}`;
params: z.ZodType<Params>;
toRequest(params: Params): PanelOpenRequest;
toParams(target: Extract<WorkspaceTabTarget, { kind: K }>): PluginPanelTargetParams;
}): PanelPublicIdentity<K> {
return {
publicId: input.publicId,
toParams: input.toParams,
fromParams(params) {
const parsed = input.params.safeParse(params);
if (!parsed.success) return null;
const request = input.toRequest(parsed.data);
const target = normalizeWorkspaceTabTarget(request.target);
return target ? { ...request, target } : null;
},
};
}
const noParams = z.strictObject({});
const lineNumber = z.number().int().positive();
const fileParams = z
.strictObject({
path: z.string(),
lineStart: lineNumber.optional(),
lineEnd: lineNumber.optional(),
})
.refine(
({ lineStart, lineEnd }) =>
lineEnd === undefined || (lineStart !== undefined && lineEnd >= lineStart),
);
const filesParams = z.strictObject({
reveal: z
.string()
.transform((path) => path.trim().replace(/\\/g, "/"))
.refine((path) => path.length > 0 && !isAbsolutePath(path) && !path.split("/").includes(".."))
.optional(),
});
const manifests = {
new_tab: {
kind: "new_tab",
supportedHosts: ["main", "explorer"],
showCloseButton: true,
singleton: false,
oneTabPerInstance: false,
compactSheet: null,
resourceKey: () => "new_tab",
public: null,
},
draft: {
kind: "draft",
supportedHosts: ["main", "explorer"],
showCloseButton: true,
singleton: false,
oneTabPerInstance: false,
compactSheet: null,
resourceKey: (target) => target.draftId,
public: null,
},
agent: {
kind: "agent",
supportedHosts: ["main", "explorer"],
showCloseButton: true,
singleton: false,
oneTabPerInstance: true,
compactSheet: (target, facts) =>
facts.isWorkspaceRootAgent(target.agentId) ? null : { openAsTab: true },
resourceKey: (target) => target.agentId,
public: publicPanel<"agent", { agentId: string }>({
publicId: "paseo/agent",
params: z.strictObject({ agentId: z.string() }),
toRequest: ({ agentId }) => ({ target: { kind: "agent", agentId } }),
toParams: ({ agentId }) => ({ agentId }),
}),
},
provider_subagent: {
kind: "provider_subagent",
supportedHosts: ["main", "explorer"],
showCloseButton: true,
singleton: false,
oneTabPerInstance: false,
compactSheet: { openAsTab: false },
resourceKey: (target) => `${target.parentAgentId}:${target.subagentId}`,
public: publicPanel<"provider_subagent", { parentAgentId: string; subagentId: string }>({
publicId: "paseo/subagent",
params: z.strictObject({ parentAgentId: z.string(), subagentId: z.string() }),
toRequest: (params) => ({ target: { kind: "provider_subagent", ...params } }),
toParams: ({ parentAgentId, subagentId }) => ({ parentAgentId, subagentId }),
}),
},
terminal: {
kind: "terminal",
supportedHosts: ["main", "explorer"],
showCloseButton: true,
singleton: false,
oneTabPerInstance: true,
compactSheet: null,
resourceKey: (target) => target.terminalId,
public: publicPanel<"terminal", { terminalId: string }>({
publicId: "paseo/terminal",
params: z.strictObject({ terminalId: z.string() }),
toRequest: ({ terminalId }) => ({ target: { kind: "terminal", terminalId } }),
toParams: ({ terminalId }) => ({ terminalId }),
}),
},
browser: {
kind: "browser",
supportedHosts: ["main"],
showCloseButton: true,
singleton: false,
oneTabPerInstance: true,
compactSheet: null,
resourceKey: (target) => target.browserId,
public: publicPanel<"browser", { browserId: string }>({
publicId: "paseo/browser",
params: z.strictObject({ browserId: z.string() }),
toRequest: ({ browserId }) => ({ target: { kind: "browser", browserId } }),
toParams: ({ browserId }) => ({ browserId }),
}),
},
changes_tree: {
kind: "changes_tree",
supportedHosts: ["explorer"],
showCloseButton: false,
singleton: true,
oneTabPerInstance: true,
compactSheet: null,
resourceKey: () => "changes_tree",
public: publicPanel<"changes_tree", Record<string, never>>({
publicId: "paseo/changes",
params: noParams,
toRequest: () => ({ target: { kind: "changes_tree" } }),
toParams: () => ({}),
}),
},
files: {
kind: "files",
supportedHosts: ["explorer"],
showCloseButton: false,
singleton: true,
oneTabPerInstance: true,
compactSheet: null,
resourceKey: () => "files",
public: publicPanel<"files", { reveal?: string }>({
publicId: "paseo/files",
params: filesParams,
toRequest: ({ reveal }) => ({ target: { kind: "files" }, revealPath: reveal }),
// A reveal is something to do once, not part of which tab this is.
toParams: () => ({}),
}),
},
pull_request: {
kind: "pull_request",
supportedHosts: ["main", "explorer"],
showCloseButton: true,
singleton: false,
oneTabPerInstance: false,
compactSheet: null,
resourceKey: () => "pull_request",
public: publicPanel<"pull_request", Record<string, never>>({
publicId: "paseo/pull-request",
params: noParams,
toRequest: () => ({ target: { kind: "pull_request" } }),
toParams: () => ({}),
}),
},
file: {
kind: "file",
supportedHosts: ["main", "explorer"],
showCloseButton: true,
singleton: false,
oneTabPerInstance: false,
compactSheet: { openAsTab: false },
resourceKey: (target) => target.path,
public: publicPanel<"file", z.infer<typeof fileParams>>({
publicId: "paseo/file",
params: fileParams,
toRequest: (params) => ({ target: { kind: "file", ...params } }),
toParams: ({ path, lineStart, lineEnd }) => ({
path,
...(lineStart ? { lineStart } : {}),
...(lineEnd ? { lineEnd } : {}),
}),
}),
},
working_diff: {
kind: "working_diff",
supportedHosts: ["main", "explorer"],
showCloseButton: true,
singleton: false,
oneTabPerInstance: false,
compactSheet: null,
resourceKey: () => "working_diff",
public: publicPanel<"working_diff", Record<string, never>>({
publicId: "paseo/diff",
params: noParams,
toRequest: () => ({ target: { kind: "working_diff" } }),
toParams: () => ({}),
}),
},
plugin: {
kind: "plugin",
@@ -136,27 +278,39 @@ const manifests = {
supportedHosts: ["main", "explorer"],
showCloseButton: true,
singleton: false,
oneTabPerInstance: false,
compactSheet: null,
resourceKey: (target) =>
target.context === "agent"
? `${target.pluginId}:${target.panelId}:agent:${target.agentId}`
: `${target.pluginId}:${target.panelId}:workspace`,
// Plugin panels are named by their registration, not by this kind.
public: null,
},
setup: {
kind: "setup",
supportedHosts: ["main"],
showCloseButton: true,
singleton: false,
oneTabPerInstance: false,
compactSheet: null,
resourceKey: (target) => target.workspaceId,
public: null,
},
commit_diff: {
kind: "commit_diff",
supportedHosts: ["main", "explorer"],
showCloseButton: true,
singleton: false,
oneTabPerInstance: false,
compactSheet: null,
resourceKey: (target) => target.sha,
public: publicPanel<"commit_diff", { sha: string }>({
publicId: "paseo/commit-diff",
params: z.strictObject({ sha: z.string() }),
toRequest: ({ sha }) => ({ target: { kind: "commit_diff", sha } }),
toParams: ({ sha }) => ({ sha }),
}),
},
} satisfies PanelManifestByKind;
@@ -189,3 +343,22 @@ export function panelResourceKey(target: WorkspaceTabTarget): string {
const manifest = getPanelManifest(target.kind);
return `${target.kind}:${manifest.resourceKey(target as never)}`;
}
/** How plugins read a built-in tab back. A kind they cannot open reads as its kind name. */
export function panelPublicReference(target: Exclude<WorkspaceTabTarget, { kind: "plugin" }>): {
panelId: string;
params: PluginPanelTargetParams;
} {
const identity = getPanelManifest(target.kind).public;
if (!identity) return { panelId: `paseo/${target.kind}`, params: {} };
return { panelId: identity.publicId, params: identity.toParams(target as never) };
}
export function findPublicPanel(publicId: string): PanelPublicIdentity | null {
for (const manifest of Object.values(manifests)) {
if (manifest.public?.publicId === publicId) {
return manifest.public as unknown as PanelPublicIdentity;
}
}
return null;
}
@@ -15,6 +15,7 @@ import type { AgentScreenAgent } from "@/hooks/use-agent-screen-state-machine";
import { usePaneContext } from "@/panels/pane-context";
import { PaneSubtitle } from "@/panels/pane-subtitle";
import { definePanel, type PanelDescriptor } from "@/panels/panel-registry";
import { providerSubagentTabLabel } from "@/panels/tab-labels";
import { useSessionStore } from "@/stores/session-store";
import type { SheetTab } from "@/stores/workspace-layout-store";
import { ParentAgentCallout } from "@/subagents/parent";
@@ -96,9 +97,8 @@ function useProviderSubagentDescriptor(
(state) => state.sessions[context.serverId]?.agents.get(target.parentAgentId)?.provider,
);
const provider = descriptor?.provider ?? parentProvider ?? "agent";
// The task names the tab; the subagent type is supporting detail beside the provider.
const subagentType = descriptor?.title?.trim();
const label = descriptor?.description?.trim() || subagentType || "Subagent";
const label = providerSubagentTabLabel(descriptor);
const providerLabel = `${formatProviderLabel(provider)} subagent`;
return {
label,
+60
View File
@@ -0,0 +1,60 @@
/** Naming rules shared by a tab's React descriptor and the title read outside React. */
/** Null until the agent has a name of its own. */
export function resolveAgentLabel(title: string | null | undefined): string | null {
if (typeof title !== "string") {
return null;
}
const normalized = title.trim();
if (!normalized) {
return null;
}
if (normalized.toLowerCase() === "new agent") {
return null;
}
return normalized;
}
export function terminalTabLabel(
terminal: { title?: string | null; name?: string | null } | null | undefined,
fallback: string,
): string {
return (terminal?.title ?? terminal?.name)?.trim() || fallback;
}
export function browserTabLabel(input: { title: string; url: string }): string {
const title = input.title.trim();
if (title) {
return title;
}
try {
const parsed = new URL(input.url);
return parsed.hostname || input.url;
} catch {
return input.url;
}
}
// The task names the tab; the subagent type is supporting detail.
export function providerSubagentTabLabel(
descriptor: { description?: string | null; title?: string | null } | null | undefined,
): string {
return descriptor?.description?.trim() || descriptor?.title?.trim() || "Subagent";
}
export function draftTabLabel(input: {
isCreating: boolean;
pendingPrompt?: string | null;
newAgentLabel: string;
}): string {
return (input.isCreating && input.pendingPrompt?.trim()) || input.newAgentLabel;
}
export function fileTabLabel(path: string): string {
return path.split("/").findLast(Boolean) ?? path;
}
export function commitDiffTabLabel(sha: string): string {
return sha.slice(0, 7);
}
+141
View File
@@ -0,0 +1,141 @@
import type { ListTerminalsResponse } from "@getpaseo/protocol/messages";
import { queryClient } from "@/data/query-client";
import { useBrowserStore } from "@/desktop/browser/store";
import type { CheckoutPrStatusPayload } from "@/git/pr-status";
import { formatPrTabLabel } from "@/git/pull-request-panel/tab-label";
import { checkoutPrStatusQueryKey } from "@/git/query-keys";
import { i18n } from "@/i18n/i18next";
import {
browserTabLabel,
commitDiffTabLabel,
draftTabLabel,
fileTabLabel,
providerSubagentTabLabel,
resolveAgentLabel,
terminalTabLabel,
} from "@/panels/tab-labels";
import { pluginRegistry } from "@/plugins/registry";
import { resolvePluginWorkspacePanel } from "@/plugins/workspace-panels/resolution";
import { buildTerminalsQueryKey } from "@/screens/workspace/terminals/state";
import { useCreateFlowStore } from "@/stores/create-flow-store";
import { useSessionStore } from "@/stores/session-store";
import { selectWorkspaceDirectory } from "@/stores/session-store-hooks/selectors";
import { providerSubagentKey, useProviderSubagentStore } from "@/subagents/provider-store";
import type { PluginWorkspaceTabTarget, WorkspaceTabTarget } from "@/workspace-tabs/model";
interface TabTitleInput {
serverId: string;
workspaceId: string;
target: WorkspaceTabTarget;
}
/**
* What a tab is called, from what the client already holds. Reads only: a terminal or pull
* request nobody has loaded yet keeps its generic name.
*/
export function readTabTitle({ serverId, workspaceId, target }: TabTitleInput): string {
switch (target.kind) {
case "new_tab":
return i18n.t("workspace.tabs.actions.newTab");
case "draft":
return readDraftTitle(serverId, target.draftId);
case "agent":
return readAgentTitle(serverId, target.agentId);
case "provider_subagent":
return providerSubagentTabLabel(
useProviderSubagentStore
.getState()
.descriptors.get(providerSubagentKey(serverId, target.parentAgentId, target.subagentId)),
);
case "terminal":
return readTerminalTitle(serverId, workspaceId, target.terminalId);
case "browser": {
const browser = useBrowserStore.getState().browsersById[target.browserId];
return browserTabLabel({
title: browser?.title ?? "",
url: browser?.url ?? "https://example.com",
});
}
case "changes_tree":
return i18n.t("panels.diff.changesLabel");
case "files":
return i18n.t("panels.files.label");
case "pull_request":
return readPullRequestTitle(serverId, workspaceId);
case "file":
return fileTabLabel(target.path);
case "working_diff":
return i18n.t("panels.diff.diffLabel");
case "plugin":
return readPluginPanelTitle(serverId, target);
case "setup":
return i18n.t("workspace.setup.descriptor.label");
case "commit_diff":
return commitDiffTabLabel(target.sha);
}
}
/** Calls back whenever a title may read differently. */
export function subscribeTabTitles(listener: () => void): () => void {
i18n.on("languageChanged", listener);
const releases = [
useSessionStore.subscribe(listener),
useCreateFlowStore.subscribe(listener),
useProviderSubagentStore.subscribe(listener),
useBrowserStore.subscribe(listener),
queryClient.getQueryCache().subscribe(listener),
pluginRegistry.subscribe(listener),
() => {
i18n.off("languageChanged", listener);
},
];
return () => {
for (const release of releases) release();
};
}
function readDraftTitle(serverId: string, draftId: string): string {
const pending = useCreateFlowStore.getState().pendingByDraftId[draftId];
return draftTabLabel({
isCreating: pending?.serverId === serverId && pending.lifecycle === "active",
pendingPrompt: pending?.text,
newAgentLabel: i18n.t("panels.draft.newAgent"),
});
}
function readAgentTitle(serverId: string, agentId: string): string {
const session = useSessionStore.getState().sessions[serverId];
const agent = session?.agents.get(agentId) ?? session?.agentDetails.get(agentId);
return resolveAgentLabel(agent?.title) ?? "";
}
function readTerminalTitle(serverId: string, workspaceId: string, terminalId: string): string {
const directory = selectWorkspaceDirectory(useSessionStore.getState(), serverId, workspaceId);
const list = queryClient.getQueryData<ListTerminalsResponse["payload"]>(
buildTerminalsQueryKey(serverId, directory, workspaceId),
);
return terminalTabLabel(
list?.terminals.find((terminal) => terminal.id === terminalId),
i18n.t("workspace.tabs.fallback.terminal"),
);
}
function readPullRequestTitle(serverId: string, workspaceId: string): string {
const directory = selectWorkspaceDirectory(useSessionStore.getState(), serverId, workspaceId);
const payload = queryClient.getQueryData<CheckoutPrStatusPayload>(
checkoutPrStatusQueryKey(serverId, directory ?? ""),
);
const prNumber = payload?.status?.number ?? null;
return prNumber === null ? i18n.t("panels.pullRequest.label") : formatPrTabLabel(prNumber);
}
function readPluginPanelTitle(serverId: string, target: PluginWorkspaceTabTarget): string {
const plugin =
pluginRegistry
.getSnapshot()
.find((candidate) => candidate.serverId === serverId && candidate.id === target.pluginId) ??
null;
const panel = resolvePluginWorkspacePanel(plugin, target);
if (!plugin || !panel) return "Plugin unavailable";
return plugin.i18n.resolve(panel.title, plugin.locale);
}
+2 -11
View File
@@ -10,6 +10,7 @@ import { TerminalPane } from "@/components/terminal-pane";
import { openUrlInWorkspaceBrowser } from "@/desktop/browser/open-url-in-workspace";
import { usePaneContext, usePaneFocus } from "@/panels/pane-context";
import { definePanel, type PanelDescriptor } from "@/panels/panel-registry";
import { terminalTabLabel } from "@/panels/tab-labels";
import { queryClient } from "@/data/query-client";
import { buildTerminalsQueryKey } from "@/screens/workspace/terminals/state";
import { showExplorerSidebar } from "@/workspace-tabs/explorer-sidebar";
@@ -27,14 +28,6 @@ const CENTERED_PADDED_STYLE = {
padding: 16,
} as const;
function trimNonEmpty(value: string | null | undefined): string | null {
if (typeof value !== "string") {
return null;
}
const trimmed = value.trim();
return trimmed.length > 0 ? trimmed : null;
}
function useTerminalPanelDescriptor(
target: { kind: "terminal"; terminalId: string },
context: { serverId: string; workspaceId: string },
@@ -64,9 +57,7 @@ function useTerminalPanelDescriptor(
);
const terminal =
terminalsQuery.data?.terminals.find((entry) => entry.id === target.terminalId) ?? null;
const label =
trimNonEmpty(terminal?.title ?? terminal?.name ?? null) ??
t("workspace.tabs.fallback.terminal");
const label = terminalTabLabel(terminal, t("workspace.tabs.fallback.terminal"));
return {
label,
@@ -1,16 +1,26 @@
import { PluginTranslationRuntime } from "@getpaseo/plugin/client/host";
import { usePaseo, useRpc, useWorkspace, useWorkspaces } from "@getpaseo/plugin/client";
import {
usePaseo,
useRpc,
useWorkspace,
useWorkspaceLayout,
useWorkspaces,
type PluginWorkspaceLayout,
} from "@getpaseo/plugin/client";
import { defineRpc } from "@getpaseo/plugin";
import { createPaseoApi, type PaseoApi } from "@getpaseo/client";
import { DaemonClient } from "@getpaseo/client/internal/daemon-client";
import { QueryClient } from "@tanstack/react-query";
import React from "react";
import { renderToStaticMarkup } from "react-dom/server";
import { expect, it } from "vitest";
import { expect, it, vi } from "vitest";
import { z } from "zod";
import type { PluginWorkspaceSnapshot } from "@getpaseo/plugin";
import type { PluginClientStateSource } from "@getpaseo/plugin/client/host";
import type { ToastApi } from "@/components/toast-host";
import { useSessionStore, type WorkspaceDescriptor } from "@/stores/session-store";
import { useWorkspaceLayoutStore } from "@/stores/workspace-layout-store";
import { seedSessionWorkspaces } from "@/test/seed-session";
import { PluginInstallationProvider } from "./installation-provider";
import { PluginEnvironmentProvider } from "./popover";
import type { InstalledPlugin } from "./types";
@@ -144,3 +154,45 @@ it("lets a surface read the state source its host passes", async () => {
plugin.lifetime.abort();
await plugin.paseo.dispose();
});
it("lets a surface arrange a workspace's layout and read it reactively", async () => {
await vi.waitFor(() => expect(useWorkspaceLayoutStore.persist.hasHydrated()).toBe(true));
const plugin = installation([]);
useSessionStore.getState().initializeSession("host", {} as DaemonClient);
seedSessionWorkspaces(
"host",
new Map([
[
"ws",
{
id: "ws",
projectId: "project",
projectDisplayName: "project",
projectRootPath: "/repo",
workspaceDirectory: "/repo",
projectKind: "git",
} as WorkspaceDescriptor,
],
]),
);
let handle: PluginWorkspaceLayout | null = null;
function Surface() {
handle = useWorkspaceLayout("ws");
const focused = useWorkspaceLayout("ws", (state) =>
state.tabs.find((tab) => tab.id === state.focusedTabId),
);
return <span>{focused?.panelId}</span>;
}
const render = () =>
renderToStaticMarkup(
<PluginInstallationProvider plugin={plugin}>
<Surface />
</PluginInstallationProvider>,
);
expect(render()).toBe("<span>paseo/new_tab</span>");
handle!.open({ panelId: "paseo/file", params: { path: "src/a.ts" } });
expect(render()).toBe("<span>paseo/file</span>");
plugin.lifetime.abort();
await plugin.paseo.dispose();
});
@@ -6,12 +6,14 @@ import {
PluginComposersProvider,
PluginRpcProvider,
PluginTranslationProvider,
PluginWorkspaceLayoutProvider,
type PluginClientStateSource,
} from "@getpaseo/plugin/client/host";
import React, { createContext, useCallback, useContext, useMemo, type ReactNode } from "react";
import { createPluginClientStateSource } from "./client-state/source";
import { pluginComposersSource } from "./composer-items/source";
import type { InstalledPlugin } from "./types";
import { pluginWorkspaceLayoutSource } from "./workspace-layout";
const PluginInstallationServerIdContext = createContext<string | undefined>(undefined);
@@ -33,6 +35,23 @@ export function usePluginInstallationServerIdBridge() {
);
}
/** Where the handle hooks, such as `useComposer` and `useWorkspaceLayout`, get their handles. */
function PluginHandleSources({
plugin,
children,
}: {
plugin: InstalledPlugin;
children: ReactNode;
}) {
return (
<PluginComposersProvider source={pluginComposersSource(plugin)}>
<PluginWorkspaceLayoutProvider source={pluginWorkspaceLayoutSource(plugin)}>
{children}
</PluginWorkspaceLayoutProvider>
</PluginComposersProvider>
);
}
/**
* Every plugin surface renders under its installation: one query cache, one Paseo client, RPCs,
* and the state the plugin state hooks read. That state is scoped to the installation's host
@@ -57,9 +76,9 @@ export function PluginInstallationProvider({
<PaseoApiProvider paseo={getPluginClientApi(plugin).paseo}>
<PluginRpcProvider invoke={plugin.invoke} subscribe={plugin.subscribe}>
<PluginTranslationProvider runtime={plugin.i18n}>
<PluginComposersProvider source={pluginComposersSource(plugin)}>
<PluginHandleSources plugin={plugin}>
<PluginClientStateProvider source={state}>{children}</PluginClientStateProvider>
</PluginComposersProvider>
</PluginHandleSources>
</PluginTranslationProvider>
</PluginRpcProvider>
</PaseoApiProvider>
@@ -0,0 +1,823 @@
import type { DaemonClient } from "@getpaseo/client/internal/daemon-client";
import {
PluginWorkspaceUnavailableError,
type PluginPanelTarget,
type PluginTabPlacement,
type PluginWorkspaceLayout,
} from "@getpaseo/plugin/client";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { setPanelInstanceAttributes } from "@/panels/panel-instance-attributes";
import { usePanelStore } from "@/stores/panel-store";
import { useSessionStore, type Agent, type WorkspaceDescriptor } from "@/stores/session-store";
import {
collectAllPanes,
collectAllTabs,
useWorkspaceLayoutStore,
type SplitNode,
} from "@/stores/workspace-layout-store";
import { seedSessionHosts, seedSessionWorkspaces } from "@/test/seed-session";
import { pluginRegistry } from "../registry";
import { pluginWorkspaceLayoutSource } from "./index";
const SERVER_ID = "server-layout";
const WORKSPACE_ID = "workspace-1";
const WORKSPACE_KEY = `${SERVER_ID}:${WORKSPACE_ID}`;
const MODES = ["compact", "single-pane", "split-panes"] as const;
const initialPanelState = usePanelStore.getState();
/** An in-memory daemon: one `src` directory, and a record of what it was asked to archive. */
function createFakeDaemon() {
const archived: string[] = [];
const entry = (name: string, path: string, kind: "file" | "directory") => ({
name,
path,
kind,
size: 0,
modifiedAt: "2026-11-01T00:00:00.000Z",
});
const directories: Record<string, ReturnType<typeof entry>[]> = {
".": [entry("src", "src", "directory")],
src: [entry("a.ts", "src/a.ts", "file")],
};
return {
archived,
client: {
observeEvents: () => ({
ready: Promise.resolve({ subscriptionId: "events" }),
subscribe: () => () => undefined,
release: async () => undefined,
}),
async listDirectory(_root: string, path: string) {
return { path, entries: directories[path] ?? [] };
},
async archiveAgent(agentId: string) {
archived.push(agentId);
return { archivedAt: "2026-11-01T00:00:00.000Z" };
},
} as unknown as DaemonClient,
};
}
/** A plugin as the daemon catalog delivers it, registering panels the way an author does. */
function bundle(id: string, register: string) {
return {
id,
requirements: { paseo: ">=0.8.0" },
clientBundle: `(function() { return { default: function(plugin) {
const Component = function() { return null; };
${register}
return function() {};
} }; })`,
};
}
function workspacePanel(id: string, locations?: readonly string[]): string {
return `plugin.addWorkspacePanel({ id: "${id}", title: "${id}", icon: "Square", Component, locations: ${JSON.stringify(locations)} });`;
}
const REVIEW_PANELS = [
workspacePanel("overview"),
workspacePanel("tree", ["explorer"]),
workspacePanel("notes", ["workspace", "explorer"]),
`plugin.addAgentPanel({ id: "chat", title: "chat", icon: "Square", Component });`,
].join("\n");
let daemon: ReturnType<typeof createFakeDaemon>;
function install(reviewPanels = REVIEW_PANELS): void {
pluginRegistry.installCatalog(
SERVER_ID,
[bundle("review", reviewPanels), bundle("other", workspacePanel("board"))],
{ client: daemon.client, audio: { play: async () => 0 } },
);
}
function handle(workspaceId = WORKSPACE_ID): PluginWorkspaceLayout {
const plugin = pluginRegistry.getSnapshot().find((candidate) => candidate.id === "review");
if (!plugin) throw new Error("The review plugin is not installed");
return pluginWorkspaceLayoutSource(plugin).layout(workspaceId);
}
function descriptor(id = WORKSPACE_ID): WorkspaceDescriptor {
return {
createdAt: null,
lastUserMessageAt: null,
id,
projectId: "project-1",
projectDisplayName: "project",
projectRootPath: "/repo",
workspaceDirectory: "/repo",
projectKind: "git",
workspaceKind: "local_checkout",
name: "main",
status: "done",
diffStat: null,
scripts: [],
statusEnteredAt: null,
archivingAt: null,
};
}
function seedAgent(id: string, title: string): void {
const agent: Agent = {
serverId: SERVER_ID,
id,
provider: "codex",
status: "idle",
createdAt: new Date("2026-04-01T03:00:00.000Z"),
updatedAt: new Date("2026-04-01T03:00:00.000Z"),
lastUserMessageAt: null,
lastActivityAt: new Date("2026-04-01T03:00:00.000Z"),
capabilities: {
supportsStreaming: true,
supportsSessionPersistence: true,
supportsDynamicModes: true,
supportsMcpServers: true,
supportsReasoningStream: true,
supportsToolInvocations: true,
},
currentModeId: null,
availableModes: [],
pendingPermissions: [],
persistence: null,
title,
cwd: "/repo",
model: null,
parentAgentId: null,
labels: {},
archivedAt: null,
turn: { phase: "idle", cancellationRequestId: null },
};
useSessionStore.getState().setAgents(SERVER_ID, (current) => new Map(current).set(id, agent));
}
function setMode(mode: (typeof MODES)[number]): void {
useWorkspaceLayoutStore.getState().setLayoutMode(mode);
}
function setModified(tabId: string, modified: boolean): void {
setPanelInstanceAttributes(
{ serverId: SERVER_ID, workspaceId: WORKSPACE_ID, tabId },
{ modified },
);
}
function tab(layout: PluginWorkspaceLayout, tabId: string) {
const found = layout.get().tabs.find((candidate) => candidate.id === tabId);
if (!found) throw new Error(`Tab ${tabId} is not listed`);
return found;
}
function tabIds(layout: PluginWorkspaceLayout): string[] {
return layout.get().tabs.map((open) => open.id);
}
function mainPaneIds(layout: PluginWorkspaceLayout): string[] {
return layout
.get()
.panes.filter((pane) => pane.kind === "main")
.map((pane) => pane.id);
}
function explorerPaneId(): string {
const paneId =
useWorkspaceLayoutStore.getState().explorerSidebarPaneIdByWorkspace[WORKSPACE_KEY] ??
"explorer";
return paneId;
}
/** The share of its parent each child of the outermost split takes. */
function rootSizes(): number[] {
const root: SplitNode = useWorkspaceLayoutStore.getState().layoutByWorkspace[WORKSPACE_KEY].root;
return root.kind === "group" ? root.group.sizes : [1];
}
/** Stands in for the platform's confirm dialog, which Node does not have. */
function answerDialogs(): { prompts: string[]; answer: boolean; restore: () => void } {
const platform = globalThis as { confirm?: (message: string) => boolean };
const original = platform.confirm;
const dialog = {
prompts: [] as string[],
answer: false,
restore: () => {
platform.confirm = original;
},
};
platform.confirm = (message) => {
dialog.prompts.push(message);
return dialog.answer;
};
return dialog;
}
const file = (path: string): PluginPanelTarget => ({ panelId: "paseo/file", params: { path } });
beforeEach(async () => {
await vi.waitFor(() => expect(useWorkspaceLayoutStore.persist.hasHydrated()).toBe(true));
useSessionStore.setState((state) => ({ ...state, sessions: {} }));
usePanelStore.setState(initialPanelState, true);
useWorkspaceLayoutStore.setState({
layoutMode: "split-panes",
sheetsByWorkspace: {},
layoutByWorkspace: {},
splitSizesByWorkspace: {},
explorerSidebarPaneIdByWorkspace: {},
sidePaneIdByWorkspace: {},
hiddenAgentIdsByWorkspace: {},
pinnedAgentIdsByWorkspace: {},
focusRestorationByWorkspace: {},
});
daemon = createFakeDaemon();
seedSessionHosts([SERVER_ID]);
useSessionStore.getState().updateSessionClient(SERVER_ID, daemon.client);
seedSessionWorkspaces(SERVER_ID, new Map([[WORKSPACE_ID, descriptor()]]));
install();
});
afterEach(() => {
const layout = useWorkspaceLayoutStore.getState().layoutByWorkspace[WORKSPACE_KEY];
for (const open of layout ? collectAllTabs(layout.root) : []) setModified(open.tabId, false);
pluginRegistry.removeHost(SERVER_ID);
seedSessionHosts([]);
});
describe("reading the layout", () => {
it("describes a workspace nobody has arranged, with the Explorer hidden", () => {
const layout = handle();
const state = layout.get();
expect(state.panes).toEqual([
{ id: "main", kind: "main", tabIds: expect.any(Array), activeTabId: expect.any(String) },
]);
expect(state.explorer).toEqual({ visible: false });
expect(state.focusedPaneId).toBe("main");
expect(state.focusedTabId).toBe(state.panes[0].activeTabId);
expect(state.tabs.map(({ panelId, paneId }) => ({ panelId, paneId }))).toEqual([
{ panelId: "paseo/new_tab", paneId: "main" },
{ panelId: "paseo/files", paneId: "explorer" },
{ panelId: "paseo/changes", paneId: "explorer" },
]);
expect(tab(layout, state.tabs[1].id).locations).toEqual(["explorer"]);
});
it("lists the Explorer as a pane while it is visible", () => {
const layout = handle();
layout.explorer.show();
expect(layout.get().explorer).toEqual({ visible: true });
expect(layout.get().panes.map((pane) => pane.kind)).toEqual(["main", "explorer"]);
layout.explorer.toggle();
expect(layout.get().explorer).toEqual({ visible: false });
expect(layout.get().panes.map((pane) => pane.kind)).toEqual(["main"]);
});
it("returns the same object until something it reports changes", () => {
const layout = handle();
const before = layout.get();
expect(layout.get()).toBe(before);
usePanelStore.getState().toggleExplorerShowHiddenFiles();
expect(layout.get()).toBe(before);
layout.open(file("src/a.ts"));
expect(layout.get()).not.toBe(before);
});
it("reports changes to subscribers, including titles and unsaved work", () => {
const layout = handle();
seedAgent("a1", "First title");
const { tabId } = layout.open({ panelId: "paseo/agent", params: { agentId: "a1" } });
const events: unknown[] = [];
const unsubscribe = layout.subscribe((event) => events.push(event));
expect(tab(layout, tabId).title).toBe("First title");
seedAgent("a1", "Second title");
expect(tab(layout, tabId).title).toBe("Second title");
expect(events).toEqual([{ type: "changed" }]);
setModified(tabId, true);
expect(tab(layout, tabId).modified).toBe(true);
expect(events).toHaveLength(2);
unsubscribe();
layout.explorer.show();
expect(events).toHaveLength(2);
});
it("hands out one handle per workspace", () => {
expect(handle()).toBe(handle());
expect(handle().workspaceId).toBe(WORKSPACE_ID);
});
});
describe("a workspace this client does not know", () => {
it("reads as empty and fires once the workspace arrives", () => {
const layout = handle("workspace-2");
const events: unknown[] = [];
const unsubscribe = layout.subscribe((event) => events.push(event));
expect(layout.get()).toEqual({
panes: [],
tabs: [],
focusedPaneId: null,
focusedTabId: null,
explorer: { visible: false },
});
seedSessionWorkspaces(
SERVER_ID,
new Map([
[WORKSPACE_ID, descriptor()],
["workspace-2", descriptor("workspace-2")],
]),
);
expect(events).toEqual([{ type: "changed" }]);
expect(layout.get().panes).toHaveLength(1);
unsubscribe();
});
it("rejects every command", () => {
const layout = handle("missing");
const commands = [
() => layout.open({ panelId: "overview" }),
() => layout.focus("tab"),
() => layout.close("tab"),
() => layout.move("tab", { type: "focused" }),
() => layout.closePane("main"),
() => layout.explorer.show(),
() => layout.explorer.hide(),
() => layout.explorer.toggle(),
];
for (const command of commands) expect(command).toThrow(PluginWorkspaceUnavailableError);
expect(useWorkspaceLayoutStore.getState().layoutByWorkspace).toEqual({});
});
});
describe.each(MODES)("placing a tab in the %s layout", (mode) => {
beforeEach(() => setMode(mode));
const splits = mode === "split-panes";
it("uses the focused pane by default and when asked", () => {
const layout = handle();
expect(layout.open({ panelId: "overview" }).paneId).toBe("main");
expect(layout.open({ panelId: "notes" }, { placement: { type: "focused" } }).paneId).toBe(
"main",
);
expect(mainPaneIds(layout)).toEqual(["main"]);
});
it("sends a panel that cannot be in a main pane to the Explorer", () => {
const layout = handle();
const location = layout.open({ panelId: "tree" });
expect(location.paneId).toBe("explorer");
expect(layout.get().explorer.visible).toBe(true);
expect(tab(layout, location.tabId).locations).toEqual(["explorer"]);
});
it("opens in the Explorer on request, by placement or by its pane id", () => {
const layout = handle();
expect(layout.open({ panelId: "notes" }, { placement: { type: "explorer" } }).paneId).toBe(
"explorer",
);
const inExplorer = layout.open(file("src/a.ts"), {
placement: { type: "pane", paneId: explorerPaneId() },
});
expect(inExplorer.paneId).toBe("explorer");
expect(layout.get().explorer.visible).toBe(true);
// The Explorer shows the tab without taking focus from the main pane.
expect(layout.get().panes.find((pane) => pane.kind === "explorer")?.activeTabId).toBe(
inExplorer.tabId,
);
expect(layout.get().focusedPaneId).toBe("main");
});
it(splits ? "opens in the named pane" : "means the main pane when a pane is named", () => {
const layout = handle();
const right = splits
? layout.open(
{ panelId: "overview" },
{ placement: { type: "split", paneId: "main", side: "right" } },
).paneId
: "stale-pane-id";
const location = layout.open(
{ panelId: "notes" },
{ placement: { type: "pane", paneId: right as string } },
);
expect(location.paneId).toBe(splits ? right : "main");
});
it(splits ? "opens beside, reusing the side pane" : "opens beside in the main pane", () => {
const layout = handle();
const first = layout.open({ panelId: "overview" }, { placement: { type: "beside" } });
const second = layout.open({ panelId: "notes" }, { placement: { type: "beside" } });
expect(second.paneId).toBe(first.paneId);
expect(first.paneId === "main").toBe(!splits);
expect(mainPaneIds(layout)).toHaveLength(splits ? 2 : 1);
});
it(splits ? "splits a pane at the size asked for" : "does not split", () => {
const layout = handle();
const location = layout.open(
{ panelId: "overview" },
{ placement: { type: "split", paneId: "main", side: "right", size: 0.3 } },
);
if (!splits) {
expect(location.paneId).toBe("main");
expect(mainPaneIds(layout)).toEqual(["main"]);
return;
}
expect(mainPaneIds(layout)).toEqual(["main", location.paneId]);
const sizes = rootSizes();
expect(sizes[1] / (sizes[0] + sizes[1])).toBeCloseTo(0.3);
});
it("refuses to split the Explorer", () => {
const layout = handle();
const before = layout.get();
expect(() =>
layout.open(
{ panelId: "notes" },
{ placement: { type: "split", paneId: explorerPaneId(), side: "bottom" } },
),
).toThrow("The Explorer cannot be split");
expect(layout.get()).toBe(before);
});
it("moves an open tab to the Explorer and back", () => {
const layout = handle();
const { tabId } = layout.open({ panelId: "notes" });
expect(layout.move(tabId, { type: "explorer" })).toEqual({ tabId, paneId: "explorer" });
expect(layout.get().explorer.visible).toBe(false);
expect(layout.move(tabId, { type: "focused" }).paneId).toBe("main");
});
it("shows the Explorer to focus a tab in it, and puts it behind a main pane tab", () => {
const layout = handle();
const inExplorer = layout.open({ panelId: "tree" }, { intent: "background" });
layout.focus(inExplorer.tabId);
expect(layout.get().explorer.visible).toBe(true);
const inMain = layout.open({ panelId: "overview" });
expect(layout.get().focusedTabId).toBe(inMain.tabId);
// A phone's Explorer covers the workspace, so showing a main pane tab has to close it.
expect(layout.get().explorer.visible).toBe(mode !== "compact");
});
it(splits ? "moves a tab beside and into a split" : "keeps a moved tab in the main pane", () => {
const layout = handle();
layout.open({ panelId: "overview" });
const { tabId } = layout.open({ panelId: "notes" });
const beside = layout.move(tabId, { type: "beside" });
expect(beside.paneId === "main").toBe(!splits);
const split = layout.move(tabId, {
type: "split",
paneId: "main",
side: "bottom",
size: 0.25,
});
expect(split.paneId === "main").toBe(!splits);
expect(tab(layout, tabId).paneId).toBe(split.paneId);
});
});
describe("placements the layout cannot satisfy", () => {
it("throws for a pane that does not exist, leaving the layout alone", () => {
const layout = handle();
const { tabId } = layout.open({ panelId: "overview" });
const before = layout.get();
const placements: PluginTabPlacement[] = [
{ type: "pane", paneId: "gone" },
{ type: "split", paneId: "gone", side: "right" },
];
for (const placement of placements) {
expect(() => layout.open({ panelId: "notes" }, { placement })).toThrow(
'Pane "gone" does not exist',
);
expect(() => layout.move(tabId, placement)).toThrow('Pane "gone" does not exist');
}
expect(layout.get()).toBe(before);
});
it("throws when moving a tab that is not open", () => {
expect(() => handle().move("missing", { type: "focused" })).toThrow(
'Tab "missing" is not open',
);
});
it("keeps Paseo's own panels where they are registered to be", () => {
const layout = handle();
const filesTab = layout.get().tabs.find((open) => open.panelId === "paseo/files");
const browser = layout.open({ panelId: "paseo/browser", params: { browserId: "b1" } });
const filesId = filesTab?.id as string;
expect(() => layout.move(filesId, { type: "pane", paneId: "main" })).toThrow(
'Panel "paseo/files" does not allow a main pane',
);
expect(() => layout.move(filesId, { type: "beside" })).toThrow(
'Panel "paseo/files" does not allow a main pane',
);
// "focused" is the default placement, which falls back to where the panel can be.
expect(layout.move(filesId, { type: "focused" }).paneId).toBe("explorer");
expect(() => layout.move(browser.tabId, { type: "explorer" })).toThrow(
'Panel "paseo/browser" does not allow the Explorer',
);
});
it("allows the Explorer once the plugin registers the panel for it and reloads", () => {
const placement: PluginTabPlacement = { type: "explorer" };
expect(() => handle().open({ panelId: "overview" }, { placement })).toThrow(
'Panel "review/overview" does not allow the Explorer',
);
install(workspacePanel("overview", ["workspace", "explorer"]));
const layout = handle();
const location = layout.open({ panelId: "overview" }, { placement });
expect(location.paneId).toBe("explorer");
expect(tab(layout, location.tabId).locations).toEqual(["workspace", "explorer"]);
});
});
describe("opening", () => {
it("shows the open tab instead of adding a second one, wherever it was asked to go", () => {
const layout = handle();
const first = layout.open(file("src/a.ts"));
layout.open(file("src/b.ts"));
const again = layout.open(file("src/a.ts"), { placement: { type: "beside" } });
expect(again).toEqual(first);
expect(mainPaneIds(layout)).toEqual(["main"]);
expect(layout.get().focusedTabId).toBe(first.tabId);
});
it("changes nothing the second time a review layout is arranged", () => {
const layout = handle();
const arrange = () => {
layout.explorer.show();
layout.open({ panelId: "paseo/changes" });
layout.open({ panelId: "paseo/diff" });
layout.open({ panelId: "overview" }, { placement: { type: "beside" } });
};
arrange();
const arranged = layout.get();
arrange();
expect(layout.get()).toBe(arranged);
});
it("leaves focus where it is in the background", () => {
const layout = handle();
const shown = layout.open(file("src/a.ts"));
const beside = layout.open(file("src/b.ts"), {
placement: { type: "beside" },
intent: "background",
});
const split = layout.open(file("src/c.ts"), {
placement: { type: "split", paneId: "main", side: "bottom" },
intent: "background",
});
const hidden = layout.open({ panelId: "tree" }, { intent: "background" });
expect(beside.paneId).not.toBe("main");
expect(split.paneId).not.toBe("main");
expect(hidden.paneId).toBe("explorer");
expect(layout.get().focusedPaneId).toBe("main");
expect(layout.get().focusedTabId).toBe(shown.tabId);
expect(layout.get().explorer.visible).toBe(false);
});
it("sends an open tab the params of the latest open", () => {
const layout = handle();
const first = layout.open({ panelId: "paseo/file", params: { path: "a.ts", lineStart: 2 } });
const again = layout.open({ panelId: "paseo/file", params: { path: "a.ts", lineStart: 9 } });
expect(again).toEqual(first);
expect(tab(layout, first.tabId).params).toEqual({ path: "a.ts", lineStart: 9 });
});
it("adds a second tab for a new open, except where a panel has only one", () => {
const layout = handle();
const first = layout.open(file("src/a.ts"));
const terminal = layout.open({ panelId: "paseo/terminal", params: { terminalId: "t1" } });
expect(layout.open(file("src/a.ts"), { intent: "new" }).tabId).not.toBe(first.tabId);
expect(
layout.open({ panelId: "paseo/terminal", params: { terminalId: "t1" } }, { intent: "new" }),
).toEqual(terminal);
});
it("opens a file as a sheet on a compact layout", () => {
setMode("compact");
const layout = handle();
const location = layout.open(file("src/a.ts"));
expect(location.paneId).toBeNull();
expect(tab(layout, location.tabId).paneId).toBeNull();
expect(layout.get().focusedTabId).toBe(location.tabId);
expect(layout.open(file("src/a.ts"), { intent: "background" })).toEqual(location);
expect(layout.move(location.tabId, { type: "focused" }).paneId).toBe("main");
expect(layout.get().tabs.filter((open) => open.panelId === "paseo/file")).toHaveLength(1);
});
});
describe("panels", () => {
const paseoPanels: Array<[string, PluginPanelTarget["params"], PluginPanelTarget["params"]]> = [
["paseo/agent", { agentId: "a1" }, { agentId: "a1" }],
[
"paseo/subagent",
{ parentAgentId: "a1", subagentId: "s1" },
{ parentAgentId: "a1", subagentId: "s1" },
],
["paseo/terminal", { terminalId: "t1" }, { terminalId: "t1" }],
["paseo/browser", { browserId: "b1" }, { browserId: "b1" }],
["paseo/changes", {}, {}],
["paseo/files", {}, {}],
["paseo/files", { reveal: "src/a.ts" }, {}],
["paseo/pull-request", {}, {}],
["paseo/file", { path: "src/a.ts" }, { path: "src/a.ts" }],
[
"paseo/file",
{ path: "src/a.ts", lineStart: 2, lineEnd: 4 },
{ path: "src/a.ts", lineStart: 2, lineEnd: 4 },
],
["paseo/diff", {}, {}],
["paseo/commit-diff", { sha: "abc1234" }, { sha: "abc1234" }],
];
it.each(paseoPanels)("reads %s back as it was opened with %j", (panelId, params, readBack) => {
const layout = handle();
const { tabId } = layout.open({ panelId, params });
expect(tab(layout, tabId)).toMatchObject({ panelId, params: readBack });
});
it("reveals a path in the Files tree", async () => {
const layout = handle();
layout.open({ panelId: "paseo/files", params: { reveal: "src/a.ts" } });
const stateKey = `workspace:${WORKSPACE_ID}`;
await vi.waitFor(() =>
expect(
useSessionStore.getState().sessions[SERVER_ID].fileExplorer.get(stateKey)
?.selectedEntryPath,
).toBe("src/a.ts"),
);
expect(usePanelStore.getState().expandedPathsByWorkspace[stateKey]).toContain("src");
});
const rejected: PluginPanelTarget[] = [
{ panelId: "paseo/agent" },
{ panelId: "paseo/agent", params: { agentId: "" } },
{ panelId: "paseo/subagent", params: { parentAgentId: "a1" } },
{ panelId: "paseo/terminal", params: { terminalId: 1 } },
{ panelId: "paseo/browser", params: { url: "https://example.com" } },
{ panelId: "paseo/changes", params: { path: "src" } },
{ panelId: "paseo/files", params: { reveal: "../secrets" } },
{ panelId: "paseo/files", params: { reveal: "/etc/passwd" } },
{ panelId: "paseo/file", params: { path: "" } },
{ panelId: "paseo/file", params: { path: "a.ts", lineEnd: 4 } },
{ panelId: "paseo/commit-diff" },
{ panelId: "overview", params: { extra: "yes" } },
{ panelId: "chat" },
];
it.each(rejected)("rejects params $panelId does not accept: $params", (target) => {
const layout = handle();
const before = layout.get();
expect(() => layout.open(target)).toThrow("does not accept these params");
expect(layout.get()).toBe(before);
});
it.each(["missing", "other/missing", "missing/board", "paseo/missing", "paseo/new_tab"])(
"rejects the unregistered panel %s",
(panelId) => {
expect(() => handle().open({ panelId })).toThrow("is not registered");
},
);
it("names plugin panels in full, whoever opens them", () => {
const layout = handle();
const own = layout.open({ panelId: "overview" });
const other = layout.open({ panelId: "other/board" });
const agentPanel = layout.open({ panelId: "chat", params: { agentId: "a1" } });
expect(tab(layout, own.tabId)).toMatchObject({
panelId: "review/overview",
params: {},
locations: ["workspace"],
title: "overview",
});
expect(tab(layout, other.tabId).panelId).toBe("other/board");
expect(tab(layout, agentPanel.tabId)).toMatchObject({
panelId: "review/chat",
params: { agentId: "a1" },
});
expect(layout.open({ panelId: "review/overview" })).toEqual(own);
});
});
describe("focusing and closing", () => {
it("focuses a tab and ignores one that is not open", () => {
const layout = handle();
const first = layout.open(file("src/a.ts"));
layout.open(file("src/b.ts"));
layout.focus(first.tabId);
expect(layout.get().focusedTabId).toBe(first.tabId);
const before = layout.get();
layout.focus("missing");
layout.close("missing");
layout.closePane("missing");
expect(layout.get()).toBe(before);
});
it("asks before closing a modified file tab and keeps it when the user cancels", async () => {
const dialog = answerDialogs();
try {
const layout = handle();
const { tabId } = layout.open(file("src/a.ts"));
setModified(tabId, true);
layout.close(tabId);
await vi.waitFor(() => expect(dialog.prompts).toHaveLength(1));
expect(tab(layout, tabId).modified).toBe(true);
dialog.answer = true;
layout.close(tabId);
await vi.waitFor(() => expect(tabIds(layout)).not.toContain(tabId));
expect(dialog.prompts).toHaveLength(2);
} finally {
dialog.restore();
}
});
it("archives an agent whose tab it closes, as the close button does", async () => {
seedAgent("a1", "Agent");
const layout = handle();
const { tabId } = layout.open({ panelId: "paseo/agent", params: { agentId: "a1" } });
layout.close(tabId);
await vi.waitFor(() => expect(daemon.archived).toEqual(["a1"]));
expect(tabIds(layout)).not.toContain(tabId);
});
it("closes a pane with its tabs once the user agrees, as the pane's close does", async () => {
const dialog = answerDialogs();
dialog.answer = true;
try {
const layout = handle();
const side = layout.open(file("src/a.ts"), { placement: { type: "beside" } });
layout.closePane(side.paneId as string);
await vi.waitFor(() => expect(mainPaneIds(layout)).toEqual(["main"]));
expect(tabIds(layout)).not.toContain(side.tabId);
expect(dialog.prompts).toHaveLength(1);
} finally {
dialog.restore();
}
});
it("puts the Explorer away rather than closing its tabs", () => {
const layout = handle();
layout.explorer.show();
layout.closePane("explorer");
expect(layout.get().explorer.visible).toBe(false);
const root = useWorkspaceLayoutStore.getState().layoutByWorkspace[WORKSPACE_KEY].root;
expect(collectAllPanes(root).map((pane) => pane.id)).toEqual(["main"]);
expect(layout.get().tabs.map((open) => open.panelId)).toContain("paseo/files");
});
});
@@ -0,0 +1,85 @@
/**
* A plugin's handle on a workspace's panes and tabs. A facade: opening, moving, closing and
* revealing belong to the layout store and `workspace-tabs`, so what a plugin does behaves as the
* same action in the UI.
*/
import type { PluginWorkspaceLayout, PluginWorkspaceLayoutState } from "@getpaseo/plugin/client";
import type { PluginWorkspaceLayoutSource } from "@getpaseo/plugin/client/host";
import { replaceEqualDeep } from "@tanstack/react-query";
import type { InstalledPlugin } from "../types";
import {
closePane,
closeTab,
focusTab,
hideExplorer,
moveTab,
openTab,
showExplorer,
toggleExplorer,
} from "./internal/commands";
import { resolvePanel } from "./internal/panels";
import { readState, subscribeStateSources, UNAVAILABLE_STATE } from "./internal/state";
import { findWorkspace, requireWorkspace } from "./internal/workspace";
const sources = new WeakMap<AbortSignal, PluginWorkspaceLayoutSource>();
/** One source per installation, and one handle per workspace id within it. */
export function pluginWorkspaceLayoutSource(plugin: InstalledPlugin): PluginWorkspaceLayoutSource {
const lifetime = plugin.lifetime.signal;
let source = sources.get(lifetime);
if (!source) {
const caller = { serverId: plugin.serverId, pluginId: plugin.id };
const handles = new Map<string, PluginWorkspaceLayout>();
source = {
layout(workspaceId) {
let handle = handles.get(workspaceId);
if (!handle) {
handle = createHandle(caller, workspaceId);
handles.set(workspaceId, handle);
}
return handle;
},
};
sources.set(lifetime, source);
}
return source;
}
// No method reads `this`: plugins pass them around as plain functions.
function createHandle(
caller: { serverId: string; pluginId: string },
workspaceId: string,
): PluginWorkspaceLayout {
const require = () => requireWorkspace(caller.serverId, workspaceId);
let last: PluginWorkspaceLayoutState = UNAVAILABLE_STATE;
function get(): PluginWorkspaceLayoutState {
const workspace = findWorkspace(caller.serverId, workspaceId);
last = workspace ? replaceEqualDeep(last, readState(workspace)) : UNAVAILABLE_STATE;
return last;
}
return Object.freeze({
workspaceId,
open: (target, options) => openTab(require(), resolvePanel(caller, target), options),
focus: (tabId) => focusTab(require(), tabId),
close: (tabId) => closeTab(require(), tabId),
move: (tabId, placement) => moveTab(require(), tabId, placement),
closePane: (paneId) => closePane(require(), paneId),
explorer: Object.freeze({
show: () => showExplorer(require()),
hide: () => hideExplorer(require()),
toggle: () => toggleExplorer(require()),
}),
get,
subscribe(listener) {
let seen = get();
return subscribeStateSources(() => {
const next = get();
if (next === seen) return;
seen = next;
listener({ type: "changed" });
});
},
} satisfies PluginWorkspaceLayout);
}
@@ -0,0 +1,272 @@
/** The handle's commands, each one a call into the module that already owns that operation. */
import type {
PluginOpenTabOptions,
PluginTabLocation,
PluginTabPlacement,
} from "@getpaseo/plugin/client";
import {
revealWorkspaceExplorerEntry,
buildWorkspaceExplorerStateKey,
} from "@/file-explorer/workspace-tree";
import { getPanelManifest, panelResourceKey } from "@/panels/panel-manifest";
import {
collectAllPanes,
findPaneById,
useWorkspaceLayoutStore,
type WorkspaceTabPlacement,
} from "@/stores/workspace-layout-store";
import { closeWorkspacePane, closeWorkspaceTab } from "@/workspace-tabs/close";
import {
hideExplorerSidebar,
showExplorerSidebar,
toggleExplorerSidebar,
} from "@/workspace-tabs/explorer-sidebar";
import type { WorkspaceTabTarget } from "@/workspace-tabs/model";
import { revealWorkspaceTab } from "@/workspace-tabs/navigation";
import { describePanel, panelLocations, type ResolvedPanel } from "./panels";
import {
hasSplitPanes,
isCompactLayout,
listOpenTabs,
readExplorerPaneId,
readLayout,
readSheets,
type Workspace,
} from "./workspace";
type OpenIntent = NonNullable<PluginOpenTabOptions["intent"]>;
/** Where a placement lands for one panel, after checking the panel and the layout allow it. */
type Destination =
| { type: "explorer" }
| { type: "focused" }
| Extract<PluginTabPlacement, { type: "pane" | "beside" | "split" }>;
export function openTab(
workspace: Workspace,
panel: ResolvedPanel,
options: PluginOpenTabOptions = {},
): PluginTabLocation {
const { target } = panel;
const destination = resolveDestination(workspace, target, options.placement);
const intent = resolveIntent(target, options.intent ?? "reveal");
// An open tab stays where the user has it; placement only decides where a new one goes.
const existing =
intent === "new"
? null
: listOpenTabs(workspace).find(
(open) => panelResourceKey(open.tab.target) === panelResourceKey(target),
);
let tabId: string;
if (existing && existing.paneId === null && intent === "background") {
// Opening over a sheet would add a second tab for what the sheet already shows.
tabId = existing.tab.tabId;
} else {
const placement = existing ? undefined : preparePlacement(workspace, destination, intent);
const opened = useWorkspaceLayoutStore.getState().openTab({
workspaceKey: workspace.key,
target,
intent,
placement,
// An agent the plugin asked for stays, even before the agent list has caught up.
pin: true,
});
if (!opened) throw new Error(`Panel "${panel.panelId}" could not be opened`);
tabId = opened;
if (intent !== "background") revealWorkspaceTab(workspace.key, tabId);
}
if (panel.revealPath) revealFile(workspace, panel.revealPath);
return locateTab(workspace, tabId);
}
export function focusTab(workspace: Workspace, tabId: string): void {
const sheets = readSheets(workspace);
const sheet = sheets.find((candidate) => candidate.tab.tabId === tabId);
if (sheet) {
// Revealing what a lower sheet shows closes the sheets covering it.
if (sheet !== sheets.at(-1)) {
useWorkspaceLayoutStore
.getState()
.openTab({ workspaceKey: workspace.key, target: sheet.tab.target, intent: "reveal" });
}
return;
}
revealWorkspaceTab(workspace.key, tabId);
}
export function closeTab(workspace: Workspace, tabId: string): void {
void closeWorkspaceTab(workspace.key, tabId);
}
export function moveTab(
workspace: Workspace,
tabId: string,
placement: PluginTabPlacement,
): PluginTabLocation {
const open = listOpenTabs(workspace).find((candidate) => candidate.tab.tabId === tabId);
if (!open) throw new Error(`Tab "${tabId}" is not open`);
const destination = resolveDestination(workspace, open.tab.target, placement);
const sheet = readSheets(workspace).find((candidate) => candidate.tab.tabId === tabId);
if (sheet) useWorkspaceLayoutStore.getState().openTabInFront(workspace.key, sheet);
placeOpenTab(workspace, tabId, destination);
return locateTab(workspace, tabId);
}
export function closePane(workspace: Workspace, paneId: string): void {
if (!findPaneById(readLayout(workspace).root, paneId)) return;
// The Explorer is put away with its tabs, never torn down.
if (paneId === readExplorerPaneId(workspace)) {
hideExplorer(workspace);
return;
}
void closeWorkspacePane(workspace.key, paneId);
}
export function showExplorer(workspace: Workspace): void {
showExplorerSidebar({ isCompact: isCompactLayout(), workspaceKey: workspace.key });
}
export function hideExplorer(workspace: Workspace): void {
hideExplorerSidebar({ isCompact: isCompactLayout(), workspaceKey: workspace.key });
}
export function toggleExplorer(workspace: Workspace): void {
toggleExplorerSidebar({ isCompact: isCompactLayout(), workspaceKey: workspace.key });
}
function resolveIntent(target: WorkspaceTabTarget, intent: OpenIntent): OpenIntent {
if (intent === "new" && getPanelManifest(target.kind).oneTabPerInstance) return "reveal";
return intent;
}
function resolveDestination(
workspace: Workspace,
target: WorkspaceTabTarget,
placement: PluginTabPlacement = { type: "focused" },
): Destination {
const locations = panelLocations(workspace.serverId, target);
const explorerPaneId = readExplorerPaneId(workspace);
const { panelId } = describePanel(target);
// The Explorer is never the focused pane, so a panel that cannot be in a main pane goes there.
const wantsExplorer =
placement.type === "explorer" ||
(placement.type === "pane" && placement.paneId === explorerPaneId) ||
(placement.type === "focused" && !locations.includes("workspace"));
if (wantsExplorer) {
if (!locations.includes("explorer")) {
throw new Error(`Panel "${panelId}" does not allow the Explorer`);
}
return { type: "explorer" };
}
if (!locations.includes("workspace")) {
throw new Error(`Panel "${panelId}" does not allow a main pane`);
}
if (placement.type === "split" && placement.paneId === explorerPaneId) {
throw new Error("The Explorer cannot be split");
}
if (!hasSplitPanes()) return { type: "focused" };
if (placement.type === "pane" || placement.type === "split") {
const panes = collectAllPanes(readLayout(workspace).root);
if (!panes.some((pane) => pane.id === placement.paneId)) {
throw new Error(`Pane "${placement.paneId}" does not exist`);
}
}
return placement;
}
/** Makes the destination exist, and names it the way an open asks for it. */
function preparePlacement(
workspace: Workspace,
destination: Destination,
intent: OpenIntent,
): WorkspaceTabPlacement | undefined {
const store = useWorkspaceLayoutStore.getState();
const takeFocus = intent !== "background";
switch (destination.type) {
case "focused":
// Left unplaced so a compact layout can still choose a sheet.
return undefined;
case "explorer": {
const paneId = takeFocus
? showExplorerSidebar({ isCompact: isCompactLayout(), workspaceKey: workspace.key })
: store.ensureExplorerSidebar(workspace.key);
return paneId ? { mode: "pane", paneId } : undefined;
}
case "pane":
return { mode: "pane", paneId: destination.paneId };
case "beside": {
const paneId = store.ensureSidePane(workspace.key, { focus: takeFocus });
return paneId ? { mode: "pane", paneId } : undefined;
}
case "split": {
const paneId = store.splitPaneEmpty(workspace.key, {
targetPaneId: destination.paneId,
position: destination.side,
newPaneShare: destination.size,
focus: takeFocus,
});
if (!paneId) throw splitRefused(destination.paneId);
return { mode: "pane", paneId };
}
}
}
function placeOpenTab(workspace: Workspace, tabId: string, destination: Destination): void {
const store = useWorkspaceLayoutStore.getState();
const current = store.getTabDestination(workspace.key, tabId);
const currentPaneId = current?.kind === "pane" ? current.paneId : null;
const moveTo = (paneId: string | null) => {
if (paneId && paneId !== currentPaneId) store.moveTabToPane(workspace.key, tabId, paneId);
};
switch (destination.type) {
case "explorer":
moveTo(store.ensureExplorerSidebar(workspace.key));
return;
case "focused": {
// Without splits, any main pane is already "the" main pane.
const alreadyInMain = current?.kind === "pane" && current.host === "main";
if (!hasSplitPanes() && alreadyInMain) return;
moveTo(readLayout(workspace).focusedPaneId);
return;
}
case "pane":
moveTo(destination.paneId);
return;
case "beside":
moveTo(store.ensureSidePane(workspace.key, { focus: false }));
return;
case "split": {
const paneId = store.splitPane(workspace.key, {
tabId,
targetPaneId: destination.paneId,
position: destination.side,
newPaneShare: destination.size,
});
if (!paneId) throw splitRefused(destination.paneId);
}
}
}
function splitRefused(paneId: string): Error {
return new Error(`Pane "${paneId}" cannot be split any further`);
}
function locateTab(workspace: Workspace, tabId: string): PluginTabLocation {
const destination = useWorkspaceLayoutStore.getState().getTabDestination(workspace.key, tabId);
return { tabId, paneId: destination?.kind === "pane" ? destination.paneId : null };
}
function revealFile(workspace: Workspace, path: string): void {
const stateKey = buildWorkspaceExplorerStateKey({ workspaceId: workspace.workspaceId });
if (!stateKey) return;
// The tree shows its own listing errors.
void revealWorkspaceExplorerEntry(
{ serverId: workspace.serverId, stateKey, workspaceRoot: workspace.directory },
path,
);
}
@@ -0,0 +1,110 @@
/** Between a plugin's `panelId` and params and the targets the workspace holds. */
import type {
PluginPanelLocation,
PluginPanelTarget,
PluginPanelTargetParams,
} from "@getpaseo/plugin/client";
import { z } from "zod";
import {
findPublicPanel,
panelPublicReference,
type PanelOpenRequest,
} from "@/panels/panel-manifest";
import { panelTargetSupportsHost } from "@/plugins/workspace-panels/locations";
import { normalizeWorkspaceTabTarget } from "@/workspace-tabs/identity";
import type { PluginWorkspaceTabTarget, WorkspaceTabTarget } from "@/workspace-tabs/model";
import { pluginRegistry } from "../../registry";
const PASEO_NAMESPACE = "paseo";
const workspacePanelParams = z.strictObject({});
const agentPanelParams = z.strictObject({ agentId: z.string().trim().min(1) });
export interface ResolvedPanel extends PanelOpenRequest {
/** Always qualified. */
panelId: string;
}
/** Throws for a panel that is not registered and for params the panel does not accept. */
export function resolvePanel(
caller: { serverId: string; pluginId: string },
input: PluginPanelTarget,
): ResolvedPanel {
const panelId = input.panelId.includes("/")
? input.panelId
: `${caller.pluginId}/${input.panelId}`;
const separator = panelId.indexOf("/");
const namespace = panelId.slice(0, separator);
const params = input.params ?? {};
const request =
namespace === PASEO_NAMESPACE
? resolvePaseoPanel(panelId, params)
: resolvePluginPanel(
{ serverId: caller.serverId, pluginId: namespace, panelId: panelId.slice(separator + 1) },
params,
);
return { ...request, panelId };
}
export function describePanel(target: WorkspaceTabTarget): {
panelId: string;
params: PluginPanelTargetParams;
} {
if (target.kind !== "plugin") return panelPublicReference(target);
return {
panelId: `${target.pluginId}/${target.panelId}`,
params: target.context === "agent" ? { agentId: target.agentId } : {},
};
}
export function panelLocations(
serverId: string,
target: WorkspaceTabTarget,
): PluginPanelLocation[] {
const locations: PluginPanelLocation[] = [];
if (panelTargetSupportsHost(serverId, target, "main")) locations.push("workspace");
if (panelTargetSupportsHost(serverId, target, "explorer")) locations.push("explorer");
return locations;
}
function resolvePaseoPanel(panelId: string, params: PluginPanelTargetParams): PanelOpenRequest {
const identity = findPublicPanel(panelId);
if (!identity) throw notRegistered(panelId);
const request = identity.fromParams(params);
if (!request) throw rejectedParams(panelId);
return request;
}
function resolvePluginPanel(
reference: { serverId: string; pluginId: string; panelId: string },
params: PluginPanelTargetParams,
): PanelOpenRequest {
const { serverId, pluginId, panelId } = reference;
const qualified = `${pluginId}/${panelId}`;
const panel = pluginRegistry
.getSnapshot()
.find((plugin) => plugin.serverId === serverId && plugin.id === pluginId)
?.workspacePanels.find((candidate) => candidate.id === panelId);
if (!panel) throw notRegistered(qualified);
const base = { kind: "plugin", pluginId, panelId } as const;
let target: PluginWorkspaceTabTarget;
if (panel.context === "agent") {
const parsed = agentPanelParams.safeParse(params);
if (!parsed.success) throw rejectedParams(qualified);
target = { ...base, context: "agent", agentId: parsed.data.agentId };
} else {
if (!workspacePanelParams.safeParse(params).success) throw rejectedParams(qualified);
target = { ...base, context: "workspace" };
}
const normalized = normalizeWorkspaceTabTarget(target);
if (!normalized) throw notRegistered(qualified);
return { target: normalized };
}
function notRegistered(panelId: string): Error {
return new Error(`Panel "${panelId}" is not registered`);
}
function rejectedParams(panelId: string): Error {
return new Error(`Panel "${panelId}" does not accept these params`);
}
@@ -0,0 +1,93 @@
/** The layout as a plugin reads it, and when to read it again. */
import type {
PluginLayoutTab,
PluginPane,
PluginWorkspaceLayoutState,
} from "@getpaseo/plugin/client";
import {
getWorkspacePanelAttributes,
subscribeAllPanelInstanceAttributes,
} from "@/panels/panel-instance-attributes";
import { readTabTitle, subscribeTabTitles } from "@/panels/tab-title";
import { usePanelStore } from "@/stores/panel-store";
import {
collectAllPanes,
findPaneById,
useWorkspaceLayoutStore,
type SplitPane,
} from "@/stores/workspace-layout-store";
import { isExplorerSidebarOpen } from "@/workspace-tabs/explorer-sidebar";
import { describePanel, panelLocations } from "./panels";
import {
isCompactLayout,
listOpenTabs,
readExplorerPaneId,
readLayout,
readSheets,
type OpenTab,
type Workspace,
} from "./workspace";
export const UNAVAILABLE_STATE: PluginWorkspaceLayoutState = Object.freeze({
panes: Object.freeze([]),
tabs: Object.freeze([]),
focusedPaneId: null,
focusedTabId: null,
explorer: Object.freeze({ visible: false }),
});
export function readState(workspace: Workspace): PluginWorkspaceLayoutState {
const layout = readLayout(workspace);
const explorerPaneId = readExplorerPaneId(workspace);
const explorerVisible = isExplorerSidebarOpen({
isCompact: isCompactLayout(),
workspaceKey: workspace.key,
});
const panes = collectAllPanes(layout.root)
.filter((pane) => pane.id !== explorerPaneId)
.map((pane) => toPane(pane, "main"));
const explorerPane = findPaneById(layout.root, explorerPaneId);
if (explorerVisible && explorerPane) panes.push(toPane(explorerPane, "explorer"));
const focusedPane = findPaneById(layout.root, layout.focusedPaneId);
const topSheet = readSheets(workspace).at(-1);
return {
panes,
tabs: listOpenTabs(workspace).map((open) => toTab(workspace, open)),
focusedPaneId: layout.focusedPaneId,
focusedTabId: topSheet?.tab.tabId ?? focusedPane?.focusedTabId ?? null,
explorer: { visible: explorerVisible },
};
}
/** Calls back whenever anything `readState` reads may have changed. */
export function subscribeStateSources(listener: () => void): () => void {
const releases = [
useWorkspaceLayoutStore.subscribe(listener),
useWorkspaceLayoutStore.persist.onFinishHydration(listener),
usePanelStore.subscribe(listener),
subscribeAllPanelInstanceAttributes(listener),
// Covers the session and the plugin registry, which titles come from.
subscribeTabTitles(listener),
];
return () => {
for (const release of releases) release();
};
}
function toPane(pane: SplitPane, kind: PluginPane["kind"]): PluginPane {
return { id: pane.id, kind, tabIds: [...pane.tabIds], activeTabId: pane.focusedTabId };
}
function toTab(workspace: Workspace, { tab, paneId }: OpenTab): PluginLayoutTab {
return {
id: tab.tabId,
paneId,
...describePanel(tab.target),
locations: panelLocations(workspace.serverId, tab.target),
title: readTabTitle({ ...workspace, target: tab.target }),
modified: getWorkspacePanelAttributes(workspace.key, tab.tabId).modified,
};
}
@@ -0,0 +1,83 @@
import { PluginWorkspaceUnavailableError } from "@getpaseo/plugin/client";
import { selectWorkspace } from "@/stores/session-store-hooks/selectors";
import { useSessionStore } from "@/stores/session-store";
import {
collectAllTabs,
createWorkspaceLayoutWithExplorerSidebar,
findPaneContainingTab,
selectExplorerSidebarPaneId,
useWorkspaceLayoutStore,
type SheetTab,
type WorkspaceLayout,
} from "@/stores/workspace-layout-store";
import { buildWorkspaceTabPersistenceKey, type WorkspaceTab } from "@/workspace-tabs/model";
/** A workspace this client knows, ready to be read and arranged. */
export interface Workspace {
serverId: string;
workspaceId: string;
key: string;
directory: string | null;
}
/** Null until the session knows the workspace and the stored layouts have loaded. */
export function findWorkspace(serverId: string, workspaceId: string): Workspace | null {
if (!useWorkspaceLayoutStore.persist.hasHydrated()) return null;
const descriptor = selectWorkspace(useSessionStore.getState(), serverId, workspaceId);
if (!descriptor) return null;
const key = buildWorkspaceTabPersistenceKey({ serverId, workspaceId: descriptor.id });
if (!key) return null;
return {
serverId,
workspaceId: descriptor.id,
key,
directory: descriptor.workspaceDirectory || null,
};
}
export function requireWorkspace(serverId: string, workspaceId: string): Workspace {
const workspace = findWorkspace(serverId, workspaceId);
if (!workspace) throw new PluginWorkspaceUnavailableError();
return workspace;
}
// One instance, so a workspace nobody has laid out yet reads the same ids every time.
const UNTOUCHED_LAYOUT = createWorkspaceLayoutWithExplorerSidebar();
export function readLayout(workspace: Workspace): WorkspaceLayout {
return useWorkspaceLayoutStore.getState().layoutByWorkspace[workspace.key] ?? UNTOUCHED_LAYOUT;
}
export function readExplorerPaneId(workspace: Workspace): string | null {
return selectExplorerSidebarPaneId(useWorkspaceLayoutStore.getState(), workspace.key);
}
/** Tabs shown over the workspace instead of in a pane, bottom first. */
export function readSheets(workspace: Workspace): readonly SheetTab[] {
return useWorkspaceLayoutStore.getState().sheetsByWorkspace[workspace.key] ?? [];
}
export interface OpenTab {
tab: WorkspaceTab;
/** Null for a tab in a sheet. */
paneId: string | null;
}
export function listOpenTabs(workspace: Workspace): OpenTab[] {
const layout = readLayout(workspace);
const inPanes = collectAllTabs(layout.root).map((tab) => ({
tab,
paneId: findPaneContainingTab(layout.root, tab.tabId)?.id ?? null,
}));
const inSheets = readSheets(workspace).map((sheet) => ({ tab: sheet.tab, paneId: null }));
return [...inPanes, ...inSheets];
}
export function isCompactLayout(): boolean {
return useWorkspaceLayoutStore.getState().layoutMode === "compact";
}
/** Phones and touch tablets render one pane, so placements that need splits mean that pane. */
export function hasSplitPanes(): boolean {
return useWorkspaceLayoutStore.getState().layoutMode === "split-panes";
}
@@ -102,6 +102,7 @@ interface InsertSplitInternalInput {
position: "left" | "right" | "top" | "bottom";
createNodeId: (prefix: WorkspaceLayoutNodeIdPrefix) => string;
replacementFocusedTabId?: string | null;
newPaneShare?: number;
}
interface InsertSplitInternalResult {
@@ -215,6 +216,8 @@ interface SplitPaneInLayoutInput {
createNodeId: (prefix: WorkspaceLayoutNodeIdPrefix) => string;
maxTreeDepth: number;
paneFocusHistory?: PaneTabFocusHistory;
/** The new pane's share of the space the target pane had. Half when omitted. */
newPaneShare?: number;
}
interface SplitPaneInLayoutResult {
@@ -228,6 +231,8 @@ interface SplitPaneEmptyInLayoutInput {
position: "left" | "right" | "top" | "bottom";
createNodeId: (prefix: WorkspaceLayoutNodeIdPrefix) => string;
maxTreeDepth: number;
/** The new pane's share of the space the target pane had. Half when omitted. */
newPaneShare?: number;
}
interface SplitWorkspaceRootRightInLayoutInput {
@@ -972,11 +977,57 @@ function updatePaneInTree(
});
}
function insertSplitInternal(input: InsertSplitInternalInput): InsertSplitInternalResult {
interface PlacePaneBesideTargetInput {
root: SplitNodeInternal;
targetPaneId: string;
paneNode: SplitNodeInternal;
position: "left" | "right" | "top" | "bottom";
createNodeId: (prefix: WorkspaceLayoutNodeIdPrefix) => string;
newPaneShare?: number;
}
/** Puts a pane on one side of another, taking its share out of the target's space only. */
function placePaneBesideTarget(input: PlacePaneBesideTargetInput): SplitNodeInternal {
const direction =
input.position === "left" || input.position === "right" ? "horizontal" : "vertical";
const insertAfter = input.position === "right" || input.position === "bottom";
const requested = Math.min(Math.max(input.newPaneShare ?? 0.5, 0), 1);
const [newShare = 0.5, targetShare = 0.5] = clampNormalizedSizes([requested, 1 - requested]);
const targetPath = findPanePathById(input.root, input.targetPaneId);
invariant(targetPath, `Target pane not found: ${input.targetPaneId}`);
const targetNode = getNodeAtPath(input.root, targetPath);
invariant(targetNode.kind === "pane", "Expected target pane");
const parentPath = targetPath.slice(0, -1);
const targetIndex = targetPath[targetPath.length - 1] ?? 0;
const parentNode = findParentGroup(input.root, targetPath);
if (parentNode?.kind === "group" && parentNode.group.direction === direction) {
const targetSize = parentNode.group.sizes[targetIndex] ?? 0;
const nextSizes = parentNode.group.sizes.slice();
const insertIndex = insertAfter ? targetIndex + 1 : targetIndex;
nextSizes.splice(insertIndex, 0, targetSize * newShare);
nextSizes[targetIndex + (insertAfter ? 0 : 1)] = targetSize * targetShare;
return replaceNodeAtPath(input.root, parentPath, () =>
insertChildIntoGroup(parentNode, {
index: insertIndex,
node: input.paneNode,
sizes: nextSizes,
}),
);
}
const newGroup = createGroupNode({
id: input.createNodeId("group"),
direction,
children: insertAfter ? [targetNode, input.paneNode] : [input.paneNode, targetNode],
sizes: insertAfter ? [targetShare, newShare] : [newShare, targetShare],
});
return replaceNodeAtPath(input.root, targetPath, () => newGroup);
}
function insertSplitInternal(input: InsertSplitInternalInput): InsertSplitInternalResult {
const targetPathBeforeDetach = findPanePathById(input.root, input.targetPaneId);
invariant(targetPathBeforeDetach, `Target pane not found: ${input.targetPaneId}`);
@@ -987,52 +1038,21 @@ function insertSplitInternal(input: InsertSplitInternalInput): InsertSplitIntern
});
invariant(detached.tab, `Tab not found: ${input.tabId}`);
const targetPath = findPanePathById(detached.root, input.targetPaneId);
invariant(targetPath, `Target pane not found after detach: ${input.targetPaneId}`);
const targetNode = getNodeAtPath(detached.root, targetPath);
invariant(targetNode.kind === "pane", "Expected target pane after detach");
const newPaneId = input.createNodeId("pane");
const newPaneNode = createPaneNode({
id: newPaneId,
tabs: [detached.tab],
focusedTabId: detached.tab.tabId,
const root = placePaneBesideTarget({
root: detached.root,
targetPaneId: input.targetPaneId,
paneNode: createPaneNode({
id: newPaneId,
tabs: [detached.tab],
focusedTabId: detached.tab.tabId,
}),
position: input.position,
createNodeId: input.createNodeId,
newPaneShare: input.newPaneShare,
});
const parentPath = targetPath.slice(0, -1);
const targetIndex = targetPath[targetPath.length - 1] ?? 0;
const parentNode = findParentGroup(detached.root, targetPath);
if (parentNode?.kind === "group" && parentNode.group.direction === direction) {
const targetSize = parentNode.group.sizes[targetIndex] ?? 0;
const nextSizes = parentNode.group.sizes.slice();
const insertIndex = insertAfter ? targetIndex + 1 : targetIndex;
nextSizes.splice(insertIndex, 0, targetSize / 2);
nextSizes[targetIndex + (insertAfter ? 0 : 1)] = targetSize / 2;
return {
root: replaceNodeAtPath(detached.root, parentPath, () =>
insertChildIntoGroup(parentNode, {
index: insertIndex,
node: newPaneNode,
sizes: nextSizes,
}),
),
newPaneId,
};
}
const newGroup = createGroupNode({
id: input.createNodeId("group"),
direction,
children: insertAfter ? [targetNode, newPaneNode] : [newPaneNode, targetNode],
sizes: [0.5, 0.5],
});
return {
root: replaceNodeAtPath(detached.root, targetPath, () => newGroup),
newPaneId,
};
return { root, newPaneId };
}
function repairDuplicateTabIds(root: SplitNodeInternal): {
@@ -2032,6 +2052,7 @@ export function splitPaneInLayout(input: SplitPaneInLayoutInput): SplitPaneInLay
position: input.position,
createNodeId: input.createNodeId,
replacementFocusedTabId,
newPaneShare: input.newPaneShare,
});
if (getTreeDepth(result.root) > input.maxTreeDepth) {
return null;
@@ -2055,41 +2076,15 @@ export function splitPaneEmptyInLayout(
return null;
}
const direction =
input.position === "left" || input.position === "right" ? "horizontal" : "vertical";
const insertAfter = input.position === "right" || input.position === "bottom";
const targetPath = findPanePathById(layout.root, input.targetPaneId);
invariant(targetPath, `Target pane not found: ${input.targetPaneId}`);
const targetNode = getNodeAtPath(layout.root, targetPath);
invariant(targetNode.kind === "pane", "Expected target pane");
const newPaneId = input.createNodeId("pane");
const newPaneNode = createPaneNode({ id: newPaneId, tabs: [createNewWorkspaceTab()] });
const parentPath = targetPath.slice(0, -1);
const targetIndex = targetPath[targetPath.length - 1] ?? 0;
const parentNode = findParentGroup(layout.root, targetPath);
let nextRoot: SplitNodeInternal;
if (parentNode?.kind === "group" && parentNode.group.direction === direction) {
const targetSize = parentNode.group.sizes[targetIndex] ?? 0;
const nextSizes = parentNode.group.sizes.slice();
const insertIndex = insertAfter ? targetIndex + 1 : targetIndex;
nextSizes.splice(insertIndex, 0, targetSize / 2);
nextSizes[targetIndex + (insertAfter ? 0 : 1)] = targetSize / 2;
nextRoot = replaceNodeAtPath(layout.root, parentPath, () =>
insertChildIntoGroup(parentNode, { index: insertIndex, node: newPaneNode, sizes: nextSizes }),
);
} else {
const newGroup = createGroupNode({
id: input.createNodeId("group"),
direction,
children: insertAfter ? [targetNode, newPaneNode] : [newPaneNode, targetNode],
sizes: [0.5, 0.5],
});
nextRoot = replaceNodeAtPath(layout.root, targetPath, () => newGroup);
}
const nextRoot = placePaneBesideTarget({
root: layout.root,
targetPaneId: input.targetPaneId,
paneNode: createPaneNode({ id: newPaneId, tabs: [createNewWorkspaceTab()] }),
position: input.position,
createNodeId: input.createNodeId,
newPaneShare: input.newPaneShare,
});
if (getTreeDepth(nextRoot) > input.maxTreeDepth) {
return null;
@@ -2132,7 +2127,10 @@ export function moveTabToPaneInLayout(input: MoveTabToPaneInLayoutInput): Worksp
const layout = asInternalLayout(input.layout);
const sourcePane = findPaneContainingTab(layout.root, input.tabId);
const targetPane = findPaneById(layout.root, input.toPaneId);
if (!sourcePane || !targetPane || targetPane.hidden === true) {
// The Explorer takes tabs while it is off screen: on a phone its pane is never shown.
const targetRefusesTabs =
targetPane?.hidden === true && targetPane.id !== input.explorerSidebarPaneId;
if (!sourcePane || !targetPane || targetRefusesTabs) {
return null;
}
@@ -206,6 +206,7 @@ interface WorkspaceLayoutStore {
tabId: string;
targetPaneId: string;
position: "left" | "right" | "top" | "bottom";
newPaneShare?: number;
},
) => string | null;
splitPaneEmpty: (
@@ -213,6 +214,9 @@ interface WorkspaceLayoutStore {
input: {
targetPaneId: string;
position: "left" | "right" | "top" | "bottom";
newPaneShare?: number;
/** False keeps keyboard focus on the pane that has it. */
focus?: boolean;
},
) => string | null;
moveTabToPane: (workspaceKey: string, tabId: string, toPaneId: string) => void;
@@ -1850,6 +1854,7 @@ export function createWorkspaceLayoutStore(
tabId: normalizedTabId,
targetPaneId: normalizedTargetPaneId,
position: input.position,
newPaneShare: input.newPaneShare,
maxTreeDepth: MAX_TREE_DEPTH,
createNodeId: ids.createNodeId,
paneFocusHistory: get().paneTabFocusHistoryByWorkspace[normalizedWorkspaceKey],
@@ -1885,16 +1890,21 @@ export function createWorkspaceLayoutStore(
layout: currentLayout,
targetPaneId: normalizedTargetPaneId,
position: input.position,
newPaneShare: input.newPaneShare,
maxTreeDepth: MAX_TREE_DEPTH,
createNodeId: ids.createNodeId,
});
if (!result) {
return null;
}
const nextLayout =
input.focus === false
? { ...result.layout, focusedPaneId: currentLayout.focusedPaneId }
: result.layout;
set((state) => ({
...withoutFocusRestoration(state, normalizedWorkspaceKey),
...withUpdatedWorkspaceLayout(state, normalizedWorkspaceKey, result.layout),
...withUpdatedWorkspaceLayout(state, normalizedWorkspaceKey, nextLayout),
}));
return result.paneId;
+82
View File
@@ -225,6 +225,88 @@ describe("plugin panel SDK boundary", () => {
});
});
describe("plugin workspace layout SDK boundary", () => {
it("lets a panel arrange and read a workspace through one handle", () => {
expect(
typeErrors(`
import {
PluginWorkspaceUnavailableError,
useWorkspaceLayout,
type PluginAgentPanelProps,
type PluginClientContext,
type PluginLayoutTab,
type PluginOpenTabOptions,
type PluginPane,
type PluginPanelLocation,
type PluginPanelTarget,
type PluginPanelTargetParams,
type PluginTabLocation,
type PluginTabPlacement,
type PluginWorkspaceLayout,
type PluginWorkspaceLayoutEvent,
type PluginWorkspaceLayoutState,
} from "@getpaseo/plugin/client";
function focusedFile(state: PluginWorkspaceLayoutState): string | null {
const tab: PluginLayoutTab | undefined = state.tabs.find((entry) => entry.id === state.focusedTabId);
return tab?.panelId === "paseo/file" ? String(tab.params.path) : null;
}
function ReviewPanel({ workspaceId, params }: PluginAgentPanelProps) {
const layout: PluginWorkspaceLayout = useWorkspaceLayout(workspaceId);
const path: string | null = useWorkspaceLayout(workspaceId, focusedFile);
function arrange() {
const agentParams: PluginPanelTargetParams = { agentId: params.agentId };
const target: PluginPanelTarget = { panelId: "paseo/agent", params: agentParams };
const agent: PluginTabLocation = layout.open(target);
if (!agent.paneId) return;
const placement: PluginTabPlacement = { type: "split", paneId: agent.paneId, side: "right", size: 0.4 };
const options: PluginOpenTabOptions = { placement };
const review = layout.open({ panelId: "review", params: agentParams }, options);
layout.open({ panelId: "paseo/diff" }, { placement: { type: "pane", paneId: agent.paneId }, intent: "background" });
layout.open({ panelId: "acme-coverage/report" }, { placement: { type: "beside" }, intent: "new" });
layout.open({ panelId: "findings" }, { placement: { type: "explorer" }, intent: "reveal" });
const moved: PluginTabLocation = layout.move(review.tabId, { type: "focused" });
layout.focus(moved.tabId);
layout.close(moved.tabId);
layout.closePane(agent.paneId);
layout.explorer.show();
layout.explorer.hide();
layout.explorer.toggle();
const stop: () => void = layout.subscribe((event: PluginWorkspaceLayoutEvent) => {
const type: "changed" = event.type;
});
const state = layout.get();
const pane: PluginPane | undefined = state.panes[0];
const kind: "main" | "explorer" | undefined = pane?.kind;
const locations: readonly PluginPanelLocation[] = state.tabs[0]?.locations ?? [];
// @ts-expect-error reads are not writable
state.tabs = [];
// @ts-expect-error the split tree is not exposed
state.root;
// @ts-expect-error arranging is not navigating
layout.navigate();
// @ts-expect-error placements name places a user can see
layout.open({ panelId: "findings" }, { placement: { type: "group" } });
// @ts-expect-error params are strings and numbers
layout.open({ panelId: "findings", params: { nested: {} } });
}
function guarded() {
try {
arrange();
} catch (error) {
if (!(error instanceof PluginWorkspaceUnavailableError)) throw error;
}
}
return null;
}
export default function contribute(client: PluginClientContext) {
client.addAgentPanel({ id: "review", title: "Review", icon: "File", Component: ReviewPanel });
return () => {};
}
`),
).toEqual([]);
});
});
describe("plugin composer SDK boundary", () => {
it("lets a composer item read and change the composer through typed commands and controls", () => {
expect(
+4
View File
@@ -12,6 +12,10 @@ export {
type PluginComposersSource,
} from "./composer.js";
export { PluginNewWorkspaceProvider } from "./new-workspace.js";
export {
PluginWorkspaceLayoutProvider,
type PluginWorkspaceLayoutSource,
} from "./workspace-layout.js";
export {
usePluginRuntimeContextBridge,
type PluginRuntimeContextBridge,
+14
View File
@@ -137,6 +137,20 @@ export type { PluginText, PluginMessage, PluginTranslations } from "../text.js";
export { useTabState } from "./tab.js";
export { PluginWorkspaceUnavailableError, useWorkspaceLayout } from "./workspace-layout.js";
export type {
PluginWorkspaceLayout,
PluginWorkspaceLayoutEvent,
PluginWorkspaceLayoutState,
PluginPane,
PluginLayoutTab,
PluginTabLocation,
PluginPanelTarget,
PluginPanelTargetParams,
PluginTabPlacement,
PluginOpenTabOptions,
} from "./workspace-layout.js";
export type { WorkspaceRef, AgentRef, ProjectRef, TerminalRef } from "../refs.js";
export type { Query, Group, GroupKey } from "./query.js";
@@ -10,6 +10,10 @@ import { PluginClientStateProvider, usePluginClientStateSource } from "./client-
import { PluginNewWorkspaceProvider, usePluginNewWorkspaceValue } from "./new-workspace.js";
import { PaseoApiProvider, usePaseoContextValue } from "./paseo-context.js";
import { PluginRpcProvider, usePluginRpcContextValue } from "./rpc-context.js";
import {
PluginWorkspaceLayoutProvider,
usePluginWorkspaceLayoutSource,
} from "./workspace-layout.js";
export type PluginRuntimeContextBridge = (children: ReactNode) => ReactNode;
@@ -22,6 +26,7 @@ export function usePluginRuntimeContextBridge(): PluginRuntimeContextBridge {
const composer = usePluginComposerValue();
const composers = usePluginComposersSource();
const newWorkspace = usePluginNewWorkspaceValue();
const workspaceLayouts = usePluginWorkspaceLayoutSource();
if (!paseo || !rpc) {
throw new Error("Plugin UI must run inside a contributed plugin surface");
@@ -46,11 +51,18 @@ export function usePluginRuntimeContextBridge(): PluginRuntimeContextBridge {
) : (
withComposers
);
const content = composer ? (
<PluginComposerProvider composer={composer}>{withNewWorkspace}</PluginComposerProvider>
const withWorkspaceLayouts = workspaceLayouts ? (
<PluginWorkspaceLayoutProvider source={workspaceLayouts}>
{withNewWorkspace}
</PluginWorkspaceLayoutProvider>
) : (
withNewWorkspace
);
const content = composer ? (
<PluginComposerProvider composer={composer}>{withWorkspaceLayouts}</PluginComposerProvider>
) : (
withWorkspaceLayouts
);
return (
<PaseoApiProvider paseo={paseo}>
<PluginRpcProvider invoke={rpc.invoke} subscribe={rpc.subscribe}>
@@ -59,6 +71,6 @@ export function usePluginRuntimeContextBridge(): PluginRuntimeContextBridge {
</PaseoApiProvider>
);
},
[composer, composers, newWorkspace, paseo, rpc, state, translations],
[composer, composers, newWorkspace, paseo, rpc, state, translations, workspaceLayouts],
);
}
@@ -0,0 +1,199 @@
import { createContext, useContext, type ReactNode } from "react";
import { useSyncExternalStoreWithSelector } from "use-sync-external-store/shim/with-selector";
import type { PluginPanelLocation } from "./contracts.js";
import { shallowEqual } from "./shallow.js";
/**
* A workspace's panes and tabs on this client. One per workspace, stable for the installation.
* Commands arrange the workspace and never change the screen the user is on.
*
* Every command throws `PluginWorkspaceUnavailableError` when the client does not know the
* workspace on the plugin's host. `get` returns an empty state then.
*/
export interface PluginWorkspaceLayout {
readonly workspaceId: string;
/**
* Opens a registered panel. With the default intent, `reveal`, an open tab of the same panel and
* identity is focused where it is and gets the params again with a new `revision`; `placement`
* decides where a tab that is not open yet goes.
*
* Throws for a panel that is not registered, params the panel rejects, a placement the panel does
* not allow, or a pane that does not exist.
*/
open(target: PluginPanelTarget, options?: PluginOpenTabOptions): PluginTabLocation;
/** Does nothing when no tab has this id. */
focus(tabId: string): void;
/**
* Asks the user first when the tab reports unsaved work, as the close button does. Does nothing
* when no tab has this id.
*/
close(tabId: string): void;
/**
* Moves an open tab. Throws for a tab that is not open, a placement the tab's panel does not
* allow, or a pane that does not exist. Moving a tab into a hidden Explorer leaves it hidden.
*/
move(tabId: string, placement: PluginTabPlacement): PluginTabLocation;
/**
* Removes an ordinary pane and its tabs, asking what the UI asks first; hides the Explorer. Does
* nothing when no pane has this id, or when it is the only pane left.
*/
closePane(paneId: string): void;
readonly explorer: {
show(): void;
hide(): void;
toggle(): void;
};
/** Returns the same object until the layout changes. */
get(): PluginWorkspaceLayoutState;
/** Calls `listener` after the state `get` returns changes. Returns the unsubscribe function. */
subscribe(listener: (event: PluginWorkspaceLayoutEvent) => void): () => void;
}
/** What happened to the layout. Switch on `type`; later versions may add fields. */
export interface PluginWorkspaceLayoutEvent {
type: "changed";
}
export interface PluginWorkspaceLayoutState {
/** Visible panes in reading order. The Explorer is a pane of kind `explorer` while shown. */
readonly panes: readonly PluginPane[];
/** Every open tab, including tabs of a hidden Explorer. */
readonly tabs: readonly PluginLayoutTab[];
/** A main pane. The Explorer never takes focus; read its `activeTabId` for what it shows. */
readonly focusedPaneId: string | null;
/** The focused pane's active tab, or the tab shown over the workspace on a phone. */
readonly focusedTabId: string | null;
readonly explorer: { readonly visible: boolean };
}
export interface PluginPane {
readonly id: string;
readonly kind: "main" | "explorer";
readonly tabIds: readonly string[];
readonly activeTabId: string | null;
}
export interface PluginLayoutTab {
readonly id: string;
/** Null for a tab shown over the workspace on a phone. */
readonly paneId: string | null;
/** Always qualified: `paseo/file`, `my-plugin/review`. */
readonly panelId: string;
/** The params that identify what the tab shows. */
readonly params: PluginPanelTargetParams;
/** Where this tab's panel may live, from its registration. */
readonly locations: readonly PluginPanelLocation[];
readonly title: string;
/** The tab reports unsaved work. */
readonly modified: boolean;
}
export interface PluginTabLocation {
readonly tabId: string;
/** Null for a tab shown over the workspace on a phone. */
readonly paneId: string | null;
}
/** A registered panel and the params that identify one instance of it. */
export interface PluginPanelTarget {
/**
* `<pluginId>/<panelId>`. `paseo/...` names one of Paseo's own panels. A bare id is the calling
* plugin's own panel.
*/
panelId: string;
params?: PluginPanelTargetParams;
}
export type PluginPanelTargetParams = Readonly<Record<string, string | number>>;
/**
* Where a tab goes. On phones and touch tablets, which have no splits, `pane`, `beside` and `split`
* mean the main pane.
*/
export type PluginTabPlacement =
/** The default. A panel that cannot live in the focused pane goes to its first location. */
| { type: "focused" }
| { type: "pane"; paneId: string }
/** The side pane, created on first use. */
| { type: "beside" }
/** A new pane next to `paneId`. `size` is its share of the split, 0.1 to 0.9; default half. */
| { type: "split"; paneId: string; side: "left" | "right" | "top" | "bottom"; size?: number }
| { type: "explorer" };
export interface PluginOpenTabOptions {
placement?: PluginTabPlacement;
/**
* `reveal` (default) reuses an open tab and focuses it. `background` does the same without taking
* focus. `new` always adds a tab; for panels that allow one tab per identity, such as an agent's
* chat, it behaves as `reveal`.
*/
intent?: "reveal" | "background" | "new";
}
/** The client does not know this workspace on the plugin's host. */
export class PluginWorkspaceUnavailableError extends Error {
constructor(message = "The workspace is not available on this client.") {
super(message);
this.name = "PluginWorkspaceUnavailableError";
}
}
export interface PluginWorkspaceLayoutSource {
/** The same handle for the same workspace id. */
layout(workspaceId: string): PluginWorkspaceLayout;
}
const PluginWorkspaceLayoutContext = createContext<PluginWorkspaceLayoutSource | null>(null);
export function usePluginWorkspaceLayoutSource(): PluginWorkspaceLayoutSource | null {
return useContext(PluginWorkspaceLayoutContext);
}
export function PluginWorkspaceLayoutProvider({
children,
source,
}: {
children: ReactNode;
source: PluginWorkspaceLayoutSource;
}) {
return (
<PluginWorkspaceLayoutContext.Provider value={source}>
{children}
</PluginWorkspaceLayoutContext.Provider>
);
}
function subscribeNever() {
return () => {};
}
/**
* The layout of a workspace on the plugin's host. Without a selector, the handle. With one, what it
* selects from the state, re-rendering when that changes (compared shallowly).
*/
export function useWorkspaceLayout(workspaceId: string): PluginWorkspaceLayout;
export function useWorkspaceLayout<Selection>(
workspaceId: string,
selector: (state: PluginWorkspaceLayoutState) => Selection,
): Selection;
export function useWorkspaceLayout<Selection>(
workspaceId: string,
selector?: (state: PluginWorkspaceLayoutState) => Selection,
): PluginWorkspaceLayout | Selection {
const source = usePluginWorkspaceLayoutSource();
if (!source) throw new Error("useWorkspaceLayout must run inside a plugin host");
const layout = source.layout(workspaceId);
const read: () => PluginWorkspaceLayout | PluginWorkspaceLayoutState = selector
? layout.get
: () => layout;
return useSyncExternalStoreWithSelector(
selector ? layout.subscribe : subscribeNever,
read,
read,
(value) => (selector ? selector(value as PluginWorkspaceLayoutState) : layout),
shallowEqual,
);
}
@@ -117,7 +117,7 @@ export default function contribute() { void payload; return () => {}; }`,
}
}, 60_000);
test("directory, Git, and npm installs reject a built-in ID", async () => {
test("directory, Git, and npm installs reject a reserved ID", async () => {
const root = await mkdtemp(path.join(os.tmpdir(), "paseo-builtin-install-"));
roots.push(root);
const directory = await fixture(root, "reserved");
@@ -165,6 +165,13 @@ test("directory, Git, and npm installs reject a built-in ID", async () => {
await expect(
client.installPluginSource({ source: "npm:unused-fixture", id: "reserved" }),
).rejects.toThrow(/reserved for a built-in/);
// "paseo/<panel>" names Paseo's own panels, so no plugin can take the id.
await expect(client.installDirectoryPlugin(gitDirectory, "paseo")).rejects.toThrow(
/reserved for Paseo/,
);
await expect(
client.installPluginSource({ source: "npm:unused-fixture", id: "paseo" }),
).rejects.toThrow(/reserved for Paseo/);
expect(await client.listPlugins()).toEqual([]);
} finally {
await client.close();
+13 -9
View File
@@ -384,15 +384,23 @@ export class PluginService {
return this.runtime.catalog();
}
private assertPluginIdNotReserved(pluginId: string): void {
// "paseo/<panel>" names Paseo's own panels to plugins.
if (pluginId === "paseo") {
throw new Error(`Plugin ID "${pluginId}" is reserved for Paseo`);
}
if (this.builtinPluginIds.has(pluginId)) {
throw new Error(`Plugin ID "${pluginId}" is reserved for a built-in plugin`);
}
}
async installDirectory(input: { path: string; id?: string }): Promise<PluginListItem> {
return this.enqueue(async () => {
const directory = path.resolve(input.path);
const manifest = await readPluginManifest(directory);
assertPluginCompatibility({ ...manifest, version: this.daemonVersion, runtime: "daemon" });
const pluginId = PluginIdSchema.parse(input.id ?? manifest.id);
if (this.builtinPluginIds.has(pluginId)) {
throw new Error(`Plugin ID "${pluginId}" is reserved for a built-in plugin`);
}
this.assertPluginIdNotReserved(pluginId);
if (this.configStore.get().plugins?.[pluginId]) {
throw new Error(
`Plugin ID "${pluginId}" is already configured; choose another ID with --id`,
@@ -418,9 +426,7 @@ export class PluginService {
id?: string;
ref?: string;
}): Promise<PluginListItem> {
if (input.id && this.builtinPluginIds.has(input.id)) {
throw new Error(`Plugin ID "${input.id}" is reserved for a built-in plugin`);
}
if (input.id) this.assertPluginIdNotReserved(input.id);
const reference = parsePluginSourceReference(input.source);
if (reference.kind === "directory") {
const directory = path.resolve(expandTilde(reference.source));
@@ -441,9 +447,7 @@ export class PluginService {
try {
await this.checkRequirements(candidate.directory);
pluginId = PluginIdSchema.parse(input.id ?? candidate.defaultId);
if (this.builtinPluginIds.has(pluginId)) {
throw new Error(`Plugin ID "${pluginId}" is reserved for a built-in plugin`);
}
this.assertPluginIdNotReserved(pluginId);
if (this.configStore.get().plugins?.[pluginId]) {
throw new Error(
`Plugin ID "${pluginId}" is already configured; choose another ID with --id`,