Compare commits

..
Author SHA1 Message Date
paseo-bot[bot]andMatteo Pietro Dazzi 097a0f3a7d Restore Android scrolling in provider model settings (#11350)
* fix(app): scroll the provider models list on Android

The models list sits in a ScrollView nested in the provider sheet's own
scrolling body. On Android the sheet's pan gesture claims the drag and cancels
that inner scroll, so the scrollbar appears and the content stays put;
nestedScrollEnabled covers Android's nested scrolling, not gesture
cancellation.

Claim the touch stream for the nested scroller instead, with the Android-only
gesture the model browser already used for the same problem. It moves out of
model-browser.tsx into components/ui/independent-scroll-boundary.tsx, so the
provider settings can use it without importing the model browser. The gesture
activates on the first move and refuses interruption, which keeps Android's
native scroll and its ACTION_UP for the fling.

The provider update output box has the same shape in the same sheet and gets
the same wrapper.

The claim and the platform gate are covered by a test; the drag itself needs a
device.

Closes #10544

* fix(app): preserve model checkbox taps while scrolling provider settings

Wait for Android to detect a drag before the provider list claims the touch. Exercise the sheet with the native swipe and checkbox interactions.

Co-authored-by: Matteo Pietro Dazzi <matteopietro.dazzi@gmail.com>

---------

Co-authored-by: Matteo Pietro Dazzi <matteopietro.dazzi@gmail.com>
Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-11-29 19:12:40 +00:00
paseo-bot[bot]andClaude Opus 5.5 47b4205098 test(website): wait for the plugin section fade before checking the reduced-motion demo (#11351)
The reduced-motion plugin demo test gave scrolling plus the section's
0.5 s fade-in a 2 s budget. On slow WebKit runners each scroll call took
up to 0.9 s and the row was still at opacity 0 when the budget ran out.
Wait for the section to finish fading in, then check the row at once:
the staged demo would still be hiding it at that point.

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 18:39:17 +00:00
paseo-bot[bot] d8e9a39953 test(server): receive live shell events in Codex steering tests (#11336)
The test waits for a running shell call before sending a follow-up. Subscribe to the agent timeline before the first prompt so the collector receives that event. Let the installed Codex select its supported default model.

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-11-29 17:12:43 +00:00
Feraidoon MehriandClaude Opus 5.5 d63f0204e5 fix(cli): list pending permissions of background agents in permit ls (#10655)
permit ls read one page of fetch_agents without includeBackground, so it missed requests from background agents and from any agent past the first 200. Read every page through fetchAllAgents and include background agents when the host supports them.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 16:12:45 +00:00
paseo-bot[bot]andThomas Van 9c9c839bd0 fix(pi): keep the daemon alive when an extension prompt fails (#11329)
Observe extension result rejections before awaiting the prompt response. Callers still receive the original prompt or extension error.

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
Co-authored-by: Thomas Van <9481872+thomasvan@users.noreply.github.com>
2026-11-29 15:42:43 +00:00
paseo-bot[bot]andClaude Opus 5.5 0e8e3987a0 Wait for the model sheet to settle before comparing Profiles and Model (#11330)
The compact-drawer step read the Profiles and Model rows' boxes in two
calls while the bottom sheet was still sliding up, so the second read
could land above the first. Wait for the sheet to stop moving first,
with the existing sheet-layout helper.

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 15:38:05 +00:00
0b1b2dd286 Keep plugin-transformed replies distinct in chat history (#8498)
* fix(app): keep chat history from crashing when two rows share an id

The chat virtualizer caches measured row sizes by key, and the key was the
row id. When two history rows had the same id, both rows wrote the same
cache entry. Each measurement pass set the size to the other row's height,
so the layout effect re-rendered without end and React aborted with
"Maximum update depth exceeded" (minified error #185).

Give each virtualized row a unique key. A repeated id gets a numeric
suffix, and the first occurrence keeps its plain id so the reading anchor
still matches it.

* fix(plugins): keep transformed replies distinct in chat history

Replacement IDs are local to their source message. Reusing a stable output
ID across replies aliased the row and virtualizer caches, reproducing a
packaged desktop React #185 crash. Scope row identity at projection and
retain the original prompt identity for navigation.

Build on the contributor regression, exercising transformed source rows
instead of assigning occurrence keys in the virtualizer.

Co-authored-by: Kevin Le <anhle12892@gmail.com>
Co-authored-by: ykurilov <110710320+ykurilov@users.noreply.github.com>

* test(plugins): verify repeated timeline IDs in a real browser

Exercise the installed plugin through the real daemon and chat viewport. Read the oldest virtualized replacement before and after reload, using actual browser row heights instead of extending the legacy JSDOM harness.

* test(app): use projected row IDs in turn footer assertions

---------

Co-authored-by: Kevin Le <anhle12892@gmail.com>
Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
Co-authored-by: ykurilov <110710320+ykurilov@users.noreply.github.com>
2026-11-29 14:42:45 +00:00
Mohamed Boudra 2c0bc525d3 perf(app): stop holding a copy of every cached transcript in renderer memory (#11322)
* perf(app): keep only row keys and sizes in the replica cache index

The replica cache kept every stored payload string in memory to enforce its
disk budget, so the renderer held a second copy of each cached transcript until
restart (#6477). Row stores now report each row's key and UTF-8 payload size
without loading payloads, and the cache budgets on those sizes alone.

* test(app): seed and read the replica cache at the app's database version
2026-11-29 20:54:01 +07:00
Mohamed Boudra 27e35a198d fix(app): close the keyboard when opening a file from the Files tree (#11320)
Since the Files tree gained a filter, its input stays focused when a match is
tapped. The preview sheet opens over the pane without taking input, so the
software keyboard covered the bottom of the file.
2026-11-29 20:23:44 +07:00
Mohamed Boudra 8b7cb47ef2 fix(app): keep Gboard suggestions and double-space period from corrupting Android terminal input (#11318)
* fix(app): keep Gboard suggestions and double-space period intact in the Android terminal

The Android terminal input connection emptied its editable after every
commit, while Gboard keeps its own copy of the committed text and edits it
by offset. On Android 14+ a suggestion pick or double-space period arrives as
replaceText(start, end, text); against the empty editable the range clamped
to [0, 0], so the insert reached the shell but the deletion was lost
(helo -> hello sent "lo ", giving "helolo ").

Keep the current shell line's IME text in the editable and diff it against
what the terminal holds, so offset edits become rubouts plus the new
suffix. Terminal keys still empty the editable; they now restart the IME
because Gboard ignores updateSelection as a signal to reload its text.

* fix(app): reset the Android terminal IME line on Gboard arrow keys

Gboard's editing-panel arrows reach the input connection as key events and move the shell cursor, but the editable kept the typed line. A later suggestion pick then sent rubouts for text the shell cursor was no longer after. Arrows now empty the editable and restart the IME like the other terminal keys.
2026-11-29 19:39:42 +07:00
Mohamed Boudra 693fa22377 fix(app): step back a page on Android Back in Agent settings (#11313)
AdaptiveModalSheet now forwards its header's back to the sheet's Android
Back handling, so Back from the Model page returns to Agent settings and
closes the sheet only from the first page.
2026-11-29 19:39:38 +07:00
Mohamed Boudra 22a318b1de fix(terminal): deliver one DEC 2031 report per theme switch (#11312)
The browser xterm (web and desktop) tracked CSI ?2031h itself and sent its
own unsolicited ESC[?997;Nn whenever its theme changed, on top of the
daemon's report. Query suppression could not catch it because no query is
involved. Every mounted viewer did this, so a background viewer that does
not own the terminal palette could also report a scheme the owner never
showed.

Turn off xterm's colorSchemeQuery extension so the daemon stays the only
DEC 2031 / DSR 996 responder, behind the existing palette ownership.

Refs #2795
2026-11-29 19:38:31 +07:00
paseo-bot[bot] 4f8fed2e2b test(app): wait for both pins before the pinned sidebar drag (#11319)
The pinned drag matched its two rows anywhere in the sidebar. Both rows
also exist in their project groups, so the test read the order while only
one pin had reached the Pinned section. The second pin then put its row on
top, and the drag moved it back down, which left the order the test read.

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-11-29 12:36:39 +00:00
124 changed files with 2028 additions and 5685 deletions
+6 -1
View File
@@ -601,7 +601,12 @@ 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 row store is not encrypted. A cached timeline can contain
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
source code, prompts, and tool output; encrypted-at-rest storage is a separate security decision.
### Saved hosts
-4
View File
@@ -36,10 +36,6 @@ 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
+2 -6
View File
@@ -267,10 +267,6 @@ 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
@@ -1022,8 +1018,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 `workspaceLayout` capabilities as the
matching Command Center callback.
the same `paseo`, `rpc`, `openScreen`, workspace, agent, and `openPanel` capabilities as the matching
Command Center callback.
```ts
client.addSlashCommand({
@@ -30,6 +30,7 @@ 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";
@@ -323,6 +324,7 @@ 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,6 +15,9 @@ import {
expectBothConsecutiveTools,
trackPluginChatRecovery,
reconnectPluginChat,
withRepeatedOutputTimeline,
readOldestPluginReplacement,
expectOldestPluginReplacementReadable,
} from "../support/helpers/plugin-timeline";
for (const width of [1100, 390]) {
@@ -82,3 +85,15 @@ 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);
});
});
@@ -1,324 +0,0 @@
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,10 +118,14 @@ 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.locator(
`[data-testid="${firstWorkspaceTestId}"], [data-testid="${secondProjectWorkspaceTestId}"]`,
),
page
.getByTestId("sidebar-pinned-section")
.locator(
`[data-testid="${firstWorkspaceTestId}"], [data-testid="${secondProjectWorkspaceTestId}"]`,
),
pressWorkspaceRow,
);
} finally {
@@ -392,6 +392,8 @@ 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, {
@@ -428,6 +430,10 @@ 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);
}
@@ -0,0 +1,60 @@
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,6 +18,9 @@ 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
# Reopen, dismiss the nested model browser, then dismiss its restored parent.
# Android Back steps from Model back to Agent settings, then closes the sheet.
press "id=\"combined-model-selector\""
wait "id=\"agent-controls-model\"" 10000
press "id=\"agent-controls-model\""
wait stable 300 5000
gesture pan 540 790 0 960 500
wait "id=\"model-search-all-input\"" 10000
back
wait "id=\"agent-controls-model\"" 3000
gesture pan 540 790 0 960 500
back
wait "id=\"combined-model-selector\"" 3000
close
@@ -0,0 +1,61 @@
#!/usr/bin/env bash
set -euo pipefail
# Open Pi settings from the Android model picker. Scroll the sheet body until
# most of the Models list is visible. Use a host with several Pi models and
# the default shown-models selection.
session="${1:?Pass the agent-device session with the Pi provider sheet open}"
artifacts="${2:-.artifacts/provider-model-scroll}"
mkdir -p "$artifacts"
ad() {
agent-device "$@" --session "$session"
}
visible_rows() {
jq -ce '
.data.nodes as $nodes
| ($nodes[] | select(.identifier == "provider-discovered-models")) as $list
| [$nodes[]
| select((.identifier // "") | startswith("provider-shown-model-"))
| select(.rect.height > 0 and .rect.y < ($list.rect.y + $list.rect.height))
| select(.rect.y + .rect.height > $list.rect.y)
| .label]
| select(length > 1)
' "$1"
}
ad snapshot --json > "$artifacts/before.json"
read -r x y dy < <(jq -er '
.data.nodes[]
| select(.identifier == "provider-discovered-models" and .rect.height >= 350)
| .rect
| [(.x + .width / 2 | floor), (.y + .height * 0.7 | floor), (-.height * 0.5 | floor)]
| @tsv
' "$artifacts/before.json") || {
printf 'Scroll the sheet body until the Models list is visible.\n' >&2
exit 1
}
before=$(visible_rows "$artifacts/before.json")
ad gesture pan "$x" "$y" 0 "$dy" 580
ad snapshot --json > "$artifacts/after.json"
after=$(visible_rows "$artifacts/after.json")
printf 'Before %s\nAfter %s\n' "$before" "$after"
first=$(jq -r '.[0]' <<<"$before")
if jq -e --arg first "$first" 'index($first) != null' <<<"$after" >/dev/null; then
printf 'The first model stayed visible after the upward drag.\n' >&2
exit 1
fi
model=$(jq -r '.[1]' <<<"$after")
ad press "role=checkbox label=\"$model\"" --settle
ad snapshot --json > "$artifacts/checked.json"
jq -e --arg model "$model" '
any(.data.nodes[]; .kind == "checkbox" and .label == $model and .checked == true)
' "$artifacts/checked.json" >/dev/null
ad press 'id="provider-shown-models-reset"' --settle
ad snapshot --json > "$artifacts/reset.json"
jq -e --arg model "$model" '
any(.data.nodes[]; .kind == "checkbox" and .label == $model and .checked == false)
' "$artifacts/reset.json" >/dev/null
@@ -7,6 +7,7 @@ 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";
@@ -373,3 +374,81 @@ 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,18 +61,24 @@ async function readRows(input: {
storeName: string;
}): Promise<ReplicaRowRecord[]> {
const database = await new Promise<IDBDatabase>((resolve, reject) => {
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();
// The app owns the database version; open whatever version it created.
const request = indexedDB.open(input.databaseName);
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 {
@@ -185,19 +191,27 @@ 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, 1);
const request = indexedDB.open(databaseName);
request.addEventListener("success", () => resolve(request.result));
request.addEventListener("error", () => reject(request.error));
});
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));
});
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();
}
},
{ databaseName: DATABASE_NAME, storeName: STORE_NAME, nextRows: rows },
);
@@ -1,11 +1,13 @@
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
@@ -77,6 +79,15 @@ 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 {
@@ -100,13 +111,8 @@ class TerminalInputConnectionTest {
@Test
fun batchedCommitTextAndSetComposingTextDoNotDoubleCharacters() {
withInputHarness { _, ic, _, terminal ->
for (ch in listOf("a", "b", "c", "d")) {
ic.beginBatchEdit()
ic.commitText(ch, 1)
ic.endBatchEdit()
}
ic.typeLikeGboard("abcd")
assertEquals("abcd", terminal.rawStream)
assertEquals("", ic.editable.toString())
// Coalesced setComposingText + finishComposingText inside one batch emits once.
ic.beginBatchEdit()
@@ -114,28 +120,96 @@ 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 (empty editable after commit)
// Path 1: deleteSurroundingText
ic.deleteSurroundingText(0, 0)
assertEquals("abcd", terminal.applyToLine())
ic.deleteSurroundingText(1, 0)
assertEquals("abc", terminal.applyToLine())
// Path 2: deleteSurroundingTextInCodePoints (empty editable)
// Path 2: deleteSurroundingTextInCodePoints
ic.deleteSurroundingTextInCodePoints(1, 0)
assertEquals("ab", terminal.applyToLine())
// Path 2b: deleteSurroundingTextInCodePoints on surrogate-pair emoji in composing buffer
ic.setComposingText("😀", 1)
// Path 2b: deleteSurroundingTextInCodePoints removes a surrogate-pair emoji as one code point
ic.commitText("😀", 1)
assertEquals("ab😀", terminal.applyToLine())
ic.deleteSurroundingTextInCodePoints(1, 0)
assertEquals("ab", terminal.applyToLine())
@@ -145,10 +219,16 @@ class TerminalInputConnectionTest {
ic.sendKeyEvent(KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_DEL))
assertEquals("a", terminal.applyToLine())
// Multi-char deleteSurroundingText on empty buffer
// Multi-char deleteSurroundingText
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))
}
}
@@ -242,7 +322,7 @@ class TerminalInputConnectionTest {
ic.commitText("the", 1)
assertEquals("hellothe", terminal.applyToLine())
// Repeated clipboard paste of identical text works because editable clears after commit
// Repeated clipboard paste of identical text appends both copies
ic.commitText("echo ok", 1)
ic.commitText("echo ok", 1)
assertEquals("hellotheecho okecho ok", terminal.applyToLine())
@@ -22,9 +22,16 @@ internal data class TerminalKeyPayload(
/**
* Single authoritative IME + key stream for the Android native terminal.
*
* 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.
* 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.
*/
internal class TerminalInputConnection(
private val targetView: View,
@@ -196,6 +203,7 @@ 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"
@@ -342,57 +350,38 @@ internal class TerminalInputConnection(
if (diff.isNotEmpty()) {
out.append(normalizeLineEndings(diff))
}
lastSentText = currentText
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)
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
}
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
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())
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)
}
}
@@ -411,10 +400,6 @@ 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
+14 -3
View File
@@ -3,12 +3,9 @@ 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";
@@ -20,6 +17,20 @@ 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 },
+8 -7
View File
@@ -603,14 +603,15 @@ describe("layoutStream", () => {
splitIntoCards,
);
const layout = layoutFor({
platform,
tail,
timingIds: ["genui/a1/card", "genui/a2/card"],
});
const footerCardIds = tail
.filter((item) => item.kind === "plugin" && item.itemKind === "genui-card")
.map((item) => item.id);
expect(footerCardIds).toHaveLength(2);
expect(footerOwners(layout)).toEqual(["genui/a1/card", "genui/a2/card"]);
expect(findLayoutItem(layout, "genui/a1/card").completedFooter?.turnMetrics).toBe(
const layout = layoutFor({ platform, tail, timingIds: footerCardIds });
expect(footerOwners(layout)).toEqual(footerCardIds);
expect(findLayoutItem(layout, footerCardIds[0]).completedFooter?.turnMetrics).toBe(
first.turnMetrics,
);
expect(layout.auxiliaryTurnFooter?.turnMetrics).toBe(metrics);
@@ -203,7 +203,9 @@ 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", id: "probe-plugin/prompt-1/0" }]);
expect(rendered).toMatchObject([
{ kind: "plugin", source: { id: "prompt-1" }, pluginItemId: "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"]);
});
@@ -611,7 +613,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",
"probe-plugin/reply/0",
JSON.stringify(["probe-plugin", "reply", "reply/0"]),
]);
expect(pluginData(result.tail)).toEqual([{ text: "$$x^2$$", phase: "complete" }]);
});
@@ -640,7 +642,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",
"probe-plugin/reply/0",
JSON.stringify(["probe-plugin", "reply", "reply/0"]),
]);
const expandedTurnHostIds = new Set(["prompt"]);
const opened = present({ ...completed, expandedTurnHostIds });
@@ -648,14 +650,16 @@ it("keeps streaming replies native, then folds work without losing manual expans
"prompt",
"turn-summary:prompt",
"tool-one",
"probe-plugin/reply/0",
JSON.stringify(["probe-plugin", "reply", "reply/0"]),
]);
expect(opened.turns.nestedItemIds.has("probe-plugin/reply/0")).toBe(false);
expect(opened.turns.nestedItemIds.has(JSON.stringify(["probe-plugin", "reply", "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",
"probe-plugin/reply/0",
JSON.stringify(["probe-plugin", "reply", "reply/0"]),
]);
});
@@ -679,7 +683,7 @@ it.each(["full", "collapseToolCalls"] as const)(
expect(result.tail.map((item) => item.id)).toEqual([
"prompt",
"tool-one",
"probe-plugin/reply/0",
JSON.stringify(["probe-plugin", "reply", "reply/0"]),
]);
expect(result.turns.summaryRowsByHostId.size).toBe(0);
},
-2
View File
@@ -78,7 +78,6 @@ 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,
@@ -1004,7 +1003,6 @@ function RootOverlayProviders({ children }: { children: ReactNode }) {
<BottomSheetModalProvider>
{children}
<WindowLayoutActionsHost />
<WorkspaceTabCloseErrorToasts />
</BottomSheetModalProvider>
</PortalProvider>
</ToastProvider>
@@ -60,6 +60,10 @@ 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;
@@ -738,10 +742,17 @@ 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,6 +12,7 @@ import { useQuery } from "@tanstack/react-query";
import { useTranslation } from "react-i18next";
import {
FlatList,
Keyboard,
type LayoutChangeEvent,
ListRenderItemInfo,
Pressable,
@@ -629,6 +630,8 @@ 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],
@@ -4,8 +4,8 @@ import { FlatList, Text, View } from "react-native";
import { StyleSheet, withUnistyles } from "react-native-unistyles";
import { AlertTriangle, ChevronDown, Layers } from "lucide-react-native";
import type { AgentProfilePickerRow } from "@/agent-profiles";
import { IndependentScrollBoundary } from "@/components/ui/independent-scroll-boundary";
import {
IndependentScrollBoundary,
MODEL_PICKER_ROW_HEIGHT,
ModelBrowserLoadingState,
ModelBrowserNoProviders,
+5 -29
View File
@@ -12,7 +12,6 @@ import {
import { useTranslation } from "react-i18next";
import {
FlatList,
Platform,
Pressable,
ScrollView,
Text,
@@ -27,6 +26,10 @@ import {
type StyleProp,
type ViewStyle,
} from "react-native";
import {
IndependentScrollBoundary,
useIndependentScrollGesture,
} from "@/components/ui/independent-scroll-boundary";
import { Gesture, GestureDetector } from "react-native-gesture-handler";
import { StyleSheet, withUnistyles } from "react-native-unistyles";
import {
@@ -209,10 +212,6 @@ function AgentProfilesEditAction({ onPress }: { onPress: () => void }) {
);
}
const IndependentScrollGestureContext = createContext<ReturnType<typeof Gesture.Native> | null>(
null,
);
interface ModelBrowserNavContextValue {
activeKey: string | null;
onActivateKey: (key: string) => void;
@@ -616,7 +615,7 @@ function ModelBrowserPressable({
onLayout,
testID,
}: ModelBrowserPressableProps) {
const independentScrollGesture = useContext(IndependentScrollGestureContext);
const independentScrollGesture = useIndependentScrollGesture();
const [pressed, setPressed] = useState(false);
// Android's scroll handler must keep the pointer stream until release so a
// fling survives leaving the short viewport. A simultaneous Tap keeps rows
@@ -1381,29 +1380,6 @@ function GroupedProviderRows({
);
}
export function IndependentScrollBoundary({ children }: { children: React.ReactElement }) {
// Prevent the parent sheet from cancelling Android's native scroll when the
// finger crosses this viewport; receiving ACTION_UP is what preserves fling.
const nativeScrollGesture = useMemo(
() =>
Gesture.Native()
.shouldActivateOnStart(true)
.shouldCancelWhenOutside(false)
.disallowInterruption(true),
[],
);
if (Platform.OS !== "android") {
return children;
}
return (
<IndependentScrollGestureContext.Provider value={nativeScrollGesture}>
<GestureDetector gesture={nativeScrollGesture}>{children}</GestureDetector>
</IndependentScrollGestureContext.Provider>
);
}
function resolveModelListRevealTarget({
shouldRevealActive,
hasActiveHeaderItem,
@@ -54,8 +54,6 @@ import type { WorkspaceTabDescriptor } from "@/screens/workspace/workspace-tabs-
import {
collectAllPanes,
createDefaultLayout,
resolveGroupSizes,
resolveMainSplitTree,
selectExplorerSidebarPaneId,
useWorkspaceLayoutStore,
type SplitNode,
@@ -82,7 +80,7 @@ interface SplitContainerProps {
uiTabs: WorkspaceTab[];
hoveredCloseTabKey: string | null;
setHoveredCloseTabKey: Dispatch<SetStateAction<string | null>>;
closingTabIds: ReadonlySet<string>;
closingTabIds: Set<string>;
onNavigateTab: (tabId: string) => void;
onCloseTab: (tabId: string) => Promise<void> | void;
onCopyResumeCommand: (agentId: string) => Promise<void> | void;
@@ -207,7 +205,7 @@ export function SplitContainer({
);
const mainRoot = useMemo(
() => resolveMainSplitTree(layout.root, explorerSidebarPaneId),
() => removePaneFromSplitTree(layout.root, explorerSidebarPaneId),
[layout.root, explorerSidebarPaneId],
);
const workspaceHasMultiplePanes = Boolean(mainRoot && hasMultipleVisiblePanes(mainRoot));
@@ -461,10 +459,11 @@ 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. A list of the wrong length would leave the dividers past its end
// unable to move.
// 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;
const groupSizes =
node.kind === "group" ? resolveGroupSizes(node.group, storedGroupSizes) : EMPTY_SPLIT_SIZES;
storedGroupSizes?.length === groupChildren.length ? storedGroupSizes : layoutGroupSizes;
const visibleFlex = useMemo(
() => resolveVisibleGroupFlex(groupChildren, groupSizes, maximizedPaneId),
[groupChildren, groupSizes, maximizedPaneId],
@@ -911,6 +910,34 @@ 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,
@@ -0,0 +1,44 @@
import { createContext, useContext, useMemo, type ReactElement } from "react";
import { Platform } from "react-native";
import { Gesture, GestureDetector } from "react-native-gesture-handler";
const IndependentScrollGestureContext = createContext<ReturnType<typeof Gesture.Native> | null>(
null,
);
/** The native scroll gesture of the enclosing boundary, for gestures that must not cancel it. */
export function useIndependentScrollGesture(): ReturnType<typeof Gesture.Native> | null {
return useContext(IndependentScrollGestureContext);
}
/**
* Keeps a parent pan from interrupting an Android scroll and lets the list receive ACTION_UP
* for the fling. With activation on start, child taps must join the native scroll gesture.
* When activation waits for the scroll view to intercept a drag, ordinary pressables receive taps.
*/
export function IndependentScrollBoundary({
children,
activateOnStart = true,
}: {
children: ReactElement;
activateOnStart?: boolean;
}) {
const nativeScrollGesture = useMemo(
() =>
Gesture.Native()
.shouldActivateOnStart(activateOnStart)
.shouldCancelWhenOutside(false)
.disallowInterruption(true),
[activateOnStart],
);
if (Platform.OS !== "android") {
return children;
}
return (
<IndependentScrollGestureContext.Provider value={nativeScrollGesture}>
<GestureDetector gesture={nativeScrollGesture}>{children}</GestureDetector>
</IndependentScrollGestureContext.Provider>
);
}
+15 -2
View File
@@ -5,10 +5,23 @@ 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), []);
@@ -29,7 +42,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 = browserTabLabel({ title: browser?.title ?? "", url });
const label = getBrowserLabel({ title: browser?.title ?? "", url });
return {
label,
@@ -1,135 +0,0 @@
/** 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;
}
+2 -3
View File
@@ -155,15 +155,14 @@ function MountedFilePanel({
revision: number;
onModifiedChange: (modified: boolean) => void;
}) {
const { tabId, state, setCurrentTabState } = usePaneContext();
const { state, setCurrentTabState } = usePaneContext();
const tab = useMemo<PluginTab>(
() => ({
id: tabId,
setModified: onModifiedChange,
state,
setState: setCurrentTabState,
}),
[tabId, onModifiedChange, state, setCurrentTabState],
[onModifiedChange, state, setCurrentTabState],
);
useEffect(() => () => onModifiedChange(false), [onModifiedChange]);
return <FilePanelView panel={panel} file={file} tab={tab} params={params} revision={revision} />;
+41 -49
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 { i18n } from "@/i18n/i18next";
import { useTranslation } from "react-i18next";
import { useSessionStore } from "@/stores/session-store";
import { agentHistoryQueryKey, allAgentHistoryQueryRootKey } from "./agent-history-query-key";
@@ -380,95 +380,87 @@ export function usePendingArchiveAgentIds(serverId: string): ReadonlySet<string>
);
}
/**
* 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;
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;
if (!client) {
throw new Error(i18n.t("common.errors.daemonClientUnavailable"));
throw new Error(t("common.errors.daemonClientUnavailable"));
}
return await client.archiveAgent(variables.agentId);
return await client.archiveAgent(input.agentId);
},
onMutate: (variables) => {
onMutate: (input) => {
const context: ArchiveAgentMutationContext = {
agent: getStoredAgentSnapshot(variables),
lists: getArchivedAgentListCacheSnapshot(queryClient, variables.serverId),
agent: getStoredAgentSnapshot(input),
lists: getArchivedAgentListCacheSnapshot(queryClient, input.serverId),
};
const archivedAt = new Date().toISOString();
applyArchivedAgentCloseResults({
queryClient,
serverId: variables.serverId,
results: [{ agentId: variables.agentId, archivedAt }],
serverId: input.serverId,
results: [{ agentId: input.agentId, archivedAt }],
invalidateQueries: false,
});
setAgentArchiving({
queryClient,
serverId: variables.serverId,
agentId: variables.agentId,
serverId: input.serverId,
agentId: input.agentId,
isArchiving: true,
});
return context;
},
onSuccess: (result, variables) => {
onSuccess: (result, input) => {
markAgentArchivedInStore({
serverId: variables.serverId,
agentId: variables.agentId,
serverId: input.serverId,
agentId: input.agentId,
archivedAt: result.archivedAt,
});
},
onError: (_error, variables, context) => {
onError: (_error, input, context) => {
if (!context) {
return;
}
restoreAgentSnapshot({
serverId: variables.serverId,
agentId: variables.agentId,
serverId: input.serverId,
agentId: input.agentId,
agent: context.agent,
});
restoreArchivedAgentListCacheSnapshot(queryClient, variables.serverId, context.lists);
restoreArchivedAgentListCacheSnapshot(queryClient, input.serverId, context.lists);
},
onSettled: (_result, _error, variables) => {
onSettled: (_result, _error, input) => {
clearArchiveAgentPending({
queryClient,
serverId: variables.serverId,
agentId: variables.agentId,
serverId: input.serverId,
agentId: input.agentId,
});
void queryClient.invalidateQueries({
queryKey: ["sidebarAgentsList", variables.serverId],
queryKey: ["sidebarAgentsList", input.serverId],
});
void queryClient.invalidateQueries({
queryKey: ["allAgents", variables.serverId],
queryKey: ["allAgents", input.serverId],
});
void queryClient.invalidateQueries({
queryKey: agentHistoryQueryKey(variables.serverId),
queryKey: agentHistoryQueryKey(input.serverId),
});
void queryClient.invalidateQueries({
queryKey: allAgentHistoryQueryRootKey(),
});
},
};
await queryClient.getMutationCache().build(queryClient, options).execute(input);
}
});
export function useArchiveAgent() {
const queryClient = useQueryClient();
const pendingQuery = useArchiveAgentPendingQuery();
const archiveMutateAsync = archiveMutation.mutateAsync;
const archive = useCallback(
(input: ArchiveAgentInput): Promise<void> => archiveAgent(queryClient, input),
[queryClient],
const archiveAgent = useCallback(
async (input: ArchiveAgentInput): Promise<void> => {
await archiveMutateAsync(input);
},
[archiveMutateAsync],
);
const isArchivingAgent = useCallback(
@@ -483,7 +475,7 @@ export function useArchiveAgent() {
);
return {
archiveAgent: archive,
archiveAgent,
isArchivingAgent,
};
}
@@ -1,32 +1,61 @@
import { useCallback, useMemo } from "react";
import { useTranslation } from "react-i18next";
import { useSessionStore, type AgentFileExplorerState } from "@/stores/session-store";
import { revealExplorerDirectory } from "@/file-explorer/tree";
import { usePanelStore } from "@/stores/panel-store";
import { revealExplorerDirectory, revealExplorerEntry } from "@/file-explorer/tree";
import { useExplorerRevealStore } from "@/file-explorer/reveal-request";
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";
export { buildWorkspaceExplorerStateKey, type FileExplorerWorkspaceScope };
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 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],
@@ -40,28 +69,66 @@ 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 => (tree ? updateWorkspaceExplorerState(tree, updater) : null),
[tree],
): 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],
);
const requestDirectoryListing = useCallback(
async (
path: string,
options?: { recordHistory?: boolean; setCurrentPath?: boolean },
): Promise<DirectoryListingResult> =>
tree ? listWorkspaceExplorerDirectory(tree, path, options) : null,
[tree],
): 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],
);
const selectExplorerEntry = useCallback(
@@ -74,27 +141,50 @@ 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 (!tree) return;
if (!workspaceStateKey) return;
const listed = await revealExplorerDirectory({
directoryPath,
requestDirectoryListing,
showHiddenFiles: showWorkspaceExplorerHiddenFiles,
expandPaths: (paths) => expandWorkspaceExplorerPaths(tree.stateKey, paths),
showHiddenFiles,
expandPaths,
});
clearFileFilter(tree.stateKey);
if (listed && select) showWorkspaceExplorerEntry(tree, directoryPath);
clearFileFilter(workspaceStateKey);
if (listed && select) showEntry(directoryPath);
},
[requestDirectoryListing, tree],
[expandPaths, requestDirectoryListing, showEntry, showHiddenFiles, workspaceStateKey],
);
/** Expands to an entry, selects it, and asks the tree to scroll to it. */
const revealEntry = useCallback(
async (entryPath: string): Promise<boolean> =>
tree ? revealWorkspaceExplorerEntry(tree, entryPath) : false,
[tree],
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],
);
const requestFileDownloadToken = useCallback(
+1 -2
View File
@@ -16,7 +16,6 @@ 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";
@@ -229,7 +228,7 @@ function useCommitDiffPanelDescriptor(
): PanelDescriptor {
const { t } = useTranslation();
return {
label: commitDiffTabLabel(target.sha),
label: target.sha.slice(0, 7),
subtitle: t("panels.diff.commitSubtitle"),
tooltip: target.sha,
titleState: "ready",
@@ -1,7 +1,6 @@
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;
@@ -10,7 +9,7 @@ export function buildDraftPanelDescriptor(input: {
}): PanelDescriptor {
const { icon, isCreating, pendingPrompt } = input;
const newAgentLabel = i18n.t("panels.draft.newAgent");
const creatingLabel = draftTabLabel({ isCreating, pendingPrompt, newAgentLabel });
const creatingLabel = pendingPrompt?.trim() || newAgentLabel;
if (isCreating) {
return {
label: creatingLabel,
+1 -2
View File
@@ -5,7 +5,6 @@ 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";
@@ -17,7 +16,7 @@ const CENTERED_PADDED_STYLE = {
} as const;
function useFilePanelDescriptor(target: { kind: "file"; path: string }) {
const fileName = fileTabLabel(target.path);
const fileName = target.path.split("/").findLast(Boolean) ?? target.path;
const icon = useMemo(() => createMaterialFileIcon(fileName), [fileName]);
return {
label: fileName,
@@ -60,21 +60,16 @@ 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(
subscribeAllPanelInstanceAttributes,
useCallback((listener: () => void) => {
allListeners.add(listener);
return () => allListeners.delete(listener);
}, []),
() => attributesRevision,
() => attributesRevision,
);
-173
View File
@@ -1,7 +1,3 @@
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. */
@@ -26,26 +22,6 @@ 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. */
@@ -58,219 +34,101 @@ 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",
@@ -278,39 +136,27 @@ 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;
@@ -343,22 +189,3 @@ 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,7 +15,6 @@ 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";
@@ -97,8 +96,9 @@ 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 = providerSubagentTabLabel(descriptor);
const label = descriptor?.description?.trim() || subagentType || "Subagent";
const providerLabel = `${formatProviderLabel(provider)} subagent`;
return {
label,
-60
View File
@@ -1,60 +0,0 @@
/** 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
@@ -1,141 +0,0 @@
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);
}
+11 -2
View File
@@ -10,7 +10,6 @@ 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";
@@ -28,6 +27,14 @@ 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 },
@@ -57,7 +64,9 @@ function useTerminalPanelDescriptor(
);
const terminal =
terminalsQuery.data?.terminals.find((entry) => entry.id === target.terminalId) ?? null;
const label = terminalTabLabel(terminal, t("workspace.tabs.fallback.terminal"));
const label =
trimNonEmpty(terminal?.title ?? terminal?.name ?? null) ??
t("workspace.tabs.fallback.terminal");
return {
label,
-3
View File
@@ -12,7 +12,6 @@ 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;
@@ -65,7 +64,6 @@ 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}`);
@@ -92,7 +90,6 @@ 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,9 +153,6 @@ function harness() {
openSurface() {},
composers: () => [],
async playAudio() {},
workspaceLayout: () => {
throw new Error("Layouts are not used here");
},
openPanel() {},
addComposerPill: () => ({ update() {}, remove() {} }),
addHeaderButton: () => ({ update() {}, remove() {} }),
@@ -12,7 +12,6 @@ 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,
@@ -34,7 +33,6 @@ 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,7 +5,6 @@ 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[];
@@ -35,13 +34,11 @@ 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",
@@ -60,7 +57,6 @@ 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,7 +114,6 @@ export type PluginClientRuntime = Pick<
| "openSurface"
| "composers"
| "openPanel"
| "workspaceLayout"
| "subscribe"
| "addComposerPill"
| "addHeaderButton"
@@ -1,26 +1,16 @@
import { PluginTranslationRuntime } from "@getpaseo/plugin/client/host";
import {
usePaseo,
useRpc,
useWorkspace,
useWorkspaceLayout,
useWorkspaces,
type PluginWorkspaceLayout,
} from "@getpaseo/plugin/client";
import { usePaseo, useRpc, useWorkspace, useWorkspaces } 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, vi } from "vitest";
import { expect, it } 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";
@@ -154,45 +144,3 @@ 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,14 +6,12 @@ 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);
@@ -35,23 +33,6 @@ 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
@@ -76,9 +57,9 @@ export function PluginInstallationProvider({
<PaseoApiProvider paseo={getPluginClientApi(plugin).paseo}>
<PluginRpcProvider invoke={plugin.invoke} subscribe={plugin.subscribe}>
<PluginTranslationProvider runtime={plugin.i18n}>
<PluginHandleSources plugin={plugin}>
<PluginComposersProvider source={pluginComposersSource(plugin)}>
<PluginClientStateProvider source={state}>{children}</PluginClientStateProvider>
</PluginHandleSources>
</PluginComposersProvider>
</PluginTranslationProvider>
</PluginRpcProvider>
</PaseoApiProvider>
@@ -61,9 +61,6 @@ function registry(
composers: () => [],
openSettings: () => {},
playAudio: async () => {},
workspaceLayout: () => {
throw new Error("Layouts are not used here");
},
openPanel: () => {},
addComposerPill: () => ({ update() {}, remove() {} }),
addHeaderButton: () => ({ update() {}, remove() {} }),
@@ -38,9 +38,6 @@ function registry(version: string) {
openSurface() {},
composers: () => [],
async playAudio() {},
workspaceLayout: () => {
throw new Error("Layouts are not used here");
},
openPanel() {},
addComposerPill: () => ({ update() {}, remove() {} }),
addHeaderButton: () => ({ update() {}, remove() {} }),
@@ -82,6 +82,69 @@ 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 = {
@@ -126,8 +189,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" },
},
]);
@@ -214,10 +277,11 @@ describe("plugin timeline projection", () => {
]);
const filtered = projectPluginTimelineItems([source], () => []);
expect(exploded.map((item) => item.id)).toEqual([
"split/thought-1/left",
"split/thought-1/right",
expect(exploded).toMatchObject([
{ source: { id: "thought-1" }, pluginItemId: "thought-1/left" },
{ source: { id: "thought-1" }, pluginItemId: "thought-1/right" },
]);
expect(new Set(exploded.map((item) => item.id)).size).toBe(2);
expect(filtered).toEqual([]);
});
@@ -254,13 +318,13 @@ describe("plugin timeline projection", () => {
expect(projected).toMatchObject([
{
kind: "plugin",
id: "genui/assistant-1/text",
pluginItemId: "assistant-1/text",
timelineCursor: { epoch: "e1", seq: 7 },
turnId: "turn-1",
},
{
kind: "plugin",
id: "genui/assistant-1/card",
pluginItemId: "assistant-1/card",
timelineCursor: { epoch: "e1", seq: 7 },
turnId: "turn-1",
},
@@ -94,7 +94,9 @@ function transformSourceItem(
return transformed.map((pluginItem) => {
const projected: PluginTimelineStreamItem = {
kind: "plugin",
id: `${pluginItem.pluginId}/${pluginItem.id}`,
// 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]),
source: item,
timestamp: item.timestamp,
pluginId: pluginItem.pluginId,
File diff suppressed because it is too large Load Diff
@@ -1,93 +0,0 @@
/**
* 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);
}
@@ -1,286 +0,0 @@
/** 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,
);
}
@@ -1,110 +0,0 @@
/** 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`);
}
@@ -1,93 +0,0 @@
/** 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,
};
}
@@ -1,97 +0,0 @@
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,7 +35,6 @@ function PluginPanelBody({ theme }: { theme: PluginTheme }) {
const {
serverId,
workspaceId,
tabId,
target,
state: tabState,
setCurrentTabState,
@@ -44,8 +43,8 @@ function PluginPanelBody({ theme }: { theme: PluginTheme }) {
const [modified, setModified] = useState(false);
usePublishPanelInstanceAttributes({ modified });
const tab = useMemo<PluginTab>(
() => ({ id: tabId, state: tabState, setState: setCurrentTabState, setModified }),
[tabId, tabState, setCurrentTabState],
() => ({ state: tabState, setState: setCurrentTabState, setModified }),
[tabState, setCurrentTabState],
);
invariant(target.kind === "plugin", "PluginPanel requires plugin target");
const plugin = useInstalledPlugin(serverId, target.pluginId);
@@ -15,6 +15,7 @@ import { SettingsRow, SettingsSection } from "@/components/settings";
import { Button } from "@/components/ui/button";
import { CheckboxRow } from "@/components/ui/checkbox";
import { bySizing, TOUCH_TARGET } from "@/components/ui/control-geometry";
import { IndependentScrollBoundary } from "@/components/ui/independent-scroll-boundary";
import { ToolbarButton, paneContentToolbarIconSize } from "@/components/ui/pane-content-toolbar";
import { SearchField } from "@/components/ui/search-field";
import { useIsCompactFormFactor } from "@/constants/layout";
@@ -232,14 +233,16 @@ export function ProviderModels({
/>
) : null}
{/* A provider can report hundreds of models; the rest of the page stays in reach. */}
<ScrollView
// Android scrolls a ScrollView nested in the page or the sheet only with this flag.
nestedScrollEnabled
style={[styles.discoveredList, curating && settingsStyles.rowBorder]}
testID="provider-discovered-models"
>
{discoveredBody}
</ScrollView>
<IndependentScrollBoundary activateOnStart={false}>
<ScrollView
// Android scrolls a ScrollView nested in the page or the sheet only with this flag.
nestedScrollEnabled
style={[styles.discoveredList, curating && settingsStyles.rowBorder]}
testID="provider-discovered-models"
>
{discoveredBody}
</ScrollView>
</IndependentScrollBoundary>
</View>
</SettingsSection>
) : null}
@@ -29,7 +29,8 @@ import {
type HostRuntimeControllerDeps,
type HostRuntimeStorage,
} from "./host-runtime";
import type { ReplicaRow, ReplicaRowStore } from "./replica-cache/row-store";
import { replicaPayloadBytes } from "./replica-cache/payload-bytes";
import type { ReplicaRow, ReplicaRowSize, ReplicaRowStore } from "./replica-cache/row-store";
import { subscriptionFixture } from "./subscription-fixture";
import { readDesktopManagedLocalCredential } from "@/desktop/daemon/local-credential";
@@ -640,12 +641,12 @@ function createMemoryReplicaRowStore(): ReplicaRowStore {
(!acceptedIds || acceptedIds.has(row.id)),
);
},
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);
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);
}
return [...hosts].map(([serverId, hostRows]) => ({ serverId, rows: hostRows }));
},
@@ -0,0 +1,128 @@
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,7 +13,14 @@ import {
} from "@/plugins/client-state/snapshots";
import { ReplicaCache } from ".";
import type { DirectoryCheckpoint } from "@/runtime/replica-cache";
import type { ReplicaHostRows, ReplicaRow, ReplicaRowChanges, ReplicaRowStore } from "./row-store";
import { replicaPayloadBytes } from "./payload-bytes";
import type {
ReplicaHostIndex,
ReplicaRow,
ReplicaRowChanges,
ReplicaRowSize,
ReplicaRowStore,
} from "./row-store";
const SERVER_ID = "cached-host";
@@ -41,8 +48,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 lists every row or deletes a host, so a test can interleave there. */
beforeReadAll: (() => Promise<void>) | null = null;
/** Awaited before the store indexes every row or deletes a host, so a test can interleave there. */
beforeReadIndex: (() => Promise<void>) | null = null;
beforeDeleteHost: (() => Promise<void>) | null = null;
private key(row: Pick<ReplicaRow, "serverId" | "kind" | "id">): string {
@@ -74,13 +81,13 @@ class MemoryStorage implements ReplicaRowStore {
);
}
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);
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);
}
return [...hosts].map(([serverId, rows]) => ({ serverId, rows }));
}
@@ -1143,7 +1150,7 @@ describe("ReplicaCache", () => {
).toEqual(["agent", "checkpoint", "project", "workspace"]);
});
it.each(["beforeReadAll", "beforeDeleteHost"] as const)(
it.each(["beforeReadIndex", "beforeDeleteHost"] as const)(
"stores no checkpoint for a host evicted after its update was queued (%s)",
async (pausePoint) => {
const storage = new MemoryStorage();
+33 -37
View File
@@ -27,12 +27,14 @@ 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";
@@ -869,31 +871,27 @@ function pendingRowKey(key: ReplicaRowKey): string {
return `${key.serverId}\u0000${rowKey(key)}`;
}
// 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>();
// 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>();
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;
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);
}
return bytes;
return size;
}
function rowBytes(row: ReplicaRow): number {
let bytes = rowBytesCache.get(row);
if (bytes === undefined) {
bytes = utf8ByteLength(row.payload);
rowBytesCache.set(row, bytes);
}
function sumBytes(rows: Iterable<ReplicaRowSize>): number {
let bytes = 0;
for (const row of rows) bytes += row.bytes;
return bytes;
}
@@ -980,7 +978,8 @@ function matchesReplicaRead(read: ReplicaRead, row: ReplicaRowKey): boolean {
export class ReplicaCache {
private readonly activeServerIds = new Set<string>();
private readonly activeReads = new Set<ReplicaRead>();
private readonly storedRows = new Map<string, Map<string, ReplicaRow>>();
// 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 hostBytes = new Map<string, number>();
private readonly hostWriteOrder = new Map<string, true>();
private pendingUpserts = new Map<string, StructuredReplicaUpsert>();
@@ -1283,13 +1282,13 @@ export class ReplicaCache {
this.invalidateHostReads(newServerId);
const rows = this.storedRows.get(oldServerId);
if (rows) {
const newRows = this.storedRows.get(newServerId) ?? new Map<string, ReplicaRow>();
const newRows = this.storedRows.get(newServerId) ?? new Map<string, ReplicaRowSize>();
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 = [...newRows.values()].reduce((sum, row) => sum + rowBytes(row), 0);
const bytes = sumBytes(newRows.values());
this.hostBytes.delete(oldServerId);
this.hostBytes.set(newServerId, bytes);
this.totalBytes += bytes;
@@ -1529,17 +1528,17 @@ export class ReplicaCache {
const previous = rows?.get(rowKey(key));
if (previous) {
rows?.delete(rowKey(key));
this.adjustHostBytes(key.serverId, -rowBytes(previous));
this.adjustHostBytes(key.serverId, -previous.bytes);
}
touchedServerIds.add(key.serverId);
}
for (const row of changes.upserts) {
const rows = this.storedRows.get(row.serverId) ?? new Map<string, ReplicaRow>();
const rows = this.storedRows.get(row.serverId) ?? new Map<string, ReplicaRowSize>();
const previous = rows.get(rowKey(row));
const previousBytes = previous ? rowBytes(previous) : 0;
rows.set(rowKey(row), row);
const size = rowSize(row);
rows.set(rowKey(row), size);
this.storedRows.set(row.serverId, rows);
this.adjustHostBytes(row.serverId, rowBytes(row) - previousBytes);
this.adjustHostBytes(row.serverId, size.bytes - (previous?.bytes ?? 0));
touchedServerIds.add(row.serverId);
}
for (const serverId of touchedServerIds) {
@@ -1568,7 +1567,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, ReplicaRow>>();
const projectedRows = new Map<string, Map<string, ReplicaRowSize>>();
const projectedBytes = new Map(this.hostBytes);
for (const serverId of touchedServerIds) {
projectedRows.set(serverId, new Map(this.storedRows.get(serverId)));
@@ -1577,13 +1576,10 @@ export class ReplicaCache {
projectedRows.get(key.serverId)?.delete(rowKey(key));
}
for (const row of changes.upserts) {
projectedRows.get(row.serverId)?.set(rowKey(row), row);
projectedRows.get(row.serverId)?.set(rowKey(row), rowSize(row));
}
for (const [serverId, rows] of projectedRows) {
projectedBytes.set(
serverId,
[...rows.values()].reduce((sum, row) => sum + rowBytes(row), 0),
);
projectedBytes.set(serverId, sumBytes(rows.values()));
}
const writeOrder = [...this.hostWriteOrder.keys()].filter(
@@ -1656,7 +1652,7 @@ export class ReplicaCache {
}
private ensureStoredIndex(): Promise<void> {
this.storedIndexPromise ??= this.rowStore.readAll().then(async (hosts) => {
this.storedIndexPromise ??= this.rowStore.readIndex().then(async (hosts) => {
this.storedRows.clear();
this.hostBytes.clear();
this.hostWriteOrder.clear();
@@ -1667,7 +1663,7 @@ export class ReplicaCache {
continue;
}
const rows = new Map(host.rows.map((row) => [rowKey(row), row]));
const bytes = host.rows.reduce((sum, row) => sum + rowBytes(row), 0);
const bytes = sumBytes(host.rows);
this.storedRows.set(host.serverId, rows);
this.hostBytes.set(host.serverId, bytes);
this.totalBytes += bytes;
@@ -0,0 +1,15 @@
// 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;
}
@@ -0,0 +1,37 @@
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,4 +1,10 @@
import type { ReplicaHostRows, ReplicaRow, ReplicaRowChanges, ReplicaRowStore } from "./row-store";
import type {
ReplicaHostIndex,
ReplicaRow,
ReplicaRowChanges,
ReplicaRowSize,
ReplicaRowStore,
} from "./row-store";
export type SqliteValue = string | number | null;
@@ -34,6 +40,13 @@ interface StoredMeta {
value: string;
}
interface StoredRowSize {
server_id: string;
kind: ReplicaRow["kind"];
id: string;
bytes: number;
}
interface StoredRow {
server_id: string;
kind: ReplicaRow["kind"];
@@ -89,18 +102,20 @@ export function createSqliteReplicaRowStore(
}
}
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",
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`,
);
const hosts = new Map<string, ReplicaRow[]>();
const hosts = new Map<string, ReplicaRowSize[]>();
for (const storedRow of storedRows) {
const rows = hosts.get(storedRow.server_id) ?? [];
rows.push({
serverId: storedRow.server_id,
kind: storedRow.kind,
id: storedRow.id,
payload: storedRow.payload,
bytes: storedRow.bytes,
});
hosts.set(storedRow.server_id, rows);
}
@@ -169,5 +184,5 @@ export function createSqliteReplicaRowStore(
await getConnection().run("DELETE FROM rows");
}
return { open, read, readAll, apply, deleteHost, renameHost, clear };
return { open, read, readIndex, apply, deleteHost, renameHost, clear };
}
@@ -8,6 +8,23 @@ 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 };
}
@@ -27,7 +44,7 @@ export function runReplicaRowStoreContract(
});
it("reads an empty store", async () => {
expect(await store.readAll()).toEqual([]);
expect(await readEveryRow(store)).toEqual([]);
});
it("round-trips opaque payloads grouped by server", async () => {
@@ -40,7 +57,7 @@ export function runReplicaRowStoreContract(
deletes: [],
});
expect(await store.readAll()).toEqual([
expect(await readEveryRow(store)).toEqual([
{
serverId: "server-a",
rows: [
@@ -81,7 +98,7 @@ export function runReplicaRowStoreContract(
deletes: [],
});
expect(await store.readAll()).toEqual([
expect(await readEveryRow(store)).toEqual([
{
serverId: "server-a",
rows: [row("server-a", "agent", "agent-1", "new")],
@@ -102,7 +119,7 @@ export function runReplicaRowStoreContract(
deletes: [{ serverId: "server-a", kind: "agent", id: "same-id" }],
});
expect(await store.readAll()).toEqual([
expect(await readEveryRow(store)).toEqual([
{
serverId: "server-a",
rows: [row("server-a", "workspace", "same-id", "workspace")],
@@ -122,7 +139,7 @@ export function runReplicaRowStoreContract(
deletes: [],
}),
).rejects.toBeInstanceOf(Error);
expect(await store.readAll()).toEqual([]);
expect(await readEveryRow(store)).toEqual([]);
});
it("deletes every row belonging to one host", async () => {
@@ -137,7 +154,7 @@ export function runReplicaRowStoreContract(
await store.deleteHost("server-a");
expect(await store.readAll()).toEqual([
expect(await readEveryRow(store)).toEqual([
{ serverId: "server-b", rows: [row("server-b", "agent", "agent-2", "b")] },
]);
});
@@ -155,7 +172,7 @@ export function runReplicaRowStoreContract(
await store.renameHost("temporary", "canonical");
expect(await store.readAll()).toEqual([
expect(await readEveryRow(store)).toEqual([
{
serverId: "canonical",
rows: [
@@ -178,7 +195,67 @@ export function runReplicaRowStoreContract(
await store.clear();
expect(await store.readAll()).toEqual([]);
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}'),
]);
});
it("wipes cached rows when the schema version changes on open", async () => {
@@ -189,7 +266,7 @@ export function runReplicaRowStoreContract(
const upgradedStore = await harness.openWithSchemaVersion(2);
expect(await upgradedStore.readAll()).toEqual([]);
expect(await readEveryRow(upgradedStore)).toEqual([]);
});
});
}
@@ -1,45 +1,6 @@
import { DatabaseSync, type SQLInputValue } from "node:sqlite";
import { runReplicaRowStoreContract } from "./row-store.contract";
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();
},
};
}
import { createSqliteReplicaRowStore } from "./row-store-sqlite";
import { createNodeSqliteDriver } from "./row-store-sqlite.test-driver";
runReplicaRowStoreContract("SQLite", async () => {
const driver = createNodeSqliteDriver();
@@ -9,11 +9,12 @@ import {
} from "./row-store-sqlite";
export type {
ReplicaHostRows,
ReplicaHostIndex,
ReplicaRow,
ReplicaRowChanges,
ReplicaRowKey,
ReplicaRowKind,
ReplicaRowSize,
ReplicaRowStore,
} from "./row-store";
export { REPLICA_ROW_STORE_SCHEMA_VERSION, REPLICA_SINGLETON_ROW_ID } from "./row-store-schema";
@@ -23,9 +23,15 @@ export interface ReplicaRowApplyOptions {
directoryBaselines?: ReadonlySet<string>;
}
export interface ReplicaHostRows {
// 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 {
serverId: string;
rows: ReplicaRow[];
rows: ReplicaRowSize[];
}
export interface ReplicaRowStore {
@@ -35,7 +41,8 @@ export interface ReplicaRowStore {
kinds: readonly ReplicaRowKind[],
ids?: readonly string[],
): Promise<ReplicaRow[]>;
readAll(): Promise<ReplicaHostRows[]>;
// Every stored row's key and payload size, grouped by host, read without loading payloads.
readIndex(): Promise<ReplicaHostIndex[]>;
// 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,3 +49,29 @@ 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,38 +1,62 @@
import { replicaPayloadBytes } from "./payload-bytes";
import type {
ReplicaHostRows,
ReplicaHostIndex,
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 {
ReplicaHostRows,
ReplicaHostIndex,
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 = 1;
const DATABASE_VERSION = 2;
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 withoutDirectoryRevision(row: IndexedDbReplicaRow): ReplicaRow {
if (row.directoryRevision === undefined) return row;
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 {
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;
@@ -84,8 +108,14 @@ async function openDatabase(databaseName: string): Promise<IDBDatabase> {
return new Promise((resolve, reject) => {
const request = indexedDB.open(databaseName, DATABASE_VERSION);
request.addEventListener("upgradeneeded", () => {
if (!request.result.objectStoreNames.contains(ROWS_STORE)) {
request.result.createObjectStore(ROWS_STORE, { keyPath: ["serverId", "kind", "id"] });
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(META_STORE)) {
request.result.createObjectStore(META_STORE);
@@ -144,17 +174,34 @@ export function createIndexedDbReplicaRowStore(
}
}
async function readAll(): Promise<ReplicaHostRows[]> {
async function readIndex(): Promise<ReplicaHostIndex[]> {
const transaction = getDatabase().transaction(ROWS_STORE, "readonly");
const completion = transactionComplete(transaction);
const rows = await requestResult<IndexedDbReplicaRow[]>(
transaction.objectStore(ROWS_STORE).getAll(),
);
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")),
);
});
await completion;
const hosts = new Map<string, ReplicaRow[]>();
for (const row of rows) {
const hosts = new Map<string, ReplicaRowSize[]>();
for (const row of rows.sort(compareRowKeys)) {
const hostRows = hosts.get(row.serverId) ?? [];
hostRows.push(withoutDirectoryRevision(row));
hostRows.push(row);
hosts.set(row.serverId, hostRows);
}
return Array.from(hosts, ([serverId, hostRows]) => ({ serverId, rows: hostRows }));
@@ -192,7 +239,7 @@ export function createIndexedDbReplicaRowStore(
observeDirectoryRevision(serverId, checkpoint?.directoryRevision);
}
return rows
.map(withoutDirectoryRevision)
.map(toReplicaRow)
.sort((left, right) =>
left.kind === right.kind
? left.id.localeCompare(right.id)
@@ -222,7 +269,7 @@ export function createIndexedDbReplicaRowStore(
for (const row of accepted.upserts) {
const directoryRevision =
row.kind === "checkpoint" ? nextRevisions.get(row.serverId) : undefined;
await requestResult(rows.put(directoryRevision ? { ...row, directoryRevision } : row));
await requestResult(rows.put(toStoredRow(row, directoryRevision)));
}
});
for (const [serverId, revision] of nextRevisions) observeDirectoryRevision(serverId, revision);
@@ -308,7 +355,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<ReplicaRow[]>(rows.getAll(range));
const oldRows = await requestResult<IndexedDbReplicaRow[]>(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]));
@@ -327,7 +374,7 @@ export function createIndexedDbReplicaRowStore(
});
}
return { open, read, readAll, apply, deleteHost, renameHost, clear };
return { open, read, readIndex, apply, deleteHost, renameHost, clear };
}
export function createReplicaRowStore(): ReplicaRowStore {
@@ -38,7 +38,7 @@ interface ExplorerSidebarDockProps extends Pick<
normalizedWorkspaceId: string;
isWorkspaceFocused: boolean;
paneFocusSuspended: boolean;
closingTabIds: ReadonlySet<string>;
closingTabIds: Set<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, useState } from "react";
import { useCallback, useEffect, useRef } from "react";
import {
FULL_SHEET_SNAP_POINTS,
SheetBackground,
@@ -76,31 +76,15 @@ function WorkspaceSheetTabs({
);
}
/**
* 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 }) {
function SheetTabSheet({ sheet, isTop, onClose }: SheetTabSheetProps) {
const { tab } = sheet;
const sheetRef = useRef<IsolatedBottomSheetModalRef>(null);
const isScreenFocused = useIsFocused();
const { isWorkspaceFocused } = useSheetPaneHost();
const contextBridge = useSheetPaneBridge();
// 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
// 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
// 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);
@@ -125,8 +109,8 @@ function PresentedSheetTab({
},
[onClose, tab.tabId],
);
// Only the workspace on screen owns Back.
const ownsBackPress = isTop && isOnScreen;
// Hidden workspaces stay mounted in the deck and under Settings; only the visible one owns Back.
const ownsBackPress = isTop && isWorkspaceFocused && isScreenFocused;
useEffect(() => {
if (!ownsBackPress) return;
return systemBackPress.subscribe(() => {
@@ -7,21 +7,12 @@ 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 [
...buildHostTerminalsQueryKey(serverId),
workspaceDirectory,
workspaceId ?? null,
] as const;
return ["terminals", serverId, workspaceDirectory, workspaceId ?? null] as const;
}
export function canCreateWorkspaceTerminal(input: {
@@ -15,6 +15,7 @@ import {
collectScriptTerminalIds,
collectStandaloneTerminalIds,
reconcilePendingScriptTerminals,
removeTerminalFromPayload,
type ListTerminalsPayload,
upsertCreatedTerminalPayload,
} from "@/screens/workspace/terminals/state";
@@ -178,6 +179,19 @@ 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;
@@ -256,17 +270,34 @@ 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,42 +143,3 @@ 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,9 +1,5 @@
import { useRef } from "react";
import {
collectAllPanes,
findPaneById,
type WorkspaceLayout,
} from "@/stores/workspace-layout-store";
import { collectAllPanes, type WorkspaceLayout } from "@/stores/workspace-layout-store";
import type { WorkspaceTab } from "@/workspace-tabs/model";
import { deriveWorkspacePaneState } from "./workspace-pane-state";
@@ -18,16 +14,13 @@ export function selectVisibleAgentIds(input: {
if (!input.routeFocused || !input.layout) {
return [];
}
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 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 targets = panes.flatMap((pane) => {
const target = deriveWorkspacePaneState({ pane, tabs: input.tabs }).activeTab?.descriptor
@@ -3,7 +3,7 @@ import {
buildBulkCloseConfirmationMessage,
classifyBulkClosableTabs,
closeBulkWorkspaceTabs,
} from "@/workspace-tabs/close/internal/bulk";
} from "@/screens/workspace/workspace-bulk-close";
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?.(`[workspaceTabClose] Failed to close subagent tab ${logLabel}`, { error, agentId });
warn?.(`[WorkspaceScreen] 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?.(`[workspaceTabClose] Failed to bulk close tabs ${logLabel}`, { error });
warn?.(`[WorkspaceScreen] Failed to bulk close tabs ${logLabel}`, { error });
});
} else if (hasDestructiveTabs) {
warn?.(`[workspaceTabClose] Failed to bulk close tabs ${logLabel}`, {
warn?.(`[WorkspaceScreen] Failed to bulk close tabs ${logLabel}`, {
error: new Error(i18n.t("common.errors.daemonClientUnavailable")),
});
}
@@ -25,6 +25,7 @@ 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,
@@ -71,6 +72,7 @@ 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 {
@@ -88,6 +90,7 @@ 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,
@@ -132,9 +135,12 @@ 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 { createWorkspaceBrowser } from "@/desktop/browser/store";
import { removeResidentBrowserWebview } from "@/desktop/browser/resident-webviews";
import { createWorkspaceBrowser, useBrowserStore } from "@/desktop/browser/store";
import { getDesktopHost } from "@/desktop/host";
import { buildProviderCommand } from "@/utils/provider-command-templates";
import { generateDraftId } from "@/stores/draft-keys";
@@ -195,13 +201,16 @@ import {
} from "@/workspace-tabs/launcher";
import type { TerminalTabDestination } from "@/screens/workspace/terminals/use-workspace-terminals";
import {
closeWorkspacePane,
closeWorkspaceTab,
closeWorkspaceTabs,
useClosingWorkspaceTabIds,
type BulkCloseScope,
} from "@/workspace-tabs/close";
import { useModifiedPanelTabIds } from "@/panels/panel-instance-attributes";
buildBulkCloseConfirmationMessage,
type BulkCloseConfirmationLabels,
classifyBulkClosableTabs,
closeBulkWorkspaceTabs,
} from "@/screens/workspace/workspace-bulk-close";
import { resolveCloseAgentTabPolicy } from "@/subagents";
import {
getPanelInstanceAttributes,
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";
@@ -441,6 +450,33 @@ 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;
@@ -1176,11 +1212,14 @@ function WorkspaceScreenContent({
createTerminal,
handleScriptTerminalStarted,
handleViewScriptTerminal,
invalidateTerminals,
killMutation: killTerminalMutation,
knownTerminalIds,
liveTerminalIds,
pendingCreateInput: pendingTerminalCreateInput,
query: terminalsQuery,
queryKey: terminalsQueryKey,
removeTerminalFromCache,
standaloneTerminalIds,
} = useWorkspaceTerminals({
client,
@@ -1205,6 +1244,7 @@ function WorkspaceScreenContent({
scripts: workspaceScripts,
onScriptTerminalStarted: handleScriptTerminalStarted,
});
const { archiveAgent } = useArchiveAgent();
const { checkoutQuery, isCheckoutStatusLoading } = useWorkspaceCheckoutStatus({
client,
@@ -1325,14 +1365,18 @@ 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,
@@ -1351,7 +1395,31 @@ function WorkspaceScreenContent({
persistenceKey ? (state.hiddenAgentIdsByWorkspace[persistenceKey] ?? EMPTY_SET) : EMPTY_SET,
);
const pendingByDraftId = useCreateFlowStore((state) => state.pendingByDraftId);
const closingTabIds = useClosingWorkspaceTabIds(persistenceKey);
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 focusedPaneTabState = useMemo(
() =>
@@ -1724,6 +1792,47 @@ 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 }) => {
@@ -1846,19 +1955,187 @@ function WorkspaceScreenContent({
[persistenceKey, splitWorkspacePaneEmpty],
);
const clearCloseHover = useCallback((closedTabIds: readonly string[]) => {
setHoveredCloseTabKey((current) =>
current && closedTabIds.includes(current) ? null : current,
);
}, []);
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 handleCloseTabById = useCallback(
async (tabId: string) => {
if (persistenceKey && (await closeWorkspaceTab(persistenceKey, tabId))) {
clearCloseHover([tabId]);
if (persistenceKey && sheets.some((sheet) => sheet.tab.tabId === tabId)) {
if (await confirmDiscardModifiedTab(tabId)) {
closeWorkspaceTab(persistenceKey, tabId);
}
return;
}
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 });
},
[clearCloseHover, persistenceKey],
[
allTabDescriptorsById,
closeWorkspaceTab,
confirmDiscardModifiedTab,
handleCloseAgentTab,
handleClosePassiveTab,
handleCloseTerminalTab,
persistenceKey,
sheets,
],
);
const handleCopyAgentId = useCallback(
@@ -2000,16 +2277,88 @@ function WorkspaceScreenContent({
}, [normalizedWorkspaceId, openWorkspaceTabFocused, persistenceKey]);
const handleBulkCloseTabs = useCallback(
async (tabsToClose: WorkspaceTabDescriptor[], scope: BulkCloseScope) => {
if (!persistenceKey) {
return;
async (input: {
tabsToClose: WorkspaceTabDescriptor[];
title: string;
logLabel: string;
}): Promise<boolean> => {
const { tabsToClose, title, logLabel } = input;
if (tabsToClose.length === 0) {
return true;
}
const tabIds = tabsToClose.map((tab) => tab.tabId);
if (await closeWorkspaceTabs(persistenceKey, tabIds, scope)) {
clearCloseHover(tabIds);
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;
}
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;
},
[clearCloseHover, persistenceKey],
[
archiveAgent,
bulkCloseConfirmationLabels,
client,
closeTab,
closeWorkspaceTabWithCleanup,
normalizedServerId,
normalizedWorkspaceId,
persistenceKey,
t,
],
);
const handleCloseTabsToLeftInPane = useCallback(
@@ -2018,9 +2367,13 @@ function WorkspaceScreenContent({
if (index < 0) {
return;
}
await handleBulkCloseTabs(paneTabs.slice(0, index), "left");
await handleBulkCloseTabs({
tabsToClose: paneTabs.slice(0, index),
title: t("workspace.tabs.confirmations.closeTabsLeftTitle"),
logLabel: "to the left",
});
},
[handleBulkCloseTabs],
[handleBulkCloseTabs, t],
);
const handleCloseTabsToLeft = useCallback(
@@ -2036,9 +2389,13 @@ function WorkspaceScreenContent({
if (index < 0) {
return;
}
await handleBulkCloseTabs(paneTabs.slice(index + 1), "right");
await handleBulkCloseTabs({
tabsToClose: paneTabs.slice(index + 1),
title: t("workspace.tabs.confirmations.closeTabsRightTitle"),
logLabel: "to the right",
});
},
[handleBulkCloseTabs],
[handleBulkCloseTabs, t],
);
const handleCloseTabsToRight = useCallback(
@@ -2050,12 +2407,14 @@ function WorkspaceScreenContent({
const handleCloseOtherTabsInPane = useCallback(
async (tabId: string, paneTabs: WorkspaceTabDescriptor[]) => {
await handleBulkCloseTabs(
paneTabs.filter((tab) => tab.tabId !== tabId),
"others",
);
const tabsToClose = paneTabs.filter((tab) => tab.tabId !== tabId);
await handleBulkCloseTabs({
tabsToClose,
title: t("workspace.tabs.confirmations.closeOtherTabsTitle"),
logLabel: "from close other tabs",
});
},
[handleBulkCloseTabs],
[handleBulkCloseTabs, t],
);
const handleCloseOtherTabs = useCallback(
@@ -2067,17 +2426,39 @@ function WorkspaceScreenContent({
const handleClosePane = useCallback(
async (paneId: string) => {
if (!persistenceKey) {
if (!persistenceKey || !workspaceLayout) {
return;
}
const closingIds = workspaceLayout
? (findPaneById(workspaceLayout.root, paneId)?.tabIds ?? [])
: [];
if (await closeWorkspacePane(persistenceKey, paneId)) {
clearCloseHover(closingIds);
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 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);
},
[clearCloseHover, persistenceKey, workspaceLayout],
[
allTabDescriptorsById,
closeWorkspacePane,
handleBulkCloseTabs,
persistenceKey,
t,
workspaceLayout,
explorerSidebarPaneId,
],
);
const handleWorkspacePanelOpenAction = useCallback(
@@ -972,155 +972,11 @@ function updatePaneInTree(
});
}
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 {
function insertSplitInternal(input: InsertSplitInternalInput): InsertSplitInternalResult {
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}`);
@@ -1131,20 +987,52 @@ 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 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 newPaneNode = createPaneNode({
id: newPaneId,
tabs: [detached.tab],
focusedTabId: detached.tab.tabId,
});
return { root, newPaneId };
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,
};
}
function repairDuplicateTabIds(root: SplitNodeInternal): {
@@ -2167,14 +2055,41 @@ 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 nextRoot = placePaneBesideTarget({
root: layout.root,
targetPaneId: input.targetPaneId,
paneNode: createPaneNode({ id: newPaneId, tabs: [createNewWorkspaceTab()] }),
position: input.position,
createNodeId: input.createNodeId,
});
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);
}
if (getTreeDepth(nextRoot) > input.maxTreeDepth) {
return null;
@@ -2217,10 +2132,7 @@ 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);
// 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) {
if (!sourcePane || !targetPane || targetPane.hidden === true) {
return null;
}
@@ -827,43 +827,6 @@ 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,9 +46,6 @@ import {
removeTabFromTree,
reorderFocusedPaneTabsInLayout,
reorderPaneTabsInLayout,
resolveGroupSizes,
resolveMainSplitTree,
resolveRequestedSplitSizes,
setPaneHiddenInLayout,
setTabStateInLayout,
selectTabInPaneInLayout,
@@ -95,8 +92,6 @@ export {
normalizeLayout,
removePaneFromTree,
removeTabFromTree,
resolveGroupSizes,
resolveMainSplitTree,
stripEphemeralTabsFromLayout,
};
export type {
@@ -211,8 +206,6 @@ 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: (
@@ -220,10 +213,6 @@ 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;
@@ -706,42 +695,6 @@ 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,
@@ -1908,14 +1861,6 @@ 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;
@@ -1946,22 +1891,10 @@ 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, nextLayout),
...withRequestedSplitSizes(state, normalizedWorkspaceKey, {
before: currentLayout.root,
after: nextLayout.root,
explorerSidebarPaneId,
targetPaneId: normalizedTargetPaneId,
newPaneId: result.paneId,
newPaneShare: input.newPaneShare,
}),
...withUpdatedWorkspaceLayout(state, normalizedWorkspaceKey, result.layout),
}));
return result.paneId;
@@ -762,6 +762,29 @@ 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,6 +577,10 @@ 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;
@@ -1,50 +0,0 @@
import { useEffect } from "react";
import { useStore } from "zustand";
import { useToast } from "@/contexts/toast-api-context";
import { queryClient } from "@/data/query-client";
import { getHostRuntimeStore } from "@/runtime/host-runtime";
import { confirmDialog } from "@/utils/confirm-dialog";
import { createWorkspaceTabClose, type BulkCloseScope } from "./internal/command";
export type { BulkCloseScope };
const NO_CLOSING_TAB_IDS: ReadonlySet<string> = new Set();
let showError: ((message: string) => void) | null = null;
const workspaceTabClose = createWorkspaceTabClose({
confirm: confirmDialog,
reportError: (message) => {
if (showError) showError(message);
else console.warn("[workspaceTabClose]", message);
},
getClient: (serverId) => getHostRuntimeStore().getClient(serverId),
queryClient,
});
/**
* Closing a workspace tab the way its close button does: the unsaved-work and destructive
* prompts, then the teardown of what the tab owns. Callable from anywhere in the app.
*/
export const closeWorkspaceTab = workspaceTabClose.closeTab;
export const closeWorkspaceTabs = workspaceTabClose.closeTabs;
export const closeWorkspacePane = workspaceTabClose.closePane;
/** Tabs whose close is waiting on the user or the daemon. */
export function useClosingWorkspaceTabIds(workspaceKey: string | null): ReadonlySet<string> {
return useStore(
workspaceTabClose.closing,
(state) => (workspaceKey ? state[workspaceKey] : undefined) ?? NO_CLOSING_TAB_IDS,
);
}
/** Shows close failures as app toasts. Mounted once, under the app's toast provider. */
export function WorkspaceTabCloseErrorToasts(): null {
const toast = useToast();
useEffect(() => {
showError = toast.error;
return () => {
showError = null;
};
}, [toast]);
return null;
}
@@ -1,414 +0,0 @@
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));
});
});
@@ -1,411 +0,0 @@
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,7 +4,6 @@ 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";
@@ -20,11 +19,6 @@ 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 {
@@ -49,8 +43,8 @@ export function openExplorerSidebarView(
});
}
export function showExplorerSidebar(input: ExplorerSidebarCommand): string | null {
if (input.isCompact && input.overlays !== "keep") {
export function showExplorerSidebar(input: ExplorerSidebarQuery): string | null {
if (input.isCompact) {
usePanelStore.getState().showMobileFileExplorer();
}
if (input.workspaceKey) {
@@ -62,9 +56,9 @@ export function showExplorerSidebar(input: ExplorerSidebarCommand): string | nul
return null;
}
export function hideExplorerSidebar(input: ExplorerSidebarCommand): void {
export function hideExplorerSidebar(input: ExplorerSidebarQuery): void {
if (input.isCompact) {
if (input.overlays !== "keep") usePanelStore.getState().showMobileAgent();
usePanelStore.getState().showMobileAgent();
return;
}
if (input.workspaceKey) {
@@ -72,7 +66,7 @@ export function hideExplorerSidebar(input: ExplorerSidebarCommand): void {
}
}
export function toggleExplorerSidebar(input: ExplorerSidebarCommand): void {
export function toggleExplorerSidebar(input: ExplorerSidebarQuery): void {
if (input.isCompact) {
if (isExplorerSidebarOpen(input)) hideExplorerSidebar(input);
else showExplorerSidebar(input);
-14
View File
@@ -67,17 +67,3 @@ export function buildWorkspaceTabPersistenceKey(input: {
}
return `${serverId}:${workspaceId}`;
}
/** The inverse of {@link buildWorkspaceTabPersistenceKey}. Server ids contain no colon. */
export function parseWorkspaceTabPersistenceKey(
workspaceKey: string,
): { serverId: string; workspaceId: string } | null {
const separator = workspaceKey.indexOf(":");
if (separator <= 0 || separator === workspaceKey.length - 1) {
return null;
}
return {
serverId: workspaceKey.slice(0, separator),
workspaceId: workspaceKey.slice(separator + 1),
};
}
+1 -14
View File
@@ -1,20 +1,8 @@
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,
{ overlays = "follow" }: { overlays?: AppOverlays } = {},
): string | null {
export function revealWorkspaceTab(workspaceKey: string, tabId: string | null): string | null {
if (!tabId) return null;
const store = useWorkspaceLayoutStore.getState();
const destination = store.getTabDestination(workspaceKey, tabId);
@@ -22,7 +10,6 @@ export function revealWorkspaceTab(
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();
+19 -2
View File
@@ -2,6 +2,7 @@ import type { Command } from "commander";
import type { AgentPermissionRequest } from "@getpaseo/protocol/agent-types";
import type { AgentSnapshotPayload } from "@getpaseo/protocol/messages";
import { connectToDaemon } from "../../utils/client.js";
import { fetchAllAgents, type AgentDirectoryClient } from "../../utils/agent-directory.js";
import type { CommandOptions, ListResult, OutputSchema, CommandError } from "../../output/index.js";
/** Permission list item for display */
@@ -56,6 +57,23 @@ export function listPendingPermissions(agents: AgentSnapshotPayload[]): PermitLs
};
}
export interface PermitAgentsClient extends AgentDirectoryClient {
supportsBackgroundWorkspaces(): boolean;
}
/**
* Read every agent that can hold a pending permission: all pages, and background agents too,
* since unattended workers are the ones most likely to be waiting on a prompt.
*/
export function fetchPermitAgents(client: PermitAgentsClient): Promise<AgentSnapshotPayload[]> {
return fetchAllAgents(client, {
filter: {
includeArchived: true,
...(client.supportsBackgroundWorkspaces() ? { includeBackground: true } : {}),
},
});
}
export interface PermitLsOptions extends CommandOptions {
host?: string;
}
@@ -67,8 +85,7 @@ export async function runLsCommand(
const client = await connectToDaemon({ target: options.daemonTarget });
try {
const agentsPayload = await client.fetchAgents({ filter: { includeArchived: true } });
const agents = agentsPayload.entries.map((entry) => entry.agent);
const agents = await fetchPermitAgents(client);
await client.close();
return listPendingPermissions(agents);
@@ -3,7 +3,7 @@ import type { AgentSnapshotPayload } from "@getpaseo/protocol/messages";
import { describe, expect, it } from "vitest";
import { render } from "../../output/render.js";
import { permitResponseSchema, toPermissionResponseItem } from "./allow.js";
import { listPendingPermissions } from "./ls.js";
import { fetchPermitAgents, listPendingPermissions } from "./ls.js";
const agentId = "2d85f428-fdaf-4d98-906f-c583de2b805f";
@@ -43,3 +43,45 @@ describe("permit allow and deny output", () => {
expect(answered.map((item) => item.requestId)).toEqual([writeRequest.id]);
});
});
describe("permit ls agent directory read", () => {
function fakeClient(pages: AgentSnapshotPayload[][], supportsBackground: boolean) {
const calls: unknown[] = [];
return {
calls,
supportsBackgroundWorkspaces: () => supportsBackground,
async fetchAgents(options?: unknown) {
calls.push(options);
const index = calls.length - 1;
return {
entries: (pages[index] ?? []).map((entry) => ({ agent: entry })),
pageInfo: { nextCursor: index + 1 < pages.length ? `cursor-${index + 1}` : null },
};
},
};
}
it("includes background agents and reads past the first page", async () => {
const backgroundAgent = {
id: "7b0e3f52-9d1c-4f0a-8a59-0f1d2e3c4b5a",
pendingPermissions: [writeRequest],
} as AgentSnapshotPayload;
const client = fakeClient([[{ id: agentId } as AgentSnapshotPayload], [backgroundAgent]], true);
const result = listPendingPermissions(await fetchPermitAgents(client));
expect(result.data.map((item) => item.agentId)).toEqual([backgroundAgent.id]);
expect(client.calls).toEqual([
expect.objectContaining({ filter: { includeArchived: true, includeBackground: true } }),
expect.objectContaining({ page: expect.objectContaining({ cursor: "cursor-1" }) }),
]);
});
it("leaves background out on hosts without background workspaces", async () => {
const client = fakeClient([[agent]], false);
await fetchPermitAgents(client);
expect(client.calls).toEqual([expect.objectContaining({ filter: { includeArchived: true } })]);
});
});
-123
View File
@@ -225,129 +225,6 @@ describe("plugin panel SDK boundary", () => {
});
});
describe("plugin workspace layout SDK boundary", () => {
it("lets a panel arrange and read a workspace through one handle", () => {
expect(
typeErrors(`
import {
PluginWorkspaceUnavailableError,
useWorkspaceLayout,
type PluginAgentPanelProps,
type PluginClientContext,
type PluginLayoutTab,
type PluginOpenTabOptions,
type PluginPane,
type PluginPanelLocation,
type PluginPanelTarget,
type PluginPanelTargetParams,
type PluginTabLocation,
type PluginTabPlacement,
type PluginWorkspaceLayout,
type PluginWorkspaceLayoutEvent,
type PluginWorkspaceLayoutState,
} from "@getpaseo/plugin/client";
function focusedFile(state: PluginWorkspaceLayoutState): string | null {
const tab: PluginLayoutTab | undefined = state.tabs.find((entry) => entry.id === state.focusedTabId);
return tab?.panelId === "paseo/file" ? String(tab.params.path) : null;
}
function ReviewPanel({ workspaceId, params }: PluginAgentPanelProps) {
const layout: PluginWorkspaceLayout = useWorkspaceLayout(workspaceId);
const path: string | null = useWorkspaceLayout(workspaceId, focusedFile);
function arrange() {
const agentParams: PluginPanelTargetParams = { agentId: params.agentId };
const target: PluginPanelTarget = { panelId: "paseo/agent", params: agentParams };
const agent: PluginTabLocation = layout.open(target);
if (!agent.paneId) return;
const placement: PluginTabPlacement = { type: "split", paneId: agent.paneId, side: "right", size: 0.4 };
const options: PluginOpenTabOptions = { placement };
const review = layout.open({ panelId: "review", params: agentParams }, options);
layout.open({ panelId: "paseo/diff" }, { placement: { type: "pane", paneId: agent.paneId }, intent: "background" });
layout.open({ panelId: "acme-coverage/report" }, { placement: { type: "beside" }, intent: "new" });
layout.open({ panelId: "findings" }, { placement: { type: "explorer" }, intent: "reveal" });
const moved: PluginTabLocation = layout.move(review.tabId, { type: "focused" });
layout.focus(moved.tabId);
layout.close(moved.tabId);
layout.closePane(agent.paneId);
layout.explorer.show();
layout.explorer.hide();
layout.explorer.toggle();
const stop: () => void = layout.subscribe((event: PluginWorkspaceLayoutEvent) => {
const type: "changed" = event.type;
});
const state = layout.get();
const pane: PluginPane | undefined = state.panes[0];
const kind: "main" | "explorer" | undefined = pane?.kind;
const locations: readonly PluginPanelLocation[] = state.tabs[0]?.locations ?? [];
// @ts-expect-error reads are not writable
state.tabs = [];
// @ts-expect-error the split tree is not exposed
state.root;
// @ts-expect-error arranging is not navigating
layout.navigate();
// @ts-expect-error placements name places a user can see
layout.open({ panelId: "findings" }, { placement: { type: "group" } });
// @ts-expect-error params are strings and numbers
layout.open({ panelId: "findings", params: { nested: {} } });
}
function guarded() {
try {
arrange();
} catch (error) {
if (!(error instanceof PluginWorkspaceUnavailableError)) throw error;
}
}
return null;
}
export default function contribute(client: PluginClientContext) {
client.addAgentPanel({ id: "review", title: "Review", icon: "File", Component: ReviewPanel });
return () => {};
}
`),
).toEqual([]);
});
});
describe("plugin workspace layout reach SDK boundary", () => {
it("reaches the handle from the entry context, workspace and agent commands, and a tab", () => {
expect(
typeErrors(`
import {
type PluginClientContext,
type PluginWorkspaceLayout,
type PluginWorkspacePanelProps,
} from "@getpaseo/plugin/client";
function Panel({ tab }: PluginWorkspacePanelProps) {
const id: string = tab.id;
// @ts-expect-error the host names the tab
tab.id = "other";
return null;
}
export default function contribute(client: PluginClientContext) {
client.addWorkspacePanel({ id: "panel", title: "Panel", icon: "File", Component: Panel });
const layout: PluginWorkspaceLayout = client.workspaceLayout("workspace-1");
client.addCommandCenterItem({ id: "workspace", title: "Workspace", icon: "File", context: "workspace",
onSelect({ workspaceLayout }) { workspaceLayout.open({ panelId: "panel" }); } });
client.addSlashCommand({ name: "aside", description: "Aside", argumentHint: "<message>", context: "agent",
async onSubmit({ args, agent, workspace, paseo, workspaceLayout }) {
const aside = await paseo.workspaces.ref(workspace.id).agents.create({
config: { provider: \`\${agent.provider}/\${agent.model}\` },
parent: agent.id,
prompt: args,
});
workspaceLayout.open({ panelId: "paseo/agent", params: { agentId: aside.id } }, { placement: { type: "explorer" } });
} });
client.addCommandCenterItem({ id: "global", title: "Global", icon: "File", context: "global",
onSelect(context) {
// @ts-expect-error a global command has no workspace to arrange
context.workspaceLayout;
} });
return () => {};
}
`),
).toEqual([]);
});
});
describe("plugin composer SDK boundary", () => {
it("lets a composer item read and change the composer through typed commands and controls", () => {
expect(
-24
View File
@@ -5,7 +5,6 @@ import type { PluginPaseoApi } from "./reference-api.js";
import type { AgentTimelineItem, JsonValue } from "@getpaseo/protocol/agent-types";
import type { ZodType, input as ZodInput, output as ZodOutput } from "zod";
import type { PluginFile } from "./file.js";
import type { PluginWorkspaceLayout } from "./workspace-layout.js";
import type {
PluginComposer,
PluginComposerItemContribution,
@@ -173,8 +172,6 @@ interface PluginWorkspacePanelBase<Text extends PluginText = string> {
}
export interface PluginTab {
/** This tab in its workspace's layout, as `useWorkspaceLayout` reads and arranges it. */
readonly id: string;
/** Shows the tab's unsaved dot and asks before closing. */
setModified(modified: boolean): void;
/** Opaque persisted JSON. Undefined until written; the panel validates it. */
@@ -272,16 +269,6 @@ export interface PluginClientContext extends PluginCommandCapabilities, PluginCl
contribution: PluginTimelineRendererContribution<Schema>,
): PluginCleanup;
onNotificationOpen(handler: PluginNotificationOpenHandler): PluginCleanup;
/**
* A handle on a workspace's panes and tabs on this client, for any workspace of the plugin's
* host. Components use `useWorkspaceLayout`, which returns the same handle.
*/
workspaceLayout(workspaceId: string): PluginWorkspaceLayout;
// COMPAT(pluginOpenPanel): added in v0.18.2, remove after 2027-05-01
/**
* @deprecated Use `workspaceLayout(workspaceId).open({ panelId }, { placement })`, then
* `navigation.openWorkspace` when the user is somewhere else.
*/
openPanel(id: string, options: PluginClientOpenPanelOptions): void;
/**
* Subscribes to a plugin subscription on this client's host. Paseo re-subscribes after a
@@ -402,10 +389,6 @@ export interface PluginGlobalCommandContext extends PluginCommandCapabilities {
export interface PluginWorkspaceCommandContext extends PluginCommandCapabilities {
context: "workspace";
workspace: PluginWorkspaceSnapshot;
/** The panes and tabs of `workspace`. */
workspaceLayout: PluginWorkspaceLayout;
// COMPAT(pluginOpenPanel): added in v0.18.2, remove after 2027-05-01
/** @deprecated Use `workspaceLayout.open({ panelId }, { placement })`. */
openPanel(id: string, options?: PluginOpenPanelOptions): void;
}
@@ -413,13 +396,6 @@ export interface PluginAgentCommandContext extends PluginCommandCapabilities {
context: "agent";
workspace: PluginWorkspaceSnapshot;
agent: PluginAgentSnapshot;
/** The panes and tabs of `workspace`. */
workspaceLayout: PluginWorkspaceLayout;
// COMPAT(pluginOpenPanel): added in v0.18.2, remove after 2027-05-01
/**
* @deprecated Use `workspaceLayout.open({ panelId }, { placement })`. An agent panel takes
* `params: { agentId: agent.id }`.
*/
openPanel(id: string, options?: PluginOpenPanelOptions): void;
}
-4
View File
@@ -12,10 +12,6 @@ export {
type PluginComposersSource,
} from "./composer.js";
export { PluginNewWorkspaceProvider } from "./new-workspace.js";
export {
PluginWorkspaceLayoutProvider,
type PluginWorkspaceLayoutSource,
} from "./workspace-layout.js";
export {
usePluginRuntimeContextBridge,
type PluginRuntimeContextBridge,
-14
View File
@@ -137,20 +137,6 @@ export type { PluginText, PluginMessage, PluginTranslations } from "../text.js";
export { useTabState } from "./tab.js";
export { PluginWorkspaceUnavailableError, useWorkspaceLayout } from "./workspace-layout.js";
export type {
PluginWorkspaceLayout,
PluginWorkspaceLayoutEvent,
PluginWorkspaceLayoutState,
PluginPane,
PluginLayoutTab,
PluginTabLocation,
PluginPanelTarget,
PluginPanelTargetParams,
PluginTabPlacement,
PluginOpenTabOptions,
} from "./workspace-layout.js";
export type { WorkspaceRef, AgentRef, ProjectRef, TerminalRef } from "../refs.js";
export type { Query, Group, GroupKey } from "./query.js";
@@ -10,10 +10,6 @@ import { PluginClientStateProvider, usePluginClientStateSource } from "./client-
import { PluginNewWorkspaceProvider, usePluginNewWorkspaceValue } from "./new-workspace.js";
import { PaseoApiProvider, usePaseoContextValue } from "./paseo-context.js";
import { PluginRpcProvider, usePluginRpcContextValue } from "./rpc-context.js";
import {
PluginWorkspaceLayoutProvider,
usePluginWorkspaceLayoutSource,
} from "./workspace-layout.js";
export type PluginRuntimeContextBridge = (children: ReactNode) => ReactNode;
@@ -26,7 +22,6 @@ export function usePluginRuntimeContextBridge(): PluginRuntimeContextBridge {
const composer = usePluginComposerValue();
const composers = usePluginComposersSource();
const newWorkspace = usePluginNewWorkspaceValue();
const workspaceLayouts = usePluginWorkspaceLayoutSource();
if (!paseo || !rpc) {
throw new Error("Plugin UI must run inside a contributed plugin surface");
@@ -51,18 +46,11 @@ export function usePluginRuntimeContextBridge(): PluginRuntimeContextBridge {
) : (
withComposers
);
const withWorkspaceLayouts = workspaceLayouts ? (
<PluginWorkspaceLayoutProvider source={workspaceLayouts}>
{withNewWorkspace}
</PluginWorkspaceLayoutProvider>
const content = composer ? (
<PluginComposerProvider composer={composer}>{withNewWorkspace}</PluginComposerProvider>
) : (
withNewWorkspace
);
const content = composer ? (
<PluginComposerProvider composer={composer}>{withWorkspaceLayouts}</PluginComposerProvider>
) : (
withWorkspaceLayouts
);
return (
<PaseoApiProvider paseo={paseo}>
<PluginRpcProvider invoke={rpc.invoke} subscribe={rpc.subscribe}>
@@ -71,6 +59,6 @@ export function usePluginRuntimeContextBridge(): PluginRuntimeContextBridge {
</PaseoApiProvider>
);
},
[composer, composers, newWorkspace, paseo, rpc, state, translations, workspaceLayouts],
[composer, composers, newWorkspace, paseo, rpc, state, translations],
);
}
@@ -1,207 +0,0 @@
import { createContext, useContext, type ReactNode } from "react";
import { useSyncExternalStoreWithSelector } from "use-sync-external-store/shim/with-selector";
import type { PluginPanelLocation } from "./contracts.js";
import { shallowEqual } from "./shallow.js";
/**
* A workspace's panes and tabs on this client. One per workspace, stable for the installation.
* Commands arrange the workspace and never change the screen the user is on. For a workspace that
* is not on screen, they do not open or close what is.
*
* Every command throws `PluginWorkspaceUnavailableError` when the client does not know the
* workspace on the plugin's host. `get` returns an empty state then.
*/
export interface PluginWorkspaceLayout {
readonly workspaceId: string;
/**
* Opens a registered panel. With the default intent, `reveal`, an open tab of the same panel and
* identity is focused where it is and gets the params again with a new `revision`; `placement`
* decides where a tab that is not open yet goes.
*
* Throws for a panel that is not registered, params the panel rejects, a placement the panel does
* not allow, or a pane that does not exist.
*/
open(target: PluginPanelTarget, options?: PluginOpenTabOptions): PluginTabLocation;
/** Does nothing when no tab has this id. */
focus(tabId: string): void;
/**
* Asks the user first when the tab reports unsaved work, as the close button does. Does nothing
* when no tab has this id.
*/
close(tabId: string): void;
/**
* Moves an open tab. Throws for a tab that is not open, a placement the tab's panel does not
* allow, or a pane that does not exist. Moving a tab into a hidden Explorer leaves it hidden.
*/
move(tabId: string, placement: PluginTabPlacement): PluginTabLocation;
/**
* Removes an ordinary pane and its tabs, asking what the UI asks first; hides the Explorer. Does
* nothing when no pane has this id, or when it is the only pane left.
*/
closePane(paneId: string): void;
readonly explorer: {
show(): void;
hide(): void;
toggle(): void;
};
/** Returns the same object until the layout changes. */
get(): PluginWorkspaceLayoutState;
/**
* Calls `listener` after the state `get` returns changes. Returns the unsubscribe function.
* Paseo releases what is left when the plugin stops.
*/
subscribe(listener: (event: PluginWorkspaceLayoutEvent) => void): () => void;
}
/** What happened to the layout. Switch on `type`; later versions may add fields. */
export interface PluginWorkspaceLayoutEvent {
type: "changed";
}
export interface PluginWorkspaceLayoutState {
/** Visible panes in reading order. The Explorer is a pane of kind `explorer` while shown. */
readonly panes: readonly PluginPane[];
/** Every open tab, including tabs of a hidden Explorer. */
readonly tabs: readonly PluginLayoutTab[];
/** A main pane. The Explorer never takes focus; read its `activeTabId` for what it shows. */
readonly focusedPaneId: string | null;
/** The focused pane's active tab, or the tab shown over the workspace on a phone. */
readonly focusedTabId: string | null;
/** On a phone, the app's one Explorer overlay, whichever workspace is on screen. */
readonly explorer: { readonly visible: boolean };
}
export interface PluginPane {
readonly id: string;
readonly kind: "main" | "explorer";
readonly tabIds: readonly string[];
readonly activeTabId: string | null;
}
export interface PluginLayoutTab {
readonly id: string;
/** Null for a tab shown over the workspace on a phone. */
readonly paneId: string | null;
/** Always qualified: `paseo/file`, `my-plugin/review`. */
readonly panelId: string;
/** The params that identify what the tab shows. */
readonly params: PluginPanelTargetParams;
/** Where this tab's panel may live, from its registration. */
readonly locations: readonly PluginPanelLocation[];
readonly title: string;
/** The tab reports unsaved work. */
readonly modified: boolean;
}
export interface PluginTabLocation {
readonly tabId: string;
/** Null for a tab shown over the workspace on a phone. */
readonly paneId: string | null;
}
/** A registered panel and the params that identify one instance of it. */
export interface PluginPanelTarget {
/**
* `<pluginId>/<panelId>`. `paseo/...` names one of Paseo's own panels. A bare id is the calling
* plugin's own panel.
*/
panelId: string;
params?: PluginPanelTargetParams;
}
export type PluginPanelTargetParams = Readonly<Record<string, string | number>>;
/**
* Where a tab goes. On phones and touch tablets, which have no splits, `pane`, `beside` and `split`
* mean the main pane.
*/
export type PluginTabPlacement =
/** The default. A panel that cannot live in the focused pane goes to its first location. */
| { type: "focused" }
| { type: "pane"; paneId: string }
/** The side pane, created on first use. */
| { type: "beside" }
/**
* A new pane next to `paneId`. `size` is its share of that pane's space, 0.1 to 0.9. Without it,
* the split is sized as one made in the UI.
*/
| { type: "split"; paneId: string; side: "left" | "right" | "top" | "bottom"; size?: number }
| { type: "explorer" };
export interface PluginOpenTabOptions {
placement?: PluginTabPlacement;
/**
* `reveal` (default) reuses an open tab and focuses it. `background` does the same without taking
* focus. `new` always adds a tab; for panels that allow one tab per identity, such as an agent's
* chat, it behaves as `reveal`.
*/
intent?: "reveal" | "background" | "new";
}
/** The client does not know this workspace on the plugin's host. */
export class PluginWorkspaceUnavailableError extends Error {
constructor(message = "The workspace is not available on this client.") {
super(message);
this.name = "PluginWorkspaceUnavailableError";
}
}
export interface PluginWorkspaceLayoutSource {
/** The same handle for the same workspace id. */
layout(workspaceId: string): PluginWorkspaceLayout;
}
const PluginWorkspaceLayoutContext = createContext<PluginWorkspaceLayoutSource | null>(null);
export function usePluginWorkspaceLayoutSource(): PluginWorkspaceLayoutSource | null {
return useContext(PluginWorkspaceLayoutContext);
}
export function PluginWorkspaceLayoutProvider({
children,
source,
}: {
children: ReactNode;
source: PluginWorkspaceLayoutSource;
}) {
return (
<PluginWorkspaceLayoutContext.Provider value={source}>
{children}
</PluginWorkspaceLayoutContext.Provider>
);
}
function subscribeNever() {
return () => {};
}
/**
* The layout of a workspace on the plugin's host. Without a selector, the handle. With one, what it
* selects from the state, re-rendering when that changes (compared shallowly).
*/
export function useWorkspaceLayout(workspaceId: string): PluginWorkspaceLayout;
export function useWorkspaceLayout<Selection>(
workspaceId: string,
selector: (state: PluginWorkspaceLayoutState) => Selection,
): Selection;
export function useWorkspaceLayout<Selection>(
workspaceId: string,
selector?: (state: PluginWorkspaceLayoutState) => Selection,
): PluginWorkspaceLayout | Selection {
const source = usePluginWorkspaceLayoutSource();
if (!source) throw new Error("useWorkspaceLayout must run inside a plugin host");
const layout = source.layout(workspaceId);
const read: () => PluginWorkspaceLayout | PluginWorkspaceLayoutState = selector
? layout.get
: () => layout;
return useSyncExternalStoreWithSelector(
selector ? layout.subscribe : subscribeNever,
read,
read,
(value) => (selector ? selector(value as PluginWorkspaceLayoutState) : layout),
shallowEqual,
);
}

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