Compare commits

..
Author SHA1 Message Date
ba765ba3f2 test(server): reproduce stale plugin history after rewind
Preserve the manager-level reproduction for #4667 and a file-only
control. A second red case shows that discarded timeline snapshots
also shorten replacement output when an item identity is reused.
These are diagnostic tests; production behavior is unchanged.

Refs #4667

Co-authored-by: Matt Cowger <matt@cowger.us>
Co-authored-by: Omer Cohen <639682+omercnet@users.noreply.github.com>
2026-10-27 18:22:30 +00:00
156 changed files with 1108 additions and 4699 deletions
-19
View File
@@ -1,19 +0,0 @@
---
name: store-screenshots
description: Refresh the App Store and Google Play screenshots for phones and tablets. Use when the user says "store screenshots", "app store screenshots", "play store screenshots", "iPad screenshots", "recapture the screenshots", or wants the store panels changed.
user-invocable: true
---
# Store screenshots
Follow `assets/store-screenshots/README.md`. It owns the panels, the creative direction, the render command and the recapture steps. Change copy, crops and layout in `assets/store-screenshots/render.mjs`, not in the exports.
Working rules:
- Capture at native density: `--pixel-density 3` on the iPhone 16 Pro Max, `--pixel-density 2` on the iPad Pro 13-inch. The default is 1x, which is too soft for the store.
- Every headline wraps to two lines and every subline fits on one. The renderer enforces this; rewrite the copy rather than shrink the type.
- Use SF Pro. Never substitute another font.
- Open `output/preview.png` and a full-size panel from each store before you report a render. Show the user the preview.
- Do not upload screenshots to a store, a PR, or anywhere public, and do not commit, unless the user asks.
- Stage the demo host on its own port and pick a free Metro port. Do not restart the main daemons.
- When you learn something the next capture needs, fix the README rather than this skill.
+18 -11
View File
@@ -133,12 +133,11 @@ jobs:
if: ${{ !cancelled() && steps.install.outcome == 'success' && (needs.changes.outputs.full != 'false' || needs.changes.outputs.sdk != 'false') }}
run: npm run typecheck:examples --workspace=@getpaseo/client
# The locked Playwright installers do not support ubuntu-latest's Ubuntu 26.04.
typecheck:
name: typecheck
needs: changes
if: ${{ !cancelled() && (needs.changes.outputs.full != 'false' || needs.changes.outputs.quality != 'false') }}
runs-on: ubuntu-24.04
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
@@ -396,7 +395,7 @@ jobs:
name: app-tests
needs: changes
if: ${{ !cancelled() && (needs.changes.outputs.full != 'false' || needs.changes.outputs.app != 'false') }}
runs-on: ubuntu-24.04
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
@@ -418,11 +417,19 @@ jobs:
- name: Run app unit tests
run: npm run test --workspace=@getpaseo/app
- uses: actions/setup-java@v4
with:
distribution: temurin
java-version: "21"
- name: Run Android module tests
run: npm run test:android --workspace=@getpaseo/app
playwright-1:
name: playwright (shard 1/8)
needs: changes
if: ${{ !cancelled() && (needs.changes.outputs.full != 'false' || needs.changes.outputs.browser != 'false') }}
runs-on: ubuntu-24.04
runs-on: ubuntu-latest
env:
PLAYWRIGHT_SHARD: "1/8"
PLAYWRIGHT_ARTIFACT: "1"
@@ -478,7 +485,7 @@ jobs:
name: playwright (shard 2/8)
needs: changes
if: ${{ !cancelled() && (needs.changes.outputs.full != 'false' || needs.changes.outputs.browser != 'false') }}
runs-on: ubuntu-24.04
runs-on: ubuntu-latest
env:
PLAYWRIGHT_SHARD: "2/8"
PLAYWRIGHT_ARTIFACT: "2"
@@ -488,7 +495,7 @@ jobs:
name: playwright (shard 3/8)
needs: changes
if: ${{ !cancelled() && (needs.changes.outputs.full != 'false' || needs.changes.outputs.browser != 'false') }}
runs-on: ubuntu-24.04
runs-on: ubuntu-latest
env:
PLAYWRIGHT_SHARD: "3/8"
PLAYWRIGHT_ARTIFACT: "3"
@@ -498,7 +505,7 @@ jobs:
name: playwright (shard 4/8)
needs: changes
if: ${{ !cancelled() && (needs.changes.outputs.full != 'false' || needs.changes.outputs.browser != 'false') }}
runs-on: ubuntu-24.04
runs-on: ubuntu-latest
env:
PLAYWRIGHT_SHARD: "4/8"
PLAYWRIGHT_ARTIFACT: "4"
@@ -508,7 +515,7 @@ jobs:
name: playwright (shard 5/8)
needs: changes
if: ${{ !cancelled() && (needs.changes.outputs.full != 'false' || needs.changes.outputs.browser != 'false') }}
runs-on: ubuntu-24.04
runs-on: ubuntu-latest
env:
PLAYWRIGHT_SHARD: "5/8"
PLAYWRIGHT_ARTIFACT: "5"
@@ -518,7 +525,7 @@ jobs:
name: playwright (shard 6/8)
needs: changes
if: ${{ !cancelled() && (needs.changes.outputs.full != 'false' || needs.changes.outputs.browser != 'false') }}
runs-on: ubuntu-24.04
runs-on: ubuntu-latest
env:
PLAYWRIGHT_SHARD: "6/8"
PLAYWRIGHT_ARTIFACT: "6"
@@ -528,7 +535,7 @@ jobs:
name: playwright (shard 7/8)
needs: changes
if: ${{ !cancelled() && (needs.changes.outputs.full != 'false' || needs.changes.outputs.browser != 'false') }}
runs-on: ubuntu-24.04
runs-on: ubuntu-latest
env:
PLAYWRIGHT_SHARD: "7/8"
PLAYWRIGHT_ARTIFACT: "7"
@@ -538,7 +545,7 @@ jobs:
name: playwright (shard 8/8)
needs: changes
if: ${{ !cancelled() && (needs.changes.outputs.full != 'false' || needs.changes.outputs.browser != 'false') }}
runs-on: ubuntu-24.04
runs-on: ubuntu-latest
env:
PLAYWRIGHT_SHARD: "8/8"
PLAYWRIGHT_ARTIFACT: "8"
-1
View File
@@ -1 +0,0 @@
output/preview.png
-98
View File
@@ -1,98 +0,0 @@
# Store screenshots
Five panels for the App Store and Google Play, in phone and tablet sets, made from native captures of the real app. Both sets tell the same story with the same copy; only the capture, the device frame and the callouts change.
| # | Headline | Capture | Phone callout | Tablet callout |
| --- | --------------------------------------- | ---------------------------------------------------------------------- | -------------------------------------------- | ------------------------------------- |
| 1 | Run many coding agents at once | Sidebar grouped by status: Needs input, Ready to review, Working, Done | — (agent marks in the background) | — (agent marks in the background) |
| 2 | Your full dev environment on your phone | Agent chat: reasoning, tool calls, final summary | — | — (Changes pane open beside the chat) |
| 3 | Ask an agent to change the app itself | A chat asking for a plugin, the turn collapsed, the new Deploys pill | The plugin's Preview deploys sheet | The plugin's Deploys popover |
| 4 | Review the diff before you merge | `daemon-client.ts` diff with removed and added lines | Jump to file: four changed files with counts | — (the full-width diff reads as is) |
| 5 | A real terminal in every workspace | `git status` and a vitest run in the same worktree | The passing test tree | The passing test tree |
On tablets, panel 2 says "on your tablet" and panel 3 calls the popover a panel. A scene overrides its copy per device in `render.mjs`.
## Creative direction
The panels follow paseo.sh:
- **Canvas:** the site's `#101615` background.
- **Type:** centred SF Pro headlines in sentence case, with no closing period. Every headline wraps to exactly two lines.
- **Sublines:** one plain grey sentence on one line that says what you can do. The renderer fails if a headline or subline wraps differently, because the device is placed from that fixed text height.
- **Agent marks:** panel 1 scatters faded, rotated, monochrome marks of the agents featured on the homepage behind the device. They are rendered from `packages/website/src/components/agent-icons.tsx`, so they follow the site.
- **Device:** dark-mode captures in a plain black frame; the iPhone frame has a Dynamic Island. The device starts a fixed gap below the text and runs just off the bottom edge, so a taller canvas gets a larger device instead of a larger gap. A canvas too narrow for that, like a 3:4 iPad on Google's 9:16 tablet canvas, shows the whole device at full width with the text and device centred.
- **Callouts:** a callout lifts one region of a capture out of the device, larger than the device around it, so the detail reads at store thumbnail size. On tablets, place callouts over empty screen so they do not hide the context they explain.
Everything on screen is real app UI showing one story. The hero agent adds jitter to the reconnect backoff in this repository. Its diff, test run and terminal come from a real worktree. The other workspaces fill the sidebar's status groups.
Panel 3 shows a real plugin. `demo/preview-deploys/` is a trusted local plugin that adds a Deploys composer pill; its popover opens as a sheet on phones and as a popover on tablets. The deploys it lists are sample data. The demo host installs it, and a scripted agent in the "Build a preview deploys plugin" workspace plays the turn that writes it.
## Files
- `raw/iphone/`: native 1320 × 2868 captures from an iPhone 16 Pro Max simulator. `files.png` and `plugin-sheet.png` are the sources for the Jump to file and Preview deploys callouts.
- `raw/ipad/`: native 2064 × 2752 captures from an iPad Pro 13-inch (M4) simulator. `plugin-sheet.png` is the source for the Deploys popover callout.
- `render.mjs`: the layout, copy and callout crops. Edit `SCENES`, `DEVICES` and `STORES` there.
- `demo/`: the staged demo host the captures come from.
- `output/apple/`: 1320 × 2868 for the iPhone 6.9-inch slot.
- `output/google/`: 1440 × 2560 (9:16) phone screenshots, reusing the iPhone captures.
- `output/apple-ipad/`: 2064 × 2752 for the iPad 13-inch slot.
- `output/google-tablet/`: 1800 × 3200 (9:16) tablet screenshots, reusing the iPad captures.
- `output/preview.png`: contact sheet with one row per store, for review only. It is ignored by Git; do not upload it to a store.
All exports are opaque RGB PNGs.
## Render
```sh
SF_FONT_DIR=/path/to/fonts node assets/store-screenshots/render.mjs
```
`SF_FONT_DIR` must hold `SFNS.ttf` copied from a Mac's `/System/Library/Fonts`. On macOS the renderer finds it without the variable. SF Pro is not redistributable, so it is not in the repository. The renderer fails rather than fall back to another font.
Each capture and callout is resized with Lanczos to the exact pixels it fills, and the page renders at device scale 1. Do not render at a higher scale and downsample: Chrome's image downscaling is what made earlier exports look soft and aliased.
Open `output/preview.png` and at least one full-size panel per store before you call a render done. The line guard catches wrapping, not a callout that covers the wrong thing.
Callout crops are in native capture pixels. To find them, overlay a 100 px grid on the capture with sharp and read the coordinates off it.
## Recapture
1. Stage the demo host. It runs an in-process daemon on port 7791 with scripted Claude Code and Codex clients, a local clone of this repository as the `paseo` project, real worktrees, and a terminal in the hero worktree:
```sh
npx tsx assets/store-screenshots/demo/stage.mts
```
Each run re-clones the repository into the demo home, so stale worktrees from an earlier run do not block it. The hero agent is paced so it reports a realistic "Worked for" time. Wait for `READY` in its output.
2. Start Metro against it on a free port. When the simulator runs on another Mac, forward Metro and the daemon to it. Other agents may already hold a Metro port; pick another one rather than stopping theirs.
```sh
EXPO_PUBLIC_LOCAL_DAEMON=127.0.0.1:7791 npm run start:expo --workspace=@getpaseo/app -- --port <port>
ssh -o ExitOnForwardFailure=yes -R <port>:127.0.0.1:<port> -R 7791:127.0.0.1:7791 <mac-host>
```
3. On the simulator, install and open the dev client (`sh.paseo.debug`) at `http://127.0.0.1:<port>`. Use an iPhone 16 Pro Max for the phone set and an iPad Pro 13-inch (M4) in portrait for the tablet set.
- Set dark appearance and override the status bar to 9:41 with full battery and signal (`xcrun simctl status_bar <device> override`).
- On first launch, accept the open-in-app dialog, decline notifications, turn off the dev client's Tools button, and close any error toast. `agent-device react-native dismiss-overlay` clears overlays.
- Name the host "MacBook Pro" and set the sidebar badge to Hidden.
- Group the sidebar by status.
- If you reset the simulator, reinstall the dev client.
4. Capture the sidebar first. Opening a "Ready to review" workspace marks it done. Select a Working row before you capture.
5. Capture every screen at native density. `agent-device screenshot` defaults to 1x, which is too soft for the store:
```sh
agent-device screenshot /tmp/sidebar.png --pixel-density 3 --session store # iPhone: 1320 × 2868
agent-device screenshot /tmp/sidebar.png --pixel-density 2 --session store # iPad: 2064 × 2752
```
- **Chat:** expand the tool-call group and scroll to the bottom. On iPad, open Explorer → Changes beside the chat.
- **Diff:** on iPhone, Explorer → Changes, then use Jump to file to reach `daemon-client.ts`. On iPad, collapse the sidebar, open a Diff tab from the main area's **+** menu and scroll to the `daemon-client.ts` hunks.
- **Terminal:** the second workspace tab. Type the commands with `npm run cli -- terminal send-keys --host 127.0.0.1:7791 <terminal-id> "<text>" Enter` instead of the simulator keyboard, then dismiss the software keyboard.
- **Plugin:** the "Build a preview deploys plugin" workspace with the turn collapsed, then tap **Deploys** for `plugin-sheet.png`. After editing the plugin, reload it with `npm run cli -- plugin reload --host 127.0.0.1:7791 preview-deploys`.
6. Copy the captures into `raw/iphone/` or `raw/ipad/` under the names `render.mjs` uses, render, and check the preview.
Dimensions are checked against [Apple's screenshot specifications](https://developer.apple.com/help/app-store-connect/reference/app-information/screenshot-specifications/) and [Google Play's preview asset requirements](https://support.google.com/googleplay/android-developer/answer/9866151?hl=en).
@@ -1,84 +0,0 @@
// Applies the demo change to a checkout of the Paseo repository.
import { copyFileSync, readFileSync, writeFileSync } from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
const here = path.dirname(fileURLToPath(import.meta.url));
const repo = process.argv[2];
const client = path.join(repo, "packages/client/src");
copyFileSync(
path.join(here, "reconnect-delay.ts"),
path.join(client, "connection/reconnect-delay.ts"),
);
copyFileSync(
path.join(here, "reconnect-delay.test.ts"),
path.join(client, "connection/reconnect-delay.test.ts"),
);
function edit(file, pairs) {
let text = readFileSync(file, "utf8");
for (const [from, to] of pairs) {
if (!text.includes(from)) throw new Error(`Missing anchor in ${file}: ${from.slice(0, 60)}`);
text = text.replace(from, to);
}
writeFileSync(file, text);
}
edit(path.join(client, "daemon-client.ts"), [
[
`import { CreationClient } from "./creation/index.js";\n`,
`import { CreationClient } from "./creation/index.js";\nimport { getReconnectDelayMs } from "./connection/reconnect-delay.js";\n`,
],
[
` private reconnectAttempt = 0;\n`,
` private reconnectAttempt = 0;\n private nextReconnectDelay: { attempt: number; delayMs: number } | null = null;\n`,
],
[
` nextRetryAt: new Date(
Date.now() +
Math.min(
(this.config.reconnect?.baseDelayMs ?? DEFAULT_RECONNECT_BASE_DELAY_MS) *
2 ** this.reconnectAttempt,
this.config.reconnect?.maxDelayMs ?? DEFAULT_RECONNECT_MAX_DELAY_MS,
),
).toISOString(),
`,
` nextRetryAt: new Date(Date.now() + this.getNextReconnectDelayMs()).toISOString(),
`,
],
[
` private armReconnectTimer(): void {
const attempt = this.reconnectAttempt;
const baseDelay = this.config.reconnect?.baseDelayMs ?? DEFAULT_RECONNECT_BASE_DELAY_MS;
const maxDelay = this.config.reconnect?.maxDelayMs ?? DEFAULT_RECONNECT_MAX_DELAY_MS;
const delay = Math.min(baseDelay * 2 ** attempt, maxDelay);
`,
` // The countdown and the timer must agree, so each attempt draws its jitter once.
private getNextReconnectDelayMs(): number {
const attempt = this.reconnectAttempt;
if (this.nextReconnectDelay?.attempt !== attempt) {
this.nextReconnectDelay = {
attempt,
delayMs: getReconnectDelayMs(attempt, {
baseDelayMs: this.config.reconnect?.baseDelayMs ?? DEFAULT_RECONNECT_BASE_DELAY_MS,
maxDelayMs: this.config.reconnect?.maxDelayMs ?? DEFAULT_RECONNECT_MAX_DELAY_MS,
}),
};
}
return this.nextReconnectDelay.delayMs;
}
private armReconnectTimer(): void {
const attempt = this.reconnectAttempt;
const delay = this.getNextReconnectDelayMs();
`,
],
]);
edit(path.join(repo, "CHANGELOG.md"), [
[
`# Changelog\n\n`,
`# Changelog\n\n## Unreleased\n\n### Fixed\n\n- Spread reconnect attempts after a relay restart instead of retrying every client at once\n\n`,
],
]);
@@ -1,29 +0,0 @@
import { describe, expect, it } from "vitest";
import { getReconnectDelayMs } from "./reconnect-delay";
const options = { baseDelayMs: 1500, maxDelayMs: 30_000 };
describe("getReconnectDelayMs", () => {
it("doubles the ceiling on each attempt", () => {
const top = () => 1;
expect(getReconnectDelayMs(0, options, top)).toBe(1500);
expect(getReconnectDelayMs(1, options, top)).toBe(3000);
expect(getReconnectDelayMs(2, options, top)).toBe(6000);
});
it("never waits longer than the max delay", () => {
expect(getReconnectDelayMs(12, options, () => 1)).toBe(30_000);
});
it("spreads retries between half and the full ceiling", () => {
expect(getReconnectDelayMs(3, options, () => 0)).toBe(6000);
expect(getReconnectDelayMs(3, options, () => 0.5)).toBe(9000);
expect(getReconnectDelayMs(3, options, () => 1)).toBe(12_000);
});
it("keeps the first retry under two seconds", () => {
for (let i = 0; i < 100; i += 1) {
expect(getReconnectDelayMs(0, options)).toBeLessThanOrEqual(1500);
}
});
});
@@ -1,18 +0,0 @@
export interface ReconnectDelayOptions {
baseDelayMs: number;
maxDelayMs: number;
}
/**
* Exponential backoff with equal jitter. Half of each delay is fixed and half
* is random, so a relay restart spreads reconnects out instead of every client
* retrying on the same tick.
*/
export function getReconnectDelayMs(
attempt: number,
options: ReconnectDelayOptions,
random: () => number = Math.random,
): number {
const ceiling = Math.min(options.baseDelayMs * 2 ** attempt, options.maxDelayMs);
return Math.round(ceiling / 2 + random() * (ceiling / 2));
}
@@ -1,204 +0,0 @@
// The plugin the demo agent "builds" in the store screenshots: a Deploys pill on
// every composer that opens the latest preview deploy for each branch. The
// deploys are fixed sample data; the UI is a real plugin surface.
import type {
PluginButtonContentProps,
PluginButtonRegistration,
PluginClientContext,
} from "@getpaseo/plugin/client";
import { useMemo } from "react";
import { Text, View } from "react-native";
type DeployStatus = "ready" | "building" | "failed";
interface Deploy {
branch: string;
status: DeployStatus;
detail: string;
age: string;
progress?: number;
}
const DEPLOYS: Deploy[] = [
{ branch: "fix/reconnect-jitter", status: "ready", detail: "Built in 48s", age: "2m" },
{
branch: "perf/provider-snapshot-cache",
status: "building",
detail: "Bundling app",
age: "now",
progress: 0.64,
},
{ branch: "feat/remember-terminal", status: "ready", detail: "Built in 51s", age: "18m" },
{
branch: "i18n/ko-settings",
status: "failed",
detail: "Missing key settings.notifications",
age: "26m",
},
];
function DeploysSheet({ theme, layout }: PluginButtonContentProps) {
const mono = layout.platform === "ios" ? "Menlo" : "monospace";
const styles = useMemo(
() => ({
// Popovers on tablets and desktop are narrow by default; give the
// branch names room. Phones show the sheet at full width.
body: { gap: 14, width: layout.compact ? undefined : 400 },
production: {
padding: 14,
gap: 6,
borderRadius: 12,
backgroundColor: theme.colors.surface2,
},
productionTop: { flexDirection: "row" as const, alignItems: "center" as const, gap: 8 },
label: { color: theme.colors.foregroundMuted, fontSize: 13 },
version: { color: theme.colors.foreground, fontSize: 22, fontWeight: "600" as const },
live: { color: theme.colors.statusSuccess, fontSize: 13, fontWeight: "600" as const },
heading: { color: theme.colors.foregroundMuted, fontSize: 13, marginTop: 4 },
list: {
borderRadius: 12,
borderWidth: 1,
borderColor: theme.colors.border,
overflow: "hidden" as const,
},
row: {
flexDirection: "row" as const,
alignItems: "center" as const,
gap: 12,
paddingVertical: 12,
paddingHorizontal: 14,
},
divider: { height: 1, backgroundColor: theme.colors.border },
text: { flex: 1, gap: 4 },
branch: { color: theme.colors.foreground, fontSize: 14, fontFamily: mono },
detail: { color: theme.colors.foregroundMuted, fontSize: 13 },
failed: { color: theme.colors.statusDanger, fontSize: 13 },
age: { color: theme.colors.foregroundMuted, fontSize: 13 },
track: {
height: 4,
marginTop: 4,
borderRadius: 2,
backgroundColor: theme.colors.surface2,
overflow: "hidden" as const,
},
}),
[theme, mono, layout.compact],
);
const dotColor: Record<DeployStatus, string> = {
ready: theme.colors.statusSuccess,
building: theme.colors.statusWarning,
failed: theme.colors.statusDanger,
};
return (
<View style={styles.body}>
<View style={styles.production}>
<View style={styles.productionTop}>
<Dot color={theme.colors.statusSuccess} />
<Text style={styles.live}>Live</Text>
<Text style={styles.label}>Production · main</Text>
</View>
<Text style={styles.version}>v0.14.0-beta.1</Text>
<Text style={styles.label}>Deployed 3h ago</Text>
</View>
<Text style={styles.heading}>Previews</Text>
<View style={styles.list}>
{DEPLOYS.map((deploy, index) => (
<View key={deploy.branch}>
{index > 0 ? <View style={styles.divider} /> : null}
<View style={styles.row}>
<Dot color={dotColor[deploy.status]} />
<View style={styles.text}>
<Text style={styles.branch} numberOfLines={1}>
{deploy.branch}
</Text>
<Text style={deploy.status === "failed" ? styles.failed : styles.detail}>
{deploy.detail}
</Text>
{deploy.progress !== undefined ? (
<Progress
value={deploy.progress}
track={styles.track}
color={theme.colors.statusWarning}
/>
) : null}
</View>
<Text style={styles.age}>{deploy.age}</Text>
</View>
</View>
))}
</View>
</View>
);
}
function Progress({ value, track, color }: { value: number; track: object; color: string }) {
const fill = useMemo(
() => ({ width: `${value * 100}%` as const, height: 4, backgroundColor: color }),
[value, color],
);
return (
<View style={track}>
<View style={fill} />
</View>
);
}
function Dot({ color }: { color: string }) {
const style = useMemo(
() => ({ width: 8, height: 8, borderRadius: 4, backgroundColor: color }),
[color],
);
return <View style={style} />;
}
export default function contribute(client: PluginClientContext) {
const pills = new Map<string, PluginButtonRegistration>();
const lifetime = new AbortController();
const register = (agent: { id: string; workspaceId?: string | null }) => {
if (lifetime.signal.aborted || !agent.workspaceId) return;
pills.get(agent.id)?.remove();
pills.set(
agent.id,
client.addComposerPill({
id: "deploys",
workspaceId: agent.workspaceId,
agentId: agent.id,
button: {
title: "Preview deploys",
icon: "Rocket",
label: "Deploys",
behavior: { kind: "popover", Content: DeploysSheet },
},
}),
);
};
void client.paseo.agents
.list({ subscribe: {}, signal: lifetime.signal })
.then(({ subscription }) => {
subscription.subscribe({
snapshot: ({ entries }) => {
for (const pill of pills.values()) pill.remove();
pills.clear();
for (const { agent } of entries) register(agent);
},
update: (message) => {
if (message.type !== "agent_update") return;
const update = message.payload;
if (update.kind === "remove") {
pills.get(update.agentId)?.remove();
pills.delete(update.agentId);
} else register(update.agent);
},
});
return undefined;
})
.catch((error) => {
if (!lifetime.signal.aborted) console.error("Agent observation failed", error);
});
return () => {
lifetime.abort();
for (const pill of pills.values()) pill.remove();
pills.clear();
};
}
@@ -1,4 +0,0 @@
{
"id": "preview-deploys",
"requirements": { "paseo": ">=0.8.0" }
}
@@ -1,281 +0,0 @@
// Scripted Claude Code and Codex clients for staging store screenshots.
// Each agent replays a fixed conversation through the real daemon, so the app
// renders real timeline rows, permission prompts, and running states.
import { randomUUID } from "node:crypto";
import type {
AgentCapabilityFlags,
AgentClient,
AgentMode,
AgentModelDefinition,
AgentPermissionRequest,
AgentPermissionResponse,
AgentPersistenceHandle,
AgentPromptInput,
AgentRunResult,
AgentSession,
AgentSessionConfig,
AgentStreamEvent,
AgentTimelineItem,
ToolCallDetail,
} from "../../../packages/server/src/server/agent/agent-sdk-types.js";
import { getAgentProviderDefinition } from "@getpaseo/protocol/provider-manifest";
export type ScriptStep =
| { kind: "say"; text: string }
| { kind: "think"; text: string }
| { kind: "tool"; name: string; detail: ToolCallDetail }
| { kind: "todo"; items: { text: string; completed: boolean }[] }
| { kind: "wait"; ms: number }
| { kind: "running-tool"; name: string; detail: ToolCallDetail }
| { kind: "ask"; name: string; title: string; detail: ToolCallDetail };
export interface AgentScript {
/** Matched against the start of the prompt that opens the turn. */
prompt: string;
steps: ScriptStep[];
/** Leave the turn open after the last step. */
keepRunning?: boolean;
/** Pause between steps, so "Worked for" reflects a believable duration. */
stepDelayMs?: number;
}
const CAPABILITIES: AgentCapabilityFlags = {
supportsStreaming: true,
supportsSessionPersistence: true,
supportsDynamicModes: false,
supportsMcpServers: false,
supportsReasoningStream: true,
supportsToolInvocations: true,
supportsRewindConversation: false,
supportsRewindFiles: false,
supportsRewindBoth: false,
};
const MODELS: Record<string, AgentModelDefinition[]> = {
claude: [
{
provider: "claude",
id: "claude-opus-5-5",
label: "Opus 5.5",
isDefault: true,
thinkingOptions: [
{ id: "medium", label: "Medium", isDefault: true },
{ id: "high", label: "High" },
],
defaultThinkingOptionId: "medium",
},
{ provider: "claude", id: "claude-sonnet-5-5", label: "Sonnet 5.5" },
],
codex: [
{
provider: "codex",
id: "gpt-5.6-sol",
label: "GPT-5.6-Sol",
isDefault: true,
thinkingOptions: [
{ id: "medium", label: "Medium", isDefault: true },
{ id: "high", label: "High" },
],
defaultThinkingOptionId: "medium",
},
],
};
function promptText(prompt: AgentPromptInput): string {
if (typeof prompt === "string") return prompt;
return prompt
.map((block) => ("text" in block && typeof block.text === "string" ? block.text : ""))
.join("");
}
class ScriptedSession implements AgentSession {
readonly capabilities = CAPABILITIES;
readonly id = randomUUID();
private readonly listeners = new Set<(event: AgentStreamEvent) => void>();
private readonly history: AgentStreamEvent[] = [];
private pending: AgentPermissionRequest[] = [];
private activeTurnId: string | null = null;
constructor(
readonly provider: string,
private readonly config: AgentSessionConfig,
private readonly scripts: AgentScript[],
) {}
private emit(event: AgentStreamEvent): void {
const tagged = this.activeTurnId ? { ...event, turnId: this.activeTurnId } : event;
this.history.push(tagged);
for (const listener of this.listeners) listener(tagged);
}
private timeline(item: AgentTimelineItem): void {
this.emit({ type: "timeline", provider: this.provider, item });
}
async run(): Promise<AgentRunResult> {
return { sessionId: this.id, finalText: "", timeline: [] };
}
async startTurn(prompt: AgentPromptInput): Promise<{ turnId: string }> {
const turnId = randomUUID();
this.activeTurnId = turnId;
const text = promptText(prompt);
const script = this.scripts.find((candidate) => text.startsWith(candidate.prompt));
setTimeout(() => void this.play(text, script), 50);
return { turnId };
}
private async play(text: string, script: AgentScript | undefined): Promise<void> {
this.emit({ type: "turn_started", provider: this.provider });
this.timeline({ type: "user_message", text, messageId: randomUUID() });
const delay = script?.stepDelayMs ?? 400;
for (const step of script?.steps ?? [{ kind: "say", text: "Done." } as const]) {
await new Promise((resolve) => setTimeout(resolve, step.kind === "wait" ? step.ms : delay));
this.playStep(step);
if (step.kind === "ask") return;
}
if (script?.keepRunning) return;
this.emit({
type: "turn_completed",
provider: this.provider,
usage: { inputTokens: 48_210, outputTokens: 3_904 },
});
this.activeTurnId = null;
}
private playStep(step: ScriptStep): void {
switch (step.kind) {
case "say":
this.timeline({ type: "assistant_message", text: step.text, messageId: randomUUID() });
return;
case "think":
this.timeline({ type: "reasoning", text: step.text });
return;
case "todo":
this.timeline({ type: "todo", items: step.items });
return;
case "wait":
return;
case "tool":
case "running-tool": {
const callId = randomUUID();
this.timeline({
type: "tool_call",
callId,
name: step.name,
status: "running",
error: null,
detail: step.detail,
});
if (step.kind === "tool") {
this.timeline({
type: "tool_call",
callId,
name: step.name,
status: "completed",
error: null,
detail: step.detail,
});
}
return;
}
case "ask": {
const request: AgentPermissionRequest = {
id: randomUUID(),
provider: this.provider,
name: step.name,
kind: "tool",
title: step.title,
detail: step.detail,
};
this.pending = [request];
this.emit({ type: "permission_requested", provider: this.provider, request });
}
}
}
subscribe(callback: (event: AgentStreamEvent) => void): () => void {
this.listeners.add(callback);
return () => this.listeners.delete(callback);
}
async *streamHistory(): AsyncGenerator<AgentStreamEvent> {
yield* this.history;
}
async getRuntimeInfo() {
return {
provider: this.provider,
sessionId: this.id,
model: this.config.model ?? MODELS[this.provider]?.[0]?.id ?? null,
thinkingOptionId: this.config.thinkingOptionId ?? "medium",
modeId: this.config.modeId ?? null,
};
}
async getAvailableModes(): Promise<AgentMode[]> {
return getAgentProviderDefinition(this.provider).modes;
}
async getCurrentMode(): Promise<string | null> {
return this.config.modeId ?? null;
}
async setMode(): Promise<void> {}
getPendingPermissions(): AgentPermissionRequest[] {
return this.pending;
}
async respondToPermission(requestId: string, resolution: AgentPermissionResponse) {
this.pending = [];
this.emit({ type: "permission_resolved", provider: this.provider, requestId, resolution });
}
describePersistence(): AgentPersistenceHandle {
return { provider: this.provider, sessionId: this.id };
}
async interrupt(): Promise<void> {
if (!this.activeTurnId) return;
this.emit({ type: "turn_canceled", provider: this.provider, reason: "Interrupted" });
this.activeTurnId = null;
}
async close(): Promise<void> {}
}
export class ScriptedAgentClient implements AgentClient {
readonly capabilities = CAPABILITIES;
constructor(
readonly provider: string,
private readonly scripts: AgentScript[],
) {}
async createSession(config: AgentSessionConfig): Promise<AgentSession> {
return new ScriptedSession(this.provider, config, this.scripts);
}
async resumeSession(
_handle: AgentPersistenceHandle,
overrides?: Partial<AgentSessionConfig>,
): Promise<AgentSession> {
return new ScriptedSession(
this.provider,
{ provider: this.provider, cwd: overrides?.cwd ?? process.cwd(), ...overrides },
this.scripts,
);
}
async fetchCatalog() {
return {
models: MODELS[this.provider] ?? [],
modes: getAgentProviderDefinition(this.provider).modes,
};
}
async isAvailable(): Promise<boolean> {
return true;
}
}
-556
View File
@@ -1,556 +0,0 @@
// Stages the demo host used for store screenshots.
//
// npx tsx assets/store-screenshots/demo/stage.mts
//
// Starts an in-process daemon on DEMO_PORT (default 7791) with scripted Claude
// Code and Codex clients, adds a local clone of this repository as the `paseo`
// project, cuts real worktrees, applies a real change to the hero worktree, and
// opens a terminal there. Leave it running while you capture.
import { execFileSync, execSync } from "node:child_process";
import { existsSync } from "node:fs";
import { mkdir, readFile, rm, symlink, writeFile } from "node:fs/promises";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { createTestPaseoDaemon } from "../../../packages/server/src/server/test-utils/paseo-daemon.js";
import { DaemonClient } from "../../../packages/server/src/server/test-utils/daemon-client.js";
import { type AgentScript, ScriptedAgentClient } from "./scripted-agents.mjs";
const here = path.dirname(fileURLToPath(import.meta.url));
const repoRoot = path.resolve(here, "../../..");
const demoRoot = path.join(repoRoot, ".dev/store-capture/demo");
const codeRoot = path.join(demoRoot, "code");
const pluginDir = path.join(here, "preview-deploys");
const port = Number(process.env.DEMO_PORT ?? 7791);
const minute = 60_000;
const claudeScripts: AgentScript[] = [];
const codexScripts: AgentScript[] = [];
function git(cwd: string, ...args: string[]): string {
return execFileSync("git", ["-c", "user.name=Mo", "-c", "user.email=mo@paseo.sh", ...args], {
cwd,
encoding: "utf8",
});
}
function run(cwd: string, command: string): string {
return execSync(command, { cwd, encoding: "utf8", env: { ...process.env, FORCE_COLOR: "0" } });
}
async function prepareRepos(): Promise<void> {
// A fresh clone each run: worktrees from an earlier run stay registered in it.
// Worktree setup (npm ci, builds) is dropped so new worktrees open instantly.
const paseo = path.join(codeRoot, "paseo");
await rm(paseo, { recursive: true, force: true });
await mkdir(codeRoot, { recursive: true });
execFileSync("git", ["clone", "-q", "--local", repoRoot, paseo]);
git(paseo, "checkout", "-q", "-B", "main");
git(paseo, "remote", "remove", "origin");
const config = JSON.parse(await readFile(path.join(paseo, "paseo.json"), "utf8"));
delete config.worktree;
await writeFile(path.join(paseo, "paseo.json"), `${JSON.stringify(config, null, 2)}\n`);
git(paseo, "commit", "-qam", "chore: skip worktree setup in demo");
const dotfiles = path.join(codeRoot, "dotfiles");
if (!existsSync(dotfiles)) {
await mkdir(dotfiles, { recursive: true });
await writeFile(path.join(dotfiles, "tmux.conf"), "set -g mouse on\nset -g base-index 1\n");
await writeFile(path.join(dotfiles, "zshrc"), "export EDITOR=nvim\nalias g=git\n");
git(dotfiles, "init", "-q", "-b", "main");
git(dotfiles, "add", ".");
git(dotfiles, "commit", "-qm", "Initial dotfiles");
}
}
async function main(): Promise<void> {
await prepareRepos();
const home = path.join(demoRoot, "home");
await rm(home, { recursive: true, force: true });
await mkdir(home, { recursive: true });
const daemon = await createTestPaseoDaemon({
agentClients: {
claude: new ScriptedAgentClient("claude", claudeScripts),
codex: new ScriptedAgentClient("codex", codexScripts),
},
listen: "127.0.0.1",
listenPort: port,
paseoHomeRoot: home,
mcpEnabled: false,
cleanup: false,
pluginsEnabled: true,
plugins: {
"preview-deploys": { source: "directory", path: pluginDir, enabled: true },
},
});
const client = new DaemonClient({
url: `ws://127.0.0.1:${daemon.port}/ws`,
appVersion: "0.14.0",
});
await client.connect();
await client.fetchAgents({ subscribe: {} });
const paseo = await client.addProject(path.join(codeRoot, "paseo"));
const dotfiles = await client.addProject(path.join(codeRoot, "dotfiles"));
const paseoProjectId = paseo.project!.projectId;
async function worktree(title: string, branchName: string) {
const result = await client.createWorkspace({
title,
source: {
kind: "worktree",
projectId: paseoProjectId,
action: "branch-off",
baseBranch: "main",
branchName,
},
});
if (!result.workspace) throw new Error(`No workspace for ${title}: ${JSON.stringify(result)}`);
return result.workspace;
}
async function agent(input: {
provider: "claude" | "codex";
workspace: { id: string; workspaceDirectory?: string | null };
cwd: string;
title: string;
script: AgentScript;
}) {
(input.provider === "claude" ? claudeScripts : codexScripts).push(input.script);
return client.createAgent({
provider: input.provider,
cwd: input.cwd,
workspaceId: input.workspace.id,
title: input.title,
initialPrompt: input.script.prompt,
});
}
const pause = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
// Done: finished earlier and already read.
const release = await worktree("Release v0.14.0-beta.1", "release/0.14.0-beta.1");
const releaseAgent = await agent({
provider: "codex",
workspace: release,
cwd: release.workspaceDirectory!,
title: "Release v0.14.0-beta.1",
script: {
prompt: "Cut 0.14.0-beta.1 from main and draft the release notes.",
steps: [
{
kind: "tool",
name: "shell",
detail: {
type: "shell",
command: "npm run release:beta",
output: "Tagged v0.14.0-beta.1\n",
exitCode: 0,
},
},
{
kind: "say",
text: "Tagged `v0.14.0-beta.1` and drafted the release notes. CI is building the desktop and mobile artifacts.",
},
],
},
});
const dotfilesWorkspace = (
await client.createWorkspace({
title: "Add a tmux status line",
source: {
kind: "directory",
path: path.join(codeRoot, "dotfiles"),
projectId: dotfiles.project!.projectId,
},
})
).workspace!;
const tmuxAgent = await agent({
provider: "claude",
workspace: dotfilesWorkspace,
cwd: path.join(codeRoot, "dotfiles"),
title: "Add a tmux status line",
script: {
prompt: "Add a minimal tmux status line with the session name and battery.",
steps: [
{
kind: "tool",
name: "Edit",
detail: {
type: "edit",
filePath: "tmux.conf",
oldString: "",
newString: "set -g status-right '#S · #{battery_percentage}'",
},
},
{
kind: "say",
text: "Added a status line with the session name on the left and battery on the right.",
},
],
},
});
await pause(3000);
await client.clearAgentAttention([releaseAgent.id, tmuxAgent.id]);
// Working: turns that stay open while you capture.
const ipad = await worktree(
"Keep the composer above the iPad keyboard",
"fix/ipad-keyboard-inset",
);
await agent({
provider: "codex",
workspace: ipad,
cwd: ipad.workspaceDirectory!,
title: "Keep the composer above the iPad keyboard",
script: {
prompt:
"On iPad with a hardware keyboard attached, the composer jumps up as if the software keyboard were open. Find out why and fix it.",
keepRunning: true,
steps: [
{
kind: "tool",
name: "shell",
detail: {
type: "shell",
command: 'rg -n "keyboardHeight" packages/app/src',
output:
"packages/app/src/keyboard/shift/internal/provider.ts:41: const keyboardHeight = useSharedValue(0);\n",
exitCode: 0,
},
},
{
kind: "tool",
name: "read",
detail: {
type: "read",
filePath: "packages/app/src/keyboard/shift/internal/provider.ts",
},
},
{
kind: "say",
text: "The shift provider trusts the keyboard frame event. With a hardware keyboard, iPadOS still reports the shortcuts bar as a keyboard frame, so we lift the composer by its full height. Checking the frame against the screen bottom next.",
},
{
kind: "running-tool",
name: "shell",
detail: { type: "shell", command: "npx vitest run packages/app/src/keyboard" },
},
],
},
});
const snapshots = await worktree(
"Cache provider snapshots on disk",
"perf/provider-snapshot-cache",
);
await agent({
provider: "claude",
workspace: snapshots,
cwd: snapshots.workspaceDirectory!,
title: "Cache provider snapshots on disk",
script: {
prompt:
"Cold start spends about two seconds probing providers. Cache the last provider snapshot on disk and refresh it in the background.",
keepRunning: true,
steps: [
{
kind: "todo",
items: [
{ text: "Find where snapshots are built", completed: true },
{ text: "Persist the last snapshot per host", completed: false },
{ text: "Refresh in the background after boot", completed: false },
],
},
{
kind: "tool",
name: "Read",
detail: {
type: "read",
filePath: "packages/server/src/server/agent/provider-snapshot-manager.ts",
},
},
{
kind: "running-tool",
name: "Edit",
detail: {
type: "edit",
filePath: "packages/server/src/server/agent/provider-snapshot-manager.ts",
},
},
],
},
});
// Needs input: waiting on a permission.
const korean = await worktree("Korean translations for Settings", "i18n/ko-settings");
await agent({
provider: "claude",
workspace: korean,
cwd: korean.workspaceDirectory!,
title: "Korean translations for Settings",
script: {
prompt: "Translate the new Settings strings into Korean and open a PR.",
steps: [
{
kind: "tool",
name: "Read",
detail: { type: "read", filePath: "packages/app/src/i18n/resources/en.ts" },
},
{
kind: "tool",
name: "Edit",
detail: { type: "edit", filePath: "packages/app/src/i18n/resources/ko.ts" },
},
{
kind: "tool",
name: "Bash",
detail: {
type: "shell",
command: "npm run test --workspace=@getpaseo/app -- i18n",
output: "Test Files 3 passed (3)\n Tests 41 passed (41)\n",
exitCode: 0,
},
},
{ kind: "say", text: "Translated 18 strings. I'll push the branch so I can open the PR." },
{
kind: "ask",
name: "Bash",
title: "Bash",
detail: { type: "shell", command: "git push -u origin i18n/ko-settings" },
},
],
},
});
// Ready to review: a second finished agent.
const terminals = await worktree(
"Remember the last terminal per workspace",
"feat/remember-terminal",
);
await agent({
provider: "codex",
workspace: terminals,
cwd: terminals.workspaceDirectory!,
title: "Remember the last terminal per workspace",
script: {
prompt:
"When I switch back to a workspace, open the terminal I was using last instead of the first one.",
steps: [
{
kind: "tool",
name: "shell",
detail: {
type: "shell",
command: 'rg -n "activeTerminalId" packages/app/src',
output: "",
exitCode: 0,
},
},
{
kind: "say",
text: "Workspaces now remember their last focused terminal and reopen it when you switch back. The choice is stored per host, so it survives restarts.",
},
],
},
});
// Plugin: the agent "built" the preview-deploys plugin this daemon runs.
const plugin = await worktree("Build a preview deploys plugin", "plugins/preview-deploys");
const pluginSource = (file: string) => run(pluginDir, `cat ${file}`);
await agent({
provider: "claude",
workspace: plugin,
cwd: plugin.workspaceDirectory!,
title: "Build a preview deploys plugin",
script: {
prompt: "Build me a plugin that shows our preview deploys right next to the composer.",
stepDelayMs: 6_000,
steps: [
{ kind: "tool", name: "Read", detail: { type: "read", filePath: "docs/plugins.md" } },
{
kind: "tool",
name: "Write",
detail: {
type: "write",
filePath: "plugins/preview-deploys/paseo-plugin.json",
content: pluginSource("paseo-plugin.json"),
},
},
{
kind: "tool",
name: "Write",
detail: {
type: "write",
filePath: "plugins/preview-deploys/index.client.tsx",
content: pluginSource("index.client.tsx"),
},
},
{
kind: "tool",
name: "Bash",
detail: {
type: "shell",
command: "paseo plugin install ./plugins/preview-deploys",
output: "Installed preview-deploys\n",
exitCode: 0,
},
},
{
kind: "say",
text: "Done. **Deploys** now sits above the composer in every workspace. Tap it to see production and the latest preview for each branch, with build progress and failures.",
},
],
},
});
// Hero: Claude finished a real change in a real worktree.
const jitter = await worktree("Add jitter to reconnect backoff", "fix/reconnect-jitter");
const cwd = jitter.workspaceDirectory!;
await symlink(path.join(repoRoot, "node_modules"), path.join(cwd, "node_modules"));
execFileSync("node", [path.join(here, "change/apply.mjs"), cwd]);
const clientDiff = git(cwd, "diff", "--", "packages/client/src/daemon-client.ts");
const vitest = run(
cwd,
"npx vitest run packages/client/src/connection/reconnect-delay.test.ts",
).replace(/^ RUN .*\n/m, "");
const readExcerpt = run(cwd, "sed -n '7067,7086p' packages/client/src/daemon-client.ts");
await agent({
provider: "claude",
workspace: jitter,
cwd,
title: "Add jitter to reconnect backoff",
script: {
prompt:
'When the relay restarts, every phone reconnects at the same moment and we get a spike. Add jitter to the reconnect backoff, keep the 30s cap, and make sure the "Retrying in" countdown still matches the real delay.',
stepDelayMs: 7_000,
steps: [
{
kind: "tool",
name: "Grep",
detail: {
type: "search",
toolName: "grep",
query: "reconnectAttempt",
filePaths: ["packages/client/src/daemon-client.ts"],
numFiles: 1,
numMatches: 9,
mode: "files_with_matches",
},
},
{
kind: "tool",
name: "Read",
detail: {
type: "read",
filePath: "packages/client/src/daemon-client.ts",
offset: 7040,
limit: 60,
content: readExcerpt,
},
},
{
kind: "say",
text: "The delay is calculated twice: once for `nextRetryAt`, which drives the countdown, and again when the timer is armed. Both use plain doubling, so every client retries on the same schedule. If I add randomness in both places the countdown will be wrong, so I'll draw the jitter once per attempt and share it.",
},
{
kind: "tool",
name: "Write",
detail: {
type: "write",
filePath: "packages/client/src/connection/reconnect-delay.ts",
content: run(cwd, "cat packages/client/src/connection/reconnect-delay.ts"),
},
},
{
kind: "tool",
name: "Edit",
detail: {
type: "edit",
filePath: "packages/client/src/daemon-client.ts",
unifiedDiff: clientDiff,
},
},
{
kind: "tool",
name: "Write",
detail: {
type: "write",
filePath: "packages/client/src/connection/reconnect-delay.test.ts",
content: run(cwd, "cat packages/client/src/connection/reconnect-delay.test.ts"),
},
},
{
kind: "tool",
name: "Bash",
detail: {
type: "shell",
command: "npx vitest run packages/client/src/connection/reconnect-delay.test.ts",
output: vitest,
exitCode: 0,
},
},
{
kind: "tool",
name: "Edit",
detail: {
type: "edit",
filePath: "CHANGELOG.md",
unifiedDiff: git(cwd, "diff", "--", "CHANGELOG.md"),
},
},
{
kind: "say",
text: [
"Reconnects now back off with jitter.",
"",
"- `getReconnectDelayMs` picks a delay between half and the full backoff, still capped at 30s.",
'- `DaemonClient` draws the delay once per attempt, so the "Retrying in" countdown matches the actual retry.',
"- Four new tests cover the doubling, the cap, the jitter range, and a quick first retry.",
"",
"Tests pass. After a relay restart, clients now spread their reconnects across the backoff window instead of arriving together.",
].join("\n"),
},
],
},
});
const terminal = await client.createTerminal(cwd, "zsh", undefined, {
workspaceId: jitter.id,
command: "bash",
args: ["--rcfile", path.join(here, "terminal-rc.sh"), "-i"],
});
const terminalId = terminal.terminal?.id;
if (terminalId) {
await pause(1500);
for (const line of [
"git status --short",
"cd packages/client",
"npx vitest run reconnect --reporter=tree",
]) {
client.sendTerminalInput(terminalId, { type: "input", data: `${line}\r` });
await pause(4000);
}
}
console.log(`READY port=${daemon.port} home=${daemon.paseoHome}`);
await writeFile(
path.join(demoRoot, "state.json"),
JSON.stringify(
{ port: daemon.port, home: daemon.paseoHome, hero: { workspaceId: jitter.id, cwd } },
null,
2,
),
);
const stop = async () => {
await client.close();
await daemon.close();
process.exit(0);
};
process.on("SIGTERM", stop);
process.on("SIGINT", stop);
void minute;
}
main().catch((error) => {
console.error(error);
process.exit(1);
});
@@ -1,19 +0,0 @@
# Shell profile for the demo terminal: a Pure-style two-line prompt that fits a
# phone-width terminal, and vitest output without the absolute checkout path
# or the long timing breakdown. Vitest drops its colors when piped, so the
# wrapper puts its usual green checks and grey timings back.
export FORCE_COLOR=1
__where() { local top; top=$(git rev-parse --show-toplevel 2>/dev/null); printf '~/paseo%s' "${PWD#"$top"}"; }
__branch() { git branch --show-current 2>/dev/null; }
__dirty() { [ -n "$(git status --porcelain 2>/dev/null)" ] && printf '*'; }
PROMPT_COMMAND='printf "\e]0;zsh\a"'
PS1='\n\[\e[34m\]$(__where)\[\e[0m\] \[\e[90m\]$(__branch)$(__dirty)\[\e[0m\]\n\[\e[35m\]❯\[\e[0m\] '
npx() {
command npx "$@" 2>&1 | sed -E \
-e '1{/^$/d}' -e '/ RUN /d' -e '/Start at/d' -e 's/ \(transform.*\)//' \
-e $'s/✓/\e[32m✓\e[0m/' \
-e $'s/ ([0-9]+ms)$/ \e[90m\\1\e[0m/' \
-e $'s/ (\\([0-9]+( tests)?\\))/ \e[90m\\1\e[0m/' \
-e $'s/([0-9]+ passed)/\e[1;32m\\1\e[0m/'
}
clear
Binary file not shown.

Before

Width:  |  Height:  |  Size: 541 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.3 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 599 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 931 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 736 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 373 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 701 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 463 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 514 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 510 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 537 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.4 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 607 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1006 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 760 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 358 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 645 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 431 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 470 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 473 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.0 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 694 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 397 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 370 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 396 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 454 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 492 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 497 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 281 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 248 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 272 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 257 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 298 KiB

-396
View File
@@ -1,396 +0,0 @@
// Renders the App Store and Google Play screenshots from the native captures in
// raw/. Every image is resized with Lanczos to the exact pixel size it occupies
// on the canvas, and the page renders at device scale 1, so the browser never
// resamples a capture.
//
// node assets/store-screenshots/render.mjs
//
// SF Pro is not redistributable. On macOS it comes from /System/Library/Fonts;
// elsewhere point SF_FONT_DIR at a folder holding SFNS.ttf copied from a Mac.
import { existsSync } from "node:fs";
import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import { fileURLToPath, pathToFileURL } from "node:url";
import { build } from "esbuild";
import { chromium } from "playwright";
import { createElement } from "react";
import { renderToStaticMarkup } from "react-dom/server";
import sharp from "sharp";
const root = path.dirname(fileURLToPath(import.meta.url));
const repo = path.resolve(root, "../..");
const raw = (device, name) => path.join(root, "raw", device, `${name}.png`);
const output = path.join(root, "output");
// Native captures per device: iPhone 16 Pro Max at 3x and iPad Pro 13-inch at
// 2x. The frame's screen radius and Dynamic Island are in capture pixels.
const DEVICES = {
iphone: {
capture: { width: 1320, height: 2868 },
radius: 186,
bezel: 22,
island: { width: 378, height: 112, top: 33 },
},
ipad: { capture: { width: 2064, height: 2752 }, radius: 44, bezel: 30, island: null },
};
// Every title wraps to two lines and every subline fits on one; the renderer
// fails otherwise, because the device is placed from that fixed text height.
//
// Each scene names its capture per device, and a device entry may override the
// title or subline where the copy depends on the form factor.
//
// A callout lifts a region of a capture out of the device. `crop` is in native
// capture pixels, `zoom` is its size relative to the device screen (capped to
// the canvas width), and the callout is centred on the spot the crop comes
// from, moved by `shift` native pixels down the screen.
const SCENES = [
{
id: "sidebar",
backdrop: "agents",
title: "Run many coding agents at once",
body: "See which agents are working and which need you.",
iphone: { capture: "sidebar" },
ipad: { capture: "sidebar" },
},
{
id: "chat",
title: "Your full dev environment on your phone",
body: "Start agents and follow every edit and command.",
iphone: { capture: "chat" },
ipad: { capture: "chat", title: "Your full dev environment on your tablet" },
},
{
id: "plugins",
title: "Ask an agent to change the app itself",
body: "This Deploys sheet is a plugin an agent wrote.",
iphone: {
capture: "plugin",
callout: { from: "plugin-sheet", crop: [0, 1340, 1320, 1400], zoom: 1.04, shift: -1400 },
},
ipad: {
capture: "plugin",
body: "This Deploys panel is a plugin an agent wrote.",
callout: { from: "plugin-sheet", crop: [670, 1486, 844, 970], zoom: 1.3, shift: -900 },
},
},
{
id: "review",
title: "Review the diff before you merge",
body: "Every file the agent changed, on its own branch.",
iphone: {
capture: "diff",
callout: { from: "files", crop: [0, 1060, 1320, 870], zoom: 1.26, shift: 110 },
},
ipad: { capture: "diff" },
},
{
id: "terminal",
title: "A real terminal in every workspace",
body: "Run the tests yourself, on your own machine.",
iphone: {
capture: "terminal",
callout: { from: "terminal", crop: [0, 950, 1320, 460], zoom: 1.35, shift: 110 },
},
ipad: {
capture: "terminal",
callout: { from: "terminal", crop: [596, 640, 1010, 412], zoom: 1.35, shift: 650 },
},
},
];
// `textTop` is where the text starts when the device is sized by the canvas
// height. A canvas too narrow for that, like a tablet on 9:16, sizes the device
// by its width and centres the text and device instead.
const STORES = {
apple: {
device: "iphone",
width: 1320,
height: 2868,
textTop: 230,
titleSize: 100,
bodySize: 46,
textWidth: 1120,
},
google: {
device: "iphone",
width: 1440,
height: 2560,
textTop: 150,
titleSize: 96,
bodySize: 44,
textWidth: 1200,
},
"apple-ipad": {
device: "ipad",
width: 2064,
height: 2752,
textTop: 200,
titleSize: 124,
bodySize: 56,
textWidth: 1400,
},
"google-tablet": {
device: "ipad",
width: 1800,
height: 3200,
textTop: 200,
titleSize: 136,
bodySize: 60,
textWidth: 1560,
},
};
const TITLE_LINE = 1.06;
const BODY_LINE = 1.3;
const BODY_GAP = 30;
// The device starts this far below the text and runs BLEED off the bottom.
const GAP = 140;
const BLEED = 40;
const MARGIN = 56;
const COLORS = { canvas: "#101615", title: "#ffffff", body: "rgba(255, 255, 255, 0.58)" };
function findFont() {
const dirs = [process.env.SF_FONT_DIR, "/System/Library/Fonts", "/Library/Fonts"].filter(Boolean);
for (const dir of dirs) {
const file = path.join(dir, "SFNS.ttf");
if (existsSync(file)) return file;
}
throw new Error("SF Pro not found. Set SF_FONT_DIR to a folder containing SFNS.ttf from macOS.");
}
// The device fills the canvas from GAP below the text to just past the bottom
// edge, so a taller canvas gets a larger device rather than a larger gap. When
// that would be wider than the canvas, the device takes the full width and the
// text and the whole device sit centred, still GAP apart.
function deviceLayout(store, device) {
const { capture, bezel } = device;
const textHeight = 2 * store.titleSize * TITLE_LINE + BODY_GAP + store.bodySize * BODY_LINE;
const tallest = store.height + BLEED - (store.textTop + textHeight + GAP) - 2 * bezel;
const widest = store.width - 2 * MARGIN - 2 * bezel;
const screenWidth = Math.min(Math.round((tallest * capture.width) / capture.height), widest);
const screenHeight = Math.round((screenWidth * capture.height) / capture.width);
const scale = screenWidth / capture.width;
const width = screenWidth + 2 * bezel;
const height = screenHeight + 2 * bezel;
const textTop =
screenWidth < widest
? store.height + BLEED - height - GAP - textHeight
: (store.height - height - GAP - textHeight) / 2;
const island = device.island && {
width: Math.round(device.island.width * scale),
height: Math.round(device.island.height * scale),
top: Math.round(device.island.top * scale),
};
return {
textTop: Math.round(textTop),
left: Math.round((store.width - width) / 2),
top: Math.round(textTop + textHeight + GAP),
width,
height,
bezel,
screenWidth,
screenHeight,
scale,
radius: Math.round(device.radius * scale),
island,
};
}
function calloutLayout(callout, frame, store) {
const [cropX, cropY, cropWidth, cropHeight] = callout.crop;
const scale = Math.min(frame.scale * callout.zoom, (store.width - 2 * MARGIN) / cropWidth);
const width = Math.round(cropWidth * scale);
const height = Math.round(cropHeight * scale);
const centreX = frame.left + frame.bezel + (cropX + cropWidth / 2) * frame.scale;
const centreY = frame.top + frame.bezel + (cropY + cropHeight / 2 + callout.shift) * frame.scale;
const clamp = (value, max) => Math.round(Math.min(Math.max(value, MARGIN), max - MARGIN));
return {
width,
height,
left: clamp(centreX - width / 2, store.width - width),
top: clamp(centreY - height / 2, store.height - height),
};
}
async function resize(source, crop, width, height, file) {
let image = sharp(source);
if (crop) image = image.extract({ left: crop[0], top: crop[1], width: crop[2], height: crop[3] });
await image.resize(width, height, { kernel: "lanczos3" }).png().toFile(file);
return pathToFileURL(file).href;
}
// Agent marks scattered behind the first panel, from the homepage's featured
// agents. Each entry is [mark, centre x, centre y, size, rotation], with the
// centre as a fraction of the canvas and the size as a fraction of its width.
const AGENT_MARKS = [
["ClaudeCodeIcon", 0.11, 0.075, 0.12, -14],
["CodexIcon", 0.89, 0.1, 0.13, 12],
["PiIcon", 0.07, 0.34, 0.1, 10],
["OmpIcon", 0.93, 0.37, 0.11, -10],
["OpenCodeIcon", 0.08, 0.6, 0.11, -8],
["CursorIcon", 0.92, 0.63, 0.1, 16],
["MuseCodeIcon", 0.07, 0.85, 0.11, 14],
["AntigravityIcon", 0.92, 0.88, 0.12, -12],
];
async function loadAgentMarks(work) {
const bundle = path.join(work, "agent-icons.mjs");
await build({
entryPoints: [path.join(repo, "packages/website/src/components/agent-icons.tsx")],
outfile: bundle,
bundle: true,
format: "esm",
platform: "node",
jsx: "automatic",
});
const icons = await import(pathToFileURL(bundle).href);
return Object.fromEntries(
AGENT_MARKS.map(([name]) => [name, renderToStaticMarkup(createElement(icons[name]))]),
);
}
function backdrop(store, marks) {
return AGENT_MARKS.map(([name, x, y, size, rotation]) => {
const side = Math.round(size * store.width);
const left = Math.round(x * store.width - side / 2);
const top = Math.round(y * store.height - side / 2);
return `<div class="mark" style="left:${left}px;top:${top}px;width:${side}px;height:${side}px;transform:rotate(${rotation}deg)">${marks[name]}</div>`;
}).join("");
}
function page({ store, shot, frame, screen, callout, calloutImage, font, marks }) {
const behind = shot.backdrop === "agents" ? backdrop(store, marks) : "";
const { island } = frame;
const notch = island
? `<div class="island" style="top:${island.top}px;width:${island.width}px;height:${island.height}px;margin-left:-${island.width / 2}px;border-radius:${island.height / 2}px"></div>`
: "";
const lifted = callout
? `<img class="callout" src="${calloutImage}" style="left:${callout.left}px;top:${callout.top}px;width:${callout.width}px;height:${callout.height}px">`
: "";
return `<!doctype html>
<meta charset="utf-8">
<style>
@font-face { font-family: "SF Pro"; src: url("${pathToFileURL(font).href}"); font-weight: 1 1000; }
* { margin: 0; box-sizing: border-box; }
html, body { width: ${store.width}px; height: ${store.height}px; overflow: hidden; background: ${COLORS.canvas}; }
body { position: relative; font-family: "SF Pro"; -webkit-font-smoothing: antialiased; }
.text { position: absolute; top: ${frame.textTop}px; left: 0; right: 0; margin: 0 auto; width: ${store.textWidth}px; text-align: center; }
.mark { position: absolute; color: #fff; opacity: 0.09; filter: grayscale(1) brightness(0) invert(1); }
.mark svg { display: block; width: 100%; height: 100%; }
h1 { color: ${COLORS.title}; font-size: ${store.titleSize}px; font-weight: 600; line-height: ${TITLE_LINE}; letter-spacing: -0.022em; text-wrap: balance; }
p { margin-top: ${BODY_GAP}px; color: ${COLORS.body}; font-size: ${store.bodySize}px; font-weight: 400; line-height: ${BODY_LINE}; letter-spacing: -0.005em; text-wrap: balance; }
.device { position: absolute; left: ${frame.left}px; top: ${frame.top}px; width: ${frame.width}px; height: ${frame.height}px; padding: ${frame.bezel}px; border-radius: ${frame.radius + frame.bezel}px; background: #040505; box-shadow: 0 0 0 3px #343b39, 0 0 0 5px #161b1a, 0 60px 140px rgba(0, 0, 0, 0.55); }
.screen { position: relative; width: ${frame.screenWidth}px; height: ${frame.screenHeight}px; border-radius: ${frame.radius}px; overflow: hidden; }
.screen img { display: block; width: ${frame.screenWidth}px; height: ${frame.screenHeight}px; }
.island { position: absolute; left: 50%; background: #000; }
.callout { position: absolute; display: block; border-radius: 36px; box-shadow: 0 0 0 2px rgba(255, 255, 255, 0.14), 0 40px 100px rgba(0, 0, 0, 0.6); }
</style>
${behind}
<div class="text"><h1>${shot.title}</h1><p>${shot.body}</p></div>
<div class="device"><div class="screen"><img src="${screen}">${notch}</div></div>
${lifted}`;
}
async function renderStore(browser, name, store, font, marks, work) {
const dir = path.join(output, name);
await mkdir(dir, { recursive: true });
const view = await browser.newPage({
viewport: { width: store.width, height: store.height },
deviceScaleFactor: 1,
});
const device = DEVICES[store.device];
const frame = deviceLayout(store, device);
const files = [];
for (const [index, scene] of SCENES.entries()) {
const stem = `${name}-${scene.id}`;
const shot = { ...scene, ...scene[store.device] };
const screen = await resize(
raw(store.device, shot.capture),
null,
frame.screenWidth,
frame.screenHeight,
path.join(work, `${stem}-screen.png`),
);
const callout = shot.callout ? calloutLayout(shot.callout, frame, store) : null;
const calloutImage = callout
? await resize(
raw(store.device, shot.callout.from),
shot.callout.crop,
callout.width,
callout.height,
path.join(work, `${stem}-callout.png`),
)
: null;
const html = path.join(work, `${stem}.html`);
await writeFile(html, page({ store, shot, frame, screen, callout, calloutImage, font, marks }));
await view.goto(pathToFileURL(html).href);
await view.evaluate(async () => {
await document.fonts.ready;
await Promise.all(Array.from(document.images, (image) => image.decode()));
});
await expectLines(view, "h1", 2, `${stem} title`);
await expectLines(view, "p", 1, `${stem} subline`);
const file = path.join(dir, `${String(index + 1).padStart(2, "0")}-${scene.id}.png`);
await sharp(await view.screenshot())
.removeAlpha()
.png()
.toFile(file);
files.push(file);
console.log(path.relative(repo, file));
}
await view.close();
return files;
}
async function expectLines(view, selector, expected, label) {
const lines = await view.$eval(selector, (element) =>
Math.round(element.clientHeight / parseFloat(getComputedStyle(element).lineHeight)),
);
if (lines !== expected) throw new Error(`${label} wraps to ${lines} lines, expected ${expected}`);
}
async function renderPreview(rows) {
const tile = 440;
const gap = 40;
const resized = [];
let top = gap;
let width = 0;
for (const files of rows) {
let left = gap;
let rowHeight = 0;
for (const file of files) {
const meta = await sharp(file).metadata();
const height = Math.round((meta.height * tile) / meta.width);
const input = await sharp(file).resize(tile, height, { kernel: "lanczos3" }).toBuffer();
resized.push({ input, left, top });
left += tile + gap;
rowHeight = Math.max(rowHeight, height);
}
width = Math.max(width, left);
top += rowHeight + gap;
}
const file = path.join(output, "preview.png");
await sharp({ create: { width, height: top, channels: 3, background: "#070a09" } })
.composite(resized)
.png()
.toFile(file);
console.log(path.relative(repo, file));
}
const font = findFont();
const work = await mkdtemp(path.join(os.tmpdir(), "paseo-store-"));
const browser = await chromium.launch({ headless: true });
try {
const marks = await loadAgentMarks(work);
const rows = [];
for (const [name, store] of Object.entries(STORES)) {
rows.push(await renderStore(browser, name, store, font, marks, work));
}
await renderPreview(rows);
} finally {
await browser.close();
await rm(work, { recursive: true, force: true });
}
+1 -1
View File
@@ -288,7 +288,7 @@ parentAgentId === thisAgent.id AND !archivedAt
- **Provider subagents** are child executions owned by Claude, Codex, or OpenCode. They are not inserted into `AgentManager` as managed agents. Providers emit a separate descriptor and timeline stream through `agent.provider_subagents.*`; the client keeps that state outside the normal agent store and merges only the presentation rows into the track. A descriptor's optional `parentSubagentId` identifies its direct provider-subagent parent; an absent value identifies a direct child of the managed agent.
Clicking either kind opens a workspace tab. On compact layouts it opens in a [sheet](explorer-sidebar.md#sheets) instead, replacing the subagents list in place (Back returns to the list); the sheet hides the composer and shows the agent's model and thinking as one line in its place (`PaneSubtitle`, the row provider subagents already use), and a Paseo subagent's sheet offers **Open as tab** (the full-screen glyph in the header) to get the composer back. A Paseo subagent tab is a normal interactive agent pane. A provider subagent tab is a read-only timeline pane with no composer, archive, detach, rewind, or fork actions. It shows its own direct children in a subagents track. Every subagent pane links back to its parent (`packages/app/src/subagents/parent/`): a pill above the composer when there is one, a parent box in the composer's place when there is not. Both panes use `AgentStreamView`, so message, reasoning, tool-call, and layout rendering stay identical.
Clicking either kind opens a workspace tab. On compact layouts it opens in a [sheet](explorer-sidebar.md#sheets) over the subagents list instead; the sheet hides the composer and shows the agent's model and thinking as one line in its place (`PaneSubtitle`, the row provider subagents already use), and a Paseo subagent's sheet offers **Open as tab** (the full-screen glyph in the header) to get the composer back. A Paseo subagent tab is a normal interactive agent pane. A provider subagent tab is a read-only timeline pane with no composer, archive, detach, rewind, or fork actions. It shows its own direct children in a subagents track. Every subagent pane links back to its parent (`packages/app/src/subagents/parent/`): a pill above the composer when there is one, a parent box in the composer's place when there is not. Both panes use `AgentStreamView`, so message, reasoning, tool-call, and layout rendering stay identical.
Provider timelines use the same structural timeline item format but deliberately have a separate lifecycle and transport. A provider thread/session identifier is not a Paseo agent identifier, and closing its tab is always layout-only.
+1 -1
View File
@@ -98,7 +98,7 @@ The older `android`, `android:development`, and `ios` commands remain aliases fo
`android:production` still builds and installs a release through Expo; use `build:apk` when you
need an artifact. `android:clear` removes the generated Android project.
Run `npm run test:android --workspace=@getpaseo/app` explicitly with a local Android toolchain to prebuild Android and run native module unit tests. Ordinary CI does not prebuild Android or run these tests.
Run `npm run test:android --workspace=@getpaseo/app` to prebuild Android and run native module unit tests. The app CI job runs this command with the Android toolchain.
### Diagnostic logs without ADB
+4 -6
View File
@@ -150,20 +150,18 @@ One row off the rail makes the whole card look unconsidered.
Compact-first. The small case is designed; the large case adds chrome around it.
Use `md: 600` for both the compact/wide layout boundary and responsive density, in logical points on native and CSS pixels on web. Do not add a separate density breakpoint. Measured content constraints remain independent: composer controls use `COMPACT_CONTENT_WIDTH` (500), so a narrow pane can keep compact controls inside a wide window.
The settings shell (`packages/app/src/screens/settings-screen.tsx`) and the projects screen (`packages/app/src/screens/projects-screen.tsx`) share the canonical list+detail navigation pattern:
The list+detail pattern is canonical and reused across surfaces. The settings shell (`packages/app/src/screens/settings-screen.tsx`) and the projects screen (`packages/app/src/screens/projects-screen.tsx`) implement it identically:
- On compact: full-screen list with `<BackHeader>` at the top. Tapping a row pushes a full-screen detail with its own `<BackHeader>` that returns to the list.
- On wide layouts: a sidebar on the left holds the list with `surfaceSidebar` background. The content pane on the right holds the selected detail with `<ScreenHeader>`, `<HeaderIconBadge>`, and `<ScreenTitle>`.
- On desktop: a 320px sidebar on the left holds the list with `surfaceSidebar` background. The content pane on the right holds the selected detail with `<ScreenHeader>`, `<HeaderIconBadge>`, and `<ScreenTitle>`.
The branching is one `useIsCompactFormFactor()` check at the top of the screen component. The list and the detail are the same components in both layouts; only the framing changes.
The workspace screen (`packages/app/src/screens/workspace/workspace-screen.tsx`) follows a different but parallel rule: tabs collapse on compact, panes split on desktop. The sidebar (`packages/app/src/components/left-sidebar.tsx`) is overlaid on compact and pinned on desktop.
On a narrow window using the wide layout, app navigation yields when the remaining width cannot accommodate the content topology. Settings prefers a 720px split (320px list + 400px detail); its list shrinks first to keep forms readable without reducing the detail below 400px. Explorer reserves at least 240px plus a 360px workspace. These are local space budgets, not compact breakpoints. The app sidebar shrinks from its preferred 320px toward a 200px minimum to leave a 400px center target; its preferred width fits at 720px. Temporary width clamps are render-only; widening restores the user's saved sidebar widths.
On a narrow desktop route, app navigation yields to the rendered content topology when the remaining width cannot preserve its center target: Settings keeps its 320px list + 400px detail split, and a workspace Explorer keeps its current visible width plus a 400px center pane. That is a topology decision at the app container, not a second compact breakpoint. Temporary width clamps are render-only; widening restores the user's saved sidebar widths.
Electron window controls are top-corner obstructions, not a compact-layout condition. Rendered surfaces declare which top corners they physically occupy; only those corners receive clearance. Full-window overlays redeclare both corners. A focused split pane owns both corners; if focus restoration temporarily exposes the full split tree, the split boundary reserves one top strip instead of assigning a control rectangle to an arbitrarily narrow leaf.
Electron window controls are top-corner obstructions, not a compact-layout condition. Rendered surfaces declare which top corners they physically occupy; only those corners receive clearance. Full-window overlays redeclare both corners. A focused split pane owns both corners; if focus restoration temporarily exposes the full split tree, the split boundary reserves one top strip instead of assigning a control rectangle to an arbitrarily narrow leaf. The 720px desktop breakpoint preserves the default 320px sidebar and target 400px center width when the Explorer is closed; it is product policy, not an obstruction gate.
Windows and Linux controls are fixed window chrome, outside scrolling header content. A tab rail that reaches them ends at their obstruction and shows the shared overflow fade. On macOS, the Explorer toggle occupies a fixed top-right window slot so opening and closing Explorer does not move the pointer target.
+13 -24
View File
@@ -33,36 +33,25 @@ keeps only agents and terminals. A panel kind opts in with `compactSheet` in its
(`packages/app/src/panels/panel-manifest.ts`), and the layout store's `openTab` decides between
sheet and tab, so callers open targets the same way on every layout. Each such sheet holds one
ordinary `WorkspaceTab` (`SheetTab` in the store) and is an `IsolatedBottomSheetModal` like every
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.
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
the `SheetTab` a reveal would show without opening it, so the page never enters `sheetsByWorkspace`.
See [menus.md](menus.md#a-page-that-fills-the-sheet) for the page contract.
other sheet in the app, so it sits on the one app-wide stack: a sheet opened from any sheet, a
subagent chosen from the subagents list included, lands on top of it, and closing the top sheet
(drag, Close, backdrop, or Android Back) uncovers the one below. The list stays open under the
sheet it opened; see [menus.md](menus.md#selecting-an-item-on-ios) for the row contract.
The store keeps `sheetsByWorkspace` in opening order and never reorders it, because moving a sheet
remounts its panel. Revealing a target that already has a sheet uncovers that sheet by closing the
ones above it, except ones holding unsaved work, which stay where they are. Opening a sheet as a tab
dismisses the sheets above it, since the tab would sit under them. The stack is not persisted.
Both kinds render the same `SheetPane` (`packages/app/src/screens/workspace/sheet-pane/`): the
header (icon, title, Back when there is a list to return to, Open as tab, Close), the pane, its
bottom inset, and its focus. Only the container differs, a workspace sheet in `sheet-tabs.tsx` or a
menu page in `sheet-pane/page.tsx`, so a fix to what a sheet shows lands in one place. The
container owns Android Back; the pane never subscribes to it.
Sheets are modal and cover both compact sidebars as well as the workspace. The header drags the
sheet through `SheetDragArea`, because the panel scrolls on its own and content panning would fight
it. Its trailing rail holds icon buttons only (`SheetHeaderIconButton`): Open as tab is the
full-screen glyph beside Close, so the title keeps its width. Compact sheets use the app overlay
host: a workspace-local host sits behind the app-level left sidebar. The sheet pane bridge
(`useSheetPaneBridge`) preserves existing editing sessions, caches, file-link resolution and
supported navigation context without moving their providers. Keep this capability at the workspace
boundary; new sheet callers must not assemble provider internals. Wide layouts retain local hosting
and pane geometry. Both hosts forward the same Gorhom modal queue; neither creates another stack.
See
Sheets are modal and cover both compact sidebars as well as the workspace. A sheet's header is its drag
handle, because the panel scrolls on its own and content panning would fight it. Its trailing rail
holds icon buttons only (`SheetHeaderIconButton`): Open as tab is the full-screen glyph beside
Close, so the title keeps its width. Compact sheets use the app overlay host: a workspace-local
host sits behind the app-level left sidebar. The workspace environment bridge preserves existing
editing sessions, caches, file-link resolution and supported navigation context without moving
their providers. Keep this capability at the workspace boundary; new sheet callers must not
assemble provider internals. Wide layouts retain local hosting and pane geometry. Both hosts
forward the same Gorhom modal queue; neither creates another stack. See
[floating-panels.md Gotcha 7](floating-panels.md#gotcha-7--a-sheet-cannot-read-context-from-its-call-site).
A sheet holding unsaved work is never implicitly displaced; only its guarded close removes it.
-13
View File
@@ -410,19 +410,6 @@ bridges the menu's two contexts; the rest pass `null`.
Wrapping providers _around_ the modal does nothing. They land on the wrong side.
## Gotcha 8 — Read safe-area insets where the overlay draws
A compact sheet tab's body (`SheetBottomInset` in `adaptive-modal-sheet.tsx`) pads the bottom
inset and gives its content a bottom inset of 0, so the composer dock sits the same in a sheet as
in a tab. An overlay opened from that content and calling `useSafeAreaInsets()` at its call site
gets that 0 and draws over the navigation bar.
- A Gorhom sheet reads the inset inside its children, which render in the app's sheet host. See
`CompactSheetBody`, `MenuSheetScrollView` and `ComboboxSheetFrame`.
- An RN `Modal` passes the call site's context straight through, so put a `SafeAreaProvider`
inside it and read the inset below that. The modal is its own window, and the provider measures
it. See `attachment-lightbox.tsx`.
## Recipe for a new anchored panel
Before you write a new one, ask:
+1 -1
View File
@@ -22,7 +22,7 @@ Authoritative terminology. UI label wins. Don't invent synonyms; use what's here
- **Sidebar items** — The configurable entries of the app sidebar, in two sections. Header: the rows at the head of the sidebar — New workspace, History, Search, Schedules, and plugin header items. Footer: the full-width rows between Add project and the footer icon row — Usage and plugin footer items. Add project and the icon row (Hosts, Help and support, Settings) are fixed and are not sidebar items. A plugin item may render several rows, such as one per bot; it is still one item that moves and hides as a block. Each section's order and visibility is one per-device preference (`AppSettings.sidebarNavItems`, `AppSettings.sidebarFooterItems`); every item may be off. UI: the Header and Footer cards on the Sidebar settings page. Code: `packages/app/src/sidebar-nav/model.ts` resolves a section, and the sidebar (`components/sidebar/sidebar-nav-rows.tsx`, the footer in `components/left-sidebar.tsx`) and the settings page (`screens/settings/sidebar/sidebar-nav-section.tsx`) read it through `useSidebarNavItems(section)`. Never hardcode one of these entries or add a second place that decides which ones show. Don't confuse with **Explorer sidebar**.
- **Explorer sidebar** — The dedicated navigation dock containing the Files and Changes trees. UI: "Explorer sidebar". Code: `packages/app/src/workspace-tabs/explorer-sidebar.ts`; persisted pane identifiers retain the `explorer` spelling. See [explorer-sidebar.md](explorer-sidebar.md).
- **Sheet** — Any bottom sheet; there is one kind and one app-wide stack, so a sheet opened from a sheet lands on top of it and closing it uncovers the one below. Code: `IsolatedBottomSheetModal` (`packages/app/src/components/ui/isolated-bottom-sheet-modal`). Forbidden: "Workspace sheet", "modal sheet" as a distinct kind. See [floating-panels.md](floating-panels.md).
- **Sheet tab** — A compact-layout sheet holding one file or subagent tab over the workspace without adding it to the tab switcher. A subagent chosen from the subagents list shows as a page of the list's sheet instead of a sheet of its own. UI action: "Open as tab". Code: `SheetTab` and `sheetsByWorkspace` in `packages/app/src/stores/workspace-layout-store.ts`, `SheetPane` (`packages/app/src/screens/workspace/sheet-pane/`). See [explorer-sidebar.md](explorer-sidebar.md#sheets).
- **Sheet tab** — A compact-layout sheet holding one file or subagent tab over the workspace without adding it to the tab switcher. UI action: "Open as tab". Code: `SheetTab` and `sheetsByWorkspace` in `packages/app/src/stores/workspace-layout-store.ts`, `SheetTabs` (`packages/app/src/screens/workspace/sheet-tabs.tsx`). See [explorer-sidebar.md](explorer-sidebar.md#sheets).
- **Side pane** — An ordinary right-side workspace pane used for content opened beside the user's work. It closes and participates in workspace splits like every other main-host pane. See [explorer-sidebar.md](explorer-sidebar.md#side-pane). Forbidden: "Side panel".
- **Directory-backed surface** — A right-sidebar surface whose content is determined by the workspace's `cwd`, so two workspaces on the same directory see identical content: git diff/status, forge change-request info, file preview/explorer contents. Keyed by `(serverId, cwd)`, never `workspaceId`. See [architecture.md](architecture.md#right-sidebar-boundary-directory-backed-vs-workspace-owned).
- **Workspace-owned state** — Per-workspace state that never leaks to a same-`cwd` sibling: tabs, agents, terminals, panes, title, plus review drafts, diff-mode overrides, composer attachments, and file-explorer open/expand state. Keyed by `workspaceId` (`cwd` only as a fallback for old payloads). See [architecture.md](architecture.md#right-sidebar-boundary-directory-backed-vs-workspace-owned).
+4 -23
View File
@@ -52,12 +52,10 @@ is another, with its own icons and hover-revealed actions — but both hand the
and take `closeOnSelect` to say whether choosing them ends the surface. A row that owns its press
outright leaves the surface open behind whatever it opened, and skips the iOS wait.
A row whose result opens a sheet opens it as a page of the menu's own sheet, never as a second
sheet over it: the row names a [fill page](#a-page-that-fills-the-sheet) with `opensPage`, the page
replaces the list in place, Back returns to the list, and Close ends both. A row that opens a tab
A row whose result opens a sheet passes `closeOnSelect={false}`: the sheet stacks over the menu
sheet and uncovers it on close, so the menu is where the user lands next. A row that opens a tab
closes, because the tab replaces the pane the menu belongs to. The subagents track asks the layout
store which sheet tab a row would show (`useSubagentSheetTab`), since the answer changes with the
layout; a row with none opens its tab.
store which one a row is (`useSubagentOpensInSheet`), since the answer changes with the layout.
## Pages
@@ -103,23 +101,6 @@ The sheet keeps `keyboardBehavior="interactive"`. `extend` grows a sheet to its
point, and with `enableDynamicSizing` that point is the content's own height — a short page does
not grow, and the keyboard comes up over the field you are typing into.
## A page that fills the sheet
A page can carry its own content instead of rows: `{ id, fill: true, content }`. Only the sheet
renders one. It takes the full-sheet snap point (`FULL_SHEET_SNAP_POINTS`) instead of sizing to
content, and the sheet stops panning on content drags, because the page scrolls on its own and a
drag would fight that scroll. The page's header drags the sheet instead, through `SheetDragArea`.
The content renders on the far side of the sheet's portal, so it brings its own context bridge,
built where the page is defined. Sheet tabs are the one user: `useSheetPanePage` turns a `SheetTab`
into a fill page around the same `SheetPane` the workspace's own sheets render. See
[explorer-sidebar.md](explorer-sidebar.md#sheets).
Back pops one page. The header's Back and Android Back both call `goBack`, which answers `false` at
the root so the sheet closes instead. A page whose definition disappears while it is open, such as
a subagent archived from elsewhere, is pruned from the path, and the sheet falls back to the page
that opened it.
## Hover intent
A flyout **overlaps its parent by 5pt** rather than sitting beside it. With a gap there is a strip
@@ -208,7 +189,7 @@ its own.
entering animation never ends at the off-screen measuring position; on a slow machine that
write moved the open menu back off-screen.
- **Sheets size to content.** `enableDynamicSizing`, not fixed snap points. A pushed page is
rarely the height of the page before it. A fill page is the one exception.
rarely the height of the page before it.
- **The sheet's content is teleported out of the menu's subtree**, so `MenuSheetSurface` rebuilds
both menu contexts through the sheet's `contextBridge`. Providing them around the modal puts
them on the wrong side of the portal and every item inside throws. Gotcha 7 in
+6 -8
View File
@@ -333,10 +333,11 @@ export default function contribute(client: PluginClientContext) {
}
```
The contribution function must return cleanup for resources created by plugin code. Server cleanup
may be async; Paseo waits for it when stopping the server plugin. Cleanup errors are logged and do
not interrupt host teardown. Client installation retention and disposal follow the public
[hosts and lifecycle contract](../public-docs/plugins/reference.md#hosts-and-lifecycle).
The contribution function must return cleanup. Server cleanup may be async; Paseo waits for it when
the plugin is reloaded, disabled, removed, disconnected, or shut down. Cleanup is for resources
created by plugin code. Paseo removes registered contributions, unmounts surfaces, clears query
state, rejects pending RPCs, closes the plugin's daemon session, and stops the subprocess. Cleanup
errors are logged and do not interrupt host teardown.
Paseo owns the route, screen header, icon validation, close action, theme DTO, layout facts,
and render error boundary. The contributed component owns the complete body below the header.
@@ -621,10 +622,7 @@ Request observation with `client.paseo.agents.list({ subscribe: {} })` and consu
demand. Provider and project `subscribe()` calls establish their own demand. On capable daemons, each
list-and-subscribe call has its own server ID, even for the same query. Older daemons retain
[shared delivery behavior](protocol-compatibility.md#owned-observations). Handle snapshots
also run after reconnect; replace your view before applying its subsequent updates. An installation
stays loaded during a dropped connection while the app retains its `DaemonClient` object. An
unchanged installation does not rerun setup on reconnect, so refresh state from those snapshots
rather than from setup. Switching connections replaces the client object and reinstalls plugins. The installation
also run after reconnect; replace your view before applying its subsequent updates. The installation
owns every observation created through its API and releases them on unload, including setup failure.
Mounted surfaces and command invocations have shorter API lifetimes.
@@ -5,16 +5,12 @@ import { expectComposerVisible } from "../support/helpers/composer";
import { installDaemonWebSocketGate } from "../support/helpers/daemon-websocket-gate";
import { openAgentRoute, seedMockAgentWorkspace } from "../support/helpers/mock-agent";
import {
expectSubagentRowGone,
expectSubagentRowVisible,
openSubagentFromCompactTrack,
seedSubagent,
} from "../support/helpers/subagents";
import {
backToList,
closeSheet,
expectNoSheetOpen,
expectOneSheetOpen,
expectOpenTabCount,
openSheetAsTab,
expectDeclinedDiscardPrompt,
@@ -56,10 +52,6 @@ test("compact opens files and subagents in a sheet, leaving the tabs for agents"
{ client: workspace.client, repoPath: workspace.cwd, workspaceId: workspace.workspaceId },
{ parentId: workspace.agentId, title: "Sheet child" },
);
const grandchild = await seedSubagent(
{ client: workspace.client, repoPath: workspace.cwd, workspaceId: workspace.workspaceId },
{ parentId: child.id, title: "Sheet grandchild" },
);
await openAgentRoute(page, { workspaceId: workspace.workspaceId, agentId: workspace.agentId });
await expectOpenTabCount(page, 1);
@@ -87,14 +79,12 @@ test("compact opens files and subagents in a sheet, leaving the tabs for agents"
await tapSheetBackdrop(page);
});
await test.step("a subagent opens in place of the subagents list", async () => {
await test.step("a subagent opens in a sheet over the subagents list", async () => {
await openSubagentFromCompactTrack(page, child.id);
const childSheet = sheet(page, child.title);
await expect(childSheet).toBeVisible();
await expectSheetAtSnap(page, child.title);
await expectSubagentRowGone(page, child.id);
await expectOneSheetOpen(page);
await expect(childSheet.getByRole("textbox", { name: "Message agent..." })).toHaveCount(0);
// The composer's model, thinking, and mode stand in for it, resolved the same way. An idle
// seeded agent has no context usage yet.
@@ -104,51 +94,23 @@ test("compact opens files and subagents in a sheet, leaving the tabs for agents"
await expectOpenTabCount(page, 1);
});
await test.step("Back returns the sheet to the list", async () => {
await backToList(page, child.title);
await expectSubagentRowVisible(page, child.id);
await expectOneSheetOpen(page);
});
await test.step("Close closes the list with the subagent", async () => {
await page.getByTestId(`subagents-track-row-${child.id}`).click();
await test.step("closing the subagent's sheet uncovers the list", async () => {
await closeSheet(page, child.title);
await expectSubagentRowGone(page, child.id);
await expectNoSheetOpen(page);
await expectSubagentRowVisible(page, child.id);
});
await test.step("the parent box in a subagent's sheet closes it onto the parent", async () => {
await openSubagentFromCompactTrack(page, child.id);
await page.getByTestId(`subagents-track-row-${child.id}`).click();
const childSheet = sheet(page, child.title);
await expectSheetAtSnap(page, child.title);
await expect(childSheet.getByTestId("composer-parent-agent-pill")).toHaveCount(0);
await childSheet.getByTestId("parent-agent-callout-open").click();
await expect(childSheet).toHaveCount(0);
await expectNoSheetOpen(page);
await expectOpenTabCount(page, 1);
});
await test.step("a nested subagent's parent box lands on its parent's sheet", async () => {
await openSubagentFromCompactTrack(page, child.id);
const childSheet = sheet(page, child.title);
await openSubagentFromCompactTrack(page, grandchild.id, childSheet);
const grandchildSheet = sheet(page, grandchild.title);
await expectSheetAtSnap(page, grandchild.title);
await expect(grandchildSheet.getByTestId("parent-agent-callout")).toContainText(child.title);
await grandchildSheet.getByTestId("parent-agent-callout-open").click();
await expect(grandchildSheet).toHaveCount(0);
await expect(childSheet).toBeVisible();
await expectOneSheetOpen(page);
await childSheet.getByTestId("parent-agent-callout-open").click();
await expect(childSheet).toHaveCount(0);
await expectNoSheetOpen(page);
await expectOpenTabCount(page, 1);
});
await test.step("Open as tab promotes the subagent to a full tab and ends the list", async () => {
await openSubagentFromCompactTrack(page, child.id);
await page.getByTestId(`subagents-track-row-${child.id}`).click();
await expectSheetAtSnap(page, child.title);
await openSheetAsTab(page, child.title);
await expect(page.getByTestId(`subagents-track-row-${child.id}`)).toHaveCount(0);
@@ -161,7 +123,7 @@ test("compact opens files and subagents in a sheet, leaving the tabs for agents"
await expect(page.getByTestId(`subagents-track-row-${child.id}`)).toHaveCount(0);
});
await test.step("once its tab closes, the subagent reopens in place of the list", async () => {
await test.step("once its tab closes, the subagent reopens in a sheet that keeps the list", async () => {
await page
.getByRole("button", { name: /Switch tabs/ })
.filter({ visible: true })
@@ -179,7 +141,7 @@ test("compact opens files and subagents in a sheet, leaving the tabs for agents"
await openSubagentFromCompactTrack(page, child.id);
await expectSheetAtSnap(page, child.title);
await backToList(page, child.title);
await closeSheet(page, child.title);
await expectSubagentRowVisible(page, child.id);
await tapSheetBackdrop(page);
await expect(page.getByRole("button", { name: "Bottom sheet backdrop" })).toHaveCount(0);
@@ -1,13 +1,3 @@
import {
withRetainedPlugin,
editRetainedDraft,
expectRetainedDraft,
expectStoredPluginTitle,
hideRetainedPreferences,
showRetainedPreferences,
expectChangedPlugin,
expectRemovedPlugin,
} from "../support/helpers/plugin-reconnect";
import { verifyPluginTranslations } from "../support/helpers/plugin-translations";
import { pluginRequirements } from "../support/helpers/plugin-fixture";
import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
@@ -198,51 +188,3 @@ test("plugin content and host labels follow app language without losing an open
test.setTimeout(180_000);
await verifyPluginTranslations(page, info);
});
test("retains plugin state offline and reconciles settings, changed code and removal", async ({
page,
}) => {
test.setTimeout(180_000);
await withRetainedPlugin(page, async (probe) => {
await probe.open();
await editRetainedDraft(page, "Connected draft", 0);
await test.step("local plugin UI remains mounted and usable while disconnected", async () => {
await probe.disconnect();
await expectRetainedDraft(page, "Connected draft", 1);
await editRetainedDraft(page, "Offline draft", 1);
await probe.changeStoredTitle("Saved by another client");
await expectStoredPluginTitle(page, "Agent monitor");
await probe.reconnect();
await expectStoredPluginTitle(page, "Saved by another client");
await expectRetainedDraft(page, "Offline draft", 2);
});
await test.step("inactive settings refresh without replacing the installation", async () => {
await hideRetainedPreferences(page);
await probe.disconnect();
await probe.changeStoredTitle("Saved while preferences hidden");
await probe.reconnect();
await showRetainedPreferences(page);
await expectStoredPluginTitle(page, "Saved while preferences hidden");
await expectRetainedDraft(page, "Offline draft", 2);
});
await test.step("changed code replaces the retained installation after reconnect", async () => {
await probe.disconnect();
await probe.changeCode();
await expectRetainedDraft(page, "Offline draft", 2);
await probe.reconnect();
await expectChangedPlugin(page);
await editRetainedDraft(page, "New code draft", 0);
});
await test.step("removal is reconciled after reconnect", async () => {
await probe.disconnect();
await probe.remove();
await expectRetainedDraft(page, "New code draft", 1);
await probe.reconnect();
await expectRemovedPlugin(page);
});
});
});
@@ -479,76 +479,3 @@ test.describe("Settings — compact master-detail", () => {
await expect(page.getByTestId("welcome-direct-connection")).toBeVisible();
});
});
async function measureDockedNavigation(page: import("@playwright/test").Page, width: number) {
await page.setViewportSize({ width, height: 951 });
const history = page.getByRole("button", { name: /^History/ }).filter({ visible: true });
const settings = page
.getByRole("button", { name: "Settings", exact: true })
.filter({ visible: true });
await expect(history).toBeVisible();
await expect(settings).toBeVisible();
return {
width,
history: await history.evaluate((el) => el.getBoundingClientRect().height),
settings: await settings.evaluate((el) => el.getBoundingClientRect().height),
};
}
async function measureSettingsSplit(page: import("@playwright/test").Page, width: number) {
await page.setViewportSize({ width, height: 951 });
const sidebar = page.getByTestId("settings-sidebar");
const detail = page.getByTestId("settings-detail-pane");
await expect(sidebar).toBeVisible();
await expect(detail).toBeVisible();
return {
width,
sidebar: await sidebar.evaluate((el) => el.getBoundingClientRect().width),
detail: await detail.evaluate((el) => el.getBoundingClientRect().width),
};
}
async function expectConsistentDockedNavigation(page: import("@playwright/test").Page) {
const wide = await measureDockedNavigation(page, 951);
for (const width of [600, 669, 719, 720]) {
const narrow = await measureDockedNavigation(page, width);
expect
.soft(narrow.history, `History keeps its wide-layout density at ${width}`)
.toBeCloseTo(wide.history, 0);
expect
.soft(narrow.settings, `Settings keeps its wide-layout density at ${width}`)
.toBeCloseTo(wide.settings, 0);
}
}
async function expectSettingsDetailKeepsReadingWidth(page: import("@playwright/test").Page) {
const reference = await measureSettingsSplit(page, 720);
for (const width of [600, 669, 719]) {
const narrow = await measureSettingsSplit(page, width);
expect
.soft(narrow.detail, `Settings preserves its detail budget at ${width}`)
.toBeGreaterThanOrEqual(reference.detail);
expect
.soft(narrow.sidebar, `Settings navigation yields width at ${width}`)
.toBeLessThan(reference.sidebar);
}
const wide = await measureSettingsSplit(page, 951);
expect(wide.sidebar).toBeCloseTo(reference.sidebar, 0);
expect(wide.detail).toBeGreaterThan(reference.detail);
}
test("docked navigation keeps its density and Settings preserves reading width", async ({
page,
withWorkspace,
}) => {
const workspace = await withWorkspace({ prefix: "narrow-wide-layout-" });
await gotoWorkspace(page, workspace.workspaceId);
await expectConsistentDockedNavigation(page);
await openSettings(page);
await openSettingsSection(page, "appearance");
await expectAppearanceContent(page);
await expectSettingsDetailKeepsReadingWidth(page);
await page.setViewportSize({ width: 599, height: 951 });
await expectSettingsSidebarHidden(page);
await expectAppearanceContent(page);
});
@@ -203,47 +203,6 @@ test("received messages show their sender and open that agent", async ({ page })
}
});
test("long sender attribution stays on one line in compact chat", async ({ page }, testInfo) => {
await page.setViewportSize({ width: 390, height: 844 });
await page.addInitScript(() =>
localStorage.setItem("@paseo:app-settings", JSON.stringify({ theme: "dark" })),
);
const recipient = await seedMockAgentWorkspace({
repoPrefix: "compact-attribution-",
title: "Implementation",
});
try {
const title = "Reviewer checking the compact chat timeline and sender attribution";
const sender = await recipient.client.createAgent({
provider: "codex",
cwd: recipient.cwd,
workspaceId: recipient.workspaceId,
title,
model: "gpt-6.1-sol",
modeId: "full-access",
});
await recipient.client.sendAgentMessage(
recipient.agentId,
"The sender label stays on one line, even when the agent has a long name.",
{ sourceAgentId: sender.id },
);
await openAgentRoute(page, recipient);
await expectComposerVisible(page);
const attribution = page.getByRole("button", { name: `Sent by ${title}`, exact: true });
await expect(attribution).toBeVisible();
await expectSenderTruncatedWithinMessage(attribution, title);
await expectSenderAlignedWithBubble(attribution);
await attribution.scrollIntoViewIfNeeded();
await page.screenshot({ path: testInfo.outputPath("sender-compact-390.png") });
await page.setViewportSize({ width: 320, height: 740 });
await expectSenderTruncatedWithinMessage(attribution, title);
await expectSenderAlignedWithBubble(attribution);
await page.screenshot({ path: testInfo.outputPath("sender-compact-320.png") });
} finally {
await recipient.cleanup();
}
});
interface MessagePreviewWatch {
/** Frames after the watch started on which the fade or "Show more" control was missing. */
framesWithoutClip: number[];
@@ -357,20 +316,6 @@ test("opening a turn keeps the received message above it clipped on every frame"
}
});
async function expectSenderTruncatedWithinMessage(attribution: Locator, title: string) {
const label = attribution.getByText(`Sent by ${title}`, { exact: true });
await expect(label).toHaveCSS("white-space", "nowrap");
await expect(label).toHaveCSS("text-overflow", "ellipsis");
const bounds = await label.evaluate((element) => ({
textWidth: element.scrollWidth,
visibleWidth: element.clientWidth,
right: element.getBoundingClientRect().right,
viewportWidth: document.documentElement.clientWidth,
}));
expect(bounds.textWidth).toBeGreaterThan(bounds.visibleWidth);
expect(bounds.right).toBeLessThanOrEqual(bounds.viewportWidth);
}
async function expectSenderAlignedWithBubble(attribution: Locator) {
const edges = await attribution.evaluate((button) => {
const bubble = button.nextElementSibling;
@@ -1,14 +0,0 @@
# Native user message preview
Open a chat with a user message containing 16 newline-separated lines of
`Preview line N`, with N from 1 to 16. Scroll the message into view on a
phone-sized Android emulator or iOS simulator. Its text must exceed the 240-point preview cap,
while its expanded bubble and toggle fit in the chat viewport. Close any other
expanded messages so the toggle labels identify this message.
Replay `native-user-message-preview.android.ad` or
`native-user-message-preview.ios.ad` through the existing mobile runner or
agent-device. It checks that a clipped message offers Show more and
that two expand/collapse round trips keep both controls reachable. Before the
fix, the first Show more assertion fails because native layout reports the
capped height as the full content height.
@@ -1,14 +0,0 @@
context platform=android timeout=60000 retries=0
env APP_ID=sh.paseo.debug
open "${APP_ID}"
wait "role=\"button\" label=\"Show more\"" 10000
press "role=\"button\" label=\"Show more\""
wait "role=\"button\" label=\"Show less\"" 10000
press "role=\"button\" label=\"Show less\""
wait "role=\"button\" label=\"Show more\"" 10000
press "role=\"button\" label=\"Show more\""
wait "role=\"button\" label=\"Show less\"" 10000
press "role=\"button\" label=\"Show less\""
wait "role=\"button\" label=\"Show more\"" 10000
close
@@ -1,14 +0,0 @@
context platform=ios timeout=60000 retries=0
env APP_ID=sh.paseo.debug
open "${APP_ID}"
wait "role=\"button\" label=\"Show more\"" 10000
press "role=\"button\" label=\"Show more\""
wait "role=\"button\" label=\"Show less\"" 10000
press "role=\"button\" label=\"Show less\""
wait "role=\"button\" label=\"Show more\"" 10000
press "role=\"button\" label=\"Show more\""
wait "role=\"button\" label=\"Show less\"" 10000
press "role=\"button\" label=\"Show less\""
wait "role=\"button\" label=\"Show more\"" 10000
close
@@ -12,22 +12,6 @@ point and Metro workflow in [status-ring](../status-ring/README.md), importing
`MarkdownFormattingRegression` from `./e2e/mobile/markdown-formatting/native`.
Open the same Metro URL in a browser to compare web. Restore `index.ts` afterward.
With this fixture open in an Android Agent Device session, run:
```sh
node packages/app/e2e/mobile/markdown-formatting/android.mjs <session>
```
The runner switches to paragraphs with long inline code at a fixed 300 dp width.
It compares the native Markdown host’s bottom with its last TextView’s bottom,
then repeats in compact mode and after restoring regular text. More than one
pixel of surplus fails. Keep the whole fixture visible: clipped accessibility
bounds cannot establish measurement parity.
`scripts/postinstall-patches.test.mjs` regenerates both platforms’ props and
compares them with the shipped headers. This catches missing C++ fields in the
measurement path, which the Kotlin tests cannot exercise.
The package patch contains `InlineCodeFormattingTest`, which exercises actual
Android spans in Robolectric native graphics mode, covering draw and measurement,
span order, code inside paragraph/heading sizes, bold/italic composition, and
@@ -1,60 +0,0 @@
import assert from "node:assert/strict";
import { execFileSync } from "node:child_process";
const session = process.argv[2];
assert(session, "Pass an Android agent-device session serving native.tsx");
function ad(...args) {
return execFileSync("agent-device", ["--session", session, ...args], {
encoding: "utf8",
timeout: 60_000,
});
}
function assertMeasurementParity(mode) {
const snapshot = JSON.parse(ad("snapshot", "--raw", "--json"));
assert.equal(snapshot.success, true);
const nodes = snapshot.data.nodes;
let last = nodes.find((node) => node.label?.endsWith("End of measurement fixture."));
assert(last?.rect, "The last paragraph must be visible, including its bottom");
// EnrichedMarkdownText exposes paragraph accessibility nodes inside its TextView;
// EnrichedMarkdown exposes the TextViews themselves. Measure the native child.
let host = nodes.find((node) => node.index === last.parentIndex);
if (host?.type === "android.widget.TextView") {
last = host;
host = nodes.find((node) => node.index === last.parentIndex);
}
assert.equal(host?.type, "android.widget.FrameLayout");
const viewport = nodes.find((node) => node.type === "android.widget.ScrollView");
const footer = nodes.find((node) => node.label === "End of Markdown host");
assert(viewport?.rect && footer?.rect, "The fixture and footer must be visible");
assert(
host.rect.y >= viewport.rect.y &&
footer.rect.y + footer.rect.height <= viewport.rect.y + viewport.rect.height,
"The whole fixture must fit in the viewport; clipped bounds cannot prove parity",
);
const hostBottom = host.rect.y + host.rect.height;
const childBottom = last.rect.y + last.rect.height;
console.log(
JSON.stringify({
mode,
host: host.rect,
lastChild: last.rect,
surplus: hostBottom - childBottom,
}),
);
assert(
Math.abs(hostBottom - childBottom) <= 1,
`Markdown reserves blank space in ${mode}: host bottom ${hostBottom}, last child bottom ${childBottom}`,
);
}
ad("press", 'label="Show wrapping fixture"');
ad("wait", "text", "End of Markdown host", "10000");
assertMeasurementParity("regular");
ad("press", 'label="Use compact text"');
ad("wait", "text", "Use regular text", "10000");
assertMeasurementParity("compact");
ad("press", 'label="Use regular text"');
ad("wait", "text", "Use compact text", "10000");
assertMeasurementParity("regular restored");
console.log("PASS Android Markdown host measurement matches its last child");
@@ -1,6 +1,6 @@
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { useCallback, useState } from "react";
import { Button, ScrollView, Text, View } from "react-native";
import { Button, ScrollView, Text } from "react-native";
import { StyleSheet } from "react-native-unistyles";
import { GestureHandlerRootView } from "react-native-gesture-handler";
import { MarkdownRenderer } from "@/components/markdown/renderer";
@@ -10,7 +10,6 @@ const styles = StyleSheet.create((theme) => ({
scroll: { backgroundColor: theme.colors.surface0 },
content: { padding: 32, paddingTop: 60 },
title: { color: theme.colors.foreground },
wrapping: { width: 300 },
}));
const queryClient = new QueryClient();
@@ -33,15 +32,7 @@ const source = [
"Normal **bold** and *italic* prose.",
].join("\n\n");
const wrappingSource = [
"Measurement parity. Take a repo with a gitignored `.env` in the main checkout and a `.worktreeinclude` containing `.env`.",
"Every creation path goes through `createPaseoWorktreeWorkflow` in `worktree-session.ts:341`, before `createAgent` in `creation/index.ts:160-174` starts.",
"The built-in plugin lives in `plugins/worktree-include/index.server.ts` and copies `paseo.json` beside `.worktreeinclude`. End of measurement fixture.",
].join("\n\n");
export default function MarkdownFormattingRegression() {
const [wrapping, setWrapping] = useState(false);
const toggleWrapping = useCallback(() => setWrapping((value) => !value), []);
const [compact, setCompact] = useState(false);
const toggleCompact = useCallback(() => setCompact((value) => !value), []);
return (
@@ -53,14 +44,7 @@ export default function MarkdownFormattingRegression() {
title={compact ? "Use regular text" : "Use compact text"}
onPress={toggleCompact}
/>
<Button
title={wrapping ? "Show formatting fixture" : "Show wrapping fixture"}
onPress={toggleWrapping}
/>
<View style={wrapping ? styles.wrapping : undefined}>
<MarkdownRenderer text={wrapping ? wrappingSource : source} compact={compact} />
</View>
<Text style={styles.title}>End of Markdown host</Text>
<MarkdownRenderer text={source} compact={compact} />
</ScrollView>
</GestureHandlerRootView>
</QueryClientProvider>
@@ -1,159 +0,0 @@
import { writeFile } from "node:fs/promises";
import path from "node:path";
import { settingsRpc } from "@getpaseo/plugin";
import type { DaemonClient } from "@getpaseo/client/internal/daemon-client";
import { z } from "zod";
import { expect, type Page } from "../fixtures";
import { gotoAppShell } from "./app";
import { installDaemonWebSocketGate } from "./daemon-websocket-gate";
import { connectDaemonClient } from "./daemon-client-loader";
import { copyPluginExample, pluginRequirements } from "./plugin-fixture";
const PLUGIN_ID = "retained-plugin-e2e";
export function retainedPluginSource(version: string) {
return `import { useState } from "react";
import { Text, View, TextInput, Pressable } from "react-native";
import { useSettings } from "@getpaseo/plugin/client";
import { preferences } from "./shared/preferences";
function Preferences({ color }) {
const settings = useSettings(preferences);
return <Text style={{ color }}>{settings.status === "ready" ? "Stored title: " + settings.values.title : "Preferences " + settings.status}</Text>;
}
function Surface({ theme }) {
const [draft, setDraft] = useState("");
const [clicks, setClicks] = useState(0);
const [showPreferences, setShowPreferences] = useState(true);
const color = theme.colors.foreground;
return <View>
<Text style={{ color }}>Plugin version ${version}</Text>
<TextInput accessibilityLabel="Plugin draft" value={draft} onChangeText={setDraft} style={{ color }} />
<Pressable accessibilityRole="button" onPress={() => setClicks(value => value + 1)}><Text style={{ color }}>{"Local clicks " + clicks}</Text></Pressable>
<Pressable accessibilityRole="button" onPress={() => setShowPreferences(value => !value)}><Text style={{ color }}>{showPreferences ? "Hide preferences" : "Show preferences"}</Text></Pressable>
{showPreferences ? <Preferences color={color} /> : null}
</View>;
}
export default function contribute(plugin) {
plugin.addSurface("main", Surface);
plugin.addSidebarItem({ id: "main", title: "Reconnect probe", icon: "PanelsTopLeft", surface: "main" });
return () => {};
}`;
}
export async function withRetainedPlugin(
page: Page,
run: (probe: Awaited<ReturnType<typeof createProbe>>) => Promise<void>,
) {
const probe = await createProbe(page);
try {
await run(probe);
} finally {
await probe.close();
}
}
async function createProbe(page: Page) {
const example = await copyPluginExample("settings");
const peer = await connectDaemonClient<DaemonClient>({ clientIdPrefix: "plugin-reconnect" });
const previous = await peer.getDaemonConfig();
const gate = await installDaemonWebSocketGate(page);
const clientEntry = path.join(example.directory, "index.client.tsx");
let catalogCount = 0;
try {
await writeFile(
path.join(example.directory, "paseo-plugin.json"),
JSON.stringify({ id: PLUGIN_ID, requirements: pluginRequirements }),
);
await writeFile(clientEntry, retainedPluginSource("one"));
await peer.patchDaemonConfig({ pluginsEnabled: true });
await peer.installDirectoryPlugin(example.directory);
} catch (error) {
await peer.close();
await example.cleanup();
throw error;
}
return {
async open() {
await page.setViewportSize({ width: 1100, height: 800 });
await gotoAppShell(page);
await page.getByRole("button", { name: "Reconnect probe", exact: true }).click();
await expect(page.getByText("Stored title: Agent monitor", { exact: true })).toBeVisible();
},
async disconnect() {
catalogCount = gate.getClientRequestCount("plugin.catalog.get.request");
await gate.drop();
await gate.waitForBlockedConnection();
},
async reconnect() {
gate.restore();
await gate.waitForServerMessage("plugin.catalog.get.response", catalogCount + 1);
},
async changeStoredTitle(title: string) {
const rpc = settingsRpc("display");
const current = rpc.read.output.parse(
await peer.invokePluginRpc(PLUGIN_ID, rpc.read.name, {}),
);
if (current.status !== "ready") throw new Error("Expected ready settings");
const values = z
.object({ groupBy: z.string(), showMetadata: z.boolean(), title: z.string() })
.parse(current.values);
const result = await peer.invokePluginRpc(PLUGIN_ID, rpc.write.name, {
revision: current.revision,
values: { ...values, title },
});
expect(result).toMatchObject({ status: "saved", values: { title } });
},
async changeCode() {
await writeFile(clientEntry, retainedPluginSource("two"));
await peer.reloadPlugin(PLUGIN_ID);
},
async remove() {
await peer.removePlugin(PLUGIN_ID);
},
async close() {
gate.restore();
await peer.removePlugin(PLUGIN_ID).catch(() => undefined);
await peer.patchDaemonConfig({ pluginsEnabled: previous.config.pluginsEnabled ?? false });
await peer.close();
await example.cleanup();
},
};
}
export async function editRetainedDraft(page: Page, draft: string, clicks: number) {
await page.getByRole("textbox", { name: "Plugin draft", exact: true }).fill(draft);
await page.getByRole("button", { name: `Local clicks ${clicks}`, exact: true }).click();
await expectRetainedDraft(page, draft, clicks + 1);
}
export async function expectRetainedDraft(page: Page, draft: string, clicks: number) {
await expect(page.getByRole("textbox", { name: "Plugin draft", exact: true })).toHaveValue(draft);
await expect(
page.getByRole("button", { name: `Local clicks ${clicks}`, exact: true }),
).toBeVisible();
}
export async function expectStoredPluginTitle(page: Page, title: string) {
await expect(page.getByText(`Stored title: ${title}`, { exact: true })).toBeVisible();
}
export async function hideRetainedPreferences(page: Page) {
await page.getByRole("button", { name: "Hide preferences", exact: true }).click();
await expect(page.getByText(/^Stored title:/)).toHaveCount(0);
}
export async function showRetainedPreferences(page: Page) {
await page.getByRole("button", { name: "Show preferences", exact: true }).click();
}
export async function expectChangedPlugin(page: Page) {
await expect(page.getByText("Plugin version two", { exact: true })).toBeVisible();
await expectRetainedDraft(page, "", 0);
}
export async function expectRemovedPlugin(page: Page) {
await expect(
page.getByText("This plugin surface is unavailable.", { exact: true }),
).toBeVisible();
await expect(page.getByRole("button", { name: "Reconnect probe", exact: true })).toHaveCount(0);
}
+1 -16
View File
@@ -5,7 +5,7 @@ export function sheet(page: Page, label: string): Locator {
return page.getByRole("dialog", { name: label });
}
/** A sheet tab's header, which carries its title, Back, Close, and the Open as tab glyph. */
/** A sheet tab's header, which carries its title, Close, and the Open as tab glyph. */
export function sheetHeader(page: Page, label: string): Locator {
return page.getByTestId("sheet-tab-header").filter({ hasText: label });
}
@@ -48,12 +48,6 @@ export async function closeSheet(page: Page, label: string): Promise<void> {
await expect(sheet(page, label)).toHaveCount(0);
}
/** Steps a sheet opened from a list back to that list, in the same sheet. */
export async function backToList(page: Page, label: string): Promise<void> {
await sheetHeader(page, label).getByRole("button", { name: "Back" }).click();
await expect(sheet(page, label)).toHaveCount(0);
}
export async function openSheetAsTab(page: Page, label: string): Promise<void> {
await sheetHeader(page, label).getByRole("button", { name: "Open as tab" }).click();
await expect(sheet(page, label)).toHaveCount(0);
@@ -82,15 +76,6 @@ export async function selectTabFromSwitcher(page: Page, label: string): Promise<
await expect(page.getByRole("button", { name: "Bottom sheet backdrop" })).toHaveCount(0);
}
/** Each open sheet renders its own backdrop, so counting them counts the sheets. */
export async function expectOneSheetOpen(page: Page): Promise<void> {
await expect(page.getByRole("button", { name: "Bottom sheet backdrop" })).toHaveCount(1);
}
export async function expectNoSheetOpen(page: Page): Promise<void> {
await expect(page.getByRole("button", { name: "Bottom sheet backdrop" })).toHaveCount(0);
}
/** Taps the top sheet's backdrop; each stacked sheet renders its own, top last. */
export async function tapSheetBackdrop(page: Page): Promise<void> {
await page
+5 -16
View File
@@ -3,7 +3,7 @@ import { startIsolatedHostDaemon } from "./isolated-host-daemon";
import { seedWorkspace } from "./seed-client";
import { getE2EDaemonPort } from "./daemon-port";
import { PARENT_AGENT_ID_LABEL } from "@getpaseo/protocol/agent-labels";
import { expect, type Locator, type Page } from "@playwright/test";
import { expect, type Page } from "@playwright/test";
import { daemonWsRoutePattern } from "./daemon-port";
import type { SeededWorkspace } from "./seed-client";
@@ -151,21 +151,10 @@ export async function openSubagentsTrack(page: Page): Promise<void> {
await expect(panel).toBeVisible({ timeout: 30_000 });
}
/**
* On compact the track opens as a sheet, and the chosen row opens in its place. `track` is the
* pane whose track to open, for when a subagent's sheet shows a track of its own.
*/
export async function openSubagentFromCompactTrack(
page: Page,
childId: string,
track: Page | Locator = page,
): Promise<void> {
await track.getByTestId("subagents-track-header").click();
const row = page.getByTestId(`subagents-track-row-${childId}`);
// Tap the row once the sheet has brought it on screen, as a finger would. Clicking it while it is
// still below the fold makes Playwright scroll the sheet host, and every sheet then docks short.
await expect(row).toBeInViewport();
await row.click();
/** On compact the track opens as a sheet, which closes once a row is chosen. */
export async function openSubagentFromCompactTrack(page: Page, childId: string): Promise<void> {
await page.getByTestId("subagents-track-header").click();
await page.getByTestId(`subagents-track-row-${childId}`).click();
}
export async function expectSubagentRowVisible(page: Page, childId: string): Promise<void> {
@@ -1,33 +0,0 @@
/**
* @vitest-environment jsdom
*/
import React from "react";
import { render, screen } from "@testing-library/react";
import { Text } from "react-native";
import { SafeAreaInsetsContext, useSafeAreaInsets } from "react-native-safe-area-context";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { SheetBottomInset } from "./adaptive-modal-sheet";
beforeEach(() => vi.stubGlobal("React", React));
const SCREEN_INSETS = { top: 24, right: 0, bottom: 34, left: 0 };
function BottomInsetProbe() {
return <Text testID="content-bottom-inset">{String(useSafeAreaInsets().bottom)}</Text>;
}
describe("SheetBottomInset", () => {
it("pads the bottom inset once and leaves none for its content", () => {
render(
<SafeAreaInsetsContext.Provider value={SCREEN_INSETS}>
<SheetBottomInset testID="sheet-body">
<BottomInsetProbe />
</SheetBottomInset>
</SafeAreaInsetsContext.Provider>,
);
expect(screen.getByTestId("sheet-body").style.paddingBottom).toBe("34px");
// Content that pads the inset itself, like the composer dock, must not pad it again.
expect(screen.getByTestId("content-bottom-inset").textContent).toBe("0");
});
});
@@ -3,7 +3,7 @@ import type { ComponentProps, ReactNode } from "react";
import { createPortal } from "react-dom";
import { useTranslation } from "react-i18next";
import { Keyboard, Pressable, Text, View } from "react-native";
import type { DimensionValue, StyleProp, ViewProps, ViewStyle } from "react-native";
import type { DimensionValue, StyleProp, ViewStyle } from "react-native";
import { StyleSheet, useUnistyles, withUnistyles } from "react-native-unistyles";
import { useIsCompactFormFactor } from "@/constants/layout";
import {
@@ -12,12 +12,7 @@ import {
useGlobalWebOverlayLayer,
useWebOverlayRegistration,
} from "../lib/overlay-root";
import {
BottomSheetHandle,
useBottomSheetGestureHandlers,
type BottomSheetBackgroundProps,
} from "@gorhom/bottom-sheet";
import { Gesture, GestureDetector } from "react-native-gesture-handler";
import { BottomSheetHandle, type BottomSheetBackgroundProps } from "@gorhom/bottom-sheet";
import Animated from "react-native-reanimated";
import { ArrowLeft, Search, X, type LucideIcon } from "lucide-react-native";
import {
@@ -30,7 +25,7 @@ import { getCompactSheetSafeAreaPadding } from "@/components/adaptive-modal-shee
import { ScrollView } from "@/components/ui/scroll-view";
import { isWeb } from "@/constants/platform";
import { useKeyboardVisibility } from "@/hooks/use-keyboard-visibility";
import { SafeAreaInsetsContext, useSafeAreaInsets } from "react-native-safe-area-context";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { AdaptiveTextInput } from "@/components/adaptive-text-input";
export { AdaptiveTextInput, type AdaptiveTextInputProps } from "@/components/adaptive-text-input";
@@ -45,9 +40,6 @@ export const SHEET_HORIZONTAL_PADDING_SCALE = 6;
// glyph should line up with the X must reach the same rail.
export const SHEET_HEADER_CLOSE_PADDING_SCALE = 2;
/** The one height a sheet takes when it shows a whole pane rather than sizing to its content. */
export const FULL_SHEET_SNAP_POINTS = ["92%"];
export interface SheetHeaderSearch {
onChange: (value: string) => void;
onFocus?: () => void;
@@ -252,55 +244,32 @@ const ThemedBottomSheetHandle = withUnistyles(BottomSheetHandle, (theme) => ({
indicatorStyle: { backgroundColor: theme.colors.palette.zinc[600] },
}));
/** The compact sheet's drag handle: Gorhom's `handleComponent` for every bottom sheet. */
const HANDLE_WITH_CONTENT_STYLE = { paddingHorizontal: 0, paddingBottom: 0 };
/**
* The compact sheet's drag handle: Gorhom's `handleComponent` for every bottom sheet. Children
* join the handle, so a header passed here drags the sheet like the indicator does. That is how a
* sheet whose content scrolls on its own keeps its header draggable without content panning.
*/
export function SheetHandle({
children,
// Gorhom passes `indicatorStyle={undefined}`, which would override the themed indicator.
indicatorStyle: _indicatorStyle,
...props
}: ComponentProps<typeof BottomSheetHandle>) {
return <ThemedBottomSheetHandle {...props} />;
}
/**
* Content that drags the sheet the way its handle does. A sheet whose body scrolls on its own
* turns content panning off and wraps its header in this, so the header still pulls it down.
* Render it inside the sheet's content.
*/
export function SheetDragArea({ children }: { children: ReactNode }) {
const { handlePanGestureHandler } = useBottomSheetGestureHandlers();
const gesture = useMemo(
() =>
Gesture.Pan()
.shouldCancelWhenOutside(false)
.runOnJS(false)
.onStart(handlePanGestureHandler.handleOnStart)
.onChange(handlePanGestureHandler.handleOnChange)
.onEnd(handlePanGestureHandler.handleOnEnd)
.onFinalize(handlePanGestureHandler.handleOnFinalize),
[handlePanGestureHandler],
);
if (!children) return <ThemedBottomSheetHandle {...props} />;
// The children carry their own semantics; the handle's slider role would swallow them on web.
return (
<GestureDetector gesture={gesture}>
<View>{children}</View>
</GestureDetector>
);
}
/**
* A compact sheet's content area that reaches the bottom of the screen. It owns the system
* navigation inset: it pads it once and tells its content none is left, so content that pads the
* inset itself, like the composer dock, sits the same in a sheet as in a tab.
*/
export function SheetBottomInset({ style, children, ...props }: ViewProps) {
const insets = useSafeAreaInsets();
const contentInsets = useMemo(() => ({ ...insets, bottom: 0 }), [insets]);
const insetStyle = useMemo(() => [style, { paddingBottom: insets.bottom }], [style, insets]);
return (
<View {...props} style={insetStyle}>
<SafeAreaInsetsContext.Provider value={contentInsets}>
{children}
</SafeAreaInsetsContext.Provider>
</View>
<ThemedBottomSheetHandle
{...props}
style={HANDLE_WITH_CONTENT_STYLE}
accessible={false}
accessibilityRole={null}
accessibilityLabel={null}
accessibilityHint={null}
>
{children}
</ThemedBottomSheetHandle>
);
}
@@ -519,76 +488,6 @@ export interface AdaptiveModalSheetProps {
contextBridge?: ContextBridge | null;
}
/**
* The compact sheet's body. It renders on the far side of the sheet's portal so it reads the
* screen's bottom inset, not the one left where the sheet was opened: inside a sheet tab, none is.
*/
function CompactSheetBody({
header,
onClose,
testID,
footer,
isKeyboardVisible,
scrollable,
bodyStyle,
contentStyle,
children,
}: {
header: SheetHeader;
onClose: () => void;
testID?: string;
footer: ReactNode;
isKeyboardVisible: boolean;
scrollable: boolean;
bodyStyle?: StyleProp<ViewStyle>;
contentStyle?: StyleProp<ViewStyle>;
children: ReactNode;
}) {
const insets = useSafeAreaInsets();
const { contentPaddingBottom = 0, footerPaddingBottom = 0 } = getCompactSheetSafeAreaPadding({
isCompact: true,
isKeyboardVisible,
hasFooter: Boolean(footer),
safeAreaBottom: insets.bottom,
});
// Safe-area clearance is a separate layer: it must not replace the caller's
// padding (including an explicit zero), and the footer owns it when present.
const bodyClearanceStyle = { paddingBottom: contentPaddingBottom };
const footerClearanceStyle = useMemo(
() => ({ paddingBottom: footerPaddingBottom }),
[footerPaddingBottom],
);
const footerView = useMemo(
() => (footer ? <View style={footerClearanceStyle}>{footer}</View> : null),
[footer, footerClearanceStyle],
);
return (
<SheetVisibleFrame footer={footerView}>
<SheetHeaderView header={header} onClose={onClose} testID={testID} />
<View style={[styles.compactStaticContent, bodyStyle]}>
{scrollable ? (
<ScrollView
style={styles.bottomSheetVisibleScroll}
contentContainerStyle={SCROLL_CONTENT_GROW}
keyboardShouldPersistTaps="handled"
showsVerticalScrollIndicator={false}
>
<View style={[styles.contentGrow, bodyClearanceStyle]}>
<SheetContent style={[styles.contentGrow, contentStyle]}>{children}</SheetContent>
</View>
</ScrollView>
) : (
<View style={[styles.compactStaticContent, bodyClearanceStyle]}>
<SheetContent style={[styles.compactStaticContent, contentStyle]}>
{children}
</SheetContent>
</View>
)}
</View>
</SheetVisibleFrame>
);
}
export function AdaptiveModalSheet({
header,
visible,
@@ -609,11 +508,34 @@ export function AdaptiveModalSheet({
}: AdaptiveModalSheetProps) {
const { t } = useTranslation();
const isMobile = useIsCompactFormFactor();
const insets = useSafeAreaInsets();
const isKeyboardVisible = useKeyboardVisibility(visible);
const resolvedSnapPoints = useMemo(() => snapPoints ?? ["65%", "90%"], [snapPoints]);
const compactSafeAreaPadding = useMemo(
() =>
getCompactSheetSafeAreaPadding({
isCompact: isMobile,
isKeyboardVisible,
hasFooter: Boolean(footer),
safeAreaBottom: insets.bottom,
}),
[footer, insets.bottom, isKeyboardVisible, isMobile],
);
// Safe-area clearance is a separate layer: it must not replace the caller's
// padding (including an explicit zero), and the footer owns it when present.
const bodyClearanceStyle = { paddingBottom: compactSafeAreaPadding.contentPaddingBottom ?? 0 };
const footerClearanceStyle = useMemo(
() => ({ paddingBottom: compactSafeAreaPadding.footerPaddingBottom ?? 0 }),
[compactSafeAreaPadding.footerPaddingBottom],
);
const footerView = useMemo(
() => (footer ? <View style={[styles.footer, footerContainerStyle]}>{footer}</View> : null),
[footer, footerContainerStyle],
() =>
footer ? (
<View style={footerClearanceStyle}>
<View style={[styles.footer, footerContainerStyle]}>{footer}</View>
</View>
) : null,
[footer, footerClearanceStyle, footerContainerStyle],
);
useEffect(() => {
if (!isWeb && visible) {
@@ -692,6 +614,32 @@ export function AdaptiveModalSheet({
}, [visible, isMobile, onDismiss, shouldRenderWeb]);
if (isMobile) {
const sheetContent = (
<>
<SheetHeaderView header={header} onClose={onClose} testID={testID} />
<View style={[styles.compactStaticContent, bodyStyle]}>
{scrollable ? (
<ScrollView
style={styles.bottomSheetVisibleScroll}
contentContainerStyle={SCROLL_CONTENT_GROW}
keyboardShouldPersistTaps="handled"
showsVerticalScrollIndicator={false}
>
<View style={[styles.contentGrow, bodyClearanceStyle]}>
<SheetContent style={[styles.contentGrow, contentStyle]}>{children}</SheetContent>
</View>
</ScrollView>
) : (
<View style={[styles.compactStaticContent, bodyClearanceStyle]}>
<SheetContent style={[styles.compactStaticContent, contentStyle]}>
{children}
</SheetContent>
</View>
)}
</View>
</>
);
return (
<IsolatedBottomSheetModal
ref={sheetRef}
@@ -710,18 +658,7 @@ export function AdaptiveModalSheet({
accessible={false}
presentation={presentation}
>
<CompactSheetBody
header={header}
onClose={onClose}
testID={testID}
footer={footerView}
isKeyboardVisible={isKeyboardVisible}
scrollable={scrollable}
bodyStyle={bodyStyle}
contentStyle={contentStyle}
>
{children}
</CompactSheetBody>
<SheetVisibleFrame footer={footerView}>{sheetContent}</SheetVisibleFrame>
</IsolatedBottomSheetModal>
);
}
@@ -72,7 +72,6 @@ vi.mock("react-i18next", () => ({
}));
vi.mock("react-native-safe-area-context", () => ({
SafeAreaProvider: ({ children }: { children?: React.ReactNode }) => children,
useSafeAreaInsets: () => ({ top: 0, right: 0, bottom: 0, left: 0 }),
}));
@@ -1,8 +1,8 @@
import { type ReactNode, useCallback, useEffect, useMemo, useState } from "react";
import { useCallback, useEffect, useMemo, useState } from "react";
import { Modal, Pressable, Text, View } from "react-native";
import { GestureHandlerRootView } from "react-native-gesture-handler";
import { StyleSheet } from "react-native-unistyles";
import { SafeAreaProvider, useSafeAreaInsets } from "react-native-safe-area-context";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { X } from "lucide-react-native";
import { useTranslation } from "react-i18next";
import type { AttachmentMetadata } from "@/attachments/types";
@@ -28,6 +28,7 @@ const LIGHTBOX_FIT = { padding: SPACING[4], maxWidth: 960, maxHeight: 640 };
export function AttachmentLightbox({ source, onClose }: AttachmentLightboxProps) {
const { t } = useTranslation();
const insets = useSafeAreaInsets();
const metadata = source?.type === "attachment" ? source.metadata : null;
const attachmentUrl = useAttachmentPreviewUrl(metadata);
const url = source?.type === "uri" ? source.uri : attachmentUrl;
@@ -55,6 +56,18 @@ export function AttachmentLightbox({ source, onClose }: AttachmentLightboxProps)
onKeyDown: handleWebOverlayKeyDown,
});
const contentLayerStyle = useMemo(
() => [
styles.contentLayer,
{
paddingTop: insets.top,
paddingRight: insets.right,
paddingBottom: insets.bottom,
paddingLeft: insets.left,
},
],
[insets.bottom, insets.left, insets.right, insets.top],
);
const actions = useMemo(
() => [
{
@@ -78,19 +91,17 @@ export function AttachmentLightbox({ source, onClose }: AttachmentLightboxProps)
return (
<Modal transparent animationType="fade" statusBarTranslucent visible onRequestClose={onClose}>
<ModalRoot style={styles.root}>
{/* The modal is its own window: its insets are the window's, not the ones left where the
image was opened (inside a sheet tab, the bottom one is already spent). */}
<SafeAreaProvider>
<WindowChromeRootRegion corners="both">
<View ref={setWebOverlayScope} style={styles.root}>
<Pressable
testID="attachment-lightbox-backdrop"
accessibilityRole="button"
accessibilityLabel={t("message.attachments.dismissImage")}
onPress={onClose}
style={styles.backdrop}
/>
<LightboxImageArea>
<WindowChromeRootRegion corners="both">
<View ref={setWebOverlayScope} style={styles.root}>
<Pressable
testID="attachment-lightbox-backdrop"
accessibilityRole="button"
accessibilityLabel={t("message.attachments.dismissImage")}
onPress={onClose}
style={styles.backdrop}
/>
<View pointerEvents="box-none" style={contentLayerStyle}>
<View pointerEvents="box-none" style={styles.imageArea}>
{hasError ? (
<Text style={styles.errorText}>{t("message.attachments.imageLoadFailed")}</Text>
) : (
@@ -106,38 +117,15 @@ export function AttachmentLightbox({ source, onClose }: AttachmentLightboxProps)
uri={url}
/>
)}
</LightboxImageArea>
</View>
</View>
</WindowChromeRootRegion>
</SafeAreaProvider>
</View>
</WindowChromeRootRegion>
</ModalRoot>
</Modal>
);
}
function LightboxImageArea({ children }: { children: ReactNode }) {
const insets = useSafeAreaInsets();
const style = useMemo(
() => [
styles.contentLayer,
{
paddingTop: insets.top,
paddingRight: insets.right,
paddingBottom: insets.bottom,
paddingLeft: insets.left,
},
],
[insets.bottom, insets.left, insets.right, insets.top],
);
return (
<View pointerEvents="box-none" style={style}>
<View pointerEvents="box-none" style={styles.imageArea}>
{children}
</View>
</View>
);
}
const styles = StyleSheet.create((theme) => ({
root: {
flex: 1,
+1 -7
View File
@@ -168,7 +168,6 @@ export function Button({
trailing,
style,
textStyle,
numberOfLines,
disabled,
loading = false,
accessibilityRole,
@@ -183,7 +182,6 @@ export function Button({
trailing?: ReactNode;
style?: StyleProp<ViewStyle>;
textStyle?: StyleProp<TextStyle>;
numberOfLines?: number;
loading?: boolean;
}
>) {
@@ -279,11 +277,7 @@ export function Button({
iconSize={buttonIconSize[size]}
uniProps={resolveIconMapping()}
/>
{children != null ? (
<Text numberOfLines={numberOfLines} style={resolvedTextStyle}>
{children}
</Text>
) : null}
{children != null ? <Text style={resolvedTextStyle}>{children}</Text> : null}
{trailing}
</Pressable>
);
+59 -64
View File
@@ -938,6 +938,7 @@ interface MobileBodyProps {
handleSelect: (id: string) => void;
renderOption: RenderOptionFn | undefined;
children: ReactNode;
safeAreaBottom: number;
}
function MobileComboboxBody(props: MobileBodyProps): ReactElement | null {
@@ -960,6 +961,21 @@ function MobileComboboxSheet(props: MobileBodyProps): ReactElement {
() => [styles.comboboxTitle, { color: props.titleColor }],
[props.titleColor],
);
const { footer, safeAreaBottom } = props;
const frameStyle = useMemo(
() => [styles.mobileSheetFrame, { paddingBottom: footer ? 0 : safeAreaBottom }],
[footer, safeAreaBottom],
);
const footerStyle = useMemo(
() => [styles.footer, { paddingBottom: safeAreaBottom }],
[safeAreaBottom],
);
const footerView = useMemo(
() => (footer ? <View style={footerStyle}>{footer}</View> : undefined),
[footer, footerStyle],
);
const body = props.hasChildren ? (
props.children
) : (
@@ -990,74 +1006,51 @@ function MobileComboboxSheet(props: MobileBodyProps): ReactElement {
keyboardBlurBehavior="none"
presentation={props.presentation}
>
<ComboboxSheetFrame footer={props.footer}>
{props.header ? (
<SheetHeaderView header={props.header} onClose={props.onClose} />
) : (
<>
<View style={styles.bottomSheetHeader}>
<Text key={props.titleColor} style={comboboxTitleStyle}>
{props.title}
</Text>
</View>
{props.stickyHeader}
{!props.hasChildren && props.searchable ? (
<SearchInput
placeholder={props.searchPlaceholder}
onChangeText={props.setSearchQueryWithCallback}
onSubmitEditing={props.handleSubmitSearch}
autoFocus={false}
useBottomSheetInput
resetKey={props.searchResetKey}
/>
) : null}
</>
)}
{props.hasChildren && !props.mobileChildrenScrollEnabled ? (
body
) : (
<BottomSheetScrollView
style={styles.mobileSheetBody}
contentContainerStyle={[
styles.comboboxScrollContent,
props.mobileChildrenContentContainerStyle,
]}
keyboardShouldPersistTaps="handled"
showsVerticalScrollIndicator={false}
>
{body}
</BottomSheetScrollView>
)}
</ComboboxSheetFrame>
<SheetVisibleFrame footer={footerView}>
<View style={frameStyle}>
{props.header ? (
<SheetHeaderView header={props.header} onClose={props.onClose} />
) : (
<>
<View style={styles.bottomSheetHeader}>
<Text key={props.titleColor} style={comboboxTitleStyle}>
{props.title}
</Text>
</View>
{props.stickyHeader}
{!props.hasChildren && props.searchable ? (
<SearchInput
placeholder={props.searchPlaceholder}
onChangeText={props.setSearchQueryWithCallback}
onSubmitEditing={props.handleSubmitSearch}
autoFocus={false}
useBottomSheetInput
resetKey={props.searchResetKey}
/>
) : null}
</>
)}
{props.hasChildren && !props.mobileChildrenScrollEnabled ? (
body
) : (
<BottomSheetScrollView
style={styles.mobileSheetBody}
contentContainerStyle={[
styles.comboboxScrollContent,
props.mobileChildrenContentContainerStyle,
]}
keyboardShouldPersistTaps="handled"
showsVerticalScrollIndicator={false}
>
{body}
</BottomSheetScrollView>
)}
</View>
</SheetVisibleFrame>
</IsolatedBottomSheetModal>
);
}
/**
* Rendered on the far side of the sheet's portal so it clears the screen's bottom inset, not the
* one left where the combobox was opened: inside a sheet tab, none is.
*/
function ComboboxSheetFrame({ footer, children }: { footer?: ReactNode; children: ReactNode }) {
const { bottom: safeAreaBottom } = useSafeAreaInsets();
const frameStyle = useMemo(
() => [styles.mobileSheetFrame, { paddingBottom: footer ? 0 : safeAreaBottom }],
[footer, safeAreaBottom],
);
const footerStyle = useMemo(
() => [styles.footer, { paddingBottom: safeAreaBottom }],
[safeAreaBottom],
);
const footerView = useMemo(
() => (footer ? <View style={footerStyle}>{footer}</View> : undefined),
[footer, footerStyle],
);
return (
<SheetVisibleFrame footer={footerView}>
<View style={frameStyle}>{children}</View>
</SheetVisibleFrame>
);
}
interface DesktopBodyProps {
overlayLayer: number;
isOpen: boolean;
@@ -1334,6 +1327,7 @@ export function Combobox({
const isMobile = useIsCompactFormFactor();
const active = useRetainedPanelActive();
const floatingLayer = useOverlayLayer("floating");
const safeAreaInsets = useSafeAreaInsets();
const titleColor = theme.colors.foreground;
const effectiveOptionsPosition = resolveEffectiveOptionsPosition(isMobile, optionsPosition);
const isDesktopAboveSearch = resolveIsDesktopAboveSearch(isMobile, effectiveOptionsPosition);
@@ -1614,6 +1608,7 @@ export function Combobox({
emptyText={resolvedEmptyText}
handleSelect={handleSelect}
renderOption={renderOption}
safeAreaBottom={safeAreaInsets.bottom}
>
{children}
</MobileComboboxBody>
@@ -123,25 +123,19 @@ export function useIsolatedBottomSheetVisibility({
visible,
isEnabled,
onClose,
onBack,
}: {
visible: boolean;
isEnabled?: boolean;
onClose: () => void;
/** Offered Android Back before it closes the sheet; returns true when it handled the press. */
onBack?: () => boolean;
}) {
const onCloseRef = useRef(onClose);
onCloseRef.current = onClose;
const onBackRef = useRef(onBack);
onBackRef.current = onBack;
const tracker = useMemo(
() =>
createBottomSheetVisibilityTracker({
onClose: () => onCloseRef.current(),
backPress: systemBackPress,
onBack: () => onBackRef.current?.() ?? false,
}),
[],
);
@@ -204,31 +204,6 @@ describe("bottom sheet visibility tracker", () => {
expect(context.sheet.events).toEqual([{ type: "present" }, { type: "dismiss" }]);
});
it("lets the sheet step back through its own pages before Back dismisses it", () => {
const sheet = new FakeBottomSheet();
const backPress = new FakeBackPress();
let openPages = 1;
const tracker = createBottomSheetVisibilityTracker({
onClose: () => {},
onBack: () => {
if (openPages === 0) return false;
openPages -= 1;
return true;
},
backPress,
});
tracker.attachController(sheet);
tracker.syncDesired({ visible: true });
tracker.handleSheetIndexChange(0);
expect(backPress.press()).toBe(true);
expect(openPages).toBe(0);
expect(sheet.events).toEqual([{ type: "present" }]);
expect(backPress.press()).toBe(true);
expect(sheet.events).toEqual([{ type: "present" }, { type: "dismiss" }]);
});
it("leaves Back to the navigator before the sheet is on screen and after it closes", () => {
const context = setup();
context.tracker.attachController(context.sheet);
@@ -36,11 +36,6 @@ type BottomSheetPhase = "closed" | "presenting" | "presented" | "dismissing";
export function createBottomSheetVisibilityTracker(opts: {
onClose: () => void;
backPress?: BackPressSource;
/**
* Offered the Back press before the sheet takes it as a close. Returns true when it handled
* the press itself, such as stepping back a page inside the sheet.
*/
onBack?: () => boolean;
}): BottomSheetVisibilityTracker {
let controller: BottomSheetController | null = null;
let visible = false;
@@ -65,7 +60,6 @@ export function createBottomSheetVisibilityTracker(opts: {
}
releaseBackPress =
opts.backPress?.subscribe(() => {
if (opts.onBack?.()) return true;
dismiss();
return true;
}) ?? null;
@@ -12,8 +12,6 @@ export { MenuRoot, MenuTrigger, type MenuTriggerProps, type MenuTriggerState } f
export {
MenuSurface,
useMenuSurface,
type MenuFillPageDefinition,
type MenuListPageDefinition,
type MenuPageDefinition,
type MenuSurfaceProps,
} from "./menu-surface";
@@ -61,38 +61,3 @@ describe("useMenuState selectItem elsewhere", () => {
expect(onSelect).toHaveBeenCalledTimes(1);
});
});
describe("useMenuState pages", () => {
it("pops the open page on Back and leaves Back at the root to the surface", () => {
const { result } = renderHook(() => useMenuState({ defaultOpen: true }));
act(() => result.current.openSub({ id: "row", depth: 0 }));
let handled = false;
act(() => {
handled = result.current.goBack();
});
expect(handled).toBe(true);
expect(result.current.path).toEqual([]);
act(() => {
handled = result.current.goBack();
});
expect(handled).toBe(false);
expect(result.current.open).toBe(true);
});
it("falls back to the list when the open page's definition goes away", () => {
const { result } = renderHook(() => useMenuState({ defaultOpen: true }));
act(() => result.current.openSub({ id: "row", depth: 0 }));
const keepNoPage = () => false;
act(() => result.current.prunePages(keepNoPage));
expect(result.current.path).toEqual([]);
let handled = true;
act(() => {
handled = result.current.goBack();
});
expect(handled).toBe(false);
});
});
@@ -7,7 +7,6 @@ import {
goBack as goBackPath,
MENU_ROOT_PATH,
openSubPage,
pruneMissingPages,
type MenuPath,
} from "./menu-navigation";
import type { Rect } from "../anchor";
@@ -41,10 +40,7 @@ export interface MenuContextValue {
path: MenuPath;
openSub: (sub: { id: string; depth: number }) => void;
closeSub: (depth: number) => void;
/** Pops the open page. False at the root, where Back is the surface's to answer. */
goBack: () => boolean;
/** Closes any open page that no longer has a definition, falling back to its parent. */
prunePages: (hasPage: (id: string) => boolean) => void;
goBack: () => void;
}
const MenuContext = createContext<MenuContextValue | null>(null);
@@ -164,13 +160,7 @@ export function useMenuState({
}, []);
const goBack = useCallback(() => {
if (path.length === 0) return false;
setPath((current) => goBackPath(current));
return true;
}, [path.length]);
const prunePages = useCallback((hasPage: (id: string) => boolean) => {
setPath((current) => pruneMissingPages(current, hasPage));
}, []);
return useMemo(
@@ -186,19 +176,7 @@ export function useMenuState({
openSub,
closeSub,
goBack,
prunePages,
}),
[
isOpen,
setOpen,
selectItem,
anchorRect,
presentation,
path,
openSub,
closeSub,
goBack,
prunePages,
],
[isOpen, setOpen, selectItem, anchorRect, presentation, path, openSub, closeSub, goBack],
);
}
@@ -6,7 +6,6 @@ import {
isSubPageOpen,
MENU_ROOT_PATH,
openSubPage,
pruneMissingPages,
} from "./menu-navigation";
describe("openSubPage", () => {
@@ -74,15 +73,3 @@ describe("isSubPageOpen", () => {
expect(isSubPageOpen(path, { id: "grouping", depth: 0 })).toBe(false);
});
});
describe("pruneMissingPages", () => {
it("falls back to the deepest page that still exists", () => {
expect(pruneMissingPages(["list", "row"], (id) => id === "list")).toEqual(["list"]);
expect(pruneMissingPages(["list", "row"], (id) => id === "row")).toEqual([]);
});
it("returns the same path when every page exists", () => {
const path = ["list", "row"];
expect(pruneMissingPages(path, () => true)).toBe(path);
});
});
@@ -33,16 +33,6 @@ export function closeSubPage(path: MenuPath, depth: number): MenuPath {
return path.slice(0, depth);
}
/**
* Cuts the path back to the deepest page that still has a definition. A page can lose its
* definition while it is open (a subagent's page goes with its row when the subagent is
* archived), and the pages it opened go with it.
*/
export function pruneMissingPages(path: MenuPath, hasPage: (id: string) => boolean): MenuPath {
const missing = path.findIndex((id) => !hasPage(id));
return missing === -1 ? path : path.slice(0, missing);
}
export function goBack(path: MenuPath): MenuPath {
if (path.length === 0) return path;
return path.slice(0, -1);
@@ -19,11 +19,6 @@ import {
useIsolatedBottomSheetVisibility,
type ContextBridge,
} from "@/components/ui/isolated-bottom-sheet-modal";
import {
FULL_SHEET_SNAP_POINTS,
SheetBackground,
SheetHandle,
} from "@/components/adaptive-modal-sheet";
import { SPACING, type Theme } from "@/styles/theme";
import { useRetainedPanelActive } from "@/components/retained-panel";
import { useMenuContext, MenuContextProvider } from "./menu-context";
@@ -37,6 +32,24 @@ import type { KeyboardFocusScope } from "@/keyboard/actions";
const ThemedChevronLeft = withUnistyles(ChevronLeft);
const mutedIconMapping = (theme: Theme) => ({ color: theme.colors.foregroundMuted });
// `backgroundStyle` and `handleIndicatorStyle` are style-shaped props the Babel plugin does not
// track, so the sheet is wrapped rather than reading the theme through a hook.
// See docs/unistyles.md.
const ThemedBottomSheetModal = withUnistyles(IsolatedBottomSheetModal, (theme) => ({
backgroundStyle: {
borderTopLeftRadius: theme.borderRadius.xl,
borderTopRightRadius: theme.borderRadius.xl,
borderWidth: 1,
backgroundColor: theme.colors.surface0,
borderColor: theme.colors.border,
},
handleIndicatorStyle: {
width: 36,
height: 4,
backgroundColor: theme.colors.surface2,
},
}));
/** How long the pointer must rest on a submenu row before its flyout opens. */
const HOVER_OPEN_DELAY_MS = 90;
/**
@@ -52,7 +65,7 @@ const HOVER_CLOSE_GRACE_MS = 260;
*/
const SUBMENU_OVERLAP = 5;
export interface MenuListPageDefinition {
export interface MenuPageDefinition {
id: string;
title: string;
content: ReactNode;
@@ -65,24 +78,6 @@ export interface MenuListPageDefinition {
* surface stops closing on hover, since its parent leads back to the same dismissal.
*/
hoverIntent?: boolean;
fill?: false;
}
/**
* A sheet page that takes the sheet's full height and draws everything itself, header included:
* no back header, no scroller, no content panning. Only the sheet presentation opens one; a
* popover never has a trigger for it.
*/
export interface MenuFillPageDefinition {
id: string;
fill: true;
content: ReactNode;
}
export type MenuPageDefinition = MenuListPageDefinition | MenuFillPageDefinition;
function pageHoverIntent(page: MenuPageDefinition | undefined): boolean {
return !page || page.fill === true || page.hoverIntent !== false;
}
interface MenuSurfaceContextValue {
@@ -131,15 +126,8 @@ export interface MenuSurfaceProps {
* popover (plus one flyout per open submenu) or a bottom sheet showing one page at a time.
*/
export function MenuSurface(props: MenuSurfaceProps): ReactElement | null {
const { presentation, open, setOpen, path, prunePages } = useMenuContext("MenuSurface");
const { presentation, open, setOpen } = useMenuContext("MenuSurface");
const active = useRetainedPanelActive();
// An open page whose definition went away (its row was removed) falls back to its parent, so
// neither a render nor a later Back walks a path to a page that no longer exists.
const { pages } = props;
useEffect(() => {
if (path.length === 0) return;
prunePages((id) => pages?.some((page) => page.id === id) ?? false);
}, [pages, path, prunePages]);
// A menu belongs to the panel that opened it. When that panel leaves the screen the menu closes
// for good, rather than waiting hidden to reappear with the panel: a row that opened a sheet
// and promoted it to a tab, say, would otherwise bring the list back on the next tab switch.
@@ -246,11 +234,11 @@ function MenuPopoverSurface({
// `hoverIntent: false` takes a page off the pointer entirely — it is not opened by resting on
// its trigger, and while it is open nothing on this surface closes on a pointer leaving it.
const hoverValue = useMemo<MenuSurfaceContextValue>(() => {
const locked = openPages.some(({ page }) => !pageHoverIntent(page));
const locked = openPages.some(({ page }) => page.hoverIntent === false);
return {
...surfaceValue,
hoverOpen: (sub) => {
if (!pageHoverIntent(pages.find((page) => page.id === sub.id))) return;
if (pages.find((page) => page.id === sub.id)?.hoverIntent === false) return;
surfaceValue.hoverOpen(sub);
},
hoverClose: (depth) => {
@@ -365,6 +353,17 @@ function MenuSheetSurface({
const { height: windowHeight } = useWindowDimensions();
const menu = useMenuContext("MenuSurface");
const { value: surfaceValue } = useSubAnchors();
const safeAreaInsets = useSafeAreaInsets();
const sheetScrollContentStyle = useMemo(
() => ({
paddingBottom: getMenuSheetBottomPadding({
safeAreaBottom: safeAreaInsets.bottom,
breathingRoom: SPACING[1],
}),
}),
[safeAreaInsets.bottom],
);
const sheetDataSet = useMemo(
() => (keyboardFocusScope ? { keyboardScope: keyboardFocusScope } : undefined),
[keyboardFocusScope],
@@ -375,15 +374,11 @@ function MenuSheetSurface({
visible: menu.open,
isEnabled: true,
onClose: handleClose,
// Android Back steps back through the pages before it closes the sheet.
onBack: menu.goBack,
});
const openPageId = currentPageId(menu.path);
const openPage = openPageId ? pages.find((page) => page.id === openPageId) : null;
const depth = menu.path.length;
const fillPage = openPage?.fill === true ? openPage : null;
const listPage = openPage?.fill === true ? null : openPage;
// The sheet's content is teleported out of this subtree, so both menu contexts have to be
// rebuilt on the other side. Providing them around the modal instead would put them on the
@@ -398,18 +393,12 @@ function MenuSheetSurface({
);
return (
<IsolatedBottomSheetModal
<ThemedBottomSheetModal
ref={sheetRef}
contextBridge={contextBridge}
backgroundComponent={SheetBackground}
handleComponent={SheetHandle}
// Content-sized rather than fixed snap points: a pushed page is rarely the same height
// as the page it replaced, and a fixed sheet would either clip it or leave dead space.
// A fill page is the exception: it takes the height every full sheet has, and its own
// content scrolls, so dragging it would fight that scroll.
enableDynamicSizing={!fillPage}
snapPoints={fillPage ? FULL_SHEET_SNAP_POINTS : undefined}
enableContentPanningGesture={!fillPage}
enableDynamicSizing
maxDynamicContentSize={windowHeight * 0.8}
onChange={handleSheetChange}
onDismiss={handleSheetDismiss}
@@ -423,64 +412,28 @@ function MenuSheetSurface({
keyboardBehavior="interactive"
keyboardBlurBehavior="restore"
>
{fillPage ? (
<View style={styles.fillPage} testID={testID ? `${testID}-${fillPage.id}` : undefined}>
{fillPage.content}
</View>
) : (
<MenuSheetScrollView dataSet={sheetDataSet} testID={testID}>
{listPage ? (
<>
<MenuSheetHeader title={listPage.title} onBack={menu.goBack} />
<MenuPage depth={depth}>{listPage.content}</MenuPage>
</>
) : (
<>
{sheetTitle ? (
<MenuSheetHeader title={sheetTitle} onBack={null} trailing={sheetTrailing} />
) : null}
<MenuPage depth={0}>{children}</MenuPage>
</>
)}
</MenuSheetScrollView>
)}
</IsolatedBottomSheetModal>
);
}
/**
* Rendered on the far side of the sheet's portal so it clears the screen's bottom inset, not the
* one left where the menu was opened: inside a sheet tab, none is.
*/
function MenuSheetScrollView({
dataSet,
testID,
children,
}: {
dataSet: { keyboardScope: KeyboardFocusScope } | undefined;
testID?: string;
children: ReactNode;
}) {
const safeAreaInsets = useSafeAreaInsets();
const contentStyle = useMemo(
() => ({
paddingBottom: getMenuSheetBottomPadding({
safeAreaBottom: safeAreaInsets.bottom,
breathingRoom: SPACING[1],
}),
}),
[safeAreaInsets.bottom],
);
return (
<BottomSheetScrollView
dataSet={dataSet}
contentContainerStyle={contentStyle}
keyboardShouldPersistTaps="handled"
showsVerticalScrollIndicator={false}
testID={testID ? `${testID}-content` : undefined}
>
{children}
</BottomSheetScrollView>
<BottomSheetScrollView
dataSet={sheetDataSet}
contentContainerStyle={sheetScrollContentStyle}
keyboardShouldPersistTaps="handled"
showsVerticalScrollIndicator={false}
testID={testID ? `${testID}-content` : undefined}
>
{openPage ? (
<>
<MenuSheetHeader title={openPage.title} onBack={menu.goBack} />
<MenuPage depth={depth}>{openPage.content}</MenuPage>
</>
) : (
<>
{sheetTitle ? (
<MenuSheetHeader title={sheetTitle} onBack={null} trailing={sheetTrailing} />
) : null}
<MenuPage depth={0}>{children}</MenuPage>
</>
)}
</BottomSheetScrollView>
</ThemedBottomSheetModal>
);
}
@@ -517,10 +470,6 @@ function MenuSheetHeader({
}
const styles = StyleSheet.create((theme) => ({
fillPage: {
flex: 1,
minHeight: 0,
},
sheetHeader: {
flexDirection: "row",
alignItems: "center",
@@ -1,5 +1,5 @@
import { useState, useCallback, useMemo, type ReactNode } from "react";
import { View, type LayoutChangeEvent, type ViewStyle } from "react-native";
import { View, type LayoutChangeEvent } from "react-native";
import { StyleSheet } from "react-native-unistyles";
import { useTranslation } from "react-i18next";
import type { AgentMessage } from "@getpaseo/protocol/agent-message";
@@ -8,29 +8,23 @@ import { EdgeFade } from "@/components/ui/edge-fade";
import { useProviderIcon } from "@/components/provider-icons";
import { useSessionStore } from "@/stores/session-store";
import { navigateToAgent } from "@/utils/navigate-to-agent";
import { isNative } from "@/constants/platform";
const PREVIEW_HEIGHT = 240;
// Native View still clips with "scroll", but Yoga measures its children without
// the height cap. "hidden" caps the measured body too, hiding the expand control.
const previewStyle: ViewStyle = {
maxHeight: PREVIEW_HEIGHT,
overflow: isNative ? "scroll" : "hidden",
};
export function MessagePreview({ children }: { children: ReactNode }) {
const { t } = useTranslation();
const [expanded, setExpanded] = useState(false);
const [overflowing, setOverflowing] = useState(false);
const [height, setHeight] = useState(0);
const overflowing = height > PREVIEW_HEIGHT;
const measure = useCallback(
(event: LayoutChangeEvent) => setOverflowing(event.nativeEvent.layout.height > PREVIEW_HEIGHT),
(event: LayoutChangeEvent) => setHeight(event.nativeEvent.layout.height),
[],
);
const toggle = useCallback(() => setExpanded((value) => !value), []);
const accessibilityState = useMemo(() => ({ expanded }), [expanded]);
return (
<>
<View style={!expanded && previewStyle}>
<View style={!expanded && styles.preview}>
<View style={styles.body} onLayout={measure}>
{children}
</View>
@@ -80,8 +74,6 @@ export function MessageSender({
size="sm"
leftIcon={renderProviderIcon}
style={styles.sender}
textStyle={styles.senderText}
numberOfLines={1}
disabled={!host}
onPress={openSender}
>
@@ -91,9 +83,9 @@ export function MessageSender({
}
const styles = StyleSheet.create((theme) => ({
preview: { maxHeight: PREVIEW_HEIGHT, overflow: "hidden" },
body: { flexShrink: 0 },
sender: { paddingRight: 0, borderRightWidth: 0, maxWidth: "100%" },
senderText: { flexShrink: 1 },
sender: { paddingRight: 0, borderRightWidth: 0 },
toggle: { alignSelf: "flex-start", paddingHorizontal: 0, minHeight: 0, borderWidth: 0 },
expandedToggle: { marginTop: theme.spacing[2] },
fade: { position: "absolute", bottom: 0, left: 0, right: 0, height: theme.spacing[12] },
@@ -41,7 +41,7 @@ import {
useWorkspaceAttachmentsStore,
} from "@/attachments/workspace-attachments-store";
import type { UserMessageImageAttachment } from "@/types/stream";
import { COMPACT_CONTENT_WIDTH, useIsCompactFormFactor } from "@/constants/layout";
import { COMPACT_FORM_FACTOR_WIDTH, useIsCompactFormFactor } from "@/constants/layout";
import { isWeb } from "@/constants/platform";
import {
buildWorkspaceTabPersistenceKey,
@@ -390,7 +390,7 @@ export function WorkspaceDraftAgentTab({
const editingSession = useComposerEditingSession("chat");
const isComposerFullscreen = useComposerFullscreen(editingSession);
const { onLayout: onInputAreaLayout, isBelow: isCompactComposerLayout } = useContainerWidthBelow(
COMPACT_CONTENT_WIDTH,
COMPACT_FORM_FACTOR_WIDTH,
{ initialIsBelow: isCompactFormFactor },
);
const workspaceAttachmentScopeKey = useWorkspaceAttachmentScopeKey({
+6 -22
View File
@@ -8,8 +8,6 @@ import {
MenuSurface,
MenuTrigger,
useMenuContext,
useMenuDepth,
type MenuPageDefinition,
type MenuTriggerState,
} from "@/components/ui/menu";
import { StatusRing } from "@/components/status-ring";
@@ -63,8 +61,6 @@ export interface ComposerTrackPillProps {
accessibilityLabel?: string;
/** Panel body. Rendered into a popover on wide screens and a sheet on compact ones. */
children: ReactNode;
/** Pages a row can open in place of the list (`ComposerTrackRow` `opensPage`). */
pages?: readonly MenuPageDefinition[];
}
/**
@@ -89,7 +85,6 @@ export function ComposerTrackPill({
testID,
accessibilityLabel,
children,
pages,
}: ComposerTrackPillProps): ReactElement {
return (
<MenuRoot compactMode="sheet">
@@ -103,7 +98,6 @@ export function ComposerTrackPill({
align="start"
offset={PANEL_OFFSET}
sheetTitle={panelTitle}
pages={pages}
minWidth={PANEL_MIN_WIDTH}
maxWidth={PANEL_MAX_WIDTH}
maxHeight={PANEL_MAX_HEIGHT}
@@ -205,11 +199,6 @@ export interface ComposerTrackRowProps {
* lands inside the panel is not.
*/
closeOnSelect?: boolean;
/**
* A page of the panel this row opens in place of the list, instead of running `onPress`. The
* panel stays open: Back returns to the list.
*/
opensPage?: string;
disabled?: boolean;
accessibilityLabel?: string;
testID?: string;
@@ -231,23 +220,18 @@ export function ComposerTrackRow({
children,
onPress,
closeOnSelect = true,
opensPage,
disabled = false,
accessibilityLabel,
testID,
}: ComposerTrackRowProps): ReactElement {
const { selectItem, openSub } = useMenuContext("ComposerTrackRow");
const depth = useMenuDepth();
const { selectItem } = useMenuContext("ComposerTrackRow");
const [hovered, setHovered] = useState(false);
const handlePointerEnter = useCallback(() => setHovered(true), []);
const handlePointerLeave = useCallback(() => setHovered(false), []);
const handleSelect = useCallback(() => {
if (opensPage) {
selectItem(() => openSub({ id: opensPage, depth }), false);
return;
}
selectItem(onPress, closeOnSelect);
}, [closeOnSelect, depth, onPress, openSub, opensPage, selectItem]);
const handleSelect = useCallback(
() => selectItem(onPress, closeOnSelect),
[closeOnSelect, onPress, selectItem],
);
const itemDataSet = useMemo(
() => ({ menuItem: "true", menuDisabled: disabled ? "true" : "false" }),
@@ -267,7 +251,7 @@ export function ComposerTrackRow({
[hovered, renderRow],
);
if (!onPress && !opensPage) {
if (!onPress) {
return <View accessibilityLabel={accessibilityLabel}>{renderRow(false)}</View>;
}
+4 -5
View File
@@ -11,11 +11,10 @@ export const HEADER_INNER_HEIGHT_MOBILE = 56;
export const WORKSPACE_SECONDARY_HEADER_HEIGHT = 36;
export const HEADER_TOP_PADDING_MOBILE = 8;
// Measured composer width; independent of the window's compact/wide breakpoint.
export const COMPACT_CONTENT_WIDTH = 500;
export const COMPACT_FORM_FACTOR_WIDTH = 500;
// Settings navigation can shrink below its preferred width to preserve the detail
// minimum. Both targets must fit before Settings shares width with app navigation.
// Settings uses the canonical desktop list + detail layout. Its sidebar and
// detail target must fit together before it can share width with app navigation.
export const SETTINGS_DESKTOP_SIDEBAR_WIDTH = 320;
export const SETTINGS_DESKTOP_DETAIL_MIN_WIDTH = 400;
export const SETTINGS_DESKTOP_SPLIT_MIN_WIDTH =
@@ -34,7 +33,7 @@ export {
getIsElectronMac as getIsElectronRuntimeMac,
} from "./platform";
/** Below md (600 points), sidebars overlay the workspace; wider layouts can dock them. */
/** Below 600 points, sidebars overlay the workspace. Medium and wider layouts dock them. */
export function isCompactBreakpoint(breakpoint: string | undefined): boolean {
return breakpoint === "xs" || breakpoint === "sm";
}
+1
View File
@@ -1914,6 +1914,7 @@ export const ar: TranslationResources = {
parent: {
backToParent: "العودة إلى الوكيل الأصلي",
backTo: "العودة إلى {{label}}",
parent: "الأصل",
parentAgent: "الوكيل الأصلي",
openParent: "فتح الوكيل الأصلي",
},
+1
View File
@@ -1939,6 +1939,7 @@ export const en = {
parent: {
backToParent: "Back to parent",
backTo: "Back to {{label}}",
parent: "Parent",
parentAgent: "Parent agent",
openParent: "Open parent",
},
+1
View File
@@ -1962,6 +1962,7 @@ export const es: TranslationResources = {
parent: {
backToParent: "Volver al padre",
backTo: "Volver a {{label}}",
parent: "Padre",
parentAgent: "Agente padre",
openParent: "Abrir padre",
},
+1
View File
@@ -1960,6 +1960,7 @@ export const fr: TranslationResources = {
parent: {
backToParent: "Retour au parent",
backTo: "Retour à {{label}}",
parent: "Parent",
parentAgent: "Agent parent",
openParent: "Ouvrir le parent",
},
+1
View File
@@ -1933,6 +1933,7 @@ export const ja: TranslationResources = {
parent: {
backToParent: "親に戻る",
backTo: "{{label}} に戻る",
parent: "親",
parentAgent: "親エージェント",
openParent: "親を開く",
},
+1
View File
@@ -1924,6 +1924,7 @@ export const ko: TranslationResources = {
parent: {
backToParent: "상위 에이전트로 돌아가기",
backTo: "{{label}}(으)로 돌아가기",
parent: "상위",
parentAgent: "상위 에이전트",
openParent: "상위 에이전트 열기",
},
+1
View File
@@ -1947,6 +1947,7 @@ export const ptBR: TranslationResources = {
parent: {
backToParent: "Voltar ao pai",
backTo: "Voltar para {{label}}",
parent: "Pai",
parentAgent: "Agente pai",
openParent: "Abrir pai",
},
+1
View File
@@ -1946,6 +1946,7 @@ export const ru: TranslationResources = {
parent: {
backToParent: "Назад к родителю",
backTo: "Назад к {{label}}",
parent: "Родитель",
parentAgent: "Родительский агент",
openParent: "Открыть родителя",
},
+1
View File
@@ -1892,6 +1892,7 @@ export const zhCN: TranslationResources = {
parent: {
backToParent: "返回父代理",
backTo: "返回 {{label}}",
parent: "父代理",
parentAgent: "父代理",
openParent: "打开父代理",
},
+2 -2
View File
@@ -44,7 +44,7 @@ import { useAgentDescriptor } from "@/agent-presentation";
import { useToastHost, type ToastApi, type ToastState } from "@/components/toast-host";
import type { WorkspaceComposerAttachment } from "@/attachments/types";
import { useWorkspaceAttachmentScopeKey } from "@/attachments/workspace-attachments-store";
import { COMPACT_CONTENT_WIDTH, useIsCompactFormFactor } from "@/constants/layout";
import { COMPACT_FORM_FACTOR_WIDTH, useIsCompactFormFactor } from "@/constants/layout";
import { isNative, isWeb } from "@/constants/platform";
import { useAgentAttentionClear } from "@/hooks/use-agent-attention-clear";
import { useAgentInputDraft, type AgentInputDraft } from "@/composer/draft/input-draft";
@@ -1512,7 +1512,7 @@ function ActiveAgentComposer({
}) {
const isCompactFormFactor = useIsCompactFormFactor();
const { onLayout: onInputAreaLayout, isBelow: isCompactComposerLayout } = useContainerWidthBelow(
COMPACT_CONTENT_WIDTH,
COMPACT_FORM_FACTOR_WIDTH,
{ initialIsBelow: isCompactFormFactor },
);
const paneContext = usePaneContext();
+3 -3
View File
@@ -13,7 +13,7 @@ import {
type ArchiveFinishedStatus,
useArchiveSubagent,
useDetachSubagent,
useSubagentSheetTab,
useSubagentOpensInSheet,
type SubagentRow,
} from "@/subagents";
import { ParentAgentPill } from "@/subagents/parent";
@@ -100,7 +100,7 @@ export const AgentTracks = memo(function AgentTracks({
},
[openSubagentTarget],
);
const sheetTabFor = useSubagentSheetTab(workspaceKey, tabId);
const opensInSheet = useSubagentOpensInSheet(workspaceKey);
const handleOpenChanges = useCallback(() => {
if (!workspaceKey) {
return;
@@ -134,7 +134,7 @@ export const AgentTracks = memo(function AgentTracks({
rows={subagentRows}
onOpenSubagent={handleOpenSubagent}
onOpenProviderSubagent={handleOpenProviderSubagent}
sheetTabFor={sheetTabFor}
opensInSheet={opensInSheet}
onArchiveSubagent={archiveSubagent}
onArchiveFinished={onArchiveFinished}
archiveFinishedStatus={archiveFinishedStatus}
@@ -16,10 +16,9 @@ import { usePaneContext } from "@/panels/pane-context";
import { PaneSubtitle } from "@/panels/pane-subtitle";
import { definePanel, type PanelDescriptor } from "@/panels/panel-registry";
import { useSessionStore } from "@/stores/session-store";
import type { SheetTab } from "@/stores/workspace-layout-store";
import { ParentAgentCallout } from "@/subagents/parent";
import { type SubagentRow, useSubagentsForParent } from "@/subagents/select";
import { useSubagentSheetTab } from "@/subagents/sheet-tab";
import { useSubagentOpensInSheet } from "@/subagents/opens-in-sheet";
import { SubagentsTrack } from "@/subagents/track";
import {
providerSubagentKey,
@@ -52,12 +51,12 @@ function ProviderSubagentChildTrack({
serverId,
rows,
onOpenProviderSubagent,
sheetTabFor,
opensInSheet,
}: {
serverId: string;
rows: ReturnType<typeof useSubagentsForParent>;
onOpenProviderSubagent: (parentAgentId: string, subagentId: string) => void;
sheetTabFor: (row: SubagentRow) => SheetTab | null;
opensInSheet: (row: SubagentRow) => boolean;
}) {
if (rows.length === 0) return null;
return (
@@ -67,7 +66,7 @@ function ProviderSubagentChildTrack({
rows={rows}
onOpenSubagent={NOOP_SUBAGENT}
onOpenProviderSubagent={onOpenProviderSubagent}
sheetTabFor={sheetTabFor}
opensInSheet={opensInSheet}
onArchiveSubagent={NOOP_SUBAGENT}
/>
</ComposerTrackBar>
@@ -117,7 +116,7 @@ function useProviderSubagentDescriptor(
function ProviderSubagentPanel() {
const { t } = useTranslation();
const { serverId, workspaceId, tabId, target, openFileInWorkspace, openTab } = usePaneContext();
const { serverId, workspaceId, target, openFileInWorkspace, openTab } = usePaneContext();
invariant(target.kind === "provider_subagent", "ProviderSubagentPanel requires provider target");
const key = providerSubagentKey(serverId, target.parentAgentId, target.subagentId);
const streamId = `provider:${encodeURIComponent(target.parentAgentId)}:${encodeURIComponent(target.subagentId)}`;
@@ -145,9 +144,8 @@ function ProviderSubagentPanel() {
providerParentSubagentId: target.subagentId,
});
const childTrackClearance = resolveChildTrackClearance(childRows.length, isCompact);
const sheetTabFor = useSubagentSheetTab(
const opensInSheet = useSubagentOpensInSheet(
buildWorkspaceTabPersistenceKey({ serverId, workspaceId }),
tabId,
);
const openProviderChild = useCallback(
(parentAgentId: string, subagentId: string) => {
@@ -276,7 +274,7 @@ function ProviderSubagentPanel() {
serverId={serverId}
rows={childRows}
onOpenProviderSubagent={openProviderChild}
sheetTabFor={sheetTabFor}
opensInSheet={opensInSheet}
/>
</View>
<ParentAgentCallout serverId={serverId} parentAgentId={target.parentAgentId} />
@@ -34,24 +34,11 @@ import {
import type { ContextBridge } from "@/components/ui/isolated-bottom-sheet-modal";
import { render as renderEnvironment } from "@testing-library/react";
import {
SheetPaneHostProvider,
useSheetPaneBridge,
type SheetPaneHost,
} from "@/screens/workspace/sheet-pane";
import { useWorkspaceSheetEnvironment } from "@/screens/workspace/workspace-sheet-environment";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { useAssistantFileLinkActions, type InlinePathTarget } from "@/assistant-file-links";
Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });
const SHEET_PANE_HOST: SheetPaneHost = {
workspaceKey: "host:workspace",
serverId: "host",
workspaceId: "workspace",
isWorkspaceFocused: true,
buildContent: () => {
throw new Error("The environment probe builds no pane content");
},
};
let root: Root;
let container: HTMLDivElement;
beforeEach(() => {
@@ -168,21 +155,14 @@ describe("workspace sheet environment", () => {
}, [name]);
return null;
}
function CaptureBridge() {
bridge = useSheetPaneBridge();
function Capture() {
bridge = useWorkspaceSheetEnvironment();
return (
<ComposerEditingScope tabId="file" targetKey="file:a">
<Probe name="pane" />
</ComposerEditingScope>
);
}
function Capture() {
return (
<SheetPaneHostProvider value={SHEET_PANE_HOST}>
<CaptureBridge />
</SheetPaneHostProvider>
);
}
function Source({ workspaceRoot, active }: { workspaceRoot: string; active: boolean }) {
const onOpenFile = useCallback(
(target: InlinePathTarget) => {
@@ -1,424 +0,0 @@
import appPackage from "../../package.json";
import { afterEach, expect, it } from "vitest";
import { QueryObserver } from "@tanstack/react-query";
import { DaemonClient } from "@getpaseo/client/internal/daemon-client";
import type { SessionOutboundMessage } from "@getpaseo/protocol/messages";
import { settingsRpc } from "@getpaseo/plugin";
import { syncPluginCatalog } from "./catalog-sync-model";
import { createPluginHosts } from "./hosts";
import { PluginRegistry } from "./registry";
import { pluginSettingsKey } from "./settings/query";
import type { InstalledPlugin } from "./types";
const audio = { play: async () => 0 };
const rpc = settingsRpc("preferences");
type Catalog = Awaited<ReturnType<DaemonClient["getPluginCatalog"]>>;
type Observation = ReturnType<DaemonClient["observeEvents"]>;
type Observer = Parameters<Observation["subscribe"]>[0];
class SettingsStore {
private revision = 1;
private values = { label: "original" };
reads = 0;
read() {
this.reads++;
return { status: "ready", revision: String(this.revision), values: this.values } as const;
}
write(input: unknown) {
const write = rpc.write.input.parse(input);
if (write.revision !== String(this.revision)) {
return { status: "conflict", error: "Settings changed" } as const;
}
const values = write.values;
if (typeof values !== "object" || values === null || !("label" in values)) {
throw new Error("Expected settings values");
}
if (typeof values.label !== "string") throw new Error("Expected label");
this.values = { label: values.label };
this.revision++;
return { status: "saved", revision: String(this.revision), values: this.values } as const;
}
}
/** In-memory daemon port; it delivers owned snapshots and stops updates on release. */
class CatalogClient extends DaemonClient {
catalog = catalog("one");
fetches = 0;
releases = 0;
events: Parameters<DaemonClient["observeEvents"]>[0] = [];
private readonly observers = new Set<Observer>();
constructor(readonly settings = new SettingsStore()) {
super({ url: "ws://unused.test", clientId: "catalog-sync-test" });
}
override async getPluginCatalog(): Promise<Catalog> {
this.fetches++;
return this.catalog;
}
override observeEvents(events: Parameters<DaemonClient["observeEvents"]>[0]): Observation {
this.events = events;
const snapshot = { requestId: "events", subscriptionId: "catalog" };
const subscribers = new Set<Observer>();
return {
subscriptionId: snapshot.subscriptionId,
ready: Promise.resolve(snapshot),
subscribe: (observer) => {
subscribers.add(observer);
this.observers.add(observer);
observer.snapshot(snapshot);
return () => {
subscribers.delete(observer);
this.observers.delete(observer);
};
},
release: async () => {
this.releases++;
for (const observer of subscribers) this.observers.delete(observer);
subscribers.clear();
},
};
}
override async invokePluginRpc(_pluginId: string, method: string, input: unknown) {
if (method === rpc.read.name) return this.settings.read();
if (method === rpc.write.name) return this.settings.write(input);
throw new Error(`Unexpected RPC: ${method}`);
}
update(message: SessionOutboundMessage) {
for (const observer of this.observers) observer.update(message);
}
snapshot() {
for (const observer of this.observers) {
observer.snapshot({ requestId: "reconnect", subscriptionId: "catalog" });
}
}
}
function catalog(marker: string): Catalog {
return [
{
id: "reports",
requirements: { paseo: `>=${appPackage.version}` },
clientBundle: `(function() { return { default: function(plugin) {
plugin.addTimelineTransformer({
id: "report", query: { itemType: "tool_call" },
transform() { return ${JSON.stringify(marker)} ? { items: [] } : undefined; }
});
return function() { plugin.openSettings("cleanup"); };
} }; })`,
},
];
}
const cleanups: Array<() => void> = [];
afterEach(() => {
for (const cleanup of cleanups.splice(0).toReversed()) cleanup();
});
function harness() {
let evaluations = 0;
let disposals = 0;
const registry = new PluginRegistry({
localeSource: { getLocale: () => "en", subscribe: () => () => {} },
version: appPackage.version,
createRuntime(installation) {
evaluations++;
return {
hosts: createPluginHosts(
{
getHosts: () => [],
getSnapshot: () => null,
subscribeAll: () => () => {},
subscribeHostList: () => () => {},
},
installation.lifetime.signal,
),
paseo: installation.paseo,
i18n: installation.i18n,
rpc: async () => {
throw new Error("Unexpected runtime RPC");
},
openSettings: () => {
disposals++;
},
openScreen() {},
openSurface() {},
async playAudio() {},
openPanel() {},
addComposerPill: () => ({ update() {}, remove() {} }),
addHeaderButton: () => ({ update() {}, remove() {} }),
};
},
});
const client = new CatalogClient();
cleanups.push(() => {
registry.removeHost("host");
registry.removeHost("other");
});
function sync(options: Partial<Parameters<typeof syncPluginCatalog>[0]> = {}) {
const stop = syncPluginCatalog({
serverId: "host",
client,
audio,
connected: true,
supported: true,
registry,
...options,
});
cleanups.push(stop);
return stop;
}
function installed(serverId = "host") {
const plugin = registry.getSnapshot().find((entry) => entry.serverId === serverId);
if (!plugin) throw new Error(`Missing installation: ${serverId}`);
return plugin;
}
return {
registry,
client,
sync,
installed,
evaluations: () => evaluations,
disposals: () => disposals,
};
}
async function connected() {
const h = harness();
const stop = h.sync();
await expect.poll(() => h.registry.getSnapshot().length).toBe(1);
return { ...h, stop };
}
function settingsQuery(plugin: InstalledPlugin) {
return {
queryKey: pluginSettingsKey("preferences"),
queryFn: async () => rpc.read.output.parse(await plugin.invoke(rpc.read.name, {})),
// The replica policy used by useSettings deliberately disables automatic refetches.
gcTime: Infinity,
staleTime: Infinity,
refetchOnMount: false,
refetchOnReconnect: false,
refetchOnWindowFocus: false,
retry: false,
} as const;
}
it("retains installations and timeline transforms while disconnected", async () => {
const h = await connected();
const plugin = h.installed();
const snapshot = h.registry.getSnapshot();
const transformers = plugin.timelineTransformers;
h.stop();
h.sync({ connected: false });
h.client.update({
type: "status",
payload: { status: "plugin_catalog_changed", pluginId: "reports" },
});
expect(h.registry.getSnapshot()).toBe(snapshot);
expect(h.installed().timelineTransformers).toBe(transformers);
expect(plugin.lifetime.signal.aborted).toBe(false);
expect(h.disposals()).toBe(0);
expect(h.client.fetches).toBe(1);
expect(h.client.events).toEqual([
"status.plugin_catalog_changed",
"status.plugin_settings_changed",
]);
});
it.each(["mounted", "unmounted"])(
"refreshes %s settings and revisions after another client saves offline",
async (surface) => {
const h = await connected();
const plugin = h.installed();
const snapshot = h.registry.getSnapshot();
const options = settingsQuery(plugin);
const original = await plugin.queryClient.fetchQuery(options);
const observer = new QueryObserver(plugin.queryClient, options);
const unsubscribe = observer.subscribe(() => {});
cleanups.push(unsubscribe);
if (surface === "unmounted") unsubscribe();
plugin.queryClient.setQueryData(["attachment-search"], "retained");
const otherClient = new CatalogClient();
h.registry.installCatalog("other", otherClient.catalog, { client: otherClient, audio });
const otherPlugin = h.installed("other");
await otherPlugin.queryClient.fetchQuery(settingsQuery(otherPlugin));
// Another host publishes new presentation snapshots without replacing the owning lifetime.
const beforeReconnect = h.registry.getSnapshot();
const retainedInstallation = h.installed();
h.stop();
h.sync({ connected: false });
const clientB = new CatalogClient(h.client.settings);
expect(
await clientB.invokePluginRpc("reports", rpc.write.name, {
revision: original.revision,
values: { label: "client B" },
}),
).toEqual({ status: "saved", revision: "2", values: { label: "client B" } });
expect(plugin.queryClient.getQueryData(options.queryKey)).toEqual(original);
h.sync();
await expect
.poll(() => plugin.queryClient.getQueryData(options.queryKey))
.toEqual({
status: "ready",
revision: "2",
values: { label: "client B" },
});
const refreshed = await plugin.queryClient.fetchQuery(options);
expect(
await plugin.invoke(rpc.write.name, {
revision: refreshed.revision,
values: { label: "client A" },
}),
).toEqual({ status: "saved", revision: "3", values: { label: "client A" } });
expect(h.registry.getSnapshot()).toBe(beforeReconnect);
expect(h.installed()).toBe(retainedInstallation);
expect(h.installed().lifetime).toBe(plugin.lifetime);
expect(h.installed().queryClient).toBe(plugin.queryClient);
expect(h.installed().timelineTransformers).toBe(snapshot[0].timelineTransformers);
expect(plugin.queryClient.getQueryData(["attachment-search"])).toBe("retained");
expect(otherClient.settings.reads).toBe(1);
expect(otherPlugin.queryClient.getQueryState(options.queryKey)?.isInvalidated).toBe(false);
expect(otherPlugin.queryClient.getQueryData(options.queryKey)).toEqual(original);
expect(h.evaluations()).toBe(2);
expect(h.disposals()).toBe(0);
},
);
it("replaces changed bundles on reconnect and disposes the old installation", async () => {
const h = await connected();
const plugin = h.installed();
plugin.queryClient.setQueryData(["attachment-search"], "old");
h.stop();
h.client.catalog = catalog("two");
h.sync();
await expect.poll(() => h.installed() === plugin).toBe(false);
expect(plugin.lifetime.signal.aborted).toBe(true);
expect(plugin.queryClient.getQueryCache().getAll()).toEqual([]);
expect(h.installed().timelineTransformers.map((entry) => entry.id)).toEqual(["report"]);
expect(h.evaluations()).toBe(2);
expect(h.disposals()).toBe(1);
});
it("replaces an explicitly reloaded bundle even when its source is unchanged", async () => {
const h = await connected();
const plugin = h.installed();
h.client.update({
type: "status",
payload: { status: "plugin_catalog_changed", pluginId: "reports" },
});
await expect.poll(() => h.installed() === plugin).toBe(false);
expect(h.disposals()).toBe(1);
expect(h.evaluations()).toBe(2);
});
it.each(["unsupported", "no audio"])("disposes plugins when %s", async (reason) => {
const h = await connected();
const plugin = h.installed();
h.stop();
h.sync({ supported: reason !== "unsupported", audio: reason === "no audio" ? null : audio });
expect(h.registry.getSnapshot()).toEqual([]);
expect(plugin.lifetime.signal.aborted).toBe(true);
expect(h.disposals()).toBe(1);
});
it("refreshes settings on a replayed subscription snapshot without reinstalling", async () => {
const h = await connected();
const plugin = h.installed();
const options = settingsQuery(plugin);
await plugin.queryClient.fetchQuery(options);
h.client.settings.write({ revision: "1", values: { label: "replayed" } });
h.client.snapshot();
await expect
.poll(() => plugin.queryClient.getQueryData(options.queryKey))
.toEqual({
status: "ready",
revision: "2",
values: { label: "replayed" },
});
expect(h.installed()).toBe(plugin);
expect(h.evaluations()).toBe(1);
});
it("invalidates only the named settings on its host for a live notification", async () => {
const h = await connected();
const plugin = h.installed();
const options = settingsQuery(plugin);
await plugin.queryClient.fetchQuery(options);
const observer = new QueryObserver(plugin.queryClient, options);
cleanups.push(observer.subscribe(() => {}));
plugin.queryClient.setQueryData(pluginSettingsKey("other-settings"), "unchanged");
const other = new CatalogClient();
h.registry.installCatalog("other", other.catalog, { client: other, audio });
await h.installed("other").queryClient.fetchQuery(settingsQuery(h.installed("other")));
const beforeNotification = h.registry.getSnapshot();
const retainedInstallation = h.installed();
h.client.settings.write({ revision: "1", values: { label: "live" } });
h.client.update({
type: "status",
payload: {
status: "plugin_settings_changed",
pluginId: "reports",
settingsId: "preferences",
},
});
await expect
.poll(() => plugin.queryClient.getQueryData(options.queryKey))
.toEqual({
status: "ready",
revision: "2",
values: { label: "live" },
});
expect(plugin.queryClient.getQueryState(pluginSettingsKey("other-settings"))?.isInvalidated).toBe(
false,
);
expect(other.settings.reads).toBe(1);
expect(h.registry.getSnapshot()).toBe(beforeNotification);
expect(h.installed()).toBe(retainedInstallation);
expect(h.installed().lifetime).toBe(plugin.lifetime);
expect(h.installed().queryClient).toBe(plugin.queryClient);
expect(h.evaluations()).toBe(2);
expect(h.client.fetches).toBe(1);
});
it("ignores an in-flight catalog snapshot after disconnect", async () => {
const h = await connected();
const plugin = h.installed();
await plugin.queryClient.fetchQuery(settingsQuery(plugin));
const snapshot = h.registry.getSnapshot();
h.stop();
let resolveCatalog: (value: Catalog) => void = () => {};
const pending = new Promise<Catalog>((resolve) => {
resolveCatalog = resolve;
});
let fetching: () => void = () => {};
const started = new Promise<void>((resolve) => {
fetching = resolve;
});
class PendingClient extends CatalogClient {
override getPluginCatalog() {
fetching();
return pending;
}
}
const stop = h.sync({ client: new PendingClient(h.client.settings) });
await started;
stop();
resolveCatalog(catalog("late"));
await pending;
// Drain the catalog continuation through a subsequently queued task.
await new Promise<void>((resolve) => setTimeout(resolve, 0));
expect(h.registry.getSnapshot()).toBe(snapshot);
expect(h.client.settings.reads).toBe(1);
expect(h.evaluations()).toBe(1);
});

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