Compare commits

..
Author SHA1 Message Date
Mohamed Boudra cbedec1ed6 fix(app): keep a panel's render error inside that panel
A render exception in any workspace panel, in the explorer or a split
pane, had no boundary between it and the root error boundary, so it
replaced the whole app with the root error screen. A workspace saved
with that panel selected took the app down again on every open.

The plugin surface boundary already contained errors for plugin
surfaces. Its error-catching core is now a shared RenderErrorBoundary,
and the panel host wraps every mounted panel in it. A failed panel
shows the error with a Retry button; the other panels, the chat, the
sidebar and workspace switching keep working. Plugin surfaces keep
their own "Plugin failed" state because their boundary sits inside the
panel and catches first.
2026-11-29 17:53:33 +01:00
91 changed files with 679 additions and 2099 deletions
+1 -1
View File
@@ -136,7 +136,7 @@ Cards inside a section sit closer than sections. Rows inside a card touch — on
Rows have generous vertical padding: roughly 16px of content plus 16px of vertical padding for settings rows, 8–12px for sidebar list items where many rows must fit. Every row is at least as tall as one holding a switch, so text rows, switch rows and rows that open something (`<SettingsDetailRow>`, a collapsible row's header) line up. A row holding a button or a select is taller. Compressing rows below the established density to fit more on the screen is wrong. Too many rows means more cards or more sections, not smaller rows.
Rows revealed under a `<SettingsCollapsibleRow>` are nested rows, one step smaller than card rows: 8px of vertical padding, `fontSize.sm` text, `sm` controls, and one fixed height so rows with and without a trailing button line up. The collapsible row sets this for everything under it (`packages/app/src/components/settings/row-density.tsx`). Never pass a density to a row, and never pad or resize a nested row by hand. Settings rows that share a menu surface with menu rows, such as Usage's options, go inside `<MenuSettingsRows>`, which puts their labels on the menu rows' label rail (`menuRowContentInset`). Settings rows that share a sheet with list rows, such as Agent settings with its radio choices and section headers, go inside `<ListSettingsRows>`, which makes every row one touch target tall so Model, switch and radio rows line up.
Rows revealed under a `<SettingsCollapsibleRow>` are nested rows, one step smaller than card rows: 8px of vertical padding, `fontSize.sm` text, `sm` controls, and one fixed height so rows with and without a trailing button line up. The collapsible row sets this for everything under it (`packages/app/src/components/settings/row-density.tsx`). Never pass a density to a row, and never pad or resize a nested row by hand. Settings rows that share a menu surface with menu rows, such as Usage's options, go inside `<MenuSettingsRows>`, which puts their labels on the menu rows' label rail (`menuRowContentInset`).
The whitespace is the design.
-2
View File
@@ -5,7 +5,6 @@ const withAndroidAsyncStorageSize = require("./plugins/with-android-async-storag
const withAndroidIgnoreBoldText = require("./plugins/with-android-ignore-bold-text");
const withAndroidOptionalCamera = require("./plugins/with-android-optional-camera");
const withAndroidProfileable = require("./plugins/with-android-profileable");
const withAndroidSplashWindowBackground = require("./plugins/with-android-splash-window-background");
const withFdroidAutolinking = require("./plugins/with-fdroid-autolinking");
const withPasteInput = require("./plugins/with-paste-input");
const withAndroidScroll = require("./modules/paseo-scroll/app.plugin");
@@ -166,7 +165,6 @@ export default {
},
},
],
withAndroidSplashWindowBackground,
...buildProfile.notificationPlugins,
"expo-audio",
[
-29
View File
@@ -26,29 +26,6 @@ async function resolveAndroidManifest() {
return exp._internal.modResults.android.manifest.manifest;
}
interface StyleItem {
$: { name: string };
_: string;
}
interface StyleGroup {
$: { name: string };
item?: StyleItem[];
}
async function resolveAndroidAppThemeItems(): Promise<Record<string, string>> {
const { exp } = await getPrebuildConfigAsync(__dirname, { platforms: ["android"] });
await compileModsAsync(exp, {
projectRoot: __dirname,
introspect: true,
platforms: ["android"],
assertMissingModProviders: false,
});
const styles: StyleGroup[] = exp._internal.modResults.android.styles.resources.style;
const appTheme = styles.find((style) => style.$.name === "AppTheme");
return Object.fromEntries((appTheme?.item ?? []).map((item) => [item.$.name, item._]));
}
describe("Android app config", () => {
afterEach(() => {
if (originalFdroidFlag === undefined) {
@@ -81,12 +58,6 @@ describe("Android app config", () => {
},
30_000,
);
// Without it, a dark device paints AppCompat's #303030 between the splash and the first screen.
it("paints the app window in the splash colour", async () => {
const appTheme = await resolveAndroidAppThemeItems();
expect(appTheme["android:windowBackground"]).toBe("@color/splashscreen_background");
}, 30_000);
});
it("follows system rotation on Android", async () => {
@@ -128,45 +128,6 @@ test.describe("Agent profiles in the model picker", () => {
}
});
test("the compact drawer keeps a running agent's Profiles collapsed and its rows one height", async ({
page,
}, testInfo) => {
const seed = await seedAgentProfiles([PROFILE]);
const workspace = await seedMockAgentWorkspace({
repoPrefix: "agent-profiles-compact-running-",
title: "Agent profiles compact running",
model: "ten-second-stream",
modeId: "load-test",
});
try {
await page.setViewportSize({ width: 390, height: 800 });
await openAgentRoute(page, workspace);
await expectComposerVisible(page);
await page.getByTestId("combined-model-selector").filter({ visible: true }).first().click();
await expect(page.getByTestId("agent-controls-profiles")).toBeVisible();
await expect(page.getByTestId("agent-controls-profiles-list")).toHaveCount(0);
// Settings rows (Model, switches) sit in the same list as the Profiles header and mode rows.
const sheet = page.getByTestId("agent-controls-settings-list");
const rows = [
sheet.getByTestId("agent-controls-profiles"),
sheet.getByTestId("agent-controls-model"),
sheet.locator('[data-testid^="mode-option-"]').first(),
];
const heights = [];
for (const row of rows) {
await expect(row).toBeVisible();
heights.push(Math.round((await row.boundingBox())!.height));
}
await page.screenshot({ path: testInfo.outputPath("compact-agent-settings.png") });
expect(new Set(heights).size, `row heights ${heights.join(", ")}`).toBe(1);
} finally {
await workspace.cleanup();
await seed.restore();
}
});
test("a model row and its create-profile action are separate buttons", async ({ page }) => {
const seed = await seedAgentProfiles([]);
const workspace = await seedMockAgentWorkspace({
@@ -317,16 +317,13 @@ test.describe("Cross-provider model search", () => {
await expectComposerFocused(page);
});
await test.step("the compact drawer opens a new agent's Profiles above Model on Home and keeps provider headers stable on collapse", async () => {
await test.step("the compact drawer surfaces collapsed Profiles above Model on Home and keeps provider headers stable on collapse", async () => {
await page.setViewportSize({ width: 390, height: 800 });
await page.getByTestId("combined-model-selector").filter({ visible: true }).first().click();
const profilesToggle = page.getByTestId("agent-controls-profiles");
const profilesList = page.getByTestId("agent-controls-profiles-list");
const modelRowButton = page.getByTestId("agent-controls-model");
await expect(profilesToggle).toBeVisible();
await expect(profilesList).toBeVisible();
await profilesToggle.click();
await expect(profilesList).toHaveCount(0);
await expect(page.getByTestId("agent-controls-profiles-list")).toHaveCount(0);
await waitForSettledPosition(profilesToggle);
const profilesBox = await profilesToggle.boundingBox();
const modelBox = await modelRowButton.boundingBox();
@@ -364,7 +361,6 @@ test.describe("Cross-provider model search", () => {
// Return Home, expand Profiles in place, and apply the profile.
await page.getByTestId("sheet-header-back").click();
await expect(profilesList).toHaveCount(0);
await profilesToggle.click();
const sheetProfileRow = page.getByTestId("model-profile-row-agent_profile_e2e_arrows");
await expect(sheetProfileRow).toBeVisible();
@@ -1,4 +1,3 @@
import { createServer, type Socket } from "node:net";
import { expect, test, type Page } from "../support/fixtures";
import { gotoAppShell } from "../support/helpers/app";
import { addScheduleHostAndReload, createScheduleHost } from "../support/helpers/schedule-host";
@@ -142,68 +141,6 @@ async function findScheduleIdByName(workspace: SeededWorkspace, name: string): P
return schedule.id;
}
async function createConnectingHost() {
const sockets = new Set<Socket>();
// Accept TCP without completing the WebSocket handshake, like a stalled host.
const server = createServer((socket) => {
sockets.add(socket);
socket.on("close", () => sockets.delete(socket));
});
await new Promise<void>((resolve, reject) => {
server.once("error", reject);
server.listen(0, "127.0.0.1", resolve);
});
const address = server.address();
if (!address || typeof address === "string") throw new Error("Expected a TCP address");
return {
port: address.port,
close: async () => {
for (const socket of sockets) socket.destroy();
await new Promise<void>((resolve, reject) => {
server.close((error) => {
if (error) {
reject(error);
return;
}
resolve();
});
});
},
};
}
async function openSchedulesWithConnectingHost(
page: Page,
cleanupTasks: Array<() => Promise<void>>,
): Promise<void> {
const workspace = await seedWorkspace({ repoPrefix: "schedule-partial-hosts-", git: false });
cleanupTasks.push(() => workspace.cleanup());
const stalledHost = await createConnectingHost();
cleanupTasks.push(() => stalledHost.close());
await gotoAppShell(page);
await waitForSidebarHydration(page);
await page.goto(buildSchedulesRoute());
await addScheduleHostAndReload({
page,
serverId: "stalled-schedule-host",
label: "Connecting host",
port: stalledHost.port,
});
}
async function expectPartialEmptySchedules(page: Page): Promise<void> {
await expect(page.getByText("No active schedules", { exact: true })).toBeVisible();
await expect(page.getByText("Connecting host: Still connecting", { exact: true })).toBeVisible();
await expect(page.getByRole("button", { name: "New schedule", exact: true })).toBeVisible();
}
async function expectScheduleCreationAvailable(page: Page): Promise<void> {
await openNewScheduleSheet(page);
await page.getByRole("button", { name: "Cancel", exact: true }).click();
await expect(page.getByTestId("schedule-form-sheet")).toHaveCount(0);
}
test.describe("Schedules project target", () => {
const cleanupTasks: Array<() => Promise<void>> = [];
@@ -214,12 +151,6 @@ test.describe("Schedules project target", () => {
cleanupTasks.length = 0;
});
test("shows empty schedules while another host is still connecting", async ({ page }) => {
await openSchedulesWithConnectingHost(page, cleanupTasks);
await expectPartialEmptySchedules(page);
await expectScheduleCreationAvailable(page);
});
test("dismisses the new schedule sheet without reopening", async ({ page }) => {
const workspace = await seedWorkspace({ repoPrefix: "schedule-sheet-dismiss-", git: false });
cleanupTasks.push(() => workspace.cleanup());
@@ -46,7 +46,7 @@ import { installDaemonWebSocketGate } from "../support/helpers/daemon-websocket-
import { addConnectedHostAndReload, addOfflineHostAndReload } from "../support/helpers/hosts";
import { startIsolatedHostDaemon } from "../support/helpers/isolated-host-daemon";
const LOADING_WORKSPACE_TEST_ID = "workspace-loading";
const LOADING_WORKSPACE_TEXT_PATTERN = /Loading workspace/i;
async function expectNoLoadingWorkspacePane(
page: Page,
input: { label: string; durationMs?: number },
@@ -63,7 +63,7 @@ async function expectNoLoadingWorkspacePane(
.catch((error) => `[body unavailable: ${error instanceof Error ? error.message : error}]`);
samples.push(`${Date.now() - startedAt}ms ${url}\n${text.slice(0, 1000)}`);
if ((await page.getByTestId(LOADING_WORKSPACE_TEST_ID).count()) > 0) {
if (LOADING_WORKSPACE_TEXT_PATTERN.test(text)) {
throw new Error(
`${input.label}: loading workspace pane appeared during reconnect window.\n\n${samples.join(
"\n\n---\n\n",
@@ -76,7 +76,7 @@ async function expectNoLoadingWorkspacePane(
}
async function expectNoLoadingPane(page: Page): Promise<void> {
await expect(page.getByTestId(LOADING_WORKSPACE_TEST_ID)).toHaveCount(0);
await expect(page.getByText(LOADING_WORKSPACE_TEXT_PATTERN)).toHaveCount(0);
}
async function getVisibleDraftTabCount(page: Page): Promise<number> {
@@ -1,61 +0,0 @@
#!/usr/bin/env bash
set -euo pipefail
# Open Pi settings from the Android model picker. Scroll the sheet body until
# most of the Models list is visible. Use a host with several Pi models and
# the default shown-models selection.
session="${1:?Pass the agent-device session with the Pi provider sheet open}"
artifacts="${2:-.artifacts/provider-model-scroll}"
mkdir -p "$artifacts"
ad() {
agent-device "$@" --session "$session"
}
visible_rows() {
jq -ce '
.data.nodes as $nodes
| ($nodes[] | select(.identifier == "provider-discovered-models")) as $list
| [$nodes[]
| select((.identifier // "") | startswith("provider-shown-model-"))
| select(.rect.height > 0 and .rect.y < ($list.rect.y + $list.rect.height))
| select(.rect.y + .rect.height > $list.rect.y)
| .label]
| select(length > 1)
' "$1"
}
ad snapshot --json > "$artifacts/before.json"
read -r x y dy < <(jq -er '
.data.nodes[]
| select(.identifier == "provider-discovered-models" and .rect.height >= 350)
| .rect
| [(.x + .width / 2 | floor), (.y + .height * 0.7 | floor), (-.height * 0.5 | floor)]
| @tsv
' "$artifacts/before.json") || {
printf 'Scroll the sheet body until the Models list is visible.\n' >&2
exit 1
}
before=$(visible_rows "$artifacts/before.json")
ad gesture pan "$x" "$y" 0 "$dy" 580
ad snapshot --json > "$artifacts/after.json"
after=$(visible_rows "$artifacts/after.json")
printf 'Before %s\nAfter %s\n' "$before" "$after"
first=$(jq -r '.[0]' <<<"$before")
if jq -e --arg first "$first" 'index($first) != null' <<<"$after" >/dev/null; then
printf 'The first model stayed visible after the upward drag.\n' >&2
exit 1
fi
model=$(jq -r '.[1]' <<<"$after")
ad press "role=checkbox label=\"$model\"" --settle
ad snapshot --json > "$artifacts/checked.json"
jq -e --arg model "$model" '
any(.data.nodes[]; .kind == "checkbox" and .label == $model and .checked == true)
' "$artifacts/checked.json" >/dev/null
ad press 'id="provider-shown-models-reset"' --settle
ad snapshot --json > "$artifacts/reset.json"
jq -e --arg model "$model" '
any(.data.nodes[]; .kind == "checkbox" and .label == $model and .checked == false)
' "$artifacts/reset.json" >/dev/null
@@ -173,11 +173,8 @@ export async function expectHostConnectingOrOffline(
page: Page,
options?: { timeout?: number },
): Promise<void> {
// A host that is still connecting shows the workspace loading state; one that failed says so.
await expect(
page
.getByTestId("workspace-loading")
.or(page.getByText(/localhost is offline|Cannot reach localhost/i)),
page.getByText(/^Connecting$|localhost is offline|Cannot reach localhost/i),
).toBeVisible({ timeout: options?.timeout ?? 30_000 });
}
-2
View File
@@ -1,8 +1,6 @@
// Install runtime polyfills before any other module evaluates. Keep this the first import.
// oxlint-disable-next-line import/no-unassigned-import -- Polyfills install on import.
import "./src/polyfills/install-early";
import { keepNativeSplash } from "./src/native-splash";
keepNativeSplash();
// Configure Unistyles before Expo Router pulls in any components using StyleSheet.
import "./src/styles/unistyles";
@@ -1,22 +0,0 @@
const { AndroidConfig, withAndroidStyles } = require("expo/config-plugins");
// The activity window shows under the splash while it fades out and until React
// paints. Expo's AppTheme sets no window background, so Android paints the
// AppCompat default (#303030 in dark mode, #fafafa in light mode) there.
// expo-splash-screen already defines `splashscreen_background` for day and night,
// so pointing the window at it keeps one colour from launch to the first screen.
const WINDOW_BACKGROUND = "@color/splashscreen_background";
function withAndroidSplashWindowBackground(config) {
return withAndroidStyles(config, (modConfig) => {
modConfig.modResults = AndroidConfig.Styles.assignStylesValue(modConfig.modResults, {
add: true,
parent: AndroidConfig.Styles.getAppThemeGroup(),
name: "android:windowBackground",
value: WINDOW_BACKGROUND,
});
return modConfig;
});
}
module.exports = withAndroidSplashWindowBackground;
@@ -43,8 +43,6 @@ export interface AgentProfilePickerRow {
export interface AgentProfilePicker {
rows: AgentProfilePickerRow[];
applyProfile: (profileId: string) => void;
/** What a picked profile configures: a running agent, or the draft of a new one. */
target: AgentProfileApplyTarget["kind"];
}
export interface UseAgentProfilePickerInput {
@@ -168,7 +166,7 @@ export function useAgentProfilePicker(
);
return useMemo(
() => (isSupported && profiles !== null ? { rows, applyProfile, target: target.kind } : null),
[applyProfile, isSupported, profiles, rows, target.kind],
() => (isSupported && profiles !== null ? { rows, applyProfile } : null),
[applyProfile, isSupported, profiles, rows],
);
}
@@ -26,10 +26,8 @@ import {
} from "@legendapp/list/react-native";
import { withUnistyles } from "react-native-unistyles";
import { LoadingSpinner } from "@/components/ui/loading-spinner";
import { LoadingState } from "@/components/ui/loading-state";
import { Button } from "@/components/ui/button";
import { useRetainedPanelActive } from "@/components/retained-panel";
import { useNativeSplashHold } from "@/native-splash";
import { useTranslation } from "react-i18next";
import type { StreamItem } from "@/types/stream";
import type { Theme } from "@/styles/theme";
@@ -763,9 +761,6 @@ function NativeStreamViewport(props: StreamRenderInput & { strategy: StreamStrat
);
}, [historyStartPaginationState, hasOlderHistory, retryHistoryStart, t]);
// The launch splash stays up until the visible conversation has placed its rows. A hidden first
// fill means the cache had no history, so it waits on the host and shows its own loading state.
useNativeSplashHold(isActive && !isListPlaced);
const canExpandDrawDistance =
drawDistance < NATIVE_STREAM_DRAW_DISTANCE &&
isActive &&
@@ -812,8 +807,8 @@ function NativeStreamViewport(props: StreamRenderInput & { strategy: StreamStrat
<InitialDrawDistanceExpansion schedule={drawDistanceExpansion.schedule} />
) : null}
{!historyStartPaginationState.visible ? (
<View pointerEvents="none" style={initialFillStyle}>
<LoadingState testID="agent-initial-fill" title={t("agentPanel.states.loadingHistory")} />
<View pointerEvents="none" testID="agent-initial-fill" style={initialFillStyle}>
<ThemedLoadingSpinner size="large" uniProps={foregroundMutedColorMapping} />
</View>
) : null}
</View>
@@ -19,7 +19,6 @@ import { flushSync } from "react-dom";
import { withUnistyles } from "react-native-unistyles";
import { useRetainedPanelActive } from "@/components/retained-panel";
import { LoadingSpinner } from "@/components/ui/loading-spinner";
import { LoadingState } from "@/components/ui/loading-state";
import { useStableEvent } from "@/hooks/use-stable-event";
import { useTranslation } from "react-i18next";
import { getStreamItemMessageId, type StreamItem } from "@/types/stream";
@@ -1720,8 +1719,8 @@ function WebStreamViewport(props: StreamRenderInput & { isMobileBreakpoint: bool
</div>
</div>
{!historyStartPaginationState.visible ? (
<div style={initialFillStyle}>
<LoadingState testID="agent-initial-fill" title={t("agentPanel.states.loadingHistory")} />
<div data-testid="agent-initial-fill" style={initialFillStyle}>
<ThemedLoadingSpinner size="large" uniProps={foregroundMutedColorMapping} />
</div>
) : null}
{scrollEnabled && !isMobileBreakpoint ? (
+26 -18
View File
@@ -1,5 +1,4 @@
import { useHardwareKeyboardPresent } from "@/keyboard";
import { LaunchScreen, useNativeSplashLaunchCommit } from "@/native-splash";
import {
WindowLayoutProvider,
WindowLayoutActionsHost,
@@ -83,6 +82,7 @@ import { VoiceProvider } from "@/contexts/voice-context";
import {
resolveStartupBlocker,
resolveStartupNavigationReady,
shouldRunStartupGiveUpTimer,
startHostRuntimeBootstrap,
bindHostRuntimeAppState,
type StartupBlocker,
@@ -156,7 +156,7 @@ polyfillCrypto();
export interface HostRuntimeBootstrapState {
splashError: string | null;
retry: () => void;
isWaitingForHost: boolean;
hasGivenUpWaitingForHost: boolean;
isWaitingForSetup: boolean;
storeReady: boolean;
startupBlocker: StartupBlocker;
@@ -165,7 +165,7 @@ export interface HostRuntimeBootstrapState {
const HostRuntimeBootstrapContext = createContext<HostRuntimeBootstrapState>({
splashError: null,
retry: () => {},
isWaitingForHost: true,
hasGivenUpWaitingForHost: false,
isWaitingForSetup: false,
storeReady: false,
startupBlocker: { kind: "none" },
@@ -262,6 +262,7 @@ function useDaemonStartIsRunning(): boolean {
);
}
const STARTUP_GIVE_UP_TIMEOUT_MS = 5_000;
// How long the splash waits on top of host startup to learn whether setup opens. A slow host
// lands on the home instead, and setup opens over it once it is decided.
const STARTUP_SETUP_WAIT_TIMEOUT_MS = 3_000;
@@ -283,29 +284,20 @@ function HostRuntimeBootstrapProvider({ children }: { children: ReactNode }) {
return bindHostRuntimeAppState(store, AppState);
}, []);
const [isWaitingForHost, setIsWaitingForHost] = useState(true);
useEffect(() => {
let isMounted = true;
const store = getHostRuntimeStore();
const daemonStartService = getDaemonStartService({ store });
void startHostRuntimeBootstrap({
startHostRuntimeBootstrap({
store,
daemonStartService,
shouldStartDaemon: shouldStartBuiltInDaemon,
}).then(() => {
if (isMounted) {
setIsWaitingForHost(false);
}
return;
});
return () => {
isMounted = false;
};
}, []);
const anyOnlineHostServerId = useEarliestOnlineHostServerId();
const daemonStartError = useDaemonStartLastError();
const daemonStartIsRunning = useDaemonStartIsRunning();
const [hasGivenUpWaitingForHost, setHasGivenUpWaitingForHost] = useState(false);
const isDesktopRuntime = shouldUseDesktopDaemon();
const startupBlocker = useMemo(
() =>
@@ -317,6 +309,24 @@ function HostRuntimeBootstrapProvider({ children }: { children: ReactNode }) {
}),
[anyOnlineHostServerId, daemonStartError, daemonStartIsRunning, isDesktopRuntime],
);
const shouldRunGiveUpTimer = shouldRunStartupGiveUpTimer({
startupBlocker,
anyOnlineHostServerId,
hasGivenUpWaitingForHost,
});
useEffect(() => {
if (!shouldRunGiveUpTimer) {
return;
}
const handle = setTimeout(() => {
setHasGivenUpWaitingForHost(true);
}, STARTUP_GIVE_UP_TIMEOUT_MS);
return () => {
clearTimeout(handle);
};
}, [shouldRunGiveUpTimer]);
const isSetupDecisionPending = useIsSetupDecisionPending();
const [hasGivenUpWaitingForSetup, setHasGivenUpWaitingForSetup] = useState(false);
const isWaitingForSetup = isSetupDecisionPending && !hasGivenUpWaitingForSetup;
@@ -347,12 +357,12 @@ function HostRuntimeBootstrapProvider({ children }: { children: ReactNode }) {
() => ({
splashError,
retry,
isWaitingForHost,
hasGivenUpWaitingForHost,
isWaitingForSetup,
storeReady,
startupBlocker,
}),
[splashError, retry, isWaitingForHost, isWaitingForSetup, storeReady, startupBlocker],
[splashError, retry, hasGivenUpWaitingForHost, isWaitingForSetup, storeReady, startupBlocker],
);
return (
@@ -905,7 +915,6 @@ const ROOT_STACK_SCREEN_OWNED_APPEARANCE = ["settings/[section]"] as const;
function RootStack() {
const storeReady = useStoreReady();
useNativeSplashLaunchCommit();
return (
<ThemedStack
screenOptions={ROOT_STACK_SCREEN_OPTIONS}
@@ -1034,7 +1043,6 @@ function RootAppTree() {
</AddHostProvider>
</LucideProvider>
</View>
<LaunchScreen />
</GestureHandlerRootView>
);
}
+10 -14
View File
@@ -24,20 +24,16 @@ export default function HostIndexRoute() {
return <StartupSplashScreen />;
}
// The loading screen stays up until the target route paints; a redirect alone renders nothing.
return (
<>
<StartupSplashScreen />
<Redirect
href={resolveHostIndexRoute({
serverId,
workspaceSelection,
workspaceSelectionStatus: resolveWorkspaceSelectionStatus({
hasHydratedWorkspaces,
workspaceExists: workspaceSelectionExists,
}),
})}
/>
</>
<Redirect
href={resolveHostIndexRoute({
serverId,
workspaceSelection,
workspaceSelectionStatus: resolveWorkspaceSelectionStatus({
hasHydratedWorkspaces,
workspaceExists: workspaceSelectionExists,
}),
})}
/>
);
}
+1 -1
View File
@@ -44,7 +44,7 @@ export default function Index() {
workspaceExists: workspaceSelectionExists,
}),
isWorkspaceSelectionLoaded,
isWaitingForHost: bootstrapState.isWaitingForHost,
hasGivenUpWaitingForHost: bootstrapState.hasGivenUpWaitingForHost,
isWaitingForSetup: bootstrapState.isWaitingForSetup,
});
@@ -308,24 +308,6 @@ describe("parseAssistantFileLink", () => {
});
});
it.each(["C:/repo", "\\\\host\\share\\repo"])(
"leaves Windows variable paths in inline code unlinked in %s",
(workspaceRoot) => {
expect(classifyAssistantFileLink("%TEMP%\\debug.md", { workspaceRoot })).toBeNull();
expect(classifyAssistantFileLink("%LOCALAPPDATA%/debug.md:3", { workspaceRoot })).toBeNull();
expect(classifyAssistantFileLink("C:\\Temp\\debug.md", { workspaceRoot })?.kind).toBe(
"directFile",
);
},
);
it("allows a literal percent-delimited directory in an authored file link", () => {
expect(
parseAssistantFileLink("%TEMP%/notes.md", { workspaceRoot: "C:/repo", explicitLink: true })
?.path,
).toBe("C:/repo/%TEMP%/notes.md");
});
it("parses absolute Windows hrefs inside the active workspace", () => {
expect(
parseAssistantFileLink("C:/repo/src/app.tsx#L12-L20", {
@@ -393,14 +393,6 @@ function parseWorkspaceRelativeFileLink(
value: string,
options: AssistantHrefParseOptions,
): InlinePathTarget | null {
// cmd.exe variables are shell expressions. The file opener only resolves literal paths.
if (
!options.explicitLink &&
/^(?:[A-Za-z]:[\\/]|[\\/]{2})/.test(options.workspaceRoot ?? "") &&
/^%[^%\\/]+%[\\/]/.test(value)
) {
return null;
}
const parsed = parseLocalPathParts(value, options);
if (!parsed || isAbsolutePath(parsed.path)) {
return null;
@@ -1,13 +1,10 @@
import React, { act, useCallback, useState } from "react";
import React, { act } from "react";
import { createRoot, type Root } from "react-dom/client";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { persistAttachmentFromBlob } from "@/attachments/service";
import { SafeAreaProvider } from "react-native-safe-area-context";
import { i18n } from "@/i18n/i18next";
import { WindowLayoutProvider } from "@/window-layout";
import { RetainedPanelActivity } from "@/components/retained-panel";
import { RetainedChatContent as NativeChatContent } from "@/panels/retained-chat-content.native";
import { RetainedChatContent as WebChatContent } from "@/panels/retained-chat-content.web";
import { AttachmentLightbox, type ImageLightboxSource } from "./attachment-lightbox";
interface FrameSample {
@@ -150,48 +147,3 @@ describe("AttachmentLightbox opening in the browser", () => {
await expectOpeningPaintsOnlyTheFittedImage({ type: "uri", uri });
});
});
let openImage: (() => void) | null = null;
function ThreadWithImage({ uri }: { uri: string }) {
const [source, setSource] = useState<ImageLightboxSource | null>(null);
openImage = () => setSource({ type: "uri", uri });
const close = useCallback(() => setSource(null), []);
return <AttachmentLightbox source={source} onClose={close} />;
}
function isLightboxShown(): boolean {
return document.querySelector('[data-testid="attachment-lightbox-backdrop"]') !== null;
}
describe("AttachmentLightbox when its chat leaves the screen", () => {
for (const [platform, ChatContent] of [
["web", WebChatContent],
["native", NativeChatContent],
] as const) {
it(`closes on ${platform} when another session takes over, and stays closed on return`, async () => {
const uri = URL.createObjectURL(await createPng(400, 300));
const showThread = (active: boolean) =>
root.render(
<SafeAreaProvider>
<WindowLayoutProvider>
<RetainedPanelActivity active={active}>
<ChatContent>
<ThreadWithImage uri={uri} />
</ChatContent>
</RetainedPanelActivity>
</WindowLayoutProvider>
</SafeAreaProvider>,
);
await act(async () => showThread(true));
await act(async () => openImage?.());
expect(isLightboxShown()).toBe(true);
await act(async () => showThread(false));
expect(isLightboxShown()).toBe(false);
await act(async () => showThread(true));
expect(isLightboxShown()).toBe(false);
});
}
});
@@ -13,7 +13,6 @@ import {
useAttachmentPreviewUrl,
} from "@/attachments/use-attachment-preview-url";
import { isNative } from "@/constants/platform";
import { useRetainedPanelActive } from "@/components/retained-panel";
import { SPACING } from "@/styles/theme";
import { WindowChromeRootRegion } from "@/utils/desktop-window";
import { ZoomableImage } from "@/components/zoomable-viewport/image";
@@ -43,21 +42,12 @@ export function AttachmentLightbox({ source, onClose }: AttachmentLightboxProps)
const contentSize = source?.type === "uri" ? source.contentSize : undefined;
const [errored, setErrored] = useState(false);
const failed = errored || image.status === "failed";
const panelActive = useRetainedPanelActive();
const open = source !== null && panelActive;
const modalLayer = useGlobalOverlayLayer("modal", open);
const modalLayer = useGlobalOverlayLayer("modal", source !== null);
useEffect(() => {
setErrored(false);
}, [metadata?.id, url]);
// The image belongs to the panel that opened it and closes for good when that panel leaves the
// screen. On web the Modal portals out of the hidden panel, and the hidden chat is frozen on the
// next commit, so the lightbox must also unmount in this inactive commit (see MenuSurface).
useEffect(() => {
if (source !== null && !panelActive) onClose();
}, [onClose, panelActive, source]);
const handleOverlayKeyDown = useCallback(
(event: KeyboardInputEvent) => {
if (event.key !== "Escape") return false;
@@ -70,7 +60,7 @@ export function AttachmentLightbox({ source, onClose }: AttachmentLightboxProps)
);
const setOverlayScope = useOverlayRegistration({
keys: ["Escape"],
active: open,
active: source !== null,
layer: modalLayer,
onKeyDown: handleOverlayKeyDown,
});
@@ -89,7 +79,7 @@ export function AttachmentLightbox({ source, onClose }: AttachmentLightboxProps)
const handleImageError = useCallback(() => setErrored(true), []);
if (!open) {
if (!source) {
return null;
}
@@ -84,9 +84,6 @@ export function DraggableListHandle({ testID, style, children }: DraggableListHa
}
const SCROLL_ENABLED_FLEX_STYLE = { flex: 1 };
// Viewports of rows a nestable list keeps rendered around the container's viewport: two above,
// two below. FlatList's default of 21 would still render a long sidebar in full.
const NESTED_WINDOW_SIZE = 5;
// A drop remounts every row between the drag's start and end slots (see the draggable-flatlist
// patch), so state held inside a rendered row resets when a drop moves it. Keep state that must
@@ -209,12 +206,9 @@ export function DraggableList<T>({
showsVerticalScrollIndicator={showsVerticalScrollIndicator}
scrollEnabled={scrollEnabled}
// A list that doesn't scroll shows every row, so it renders them all in its first commit.
// FlatList's default first render is 10 rows; a list remounted by a drop would paint 10
// rows, then grow on a later commit. A nestable list is the exception: its
// NestableScrollContainer is a VirtualizedList, so it renders only the rows near that
// container's viewport, and a hidden sidebar does not render rows nobody can see.
initialNumToRender={scrollEnabled || nestable ? undefined : data.length}
windowSize={nestable ? NESTED_WINDOW_SIZE : undefined}
// FlatList's default first render is 10 rows; a nested list remounted by a drop would paint
// 10 rows, then grow on a later commit.
initialNumToRender={scrollEnabled ? undefined : data.length}
extraData={extraData}
simultaneousHandlers={simultaneousHandlers}
dragGestureHostPresented={gestureHostPresented}
@@ -4,8 +4,8 @@ import { FlatList, Text, View } from "react-native";
import { StyleSheet, withUnistyles } from "react-native-unistyles";
import { AlertTriangle, ChevronDown, Layers } from "lucide-react-native";
import type { AgentProfilePickerRow } from "@/agent-profiles";
import { IndependentScrollBoundary } from "@/components/ui/independent-scroll-boundary";
import {
IndependentScrollBoundary,
MODEL_PICKER_ROW_HEIGHT,
ModelBrowserLoadingState,
ModelBrowserNoProviders,
+29 -5
View File
@@ -12,6 +12,7 @@ import {
import { useTranslation } from "react-i18next";
import {
FlatList,
Platform,
Pressable,
ScrollView,
Text,
@@ -26,10 +27,6 @@ import {
type StyleProp,
type ViewStyle,
} from "react-native";
import {
IndependentScrollBoundary,
useIndependentScrollGesture,
} from "@/components/ui/independent-scroll-boundary";
import { Gesture, GestureDetector } from "react-native-gesture-handler";
import { StyleSheet, withUnistyles } from "react-native-unistyles";
import {
@@ -212,6 +209,10 @@ function AgentProfilesEditAction({ onPress }: { onPress: () => void }) {
);
}
const IndependentScrollGestureContext = createContext<ReturnType<typeof Gesture.Native> | null>(
null,
);
interface ModelBrowserNavContextValue {
activeKey: string | null;
onActivateKey: (key: string) => void;
@@ -615,7 +616,7 @@ function ModelBrowserPressable({
onLayout,
testID,
}: ModelBrowserPressableProps) {
const independentScrollGesture = useIndependentScrollGesture();
const independentScrollGesture = useContext(IndependentScrollGestureContext);
const [pressed, setPressed] = useState(false);
// Android's scroll handler must keep the pointer stream until release so a
// fling survives leaving the short viewport. A simultaneous Tap keeps rows
@@ -1380,6 +1381,29 @@ function GroupedProviderRows({
);
}
export function IndependentScrollBoundary({ children }: { children: React.ReactElement }) {
// Prevent the parent sheet from cancelling Android's native scroll when the
// finger crosses this viewport; receiving ACTION_UP is what preserves fling.
const nativeScrollGesture = useMemo(
() =>
Gesture.Native()
.shouldActivateOnStart(true)
.shouldCancelWhenOutside(false)
.disallowInterruption(true),
[],
);
if (Platform.OS !== "android") {
return children;
}
return (
<IndependentScrollGestureContext.Provider value={nativeScrollGesture}>
<GestureDetector gesture={nativeScrollGesture}>{children}</GestureDetector>
</IndependentScrollGestureContext.Provider>
);
}
function resolveModelListRevealTarget({
shouldRevealActive,
hasActiveHeaderItem,
@@ -0,0 +1,52 @@
import { Component, type ErrorInfo, type ReactNode } from "react";
interface RenderErrorBoundaryProps {
children: ReactNode;
/** A caught error is cleared when any of these values change, so new content renders. */
resetKeys: readonly unknown[];
/** The error state shown in place of the children. `retry` renders the children again. */
renderError(error: string, retry: () => void): ReactNode;
onError(error: unknown, componentStack: string | null | undefined): void;
}
interface RenderErrorBoundaryState {
error: string | null;
}
/**
* Keeps a render error inside one surface. Without it the error reaches the root boundary,
* which replaces the whole app.
*/
export class RenderErrorBoundary extends Component<
RenderErrorBoundaryProps,
RenderErrorBoundaryState
> {
state: RenderErrorBoundaryState = { error: null };
static getDerivedStateFromError(error: unknown): RenderErrorBoundaryState {
return { error: error instanceof Error ? error.message : String(error) };
}
componentDidCatch(error: unknown, info: ErrorInfo): void {
this.props.onError(error, info.componentStack);
}
componentDidUpdate(previous: RenderErrorBoundaryProps): void {
if (this.state.error !== null && resetKeysChanged(previous.resetKeys, this.props.resetKeys)) {
this.retry();
}
}
retry = (): void => {
this.setState({ error: null });
};
render() {
if (this.state.error !== null) return this.props.renderError(this.state.error, this.retry);
return this.props.children;
}
}
function resetKeysChanged(previous: readonly unknown[], next: readonly unknown[]): boolean {
return previous.length !== next.length || previous.some((key, index) => key !== next[index]);
}
@@ -37,7 +37,7 @@ export type { SettingsRowHintStatus } from "./row-header";
export { SettingsAddRow } from "./add-row";
export { SettingsBackLink, SettingsDetailHeader } from "./detail-header";
export { SettingsInfoTip } from "./headings/settings-info-tip";
export { ListSettingsRows, MenuSettingsRows } from "./row-density";
export { MenuSettingsRows } from "./row-density";
/**
* What app screens can add to a plugin-facing row: an accessory beside the label, such as an info
@@ -1,12 +1,7 @@
import { createContext, useContext, useMemo, type ReactNode } from "react";
import type { StyleProp, TextStyle, ViewStyle } from "react-native";
import { StyleSheet } from "react-native-unistyles";
import {
CONTROL_HEIGHTS,
mapLayout,
TOUCH_TARGET,
type ControlSize,
} from "@/components/ui/control-geometry";
import { CONTROL_HEIGHTS, mapLayout, type ControlSize } from "@/components/ui/control-geometry";
import { menuRowContentInset } from "@/components/ui/menu";
import { settingsStyles } from "@/styles/settings";
@@ -17,9 +12,7 @@ import { settingsStyles } from "@/styles/settings";
// - nested: rows revealed under a collapsible row belong to it, so they sit one step smaller than
// the rows of the card: tighter padding, smaller text, smaller controls.
// - menu: rows that share a menu surface with menu rows put their labels on the menu's label rail.
// - list: rows that share a sheet with list rows, such as radio choices and section headers, take
// the list row's height so every row in the sheet lines up.
type RowPlacement = "card" | "nested" | "menu" | "list";
type RowPlacement = "card" | "nested" | "menu";
const RowPlacementContext = createContext<RowPlacement>("card");
@@ -32,11 +25,6 @@ export function MenuSettingsRows({ children }: { children: ReactNode }) {
return <RowPlacementContext.Provider value="menu">{children}</RowPlacementContext.Provider>;
}
/** Settings rows rendered in a sheet of list rows, such as Agent settings. */
export function ListSettingsRows({ children }: { children: ReactNode }) {
return <RowPlacementContext.Provider value="list">{children}</RowPlacementContext.Provider>;
}
export interface SettingsRowLayout {
row: StyleProp<ViewStyle>;
title: StyleProp<TextStyle>;
@@ -61,13 +49,6 @@ function layoutFor(placement: RowPlacement): SettingsRowLayout {
hint: settingsStyles.rowHint,
controlSize: "md",
};
case "list":
return {
row: [settingsStyles.row, styles.listRow],
title: settingsStyles.rowTitle,
hint: settingsStyles.rowHint,
controlSize: "md",
};
case "card":
return {
row: settingsStyles.row,
@@ -91,11 +72,6 @@ const styles = StyleSheet.create((theme) => ({
paddingVertical: theme.spacing[2],
minHeight: mapLayout(CONTROL_HEIGHTS.sm, (height) => height + theme.spacing[2] * 2),
},
// A list row is a touch target tall on every input; a switch still fits inside its padding.
listRow: {
paddingVertical: theme.spacing[2],
minHeight: TOUCH_TARGET,
},
nestedText: {
fontSize: theme.fontSize.sm,
},
@@ -2311,7 +2311,7 @@ function ProjectModeList({
() =>
parentGestureRef
? ({
// NestableScrollContainer forwards props to an RNGH FlatList. Keep
// NestableScrollContainer forwards props to RNGH ScrollView. Keep
// vertical scroll and sidebar close pan simultaneous: vertical
// intent scrolls immediately, clear horizontal intent can still
// activate close from inside the list.
@@ -1,44 +0,0 @@
import { createContext, useContext, useMemo, type ReactElement } from "react";
import { Platform } from "react-native";
import { Gesture, GestureDetector } from "react-native-gesture-handler";
const IndependentScrollGestureContext = createContext<ReturnType<typeof Gesture.Native> | null>(
null,
);
/** The native scroll gesture of the enclosing boundary, for gestures that must not cancel it. */
export function useIndependentScrollGesture(): ReturnType<typeof Gesture.Native> | null {
return useContext(IndependentScrollGestureContext);
}
/**
* Keeps a parent pan from interrupting an Android scroll and lets the list receive ACTION_UP
* for the fling. With activation on start, child taps must join the native scroll gesture.
* When activation waits for the scroll view to intercept a drag, ordinary pressables receive taps.
*/
export function IndependentScrollBoundary({
children,
activateOnStart = true,
}: {
children: ReactElement;
activateOnStart?: boolean;
}) {
const nativeScrollGesture = useMemo(
() =>
Gesture.Native()
.shouldActivateOnStart(activateOnStart)
.shouldCancelWhenOutside(false)
.disallowInterruption(true),
[activateOnStart],
);
if (Platform.OS !== "android") {
return children;
}
return (
<IndependentScrollGestureContext.Provider value={nativeScrollGesture}>
<GestureDetector gesture={nativeScrollGesture}>{children}</GestureDetector>
</IndependentScrollGestureContext.Provider>
);
}
@@ -1,36 +0,0 @@
import React, { act } from "react";
import { createRoot, type Root } from "react-dom/client";
import { afterEach, beforeEach, expect, it, vi } from "vitest";
import { page } from "vitest/browser";
import { i18n } from "@/i18n/i18next";
import { LoadingSpinner } from "./loading-spinner";
let root: Root;
let host: HTMLDivElement;
beforeEach(async () => {
await i18n.changeLanguage("en");
vi.stubGlobal("React", React);
vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
host = document.createElement("div");
document.body.appendChild(host);
root = createRoot(host);
});
afterEach(() => {
act(() => root.unmount());
host.remove();
vi.unstubAllGlobals();
});
it("announces itself as loading when the caller gives no label", async () => {
act(() => root.render(<LoadingSpinner color="#888888" />));
await expect.element(page.getByRole("progressbar", { name: "Loading..." })).toBeVisible();
});
it("announces what is loading when the caller names it", async () => {
act(() => root.render(<LoadingSpinner color="#888888" accessibilityLabel="Loading commits" />));
await expect.element(page.getByRole("progressbar", { name: "Loading commits" })).toBeVisible();
});
@@ -1,29 +1,12 @@
import React from "react";
import { useTranslation } from "react-i18next";
import { ActivityIndicator, type ActivityIndicatorProps } from "react-native";
interface LoadingSpinnerProps {
color: string;
size?: ActivityIndicatorProps["size"];
style?: ActivityIndicatorProps["style"];
/** What is loading. Screen readers announce "Loading" when this is absent. */
accessibilityLabel?: string;
}
export function LoadingSpinner({
color,
size = "small",
style,
accessibilityLabel,
}: LoadingSpinnerProps) {
const { t } = useTranslation();
return (
<ActivityIndicator
size={size}
color={color}
style={style}
accessibilityRole="progressbar"
accessibilityLabel={accessibilityLabel ?? t("common.loading")}
/>
);
export function LoadingSpinner({ color, size = "small", style }: LoadingSpinnerProps) {
return <ActivityIndicator size={size} color={color} style={style} />;
}
@@ -1,66 +0,0 @@
import { Text, View } from "react-native";
import { StyleSheet, withUnistyles } from "react-native-unistyles";
import { LoadingSpinner } from "@/components/ui/loading-spinner";
import type { Theme } from "@/styles/theme";
const ThemedLoadingSpinner = withUnistyles(LoadingSpinner);
const foregroundMutedColorMapping = (theme: Theme) => ({
color: theme.colors.foregroundMuted,
});
/**
* A screen or pane waiting for its content. Every wait shows the same spinner in the same place,
* so a wait that changes what it is waiting for changes only the words under it.
*/
export function LoadingState({
title,
description,
testID,
}: {
/** What the wait is for. Leave it out while the wait is too short to read. */
title?: string;
description?: string;
testID?: string;
}) {
return (
<View style={styles.container} testID={testID}>
<ThemedLoadingSpinner
size="small"
uniProps={foregroundMutedColorMapping}
accessibilityLabel={title}
/>
{title ? (
<View style={styles.textStack}>
<Text style={styles.title}>{title}</Text>
{description ? <Text style={styles.description}>{description}</Text> : null}
</View>
) : null}
</View>
);
}
const styles = StyleSheet.create((theme) => ({
container: {
flex: 1,
alignItems: "center",
justifyContent: "center",
gap: theme.spacing[3],
paddingHorizontal: theme.spacing[6],
},
textStack: {
alignItems: "center",
gap: theme.spacing[2],
maxWidth: 520,
},
title: {
color: theme.colors.foreground,
fontSize: theme.fontSize.base,
fontWeight: theme.fontWeight.normal,
textAlign: "center",
},
description: {
color: theme.colors.foregroundMuted,
fontSize: theme.fontSize.base,
textAlign: "center",
},
}));
@@ -88,11 +88,7 @@ export function AgentSettingsDrawer({
}: AgentSettingsDrawerProps) {
const { t } = useTranslation();
const [page, setPage] = useState<AgentSheetPage>(AGENT_SHEET_HOME);
// Profiles open on Home for a new agent, where a profile is the quickest way to configure it.
// `null` until the user toggles the card in this opening.
const [profilesToggled, setProfilesToggled] = useState<boolean | null>(null);
const profilesExpanded =
profilesToggled ?? (profiles?.target === "draft" && profiles.rows.length > 0);
const [profilesExpanded, setProfilesExpanded] = useState(false);
// Select pages search with this; the Model page keeps its own.
const [pageQuery, setPageQuery] = useState("");
const [pageSearchKey, setPageSearchKey] = useState(0);
@@ -107,8 +103,8 @@ export function AgentSettingsDrawer({
});
const toggleProfiles = useCallback(() => {
setProfilesToggled(!profilesExpanded);
}, [profilesExpanded]);
setProfilesExpanded((expanded) => !expanded);
}, []);
const goTo = useCallback((next: AgentSheetPage) => {
Keyboard.dismiss();
@@ -129,7 +125,7 @@ export function AgentSettingsDrawer({
const close = useCallback(() => {
Keyboard.dismiss();
setPage(AGENT_SHEET_HOME);
setProfilesToggled(null);
setProfilesExpanded(false);
setPageQuery("");
modelPage.reset();
onClose();
@@ -8,7 +8,6 @@ import type { AgentMode } from "@getpaseo/protocol/agent-types";
import { getAgentModeOptionIcon } from "@/agent-controls/icons";
import { formatAgentModeLabel } from "@/agent-controls/labels";
import {
ListSettingsRows,
SettingsCard,
SettingsDetailRow,
SettingsSection,
@@ -20,7 +19,6 @@ import { PressHighlight } from "@/components/ui/press-highlight";
import { ScrollView as SheetScrollView } from "@/components/ui/scroll-view";
import { SegmentedControl, type SegmentedControlOption } from "@/components/ui/segmented-control";
import { SteppedSlider, type SteppedSliderOption } from "@/components/ui/stepped-slider";
import { TOUCH_TARGET } from "@/components/ui/control-geometry";
import { isNative } from "@/constants/platform";
import { ICON_SIZE } from "@/styles/theme";
import {
@@ -87,19 +85,17 @@ export function AgentSheetHome({
>
{/* Themed insets sit on a View: the sheet scroller drops a themed contentContainerStyle on web. */}
<View style={styles.content}>
<ListSettingsRows>
<View style={styles.block}>{topCard}</View>
{blocks.map((block) => (
<HomeBlock
key={blockKey(block)}
block={block}
modeControl={modeControl}
disabled={disabled}
onOpenSelect={onOpenSelect}
/>
))}
{footer}
</ListSettingsRows>
<View style={styles.block}>{topCard}</View>
{blocks.map((block) => (
<HomeBlock
key={blockKey(block)}
block={block}
modeControl={modeControl}
disabled={disabled}
onOpenSelect={onOpenSelect}
/>
))}
{footer}
</View>
</SheetScrollView>
);
@@ -667,7 +663,7 @@ const styles = StyleSheet.create((theme) => ({
fontSize: theme.fontSize.base,
},
radioRow: {
minHeight: TOUCH_TARGET,
minHeight: 44,
flexDirection: "row",
alignItems: "center",
paddingHorizontal: theme.spacing[4],
@@ -43,7 +43,7 @@ describe("schedule mutation cache updates", () => {
const current: FetchAggregatedSchedulesResult = {
status: "loaded",
data: [schedule()],
hostWarnings: [],
hostErrors: [],
};
const result = updateAggregatedSchedulesData(current, pauseSchedules);
@@ -51,7 +51,7 @@ describe("schedule mutation cache updates", () => {
expect(result).toEqual({
status: "loaded",
data: [schedule({ status: "paused" })],
hostWarnings: [],
hostErrors: [],
});
});
@@ -69,7 +69,7 @@ describe("schedule mutation cache updates", () => {
const loaded: FetchAggregatedSchedulesResult = {
status: "loaded",
data: [schedule()],
hostWarnings: [],
hostErrors: [],
};
queryClient.setQueryData(connectingKey, connecting);
queryClient.setQueryData(loadedKey, loaded);
@@ -85,7 +85,7 @@ describe("schedule mutation cache updates", () => {
expect(queryClient.getQueryData(loadedKey)).toEqual({
status: "loaded",
data: [schedule({ status: "paused" })],
hostWarnings: [],
hostErrors: [],
});
});
});
+4 -4
View File
@@ -10,14 +10,14 @@ import {
schedulesQueryBaseKey,
type AggregateLoadState,
type AggregatedSchedule,
type ScheduleHostWarning,
type ScheduleHostError,
type ScheduleHostInput,
} from "@/schedules/aggregated-schedules";
export type {
AggregateLoadState,
AggregatedSchedule,
ScheduleHostWarning,
ScheduleHostError,
} from "@/schedules/aggregated-schedules";
export function schedulesQueryKey(serverIds: readonly string[]) {
@@ -26,7 +26,7 @@ export function schedulesQueryKey(serverIds: readonly string[]) {
export interface UseSchedulesResult {
loadState: AggregateLoadState<AggregatedSchedule>;
hostWarnings: ScheduleHostWarning[];
hostErrors: ScheduleHostError[];
isError: boolean;
error: Error | null;
refetch: () => void;
@@ -65,7 +65,7 @@ export function useSchedules(): UseSchedulesResult {
return {
loadState,
hostWarnings: query.data?.status === "loaded" ? query.data.hostWarnings : [],
hostErrors: query.data?.status === "loaded" ? query.data.hostErrors : [],
isError: query.isError,
error: query.error,
refetch: () => {
+3 -2
View File
@@ -278,8 +278,6 @@ export const ar: TranslationResources = {
failedToLoad: "فشل تحميل الوكيل",
reconnecting: "جارٍ إعادة الاتصال",
updating: "جارٍ تحديث الرسائل",
loadingAgent: "جارٍ تحميل الوكيل",
loadingHistory: "جارٍ تحميل سجل الوكيل",
timelineSyncFailed: "تعذر تحديث سجل الوكيل.",
timelineSyncRetrying: "جارٍ إعادة المحاولة…",
archivingTitle: "وكيل الارشيف...",
@@ -2185,6 +2183,9 @@ export const ar: TranslationResources = {
archiveFinishedRetry: "إعادة المحاولة ({{failed}}/{{total}})",
},
panels: {
renderError: {
title: "تعذّر عرض هذه اللوحة",
},
draft: {
newAgent: "وكيل جديد",
creatingAgent: "وكيل الخلق",
+3 -2
View File
@@ -276,8 +276,6 @@ export const en = {
failedToLoad: "Failed to load agent",
reconnecting: "Reconnecting",
updating: "Updating messages",
loadingAgent: "Loading agent",
loadingHistory: "Loading agent history",
timelineSyncFailed: "Couldn't refresh agent history.",
timelineSyncRetrying: "Retrying…",
archivingTitle: "Archiving agent...",
@@ -2215,6 +2213,9 @@ export const en = {
archiveFinishedRetry: "Retry ({{failed}}/{{total}})",
},
panels: {
renderError: {
title: "Unable to show this panel",
},
draft: {
newAgent: "New Agent",
creatingAgent: "Creating agent",
+3 -2
View File
@@ -280,8 +280,6 @@ export const es: TranslationResources = {
failedToLoad: "No se pudo cargar el agente",
reconnecting: "Reconectando",
updating: "Actualizando mensajes",
loadingAgent: "Cargando agente",
loadingHistory: "Cargando historial del agente",
timelineSyncFailed: "No se pudo actualizar el historial del agente.",
timelineSyncRetrying: "Reintentando…",
archivingTitle: "Agente de archivo...",
@@ -2241,6 +2239,9 @@ export const es: TranslationResources = {
archiveFinishedRetry: "Reintentar ({{failed}}/{{total}})",
},
panels: {
renderError: {
title: "No se puede mostrar este panel",
},
draft: {
newAgent: "Nuevo agente",
creatingAgent: "Agente creador",
+3 -2
View File
@@ -281,8 +281,6 @@ export const fr: TranslationResources = {
failedToLoad: "Impossible de charger l’agent",
reconnecting: "Reconnexion…",
updating: "Mise à jour des messages…",
loadingAgent: "Chargement de l’agent",
loadingHistory: "Chargement de l’historique de l’agent",
timelineSyncFailed: "Impossible d’actualiser l’historique de l’agent.",
timelineSyncRetrying: "Nouvelle tentative…",
archivingTitle: "Archivage de l’agent…",
@@ -2238,6 +2236,9 @@ export const fr: TranslationResources = {
archiveFinishedRetry: "Réessayer ({{failed}}/{{total}})",
},
panels: {
renderError: {
title: "Impossible d'afficher ce panneau",
},
draft: {
newAgent: "Nouvel agent",
creatingAgent: "Création de l’agent",
+3 -2
View File
@@ -280,8 +280,6 @@ export const ja: TranslationResources = {
failedToLoad: "エージェントの読み込みに失敗しました",
reconnecting: "再接続中",
updating: "メッセージを更新中",
loadingAgent: "エージェントを読み込み中",
loadingHistory: "エージェントの履歴を読み込み中",
timelineSyncFailed: "エージェントの履歴を更新できませんでした。",
timelineSyncRetrying: "再試行しています…",
archivingTitle: "エージェントをアーカイブ中...",
@@ -2208,6 +2206,9 @@ export const ja: TranslationResources = {
archiveFinishedRetry: "再試行 ({{failed}}/{{total}})",
},
panels: {
renderError: {
title: "このパネルを表示できません",
},
draft: {
newAgent: "新しいエージェント",
creatingAgent: "エージェントを作成中",
+3 -2
View File
@@ -278,8 +278,6 @@ export const ko: TranslationResources = {
failedToLoad: "에이전트를 불러오지 못했습니다",
reconnecting: "다시 연결하는 중",
updating: "메시지 업데이트 중",
loadingAgent: "에이전트 불러오는 중",
loadingHistory: "에이전트 기록 불러오는 중",
timelineSyncFailed: "에이전트 기록을 새로고침할 수 없습니다.",
timelineSyncRetrying: "재시도 중…",
archivingTitle: "에이전트 보관 중...",
@@ -2197,6 +2195,9 @@ export const ko: TranslationResources = {
archiveFinishedRetry: "다시 시도 ({{failed}}/{{total}})",
},
panels: {
renderError: {
title: "이 패널을 표시할 수 없습니다",
},
draft: {
newAgent: "새 에이전트",
creatingAgent: "에이전트 생성 중",
+3 -2
View File
@@ -279,8 +279,6 @@ export const ptBR: TranslationResources = {
failedToLoad: "Falha ao carregar agente",
reconnecting: "Reconectando",
updating: "Atualizando mensagens",
loadingAgent: "Carregando agente",
loadingHistory: "Carregando histórico do agente",
timelineSyncFailed: "Não foi possível atualizar o histórico do agente.",
timelineSyncRetrying: "Tentando novamente…",
archivingTitle: "Arquivando agente...",
@@ -2225,6 +2223,9 @@ export const ptBR: TranslationResources = {
archiveFinishedRetry: "Tentar novamente ({{failed}}/{{total}})",
},
panels: {
renderError: {
title: "Não foi possível exibir este painel",
},
draft: {
newAgent: "Novo Agente",
creatingAgent: "Criando agente",
+3 -2
View File
@@ -280,8 +280,6 @@ export const ru: TranslationResources = {
failedToLoad: "Не удалось загрузить агента",
reconnecting: "Повторное подключение",
updating: "Обновление сообщений",
loadingAgent: "Загрузка агента",
loadingHistory: "Загрузка истории агента",
timelineSyncFailed: "Не удалось обновить историю агента.",
timelineSyncRetrying: "Повторная попытка…",
archivingTitle: "Агент перемещается в архив...",
@@ -2225,6 +2223,9 @@ export const ru: TranslationResources = {
archiveFinishedRetry: "Повторить ({{failed}}/{{total}})",
},
panels: {
renderError: {
title: "Не удалось показать эту панель",
},
draft: {
newAgent: "Новый агент",
creatingAgent: "Создание агента",
+3 -2
View File
@@ -278,8 +278,6 @@ export const zhCN: TranslationResources = {
failedToLoad: "加载 Agent 失败",
reconnecting: "正在重新连接",
updating: "正在更新消息",
loadingAgent: "正在加载代理",
loadingHistory: "正在加载代理历史记录",
timelineSyncFailed: "无法刷新代理历史记录。",
timelineSyncRetrying: "正在重试…",
archivingTitle: "正在归档 Agent...",
@@ -2162,6 +2160,9 @@ export const zhCN: TranslationResources = {
archiveFinishedRetry: "重试 ({{failed}}/{{total}})",
},
panels: {
renderError: {
title: "无法显示此面板",
},
draft: {
newAgent: "新建 Agent",
creatingAgent: "正在创建 Agent",
-51
View File
@@ -1,51 +0,0 @@
import { useEffect, useLayoutEffect } from "react";
import { createNativeSplashController, type NativeSplashController } from "./internal/controller";
import { launchSurface } from "./internal/launch-surface";
export { LaunchScreen } from "./internal/launch-surface";
// Guards against a screen that never releases its hold. A slow device places the first
// conversation 2-4 s after the JS entry, so a shorter cap cuts in before it paints.
const CAP_MS = 5_000;
let controller: NativeSplashController | null = null;
let releaseLaunch: (() => void) | null = null;
/**
* Call once at the JS entry. The launch surface (the native splash, or on Android the
* `LaunchScreen` that replaces it) then covers the app until the root navigator has committed its
* first screen and no screen holds it, and leaves from here alone.
*/
export function keepNativeSplash(): void {
if (controller) return;
launchSurface.keep();
controller = createNativeSplashController(
{
hide: () => launchSurface.leave(),
afterNextFrame: (callback) => {
requestAnimationFrame(() => callback());
},
startTimer: (callback, ms) => {
setTimeout(callback, ms);
},
},
{ capMs: CAP_MS },
);
releaseLaunch = controller.hold();
}
/** The root navigator's first commit ends the launch hold. Screens committed with it hold first. */
export function useNativeSplashLaunchCommit(): void {
useEffect(() => {
releaseLaunch?.();
releaseLaunch = null;
}, []);
}
/** Keeps the launch surface up while `active`, for a screen that has nothing to show yet. */
export function useNativeSplashHold(active: boolean): void {
useLayoutEffect(() => {
if (!active) return;
return controller?.hold();
}, [active]);
}
@@ -1,86 +0,0 @@
import { describe, expect, it } from "vitest";
import { createNativeSplashController } from "./controller";
function createFakeSplash() {
const frames: Array<() => void> = [];
const timers: Array<{ callback: () => void; ms: number }> = [];
const splash = { hides: 0 };
const controller = createNativeSplashController(
{
hide: () => {
splash.hides += 1;
},
afterNextFrame: (callback) => {
frames.push(callback);
},
startTimer: (callback, ms) => {
timers.push({ callback, ms });
},
},
{ capMs: 3_000 },
);
const runFrame = () => {
for (const callback of frames.splice(0)) callback();
};
const runCap = () => {
for (const timer of timers.splice(0)) timer.callback();
};
return { controller, splash, runFrame, runCap, timers };
}
describe("native splash", () => {
it("stays up while a screen holds it and hides a frame after the last release", () => {
const { controller, splash, runFrame } = createFakeSplash();
const releaseLaunch = controller.hold();
const releaseScreen = controller.hold();
releaseLaunch();
runFrame();
expect(splash.hides).toBe(0);
releaseScreen();
expect(splash.hides).toBe(0);
runFrame();
expect(splash.hides).toBe(1);
});
it("stays up when the next screen takes the hold before the frame passes", () => {
const { controller, splash, runFrame } = createFakeSplash();
const releaseSplashRoute = controller.hold();
releaseSplashRoute();
const releaseWorkspace = controller.hold();
runFrame();
expect(splash.hides).toBe(0);
releaseWorkspace();
runFrame();
expect(splash.hides).toBe(1);
});
it("hides when the cap runs out even while a screen still holds it", () => {
const { controller, splash, runCap, runFrame, timers } = createFakeSplash();
const release = controller.hold();
expect(timers.map((timer) => timer.ms)).toEqual([3_000]);
runCap();
expect(splash.hides).toBe(1);
release();
runFrame();
expect(controller.hold()).toBeTypeOf("function");
runFrame();
expect(splash.hides).toBe(1);
});
it("counts a repeated release once", () => {
const { controller, splash, runFrame } = createFakeSplash();
const first = controller.hold();
controller.hold();
first();
first();
runFrame();
expect(splash.hides).toBe(0);
});
});
@@ -1,53 +0,0 @@
export interface NativeSplashPort {
hide(): void;
/** Runs the callback after the next frame, once the committed screen has been drawn. */
afterNextFrame(callback: () => void): void;
startTimer(callback: () => void, ms: number): void;
}
export interface NativeSplashController {
/** Keeps the splash up until the returned release runs. Holds after the hide do nothing. */
hold(): () => void;
}
/**
* The splash hides once, after a frame passes with nothing holding it, or when the cap runs out.
* The frame wait lets a screen that replaces a holding screen in the same commit take over.
*/
export function createNativeSplashController(
port: NativeSplashPort,
options: { capMs: number },
): NativeSplashController {
let holds = 0;
let hidden = false;
let checkScheduled = false;
const hide = () => {
if (hidden) return;
hidden = true;
port.hide();
};
const hideIfReleased = () => {
checkScheduled = false;
if (holds === 0) hide();
};
port.startTimer(hide, options.capMs);
return {
hold() {
if (hidden) return () => undefined;
holds += 1;
let released = false;
return () => {
if (released) return;
released = true;
holds -= 1;
if (holds > 0 || hidden || checkScheduled) return;
checkScheduled = true;
port.afterNextFrame(hideIfReleased);
};
},
};
}
@@ -1,104 +0,0 @@
import { useEffect, useState, useSyncExternalStore } from "react";
import { useColorScheme, View } from "react-native";
import Animated, { useAnimatedStyle, useSharedValue, withTiming } from "react-native-reanimated";
import { scheduleOnRN } from "react-native-worklets";
import { StyleSheet } from "react-native-unistyles";
import * as SplashScreen from "expo-splash-screen";
import { PaseoLogo } from "@/components/icons/paseo-logo";
// Android hands its splash to the app in a way the app cannot time: the system can show one app
// frame before its copy of the splash draws, and a frame the app draws first can be empty. So the
// native splash leaves as soon as React commits this screen, which looks the same as the splash,
// and this screen covers the app until launch is done.
// The splash colours from the expo-splash-screen entry in app.config.js. Android picks them from
// the system dark mode, not from the app theme.
const SPLASH_BACKGROUND = { dark: "#000000", light: "#ffffff" } as const;
// Android draws a splash icon without a background inside a 192dp circle.
const ICON_CIRCLE_SIZE = 192;
// The splash icon's glyph is 135dp wide, which the logo's glyph reaches at this SVG size.
const LOGO_SIZE = 182;
const EXIT_MS = 200;
let launchDone = false;
const listeners = new Set<() => void>();
function subscribe(listener: () => void): () => void {
listeners.add(listener);
return () => listeners.delete(listener);
}
function isLaunchDone(): boolean {
return launchDone;
}
/** Android: this screen covers the app until launch is done, then fades out. */
export const launchSurface = {
keep(): void {
void SplashScreen.preventAutoHideAsync().catch(() => undefined);
// The system's copy of the splash fades over this screen, which looks the same.
SplashScreen.setOptions({ duration: 150, fade: true });
},
leave(): void {
if (launchDone) return;
launchDone = true;
for (const listener of listeners) listener();
},
};
export function LaunchScreen() {
const leaving = useSyncExternalStore(subscribe, isLaunchDone);
const [gone, setGone] = useState(false);
const scheme = useColorScheme() === "light" ? "light" : "dark";
const opacity = useSharedValue(1);
const fadeStyle = useAnimatedStyle(() => ({ opacity: opacity.value }));
useEffect(() => {
SplashScreen.hide();
}, []);
useEffect(() => {
if (!leaving) return;
opacity.value = withTiming(0, { duration: EXIT_MS }, (finished) => {
if (finished) scheduleOnRN(setGone, true);
});
}, [leaving, opacity]);
if (gone) return null;
return (
<Animated.View
pointerEvents={leaving ? "none" : "auto"}
style={[styles.screen, { backgroundColor: SPLASH_BACKGROUND[scheme] }, fadeStyle]}
>
<View style={styles.iconCircle}>
<View style={styles.logo}>
<PaseoLogo size={LOGO_SIZE} color="#ffffff" />
</View>
</View>
</Animated.View>
);
}
const styles = StyleSheet.create({
screen: {
position: "absolute",
top: 0,
left: 0,
right: 0,
bottom: 0,
alignItems: "center",
justifyContent: "center",
},
iconCircle: {
width: ICON_CIRCLE_SIZE,
height: ICON_CIRCLE_SIZE,
borderRadius: ICON_CIRCLE_SIZE / 2,
backgroundColor: "#000000",
alignItems: "center",
justifyContent: "center",
},
logo: {
// Optical: the glyph sits right of the SVG's centre. The splash centres the glyph.
transform: [{ translateX: -4 }],
},
});
@@ -1,20 +0,0 @@
import * as SplashScreen from "expo-splash-screen";
// iOS fades the native splash straight into the first screen.
const FADE_MS = 150;
/** iOS and web: the native splash itself covers the app until launch is done. */
export const launchSurface = {
keep(): void {
// Taking control stops expo-router from hiding the splash when navigation is ready.
void SplashScreen.preventAutoHideAsync().catch(() => undefined);
SplashScreen.setOptions({ duration: FADE_MS, fade: true });
},
leave(): void {
SplashScreen.hide();
},
};
export function LaunchScreen(): null {
return null;
}
@@ -4,6 +4,7 @@ import {
resolveStartupNavigationReady,
resolveHostIndexRoute,
resolveStartupRoute,
shouldRunStartupGiveUpTimer,
startHostRuntimeBootstrap,
bindHostRuntimeAppState,
} from "./host-runtime-bootstrap";
@@ -89,41 +90,6 @@ describe("startHostRuntimeBootstrap", () => {
"decision:true",
]);
});
it("settles once the registry boot and the managed-daemon start have both finished", async () => {
let resolveBoot!: () => void;
let resolveDaemonStart!: (result: DaemonStartResult) => void;
let settled = false;
const bootstrap = startHostRuntimeBootstrap({
store: {
boot: () =>
new Promise<void>((resolve) => {
resolveBoot = resolve;
}),
},
daemonStartService: {
startIfEnabled: () =>
new Promise<DaemonStartResult>((resolve) => {
resolveDaemonStart = resolve;
}),
},
shouldStartDaemon: false,
});
void bootstrap.then(() => {
settled = true;
return;
});
resolveBoot();
await Promise.resolve();
await Promise.resolve();
expect(settled).toBe(false);
resolveDaemonStart({ ok: false, error: "daemon failed to start" });
await bootstrap;
expect(settled).toBe(true);
});
});
describe("startup blocking policy", () => {
@@ -134,11 +100,18 @@ describe("startup blocking policy", () => {
daemonStartError: null,
};
it("does not block navigation when no startup blocker is active", () => {
it("runs the give-up timer when no startup blocker is active", () => {
const blocker = resolveStartupBlocker(noBlockerInput);
expect(blocker).toEqual({ kind: "none" });
expect(resolveStartupNavigationReady({ startupBlocker: blocker })).toBe(true);
expect(
shouldRunStartupGiveUpTimer({
startupBlocker: blocker,
anyOnlineHostServerId: null,
hasGivenUpWaitingForHost: false,
}),
).toBe(true);
});
it("blocks navigation while desktop is starting the managed daemon", () => {
@@ -150,6 +123,13 @@ describe("startup blocking policy", () => {
expect(blocker).toEqual({ kind: "managed-daemon-starting" });
expect(resolveStartupNavigationReady({ startupBlocker: blocker })).toBe(false);
expect(
shouldRunStartupGiveUpTimer({
startupBlocker: blocker,
anyOnlineHostServerId: null,
hasGivenUpWaitingForHost: false,
}),
).toBe(false);
});
it("unblocks navigation when any host is online", () => {
@@ -176,6 +156,13 @@ describe("startup blocking policy", () => {
message: "daemon failed to start",
});
expect(resolveStartupNavigationReady({ startupBlocker: blocker })).toBe(true);
expect(
shouldRunStartupGiveUpTimer({
startupBlocker: blocker,
anyOnlineHostServerId: null,
hasGivenUpWaitingForHost: false,
}),
).toBe(false);
});
});
@@ -189,7 +176,7 @@ describe("resolveStartupRoute", () => {
workspaceSelection: null,
workspaceSelectionStatus: "unknown" as const,
isWorkspaceSelectionLoaded: true,
isWaitingForHost: true,
hasGivenUpWaitingForHost: false,
isWaitingForSetup: false,
};
const baseHostInput = {
@@ -233,7 +220,7 @@ describe("resolveStartupRoute", () => {
...baseIndexInput,
hostRegistryStatus: "loading",
workspaceSelection: { serverId: "server-1", workspaceId: "workspace-a" },
isWaitingForHost: false,
hasGivenUpWaitingForHost: true,
}),
).toEqual({ kind: "splash" });
});
@@ -278,7 +265,7 @@ describe("resolveStartupRoute", () => {
...baseIndexInput,
workspaceSelection: { serverId: "server-saved", workspaceId: "workspace-a" },
hosts: [{ serverId: "server-next" }],
isWaitingForHost: false,
hasGivenUpWaitingForHost: true,
}),
).toEqual({ kind: "redirect", href: "/h/server-next" });
});
@@ -319,25 +306,16 @@ describe("resolveStartupRoute", () => {
resolveStartupRoute({
...baseIndexInput,
hosts: [{ serverId: "server-saved" }],
isWaitingForHost: false,
hasGivenUpWaitingForHost: true,
}),
).toEqual({ kind: "redirect", href: "/h/server-saved" });
});
it("holds the splash while a startup host source can still add a host", () => {
it("shows welcome after root startup gives up and no host exists", () => {
expect(
resolveStartupRoute({
...baseIndexInput,
isWaitingForHost: true,
}),
).toEqual({ kind: "splash" });
});
it("shows welcome as soon as no host exists and none can still arrive", () => {
expect(
resolveStartupRoute({
...baseIndexInput,
isWaitingForHost: false,
hasGivenUpWaitingForHost: true,
}),
).toEqual({ kind: "redirect", href: "/welcome" });
});
@@ -26,15 +26,9 @@ export interface StartHostRuntimeBootstrapInput {
shouldStartDaemon: DaemonStartCondition;
}
/**
* Starts every source that can add a host at launch: the registry boot with its connection probes,
* and the managed daemon. Settles once none of them can still add one.
*/
export async function startHostRuntimeBootstrap(
input: StartHostRuntimeBootstrapInput,
): Promise<void> {
export function startHostRuntimeBootstrap(input: StartHostRuntimeBootstrapInput): void {
const registryReady = input.store.boot();
const daemonStart = input.daemonStartService.startIfEnabled({
void input.daemonStartService.startIfEnabled({
shouldStart: async () => {
await registryReady;
return typeof input.shouldStartDaemon === "boolean"
@@ -42,7 +36,6 @@ export async function startHostRuntimeBootstrap(
: input.shouldStartDaemon();
},
});
await Promise.allSettled([registryReady, daemonStart]);
}
const WELCOME_ROUTE: Href = "/welcome";
@@ -83,6 +76,20 @@ export function resolveStartupNavigationReady(input: { startupBlocker: StartupBl
return input.startupBlocker.kind !== "managed-daemon-starting";
}
export function shouldRunStartupGiveUpTimer(input: {
startupBlocker: StartupBlocker;
anyOnlineHostServerId: string | null;
hasGivenUpWaitingForHost: boolean;
}): boolean {
if (input.anyOnlineHostServerId) {
return false;
}
if (input.hasGivenUpWaitingForHost) {
return false;
}
return input.startupBlocker.kind === "none";
}
export type StartupRegistryStatus = "loading" | "ready";
export interface IndexStartupRouteTarget {
@@ -109,8 +116,7 @@ export interface ResolveIndexStartupRouteInput extends ResolveStartupRouteBaseIn
workspaceSelection: ActiveWorkspaceSelection | null;
workspaceSelectionStatus: WorkspaceSelectionStatus;
isWorkspaceSelectionLoaded: boolean;
/** A startup host source can still add a host; see `startHostRuntimeBootstrap`. */
isWaitingForHost: boolean;
hasGivenUpWaitingForHost: boolean;
/** Setup may still open over the empty home; see `useIsSetupDecisionPending`. */
isWaitingForSetup: boolean;
}
@@ -209,11 +215,11 @@ function resolveReadyIndexStartupRoute(input: ResolveIndexStartupRouteInput): St
return { kind: "redirect", href: buildHostRootRoute(savedHostServerId) };
}
if (input.isWaitingForHost) {
return { kind: "splash" };
if (input.hasGivenUpWaitingForHost) {
return { kind: "redirect", href: WELCOME_ROUTE };
}
return { kind: "redirect", href: WELCOME_ROUTE };
return { kind: "splash" };
}
function resolveReadyHostStartupRoute(input: ResolveHostStartupRouteInput): StartupRouteDecision {
+19 -54
View File
@@ -1,8 +1,6 @@
import { getHostRuntimeStore } from "@/runtime/host-runtime";
import { useNativeSplashHold } from "@/native-splash";
import { Button } from "@/components/ui/button";
import { LoadingSpinner } from "@/components/ui/loading-spinner";
import { LoadingState } from "@/components/ui/loading-state";
import type { DaemonClient } from "@getpaseo/client/internal/daemon-client";
import type { TFunction } from "i18next";
import { SquarePen } from "lucide-react-native";
@@ -99,7 +97,6 @@ import { ParentAgentCallout, useParentAgentId } from "@/subagents/parent";
import { useCreateFlowStore } from "@/stores/create-flow-store";
import { buildDraftStoreKey, generateDraftId } from "@/stores/draft-keys";
import {
selectAgentLoadingWait,
selectAgentTimelineState,
selectAgentTimelineTurnPresentation,
type Agent,
@@ -245,7 +242,6 @@ function AgentLoadErrorView({ message, onRetry }: { message: string; onRetry: ()
/** A draft has no agent to wait for; an agent shows its loading and error states until ready. */
function renderConversationNonReadyView(args: {
serverId: string;
draft: DraftConversation | null;
agentId: string | undefined;
cwd: string | null;
@@ -257,25 +253,23 @@ function renderConversationNonReadyView(args: {
if (args.draft) {
return null;
}
invariant(args.agentId, "agent id is defined when the conversation is not a draft");
const nonReadyView = renderChatAgentNonReadyView({ ...args, agentId: args.agentId });
const nonReadyView = renderChatAgentNonReadyView(args);
if (nonReadyView) {
return nonReadyView;
}
invariant(args.agentId, "agent id is defined when agent content is ready");
invariant(args.effectiveAgent, "effectiveAgent is defined when the non-ready view is absent");
invariant(args.cwd, "agent cwd is defined when agent content is ready");
return null;
}
function renderChatAgentNonReadyView(args: {
serverId: string;
agentId: string;
viewState: AgentScreenViewState;
effectiveAgent: AgentScreenAgent | null;
t: TFunction;
onRetryLoad: () => void;
}): React.ReactElement | null {
const { serverId, agentId, viewState, effectiveAgent, t, onRetryLoad } = args;
const { viewState, effectiveAgent, t, onRetryLoad } = args;
if (viewState.tag === "not_found") {
return (
<View style={styles.container} testID="agent-not-found">
@@ -289,7 +283,13 @@ function renderChatAgentNonReadyView(args: {
return <AgentLoadErrorView message={viewState.message} onRetry={onRetryLoad} />;
}
if (viewState.tag === "boot" || !effectiveAgent) {
return <AgentLoadingView serverId={serverId} agentId={agentId} />;
return (
<View style={styles.container} testID="agent-loading">
<View style={styles.errorContainer}>
<ThemedLoadingSpinner size="large" uniProps={foregroundMutedColorMapping} />
</View>
</View>
);
}
return null;
}
@@ -647,7 +647,13 @@ function AgentPanelBody({
: null;
if (target.kind === "agent" && !agent) {
return <AgentLoadingView serverId={serverId} agentId={target.agentId} />;
return (
<View style={styles.container} testID="agent-loading">
<View style={styles.errorContainer}>
<ThemedLoadingSpinner size="large" uniProps={foregroundMutedColorMapping} />
</View>
</View>
);
}
return (
@@ -663,46 +669,6 @@ function AgentPanelBody({
);
}
/**
* The pane's loading state, for its agent or the agent's history. A visible pane keeps the launch
* splash up while the cache can still answer; after that it says what the host has yet to send.
*/
function AgentLoadingState({
serverId,
agentId,
testID,
}: {
serverId: string;
agentId: string;
testID: string;
}) {
const { t } = useTranslation();
const isPaneVisible = useRetainedPanelActive();
const wait = useSessionStore(
useShallow((state) => selectAgentLoadingWait(state.sessions[serverId], agentId)),
);
useNativeSplashHold(isPaneVisible && wait.source === "cache");
if (wait.source === "cache") return <LoadingState testID={testID} />;
return (
<LoadingState
testID={testID}
title={
wait.waitingFor === "agent"
? t("agentPanel.states.loadingAgent")
: t("agentPanel.states.loadingHistory")
}
/>
);
}
function AgentLoadingView(props: { serverId: string; agentId: string }) {
return (
<View style={styles.container}>
<AgentLoadingState {...props} testID="agent-loading" />
</View>
);
}
function ChatAgentContent({
serverId,
workspaceId,
@@ -1037,7 +1003,6 @@ function ChatAgentContent({
[tabId, target, workspaceId],
);
const nonReadyView = renderConversationNonReadyView({
serverId,
draft,
agentId,
cwd: agentState.cwd,
@@ -1312,8 +1277,8 @@ const ChatAgentReadyContent = memo(function ChatAgentReadyContent({
const dockOverlay = (
<>
{showHistorySyncOverlay ? (
<View style={styles.historySyncOverlay}>
<AgentLoadingState serverId={serverId} agentId={agentId} testID="agent-history-overlay" />
<View style={styles.historySyncOverlay} testID="agent-history-overlay">
<ThemedLoadingSpinner size="large" uniProps={foregroundMutedColorMapping} />
</View>
) : null}
@@ -1,6 +1,7 @@
import React, { Component, type ErrorInfo, type ReactNode } from "react";
import type { ReactNode } from "react";
import { Text } from "react-native";
import { StyleSheet } from "react-native-unistyles";
import { RenderErrorBoundary } from "@/components/render-error-boundary";
interface SurfaceErrorBoundaryProps {
children: ReactNode;
@@ -10,42 +11,30 @@ interface SurfaceErrorBoundaryProps {
renderError?(error: string): ReactNode;
}
interface SurfaceErrorBoundaryState {
error: string | null;
export function SurfaceErrorBoundary({
children,
installation,
resetKey,
Surface,
renderError,
}: SurfaceErrorBoundaryProps) {
return (
<RenderErrorBoundary
resetKeys={[installation, resetKey, Surface]}
onError={warnSurfaceRenderFailed}
renderError={renderError ?? renderPluginFailed}
>
{children}
</RenderErrorBoundary>
);
}
export class SurfaceErrorBoundary extends Component<
SurfaceErrorBoundaryProps,
SurfaceErrorBoundaryState
> {
state: SurfaceErrorBoundaryState = { error: null };
function renderPluginFailed(error: string) {
return <Text style={styles.errorText}>Plugin failed: {error}</Text>;
}
static getDerivedStateFromError(error: unknown): SurfaceErrorBoundaryState {
return { error: error instanceof Error ? error.message : String(error) };
}
componentDidCatch(error: Error, info: ErrorInfo): void {
console.warn("[Plugins] Surface render failed", error, info.componentStack);
}
componentDidUpdate(previous: SurfaceErrorBoundaryProps): void {
if (
this.state.error &&
(previous.installation !== this.props.installation ||
previous.resetKey !== this.props.resetKey ||
previous.Surface !== this.props.Surface)
) {
this.setState({ error: null });
}
}
render() {
if (this.state.error) {
if (this.props.renderError) return this.props.renderError(this.state.error);
return <Text style={styles.errorText}>Plugin failed: {this.state.error}</Text>;
}
return this.props.children;
}
function warnSurfaceRenderFailed(error: unknown, componentStack: string | null | undefined): void {
console.warn("[Plugins] Surface render failed", error, componentStack);
}
const styles = StyleSheet.create((theme) => ({
@@ -15,7 +15,6 @@ import { SettingsRow, SettingsSection } from "@/components/settings";
import { Button } from "@/components/ui/button";
import { CheckboxRow } from "@/components/ui/checkbox";
import { bySizing, TOUCH_TARGET } from "@/components/ui/control-geometry";
import { IndependentScrollBoundary } from "@/components/ui/independent-scroll-boundary";
import { ToolbarButton, paneContentToolbarIconSize } from "@/components/ui/pane-content-toolbar";
import { SearchField } from "@/components/ui/search-field";
import { useIsCompactFormFactor } from "@/constants/layout";
@@ -233,16 +232,14 @@ export function ProviderModels({
/>
) : null}
{/* A provider can report hundreds of models; the rest of the page stays in reach. */}
<IndependentScrollBoundary activateOnStart={false}>
<ScrollView
// Android scrolls a ScrollView nested in the page or the sheet only with this flag.
nestedScrollEnabled
style={[styles.discoveredList, curating && settingsStyles.rowBorder]}
testID="provider-discovered-models"
>
{discoveredBody}
</ScrollView>
</IndependentScrollBoundary>
<ScrollView
// Android scrolls a ScrollView nested in the page or the sheet only with this flag.
nestedScrollEnabled
style={[styles.discoveredList, curating && settingsStyles.rowBorder]}
testID="provider-discovered-models"
>
{discoveredBody}
</ScrollView>
</View>
</SettingsSection>
) : null}
@@ -294,75 +294,6 @@ afterEach(() => {
});
describe("DirectorySync session readiness", () => {
function createCachedDirectory(
serverId: string,
readDirectory: DirectoryCheckpointStorage["readDirectory"] | null,
): DirectorySync {
serverIds.add(serverId);
const directory = new DirectorySync(
serverId,
{
onAgentStoppedRunning: () => undefined,
markAgentLoading: () => undefined,
markAgentReady: () => undefined,
markAgentError: () => undefined,
},
readDirectory
? {
readAgent: async () => undefined,
readWorkspace: async () => undefined,
readDirectory,
commitDirectoryMutations: () => undefined,
}
: undefined,
);
useSessionStore.getState().initializeSession(serverId, null, 0);
return directory;
}
const hasRestoredCachedDirectory = (serverId: string) =>
useSessionStore.getState().sessions[serverId]?.hasRestoredCachedDirectory;
it("records the cached directory as restored once its read settles, even when it is empty", async () => {
let finishRead: (
value: Awaited<ReturnType<DirectoryCheckpointStorage["readDirectory"]>>,
) => void = () => undefined;
const read = new Promise<Awaited<ReturnType<DirectoryCheckpointStorage["readDirectory"]>>>(
(resolve) => {
finishRead = resolve;
},
);
const directory = createCachedDirectory("restoring-empty-cache", () => read);
const restored = directory.restoreCachedDirectory();
expect(hasRestoredCachedDirectory("restoring-empty-cache")).toBe(false);
finishRead({ agents: new Map(), workspaces: new Map(), projects: new Map() });
await restored;
expect(hasRestoredCachedDirectory("restoring-empty-cache")).toBe(true);
directory.dispose();
});
it("records the cached directory as restored when its read fails", async () => {
const directory = createCachedDirectory("failed-cache-read", async () => {
throw new Error("storage unavailable");
});
await directory.restoreCachedDirectory().catch(() => undefined);
expect(hasRestoredCachedDirectory("failed-cache-read")).toBe(true);
directory.dispose();
});
it("records a host without cache storage as restored", async () => {
const directory = createCachedDirectory("no-cache-storage", null);
await directory.restoreCachedDirectory();
expect(hasRestoredCachedDirectory("no-cache-storage")).toBe(true);
directory.dispose();
});
it("restores the cached directory before network demand", async () => {
const serverId = "offline-cached-directory";
serverIds.add(serverId);
@@ -538,10 +538,7 @@ export class DirectorySync {
private loadCachedDirectory(): Promise<void> {
const checkpoints = this.checkpoints;
if (!checkpoints) {
useSessionStore.getState().markCachedDirectoryRestored(this.serverId);
return Promise.resolve();
}
if (!checkpoints) return Promise.resolve();
this.cacheLoad ??= (async () => {
const revision = this.revision;
const cached = await checkpoints.readDirectory(this.serverId);
@@ -552,7 +549,7 @@ export class DirectorySync {
this.workspaces.commitCached(cached);
if (this.revision === revision) this.cursors = cached.checkpoint ?? {};
this.cacheAccepted = true;
})().finally(() => useSessionStore.getState().markCachedDirectoryRestored(this.serverId));
})();
return this.cacheLoad;
}
@@ -3264,48 +3264,6 @@ describe("HostRuntimeStore", () => {
session.clearSession(host.serverId);
});
// A route waits on the cache until the host's cached directory is restored, so every host
// restores it, not only the hosts in the registry at launch.
it("restores the cached directory of a host added after the registry loaded", async () => {
const host = makeHost();
const storage = createMemoryHostRuntimeStorage({ "@paseo:e2e": "1" });
let fullScans = 0;
const backingStore = createMemoryReplicaRowStore();
const replicaRowStore: ReplicaRowStore = {
...backingStore,
read: async (...args) => {
fullScans += 1;
return backingStore.read(...args);
},
};
const store = new HostRuntimeStore({
storage,
replicaRowStore,
deps: {
createClient: () => new FakeDaemonClient() as unknown as DaemonClient,
connectToDaemon: async () => {
throw new Error("unreachable");
},
getClientId: async () => "cid_test_runtime",
},
});
const registryLoaded = onceHostListMatches(store, () => store.isHostRegistryLoaded());
store.boot();
await registryLoaded;
store.syncHosts([host]);
await vi.waitFor(() =>
expect(useSessionStore.getState().sessions[host.serverId]?.hasRestoredCachedDirectory).toBe(
true,
),
);
expect(fullScans).toBe(1);
store.syncHosts([]);
useSessionStore.getState().clearSession(host.serverId);
});
it("loads the directory for a consumer that sees a restored host before the registry finishes loading", async () => {
const host = makeHost({
connections: [{ id: "direct:lan:6767", type: "directTcp", endpoint: "lan:6767" }],
+44 -30
View File
@@ -2034,6 +2034,12 @@ export class HostRuntimeStore {
projectIconCache.setHosts(profiles.map((profile) => profile.serverId));
await projectIconCache.restore();
this.setHostsAndSync(profiles);
for (const profile of profiles) {
void this.directorySyncByServer
.get(profile.serverId)
?.restoreCachedDirectory()
.catch(() => undefined);
}
} catch (error) {
console.error("[HostRuntime] Failed to load host registry from storage", error);
} finally {
@@ -2151,34 +2157,6 @@ export class HostRuntimeStore {
}
}
/**
* Creates the host's directory and timeline replicas and restores its cached directory, so a
* route waiting on the cache always gets an answer.
*/
private startDirectory(serverId: string, controller: HostRuntimeController): DirectorySync {
const directory = new DirectorySync(
serverId,
{
onAgentStoppedRunning: (agentId) => this.drainQueuedAgentMessage(serverId, agentId),
markAgentLoading: () => controller.markAgentDirectorySyncLoading(),
markAgentReady: () => controller.markAgentDirectorySyncReady(),
markAgentError: (error) => controller.markAgentDirectorySyncError(error),
},
this.replicaCache,
);
this.directorySyncByServer.set(serverId, directory);
this.timelineReplicaByServer.set(
serverId,
createTimelineReplica({
serverId,
storage: this.replicaCache,
prepareAgent: (agentId) => directory.prepareAgentRoute(agentId),
}),
);
void directory.restoreCachedDirectory().catch(() => undefined);
return directory;
}
reconcileServerId(oldServerId: string, newServerId: string): void {
if (oldServerId === newServerId) {
return;
@@ -2200,7 +2178,25 @@ export class HostRuntimeStore {
this.directorySyncByServer.get(oldServerId)?.dispose();
this.directorySyncByServer.delete(oldServerId);
this.timelineReplicaByServer.delete(oldServerId);
const directory = this.startDirectory(newServerId, controller);
const directory = new DirectorySync(
newServerId,
{
onAgentStoppedRunning: (agentId) => this.drainQueuedAgentMessage(newServerId, agentId),
markAgentLoading: () => controller.markAgentDirectorySyncLoading(),
markAgentReady: () => controller.markAgentDirectorySyncReady(),
markAgentError: (error) => controller.markAgentDirectorySyncError(error),
},
this.replicaCache,
);
this.directorySyncByServer.set(newServerId, directory);
this.timelineReplicaByServer.set(
newServerId,
createTimelineReplica({
serverId: newServerId,
storage: this.replicaCache,
prepareAgent: (agentId) => directory.prepareAgentRoute(agentId),
}),
);
controller.adoptReconciledServerId(newServerId);
const snapshot = controller.getSnapshot();
this.clearHostReplica(oldServerId);
@@ -2718,7 +2714,25 @@ export class HostRuntimeStore {
});
this.controllers.set(host.serverId, controller);
useSessionStore.getState().initializeSession(host.serverId, null);
this.startDirectory(host.serverId, controller);
const directory = new DirectorySync(
host.serverId,
{
onAgentStoppedRunning: (agentId) => this.drainQueuedAgentMessage(host.serverId, agentId),
markAgentLoading: () => controller.markAgentDirectorySyncLoading(),
markAgentReady: () => controller.markAgentDirectorySyncReady(),
markAgentError: (error) => controller.markAgentDirectorySyncError(error),
},
this.replicaCache,
);
this.directorySyncByServer.set(host.serverId, directory);
this.timelineReplicaByServer.set(
host.serverId,
createTimelineReplica({
serverId: host.serverId,
storage: this.replicaCache,
prepareAgent: (agentId) => directory.prepareAgentRoute(agentId),
}),
);
const initialSnapshot = controller.getSnapshot();
this.lastConnectionStatusByServer.set(host.serverId, initialSnapshot.connectionStatus);
if (initialSnapshot.connectionStatus === "online") {
@@ -1,7 +1,6 @@
import type { ScheduleSummary } from "@getpaseo/protocol/schedule/types";
import { describe, expect, it } from "vitest";
import {
ALL_SCHEDULE_HOSTS_FAILED_MESSAGE,
fetchAggregatedSchedules,
type ScheduleRuntime,
type ScheduleRuntimeSnapshot,
@@ -29,8 +28,6 @@ function makeSchedule(overrides: Partial<ScheduleSummary> = {}): ScheduleSummary
function makeRuntime(input: {
snapshots: Record<string, ScheduleRuntimeSnapshot | null>;
schedules?: Record<string, ScheduleSummary[]>;
errors?: Record<string, string>;
beforeResponse?: () => Promise<void>;
}): ScheduleRuntime {
return {
getSnapshot: (serverId) => input.snapshots[serverId] ?? null,
@@ -40,31 +37,12 @@ function makeRuntime(input: {
return null;
}
return {
scheduleList: async () => {
await input.beforeResponse?.();
return { requestId: "test-request", schedules, error: input.errors?.[serverId] ?? null };
},
scheduleList: async () => ({ requestId: "test-request", schedules, error: null }),
};
},
};
}
function makeTransitionRuntime(initial: string, next: string, schedule: ScheduleSummary) {
const snapshots: Record<string, ScheduleRuntimeSnapshot> = {
"host-a": { connectionStatus: "online" },
"host-b": { connectionStatus: initial },
};
return makeRuntime({
snapshots,
schedules: { "host-a": [], "host-b": [schedule] },
beforeResponse: async () => {
// Both hosts have been considered before the first response arrives.
await Promise.resolve();
snapshots["host-b"] = { connectionStatus: next };
},
});
}
describe("fetchAggregatedSchedules load state", () => {
it("does not report loaded empty while known hosts are still connecting", async () => {
const result = await fetchAggregatedSchedules({
@@ -102,10 +80,10 @@ describe("fetchAggregatedSchedules load state", () => {
}),
});
expect(result).toEqual({ status: "loaded", data: [], hostWarnings: [] });
expect(result).toEqual({ status: "loaded", data: [], hostErrors: [] });
});
it("shows the empty result with a warning while another host is connecting", async () => {
it("does not report loaded empty while another known host is still connecting", async () => {
const result = await fetchAggregatedSchedules({
hosts: [
{ serverId: "host-a", serverName: "Host A" },
@@ -122,62 +100,7 @@ describe("fetchAggregatedSchedules load state", () => {
}),
});
expect(result).toEqual({
status: "loaded",
data: [],
hostWarnings: [
{
serverId: "host-b",
serverName: "Host B",
reason: "connecting",
},
],
});
});
it.each([
{ initial: "connecting", next: "online", includedHosts: [], missingHosts: ["host-b"] },
{ initial: "online", next: "connecting", includedHosts: ["host-b"], missingHosts: [] },
])(
"keeps warnings consistent when a host changes from $initial to $next",
async ({ initial, next, includedHosts, missingHosts }) => {
const schedule = makeSchedule();
const result = await fetchAggregatedSchedules({
hosts: [
{ serverId: "host-a", serverName: "Host A" },
{ serverId: "host-b", serverName: "Host B" },
],
runtime: makeTransitionRuntime(initial, next, schedule),
});
expect(result).toEqual({
status: "loaded",
data: includedHosts.map((serverId) => ({ ...schedule, serverId, serverName: "Host B" })),
hostWarnings: missingHosts.map((serverId) => ({
serverId,
serverName: "Host B",
reason: "connecting",
})),
});
},
);
it("keeps the error state when the only connected host fails", async () => {
await expect(
fetchAggregatedSchedules({
hosts: [
{ serverId: "host-a", serverName: "Host A" },
{ serverId: "host-b", serverName: "Host B" },
],
runtime: makeRuntime({
snapshots: {
"host-a": { connectionStatus: "online" },
"host-b": { connectionStatus: "connecting" },
},
schedules: { "host-a": [] },
errors: { "host-a": "Schedule storage unavailable" },
}),
}),
).rejects.toThrow(ALL_SCHEDULE_HOSTS_FAILED_MESSAGE);
expect(result).toEqual({ status: "connecting" });
});
it("loads reachable host data when another known host is still connecting", async () => {
@@ -201,13 +124,7 @@ describe("fetchAggregatedSchedules load state", () => {
expect(result).toEqual({
status: "loaded",
data: [{ ...schedule, serverId: "host-a", serverName: "Host A" }],
hostWarnings: [
{
serverId: "host-b",
serverName: "Host B",
reason: "connecting",
},
],
hostErrors: [],
});
});
});
@@ -1,5 +1,6 @@
import type { DaemonClient } from "@getpaseo/client/internal/daemon-client";
import type { ScheduleSummary } from "@getpaseo/protocol/schedule/types";
import { toErrorMessage } from "@/utils/error-messages";
export const schedulesQueryBaseKey = ["schedules"] as const;
@@ -26,8 +27,10 @@ export interface AggregatedSchedule extends ScheduleSummary {
serverName: string;
}
export interface ScheduleHostWarning extends ScheduleHostInput {
reason: "connecting" | "request-failed";
export interface ScheduleHostError {
serverId: string;
serverName: string;
message: string;
}
export interface FetchAggregatedSchedulesConnectingResult {
@@ -37,7 +40,7 @@ export interface FetchAggregatedSchedulesConnectingResult {
export interface FetchAggregatedSchedulesResult {
status: "loaded";
data: AggregatedSchedule[];
hostWarnings: ScheduleHostWarning[];
hostErrors: ScheduleHostError[];
}
export type FetchAggregatedSchedulesState =
@@ -59,9 +62,9 @@ export interface FetchAggregatedSchedulesInput {
* Connectivity is checked here at execution time, so explicit query refreshes
* pick up the currently connected host set.
*
* Offline hosts are skipped. Hosts that are still connecting or fail to load
* schedules contribute warnings. If every request fails, the screen shows
* a full error instead.
* Offline hosts are skipped. A connected host that fails contributes to
* `hostErrors` (surfaced as a banner) while the rest still render; only when
* every connected host fails do we throw so the screen shows a full error.
*/
export async function fetchAggregatedSchedules(
input: FetchAggregatedSchedulesInput,
@@ -79,9 +82,8 @@ export async function fetchAggregatedSchedules(
}
const schedules: AggregatedSchedule[] = [];
const hostWarnings: ScheduleHostWarning[] = [];
const hostErrors: ScheduleHostError[] = [];
let connectedAttempts = 0;
let failedAttempts = 0;
await Promise.all(
input.hosts.map(async (host) => {
@@ -89,9 +91,6 @@ export async function fetchAggregatedSchedules(
const isOnline = snapshot?.connectionStatus === "online";
const client = input.runtime.getClient(host.serverId);
if (!client || !isOnline) {
if (isScheduleHostConnectionSettling(snapshot)) {
hostWarnings.push({ ...host, reason: "connecting" });
}
return;
}
connectedAttempts += 1;
@@ -103,18 +102,25 @@ export async function fetchAggregatedSchedules(
for (const schedule of payload.schedules) {
schedules.push({ ...schedule, serverId: host.serverId, serverName: host.serverName });
}
} catch {
failedAttempts += 1;
hostWarnings.push({ ...host, reason: "request-failed" });
} catch (error) {
hostErrors.push({
serverId: host.serverId,
serverName: host.serverName,
message: toErrorMessage(error),
});
}
}),
);
if (connectedAttempts > 0 && failedAttempts === connectedAttempts) {
if (connectedAttempts > 0 && schedules.length === 0 && hostErrors.length === connectedAttempts) {
throw new Error(ALL_SCHEDULE_HOSTS_FAILED_MESSAGE);
}
return { status: "loaded", data: schedules, hostWarnings };
if (schedules.length === 0 && hasSettlingHost) {
return { status: "connecting" };
}
return { status: "loaded", data: schedules, hostErrors };
}
function isScheduleHostConnectionSettling(
+11 -15
View File
@@ -25,7 +25,7 @@ import {
useSchedules,
type AggregateLoadState,
type AggregatedSchedule,
type ScheduleHostWarning,
type ScheduleHostError,
} from "@/hooks/use-schedules";
import { getHostRuntimeStore, useHosts } from "@/runtime/host-runtime";
import {
@@ -63,7 +63,7 @@ export function SchedulesScreen(): ReactElement {
}
function SchedulesScreenContent(): ReactElement {
const { loadState, hostWarnings, isError, refetch } = useSchedules();
const { loadState, hostErrors, isError, refetch } = useSchedules();
const schedules = loadState.status === "loaded" ? loadState.data : EMPTY_SCHEDULES;
const { agents } = useAggregatedAgents({ includeArchived: true });
const { projects } = useProjects();
@@ -169,7 +169,7 @@ function SchedulesScreenContent(): ReactElement {
<SchedulesScreenBody
rows={visibleRows}
loadState={loadState}
hostWarnings={hostWarnings}
hostErrors={hostErrors}
showLoadError={showLoadError}
statusFilter={statusFilter}
onStatusFilterChange={setStatusFilter}
@@ -195,7 +195,7 @@ function SchedulesScreenContent(): ReactElement {
function SchedulesScreenBody({
rows,
loadState,
hostWarnings,
hostErrors,
showLoadError,
statusFilter,
onStatusFilterChange,
@@ -209,7 +209,7 @@ function SchedulesScreenBody({
}: {
rows: ScheduleRowView[];
loadState: AggregateLoadState<AggregatedSchedule>;
hostWarnings: ScheduleHostWarning[];
hostErrors: ScheduleHostError[];
showLoadError: boolean;
statusFilter: ScheduleBucket;
onStatusFilterChange: (value: ScheduleBucket) => void;
@@ -245,7 +245,7 @@ function SchedulesScreenBody({
if (bodyState.kind === "empty") {
return (
<View style={styles.centered}>
{hostWarnings.length > 0 ? <ScheduleHostWarningsBanner warnings={hostWarnings} /> : null}
{hostErrors.length > 0 ? <ScheduleHostErrorsBanner errors={hostErrors} /> : null}
<SchedulesEmptyState onCreate={onCreate} testID="schedules-empty" />
</View>
);
@@ -294,7 +294,7 @@ function SchedulesScreenBody({
keyboardShouldPersistTaps="handled"
testID="schedules-list"
>
{hostWarnings.length > 0 ? <ScheduleHostWarningsBanner warnings={hostWarnings} /> : null}
{hostErrors.length > 0 ? <ScheduleHostErrorsBanner errors={hostErrors} /> : null}
{schedulesContent}
</ScrollView>
</View>
@@ -334,17 +334,13 @@ function SchedulesEndedEmptyState(): ReactElement {
);
}
function ScheduleHostWarningsBanner({
warnings,
}: {
warnings: ScheduleHostWarning[];
}): ReactElement {
function ScheduleHostErrorsBanner({ errors }: { errors: ScheduleHostError[] }): ReactElement {
return (
<View style={styles.errorsBannerWrap}>
<View style={styles.errorsBanner} testID="schedules-host-errors">
{warnings.map((warning) => (
<Text key={warning.serverId} style={styles.errorsBannerText}>
{`${warning.serverName}: ${warning.reason === "connecting" ? "Still connecting" : "Could not load schedules"}`}
{errors.map((error) => (
<Text key={error.serverId} style={styles.errorsBannerText}>
{`${error.serverName}: Could not load schedules`}
</Text>
))}
</View>
@@ -20,7 +20,6 @@ import { Button } from "@/components/ui/button";
import { getDesktopDaemonLogs, type DesktopDaemonLogs } from "@/desktop/daemon/desktop-daemon";
import { TitlebarDragRegion } from "@/components/desktop/titlebar-drag-region";
import { isNative, isWeb } from "@/constants/platform";
import { useNativeSplashHold } from "@/native-splash";
import { CODE_SURFACE_DATASET } from "@/styles/code-surface";
interface StartupSplashScreenProps {
@@ -33,9 +32,7 @@ interface StartupSplashScreenProps {
const GITHUB_ISSUE_URL = "https://github.com/getpaseo/paseo/issues/new";
const DOCS_URL = "https://paseo.sh/docs";
// On native this screen sits under the launch splash and takes over when it fades, so its logo
// matches the launch logo: 135dp wide, which the glyph reaches at this SVG size.
const LOGO_SIZE = isNative ? 182 : 96;
const LOGO_SIZE = 96;
const SHIMMER_PEAK_WIDTH = 120;
const SHIMMER_DURATION_MS = 1800;
@@ -276,10 +273,6 @@ const styles = StyleSheet.create((theme) => ({
gap: theme.spacing[3],
flexWrap: "wrap",
},
logo: {
// Optical: the glyph sits right of the SVG's centre. The launch splash centres the glyph.
transform: [{ translateX: isNative ? -4 : 0 }],
},
shimmerMask: {
width: LOGO_SIZE,
height: LOGO_SIZE,
@@ -311,7 +304,6 @@ export function StartupSplashScreen({ bootstrapState }: StartupSplashScreenProps
const [isLoadingLogs, setIsLoadingLogs] = useState(false);
const isError = bootstrapState !== undefined && bootstrapState.splashError !== null;
useNativeSplashHold(!isError);
useEffect(() => {
if (!isError) {
@@ -393,9 +385,7 @@ export function StartupSplashScreen({ bootstrapState }: StartupSplashScreenProps
return (
<View testID="startup-splash" style={styles.container}>
<TitlebarDragRegion />
<View style={styles.logo}>
<LogoShimmer />
</View>
<LogoShimmer />
</View>
);
}
@@ -0,0 +1,131 @@
/**
* @vitest-environment jsdom
*/
import { act } from "@testing-library/react";
import React from "react";
import { createRoot, type Root } from "react-dom/client";
import { Text, View } from "react-native";
import { afterEach, describe, expect, it, vi } from "vitest";
import { definePanel, registerPanel } from "@/panels/panel-registry";
import { buildWorkspacePaneContentModel } from "@/screens/workspace/workspace-pane-content";
import { WorkspacePanelHost } from "@/screens/workspace/workspace-panel-host";
import type { WorkspaceTabDescriptor } from "@/screens/workspace/workspace-tabs-types";
let panelFails = true;
function FailingPanel() {
if (panelFails) throw new Error("Changes exploded");
return <Text>Changes recovered</Text>;
}
function HealthyPanel() {
return <Text>Draft panel</Text>;
}
// The workspace screen registers the real panels; these stand in for the two kinds the test opens.
registerPanel(
definePanel("agent", {
component: FailingPanel,
useDescriptor: () => {
throw new Error("The test panel has no descriptor");
},
}),
);
registerPanel(
definePanel("draft", {
component: HealthyPanel,
useDescriptor: () => {
throw new Error("The test panel has no descriptor");
},
}),
);
const failingTab: WorkspaceTabDescriptor = {
key: "agent_agent-a",
tabId: "agent_agent-a",
kind: "agent",
target: { kind: "agent", agentId: "agent-a" },
};
const healthyTab: WorkspaceTabDescriptor = {
key: "draft_draft-a",
tabId: "draft_draft-a",
kind: "draft",
target: { kind: "draft", draftId: "draft-a" },
};
function buildContent({ tab }: { paneId: string; tab: WorkspaceTabDescriptor }) {
return buildWorkspacePaneContentModel({
tab,
normalizedServerId: "server-a",
normalizedWorkspaceId: "workspace-a",
host: "main",
onOpenTab: vi.fn(),
onOpenPreferredTarget: vi.fn(),
onOpenTargetToSide: vi.fn(),
onCloseCurrentTab: vi.fn(),
onRetargetCurrentTab: vi.fn(),
onSetCurrentTabState: vi.fn(),
onOpenWorkspaceFile: vi.fn(),
onOpenImportSheet: vi.fn(),
});
}
function Workspace({ activeTabId }: { activeTabId: string }) {
return (
<View>
<Text>Sidebar</Text>
<WorkspacePanelHost
paneId="pane-a"
tabs={[failingTab, healthyTab]}
activeTabId={activeTabId}
normalizedServerId="server-a"
normalizedWorkspaceId="workspace-a"
isWorkspaceFocused
isPaneFocused
buildPaneContentModel={buildContent}
/>
</View>
);
}
function byTestId(container: HTMLElement, testID: string): HTMLElement | null {
return container.querySelector(`[data-testid="${testID}"]`);
}
describe("WorkspacePanelHost", () => {
let root: Root | null = null;
let container: HTMLElement | null = null;
afterEach(() => {
if (root) act(() => root?.unmount());
root = null;
container?.remove();
container = null;
panelFails = true;
vi.restoreAllMocks();
});
it("keeps a panel's render error inside that panel and retries it", () => {
vi.spyOn(console, "error").mockImplementation(() => undefined);
vi.spyOn(console, "warn").mockImplementation(() => undefined);
container = document.createElement("div");
document.body.appendChild(container);
root = createRoot(container);
act(() => root?.render(<Workspace activeTabId={failingTab.tabId} />));
expect(container.textContent).toContain("Sidebar");
expect(byTestId(container, "panel-render-error")?.textContent).toContain("Changes exploded");
act(() => root?.render(<Workspace activeTabId={healthyTab.tabId} />));
expect(container.textContent).toContain("Draft panel");
panelFails = false;
act(() => root?.render(<Workspace activeTabId={failingTab.tabId} />));
const retry = byTestId(container, "panel-render-error-retry");
expect(retry).not.toBeNull();
act(() => retry?.click());
expect(byTestId(container, "panel-render-error")).toBeNull();
expect(container.textContent).toContain("Changes recovered");
expect(container.textContent).toContain("Sidebar");
});
});
@@ -1,5 +1,11 @@
import { memo, useCallback, useEffect, useMemo, useRef } from "react";
import { useTranslation } from "react-i18next";
import { View } from "react-native";
import { StyleSheet } from "react-native-unistyles";
import { RenderErrorBoundary } from "@/components/render-error-boundary";
import { RetainedPanel } from "@/components/retained-panel";
import { Alert } from "@/components/ui/alert";
import { Button } from "@/components/ui/button";
import { useModifiedPanelTabIds } from "@/panels/panel-instance-attributes";
import {
WorkspacePaneContent,
@@ -52,17 +58,44 @@ const MountedTab = memo(function MountedTab({
return (
<RenderProfile id={`DesktopMountedTab:${tab.kind}:${tab.tabId}`}>
<RetainedPanel active={visible}>
<WorkspacePaneContent
content={content}
isWorkspaceFocused={isWorkspaceFocused}
isPaneFocused={interactive}
onFocusPane={onFocusPane ? handleFocusPane : undefined}
/>
<RenderErrorBoundary
resetKeys={[tab]}
onError={logPanelRenderError}
renderError={renderPanelError}
>
<WorkspacePaneContent
content={content}
isWorkspaceFocused={isWorkspaceFocused}
isPaneFocused={interactive}
onFocusPane={onFocusPane ? handleFocusPane : undefined}
/>
</RenderErrorBoundary>
</RetainedPanel>
</RenderProfile>
);
});
function logPanelRenderError(error: unknown, componentStack: string | null | undefined): void {
console.error("[WorkspacePanel] Render failed", error, componentStack);
}
function renderPanelError(error: string, retry: () => void) {
return <PanelRenderError error={error} onRetry={retry} />;
}
function PanelRenderError({ error, onRetry }: { error: string; onRetry: () => void }) {
const { t } = useTranslation();
return (
<View style={styles.renderError} testID="panel-render-error">
<Alert variant="error" title={t("panels.renderError.title")} description={error}>
<Button variant="outline" size="sm" onPress={onRetry} testID="panel-render-error-retry">
{t("common.actions.retry")}
</Button>
</Alert>
</View>
);
}
function useStableTabs(tabs: WorkspaceTabDescriptor[]) {
const cacheRef = useRef(new Map<string, WorkspaceTabDescriptor>());
const stableTabs = useMemo(() => {
@@ -136,3 +169,9 @@ export function WorkspacePanelHost({
);
});
}
const styles = StyleSheet.create((theme) => ({
renderError: {
padding: theme.spacing[4],
},
}));
@@ -4,14 +4,9 @@ import { useTranslation } from "react-i18next";
import { StyleSheet, withUnistyles } from "react-native-unistyles";
import { Button } from "@/components/ui/button";
import { LoadingSpinner } from "@/components/ui/loading-spinner";
import { LoadingState } from "@/components/ui/loading-state";
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
import { formatConnectionStatus } from "@/utils/daemons";
import { useNativeSplashHold } from "@/native-splash";
import type {
WorkspaceLoadingSource,
WorkspaceRouteState,
} from "@/screens/workspace/workspace-route-state";
import type { WorkspaceRouteState } from "@/screens/workspace/workspace-route-state";
import type { Theme } from "@/styles/theme";
const ThemedLoadingSpinner = withUnistyles(LoadingSpinner);
@@ -33,9 +28,7 @@ export function renderWorkspaceRouteGate(input: {
}): React.ReactNode {
switch (input.state.kind) {
case "loading":
return (
<WorkspaceLoading waitingFor={input.state.waitingFor} hostName={input.state.hostName} />
);
return <WorkspaceConnecting hostName={input.state.hostName} />;
case "missing":
return (
<WorkspaceEmptyState
@@ -93,35 +86,26 @@ function getWorkspaceHostStateTitle(
state: Extract<WorkspaceRouteState, { kind: "unreachable" }>,
t: ReturnType<typeof useTranslation>["t"],
): string {
if (state.connectionStatus === "connecting" || state.connectionStatus === "idle") {
return t("workspace.route.connecting");
}
if (state.connectionStatus === "offline") {
return t("workspace.route.hostOffline", { hostName: state.hostName });
}
return t("workspace.route.cannotReachHost", { hostName: state.hostName });
}
/**
* The one loading state of a workspace, from the route waiting for its workspace to the content
* waiting for its tabs. Each stage puts the same spinner in the same place. The launch splash stays
* up while the cache can still deliver; a wait on the host shows here and says so.
*/
export function WorkspaceLoading({
waitingFor,
hostName,
}: {
waitingFor: WorkspaceLoadingSource;
hostName: string;
}) {
function WorkspaceConnecting({ hostName }: { hostName: string }) {
const { t } = useTranslation();
useNativeSplashHold(waitingFor === "cache");
if (waitingFor === "cache") return <LoadingState testID="workspace-loading" />;
return (
<LoadingState
testID="workspace-loading"
title={
waitingFor === "connection" ? t("workspace.route.connecting") : t("workspace.route.loading")
}
description={hostName}
/>
<View style={styles.emptyState}>
<ThemedLoadingSpinner size="small" uniProps={foregroundMutedColorMapping} />
<View style={styles.textStack}>
<Text style={styles.title}>{t("workspace.route.loading")}</Text>
<Text style={styles.description}>{hostName}</Text>
</View>
</View>
);
}
@@ -229,14 +213,21 @@ function WorkspaceUnreachable({
onManageHost: () => void;
}) {
const { t } = useTranslation();
const canRetry = state.connectionStatus === "offline" || state.connectionStatus === "error";
return (
<View style={styles.emptyState}>
{state.connectionStatus === "connecting" || state.connectionStatus === "idle" ? (
<ThemedLoadingSpinner size="small" uniProps={foregroundMutedColorMapping} />
) : null}
<View style={styles.textStack}>
<Text style={styles.title}>{getWorkspaceHostStateTitle(state, t)}</Text>
<Text style={styles.description}>
{t("workspace.route.hostStatus", {
status: formatConnectionStatus(state.connectionStatus),
})}
{state.connectionStatus === "connecting" || state.connectionStatus === "idle"
? state.hostName
: t("workspace.route.hostStatus", {
status: formatConnectionStatus(state.connectionStatus),
})}
</Text>
{state.lastError ? (
<Tooltip delayDuration={0} enabledOnDesktop enabledOnMobile={false}>
@@ -251,14 +242,16 @@ function WorkspaceUnreachable({
</Tooltip>
) : null}
</View>
<View style={styles.actions}>
<Button variant="default" leftIcon={RotateCw} onPress={onRetry}>
{t("common.actions.retry")}
</Button>
<Button variant="outline" leftIcon={Settings} onPress={onManageHost}>
{t("workspace.route.manageHost")}
</Button>
</View>
{canRetry ? (
<View style={styles.actions}>
<Button variant="default" leftIcon={RotateCw} onPress={onRetry}>
{t("common.actions.retry")}
</Button>
<Button variant="outline" leftIcon={Settings} onPress={onManageHost}>
{t("workspace.route.manageHost")}
</Button>
</View>
) : null}
</View>
);
}
@@ -31,9 +31,8 @@ function createWorkspaceDescriptor(): WorkspaceDescriptor {
function resolve(input: {
workspace?: WorkspaceDescriptor | null;
connectionStatus?: "online" | "offline" | "connecting" | "idle";
connectionStatus?: "online" | "offline";
hasHydratedWorkspaces?: boolean;
hasRestoredCachedDirectory?: boolean;
recovery?: WorkspaceRecoveryModel;
}) {
return resolveWorkspaceRouteState({
@@ -42,7 +41,6 @@ function resolve(input: {
lastError: input.connectionStatus === "offline" ? "transport closed" : null,
workspace: input.workspace ?? null,
hasHydratedWorkspaces: input.hasHydratedWorkspaces ?? true,
hasRestoredCachedDirectory: input.hasRestoredCachedDirectory ?? true,
recovery: input.recovery ?? { kind: "checking" },
});
}
@@ -70,32 +68,6 @@ describe("resolveWorkspaceRouteState", () => {
});
});
// The launch splash covers a wait on the cache, which ends without the host. Once only the
// host can deliver the workspace, the route shows what it is waiting for.
it.each(["online", "connecting", "idle", "offline"] as const)(
"waits on the cache while it can still restore the workspace and the host is %s",
(connectionStatus) => {
expect(
resolve({
connectionStatus,
hasHydratedWorkspaces: false,
hasRestoredCachedDirectory: false,
}),
).toEqual({ kind: "loading", hostName: "Laptop", waitingFor: "cache" });
},
);
it.each(["connecting", "idle"] as const)(
"waits on the connection once the cache has no workspace and the host is %s",
(connectionStatus) => {
expect(resolve({ connectionStatus, hasHydratedWorkspaces: false })).toEqual({
kind: "loading",
hostName: "Laptop",
waitingFor: "connection",
});
},
);
it("keeps a cached workspace visible while its host reconnects", () => {
expect(
resolve({ workspace: createWorkspaceDescriptor(), connectionStatus: "offline" }),
@@ -107,16 +79,14 @@ describe("resolveWorkspaceRouteState", () => {
});
});
it("waits on the host for workspace hydration and authoritative recovery inspection", () => {
it("waits for workspace hydration and authoritative recovery inspection", () => {
expect(resolve({ hasHydratedWorkspaces: false })).toEqual({
kind: "loading",
hostName: "Laptop",
waitingFor: "workspace",
});
expect(resolve({ recovery: { kind: "checking" } })).toEqual({
kind: "loading",
hostName: "Laptop",
waitingFor: "workspace",
});
});
@@ -442,7 +412,7 @@ describe("post-restore handoff state machine", () => {
lastError: "closed",
},
{ kind: "unreachable", hostName: "Laptop", connectionStatus: "offline", lastError: "closed" },
{ kind: "loading", hostName: "Laptop", waitingFor: "workspace" },
{ kind: "loading", hostName: "Laptop" },
{ kind: "missing", hostName: "Laptop" },
{ kind: "recoveryUnavailable", hostName: "Laptop", message: "missing" },
{ kind: "recoveryInspectionFailed", hostName: "Laptop", error: "boom" },
@@ -13,10 +13,10 @@ export type WorkspaceRouteState =
| {
kind: "unreachable";
hostName: string;
connectionStatus: Extract<HostRuntimeConnectionStatus, "offline" | "error">;
connectionStatus: Exclude<HostRuntimeConnectionStatus, "online">;
lastError: string | null;
}
| { kind: "loading"; hostName: string; waitingFor: WorkspaceLoadingSource }
| { kind: "loading"; hostName: string }
| { kind: "missing"; hostName: string }
| { kind: "needsHostUpgrade"; hostName: string }
| {
@@ -27,20 +27,12 @@ export type WorkspaceRouteState =
| { kind: "recoveryUnavailable"; hostName: string; message: string }
| { kind: "recoveryInspectionFailed"; hostName: string; error: string };
/**
* What a missing workspace is waiting on. The local cache answers without the host; "connection"
* and "workspace" wait on the host, first for it to connect, then for it to send the workspace.
*/
export type WorkspaceLoadingSource = "cache" | "connection" | "workspace";
export function resolveWorkspaceRouteState(input: {
hostName: string;
connectionStatus: HostRuntimeConnectionStatus;
lastError: string | null;
workspace: WorkspaceDescriptor | null;
hasHydratedWorkspaces: boolean;
/** The host's cached directory has been read, so a workspace it holds is in the store. */
hasRestoredCachedDirectory: boolean;
recovery: WorkspaceRecoveryModel;
}): WorkspaceRouteState {
if (input.workspace) {
@@ -59,15 +51,6 @@ export function resolveWorkspaceRouteState(input: {
};
}
if (!input.hasRestoredCachedDirectory) {
return { kind: "loading", hostName: input.hostName, waitingFor: "cache" };
}
// A host that is still connecting has not failed yet, so the workspace is still loading.
if (input.connectionStatus === "connecting" || input.connectionStatus === "idle") {
return { kind: "loading", hostName: input.hostName, waitingFor: "connection" };
}
if (input.connectionStatus !== "online") {
return {
kind: "unreachable",
@@ -78,7 +61,7 @@ export function resolveWorkspaceRouteState(input: {
}
if (!input.hasHydratedWorkspaces) {
return { kind: "loading", hostName: input.hostName, waitingFor: "workspace" };
return { kind: "loading", hostName: input.hostName };
}
if (input.recovery.kind === "idle") {
return { kind: "missing", hostName: input.hostName };
@@ -86,7 +69,7 @@ export function resolveWorkspaceRouteState(input: {
switch (input.recovery.kind) {
case "checking":
return { kind: "loading", hostName: input.hostName, waitingFor: "workspace" };
return { kind: "loading", hostName: input.hostName };
case "needsHostUpgrade":
return { kind: "needsHostUpgrade", hostName: input.hostName };
case "recoverable":
@@ -22,6 +22,7 @@ import {
WorkspaceComposerEditingSessionsProvider,
useComposerTabFullscreen,
} from "@/composer/editing-session";
import { LoadingSpinner } from "@/components/ui/loading-spinner";
import { SheetHostScope } from "@/components/ui/isolated-bottom-sheet-modal";
import type { JsonValue } from "@getpaseo/protocol/agent-types";
import { getOpenAgentTabLabel } from "@getpaseo/protocol/agent-labels";
@@ -44,7 +45,8 @@ import { useRouter, type Href } from "expo-router";
import * as Clipboard from "expo-clipboard";
import { useTranslation } from "react-i18next";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { StyleSheet } from "react-native-unistyles";
import { StyleSheet, withUnistyles } from "react-native-unistyles";
import type { Theme } from "@/styles/theme";
import invariant from "tiny-invariant";
import { SidebarMenuToggle } from "@/components/headers/sidebar-menu-toggle";
import { ScreenHeader } from "@/components/headers/screen-header";
@@ -170,10 +172,7 @@ import {
canSyncVisibleAgents,
usePostRestoreWorkspaceRouteState,
} from "@/screens/workspace/use-post-restore-handoff";
import {
renderWorkspaceRouteGate,
WorkspaceLoading,
} from "@/screens/workspace/workspace-route-state-views";
import { renderWorkspaceRouteGate } from "@/screens/workspace/workspace-route-state-views";
import { useWorkspaceRecovery } from "@/workspace-recovery/use-workspace-recovery";
import type { WorkspaceRecoveryModel } from "@/workspace-recovery/model";
import {
@@ -276,6 +275,10 @@ function buildWorkspaceFileLocation(
return { path: fields.path, lineStart: fields.lineStart, lineEnd: fields.lineEnd };
}
const ThemedLoadingSpinner = withUnistyles(LoadingSpinner);
const mutedColorMapping = (theme: Theme) => ({ color: theme.colors.foregroundMuted });
interface WorkspaceScreenProps {
serverId: string;
workspaceId: string;
@@ -553,8 +556,6 @@ function parsePaneDirection(actionId: string): PaneDirection | null {
interface RenderWorkspaceContentInput {
isMissingWorkspaceDirectory: boolean;
activeTabDescriptor: WorkspaceTabDescriptor | null;
hostName: string;
hasHydratedWorkspaceLayoutStore: boolean;
hasHydratedAgents: boolean;
hasLoadedTerminals: boolean;
mountedFocusedPaneTabIds: string[];
@@ -573,8 +574,6 @@ function renderWorkspaceContent(input: RenderWorkspaceContentInput): React.React
const {
isMissingWorkspaceDirectory,
activeTabDescriptor,
hostName,
hasHydratedWorkspaceLayoutStore,
hasHydratedAgents,
hasLoadedTerminals,
mountedFocusedPaneTabIds,
@@ -595,13 +594,12 @@ function renderWorkspaceContent(input: RenderWorkspaceContentInput): React.React
</View>
);
}
// The saved tabs come from local storage. Without them, the tabs wait on the host's agents
// and terminals.
if (!activeTabDescriptor && !hasHydratedWorkspaceLayoutStore) {
return <WorkspaceLoading waitingFor="cache" hostName={hostName} />;
}
if (!activeTabDescriptor && (!hasHydratedAgents || !hasLoadedTerminals)) {
return <WorkspaceLoading waitingFor="workspace" hostName={hostName} />;
return (
<View style={styles.emptyState}>
<ThemedLoadingSpinner uniProps={mutedColorMapping} />
</View>
);
}
if (!activeTabDescriptor) {
return (
@@ -728,44 +726,35 @@ function useWorkspaceRouteActions(normalizedServerId: string): {
};
}
function useWorkspaceHostName(serverId: string): string {
const hosts = useHosts();
const host = useMemo(
() => hosts.find((entry) => entry.serverId === serverId) ?? null,
[hosts, serverId],
);
return useMemo(() => getHostDisplayName(host, serverId), [host, serverId]);
}
function useResolvedWorkspaceRouteState(input: {
serverId: string;
hostName: string;
workspace: WorkspaceDescriptor | null;
hasHydratedWorkspaces: boolean;
recovery: WorkspaceRecoveryModel;
}): WorkspaceRouteState {
const hostSnapshot = useHostRuntimeSnapshot(input.serverId);
const hasRestoredCachedDirectory = useSessionStore(
(state) => state.sessions[input.serverId]?.hasRestoredCachedDirectory ?? false,
const hosts = useHosts();
const host = useMemo(
() => hosts.find((entry) => entry.serverId === input.serverId) ?? null,
[hosts, input.serverId],
);
const hostSnapshot = useHostRuntimeSnapshot(input.serverId);
const hostName = useMemo(() => getHostDisplayName(host, input.serverId), [host, input.serverId]);
return useMemo(
() =>
resolveWorkspaceRouteState({
hostName: input.hostName,
hostName,
connectionStatus: hostSnapshot?.connectionStatus ?? "connecting",
lastError: hostSnapshot?.lastError ?? null,
workspace: input.workspace,
hasHydratedWorkspaces: input.hasHydratedWorkspaces,
hasRestoredCachedDirectory,
recovery: input.recovery,
}),
[
input.hostName,
hostName,
hostSnapshot?.connectionStatus,
hostSnapshot?.lastError,
input.workspace,
input.hasHydratedWorkspaces,
hasRestoredCachedDirectory,
input.recovery,
],
);
@@ -1273,10 +1262,8 @@ function WorkspaceScreenContent({
serverId: normalizedServerId,
workspaceId: normalizedWorkspaceId,
});
const hostName = useWorkspaceHostName(normalizedServerId);
const workspaceRouteState = useResolvedWorkspaceRouteState({
serverId: normalizedServerId,
hostName,
workspace: workspaceDescriptor,
hasHydratedWorkspaces,
recovery: workspaceRecovery.state,
@@ -3157,8 +3144,6 @@ function WorkspaceScreenContent({
const content = renderWorkspaceContent({
isMissingWorkspaceDirectory,
activeTabDescriptor,
hostName,
hasHydratedWorkspaceLayoutStore,
hasHydratedAgents,
hasLoadedTerminals: terminalsQuery.isSuccess,
mountedFocusedPaneTabIds,
@@ -5,7 +5,6 @@ import type { WorkspaceDescriptorPayload } from "@getpaseo/protocol/messages";
import {
normalizeWorkspaceDescriptor,
selectAgentLoadingWait,
selectAgentSentMessages,
selectAgentTurnPresentation,
selectAgentTimelineState,
@@ -315,44 +314,6 @@ describe("agent timeline state", () => {
});
});
describe("what a loading agent pane waits on", () => {
const session = () => useSessionStore.getState().sessions["test-server"];
const wait = (agentId = "agent-1") => selectAgentLoadingWait(session(), agentId);
it("waits on the cache for an agent until the cached directory is read", () => {
initializeTestSession();
expect(wait()).toEqual({ waitingFor: "agent", source: "cache" });
});
it("waits on the host for an agent the cached directory did not have", () => {
initializeTestSession();
useSessionStore.getState().markCachedDirectoryRestored("test-server");
expect(wait()).toEqual({ waitingFor: "agent", source: "host" });
});
it("waits on the history cache for a cached agent once the directory is read", () => {
initializeTestSession();
useSessionStore
.getState()
.setAgents("test-server", new Map([["agent-1", createTestAgent("agent-1")]]));
useSessionStore.getState().markCachedDirectoryRestored("test-server");
expect(wait()).toEqual({ waitingFor: "history", source: "cache" });
});
it("waits on the host for history the cache did not have", () => {
initializeTestSession();
useSessionStore
.getState()
.setAgents("test-server", new Map([["agent-1", createTestAgent("agent-1")]]));
useSessionStore.getState().markCachedTimelineRestored("test-server", "agent-1");
expect(wait()).toEqual({ waitingFor: "history", source: "host" });
});
});
describe("message submission ordering", () => {
const agentId = "agent-1";
const clientMessageId = "client-1";
-69
View File
@@ -338,37 +338,6 @@ export type AgentTimelineState =
newer: "available" | "none";
};
/** The agent's cached history has been read, so a cold timeline now waits on the host. */
export function hasRestoredCachedTimeline(
session: SessionState | undefined,
agentId: string,
): boolean {
return session?.agentCachedTimelineRestored.get(agentId) === true;
}
/** What a loading agent pane waits for, and whether the cache can still answer or only the host. */
export interface AgentLoadingWait {
waitingFor: "agent" | "history";
source: "cache" | "host";
}
export function selectAgentLoadingWait(
session: SessionState | undefined,
agentId: string,
): AgentLoadingWait {
const hasAgent = Boolean(session?.agents.has(agentId) || session?.agentDetails.has(agentId));
if (!hasAgent) {
return {
waitingFor: "agent",
source: session?.hasRestoredCachedDirectory ? "host" : "cache",
};
}
return {
waitingFor: "history",
source: hasRestoredCachedTimeline(session, agentId) ? "host" : "cache",
};
}
export function selectAgentTimelineState(
session: SessionState | undefined,
agentId: string,
@@ -515,8 +484,6 @@ export interface SessionState {
hasHydratedAgents: boolean;
hasHydratedWorkspaces: boolean;
hasWorkspaceDirectorySnapshot: boolean;
/** The cached directory has been read, so whatever it holds is in this session. */
hasRestoredCachedDirectory: boolean;
// Audio state
isPlayingAudio: boolean;
@@ -538,7 +505,6 @@ export interface SessionState {
historySyncGeneration: number;
agentHistorySyncGeneration: Map<string, number>;
agentAuthoritativeHistoryApplied: Map<string, boolean>;
agentCachedTimelineRestored: Map<string, boolean>;
// Initializing agents (used for UI loading state)
initializingAgents: Map<string, boolean>;
@@ -757,8 +723,6 @@ interface SessionStoreActions {
setHasHydratedAgents: (serverId: string, hydrated: boolean) => void;
setHasHydratedWorkspaces: (serverId: string, hydrated: boolean) => void;
setHasWorkspaceDirectorySnapshot: (serverId: string, available: boolean) => void;
markCachedDirectoryRestored: (serverId: string) => void;
markCachedTimelineRestored: (serverId: string, agentId: string) => void;
// Agent directory (derived from agents)
getAgentDirectory: (serverId: string) => AgentDirectoryEntry[] | undefined;
@@ -783,7 +747,6 @@ function createInitialSessionState(
hasHydratedAgents: false,
hasHydratedWorkspaces: false,
hasWorkspaceDirectorySnapshot: false,
hasRestoredCachedDirectory: false,
isPlayingAudio: false,
focusedAgentId: null,
focusedTerminalId: null,
@@ -799,7 +762,6 @@ function createInitialSessionState(
historySyncGeneration: 0,
agentHistorySyncGeneration: new Map(),
agentAuthoritativeHistoryApplied: new Map(),
agentCachedTimelineRestored: new Map(),
initializingAgents: new Map(),
agents: new Map(),
workspaceAgentActivity: new Map(),
@@ -1401,7 +1363,6 @@ export const useSessionStore = create<SessionStore>()(
"agentTimelineOlderFetchInFlight",
"agentHistorySyncGeneration",
"agentAuthoritativeHistoryApplied",
"agentCachedTimelineRestored",
] as const satisfies readonly (keyof SessionState)[];
let next: SessionState | null = null;
for (const key of timelineKeys) {
@@ -2065,36 +2026,6 @@ export const useSessionStore = create<SessionStore>()(
});
},
markCachedDirectoryRestored: (serverId) => {
set((prev) => {
const session = prev.sessions[serverId];
if (!session || session.hasRestoredCachedDirectory) return prev;
return {
...prev,
sessions: {
...prev.sessions,
[serverId]: { ...session, hasRestoredCachedDirectory: true },
},
};
});
},
markCachedTimelineRestored: (serverId, agentId) => {
set((prev) => {
const session = prev.sessions[serverId];
if (!session || session.agentCachedTimelineRestored.get(agentId) === true) return prev;
const restored = new Map(session.agentCachedTimelineRestored);
restored.set(agentId, true);
return {
...prev,
sessions: {
...prev.sessions,
[serverId]: { ...session, agentCachedTimelineRestored: restored },
},
};
});
},
// Agent directory - derived from agents (computed on-demand)
getAgentDirectory: (serverId) => {
const state = get();
-62
View File
@@ -18,7 +18,6 @@ import { WorkspaceDirectoryReplica } from "@/runtime/directory-sync/workspace-re
import type { CachedTimeline } from "@/runtime/replica-cache";
import {
normalizeWorkspaceDescriptor,
hasRestoredCachedTimeline,
selectAgentTimelineState,
selectAgentTimelineTurnPresentation,
selectAgentTurnPresentation,
@@ -339,67 +338,6 @@ describe("viewed timeline persistence", () => {
expect(replica.readCursor(AGENT_ID)).toEqual({ epoch: "epoch-1", endSeq: 4 });
});
it("records that an agent's cached history was read when the cache holds none", async () => {
useSessionStore.getState().initializeSession(SERVER_ID, null);
let release!: (value: CachedTimeline | undefined) => void;
const read = new Promise<CachedTimeline | undefined>((resolve) => {
release = resolve;
});
const replica = createTimelineReplica({
serverId: SERVER_ID,
storage: { readTimeline: () => read, commitTimeline: () => undefined },
prepareAgent: async () => undefined,
});
const isRestored = () =>
hasRestoredCachedTimeline(useSessionStore.getState().sessions[SERVER_ID], AGENT_ID);
const preparation = replica.prepare(AGENT_ID);
expect(isRestored()).toBe(false);
release(undefined);
await preparation;
expect(isRestored()).toBe(true);
expect(
selectAgentTimelineState(useSessionStore.getState().sessions[SERVER_ID], AGENT_ID).status,
).toBe("cold");
});
it("records that an agent's cached history was read when the read fails", async () => {
useSessionStore.getState().initializeSession(SERVER_ID, null);
const replica = createTimelineReplica({
serverId: SERVER_ID,
storage: {
readTimeline: async () => {
throw new Error("storage unavailable");
},
commitTimeline: () => undefined,
},
prepareAgent: async () => undefined,
});
await expect(replica.prepare(AGENT_ID)).rejects.toThrow("storage unavailable");
expect(
hasRestoredCachedTimeline(useSessionStore.getState().sessions[SERVER_ID], AGENT_ID),
).toBe(true);
});
it("forgets that the cached history was read when the timeline is released", async () => {
useSessionStore.getState().initializeSession(SERVER_ID, null);
const replica = createTimelineReplica({
serverId: SERVER_ID,
storage: { readTimeline: async () => cachedTimeline(), commitTimeline: () => undefined },
prepareAgent: async () => undefined,
});
await replica.prepare(AGENT_ID);
useSessionStore.getState().releaseAgentTimeline(SERVER_ID, AGENT_ID);
expect(
hasRestoredCachedTimeline(useSessionStore.getState().sessions[SERVER_ID], AGENT_ID),
).toBe(false);
});
it("paints cached history without claiming authoritative synchronization", async () => {
useSessionStore.getState().initializeSession(SERVER_ID, null);
const owner = createOwner({
@@ -149,7 +149,7 @@ class TimelineReplicaOwner implements TimelineReplica {
storage: this.storage,
prepareAgent: this.prepareAgent,
isTurnSettled: () => this.settledDuringPreparation.has(agentId),
}).finally(() => useSessionStore.getState().markCachedTimelineRestored(this.serverId, agentId));
});
if (!stored) return;
if (stored.range) {
this.cachedRanges.set(agentId, stored.range);
+1 -3
View File
@@ -1,4 +1,4 @@
// Bundles @getpaseo/cli into thin ESM entrypoints plus lazy code-split command chunks.
// Bundles @getpaseo/cli into a thin ESM entrypoint plus lazy code-split command chunks.
// Keeps @getpaseo/server/daemon-files bundled for zero-Zod thin RPC startup while leaving
// @getpaseo/server and its heavy subpaths external so daemon spawning and heavy commands
// resolve from the installed @getpaseo/server package.
@@ -29,8 +29,6 @@ await rm(outDir, { recursive: true, force: true });
await build({
entryPoints: {
index: path.join(packageRoot, "src/index.ts"),
// Electron imports runCli to supply its own argv and handle the exit code.
run: path.join(packageRoot, "src/run.ts"),
},
outdir: outDir,
bundle: true,
+1 -1
View File
@@ -446,10 +446,10 @@ export async function runLogsCommand(
const transcript = formatAgentActivityTranscript(timelineItems, tailCount);
console.log(transcript);
} catch (err) {
await client.close().catch(() => {});
if (err && typeof err === "object" && "code" in err) throw err;
const message = err instanceof Error ? err.message : String(err);
console.error(`Error: Failed to get logs: ${message}`);
await client.close().catch(() => {});
process.exit(1);
}
}
@@ -13,26 +13,13 @@ import { connectToDaemon } from "../../utils/client.js";
const repo = fileURLToPath(new URL("../../../../..", import.meta.url));
const cli = path.join(repo, "packages/cli/dist/index.js");
// Reserved ports come from below every OS's ephemeral range (Linux starts at
// 32768, macOS and Windows at 49152). A port from port 0 is ephemeral, and the
// OS may give it to another process between the reservation and the daemon's
// listen. A port from this range is never handed out that way.
const reservedPorts = { first: 20_000, count: 12_000 };
async function port() {
for (let attempt = 0; attempt < 50; attempt++) {
const value = reservedPorts.first + Math.floor(Math.random() * reservedPorts.count);
if (await isFree(value)) return value;
}
throw new Error("No free test port");
}
function isFree(value: number) {
return new Promise<boolean>((resolve) => {
const server = net.createServer();
server.once("error", () => resolve(false));
server.listen(value, "127.0.0.1", () => server.close(() => resolve(true)));
});
const server = net.createServer();
await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
const value = (server.address() as net.AddressInfo).port;
await new Promise<void>((resolve) => server.close(() => resolve()));
if (value === 6767 || value === 6768) throw new Error("Unsafe test port");
return value;
}
// Port zero lets the daemon bind its own port, with no gap for another
+1 -18
View File
@@ -1,7 +1,7 @@
import { existsSync, readFileSync } from "node:fs";
import { spawnSync } from "node:child_process";
import path from "node:path";
import { fileURLToPath, pathToFileURL } from "node:url";
import { fileURLToPath } from "node:url";
import { build, type Metafile } from "esbuild";
import { describe, expect, it } from "vitest";
@@ -110,23 +110,6 @@ describe("CLI startup import boundary", () => {
const distEntry = path.join(packageRoot, "dist/index.js");
it.skipIf(!existsSync(distEntry))(
"bundled CLI exposes a programmatic entry for desktop passthrough",
() => {
const runnerUrl = pathToFileURL(path.join(packageRoot, "dist/run.js")).href;
const script = `
import { runCli } from ${JSON.stringify(runnerUrl)};
process.exitCode = await runCli(["--help"]);
`;
const run = spawnSync(process.execPath, ["--input-type=module", "-e", script], {
encoding: "utf8",
});
expect(run.status, run.stderr).toBe(0);
expect(run.stdout).toContain("Usage: paseo");
},
);
it.skipIf(!existsSync(distEntry))(
"bundled dist/index.js serves --version without loading heavy modules at runtime",
() => {
+2 -8
View File
@@ -56,23 +56,17 @@ export function buildDaemonConnectionCommandError(options: ConnectOptions & { er
message: message.startsWith("Cannot connect to daemon at ")
? message
: `Cannot connect to daemon at ${describeDaemonTarget(options.target)}: ${message}`,
details: describeConnectionRemedy(code, options.target, message),
details: describeConnectionRemedy(code, options.target),
};
}
function describeConnectionRemedy(code: string, target: DaemonTarget, message: string): string {
function describeConnectionRemedy(code: string, target: DaemonTarget): string {
if (code === "AUTH_REQUIRED")
return "The daemon requires a password. Set PASEO_PASSWORD and retry.";
if (code === "AUTH_FAILED")
return "The daemon rejected the password. Check PASEO_PASSWORD and retry.";
if (target.kind === "instance")
return `Start with: paseo daemon start --home ${JSON.stringify(target.home)}`;
const host = target.host.trim();
if (
message === "Unexpected server response: 400" &&
/^(?:[\w.-]+|\[[\da-f:.]+\]):\d+$/i.test(host)
)
return `The endpoint returned HTTP 400 to a plaintext WebSocket request. If this endpoint uses TLS, use wss://${host}.`;
return "Check the selected endpoint and credentials. SSH transport does not install or start the daemon.";
}
+1 -1
View File
@@ -3,7 +3,7 @@ import { selectDaemonTarget } from "./daemon-target.js";
const JSON_OPTION_DESCRIPTION = "Output in JSON format";
const DAEMON_HOST_OPTION_DESCRIPTION =
"Explicit daemon endpoint: host:port, TCP, socket, SSH, or pairing URL (default: local home). For TLS, use wss://host:port.";
"Explicit daemon endpoint: host:port, TCP, socket, SSH, or pairing URL (default: local home)";
const localCommands = new WeakSet<Command>();
+2 -34
View File
@@ -20,8 +20,6 @@
*/
import assert from "node:assert";
import { once } from "node:events";
import { createServer } from "node:http";
import { mkdtemp, rm } from "fs/promises";
import { tmpdir } from "os";
import { join } from "path";
@@ -181,39 +179,9 @@ try {
console.log("✓ global --host targets the requested daemon\n");
}
// Test 11: a bare endpoint that returns HTTP 400 gets TLS guidance
// Test 11: conflicting explicit --host selectors are rejected
{
const server = createServer((_request, response) => {
response.writeHead(400).end();
});
server.listen(0, "127.0.0.1");
try {
await once(server, "listening");
const address = server.address();
assert(address && typeof address !== "string");
const host = `127.0.0.1:${address.port}`;
const result = await runLocalPaseo(["--host", host, "ls"], { PASEO_HOME: paseoHome });
assert.strictEqual(result.exitCode, 1);
assert.match(result.stderr, /Unexpected server response: 400/);
assert(result.stderr.includes(`If this endpoint uses TLS, use wss://${host}`));
const explicit = await runLocalPaseo(["--host", `ws://${host}`, "ls"], {
PASEO_HOME: paseoHome,
});
assert.strictEqual(explicit.exitCode, 1);
assert.match(explicit.stderr, /Unexpected server response: 400/);
assert(!explicit.stderr.includes("If this endpoint uses TLS"));
const help = await runLocalPaseo(["ls", "--help"]);
assert.strictEqual(help.exitCode, 0);
assert.match(help.stdout, /For TLS, use\s+wss:\/\/host:port/);
} finally {
server.close();
}
}
// Test 12: conflicting explicit --host selectors are rejected
{
console.log("Test 12: conflicting explicit --host selectors are rejected");
console.log("Test 11: conflicting explicit --host selectors are rejected");
const firstHost = `localhost:${port}`;
const lastHost = `localhost:${await getAvailablePort()}`;
const result = await runLocalPaseo(["--host", firstHost, "ls", "--host", lastHost]);
+14 -26
View File
@@ -1372,8 +1372,20 @@ async function main() {
let client = null;
try {
// Observe the real Electron shell handoff without launching a user's browser.
const openerDirectory = path.join(runtimeDir, "url-handler");
const externalOpenLog = path.join(artifactDir, "external-opens.txt");
fs.mkdirSync(openerDirectory, { recursive: true });
fs.writeFileSync(externalOpenLog, "");
fs.writeFileSync(
path.join(openerDirectory, "xdg-open"),
'#!/bin/sh\nprintf "%s\\n" "$1" >> "$PASEO_TEST_EXTERNAL_OPEN_LOG"\n',
{ mode: 0o755 },
);
const commonEnv = {
...process.env,
PATH: `${openerDirectory}${path.delimiter}${process.env.PATH}`,
PASEO_TEST_EXTERNAL_OPEN_LOG: externalOpenLog,
PASEO_HOME: paseoHome,
PASEO_LISTEN: listen,
PASEO_DAEMON_ENDPOINT: `localhost:${daemonPort}`,
@@ -1413,30 +1425,6 @@ async function main() {
children.push(remoteDaemon.child);
await waitForPort(remotePort, "remote daemon", remoteDaemon);
const desktopEnv = { ...commonEnv };
let externalOpenLog = null;
if (process.platform === "linux") {
// Observe Electron's shell handoff without launching the system browser.
const openerDirectory = path.join(runtimeDir, "url-handler");
externalOpenLog = path.join(artifactDir, "external-opens.txt");
fs.mkdirSync(openerDirectory, { recursive: true });
fs.writeFileSync(externalOpenLog, "");
fs.writeFileSync(
path.join(openerDirectory, "xdg-open"),
'#!/bin/sh\nprintf "%s\\n" "$1" >> "$PASEO_TEST_EXTERNAL_OPEN_LOG"\n',
{ mode: 0o755 },
);
// Keep the test PATH when Electron imports its login shell environment.
const loginShell = path.join(runtimeDir, "login-shell");
fs.writeFileSync(loginShell, '#!/bin/sh\nexec /bin/bash --noprofile --norc "$@"\n', {
mode: 0o755,
});
desktopEnv.SHELL = loginShell;
desktopEnv.PATH = `${openerDirectory}${path.delimiter}${process.env.PATH}`;
desktopEnv.PASEO_TEST_EXTERNAL_OPEN_LOG = externalOpenLog;
}
const desktopArgs = [
process.execPath,
devRunner,
@@ -1455,7 +1443,7 @@ async function main() {
{
cwd: rootDir,
env: {
...desktopEnv,
...commonEnv,
EXPO_UNSTABLE_HEADLESS: "1",
EXPO_PORT: String(expoPort),
EXPO_DEV_URL: `http://localhost:${expoPort}`,
@@ -1483,7 +1471,7 @@ async function main() {
remoteWorkspaceId: workspaceIds[1],
url: target.url,
artifactDir,
externalOpenLog,
externalOpenLog: process.platform === "linux" ? externalOpenLog : null,
});
const checkFocusIsolation = (browserClient, callerAgentId, typingAgent) =>
runBrowserFocusIsolationRegression({
@@ -1886,70 +1886,6 @@ test("steers a run Pi started by itself instead of aborting it", async () => {
}
});
test.each([
{ behavior: "interrupt", options: {} },
{ behavior: "steer", options: { activeTurnBehavior: "steer" as const } },
])(
"runs a Pi extension command sent mid-turn ($behavior) without aborting the turn",
async ({ options }) => {
const runtime = new FakePi();
const manager = new AgentManager({
clients: {
pi: new PiRpcAgentClient({
runtime,
logger,
runtimeSettings: { command: { mode: "replace", argv: [process.execPath] } },
}),
},
logger,
});
const workdir = mkdtempSync(join(tmpdir(), "agent-manager-pi-extension-command-"));
let agentId: string | null = null;
try {
const agent = await manager.createAgent({ provider: "pi", cwd: workdir }, undefined, {
workspaceId: undefined,
});
agentId = agent.id;
const fakeSession = runtime.latestSession();
fakeSession.commands = [{ name: "keepwarm", description: "Keep warm", source: "extension" }];
await startAgentRun(manager, agent.id, "long task", logger);
await vi.waitFor(() =>
expect(fakeSession.prompts).toEqual([{ message: "long task", imageCount: 0 }]),
);
const turnId = manager.getAgent(agent.id)?.activeTurnId;
expect(turnId).toEqual(expect.any(String));
const result = await startAgentRun(manager, agent.id, "/keepwarm on", logger, {
...options,
replaceRunning: true,
runOptions: { clientMessageId: "keepwarm-client" },
});
expect(result).toEqual({ disposition: "out_of_band" });
await vi.waitFor(() =>
expect(fakeSession.prompts).toEqual([
{ message: "long task", imageCount: 0 },
{ message: "/keepwarm on", imageCount: 0 },
]),
);
expect(fakeSession.controlRequests).toEqual([]);
expect(fakeSession.steerCalls).toEqual([]);
expect(manager.getAgent(agent.id)?.activeTurnId).toBe(turnId);
expect(manager.getTimeline(agent.id)).toContainEqual(
expect.objectContaining({
type: "user_message",
text: "/keepwarm on",
clientMessageId: "keepwarm-client",
}),
);
} finally {
if (agentId) await manager.closeAgent(agentId).catch(() => undefined);
rmSync(workdir, { recursive: true, force: true });
}
},
);
test("isolated rewind falls back from steering to the normal replacement path", async () => {
const session = new SteeringTestSession({ provider: "claude", cwd: process.cwd() });
session.steerResult = "unavailable";
@@ -3027,62 +3027,6 @@ describe("PiRpcAgentSession steering", () => {
expect(fakeSession.steerCalls).toEqual([]);
});
test("runs a Pi extension command sent mid-turn without interrupting the turn", async () => {
const { pi, session, events } = await createSession();
const fakeSession = pi.latestSession();
fakeSession.commands = [
{ name: "keepwarm", description: "Keep the cache warm", source: "extension" },
{ name: "skill:review", description: "Review", source: "skill" },
{ name: "fix-tests", description: "Fix tests", source: "prompt" },
];
const { turnId } = await session.startTurn("run");
await flushTurnScheduling();
const handler = session.tryHandleOutOfBand(" /keepwarm on 3h ");
expect(handler).not.toBeNull();
await handler?.run({ emit: () => {} });
await flushTurnScheduling();
expect(fakeSession.prompts).toEqual([
{ message: "run", imageCount: 0 },
{ message: "/keepwarm on 3h", imageCount: 0 },
]);
expect(fakeSession.controlRequests).toEqual([]);
// Skills, prompt templates and commands Pi doesn't list keep the normal path.
for (const input of ["/skill:review", "/fix-tests", "/model", "/keepwarmer"]) {
expect(session.tryHandleOutOfBand(input)).toBeNull();
}
fakeSession.finishTurn();
await events.nextTurnCompletion();
expect(events.turnLifecycleEvents()).toContainEqual({ type: "turn_completed", turnId });
expect(session.tryHandleOutOfBand("/keepwarm off")).toBeNull();
});
test("reports a mid-turn extension command failure without waiting for its ack", async () => {
const { pi, session } = await createSession();
const fakeSession = pi.latestSession();
fakeSession.commands = [{ name: "keepwarm", description: "Keep warm", source: "extension" }];
await session.startTurn("run");
await flushTurnScheduling();
fakeSession.holdNextPrompt();
const emitted: AgentStreamEvent[] = [];
// The handler returns while Pi still runs the command, so Stop stays available.
await session.tryHandleOutOfBand("/keepwarm on")?.run({ emit: (event) => emitted.push(event) });
expect(emitted).toEqual([]);
await fakeSession.failHeldPrompt(new Error("keepwarm exploded"));
expect(emitted).toEqual([
{
type: "timeline",
provider: "pi",
item: { type: "assistant_message", text: "[Error] keepwarm exploded" },
},
]);
expect(fakeSession.controlRequests).toEqual([]);
});
test("falls back when the Pi binary lacks the steer RPC", async () => {
const { pi, session } = await createSession();
const fakeSession = pi.latestSession();
@@ -1216,7 +1216,6 @@ export class PiRpcAgentSession implements AgentSession {
private outOfBandCompactionStarted = false;
private outOfBandCompactionCompleted = false;
private commandCache: AgentSlashCommand[] | null = null;
private extensionCommandNames = new Set<string>();
private state: PiSessionState;
private readonly currentModeId: string | null;
private readonly logger: Logger;
@@ -1333,12 +1332,6 @@ export class PiRpcAgentSession implements AgentSession {
this.activePromptRequestId = null;
this.pendingSteerSubmissions.length = 0;
this.clearNoTurnBuffers();
// tryHandleOutOfBand decides synchronously, so learn the extension commands before a
// slash command can arrive mid-turn.
void this.runtimeSession.getCommands().then(
(commands) => this.rememberExtensionCommands(commands),
() => undefined,
);
const payload = await convertPromptInput(prompt, { model: this.state.model });
if (this.closed) throw new Error("Pi session is closed");
if (this.activeTurnId !== turnId) return { turnId };
@@ -1705,17 +1698,10 @@ export class PiRpcAgentSession implements AgentSession {
return this.commandCache;
}
const commands = await this.runtimeSession.getCommands();
this.rememberExtensionCommands(commands);
const mappedCommands = mapPiSlashCommands(commands);
return mappedCommands;
}
private rememberExtensionCommands(commands: PiRpcSlashCommand[]): void {
this.extensionCommandNames = new Set(
commands.filter((command) => command.source === "extension").map((command) => command.name),
);
}
tryHandleOutOfBand(
prompt: AgentPromptInput,
): { run(ctx: { emit: (event: AgentStreamEvent) => void }): Promise<void> } | null {
@@ -1741,34 +1727,6 @@ export class PiRpcAgentSession implements AgentSession {
},
};
}
if (
(this.activeTurnId || this.autonomousTurnId) &&
this.extensionCommandNames.has(parsed.commandName)
) {
// Pi runs extension commands as soon as the prompt arrives, even mid-turn, so the turn
// keeps running. Pi acks only when the command returns; waiting here would hold the
// foreground lane, and Stop with it, while an interactive command waits for an answer.
const text = prompt.trim();
return {
run: async ({ emit }) => {
void (async () => {
try {
const ack = await this.runtimeSession.prompt(text);
if (ack.requestId) this.pendingPromptResults.delete(ack.requestId);
} catch (error) {
emit({
type: "timeline",
provider: this.provider,
item: {
type: "assistant_message",
text: `[Error] ${toDiagnosticErrorMessage(error)}`,
},
});
}
})();
},
};
}
return null;
}
@@ -285,7 +285,7 @@ test("logs --since filters history and live output through the CLI and daemon",
}
}, 120_000);
test("one-shot logs preserve history order across pages and exit when a page times out", async () => {
test("one-shot logs preserve history order across pages", async () => {
const ctx = await createDaemonTestContext();
try {
const proxy = new WebSocketServer({ port: 0, host: "127.0.0.1" });
@@ -299,7 +299,6 @@ test("one-shot logs preserve history order across pages and exit when a page tim
limit?: number;
cursor?: { epoch: string; seq: number };
}> = [];
let dropTimelineRequests = false;
proxy.on("connection", (downstream) => {
const upstream = new WebSocket(`ws://127.0.0.1:${ctx.daemon.port}/ws`);
upstreams.push(upstream);
@@ -322,7 +321,6 @@ test("one-shot logs preserve history order across pages and exit when a page tim
limit: frame.message.limit,
cursor: frame.message.cursor,
});
if (dropTimelineRequests) return;
}
upstream.send(data, { binary });
} catch {
@@ -411,23 +409,25 @@ test("one-shot logs preserve history order across pages and exit when a page tim
json: false,
},
];
const runLogs = (flags: string[], timeout = 30_000) =>
promisify(execFile)(process.execPath, [...prefix, ...flags], {
cwd: ctx.daemon.paseoHome,
env: {
...Object.fromEntries(
Object.entries(process.env).filter(([key]) => !key.startsWith("PASEO_")),
),
HOME: ctx.daemon.paseoHome,
USERPROFILE: ctx.daemon.paseoHome,
},
maxBuffer: 8 * 1024 * 1024,
timeout,
});
const observed: Array<typeof requests> = [];
for (const entry of cases) {
requests.length = 0;
const { stdout, stderr } = await runLogs(entry.flags);
const { stdout, stderr } = await promisify(execFile)(
process.execPath,
[...prefix, ...entry.flags],
{
cwd: ctx.daemon.paseoHome,
env: {
...Object.fromEntries(
Object.entries(process.env).filter(([key]) => !key.startsWith("PASEO_")),
),
HOME: ctx.daemon.paseoHome,
USERPROFILE: ctx.daemon.paseoHome,
},
maxBuffer: 8 * 1024 * 1024,
timeout: 30_000,
},
);
const parsed = entry.json
? (JSON.parse(stdout) as { agentId: string; items: Array<{ text: string }> })
: undefined;
@@ -477,20 +477,6 @@ test("one-shot logs preserve history order across pages and exit when a page tim
assert.deepStrictEqual(observed[6], []);
assert.deepStrictEqual(observed[9], []);
assert.deepStrictEqual(observed[10], []);
// Leave the connection open and withhold only the timeline reply.
requests.length = 0;
dropTimelineRequests = true;
const timedOut = await runLogs(["--tail", "5"], 75_000).then(
() => assert.fail("The CLI should exit with an error when the daemon does not reply"),
(error: { code: number | null; signal: string | null; stdout: string; stderr: string }) =>
error,
);
assert.strictEqual(requests.length, 1);
assert.strictEqual(timedOut.stdout, "");
assert.match(timedOut.stderr, /No response to fetch_agent_timeline_request after 60000ms/);
assert.strictEqual(timedOut.signal, null, "CLI remained running after printing the timeout");
assert.strictEqual(timedOut.code, 1);
} finally {
for (const downstream of proxy.clients) downstream.terminate();
for (const upstream of upstreams) upstream.terminate();
@@ -262,16 +262,12 @@ describe("daemon E2E (real codex) - send message during tool call", () => {
cwd: cwd ?? process.cwd(),
title: "codex-exact-turn-steer",
provider: "codex",
model: "gpt-5.4",
thinkingOptionId: "low",
modeId: "full-access",
}),
);
resources.collector = createMessageCollector(client);
await within(
"subscribe to steering agent timeline",
15_000,
client.observeTimeline([agent.id]).ready,
);
await within(
"submit Codex foreground sleep turn",
30_000,
@@ -405,12 +401,12 @@ describe("daemon E2E (real codex) - send message during tool call", () => {
cwd,
title: "codex-tool-interrupt-repro",
provider: "codex",
model: "gpt-5.4",
thinkingOptionId: "low",
modeId: "full-access",
});
collector = createMessageCollector(client);
await client.observeTimeline([agent.id]).ready;
await client.sendMessage(
agent.id,
@@ -484,12 +480,12 @@ describe("daemon E2E (real codex) - send message during tool call", () => {
cwd,
title: "codex-quick-follow-up-repro",
provider: "codex",
model: "gpt-5.4",
thinkingOptionId: "low",
modeId: "full-access",
});
collector = createMessageCollector(client);
await client.observeTimeline([agent.id]).ready;
await client.sendAgentMessage(
agent.id,
@@ -90,10 +90,7 @@ async function waitForState(
await new Promise((resolve) => setTimeout(resolve, 50));
}
const lines = getLines(await readTerminalState(session)).filter((line) => line.length > 0);
throw new Error(
`Timeout waiting for terminal state predicate to match.\nScreen:\n${lines.join("\n")}`,
);
throw new Error("Timeout waiting for terminal state predicate to match");
}
async function waitForTitle(
@@ -362,13 +359,6 @@ function lastNonEmptyLineIsPrompt(state: TerminalState): boolean {
return last === "$";
}
// Type a command only once the shell shows its prompt. Typed ahead while the
// previous helper still runs, its output lands on the prompt row ("$ OK:...").
async function runAtPrompt(session: TerminalSession, command: string): Promise<void> {
await waitForState(session, lastNonEmptyLineIsPrompt);
session.send({ type: "input", data: `${command}\r` });
}
function removeZshShellIntegrationRuntimeDir(): void {
rmSync(join(tmpdir(), `${userInfo().username || "unknown"}-paseo-zsh-${process.pid}`), {
recursive: true,
@@ -1206,7 +1196,7 @@ describe.skipIf(isPlatform("win32"))("terminal POSIX-only", () => {
);
await waitForLines(session, ["$"]);
await runAtPrompt(session, 'echo "CFGBG=$COLORFGBG"');
session.send({ type: "input", data: 'echo "CFGBG=$COLORFGBG"\r' });
await waitForOutputLine(session, "CFGBG=0;15");
for (const [code, expected] of [
@@ -1214,7 +1204,7 @@ describe.skipIf(isPlatform("win32"))("terminal POSIX-only", () => {
[11, "rgb:abab/cdcd/efef"],
[12, "rgb:4444/5555/6666"],
] as const) {
await runAtPrompt(session, `${process.execPath} ${helperPath} ${code}`);
session.send({ type: "input", data: `${process.execPath} ${helperPath} ${code}\r` });
await waitForState(session, (state) =>
getLines(state).some((line) => line.startsWith(`OSC_COLOR_OK:${code}:`)),
);
@@ -1249,7 +1239,7 @@ describe.skipIf(isPlatform("win32"))("terminal POSIX-only", () => {
[11, "rgb:1010/1d1d/2b2b"],
[12, "rgb:3737/4949/5c5c"],
] as const) {
await runAtPrompt(session, `${process.execPath} ${helperPath} ${code}`);
session.send({ type: "input", data: `${process.execPath} ${helperPath} ${code}\r` });
await waitForState(session, (state) =>
getLines(state).some((line) => line.startsWith(`OSC_COLOR_OK:${code}:`)),
);
@@ -1279,15 +1269,15 @@ describe.skipIf(isPlatform("win32"))("terminal POSIX-only", () => {
await waitForLines(session, ["$"]);
// DSR 996 query reports light (2) initially
await runAtPrompt(session, `${process.execPath} ${schemeHelper} query`);
session.send({ type: "input", data: `${process.execPath} ${schemeHelper} query\r` });
await waitForOutputLine(session, "SCHEME_QUERY_OK:2");
// DECRQM 2031 reports reset (2) before enabling and set (1) after enabling
await runAtPrompt(session, `${process.execPath} ${schemeHelper} decrqm`);
session.send({ type: "input", data: `${process.execPath} ${schemeHelper} decrqm\r` });
await waitForOutputLine(session, "DECRQM_OK:2:1");
// Start mode 2031 watcher
await runAtPrompt(session, `${process.execPath} ${schemeHelper} watch`);
session.send({ type: "input", data: `${process.execPath} ${schemeHelper} watch\r` });
await waitForOutputLine(session, "SCHEME_WATCH_READY");
// Same polarity update (another light palette) does NOT emit a 997 report
@@ -1311,10 +1301,10 @@ describe.skipIf(isPlatform("win32"))("terminal POSIX-only", () => {
await waitForOutputLine(session, "SCHEME_DONE:1,2");
// Subsequent OSC 11 and DSR 996 queries immediately reflect the updated dark palette
await runAtPrompt(session, `${process.execPath} ${oscHelper} 11`);
session.send({ type: "input", data: `${process.execPath} ${oscHelper} 11\r` });
await waitForOutputLine(session, "OSC_COLOR_OK:11:ESC]11;rgb:1818/1b1b/1a1aESC\\");
await runAtPrompt(session, `${process.execPath} ${schemeHelper} query`);
session.send({ type: "input", data: `${process.execPath} ${schemeHelper} query\r` });
await waitForOutputLine(session, "SCHEME_QUERY_OK:1");
});
});
+2 -6
View File
@@ -364,14 +364,10 @@ test("the plugin demo shows its finished state when motion is reduced", async ({
const builtPanelRow = page.getByText("Add Gruvbox theme", { exact: true });
const panel = builtPanelRow.locator("xpath=ancestor::div[contains(@class, 'md:border-l')]");
const heading = page.getByRole("heading", { name: "Ask Paseo to change Paseo" });
const section = heading.locator("xpath=ancestor::section[1]");
// The section fades in when it scrolls into view. The demo inside must already be finished
// when that fade ends; the staged demo would still be hiding the row for seconds.
await expect(async () => {
await heading.scrollIntoViewIfNeeded();
expect(await renderedOpacity(section)).toBe(1);
}).toPass();
expect(await renderedOpacity(builtPanelRow)).toBe(1);
expect(await renderedOpacity(builtPanelRow)).toBe(1);
}).toPass({ timeout: 2_000 });
expect(await panel.evaluate((element) => getComputedStyle(element).transform)).toBe("none");
});
@@ -634,72 +634,6 @@ index 1559352..33eb5de 100644
onAnimValInit={onAnimValInit}
/>
);
diff --git a/node_modules/react-native-draggable-flatlist/src/components/NestableScrollContainer.tsx b/node_modules/react-native-draggable-flatlist/src/components/NestableScrollContainer.tsx
--- a/node_modules/react-native-draggable-flatlist/src/components/NestableScrollContainer.tsx
+++ b/node_modules/react-native-draggable-flatlist/src/components/NestableScrollContainer.tsx
@@ -1,6 +1,6 @@
-import React from "react";
+import React, { useCallback } from "react";
import { LayoutChangeEvent, ScrollViewProps } from "react-native";
-import { ScrollView } from "react-native-gesture-handler";
+import { FlatList, ScrollView } from "react-native-gesture-handler";
import Animated, { useAnimatedScrollHandler } from "react-native-reanimated";
import {
NestableScrollContainerProvider,
@@ -8,7 +8,12 @@
} from "../context/nestableScrollContainerContext";
import { useStableCallback } from "../hooks/useStableCallback";
-const AnimatedScrollView = Animated.createAnimatedComponent(ScrollView);
+// The container is a one-cell VirtualizedList, not a ScrollView. A VirtualizedList nested in
+// another one windows its rows against the outermost list's viewport; nested in a ScrollView it
+// renders every row. So nested draggable lists here render only the rows near the viewport.
+const AnimatedFlatList = Animated.createAnimatedComponent(FlatList);
+const CONTENT_CELL = [0];
+const contentCellKey = () => "content";
function NestableScrollContainerInner(props: ScrollViewProps) {
const {
@@ -18,6 +23,7 @@
scrollableRef,
outerScrollEnabled,
} = useSafeNestableScrollContainerContext();
+ const { children, ...scrollProps } = props;
const onScroll = useAnimatedScrollHandler({
onScroll: ({ contentOffset }) => {
@@ -37,13 +43,28 @@
props.onContentSizeChange?.(w, h);
});
+ // Nested lists measure against, and auto-scroll, the host scroll view under the list.
+ const listRef = useCallback(
+ (list: FlatList<number> | null) => {
+ (scrollableRef as React.MutableRefObject<ScrollView | null>).current =
+ (list?.getNativeScrollRef() as unknown as ScrollView | null) ?? null;
+ },
+ [scrollableRef]
+ );
+
+ const renderContent = useCallback(() => <>{children}</>, [children]);
+
return (
- <AnimatedScrollView
- {...props}
+ <AnimatedFlatList
+ {...(scrollProps as object)}
+ data={CONTENT_CELL}
+ keyExtractor={contentCellKey}
+ renderItem={renderContent}
+ extraData={children}
onLayout={onLayout}
onContentSizeChange={onContentSizeChange}
scrollEnabled={outerScrollEnabled}
- ref={scrollableRef}
+ ref={listRef}
scrollEventThrottle={1}
onScroll={onScroll}
/>
diff --git a/node_modules/react-native-draggable-flatlist/src/context/draggableFlatListContext.tsx b/node_modules/react-native-draggable-flatlist/src/context/draggableFlatListContext.tsx
index 75f7db7..e99faf3 100644
--- a/node_modules/react-native-draggable-flatlist/src/context/draggableFlatListContext.tsx
-3
View File
@@ -63,9 +63,6 @@ const patchedPackages = [
// each moved cell a fresh transform host. Reanimated re-applies a view's last animated
// transform to every React commit, so a reused host painted one frame of new order plus old
// drag translate (upstream computerjazz/react-native-draggable-flatlist#621, open).
// NestableScrollContainer is a one-cell FlatList instead of a ScrollView, so nested lists render
// only the rows near its viewport. As a ScrollView it made a closed sidebar render every project
// on launch. No upstream fix.
{
nodeModulesPath: "node_modules/react-native-draggable-flatlist",
patchPrefix: "react-native-draggable-flatlist+",
-1
View File
@@ -164,7 +164,6 @@ async function main() {
...(traceDesktop
? [
["packages/desktop/dist/daemon/runtime-paths.js", ["@getpaseo/server"]],
["packages/desktop/dist/daemon/cli/entrypoints.js", ["@getpaseo/cli/dist/run.js"]],
["packages/desktop/dist/integrations/cli-install/paths.js", ["@getpaseo/cli/bin/paseo"]],
]
: []),