Compare commits

..
Author SHA1 Message Date
paseo-bot[bot] 217223b1e6 fix(cli): explain how to connect to TLS endpoints
A bare host and port selects plaintext WebSocket. A TLS proxy that replies with HTTP 400 leaves the user with generic connection advice, even though the same address works with wss://.
2026-11-30 03:58:26 +00:00
paseo-bot[bot]andClaude Opus 5.5 a099673413 test(cli): reserve lifecycle test ports outside the ephemeral range (#11378)
port() took a port from port 0 and released it before the daemon
listened. Port-0 ports are ephemeral, so the OS could give the same
port to another process in that gap, and the daemon failed with
EADDRINUSE. port() now picks a free port from 20000-31999, below the
ephemeral range of Linux, macOS, and Windows.

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-30 03:27:15 +00:00
SunicemanandShane Su 3abb0cb18e Leave unexpanded Windows variable paths unlinked in chat (#11228)
Co-authored-by: Shane Su <26364206+suniceman@users.noreply.github.com>
2026-11-30 03:12:59 +00:00
Mohamed Boudra c77a53ffdc fix(app): hold the launch splash until the restored workspace is on screen (#11348)
On a cold start the app showed the native splash, a grey frame, an empty
frame, a smaller second logo, then a series of different spinners before
the conversation appeared.

The grey came from the Android activity window, which had no background
and fell back to the AppCompat default under the fading splash. The rest
came from every screen in the startup chain rendering its own loading
state the moment it mounted, while the splash had already been hidden by
expo-router on first navigation.

native-splash now owns "launch is still loading": screens hold it while
their content can still come from the local cache, and it leaves once a
frame passes with no holds (5 s cap). It does not wait for the network;
a route that waits on the host shows one shared LoadingState that says
what it is waiting for. A host that is still connecting is loading, not
unreachable.

Android cannot time the hand-off from the system splash, so it swaps to
an identical in-app LaunchScreen at first commit and fades that out.

Also: the nested sidebar list is virtualised, and first launch waits
for host bootstrap to settle instead of giving up after a fixed 5 s.
2026-11-30 09:46:20 +07:00
Mohamed Boudra 614b4d3860 Open Profiles first and even out row heights in mobile Agent settings (#11371)
* feat(app): open Profiles by default when configuring a new agent on mobile

On a phone, picking a profile is the quickest way to set up a new agent, so
the agent settings drawer now opens with the Profiles card expanded for a
draft (New Chat, New Workspace) when profiles exist. A running agent keeps it
collapsed, since there a profile overwrites settings the agent already runs
with. A toggle holds until the drawer closes.

* fix(app): give every Agent settings row on mobile the same height

Model and switch rows used the settings-card row, sized for spacious settings
pages (switch height plus 16pt padding, 58pt on touch), while the sheet's
Profiles header and mode choices are 44pt list rows. A new list placement in
the row-density context makes settings rows in a sheet of list rows one touch
target tall, and Agent settings Home opts into it.
2026-11-30 09:44:32 +07:00
paseo-bot[bot] 80f0b11386 test(desktop): keep the link opener available during browser E2E (#11366)
A login shell that resets PATH removes the test opener before Electron launches a plugin link. Run the Linux desktop test with an isolated shell so the fixture receives both expected opens.

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-11-30 01:42:48 +00:00
paseo-bot[bot] 95a90f5259 fix(cli): restore arguments on the desktop executable (#11363)
The bundled CLI build stopped emitting the runCli module that Electron imports for direct CLI calls. Build that module alongside the standalone CLI and include it in the Nix desktop trace.

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-11-30 00:42:52 +00:00
paseo-bot[bot]andMarkA d059fcfd10 Show Schedules when a saved host is still connecting (#11361)
* fix(schedules): show results while another host connects

## Problem
An online host returning no schedules leaves the page loading indefinitely when
another saved host is still connecting. The user cannot reach the empty state or
create a schedule despite a successful response.

## Solution
Return the available results, including an empty list, and include a warning for
hosts still connecting. Preserve the initial connecting state when no host can
answer and existing errors when every attempted request fails.

* test(schedules): cover stalled hosts in the browser

## Problem
The schedules spinner regression needs a user-visible check, and partial
loading must not hide errors from the only connected host.

## Solution
Exercise an isolated daemon alongside a stalled WebSocket connection in the
existing schedules suite. Verify the empty state, warning, and creation
button, capture both responsive layouts, and preserve failed-host coverage.

* fix(schedules): keep host warnings consistent with fetched results

## Problem
A host changing connection state during another request could lose its
missing-results warning or gain a warning despite returning schedules.

## Solution
Remember settling hosts when deciding which requests to send. Cover both
connection transitions and express the browser regression through concise
user-level helpers.

* test(schedules): keep scenario mechanics in runtime fixtures

## Problem
Host-specific branching inside test bodies obscures the behaviors being
asserted and conflicts with the repository's test conventions.

## Solution
Reuse the runtime fixture for failed responses and isolate connection
transitions in a focused helper while preserving unconditional assertions.

* test(schedules): assert the empty state and creation control

Check the text and action the user sees when another host is still connecting.

Co-authored-by: MarkA <agenore990@gmail.com>

* fix(schedules): identify hosts that are still connecting

Carry the reason for each partial result so the banner can distinguish a pending connection from a failed schedule request.

---------

Co-authored-by: MarkA <agenore990@gmail.com>
Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-11-29 23:42:49 +00:00
paseo-bot[bot] cfd4efe289 fix(cli): exit agent logs after a daemon timeout (#11360)
Close the daemon connection before passing coded errors to the CLI error handler. An open connection kept the process running after the CLI printed the timeout.

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-11-29 22:42:45 +00:00
Matchy 830697ba62 Close the image lightbox when switching sessions on web (#11358)
* fix(app): close the image lightbox when its panel goes inactive

Switching sessions (for example from a notification) keeps the old chat
mounted in a RetainedPanel that becomes inactive. On web, the next commit
freezes the hidden chat with react-freeze. The lightbox renders an RN Modal
that portals to document.body, so the image stayed on top of the new
session, and its close button, backdrop and Escape all set state inside the
frozen subtree, which never committed. On native the chat is not frozen,
but the old image was still left over the new session.

Do what MenuSurface already does: read useRetainedPanelActive(), call
onClose() when the panel turns inactive, and render nothing (with the
overlay layer and Escape registration off) in that same inactive commit, so
the portal is gone before the freeze. Outside a retained panel the signal
is true, so other callers are unaffected.

Checked with a browser test that opens the lightbox, deactivates the panel
under the web and native RetainedChatContent, and tries every close path:
it failed before this change and passes after.

* test(app): pin the lightbox closing when its chat leaves the screen

Opens the image lightbox inside a retained chat, deactivates the panel the
way a session switch does, and checks the lightbox is gone and stays gone
when the chat comes back. Runs under both the web RetainedChatContent,
which freezes the hidden chat, and the native one, which keeps it live.

Both cases fail on the commit before the lightbox fix and pass after it.

Refs #11355
2026-11-29 22:12:51 +00:00
paseo-bot[bot]andClaude Opus 5.5 41aceb042b test(server): wait for the shell prompt between terminal protocol helpers (#11357)
The three protocol-query tests typed the next helper command as soon as
the previous helper printed its OK line. That helper was still running,
so the shell printed its prompt and the typed-ahead command's output on
one row ("$ OSC_COLOR_OK:12:..."). The checks need the line to start
with, or equal, the OK text, so they waited until the 5 s timeout.

Each command now waits for the prompt before it is typed. A timeout
also prints the screen, so the next failure shows what it saw.

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 21:35:27 +00:00
Tri Dao 74f629bee1 fix(pi): run extension commands sent mid-turn without aborting the turn (#11341)
Slash input sent while a Pi turn runs used to replace the turn: steering refuses slash
commands, so Paseo aborted the turn and sent the command as a new prompt. Pi runs
extension commands immediately even while streaming, so the provider now claims them
through tryHandleOutOfBand (as /compact already is) and forwards them as a plain prompt.
The handler doesn't wait for Pi's ack, which arrives only when the command returns, so an
interactive command can't hold Stop. Idle input, skills, prompt templates and unknown
commands keep their existing paths.
2026-11-29 20:42:37 +00:00
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
198 changed files with 3952 additions and 6043 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
+1 -1
View File
@@ -136,7 +136,7 @@ Cards inside a section sit closer than sections. Rows inside a card touch — on
Rows have generous vertical padding: roughly 16px of content plus 16px of vertical padding for settings rows, 8–12px for sidebar list items where many rows must fit. Every row is at least as tall as one holding a switch, so text rows, switch rows and rows that open something (`<SettingsDetailRow>`, a collapsible row's header) line up. A row holding a button or a select is taller. Compressing rows below the established density to fit more on the screen is wrong. Too many rows means more cards or more sections, not smaller rows.
Rows revealed under a `<SettingsCollapsibleRow>` are nested rows, one step smaller than card rows: 8px of vertical padding, `fontSize.sm` text, `sm` controls, and one fixed height so rows with and without a trailing button line up. The collapsible row sets this for everything under it (`packages/app/src/components/settings/row-density.tsx`). Never pass a density to a row, and never pad or resize a nested row by hand. Settings rows that share a menu surface with menu rows, such as Usage's options, go inside `<MenuSettingsRows>`, which puts their labels on the menu rows' label rail (`menuRowContentInset`).
Rows revealed under a `<SettingsCollapsibleRow>` are nested rows, one step smaller than card rows: 8px of vertical padding, `fontSize.sm` text, `sm` controls, and one fixed height so rows with and without a trailing button line up. The collapsible row sets this for everything under it (`packages/app/src/components/settings/row-density.tsx`). Never pass a density to a row, and never pad or resize a nested row by hand. Settings rows that share a menu surface with menu rows, such as Usage's options, go inside `<MenuSettingsRows>`, which puts their labels on the menu rows' label rail (`menuRowContentInset`). Settings rows that share a sheet with list rows, such as Agent settings with its radio choices and section headers, go inside `<ListSettingsRows>`, which makes every row one touch target tall so Model, switch and radio rows line up.
The whitespace is the design.
-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({
+2
View File
@@ -5,6 +5,7 @@ const withAndroidAsyncStorageSize = require("./plugins/with-android-async-storag
const withAndroidIgnoreBoldText = require("./plugins/with-android-ignore-bold-text");
const withAndroidOptionalCamera = require("./plugins/with-android-optional-camera");
const withAndroidProfileable = require("./plugins/with-android-profileable");
const withAndroidSplashWindowBackground = require("./plugins/with-android-splash-window-background");
const withFdroidAutolinking = require("./plugins/with-fdroid-autolinking");
const withPasteInput = require("./plugins/with-paste-input");
const withAndroidScroll = require("./modules/paseo-scroll/app.plugin");
@@ -165,6 +166,7 @@ export default {
},
},
],
withAndroidSplashWindowBackground,
...buildProfile.notificationPlugins,
"expo-audio",
[
+29
View File
@@ -26,6 +26,29 @@ async function resolveAndroidManifest() {
return exp._internal.modResults.android.manifest.manifest;
}
interface StyleItem {
$: { name: string };
_: string;
}
interface StyleGroup {
$: { name: string };
item?: StyleItem[];
}
async function resolveAndroidAppThemeItems(): Promise<Record<string, string>> {
const { exp } = await getPrebuildConfigAsync(__dirname, { platforms: ["android"] });
await compileModsAsync(exp, {
projectRoot: __dirname,
introspect: true,
platforms: ["android"],
assertMissingModProviders: false,
});
const styles: StyleGroup[] = exp._internal.modResults.android.styles.resources.style;
const appTheme = styles.find((style) => style.$.name === "AppTheme");
return Object.fromEntries((appTheme?.item ?? []).map((item) => [item.$.name, item._]));
}
describe("Android app config", () => {
afterEach(() => {
if (originalFdroidFlag === undefined) {
@@ -58,6 +81,12 @@ describe("Android app config", () => {
},
30_000,
);
// Without it, a dark device paints AppCompat's #303030 between the splash and the first screen.
it("paints the app window in the splash colour", async () => {
const appTheme = await resolveAndroidAppThemeItems();
expect(appTheme["android:windowBackground"]).toBe("@color/splashscreen_background");
}, 30_000);
});
it("follows system rotation on Android", async () => {
@@ -128,6 +128,45 @@ test.describe("Agent profiles in the model picker", () => {
}
});
test("the compact drawer keeps a running agent's Profiles collapsed and its rows one height", async ({
page,
}, testInfo) => {
const seed = await seedAgentProfiles([PROFILE]);
const workspace = await seedMockAgentWorkspace({
repoPrefix: "agent-profiles-compact-running-",
title: "Agent profiles compact running",
model: "ten-second-stream",
modeId: "load-test",
});
try {
await page.setViewportSize({ width: 390, height: 800 });
await openAgentRoute(page, workspace);
await expectComposerVisible(page);
await page.getByTestId("combined-model-selector").filter({ visible: true }).first().click();
await expect(page.getByTestId("agent-controls-profiles")).toBeVisible();
await expect(page.getByTestId("agent-controls-profiles-list")).toHaveCount(0);
// Settings rows (Model, switches) sit in the same list as the Profiles header and mode rows.
const sheet = page.getByTestId("agent-controls-settings-list");
const rows = [
sheet.getByTestId("agent-controls-profiles"),
sheet.getByTestId("agent-controls-model"),
sheet.locator('[data-testid^="mode-option-"]').first(),
];
const heights = [];
for (const row of rows) {
await expect(row).toBeVisible();
heights.push(Math.round((await row.boundingBox())!.height));
}
await page.screenshot({ path: testInfo.outputPath("compact-agent-settings.png") });
expect(new Set(heights).size, `row heights ${heights.join(", ")}`).toBe(1);
} finally {
await workspace.cleanup();
await seed.restore();
}
});
test("a model row and its create-profile action are separate buttons", async ({ page }) => {
const seed = await seedAgentProfiles([]);
const workspace = await seedMockAgentWorkspace({
@@ -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";
@@ -316,13 +317,17 @@ test.describe("Cross-provider model search", () => {
await expectComposerFocused(page);
});
await test.step("the compact drawer surfaces collapsed Profiles above Model on Home and keeps provider headers stable on collapse", async () => {
await test.step("the compact drawer opens a new agent's Profiles above Model on Home and keeps provider headers stable on collapse", async () => {
await page.setViewportSize({ width: 390, height: 800 });
await page.getByTestId("combined-model-selector").filter({ visible: true }).first().click();
const profilesToggle = page.getByTestId("agent-controls-profiles");
const profilesList = page.getByTestId("agent-controls-profiles-list");
const modelRowButton = page.getByTestId("agent-controls-model");
await expect(profilesToggle).toBeVisible();
await expect(page.getByTestId("agent-controls-profiles-list")).toHaveCount(0);
await expect(profilesList).toBeVisible();
await profilesToggle.click();
await expect(profilesList).toHaveCount(0);
await waitForSettledPosition(profilesToggle);
const profilesBox = await profilesToggle.boundingBox();
const modelBox = await modelRowButton.boundingBox();
expect(profilesBox && modelBox && profilesBox.y < modelBox.y).toBe(true);
@@ -359,6 +364,7 @@ test.describe("Cross-provider model search", () => {
// Return Home, expand Profiles in place, and apply the profile.
await page.getByTestId("sheet-header-back").click();
await expect(profilesList).toHaveCount(0);
await profilesToggle.click();
const sheetProfileRow = page.getByTestId("model-profile-row-agent_profile_e2e_arrows");
await expect(sheetProfileRow).toBeVisible();
@@ -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);
});
});
});
@@ -1,3 +1,4 @@
import { createServer, type Socket } from "node:net";
import { expect, test, type Page } from "../support/fixtures";
import { gotoAppShell } from "../support/helpers/app";
import { addScheduleHostAndReload, createScheduleHost } from "../support/helpers/schedule-host";
@@ -141,6 +142,68 @@ async function findScheduleIdByName(workspace: SeededWorkspace, name: string): P
return schedule.id;
}
async function createConnectingHost() {
const sockets = new Set<Socket>();
// Accept TCP without completing the WebSocket handshake, like a stalled host.
const server = createServer((socket) => {
sockets.add(socket);
socket.on("close", () => sockets.delete(socket));
});
await new Promise<void>((resolve, reject) => {
server.once("error", reject);
server.listen(0, "127.0.0.1", resolve);
});
const address = server.address();
if (!address || typeof address === "string") throw new Error("Expected a TCP address");
return {
port: address.port,
close: async () => {
for (const socket of sockets) socket.destroy();
await new Promise<void>((resolve, reject) => {
server.close((error) => {
if (error) {
reject(error);
return;
}
resolve();
});
});
},
};
}
async function openSchedulesWithConnectingHost(
page: Page,
cleanupTasks: Array<() => Promise<void>>,
): Promise<void> {
const workspace = await seedWorkspace({ repoPrefix: "schedule-partial-hosts-", git: false });
cleanupTasks.push(() => workspace.cleanup());
const stalledHost = await createConnectingHost();
cleanupTasks.push(() => stalledHost.close());
await gotoAppShell(page);
await waitForSidebarHydration(page);
await page.goto(buildSchedulesRoute());
await addScheduleHostAndReload({
page,
serverId: "stalled-schedule-host",
label: "Connecting host",
port: stalledHost.port,
});
}
async function expectPartialEmptySchedules(page: Page): Promise<void> {
await expect(page.getByText("No active schedules", { exact: true })).toBeVisible();
await expect(page.getByText("Connecting host: Still connecting", { exact: true })).toBeVisible();
await expect(page.getByRole("button", { name: "New schedule", exact: true })).toBeVisible();
}
async function expectScheduleCreationAvailable(page: Page): Promise<void> {
await openNewScheduleSheet(page);
await page.getByRole("button", { name: "Cancel", exact: true }).click();
await expect(page.getByTestId("schedule-form-sheet")).toHaveCount(0);
}
test.describe("Schedules project target", () => {
const cleanupTasks: Array<() => Promise<void>> = [];
@@ -151,6 +214,12 @@ test.describe("Schedules project target", () => {
cleanupTasks.length = 0;
});
test("shows empty schedules while another host is still connecting", async ({ page }) => {
await openSchedulesWithConnectingHost(page, cleanupTasks);
await expectPartialEmptySchedules(page);
await expectScheduleCreationAvailable(page);
});
test("dismisses the new schedule sheet without reopening", async ({ page }) => {
const workspace = await seedWorkspace({ repoPrefix: "schedule-sheet-dismiss-", git: false });
cleanupTasks.push(() => workspace.cleanup());
@@ -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);
}
@@ -46,7 +46,7 @@ import { installDaemonWebSocketGate } from "../support/helpers/daemon-websocket-
import { addConnectedHostAndReload, addOfflineHostAndReload } from "../support/helpers/hosts";
import { startIsolatedHostDaemon } from "../support/helpers/isolated-host-daemon";
const LOADING_WORKSPACE_TEXT_PATTERN = /Loading workspace/i;
const LOADING_WORKSPACE_TEST_ID = "workspace-loading";
async function expectNoLoadingWorkspacePane(
page: Page,
input: { label: string; durationMs?: number },
@@ -63,7 +63,7 @@ async function expectNoLoadingWorkspacePane(
.catch((error) => `[body unavailable: ${error instanceof Error ? error.message : error}]`);
samples.push(`${Date.now() - startedAt}ms ${url}\n${text.slice(0, 1000)}`);
if (LOADING_WORKSPACE_TEXT_PATTERN.test(text)) {
if ((await page.getByTestId(LOADING_WORKSPACE_TEST_ID).count()) > 0) {
throw new Error(
`${input.label}: loading workspace pane appeared during reconnect window.\n\n${samples.join(
"\n\n---\n\n",
@@ -76,7 +76,7 @@ async function expectNoLoadingWorkspacePane(
}
async function expectNoLoadingPane(page: Page): Promise<void> {
await expect(page.getByText(LOADING_WORKSPACE_TEXT_PATTERN)).toHaveCount(0);
await expect(page.getByTestId(LOADING_WORKSPACE_TEST_ID)).toHaveCount(0);
}
async function getVisibleDraftTabCount(page: Page): Promise<number> {
@@ -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 },
);
@@ -173,8 +173,11 @@ export async function expectHostConnectingOrOffline(
page: Page,
options?: { timeout?: number },
): Promise<void> {
// A host that is still connecting shows the workspace loading state; one that failed says so.
await expect(
page.getByText(/^Connecting$|localhost is offline|Cannot reach localhost/i),
page
.getByTestId("workspace-loading")
.or(page.getByText(/localhost is offline|Cannot reach localhost/i)),
).toBeVisible({ timeout: options?.timeout ?? 30_000 });
}
+2
View File
@@ -1,6 +1,8 @@
// Install runtime polyfills before any other module evaluates. Keep this the first import.
// oxlint-disable-next-line import/no-unassigned-import -- Polyfills install on import.
import "./src/polyfills/install-early";
import { keepNativeSplash } from "./src/native-splash";
keepNativeSplash();
// Configure Unistyles before Expo Router pulls in any components using StyleSheet.
import "./src/styles/unistyles";
@@ -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
@@ -0,0 +1,22 @@
const { AndroidConfig, withAndroidStyles } = require("expo/config-plugins");
// The activity window shows under the splash while it fades out and until React
// paints. Expo's AppTheme sets no window background, so Android paints the
// AppCompat default (#303030 in dark mode, #fafafa in light mode) there.
// expo-splash-screen already defines `splashscreen_background` for day and night,
// so pointing the window at it keeps one colour from launch to the first screen.
const WINDOW_BACKGROUND = "@color/splashscreen_background";
function withAndroidSplashWindowBackground(config) {
return withAndroidStyles(config, (modConfig) => {
modConfig.modResults = AndroidConfig.Styles.assignStylesValue(modConfig.modResults, {
add: true,
parent: AndroidConfig.Styles.getAppThemeGroup(),
name: "android:windowBackground",
value: WINDOW_BACKGROUND,
});
return modConfig;
});
}
module.exports = withAndroidSplashWindowBackground;
+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 },
@@ -43,6 +43,8 @@ export interface AgentProfilePickerRow {
export interface AgentProfilePicker {
rows: AgentProfilePickerRow[];
applyProfile: (profileId: string) => void;
/** What a picked profile configures: a running agent, or the draft of a new one. */
target: AgentProfileApplyTarget["kind"];
}
export interface UseAgentProfilePickerInput {
@@ -166,7 +168,7 @@ export function useAgentProfilePicker(
);
return useMemo(
() => (isSupported && profiles !== null ? { rows, applyProfile } : null),
[applyProfile, isSupported, profiles, rows],
() => (isSupported && profiles !== null ? { rows, applyProfile, target: target.kind } : null),
[applyProfile, isSupported, profiles, rows, target.kind],
);
}
+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);
},
@@ -26,8 +26,10 @@ import {
} from "@legendapp/list/react-native";
import { withUnistyles } from "react-native-unistyles";
import { LoadingSpinner } from "@/components/ui/loading-spinner";
import { LoadingState } from "@/components/ui/loading-state";
import { Button } from "@/components/ui/button";
import { useRetainedPanelActive } from "@/components/retained-panel";
import { useNativeSplashHold } from "@/native-splash";
import { useTranslation } from "react-i18next";
import type { StreamItem } from "@/types/stream";
import type { Theme } from "@/styles/theme";
@@ -761,6 +763,9 @@ function NativeStreamViewport(props: StreamRenderInput & { strategy: StreamStrat
);
}, [historyStartPaginationState, hasOlderHistory, retryHistoryStart, t]);
// The launch splash stays up until the visible conversation has placed its rows. A hidden first
// fill means the cache had no history, so it waits on the host and shows its own loading state.
useNativeSplashHold(isActive && !isListPlaced);
const canExpandDrawDistance =
drawDistance < NATIVE_STREAM_DRAW_DISTANCE &&
isActive &&
@@ -807,8 +812,8 @@ function NativeStreamViewport(props: StreamRenderInput & { strategy: StreamStrat
<InitialDrawDistanceExpansion schedule={drawDistanceExpansion.schedule} />
) : null}
{!historyStartPaginationState.visible ? (
<View pointerEvents="none" testID="agent-initial-fill" style={initialFillStyle}>
<ThemedLoadingSpinner size="large" uniProps={foregroundMutedColorMapping} />
<View pointerEvents="none" style={initialFillStyle}>
<LoadingState testID="agent-initial-fill" title={t("agentPanel.states.loadingHistory")} />
</View>
) : null}
</View>
@@ -19,6 +19,7 @@ import { flushSync } from "react-dom";
import { withUnistyles } from "react-native-unistyles";
import { useRetainedPanelActive } from "@/components/retained-panel";
import { LoadingSpinner } from "@/components/ui/loading-spinner";
import { LoadingState } from "@/components/ui/loading-state";
import { useStableEvent } from "@/hooks/use-stable-event";
import { useTranslation } from "react-i18next";
import { getStreamItemMessageId, type StreamItem } from "@/types/stream";
@@ -1719,8 +1720,8 @@ function WebStreamViewport(props: StreamRenderInput & { isMobileBreakpoint: bool
</div>
</div>
{!historyStartPaginationState.visible ? (
<div data-testid="agent-initial-fill" style={initialFillStyle}>
<ThemedLoadingSpinner size="large" uniProps={foregroundMutedColorMapping} />
<div style={initialFillStyle}>
<LoadingState testID="agent-initial-fill" title={t("agentPanel.states.loadingHistory")} />
</div>
) : null}
{scrollEnabled && !isMobileBreakpoint ? (
+18 -28
View File
@@ -1,4 +1,5 @@
import { useHardwareKeyboardPresent } from "@/keyboard";
import { LaunchScreen, useNativeSplashLaunchCommit } from "@/native-splash";
import {
WindowLayoutProvider,
WindowLayoutActionsHost,
@@ -78,12 +79,10 @@ 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,
resolveStartupNavigationReady,
shouldRunStartupGiveUpTimer,
startHostRuntimeBootstrap,
bindHostRuntimeAppState,
type StartupBlocker,
@@ -157,7 +156,7 @@ polyfillCrypto();
export interface HostRuntimeBootstrapState {
splashError: string | null;
retry: () => void;
hasGivenUpWaitingForHost: boolean;
isWaitingForHost: boolean;
isWaitingForSetup: boolean;
storeReady: boolean;
startupBlocker: StartupBlocker;
@@ -166,7 +165,7 @@ export interface HostRuntimeBootstrapState {
const HostRuntimeBootstrapContext = createContext<HostRuntimeBootstrapState>({
splashError: null,
retry: () => {},
hasGivenUpWaitingForHost: false,
isWaitingForHost: true,
isWaitingForSetup: false,
storeReady: false,
startupBlocker: { kind: "none" },
@@ -263,7 +262,6 @@ function useDaemonStartIsRunning(): boolean {
);
}
const STARTUP_GIVE_UP_TIMEOUT_MS = 5_000;
// How long the splash waits on top of host startup to learn whether setup opens. A slow host
// lands on the home instead, and setup opens over it once it is decided.
const STARTUP_SETUP_WAIT_TIMEOUT_MS = 3_000;
@@ -285,20 +283,29 @@ function HostRuntimeBootstrapProvider({ children }: { children: ReactNode }) {
return bindHostRuntimeAppState(store, AppState);
}, []);
const [isWaitingForHost, setIsWaitingForHost] = useState(true);
useEffect(() => {
let isMounted = true;
const store = getHostRuntimeStore();
const daemonStartService = getDaemonStartService({ store });
startHostRuntimeBootstrap({
void startHostRuntimeBootstrap({
store,
daemonStartService,
shouldStartDaemon: shouldStartBuiltInDaemon,
}).then(() => {
if (isMounted) {
setIsWaitingForHost(false);
}
return;
});
return () => {
isMounted = false;
};
}, []);
const anyOnlineHostServerId = useEarliestOnlineHostServerId();
const daemonStartError = useDaemonStartLastError();
const daemonStartIsRunning = useDaemonStartIsRunning();
const [hasGivenUpWaitingForHost, setHasGivenUpWaitingForHost] = useState(false);
const isDesktopRuntime = shouldUseDesktopDaemon();
const startupBlocker = useMemo(
() =>
@@ -310,24 +317,6 @@ function HostRuntimeBootstrapProvider({ children }: { children: ReactNode }) {
}),
[anyOnlineHostServerId, daemonStartError, daemonStartIsRunning, isDesktopRuntime],
);
const shouldRunGiveUpTimer = shouldRunStartupGiveUpTimer({
startupBlocker,
anyOnlineHostServerId,
hasGivenUpWaitingForHost,
});
useEffect(() => {
if (!shouldRunGiveUpTimer) {
return;
}
const handle = setTimeout(() => {
setHasGivenUpWaitingForHost(true);
}, STARTUP_GIVE_UP_TIMEOUT_MS);
return () => {
clearTimeout(handle);
};
}, [shouldRunGiveUpTimer]);
const isSetupDecisionPending = useIsSetupDecisionPending();
const [hasGivenUpWaitingForSetup, setHasGivenUpWaitingForSetup] = useState(false);
const isWaitingForSetup = isSetupDecisionPending && !hasGivenUpWaitingForSetup;
@@ -358,12 +347,12 @@ function HostRuntimeBootstrapProvider({ children }: { children: ReactNode }) {
() => ({
splashError,
retry,
hasGivenUpWaitingForHost,
isWaitingForHost,
isWaitingForSetup,
storeReady,
startupBlocker,
}),
[splashError, retry, hasGivenUpWaitingForHost, isWaitingForSetup, storeReady, startupBlocker],
[splashError, retry, isWaitingForHost, isWaitingForSetup, storeReady, startupBlocker],
);
return (
@@ -916,6 +905,7 @@ const ROOT_STACK_SCREEN_OWNED_APPEARANCE = ["settings/[section]"] as const;
function RootStack() {
const storeReady = useStoreReady();
useNativeSplashLaunchCommit();
return (
<ThemedStack
screenOptions={ROOT_STACK_SCREEN_OPTIONS}
@@ -1004,7 +994,6 @@ function RootOverlayProviders({ children }: { children: ReactNode }) {
<BottomSheetModalProvider>
{children}
<WindowLayoutActionsHost />
<WorkspaceTabCloseErrorToasts />
</BottomSheetModalProvider>
</PortalProvider>
</ToastProvider>
@@ -1045,6 +1034,7 @@ function RootAppTree() {
</AddHostProvider>
</LucideProvider>
</View>
<LaunchScreen />
</GestureHandlerRootView>
);
}
+14 -10
View File
@@ -24,16 +24,20 @@ export default function HostIndexRoute() {
return <StartupSplashScreen />;
}
// The loading screen stays up until the target route paints; a redirect alone renders nothing.
return (
<Redirect
href={resolveHostIndexRoute({
serverId,
workspaceSelection,
workspaceSelectionStatus: resolveWorkspaceSelectionStatus({
hasHydratedWorkspaces,
workspaceExists: workspaceSelectionExists,
}),
})}
/>
<>
<StartupSplashScreen />
<Redirect
href={resolveHostIndexRoute({
serverId,
workspaceSelection,
workspaceSelectionStatus: resolveWorkspaceSelectionStatus({
hasHydratedWorkspaces,
workspaceExists: workspaceSelectionExists,
}),
})}
/>
</>
);
}
+1 -1
View File
@@ -44,7 +44,7 @@ export default function Index() {
workspaceExists: workspaceSelectionExists,
}),
isWorkspaceSelectionLoaded,
hasGivenUpWaitingForHost: bootstrapState.hasGivenUpWaitingForHost,
isWaitingForHost: bootstrapState.isWaitingForHost,
isWaitingForSetup: bootstrapState.isWaitingForSetup,
});
@@ -308,6 +308,24 @@ describe("parseAssistantFileLink", () => {
});
});
it.each(["C:/repo", "\\\\host\\share\\repo"])(
"leaves Windows variable paths in inline code unlinked in %s",
(workspaceRoot) => {
expect(classifyAssistantFileLink("%TEMP%\\debug.md", { workspaceRoot })).toBeNull();
expect(classifyAssistantFileLink("%LOCALAPPDATA%/debug.md:3", { workspaceRoot })).toBeNull();
expect(classifyAssistantFileLink("C:\\Temp\\debug.md", { workspaceRoot })?.kind).toBe(
"directFile",
);
},
);
it("allows a literal percent-delimited directory in an authored file link", () => {
expect(
parseAssistantFileLink("%TEMP%/notes.md", { workspaceRoot: "C:/repo", explicitLink: true })
?.path,
).toBe("C:/repo/%TEMP%/notes.md");
});
it("parses absolute Windows hrefs inside the active workspace", () => {
expect(
parseAssistantFileLink("C:/repo/src/app.tsx#L12-L20", {
@@ -393,6 +393,14 @@ function parseWorkspaceRelativeFileLink(
value: string,
options: AssistantHrefParseOptions,
): InlinePathTarget | null {
// cmd.exe variables are shell expressions. The file opener only resolves literal paths.
if (
!options.explicitLink &&
/^(?:[A-Za-z]:[\\/]|[\\/]{2})/.test(options.workspaceRoot ?? "") &&
/^%[^%\\/]+%[\\/]/.test(value)
) {
return null;
}
const parsed = parseLocalPathParts(value, options);
if (!parsed || isAbsolutePath(parsed.path)) {
return null;
@@ -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);
@@ -1,10 +1,13 @@
import React, { act } from "react";
import React, { act, useCallback, useState } from "react";
import { createRoot, type Root } from "react-dom/client";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { persistAttachmentFromBlob } from "@/attachments/service";
import { SafeAreaProvider } from "react-native-safe-area-context";
import { i18n } from "@/i18n/i18next";
import { WindowLayoutProvider } from "@/window-layout";
import { RetainedPanelActivity } from "@/components/retained-panel";
import { RetainedChatContent as NativeChatContent } from "@/panels/retained-chat-content.native";
import { RetainedChatContent as WebChatContent } from "@/panels/retained-chat-content.web";
import { AttachmentLightbox, type ImageLightboxSource } from "./attachment-lightbox";
interface FrameSample {
@@ -147,3 +150,48 @@ describe("AttachmentLightbox opening in the browser", () => {
await expectOpeningPaintsOnlyTheFittedImage({ type: "uri", uri });
});
});
let openImage: (() => void) | null = null;
function ThreadWithImage({ uri }: { uri: string }) {
const [source, setSource] = useState<ImageLightboxSource | null>(null);
openImage = () => setSource({ type: "uri", uri });
const close = useCallback(() => setSource(null), []);
return <AttachmentLightbox source={source} onClose={close} />;
}
function isLightboxShown(): boolean {
return document.querySelector('[data-testid="attachment-lightbox-backdrop"]') !== null;
}
describe("AttachmentLightbox when its chat leaves the screen", () => {
for (const [platform, ChatContent] of [
["web", WebChatContent],
["native", NativeChatContent],
] as const) {
it(`closes on ${platform} when another session takes over, and stays closed on return`, async () => {
const uri = URL.createObjectURL(await createPng(400, 300));
const showThread = (active: boolean) =>
root.render(
<SafeAreaProvider>
<WindowLayoutProvider>
<RetainedPanelActivity active={active}>
<ChatContent>
<ThreadWithImage uri={uri} />
</ChatContent>
</RetainedPanelActivity>
</WindowLayoutProvider>
</SafeAreaProvider>,
);
await act(async () => showThread(true));
await act(async () => openImage?.());
expect(isLightboxShown()).toBe(true);
await act(async () => showThread(false));
expect(isLightboxShown()).toBe(false);
await act(async () => showThread(true));
expect(isLightboxShown()).toBe(false);
});
}
});
@@ -13,6 +13,7 @@ import {
useAttachmentPreviewUrl,
} from "@/attachments/use-attachment-preview-url";
import { isNative } from "@/constants/platform";
import { useRetainedPanelActive } from "@/components/retained-panel";
import { SPACING } from "@/styles/theme";
import { WindowChromeRootRegion } from "@/utils/desktop-window";
import { ZoomableImage } from "@/components/zoomable-viewport/image";
@@ -42,12 +43,21 @@ export function AttachmentLightbox({ source, onClose }: AttachmentLightboxProps)
const contentSize = source?.type === "uri" ? source.contentSize : undefined;
const [errored, setErrored] = useState(false);
const failed = errored || image.status === "failed";
const modalLayer = useGlobalOverlayLayer("modal", source !== null);
const panelActive = useRetainedPanelActive();
const open = source !== null && panelActive;
const modalLayer = useGlobalOverlayLayer("modal", open);
useEffect(() => {
setErrored(false);
}, [metadata?.id, url]);
// The image belongs to the panel that opened it and closes for good when that panel leaves the
// screen. On web the Modal portals out of the hidden panel, and the hidden chat is frozen on the
// next commit, so the lightbox must also unmount in this inactive commit (see MenuSurface).
useEffect(() => {
if (source !== null && !panelActive) onClose();
}, [onClose, panelActive, source]);
const handleOverlayKeyDown = useCallback(
(event: KeyboardInputEvent) => {
if (event.key !== "Escape") return false;
@@ -60,7 +70,7 @@ export function AttachmentLightbox({ source, onClose }: AttachmentLightboxProps)
);
const setOverlayScope = useOverlayRegistration({
keys: ["Escape"],
active: source !== null,
active: open,
layer: modalLayer,
onKeyDown: handleOverlayKeyDown,
});
@@ -79,7 +89,7 @@ export function AttachmentLightbox({ source, onClose }: AttachmentLightboxProps)
const handleImageError = useCallback(() => setErrored(true), []);
if (!source) {
if (!open) {
return null;
}
@@ -84,6 +84,9 @@ export function DraggableListHandle({ testID, style, children }: DraggableListHa
}
const SCROLL_ENABLED_FLEX_STYLE = { flex: 1 };
// Viewports of rows a nestable list keeps rendered around the container's viewport: two above,
// two below. FlatList's default of 21 would still render a long sidebar in full.
const NESTED_WINDOW_SIZE = 5;
// A drop remounts every row between the drag's start and end slots (see the draggable-flatlist
// patch), so state held inside a rendered row resets when a drop moves it. Keep state that must
@@ -206,9 +209,12 @@ export function DraggableList<T>({
showsVerticalScrollIndicator={showsVerticalScrollIndicator}
scrollEnabled={scrollEnabled}
// A list that doesn't scroll shows every row, so it renders them all in its first commit.
// FlatList's default first render is 10 rows; a nested list remounted by a drop would paint
// 10 rows, then grow on a later commit.
initialNumToRender={scrollEnabled ? undefined : data.length}
// FlatList's default first render is 10 rows; a list remounted by a drop would paint 10
// rows, then grow on a later commit. A nestable list is the exception: its
// NestableScrollContainer is a VirtualizedList, so it renders only the rows near that
// container's viewport, and a hidden sidebar does not render rows nobody can see.
initialNumToRender={scrollEnabled || nestable ? undefined : data.length}
windowSize={nestable ? NESTED_WINDOW_SIZE : undefined}
extraData={extraData}
simultaneousHandlers={simultaneousHandlers}
dragGestureHostPresented={gestureHostPresented}
@@ -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,
@@ -37,7 +37,7 @@ export type { SettingsRowHintStatus } from "./row-header";
export { SettingsAddRow } from "./add-row";
export { SettingsBackLink, SettingsDetailHeader } from "./detail-header";
export { SettingsInfoTip } from "./headings/settings-info-tip";
export { MenuSettingsRows } from "./row-density";
export { ListSettingsRows, MenuSettingsRows } from "./row-density";
/**
* What app screens can add to a plugin-facing row: an accessory beside the label, such as an info
@@ -1,7 +1,12 @@
import { createContext, useContext, useMemo, type ReactNode } from "react";
import type { StyleProp, TextStyle, ViewStyle } from "react-native";
import { StyleSheet } from "react-native-unistyles";
import { CONTROL_HEIGHTS, mapLayout, type ControlSize } from "@/components/ui/control-geometry";
import {
CONTROL_HEIGHTS,
mapLayout,
TOUCH_TARGET,
type ControlSize,
} from "@/components/ui/control-geometry";
import { menuRowContentInset } from "@/components/ui/menu";
import { settingsStyles } from "@/styles/settings";
@@ -12,7 +17,9 @@ import { settingsStyles } from "@/styles/settings";
// - nested: rows revealed under a collapsible row belong to it, so they sit one step smaller than
// the rows of the card: tighter padding, smaller text, smaller controls.
// - menu: rows that share a menu surface with menu rows put their labels on the menu's label rail.
type RowPlacement = "card" | "nested" | "menu";
// - list: rows that share a sheet with list rows, such as radio choices and section headers, take
// the list row's height so every row in the sheet lines up.
type RowPlacement = "card" | "nested" | "menu" | "list";
const RowPlacementContext = createContext<RowPlacement>("card");
@@ -25,6 +32,11 @@ export function MenuSettingsRows({ children }: { children: ReactNode }) {
return <RowPlacementContext.Provider value="menu">{children}</RowPlacementContext.Provider>;
}
/** Settings rows rendered in a sheet of list rows, such as Agent settings. */
export function ListSettingsRows({ children }: { children: ReactNode }) {
return <RowPlacementContext.Provider value="list">{children}</RowPlacementContext.Provider>;
}
export interface SettingsRowLayout {
row: StyleProp<ViewStyle>;
title: StyleProp<TextStyle>;
@@ -49,6 +61,13 @@ function layoutFor(placement: RowPlacement): SettingsRowLayout {
hint: settingsStyles.rowHint,
controlSize: "md",
};
case "list":
return {
row: [settingsStyles.row, styles.listRow],
title: settingsStyles.rowTitle,
hint: settingsStyles.rowHint,
controlSize: "md",
};
case "card":
return {
row: settingsStyles.row,
@@ -72,6 +91,11 @@ const styles = StyleSheet.create((theme) => ({
paddingVertical: theme.spacing[2],
minHeight: mapLayout(CONTROL_HEIGHTS.sm, (height) => height + theme.spacing[2] * 2),
},
// A list row is a touch target tall on every input; a switch still fits inside its padding.
listRow: {
paddingVertical: theme.spacing[2],
minHeight: TOUCH_TARGET,
},
nestedText: {
fontSize: theme.fontSize.sm,
},
@@ -2311,7 +2311,7 @@ function ProjectModeList({
() =>
parentGestureRef
? ({
// NestableScrollContainer forwards props to RNGH ScrollView. Keep
// NestableScrollContainer forwards props to an RNGH FlatList. Keep
// vertical scroll and sidebar close pan simultaneous: vertical
// intent scrolls immediately, clear horizontal intent can still
// activate close from inside the list.
@@ -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>
);
}
@@ -0,0 +1,36 @@
import React, { act } from "react";
import { createRoot, type Root } from "react-dom/client";
import { afterEach, beforeEach, expect, it, vi } from "vitest";
import { page } from "vitest/browser";
import { i18n } from "@/i18n/i18next";
import { LoadingSpinner } from "./loading-spinner";
let root: Root;
let host: HTMLDivElement;
beforeEach(async () => {
await i18n.changeLanguage("en");
vi.stubGlobal("React", React);
vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
host = document.createElement("div");
document.body.appendChild(host);
root = createRoot(host);
});
afterEach(() => {
act(() => root.unmount());
host.remove();
vi.unstubAllGlobals();
});
it("announces itself as loading when the caller gives no label", async () => {
act(() => root.render(<LoadingSpinner color="#888888" />));
await expect.element(page.getByRole("progressbar", { name: "Loading..." })).toBeVisible();
});
it("announces what is loading when the caller names it", async () => {
act(() => root.render(<LoadingSpinner color="#888888" accessibilityLabel="Loading commits" />));
await expect.element(page.getByRole("progressbar", { name: "Loading commits" })).toBeVisible();
});
@@ -1,12 +1,29 @@
import React from "react";
import { useTranslation } from "react-i18next";
import { ActivityIndicator, type ActivityIndicatorProps } from "react-native";
interface LoadingSpinnerProps {
color: string;
size?: ActivityIndicatorProps["size"];
style?: ActivityIndicatorProps["style"];
/** What is loading. Screen readers announce "Loading" when this is absent. */
accessibilityLabel?: string;
}
export function LoadingSpinner({ color, size = "small", style }: LoadingSpinnerProps) {
return <ActivityIndicator size={size} color={color} style={style} />;
export function LoadingSpinner({
color,
size = "small",
style,
accessibilityLabel,
}: LoadingSpinnerProps) {
const { t } = useTranslation();
return (
<ActivityIndicator
size={size}
color={color}
style={style}
accessibilityRole="progressbar"
accessibilityLabel={accessibilityLabel ?? t("common.loading")}
/>
);
}
@@ -0,0 +1,66 @@
import { Text, View } from "react-native";
import { StyleSheet, withUnistyles } from "react-native-unistyles";
import { LoadingSpinner } from "@/components/ui/loading-spinner";
import type { Theme } from "@/styles/theme";
const ThemedLoadingSpinner = withUnistyles(LoadingSpinner);
const foregroundMutedColorMapping = (theme: Theme) => ({
color: theme.colors.foregroundMuted,
});
/**
* A screen or pane waiting for its content. Every wait shows the same spinner in the same place,
* so a wait that changes what it is waiting for changes only the words under it.
*/
export function LoadingState({
title,
description,
testID,
}: {
/** What the wait is for. Leave it out while the wait is too short to read. */
title?: string;
description?: string;
testID?: string;
}) {
return (
<View style={styles.container} testID={testID}>
<ThemedLoadingSpinner
size="small"
uniProps={foregroundMutedColorMapping}
accessibilityLabel={title}
/>
{title ? (
<View style={styles.textStack}>
<Text style={styles.title}>{title}</Text>
{description ? <Text style={styles.description}>{description}</Text> : null}
</View>
) : null}
</View>
);
}
const styles = StyleSheet.create((theme) => ({
container: {
flex: 1,
alignItems: "center",
justifyContent: "center",
gap: theme.spacing[3],
paddingHorizontal: theme.spacing[6],
},
textStack: {
alignItems: "center",
gap: theme.spacing[2],
maxWidth: 520,
},
title: {
color: theme.colors.foreground,
fontSize: theme.fontSize.base,
fontWeight: theme.fontWeight.normal,
textAlign: "center",
},
description: {
color: theme.colors.foregroundMuted,
fontSize: theme.fontSize.base,
textAlign: "center",
},
}));
@@ -88,7 +88,11 @@ export function AgentSettingsDrawer({
}: AgentSettingsDrawerProps) {
const { t } = useTranslation();
const [page, setPage] = useState<AgentSheetPage>(AGENT_SHEET_HOME);
const [profilesExpanded, setProfilesExpanded] = useState(false);
// Profiles open on Home for a new agent, where a profile is the quickest way to configure it.
// `null` until the user toggles the card in this opening.
const [profilesToggled, setProfilesToggled] = useState<boolean | null>(null);
const profilesExpanded =
profilesToggled ?? (profiles?.target === "draft" && profiles.rows.length > 0);
// Select pages search with this; the Model page keeps its own.
const [pageQuery, setPageQuery] = useState("");
const [pageSearchKey, setPageSearchKey] = useState(0);
@@ -103,8 +107,8 @@ export function AgentSettingsDrawer({
});
const toggleProfiles = useCallback(() => {
setProfilesExpanded((expanded) => !expanded);
}, []);
setProfilesToggled(!profilesExpanded);
}, [profilesExpanded]);
const goTo = useCallback((next: AgentSheetPage) => {
Keyboard.dismiss();
@@ -125,7 +129,7 @@ export function AgentSettingsDrawer({
const close = useCallback(() => {
Keyboard.dismiss();
setPage(AGENT_SHEET_HOME);
setProfilesExpanded(false);
setProfilesToggled(null);
setPageQuery("");
modelPage.reset();
onClose();
@@ -8,6 +8,7 @@ import type { AgentMode } from "@getpaseo/protocol/agent-types";
import { getAgentModeOptionIcon } from "@/agent-controls/icons";
import { formatAgentModeLabel } from "@/agent-controls/labels";
import {
ListSettingsRows,
SettingsCard,
SettingsDetailRow,
SettingsSection,
@@ -19,6 +20,7 @@ import { PressHighlight } from "@/components/ui/press-highlight";
import { ScrollView as SheetScrollView } from "@/components/ui/scroll-view";
import { SegmentedControl, type SegmentedControlOption } from "@/components/ui/segmented-control";
import { SteppedSlider, type SteppedSliderOption } from "@/components/ui/stepped-slider";
import { TOUCH_TARGET } from "@/components/ui/control-geometry";
import { isNative } from "@/constants/platform";
import { ICON_SIZE } from "@/styles/theme";
import {
@@ -85,17 +87,19 @@ export function AgentSheetHome({
>
{/* Themed insets sit on a View: the sheet scroller drops a themed contentContainerStyle on web. */}
<View style={styles.content}>
<View style={styles.block}>{topCard}</View>
{blocks.map((block) => (
<HomeBlock
key={blockKey(block)}
block={block}
modeControl={modeControl}
disabled={disabled}
onOpenSelect={onOpenSelect}
/>
))}
{footer}
<ListSettingsRows>
<View style={styles.block}>{topCard}</View>
{blocks.map((block) => (
<HomeBlock
key={blockKey(block)}
block={block}
modeControl={modeControl}
disabled={disabled}
onOpenSelect={onOpenSelect}
/>
))}
{footer}
</ListSettingsRows>
</View>
</SheetScrollView>
);
@@ -663,7 +667,7 @@ const styles = StyleSheet.create((theme) => ({
fontSize: theme.fontSize.base,
},
radioRow: {
minHeight: 44,
minHeight: TOUCH_TARGET,
flexDirection: "row",
alignItems: "center",
paddingHorizontal: theme.spacing[4],
+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(
@@ -43,7 +43,7 @@ describe("schedule mutation cache updates", () => {
const current: FetchAggregatedSchedulesResult = {
status: "loaded",
data: [schedule()],
hostErrors: [],
hostWarnings: [],
};
const result = updateAggregatedSchedulesData(current, pauseSchedules);
@@ -51,7 +51,7 @@ describe("schedule mutation cache updates", () => {
expect(result).toEqual({
status: "loaded",
data: [schedule({ status: "paused" })],
hostErrors: [],
hostWarnings: [],
});
});
@@ -69,7 +69,7 @@ describe("schedule mutation cache updates", () => {
const loaded: FetchAggregatedSchedulesResult = {
status: "loaded",
data: [schedule()],
hostErrors: [],
hostWarnings: [],
};
queryClient.setQueryData(connectingKey, connecting);
queryClient.setQueryData(loadedKey, loaded);
@@ -85,7 +85,7 @@ describe("schedule mutation cache updates", () => {
expect(queryClient.getQueryData(loadedKey)).toEqual({
status: "loaded",
data: [schedule({ status: "paused" })],
hostErrors: [],
hostWarnings: [],
});
});
});
+4 -4
View File
@@ -10,14 +10,14 @@ import {
schedulesQueryBaseKey,
type AggregateLoadState,
type AggregatedSchedule,
type ScheduleHostError,
type ScheduleHostWarning,
type ScheduleHostInput,
} from "@/schedules/aggregated-schedules";
export type {
AggregateLoadState,
AggregatedSchedule,
ScheduleHostError,
ScheduleHostWarning,
} from "@/schedules/aggregated-schedules";
export function schedulesQueryKey(serverIds: readonly string[]) {
@@ -26,7 +26,7 @@ export function schedulesQueryKey(serverIds: readonly string[]) {
export interface UseSchedulesResult {
loadState: AggregateLoadState<AggregatedSchedule>;
hostErrors: ScheduleHostError[];
hostWarnings: ScheduleHostWarning[];
isError: boolean;
error: Error | null;
refetch: () => void;
@@ -65,7 +65,7 @@ export function useSchedules(): UseSchedulesResult {
return {
loadState,
hostErrors: query.data?.status === "loaded" ? query.data.hostErrors : [],
hostWarnings: query.data?.status === "loaded" ? query.data.hostWarnings : [],
isError: query.isError,
error: query.error,
refetch: () => {
+2
View File
@@ -278,6 +278,8 @@ export const ar: TranslationResources = {
failedToLoad: "فشل تحميل الوكيل",
reconnecting: "جارٍ إعادة الاتصال",
updating: "جارٍ تحديث الرسائل",
loadingAgent: "جارٍ تحميل الوكيل",
loadingHistory: "جارٍ تحميل سجل الوكيل",
timelineSyncFailed: "تعذر تحديث سجل الوكيل.",
timelineSyncRetrying: "جارٍ إعادة المحاولة…",
archivingTitle: "وكيل الارشيف...",
+2
View File
@@ -276,6 +276,8 @@ export const en = {
failedToLoad: "Failed to load agent",
reconnecting: "Reconnecting",
updating: "Updating messages",
loadingAgent: "Loading agent",
loadingHistory: "Loading agent history",
timelineSyncFailed: "Couldn't refresh agent history.",
timelineSyncRetrying: "Retrying…",
archivingTitle: "Archiving agent...",
+2
View File
@@ -280,6 +280,8 @@ export const es: TranslationResources = {
failedToLoad: "No se pudo cargar el agente",
reconnecting: "Reconectando",
updating: "Actualizando mensajes",
loadingAgent: "Cargando agente",
loadingHistory: "Cargando historial del agente",
timelineSyncFailed: "No se pudo actualizar el historial del agente.",
timelineSyncRetrying: "Reintentando…",
archivingTitle: "Agente de archivo...",
+2
View File
@@ -281,6 +281,8 @@ export const fr: TranslationResources = {
failedToLoad: "Impossible de charger l’agent",
reconnecting: "Reconnexion…",
updating: "Mise à jour des messages…",
loadingAgent: "Chargement de l’agent",
loadingHistory: "Chargement de l’historique de l’agent",
timelineSyncFailed: "Impossible d’actualiser l’historique de l’agent.",
timelineSyncRetrying: "Nouvelle tentative…",
archivingTitle: "Archivage de l’agent…",
+2
View File
@@ -280,6 +280,8 @@ export const ja: TranslationResources = {
failedToLoad: "エージェントの読み込みに失敗しました",
reconnecting: "再接続中",
updating: "メッセージを更新中",
loadingAgent: "エージェントを読み込み中",
loadingHistory: "エージェントの履歴を読み込み中",
timelineSyncFailed: "エージェントの履歴を更新できませんでした。",
timelineSyncRetrying: "再試行しています…",
archivingTitle: "エージェントをアーカイブ中...",
+2
View File
@@ -278,6 +278,8 @@ export const ko: TranslationResources = {
failedToLoad: "에이전트를 불러오지 못했습니다",
reconnecting: "다시 연결하는 중",
updating: "메시지 업데이트 중",
loadingAgent: "에이전트 불러오는 중",
loadingHistory: "에이전트 기록 불러오는 중",
timelineSyncFailed: "에이전트 기록을 새로고침할 수 없습니다.",
timelineSyncRetrying: "재시도 중…",
archivingTitle: "에이전트 보관 중...",
+2
View File
@@ -279,6 +279,8 @@ export const ptBR: TranslationResources = {
failedToLoad: "Falha ao carregar agente",
reconnecting: "Reconectando",
updating: "Atualizando mensagens",
loadingAgent: "Carregando agente",
loadingHistory: "Carregando histórico do agente",
timelineSyncFailed: "Não foi possível atualizar o histórico do agente.",
timelineSyncRetrying: "Tentando novamente…",
archivingTitle: "Arquivando agente...",
+2
View File
@@ -280,6 +280,8 @@ export const ru: TranslationResources = {
failedToLoad: "Не удалось загрузить агента",
reconnecting: "Повторное подключение",
updating: "Обновление сообщений",
loadingAgent: "Загрузка агента",
loadingHistory: "Загрузка истории агента",
timelineSyncFailed: "Не удалось обновить историю агента.",
timelineSyncRetrying: "Повторная попытка…",
archivingTitle: "Агент перемещается в архив...",
+2
View File
@@ -278,6 +278,8 @@ export const zhCN: TranslationResources = {
failedToLoad: "加载 Agent 失败",
reconnecting: "正在重新连接",
updating: "正在更新消息",
loadingAgent: "正在加载代理",
loadingHistory: "正在加载代理历史记录",
timelineSyncFailed: "无法刷新代理历史记录。",
timelineSyncRetrying: "正在重试…",
archivingTitle: "正在归档 Agent...",
+51
View File
@@ -0,0 +1,51 @@
import { useEffect, useLayoutEffect } from "react";
import { createNativeSplashController, type NativeSplashController } from "./internal/controller";
import { launchSurface } from "./internal/launch-surface";
export { LaunchScreen } from "./internal/launch-surface";
// Guards against a screen that never releases its hold. A slow device places the first
// conversation 2-4 s after the JS entry, so a shorter cap cuts in before it paints.
const CAP_MS = 5_000;
let controller: NativeSplashController | null = null;
let releaseLaunch: (() => void) | null = null;
/**
* Call once at the JS entry. The launch surface (the native splash, or on Android the
* `LaunchScreen` that replaces it) then covers the app until the root navigator has committed its
* first screen and no screen holds it, and leaves from here alone.
*/
export function keepNativeSplash(): void {
if (controller) return;
launchSurface.keep();
controller = createNativeSplashController(
{
hide: () => launchSurface.leave(),
afterNextFrame: (callback) => {
requestAnimationFrame(() => callback());
},
startTimer: (callback, ms) => {
setTimeout(callback, ms);
},
},
{ capMs: CAP_MS },
);
releaseLaunch = controller.hold();
}
/** The root navigator's first commit ends the launch hold. Screens committed with it hold first. */
export function useNativeSplashLaunchCommit(): void {
useEffect(() => {
releaseLaunch?.();
releaseLaunch = null;
}, []);
}
/** Keeps the launch surface up while `active`, for a screen that has nothing to show yet. */
export function useNativeSplashHold(active: boolean): void {
useLayoutEffect(() => {
if (!active) return;
return controller?.hold();
}, [active]);
}
@@ -0,0 +1,86 @@
import { describe, expect, it } from "vitest";
import { createNativeSplashController } from "./controller";
function createFakeSplash() {
const frames: Array<() => void> = [];
const timers: Array<{ callback: () => void; ms: number }> = [];
const splash = { hides: 0 };
const controller = createNativeSplashController(
{
hide: () => {
splash.hides += 1;
},
afterNextFrame: (callback) => {
frames.push(callback);
},
startTimer: (callback, ms) => {
timers.push({ callback, ms });
},
},
{ capMs: 3_000 },
);
const runFrame = () => {
for (const callback of frames.splice(0)) callback();
};
const runCap = () => {
for (const timer of timers.splice(0)) timer.callback();
};
return { controller, splash, runFrame, runCap, timers };
}
describe("native splash", () => {
it("stays up while a screen holds it and hides a frame after the last release", () => {
const { controller, splash, runFrame } = createFakeSplash();
const releaseLaunch = controller.hold();
const releaseScreen = controller.hold();
releaseLaunch();
runFrame();
expect(splash.hides).toBe(0);
releaseScreen();
expect(splash.hides).toBe(0);
runFrame();
expect(splash.hides).toBe(1);
});
it("stays up when the next screen takes the hold before the frame passes", () => {
const { controller, splash, runFrame } = createFakeSplash();
const releaseSplashRoute = controller.hold();
releaseSplashRoute();
const releaseWorkspace = controller.hold();
runFrame();
expect(splash.hides).toBe(0);
releaseWorkspace();
runFrame();
expect(splash.hides).toBe(1);
});
it("hides when the cap runs out even while a screen still holds it", () => {
const { controller, splash, runCap, runFrame, timers } = createFakeSplash();
const release = controller.hold();
expect(timers.map((timer) => timer.ms)).toEqual([3_000]);
runCap();
expect(splash.hides).toBe(1);
release();
runFrame();
expect(controller.hold()).toBeTypeOf("function");
runFrame();
expect(splash.hides).toBe(1);
});
it("counts a repeated release once", () => {
const { controller, splash, runFrame } = createFakeSplash();
const first = controller.hold();
controller.hold();
first();
first();
runFrame();
expect(splash.hides).toBe(0);
});
});
@@ -0,0 +1,53 @@
export interface NativeSplashPort {
hide(): void;
/** Runs the callback after the next frame, once the committed screen has been drawn. */
afterNextFrame(callback: () => void): void;
startTimer(callback: () => void, ms: number): void;
}
export interface NativeSplashController {
/** Keeps the splash up until the returned release runs. Holds after the hide do nothing. */
hold(): () => void;
}
/**
* The splash hides once, after a frame passes with nothing holding it, or when the cap runs out.
* The frame wait lets a screen that replaces a holding screen in the same commit take over.
*/
export function createNativeSplashController(
port: NativeSplashPort,
options: { capMs: number },
): NativeSplashController {
let holds = 0;
let hidden = false;
let checkScheduled = false;
const hide = () => {
if (hidden) return;
hidden = true;
port.hide();
};
const hideIfReleased = () => {
checkScheduled = false;
if (holds === 0) hide();
};
port.startTimer(hide, options.capMs);
return {
hold() {
if (hidden) return () => undefined;
holds += 1;
let released = false;
return () => {
if (released) return;
released = true;
holds -= 1;
if (holds > 0 || hidden || checkScheduled) return;
checkScheduled = true;
port.afterNextFrame(hideIfReleased);
};
},
};
}
@@ -0,0 +1,104 @@
import { useEffect, useState, useSyncExternalStore } from "react";
import { useColorScheme, View } from "react-native";
import Animated, { useAnimatedStyle, useSharedValue, withTiming } from "react-native-reanimated";
import { scheduleOnRN } from "react-native-worklets";
import { StyleSheet } from "react-native-unistyles";
import * as SplashScreen from "expo-splash-screen";
import { PaseoLogo } from "@/components/icons/paseo-logo";
// Android hands its splash to the app in a way the app cannot time: the system can show one app
// frame before its copy of the splash draws, and a frame the app draws first can be empty. So the
// native splash leaves as soon as React commits this screen, which looks the same as the splash,
// and this screen covers the app until launch is done.
// The splash colours from the expo-splash-screen entry in app.config.js. Android picks them from
// the system dark mode, not from the app theme.
const SPLASH_BACKGROUND = { dark: "#000000", light: "#ffffff" } as const;
// Android draws a splash icon without a background inside a 192dp circle.
const ICON_CIRCLE_SIZE = 192;
// The splash icon's glyph is 135dp wide, which the logo's glyph reaches at this SVG size.
const LOGO_SIZE = 182;
const EXIT_MS = 200;
let launchDone = false;
const listeners = new Set<() => void>();
function subscribe(listener: () => void): () => void {
listeners.add(listener);
return () => listeners.delete(listener);
}
function isLaunchDone(): boolean {
return launchDone;
}
/** Android: this screen covers the app until launch is done, then fades out. */
export const launchSurface = {
keep(): void {
void SplashScreen.preventAutoHideAsync().catch(() => undefined);
// The system's copy of the splash fades over this screen, which looks the same.
SplashScreen.setOptions({ duration: 150, fade: true });
},
leave(): void {
if (launchDone) return;
launchDone = true;
for (const listener of listeners) listener();
},
};
export function LaunchScreen() {
const leaving = useSyncExternalStore(subscribe, isLaunchDone);
const [gone, setGone] = useState(false);
const scheme = useColorScheme() === "light" ? "light" : "dark";
const opacity = useSharedValue(1);
const fadeStyle = useAnimatedStyle(() => ({ opacity: opacity.value }));
useEffect(() => {
SplashScreen.hide();
}, []);
useEffect(() => {
if (!leaving) return;
opacity.value = withTiming(0, { duration: EXIT_MS }, (finished) => {
if (finished) scheduleOnRN(setGone, true);
});
}, [leaving, opacity]);
if (gone) return null;
return (
<Animated.View
pointerEvents={leaving ? "none" : "auto"}
style={[styles.screen, { backgroundColor: SPLASH_BACKGROUND[scheme] }, fadeStyle]}
>
<View style={styles.iconCircle}>
<View style={styles.logo}>
<PaseoLogo size={LOGO_SIZE} color="#ffffff" />
</View>
</View>
</Animated.View>
);
}
const styles = StyleSheet.create({
screen: {
position: "absolute",
top: 0,
left: 0,
right: 0,
bottom: 0,
alignItems: "center",
justifyContent: "center",
},
iconCircle: {
width: ICON_CIRCLE_SIZE,
height: ICON_CIRCLE_SIZE,
borderRadius: ICON_CIRCLE_SIZE / 2,
backgroundColor: "#000000",
alignItems: "center",
justifyContent: "center",
},
logo: {
// Optical: the glyph sits right of the SVG's centre. The splash centres the glyph.
transform: [{ translateX: -4 }],
},
});
@@ -0,0 +1,20 @@
import * as SplashScreen from "expo-splash-screen";
// iOS fades the native splash straight into the first screen.
const FADE_MS = 150;
/** iOS and web: the native splash itself covers the app until launch is done. */
export const launchSurface = {
keep(): void {
// Taking control stops expo-router from hiding the splash when navigation is ready.
void SplashScreen.preventAutoHideAsync().catch(() => undefined);
SplashScreen.setOptions({ duration: FADE_MS, fade: true });
},
leave(): void {
SplashScreen.hide();
},
};
export function LaunchScreen(): null {
return null;
}
@@ -4,7 +4,6 @@ import {
resolveStartupNavigationReady,
resolveHostIndexRoute,
resolveStartupRoute,
shouldRunStartupGiveUpTimer,
startHostRuntimeBootstrap,
bindHostRuntimeAppState,
} from "./host-runtime-bootstrap";
@@ -90,6 +89,41 @@ describe("startHostRuntimeBootstrap", () => {
"decision:true",
]);
});
it("settles once the registry boot and the managed-daemon start have both finished", async () => {
let resolveBoot!: () => void;
let resolveDaemonStart!: (result: DaemonStartResult) => void;
let settled = false;
const bootstrap = startHostRuntimeBootstrap({
store: {
boot: () =>
new Promise<void>((resolve) => {
resolveBoot = resolve;
}),
},
daemonStartService: {
startIfEnabled: () =>
new Promise<DaemonStartResult>((resolve) => {
resolveDaemonStart = resolve;
}),
},
shouldStartDaemon: false,
});
void bootstrap.then(() => {
settled = true;
return;
});
resolveBoot();
await Promise.resolve();
await Promise.resolve();
expect(settled).toBe(false);
resolveDaemonStart({ ok: false, error: "daemon failed to start" });
await bootstrap;
expect(settled).toBe(true);
});
});
describe("startup blocking policy", () => {
@@ -100,18 +134,11 @@ describe("startup blocking policy", () => {
daemonStartError: null,
};
it("runs the give-up timer when no startup blocker is active", () => {
it("does not block navigation when no startup blocker is active", () => {
const blocker = resolveStartupBlocker(noBlockerInput);
expect(blocker).toEqual({ kind: "none" });
expect(resolveStartupNavigationReady({ startupBlocker: blocker })).toBe(true);
expect(
shouldRunStartupGiveUpTimer({
startupBlocker: blocker,
anyOnlineHostServerId: null,
hasGivenUpWaitingForHost: false,
}),
).toBe(true);
});
it("blocks navigation while desktop is starting the managed daemon", () => {
@@ -123,13 +150,6 @@ describe("startup blocking policy", () => {
expect(blocker).toEqual({ kind: "managed-daemon-starting" });
expect(resolveStartupNavigationReady({ startupBlocker: blocker })).toBe(false);
expect(
shouldRunStartupGiveUpTimer({
startupBlocker: blocker,
anyOnlineHostServerId: null,
hasGivenUpWaitingForHost: false,
}),
).toBe(false);
});
it("unblocks navigation when any host is online", () => {
@@ -156,13 +176,6 @@ describe("startup blocking policy", () => {
message: "daemon failed to start",
});
expect(resolveStartupNavigationReady({ startupBlocker: blocker })).toBe(true);
expect(
shouldRunStartupGiveUpTimer({
startupBlocker: blocker,
anyOnlineHostServerId: null,
hasGivenUpWaitingForHost: false,
}),
).toBe(false);
});
});
@@ -176,7 +189,7 @@ describe("resolveStartupRoute", () => {
workspaceSelection: null,
workspaceSelectionStatus: "unknown" as const,
isWorkspaceSelectionLoaded: true,
hasGivenUpWaitingForHost: false,
isWaitingForHost: true,
isWaitingForSetup: false,
};
const baseHostInput = {
@@ -220,7 +233,7 @@ describe("resolveStartupRoute", () => {
...baseIndexInput,
hostRegistryStatus: "loading",
workspaceSelection: { serverId: "server-1", workspaceId: "workspace-a" },
hasGivenUpWaitingForHost: true,
isWaitingForHost: false,
}),
).toEqual({ kind: "splash" });
});
@@ -265,7 +278,7 @@ describe("resolveStartupRoute", () => {
...baseIndexInput,
workspaceSelection: { serverId: "server-saved", workspaceId: "workspace-a" },
hosts: [{ serverId: "server-next" }],
hasGivenUpWaitingForHost: true,
isWaitingForHost: false,
}),
).toEqual({ kind: "redirect", href: "/h/server-next" });
});
@@ -306,16 +319,25 @@ describe("resolveStartupRoute", () => {
resolveStartupRoute({
...baseIndexInput,
hosts: [{ serverId: "server-saved" }],
hasGivenUpWaitingForHost: true,
isWaitingForHost: false,
}),
).toEqual({ kind: "redirect", href: "/h/server-saved" });
});
it("shows welcome after root startup gives up and no host exists", () => {
it("holds the splash while a startup host source can still add a host", () => {
expect(
resolveStartupRoute({
...baseIndexInput,
hasGivenUpWaitingForHost: true,
isWaitingForHost: true,
}),
).toEqual({ kind: "splash" });
});
it("shows welcome as soon as no host exists and none can still arrive", () => {
expect(
resolveStartupRoute({
...baseIndexInput,
isWaitingForHost: false,
}),
).toEqual({ kind: "redirect", href: "/welcome" });
});
@@ -26,9 +26,15 @@ export interface StartHostRuntimeBootstrapInput {
shouldStartDaemon: DaemonStartCondition;
}
export function startHostRuntimeBootstrap(input: StartHostRuntimeBootstrapInput): void {
/**
* Starts every source that can add a host at launch: the registry boot with its connection probes,
* and the managed daemon. Settles once none of them can still add one.
*/
export async function startHostRuntimeBootstrap(
input: StartHostRuntimeBootstrapInput,
): Promise<void> {
const registryReady = input.store.boot();
void input.daemonStartService.startIfEnabled({
const daemonStart = input.daemonStartService.startIfEnabled({
shouldStart: async () => {
await registryReady;
return typeof input.shouldStartDaemon === "boolean"
@@ -36,6 +42,7 @@ export function startHostRuntimeBootstrap(input: StartHostRuntimeBootstrapInput)
: input.shouldStartDaemon();
},
});
await Promise.allSettled([registryReady, daemonStart]);
}
const WELCOME_ROUTE: Href = "/welcome";
@@ -76,20 +83,6 @@ export function resolveStartupNavigationReady(input: { startupBlocker: StartupBl
return input.startupBlocker.kind !== "managed-daemon-starting";
}
export function shouldRunStartupGiveUpTimer(input: {
startupBlocker: StartupBlocker;
anyOnlineHostServerId: string | null;
hasGivenUpWaitingForHost: boolean;
}): boolean {
if (input.anyOnlineHostServerId) {
return false;
}
if (input.hasGivenUpWaitingForHost) {
return false;
}
return input.startupBlocker.kind === "none";
}
export type StartupRegistryStatus = "loading" | "ready";
export interface IndexStartupRouteTarget {
@@ -116,7 +109,8 @@ export interface ResolveIndexStartupRouteInput extends ResolveStartupRouteBaseIn
workspaceSelection: ActiveWorkspaceSelection | null;
workspaceSelectionStatus: WorkspaceSelectionStatus;
isWorkspaceSelectionLoaded: boolean;
hasGivenUpWaitingForHost: boolean;
/** A startup host source can still add a host; see `startHostRuntimeBootstrap`. */
isWaitingForHost: boolean;
/** Setup may still open over the empty home; see `useIsSetupDecisionPending`. */
isWaitingForSetup: boolean;
}
@@ -215,11 +209,11 @@ function resolveReadyIndexStartupRoute(input: ResolveIndexStartupRouteInput): St
return { kind: "redirect", href: buildHostRootRoute(savedHostServerId) };
}
if (input.hasGivenUpWaitingForHost) {
return { kind: "redirect", href: WELCOME_ROUTE };
if (input.isWaitingForHost) {
return { kind: "splash" };
}
return { kind: "splash" };
return { kind: "redirect", href: WELCOME_ROUTE };
}
function resolveReadyHostStartupRoute(input: ResolveHostStartupRouteInput): StartupRouteDecision {
+54 -19
View File
@@ -1,6 +1,8 @@
import { getHostRuntimeStore } from "@/runtime/host-runtime";
import { useNativeSplashHold } from "@/native-splash";
import { Button } from "@/components/ui/button";
import { LoadingSpinner } from "@/components/ui/loading-spinner";
import { LoadingState } from "@/components/ui/loading-state";
import type { DaemonClient } from "@getpaseo/client/internal/daemon-client";
import type { TFunction } from "i18next";
import { SquarePen } from "lucide-react-native";
@@ -97,6 +99,7 @@ import { ParentAgentCallout, useParentAgentId } from "@/subagents/parent";
import { useCreateFlowStore } from "@/stores/create-flow-store";
import { buildDraftStoreKey, generateDraftId } from "@/stores/draft-keys";
import {
selectAgentLoadingWait,
selectAgentTimelineState,
selectAgentTimelineTurnPresentation,
type Agent,
@@ -242,6 +245,7 @@ function AgentLoadErrorView({ message, onRetry }: { message: string; onRetry: ()
/** A draft has no agent to wait for; an agent shows its loading and error states until ready. */
function renderConversationNonReadyView(args: {
serverId: string;
draft: DraftConversation | null;
agentId: string | undefined;
cwd: string | null;
@@ -253,23 +257,25 @@ function renderConversationNonReadyView(args: {
if (args.draft) {
return null;
}
const nonReadyView = renderChatAgentNonReadyView(args);
invariant(args.agentId, "agent id is defined when the conversation is not a draft");
const nonReadyView = renderChatAgentNonReadyView({ ...args, agentId: args.agentId });
if (nonReadyView) {
return nonReadyView;
}
invariant(args.agentId, "agent id is defined when agent content is ready");
invariant(args.effectiveAgent, "effectiveAgent is defined when the non-ready view is absent");
invariant(args.cwd, "agent cwd is defined when agent content is ready");
return null;
}
function renderChatAgentNonReadyView(args: {
serverId: string;
agentId: string;
viewState: AgentScreenViewState;
effectiveAgent: AgentScreenAgent | null;
t: TFunction;
onRetryLoad: () => void;
}): React.ReactElement | null {
const { viewState, effectiveAgent, t, onRetryLoad } = args;
const { serverId, agentId, viewState, effectiveAgent, t, onRetryLoad } = args;
if (viewState.tag === "not_found") {
return (
<View style={styles.container} testID="agent-not-found">
@@ -283,13 +289,7 @@ function renderChatAgentNonReadyView(args: {
return <AgentLoadErrorView message={viewState.message} onRetry={onRetryLoad} />;
}
if (viewState.tag === "boot" || !effectiveAgent) {
return (
<View style={styles.container} testID="agent-loading">
<View style={styles.errorContainer}>
<ThemedLoadingSpinner size="large" uniProps={foregroundMutedColorMapping} />
</View>
</View>
);
return <AgentLoadingView serverId={serverId} agentId={agentId} />;
}
return null;
}
@@ -647,13 +647,7 @@ function AgentPanelBody({
: null;
if (target.kind === "agent" && !agent) {
return (
<View style={styles.container} testID="agent-loading">
<View style={styles.errorContainer}>
<ThemedLoadingSpinner size="large" uniProps={foregroundMutedColorMapping} />
</View>
</View>
);
return <AgentLoadingView serverId={serverId} agentId={target.agentId} />;
}
return (
@@ -669,6 +663,46 @@ function AgentPanelBody({
);
}
/**
* The pane's loading state, for its agent or the agent's history. A visible pane keeps the launch
* splash up while the cache can still answer; after that it says what the host has yet to send.
*/
function AgentLoadingState({
serverId,
agentId,
testID,
}: {
serverId: string;
agentId: string;
testID: string;
}) {
const { t } = useTranslation();
const isPaneVisible = useRetainedPanelActive();
const wait = useSessionStore(
useShallow((state) => selectAgentLoadingWait(state.sessions[serverId], agentId)),
);
useNativeSplashHold(isPaneVisible && wait.source === "cache");
if (wait.source === "cache") return <LoadingState testID={testID} />;
return (
<LoadingState
testID={testID}
title={
wait.waitingFor === "agent"
? t("agentPanel.states.loadingAgent")
: t("agentPanel.states.loadingHistory")
}
/>
);
}
function AgentLoadingView(props: { serverId: string; agentId: string }) {
return (
<View style={styles.container}>
<AgentLoadingState {...props} testID="agent-loading" />
</View>
);
}
function ChatAgentContent({
serverId,
workspaceId,
@@ -1003,6 +1037,7 @@ function ChatAgentContent({
[tabId, target, workspaceId],
);
const nonReadyView = renderConversationNonReadyView({
serverId,
draft,
agentId,
cwd: agentState.cwd,
@@ -1277,8 +1312,8 @@ const ChatAgentReadyContent = memo(function ChatAgentReadyContent({
const dockOverlay = (
<>
{showHistorySyncOverlay ? (
<View style={styles.historySyncOverlay} testID="agent-history-overlay">
<ThemedLoadingSpinner size="large" uniProps={foregroundMutedColorMapping} />
<View style={styles.historySyncOverlay}>
<AgentLoadingState serverId={serverId} agentId={agentId} testID="agent-history-overlay" />
</View>
) : null}
+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,
);
}

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