mirror of
https://github.com/getpaseo/paseo.git
synced 2026-11-29 19:56:01 +00:00
Compare commits
5
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
38af54a7b0 | ||
|
|
b0fb288801 | ||
|
|
4a7f2d302b | ||
|
|
bf6d881ece | ||
|
|
8d5fecb595 |
@@ -36,6 +36,10 @@ ordinary `WorkspaceTab` (`SheetTab` in the store) and is an `IsolatedBottomSheet
|
||||
other sheet in the app, so it sits on the one app-wide stack: a sheet opened from any sheet lands on
|
||||
top of it, and closing the top sheet (drag, Close, backdrop, or Android Back) uncovers the one below.
|
||||
|
||||
Because that stack is app-wide and hidden workspace screens stay mounted, a sheet is not presented
|
||||
until its workspace has been on screen. A target opened in a workspace before the user gets there
|
||||
waits in the store and appears on arrival.
|
||||
|
||||
A subagent chosen from the subagents list is the exception. It opens as a page of the list's own
|
||||
sheet and replaces the list in place: Back returns to the list, Close ends both, and Open parent
|
||||
closes the list, landing on the pane the list was opened from. The store's `selectSheetTab` describes
|
||||
|
||||
+6
-2
@@ -267,6 +267,10 @@ Plugin UI runs on desktop and mobile across multiple themes: color every `Text`
|
||||
`theme.colors.foreground` or `theme.colors.foregroundMuted`, and size layout from `layout.compact`.
|
||||
See `public-docs/plugins/reference.md`.
|
||||
|
||||
A plugin reads and arranges panes and tabs through `PluginWorkspaceLayout`. Its host,
|
||||
`packages/app/src/plugins/workspace-layout/`, is a facade over the layout store and `workspace-tabs`,
|
||||
so add behavior to those owners and keep layout mechanics out of the SDK types.
|
||||
|
||||
### SDK import boundaries
|
||||
|
||||
Classify every SDK export before adding it. All client entry points and implementations live under
|
||||
@@ -1018,8 +1022,8 @@ payload that cannot be rendered intact. The daemon advertises this RPC through
|
||||
|
||||
`addSlashCommand` registers an agent- or workspace-context command in the composer. The
|
||||
callback runs in the app, receives the trimmed text after the command name as `args`, and receives
|
||||
the same `paseo`, `rpc`, `openScreen`, workspace, agent, and `openPanel` capabilities as the matching
|
||||
Command Center callback.
|
||||
the same `paseo`, `rpc`, `openScreen`, workspace, agent, and `workspaceLayout` capabilities as the
|
||||
matching Command Center callback.
|
||||
|
||||
```ts
|
||||
client.addSlashCommand({
|
||||
|
||||
@@ -0,0 +1,324 @@
|
||||
import { writeFile } from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
import type { Locator } from "@playwright/test";
|
||||
import { expect, test, type Page } from "../support/fixtures";
|
||||
import { openCommandCenter } from "../support/helpers/command-center";
|
||||
import { runWorkspaceActionFromCommandCenter } from "../support/helpers/command-center-workspace-actions";
|
||||
import { submitMessageWithButton } from "../support/helpers/composer";
|
||||
import { openFileExplorer, openFileFromExplorer } from "../support/helpers/file-explorer";
|
||||
import { openAgentRoute, seedMockAgentWorkspace } from "../support/helpers/mock-agent";
|
||||
import { connectNewWorkspaceDaemonClient } from "../support/helpers/new-workspace";
|
||||
import { copyPluginExample } from "../support/helpers/plugin-fixture";
|
||||
import { runCommand } from "../support/helpers/plugin-sidebar-items";
|
||||
import {
|
||||
closeSheet,
|
||||
expectNoSheetOpen,
|
||||
expectOneSheetOpen,
|
||||
promptMentioning,
|
||||
sheet,
|
||||
} from "../support/helpers/sheet";
|
||||
import {
|
||||
closeMobileExplorer,
|
||||
expectMobileExplorerHidden,
|
||||
expectMobileExplorerVisible,
|
||||
openMobileAgentSidebar,
|
||||
selectWorkspaceInSidebar,
|
||||
} from "../support/helpers/sidebar";
|
||||
import { getServerId } from "../support/helpers/server-id";
|
||||
|
||||
const WIDE = { width: 1600, height: 900 };
|
||||
const COMPACT = { width: 390, height: 844 };
|
||||
const AGENT_TITLE = "Layout agent";
|
||||
const FILE_LINK = "README.md:1";
|
||||
const NO_FILE = "Focus a file to see its outline";
|
||||
|
||||
const REPO_FILES = [
|
||||
{ path: "README.md", content: "# Guide\n\n## Install\n" },
|
||||
{ path: "notes.md", content: "# Notes\n\n## Open questions\n" },
|
||||
{ path: "src/app.ts", content: "// TODO: handle errors\nexport const ready = true;\n" },
|
||||
];
|
||||
|
||||
const REVIEW_TAB = "workspace-tab-plugin_agent_16_workspace-layout_6_review_";
|
||||
const FINDINGS_TAB = "workspace-tab-plugin_workspace_16_workspace-layout_8_findings";
|
||||
const OUTLINE_TAB = "workspace-tab-plugin_workspace_16_workspace-layout_7_outline";
|
||||
|
||||
async function withLayoutExample(
|
||||
initialPrompt: string | undefined,
|
||||
run: (agent: { agentId: string; workspaceId: string }) => Promise<void>,
|
||||
): Promise<void> {
|
||||
const example = await copyPluginExample("workspace-layout");
|
||||
const workspace = await seedMockAgentWorkspace({
|
||||
repoPrefix: "plugin-workspace-layout-",
|
||||
title: AGENT_TITLE,
|
||||
repo: { files: REPO_FILES },
|
||||
initialPrompt,
|
||||
});
|
||||
try {
|
||||
await withPluginInstalled(example.directory, () => run(workspace));
|
||||
} finally {
|
||||
await workspace.cleanup();
|
||||
await example.cleanup();
|
||||
}
|
||||
}
|
||||
|
||||
async function withPluginInstalled(directory: string, run: () => Promise<void>): Promise<void> {
|
||||
const client = await connectNewWorkspaceDaemonClient({ ownProjects: false });
|
||||
const previous = await client.getDaemonConfig();
|
||||
try {
|
||||
await client.patchDaemonConfig({ pluginsEnabled: true });
|
||||
await client.installDirectoryPlugin(directory);
|
||||
await run();
|
||||
} finally {
|
||||
await client.removePlugin("workspace-layout").catch(() => undefined);
|
||||
await client.patchDaemonConfig({ pluginsEnabled: previous.config.pluginsEnabled ?? false });
|
||||
await client.close();
|
||||
}
|
||||
}
|
||||
|
||||
/** `/open-elsewhere <id>` opens a file in that workspace, then one where the command ran. */
|
||||
const OPEN_ELSEWHERE_ENTRY = `import type { PluginClientContext } from "@getpaseo/plugin/client";
|
||||
|
||||
export default function contribute(client: PluginClientContext) {
|
||||
client.addSlashCommand({
|
||||
name: "open-elsewhere",
|
||||
description: "Open a file there, then one here",
|
||||
argumentHint: "<workspaceId>",
|
||||
context: "agent",
|
||||
onSubmit({ args, workspaceLayout }) {
|
||||
const there = client.workspaceLayout(args.trim());
|
||||
there.open({ panelId: "paseo/file", params: { path: "README.md" } });
|
||||
workspaceLayout.open({ panelId: "paseo/file", params: { path: "notes.md" } });
|
||||
},
|
||||
});
|
||||
return () => {};
|
||||
}
|
||||
`;
|
||||
|
||||
async function withTwoWorkspaces(
|
||||
run: (workspaces: {
|
||||
first: { agentId: string; workspaceId: string };
|
||||
second: { agentId: string; workspaceId: string };
|
||||
}) => Promise<void>,
|
||||
): Promise<void> {
|
||||
const example = await copyPluginExample("workspace-layout");
|
||||
await writeFile(path.join(example.directory, "index.client.tsx"), OPEN_ELSEWHERE_ENTRY);
|
||||
const seed = (title: string) =>
|
||||
seedMockAgentWorkspace({
|
||||
repoPrefix: "plugin-workspace-layout-",
|
||||
title,
|
||||
repo: { files: REPO_FILES },
|
||||
});
|
||||
const first = await seed("First agent");
|
||||
const second = await seed("Second agent");
|
||||
try {
|
||||
await withPluginInstalled(example.directory, () => run({ first, second }));
|
||||
} finally {
|
||||
await second.cleanup();
|
||||
await first.cleanup();
|
||||
await example.cleanup();
|
||||
}
|
||||
}
|
||||
|
||||
/** Picks a workspace in a phone's agent list. */
|
||||
async function switchToWorkspace(page: Page, workspaceId: string): Promise<void> {
|
||||
await openMobileAgentSidebar(page);
|
||||
await selectWorkspaceInSidebar(page, workspaceId);
|
||||
await expect(
|
||||
page.getByTestId(`workspace-deck-entry-${getServerId()}:${workspaceId}`),
|
||||
).toBeVisible();
|
||||
await expect(composerIn(page.locator("body"))).toBeEditable({ timeout: 30_000 });
|
||||
}
|
||||
|
||||
function mainPanes(page: Page): Locator {
|
||||
return page.locator('[data-testid^="workspace-pane-"]').filter({ visible: true });
|
||||
}
|
||||
|
||||
function explorer(page: Page): Locator {
|
||||
return page.getByTestId("workspace-explorer-sidebar");
|
||||
}
|
||||
|
||||
function agentTabs(scope: Locator): Locator {
|
||||
return scope.locator('[data-testid^="workspace-tab-agent_"]');
|
||||
}
|
||||
|
||||
function composerIn(scope: Locator): Locator {
|
||||
return scope.getByRole("textbox", { name: "Message agent..." }).filter({ visible: true });
|
||||
}
|
||||
|
||||
async function sendToMainChat(page: Page, text: string): Promise<void> {
|
||||
const composer = composerIn(mainPanes(page).first());
|
||||
await expect(composer).toBeEditable({ timeout: 30_000 });
|
||||
await composer.fill(text);
|
||||
await composer.press("Enter");
|
||||
}
|
||||
|
||||
async function expectAsideChat(page: Page, input: { message: string; tabs: number }) {
|
||||
const chats = agentTabs(explorer(page));
|
||||
await expect(chats).toHaveCount(input.tabs, { timeout: 30_000 });
|
||||
await expect(chats.last()).toHaveAttribute("aria-selected", "true");
|
||||
await expect(
|
||||
explorer(page).getByTestId("user-message").getByText(input.message, { exact: true }),
|
||||
).toBeVisible();
|
||||
await expect(composerIn(explorer(page))).toBeEditable();
|
||||
}
|
||||
|
||||
/** Every visible tab chip, pane by pane, to compare the arrangement before and after. */
|
||||
async function tabsByPane(page: Page): Promise<string[][]> {
|
||||
const scopes = [...(await mainPanes(page).all()), explorer(page)];
|
||||
return Promise.all(
|
||||
scopes.map((scope) =>
|
||||
scope
|
||||
.getByTestId("workspace-tabs-row")
|
||||
.locator('[data-testid^="workspace-tab-"]:not([data-testid^="workspace-tab-tooltip"])')
|
||||
.evaluateAll((chips) => chips.map((chip) => chip.getAttribute("data-testid") ?? "")),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
async function expectReviewLayout(page: Page, agentId: string): Promise<void> {
|
||||
await expect(mainPanes(page)).toHaveCount(2);
|
||||
const left = mainPanes(page).first();
|
||||
const right = mainPanes(page).last();
|
||||
await expect(left.getByTestId(`workspace-tab-agent_${agentId}`)).toBeVisible();
|
||||
|
||||
const review = right.getByTestId(`${REVIEW_TAB}${agentId.length}_${agentId}`);
|
||||
await expect(review).toHaveAttribute("aria-selected", "true");
|
||||
await expect(right.getByText(`Reviewing ${AGENT_TITLE}`, { exact: true })).toBeVisible();
|
||||
await expect(right.getByTestId("workspace-tab-working_diff")).toHaveAttribute(
|
||||
"aria-selected",
|
||||
"false",
|
||||
);
|
||||
await expect(explorer(page).getByTestId(FINDINGS_TAB)).toBeVisible();
|
||||
|
||||
const [leftBox, rightBox] = [await left.boundingBox(), await right.boundingBox()];
|
||||
if (!leftBox || !rightBox) throw new Error("Review layout panes have no bounds");
|
||||
expect(rightBox.x).toBeGreaterThan(leftBox.x);
|
||||
expect(rightBox.width / (leftBox.width + rightBox.width)).toBeCloseTo(0.4, 1);
|
||||
}
|
||||
|
||||
async function openFileInFocusedPane(page: Page, name: string): Promise<void> {
|
||||
await openFileExplorer(page);
|
||||
await openFileFromExplorer(page, name);
|
||||
await expect(mainPanes(page).getByTestId(`workspace-tab-file_${name}`)).toBeVisible();
|
||||
}
|
||||
|
||||
async function expectOutline(page: Page, lines: string[]): Promise<void> {
|
||||
const outline = page.getByTestId("workspace-layout-outline");
|
||||
for (const line of lines) {
|
||||
await expect(outline.getByText(line, { exact: true })).toHaveCount(1);
|
||||
}
|
||||
}
|
||||
|
||||
test("the workspace layout example arranges a wide workspace", async ({ page }) => {
|
||||
test.setTimeout(180_000);
|
||||
await withLayoutExample(undefined, async ({ agentId, workspaceId }) => {
|
||||
await page.setViewportSize(WIDE);
|
||||
await openAgentRoute(page, { workspaceId, agentId });
|
||||
|
||||
await test.step("/aside opens the child agent's chat in the Explorer", async () => {
|
||||
await sendToMainChat(page, "/aside hey");
|
||||
await expectAsideChat(page, { message: "hey", tabs: 1 });
|
||||
await expect(agentTabs(mainPanes(page))).toHaveCount(1);
|
||||
});
|
||||
|
||||
await test.step("a second /aside adds a second tab", async () => {
|
||||
await sendToMainChat(page, "/aside again");
|
||||
await expectAsideChat(page, { message: "again", tabs: 2 });
|
||||
await expect(agentTabs(mainPanes(page))).toHaveCount(1);
|
||||
});
|
||||
|
||||
await test.step("Review layout splits the workspace, and running it again changes nothing", async () => {
|
||||
await runCommand(page, "Review layout");
|
||||
await expectReviewLayout(page, agentId);
|
||||
const arranged = await tabsByPane(page);
|
||||
|
||||
await mainPanes(page).first().getByTestId(`workspace-tab-agent_${agentId}`).click();
|
||||
await runCommand(page, "Review layout");
|
||||
await expectReviewLayout(page, agentId);
|
||||
expect(await tabsByPane(page)).toEqual(arranged);
|
||||
});
|
||||
|
||||
await test.step("the outline follows the focused file across split panes", async () => {
|
||||
await mainPanes(page).first().getByTestId(`workspace-tab-agent_${agentId}`).click();
|
||||
await runCommand(page, "Show outline");
|
||||
await expectOutline(page, [NO_FILE]);
|
||||
|
||||
await openFileInFocusedPane(page, "README.md");
|
||||
await explorer(page).getByTestId(OUTLINE_TAB).click();
|
||||
await expectOutline(page, ["README.md", "Guide", "Install"]);
|
||||
|
||||
await runWorkspaceActionFromCommandCenter(page, "Split pane right");
|
||||
await expect(mainPanes(page)).toHaveCount(3);
|
||||
await openFileInFocusedPane(page, "notes.md");
|
||||
await explorer(page).getByTestId(OUTLINE_TAB).click();
|
||||
await expectOutline(page, ["notes.md", "Notes", "Open questions"]);
|
||||
|
||||
await mainPanes(page).getByTestId("workspace-tab-file_README.md").click();
|
||||
await expectOutline(page, ["README.md", "Guide", "Install"]);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
test("the workspace layout example opens over a phone's chat", async ({ page }) => {
|
||||
test.setTimeout(180_000);
|
||||
await withLayoutExample(promptMentioning(FILE_LINK), async ({ agentId, workspaceId }) => {
|
||||
await page.setViewportSize(COMPACT);
|
||||
await openAgentRoute(page, { workspaceId, agentId });
|
||||
|
||||
await test.step("/aside opens the Explorer over the chat", async () => {
|
||||
await submitMessageWithButton(page, "/aside hey");
|
||||
await expectMobileExplorerVisible(page);
|
||||
await expectAsideChat(page, { message: "hey", tabs: 1 });
|
||||
await closeMobileExplorer(page);
|
||||
await expectMobileExplorerHidden(page);
|
||||
await expect(
|
||||
page.getByRole("button", { name: "Switch tabs (1 open)" }).filter({ visible: true }),
|
||||
).toBeVisible();
|
||||
});
|
||||
|
||||
await test.step("a file sheet updates the outline, and closing it restores it", async () => {
|
||||
await openMobileAgentSidebar(page);
|
||||
const commandCenter = await openCommandCenter(page);
|
||||
await commandCenter.getByTestId("command-center-input").fill("Show outline");
|
||||
await commandCenter.getByRole("button", { name: "Show outline", exact: true }).click();
|
||||
await expectMobileExplorerVisible(page);
|
||||
await expectOutline(page, [NO_FILE]);
|
||||
await closeMobileExplorer(page);
|
||||
await expectMobileExplorerHidden(page);
|
||||
|
||||
await page.getByText(FILE_LINK, { exact: true }).first().click();
|
||||
await expect(sheet(page, "README.md")).toBeVisible();
|
||||
// The sheet covers the Explorer, so the outline can only be read, not seen.
|
||||
await expectOutline(page, ["README.md", "Guide", "Install"]);
|
||||
await closeSheet(page, "README.md");
|
||||
await expectOutline(page, [NO_FILE]);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
test("a file a plugin opens in another workspace waits there on a phone", async ({ page }) => {
|
||||
test.setTimeout(180_000);
|
||||
await withTwoWorkspaces(async ({ first, second }) => {
|
||||
await page.setViewportSize(COMPACT);
|
||||
// Visiting the first workspace leaves its screen mounted behind the second.
|
||||
await openAgentRoute(page, first);
|
||||
await expect(composerIn(page.locator("body"))).toBeEditable({ timeout: 30_000 });
|
||||
await switchToWorkspace(page, second.workspaceId);
|
||||
|
||||
await test.step("only the sheet of the workspace on screen is shown", async () => {
|
||||
await submitMessageWithButton(page, `/open-elsewhere ${first.workspaceId}`);
|
||||
await expect(sheet(page, "notes.md")).toBeVisible();
|
||||
await expectOneSheetOpen(page);
|
||||
await closeSheet(page, "notes.md");
|
||||
await expectNoSheetOpen(page);
|
||||
});
|
||||
|
||||
await test.step("the other sheet is there when the user goes to its workspace", async () => {
|
||||
await switchToWorkspace(page, first.workspaceId);
|
||||
await expect(sheet(page, "README.md")).toBeVisible();
|
||||
await expectOneSheetOpen(page);
|
||||
await closeSheet(page, "README.md");
|
||||
await expectNoSheetOpen(page);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -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 },
|
||||
|
||||
@@ -78,6 +78,7 @@ import { HorizontalScrollProvider } from "@/contexts/horizontal-scroll-context";
|
||||
import { SessionProvider } from "@/contexts/session-context";
|
||||
import { SidebarCalloutProvider } from "@/contexts/sidebar-callout-context";
|
||||
import { ToastProvider } from "@/contexts/toast-context";
|
||||
import { WorkspaceTabCloseErrorToasts } from "@/workspace-tabs/close";
|
||||
import { VoiceProvider } from "@/contexts/voice-context";
|
||||
import {
|
||||
resolveStartupBlocker,
|
||||
@@ -1003,6 +1004,7 @@ function RootOverlayProviders({ children }: { children: ReactNode }) {
|
||||
<BottomSheetModalProvider>
|
||||
{children}
|
||||
<WindowLayoutActionsHost />
|
||||
<WorkspaceTabCloseErrorToasts />
|
||||
</BottomSheetModalProvider>
|
||||
</PortalProvider>
|
||||
</ToastProvider>
|
||||
|
||||
@@ -54,6 +54,8 @@ import type { WorkspaceTabDescriptor } from "@/screens/workspace/workspace-tabs-
|
||||
import {
|
||||
collectAllPanes,
|
||||
createDefaultLayout,
|
||||
resolveGroupSizes,
|
||||
resolveMainSplitTree,
|
||||
selectExplorerSidebarPaneId,
|
||||
useWorkspaceLayoutStore,
|
||||
type SplitNode,
|
||||
@@ -80,7 +82,7 @@ interface SplitContainerProps {
|
||||
uiTabs: WorkspaceTab[];
|
||||
hoveredCloseTabKey: string | null;
|
||||
setHoveredCloseTabKey: Dispatch<SetStateAction<string | null>>;
|
||||
closingTabIds: Set<string>;
|
||||
closingTabIds: ReadonlySet<string>;
|
||||
onNavigateTab: (tabId: string) => void;
|
||||
onCloseTab: (tabId: string) => Promise<void> | void;
|
||||
onCopyResumeCommand: (agentId: string) => Promise<void> | void;
|
||||
@@ -205,7 +207,7 @@ export function SplitContainer({
|
||||
);
|
||||
|
||||
const mainRoot = useMemo(
|
||||
() => removePaneFromSplitTree(layout.root, explorerSidebarPaneId),
|
||||
() => resolveMainSplitTree(layout.root, explorerSidebarPaneId),
|
||||
[layout.root, explorerSidebarPaneId],
|
||||
);
|
||||
const workspaceHasMultiplePanes = Boolean(mainRoot && hasMultipleVisiblePanes(mainRoot));
|
||||
@@ -459,11 +461,10 @@ function SplitNodeView({
|
||||
);
|
||||
const groupChildren = node.kind === "group" ? node.group.children : EMPTY_SPLIT_NODES;
|
||||
// Dragged sizes live per group id, apart from the layout tree, and a group keeps its id when
|
||||
// panes are added or removed. They only apply while they still have one entry per child;
|
||||
// otherwise the dividers past the end of the list could not move.
|
||||
const layoutGroupSizes = node.kind === "group" ? node.group.sizes : EMPTY_SPLIT_SIZES;
|
||||
// panes are added or removed. A list of the wrong length would leave the dividers past its end
|
||||
// unable to move.
|
||||
const groupSizes =
|
||||
storedGroupSizes?.length === groupChildren.length ? storedGroupSizes : layoutGroupSizes;
|
||||
node.kind === "group" ? resolveGroupSizes(node.group, storedGroupSizes) : EMPTY_SPLIT_SIZES;
|
||||
const visibleFlex = useMemo(
|
||||
() => resolveVisibleGroupFlex(groupChildren, groupSizes, maximizedPaneId),
|
||||
[groupChildren, groupSizes, maximizedPaneId],
|
||||
@@ -910,34 +911,6 @@ function wrapRootPaneForStableMount(node: SplitNode): SplitNode {
|
||||
};
|
||||
}
|
||||
|
||||
function removePaneFromSplitTree(node: SplitNode, paneId: string | null): SplitNode | null {
|
||||
if (!paneId) {
|
||||
return node;
|
||||
}
|
||||
if (node.kind === "pane") {
|
||||
return node.pane.id === paneId ? null : node;
|
||||
}
|
||||
|
||||
const children = node.group.children.flatMap((child) => {
|
||||
const nextChild = removePaneFromSplitTree(child, paneId);
|
||||
return nextChild ? [nextChild] : [];
|
||||
});
|
||||
if (children.length === 0) {
|
||||
return null;
|
||||
}
|
||||
if (children.length === 1) {
|
||||
return children[0] ?? null;
|
||||
}
|
||||
return {
|
||||
kind: "group",
|
||||
group: {
|
||||
...node.group,
|
||||
children,
|
||||
sizes: children.map(() => 1 / children.length),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create((theme) => ({
|
||||
workspaceShell: {
|
||||
flex: 1,
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
@@ -155,14 +155,15 @@ function MountedFilePanel({
|
||||
revision: number;
|
||||
onModifiedChange: (modified: boolean) => void;
|
||||
}) {
|
||||
const { state, setCurrentTabState } = usePaneContext();
|
||||
const { tabId, state, setCurrentTabState } = usePaneContext();
|
||||
const tab = useMemo<PluginTab>(
|
||||
() => ({
|
||||
id: tabId,
|
||||
setModified: onModifiedChange,
|
||||
state,
|
||||
setState: setCurrentTabState,
|
||||
}),
|
||||
[onModifiedChange, state, setCurrentTabState],
|
||||
[tabId, onModifiedChange, state, setCurrentTabState],
|
||||
);
|
||||
useEffect(() => () => onModifiedChange(false), [onModifiedChange]);
|
||||
return <FilePanelView panel={panel} file={file} tab={tab} params={params} revision={revision} />;
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
import { getHostRuntimeStore } from "@/runtime/host-runtime";
|
||||
import { useCallback, useMemo } from "react";
|
||||
import {
|
||||
useMutation,
|
||||
useQuery,
|
||||
useQueryClient,
|
||||
type MutationOptions,
|
||||
type QueryClient,
|
||||
type QueryKey,
|
||||
} from "@tanstack/react-query";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { i18n } from "@/i18n/i18next";
|
||||
import { useSessionStore } from "@/stores/session-store";
|
||||
import { agentHistoryQueryKey, allAgentHistoryQueryRootKey } from "./agent-history-query-key";
|
||||
|
||||
@@ -380,87 +380,95 @@ export function usePendingArchiveAgentIds(serverId: string): ReadonlySet<string>
|
||||
);
|
||||
}
|
||||
|
||||
export function useArchiveAgent() {
|
||||
const queryClient = useQueryClient();
|
||||
const { t } = useTranslation();
|
||||
|
||||
const pendingQuery = useArchiveAgentPendingQuery();
|
||||
|
||||
const archiveMutation = useMutation({
|
||||
mutationFn: async (input: ArchiveAgentInput): Promise<{ archivedAt: string }> => {
|
||||
const client = useSessionStore.getState().sessions[input.serverId]?.client ?? null;
|
||||
/**
|
||||
* Archives an agent: hides it right away, then asks the daemon, and puts it back if that fails.
|
||||
*/
|
||||
export async function archiveAgent(
|
||||
queryClient: QueryClient,
|
||||
input: ArchiveAgentInput,
|
||||
): Promise<void> {
|
||||
const options: MutationOptions<
|
||||
{ archivedAt: string },
|
||||
Error,
|
||||
ArchiveAgentInput,
|
||||
ArchiveAgentMutationContext
|
||||
> = {
|
||||
mutationFn: async (variables) => {
|
||||
const client = useSessionStore.getState().sessions[variables.serverId]?.client ?? null;
|
||||
if (!client) {
|
||||
throw new Error(t("common.errors.daemonClientUnavailable"));
|
||||
throw new Error(i18n.t("common.errors.daemonClientUnavailable"));
|
||||
}
|
||||
return await client.archiveAgent(input.agentId);
|
||||
return await client.archiveAgent(variables.agentId);
|
||||
},
|
||||
onMutate: (input) => {
|
||||
onMutate: (variables) => {
|
||||
const context: ArchiveAgentMutationContext = {
|
||||
agent: getStoredAgentSnapshot(input),
|
||||
lists: getArchivedAgentListCacheSnapshot(queryClient, input.serverId),
|
||||
agent: getStoredAgentSnapshot(variables),
|
||||
lists: getArchivedAgentListCacheSnapshot(queryClient, variables.serverId),
|
||||
};
|
||||
const archivedAt = new Date().toISOString();
|
||||
|
||||
applyArchivedAgentCloseResults({
|
||||
queryClient,
|
||||
serverId: input.serverId,
|
||||
results: [{ agentId: input.agentId, archivedAt }],
|
||||
serverId: variables.serverId,
|
||||
results: [{ agentId: variables.agentId, archivedAt }],
|
||||
invalidateQueries: false,
|
||||
});
|
||||
setAgentArchiving({
|
||||
queryClient,
|
||||
serverId: input.serverId,
|
||||
agentId: input.agentId,
|
||||
serverId: variables.serverId,
|
||||
agentId: variables.agentId,
|
||||
isArchiving: true,
|
||||
});
|
||||
return context;
|
||||
},
|
||||
onSuccess: (result, input) => {
|
||||
onSuccess: (result, variables) => {
|
||||
markAgentArchivedInStore({
|
||||
serverId: input.serverId,
|
||||
agentId: input.agentId,
|
||||
serverId: variables.serverId,
|
||||
agentId: variables.agentId,
|
||||
archivedAt: result.archivedAt,
|
||||
});
|
||||
},
|
||||
onError: (_error, input, context) => {
|
||||
onError: (_error, variables, context) => {
|
||||
if (!context) {
|
||||
return;
|
||||
}
|
||||
restoreAgentSnapshot({
|
||||
serverId: input.serverId,
|
||||
agentId: input.agentId,
|
||||
serverId: variables.serverId,
|
||||
agentId: variables.agentId,
|
||||
agent: context.agent,
|
||||
});
|
||||
restoreArchivedAgentListCacheSnapshot(queryClient, input.serverId, context.lists);
|
||||
restoreArchivedAgentListCacheSnapshot(queryClient, variables.serverId, context.lists);
|
||||
},
|
||||
onSettled: (_result, _error, input) => {
|
||||
onSettled: (_result, _error, variables) => {
|
||||
clearArchiveAgentPending({
|
||||
queryClient,
|
||||
serverId: input.serverId,
|
||||
agentId: input.agentId,
|
||||
serverId: variables.serverId,
|
||||
agentId: variables.agentId,
|
||||
});
|
||||
void queryClient.invalidateQueries({
|
||||
queryKey: ["sidebarAgentsList", input.serverId],
|
||||
queryKey: ["sidebarAgentsList", variables.serverId],
|
||||
});
|
||||
void queryClient.invalidateQueries({
|
||||
queryKey: ["allAgents", input.serverId],
|
||||
queryKey: ["allAgents", variables.serverId],
|
||||
});
|
||||
void queryClient.invalidateQueries({
|
||||
queryKey: agentHistoryQueryKey(input.serverId),
|
||||
queryKey: agentHistoryQueryKey(variables.serverId),
|
||||
});
|
||||
void queryClient.invalidateQueries({
|
||||
queryKey: allAgentHistoryQueryRootKey(),
|
||||
});
|
||||
},
|
||||
});
|
||||
};
|
||||
await queryClient.getMutationCache().build(queryClient, options).execute(input);
|
||||
}
|
||||
|
||||
const archiveMutateAsync = archiveMutation.mutateAsync;
|
||||
export function useArchiveAgent() {
|
||||
const queryClient = useQueryClient();
|
||||
const pendingQuery = useArchiveAgentPendingQuery();
|
||||
|
||||
const archiveAgent = useCallback(
|
||||
async (input: ArchiveAgentInput): Promise<void> => {
|
||||
await archiveMutateAsync(input);
|
||||
},
|
||||
[archiveMutateAsync],
|
||||
const archive = useCallback(
|
||||
(input: ArchiveAgentInput): Promise<void> => archiveAgent(queryClient, input),
|
||||
[queryClient],
|
||||
);
|
||||
|
||||
const isArchivingAgent = useCallback(
|
||||
@@ -475,7 +483,7 @@ export function useArchiveAgent() {
|
||||
);
|
||||
|
||||
return {
|
||||
archiveAgent,
|
||||
archiveAgent: archive,
|
||||
isArchivingAgent,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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,
|
||||
);
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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,
|
||||
|
||||
@@ -12,6 +12,7 @@ import type { PluginClientStateSource } from "@getpaseo/plugin/client/host";
|
||||
import { resolvePluginPanelOpenLocation } from "./workspace-panels/locations";
|
||||
import { parsePluginOpenScreenInput } from "./surface-contribution";
|
||||
import type { InstalledPlugin } from "./types";
|
||||
import { pluginWorkspaceLayoutSource } from "./workspace-layout";
|
||||
|
||||
export interface PluginNavigation {
|
||||
openSettings(pluginId: string, screenId: string): void;
|
||||
@@ -64,6 +65,7 @@ export function createPluginAgentActionContext(input: {
|
||||
...createPluginCapabilities(plugin, navigation),
|
||||
workspace,
|
||||
agent,
|
||||
workspaceLayout: pluginWorkspaceLayoutSource(plugin).layout(workspace.id),
|
||||
openPanel(panelId, options) {
|
||||
const panel = plugin.workspacePanels.find((candidate) => candidate.id === panelId);
|
||||
if (!panel) throw new Error(`Workspace panel is unavailable: ${panelId}`);
|
||||
@@ -90,6 +92,7 @@ export function createPluginWorkspaceActionContext(input: {
|
||||
context: "workspace",
|
||||
...createPluginCapabilities(plugin, navigation),
|
||||
workspace,
|
||||
workspaceLayout: pluginWorkspaceLayoutSource(plugin).layout(workspace.id),
|
||||
openPanel(panelId, options) {
|
||||
const panel = plugin.workspacePanels.find(
|
||||
(candidate) => candidate.id === panelId && candidate.context === "workspace",
|
||||
|
||||
@@ -153,6 +153,9 @@ function harness() {
|
||||
openSurface() {},
|
||||
composers: () => [],
|
||||
async playAudio() {},
|
||||
workspaceLayout: () => {
|
||||
throw new Error("Layouts are not used here");
|
||||
},
|
||||
openPanel() {},
|
||||
addComposerPill: () => ({ update() {}, remove() {} }),
|
||||
addHeaderButton: () => ({ update() {}, remove() {} }),
|
||||
|
||||
@@ -12,6 +12,7 @@ import type { PluginClientRuntime } from "./evaluate";
|
||||
import { createPluginNavigation } from "./navigation";
|
||||
import { pluginButtonStore } from "./buttons";
|
||||
import type { InstalledPlugin } from "./types";
|
||||
import { pluginWorkspaceLayoutSource } from "./workspace-layout";
|
||||
|
||||
export function createPluginClientRuntime(
|
||||
installation: InstalledPlugin,
|
||||
@@ -33,6 +34,7 @@ export function createPluginClientRuntime(
|
||||
addHeaderButton(contribution) {
|
||||
return pluginButtonStore.addHeaderButton(installation, contribution);
|
||||
},
|
||||
workspaceLayout: (workspaceId) => pluginWorkspaceLayoutSource(installation).layout(workspaceId),
|
||||
openPanel(panelId, options) {
|
||||
openClientPanel({ installation, state, panelId, options });
|
||||
},
|
||||
|
||||
@@ -5,6 +5,7 @@ import { pluginIconComponent } from "../icons";
|
||||
import { resolvePluginPanelOpenLocation } from "../workspace-panels/locations";
|
||||
import type { InstalledPlugin } from "../types";
|
||||
import { createPluginCapabilities, type PluginNavigation } from "../actions";
|
||||
import { pluginWorkspaceLayoutSource } from "../workspace-layout";
|
||||
|
||||
export interface PluginCommandCenterSource {
|
||||
plugins: readonly InstalledPlugin[];
|
||||
@@ -34,11 +35,13 @@ export function buildPluginCommandCenterContributions(
|
||||
? source.state.getWorkspace(source.workspaceId)
|
||||
: null;
|
||||
if (!workspace) return;
|
||||
const workspaceLayout = pluginWorkspaceLayoutSource(plugin).layout(workspace.id);
|
||||
if (item.context === "workspace") {
|
||||
await item.onSelect({
|
||||
context: "workspace",
|
||||
...common,
|
||||
workspace,
|
||||
workspaceLayout,
|
||||
openPanel(panelId, options) {
|
||||
const panel = plugin.workspacePanels.find(
|
||||
(candidate) => candidate.id === panelId && candidate.context === "workspace",
|
||||
@@ -57,6 +60,7 @@ export function buildPluginCommandCenterContributions(
|
||||
...common,
|
||||
workspace,
|
||||
agent,
|
||||
workspaceLayout,
|
||||
openPanel(panelId, options) {
|
||||
const panel = plugin.workspacePanels.find((candidate) => candidate.id === panelId);
|
||||
if (!panel) throw new Error(`Workspace panel is unavailable: ${panelId}`);
|
||||
|
||||
@@ -114,6 +114,7 @@ export type PluginClientRuntime = Pick<
|
||||
| "openSurface"
|
||||
| "composers"
|
||||
| "openPanel"
|
||||
| "workspaceLayout"
|
||||
| "subscribe"
|
||||
| "addComposerPill"
|
||||
| "addHeaderButton"
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -61,6 +61,9 @@ function registry(
|
||||
composers: () => [],
|
||||
openSettings: () => {},
|
||||
playAudio: async () => {},
|
||||
workspaceLayout: () => {
|
||||
throw new Error("Layouts are not used here");
|
||||
},
|
||||
openPanel: () => {},
|
||||
addComposerPill: () => ({ update() {}, remove() {} }),
|
||||
addHeaderButton: () => ({ update() {}, remove() {} }),
|
||||
|
||||
@@ -38,6 +38,9 @@ function registry(version: string) {
|
||||
openSurface() {},
|
||||
composers: () => [],
|
||||
async playAudio() {},
|
||||
workspaceLayout: () => {
|
||||
throw new Error("Layouts are not used here");
|
||||
},
|
||||
openPanel() {},
|
||||
addComposerPill: () => ({ update() {}, remove() {} }),
|
||||
addHeaderButton: () => ({ update() {}, remove() {} }),
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,93 @@
|
||||
/**
|
||||
* 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, lifetime };
|
||||
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; lifetime: AbortSignal },
|
||||
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) {
|
||||
if (caller.lifetime.aborted) return () => {};
|
||||
let seen = get();
|
||||
const release = subscribeStateSources(() => {
|
||||
const next = get();
|
||||
if (next === seen) return;
|
||||
seen = next;
|
||||
listener({ type: "changed" });
|
||||
});
|
||||
// A stopped plugin hears nothing more, as with every other subscription it holds.
|
||||
const stop = () => {
|
||||
caller.lifetime.removeEventListener("abort", stop);
|
||||
release();
|
||||
};
|
||||
caller.lifetime.addEventListener("abort", stop, { once: true });
|
||||
return stop;
|
||||
},
|
||||
} satisfies PluginWorkspaceLayout);
|
||||
}
|
||||
@@ -0,0 +1,286 @@
|
||||
/** 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,
|
||||
type ExplorerSidebarCommand,
|
||||
} 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 {
|
||||
appOverlaysFor,
|
||||
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") reveal(workspace, 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;
|
||||
}
|
||||
reveal(workspace, 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(explorerCommand(workspace));
|
||||
}
|
||||
|
||||
export function hideExplorer(workspace: Workspace): void {
|
||||
hideExplorerSidebar(explorerCommand(workspace));
|
||||
}
|
||||
|
||||
export function toggleExplorer(workspace: Workspace): void {
|
||||
toggleExplorerSidebar(explorerCommand(workspace));
|
||||
}
|
||||
|
||||
function explorerCommand(workspace: Workspace): ExplorerSidebarCommand {
|
||||
return {
|
||||
isCompact: isCompactLayout(),
|
||||
workspaceKey: workspace.key,
|
||||
overlays: appOverlaysFor(workspace),
|
||||
};
|
||||
}
|
||||
|
||||
function reveal(workspace: Workspace, tabId: string): void {
|
||||
revealWorkspaceTab(workspace.key, tabId, { overlays: appOverlaysFor(workspace) });
|
||||
}
|
||||
|
||||
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(explorerCommand(workspace))
|
||||
: 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,97 @@
|
||||
import { PluginWorkspaceUnavailableError } from "@getpaseo/plugin/client";
|
||||
import { getFocusedWorkspaceSelection } from "@/navigation/workspace-route-navigation";
|
||||
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";
|
||||
import type { AppOverlays } from "@/workspace-tabs/navigation";
|
||||
|
||||
/** 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];
|
||||
}
|
||||
|
||||
/**
|
||||
* The app's overlays follow a command only when its workspace is the one on screen. Another
|
||||
* workspace, a screen that is not a workspace, and an app that has not mounted its navigation yet
|
||||
* (nothing is drawn) all count as not on screen.
|
||||
*/
|
||||
export function appOverlaysFor(workspace: Workspace): AppOverlays {
|
||||
const shown = getFocusedWorkspaceSelection();
|
||||
const onScreen =
|
||||
shown?.serverId === workspace.serverId && shown.workspaceId === workspace.workspaceId;
|
||||
return onScreen ? "follow" : "keep";
|
||||
}
|
||||
|
||||
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";
|
||||
}
|
||||
@@ -35,6 +35,7 @@ function PluginPanelBody({ theme }: { theme: PluginTheme }) {
|
||||
const {
|
||||
serverId,
|
||||
workspaceId,
|
||||
tabId,
|
||||
target,
|
||||
state: tabState,
|
||||
setCurrentTabState,
|
||||
@@ -43,8 +44,8 @@ function PluginPanelBody({ theme }: { theme: PluginTheme }) {
|
||||
const [modified, setModified] = useState(false);
|
||||
usePublishPanelInstanceAttributes({ modified });
|
||||
const tab = useMemo<PluginTab>(
|
||||
() => ({ state: tabState, setState: setCurrentTabState, setModified }),
|
||||
[tabState, setCurrentTabState],
|
||||
() => ({ id: tabId, state: tabState, setState: setCurrentTabState, setModified }),
|
||||
[tabId, tabState, setCurrentTabState],
|
||||
);
|
||||
invariant(target.kind === "plugin", "PluginPanel requires plugin target");
|
||||
const plugin = useInstalledPlugin(serverId, target.pluginId);
|
||||
|
||||
@@ -38,7 +38,7 @@ interface ExplorerSidebarDockProps extends Pick<
|
||||
normalizedWorkspaceId: string;
|
||||
isWorkspaceFocused: boolean;
|
||||
paneFocusSuspended: boolean;
|
||||
closingTabIds: Set<string>;
|
||||
closingTabIds: ReadonlySet<string>;
|
||||
onSelectTab: (paneId: string, tabId: string) => void;
|
||||
onCloseTab: (tabId: string) => Promise<void> | void;
|
||||
onReorderTabsInPane: (paneId: string, tabIds: string[]) => void;
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { useIsFocused } from "expo-router/react-navigation";
|
||||
import { useCallback, useEffect, useRef } from "react";
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
import {
|
||||
FULL_SHEET_SNAP_POINTS,
|
||||
SheetBackground,
|
||||
@@ -76,15 +76,31 @@ function WorkspaceSheetTabs({
|
||||
);
|
||||
}
|
||||
|
||||
function SheetTabSheet({ sheet, isTop, onClose }: SheetTabSheetProps) {
|
||||
const { tab } = sheet;
|
||||
const sheetRef = useRef<IsolatedBottomSheetModalRef>(null);
|
||||
/**
|
||||
* Hidden workspaces stay mounted in the deck and under Settings, and the sheet stack is app-wide.
|
||||
* So a sheet waits until its workspace has been on screen, and stays presented from then on.
|
||||
*/
|
||||
function SheetTabSheet(props: SheetTabSheetProps) {
|
||||
const isScreenFocused = useIsFocused();
|
||||
const { isWorkspaceFocused } = useSheetPaneHost();
|
||||
const isOnScreen = isWorkspaceFocused && isScreenFocused;
|
||||
const [hasBeenOnScreen, setHasBeenOnScreen] = useState(isOnScreen);
|
||||
if (isOnScreen && !hasBeenOnScreen) setHasBeenOnScreen(true);
|
||||
return hasBeenOnScreen ? <PresentedSheetTab {...props} isOnScreen={isOnScreen} /> : null;
|
||||
}
|
||||
|
||||
function PresentedSheetTab({
|
||||
sheet,
|
||||
isTop,
|
||||
isOnScreen,
|
||||
onClose,
|
||||
}: SheetTabSheetProps & { isOnScreen: boolean }) {
|
||||
const { tab } = sheet;
|
||||
const sheetRef = useRef<IsolatedBottomSheetModalRef>(null);
|
||||
const contextBridge = useSheetPaneBridge();
|
||||
|
||||
// The sheet lives as long as its store entry: it presents on mount, and unmounting takes it off
|
||||
// the stack, which uncovers the sheet below. Gorhom slides an unmounting sheet down and still
|
||||
// It presents on mount and lives as long as its store entry: unmounting takes it off the
|
||||
// stack, which uncovers the sheet below. Gorhom slides an unmounting sheet down and still
|
||||
// reports that as `onChange(-1)`, which must not read as the user closing it: the store already
|
||||
// moved on, and the same tab id may now be a pane tab (Open as tab).
|
||||
const unmounted = useRef(false);
|
||||
@@ -109,8 +125,8 @@ function SheetTabSheet({ sheet, isTop, onClose }: SheetTabSheetProps) {
|
||||
},
|
||||
[onClose, tab.tabId],
|
||||
);
|
||||
// Hidden workspaces stay mounted in the deck and under Settings; only the visible one owns Back.
|
||||
const ownsBackPress = isTop && isWorkspaceFocused && isScreenFocused;
|
||||
// Only the workspace on screen owns Back.
|
||||
const ownsBackPress = isTop && isOnScreen;
|
||||
useEffect(() => {
|
||||
if (!ownsBackPress) return;
|
||||
return systemBackPress.subscribe(() => {
|
||||
|
||||
@@ -7,12 +7,21 @@ export type ListTerminalsPayload = ListTerminalsResponse["payload"];
|
||||
type TerminalEntry = ListTerminalsPayload["terminals"][number];
|
||||
type CreatedTerminal = NonNullable<CreateTerminalResponse["payload"]["terminal"]>;
|
||||
|
||||
/** Matches every terminal list cached for a host. */
|
||||
export function buildHostTerminalsQueryKey(serverId: string) {
|
||||
return ["terminals", serverId] as const;
|
||||
}
|
||||
|
||||
export function buildTerminalsQueryKey(
|
||||
serverId: string,
|
||||
workspaceDirectory: string | null,
|
||||
workspaceId?: string | null,
|
||||
) {
|
||||
return ["terminals", serverId, workspaceDirectory, workspaceId ?? null] as const;
|
||||
return [
|
||||
...buildHostTerminalsQueryKey(serverId),
|
||||
workspaceDirectory,
|
||||
workspaceId ?? null,
|
||||
] as const;
|
||||
}
|
||||
|
||||
export function canCreateWorkspaceTerminal(input: {
|
||||
|
||||
@@ -15,7 +15,6 @@ import {
|
||||
collectScriptTerminalIds,
|
||||
collectStandaloneTerminalIds,
|
||||
reconcilePendingScriptTerminals,
|
||||
removeTerminalFromPayload,
|
||||
type ListTerminalsPayload,
|
||||
upsertCreatedTerminalPayload,
|
||||
} from "@/screens/workspace/terminals/state";
|
||||
@@ -179,19 +178,6 @@ export function useWorkspaceTerminals(input: UseWorkspaceTerminalsInput) {
|
||||
onTerminalCreateFailed(error instanceof Error ? error.message : String(error));
|
||||
},
|
||||
});
|
||||
const killMutation = useMutation({
|
||||
mutationFn: async (terminalId: string) => {
|
||||
if (!client) {
|
||||
throw new Error(t("workspace.terminal.hostDisconnected"));
|
||||
}
|
||||
const payload = await client.killTerminal(terminalId);
|
||||
if (!payload.success) {
|
||||
throw new Error("Unable to close terminal");
|
||||
}
|
||||
return payload;
|
||||
},
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (!pendingCreateInput) {
|
||||
return;
|
||||
@@ -270,34 +256,17 @@ export function useWorkspaceTerminals(input: UseWorkspaceTerminalsInput) {
|
||||
[onScriptTerminalSelected],
|
||||
);
|
||||
|
||||
const removeTerminalFromCache = useCallback(
|
||||
(terminalId: string) => {
|
||||
queryClient.setQueryData<ListTerminalsPayload>(
|
||||
queryKey,
|
||||
removeTerminalFromPayload(terminalId),
|
||||
);
|
||||
},
|
||||
[queryClient, queryKey],
|
||||
);
|
||||
|
||||
const invalidateTerminals = useCallback(() => {
|
||||
void queryClient.invalidateQueries({ queryKey });
|
||||
}, [queryClient, queryKey]);
|
||||
|
||||
return {
|
||||
canCreateNow,
|
||||
createMutation,
|
||||
createTerminal,
|
||||
handleScriptTerminalStarted,
|
||||
handleViewScriptTerminal,
|
||||
invalidateTerminals,
|
||||
killMutation,
|
||||
knownTerminalIds,
|
||||
liveTerminalIds,
|
||||
pendingCreateInput,
|
||||
query,
|
||||
queryKey,
|
||||
removeTerminalFromCache,
|
||||
standaloneTerminalIds,
|
||||
terminals,
|
||||
};
|
||||
|
||||
@@ -143,3 +143,42 @@ test("single-pane tablet includes its visible Explorer agent without including o
|
||||
}),
|
||||
).toEqual(["a", "b"]);
|
||||
});
|
||||
|
||||
// A phone's Explorer is an overlay; its pane stays hidden in the layout while it is open.
|
||||
test("the shown Explorer contributes its chat even while its pane is hidden", () => {
|
||||
const layout: WorkspaceLayout = {
|
||||
focusedPaneId: "main",
|
||||
root: {
|
||||
kind: "group",
|
||||
group: {
|
||||
id: "root",
|
||||
direction: "horizontal",
|
||||
sizes: [0.78, 0.22],
|
||||
children: [
|
||||
{ kind: "pane", pane: { id: "main", tabIds: ["a"], focusedTabId: "a" } },
|
||||
{
|
||||
kind: "pane",
|
||||
pane: { id: "explorer", tabIds: ["b"], focusedTabId: "b", hidden: true },
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
};
|
||||
const tabs: WorkspaceTab[] = [
|
||||
{ tabId: "a", target: { kind: "agent", agentId: "agent-a" }, createdAt: 1 },
|
||||
{ tabId: "b", target: { kind: "agent", agentId: "agent-b" }, createdAt: 2 },
|
||||
];
|
||||
const compact = {
|
||||
layout,
|
||||
tabs,
|
||||
routeFocused: true,
|
||||
focusedPaneOnly: true,
|
||||
explorerPaneId: "explorer",
|
||||
};
|
||||
|
||||
expect(selectVisibleAgentIds({ ...compact, explorerVisible: true })).toEqual([
|
||||
"agent-a",
|
||||
"agent-b",
|
||||
]);
|
||||
expect(selectVisibleAgentIds({ ...compact, explorerVisible: false })).toEqual(["agent-a"]);
|
||||
});
|
||||
|
||||
@@ -1,5 +1,9 @@
|
||||
import { useRef } from "react";
|
||||
import { collectAllPanes, type WorkspaceLayout } from "@/stores/workspace-layout-store";
|
||||
import {
|
||||
collectAllPanes,
|
||||
findPaneById,
|
||||
type WorkspaceLayout,
|
||||
} from "@/stores/workspace-layout-store";
|
||||
import type { WorkspaceTab } from "@/workspace-tabs/model";
|
||||
import { deriveWorkspacePaneState } from "./workspace-pane-state";
|
||||
|
||||
@@ -14,13 +18,16 @@ export function selectVisibleAgentIds(input: {
|
||||
if (!input.routeFocused || !input.layout) {
|
||||
return [];
|
||||
}
|
||||
const panes = input.focusedPaneOnly
|
||||
? collectAllPanes(input.layout.root).filter(
|
||||
(pane) =>
|
||||
pane.id === input.layout?.focusedPaneId ||
|
||||
(input.explorerVisible !== false && pane.id === input.explorerPaneId),
|
||||
)
|
||||
: collectAllPanes(input.layout.root);
|
||||
const mainPanes = collectAllPanes(input.layout.root).filter(
|
||||
(pane) =>
|
||||
pane.id !== input.explorerPaneId &&
|
||||
(!input.focusedPaneOnly || pane.id === input.layout?.focusedPaneId),
|
||||
);
|
||||
// A phone's Explorer is an overlay over a pane that stays hidden in the layout, so
|
||||
// `explorerVisible`, not the pane, says whether it is on screen.
|
||||
const explorer = findPaneById(input.layout.root, input.explorerPaneId);
|
||||
const explorerShown = input.explorerVisible ?? explorer?.hidden !== true;
|
||||
const panes = explorer && explorerShown ? [...mainPanes, explorer] : mainPanes;
|
||||
|
||||
const targets = panes.flatMap((pane) => {
|
||||
const target = deriveWorkspacePaneState({ pane, tabs: input.tabs }).activeTab?.descriptor
|
||||
|
||||
@@ -25,7 +25,6 @@ import {
|
||||
import { LoadingSpinner } from "@/components/ui/loading-spinner";
|
||||
import { SheetHostScope } from "@/components/ui/isolated-bottom-sheet-modal";
|
||||
import type { JsonValue } from "@getpaseo/protocol/agent-types";
|
||||
import { getOpenAgentTabLabel } from "@getpaseo/protocol/agent-labels";
|
||||
import {
|
||||
memo,
|
||||
useCallback,
|
||||
@@ -72,7 +71,6 @@ import { ImportSessionSheet } from "@/components/import-session-sheet";
|
||||
import { useNavigateToImportedAgent } from "@/hooks/use-import-session";
|
||||
import { useToast } from "@/contexts/toast-context";
|
||||
import { useOpenOutsideWorkspaceFolder } from "@/workspace/open-in-file-manager/outside-folder";
|
||||
import { getOrCreateClientId } from "@/utils/client-id";
|
||||
import { selectIsAgentListOpen, usePanelStore } from "@/stores/panel-store";
|
||||
import { toggleDesktopSidebarsWithCheckoutIntent } from "@/utils/desktop-sidebar-toggle";
|
||||
import {
|
||||
@@ -90,7 +88,6 @@ import { openWorkspacePullRequest } from "@/workspace-tabs/open-supporting-view"
|
||||
import { traceInstant } from "@/performance/native-trace";
|
||||
import { useSessionStore, type WorkspaceDescriptor } from "@/stores/session-store";
|
||||
import {
|
||||
canDismissPaneInLayout,
|
||||
collectAllTabs,
|
||||
DEFAULT_PANE_ID,
|
||||
findPaneById,
|
||||
@@ -135,12 +132,9 @@ import {
|
||||
} from "@/stores/workspace-setup-store";
|
||||
import { useWorkspace } from "@/stores/session-store-hooks";
|
||||
import type { CheckoutStatusPayload } from "@/git/use-status-query";
|
||||
import { confirmDialog } from "@/utils/confirm-dialog";
|
||||
import { useArchiveAgent } from "@/hooks/use-archive-agent";
|
||||
import { useWorkspaceArchiveUndoRunning } from "@/workspace/archive-undo";
|
||||
import { useStableEvent } from "@/hooks/use-stable-event";
|
||||
import { removeResidentBrowserWebview } from "@/desktop/browser/resident-webviews";
|
||||
import { createWorkspaceBrowser, useBrowserStore } from "@/desktop/browser/store";
|
||||
import { createWorkspaceBrowser } from "@/desktop/browser/store";
|
||||
import { getDesktopHost } from "@/desktop/host";
|
||||
import { buildProviderCommand } from "@/utils/provider-command-templates";
|
||||
import { generateDraftId } from "@/stores/draft-keys";
|
||||
@@ -201,16 +195,13 @@ import {
|
||||
} from "@/workspace-tabs/launcher";
|
||||
import type { TerminalTabDestination } from "@/screens/workspace/terminals/use-workspace-terminals";
|
||||
import {
|
||||
buildBulkCloseConfirmationMessage,
|
||||
type BulkCloseConfirmationLabels,
|
||||
classifyBulkClosableTabs,
|
||||
closeBulkWorkspaceTabs,
|
||||
} from "@/screens/workspace/workspace-bulk-close";
|
||||
import { resolveCloseAgentTabPolicy } from "@/subagents";
|
||||
import {
|
||||
getPanelInstanceAttributes,
|
||||
useModifiedPanelTabIds,
|
||||
} from "@/panels/panel-instance-attributes";
|
||||
closeWorkspacePane,
|
||||
closeWorkspaceTab,
|
||||
closeWorkspaceTabs,
|
||||
useClosingWorkspaceTabIds,
|
||||
type BulkCloseScope,
|
||||
} from "@/workspace-tabs/close";
|
||||
import { useModifiedPanelTabIds } from "@/panels/panel-instance-attributes";
|
||||
import { findAdjacentPane } from "@/utils/split-navigation";
|
||||
import { supportsDesktopPaneSplits, useIsCompactFormFactor } from "@/constants/layout";
|
||||
import { getIsElectron, isNative, isWeb } from "@/constants/platform";
|
||||
@@ -450,33 +441,6 @@ export const WorkspaceScreen = memo(function WorkspaceScreen({
|
||||
);
|
||||
});
|
||||
|
||||
interface UseCloseTabsResult {
|
||||
closingTabIds: Set<string>;
|
||||
closeTab: (tabId: string, action: () => Promise<void>) => Promise<void>;
|
||||
}
|
||||
|
||||
function useCloseTabs(): UseCloseTabsResult {
|
||||
const pendingRef = useRef(new Set<string>());
|
||||
const [closingTabIds, setClosingTabIds] = useState<Set<string>>(EMPTY_SET);
|
||||
|
||||
const closeTab = useCallback(async (tabId: string, action: () => Promise<void>) => {
|
||||
const normalized = tabId.trim();
|
||||
if (!normalized || pendingRef.current.has(normalized)) {
|
||||
return;
|
||||
}
|
||||
pendingRef.current.add(normalized);
|
||||
setClosingTabIds(new Set(pendingRef.current));
|
||||
try {
|
||||
await action();
|
||||
} finally {
|
||||
pendingRef.current.delete(normalized);
|
||||
setClosingTabIds(new Set(pendingRef.current));
|
||||
}
|
||||
}, []);
|
||||
|
||||
return { closingTabIds, closeTab };
|
||||
}
|
||||
|
||||
interface WorkspaceHeaderTitleBarProps {
|
||||
isLoading: boolean;
|
||||
title: string;
|
||||
@@ -1212,14 +1176,11 @@ function WorkspaceScreenContent({
|
||||
createTerminal,
|
||||
handleScriptTerminalStarted,
|
||||
handleViewScriptTerminal,
|
||||
invalidateTerminals,
|
||||
killMutation: killTerminalMutation,
|
||||
knownTerminalIds,
|
||||
liveTerminalIds,
|
||||
pendingCreateInput: pendingTerminalCreateInput,
|
||||
query: terminalsQuery,
|
||||
queryKey: terminalsQueryKey,
|
||||
removeTerminalFromCache,
|
||||
standaloneTerminalIds,
|
||||
} = useWorkspaceTerminals({
|
||||
client,
|
||||
@@ -1244,7 +1205,6 @@ function WorkspaceScreenContent({
|
||||
scripts: workspaceScripts,
|
||||
onScriptTerminalStarted: handleScriptTerminalStarted,
|
||||
});
|
||||
const { archiveAgent } = useArchiveAgent();
|
||||
|
||||
const { checkoutQuery, isCheckoutStatusLoading } = useWorkspaceCheckoutStatus({
|
||||
client,
|
||||
@@ -1365,18 +1325,14 @@ function WorkspaceScreenContent({
|
||||
const openInSidePane = useSettings((settings) => settings.openInSidePane);
|
||||
const pullRequestOpenLocation = useSettings((settings) => settings.pullRequestOpenLocation);
|
||||
const selectWorkspaceTabInPane = useWorkspaceLayoutStore((state) => state.selectTabInPane);
|
||||
const closeWorkspaceTab = useWorkspaceLayoutStore((state) => state.closeTab);
|
||||
const sheets = useWorkspaceLayoutStore((state) =>
|
||||
persistenceKey ? (state.sheetsByWorkspace[persistenceKey] ?? NO_SHEETS) : NO_SHEETS,
|
||||
);
|
||||
const unpinWorkspaceAgent = useWorkspaceLayoutStore((state) => state.unpinAgent);
|
||||
const hideWorkspaceAgent = useWorkspaceLayoutStore((state) => state.hideAgent);
|
||||
const setWorkspaceTabState = useWorkspaceLayoutStore((state) => state.setTabState);
|
||||
const reconcileWorkspaceTabs = useWorkspaceLayoutStore((state) => state.reconcileTabs);
|
||||
const splitWorkspacePane = useWorkspaceLayoutStore((state) => state.splitPane);
|
||||
const splitWorkspacePaneEmpty = useWorkspaceLayoutStore((state) => state.splitPaneEmpty);
|
||||
const moveWorkspaceTabToPane = useWorkspaceLayoutStore((state) => state.moveTabToPane);
|
||||
const closeWorkspacePane = useWorkspaceLayoutStore((state) => state.closePane);
|
||||
const handleToggleExplorerSidebar = useCallback(() => {
|
||||
toggleExplorerSidebar({
|
||||
isCompact: isMobile,
|
||||
@@ -1395,31 +1351,7 @@ function WorkspaceScreenContent({
|
||||
persistenceKey ? (state.hiddenAgentIdsByWorkspace[persistenceKey] ?? EMPTY_SET) : EMPTY_SET,
|
||||
);
|
||||
const pendingByDraftId = useCreateFlowStore((state) => state.pendingByDraftId);
|
||||
const { closingTabIds, closeTab } = useCloseTabs();
|
||||
const closeWorkspaceTabWithCleanup = useCallback(
|
||||
function closeWorkspaceTabWithCleanup(input: {
|
||||
tabId: string;
|
||||
target?: WorkspaceTabTarget | null;
|
||||
}) {
|
||||
const normalizedTabId = trimNonEmpty(input.tabId);
|
||||
if (!normalizedTabId || !persistenceKey) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (input.target?.kind === "agent") {
|
||||
unpinWorkspaceAgent(persistenceKey, input.target.agentId);
|
||||
hideWorkspaceAgent(persistenceKey, input.target.agentId);
|
||||
}
|
||||
if (input.target?.kind === "browser") {
|
||||
const { browserId } = input.target;
|
||||
useBrowserStore.getState().removeBrowser(browserId);
|
||||
removeResidentBrowserWebview(browserId);
|
||||
void getDesktopHost()?.browser?.unregisterWorkspaceBrowser?.(browserId);
|
||||
}
|
||||
closeWorkspaceTab(persistenceKey, normalizedTabId);
|
||||
},
|
||||
[closeWorkspaceTab, hideWorkspaceAgent, persistenceKey, unpinWorkspaceAgent],
|
||||
);
|
||||
const closingTabIds = useClosingWorkspaceTabIds(persistenceKey);
|
||||
|
||||
const focusedPaneTabState = useMemo(
|
||||
() =>
|
||||
@@ -1792,47 +1724,6 @@ function WorkspaceScreenContent({
|
||||
terminalsQueryKey,
|
||||
});
|
||||
|
||||
const allTabDescriptorsById = useMemo(() => {
|
||||
const map = new Map<string, WorkspaceTabDescriptor>();
|
||||
for (const tab of uiTabs) {
|
||||
map.set(tab.tabId, {
|
||||
key: tab.tabId,
|
||||
tabId: tab.tabId,
|
||||
kind: tab.target.kind,
|
||||
target: tab.target,
|
||||
});
|
||||
}
|
||||
return map;
|
||||
}, [uiTabs]);
|
||||
const bulkCloseConfirmationLabels = useMemo<BulkCloseConfirmationLabels>(
|
||||
() => ({
|
||||
newTab: t("workspace.tabs.actions.newTab"),
|
||||
all: ({ agents, terminals: terminalCount, tabs: tabCount }) =>
|
||||
t("workspace.tabs.confirmations.bulk.all", {
|
||||
agents,
|
||||
terminals: terminalCount,
|
||||
tabs: tabCount,
|
||||
}),
|
||||
agentsAndTerminals: ({ agents, terminals: terminalCount }) =>
|
||||
t("workspace.tabs.confirmations.bulk.agentsAndTerminals", {
|
||||
agents,
|
||||
terminals: terminalCount,
|
||||
}),
|
||||
terminalsAndTabs: ({ terminals: terminalCount, tabs: tabCount }) =>
|
||||
t("workspace.tabs.confirmations.bulk.terminalsAndTabs", {
|
||||
terminals: terminalCount,
|
||||
tabs: tabCount,
|
||||
}),
|
||||
agentsAndTabs: ({ agents, tabs: tabCount }) =>
|
||||
t("workspace.tabs.confirmations.bulk.agentsAndTabs", { agents, tabs: tabCount }),
|
||||
terminals: ({ terminals: terminalCount }) =>
|
||||
t("workspace.tabs.confirmations.bulk.terminals", { terminals: terminalCount }),
|
||||
tabs: ({ tabs: tabCount }) => t("workspace.tabs.confirmations.bulk.tabs", { tabs: tabCount }),
|
||||
agents: ({ agents }) => t("workspace.tabs.confirmations.bulk.agents", { agents }),
|
||||
}),
|
||||
[t],
|
||||
);
|
||||
|
||||
const activeTabKey = useMemo(() => activeTabId ?? "", [activeTabId]);
|
||||
const handleCreateDraftTab = useCallback(
|
||||
(input?: { paneId?: string }) => {
|
||||
@@ -1955,187 +1846,19 @@ function WorkspaceScreenContent({
|
||||
[persistenceKey, splitWorkspacePaneEmpty],
|
||||
);
|
||||
|
||||
const killTerminalAsync = killTerminalMutation.mutateAsync;
|
||||
|
||||
const handleCloseTerminalTab = useCallback(
|
||||
async (input: { tabId: string; terminalId: string }) => {
|
||||
const { tabId, terminalId } = input;
|
||||
await closeTab(tabId, async () => {
|
||||
const confirmed = await confirmDialog({
|
||||
title: t("workspace.tabs.confirmations.closeTerminalTitle"),
|
||||
message: t("workspace.tabs.confirmations.closeTerminalMessage"),
|
||||
confirmLabel: t("workspace.tabs.confirmations.close"),
|
||||
cancelLabel: t("workspace.tabs.confirmations.cancel"),
|
||||
destructive: true,
|
||||
});
|
||||
if (!confirmed) {
|
||||
return;
|
||||
}
|
||||
|
||||
removeTerminalFromCache(terminalId);
|
||||
setHoveredCloseTabKey((current) => (current === tabId ? null : current));
|
||||
if (persistenceKey) {
|
||||
closeWorkspaceTabWithCleanup({
|
||||
tabId,
|
||||
target: { kind: "terminal", terminalId },
|
||||
});
|
||||
}
|
||||
|
||||
void killTerminalAsync(terminalId).catch(invalidateTerminals);
|
||||
});
|
||||
},
|
||||
[
|
||||
closeTab,
|
||||
closeWorkspaceTabWithCleanup,
|
||||
invalidateTerminals,
|
||||
killTerminalAsync,
|
||||
persistenceKey,
|
||||
removeTerminalFromCache,
|
||||
t,
|
||||
],
|
||||
);
|
||||
|
||||
const handleCloseAgentTab = useCallback(
|
||||
async (input: { tabId: string; agentId: string }) => {
|
||||
const { tabId, agentId } = input;
|
||||
await closeTab(tabId, async () => {
|
||||
if (!normalizedServerId) {
|
||||
return;
|
||||
}
|
||||
|
||||
const agent =
|
||||
useSessionStore.getState().sessions[normalizedServerId]?.agents?.get(agentId) ?? null;
|
||||
let closePolicy = resolveCloseAgentTabPolicy(agent);
|
||||
const isRunning = agent?.status === "running";
|
||||
|
||||
if (isRunning && closePolicy.kind === "archive-on-close") {
|
||||
const confirmed = await confirmDialog({
|
||||
title: t("workspace.tabs.confirmations.archiveRunningAgentTitle"),
|
||||
message: t("workspace.tabs.confirmations.archiveRunningAgentMessage"),
|
||||
confirmLabel: t("workspace.tabs.confirmations.archive"),
|
||||
cancelLabel: t("workspace.tabs.confirmations.cancel"),
|
||||
destructive: true,
|
||||
});
|
||||
if (!confirmed) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
if (closePolicy.kind === "layout-only") {
|
||||
const sessionClient = useSessionStore.getState().sessions[normalizedServerId]?.client;
|
||||
if (!sessionClient) {
|
||||
toast.error(t("common.errors.daemonClientUnavailable"));
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const clientId = await getOrCreateClientId();
|
||||
await sessionClient.updateAgent(agentId, {
|
||||
labels: { [getOpenAgentTabLabel(clientId)]: "false" },
|
||||
});
|
||||
const latestAgent =
|
||||
useSessionStore.getState().sessions[normalizedServerId]?.agents?.get(agentId) ?? null;
|
||||
closePolicy = resolveCloseAgentTabPolicy(latestAgent);
|
||||
} catch (error) {
|
||||
console.error("[WorkspaceScreen] Failed to close subagent tab", { error, agentId });
|
||||
toast.error(t("workspace.tabs.toasts.failedToCloseAgent"));
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
setHoveredCloseTabKey((current) => (current === tabId ? null : current));
|
||||
if (persistenceKey) {
|
||||
closeWorkspaceTabWithCleanup({
|
||||
tabId,
|
||||
target: { kind: "agent", agentId },
|
||||
});
|
||||
}
|
||||
|
||||
if (closePolicy.kind === "layout-only") {
|
||||
return;
|
||||
}
|
||||
|
||||
// Errors (e.g. timeout) are handled by the mutation's onSettled callback
|
||||
void archiveAgent({ serverId: normalizedServerId, agentId }).catch(() => {});
|
||||
});
|
||||
},
|
||||
[
|
||||
archiveAgent,
|
||||
closeTab,
|
||||
closeWorkspaceTabWithCleanup,
|
||||
normalizedServerId,
|
||||
persistenceKey,
|
||||
t,
|
||||
toast,
|
||||
],
|
||||
);
|
||||
|
||||
const handleClosePassiveTab = useCallback(
|
||||
function handleClosePassiveTab(input: { tabId: string; target?: WorkspaceTabTarget | null }) {
|
||||
setHoveredCloseTabKey((current) => (current === input.tabId ? null : current));
|
||||
if (persistenceKey) {
|
||||
closeWorkspaceTabWithCleanup({ tabId: input.tabId, target: input.target });
|
||||
}
|
||||
},
|
||||
[closeWorkspaceTabWithCleanup, persistenceKey],
|
||||
);
|
||||
|
||||
const confirmDiscardModifiedTab = useCallback(
|
||||
async (tabId: string): Promise<boolean> => {
|
||||
const attributes = getPanelInstanceAttributes({
|
||||
serverId: normalizedServerId,
|
||||
workspaceId: normalizedWorkspaceId,
|
||||
tabId,
|
||||
});
|
||||
if (!attributes.modified) return true;
|
||||
const resumePendingSave = attributes.suspendPendingSave?.();
|
||||
const confirmed = await confirmDialog({
|
||||
title: t("workspace.tabs.confirmations.unsavedTitle"),
|
||||
message: t("workspace.tabs.confirmations.unsavedMessage"),
|
||||
confirmLabel: t("workspace.tabs.confirmations.closeWithoutSaving"),
|
||||
cancelLabel: t("workspace.tabs.confirmations.cancel"),
|
||||
destructive: true,
|
||||
});
|
||||
if (!confirmed) resumePendingSave?.();
|
||||
return confirmed;
|
||||
},
|
||||
[normalizedServerId, normalizedWorkspaceId, t],
|
||||
);
|
||||
const clearCloseHover = useCallback((closedTabIds: readonly string[]) => {
|
||||
setHoveredCloseTabKey((current) =>
|
||||
current && closedTabIds.includes(current) ? null : current,
|
||||
);
|
||||
}, []);
|
||||
|
||||
const handleCloseTabById = useCallback(
|
||||
async (tabId: string) => {
|
||||
if (persistenceKey && sheets.some((sheet) => sheet.tab.tabId === tabId)) {
|
||||
if (await confirmDiscardModifiedTab(tabId)) {
|
||||
closeWorkspaceTab(persistenceKey, tabId);
|
||||
}
|
||||
return;
|
||||
if (persistenceKey && (await closeWorkspaceTab(persistenceKey, tabId))) {
|
||||
clearCloseHover([tabId]);
|
||||
}
|
||||
const tab = allTabDescriptorsById.get(tabId);
|
||||
if (!tab) {
|
||||
return;
|
||||
}
|
||||
if (!(await confirmDiscardModifiedTab(tabId))) {
|
||||
return;
|
||||
}
|
||||
if (tab.target.kind === "terminal") {
|
||||
await handleCloseTerminalTab({ tabId, terminalId: tab.target.terminalId });
|
||||
return;
|
||||
}
|
||||
if (tab.target.kind === "agent") {
|
||||
await handleCloseAgentTab({ tabId, agentId: tab.target.agentId });
|
||||
return;
|
||||
}
|
||||
handleClosePassiveTab({ tabId, target: tab.target });
|
||||
},
|
||||
[
|
||||
allTabDescriptorsById,
|
||||
closeWorkspaceTab,
|
||||
confirmDiscardModifiedTab,
|
||||
handleCloseAgentTab,
|
||||
handleClosePassiveTab,
|
||||
handleCloseTerminalTab,
|
||||
persistenceKey,
|
||||
sheets,
|
||||
],
|
||||
[clearCloseHover, persistenceKey],
|
||||
);
|
||||
|
||||
const handleCopyAgentId = useCallback(
|
||||
@@ -2277,88 +2000,16 @@ function WorkspaceScreenContent({
|
||||
}, [normalizedWorkspaceId, openWorkspaceTabFocused, persistenceKey]);
|
||||
|
||||
const handleBulkCloseTabs = useCallback(
|
||||
async (input: {
|
||||
tabsToClose: WorkspaceTabDescriptor[];
|
||||
title: string;
|
||||
logLabel: string;
|
||||
}): Promise<boolean> => {
|
||||
const { tabsToClose, title, logLabel } = input;
|
||||
if (tabsToClose.length === 0) {
|
||||
return true;
|
||||
async (tabsToClose: WorkspaceTabDescriptor[], scope: BulkCloseScope) => {
|
||||
if (!persistenceKey) {
|
||||
return;
|
||||
}
|
||||
|
||||
const groups = classifyBulkClosableTabs(tabsToClose, (agentId) => {
|
||||
const agent = useSessionStore.getState().sessions[normalizedServerId]?.agents?.get(agentId);
|
||||
return resolveCloseAgentTabPolicy(agent).kind === "layout-only" ? "layout-only" : "archive";
|
||||
});
|
||||
const modifiedCount = tabsToClose.filter(
|
||||
(tab) =>
|
||||
getPanelInstanceAttributes({
|
||||
serverId: normalizedServerId,
|
||||
workspaceId: normalizedWorkspaceId,
|
||||
tabId: tab.tabId,
|
||||
}).modified,
|
||||
).length;
|
||||
const bulkMessage = buildBulkCloseConfirmationMessage(groups, bulkCloseConfirmationLabels);
|
||||
const confirmed = await confirmDialog({
|
||||
title,
|
||||
message:
|
||||
modifiedCount > 0
|
||||
? `${bulkMessage}\n\n${t("workspace.tabs.confirmations.bulkUnsaved", { count: modifiedCount })}`
|
||||
: bulkMessage,
|
||||
confirmLabel: t("workspace.tabs.confirmations.close"),
|
||||
cancelLabel: t("workspace.tabs.confirmations.cancel"),
|
||||
destructive: true,
|
||||
});
|
||||
if (!confirmed) {
|
||||
return false;
|
||||
const tabIds = tabsToClose.map((tab) => tab.tabId);
|
||||
if (await closeWorkspaceTabs(persistenceKey, tabIds, scope)) {
|
||||
clearCloseHover(tabIds);
|
||||
}
|
||||
|
||||
await closeBulkWorkspaceTabs({
|
||||
client,
|
||||
groups,
|
||||
closeTab,
|
||||
closeLayoutOnlyAgent: async (agentId) => {
|
||||
if (!client) {
|
||||
throw new Error(t("common.errors.daemonClientUnavailable"));
|
||||
}
|
||||
const clientId = await getOrCreateClientId();
|
||||
await client.updateAgent(agentId, {
|
||||
labels: { [getOpenAgentTabLabel(clientId)]: "false" },
|
||||
});
|
||||
const latestAgent =
|
||||
useSessionStore.getState().sessions[normalizedServerId]?.agents?.get(agentId) ?? null;
|
||||
if (resolveCloseAgentTabPolicy(latestAgent).kind === "archive-on-close") {
|
||||
await archiveAgent({ serverId: normalizedServerId, agentId });
|
||||
}
|
||||
},
|
||||
closeWorkspaceTabWithCleanup: (cleanupInput) => {
|
||||
if (!persistenceKey) {
|
||||
return;
|
||||
}
|
||||
closeWorkspaceTabWithCleanup(cleanupInput);
|
||||
},
|
||||
logLabel,
|
||||
warn: (message, payload) => {
|
||||
console.warn(message, payload);
|
||||
},
|
||||
});
|
||||
|
||||
const closedKeys = new Set(tabsToClose.map((tab) => tab.key));
|
||||
setHoveredCloseTabKey((current) => (current && closedKeys.has(current) ? null : current));
|
||||
return true;
|
||||
},
|
||||
[
|
||||
archiveAgent,
|
||||
bulkCloseConfirmationLabels,
|
||||
client,
|
||||
closeTab,
|
||||
closeWorkspaceTabWithCleanup,
|
||||
normalizedServerId,
|
||||
normalizedWorkspaceId,
|
||||
persistenceKey,
|
||||
t,
|
||||
],
|
||||
[clearCloseHover, persistenceKey],
|
||||
);
|
||||
|
||||
const handleCloseTabsToLeftInPane = useCallback(
|
||||
@@ -2367,13 +2018,9 @@ function WorkspaceScreenContent({
|
||||
if (index < 0) {
|
||||
return;
|
||||
}
|
||||
await handleBulkCloseTabs({
|
||||
tabsToClose: paneTabs.slice(0, index),
|
||||
title: t("workspace.tabs.confirmations.closeTabsLeftTitle"),
|
||||
logLabel: "to the left",
|
||||
});
|
||||
await handleBulkCloseTabs(paneTabs.slice(0, index), "left");
|
||||
},
|
||||
[handleBulkCloseTabs, t],
|
||||
[handleBulkCloseTabs],
|
||||
);
|
||||
|
||||
const handleCloseTabsToLeft = useCallback(
|
||||
@@ -2389,13 +2036,9 @@ function WorkspaceScreenContent({
|
||||
if (index < 0) {
|
||||
return;
|
||||
}
|
||||
await handleBulkCloseTabs({
|
||||
tabsToClose: paneTabs.slice(index + 1),
|
||||
title: t("workspace.tabs.confirmations.closeTabsRightTitle"),
|
||||
logLabel: "to the right",
|
||||
});
|
||||
await handleBulkCloseTabs(paneTabs.slice(index + 1), "right");
|
||||
},
|
||||
[handleBulkCloseTabs, t],
|
||||
[handleBulkCloseTabs],
|
||||
);
|
||||
|
||||
const handleCloseTabsToRight = useCallback(
|
||||
@@ -2407,14 +2050,12 @@ function WorkspaceScreenContent({
|
||||
|
||||
const handleCloseOtherTabsInPane = useCallback(
|
||||
async (tabId: string, paneTabs: WorkspaceTabDescriptor[]) => {
|
||||
const tabsToClose = paneTabs.filter((tab) => tab.tabId !== tabId);
|
||||
await handleBulkCloseTabs({
|
||||
tabsToClose,
|
||||
title: t("workspace.tabs.confirmations.closeOtherTabsTitle"),
|
||||
logLabel: "from close other tabs",
|
||||
});
|
||||
await handleBulkCloseTabs(
|
||||
paneTabs.filter((tab) => tab.tabId !== tabId),
|
||||
"others",
|
||||
);
|
||||
},
|
||||
[handleBulkCloseTabs, t],
|
||||
[handleBulkCloseTabs],
|
||||
);
|
||||
|
||||
const handleCloseOtherTabs = useCallback(
|
||||
@@ -2426,39 +2067,17 @@ function WorkspaceScreenContent({
|
||||
|
||||
const handleClosePane = useCallback(
|
||||
async (paneId: string) => {
|
||||
if (!persistenceKey || !workspaceLayout) {
|
||||
if (!persistenceKey) {
|
||||
return;
|
||||
}
|
||||
const pane = findPaneById(workspaceLayout.root, paneId);
|
||||
// Ask before tearing anything down. The layout refuses to dismiss the final
|
||||
// visible pane, and discovering that after closing its tabs would cost the
|
||||
// user the tabs and leave the pane standing.
|
||||
if (!pane || !canDismissPaneInLayout(workspaceLayout, paneId, explorerSidebarPaneId)) {
|
||||
return;
|
||||
const closingIds = workspaceLayout
|
||||
? (findPaneById(workspaceLayout.root, paneId)?.tabIds ?? [])
|
||||
: [];
|
||||
if (await closeWorkspacePane(persistenceKey, paneId)) {
|
||||
clearCloseHover(closingIds);
|
||||
}
|
||||
const tabsToClose = pane.tabIds.flatMap((tabId) => {
|
||||
const tab = allTabDescriptorsById.get(tabId);
|
||||
return tab ? [tab] : [];
|
||||
});
|
||||
const closed = await handleBulkCloseTabs({
|
||||
tabsToClose,
|
||||
title: t("workspace.tabs.confirmations.closePaneTitle"),
|
||||
logLabel: "from pane close",
|
||||
});
|
||||
if (!closed) {
|
||||
return;
|
||||
}
|
||||
closeWorkspacePane(persistenceKey, paneId);
|
||||
},
|
||||
[
|
||||
allTabDescriptorsById,
|
||||
closeWorkspacePane,
|
||||
handleBulkCloseTabs,
|
||||
persistenceKey,
|
||||
t,
|
||||
workspaceLayout,
|
||||
explorerSidebarPaneId,
|
||||
],
|
||||
[clearCloseHover, persistenceKey, workspaceLayout],
|
||||
);
|
||||
|
||||
const handleWorkspacePanelOpenAction = useCallback(
|
||||
|
||||
@@ -972,11 +972,155 @@ function updatePaneInTree(
|
||||
});
|
||||
}
|
||||
|
||||
function insertSplitInternal(input: InsertSplitInternalInput): InsertSplitInternalResult {
|
||||
interface PlacePaneBesideTargetInput {
|
||||
root: SplitNodeInternal;
|
||||
targetPaneId: string;
|
||||
paneNode: SplitNodeInternal;
|
||||
position: "left" | "right" | "top" | "bottom";
|
||||
createNodeId: (prefix: WorkspaceLayoutNodeIdPrefix) => string;
|
||||
}
|
||||
|
||||
/**
|
||||
* The tree the main canvas draws. The Explorer is docked outside it, and with it taken out a
|
||||
* group's children share the space evenly unless the group has explicit sizes.
|
||||
*/
|
||||
export function resolveMainSplitTree(
|
||||
node: SplitNode,
|
||||
explorerPaneId: string | null,
|
||||
): SplitNode | null {
|
||||
if (!explorerPaneId) {
|
||||
return node;
|
||||
}
|
||||
if (node.kind === "pane") {
|
||||
return node.pane.id === explorerPaneId ? null : node;
|
||||
}
|
||||
|
||||
const children = node.group.children.flatMap((child) => {
|
||||
const nextChild = resolveMainSplitTree(child, explorerPaneId);
|
||||
return nextChild ? [nextChild] : [];
|
||||
});
|
||||
if (children.length === 0) {
|
||||
return null;
|
||||
}
|
||||
if (children.length === 1) {
|
||||
return children[0] ?? null;
|
||||
}
|
||||
return {
|
||||
kind: "group",
|
||||
group: {
|
||||
...node.group,
|
||||
children,
|
||||
sizes: children.map(() => 1 / children.length),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/** The sizes the canvas draws a group with: the saved ones while they have one entry per child. */
|
||||
export function resolveGroupSizes(group: SplitGroup, savedSizes: number[] | undefined): number[] {
|
||||
return savedSizes?.length === group.children.length ? savedSizes : group.sizes;
|
||||
}
|
||||
|
||||
function splitNodeId(node: SplitNode): string {
|
||||
return node.kind === "pane" ? node.pane.id : node.group.id;
|
||||
}
|
||||
|
||||
function findGroupHolding(node: SplitNode, paneId: string): SplitGroup | null {
|
||||
if (node.kind === "pane") return null;
|
||||
for (const child of node.group.children) {
|
||||
if (child.kind === "pane" && child.pane.id === paneId) return node.group;
|
||||
const nested = findGroupHolding(child, paneId);
|
||||
if (nested) return nested;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function findGroupById(node: SplitNode, groupId: string): SplitGroup | null {
|
||||
if (node.kind === "pane") return null;
|
||||
if (node.group.id === groupId) return node.group;
|
||||
for (const child of node.group.children) {
|
||||
const nested = findGroupById(child, groupId);
|
||||
if (nested) return nested;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Explicit sizes for a split that asked for a share: the new pane takes it out of the space the
|
||||
* target is drawn with, and its other neighbors keep theirs. `before` and `after` are main split
|
||||
* trees; `explicitSizes` are the workspace's, by group id.
|
||||
*/
|
||||
export function resolveRequestedSplitSizes(input: {
|
||||
before: SplitNode | null;
|
||||
after: SplitNode | null;
|
||||
explicitSizes: Record<string, number[]> | undefined;
|
||||
targetPaneId: string;
|
||||
newPaneId: string;
|
||||
newPaneShare: number;
|
||||
}): { groupId: string; sizes: number[] } | null {
|
||||
const group = input.after ? findGroupHolding(input.after, input.newPaneId) : null;
|
||||
if (!group) return null;
|
||||
|
||||
// The group is new when the split wrapped the target, which then had all of it.
|
||||
const previous = input.before ? findGroupById(input.before, group.id) : null;
|
||||
const drawn = new Map<string, number>();
|
||||
if (previous) {
|
||||
const sizes = resolveGroupSizes(previous, input.explicitSizes?.[previous.id]);
|
||||
previous.children.forEach((child, index) => drawn.set(splitNodeId(child), sizes[index] ?? 0));
|
||||
}
|
||||
const evenShare = 1 / group.children.length;
|
||||
const targetSize = previous ? (drawn.get(input.targetPaneId) ?? evenShare) : 1;
|
||||
const share = Math.min(Math.max(input.newPaneShare, 0), 1);
|
||||
|
||||
const sizes = group.children.map((child) => {
|
||||
const id = splitNodeId(child);
|
||||
if (id === input.newPaneId) return targetSize * share;
|
||||
if (id === input.targetPaneId) return targetSize * (1 - share);
|
||||
return drawn.get(id) ?? evenShare;
|
||||
});
|
||||
const total = sizes.reduce((sum, size) => sum + size, 0);
|
||||
return { groupId: group.id, sizes: sizes.map((size) => size / total) };
|
||||
}
|
||||
|
||||
/** Puts a pane on one side of another, halving the target's space. */
|
||||
function placePaneBesideTarget(input: PlacePaneBesideTargetInput): SplitNodeInternal {
|
||||
const direction =
|
||||
input.position === "left" || input.position === "right" ? "horizontal" : "vertical";
|
||||
const insertAfter = input.position === "right" || input.position === "bottom";
|
||||
|
||||
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 / 2);
|
||||
nextSizes[targetIndex + (insertAfter ? 0 : 1)] = targetSize / 2;
|
||||
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: [0.5, 0.5],
|
||||
});
|
||||
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 +1131,20 @@ 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,
|
||||
});
|
||||
|
||||
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): {
|
||||
@@ -2055,41 +2167,14 @@ 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,
|
||||
});
|
||||
|
||||
if (getTreeDepth(nextRoot) > input.maxTreeDepth) {
|
||||
return null;
|
||||
@@ -2132,7 +2217,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;
|
||||
}
|
||||
|
||||
|
||||
@@ -827,6 +827,43 @@ describe("workspace-layout-store tree transforms", () => {
|
||||
});
|
||||
|
||||
describe("workspace-layout-store actions", () => {
|
||||
// The main canvas draws a group's panes evenly unless the group has explicit sizes.
|
||||
it("gives a split pane the share asked for, out of the target's space only", () => {
|
||||
const workspaceKey = createWorkspaceKey();
|
||||
const store = workspaceLayoutStore.getState();
|
||||
store.showExplorerSidebar(workspaceKey);
|
||||
const explicitSizes = () =>
|
||||
Object.values(workspaceLayoutStore.getState().splitSizesByWorkspace[workspaceKey] ?? {});
|
||||
|
||||
const right = store.splitPaneEmpty(workspaceKey, {
|
||||
targetPaneId: "main",
|
||||
position: "right",
|
||||
newPaneShare: 0.4,
|
||||
})!;
|
||||
|
||||
expect(explicitSizes()).toEqual([[expect.closeTo(0.6), expect.closeTo(0.4)]]);
|
||||
|
||||
store.splitPaneEmpty(workspaceKey, {
|
||||
targetPaneId: right,
|
||||
position: "right",
|
||||
newPaneShare: 0.5,
|
||||
});
|
||||
|
||||
expect(explicitSizes()).toEqual([
|
||||
[expect.closeTo(0.6), expect.closeTo(0.2), expect.closeTo(0.2)],
|
||||
]);
|
||||
});
|
||||
|
||||
it("leaves a split with no share to be drawn evenly", () => {
|
||||
const workspaceKey = createWorkspaceKey();
|
||||
const store = workspaceLayoutStore.getState();
|
||||
store.showExplorerSidebar(workspaceKey);
|
||||
|
||||
store.splitPaneEmpty(workspaceKey, { targetPaneId: "main", position: "right" });
|
||||
|
||||
expect(workspaceLayoutStore.getState().splitSizesByWorkspace[workspaceKey]).toBeUndefined();
|
||||
});
|
||||
|
||||
it("creates duplicate Changes instances while reveal keeps the first instance", () => {
|
||||
const workspaceKey = createWorkspaceKey();
|
||||
const store = workspaceLayoutStore.getState();
|
||||
|
||||
@@ -46,6 +46,9 @@ import {
|
||||
removeTabFromTree,
|
||||
reorderFocusedPaneTabsInLayout,
|
||||
reorderPaneTabsInLayout,
|
||||
resolveGroupSizes,
|
||||
resolveMainSplitTree,
|
||||
resolveRequestedSplitSizes,
|
||||
setPaneHiddenInLayout,
|
||||
setTabStateInLayout,
|
||||
selectTabInPaneInLayout,
|
||||
@@ -92,6 +95,8 @@ export {
|
||||
normalizeLayout,
|
||||
removePaneFromTree,
|
||||
removeTabFromTree,
|
||||
resolveGroupSizes,
|
||||
resolveMainSplitTree,
|
||||
stripEphemeralTabsFromLayout,
|
||||
};
|
||||
export type {
|
||||
@@ -206,6 +211,8 @@ interface WorkspaceLayoutStore {
|
||||
tabId: string;
|
||||
targetPaneId: string;
|
||||
position: "left" | "right" | "top" | "bottom";
|
||||
/** The new pane's share of the space the target is drawn with. */
|
||||
newPaneShare?: number;
|
||||
},
|
||||
) => string | null;
|
||||
splitPaneEmpty: (
|
||||
@@ -213,6 +220,10 @@ interface WorkspaceLayoutStore {
|
||||
input: {
|
||||
targetPaneId: string;
|
||||
position: "left" | "right" | "top" | "bottom";
|
||||
/** The new pane's share of the space the target is drawn with. */
|
||||
newPaneShare?: number;
|
||||
/** False keeps keyboard focus on the pane that has it. */
|
||||
focus?: boolean;
|
||||
},
|
||||
) => string | null;
|
||||
moveTabToPane: (workspaceKey: string, tabId: string, toPaneId: string) => void;
|
||||
@@ -695,6 +706,42 @@ function withoutFocusRestoration(
|
||||
return { focusRestorationByWorkspace };
|
||||
}
|
||||
|
||||
/** Records the sizes of a split that asked for a share, so the canvas draws them. */
|
||||
function withRequestedSplitSizes(
|
||||
state: Pick<WorkspaceLayoutStore, "splitSizesByWorkspace">,
|
||||
workspaceKey: string,
|
||||
split: {
|
||||
before: SplitNode;
|
||||
after: SplitNode;
|
||||
explorerSidebarPaneId: string | null;
|
||||
targetPaneId: string;
|
||||
newPaneId: string | null;
|
||||
newPaneShare: number | undefined;
|
||||
},
|
||||
): Pick<WorkspaceLayoutStore, "splitSizesByWorkspace"> | null {
|
||||
const { newPaneId, newPaneShare, targetPaneId, explorerSidebarPaneId } = split;
|
||||
if (newPaneId === null || newPaneShare === undefined) return null;
|
||||
const explicitSizes = state.splitSizesByWorkspace[workspaceKey];
|
||||
const requested = resolveRequestedSplitSizes({
|
||||
before: resolveMainSplitTree(split.before, explorerSidebarPaneId),
|
||||
after: resolveMainSplitTree(split.after, explorerSidebarPaneId),
|
||||
explicitSizes,
|
||||
targetPaneId,
|
||||
newPaneId,
|
||||
newPaneShare,
|
||||
});
|
||||
if (!requested) return null;
|
||||
return {
|
||||
splitSizesByWorkspace: {
|
||||
...state.splitSizesByWorkspace,
|
||||
[workspaceKey]: {
|
||||
...explicitSizes,
|
||||
[requested.groupId]: clampNormalizedSizes(requested.sizes),
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function withUpdatedWorkspaceLayout(
|
||||
state: Pick<WorkspaceLayoutStore, "layoutByWorkspace" | "paneTabFocusHistoryByWorkspace">,
|
||||
workspaceKey: string,
|
||||
@@ -1861,6 +1908,14 @@ export function createWorkspaceLayoutStore(
|
||||
set((state) => ({
|
||||
...withoutFocusRestoration(state, normalizedWorkspaceKey),
|
||||
...withUpdatedWorkspaceLayout(state, normalizedWorkspaceKey, result.layout),
|
||||
...withRequestedSplitSizes(state, normalizedWorkspaceKey, {
|
||||
before: currentLayout.root,
|
||||
after: result.layout.root,
|
||||
explorerSidebarPaneId,
|
||||
targetPaneId: normalizedTargetPaneId,
|
||||
newPaneId: result.paneId,
|
||||
newPaneShare: input.newPaneShare,
|
||||
}),
|
||||
}));
|
||||
|
||||
return result.paneId;
|
||||
@@ -1891,10 +1946,22 @@ export function createWorkspaceLayoutStore(
|
||||
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),
|
||||
...withRequestedSplitSizes(state, normalizedWorkspaceKey, {
|
||||
before: currentLayout.root,
|
||||
after: nextLayout.root,
|
||||
explorerSidebarPaneId,
|
||||
targetPaneId: normalizedTargetPaneId,
|
||||
newPaneId: result.paneId,
|
||||
newPaneShare: input.newPaneShare,
|
||||
}),
|
||||
}));
|
||||
|
||||
return result.paneId;
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
import { useEffect } from "react";
|
||||
import { useStore } from "zustand";
|
||||
import { useToast } from "@/contexts/toast-api-context";
|
||||
import { queryClient } from "@/data/query-client";
|
||||
import { getHostRuntimeStore } from "@/runtime/host-runtime";
|
||||
import { confirmDialog } from "@/utils/confirm-dialog";
|
||||
import { createWorkspaceTabClose, type BulkCloseScope } from "./internal/command";
|
||||
|
||||
export type { BulkCloseScope };
|
||||
|
||||
const NO_CLOSING_TAB_IDS: ReadonlySet<string> = new Set();
|
||||
let showError: ((message: string) => void) | null = null;
|
||||
|
||||
const workspaceTabClose = createWorkspaceTabClose({
|
||||
confirm: confirmDialog,
|
||||
reportError: (message) => {
|
||||
if (showError) showError(message);
|
||||
else console.warn("[workspaceTabClose]", message);
|
||||
},
|
||||
getClient: (serverId) => getHostRuntimeStore().getClient(serverId),
|
||||
queryClient,
|
||||
});
|
||||
|
||||
/**
|
||||
* Closing a workspace tab the way its close button does: the unsaved-work and destructive
|
||||
* prompts, then the teardown of what the tab owns. Callable from anywhere in the app.
|
||||
*/
|
||||
export const closeWorkspaceTab = workspaceTabClose.closeTab;
|
||||
export const closeWorkspaceTabs = workspaceTabClose.closeTabs;
|
||||
export const closeWorkspacePane = workspaceTabClose.closePane;
|
||||
|
||||
/** Tabs whose close is waiting on the user or the daemon. */
|
||||
export function useClosingWorkspaceTabIds(workspaceKey: string | null): ReadonlySet<string> {
|
||||
return useStore(
|
||||
workspaceTabClose.closing,
|
||||
(state) => (workspaceKey ? state[workspaceKey] : undefined) ?? NO_CLOSING_TAB_IDS,
|
||||
);
|
||||
}
|
||||
|
||||
/** Shows close failures as app toasts. Mounted once, under the app's toast provider. */
|
||||
export function WorkspaceTabCloseErrorToasts(): null {
|
||||
const toast = useToast();
|
||||
useEffect(() => {
|
||||
showError = toast.error;
|
||||
return () => {
|
||||
showError = null;
|
||||
};
|
||||
}, [toast]);
|
||||
return null;
|
||||
}
|
||||
+1
-1
@@ -3,7 +3,7 @@ import {
|
||||
buildBulkCloseConfirmationMessage,
|
||||
classifyBulkClosableTabs,
|
||||
closeBulkWorkspaceTabs,
|
||||
} from "@/screens/workspace/workspace-bulk-close";
|
||||
} from "@/workspace-tabs/close/internal/bulk";
|
||||
import type { WorkspaceTabDescriptor } from "@/screens/workspace/workspace-tabs-types";
|
||||
|
||||
function makeAgentTab(id: string): WorkspaceTabDescriptor {
|
||||
+3
-3
@@ -137,7 +137,7 @@ export async function closeBulkWorkspaceTabs(input: CloseBulkWorkspaceTabsInput)
|
||||
try {
|
||||
await closeLayoutOnlyAgent(agentId);
|
||||
} catch (error) {
|
||||
warn?.(`[WorkspaceScreen] Failed to close subagent tab ${logLabel}`, { error, agentId });
|
||||
warn?.(`[workspaceTabClose] Failed to close subagent tab ${logLabel}`, { error, agentId });
|
||||
return;
|
||||
}
|
||||
closeWorkspaceTabWithCleanup({
|
||||
@@ -154,10 +154,10 @@ export async function closeBulkWorkspaceTabs(input: CloseBulkWorkspaceTabsInput)
|
||||
terminalIds: groups.terminalTabs.map((tab) => tab.terminalId),
|
||||
})
|
||||
.catch((error) => {
|
||||
warn?.(`[WorkspaceScreen] Failed to bulk close tabs ${logLabel}`, { error });
|
||||
warn?.(`[workspaceTabClose] Failed to bulk close tabs ${logLabel}`, { error });
|
||||
});
|
||||
} else if (hasDestructiveTabs) {
|
||||
warn?.(`[WorkspaceScreen] Failed to bulk close tabs ${logLabel}`, {
|
||||
warn?.(`[workspaceTabClose] Failed to bulk close tabs ${logLabel}`, {
|
||||
error: new Error(i18n.t("common.errors.daemonClientUnavailable")),
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,414 @@
|
||||
import type { DaemonClient } from "@getpaseo/client/internal/daemon-client";
|
||||
import { QueryClient } from "@tanstack/react-query";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { setPanelInstanceAttributes } from "@/panels/panel-instance-attributes";
|
||||
import { buildTerminalsQueryKey } from "@/screens/workspace/terminals/state";
|
||||
import { useSessionStore, type Agent } from "@/stores/session-store";
|
||||
import {
|
||||
collectAllPanes,
|
||||
collectAllTabs,
|
||||
useWorkspaceLayoutStore,
|
||||
} from "@/stores/workspace-layout-store";
|
||||
import { seedSessionHosts } from "@/test/seed-session";
|
||||
import type { ConfirmDialogInput } from "@/utils/confirm-dialog";
|
||||
import type { WorkspaceTabTarget } from "@/workspace-tabs/model";
|
||||
import { createWorkspaceTabClose } from "./command";
|
||||
|
||||
const SERVER_ID = "server-close";
|
||||
const WORKSPACE_ID = "workspace-1";
|
||||
const WORKSPACE_KEY = `${SERVER_ID}:${WORKSPACE_ID}`;
|
||||
const TERMINALS_KEY = buildTerminalsQueryKey(SERVER_ID, "/repo", WORKSPACE_ID);
|
||||
|
||||
/** An in-memory daemon that records the requests a close makes. */
|
||||
function createFakeDaemon() {
|
||||
const requests: unknown[][] = [];
|
||||
const daemon = {
|
||||
requests,
|
||||
killSucceeds: true,
|
||||
async killTerminal(terminalId: string) {
|
||||
requests.push(["killTerminal", terminalId]);
|
||||
return { terminalId, success: daemon.killSucceeds, requestId: "kill" };
|
||||
},
|
||||
async archiveAgent(agentId: string) {
|
||||
requests.push(["archiveAgent", agentId]);
|
||||
return { archivedAt: "2026-11-01T00:00:00.000Z" };
|
||||
},
|
||||
async updateAgent(agentId: string, updates: { labels?: Record<string, string> }) {
|
||||
requests.push(["updateAgent", agentId, Object.values(updates.labels ?? {})]);
|
||||
},
|
||||
async closeItems(items: { agentIds?: string[]; terminalIds?: string[] }) {
|
||||
requests.push(["closeItems", items]);
|
||||
return { agents: [], terminals: [], requestId: "close-items" };
|
||||
},
|
||||
};
|
||||
return daemon;
|
||||
}
|
||||
|
||||
/** A dialog the test answers, either ahead of time or while it is still open. */
|
||||
function createFakeDialog() {
|
||||
const prompts: ConfirmDialogInput[] = [];
|
||||
const answers: Array<boolean | Promise<boolean>> = [];
|
||||
return {
|
||||
prompts,
|
||||
answer(...next: Array<boolean | Promise<boolean>>) {
|
||||
answers.push(...next);
|
||||
},
|
||||
async confirm(input: ConfirmDialogInput): Promise<boolean> {
|
||||
prompts.push(input);
|
||||
const next = answers.shift();
|
||||
if (next === undefined) throw new Error(`Unexpected prompt: ${input.title}`);
|
||||
return next;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function setup() {
|
||||
const daemon = createFakeDaemon();
|
||||
const dialog = createFakeDialog();
|
||||
const errors: string[] = [];
|
||||
const queryClient = new QueryClient();
|
||||
let connected = true;
|
||||
useSessionStore.getState().updateSessionClient(SERVER_ID, daemon as unknown as DaemonClient);
|
||||
const tabs = createWorkspaceTabClose({
|
||||
confirm: dialog.confirm,
|
||||
reportError: (message) => errors.push(message),
|
||||
getClient: () => (connected ? (daemon as unknown as DaemonClient) : null),
|
||||
queryClient,
|
||||
});
|
||||
return {
|
||||
...tabs,
|
||||
daemon,
|
||||
dialog,
|
||||
errors,
|
||||
queryClient,
|
||||
disconnect: () => {
|
||||
connected = false;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function open(target: WorkspaceTabTarget): string {
|
||||
const tabId = useWorkspaceLayoutStore
|
||||
.getState()
|
||||
.openTab({ workspaceKey: WORKSPACE_KEY, target, intent: "reveal" });
|
||||
if (!tabId) throw new Error("Tab did not open");
|
||||
return tabId;
|
||||
}
|
||||
|
||||
function openTabIds(): string[] {
|
||||
const layout = useWorkspaceLayoutStore.getState().layoutByWorkspace[WORKSPACE_KEY];
|
||||
return collectAllTabs(layout.root).map((tab) => tab.tabId);
|
||||
}
|
||||
|
||||
function seedAgent(id: string, overrides: Partial<Agent> = {}): 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: id,
|
||||
cwd: "/repo",
|
||||
model: null,
|
||||
parentAgentId: null,
|
||||
labels: {},
|
||||
archivedAt: null,
|
||||
turn: { phase: "idle", cancellationRequestId: null },
|
||||
...overrides,
|
||||
};
|
||||
useSessionStore
|
||||
.getState()
|
||||
.setAgents(SERVER_ID, (current) => new Map(current).set(agent.id, agent));
|
||||
}
|
||||
|
||||
function setModified(tabId: string, suspendPendingSave?: () => () => void): void {
|
||||
setPanelInstanceAttributes(
|
||||
{ serverId: SERVER_ID, workspaceId: WORKSPACE_ID, tabId },
|
||||
{ modified: true, suspendPendingSave },
|
||||
);
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
useSessionStore.setState((state) => ({ ...state, sessions: {} }));
|
||||
seedSessionHosts([SERVER_ID]);
|
||||
useWorkspaceLayoutStore.setState({
|
||||
layoutMode: "split-panes",
|
||||
sheetsByWorkspace: {},
|
||||
layoutByWorkspace: {},
|
||||
explorerSidebarPaneIdByWorkspace: {},
|
||||
sidePaneIdByWorkspace: {},
|
||||
hiddenAgentIdsByWorkspace: {},
|
||||
pinnedAgentIdsByWorkspace: {},
|
||||
});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
const layout = useWorkspaceLayoutStore.getState().layoutByWorkspace[WORKSPACE_KEY];
|
||||
for (const tab of layout ? collectAllTabs(layout.root) : []) {
|
||||
setPanelInstanceAttributes(
|
||||
{ serverId: SERVER_ID, workspaceId: WORKSPACE_ID, tabId: tab.tabId },
|
||||
{ modified: false },
|
||||
);
|
||||
}
|
||||
seedSessionHosts([]);
|
||||
});
|
||||
|
||||
describe("closing a tab with no guard", () => {
|
||||
it("closes an unmodified file tab without asking or calling the daemon", async () => {
|
||||
const { closeTab, dialog, daemon } = setup();
|
||||
const tabId = open({ kind: "file", path: "src/a.ts" });
|
||||
|
||||
await expect(closeTab(WORKSPACE_KEY, tabId)).resolves.toBe(true);
|
||||
|
||||
expect(openTabIds()).not.toContain(tabId);
|
||||
expect(dialog.prompts).toEqual([]);
|
||||
expect(daemon.requests).toEqual([]);
|
||||
});
|
||||
|
||||
it("does nothing for a tab that is not open", async () => {
|
||||
const { closeTab, dialog } = setup();
|
||||
const tabId = open({ kind: "file", path: "src/a.ts" });
|
||||
|
||||
await expect(closeTab(WORKSPACE_KEY, "missing")).resolves.toBe(false);
|
||||
|
||||
expect(openTabIds()).toContain(tabId);
|
||||
expect(dialog.prompts).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("closing a tab with unsaved work", () => {
|
||||
it("closes it once the user discards the changes", async () => {
|
||||
const { closeTab, dialog } = setup();
|
||||
const tabId = open({ kind: "file", path: "src/a.ts" });
|
||||
setModified(tabId);
|
||||
dialog.answer(true);
|
||||
|
||||
await expect(closeTab(WORKSPACE_KEY, tabId)).resolves.toBe(true);
|
||||
|
||||
expect(openTabIds()).not.toContain(tabId);
|
||||
expect(dialog.prompts).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("keeps it and resumes the pending save when the user cancels", async () => {
|
||||
const { closeTab, dialog } = setup();
|
||||
const tabId = open({ kind: "file", path: "src/a.ts" });
|
||||
const saves: string[] = [];
|
||||
setModified(tabId, () => {
|
||||
saves.push("suspended");
|
||||
return () => saves.push("resumed");
|
||||
});
|
||||
dialog.answer(false);
|
||||
|
||||
await expect(closeTab(WORKSPACE_KEY, tabId)).resolves.toBe(false);
|
||||
|
||||
expect(openTabIds()).toContain(tabId);
|
||||
expect(saves).toEqual(["suspended", "resumed"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("closing a terminal tab", () => {
|
||||
function openTerminal(queryClient: QueryClient): string {
|
||||
queryClient.setQueryData(TERMINALS_KEY, {
|
||||
terminals: [{ id: "t1" }, { id: "t2" }],
|
||||
});
|
||||
return open({ kind: "terminal", terminalId: "t1" });
|
||||
}
|
||||
|
||||
it("kills the terminal and drops it from the cached list once confirmed", async () => {
|
||||
const { closeTab, dialog, daemon, queryClient } = setup();
|
||||
const tabId = openTerminal(queryClient);
|
||||
dialog.answer(true);
|
||||
|
||||
await expect(closeTab(WORKSPACE_KEY, tabId)).resolves.toBe(true);
|
||||
|
||||
expect(openTabIds()).not.toContain(tabId);
|
||||
expect(daemon.requests).toEqual([["killTerminal", "t1"]]);
|
||||
expect(queryClient.getQueryData(TERMINALS_KEY)).toEqual({ terminals: [{ id: "t2" }] });
|
||||
});
|
||||
|
||||
it("keeps the tab and the terminal when cancelled", async () => {
|
||||
const { closeTab, dialog, daemon, queryClient } = setup();
|
||||
const tabId = openTerminal(queryClient);
|
||||
dialog.answer(false);
|
||||
|
||||
await expect(closeTab(WORKSPACE_KEY, tabId)).resolves.toBe(false);
|
||||
|
||||
expect(openTabIds()).toContain(tabId);
|
||||
expect(daemon.requests).toEqual([]);
|
||||
});
|
||||
|
||||
it("refetches the terminal list when the daemon cannot kill the terminal", async () => {
|
||||
const { closeTab, dialog, daemon, queryClient } = setup();
|
||||
const tabId = openTerminal(queryClient);
|
||||
daemon.killSucceeds = false;
|
||||
dialog.answer(true);
|
||||
|
||||
await closeTab(WORKSPACE_KEY, tabId);
|
||||
|
||||
await vi.waitFor(() =>
|
||||
expect(queryClient.getQueryState(TERMINALS_KEY)?.isInvalidated).toBe(true),
|
||||
);
|
||||
});
|
||||
|
||||
it("reports the tab as closing while its prompt is open and asks only once", async () => {
|
||||
const { closeTab, closing, dialog, queryClient } = setup();
|
||||
const tabId = openTerminal(queryClient);
|
||||
let answer: (confirmed: boolean) => void = () => {};
|
||||
dialog.answer(new Promise<boolean>((resolve) => (answer = resolve)));
|
||||
|
||||
const first = closeTab(WORKSPACE_KEY, tabId);
|
||||
await vi.waitFor(() => expect(dialog.prompts).toHaveLength(1));
|
||||
expect(closing.getState()[WORKSPACE_KEY]?.has(tabId)).toBe(true);
|
||||
await expect(closeTab(WORKSPACE_KEY, tabId)).resolves.toBe(false);
|
||||
|
||||
answer(false);
|
||||
await first;
|
||||
expect(closing.getState()[WORKSPACE_KEY]?.has(tabId)).toBe(false);
|
||||
expect(dialog.prompts).toHaveLength(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe("closing an agent tab", () => {
|
||||
it("archives an idle agent without asking", async () => {
|
||||
const { closeTab, dialog, daemon } = setup();
|
||||
seedAgent("a1");
|
||||
const tabId = open({ kind: "agent", agentId: "a1" });
|
||||
|
||||
await expect(closeTab(WORKSPACE_KEY, tabId)).resolves.toBe(true);
|
||||
|
||||
expect(openTabIds()).not.toContain(tabId);
|
||||
expect(dialog.prompts).toEqual([]);
|
||||
await vi.waitFor(() => expect(daemon.requests).toEqual([["archiveAgent", "a1"]]));
|
||||
});
|
||||
|
||||
it("asks before archiving a running agent", async () => {
|
||||
const { closeTab, dialog, daemon } = setup();
|
||||
seedAgent("a1", { status: "running" });
|
||||
const tabId = open({ kind: "agent", agentId: "a1" });
|
||||
dialog.answer(true);
|
||||
|
||||
await expect(closeTab(WORKSPACE_KEY, tabId)).resolves.toBe(true);
|
||||
|
||||
expect(openTabIds()).not.toContain(tabId);
|
||||
expect(dialog.prompts).toHaveLength(1);
|
||||
await vi.waitFor(() => expect(daemon.requests).toEqual([["archiveAgent", "a1"]]));
|
||||
});
|
||||
|
||||
it("keeps a running agent and its tab when cancelled", async () => {
|
||||
const { closeTab, dialog, daemon } = setup();
|
||||
seedAgent("a1", { status: "running" });
|
||||
const tabId = open({ kind: "agent", agentId: "a1" });
|
||||
dialog.answer(false);
|
||||
|
||||
await expect(closeTab(WORKSPACE_KEY, tabId)).resolves.toBe(false);
|
||||
|
||||
expect(openTabIds()).toContain(tabId);
|
||||
expect(daemon.requests).toEqual([]);
|
||||
});
|
||||
|
||||
it("only releases a subagent's open-tab label, leaving it running", async () => {
|
||||
const { closeTab, dialog, daemon } = setup();
|
||||
seedAgent("child", { status: "running", parentAgentId: "parent" });
|
||||
const tabId = open({ kind: "agent", agentId: "child" });
|
||||
|
||||
await expect(closeTab(WORKSPACE_KEY, tabId)).resolves.toBe(true);
|
||||
|
||||
expect(openTabIds()).not.toContain(tabId);
|
||||
expect(dialog.prompts).toEqual([]);
|
||||
expect(daemon.requests).toEqual([["updateAgent", "child", ["false"]]]);
|
||||
});
|
||||
|
||||
it("keeps a subagent tab and reports why when the host is unreachable", async () => {
|
||||
const { closeTab, disconnect, errors } = setup();
|
||||
seedAgent("child", { parentAgentId: "parent" });
|
||||
const tabId = open({ kind: "agent", agentId: "child" });
|
||||
disconnect();
|
||||
|
||||
await expect(closeTab(WORKSPACE_KEY, tabId)).resolves.toBe(false);
|
||||
|
||||
expect(openTabIds()).toContain(tabId);
|
||||
expect(errors).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("dismisses an agent's sheet without archiving it", async () => {
|
||||
const { closeTab, daemon } = setup();
|
||||
seedAgent("parent");
|
||||
seedAgent("child", { parentAgentId: "parent" });
|
||||
open({ kind: "file", path: "src/a.ts" });
|
||||
useWorkspaceLayoutStore.getState().setLayoutMode("compact");
|
||||
const tabId = open({ kind: "agent", agentId: "child" });
|
||||
const sheetTabIds = () =>
|
||||
useWorkspaceLayoutStore
|
||||
.getState()
|
||||
.sheetsByWorkspace[WORKSPACE_KEY]?.map((sheet) => sheet.tab.tabId) ?? [];
|
||||
expect(sheetTabIds()).toEqual([tabId]);
|
||||
|
||||
await expect(closeTab(WORKSPACE_KEY, tabId)).resolves.toBe(true);
|
||||
|
||||
expect(sheetTabIds()).toEqual([]);
|
||||
expect(daemon.requests).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("closing a pane", () => {
|
||||
function openSidePane(): { paneId: string; tabIds: string[] } {
|
||||
open({ kind: "file", path: "src/stays.ts" });
|
||||
const paneId = useWorkspaceLayoutStore
|
||||
.getState()
|
||||
.splitPaneEmpty(WORKSPACE_KEY, { targetPaneId: "main", position: "right" });
|
||||
if (!paneId) throw new Error("Pane did not split");
|
||||
seedAgent("a1");
|
||||
return {
|
||||
paneId,
|
||||
tabIds: [
|
||||
open({ kind: "agent", agentId: "a1" }),
|
||||
open({ kind: "terminal", terminalId: "t1" }),
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
function paneIds(): string[] {
|
||||
const layout = useWorkspaceLayoutStore.getState().layoutByWorkspace[WORKSPACE_KEY];
|
||||
return collectAllPanes(layout.root).map((pane) => pane.id);
|
||||
}
|
||||
|
||||
it("asks once, tears down every tab and removes the pane", async () => {
|
||||
const { closePane, dialog, daemon } = setup();
|
||||
const { paneId, tabIds } = openSidePane();
|
||||
dialog.answer(true);
|
||||
|
||||
await expect(closePane(WORKSPACE_KEY, paneId)).resolves.toBe(true);
|
||||
|
||||
expect(dialog.prompts).toHaveLength(1);
|
||||
expect(daemon.requests).toEqual([["closeItems", { agentIds: ["a1"], terminalIds: ["t1"] }]]);
|
||||
expect(paneIds()).not.toContain(paneId);
|
||||
for (const tabId of tabIds) expect(openTabIds()).not.toContain(tabId);
|
||||
});
|
||||
|
||||
it("keeps the pane and its tabs when cancelled", async () => {
|
||||
const { closePane, dialog, daemon } = setup();
|
||||
const { paneId, tabIds } = openSidePane();
|
||||
dialog.answer(false);
|
||||
|
||||
await expect(closePane(WORKSPACE_KEY, paneId)).resolves.toBe(false);
|
||||
|
||||
expect(daemon.requests).toEqual([]);
|
||||
expect(paneIds()).toContain(paneId);
|
||||
expect(openTabIds()).toEqual(expect.arrayContaining(tabIds));
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,411 @@
|
||||
import type { QueryClient } from "@tanstack/react-query";
|
||||
import type { DaemonClient } from "@getpaseo/client/internal/daemon-client";
|
||||
import { getOpenAgentTabLabel } from "@getpaseo/protocol/agent-labels";
|
||||
import { createStore } from "zustand/vanilla";
|
||||
import { getDesktopHost } from "@/desktop/host";
|
||||
import { removeResidentBrowserWebview } from "@/desktop/browser/resident-webviews";
|
||||
import { useBrowserStore } from "@/desktop/browser/store";
|
||||
import { archiveAgent } from "@/hooks/use-archive-agent";
|
||||
import { i18n } from "@/i18n/i18next";
|
||||
import { getWorkspacePanelAttributes } from "@/panels/panel-instance-attributes";
|
||||
import {
|
||||
buildHostTerminalsQueryKey,
|
||||
removeTerminalFromPayload,
|
||||
type ListTerminalsPayload,
|
||||
} from "@/screens/workspace/terminals/state";
|
||||
import type { WorkspaceTabDescriptor } from "@/screens/workspace/workspace-tabs-types";
|
||||
import { useSessionStore } from "@/stores/session-store";
|
||||
import {
|
||||
canDismissPaneInLayout,
|
||||
collectAllTabs,
|
||||
findPaneById,
|
||||
selectExplorerSidebarPaneId,
|
||||
useWorkspaceLayoutStore,
|
||||
} from "@/stores/workspace-layout-store";
|
||||
import { resolveCloseAgentTabPolicy } from "@/subagents/policies";
|
||||
import { getOrCreateClientId } from "@/utils/client-id";
|
||||
import type { ConfirmDialogInput } from "@/utils/confirm-dialog";
|
||||
import { parseWorkspaceTabPersistenceKey, type WorkspaceTabTarget } from "@/workspace-tabs/model";
|
||||
import {
|
||||
buildBulkCloseConfirmationMessage,
|
||||
classifyBulkClosableTabs,
|
||||
closeBulkWorkspaceTabs,
|
||||
type BulkCloseConfirmationLabels,
|
||||
} from "./bulk";
|
||||
|
||||
/** What closing a tab needs from the app around it. */
|
||||
export interface WorkspaceTabClosePorts {
|
||||
confirm: (input: ConfirmDialogInput) => Promise<boolean>;
|
||||
reportError: (message: string) => void;
|
||||
getClient: (
|
||||
serverId: string,
|
||||
) => Pick<DaemonClient, "killTerminal" | "updateAgent" | "closeItems"> | null;
|
||||
queryClient: QueryClient;
|
||||
}
|
||||
|
||||
/** Which neighbours of a tab are being closed together; picks the prompt's title. */
|
||||
export type BulkCloseScope = "left" | "right" | "others";
|
||||
|
||||
export type ClosingWorkspaceTabs = Readonly<Record<string, ReadonlySet<string> | undefined>>;
|
||||
|
||||
const BULK_CLOSE_PROMPTS = {
|
||||
left: {
|
||||
titleKey: "workspace.tabs.confirmations.closeTabsLeftTitle",
|
||||
logLabel: "to the left",
|
||||
},
|
||||
right: {
|
||||
titleKey: "workspace.tabs.confirmations.closeTabsRightTitle",
|
||||
logLabel: "to the right",
|
||||
},
|
||||
others: {
|
||||
titleKey: "workspace.tabs.confirmations.closeOtherTabsTitle",
|
||||
logLabel: "from close other tabs",
|
||||
},
|
||||
pane: {
|
||||
titleKey: "workspace.tabs.confirmations.closePaneTitle",
|
||||
logLabel: "from pane close",
|
||||
},
|
||||
} as const;
|
||||
|
||||
const BULK_CLOSE_LABELS: BulkCloseConfirmationLabels = {
|
||||
all: (counts) => i18n.t("workspace.tabs.confirmations.bulk.all", counts),
|
||||
agentsAndTerminals: (counts) =>
|
||||
i18n.t("workspace.tabs.confirmations.bulk.agentsAndTerminals", counts),
|
||||
terminalsAndTabs: (counts) =>
|
||||
i18n.t("workspace.tabs.confirmations.bulk.terminalsAndTabs", counts),
|
||||
agentsAndTabs: (counts) => i18n.t("workspace.tabs.confirmations.bulk.agentsAndTabs", counts),
|
||||
terminals: (counts) => i18n.t("workspace.tabs.confirmations.bulk.terminals", counts),
|
||||
tabs: (counts) => i18n.t("workspace.tabs.confirmations.bulk.tabs", counts),
|
||||
agents: (counts) => i18n.t("workspace.tabs.confirmations.bulk.agents", counts),
|
||||
};
|
||||
|
||||
function getAgent(serverId: string, agentId: string) {
|
||||
return useSessionStore.getState().sessions[serverId]?.agents?.get(agentId) ?? null;
|
||||
}
|
||||
|
||||
function getLayoutTabs(workspaceKey: string): WorkspaceTabDescriptor[] {
|
||||
const layout = useWorkspaceLayoutStore.getState().layoutByWorkspace[workspaceKey];
|
||||
if (!layout) {
|
||||
return [];
|
||||
}
|
||||
return collectAllTabs(layout.root).map((tab) => ({
|
||||
key: tab.tabId,
|
||||
tabId: tab.tabId,
|
||||
kind: tab.target.kind,
|
||||
target: tab.target,
|
||||
}));
|
||||
}
|
||||
|
||||
function pickTabs(workspaceKey: string, tabIds: readonly string[]): WorkspaceTabDescriptor[] {
|
||||
const tabsById = new Map(getLayoutTabs(workspaceKey).map((tab) => [tab.tabId, tab]));
|
||||
return tabIds.flatMap((tabId) => {
|
||||
const tab = tabsById.get(tabId);
|
||||
return tab ? [tab] : [];
|
||||
});
|
||||
}
|
||||
|
||||
/** Removes the tab and everything this client holds for it. Daemon resources are the caller's. */
|
||||
function removeTab(workspaceKey: string, tabId: string, target: WorkspaceTabTarget): void {
|
||||
const layout = useWorkspaceLayoutStore.getState();
|
||||
if (target.kind === "agent") {
|
||||
layout.unpinAgent(workspaceKey, target.agentId);
|
||||
layout.hideAgent(workspaceKey, target.agentId);
|
||||
}
|
||||
if (target.kind === "browser") {
|
||||
const { browserId } = target;
|
||||
useBrowserStore.getState().removeBrowser(browserId);
|
||||
removeResidentBrowserWebview(browserId);
|
||||
void getDesktopHost()?.browser?.unregisterWorkspaceBrowser?.(browserId);
|
||||
}
|
||||
layout.closeTab(workspaceKey, tabId);
|
||||
}
|
||||
|
||||
export function createWorkspaceTabClose(ports: WorkspaceTabClosePorts) {
|
||||
const closing = createStore<ClosingWorkspaceTabs>(() => ({}));
|
||||
|
||||
function setClosing(workspaceKey: string, tabId: string, isClosing: boolean): void {
|
||||
closing.setState((state) => {
|
||||
const tabIds = new Set(state[workspaceKey]);
|
||||
if (isClosing) tabIds.add(tabId);
|
||||
else tabIds.delete(tabId);
|
||||
return { [workspaceKey]: tabIds };
|
||||
});
|
||||
}
|
||||
|
||||
/** Runs one close per tab at a time; a repeat while it is pending does nothing. */
|
||||
async function whileClosing(
|
||||
workspaceKey: string,
|
||||
tabId: string,
|
||||
close: () => Promise<boolean>,
|
||||
): Promise<boolean> {
|
||||
if (closing.getState()[workspaceKey]?.has(tabId)) {
|
||||
return false;
|
||||
}
|
||||
setClosing(workspaceKey, tabId, true);
|
||||
try {
|
||||
return await close();
|
||||
} finally {
|
||||
setClosing(workspaceKey, tabId, false);
|
||||
}
|
||||
}
|
||||
|
||||
async function confirmDiscardChanges(workspaceKey: string, tabId: string): Promise<boolean> {
|
||||
const attributes = getWorkspacePanelAttributes(workspaceKey, tabId);
|
||||
if (!attributes.modified) return true;
|
||||
const resumePendingSave = attributes.suspendPendingSave?.();
|
||||
const confirmed = await ports.confirm({
|
||||
title: i18n.t("workspace.tabs.confirmations.unsavedTitle"),
|
||||
message: i18n.t("workspace.tabs.confirmations.unsavedMessage"),
|
||||
confirmLabel: i18n.t("workspace.tabs.confirmations.closeWithoutSaving"),
|
||||
cancelLabel: i18n.t("workspace.tabs.confirmations.cancel"),
|
||||
destructive: true,
|
||||
});
|
||||
if (!confirmed) resumePendingSave?.();
|
||||
return confirmed;
|
||||
}
|
||||
|
||||
async function killTerminal(serverId: string, terminalId: string): Promise<void> {
|
||||
const client = ports.getClient(serverId);
|
||||
if (!client) {
|
||||
throw new Error(i18n.t("workspace.terminal.hostDisconnected"));
|
||||
}
|
||||
const payload = await client.killTerminal(terminalId);
|
||||
if (!payload.success) {
|
||||
throw new Error("Unable to close terminal");
|
||||
}
|
||||
}
|
||||
|
||||
async function closeTerminalTab(input: {
|
||||
workspaceKey: string;
|
||||
serverId: string;
|
||||
tabId: string;
|
||||
terminalId: string;
|
||||
}): Promise<boolean> {
|
||||
const { workspaceKey, serverId, tabId, terminalId } = input;
|
||||
const confirmed = await ports.confirm({
|
||||
title: i18n.t("workspace.tabs.confirmations.closeTerminalTitle"),
|
||||
message: i18n.t("workspace.tabs.confirmations.closeTerminalMessage"),
|
||||
confirmLabel: i18n.t("workspace.tabs.confirmations.close"),
|
||||
cancelLabel: i18n.t("workspace.tabs.confirmations.cancel"),
|
||||
destructive: true,
|
||||
});
|
||||
if (!confirmed) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const queryKey = buildHostTerminalsQueryKey(serverId);
|
||||
// Only lists holding the terminal are written: a write also bumps a list's update time.
|
||||
ports.queryClient.setQueriesData<ListTerminalsPayload>(
|
||||
{
|
||||
queryKey,
|
||||
predicate: (query) =>
|
||||
(query.state.data as ListTerminalsPayload | undefined)?.terminals.some(
|
||||
(terminal) => terminal.id === terminalId,
|
||||
) ?? false,
|
||||
},
|
||||
removeTerminalFromPayload(terminalId),
|
||||
);
|
||||
removeTab(workspaceKey, tabId, { kind: "terminal", terminalId });
|
||||
|
||||
void killTerminal(serverId, terminalId).catch(
|
||||
() => void ports.queryClient.invalidateQueries({ queryKey }),
|
||||
);
|
||||
return true;
|
||||
}
|
||||
|
||||
async function closeAgentTab(input: {
|
||||
workspaceKey: string;
|
||||
serverId: string;
|
||||
tabId: string;
|
||||
agentId: string;
|
||||
}): Promise<boolean> {
|
||||
const { workspaceKey, serverId, tabId, agentId } = input;
|
||||
const agent = getAgent(serverId, agentId);
|
||||
let closePolicy = resolveCloseAgentTabPolicy(agent);
|
||||
|
||||
if (agent?.status === "running" && closePolicy.kind === "archive-on-close") {
|
||||
const confirmed = await ports.confirm({
|
||||
title: i18n.t("workspace.tabs.confirmations.archiveRunningAgentTitle"),
|
||||
message: i18n.t("workspace.tabs.confirmations.archiveRunningAgentMessage"),
|
||||
confirmLabel: i18n.t("workspace.tabs.confirmations.archive"),
|
||||
cancelLabel: i18n.t("workspace.tabs.confirmations.cancel"),
|
||||
destructive: true,
|
||||
});
|
||||
if (!confirmed) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
if (closePolicy.kind === "layout-only") {
|
||||
const client = ports.getClient(serverId);
|
||||
if (!client) {
|
||||
ports.reportError(i18n.t("common.errors.daemonClientUnavailable"));
|
||||
return false;
|
||||
}
|
||||
try {
|
||||
const clientId = await getOrCreateClientId();
|
||||
await client.updateAgent(agentId, {
|
||||
labels: { [getOpenAgentTabLabel(clientId)]: "false" },
|
||||
});
|
||||
// The agent may have been detached while the label was being written.
|
||||
closePolicy = resolveCloseAgentTabPolicy(getAgent(serverId, agentId));
|
||||
} catch (error) {
|
||||
console.error("[workspaceTabClose] Failed to close subagent tab", { error, agentId });
|
||||
ports.reportError(i18n.t("workspace.tabs.toasts.failedToCloseAgent"));
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
removeTab(workspaceKey, tabId, { kind: "agent", agentId });
|
||||
|
||||
if (closePolicy.kind === "archive-on-close") {
|
||||
// A failed archive restores the agent inside archiveAgent.
|
||||
void archiveAgent(ports.queryClient, { serverId, agentId }).catch(() => {});
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Closes one tab after its guards, then releases what it owns. Resolves true once removed. */
|
||||
async function closeTab(workspaceKey: string, tabId: string): Promise<boolean> {
|
||||
const identity = parseWorkspaceTabPersistenceKey(workspaceKey);
|
||||
if (!identity) {
|
||||
return false;
|
||||
}
|
||||
const { serverId } = identity;
|
||||
const sheets = useWorkspaceLayoutStore.getState().sheetsByWorkspace[workspaceKey];
|
||||
// A sheet is a view over its resource, so dismissing it releases nothing.
|
||||
if (sheets?.some((sheet) => sheet.tab.tabId === tabId)) {
|
||||
if (!(await confirmDiscardChanges(workspaceKey, tabId))) {
|
||||
return false;
|
||||
}
|
||||
useWorkspaceLayoutStore.getState().closeTab(workspaceKey, tabId);
|
||||
return true;
|
||||
}
|
||||
|
||||
const tab = getLayoutTabs(workspaceKey).find((candidate) => candidate.tabId === tabId);
|
||||
if (!tab || !(await confirmDiscardChanges(workspaceKey, tabId))) {
|
||||
return false;
|
||||
}
|
||||
const { target } = tab;
|
||||
if (target.kind === "terminal") {
|
||||
const { terminalId } = target;
|
||||
return whileClosing(workspaceKey, tabId, () =>
|
||||
closeTerminalTab({ workspaceKey, serverId, tabId, terminalId }),
|
||||
);
|
||||
}
|
||||
if (target.kind === "agent") {
|
||||
const { agentId } = target;
|
||||
return whileClosing(workspaceKey, tabId, () =>
|
||||
closeAgentTab({ workspaceKey, serverId, tabId, agentId }),
|
||||
);
|
||||
}
|
||||
removeTab(workspaceKey, tabId, target);
|
||||
return true;
|
||||
}
|
||||
|
||||
/** One prompt for the whole set. Resolves false when the user declines it. */
|
||||
async function closeTogether(
|
||||
workspaceKey: string,
|
||||
tabIds: readonly string[],
|
||||
prompt: keyof typeof BULK_CLOSE_PROMPTS,
|
||||
): Promise<boolean> {
|
||||
const identity = parseWorkspaceTabPersistenceKey(workspaceKey);
|
||||
if (!identity) {
|
||||
return false;
|
||||
}
|
||||
const { serverId } = identity;
|
||||
const tabsToClose = pickTabs(workspaceKey, tabIds);
|
||||
if (tabsToClose.length === 0) {
|
||||
return true;
|
||||
}
|
||||
const { titleKey, logLabel } = BULK_CLOSE_PROMPTS[prompt];
|
||||
const client = ports.getClient(serverId);
|
||||
|
||||
const groups = classifyBulkClosableTabs(tabsToClose, (agentId) =>
|
||||
resolveCloseAgentTabPolicy(getAgent(serverId, agentId)).kind === "layout-only"
|
||||
? "layout-only"
|
||||
: "archive",
|
||||
);
|
||||
const modifiedCount = tabsToClose.filter(
|
||||
(tab) => getWorkspacePanelAttributes(workspaceKey, tab.tabId).modified,
|
||||
).length;
|
||||
const message = buildBulkCloseConfirmationMessage(groups, BULK_CLOSE_LABELS);
|
||||
const confirmed = await ports.confirm({
|
||||
title: i18n.t(titleKey),
|
||||
message:
|
||||
modifiedCount > 0
|
||||
? `${message}\n\n${i18n.t("workspace.tabs.confirmations.bulkUnsaved", { count: modifiedCount })}`
|
||||
: message,
|
||||
confirmLabel: i18n.t("workspace.tabs.confirmations.close"),
|
||||
cancelLabel: i18n.t("workspace.tabs.confirmations.cancel"),
|
||||
destructive: true,
|
||||
});
|
||||
if (!confirmed) {
|
||||
return false;
|
||||
}
|
||||
|
||||
await closeBulkWorkspaceTabs({
|
||||
client,
|
||||
groups,
|
||||
closeTab: async (tabId, action) => {
|
||||
await whileClosing(workspaceKey, tabId, async () => {
|
||||
await action();
|
||||
return true;
|
||||
});
|
||||
},
|
||||
closeLayoutOnlyAgent: async (agentId) => {
|
||||
if (!client) {
|
||||
throw new Error(i18n.t("common.errors.daemonClientUnavailable"));
|
||||
}
|
||||
const clientId = await getOrCreateClientId();
|
||||
await client.updateAgent(agentId, {
|
||||
labels: { [getOpenAgentTabLabel(clientId)]: "false" },
|
||||
});
|
||||
const latestAgent = getAgent(serverId, agentId);
|
||||
if (resolveCloseAgentTabPolicy(latestAgent).kind === "archive-on-close") {
|
||||
await archiveAgent(ports.queryClient, { serverId, agentId });
|
||||
}
|
||||
},
|
||||
closeWorkspaceTabWithCleanup: ({ tabId, target }) => {
|
||||
if (target) removeTab(workspaceKey, tabId, target);
|
||||
},
|
||||
logLabel,
|
||||
warn: (warning, payload) => {
|
||||
console.warn(warning, payload);
|
||||
},
|
||||
});
|
||||
return true;
|
||||
}
|
||||
|
||||
function closeTabs(
|
||||
workspaceKey: string,
|
||||
tabIds: readonly string[],
|
||||
scope: BulkCloseScope,
|
||||
): Promise<boolean> {
|
||||
return closeTogether(workspaceKey, tabIds, scope);
|
||||
}
|
||||
|
||||
/** Closes a pane and its tabs behind one prompt. Resolves true once the pane is gone. */
|
||||
async function closePane(workspaceKey: string, paneId: string): Promise<boolean> {
|
||||
const state = useWorkspaceLayoutStore.getState();
|
||||
const layout = state.layoutByWorkspace[workspaceKey];
|
||||
if (!layout) {
|
||||
return false;
|
||||
}
|
||||
const pane = findPaneById(layout.root, paneId);
|
||||
// Ask before tearing anything down. The layout refuses to dismiss the final
|
||||
// visible pane, and discovering that after closing its tabs would cost the
|
||||
// user the tabs and leave the pane standing.
|
||||
const explorerSidebarPaneId = selectExplorerSidebarPaneId(state, workspaceKey);
|
||||
if (!pane || !canDismissPaneInLayout(layout, paneId, explorerSidebarPaneId)) {
|
||||
return false;
|
||||
}
|
||||
if (!(await closeTogether(workspaceKey, pane.tabIds, "pane"))) {
|
||||
return false;
|
||||
}
|
||||
useWorkspaceLayoutStore.getState().closePane(workspaceKey, paneId);
|
||||
return true;
|
||||
}
|
||||
|
||||
return { closing, closeTab, closeTabs, closePane };
|
||||
}
|
||||
@@ -4,6 +4,7 @@ import {
|
||||
useWorkspaceLayoutStore,
|
||||
} from "@/stores/workspace-layout-store";
|
||||
import type { WorkspaceTabTarget } from "@/workspace-tabs/model";
|
||||
import type { AppOverlays } from "@/workspace-tabs/navigation";
|
||||
|
||||
export type ExplorerSidebarView = "changes" | "files" | "pr";
|
||||
export type ExplorerSidebarPresentation = "overlay" | "dock";
|
||||
@@ -19,6 +20,11 @@ export interface ExplorerSidebarQuery {
|
||||
workspaceKey: string | null;
|
||||
}
|
||||
|
||||
export interface ExplorerSidebarCommand extends ExplorerSidebarQuery {
|
||||
/** A phone's Explorer is an app overlay. Defaults to `follow`. */
|
||||
overlays?: AppOverlays;
|
||||
}
|
||||
|
||||
export function resolveExplorerSidebarPresentation(
|
||||
input: Pick<ExplorerSidebarQuery, "isCompact">,
|
||||
): ExplorerSidebarPresentation {
|
||||
@@ -43,8 +49,8 @@ export function openExplorerSidebarView(
|
||||
});
|
||||
}
|
||||
|
||||
export function showExplorerSidebar(input: ExplorerSidebarQuery): string | null {
|
||||
if (input.isCompact) {
|
||||
export function showExplorerSidebar(input: ExplorerSidebarCommand): string | null {
|
||||
if (input.isCompact && input.overlays !== "keep") {
|
||||
usePanelStore.getState().showMobileFileExplorer();
|
||||
}
|
||||
if (input.workspaceKey) {
|
||||
@@ -56,9 +62,9 @@ export function showExplorerSidebar(input: ExplorerSidebarQuery): string | null
|
||||
return null;
|
||||
}
|
||||
|
||||
export function hideExplorerSidebar(input: ExplorerSidebarQuery): void {
|
||||
export function hideExplorerSidebar(input: ExplorerSidebarCommand): void {
|
||||
if (input.isCompact) {
|
||||
usePanelStore.getState().showMobileAgent();
|
||||
if (input.overlays !== "keep") usePanelStore.getState().showMobileAgent();
|
||||
return;
|
||||
}
|
||||
if (input.workspaceKey) {
|
||||
@@ -66,7 +72,7 @@ export function hideExplorerSidebar(input: ExplorerSidebarQuery): void {
|
||||
}
|
||||
}
|
||||
|
||||
export function toggleExplorerSidebar(input: ExplorerSidebarQuery): void {
|
||||
export function toggleExplorerSidebar(input: ExplorerSidebarCommand): void {
|
||||
if (input.isCompact) {
|
||||
if (isExplorerSidebarOpen(input)) hideExplorerSidebar(input);
|
||||
else showExplorerSidebar(input);
|
||||
|
||||
@@ -67,3 +67,17 @@ export function buildWorkspaceTabPersistenceKey(input: {
|
||||
}
|
||||
return `${serverId}:${workspaceId}`;
|
||||
}
|
||||
|
||||
/** The inverse of {@link buildWorkspaceTabPersistenceKey}. Server ids contain no colon. */
|
||||
export function parseWorkspaceTabPersistenceKey(
|
||||
workspaceKey: string,
|
||||
): { serverId: string; workspaceId: string } | null {
|
||||
const separator = workspaceKey.indexOf(":");
|
||||
if (separator <= 0 || separator === workspaceKey.length - 1) {
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
serverId: workspaceKey.slice(0, separator),
|
||||
workspaceId: workspaceKey.slice(separator + 1),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,8 +1,20 @@
|
||||
import { useWorkspaceLayoutStore } from "@/stores/workspace-layout-store";
|
||||
import { usePanelStore } from "@/stores/panel-store";
|
||||
|
||||
/**
|
||||
* What the app's overlays (a phone's Explorer and agent list, the touch agent list) do when a
|
||||
* workspace is arranged. There is one of each, over whatever screen the user is on. `follow` moves
|
||||
* them so the change can be seen. `keep` leaves them as they are, for a workspace that is not the
|
||||
* one on screen.
|
||||
*/
|
||||
export type AppOverlays = "follow" | "keep";
|
||||
|
||||
/** Reveals the actual destination after placement and deduplication, including existing tabs. */
|
||||
export function revealWorkspaceTab(workspaceKey: string, tabId: string | null): string | null {
|
||||
export function revealWorkspaceTab(
|
||||
workspaceKey: string,
|
||||
tabId: string | null,
|
||||
{ overlays = "follow" }: { overlays?: AppOverlays } = {},
|
||||
): string | null {
|
||||
if (!tabId) return null;
|
||||
const store = useWorkspaceLayoutStore.getState();
|
||||
const destination = store.getTabDestination(workspaceKey, tabId);
|
||||
@@ -10,6 +22,7 @@ export function revealWorkspaceTab(workspaceKey: string, tabId: string | null):
|
||||
if (!destination) return null;
|
||||
if (destination.kind === "sheet") return tabId;
|
||||
store.focusTab(workspaceKey, tabId);
|
||||
if (overlays === "keep") return tabId;
|
||||
const panels = usePanelStore.getState();
|
||||
if (store.layoutMode === "compact" && destination.host === "explorer") {
|
||||
panels.showMobileFileExplorer();
|
||||
|
||||
@@ -225,6 +225,129 @@ 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 workspace layout reach SDK boundary", () => {
|
||||
it("reaches the handle from the entry context, workspace and agent commands, and a tab", () => {
|
||||
expect(
|
||||
typeErrors(`
|
||||
import {
|
||||
type PluginClientContext,
|
||||
type PluginWorkspaceLayout,
|
||||
type PluginWorkspacePanelProps,
|
||||
} from "@getpaseo/plugin/client";
|
||||
function Panel({ tab }: PluginWorkspacePanelProps) {
|
||||
const id: string = tab.id;
|
||||
// @ts-expect-error the host names the tab
|
||||
tab.id = "other";
|
||||
return null;
|
||||
}
|
||||
export default function contribute(client: PluginClientContext) {
|
||||
client.addWorkspacePanel({ id: "panel", title: "Panel", icon: "File", Component: Panel });
|
||||
const layout: PluginWorkspaceLayout = client.workspaceLayout("workspace-1");
|
||||
client.addCommandCenterItem({ id: "workspace", title: "Workspace", icon: "File", context: "workspace",
|
||||
onSelect({ workspaceLayout }) { workspaceLayout.open({ panelId: "panel" }); } });
|
||||
client.addSlashCommand({ name: "aside", description: "Aside", argumentHint: "<message>", context: "agent",
|
||||
async onSubmit({ args, agent, workspace, paseo, workspaceLayout }) {
|
||||
const aside = await paseo.workspaces.ref(workspace.id).agents.create({
|
||||
config: { provider: \`\${agent.provider}/\${agent.model}\` },
|
||||
parent: agent.id,
|
||||
prompt: args,
|
||||
});
|
||||
workspaceLayout.open({ panelId: "paseo/agent", params: { agentId: aside.id } }, { placement: { type: "explorer" } });
|
||||
} });
|
||||
client.addCommandCenterItem({ id: "global", title: "Global", icon: "File", context: "global",
|
||||
onSelect(context) {
|
||||
// @ts-expect-error a global command has no workspace to arrange
|
||||
context.workspaceLayout;
|
||||
} });
|
||||
return () => {};
|
||||
}
|
||||
`),
|
||||
).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("plugin composer SDK boundary", () => {
|
||||
it("lets a composer item read and change the composer through typed commands and controls", () => {
|
||||
expect(
|
||||
|
||||
@@ -5,6 +5,7 @@ import type { PluginPaseoApi } from "./reference-api.js";
|
||||
import type { AgentTimelineItem, JsonValue } from "@getpaseo/protocol/agent-types";
|
||||
import type { ZodType, input as ZodInput, output as ZodOutput } from "zod";
|
||||
import type { PluginFile } from "./file.js";
|
||||
import type { PluginWorkspaceLayout } from "./workspace-layout.js";
|
||||
import type {
|
||||
PluginComposer,
|
||||
PluginComposerItemContribution,
|
||||
@@ -172,6 +173,8 @@ interface PluginWorkspacePanelBase<Text extends PluginText = string> {
|
||||
}
|
||||
|
||||
export interface PluginTab {
|
||||
/** This tab in its workspace's layout, as `useWorkspaceLayout` reads and arranges it. */
|
||||
readonly id: string;
|
||||
/** Shows the tab's unsaved dot and asks before closing. */
|
||||
setModified(modified: boolean): void;
|
||||
/** Opaque persisted JSON. Undefined until written; the panel validates it. */
|
||||
@@ -269,6 +272,16 @@ export interface PluginClientContext extends PluginCommandCapabilities, PluginCl
|
||||
contribution: PluginTimelineRendererContribution<Schema>,
|
||||
): PluginCleanup;
|
||||
onNotificationOpen(handler: PluginNotificationOpenHandler): PluginCleanup;
|
||||
/**
|
||||
* A handle on a workspace's panes and tabs on this client, for any workspace of the plugin's
|
||||
* host. Components use `useWorkspaceLayout`, which returns the same handle.
|
||||
*/
|
||||
workspaceLayout(workspaceId: string): PluginWorkspaceLayout;
|
||||
// COMPAT(pluginOpenPanel): added in v0.18.2, remove after 2027-05-01
|
||||
/**
|
||||
* @deprecated Use `workspaceLayout(workspaceId).open({ panelId }, { placement })`, then
|
||||
* `navigation.openWorkspace` when the user is somewhere else.
|
||||
*/
|
||||
openPanel(id: string, options: PluginClientOpenPanelOptions): void;
|
||||
/**
|
||||
* Subscribes to a plugin subscription on this client's host. Paseo re-subscribes after a
|
||||
@@ -389,6 +402,10 @@ export interface PluginGlobalCommandContext extends PluginCommandCapabilities {
|
||||
export interface PluginWorkspaceCommandContext extends PluginCommandCapabilities {
|
||||
context: "workspace";
|
||||
workspace: PluginWorkspaceSnapshot;
|
||||
/** The panes and tabs of `workspace`. */
|
||||
workspaceLayout: PluginWorkspaceLayout;
|
||||
// COMPAT(pluginOpenPanel): added in v0.18.2, remove after 2027-05-01
|
||||
/** @deprecated Use `workspaceLayout.open({ panelId }, { placement })`. */
|
||||
openPanel(id: string, options?: PluginOpenPanelOptions): void;
|
||||
}
|
||||
|
||||
@@ -396,6 +413,13 @@ export interface PluginAgentCommandContext extends PluginCommandCapabilities {
|
||||
context: "agent";
|
||||
workspace: PluginWorkspaceSnapshot;
|
||||
agent: PluginAgentSnapshot;
|
||||
/** The panes and tabs of `workspace`. */
|
||||
workspaceLayout: PluginWorkspaceLayout;
|
||||
// COMPAT(pluginOpenPanel): added in v0.18.2, remove after 2027-05-01
|
||||
/**
|
||||
* @deprecated Use `workspaceLayout.open({ panelId }, { placement })`. An agent panel takes
|
||||
* `params: { agentId: agent.id }`.
|
||||
*/
|
||||
openPanel(id: string, options?: PluginOpenPanelOptions): void;
|
||||
}
|
||||
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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,207 @@
|
||||
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. For a workspace that
|
||||
* is not on screen, they do not open or close what is.
|
||||
*
|
||||
* 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.
|
||||
* Paseo releases what is left when the plugin stops.
|
||||
*/
|
||||
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;
|
||||
/** On a phone, the app's one Explorer overlay, whichever workspace is on screen. */
|
||||
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 that pane's space, 0.1 to 0.9. Without it,
|
||||
* the split is sized as one made in the UI.
|
||||
*/
|
||||
| { 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();
|
||||
|
||||
@@ -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`,
|
||||
|
||||
@@ -2318,6 +2318,7 @@ const exampleDaemonVersions: Record<string, string> = {
|
||||
"sidebar-views": "0.16.0",
|
||||
notifications: "0.18.0-beta.1",
|
||||
"tunnel-provider": "0.18.0-beta.1",
|
||||
"workspace-layout": "0.18.2",
|
||||
};
|
||||
|
||||
it.each(examples)("builds and loads the %s plugin example", async (example) => {
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
# Workspace layout plugin example
|
||||
|
||||
Three features that read and arrange a workspace's panes and tabs.
|
||||
|
||||
```bash
|
||||
paseo plugin add /absolute/path/to/paseo/plugin-examples/workspace-layout
|
||||
```
|
||||
|
||||
- `/aside <message>` in an agent's composer starts a child agent and opens its chat as a tab in
|
||||
the Explorer (`client/aside.ts`).
|
||||
- **Review layout** in the Command Center puts the agent's chat on the left and a review panel on
|
||||
the right, with Diff and Findings ready (`client/review.tsx`). The findings are the repository's
|
||||
`TODO` and `FIXME` lines.
|
||||
- **Show outline** in the Command Center opens an Explorer panel with the Markdown headings of the
|
||||
focused file (`client/outline.tsx`).
|
||||
|
||||
`index.server.ts` and `server/files.ts` read the files: the plugin SDK has no file read.
|
||||
@@ -0,0 +1,24 @@
|
||||
import type { PluginClientContext } from "@getpaseo/plugin/client";
|
||||
|
||||
/** `/aside <message>` asks a child agent, whose chat opens as a tab in the Explorer. */
|
||||
export function addAsideCommand(client: PluginClientContext) {
|
||||
client.addSlashCommand({
|
||||
name: "aside",
|
||||
description: "Ask a side question without interrupting this agent",
|
||||
argumentHint: "<message>",
|
||||
context: "agent",
|
||||
async onSubmit({ args, agent, workspace, paseo, workspaceLayout }) {
|
||||
if (!agent.model) throw new Error("This agent has no model to start an aside with");
|
||||
const aside = await paseo.workspaces.ref(workspace.id).agents.create({
|
||||
config: { provider: `${agent.provider}/${agent.model}` },
|
||||
// A child agent: Paseo does not open a main-pane tab for it by itself.
|
||||
parent: agent.id,
|
||||
prompt: args,
|
||||
});
|
||||
workspaceLayout.open(
|
||||
{ panelId: "paseo/agent", params: { agentId: aside.id } },
|
||||
{ placement: { type: "explorer" } },
|
||||
);
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import {
|
||||
type PluginLayoutTab,
|
||||
type PluginWorkspaceLayoutState,
|
||||
type PluginWorkspacePanelProps,
|
||||
useRpc,
|
||||
useWorkspace,
|
||||
useWorkspaceLayout,
|
||||
} from "@getpaseo/plugin/client";
|
||||
import { ScrollView } from "@getpaseo/plugin/client/ui";
|
||||
import { useCallback, useMemo } from "react";
|
||||
import { Pressable, Text } from "react-native";
|
||||
import { outlineRpc, type Heading } from "../shared/files";
|
||||
import { useListStyles } from "./styles";
|
||||
|
||||
/** The file the user is looking at: the focused pane's, or the sheet over the workspace. */
|
||||
function focusedFilePath(state: PluginWorkspaceLayoutState): string | null {
|
||||
const focused: PluginLayoutTab | undefined = state.tabs.find(
|
||||
(tab) => tab.id === state.focusedTabId,
|
||||
);
|
||||
return focused?.panelId === "paseo/file" ? String(focused.params.path) : null;
|
||||
}
|
||||
|
||||
export function OutlinePanel({ workspaceId, theme, layout }: PluginWorkspacePanelProps) {
|
||||
const styles = useListStyles(theme, layout.compact);
|
||||
const workspaceLayout = useWorkspaceLayout(workspaceId);
|
||||
// Re-renders only when the focused file changes.
|
||||
const path = useWorkspaceLayout(workspaceId, focusedFilePath);
|
||||
const cwd = useWorkspace(workspaceId, (workspace) => workspace.directory);
|
||||
const readOutline = useRpc(outlineRpc);
|
||||
const query = useQuery({
|
||||
queryKey: ["outline", cwd, path],
|
||||
queryFn: () => readOutline({ cwd: cwd ?? "", path: path ?? "" }),
|
||||
enabled: Boolean(cwd && path),
|
||||
});
|
||||
// Reveals the open tab, which receives the new line.
|
||||
const openHeading = useCallback(
|
||||
(heading: Heading) => {
|
||||
if (!path) return;
|
||||
workspaceLayout.open({ panelId: "paseo/file", params: { path, lineStart: heading.line } });
|
||||
},
|
||||
[workspaceLayout, path],
|
||||
);
|
||||
return (
|
||||
<ScrollView
|
||||
style={styles.screen}
|
||||
contentContainerStyle={styles.content}
|
||||
testID="workspace-layout-outline"
|
||||
>
|
||||
<Text style={styles.title}>{path ?? "Focus a file to see its outline"}</Text>
|
||||
{query.error ? <Text style={styles.muted}>{query.error.message}</Text> : null}
|
||||
{query.data?.headings.length === 0 ? <Text style={styles.muted}>No headings</Text> : null}
|
||||
{query.data?.headings.map((heading) => (
|
||||
<HeadingRow key={heading.line} heading={heading} styles={styles} onSelect={openHeading} />
|
||||
))}
|
||||
</ScrollView>
|
||||
);
|
||||
}
|
||||
|
||||
function HeadingRow({
|
||||
heading,
|
||||
styles,
|
||||
onSelect,
|
||||
}: {
|
||||
heading: Heading;
|
||||
styles: ReturnType<typeof useListStyles>;
|
||||
onSelect(heading: Heading): void;
|
||||
}) {
|
||||
const textStyle = useMemo(
|
||||
() => [styles.text, { paddingLeft: (heading.level - 1) * 12 }],
|
||||
[styles.text, heading.level],
|
||||
);
|
||||
const press = useCallback(() => onSelect(heading), [onSelect, heading]);
|
||||
return (
|
||||
<Pressable accessibilityRole="button" onPress={press}>
|
||||
<Text style={textStyle}>{heading.title}</Text>
|
||||
</Pressable>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,145 @@
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import {
|
||||
type PluginAgentCommandContext,
|
||||
type PluginAgentPanelProps,
|
||||
type PluginWorkspacePanelProps,
|
||||
useAgent,
|
||||
useRpc,
|
||||
useWorkspace,
|
||||
useWorkspaceLayout,
|
||||
} from "@getpaseo/plugin/client";
|
||||
import { ScrollView } from "@getpaseo/plugin/client/ui";
|
||||
import { useCallback } from "react";
|
||||
import { Pressable, Text } from "react-native";
|
||||
import { findingsRpc, type Finding } from "../shared/files";
|
||||
import { useListStyles } from "./styles";
|
||||
|
||||
/** The agent's chat on the left, the review beside it, with Diff and Findings ready. */
|
||||
export function arrangeReviewLayout({ workspaceLayout, agent }: PluginAgentCommandContext) {
|
||||
const agentTab = workspaceLayout.open({
|
||||
panelId: "paseo/agent",
|
||||
params: { agentId: agent.id },
|
||||
});
|
||||
// `paneId` is null for a tab shown over a phone's workspace. There is then no pane to split or
|
||||
// target, so the placement is left out and the default applies.
|
||||
const review = workspaceLayout.open(
|
||||
{ panelId: "review", params: { agentId: agent.id } },
|
||||
{
|
||||
placement: agentTab.paneId
|
||||
? { type: "split", paneId: agentTab.paneId, side: "right", size: 0.4 }
|
||||
: undefined,
|
||||
},
|
||||
);
|
||||
workspaceLayout.open(
|
||||
{ panelId: "paseo/diff" },
|
||||
{
|
||||
placement: review.paneId ? { type: "pane", paneId: review.paneId } : undefined,
|
||||
intent: "background",
|
||||
},
|
||||
);
|
||||
// Findings only lives in the Explorer, so it needs no placement.
|
||||
workspaceLayout.open({ panelId: "findings" }, { intent: "background" });
|
||||
}
|
||||
|
||||
export function ReviewPanel({ workspaceId, params, theme, layout }: PluginAgentPanelProps) {
|
||||
const workspaceLayout = useWorkspaceLayout(workspaceId);
|
||||
const title = useAgent(params.agentId, (agent) => agent.title);
|
||||
// The file under review opens beside the review.
|
||||
const openBeside = useCallback(
|
||||
(finding: Finding) => {
|
||||
workspaceLayout.open(fileAt(finding), { placement: { type: "beside" } });
|
||||
},
|
||||
[workspaceLayout],
|
||||
);
|
||||
return (
|
||||
<FindingList
|
||||
heading={`Reviewing ${title ?? "agent"}`}
|
||||
workspaceId={workspaceId}
|
||||
theme={theme}
|
||||
compact={layout.compact}
|
||||
onSelect={openBeside}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export function FindingsPanel({ workspaceId, theme, layout }: PluginWorkspacePanelProps) {
|
||||
const workspaceLayout = useWorkspaceLayout(workspaceId);
|
||||
// From the Explorer, the default placement is the pane the user is working in.
|
||||
const open = useCallback(
|
||||
(finding: Finding) => {
|
||||
workspaceLayout.open(fileAt(finding));
|
||||
},
|
||||
[workspaceLayout],
|
||||
);
|
||||
return (
|
||||
<FindingList
|
||||
heading="TODO and FIXME"
|
||||
workspaceId={workspaceId}
|
||||
theme={theme}
|
||||
compact={layout.compact}
|
||||
onSelect={open}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function FindingList({
|
||||
heading,
|
||||
workspaceId,
|
||||
theme,
|
||||
compact,
|
||||
onSelect,
|
||||
}: {
|
||||
heading: string;
|
||||
workspaceId: string;
|
||||
theme: PluginWorkspacePanelProps["theme"];
|
||||
compact: boolean;
|
||||
onSelect(finding: Finding): void;
|
||||
}) {
|
||||
const styles = useListStyles(theme, compact);
|
||||
const cwd = useWorkspace(workspaceId, (workspace) => workspace.directory);
|
||||
const listFindings = useRpc(findingsRpc);
|
||||
const query = useQuery({
|
||||
queryKey: ["findings", cwd],
|
||||
queryFn: () => listFindings({ cwd: cwd ?? "" }),
|
||||
enabled: Boolean(cwd),
|
||||
});
|
||||
return (
|
||||
<ScrollView style={styles.screen} contentContainerStyle={styles.content}>
|
||||
<Text style={styles.title}>{heading}</Text>
|
||||
{query.error ? <Text style={styles.muted}>{query.error.message}</Text> : null}
|
||||
{query.data?.findings.length === 0 ? <Text style={styles.muted}>No findings</Text> : null}
|
||||
{query.data?.findings.map((finding) => (
|
||||
<FindingRow
|
||||
key={`${finding.path}:${finding.line}`}
|
||||
finding={finding}
|
||||
styles={styles}
|
||||
onSelect={onSelect}
|
||||
/>
|
||||
))}
|
||||
</ScrollView>
|
||||
);
|
||||
}
|
||||
|
||||
function FindingRow({
|
||||
finding,
|
||||
styles,
|
||||
onSelect,
|
||||
}: {
|
||||
finding: Finding;
|
||||
styles: ReturnType<typeof useListStyles>;
|
||||
onSelect(finding: Finding): void;
|
||||
}) {
|
||||
const press = useCallback(() => onSelect(finding), [onSelect, finding]);
|
||||
return (
|
||||
<Pressable accessibilityRole="button" onPress={press}>
|
||||
<Text style={styles.text}>{finding.text}</Text>
|
||||
<Text style={styles.muted}>
|
||||
{finding.path}:{finding.line}
|
||||
</Text>
|
||||
</Pressable>
|
||||
);
|
||||
}
|
||||
|
||||
function fileAt(finding: Finding) {
|
||||
return { panelId: "paseo/file", params: { path: finding.path, lineStart: finding.line } };
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
import type { PluginWorkspacePanelProps } from "@getpaseo/plugin/client";
|
||||
import { useMemo } from "react";
|
||||
import { StyleSheet } from "react-native";
|
||||
|
||||
export function useListStyles(theme: PluginWorkspacePanelProps["theme"], compact: boolean) {
|
||||
return useMemo(
|
||||
() =>
|
||||
StyleSheet.create({
|
||||
screen: { flex: 1, backgroundColor: theme.colors.surface0 },
|
||||
content: { padding: compact ? 16 : 24, gap: 12 },
|
||||
title: { color: theme.colors.foreground, fontSize: 16, fontWeight: "600" },
|
||||
text: { color: theme.colors.foreground },
|
||||
muted: { color: theme.colors.foregroundMuted },
|
||||
}),
|
||||
[theme, compact],
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
import type { PluginClientContext } from "@getpaseo/plugin/client";
|
||||
import { addAsideCommand } from "./client/aside";
|
||||
import { OutlinePanel } from "./client/outline";
|
||||
import { arrangeReviewLayout, FindingsPanel, ReviewPanel } from "./client/review";
|
||||
|
||||
export default function contribute(client: PluginClientContext) {
|
||||
addAsideCommand(client);
|
||||
|
||||
client.addAgentPanel({
|
||||
id: "review",
|
||||
title: "Review",
|
||||
icon: "SearchCheck",
|
||||
Component: ReviewPanel,
|
||||
});
|
||||
client.addWorkspacePanel({
|
||||
id: "findings",
|
||||
title: "Findings",
|
||||
icon: "ListTodo",
|
||||
locations: ["explorer"],
|
||||
Component: FindingsPanel,
|
||||
});
|
||||
client.addCommandCenterItem({
|
||||
id: "review-layout",
|
||||
title: "Review layout",
|
||||
icon: "Columns2",
|
||||
context: "agent",
|
||||
onSelect: arrangeReviewLayout,
|
||||
});
|
||||
|
||||
// The Explorer never takes focus, so the outline keeps following the file the user is in.
|
||||
client.addWorkspacePanel({
|
||||
id: "outline",
|
||||
title: "Outline",
|
||||
icon: "ListTree",
|
||||
locations: ["explorer"],
|
||||
Component: OutlinePanel,
|
||||
});
|
||||
client.addCommandCenterItem({
|
||||
id: "show-outline",
|
||||
title: "Show outline",
|
||||
icon: "ListTree",
|
||||
context: "workspace",
|
||||
onSelect({ workspaceLayout }) {
|
||||
workspaceLayout.open({ panelId: "outline" });
|
||||
},
|
||||
});
|
||||
return () => {};
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
import type { PluginServerContext } from "@getpaseo/plugin/server";
|
||||
import { listFindings, readOutline } from "./server/files";
|
||||
import { findingsRpc, outlineRpc } from "./shared/files";
|
||||
|
||||
export default function contribute(server: PluginServerContext) {
|
||||
server.handle(findingsRpc, listFindings);
|
||||
server.handle(outlineRpc, readOutline);
|
||||
return () => {};
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"id": "workspace-layout",
|
||||
"requirements": {
|
||||
"paseo": ">=0.18.2"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
import { readFile } from "node:fs/promises";
|
||||
import { resolve } from "node:path";
|
||||
import type { RpcInput } from "@getpaseo/plugin";
|
||||
import { execCommand } from "@getpaseo/plugin/server";
|
||||
import type { Finding, findingsRpc, Heading, outlineRpc } from "../shared/files";
|
||||
|
||||
const MAX_FINDINGS = 50;
|
||||
|
||||
export async function listFindings({ cwd }: RpcInput<typeof findingsRpc>) {
|
||||
const output = await grep(cwd, "(TODO|FIXME)");
|
||||
const findings: Finding[] = [];
|
||||
// `git grep -z -n` writes `path\0line\0text` for each match.
|
||||
for (const row of output.split("\n").slice(0, MAX_FINDINGS)) {
|
||||
const [path, line, text] = row.split("\0");
|
||||
if (path && line && text !== undefined) {
|
||||
findings.push({ path, line: Number(line), text: text.trim() });
|
||||
}
|
||||
}
|
||||
return { findings };
|
||||
}
|
||||
|
||||
async function grep(cwd: string, pattern: string): Promise<string> {
|
||||
try {
|
||||
const args = ["grep", "--untracked", "-I", "-n", "-z", "-E", pattern];
|
||||
return (await execCommand("git", args, { cwd })).stdout;
|
||||
} catch (error) {
|
||||
// git grep exits with 1 when nothing matches.
|
||||
if ((error as { code?: unknown }).code === 1) return "";
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
export async function readOutline({ cwd, path }: RpcInput<typeof outlineRpc>) {
|
||||
const lines = (await readFile(resolve(cwd, path), "utf8")).split("\n");
|
||||
const headings: Heading[] = [];
|
||||
let fenced = false;
|
||||
lines.forEach((text, index) => {
|
||||
if (text.startsWith("```")) fenced = !fenced;
|
||||
const match = fenced ? null : /^(#{1,6})\s+(.+)/.exec(text);
|
||||
if (match) headings.push({ level: match[1].length, title: match[2].trim(), line: index + 1 });
|
||||
});
|
||||
return { headings };
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
import { defineRpc } from "@getpaseo/plugin";
|
||||
import { z } from "zod";
|
||||
|
||||
export const FindingSchema = z.object({
|
||||
path: z.string(),
|
||||
line: z.number().int().positive(),
|
||||
text: z.string(),
|
||||
});
|
||||
|
||||
export const HeadingSchema = z.object({
|
||||
level: z.number().int().positive(),
|
||||
title: z.string(),
|
||||
line: z.number().int().positive(),
|
||||
});
|
||||
|
||||
export type Finding = z.infer<typeof FindingSchema>;
|
||||
export type Heading = z.infer<typeof HeadingSchema>;
|
||||
|
||||
/** The `TODO` and `FIXME` lines of a repository. */
|
||||
export const findingsRpc = defineRpc({
|
||||
name: "findings.list",
|
||||
input: z.object({ cwd: z.string() }),
|
||||
output: z.object({ findings: z.array(FindingSchema) }),
|
||||
});
|
||||
|
||||
/** The Markdown headings of a file. `path` is relative to `cwd` or absolute. */
|
||||
export const outlineRpc = defineRpc({
|
||||
name: "outline.read",
|
||||
input: z.object({ cwd: z.string(), path: z.string() }),
|
||||
output: z.object({ headings: z.array(HeadingSchema) }),
|
||||
});
|
||||
@@ -219,8 +219,8 @@ client.addCommandCenterItem({
|
||||
title: "Open workspace overview",
|
||||
icon: "PanelsTopLeft",
|
||||
context: "workspace",
|
||||
onSelect({ openPanel }) {
|
||||
openPanel("overview");
|
||||
onSelect({ workspaceLayout }) {
|
||||
workspaceLayout.open({ panelId: "overview" });
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
@@ -174,8 +174,8 @@ client.addCommandCenterItem({
|
||||
title: "Open workspace overview",
|
||||
icon: "PanelsTopLeft",
|
||||
context: "workspace",
|
||||
onSelect({ openPanel }) {
|
||||
openPanel("overview");
|
||||
onSelect({ workspaceLayout }) {
|
||||
workspaceLayout.open({ panelId: "overview" });
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
@@ -224,6 +224,22 @@ The filter drops entries from a turn that started after this one ended, such as
|
||||
|
||||
Plugins built against an older SDK keep receiving `timeline: []` until removal after 2027-05-31.
|
||||
|
||||
### openPanel in v0.18
|
||||
|
||||
`openPanel` is deprecated and keeps working until removal after 2027-05-01. Open panels through the
|
||||
[workspace layout](./reference.md#workspace-layout) handle, and declare `requirements.paseo` as
|
||||
`>=0.18.2` when you do.
|
||||
|
||||
`openPanel` also shows the workspace. The handle only arranges it. From a screen or another place
|
||||
outside the workspace, call `navigation.openWorkspace` after `open`.
|
||||
|
||||
| Previous API | Replacement |
|
||||
| ------------------------------------------------------ | -------------------------------------------------------------------------------------- |
|
||||
| `openPanel("review")`, workspace panel | `workspaceLayout.open({ panelId: "review" })` |
|
||||
| `openPanel("review")`, agent panel | `workspaceLayout.open({ panelId: "review", params: { agentId: agent.id } })` |
|
||||
| `openPanel("review", { location: "explorer" })` | `workspaceLayout.open({ panelId: "review" }, { placement: { type: "explorer" } })` |
|
||||
| `client.openPanel("review", { workspaceId, agentId })` | `client.workspaceLayout(workspaceId).open({ panelId: "review", params: { agentId } })` |
|
||||
|
||||
## 5. Recognize half-migration errors
|
||||
|
||||
| Compiler or load error | Meaning and fix |
|
||||
|
||||
@@ -186,6 +186,20 @@ const items = turn.entries.filter((entry) => entry.turnId === event.turnId).map(
|
||||
|
||||
基于旧版 SDK 构建的插件在 2027-05-31 之后移除兼容层之前仍会收到 `timeline: []`。
|
||||
|
||||
### v0.18 中的 openPanel {#openpanel-in-v018}
|
||||
|
||||
`openPanel` 已弃用,在 2027-05-01 之后移除前仍然可用。请通过[工作区布局](./reference.md#workspace-layout)句柄打开面板,
|
||||
并在这样做时将 `requirements.paseo` 声明为 `>=0.18.2`。
|
||||
|
||||
`openPanel` 还会显示该工作区,而句柄只做编排。在界面或工作区以外的其他位置,请在 `open` 之后调用 `navigation.openWorkspace`。
|
||||
|
||||
| 之前的 API | 替代方式 |
|
||||
| ------------------------------------------------------ | -------------------------------------------------------------------------------------- |
|
||||
| `openPanel("review")`,工作区面板 | `workspaceLayout.open({ panelId: "review" })` |
|
||||
| `openPanel("review")`,Agent 面板 | `workspaceLayout.open({ panelId: "review", params: { agentId: agent.id } })` |
|
||||
| `openPanel("review", { location: "explorer" })` | `workspaceLayout.open({ panelId: "review" }, { placement: { type: "explorer" } })` |
|
||||
| `client.openPanel("review", { workspaceId, agentId })` | `client.workspaceLayout(workspaceId).open({ panelId: "review", params: { agentId } })` |
|
||||
|
||||
## 5. 识别只迁移了一半的错误 {#5-recognize-half-migration-errors}
|
||||
|
||||
| 编译器或加载错误 | 含义与修复方法 |
|
||||
|
||||
@@ -16,7 +16,7 @@ Local plugins are directory sources installed into one Paseo daemon. A plugin ca
|
||||
|
||||
- React Native screens and sidebar header and footer items to Paseo clients;
|
||||
- a [sidebar view](/docs/plugins/sidebar-views) that replaces the sidebar list, and [badges](#workspace-row-badge-items) on workspace rows;
|
||||
- workspace and agent panels opened as workspace tabs;
|
||||
- workspace and agent panels opened as workspace tabs, and the [layout](#workspace-layout) of those tabs;
|
||||
- [file panels](#file-panels) for viewing or editing matching files;
|
||||
- global, workspace, and agent actions in the Command Center;
|
||||
- slash commands, [controls](#composer-items), pills, and searchable external resources in the message composer;
|
||||
@@ -400,7 +400,8 @@ for remote workspaces; `localhost` URLs refer to that desktop.
|
||||
| Target host/workspace is unknown or its workspace list has not loaded | Throws `Workspace is unavailable on the requested host.` before creating a tab |
|
||||
|
||||
Use the [settings API](#settings-screens) for typed host-scoped persistence across clients.
|
||||
Use `openSettings`, `openScreen`, and `openPanel` for your own registered contributions.
|
||||
Use `openSettings` and `openScreen` for your own registered contributions, and the
|
||||
[workspace layout](#workspace-layout) handle to open panels.
|
||||
|
||||
### Server runtime
|
||||
|
||||
@@ -2032,6 +2033,8 @@ Every panel receives `PluginPanelProps<Params>` with `theme`, `host`, `layout`,
|
||||
`workspaceId`, read-only `params`, `revision`, and `tab`. Workspace panels have empty
|
||||
`PluginWorkspacePanelParams`; agent panels have `PluginAgentPanelParams` containing `agentId`.
|
||||
`revision` increments whenever params are re-sent to the same tab, including an identical request.
|
||||
`tab.id` is the tab's ID in the [workspace layout](#workspace-layout). It requires Paseo 0.18.2 or
|
||||
later.
|
||||
|
||||
`tab.setModified(boolean)` marks unsaved work and asks before closing. `tab.state` is opaque
|
||||
persisted JSON, initially `undefined`; `tab.setState(value)` replaces it. Each tab owns its state.
|
||||
@@ -2125,6 +2128,188 @@ later.
|
||||
|
||||
Paseo owns tab focus, splitting, closing, persistence, query state, the API/RPC providers, and the render error boundary. A restored tab whose plugin, panel, context, workspace, or agent is unavailable stays open with an unavailable message instead of crashing the workspace.
|
||||
|
||||
## Workspace layout
|
||||
|
||||
A plugin reads and arranges the panes and tabs of a workspace on this client through a
|
||||
`PluginWorkspaceLayout` handle. Arranging is not navigating: no method changes the screen the user
|
||||
is on. To show the workspace after you arrange it, call `navigation.openWorkspace({ workspaceId })`
|
||||
from a component. Requires Paseo 0.18.2 or later.
|
||||
|
||||
| Where you are | How to get the handle |
|
||||
| ----------------------------------------------------------- | ------------------------------------------------------ |
|
||||
| A component | `useWorkspaceLayout(workspaceId)` |
|
||||
| A workspace or agent command (Command Center or slash) | `workspaceLayout` in the context, bound to `workspace` |
|
||||
| Other client code, such as a header button or composer pill | `client.workspaceLayout(workspaceId)` |
|
||||
|
||||
Each of them returns the same handle for the same workspace.
|
||||
|
||||
This command opens an agent's chat on the left and a review panel on the right:
|
||||
|
||||
```ts
|
||||
client.addCommandCenterItem({
|
||||
id: "review-layout",
|
||||
title: "Review layout",
|
||||
icon: "Columns2",
|
||||
context: "agent",
|
||||
onSelect({ workspaceLayout, agent }) {
|
||||
const chat = workspaceLayout.open({ panelId: "paseo/agent", params: { agentId: agent.id } });
|
||||
workspaceLayout.open(
|
||||
{ panelId: "review", params: { agentId: agent.id } },
|
||||
{
|
||||
// `paneId` is null when a phone shows the chat over the workspace: nothing to split.
|
||||
placement: chat.paneId
|
||||
? { type: "split", paneId: chat.paneId, side: "right", size: 0.4 }
|
||||
: undefined,
|
||||
},
|
||||
);
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
The [workspace layout example](https://github.com/getpaseo/paseo/tree/main/plugin-examples/workspace-layout)
|
||||
has this command, a `/aside` slash command, and an outline panel that follows the focused file.
|
||||
|
||||
### Open and arrange tabs
|
||||
|
||||
| Method | Effect |
|
||||
| ----------------------------------------- | -------------------------------------------------------------------------------------------------------- |
|
||||
| `open(target, options?)` | Opens a registered panel and returns `{ tabId, paneId }`. |
|
||||
| `focus(tabId)` | Shows and focuses an open tab. |
|
||||
| `close(tabId)` | Does what the tab's close button does. |
|
||||
| `move(tabId, placement)` | Moves an open tab and returns `{ tabId, paneId }`. A move into a hidden Explorer leaves it hidden. |
|
||||
| `closePane(paneId)` | Closes a main pane and its tabs, or hides the Explorer. It does nothing when only one main pane is left. |
|
||||
| `explorer.show()`, `.hide()`, `.toggle()` | Shows or hides the Explorer. |
|
||||
|
||||
`close` and `closePane` ask the same questions as the close buttons and have the same effects.
|
||||
For example, closing a terminal tab kills the terminal. `focus`, `close`, and `closePane` do nothing
|
||||
when no tab or pane has the id.
|
||||
|
||||
A `target` is `{ panelId, params? }`. By default, `open` reveals: if a tab of the same panel and
|
||||
identity is open, Paseo focuses it where it is and sends it the params again with a new `revision`.
|
||||
`placement` only decides where a tab that is not open yet goes. To move an open tab, call `move`.
|
||||
|
||||
| `placement` | Where the tab goes |
|
||||
| ---------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `{ type: "focused" }` | The default: the focused pane, or the panel's first location if it is not allowed there. |
|
||||
| `{ type: "pane", paneId }` | That pane. |
|
||||
| `{ type: "beside" }` | The side pane. Paseo creates it on first use. |
|
||||
| `{ type: "split", paneId, side, size? }` | A new pane on the `left`, `right`, `top`, or `bottom` of `paneId`. `size` is its share of the space `paneId` had, 0.1 to 0.9. Without `size`, the split is sized as one made in the UI. |
|
||||
| `{ type: "explorer" }` | The Explorer. |
|
||||
|
||||
| `intent` | Effect |
|
||||
| -------------- | ----------------------------------------------------------------------------------------- |
|
||||
| `"reveal"` | The default. Reuses an open tab, shows it, and focuses it. |
|
||||
| `"background"` | Reuses or adds a tab without taking focus. |
|
||||
| `"new"` | Adds a tab. For agents, terminals, browsers, Changes, and Files it behaves as `"reveal"`. |
|
||||
|
||||
`open` throws when the panel is not registered, the panel rejects the params, the panel does not
|
||||
allow the placement, the pane does not exist, or the pane cannot be split any further. `move` throws
|
||||
for the same placement errors and for a tab that is not open. Your own panels are registered after
|
||||
the entry function returns, so call `open` from a callback or a component.
|
||||
|
||||
Every method that changes the layout throws `PluginWorkspaceUnavailableError` when this client does
|
||||
not know the workspace on the plugin's host. That includes the time before the host's workspaces
|
||||
have loaded.
|
||||
|
||||
### Panel IDs
|
||||
|
||||
A panel ID is `<pluginId>/<panelId>`. A bare ID means your own panel. Reads always return the
|
||||
qualified form. A workspace panel takes no params, and an agent panel takes `{ agentId }`.
|
||||
|
||||
Paseo's own panels use the `paseo` namespace:
|
||||
|
||||
| Panel ID | Shows | Params | Locations |
|
||||
| -------------------- | ---------------------------- | -------------------------------- | ------------------- |
|
||||
| `paseo/agent` | An agent's chat | `{ agentId }` | workspace, explorer |
|
||||
| `paseo/subagent` | A provider's subagent | `{ parentAgentId, subagentId }` | workspace, explorer |
|
||||
| `paseo/terminal` | A terminal | `{ terminalId }` | workspace, explorer |
|
||||
| `paseo/browser` | A browser tab | `{ browserId }` | workspace |
|
||||
| `paseo/file` | A file | `{ path, lineStart?, lineEnd? }` | workspace, explorer |
|
||||
| `paseo/diff` | The working diff | none | workspace, explorer |
|
||||
| `paseo/commit-diff` | The diff of one commit | `{ sha }` | workspace, explorer |
|
||||
| `paseo/pull-request` | The workspace's pull request | none | workspace, explorer |
|
||||
| `paseo/changes` | The Changes tree | none | explorer |
|
||||
| `paseo/files` | The file tree | `{ reveal? }` | explorer |
|
||||
|
||||
- `path` is relative to the workspace directory, or absolute. `lineEnd` needs `lineStart` and must
|
||||
not be smaller than it.
|
||||
- `reveal` is a path inside the workspace to expand and select. It is relative and has no `..`.
|
||||
Reads do not return it.
|
||||
- `paseo/new_tab`, `paseo/draft`, and `paseo/setup` appear in reads. `open` cannot open them.
|
||||
|
||||
### Read the layout
|
||||
|
||||
`get()` returns the current state:
|
||||
|
||||
| Field | Meaning |
|
||||
| --------------- | ---------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `panes` | Visible panes in reading order: `{ id, kind, tabIds, activeTabId }`. `kind` is `main` or `explorer`. The Explorer is listed while shown. |
|
||||
| `tabs` | Every open tab, including tabs of a hidden Explorer: `{ id, paneId, panelId, params, locations, title, modified }`. |
|
||||
| `focusedPaneId` | The focused main pane. The Explorer never takes focus; read its `activeTabId` for what it shows. |
|
||||
| `focusedTabId` | The active tab of the focused pane, or the tab shown over the workspace on a phone. |
|
||||
| `explorer` | `{ visible }`. |
|
||||
|
||||
For a workspace this client does not know, `get()` returns empty lists, `null` IDs, and a hidden
|
||||
Explorer. `get()` returns the same object until the layout changes. `subscribe(listener)` calls
|
||||
`listener({ type: "changed" })` after it changes and returns the unsubscribe function. Paseo
|
||||
releases the subscriptions that are left when the plugin stops.
|
||||
|
||||
In a component, pass `useWorkspaceLayout` a selector. The component re-renders when the selection
|
||||
changes, compared shallowly:
|
||||
|
||||
```tsx
|
||||
const path = useWorkspaceLayout(workspaceId, (state) => {
|
||||
const focused = state.tabs.find((tab) => tab.id === state.focusedTabId);
|
||||
return focused?.panelId === "paseo/file" ? String(focused.params.path) : null;
|
||||
});
|
||||
```
|
||||
|
||||
A panel finds its own tab with `tab.id`, for example `workspaceLayout.close(tab.id)`.
|
||||
|
||||
### Phones and touch tablets
|
||||
|
||||
Phones and touch tablets show one main pane, so `pane`, `beside`, and `split` mean that pane. The
|
||||
same code works on every layout without a check.
|
||||
|
||||
On a phone:
|
||||
|
||||
- A file, a subagent, or a child agent's chat opened into the main pane shows over the workspace.
|
||||
Its `paneId` is `null`.
|
||||
- The Explorer covers the screen. The app has one Explorer overlay and one agent list, over
|
||||
whichever workspace is on screen.
|
||||
|
||||
For a workspace that is not on screen, layout commands change that workspace's layout and do not
|
||||
open or close what is on screen. Tabs are still selected inside it. `close` and `closePane` still
|
||||
ask the user first, as in the UI.
|
||||
|
||||
- After `navigation.openWorkspace` on a phone, the Explorer is closed, and the tab you opened is
|
||||
selected inside it. Call `explorer.show()` once the workspace is on screen, for example from a
|
||||
command the user runs there.
|
||||
- On a phone, `get().explorer.visible` reports the app's one overlay, whichever workspace is on
|
||||
screen.
|
||||
|
||||
### Arrange what you create
|
||||
|
||||
Create everything first. Then arrange it with no `await` between the layout calls, so the user
|
||||
cannot change the layout halfway.
|
||||
|
||||
```ts
|
||||
async onSelect({ paseo, workspace, workspaceLayout }) {
|
||||
const ref = paseo.workspaces.ref(workspace.id);
|
||||
const [agent, terminal] = await Promise.all([
|
||||
ref.agents.create({ config: { provider: "codex/gpt-5.5" }, prompt: "Run the tests" }),
|
||||
ref.terminals.create({ name: "tests" }),
|
||||
]);
|
||||
workspaceLayout.open({ panelId: "paseo/agent", params: { agentId: agent.id } });
|
||||
const tests = workspaceLayout.open({ panelId: "paseo/terminal", params: { terminalId: terminal.id } });
|
||||
workspaceLayout.move(tests.tabId, { type: "beside" });
|
||||
},
|
||||
```
|
||||
|
||||
Paseo adds a tab by itself for a new terminal and for a new agent that has no parent. That can
|
||||
happen before your `open` runs, and `open` leaves an open tab where it is. Call `move` to put such a
|
||||
tab in its place. A child agent, created with `parent`, gets no tab by itself.
|
||||
|
||||
## File panels
|
||||
|
||||
Register a component that renders a file as the body of its file tab. Your component receives a
|
||||
@@ -2334,10 +2519,10 @@ client.addCommandCenterItem({
|
||||
icon: "Scan",
|
||||
keywords: ["inspect"],
|
||||
context: "agent",
|
||||
async onSelect({ paseo, rpc, workspace, agent, openPanel }) {
|
||||
async onSelect({ paseo, rpc, workspace, agent, workspaceLayout }) {
|
||||
await paseo.workspaces.ref(workspace.id).setTitle(`Review ${agent.id}`);
|
||||
await rpc(refreshReview, { agentId: agent.id });
|
||||
openPanel("review");
|
||||
workspaceLayout.open({ panelId: "review", params: { agentId: agent.id } });
|
||||
},
|
||||
});
|
||||
```
|
||||
@@ -2357,17 +2542,21 @@ Global items appear on the installation's selected host. Workspace items appear
|
||||
|
||||
Every callback receives:
|
||||
|
||||
| Field | Context | Meaning |
|
||||
| ------------------------- | ------------------- | --------------------------------------------------------------------------------------------------------------- |
|
||||
| `context` | All | Matching discriminator. |
|
||||
| `paseo` | All | Selected host's existing `PaseoApi`. |
|
||||
| `rpc(contract, input)` | All | Typed call to this installation's daemon-side plugin handler. |
|
||||
| `openScreen(input)` | All | Opens one of this plugin's registered screens: `{ screenId, params? }`. |
|
||||
| `workspace` | Workspace and agent | Synchronous workspace snapshot. |
|
||||
| `agent` | Agent | Synchronous matching agent snapshot. |
|
||||
| `openPanel(id, options?)` | Workspace and agent | Opens a registered panel in the callback's current context. Pass `{ location: "explorer" }` to target Explorer. |
|
||||
| Field | Context | Meaning |
|
||||
| ---------------------- | ------------------- | --------------------------------------------------------------------------------------- |
|
||||
| `context` | All | Matching discriminator. |
|
||||
| `paseo` | All | Selected host's existing `PaseoApi`. |
|
||||
| `rpc(contract, input)` | All | Typed call to this installation's daemon-side plugin handler. |
|
||||
| `openScreen(input)` | All | Opens one of this plugin's registered screens: `{ screenId, params? }`. |
|
||||
| `workspace` | Workspace and agent | Synchronous workspace snapshot. |
|
||||
| `agent` | Agent | Synchronous matching agent snapshot. |
|
||||
| `workspaceLayout` | Workspace and agent | The [panes and tabs](#workspace-layout) of `workspace`. Requires Paseo 0.18.2 or later. |
|
||||
|
||||
An agent callback may open either an agent panel or a workspace panel. A workspace callback may open only a workspace panel. Unknown screen and panel IDs fail visibly. Use `paseo` for normal workspace, agent, provider, and daemon-config operations. Use `rpc` for plugin-specific filesystem, credential, vendor, or daemon-local work.
|
||||
Unknown screen and panel IDs fail visibly. Use `paseo` for normal workspace, agent, provider, and daemon-config operations. Use `rpc` for plugin-specific filesystem, credential, vendor, or daemon-local work.
|
||||
|
||||
**Deprecated until removal after 2027-05-01:** `openPanel(id, options?)`, on the command contexts and
|
||||
on `client`, continues to work. Open the panel through the [workspace layout](#workspace-layout) as
|
||||
the [migration guide](/docs/plugins/migration#openpanel-in-v018) shows.
|
||||
|
||||
## Slash commands
|
||||
|
||||
@@ -2380,9 +2569,9 @@ client.addSlashCommand({
|
||||
description: "Run the review bot",
|
||||
argumentHint: "[scope]",
|
||||
context: "agent",
|
||||
async onSubmit({ args, agent, rpc, openPanel }) {
|
||||
async onSubmit({ args, agent, rpc, workspaceLayout }) {
|
||||
await rpc(refreshReview, { agentId: agent.id, scope: args });
|
||||
openPanel("review");
|
||||
workspaceLayout.open({ panelId: "review", params: { agentId: agent.id } });
|
||||
},
|
||||
});
|
||||
```
|
||||
@@ -2424,7 +2613,7 @@ const review = client.addHeaderButton({
|
||||
behavior: {
|
||||
kind: "action",
|
||||
onPress() {
|
||||
client.openPanel("review", { workspaceId });
|
||||
client.workspaceLayout(workspaceId).open({ panelId: "review" });
|
||||
},
|
||||
},
|
||||
},
|
||||
@@ -2723,7 +2912,7 @@ const pill = client.addComposerPill({
|
||||
behavior: {
|
||||
kind: "action",
|
||||
onPress() {
|
||||
client.openPanel("review", { workspaceId, agentId });
|
||||
client.workspaceLayout(workspaceId).open({ panelId: "review", params: { agentId } });
|
||||
},
|
||||
},
|
||||
},
|
||||
|
||||
@@ -14,7 +14,7 @@ nav: 参考
|
||||
|
||||
- 为 Paseo 客户端添加 React Native 界面,以及侧边栏顶部和底部项;
|
||||
- 替换侧边栏列表的[侧边栏视图](/docs/plugins/sidebar-views),以及工作区行上的[徽标](#workspace-row-badge-items);
|
||||
- 作为工作区标签页打开的工作区面板和 Agent 面板;
|
||||
- 作为工作区标签页打开的工作区面板和 Agent 面板,以及这些标签页的[布局](#workspace-layout);
|
||||
- 用于查看或编辑匹配文件的[文件面板](#file-panels);
|
||||
- Command Center 中的全局、工作区和 Agent 操作;
|
||||
- 消息 Composer 中的斜杠命令、[控件](#composer-items)、胶囊和可搜索的外部资源;
|
||||
@@ -349,7 +349,7 @@ openBrowser({ url, workspaceId: remoteWorkspaceId, serverId: remoteServerId });
|
||||
| 应用内浏览器的工作区 ID 为空 | 在创建标签页之前抛出 `workspaceId is required.` |
|
||||
| 目标主机/工作区未知,或其工作区列表尚未加载 | 在创建标签页之前抛出 `Workspace is unavailable on the requested host.` |
|
||||
|
||||
跨客户端的、带类型的主机范围持久化请使用[设置 API](#settings-screens)。打开你自己注册的贡献请使用 `openSettings`、`openScreen` 和 `openPanel`。
|
||||
跨客户端的、带类型的主机范围持久化请使用[设置 API](#settings-screens)。打开你自己注册的贡献请使用 `openSettings` 和 `openScreen`,打开面板请使用[工作区布局](#workspace-layout)句柄。
|
||||
|
||||
### 服务端运行时 {#server-runtime}
|
||||
|
||||
@@ -1663,6 +1663,7 @@ export default function contribute(client: PluginClientContext) {
|
||||
`workspaceId`、只读的 `params`、`revision` 和 `tab`。工作区面板使用空的
|
||||
`PluginWorkspacePanelParams`;Agent 面板的 `PluginAgentPanelParams` 包含 `agentId`。
|
||||
每次向同一标签页重新发送 params 时,`revision` 都会递增,即使请求与上次相同。
|
||||
`tab.id` 是该标签页在[工作区布局](#workspace-layout)中的 ID。它需要 Paseo 0.18.2 或更高版本。
|
||||
|
||||
`tab.setModified(boolean)` 标记未保存的更改,并在关闭前询问。`tab.state` 是由面板定义的持久化
|
||||
JSON,初始为 `undefined`;`tab.setState(value)` 替换整个值。每个标签页拥有独立状态。
|
||||
@@ -1748,6 +1749,172 @@ if (busy === null) return null; // Agent 不可用。
|
||||
|
||||
标签页的焦点、拆分、关闭、持久化、查询状态、API/RPC Provider 以及渲染错误边界都由 Paseo 负责。如果恢复的标签页所对应的插件、面板、上下文、工作区或 Agent 不可用,该标签页会保持打开并显示“不可用”消息,而不会让工作区崩溃。
|
||||
|
||||
## 工作区布局 {#workspace-layout}
|
||||
|
||||
插件通过 `PluginWorkspaceLayout` 句柄读取并编排本客户端上某个工作区的窗格和标签页。编排不等于导航:
|
||||
任何方法都不会改变用户所在的屏幕。要在编排之后显示该工作区,请在组件中调用
|
||||
`navigation.openWorkspace({ workspaceId })`。需要 Paseo 0.18.2 或更高版本。
|
||||
|
||||
| 你所在的位置 | 如何获得句柄 |
|
||||
| ---------------------------------------------- | -------------------------------------------------- |
|
||||
| 组件 | `useWorkspaceLayout(workspaceId)` |
|
||||
| 工作区或 Agent 命令(Command Center 或斜杠) | 上下文中的 `workspaceLayout`,已绑定到 `workspace` |
|
||||
| 其他客户端代码,例如标题栏按钮或 Composer 标签 | `client.workspaceLayout(workspaceId)` |
|
||||
|
||||
对同一个工作区,它们返回同一个句柄。
|
||||
|
||||
这个命令把 Agent 的聊天打开在左侧,把审查面板打开在右侧:
|
||||
|
||||
```ts
|
||||
client.addCommandCenterItem({
|
||||
id: "review-layout",
|
||||
title: "Review layout",
|
||||
icon: "Columns2",
|
||||
context: "agent",
|
||||
onSelect({ workspaceLayout, agent }) {
|
||||
const chat = workspaceLayout.open({ panelId: "paseo/agent", params: { agentId: agent.id } });
|
||||
workspaceLayout.open(
|
||||
{ panelId: "review", params: { agentId: agent.id } },
|
||||
{
|
||||
// 手机把聊天显示在工作区上方时,`paneId` 为 null,此时没有可分屏的窗格。
|
||||
placement: chat.paneId
|
||||
? { type: "split", paneId: chat.paneId, side: "right", size: 0.4 }
|
||||
: undefined,
|
||||
},
|
||||
);
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
[工作区布局示例](https://github.com/getpaseo/paseo/tree/main/plugin-examples/workspace-layout)
|
||||
包含这个命令、一个 `/aside` 斜杠命令,以及一个跟随当前焦点文件的大纲面板。
|
||||
|
||||
### 打开和编排标签页 {#open-and-arrange-tabs}
|
||||
|
||||
| 方法 | 效果 |
|
||||
| ----------------------------------------- | ---------------------------------------------------------------------------------------- |
|
||||
| `open(target, options?)` | 打开一个已注册的面板,并返回 `{ tabId, paneId }`。 |
|
||||
| `focus(tabId)` | 显示并聚焦一个已打开的标签页。 |
|
||||
| `close(tabId)` | 执行该标签页关闭按钮的操作。 |
|
||||
| `move(tabId, placement)` | 移动一个已打开的标签页,并返回 `{ tabId, paneId }`。移入隐藏的 Explorer 后它仍保持隐藏。 |
|
||||
| `closePane(paneId)` | 关闭一个主窗格及其标签页,或隐藏 Explorer。只剩一个主窗格时不做任何事。 |
|
||||
| `explorer.show()`、`.hide()`、`.toggle()` | 显示或隐藏 Explorer。 |
|
||||
|
||||
`close` 和 `closePane` 会询问与关闭按钮相同的问题,并产生相同的效果。例如,关闭终端标签页会终止该终端。
|
||||
当没有标签页或窗格使用该 ID 时,`focus`、`close` 和 `closePane` 不做任何事。
|
||||
|
||||
`target` 是 `{ panelId, params? }`。默认情况下 `open` 执行显示(reveal):如果同一面板、同一标识的标签页已经打开,
|
||||
Paseo 就在原处聚焦它,并以新的 `revision` 重新把 params 发给它。`placement` 只决定尚未打开的标签页放在哪里。
|
||||
要移动已打开的标签页,请调用 `move`。
|
||||
|
||||
| `placement` | 标签页放在哪里 |
|
||||
| ---------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `{ type: "focused" }` | 默认值:获得焦点的窗格;如果面板不允许放在那里,则放到面板的第一个位置。 |
|
||||
| `{ type: "pane", paneId }` | 指定的窗格。 |
|
||||
| `{ type: "beside" }` | 侧边窗格。Paseo 在首次使用时创建它。 |
|
||||
| `{ type: "split", paneId, side, size? }` | 在 `paneId` 的 `left`、`right`、`top` 或 `bottom` 新建窗格。`size` 是它在 `paneId` 原有空间中占的比例,0.1 到 0.9。省略 `size` 时,大小与在界面中分屏相同。 |
|
||||
| `{ type: "explorer" }` | Explorer。 |
|
||||
|
||||
| `intent` | 效果 |
|
||||
| -------------- | ------------------------------------------------------------------------------------ |
|
||||
| `"reveal"` | 默认值。复用已打开的标签页,显示并聚焦它。 |
|
||||
| `"background"` | 复用或新增标签页,不抢占焦点。 |
|
||||
| `"new"` | 新增一个标签页。对 Agent、终端、浏览器、Changes 和 Files,其行为与 `"reveal"` 相同。 |
|
||||
|
||||
当面板未注册、面板拒绝 params、面板不允许该位置、窗格不存在,或窗格无法继续拆分时,`open` 会抛出错误。
|
||||
对于相同的位置错误以及未打开的标签页,`move` 会抛出错误。你自己的面板在入口函数返回之后才完成注册,
|
||||
因此请在回调或组件中调用 `open`。
|
||||
|
||||
当本客户端在插件所在主机上不认识该工作区时,所有会改变布局的方法都会抛出
|
||||
`PluginWorkspaceUnavailableError`,包括该主机的工作区尚未加载完成的时候。
|
||||
|
||||
### 面板 ID {#panel-ids}
|
||||
|
||||
面板 ID 是 `<pluginId>/<panelId>`。不带前缀的 ID 表示你自己的面板。读取时总是返回完整形式。工作区面板不接受 params,
|
||||
Agent 面板接受 `{ agentId }`。
|
||||
|
||||
Paseo 自带的面板使用 `paseo` 命名空间:
|
||||
|
||||
| 面板 ID | 显示内容 | Params | 位置 |
|
||||
| -------------------- | -------------------- | -------------------------------- | ------------------- |
|
||||
| `paseo/agent` | Agent 的聊天 | `{ agentId }` | workspace、explorer |
|
||||
| `paseo/subagent` | Provider 的 subagent | `{ parentAgentId, subagentId }` | workspace、explorer |
|
||||
| `paseo/terminal` | 终端 | `{ terminalId }` | workspace、explorer |
|
||||
| `paseo/browser` | 浏览器标签页 | `{ browserId }` | workspace |
|
||||
| `paseo/file` | 文件 | `{ path, lineStart?, lineEnd? }` | workspace、explorer |
|
||||
| `paseo/diff` | 工作区 diff | 无 | workspace、explorer |
|
||||
| `paseo/commit-diff` | 单个提交的 diff | `{ sha }` | workspace、explorer |
|
||||
| `paseo/pull-request` | 工作区的 PR | 无 | workspace、explorer |
|
||||
| `paseo/changes` | Changes 树 | 无 | explorer |
|
||||
| `paseo/files` | 文件树 | `{ reveal? }` | explorer |
|
||||
|
||||
- `path` 相对于工作区目录,或者是绝对路径。`lineEnd` 需要同时提供 `lineStart`,且不能小于它。
|
||||
- `reveal` 是工作区内要展开并选中的路径。它是相对路径,且不含 `..`。读取时不会返回它。
|
||||
- `paseo/new_tab`、`paseo/draft` 和 `paseo/setup` 会出现在读取结果中。`open` 无法打开它们。
|
||||
|
||||
### 读取布局 {#read-the-layout}
|
||||
|
||||
`get()` 返回当前状态:
|
||||
|
||||
| 字段 | 含义 |
|
||||
| --------------- | ------------------------------------------------------------------------------------------------------------------------ |
|
||||
| `panes` | 按阅读顺序排列的可见窗格:`{ id, kind, tabIds, activeTabId }`。`kind` 是 `main` 或 `explorer`。Explorer 仅在显示时列出。 |
|
||||
| `tabs` | 所有已打开的标签页,包括隐藏 Explorer 中的标签页:`{ id, paneId, panelId, params, locations, title, modified }`。 |
|
||||
| `focusedPaneId` | 获得焦点的主窗格。Explorer 从不获得焦点;要了解它显示的内容,请读取它的 `activeTabId`。 |
|
||||
| `focusedTabId` | 焦点窗格的当前标签页,或手机上覆盖在工作区之上显示的标签页。 |
|
||||
| `explorer` | `{ visible }`。 |
|
||||
|
||||
对于本客户端不认识的工作区,`get()` 返回空列表、`null` ID 和隐藏的 Explorer。在布局发生变化之前,`get()` 返回同一个对象。
|
||||
`subscribe(listener)` 在布局变化后调用 `listener({ type: "changed" })`,并返回取消订阅函数。插件停止时,Paseo
|
||||
会释放尚存的订阅。
|
||||
|
||||
在组件中,给 `useWorkspaceLayout` 传一个选择器。当选中的内容变化时(浅比较),组件重新渲染:
|
||||
|
||||
```tsx
|
||||
const path = useWorkspaceLayout(workspaceId, (state) => {
|
||||
const focused = state.tabs.find((tab) => tab.id === state.focusedTabId);
|
||||
return focused?.panelId === "paseo/file" ? String(focused.params.path) : null;
|
||||
});
|
||||
```
|
||||
|
||||
面板通过 `tab.id` 找到自己的标签页,例如 `workspaceLayout.close(tab.id)`。
|
||||
|
||||
### 手机和触屏平板 {#phones-and-touch-tablets}
|
||||
|
||||
手机和触屏平板只显示一个主窗格,因此 `pane`、`beside` 和 `split` 都指这个窗格。同一份代码无需判断即可在所有布局上运行。
|
||||
|
||||
在手机上:
|
||||
|
||||
- 打开到主窗格的文件、subagent 或子 Agent 聊天会覆盖在工作区之上显示。它的 `paneId` 是 `null`。
|
||||
- Explorer 覆盖整个屏幕。整个应用只有一个 Explorer 浮层和一个 Agent 列表,它们覆盖在屏幕上的那个工作区之上。
|
||||
|
||||
对不在屏幕上的工作区,布局命令只改变该工作区的布局,不会打开或关闭屏幕上的任何内容。标签页仍会在该工作区内被选中。`close`
|
||||
和 `closePane` 仍会像 UI 一样先询问用户。
|
||||
|
||||
- 在手机上调用 `navigation.openWorkspace` 之后,Explorer 处于关闭状态,你打开的标签页已在其中被选中。请在工作区显示到屏幕上之后再调用
|
||||
`explorer.show()`,例如在用户于该工作区运行的命令中调用。
|
||||
- 在手机上,`get().explorer.visible` 反映的是整个应用唯一的浮层,与屏幕上是哪个工作区无关。
|
||||
|
||||
### 编排你创建的内容 {#arrange-what-you-create}
|
||||
|
||||
先创建全部内容。然后在布局调用之间不插入任何 `await` 地进行编排,这样用户无法在中途改变布局。
|
||||
|
||||
```ts
|
||||
async onSelect({ paseo, workspace, workspaceLayout }) {
|
||||
const ref = paseo.workspaces.ref(workspace.id);
|
||||
const [agent, terminal] = await Promise.all([
|
||||
ref.agents.create({ config: { provider: "codex/gpt-5.5" }, prompt: "Run the tests" }),
|
||||
ref.terminals.create({ name: "tests" }),
|
||||
]);
|
||||
workspaceLayout.open({ panelId: "paseo/agent", params: { agentId: agent.id } });
|
||||
const tests = workspaceLayout.open({ panelId: "paseo/terminal", params: { terminalId: terminal.id } });
|
||||
workspaceLayout.move(tests.tabId, { type: "beside" });
|
||||
},
|
||||
```
|
||||
|
||||
对于新终端和没有父级的新 Agent,Paseo 会自行添加标签页。这可能发生在你的 `open` 运行之前,而 `open` 会让已打开的标签页留在原处。
|
||||
要把这样的标签页放到指定位置,请调用 `move`。用 `parent` 创建的子 Agent 不会自动获得标签页。
|
||||
|
||||
## 文件面板 {#file-panels}
|
||||
|
||||
注册一个组件,把文件渲染为文件标签页的主体。组件会收到所选主机上该文件的句柄,远程主机也一样。由组件读取文件、显示自己的加载状态,并在用户编辑时写回文件。面板报告有未保存更改时,标签页会显示一个圆点。
|
||||
@@ -1902,10 +2069,10 @@ client.addCommandCenterItem({
|
||||
icon: "Scan",
|
||||
keywords: ["inspect"],
|
||||
context: "agent",
|
||||
async onSelect({ paseo, rpc, workspace, agent, openPanel }) {
|
||||
async onSelect({ paseo, rpc, workspace, agent, workspaceLayout }) {
|
||||
await paseo.workspaces.ref(workspace.id).setTitle(`Review ${agent.id}`);
|
||||
await rpc(refreshReview, { agentId: agent.id });
|
||||
openPanel("review");
|
||||
workspaceLayout.open({ panelId: "review", params: { agentId: agent.id } });
|
||||
},
|
||||
});
|
||||
```
|
||||
@@ -1925,17 +2092,20 @@ client.addCommandCenterItem({
|
||||
|
||||
每个回调都会收到:
|
||||
|
||||
| 字段 | 上下文 | 含义 |
|
||||
| ------------------------- | -------------- | ----------------------------------------------------------------------------------------------- |
|
||||
| `context` | 全部 | 对应的判别字段。 |
|
||||
| `paseo` | 全部 | 所选主机现有的 `PaseoApi`。 |
|
||||
| `rpc(contract, input)` | 全部 | 对此安装的 daemon 端插件处理函数的带类型调用。 |
|
||||
| `openScreen(input)` | 全部 | 打开此插件注册的某个界面:`{ screenId, params? }`。 |
|
||||
| `workspace` | 工作区和 Agent | 同步的工作区快照。 |
|
||||
| `agent` | Agent | 同步的、与之匹配的 Agent 快照。 |
|
||||
| `openPanel(id, options?)` | 工作区和 Agent | 在回调当前的上下文中打开一个已注册的面板。传入 `{ location: "explorer" }` 可以打开到 Explorer。 |
|
||||
| 字段 | 上下文 | 含义 |
|
||||
| ---------------------- | -------------- | ------------------------------------------------------------------------------- |
|
||||
| `context` | 全部 | 对应的判别字段。 |
|
||||
| `paseo` | 全部 | 所选主机现有的 `PaseoApi`。 |
|
||||
| `rpc(contract, input)` | 全部 | 对此安装的 daemon 端插件处理函数的带类型调用。 |
|
||||
| `openScreen(input)` | 全部 | 打开此插件注册的某个界面:`{ screenId, params? }`。 |
|
||||
| `workspace` | 工作区和 Agent | 同步的工作区快照。 |
|
||||
| `agent` | Agent | 同步的、与之匹配的 Agent 快照。 |
|
||||
| `workspaceLayout` | 工作区和 Agent | `workspace` 的[窗格和标签页](#workspace-layout)。需要 Paseo 0.18.2 或更高版本。 |
|
||||
|
||||
Agent 回调可以打开 Agent 面板或工作区面板。工作区回调只能打开工作区面板。未知的界面和面板 ID 会明确报错。普通的工作区、Agent、Provider 和 daemon 配置操作请使用 `paseo`。插件特有的文件系统、凭据、厂商或 daemon 本地工作请使用 `rpc`。
|
||||
未知的界面和面板 ID 会明确报错。普通的工作区、Agent、Provider 和 daemon 配置操作请使用 `paseo`。插件特有的文件系统、凭据、厂商或 daemon 本地工作请使用 `rpc`。
|
||||
|
||||
**已弃用,2027-05-01 之后移除:** 命令上下文和 `client` 上的 `openPanel(id, options?)` 仍然可用。请按照
|
||||
[迁移指南](/docs/plugins/migration#openpanel-in-v018)通过[工作区布局](#workspace-layout)打开面板。
|
||||
|
||||
## 斜杠命令 {#slash-commands}
|
||||
|
||||
@@ -1948,9 +2118,9 @@ client.addSlashCommand({
|
||||
description: "Run the review bot",
|
||||
argumentHint: "[scope]",
|
||||
context: "agent",
|
||||
async onSubmit({ args, agent, rpc, openPanel }) {
|
||||
async onSubmit({ args, agent, rpc, workspaceLayout }) {
|
||||
await rpc(refreshReview, { agentId: agent.id, scope: args });
|
||||
openPanel("review");
|
||||
workspaceLayout.open({ panelId: "review", params: { agentId: agent.id } });
|
||||
},
|
||||
});
|
||||
```
|
||||
@@ -1990,7 +2160,7 @@ const review = client.addHeaderButton({
|
||||
behavior: {
|
||||
kind: "action",
|
||||
onPress() {
|
||||
client.openPanel("review", { workspaceId });
|
||||
client.workspaceLayout(workspaceId).open({ panelId: "review" });
|
||||
},
|
||||
},
|
||||
},
|
||||
@@ -2219,7 +2389,7 @@ const pill = client.addComposerPill({
|
||||
behavior: {
|
||||
kind: "action",
|
||||
onPress() {
|
||||
client.openPanel("review", { workspaceId, agentId });
|
||||
client.workspaceLayout(workspaceId).open({ panelId: "review", params: { agentId } });
|
||||
},
|
||||
},
|
||||
},
|
||||
|
||||
@@ -62,7 +62,7 @@ Register these on `client` in `index.client.tsx`. Each returns a remover. `addHe
|
||||
|
||||
Examples live in [`plugin-examples/`](https://github.com/getpaseo/paseo/tree/main/plugin-examples).
|
||||
|
||||
The client context also has `paseo`, `rpc`, `subscribe`, `openScreen`, `openPanel`, `openSettings`, `composers`, `playAudio`, and `i18n`. Import hooks such as `usePaseo`, `useRpc`, `useSubscription`, `useSettings`, `useWorkspace`, `useAgent`, and `useTabState` from `@getpaseo/plugin/client`.
|
||||
The client context also has `paseo`, `rpc`, `subscribe`, `openScreen`, `workspaceLayout`, `openSettings`, `composers`, `playAudio`, and `i18n`. Import hooks such as `usePaseo`, `useRpc`, `useSubscription`, `useSettings`, `useWorkspace`, `useAgent`, and `useTabState` from `@getpaseo/plugin/client`.
|
||||
|
||||
### Server contributions
|
||||
|
||||
@@ -234,15 +234,15 @@ export default function contribute(client: PluginClientContext) {
|
||||
title: "Open workspace overview",
|
||||
icon: "PanelsTopLeft",
|
||||
context: "workspace",
|
||||
onSelect({ openPanel }) {
|
||||
openPanel("overview");
|
||||
onSelect({ workspaceLayout }) {
|
||||
workspaceLayout.open({ panelId: "overview" });
|
||||
},
|
||||
});
|
||||
return () => {};
|
||||
}
|
||||
```
|
||||
|
||||
Register a panel that belongs to one agent with `addAgentPanel`, and read `params.agentId` in it. Command Center callbacks receive `paseo`, `rpc`, `openScreen`, and, in workspace and agent context, `openPanel`.
|
||||
Register a panel that belongs to one agent with `addAgentPanel`, and read `params.agentId` in it. Command Center callbacks receive `paseo`, `rpc`, `openScreen`, and, in workspace and agent context, `workspaceLayout`, which opens and arranges panes and tabs (Reference > Workspace layout, Paseo 0.18.2 or later).
|
||||
|
||||
### Add a screen and a sidebar item
|
||||
|
||||
|
||||
Reference in New Issue
Block a user