Compare commits

..
Author SHA1 Message Date
Mohamed Boudra 38af54a7b0 fix(app): hold a sheet until its workspace has been on screen
Hidden workspace screens stay mounted and the sheet stack is app-wide, so a
sheet tab presented on mount covered whichever workspace the user was on.
Plugins reach this by opening a file or a child agent's chat in another
workspace. The sheet now presents when its workspace is first on screen.
2026-11-29 16:14:21 +01:00
Mohamed Boudra b0fb288801 fix(plugins): keep layout commands for another workspace off the screen
A phone's Explorer overlay and agent list exist once for the whole app, so a
plugin arranging a workspace in the background opened or closed them over the
workspace the user was reading. Layout commands now tell workspace-tabs whether
their workspace is on screen. Built-in callers keep following the overlays,
because several reveal a tab before the route has changed.
2026-11-29 15:57:57 +01:00
Mohamed Boudra 4a7f2d302b feat(plugins): let any plugin code arrange a workspace through its layout handle
Commands, screens and slash commands now reach the layout handle, not only
panels, so a plugin can arrange a workspace the user is not looking at.
`openPanel` is deprecated in its favor and keeps its navigating behavior.

Two defects surfaced while driving the example:

- A plugin's split `size` was stored but never drawn: the desktop canvas
  gives every group equal children unless the group has saved sizes. A
  requested share is now saved the way a dragged one is, and no longer
  also written into the layout tree. A split with no size saves nothing,
  so it is sized as one made in the UI.
- A chat in a phone's Explorer overlay never loaded, because the overlay's
  pane stays hidden in the layout and hidden panes counted as off screen.
2026-11-29 15:36:56 +01:00
Mohamed Boudra bf6d881ece feat(plugins): let plugin panels read and arrange a workspace's layout
useWorkspaceLayout gives a plugin a handle on a workspace's panes and tabs:
open, focus, move and close tabs, close panes, show the Explorer, and read the
layout reactively.

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

The app side is a facade over the layout store and workspace-tabs, so a plugin's
open, move and close behave as the same action in the UI.
2026-11-29 14:23:25 +01:00
Mohamed Boudra 8d5fecb595 refactor(app): close workspace tabs through one command
The guards and teardown for closing a tab lived in the workspace screen, so
only that screen could close a tab without skipping the unsaved-work and
destructive prompts or leaking the tab's agent or terminal. They now belong
to workspace-tabs, callable from outside React, ahead of letting plugins
close tabs the same way a user does.
2026-11-29 13:41:46 +01:00
130 changed files with 5682 additions and 2171 deletions
+1 -6
View File
@@ -601,12 +601,7 @@ The cache is capped at 32 MiB and evicts whole hosts in least-recently-written o
eviction, only a baseline replacement stores that host's directory again. Mutations queued around
the eviction are dropped when they are written, so a checkpoint never outlives its rows. Budget
bookkeeping may scan opaque row sizes during a deferred write, never during host registry startup or
before a requested cache row can paint. The cache holds only each row's key and UTF-8 payload size,
never the payload: a timeline row can be megabytes, and the renderer would hold a second copy of
every cached transcript until restart. Each store reports sizes without loading payloads. SQLite
measures the stored text, and IndexedDB records the size on the row and reads an index over it.
Opening an IndexedDB database written before that index existed drops its rows, because they would
be readable but never counted against the budget. The row store is not encrypted. A cached timeline can contain
before a requested cache row can paint. The row store is not encrypted. A cached timeline can contain
source code, prompts, and tool output; encrypted-at-rest storage is a separate security decision.
### Saved hosts
+4
View File
@@ -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
View File
@@ -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({
@@ -30,7 +30,6 @@ import { openGlobalNewWorkspaceComposer } from "../support/helpers/new-workspace
import { clickNewChat, clickNewTerminal, gotoWorkspace } from "../support/helpers/launcher";
import { openAgentRoute, seedMockAgentWorkspace } from "../support/helpers/mock-agent";
import { seedWorkspace } from "../support/helpers/seed-client";
import { waitForSettledPosition } from "../support/helpers/sheet-layout";
const MOCK_PROVIDER_LABEL = "Mock Load Test";
@@ -324,7 +323,6 @@ test.describe("Cross-provider model search", () => {
const modelRowButton = page.getByTestId("agent-controls-model");
await expect(profilesToggle).toBeVisible();
await expect(page.getByTestId("agent-controls-profiles-list")).toHaveCount(0);
await waitForSettledPosition(profilesToggle);
const profilesBox = await profilesToggle.boundingBox();
const modelBox = await modelRowButton.boundingBox();
expect(profilesBox && modelBox && profilesBox.y < modelBox.y).toBe(true);
@@ -15,9 +15,6 @@ import {
expectBothConsecutiveTools,
trackPluginChatRecovery,
reconnectPluginChat,
withRepeatedOutputTimeline,
readOldestPluginReplacement,
expectOldestPluginReplacementReadable,
} from "../support/helpers/plugin-timeline";
for (const width of [1100, 390]) {
@@ -85,15 +82,3 @@ test("plugin-transformed assistant reply keeps copy, fork, and turn duration in
expect(await forkAttachment.waitForText()).toContain(ASSISTANT_TEXT);
});
});
test("keeps older plugin replacements readable when source messages reuse local output IDs", async ({
page,
}, info) => {
await withRepeatedOutputTimeline(page, info, async () => {
await readOldestPluginReplacement(page);
await expectOldestPluginReplacementReadable(page);
await page.reload({ waitUntil: "domcontentloaded" });
await readOldestPluginReplacement(page);
await expectOldestPluginReplacementReadable(page);
});
});
@@ -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);
});
});
});
@@ -118,14 +118,10 @@ test("projects and pinned chats reorder while ordinary workspaces stay newest fi
await firstProject.client.setWorkspacePinned(firstProject.workspaceId, true);
await secondProject.client.setWorkspacePinned(secondProject.workspaceId, true);
const secondProjectWorkspaceTestId = `sidebar-workspace-row-${getServerId()}:${secondProject.workspaceId}`;
// Both rows also exist in their project groups, so match them only once each pin has
// moved its row into the Pinned section.
await quickDragFirstRowAfterSecond(
page
.getByTestId("sidebar-pinned-section")
.locator(
`[data-testid="${firstWorkspaceTestId}"], [data-testid="${secondProjectWorkspaceTestId}"]`,
),
page.locator(
`[data-testid="${firstWorkspaceTestId}"], [data-testid="${secondProjectWorkspaceTestId}"]`,
),
pressWorkspaceRow,
);
} finally {
@@ -392,8 +392,6 @@ test.describe("Terminal protocol queries", () => {
await terminalSurface(page).click();
await terminalSurface(page).pressSequentially("Q", { delay: 0 });
await expectTerminalOutput(lightTerminalId, "WATCH2031_DONE");
// One report per switch: a second responder would deliver each switch twice.
expect(watch2031Events(await terminalOutput(lightTerminalId))).toEqual(["1", "2"]);
await selectAppThemeInApp(page, "Dark");
await runPaletteChecks(lightTerminalId, TERMINAL_PALETTE_SCENARIOS.dark, {
@@ -430,10 +428,6 @@ test.describe("Terminal protocol queries", () => {
return capture.lines.join("").replace(/\s/g, "");
}
function watch2031Events(output: string): string[] {
return [...output.matchAll(/WATCH2031_EVENT:([12])/g)].map(([, scheme]) => scheme);
}
async function expectTerminalOutput(terminalId: string, text: string): Promise<void> {
await expect.poll(() => terminalOutput(terminalId), { timeout: 10_000 }).toContain(text);
}
@@ -1,60 +0,0 @@
import assert from "node:assert/strict";
import { execFileSync } from "node:child_process";
import { setTimeout } from "node:timers/promises";
// Opening a file from the filtered Files tree must close the software keyboard.
//
// Before running, on a phone-sized device with a software keyboard enabled, open
// Explorer -> Files in a workspace where the first match for the query is a file.
// The app must already run the checkout being verified against a real daemon.
const serial = process.env.ANDROID_SERIAL ?? "emulator-5554";
const query = process.env.PASEO_FILES_FILTER_QUERY ?? "README";
function adb(...args) {
return execFileSync("adb", ["-s", serial, ...args], { encoding: "utf8", timeout: 60_000 });
}
function findNode(id) {
adb("shell", "uiautomator", "dump", "/sdcard/files-filter-keyboard.xml");
const tree = adb("exec-out", "cat", "/sdcard/files-filter-keyboard.xml");
const node = tree.match(new RegExp(`<node [^>]*resource-id="${id}"[^>]*>`))?.[0];
const bounds = node?.match(/bounds="\[(\d+),(\d+)\]\[(\d+),(\d+)\]"/);
if (!bounds) return null;
const [left, top, right, bottom] = bounds.slice(1).map(Number);
return { x: Math.round((left + right) / 2), y: Math.round((top + bottom) / 2) };
}
async function waitForNode(id) {
const deadline = Date.now() + 30_000;
while (Date.now() < deadline) {
const node = findNode(id);
if (node) return node;
await setTimeout(250);
}
throw new Error(`Timed out waiting for ${id}`);
}
function tap({ x, y }) {
adb("shell", "input", "tap", String(x), String(y));
}
async function waitForKeyboard(shown) {
let stable = 0;
const deadline = Date.now() + 10_000;
while (Date.now() < deadline) {
const state = adb("shell", "dumpsys", "input_method");
stable = /^ {2}mInputShown=true$/m.test(state) === shown ? stable + 1 : 0;
if (stable === 3) return;
await setTimeout(200);
}
assert.fail(`Keyboard did not settle at shown=${shown}`);
}
const clear = findNode("files-filter-clear");
if (clear) tap(clear);
tap(await waitForNode("files-filter-input"));
await waitForKeyboard(true);
adb("shell", "input", "text", query);
const match = await waitForNode("file-filter-row-0");
await waitForKeyboard(true); // Typing and new results leave the keyboard up.
tap(match);
await waitForNode("sheet-tab-body");
await waitForKeyboard(false);
console.log("PASS: opening a filtered file closes the keyboard");
@@ -18,9 +18,6 @@ press "id=\"combined-model-selector\""
wait "id=\"model-provider-${PROVIDER_ID}\"" 10000
press "id=\"model-provider-${PROVIDER_ID}\""
wait "id=\"model-row-${PROVIDER_ID}-${MODEL_ID}\"" 3000
# Back takes the header's step to the provider list first, then dismisses the modal.
back
wait "id=\"model-provider-${PROVIDER_ID}\"" 3000
back
wait "id=\"combined-model-selector\" label=\"Select model (${MODEL_LABEL})\"" 3000
close
@@ -10,13 +10,13 @@ wait "id=\"agent-controls-model\"" 10000
gesture pan 540 790 0 960 500
wait "id=\"combined-model-selector\"" 3000
# Android Back steps from Model back to Agent settings, then closes the sheet.
# Reopen, dismiss the nested model browser, then dismiss its restored parent.
press "id=\"combined-model-selector\""
wait "id=\"agent-controls-model\"" 10000
press "id=\"agent-controls-model\""
wait "id=\"model-search-all-input\"" 10000
back
wait stable 300 5000
gesture pan 540 790 0 960 500
wait "id=\"agent-controls-model\"" 3000
back
gesture pan 540 790 0 960 500
wait "id=\"combined-model-selector\"" 3000
close
@@ -7,7 +7,6 @@ import { connectNewWorkspaceDaemonClient } from "./new-workspace";
import { openAgentRoute, seedMockAgentWorkspace, type MockAgentWorkspace } from "./mock-agent";
import { installDaemonWebSocketGate } from "./daemon-websocket-gate";
import { expectReconnectingToastVisible } from "./workspace-ui";
import { userScrollsTimelineToHistoryStart } from "./timeline-pagination";
const PLUGIN_ID = "timeline-transform-e2e";
@@ -374,81 +373,3 @@ export async function viewInlineThinkingExample(page: Page, info: TestInfo): Pro
await example.cleanup();
}
}
/** Reuse plugin-local IDs across distinct source messages in a real virtualized chat. */
export async function withRepeatedOutputTimeline(
page: Page,
info: TestInfo,
run: () => Promise<void>,
): Promise<void> {
info.setTimeout(120_000);
const agent = await seedMockAgentWorkspace({
repoPrefix: "timeline-local-ids-",
title: "Repeated plugin output IDs",
});
try {
for (const label of ["First", "Second", "Third"]) {
await agent.client.sendAgentMessage(
agent.agentId,
`${label}: emit 1 coalesced agent stream updates`,
);
await agent.client.waitForFinish(agent.agentId, 15_000);
}
await withDirectoryPlugin({
pluginId: "timeline-local-ids",
source: `import React from "react";
import { Text, View } from "react-native";
import { z } from "zod";
function Row({ item }) {
return <View style={{ height: item.data.tall ? 120 : 24 }}>
<Text>{item.data.label}</Text>
</View>;
}
export default function contribute(client) {
client.addTimelineTransformer({
id: "local-ids", query: { itemType: "user_message" },
transform({ item }) {
const label = item.text.split(":")[0];
return { items: Array.from({ length: 60 }, (_, index) => ({
type: "plugin", id: "part-" + index, kind: "reply", version: 1,
data: { label: label + " replacement " + index, tall: label === "Second" },
})) };
},
});
client.addTimelineRenderer({
kind: "reply", version: 1,
schema: z.object({ label: z.string(), tall: z.boolean() }), Component: Row,
});
return () => {};
}`,
run: async () => {
await openAgentRoute(page, agent);
await expect(page.getByRole("textbox", { name: "Message agent..." }).first()).toBeVisible();
await run();
},
});
} finally {
await agent.cleanup();
}
}
export async function readOldestPluginReplacement(page: Page): Promise<void> {
await expect(page.getByText("Third replacement 59", { exact: true }).first()).toBeAttached();
await expect
.poll(async () => {
await userScrollsTimelineToHistoryStart(page);
return page.getByText("First replacement 0", { exact: true }).isVisible();
})
.toBe(true);
}
export async function expectOldestPluginReplacementReadable(page: Page): Promise<void> {
await expect(
page
.getByTestId("agent-chat-scroll")
.locator("[data-index]")
.getByText("First replacement 0", { exact: true }),
).toBeVisible();
await expect(page.getByRole("textbox", { name: "Message agent..." }).first()).toBeVisible();
await expect(page.getByText("Paseo ran into a problem.", { exact: true })).toHaveCount(0);
}
@@ -61,24 +61,18 @@ async function readRows(input: {
storeName: string;
}): Promise<ReplicaRowRecord[]> {
const database = await new Promise<IDBDatabase>((resolve, reject) => {
// The app owns the database version; open whatever version it created.
const request = indexedDB.open(input.databaseName);
const request = indexedDB.open(input.databaseName, 1);
request.addEventListener("success", () => resolve(request.result));
request.addEventListener("error", () => reject(request.error));
});
return new Promise((resolve, reject) => {
const request = database
.transaction(input.storeName, "readonly")
.objectStore(input.storeName)
.getAll();
request.addEventListener("success", () => resolve(request.result));
request.addEventListener("error", () => reject(request.error));
});
try {
return await new Promise((resolve, reject) => {
const request = database
.transaction(input.storeName, "readonly")
.objectStore(input.storeName)
.getAll();
request.addEventListener("success", () => resolve(request.result));
request.addEventListener("error", () => reject(request.error));
});
} finally {
// An open connection would block the app from upgrading the database.
database.close();
}
}
function assembleCache(rows: ReplicaRowRecord[]): ReplicaCacheRecord {
@@ -191,27 +185,19 @@ export async function writeReplicaCache(page: Page, value: ReplicaCacheRecord):
await page.evaluate(
async ({ databaseName, storeName, nextRows }) => {
const database = await new Promise<IDBDatabase>((resolve, reject) => {
const request = indexedDB.open(databaseName);
const request = indexedDB.open(databaseName, 1);
request.addEventListener("success", () => resolve(request.result));
request.addEventListener("error", () => reject(request.error));
});
try {
await new Promise<void>((resolve, reject) => {
const transaction = database.transaction(storeName, "readwrite");
const store = transaction.objectStore(storeName);
store.clear();
// The app budgets the cache on each row's recorded UTF-8 payload size.
const encoder = new TextEncoder();
for (const row of nextRows) {
store.put({ ...row, payloadBytes: encoder.encode(row.payload).length });
}
transaction.addEventListener("complete", () => resolve());
transaction.addEventListener("error", () => reject(transaction.error));
transaction.addEventListener("abort", () => reject(transaction.error));
});
} finally {
database.close();
}
await new Promise<void>((resolve, reject) => {
const transaction = database.transaction(storeName, "readwrite");
const store = transaction.objectStore(storeName);
store.clear();
for (const row of nextRows) store.put(row);
transaction.addEventListener("complete", () => resolve());
transaction.addEventListener("error", () => reject(transaction.error));
transaction.addEventListener("abort", () => reject(transaction.error));
});
},
{ databaseName: DATABASE_NAME, storeName: STORE_NAME, nextRows: rows },
);
@@ -1,13 +1,11 @@
package sh.paseo.terminal
import android.os.Build
import android.text.InputType
import android.view.KeyCharacterMap
import android.view.KeyEvent
import android.view.View
import android.view.inputmethod.EditorInfo
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.SdkSuppress
import androidx.test.platform.app.InstrumentationRegistry
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
@@ -79,15 +77,6 @@ class TerminalInputConnectionTest {
}
}
/** Gboard commits each letter in its own batch edit when the editor disables suggestions. */
private fun TerminalInputConnection.typeLikeGboard(text: String) {
for (ch in text) {
beginBatchEdit()
commitText(ch.toString(), 1)
endBatchEdit()
}
}
@Test
fun editorInfoDisablesSuggestionsFullscreenAndPersonalizedLearning() {
instrumentation.runOnMainSync {
@@ -111,8 +100,13 @@ class TerminalInputConnectionTest {
@Test
fun batchedCommitTextAndSetComposingTextDoNotDoubleCharacters() {
withInputHarness { _, ic, _, terminal ->
ic.typeLikeGboard("abcd")
for (ch in listOf("a", "b", "c", "d")) {
ic.beginBatchEdit()
ic.commitText(ch, 1)
ic.endBatchEdit()
}
assertEquals("abcd", terminal.rawStream)
assertEquals("", ic.editable.toString())
// Coalesced setComposingText + finishComposingText inside one batch emits once.
ic.beginBatchEdit()
@@ -120,96 +114,28 @@ class TerminalInputConnectionTest {
ic.finishComposingText()
ic.endBatchEdit()
assertEquals("abcdef", terminal.rawStream)
assertEquals("", ic.editable.toString())
}
}
@Test
fun editorKeepsTheTypedLineUntilTerminalKeyBoundary() {
withInputHarness { _, ic, _, terminal ->
// IMEs address edits by offsets into the text they committed, so the editor must keep it.
ic.typeLikeGboard("ab")
assertEquals("ab", ic.getTextBeforeCursor(10, 0).toString())
// Enter leaves the shell line, so the editor starts the next line empty.
ic.sendKeyEvent(KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_ENTER))
ic.sendKeyEvent(KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_ENTER))
assertEquals("", ic.getTextBeforeCursor(10, 0).toString())
ic.typeLikeGboard("helo")
ic.beginBatchEdit()
ic.setComposingRegion(0, 4)
ic.commitText("hello ", 1)
ic.endBatchEdit()
assertEquals("ab\rhello ", terminal.applyToLine())
}
}
@Test
fun gboardArrowKeyStartsTheEditorOnAnEmptyLine() {
withInputHarness { _, ic, _, terminal ->
ic.typeLikeGboard("echo helo")
// Gboard's editing panel sends arrows as key events. The shell cursor moves, so the
// editor's copy of the line no longer matches where the next edit lands.
ic.sendKeyEvent(KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DPAD_LEFT))
ic.sendKeyEvent(KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_DPAD_LEFT))
assertEquals("", ic.getTextBeforeCursor(10, 0).toString())
assertEquals(listOf("ArrowLeft"), terminal.keys.map { it.key })
assertEquals("echo helo", terminal.rawStream)
}
}
@Test
fun suggestionPickedThroughComposingRegionReplacesCommittedWord() {
withInputHarness { _, ic, _, terminal ->
// Gboard before Android 14 selects the committed word, then commits the suggestion.
ic.typeLikeGboard("helo")
ic.beginBatchEdit()
ic.setComposingRegion(3, 4)
ic.commitText("lo ", 1)
ic.endBatchEdit()
assertEquals("hello ", terminal.applyToLine())
}
}
@Test
@SdkSuppress(minSdkVersion = Build.VERSION_CODES.UPSIDE_DOWN_CAKE)
fun gboardReplaceTextRewritesCommittedText() {
// Gboard on Android 14+ picks suggestions and applies double-space period with replaceText,
// addressing text it committed earlier. Offsets and texts below are the calls Gboard made live.
fun assertReplacement(typed: String, start: Int, end: Int, replacement: String, line: String) {
withInputHarness { _, ic, _, terminal ->
ic.typeLikeGboard(typed)
ic.beginBatchEdit()
ic.replaceText(start, end, replacement, 1, null)
ic.endBatchEdit()
assertEquals("$typed -> $replacement", line, terminal.applyToLine())
}
}
assertReplacement("helo", 3, 4, "lo ", line = "hello ")
assertReplacement("helo", 3, 4, "p ", line = "help ")
assertReplacement("echo hello", 5, 10, "jello ", line = "echo jello ")
assertReplacement("ab ", 2, 3, ". ", line = "ab. ")
}
@Test
fun backspaceWorksAcrossAllThreeImePaths() {
withInputHarness { _, ic, _, terminal ->
ic.commitText("abcd", 1)
assertEquals("abcd", terminal.applyToLine())
// Path 1: deleteSurroundingText
// Path 1: deleteSurroundingText (empty editable after commit)
ic.deleteSurroundingText(0, 0)
assertEquals("abcd", terminal.applyToLine())
ic.deleteSurroundingText(1, 0)
assertEquals("abc", terminal.applyToLine())
// Path 2: deleteSurroundingTextInCodePoints
// Path 2: deleteSurroundingTextInCodePoints (empty editable)
ic.deleteSurroundingTextInCodePoints(1, 0)
assertEquals("ab", terminal.applyToLine())
// Path 2b: deleteSurroundingTextInCodePoints removes a surrogate-pair emoji as one code point
ic.commitText("😀", 1)
// Path 2b: deleteSurroundingTextInCodePoints on surrogate-pair emoji in composing buffer
ic.setComposingText("😀", 1)
assertEquals("ab😀", terminal.applyToLine())
ic.deleteSurroundingTextInCodePoints(1, 0)
assertEquals("ab", terminal.applyToLine())
@@ -219,16 +145,10 @@ class TerminalInputConnectionTest {
ic.sendKeyEvent(KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_DEL))
assertEquals("a", terminal.applyToLine())
// Multi-char deleteSurroundingText
// Multi-char deleteSurroundingText on empty buffer
ic.commitText("xyz", 1)
ic.deleteSurroundingText(2, 0)
assertEquals("ax", terminal.applyToLine())
// After Enter the editor is empty, so Backspace still reaches text the shell already holds
ic.sendKeyEvent(KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_ENTER))
ic.deleteSurroundingText(1, 0)
ic.deleteSurroundingTextInCodePoints(1, 0)
assertEquals("\r\u007f\u007f", terminal.rawStream.takeLast(3))
}
}
@@ -322,7 +242,7 @@ class TerminalInputConnectionTest {
ic.commitText("the", 1)
assertEquals("hellothe", terminal.applyToLine())
// Repeated clipboard paste of identical text appends both copies
// Repeated clipboard paste of identical text works because editable clears after commit
ic.commitText("echo ok", 1)
ic.commitText("echo ok", 1)
assertEquals("hellotheecho okecho ok", terminal.applyToLine())
@@ -22,16 +22,9 @@ internal data class TerminalKeyPayload(
/**
* Single authoritative IME + key stream for the Android native terminal.
*
* The private [SpannableStringBuilder] holds the text the IME has typed on the current shell line,
* committed and composing alike. IMEs keep their own copy of that text and edit it by offset:
* Gboard picks a suggestion or applies double-space period by replacing text it committed
* earlier. Once each batch edit settles, the editable is diffed against what the terminal already
* holds and only the difference is sent, as rubouts plus the new suffix.
*
* A terminal key (Enter, Tab, Escape, arrows, control and hardware characters) changes the shell
* line outside the IME, so it empties the editable and restarts the IME on the empty line.
* Keys sent to the terminal without passing through this connection do not empty it: the
* accessory bar, and the hardware arrows that `PaseoHardwareKeyboardModule` claims at window level.
* Keeps a private [SpannableStringBuilder] so Android IMEs can compose Hangul, Pinyin, and Latin
* candidates normally, diffs the editable against what was last sent to the PTY once each batch
* edit settles, and clears the editable as soon as no composing span remains.
*/
internal class TerminalInputConnection(
private val targetView: View,
@@ -203,7 +196,6 @@ internal class TerminalInputConnection(
KeyEvent.KEYCODE_DPAD_LEFT,
KeyEvent.KEYCODE_DPAD_RIGHT -> {
deadAccent = 0
flushAndClear()
val name = when (keyCode) {
KeyEvent.KEYCODE_DPAD_UP -> "ArrowUp"
KeyEvent.KEYCODE_DPAD_DOWN -> "ArrowDown"
@@ -350,38 +342,57 @@ internal class TerminalInputConnection(
if (diff.isNotEmpty()) {
out.append(normalizeLineEndings(diff))
}
lastSentText = currentText
var compStart = getComposingSpanStart(sharedEditable)
var compEnd = getComposingSpanEnd(sharedEditable)
if (compStart >= 0 && compEnd <= compStart) {
// An empty composing span would make hardware arrows look like IME navigation.
removeComposingSpans(sharedEditable)
compStart = -1
compEnd = -1
val compStart = getComposingSpanStart(sharedEditable)
val compEnd = getComposingSpanEnd(sharedEditable)
val isComposing = compStart >= 0 && compEnd > compStart
if (!isComposing) {
val hadText = sharedEditable.isNotEmpty()
if (hadText || compStart >= 0) {
clearEditableSilently()
}
lastSentText = ""
if (hadText) {
// The IME just advanced its cursor for the committed text; report the reset to 0, 0.
forceUpdateSelection(0, 0, -1, -1)
} else {
notifySelectionIfChanged(0, 0, -1, -1)
}
} else {
lastSentText = currentText
val selStart = maxOf(0, Selection.getSelectionStart(sharedEditable))
val selEnd = maxOf(0, Selection.getSelectionEnd(sharedEditable))
notifySelectionIfChanged(selStart, selEnd, compStart, compEnd)
}
notifySelectionIfChanged(
maxOf(0, Selection.getSelectionStart(sharedEditable)),
maxOf(0, Selection.getSelectionEnd(sharedEditable)),
compStart,
compEnd,
)
if (out.isNotEmpty()) {
onInput(out.toString())
}
}
/** Sends pending IME text, then starts the IME on an empty line before a terminal key. */
private fun flushAndClear() {
batchEditDepth = 0
flush()
if (sharedEditable.isEmpty()) return
resetState()
// The IME still holds the old line; updateSelection alone does not make Gboard reload it.
val imm = targetView.context.getSystemService(InputMethodManager::class.java) ?: return
if (imm.isActive(targetView)) {
imm.restartInput(targetView)
val hadText = sharedEditable.isNotEmpty()
val out = StringBuilder()
if (pendingBackspaces > 0) {
repeat(pendingBackspaces) { out.append('\u007f') }
pendingBackspaces = 0
}
val currentText = sharedEditable.toString()
val diff = computeDiff(lastSentText, currentText)
if (diff.isNotEmpty()) {
out.append(normalizeLineEndings(diff))
}
if (hadText || getComposingSpanStart(sharedEditable) >= 0) {
clearEditableSilently()
}
lastSentText = ""
if (hadText || lastSelStart != 0 || lastSelEnd != 0 || lastCompStart != -1 || lastCompEnd != -1) {
forceUpdateSelection(0, 0, -1, -1)
}
if (out.isNotEmpty()) {
onInput(out.toString())
}
}
@@ -400,6 +411,10 @@ internal class TerminalInputConnection(
) {
return
}
forceUpdateSelection(selStart, selEnd, compStart, compEnd)
}
private fun forceUpdateSelection(selStart: Int, selEnd: Int, compStart: Int, compEnd: Int) {
lastSelStart = selStart
lastSelEnd = selEnd
lastCompStart = compStart
+3 -14
View File
@@ -3,9 +3,12 @@ import { useTranslation } from "react-i18next";
import { i18n } from "@/i18n/i18next";
import { useProviderIcon } from "@/components/provider-icons";
import type { PanelDescriptor } from "@/panels/panel-registry";
import { resolveAgentLabel } from "@/panels/tab-labels";
import { useSessionStore, selectAgentTurnPresentation, type Agent } from "@/stores/session-store";
import { deriveSidebarStateBucket } from "@/utils/sidebar-agent-state";
export { resolveAgentLabel };
function formatProviderLabel(provider: Agent["provider"]): string {
if (!provider) {
return "Agent";
@@ -17,20 +20,6 @@ function formatProviderLabel(provider: Agent["provider"]): string {
.join(" ");
}
export function resolveAgentLabel(title: string | null | undefined): string | null {
if (typeof title !== "string") {
return null;
}
const normalized = title.trim();
if (!normalized) {
return null;
}
if (normalized.toLowerCase() === "new agent") {
return null;
}
return normalized;
}
export function useAgentDescriptor(
target: { kind: "agent"; agentId: string },
context: { serverId: string },
+7 -8
View File
@@ -603,15 +603,14 @@ describe("layoutStream", () => {
splitIntoCards,
);
const footerCardIds = tail
.filter((item) => item.kind === "plugin" && item.itemKind === "genui-card")
.map((item) => item.id);
expect(footerCardIds).toHaveLength(2);
const layout = layoutFor({
platform,
tail,
timingIds: ["genui/a1/card", "genui/a2/card"],
});
const layout = layoutFor({ platform, tail, timingIds: footerCardIds });
expect(footerOwners(layout)).toEqual(footerCardIds);
expect(findLayoutItem(layout, footerCardIds[0]).completedFooter?.turnMetrics).toBe(
expect(footerOwners(layout)).toEqual(["genui/a1/card", "genui/a2/card"]);
expect(findLayoutItem(layout, "genui/a1/card").completedFooter?.turnMetrics).toBe(
first.turnMetrics,
);
expect(layout.auxiliaryTurnFooter?.turnMetrics).toBe(metrics);
@@ -203,9 +203,7 @@ describe("stream presentation through installed plugins", () => {
const source = rows(harness.source());
expect(source).toMatchObject([{ kind: "user_message", id: "prompt-1" }]);
expect(rendered).toMatchObject([
{ kind: "plugin", source: { id: "prompt-1" }, pluginItemId: "prompt-1/0" },
]);
expect(rendered).toMatchObject([{ kind: "plugin", id: "probe-plugin/prompt-1/0" }]);
// The chat outline jumps to the source id; the row it lands on is the plugin's.
expect(rendered.map(getStreamItemMessageId)).toEqual(["prompt-1"]);
});
@@ -613,7 +611,7 @@ it("folds work before a plugin-rendered reply and leaves the reply visible", ()
expect(result.tail.map((item) => item.id)).toEqual([
"prompt",
"turn-summary:prompt",
JSON.stringify(["probe-plugin", "reply", "reply/0"]),
"probe-plugin/reply/0",
]);
expect(pluginData(result.tail)).toEqual([{ text: "$$x^2$$", phase: "complete" }]);
});
@@ -642,7 +640,7 @@ it("keeps streaming replies native, then folds work without losing manual expans
expect(present(completed).tail.map((item) => item.id)).toEqual([
"prompt",
"turn-summary:prompt",
JSON.stringify(["probe-plugin", "reply", "reply/0"]),
"probe-plugin/reply/0",
]);
const expandedTurnHostIds = new Set(["prompt"]);
const opened = present({ ...completed, expandedTurnHostIds });
@@ -650,16 +648,14 @@ it("keeps streaming replies native, then folds work without losing manual expans
"prompt",
"turn-summary:prompt",
"tool-one",
JSON.stringify(["probe-plugin", "reply", "reply/0"]),
"probe-plugin/reply/0",
]);
expect(opened.turns.nestedItemIds.has(JSON.stringify(["probe-plugin", "reply", "reply/0"]))).toBe(
false,
);
expect(opened.turns.nestedItemIds.has("probe-plugin/reply/0")).toBe(false);
expect(present({ ...completed, expandedTurnHostIds }).tail).toEqual(opened.tail);
expect(present(completed).tail.map((item) => item.id)).toEqual([
"prompt",
"turn-summary:prompt",
JSON.stringify(["probe-plugin", "reply", "reply/0"]),
"probe-plugin/reply/0",
]);
});
@@ -683,7 +679,7 @@ it.each(["full", "collapseToolCalls"] as const)(
expect(result.tail.map((item) => item.id)).toEqual([
"prompt",
"tool-one",
JSON.stringify(["probe-plugin", "reply", "reply/0"]),
"probe-plugin/reply/0",
]);
expect(result.turns.summaryRowsByHostId.size).toBe(0);
},
+2
View File
@@ -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>
@@ -60,10 +60,6 @@ export interface SheetHeaderSearch {
testID?: string;
}
/**
* One step back inside the sheet, such as from a page to the one before it. Android Back takes
* this step too, and closes the sheet only when the header has no back.
*/
export interface SheetHeaderBack {
onPress: () => void;
label?: string;
@@ -742,17 +738,10 @@ export function AdaptiveModalSheet({
}
}, [visible]);
const headerBack = header?.back?.onPress;
const handleBack = useCallback(() => {
if (!headerBack) return false;
headerBack();
return true;
}, [headerBack]);
const { sheetRef, handleSheetChange, handleSheetDismiss } = useIsolatedBottomSheetVisibility({
visible,
isEnabled: isSheet,
onClose,
onBack: handleBack,
});
const [shouldRenderWeb, setShouldRenderWeb] = useState(visible);
const [isWebClosing, setIsWebClosing] = useState(false);
@@ -12,7 +12,6 @@ import { useQuery } from "@tanstack/react-query";
import { useTranslation } from "react-i18next";
import {
FlatList,
Keyboard,
type LayoutChangeEvent,
ListRenderItemInfo,
Pressable,
@@ -630,8 +629,6 @@ export function FileExplorerPane({
if (!hasWorkspaceScope) {
return;
}
// The preview opens over this pane, so the filter must give up the keyboard.
Keyboard.dismiss();
onOpenFile?.(entry.path);
},
[hasWorkspaceScope, onOpenFile],
@@ -1,52 +0,0 @@
import { Component, type ErrorInfo, type ReactNode } from "react";
interface RenderErrorBoundaryProps {
children: ReactNode;
/** A caught error is cleared when any of these values change, so new content renders. */
resetKeys: readonly unknown[];
/** The error state shown in place of the children. `retry` renders the children again. */
renderError(error: string, retry: () => void): ReactNode;
onError(error: unknown, componentStack: string | null | undefined): void;
}
interface RenderErrorBoundaryState {
error: string | null;
}
/**
* Keeps a render error inside one surface. Without it the error reaches the root boundary,
* which replaces the whole app.
*/
export class RenderErrorBoundary extends Component<
RenderErrorBoundaryProps,
RenderErrorBoundaryState
> {
state: RenderErrorBoundaryState = { error: null };
static getDerivedStateFromError(error: unknown): RenderErrorBoundaryState {
return { error: error instanceof Error ? error.message : String(error) };
}
componentDidCatch(error: unknown, info: ErrorInfo): void {
this.props.onError(error, info.componentStack);
}
componentDidUpdate(previous: RenderErrorBoundaryProps): void {
if (this.state.error !== null && resetKeysChanged(previous.resetKeys, this.props.resetKeys)) {
this.retry();
}
}
retry = (): void => {
this.setState({ error: null });
};
render() {
if (this.state.error !== null) return this.props.renderError(this.state.error, this.retry);
return this.props.children;
}
}
function resetKeysChanged(previous: readonly unknown[], next: readonly unknown[]): boolean {
return previous.length !== next.length || previous.some((key, index) => key !== next[index]);
}
@@ -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,
+2 -15
View File
@@ -5,23 +5,10 @@ import invariant from "tiny-invariant";
import { BrowserPane } from "@/desktop/browser/pane";
import { usePaneContext, usePaneFocus } from "@/panels/pane-context";
import { definePanel, type PanelDescriptor, type PanelIconProps } from "@/panels/panel-registry";
import { browserTabLabel } from "@/panels/tab-labels";
import { useBrowserStore } from "@/desktop/browser/store";
import { useWorkspaceDirectory } from "@/stores/session-store-hooks";
function getBrowserLabel(input: { title: string; url: string }): string {
const title = input.title.trim();
if (title) {
return title;
}
try {
const parsed = new URL(input.url);
return parsed.hostname || input.url;
} catch {
return input.url;
}
}
function createBrowserTabIcon(faviconUrl: string | null) {
return function BrowserTabIcon({ size, color }: PanelIconProps) {
const source = useMemo(() => (faviconUrl ? { uri: faviconUrl } : undefined), []);
@@ -42,7 +29,7 @@ function useBrowserPanelDescriptor(target: {
const browser = useBrowserStore((state) => state.browsersById[target.browserId] ?? null);
const url = browser?.url ?? "https://example.com";
const icon = createBrowserTabIcon(browser?.faviconUrl ?? null);
const label = getBrowserLabel({ title: browser?.title ?? "", url });
const label = browserTabLabel({ title: browser?.title ?? "", url });
return {
label,
@@ -0,0 +1,135 @@
/** One workspace's file tree state, driven from inside and outside React. */
import {
loadExplorerDirectory,
type DirectoryListingResult,
} from "@/file-explorer/directory-listings";
import { clearFileFilter } from "@/file-explorer/filter";
import { useExplorerRevealStore } from "@/file-explorer/reveal-request";
import { revealExplorerEntry } from "@/file-explorer/tree";
import { i18n } from "@/i18n/i18next";
import { usePanelStore } from "@/stores/panel-store";
import { useSessionStore, type AgentFileExplorerState } from "@/stores/session-store";
export interface FileExplorerWorkspaceScope {
workspaceId?: string | null;
workspaceRoot?: string | null;
}
/** The tree being driven: its host, its state key, and the directory it lists. */
export interface WorkspaceFileTree {
serverId: string;
stateKey: string;
workspaceRoot: string | null;
}
function createExplorerState(): AgentFileExplorerState {
return {
listingGeneration: 0,
directories: new Map(),
isLoading: false,
lastError: null,
pendingRequest: null,
currentPath: ".",
history: ["."],
lastVisitedPath: ".",
selectedEntryPath: null,
};
}
export function normalizeWorkspaceValue(value: string | null | undefined): string | null {
if (typeof value !== "string") {
return null;
}
const trimmed = value.trim();
return trimmed.length > 0 ? trimmed : null;
}
export function buildWorkspaceExplorerStateKey(scope: FileExplorerWorkspaceScope): string | null {
const normalizedWorkspaceId = normalizeWorkspaceValue(scope.workspaceId);
if (normalizedWorkspaceId) {
return `workspace:${normalizedWorkspaceId}`;
}
const normalizedWorkspaceRoot = normalizeWorkspaceValue(scope.workspaceRoot);
if (!normalizedWorkspaceRoot) {
return null;
}
return `root:${normalizedWorkspaceRoot}`;
}
export function updateWorkspaceExplorerState(
tree: Pick<WorkspaceFileTree, "serverId" | "stateKey">,
updater: (prev: AgentFileExplorerState) => AgentFileExplorerState,
): AgentFileExplorerState | null {
let updated: AgentFileExplorerState | null = null;
useSessionStore.getState().setFileExplorer(tree.serverId, (prev) => {
const next = new Map(prev);
const current = next.get(tree.stateKey) ?? createExplorerState();
updated = updater(current);
next.set(tree.stateKey, updated);
return next;
});
return updated;
}
export function listWorkspaceExplorerDirectory(
tree: WorkspaceFileTree,
path: string,
options?: { recordHistory?: boolean; setCurrentPath?: boolean },
): Promise<DirectoryListingResult> {
const normalizedPath = path && path.length > 0 ? path : ".";
return loadExplorerDirectory({
path: normalizedPath,
options,
updateState: (updater) => updateWorkspaceExplorerState(tree, updater),
fallbackError: i18n.t("workspace.fileExplorer.errors.failedToListDirectory"),
listDirectory: async () => {
if (!tree.workspaceRoot) {
throw new Error(i18n.t("workspace.fileExplorer.states.unavailable"));
}
const client = useSessionStore.getState().sessions[tree.serverId]?.client;
if (!client) throw new Error(i18n.t("workspace.terminal.hostDisconnected"));
return client.listDirectory(tree.workspaceRoot, normalizedPath);
},
});
}
export function showWorkspaceExplorerHiddenFiles(): void {
const panel = usePanelStore.getState();
if (!panel.explorerShowHiddenFiles) panel.toggleExplorerShowHiddenFiles();
}
export function expandWorkspaceExplorerPaths(stateKey: string, paths: string[]): void {
usePanelStore
.getState()
.setExpandedPathsForWorkspace(stateKey, (current) =>
Array.from(new Set([...current, ...paths])),
);
}
/** Selects an entry the tree has expanded to, and asks the tree to scroll to it. */
export function showWorkspaceExplorerEntry(
tree: Pick<WorkspaceFileTree, "serverId" | "stateKey">,
entryPath: string,
): void {
updateWorkspaceExplorerState(tree, (state) => ({ ...state, selectedEntryPath: entryPath }));
useExplorerRevealStore.getState().request(tree.stateKey, entryPath);
}
/** Expands to an entry, selects it, and asks the tree to scroll to it. */
export async function revealWorkspaceExplorerEntry(
tree: WorkspaceFileTree,
entryPath: string,
): Promise<boolean> {
const found = await revealExplorerEntry({
entryPath,
requestDirectoryListing: (path) =>
listWorkspaceExplorerDirectory(tree, path, { recordHistory: false, setCurrentPath: false }),
showHiddenFiles: showWorkspaceExplorerHiddenFiles,
expandPaths: (paths) => expandWorkspaceExplorerPaths(tree.stateKey, paths),
});
if (found) {
clearFileFilter(tree.stateKey);
showWorkspaceExplorerEntry(tree, entryPath);
}
return found;
}
+3 -2
View File
@@ -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} />;
+49 -41
View File
@@ -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(
-3
View File
@@ -2183,9 +2183,6 @@ export const ar: TranslationResources = {
archiveFinishedRetry: "إعادة المحاولة ({{failed}}/{{total}})",
},
panels: {
renderError: {
title: "تعذّر عرض هذه اللوحة",
},
draft: {
newAgent: "وكيل جديد",
creatingAgent: "وكيل الخلق",
-3
View File
@@ -2213,9 +2213,6 @@ export const en = {
archiveFinishedRetry: "Retry ({{failed}}/{{total}})",
},
panels: {
renderError: {
title: "Unable to show this panel",
},
draft: {
newAgent: "New Agent",
creatingAgent: "Creating agent",
-3
View File
@@ -2239,9 +2239,6 @@ export const es: TranslationResources = {
archiveFinishedRetry: "Reintentar ({{failed}}/{{total}})",
},
panels: {
renderError: {
title: "No se puede mostrar este panel",
},
draft: {
newAgent: "Nuevo agente",
creatingAgent: "Agente creador",
-3
View File
@@ -2236,9 +2236,6 @@ export const fr: TranslationResources = {
archiveFinishedRetry: "Réessayer ({{failed}}/{{total}})",
},
panels: {
renderError: {
title: "Impossible d'afficher ce panneau",
},
draft: {
newAgent: "Nouvel agent",
creatingAgent: "Création de l’agent",
-3
View File
@@ -2206,9 +2206,6 @@ export const ja: TranslationResources = {
archiveFinishedRetry: "再試行 ({{failed}}/{{total}})",
},
panels: {
renderError: {
title: "このパネルを表示できません",
},
draft: {
newAgent: "新しいエージェント",
creatingAgent: "エージェントを作成中",
-3
View File
@@ -2195,9 +2195,6 @@ export const ko: TranslationResources = {
archiveFinishedRetry: "다시 시도 ({{failed}}/{{total}})",
},
panels: {
renderError: {
title: "이 패널을 표시할 수 없습니다",
},
draft: {
newAgent: "새 에이전트",
creatingAgent: "에이전트 생성 중",
-3
View File
@@ -2223,9 +2223,6 @@ export const ptBR: TranslationResources = {
archiveFinishedRetry: "Tentar novamente ({{failed}}/{{total}})",
},
panels: {
renderError: {
title: "Não foi possível exibir este painel",
},
draft: {
newAgent: "Novo Agente",
creatingAgent: "Criando agente",
-3
View File
@@ -2223,9 +2223,6 @@ export const ru: TranslationResources = {
archiveFinishedRetry: "Повторить ({{failed}}/{{total}})",
},
panels: {
renderError: {
title: "Не удалось показать эту панель",
},
draft: {
newAgent: "Новый агент",
creatingAgent: "Создание агента",
-3
View File
@@ -2160,9 +2160,6 @@ export const zhCN: TranslationResources = {
archiveFinishedRetry: "重试 ({{failed}}/{{total}})",
},
panels: {
renderError: {
title: "无法显示此面板",
},
draft: {
newAgent: "新建 Agent",
creatingAgent: "正在创建 Agent",
+2 -1
View File
@@ -16,6 +16,7 @@ import { useChangesPreferences } from "@/hooks/use-changes-preferences";
import { useAppSettings } from "@/hooks/use-settings";
import { usePaneContext } from "@/panels/pane-context";
import { definePanel, type PanelDescriptor, type PanelPresentation } from "@/panels/panel-registry";
import { commitDiffTabLabel } from "@/panels/tab-labels";
import { useAddFileToChat } from "@/panels/use-add-file-to-chat";
import { useWorkspaceDirectory } from "@/stores/session-store-hooks";
import type { WorkspaceTabTarget } from "@/workspace-tabs/model";
@@ -228,7 +229,7 @@ function useCommitDiffPanelDescriptor(
): PanelDescriptor {
const { t } = useTranslation();
return {
label: target.sha.slice(0, 7),
label: commitDiffTabLabel(target.sha),
subtitle: t("panels.diff.commitSubtitle"),
tooltip: target.sha,
titleState: "ready",
@@ -1,6 +1,7 @@
import type { ComponentType } from "react";
import { i18n } from "@/i18n/i18next";
import type { PanelDescriptor, PanelIconProps } from "@/panels/panel-registry";
import { draftTabLabel } from "@/panels/tab-labels";
export function buildDraftPanelDescriptor(input: {
isCreating: boolean;
@@ -9,7 +10,7 @@ export function buildDraftPanelDescriptor(input: {
}): PanelDescriptor {
const { icon, isCreating, pendingPrompt } = input;
const newAgentLabel = i18n.t("panels.draft.newAgent");
const creatingLabel = pendingPrompt?.trim() || newAgentLabel;
const creatingLabel = draftTabLabel({ isCreating, pendingPrompt, newAgentLabel });
if (isCreating) {
return {
label: creatingLabel,
+2 -1
View File
@@ -5,6 +5,7 @@ import { useTranslation } from "react-i18next";
import { FilePane } from "@/file-pane/pane";
import { usePaneContext } from "@/panels/pane-context";
import { definePanel } from "@/panels/panel-registry";
import { fileTabLabel } from "@/panels/tab-labels";
import { useWorkspaceDirectory } from "@/stores/session-store-hooks";
import { createMaterialFileIcon } from "@/components/material-file-icon";
@@ -16,7 +17,7 @@ const CENTERED_PADDED_STYLE = {
} as const;
function useFilePanelDescriptor(target: { kind: "file"; path: string }) {
const fileName = target.path.split("/").findLast(Boolean) ?? target.path;
const fileName = fileTabLabel(target.path);
const icon = useMemo(() => createMaterialFileIcon(fileName), [fileName]);
return {
label: fileName,
@@ -60,16 +60,21 @@ export function setPanelInstanceAttributes(
for (const listener of allListeners) listener();
}
/** Calls back when any panel's attributes change. */
export function subscribeAllPanelInstanceAttributes(listener: () => void): () => void {
allListeners.add(listener);
return () => {
allListeners.delete(listener);
};
}
export function useModifiedPanelTabIds(input: {
serverId: string;
workspaceId: string;
tabIds: string[];
}): Set<string> {
const revision = useSyncExternalStore(
useCallback((listener: () => void) => {
allListeners.add(listener);
return () => allListeners.delete(listener);
}, []),
subscribeAllPanelInstanceAttributes,
() => attributesRevision,
() => attributesRevision,
);
+173
View File
@@ -1,3 +1,7 @@
import type { PluginPanelTargetParams } from "@getpaseo/plugin/client";
import { z } from "zod";
import { isAbsolutePath } from "@/utils/path";
import { normalizeWorkspaceTabTarget } from "@/workspace-tabs/identity";
import type { WorkspaceTabTarget } from "@/workspace-tabs/model";
/** Where a tab renders: a split pane, the Explorer dock, or the compact workspace sheet. */
@@ -22,6 +26,26 @@ type CompactSheetRule<K extends WorkspaceTabTarget["kind"]> =
facts: PanelTargetFacts,
) => CompactSheetPolicy | null);
/** What opening a panel by its public identity asks the workspace to do. */
export interface PanelOpenRequest {
target: WorkspaceTabTarget;
/** A workspace-relative path the panel expands to and selects once it shows. */
revealPath?: string;
}
/**
* How plugins name a kind and spell one instance of it. Ids and param names are a published
* contract: add optional params, never rename, narrow or require one.
*/
export interface PanelPublicIdentity<
K extends WorkspaceTabTarget["kind"] = WorkspaceTabTarget["kind"],
> {
publicId: `paseo/${string}`;
toParams(target: Extract<WorkspaceTabTarget, { kind: K }>): PluginPanelTargetParams;
/** Null for params this panel does not accept. */
fromParams(params: PluginPanelTargetParams): PanelOpenRequest | null;
}
export interface PanelManifest<K extends WorkspaceTabTarget["kind"] = WorkspaceTabTarget["kind"]> {
kind: K;
/** The sheet is never listed: a kind renders there exactly when it has a `compactSheet` rule. */
@@ -34,101 +58,219 @@ export interface PanelManifest<K extends WorkspaceTabTarget["kind"] = WorkspaceT
*/
compactSheet: CompactSheetRule<K>;
resourceKey(target: Extract<WorkspaceTabTarget, { kind: K }>): string;
/** One instance, such as an agent's chat or a terminal, never has a second tab. */
oneTabPerInstance: boolean;
/** Null for a kind plugins cannot open. */
public: PanelPublicIdentity<K> | null;
}
type PanelManifestByKind = {
[K in WorkspaceTabTarget["kind"]]: PanelManifest<K>;
};
function publicPanel<K extends WorkspaceTabTarget["kind"], Params>(input: {
publicId: `paseo/${string}`;
params: z.ZodType<Params>;
toRequest(params: Params): PanelOpenRequest;
toParams(target: Extract<WorkspaceTabTarget, { kind: K }>): PluginPanelTargetParams;
}): PanelPublicIdentity<K> {
return {
publicId: input.publicId,
toParams: input.toParams,
fromParams(params) {
const parsed = input.params.safeParse(params);
if (!parsed.success) return null;
const request = input.toRequest(parsed.data);
const target = normalizeWorkspaceTabTarget(request.target);
return target ? { ...request, target } : null;
},
};
}
const noParams = z.strictObject({});
const lineNumber = z.number().int().positive();
const fileParams = z
.strictObject({
path: z.string(),
lineStart: lineNumber.optional(),
lineEnd: lineNumber.optional(),
})
.refine(
({ lineStart, lineEnd }) =>
lineEnd === undefined || (lineStart !== undefined && lineEnd >= lineStart),
);
const filesParams = z.strictObject({
reveal: z
.string()
.transform((path) => path.trim().replace(/\\/g, "/"))
.refine((path) => path.length > 0 && !isAbsolutePath(path) && !path.split("/").includes(".."))
.optional(),
});
const manifests = {
new_tab: {
kind: "new_tab",
supportedHosts: ["main", "explorer"],
showCloseButton: true,
singleton: false,
oneTabPerInstance: false,
compactSheet: null,
resourceKey: () => "new_tab",
public: null,
},
draft: {
kind: "draft",
supportedHosts: ["main", "explorer"],
showCloseButton: true,
singleton: false,
oneTabPerInstance: false,
compactSheet: null,
resourceKey: (target) => target.draftId,
public: null,
},
agent: {
kind: "agent",
supportedHosts: ["main", "explorer"],
showCloseButton: true,
singleton: false,
oneTabPerInstance: true,
compactSheet: (target, facts) =>
facts.isWorkspaceRootAgent(target.agentId) ? null : { openAsTab: true },
resourceKey: (target) => target.agentId,
public: publicPanel<"agent", { agentId: string }>({
publicId: "paseo/agent",
params: z.strictObject({ agentId: z.string() }),
toRequest: ({ agentId }) => ({ target: { kind: "agent", agentId } }),
toParams: ({ agentId }) => ({ agentId }),
}),
},
provider_subagent: {
kind: "provider_subagent",
supportedHosts: ["main", "explorer"],
showCloseButton: true,
singleton: false,
oneTabPerInstance: false,
compactSheet: { openAsTab: false },
resourceKey: (target) => `${target.parentAgentId}:${target.subagentId}`,
public: publicPanel<"provider_subagent", { parentAgentId: string; subagentId: string }>({
publicId: "paseo/subagent",
params: z.strictObject({ parentAgentId: z.string(), subagentId: z.string() }),
toRequest: (params) => ({ target: { kind: "provider_subagent", ...params } }),
toParams: ({ parentAgentId, subagentId }) => ({ parentAgentId, subagentId }),
}),
},
terminal: {
kind: "terminal",
supportedHosts: ["main", "explorer"],
showCloseButton: true,
singleton: false,
oneTabPerInstance: true,
compactSheet: null,
resourceKey: (target) => target.terminalId,
public: publicPanel<"terminal", { terminalId: string }>({
publicId: "paseo/terminal",
params: z.strictObject({ terminalId: z.string() }),
toRequest: ({ terminalId }) => ({ target: { kind: "terminal", terminalId } }),
toParams: ({ terminalId }) => ({ terminalId }),
}),
},
browser: {
kind: "browser",
supportedHosts: ["main"],
showCloseButton: true,
singleton: false,
oneTabPerInstance: true,
compactSheet: null,
resourceKey: (target) => target.browserId,
public: publicPanel<"browser", { browserId: string }>({
publicId: "paseo/browser",
params: z.strictObject({ browserId: z.string() }),
toRequest: ({ browserId }) => ({ target: { kind: "browser", browserId } }),
toParams: ({ browserId }) => ({ browserId }),
}),
},
changes_tree: {
kind: "changes_tree",
supportedHosts: ["explorer"],
showCloseButton: false,
singleton: true,
oneTabPerInstance: true,
compactSheet: null,
resourceKey: () => "changes_tree",
public: publicPanel<"changes_tree", Record<string, never>>({
publicId: "paseo/changes",
params: noParams,
toRequest: () => ({ target: { kind: "changes_tree" } }),
toParams: () => ({}),
}),
},
files: {
kind: "files",
supportedHosts: ["explorer"],
showCloseButton: false,
singleton: true,
oneTabPerInstance: true,
compactSheet: null,
resourceKey: () => "files",
public: publicPanel<"files", { reveal?: string }>({
publicId: "paseo/files",
params: filesParams,
toRequest: ({ reveal }) => ({ target: { kind: "files" }, revealPath: reveal }),
// A reveal is something to do once, not part of which tab this is.
toParams: () => ({}),
}),
},
pull_request: {
kind: "pull_request",
supportedHosts: ["main", "explorer"],
showCloseButton: true,
singleton: false,
oneTabPerInstance: false,
compactSheet: null,
resourceKey: () => "pull_request",
public: publicPanel<"pull_request", Record<string, never>>({
publicId: "paseo/pull-request",
params: noParams,
toRequest: () => ({ target: { kind: "pull_request" } }),
toParams: () => ({}),
}),
},
file: {
kind: "file",
supportedHosts: ["main", "explorer"],
showCloseButton: true,
singleton: false,
oneTabPerInstance: false,
compactSheet: { openAsTab: false },
resourceKey: (target) => target.path,
public: publicPanel<"file", z.infer<typeof fileParams>>({
publicId: "paseo/file",
params: fileParams,
toRequest: (params) => ({ target: { kind: "file", ...params } }),
toParams: ({ path, lineStart, lineEnd }) => ({
path,
...(lineStart ? { lineStart } : {}),
...(lineEnd ? { lineEnd } : {}),
}),
}),
},
working_diff: {
kind: "working_diff",
supportedHosts: ["main", "explorer"],
showCloseButton: true,
singleton: false,
oneTabPerInstance: false,
compactSheet: null,
resourceKey: () => "working_diff",
public: publicPanel<"working_diff", Record<string, never>>({
publicId: "paseo/diff",
params: noParams,
toRequest: () => ({ target: { kind: "working_diff" } }),
toParams: () => ({}),
}),
},
plugin: {
kind: "plugin",
@@ -136,27 +278,39 @@ const manifests = {
supportedHosts: ["main", "explorer"],
showCloseButton: true,
singleton: false,
oneTabPerInstance: false,
compactSheet: null,
resourceKey: (target) =>
target.context === "agent"
? `${target.pluginId}:${target.panelId}:agent:${target.agentId}`
: `${target.pluginId}:${target.panelId}:workspace`,
// Plugin panels are named by their registration, not by this kind.
public: null,
},
setup: {
kind: "setup",
supportedHosts: ["main"],
showCloseButton: true,
singleton: false,
oneTabPerInstance: false,
compactSheet: null,
resourceKey: (target) => target.workspaceId,
public: null,
},
commit_diff: {
kind: "commit_diff",
supportedHosts: ["main", "explorer"],
showCloseButton: true,
singleton: false,
oneTabPerInstance: false,
compactSheet: null,
resourceKey: (target) => target.sha,
public: publicPanel<"commit_diff", { sha: string }>({
publicId: "paseo/commit-diff",
params: z.strictObject({ sha: z.string() }),
toRequest: ({ sha }) => ({ target: { kind: "commit_diff", sha } }),
toParams: ({ sha }) => ({ sha }),
}),
},
} satisfies PanelManifestByKind;
@@ -189,3 +343,22 @@ export function panelResourceKey(target: WorkspaceTabTarget): string {
const manifest = getPanelManifest(target.kind);
return `${target.kind}:${manifest.resourceKey(target as never)}`;
}
/** How plugins read a built-in tab back. A kind they cannot open reads as its kind name. */
export function panelPublicReference(target: Exclude<WorkspaceTabTarget, { kind: "plugin" }>): {
panelId: string;
params: PluginPanelTargetParams;
} {
const identity = getPanelManifest(target.kind).public;
if (!identity) return { panelId: `paseo/${target.kind}`, params: {} };
return { panelId: identity.publicId, params: identity.toParams(target as never) };
}
export function findPublicPanel(publicId: string): PanelPublicIdentity | null {
for (const manifest of Object.values(manifests)) {
if (manifest.public?.publicId === publicId) {
return manifest.public as unknown as PanelPublicIdentity;
}
}
return null;
}
@@ -15,6 +15,7 @@ import type { AgentScreenAgent } from "@/hooks/use-agent-screen-state-machine";
import { usePaneContext } from "@/panels/pane-context";
import { PaneSubtitle } from "@/panels/pane-subtitle";
import { definePanel, type PanelDescriptor } from "@/panels/panel-registry";
import { providerSubagentTabLabel } from "@/panels/tab-labels";
import { useSessionStore } from "@/stores/session-store";
import type { SheetTab } from "@/stores/workspace-layout-store";
import { ParentAgentCallout } from "@/subagents/parent";
@@ -96,9 +97,8 @@ function useProviderSubagentDescriptor(
(state) => state.sessions[context.serverId]?.agents.get(target.parentAgentId)?.provider,
);
const provider = descriptor?.provider ?? parentProvider ?? "agent";
// The task names the tab; the subagent type is supporting detail beside the provider.
const subagentType = descriptor?.title?.trim();
const label = descriptor?.description?.trim() || subagentType || "Subagent";
const label = providerSubagentTabLabel(descriptor);
const providerLabel = `${formatProviderLabel(provider)} subagent`;
return {
label,
+60
View File
@@ -0,0 +1,60 @@
/** Naming rules shared by a tab's React descriptor and the title read outside React. */
/** Null until the agent has a name of its own. */
export function resolveAgentLabel(title: string | null | undefined): string | null {
if (typeof title !== "string") {
return null;
}
const normalized = title.trim();
if (!normalized) {
return null;
}
if (normalized.toLowerCase() === "new agent") {
return null;
}
return normalized;
}
export function terminalTabLabel(
terminal: { title?: string | null; name?: string | null } | null | undefined,
fallback: string,
): string {
return (terminal?.title ?? terminal?.name)?.trim() || fallback;
}
export function browserTabLabel(input: { title: string; url: string }): string {
const title = input.title.trim();
if (title) {
return title;
}
try {
const parsed = new URL(input.url);
return parsed.hostname || input.url;
} catch {
return input.url;
}
}
// The task names the tab; the subagent type is supporting detail.
export function providerSubagentTabLabel(
descriptor: { description?: string | null; title?: string | null } | null | undefined,
): string {
return descriptor?.description?.trim() || descriptor?.title?.trim() || "Subagent";
}
export function draftTabLabel(input: {
isCreating: boolean;
pendingPrompt?: string | null;
newAgentLabel: string;
}): string {
return (input.isCreating && input.pendingPrompt?.trim()) || input.newAgentLabel;
}
export function fileTabLabel(path: string): string {
return path.split("/").findLast(Boolean) ?? path;
}
export function commitDiffTabLabel(sha: string): string {
return sha.slice(0, 7);
}
+141
View File
@@ -0,0 +1,141 @@
import type { ListTerminalsResponse } from "@getpaseo/protocol/messages";
import { queryClient } from "@/data/query-client";
import { useBrowserStore } from "@/desktop/browser/store";
import type { CheckoutPrStatusPayload } from "@/git/pr-status";
import { formatPrTabLabel } from "@/git/pull-request-panel/tab-label";
import { checkoutPrStatusQueryKey } from "@/git/query-keys";
import { i18n } from "@/i18n/i18next";
import {
browserTabLabel,
commitDiffTabLabel,
draftTabLabel,
fileTabLabel,
providerSubagentTabLabel,
resolveAgentLabel,
terminalTabLabel,
} from "@/panels/tab-labels";
import { pluginRegistry } from "@/plugins/registry";
import { resolvePluginWorkspacePanel } from "@/plugins/workspace-panels/resolution";
import { buildTerminalsQueryKey } from "@/screens/workspace/terminals/state";
import { useCreateFlowStore } from "@/stores/create-flow-store";
import { useSessionStore } from "@/stores/session-store";
import { selectWorkspaceDirectory } from "@/stores/session-store-hooks/selectors";
import { providerSubagentKey, useProviderSubagentStore } from "@/subagents/provider-store";
import type { PluginWorkspaceTabTarget, WorkspaceTabTarget } from "@/workspace-tabs/model";
interface TabTitleInput {
serverId: string;
workspaceId: string;
target: WorkspaceTabTarget;
}
/**
* What a tab is called, from what the client already holds. Reads only: a terminal or pull
* request nobody has loaded yet keeps its generic name.
*/
export function readTabTitle({ serverId, workspaceId, target }: TabTitleInput): string {
switch (target.kind) {
case "new_tab":
return i18n.t("workspace.tabs.actions.newTab");
case "draft":
return readDraftTitle(serverId, target.draftId);
case "agent":
return readAgentTitle(serverId, target.agentId);
case "provider_subagent":
return providerSubagentTabLabel(
useProviderSubagentStore
.getState()
.descriptors.get(providerSubagentKey(serverId, target.parentAgentId, target.subagentId)),
);
case "terminal":
return readTerminalTitle(serverId, workspaceId, target.terminalId);
case "browser": {
const browser = useBrowserStore.getState().browsersById[target.browserId];
return browserTabLabel({
title: browser?.title ?? "",
url: browser?.url ?? "https://example.com",
});
}
case "changes_tree":
return i18n.t("panels.diff.changesLabel");
case "files":
return i18n.t("panels.files.label");
case "pull_request":
return readPullRequestTitle(serverId, workspaceId);
case "file":
return fileTabLabel(target.path);
case "working_diff":
return i18n.t("panels.diff.diffLabel");
case "plugin":
return readPluginPanelTitle(serverId, target);
case "setup":
return i18n.t("workspace.setup.descriptor.label");
case "commit_diff":
return commitDiffTabLabel(target.sha);
}
}
/** Calls back whenever a title may read differently. */
export function subscribeTabTitles(listener: () => void): () => void {
i18n.on("languageChanged", listener);
const releases = [
useSessionStore.subscribe(listener),
useCreateFlowStore.subscribe(listener),
useProviderSubagentStore.subscribe(listener),
useBrowserStore.subscribe(listener),
queryClient.getQueryCache().subscribe(listener),
pluginRegistry.subscribe(listener),
() => {
i18n.off("languageChanged", listener);
},
];
return () => {
for (const release of releases) release();
};
}
function readDraftTitle(serverId: string, draftId: string): string {
const pending = useCreateFlowStore.getState().pendingByDraftId[draftId];
return draftTabLabel({
isCreating: pending?.serverId === serverId && pending.lifecycle === "active",
pendingPrompt: pending?.text,
newAgentLabel: i18n.t("panels.draft.newAgent"),
});
}
function readAgentTitle(serverId: string, agentId: string): string {
const session = useSessionStore.getState().sessions[serverId];
const agent = session?.agents.get(agentId) ?? session?.agentDetails.get(agentId);
return resolveAgentLabel(agent?.title) ?? "";
}
function readTerminalTitle(serverId: string, workspaceId: string, terminalId: string): string {
const directory = selectWorkspaceDirectory(useSessionStore.getState(), serverId, workspaceId);
const list = queryClient.getQueryData<ListTerminalsResponse["payload"]>(
buildTerminalsQueryKey(serverId, directory, workspaceId),
);
return terminalTabLabel(
list?.terminals.find((terminal) => terminal.id === terminalId),
i18n.t("workspace.tabs.fallback.terminal"),
);
}
function readPullRequestTitle(serverId: string, workspaceId: string): string {
const directory = selectWorkspaceDirectory(useSessionStore.getState(), serverId, workspaceId);
const payload = queryClient.getQueryData<CheckoutPrStatusPayload>(
checkoutPrStatusQueryKey(serverId, directory ?? ""),
);
const prNumber = payload?.status?.number ?? null;
return prNumber === null ? i18n.t("panels.pullRequest.label") : formatPrTabLabel(prNumber);
}
function readPluginPanelTitle(serverId: string, target: PluginWorkspaceTabTarget): string {
const plugin =
pluginRegistry
.getSnapshot()
.find((candidate) => candidate.serverId === serverId && candidate.id === target.pluginId) ??
null;
const panel = resolvePluginWorkspacePanel(plugin, target);
if (!plugin || !panel) return "Plugin unavailable";
return plugin.i18n.resolve(panel.title, plugin.locale);
}
+2 -11
View File
@@ -10,6 +10,7 @@ import { TerminalPane } from "@/components/terminal-pane";
import { openUrlInWorkspaceBrowser } from "@/desktop/browser/open-url-in-workspace";
import { usePaneContext, usePaneFocus } from "@/panels/pane-context";
import { definePanel, type PanelDescriptor } from "@/panels/panel-registry";
import { terminalTabLabel } from "@/panels/tab-labels";
import { queryClient } from "@/data/query-client";
import { buildTerminalsQueryKey } from "@/screens/workspace/terminals/state";
import { showExplorerSidebar } from "@/workspace-tabs/explorer-sidebar";
@@ -27,14 +28,6 @@ const CENTERED_PADDED_STYLE = {
padding: 16,
} as const;
function trimNonEmpty(value: string | null | undefined): string | null {
if (typeof value !== "string") {
return null;
}
const trimmed = value.trim();
return trimmed.length > 0 ? trimmed : null;
}
function useTerminalPanelDescriptor(
target: { kind: "terminal"; terminalId: string },
context: { serverId: string; workspaceId: string },
@@ -64,9 +57,7 @@ function useTerminalPanelDescriptor(
);
const terminal =
terminalsQuery.data?.terminals.find((entry) => entry.id === target.terminalId) ?? null;
const label =
trimNonEmpty(terminal?.title ?? terminal?.name ?? null) ??
t("workspace.tabs.fallback.terminal");
const label = terminalTabLabel(terminal, t("workspace.tabs.fallback.terminal"));
return {
label,
+3
View File
@@ -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}`);
+1
View File
@@ -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() {} }),
@@ -1,7 +1,6 @@
import type { ReactNode } from "react";
import React, { Component, type ErrorInfo, type ReactNode } from "react";
import { Text } from "react-native";
import { StyleSheet } from "react-native-unistyles";
import { RenderErrorBoundary } from "@/components/render-error-boundary";
interface SurfaceErrorBoundaryProps {
children: ReactNode;
@@ -11,30 +10,42 @@ interface SurfaceErrorBoundaryProps {
renderError?(error: string): ReactNode;
}
export function SurfaceErrorBoundary({
children,
installation,
resetKey,
Surface,
renderError,
}: SurfaceErrorBoundaryProps) {
return (
<RenderErrorBoundary
resetKeys={[installation, resetKey, Surface]}
onError={warnSurfaceRenderFailed}
renderError={renderError ?? renderPluginFailed}
>
{children}
</RenderErrorBoundary>
);
interface SurfaceErrorBoundaryState {
error: string | null;
}
function renderPluginFailed(error: string) {
return <Text style={styles.errorText}>Plugin failed: {error}</Text>;
}
export class SurfaceErrorBoundary extends Component<
SurfaceErrorBoundaryProps,
SurfaceErrorBoundaryState
> {
state: SurfaceErrorBoundaryState = { error: null };
function warnSurfaceRenderFailed(error: unknown, componentStack: string | null | undefined): void {
console.warn("[Plugins] Surface render failed", error, componentStack);
static getDerivedStateFromError(error: unknown): SurfaceErrorBoundaryState {
return { error: error instanceof Error ? error.message : String(error) };
}
componentDidCatch(error: Error, info: ErrorInfo): void {
console.warn("[Plugins] Surface render failed", error, info.componentStack);
}
componentDidUpdate(previous: SurfaceErrorBoundaryProps): void {
if (
this.state.error &&
(previous.installation !== this.props.installation ||
previous.resetKey !== this.props.resetKey ||
previous.Surface !== this.props.Surface)
) {
this.setState({ error: null });
}
}
render() {
if (this.state.error) {
if (this.props.renderError) return this.props.renderError(this.state.error);
return <Text style={styles.errorText}>Plugin failed: {this.state.error}</Text>;
}
return this.props.children;
}
}
const styles = StyleSheet.create((theme) => ({
@@ -82,69 +82,6 @@ describe("plugin timeline projection", () => {
expect(seen).toEqual(["Inspect files"]);
});
it("keeps repeated plugin output IDs distinct across source messages", () => {
const transform: TimelineItemTransform = ({ item }) => [
{
type: "plugin",
id: "part-0",
pluginId: "split",
kind: "part",
version: 1,
data: { text: item.type === "assistant_message" ? item.text : "" },
},
];
const first: StreamItem = {
kind: "assistant_message",
id: "message-1",
text: "Short",
timestamp: new Date("2026-01-01T00:00:00.000Z"),
};
const second: StreamItem = { ...first, id: "message-2", text: "A much longer reply" };
const rows = projectPluginTimelineItems([first, second], transform);
expect(new Set(rows.map((row) => row.id)).size).toBe(2);
expect(rows).toMatchObject([
{ source: { id: "message-1" }, pluginItemId: "part-0", data: { text: "Short" } },
{
source: { id: "message-2" },
pluginItemId: "part-0",
data: { text: "A much longer reply" },
},
]);
const updated = projectPluginTimelineItems(
[{ ...second, text: "Updated reply" }],
transform,
"streaming",
);
expect(updated[0].id).toBe(rows[1].id);
const completed = projectPluginTimelineItems([{ ...second, text: "Final reply" }], transform);
expect(completed[0].id).toBe(rows[1].id);
const prepended = projectPluginTimelineItems(
[{ ...first, id: "older-message" }, first, second],
transform,
);
expect(prepended.slice(1).map((row) => row.id)).toEqual(rows.map((row) => row.id));
});
it("keeps source and output ID separators unambiguous", () => {
const rows = projectPluginTimelineItems(
[
{ ...thought("First"), id: "message/a" },
{ ...thought("Second"), id: "message" },
],
({ sourceId }) => [
{
type: "plugin",
id: sourceId === "message/a" ? "b" : "a/b",
pluginId: "split",
kind: "part",
version: 1,
data: null,
},
],
);
expect(rows[0].id).not.toBe(rows[1].id);
});
it("does not expose mutable tool detail from stream state", () => {
const detail = { type: "read" as const, filePath: "/repo/original.ts" };
const source: StreamItem = {
@@ -189,8 +126,8 @@ describe("plugin timeline projection", () => {
expect(projectPluginTimelineItems([thought("First")], transform)).toMatchObject([
{
kind: "plugin",
id: "inline-thinking/thought-1/0",
source: { kind: "thought", id: "thought-1" },
pluginItemId: "thought-1/0",
data: { text: "First", phase: "streaming" },
},
]);
@@ -277,11 +214,10 @@ describe("plugin timeline projection", () => {
]);
const filtered = projectPluginTimelineItems([source], () => []);
expect(exploded).toMatchObject([
{ source: { id: "thought-1" }, pluginItemId: "thought-1/left" },
{ source: { id: "thought-1" }, pluginItemId: "thought-1/right" },
expect(exploded.map((item) => item.id)).toEqual([
"split/thought-1/left",
"split/thought-1/right",
]);
expect(new Set(exploded.map((item) => item.id)).size).toBe(2);
expect(filtered).toEqual([]);
});
@@ -318,13 +254,13 @@ describe("plugin timeline projection", () => {
expect(projected).toMatchObject([
{
kind: "plugin",
pluginItemId: "assistant-1/text",
id: "genui/assistant-1/text",
timelineCursor: { epoch: "e1", seq: 7 },
turnId: "turn-1",
},
{
kind: "plugin",
pluginItemId: "assistant-1/card",
id: "genui/assistant-1/card",
timelineCursor: { epoch: "e1", seq: 7 },
turnId: "turn-1",
},
@@ -94,9 +94,7 @@ function transformSourceItem(
return transformed.map((pluginItem) => {
const projected: PluginTimelineStreamItem = {
kind: "plugin",
// Output IDs are local to a source item. Encode each part so separators in
// source or output IDs cannot alias another replacement.
id: JSON.stringify([pluginItem.pluginId, item.id, pluginItem.id]),
id: `${pluginItem.pluginId}/${pluginItem.id}`,
source: item,
timestamp: item.timestamp,
pluginId: pluginItem.pluginId,
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);
@@ -29,8 +29,7 @@ import {
type HostRuntimeControllerDeps,
type HostRuntimeStorage,
} from "./host-runtime";
import { replicaPayloadBytes } from "./replica-cache/payload-bytes";
import type { ReplicaRow, ReplicaRowSize, ReplicaRowStore } from "./replica-cache/row-store";
import type { ReplicaRow, ReplicaRowStore } from "./replica-cache/row-store";
import { subscriptionFixture } from "./subscription-fixture";
import { readDesktopManagedLocalCredential } from "@/desktop/daemon/local-credential";
@@ -641,12 +640,12 @@ function createMemoryReplicaRowStore(): ReplicaRowStore {
(!acceptedIds || acceptedIds.has(row.id)),
);
},
readIndex: async () => {
const hosts = new Map<string, ReplicaRowSize[]>();
for (const { serverId, kind, id, payload } of rows.values()) {
const hostRows = hosts.get(serverId) ?? [];
hostRows.push({ serverId, kind, id, bytes: replicaPayloadBytes(payload) });
hosts.set(serverId, hostRows);
readAll: async () => {
const hosts = new Map<string, ReplicaRow[]>();
for (const row of rows.values()) {
const hostRows = hosts.get(row.serverId) ?? [];
hostRows.push(row);
hosts.set(row.serverId, hostRows);
}
return [...hosts].map(([serverId, hostRows]) => ({ serverId, rows: hostRows }));
},
@@ -1,128 +0,0 @@
import { getHeapSnapshot } from "node:v8";
import { describe, expect, it } from "vitest";
import { ReplicaCache } from ".";
import { createSqliteReplicaRowStore, type ReplicaSqliteDriver } from "./row-store-sqlite";
import { createNodeSqliteDriver } from "./row-store-sqlite.test-driver";
// The SQLite store keeps rows in native memory, so any payload string left on the JS heap after a
// write or a cold start is one the cache itself holds on to.
const SERVER_ID = "cached-host";
const OTHER_SERVER_ID = "other-host";
const noLegacyCleanup = { clearLegacyCache: async () => undefined };
function openCache(driver: ReplicaSqliteDriver, maxBytes?: number): ReplicaCache {
const cache = new ReplicaCache(createSqliteReplicaRowStore(driver, 1), {
...noLegacyCleanup,
...(maxBytes ? { maxBytes } : {}),
});
cache.setHosts([SERVER_ID, OTHER_SERVER_ID]);
return cache;
}
function timeline(agentId: string, text: string) {
return {
agentId,
items: [
{
kind: "assistant_message" as const,
id: "message-1",
text,
timestamp: new Date("2026-07-18T08:02:00.000Z"),
timelineCursor: { epoch: "epoch-1", seq: 12 },
},
],
range: { epoch: "epoch-1", startSeq: 1, endSeq: 12 },
hasOlder: false,
};
}
// Built inside a function so the test keeps no reference to the transcript text once committed.
function commitLargeTimeline(cache: ReplicaCache, serverId: string, marker: string): void {
cache.commitTimeline(serverId, "agent-1", timeline("agent-1", marker + "x".repeat(1_000_000)));
}
/** Sizes of serialized payload strings, retained on the JS heap, whose text contains the marker. */
async function retainedPayloadStrings(marker: string): Promise<number[]> {
const chunks: Buffer[] = [];
// Taking a snapshot runs a full garbage collection first.
for await (const chunk of getHeapSnapshot()) chunks.push(chunk as Buffer);
const snapshot = JSON.parse(Buffer.concat(chunks).toString("utf8")) as {
snapshot: { meta: { node_fields: string[]; node_types: [string[]] } };
nodes: number[];
strings: string[];
};
const fields = snapshot.snapshot.meta.node_fields;
const types = snapshot.snapshot.meta.node_types[0];
const typeField = fields.indexOf("type");
const nameField = fields.indexOf("name");
const sizeField = fields.indexOf("self_size");
const sizes: number[] = [];
for (let base = 0; base < snapshot.nodes.length; base += fields.length) {
if (!types[snapshot.nodes[base + typeField]].includes("string")) continue;
const name = snapshot.strings[snapshot.nodes[base + nameField]];
// The transcript text itself starts with the marker; its JSON payload starts with "{".
if (name.startsWith("{") && name.includes(marker)) {
sizes.push(snapshot.nodes[base + sizeField]);
}
}
return sizes;
}
describe("ReplicaCache over SQLite", () => {
it("does not keep written payloads on the JS heap", async () => {
const marker = `written-${crypto.randomUUID()}`;
const cache = openCache(createNodeSqliteDriver());
commitLargeTimeline(cache, SERVER_ID, marker);
await cache.flush();
expect(await retainedPayloadStrings(marker)).toEqual([]);
expect((await cache.readTimeline(SERVER_ID, "agent-1"))?.items[0]).toMatchObject({
text: expect.stringMatching(new RegExp(`^${marker}x{1000000}$`)),
});
}, 60_000);
it("does not load stored payloads onto the JS heap to index a cold start", async () => {
const marker = `stored-${crypto.randomUUID()}`;
const driver = createNodeSqliteDriver();
const writer = openCache(driver);
commitLargeTimeline(writer, SERVER_ID, marker);
await writer.flush();
const cache = openCache(driver);
// The first write indexes every stored row to enforce the budget.
cache.commitTimeline(OTHER_SERVER_ID, "agent-1", timeline("agent-1", "small"));
await cache.flush();
expect(await retainedPayloadStrings(marker)).toEqual([]);
expect(await cache.readTimeline(SERVER_ID, "agent-1")).toBeDefined();
}, 60_000);
it.each([
{ budget: "exactly fits", slack: 0, evicted: false },
{ budget: "is one byte short", slack: -1, evicted: true },
])("enforces the budget in UTF-8 bytes after a cold start when it $budget", async (input) => {
const driver = createNodeSqliteDriver();
const writer = openCache(driver);
writer.commitTimeline(SERVER_ID, "agent-1", timeline("agent-1", "é😀中".repeat(500)));
writer.commitTimeline(OTHER_SERVER_ID, "agent-1", timeline("agent-1", "other"));
await writer.flush();
const storedBytes = await sumStoredPayloadBytes(driver);
const cache = openCache(driver, storedBytes + input.slack);
// Same size as the stored row, so the projected total stays at the stored total.
cache.commitTimeline(OTHER_SERVER_ID, "agent-1", timeline("agent-1", "OTHER"));
await cache.flush();
expect((await cache.readTimeline(SERVER_ID, "agent-1")) === undefined).toBe(input.evicted);
expect((await cache.readTimeline(OTHER_SERVER_ID, "agent-1"))?.items[0]).toMatchObject({
text: "OTHER",
});
});
});
async function sumStoredPayloadBytes(driver: ReplicaSqliteDriver): Promise<number> {
const connection = await driver.open();
const rows = await connection.all<{ payload: string }>("SELECT payload FROM rows");
return rows.reduce((total, row) => total + Buffer.byteLength(row.payload, "utf8"), 0);
}
@@ -13,14 +13,7 @@ import {
} from "@/plugins/client-state/snapshots";
import { ReplicaCache } from ".";
import type { DirectoryCheckpoint } from "@/runtime/replica-cache";
import { replicaPayloadBytes } from "./payload-bytes";
import type {
ReplicaHostIndex,
ReplicaRow,
ReplicaRowChanges,
ReplicaRowSize,
ReplicaRowStore,
} from "./row-store";
import type { ReplicaHostRows, ReplicaRow, ReplicaRowChanges, ReplicaRowStore } from "./row-store";
const SERVER_ID = "cached-host";
@@ -48,8 +41,8 @@ class MemoryStorage implements ReplicaRowStore {
onRead: (() => void) | null = null;
/** Throws once a read goes past this count, so a non-terminating read loop fails the test. */
readLimit: number | null = null;
/** Awaited before the store indexes every row or deletes a host, so a test can interleave there. */
beforeReadIndex: (() => Promise<void>) | null = null;
/** Awaited before the store lists every row or deletes a host, so a test can interleave there. */
beforeReadAll: (() => Promise<void>) | null = null;
beforeDeleteHost: (() => Promise<void>) | null = null;
private key(row: Pick<ReplicaRow, "serverId" | "kind" | "id">): string {
@@ -81,13 +74,13 @@ class MemoryStorage implements ReplicaRowStore {
);
}
async readIndex(): Promise<ReplicaHostIndex[]> {
await this.beforeReadIndex?.();
const hosts = new Map<string, ReplicaRowSize[]>();
for (const { serverId, kind, id, payload } of this.rows.values()) {
const rows = hosts.get(serverId) ?? [];
rows.push({ serverId, kind, id, bytes: replicaPayloadBytes(payload) });
hosts.set(serverId, rows);
async readAll(): Promise<ReplicaHostRows[]> {
await this.beforeReadAll?.();
const hosts = new Map<string, ReplicaRow[]>();
for (const row of this.rows.values()) {
const rows = hosts.get(row.serverId) ?? [];
rows.push(row);
hosts.set(row.serverId, rows);
}
return [...hosts].map(([serverId, rows]) => ({ serverId, rows }));
}
@@ -1150,7 +1143,7 @@ describe("ReplicaCache", () => {
).toEqual(["agent", "checkpoint", "project", "workspace"]);
});
it.each(["beforeReadIndex", "beforeDeleteHost"] as const)(
it.each(["beforeReadAll", "beforeDeleteHost"] as const)(
"stores no checkpoint for a host evicted after its update was queued (%s)",
async (pausePoint) => {
const storage = new MemoryStorage();
+37 -33
View File
@@ -27,14 +27,12 @@ import {
import type { UnsettledTurn } from "@/timeline/turn-liveness";
import { normalizeAgentSnapshot } from "@/utils/agent-snapshots";
import { clearLegacyReplicaCache } from "./legacy-cleanup";
import { replicaPayloadBytes } from "./payload-bytes";
import {
REPLICA_SINGLETON_ROW_ID,
type ReplicaRow,
type ReplicaRowChanges,
type ReplicaRowKey,
type ReplicaRowKind,
type ReplicaRowSize,
type ReplicaRowStore,
} from "./row-store";
@@ -871,27 +869,31 @@ function pendingRowKey(key: ReplicaRowKey): string {
return `${key.serverId}\u0000${rowKey(key)}`;
}
// A write is sized twice, once to fit the budget and once when it is stored. Sizing walks the
// whole payload, so each written row is measured once.
const writtenRowSizes = new WeakMap<ReplicaRow, ReplicaRowSize>();
// Budget accounting runs over every stored row of a touched host on each persist. Rows are
// immutable once stored, so their size is computed once. The count itself avoids the JS Buffer
// polyfill, which materialises the whole byte array just to measure it.
const rowBytesCache = new WeakMap<ReplicaRow, number>();
function rowSize(row: ReplicaRow): ReplicaRowSize {
let size = writtenRowSizes.get(row);
if (!size) {
size = {
serverId: row.serverId,
kind: row.kind,
id: row.id,
bytes: replicaPayloadBytes(row.payload),
};
writtenRowSizes.set(row, size);
function utf8ByteLength(text: string): number {
let bytes = 0;
for (let index = 0; index < text.length; index += 1) {
const code = text.charCodeAt(index);
if (code < 0x80) bytes += 1;
else if (code < 0x800) bytes += 2;
else if (code >= 0xd800 && code <= 0xdbff) {
bytes += 4;
index += 1;
} else bytes += 3;
}
return size;
return bytes;
}
function sumBytes(rows: Iterable<ReplicaRowSize>): number {
let bytes = 0;
for (const row of rows) bytes += row.bytes;
function rowBytes(row: ReplicaRow): number {
let bytes = rowBytesCache.get(row);
if (bytes === undefined) {
bytes = utf8ByteLength(row.payload);
rowBytesCache.set(row, bytes);
}
return bytes;
}
@@ -978,8 +980,7 @@ function matchesReplicaRead(read: ReplicaRead, row: ReplicaRowKey): boolean {
export class ReplicaCache {
private readonly activeServerIds = new Set<string>();
private readonly activeReads = new Set<ReplicaRead>();
// Key and size of every stored row, by host. Payloads stay in the row store.
private readonly storedRows = new Map<string, Map<string, ReplicaRowSize>>();
private readonly storedRows = new Map<string, Map<string, ReplicaRow>>();
private readonly hostBytes = new Map<string, number>();
private readonly hostWriteOrder = new Map<string, true>();
private pendingUpserts = new Map<string, StructuredReplicaUpsert>();
@@ -1282,13 +1283,13 @@ export class ReplicaCache {
this.invalidateHostReads(newServerId);
const rows = this.storedRows.get(oldServerId);
if (rows) {
const newRows = this.storedRows.get(newServerId) ?? new Map<string, ReplicaRowSize>();
const newRows = this.storedRows.get(newServerId) ?? new Map<string, ReplicaRow>();
this.totalBytes -=
(this.hostBytes.get(oldServerId) ?? 0) + (this.hostBytes.get(newServerId) ?? 0);
this.storedRows.delete(oldServerId);
for (const [key, row] of rows) newRows.set(key, { ...row, serverId: newServerId });
this.storedRows.set(newServerId, newRows);
const bytes = sumBytes(newRows.values());
const bytes = [...newRows.values()].reduce((sum, row) => sum + rowBytes(row), 0);
this.hostBytes.delete(oldServerId);
this.hostBytes.set(newServerId, bytes);
this.totalBytes += bytes;
@@ -1528,17 +1529,17 @@ export class ReplicaCache {
const previous = rows?.get(rowKey(key));
if (previous) {
rows?.delete(rowKey(key));
this.adjustHostBytes(key.serverId, -previous.bytes);
this.adjustHostBytes(key.serverId, -rowBytes(previous));
}
touchedServerIds.add(key.serverId);
}
for (const row of changes.upserts) {
const rows = this.storedRows.get(row.serverId) ?? new Map<string, ReplicaRowSize>();
const rows = this.storedRows.get(row.serverId) ?? new Map<string, ReplicaRow>();
const previous = rows.get(rowKey(row));
const size = rowSize(row);
rows.set(rowKey(row), size);
const previousBytes = previous ? rowBytes(previous) : 0;
rows.set(rowKey(row), row);
this.storedRows.set(row.serverId, rows);
this.adjustHostBytes(row.serverId, size.bytes - (previous?.bytes ?? 0));
this.adjustHostBytes(row.serverId, rowBytes(row) - previousBytes);
touchedServerIds.add(row.serverId);
}
for (const serverId of touchedServerIds) {
@@ -1567,7 +1568,7 @@ export class ReplicaCache {
for (const key of changes.deletes) touchedServerIds.add(key.serverId);
for (const row of changes.upserts) touchedServerIds.add(row.serverId);
const projectedRows = new Map<string, Map<string, ReplicaRowSize>>();
const projectedRows = new Map<string, Map<string, ReplicaRow>>();
const projectedBytes = new Map(this.hostBytes);
for (const serverId of touchedServerIds) {
projectedRows.set(serverId, new Map(this.storedRows.get(serverId)));
@@ -1576,10 +1577,13 @@ export class ReplicaCache {
projectedRows.get(key.serverId)?.delete(rowKey(key));
}
for (const row of changes.upserts) {
projectedRows.get(row.serverId)?.set(rowKey(row), rowSize(row));
projectedRows.get(row.serverId)?.set(rowKey(row), row);
}
for (const [serverId, rows] of projectedRows) {
projectedBytes.set(serverId, sumBytes(rows.values()));
projectedBytes.set(
serverId,
[...rows.values()].reduce((sum, row) => sum + rowBytes(row), 0),
);
}
const writeOrder = [...this.hostWriteOrder.keys()].filter(
@@ -1652,7 +1656,7 @@ export class ReplicaCache {
}
private ensureStoredIndex(): Promise<void> {
this.storedIndexPromise ??= this.rowStore.readIndex().then(async (hosts) => {
this.storedIndexPromise ??= this.rowStore.readAll().then(async (hosts) => {
this.storedRows.clear();
this.hostBytes.clear();
this.hostWriteOrder.clear();
@@ -1663,7 +1667,7 @@ export class ReplicaCache {
continue;
}
const rows = new Map(host.rows.map((row) => [rowKey(row), row]));
const bytes = sumBytes(host.rows);
const bytes = host.rows.reduce((sum, row) => sum + rowBytes(row), 0);
this.storedRows.set(host.serverId, rows);
this.hostBytes.set(host.serverId, bytes);
this.totalBytes += bytes;
@@ -1,15 +0,0 @@
// The size the row stores report for a payload. Counting avoids the JS Buffer polyfill, which
// materialises the whole byte array just to measure it.
export function replicaPayloadBytes(payload: string): number {
let bytes = 0;
for (let index = 0; index < payload.length; index += 1) {
const code = payload.charCodeAt(index);
if (code < 0x80) bytes += 1;
else if (code < 0x800) bytes += 2;
else if (code >= 0xd800 && code <= 0xdbff) {
bytes += 4;
index += 1;
} else bytes += 3;
}
return bytes;
}
@@ -1,37 +0,0 @@
import { DatabaseSync, type SQLInputValue } from "node:sqlite";
import type { ReplicaSqliteConnection, ReplicaSqliteDriver, SqliteValue } from "./row-store-sqlite";
/** Test driver over Node's built-in SQLite. Rows live in native memory, outside the JS heap. */
export function createNodeSqliteDriver(): ReplicaSqliteDriver {
const database = new DatabaseSync(":memory:");
function connection(): ReplicaSqliteConnection {
return {
async exec(sql) {
database.exec(sql);
},
async run(sql, params = []) {
database.prepare(sql).run(...(params as SQLInputValue[]));
},
async all<Row>(sql: string, params: readonly SqliteValue[] = []) {
return database.prepare(sql).all(...(params as SQLInputValue[])) as Row[];
},
async transaction(operation) {
database.exec("BEGIN IMMEDIATE");
try {
await operation(connection());
database.exec("COMMIT");
} catch (error) {
database.exec("ROLLBACK");
throw error;
}
},
};
}
return {
async open() {
return connection();
},
};
}
@@ -1,10 +1,4 @@
import type {
ReplicaHostIndex,
ReplicaRow,
ReplicaRowChanges,
ReplicaRowSize,
ReplicaRowStore,
} from "./row-store";
import type { ReplicaHostRows, ReplicaRow, ReplicaRowChanges, ReplicaRowStore } from "./row-store";
export type SqliteValue = string | number | null;
@@ -40,13 +34,6 @@ interface StoredMeta {
value: string;
}
interface StoredRowSize {
server_id: string;
kind: ReplicaRow["kind"];
id: string;
bytes: number;
}
interface StoredRow {
server_id: string;
kind: ReplicaRow["kind"];
@@ -102,20 +89,18 @@ export function createSqliteReplicaRowStore(
}
}
async function readIndex(): Promise<ReplicaHostIndex[]> {
// The database stores text as UTF-8, so the blob length is the payload's UTF-8 size.
const storedRows = await getConnection().all<StoredRowSize>(
`SELECT server_id, kind, id, length(CAST(payload AS BLOB)) AS bytes FROM rows
ORDER BY server_id, kind, id`,
async function readAll(): Promise<ReplicaHostRows[]> {
const storedRows = await getConnection().all<StoredRow>(
"SELECT server_id, kind, id, payload FROM rows ORDER BY server_id, kind, id",
);
const hosts = new Map<string, ReplicaRowSize[]>();
const hosts = new Map<string, ReplicaRow[]>();
for (const storedRow of storedRows) {
const rows = hosts.get(storedRow.server_id) ?? [];
rows.push({
serverId: storedRow.server_id,
kind: storedRow.kind,
id: storedRow.id,
bytes: storedRow.bytes,
payload: storedRow.payload,
});
hosts.set(storedRow.server_id, rows);
}
@@ -184,5 +169,5 @@ export function createSqliteReplicaRowStore(
await getConnection().run("DELETE FROM rows");
}
return { open, read, readIndex, apply, deleteHost, renameHost, clear };
return { open, read, readAll, apply, deleteHost, renameHost, clear };
}
@@ -8,23 +8,6 @@ export interface ReplicaRowStoreHarness {
export type CreateReplicaRowStoreHarness = () => Promise<ReplicaRowStoreHarness>;
const ALL_KINDS: ReplicaRow["kind"][] = ["agent", "checkpoint", "project", "timeline", "workspace"];
interface ReplicaHostRows {
serverId: string;
rows: ReplicaRow[];
}
async function readEveryRow(store: ReplicaRowStore): Promise<ReplicaHostRows[]> {
const hosts = await store.readIndex();
return Promise.all(
hosts.map(async (host) => ({
serverId: host.serverId,
rows: await store.read(host.serverId, ALL_KINDS),
})),
);
}
function row(serverId: string, kind: ReplicaRow["kind"], id: string, payload: string): ReplicaRow {
return { serverId, kind, id, payload };
}
@@ -44,7 +27,7 @@ export function runReplicaRowStoreContract(
});
it("reads an empty store", async () => {
expect(await readEveryRow(store)).toEqual([]);
expect(await store.readAll()).toEqual([]);
});
it("round-trips opaque payloads grouped by server", async () => {
@@ -57,7 +40,7 @@ export function runReplicaRowStoreContract(
deletes: [],
});
expect(await readEveryRow(store)).toEqual([
expect(await store.readAll()).toEqual([
{
serverId: "server-a",
rows: [
@@ -98,7 +81,7 @@ export function runReplicaRowStoreContract(
deletes: [],
});
expect(await readEveryRow(store)).toEqual([
expect(await store.readAll()).toEqual([
{
serverId: "server-a",
rows: [row("server-a", "agent", "agent-1", "new")],
@@ -119,7 +102,7 @@ export function runReplicaRowStoreContract(
deletes: [{ serverId: "server-a", kind: "agent", id: "same-id" }],
});
expect(await readEveryRow(store)).toEqual([
expect(await store.readAll()).toEqual([
{
serverId: "server-a",
rows: [row("server-a", "workspace", "same-id", "workspace")],
@@ -139,7 +122,7 @@ export function runReplicaRowStoreContract(
deletes: [],
}),
).rejects.toBeInstanceOf(Error);
expect(await readEveryRow(store)).toEqual([]);
expect(await store.readAll()).toEqual([]);
});
it("deletes every row belonging to one host", async () => {
@@ -154,7 +137,7 @@ export function runReplicaRowStoreContract(
await store.deleteHost("server-a");
expect(await readEveryRow(store)).toEqual([
expect(await store.readAll()).toEqual([
{ serverId: "server-b", rows: [row("server-b", "agent", "agent-2", "b")] },
]);
});
@@ -172,7 +155,7 @@ export function runReplicaRowStoreContract(
await store.renameHost("temporary", "canonical");
expect(await readEveryRow(store)).toEqual([
expect(await store.readAll()).toEqual([
{
serverId: "canonical",
rows: [
@@ -195,67 +178,7 @@ export function runReplicaRowStoreContract(
await store.clear();
expect(await readEveryRow(store)).toEqual([]);
});
it("indexes every row by key and UTF-8 payload size, without payloads", async () => {
await store.apply({
upserts: [
row("server-b", "checkpoint", "singleton", '{"cursor":2}'),
row("server-a", "timeline", "agent-1", "é😀中a"),
row("server-a", "agent", "agent-1", "ascii"),
],
deletes: [],
});
expect(await store.readIndex()).toEqual([
{
serverId: "server-a",
rows: [
{ serverId: "server-a", kind: "agent", id: "agent-1", bytes: 5 },
{ serverId: "server-a", kind: "timeline", id: "agent-1", bytes: 10 },
],
},
{
serverId: "server-b",
rows: [{ serverId: "server-b", kind: "checkpoint", id: "singleton", bytes: 12 }],
},
]);
});
it("keeps indexed sizes in step with overwrites, deletes, directory writes, and renames", async () => {
await store.apply({
upserts: [
row("temporary", "agent", "agent-1", "x".repeat(40)),
row("temporary", "timeline", "agent-1", "short"),
],
deletes: [],
});
await store.apply(
{
upserts: [
row("temporary", "agent", "agent-1", "ü".repeat(3)),
row("temporary", "checkpoint", "singleton", '{"a":1}'),
],
deletes: [{ serverId: "temporary", kind: "timeline", id: "agent-1" }],
},
{ directoryBaselines: new Set(["temporary"]) },
);
await store.renameHost("temporary", "canonical");
expect(await store.readIndex()).toEqual([
{
serverId: "canonical",
rows: [
{ serverId: "canonical", kind: "agent", id: "agent-1", bytes: 6 },
{ serverId: "canonical", kind: "checkpoint", id: "singleton", bytes: 7 },
],
},
]);
expect(await store.read("canonical", ["agent", "checkpoint"])).toEqual([
row("canonical", "agent", "agent-1", "ü".repeat(3)),
row("canonical", "checkpoint", "singleton", '{"a":1}'),
]);
expect(await store.readAll()).toEqual([]);
});
it("wipes cached rows when the schema version changes on open", async () => {
@@ -266,7 +189,7 @@ export function runReplicaRowStoreContract(
const upgradedStore = await harness.openWithSchemaVersion(2);
expect(await readEveryRow(upgradedStore)).toEqual([]);
expect(await upgradedStore.readAll()).toEqual([]);
});
});
}
@@ -1,6 +1,45 @@
import { DatabaseSync, type SQLInputValue } from "node:sqlite";
import { runReplicaRowStoreContract } from "./row-store.contract";
import { createSqliteReplicaRowStore } from "./row-store-sqlite";
import { createNodeSqliteDriver } from "./row-store-sqlite.test-driver";
import {
createSqliteReplicaRowStore,
type ReplicaSqliteConnection,
type ReplicaSqliteDriver,
type SqliteValue,
} from "./row-store-sqlite";
function createNodeSqliteDriver(): ReplicaSqliteDriver {
const database = new DatabaseSync(":memory:");
function connection(): ReplicaSqliteConnection {
return {
async exec(sql) {
database.exec(sql);
},
async run(sql, params = []) {
database.prepare(sql).run(...(params as SQLInputValue[]));
},
async all<Row>(sql: string, params: readonly SqliteValue[] = []) {
return database.prepare(sql).all(...(params as SQLInputValue[])) as Row[];
},
async transaction(operation) {
database.exec("BEGIN IMMEDIATE");
try {
await operation(connection());
database.exec("COMMIT");
} catch (error) {
database.exec("ROLLBACK");
throw error;
}
},
};
}
return {
async open() {
return connection();
},
};
}
runReplicaRowStoreContract("SQLite", async () => {
const driver = createNodeSqliteDriver();
@@ -9,12 +9,11 @@ import {
} from "./row-store-sqlite";
export type {
ReplicaHostIndex,
ReplicaHostRows,
ReplicaRow,
ReplicaRowChanges,
ReplicaRowKey,
ReplicaRowKind,
ReplicaRowSize,
ReplicaRowStore,
} from "./row-store";
export { REPLICA_ROW_STORE_SCHEMA_VERSION, REPLICA_SINGLETON_ROW_ID } from "./row-store-schema";
@@ -23,15 +23,9 @@ export interface ReplicaRowApplyOptions {
directoryBaselines?: ReadonlySet<string>;
}
// What a stored row costs without its payload: the cache budgets on this and never holds payloads.
export interface ReplicaRowSize extends ReplicaRowKey {
// UTF-8 byte length of the payload.
bytes: number;
}
export interface ReplicaHostIndex {
export interface ReplicaHostRows {
serverId: string;
rows: ReplicaRowSize[];
rows: ReplicaRow[];
}
export interface ReplicaRowStore {
@@ -41,8 +35,7 @@ export interface ReplicaRowStore {
kinds: readonly ReplicaRowKind[],
ids?: readonly string[],
): Promise<ReplicaRow[]>;
// Every stored row's key and payload size, grouped by host, read without loading payloads.
readIndex(): Promise<ReplicaHostIndex[]>;
readAll(): Promise<ReplicaHostRows[]>;
// Shared stores can reject directory deltas that no longer match their baseline.
// Return the accepted changes when they differ from the requested changes.
apply(
@@ -49,29 +49,3 @@ it("uses exact IndexedDB keys for targeted rows instead of scanning the host", a
get.mockRestore();
getAll.mockRestore();
});
it("drops rows stored before payload sizes were indexed, so none escape the budget", async () => {
const databaseName = `replica-row-store-unsized-${databaseSequence++}`;
await new Promise<void>((resolve, reject) => {
// The store's first on-disk shape: rows without a recorded payload size.
const request = fakeIndexedDb.open(databaseName, 1);
request.addEventListener("upgradeneeded", () => {
const rows = request.result.createObjectStore("rows", {
keyPath: ["serverId", "kind", "id"],
});
request.result.createObjectStore("meta").put(1, "schema_version");
rows.put({ serverId: "server-a", kind: "timeline", id: "agent-1", payload: "unsized" });
});
request.addEventListener("success", () => {
request.result.close();
resolve();
});
request.addEventListener("error", () => reject(request.error));
});
const store = createIndexedDbReplicaRowStore({ databaseName, schemaVersion: 1 });
await store.open();
expect(await store.readIndex()).toEqual([]);
expect(await store.read("server-a", ["timeline"])).toEqual([]);
});
@@ -1,62 +1,38 @@
import { replicaPayloadBytes } from "./payload-bytes";
import type {
ReplicaHostIndex,
ReplicaHostRows,
ReplicaRow,
ReplicaRowApplyOptions,
ReplicaRowChanges,
ReplicaRowKind,
ReplicaRowSize,
ReplicaRowStore,
} from "./row-store";
import { REPLICA_ROW_STORE_SCHEMA_VERSION, REPLICA_SINGLETON_ROW_ID } from "./row-store-schema";
export type {
ReplicaHostIndex,
ReplicaHostRows,
ReplicaRow,
ReplicaRowChanges,
ReplicaRowKey,
ReplicaRowKind,
ReplicaRowSize,
ReplicaRowStore,
} from "./row-store";
export { REPLICA_ROW_STORE_SCHEMA_VERSION, REPLICA_SINGLETON_ROW_ID } from "./row-store-schema";
const DATABASE_NAME = "paseo-replica-row-store";
const DATABASE_VERSION = 2;
const DATABASE_VERSION = 1;
const ROWS_STORE = "rows";
const PAYLOAD_BYTES_INDEX = "payloadBytes";
const META_STORE = "meta";
const SCHEMA_VERSION_KEY = "schema_version";
const DIRECTORY_KINDS = ["agent", "checkpoint", "project", "workspace"] as const;
interface IndexedDbReplicaRow extends ReplicaRow {
// Indexed, so the size index can be read with a key cursor that never loads payloads.
payloadBytes: number;
directoryRevision?: string;
}
function toStoredRow(row: ReplicaRow, directoryRevision: string | undefined): IndexedDbReplicaRow {
return {
serverId: row.serverId,
kind: row.kind,
id: row.id,
payload: row.payload,
payloadBytes: replicaPayloadBytes(row.payload),
...(directoryRevision ? { directoryRevision } : {}),
};
}
function toReplicaRow(row: IndexedDbReplicaRow): ReplicaRow {
function withoutDirectoryRevision(row: IndexedDbReplicaRow): ReplicaRow {
if (row.directoryRevision === undefined) return row;
return { serverId: row.serverId, kind: row.kind, id: row.id, payload: row.payload };
}
function compareRowKeys(left: ReplicaRowSize, right: ReplicaRowSize): number {
if (left.serverId !== right.serverId) return left.serverId < right.serverId ? -1 : 1;
if (left.kind !== right.kind) return left.kind < right.kind ? -1 : 1;
if (left.id !== right.id) return left.id < right.id ? -1 : 1;
return 0;
}
interface IndexedDbReplicaRowStoreOptions {
databaseName: string;
schemaVersion: number;
@@ -108,14 +84,8 @@ async function openDatabase(databaseName: string): Promise<IDBDatabase> {
return new Promise((resolve, reject) => {
const request = indexedDB.open(databaseName, DATABASE_VERSION);
request.addEventListener("upgradeneeded", () => {
const rows = request.result.objectStoreNames.contains(ROWS_STORE)
? request.transaction!.objectStore(ROWS_STORE)
: request.result.createObjectStore(ROWS_STORE, { keyPath: ["serverId", "kind", "id"] });
if (!rows.indexNames.contains(PAYLOAD_BYTES_INDEX)) {
// Rows stored before sizes were recorded would be missing from the index. The cache
// refills from the daemon.
rows.clear();
rows.createIndex(PAYLOAD_BYTES_INDEX, "payloadBytes");
if (!request.result.objectStoreNames.contains(ROWS_STORE)) {
request.result.createObjectStore(ROWS_STORE, { keyPath: ["serverId", "kind", "id"] });
}
if (!request.result.objectStoreNames.contains(META_STORE)) {
request.result.createObjectStore(META_STORE);
@@ -174,34 +144,17 @@ export function createIndexedDbReplicaRowStore(
}
}
async function readIndex(): Promise<ReplicaHostIndex[]> {
async function readAll(): Promise<ReplicaHostRows[]> {
const transaction = getDatabase().transaction(ROWS_STORE, "readonly");
const completion = transactionComplete(transaction);
const rows: ReplicaRowSize[] = [];
await new Promise<void>((resolve, reject) => {
const request = transaction
.objectStore(ROWS_STORE)
.index(PAYLOAD_BYTES_INDEX)
.openKeyCursor();
request.addEventListener("success", () => {
const cursor = request.result;
if (!cursor) {
resolve();
return;
}
const [serverId, kind, id] = cursor.primaryKey as [string, ReplicaRowKind, string];
rows.push({ serverId, kind, id, bytes: cursor.key as number });
cursor.continue();
});
request.addEventListener("error", () =>
reject(request.error ?? new Error("Replica row store index read failed")),
);
});
const rows = await requestResult<IndexedDbReplicaRow[]>(
transaction.objectStore(ROWS_STORE).getAll(),
);
await completion;
const hosts = new Map<string, ReplicaRowSize[]>();
for (const row of rows.sort(compareRowKeys)) {
const hosts = new Map<string, ReplicaRow[]>();
for (const row of rows) {
const hostRows = hosts.get(row.serverId) ?? [];
hostRows.push(row);
hostRows.push(withoutDirectoryRevision(row));
hosts.set(row.serverId, hostRows);
}
return Array.from(hosts, ([serverId, hostRows]) => ({ serverId, rows: hostRows }));
@@ -239,7 +192,7 @@ export function createIndexedDbReplicaRowStore(
observeDirectoryRevision(serverId, checkpoint?.directoryRevision);
}
return rows
.map(toReplicaRow)
.map(withoutDirectoryRevision)
.sort((left, right) =>
left.kind === right.kind
? left.id.localeCompare(right.id)
@@ -269,7 +222,7 @@ export function createIndexedDbReplicaRowStore(
for (const row of accepted.upserts) {
const directoryRevision =
row.kind === "checkpoint" ? nextRevisions.get(row.serverId) : undefined;
await requestResult(rows.put(toStoredRow(row, directoryRevision)));
await requestResult(rows.put(directoryRevision ? { ...row, directoryRevision } : row));
}
});
for (const [serverId, revision] of nextRevisions) observeDirectoryRevision(serverId, revision);
@@ -355,7 +308,7 @@ export function createIndexedDbReplicaRowStore(
await runTransaction(getDatabase(), ROWS_STORE, async (transaction) => {
const rows = transaction.objectStore(ROWS_STORE);
const range = IDBKeyRange.bound([oldServerId], [oldServerId, []]);
const oldRows = await requestResult<IndexedDbReplicaRow[]>(rows.getAll(range));
const oldRows = await requestResult<ReplicaRow[]>(rows.getAll(range));
for (const row of oldRows) {
await requestResult(rows.put({ ...row, serverId: newServerId }));
await requestResult(rows.delete([row.serverId, row.kind, row.id]));
@@ -374,7 +327,7 @@ export function createIndexedDbReplicaRowStore(
});
}
return { open, read, readIndex, apply, deleteHost, renameHost, clear };
return { open, read, readAll, apply, deleteHost, renameHost, clear };
}
export function createReplicaRowStore(): ReplicaRowStore {
@@ -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
@@ -1,131 +0,0 @@
/**
* @vitest-environment jsdom
*/
import { act } from "@testing-library/react";
import React from "react";
import { createRoot, type Root } from "react-dom/client";
import { Text, View } from "react-native";
import { afterEach, describe, expect, it, vi } from "vitest";
import { definePanel, registerPanel } from "@/panels/panel-registry";
import { buildWorkspacePaneContentModel } from "@/screens/workspace/workspace-pane-content";
import { WorkspacePanelHost } from "@/screens/workspace/workspace-panel-host";
import type { WorkspaceTabDescriptor } from "@/screens/workspace/workspace-tabs-types";
let panelFails = true;
function FailingPanel() {
if (panelFails) throw new Error("Changes exploded");
return <Text>Changes recovered</Text>;
}
function HealthyPanel() {
return <Text>Draft panel</Text>;
}
// The workspace screen registers the real panels; these stand in for the two kinds the test opens.
registerPanel(
definePanel("agent", {
component: FailingPanel,
useDescriptor: () => {
throw new Error("The test panel has no descriptor");
},
}),
);
registerPanel(
definePanel("draft", {
component: HealthyPanel,
useDescriptor: () => {
throw new Error("The test panel has no descriptor");
},
}),
);
const failingTab: WorkspaceTabDescriptor = {
key: "agent_agent-a",
tabId: "agent_agent-a",
kind: "agent",
target: { kind: "agent", agentId: "agent-a" },
};
const healthyTab: WorkspaceTabDescriptor = {
key: "draft_draft-a",
tabId: "draft_draft-a",
kind: "draft",
target: { kind: "draft", draftId: "draft-a" },
};
function buildContent({ tab }: { paneId: string; tab: WorkspaceTabDescriptor }) {
return buildWorkspacePaneContentModel({
tab,
normalizedServerId: "server-a",
normalizedWorkspaceId: "workspace-a",
host: "main",
onOpenTab: vi.fn(),
onOpenPreferredTarget: vi.fn(),
onOpenTargetToSide: vi.fn(),
onCloseCurrentTab: vi.fn(),
onRetargetCurrentTab: vi.fn(),
onSetCurrentTabState: vi.fn(),
onOpenWorkspaceFile: vi.fn(),
onOpenImportSheet: vi.fn(),
});
}
function Workspace({ activeTabId }: { activeTabId: string }) {
return (
<View>
<Text>Sidebar</Text>
<WorkspacePanelHost
paneId="pane-a"
tabs={[failingTab, healthyTab]}
activeTabId={activeTabId}
normalizedServerId="server-a"
normalizedWorkspaceId="workspace-a"
isWorkspaceFocused
isPaneFocused
buildPaneContentModel={buildContent}
/>
</View>
);
}
function byTestId(container: HTMLElement, testID: string): HTMLElement | null {
return container.querySelector(`[data-testid="${testID}"]`);
}
describe("WorkspacePanelHost", () => {
let root: Root | null = null;
let container: HTMLElement | null = null;
afterEach(() => {
if (root) act(() => root?.unmount());
root = null;
container?.remove();
container = null;
panelFails = true;
vi.restoreAllMocks();
});
it("keeps a panel's render error inside that panel and retries it", () => {
vi.spyOn(console, "error").mockImplementation(() => undefined);
vi.spyOn(console, "warn").mockImplementation(() => undefined);
container = document.createElement("div");
document.body.appendChild(container);
root = createRoot(container);
act(() => root?.render(<Workspace activeTabId={failingTab.tabId} />));
expect(container.textContent).toContain("Sidebar");
expect(byTestId(container, "panel-render-error")?.textContent).toContain("Changes exploded");
act(() => root?.render(<Workspace activeTabId={healthyTab.tabId} />));
expect(container.textContent).toContain("Draft panel");
panelFails = false;
act(() => root?.render(<Workspace activeTabId={failingTab.tabId} />));
const retry = byTestId(container, "panel-render-error-retry");
expect(retry).not.toBeNull();
act(() => retry?.click());
expect(byTestId(container, "panel-render-error")).toBeNull();
expect(container.textContent).toContain("Changes recovered");
expect(container.textContent).toContain("Sidebar");
});
});
@@ -1,11 +1,5 @@
import { memo, useCallback, useEffect, useMemo, useRef } from "react";
import { useTranslation } from "react-i18next";
import { View } from "react-native";
import { StyleSheet } from "react-native-unistyles";
import { RenderErrorBoundary } from "@/components/render-error-boundary";
import { RetainedPanel } from "@/components/retained-panel";
import { Alert } from "@/components/ui/alert";
import { Button } from "@/components/ui/button";
import { useModifiedPanelTabIds } from "@/panels/panel-instance-attributes";
import {
WorkspacePaneContent,
@@ -58,44 +52,17 @@ const MountedTab = memo(function MountedTab({
return (
<RenderProfile id={`DesktopMountedTab:${tab.kind}:${tab.tabId}`}>
<RetainedPanel active={visible}>
<RenderErrorBoundary
resetKeys={[tab]}
onError={logPanelRenderError}
renderError={renderPanelError}
>
<WorkspacePaneContent
content={content}
isWorkspaceFocused={isWorkspaceFocused}
isPaneFocused={interactive}
onFocusPane={onFocusPane ? handleFocusPane : undefined}
/>
</RenderErrorBoundary>
<WorkspacePaneContent
content={content}
isWorkspaceFocused={isWorkspaceFocused}
isPaneFocused={interactive}
onFocusPane={onFocusPane ? handleFocusPane : undefined}
/>
</RetainedPanel>
</RenderProfile>
);
});
function logPanelRenderError(error: unknown, componentStack: string | null | undefined): void {
console.error("[WorkspacePanel] Render failed", error, componentStack);
}
function renderPanelError(error: string, retry: () => void) {
return <PanelRenderError error={error} onRetry={retry} />;
}
function PanelRenderError({ error, onRetry }: { error: string; onRetry: () => void }) {
const { t } = useTranslation();
return (
<View style={styles.renderError} testID="panel-render-error">
<Alert variant="error" title={t("panels.renderError.title")} description={error}>
<Button variant="outline" size="sm" onPress={onRetry} testID="panel-render-error-retry">
{t("common.actions.retry")}
</Button>
</Alert>
</View>
);
}
function useStableTabs(tabs: WorkspaceTabDescriptor[]) {
const cacheRef = useRef(new Map<string, WorkspaceTabDescriptor>());
const stableTabs = useMemo(() => {
@@ -169,9 +136,3 @@ export function WorkspacePanelHost({
);
});
}
const styles = StyleSheet.create((theme) => ({
renderError: {
padding: theme.spacing[4],
},
}));
@@ -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;
@@ -762,29 +762,6 @@ describe("terminal emulator runtime in a real browser", () => {
expect(mounted.inputs).toEqual([]);
});
// The daemon owns DEC 2031: it sends one ESC[?997;Nn per palette switch. A browser
// report on top of that delivers the switch twice.
it("does not emit a PTY input report when the theme changes under DEC 2031", async () => {
await page.viewport(900, 600);
const mounted = createTerminalHost({ width: 720, height: 360 });
await waitFor({ predicate: () => mounted.sizes.length > 0 });
const writeCommitted = (bytes: string) =>
new Promise<void>((resolve) =>
mounted.runtime.write({ data: terminalOutput(bytes), onCommitted: resolve }),
);
mounted.runtime.setTheme({ theme: { background: "#ffffff", foreground: "#1a1a1e" } });
await writeCommitted("\x1b[?2031h");
mounted.runtime.setTheme({ theme: { background: "#181b1a", foreground: "#fafafa" } });
mounted.runtime.setTheme({ theme: { background: "#ffffff", foreground: "#1a1a1e" } });
await writeCommitted("\x1b]11;#000000\x07");
await nextFrame();
expect(mounted.inputs).toEqual([]);
});
it("replays snapshots without synchronously resetting the visible terminal", async () => {
await page.viewport(900, 600);
const mounted = createTerminalHost({ width: 720, height: 360 });
@@ -577,10 +577,6 @@ export class TerminalEmulatorRuntime {
},
scrollback: input.scrollback,
theme: withOverviewRulerBorderHidden(input.theme),
// The daemon owns DEC 2031 and DSR 996: it tracks the mode and reports each
// palette switch once. xterm would otherwise send its own unsolicited
// ESC[?997;Nn on every theme change, which no query suppression can catch.
vtExtensions: { colorSchemeQuery: false },
});
const fitAddon = new FitAddon();
let webglAddon: WebglAddon | null = null;
@@ -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;
}
@@ -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 {
@@ -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);
+14
View File
@@ -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),
};
}
+14 -1
View File
@@ -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();

Some files were not shown because too many files have changed in this diff Show More