mirror of
https://github.com/getpaseo/paseo.git
synced 2026-11-30 04:05:43 +00:00
Compare commits
25
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1cc1164f71 | ||
|
|
c14373201a | ||
|
|
fbc80bbce5 | ||
|
|
c77a53ffdc | ||
|
|
614b4d3860 | ||
|
|
80f0b11386 | ||
|
|
95a90f5259 | ||
|
|
d059fcfd10 | ||
|
|
cfd4efe289 | ||
|
|
830697ba62 | ||
|
|
41aceb042b | ||
|
|
74f629bee1 | ||
|
|
097a0f3a7d | ||
|
|
47b4205098 | ||
|
|
d8e9a39953 | ||
|
|
d63f0204e5 | ||
|
|
9c9c839bd0 | ||
|
|
0e8e3987a0 | ||
|
|
0b1b2dd286 | ||
|
|
2c0bc525d3 | ||
|
|
27e35a198d | ||
|
|
8b7cb47ef2 | ||
|
|
693fa22377 | ||
|
|
22a318b1de | ||
|
|
4f8fed2e2b |
+6
-1
@@ -601,7 +601,12 @@ The cache is capped at 32 MiB and evicts whole hosts in least-recently-written o
|
||||
eviction, only a baseline replacement stores that host's directory again. Mutations queued around
|
||||
the eviction are dropped when they are written, so a checkpoint never outlives its rows. Budget
|
||||
bookkeeping may scan opaque row sizes during a deferred write, never during host registry startup or
|
||||
before a requested cache row can paint. The row store is not encrypted. A cached timeline can contain
|
||||
before a requested cache row can paint. The cache holds only each row's key and UTF-8 payload size,
|
||||
never the payload: a timeline row can be megabytes, and the renderer would hold a second copy of
|
||||
every cached transcript until restart. Each store reports sizes without loading payloads. SQLite
|
||||
measures the stored text, and IndexedDB records the size on the row and reads an index over it.
|
||||
Opening an IndexedDB database written before that index existed drops its rows, because they would
|
||||
be readable but never counted against the budget. The row store is not encrypted. A cached timeline can contain
|
||||
source code, prompts, and tool output; encrypted-at-rest storage is a separate security decision.
|
||||
|
||||
### Saved hosts
|
||||
|
||||
+1
-1
@@ -136,7 +136,7 @@ Cards inside a section sit closer than sections. Rows inside a card touch — on
|
||||
|
||||
Rows have generous vertical padding: roughly 16px of content plus 16px of vertical padding for settings rows, 8–12px for sidebar list items where many rows must fit. Every row is at least as tall as one holding a switch, so text rows, switch rows and rows that open something (`<SettingsDetailRow>`, a collapsible row's header) line up. A row holding a button or a select is taller. Compressing rows below the established density to fit more on the screen is wrong. Too many rows means more cards or more sections, not smaller rows.
|
||||
|
||||
Rows revealed under a `<SettingsCollapsibleRow>` are nested rows, one step smaller than card rows: 8px of vertical padding, `fontSize.sm` text, `sm` controls, and one fixed height so rows with and without a trailing button line up. The collapsible row sets this for everything under it (`packages/app/src/components/settings/row-density.tsx`). Never pass a density to a row, and never pad or resize a nested row by hand. Settings rows that share a menu surface with menu rows, such as Usage's options, go inside `<MenuSettingsRows>`, which puts their labels on the menu rows' label rail (`menuRowContentInset`).
|
||||
Rows revealed under a `<SettingsCollapsibleRow>` are nested rows, one step smaller than card rows: 8px of vertical padding, `fontSize.sm` text, `sm` controls, and one fixed height so rows with and without a trailing button line up. The collapsible row sets this for everything under it (`packages/app/src/components/settings/row-density.tsx`). Never pass a density to a row, and never pad or resize a nested row by hand. Settings rows that share a menu surface with menu rows, such as Usage's options, go inside `<MenuSettingsRows>`, which puts their labels on the menu rows' label rail (`menuRowContentInset`). Settings rows that share a sheet with list rows, such as Agent settings with its radio choices and section headers, go inside `<ListSettingsRows>`, which makes every row one touch target tall so Model, switch and radio rows line up.
|
||||
|
||||
The whitespace is the design.
|
||||
|
||||
|
||||
@@ -5,6 +5,7 @@ const withAndroidAsyncStorageSize = require("./plugins/with-android-async-storag
|
||||
const withAndroidIgnoreBoldText = require("./plugins/with-android-ignore-bold-text");
|
||||
const withAndroidOptionalCamera = require("./plugins/with-android-optional-camera");
|
||||
const withAndroidProfileable = require("./plugins/with-android-profileable");
|
||||
const withAndroidSplashWindowBackground = require("./plugins/with-android-splash-window-background");
|
||||
const withFdroidAutolinking = require("./plugins/with-fdroid-autolinking");
|
||||
const withPasteInput = require("./plugins/with-paste-input");
|
||||
const withAndroidScroll = require("./modules/paseo-scroll/app.plugin");
|
||||
@@ -165,6 +166,7 @@ export default {
|
||||
},
|
||||
},
|
||||
],
|
||||
withAndroidSplashWindowBackground,
|
||||
...buildProfile.notificationPlugins,
|
||||
"expo-audio",
|
||||
[
|
||||
|
||||
@@ -26,6 +26,29 @@ async function resolveAndroidManifest() {
|
||||
return exp._internal.modResults.android.manifest.manifest;
|
||||
}
|
||||
|
||||
interface StyleItem {
|
||||
$: { name: string };
|
||||
_: string;
|
||||
}
|
||||
|
||||
interface StyleGroup {
|
||||
$: { name: string };
|
||||
item?: StyleItem[];
|
||||
}
|
||||
|
||||
async function resolveAndroidAppThemeItems(): Promise<Record<string, string>> {
|
||||
const { exp } = await getPrebuildConfigAsync(__dirname, { platforms: ["android"] });
|
||||
await compileModsAsync(exp, {
|
||||
projectRoot: __dirname,
|
||||
introspect: true,
|
||||
platforms: ["android"],
|
||||
assertMissingModProviders: false,
|
||||
});
|
||||
const styles: StyleGroup[] = exp._internal.modResults.android.styles.resources.style;
|
||||
const appTheme = styles.find((style) => style.$.name === "AppTheme");
|
||||
return Object.fromEntries((appTheme?.item ?? []).map((item) => [item.$.name, item._]));
|
||||
}
|
||||
|
||||
describe("Android app config", () => {
|
||||
afterEach(() => {
|
||||
if (originalFdroidFlag === undefined) {
|
||||
@@ -58,6 +81,12 @@ describe("Android app config", () => {
|
||||
},
|
||||
30_000,
|
||||
);
|
||||
|
||||
// Without it, a dark device paints AppCompat's #303030 between the splash and the first screen.
|
||||
it("paints the app window in the splash colour", async () => {
|
||||
const appTheme = await resolveAndroidAppThemeItems();
|
||||
expect(appTheme["android:windowBackground"]).toBe("@color/splashscreen_background");
|
||||
}, 30_000);
|
||||
});
|
||||
|
||||
it("follows system rotation on Android", async () => {
|
||||
|
||||
@@ -128,6 +128,45 @@ test.describe("Agent profiles in the model picker", () => {
|
||||
}
|
||||
});
|
||||
|
||||
test("the compact drawer keeps a running agent's Profiles collapsed and its rows one height", async ({
|
||||
page,
|
||||
}, testInfo) => {
|
||||
const seed = await seedAgentProfiles([PROFILE]);
|
||||
const workspace = await seedMockAgentWorkspace({
|
||||
repoPrefix: "agent-profiles-compact-running-",
|
||||
title: "Agent profiles compact running",
|
||||
model: "ten-second-stream",
|
||||
modeId: "load-test",
|
||||
});
|
||||
|
||||
try {
|
||||
await page.setViewportSize({ width: 390, height: 800 });
|
||||
await openAgentRoute(page, workspace);
|
||||
await expectComposerVisible(page);
|
||||
await page.getByTestId("combined-model-selector").filter({ visible: true }).first().click();
|
||||
await expect(page.getByTestId("agent-controls-profiles")).toBeVisible();
|
||||
await expect(page.getByTestId("agent-controls-profiles-list")).toHaveCount(0);
|
||||
|
||||
// Settings rows (Model, switches) sit in the same list as the Profiles header and mode rows.
|
||||
const sheet = page.getByTestId("agent-controls-settings-list");
|
||||
const rows = [
|
||||
sheet.getByTestId("agent-controls-profiles"),
|
||||
sheet.getByTestId("agent-controls-model"),
|
||||
sheet.locator('[data-testid^="mode-option-"]').first(),
|
||||
];
|
||||
const heights = [];
|
||||
for (const row of rows) {
|
||||
await expect(row).toBeVisible();
|
||||
heights.push(Math.round((await row.boundingBox())!.height));
|
||||
}
|
||||
await page.screenshot({ path: testInfo.outputPath("compact-agent-settings.png") });
|
||||
expect(new Set(heights).size, `row heights ${heights.join(", ")}`).toBe(1);
|
||||
} finally {
|
||||
await workspace.cleanup();
|
||||
await seed.restore();
|
||||
}
|
||||
});
|
||||
|
||||
test("a model row and its create-profile action are separate buttons", async ({ page }) => {
|
||||
const seed = await seedAgentProfiles([]);
|
||||
const workspace = await seedMockAgentWorkspace({
|
||||
|
||||
@@ -30,6 +30,7 @@ import { openGlobalNewWorkspaceComposer } from "../support/helpers/new-workspace
|
||||
import { clickNewChat, clickNewTerminal, gotoWorkspace } from "../support/helpers/launcher";
|
||||
import { openAgentRoute, seedMockAgentWorkspace } from "../support/helpers/mock-agent";
|
||||
import { seedWorkspace } from "../support/helpers/seed-client";
|
||||
import { waitForSettledPosition } from "../support/helpers/sheet-layout";
|
||||
|
||||
const MOCK_PROVIDER_LABEL = "Mock Load Test";
|
||||
|
||||
@@ -316,13 +317,17 @@ test.describe("Cross-provider model search", () => {
|
||||
await expectComposerFocused(page);
|
||||
});
|
||||
|
||||
await test.step("the compact drawer surfaces collapsed Profiles above Model on Home and keeps provider headers stable on collapse", async () => {
|
||||
await test.step("the compact drawer opens a new agent's Profiles above Model on Home and keeps provider headers stable on collapse", async () => {
|
||||
await page.setViewportSize({ width: 390, height: 800 });
|
||||
await page.getByTestId("combined-model-selector").filter({ visible: true }).first().click();
|
||||
const profilesToggle = page.getByTestId("agent-controls-profiles");
|
||||
const profilesList = page.getByTestId("agent-controls-profiles-list");
|
||||
const modelRowButton = page.getByTestId("agent-controls-model");
|
||||
await expect(profilesToggle).toBeVisible();
|
||||
await expect(page.getByTestId("agent-controls-profiles-list")).toHaveCount(0);
|
||||
await expect(profilesList).toBeVisible();
|
||||
await profilesToggle.click();
|
||||
await expect(profilesList).toHaveCount(0);
|
||||
await waitForSettledPosition(profilesToggle);
|
||||
const profilesBox = await profilesToggle.boundingBox();
|
||||
const modelBox = await modelRowButton.boundingBox();
|
||||
expect(profilesBox && modelBox && profilesBox.y < modelBox.y).toBe(true);
|
||||
@@ -359,6 +364,7 @@ test.describe("Cross-provider model search", () => {
|
||||
|
||||
// Return Home, expand Profiles in place, and apply the profile.
|
||||
await page.getByTestId("sheet-header-back").click();
|
||||
await expect(profilesList).toHaveCount(0);
|
||||
await profilesToggle.click();
|
||||
const sheetProfileRow = page.getByTestId("model-profile-row-agent_profile_e2e_arrows");
|
||||
await expect(sheetProfileRow).toBeVisible();
|
||||
|
||||
@@ -15,6 +15,9 @@ import {
|
||||
expectBothConsecutiveTools,
|
||||
trackPluginChatRecovery,
|
||||
reconnectPluginChat,
|
||||
withRepeatedOutputTimeline,
|
||||
readOldestPluginReplacement,
|
||||
expectOldestPluginReplacementReadable,
|
||||
} from "../support/helpers/plugin-timeline";
|
||||
|
||||
for (const width of [1100, 390]) {
|
||||
@@ -82,3 +85,15 @@ test("plugin-transformed assistant reply keeps copy, fork, and turn duration in
|
||||
expect(await forkAttachment.waitForText()).toContain(ASSISTANT_TEXT);
|
||||
});
|
||||
});
|
||||
|
||||
test("keeps older plugin replacements readable when source messages reuse local output IDs", async ({
|
||||
page,
|
||||
}, info) => {
|
||||
await withRepeatedOutputTimeline(page, info, async () => {
|
||||
await readOldestPluginReplacement(page);
|
||||
await expectOldestPluginReplacementReadable(page);
|
||||
await page.reload({ waitUntil: "domcontentloaded" });
|
||||
await readOldestPluginReplacement(page);
|
||||
await expectOldestPluginReplacementReadable(page);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { createServer, type Socket } from "node:net";
|
||||
import { expect, test, type Page } from "../support/fixtures";
|
||||
import { gotoAppShell } from "../support/helpers/app";
|
||||
import { addScheduleHostAndReload, createScheduleHost } from "../support/helpers/schedule-host";
|
||||
@@ -141,6 +142,68 @@ async function findScheduleIdByName(workspace: SeededWorkspace, name: string): P
|
||||
return schedule.id;
|
||||
}
|
||||
|
||||
async function createConnectingHost() {
|
||||
const sockets = new Set<Socket>();
|
||||
// Accept TCP without completing the WebSocket handshake, like a stalled host.
|
||||
const server = createServer((socket) => {
|
||||
sockets.add(socket);
|
||||
socket.on("close", () => sockets.delete(socket));
|
||||
});
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
server.once("error", reject);
|
||||
server.listen(0, "127.0.0.1", resolve);
|
||||
});
|
||||
const address = server.address();
|
||||
if (!address || typeof address === "string") throw new Error("Expected a TCP address");
|
||||
return {
|
||||
port: address.port,
|
||||
close: async () => {
|
||||
for (const socket of sockets) socket.destroy();
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
server.close((error) => {
|
||||
if (error) {
|
||||
reject(error);
|
||||
return;
|
||||
}
|
||||
resolve();
|
||||
});
|
||||
});
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async function openSchedulesWithConnectingHost(
|
||||
page: Page,
|
||||
cleanupTasks: Array<() => Promise<void>>,
|
||||
): Promise<void> {
|
||||
const workspace = await seedWorkspace({ repoPrefix: "schedule-partial-hosts-", git: false });
|
||||
cleanupTasks.push(() => workspace.cleanup());
|
||||
const stalledHost = await createConnectingHost();
|
||||
cleanupTasks.push(() => stalledHost.close());
|
||||
|
||||
await gotoAppShell(page);
|
||||
await waitForSidebarHydration(page);
|
||||
await page.goto(buildSchedulesRoute());
|
||||
await addScheduleHostAndReload({
|
||||
page,
|
||||
serverId: "stalled-schedule-host",
|
||||
label: "Connecting host",
|
||||
port: stalledHost.port,
|
||||
});
|
||||
}
|
||||
|
||||
async function expectPartialEmptySchedules(page: Page): Promise<void> {
|
||||
await expect(page.getByText("No active schedules", { exact: true })).toBeVisible();
|
||||
await expect(page.getByText("Connecting host: Still connecting", { exact: true })).toBeVisible();
|
||||
await expect(page.getByRole("button", { name: "New schedule", exact: true })).toBeVisible();
|
||||
}
|
||||
|
||||
async function expectScheduleCreationAvailable(page: Page): Promise<void> {
|
||||
await openNewScheduleSheet(page);
|
||||
await page.getByRole("button", { name: "Cancel", exact: true }).click();
|
||||
await expect(page.getByTestId("schedule-form-sheet")).toHaveCount(0);
|
||||
}
|
||||
|
||||
test.describe("Schedules project target", () => {
|
||||
const cleanupTasks: Array<() => Promise<void>> = [];
|
||||
|
||||
@@ -151,6 +214,12 @@ test.describe("Schedules project target", () => {
|
||||
cleanupTasks.length = 0;
|
||||
});
|
||||
|
||||
test("shows empty schedules while another host is still connecting", async ({ page }) => {
|
||||
await openSchedulesWithConnectingHost(page, cleanupTasks);
|
||||
await expectPartialEmptySchedules(page);
|
||||
await expectScheduleCreationAvailable(page);
|
||||
});
|
||||
|
||||
test("dismisses the new schedule sheet without reopening", async ({ page }) => {
|
||||
const workspace = await seedWorkspace({ repoPrefix: "schedule-sheet-dismiss-", git: false });
|
||||
cleanupTasks.push(() => workspace.cleanup());
|
||||
|
||||
@@ -118,10 +118,14 @@ test("projects and pinned chats reorder while ordinary workspaces stay newest fi
|
||||
await firstProject.client.setWorkspacePinned(firstProject.workspaceId, true);
|
||||
await secondProject.client.setWorkspacePinned(secondProject.workspaceId, true);
|
||||
const secondProjectWorkspaceTestId = `sidebar-workspace-row-${getServerId()}:${secondProject.workspaceId}`;
|
||||
// Both rows also exist in their project groups, so match them only once each pin has
|
||||
// moved its row into the Pinned section.
|
||||
await quickDragFirstRowAfterSecond(
|
||||
page.locator(
|
||||
`[data-testid="${firstWorkspaceTestId}"], [data-testid="${secondProjectWorkspaceTestId}"]`,
|
||||
),
|
||||
page
|
||||
.getByTestId("sidebar-pinned-section")
|
||||
.locator(
|
||||
`[data-testid="${firstWorkspaceTestId}"], [data-testid="${secondProjectWorkspaceTestId}"]`,
|
||||
),
|
||||
pressWorkspaceRow,
|
||||
);
|
||||
} finally {
|
||||
|
||||
@@ -392,6 +392,8 @@ test.describe("Terminal protocol queries", () => {
|
||||
await terminalSurface(page).click();
|
||||
await terminalSurface(page).pressSequentially("Q", { delay: 0 });
|
||||
await expectTerminalOutput(lightTerminalId, "WATCH2031_DONE");
|
||||
// One report per switch: a second responder would deliver each switch twice.
|
||||
expect(watch2031Events(await terminalOutput(lightTerminalId))).toEqual(["1", "2"]);
|
||||
|
||||
await selectAppThemeInApp(page, "Dark");
|
||||
await runPaletteChecks(lightTerminalId, TERMINAL_PALETTE_SCENARIOS.dark, {
|
||||
@@ -428,6 +430,10 @@ test.describe("Terminal protocol queries", () => {
|
||||
return capture.lines.join("").replace(/\s/g, "");
|
||||
}
|
||||
|
||||
function watch2031Events(output: string): string[] {
|
||||
return [...output.matchAll(/WATCH2031_EVENT:([12])/g)].map(([, scheme]) => scheme);
|
||||
}
|
||||
|
||||
async function expectTerminalOutput(terminalId: string, text: string): Promise<void> {
|
||||
await expect.poll(() => terminalOutput(terminalId), { timeout: 10_000 }).toContain(text);
|
||||
}
|
||||
|
||||
@@ -46,7 +46,7 @@ import { installDaemonWebSocketGate } from "../support/helpers/daemon-websocket-
|
||||
import { addConnectedHostAndReload, addOfflineHostAndReload } from "../support/helpers/hosts";
|
||||
import { startIsolatedHostDaemon } from "../support/helpers/isolated-host-daemon";
|
||||
|
||||
const LOADING_WORKSPACE_TEXT_PATTERN = /Loading workspace/i;
|
||||
const LOADING_WORKSPACE_TEST_ID = "workspace-loading";
|
||||
async function expectNoLoadingWorkspacePane(
|
||||
page: Page,
|
||||
input: { label: string; durationMs?: number },
|
||||
@@ -63,7 +63,7 @@ async function expectNoLoadingWorkspacePane(
|
||||
.catch((error) => `[body unavailable: ${error instanceof Error ? error.message : error}]`);
|
||||
samples.push(`${Date.now() - startedAt}ms ${url}\n${text.slice(0, 1000)}`);
|
||||
|
||||
if (LOADING_WORKSPACE_TEXT_PATTERN.test(text)) {
|
||||
if ((await page.getByTestId(LOADING_WORKSPACE_TEST_ID).count()) > 0) {
|
||||
throw new Error(
|
||||
`${input.label}: loading workspace pane appeared during reconnect window.\n\n${samples.join(
|
||||
"\n\n---\n\n",
|
||||
@@ -76,7 +76,7 @@ async function expectNoLoadingWorkspacePane(
|
||||
}
|
||||
|
||||
async function expectNoLoadingPane(page: Page): Promise<void> {
|
||||
await expect(page.getByText(LOADING_WORKSPACE_TEXT_PATTERN)).toHaveCount(0);
|
||||
await expect(page.getByTestId(LOADING_WORKSPACE_TEST_ID)).toHaveCount(0);
|
||||
}
|
||||
|
||||
async function getVisibleDraftTabCount(page: Page): Promise<number> {
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { execFileSync } from "node:child_process";
|
||||
import { setTimeout } from "node:timers/promises";
|
||||
|
||||
// Opening a file from the filtered Files tree must close the software keyboard.
|
||||
//
|
||||
// Before running, on a phone-sized device with a software keyboard enabled, open
|
||||
// Explorer -> Files in a workspace where the first match for the query is a file.
|
||||
// The app must already run the checkout being verified against a real daemon.
|
||||
const serial = process.env.ANDROID_SERIAL ?? "emulator-5554";
|
||||
const query = process.env.PASEO_FILES_FILTER_QUERY ?? "README";
|
||||
|
||||
function adb(...args) {
|
||||
return execFileSync("adb", ["-s", serial, ...args], { encoding: "utf8", timeout: 60_000 });
|
||||
}
|
||||
function findNode(id) {
|
||||
adb("shell", "uiautomator", "dump", "/sdcard/files-filter-keyboard.xml");
|
||||
const tree = adb("exec-out", "cat", "/sdcard/files-filter-keyboard.xml");
|
||||
const node = tree.match(new RegExp(`<node [^>]*resource-id="${id}"[^>]*>`))?.[0];
|
||||
const bounds = node?.match(/bounds="\[(\d+),(\d+)\]\[(\d+),(\d+)\]"/);
|
||||
if (!bounds) return null;
|
||||
const [left, top, right, bottom] = bounds.slice(1).map(Number);
|
||||
return { x: Math.round((left + right) / 2), y: Math.round((top + bottom) / 2) };
|
||||
}
|
||||
async function waitForNode(id) {
|
||||
const deadline = Date.now() + 30_000;
|
||||
while (Date.now() < deadline) {
|
||||
const node = findNode(id);
|
||||
if (node) return node;
|
||||
await setTimeout(250);
|
||||
}
|
||||
throw new Error(`Timed out waiting for ${id}`);
|
||||
}
|
||||
function tap({ x, y }) {
|
||||
adb("shell", "input", "tap", String(x), String(y));
|
||||
}
|
||||
async function waitForKeyboard(shown) {
|
||||
let stable = 0;
|
||||
const deadline = Date.now() + 10_000;
|
||||
while (Date.now() < deadline) {
|
||||
const state = adb("shell", "dumpsys", "input_method");
|
||||
stable = /^ {2}mInputShown=true$/m.test(state) === shown ? stable + 1 : 0;
|
||||
if (stable === 3) return;
|
||||
await setTimeout(200);
|
||||
}
|
||||
assert.fail(`Keyboard did not settle at shown=${shown}`);
|
||||
}
|
||||
|
||||
const clear = findNode("files-filter-clear");
|
||||
if (clear) tap(clear);
|
||||
tap(await waitForNode("files-filter-input"));
|
||||
await waitForKeyboard(true);
|
||||
adb("shell", "input", "text", query);
|
||||
const match = await waitForNode("file-filter-row-0");
|
||||
await waitForKeyboard(true); // Typing and new results leave the keyboard up.
|
||||
|
||||
tap(match);
|
||||
await waitForNode("sheet-tab-body");
|
||||
await waitForKeyboard(false);
|
||||
console.log("PASS: opening a filtered file closes the keyboard");
|
||||
@@ -18,6 +18,9 @@ press "id=\"combined-model-selector\""
|
||||
wait "id=\"model-provider-${PROVIDER_ID}\"" 10000
|
||||
press "id=\"model-provider-${PROVIDER_ID}\""
|
||||
wait "id=\"model-row-${PROVIDER_ID}-${MODEL_ID}\"" 3000
|
||||
# Back takes the header's step to the provider list first, then dismisses the modal.
|
||||
back
|
||||
wait "id=\"model-provider-${PROVIDER_ID}\"" 3000
|
||||
back
|
||||
wait "id=\"combined-model-selector\" label=\"Select model (${MODEL_LABEL})\"" 3000
|
||||
close
|
||||
|
||||
@@ -10,13 +10,13 @@ wait "id=\"agent-controls-model\"" 10000
|
||||
gesture pan 540 790 0 960 500
|
||||
wait "id=\"combined-model-selector\"" 3000
|
||||
|
||||
# Reopen, dismiss the nested model browser, then dismiss its restored parent.
|
||||
# Android Back steps from Model back to Agent settings, then closes the sheet.
|
||||
press "id=\"combined-model-selector\""
|
||||
wait "id=\"agent-controls-model\"" 10000
|
||||
press "id=\"agent-controls-model\""
|
||||
wait stable 300 5000
|
||||
gesture pan 540 790 0 960 500
|
||||
wait "id=\"model-search-all-input\"" 10000
|
||||
back
|
||||
wait "id=\"agent-controls-model\"" 3000
|
||||
gesture pan 540 790 0 960 500
|
||||
back
|
||||
wait "id=\"combined-model-selector\"" 3000
|
||||
close
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
# Open Pi settings from the Android model picker. Scroll the sheet body until
|
||||
# most of the Models list is visible. Use a host with several Pi models and
|
||||
# the default shown-models selection.
|
||||
session="${1:?Pass the agent-device session with the Pi provider sheet open}"
|
||||
artifacts="${2:-.artifacts/provider-model-scroll}"
|
||||
mkdir -p "$artifacts"
|
||||
|
||||
ad() {
|
||||
agent-device "$@" --session "$session"
|
||||
}
|
||||
|
||||
visible_rows() {
|
||||
jq -ce '
|
||||
.data.nodes as $nodes
|
||||
| ($nodes[] | select(.identifier == "provider-discovered-models")) as $list
|
||||
| [$nodes[]
|
||||
| select((.identifier // "") | startswith("provider-shown-model-"))
|
||||
| select(.rect.height > 0 and .rect.y < ($list.rect.y + $list.rect.height))
|
||||
| select(.rect.y + .rect.height > $list.rect.y)
|
||||
| .label]
|
||||
| select(length > 1)
|
||||
' "$1"
|
||||
}
|
||||
|
||||
ad snapshot --json > "$artifacts/before.json"
|
||||
read -r x y dy < <(jq -er '
|
||||
.data.nodes[]
|
||||
| select(.identifier == "provider-discovered-models" and .rect.height >= 350)
|
||||
| .rect
|
||||
| [(.x + .width / 2 | floor), (.y + .height * 0.7 | floor), (-.height * 0.5 | floor)]
|
||||
| @tsv
|
||||
' "$artifacts/before.json") || {
|
||||
printf 'Scroll the sheet body until the Models list is visible.\n' >&2
|
||||
exit 1
|
||||
}
|
||||
before=$(visible_rows "$artifacts/before.json")
|
||||
ad gesture pan "$x" "$y" 0 "$dy" 580
|
||||
ad snapshot --json > "$artifacts/after.json"
|
||||
after=$(visible_rows "$artifacts/after.json")
|
||||
|
||||
printf 'Before %s\nAfter %s\n' "$before" "$after"
|
||||
first=$(jq -r '.[0]' <<<"$before")
|
||||
if jq -e --arg first "$first" 'index($first) != null' <<<"$after" >/dev/null; then
|
||||
printf 'The first model stayed visible after the upward drag.\n' >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
model=$(jq -r '.[1]' <<<"$after")
|
||||
ad press "role=checkbox label=\"$model\"" --settle
|
||||
ad snapshot --json > "$artifacts/checked.json"
|
||||
jq -e --arg model "$model" '
|
||||
any(.data.nodes[]; .kind == "checkbox" and .label == $model and .checked == true)
|
||||
' "$artifacts/checked.json" >/dev/null
|
||||
ad press 'id="provider-shown-models-reset"' --settle
|
||||
ad snapshot --json > "$artifacts/reset.json"
|
||||
jq -e --arg model "$model" '
|
||||
any(.data.nodes[]; .kind == "checkbox" and .label == $model and .checked == false)
|
||||
' "$artifacts/reset.json" >/dev/null
|
||||
@@ -7,6 +7,7 @@ import { connectNewWorkspaceDaemonClient } from "./new-workspace";
|
||||
import { openAgentRoute, seedMockAgentWorkspace, type MockAgentWorkspace } from "./mock-agent";
|
||||
import { installDaemonWebSocketGate } from "./daemon-websocket-gate";
|
||||
import { expectReconnectingToastVisible } from "./workspace-ui";
|
||||
import { userScrollsTimelineToHistoryStart } from "./timeline-pagination";
|
||||
|
||||
const PLUGIN_ID = "timeline-transform-e2e";
|
||||
|
||||
@@ -373,3 +374,81 @@ export async function viewInlineThinkingExample(page: Page, info: TestInfo): Pro
|
||||
await example.cleanup();
|
||||
}
|
||||
}
|
||||
|
||||
/** Reuse plugin-local IDs across distinct source messages in a real virtualized chat. */
|
||||
export async function withRepeatedOutputTimeline(
|
||||
page: Page,
|
||||
info: TestInfo,
|
||||
run: () => Promise<void>,
|
||||
): Promise<void> {
|
||||
info.setTimeout(120_000);
|
||||
const agent = await seedMockAgentWorkspace({
|
||||
repoPrefix: "timeline-local-ids-",
|
||||
title: "Repeated plugin output IDs",
|
||||
});
|
||||
try {
|
||||
for (const label of ["First", "Second", "Third"]) {
|
||||
await agent.client.sendAgentMessage(
|
||||
agent.agentId,
|
||||
`${label}: emit 1 coalesced agent stream updates`,
|
||||
);
|
||||
await agent.client.waitForFinish(agent.agentId, 15_000);
|
||||
}
|
||||
await withDirectoryPlugin({
|
||||
pluginId: "timeline-local-ids",
|
||||
source: `import React from "react";
|
||||
import { Text, View } from "react-native";
|
||||
import { z } from "zod";
|
||||
function Row({ item }) {
|
||||
return <View style={{ height: item.data.tall ? 120 : 24 }}>
|
||||
<Text>{item.data.label}</Text>
|
||||
</View>;
|
||||
}
|
||||
export default function contribute(client) {
|
||||
client.addTimelineTransformer({
|
||||
id: "local-ids", query: { itemType: "user_message" },
|
||||
transform({ item }) {
|
||||
const label = item.text.split(":")[0];
|
||||
return { items: Array.from({ length: 60 }, (_, index) => ({
|
||||
type: "plugin", id: "part-" + index, kind: "reply", version: 1,
|
||||
data: { label: label + " replacement " + index, tall: label === "Second" },
|
||||
})) };
|
||||
},
|
||||
});
|
||||
client.addTimelineRenderer({
|
||||
kind: "reply", version: 1,
|
||||
schema: z.object({ label: z.string(), tall: z.boolean() }), Component: Row,
|
||||
});
|
||||
return () => {};
|
||||
}`,
|
||||
run: async () => {
|
||||
await openAgentRoute(page, agent);
|
||||
await expect(page.getByRole("textbox", { name: "Message agent..." }).first()).toBeVisible();
|
||||
await run();
|
||||
},
|
||||
});
|
||||
} finally {
|
||||
await agent.cleanup();
|
||||
}
|
||||
}
|
||||
|
||||
export async function readOldestPluginReplacement(page: Page): Promise<void> {
|
||||
await expect(page.getByText("Third replacement 59", { exact: true }).first()).toBeAttached();
|
||||
await expect
|
||||
.poll(async () => {
|
||||
await userScrollsTimelineToHistoryStart(page);
|
||||
return page.getByText("First replacement 0", { exact: true }).isVisible();
|
||||
})
|
||||
.toBe(true);
|
||||
}
|
||||
|
||||
export async function expectOldestPluginReplacementReadable(page: Page): Promise<void> {
|
||||
await expect(
|
||||
page
|
||||
.getByTestId("agent-chat-scroll")
|
||||
.locator("[data-index]")
|
||||
.getByText("First replacement 0", { exact: true }),
|
||||
).toBeVisible();
|
||||
await expect(page.getByRole("textbox", { name: "Message agent..." }).first()).toBeVisible();
|
||||
await expect(page.getByText("Paseo ran into a problem.", { exact: true })).toHaveCount(0);
|
||||
}
|
||||
|
||||
@@ -61,18 +61,24 @@ async function readRows(input: {
|
||||
storeName: string;
|
||||
}): Promise<ReplicaRowRecord[]> {
|
||||
const database = await new Promise<IDBDatabase>((resolve, reject) => {
|
||||
const request = indexedDB.open(input.databaseName, 1);
|
||||
request.addEventListener("success", () => resolve(request.result));
|
||||
request.addEventListener("error", () => reject(request.error));
|
||||
});
|
||||
return new Promise((resolve, reject) => {
|
||||
const request = database
|
||||
.transaction(input.storeName, "readonly")
|
||||
.objectStore(input.storeName)
|
||||
.getAll();
|
||||
// The app owns the database version; open whatever version it created.
|
||||
const request = indexedDB.open(input.databaseName);
|
||||
request.addEventListener("success", () => resolve(request.result));
|
||||
request.addEventListener("error", () => reject(request.error));
|
||||
});
|
||||
try {
|
||||
return await new Promise((resolve, reject) => {
|
||||
const request = database
|
||||
.transaction(input.storeName, "readonly")
|
||||
.objectStore(input.storeName)
|
||||
.getAll();
|
||||
request.addEventListener("success", () => resolve(request.result));
|
||||
request.addEventListener("error", () => reject(request.error));
|
||||
});
|
||||
} finally {
|
||||
// An open connection would block the app from upgrading the database.
|
||||
database.close();
|
||||
}
|
||||
}
|
||||
|
||||
function assembleCache(rows: ReplicaRowRecord[]): ReplicaCacheRecord {
|
||||
@@ -185,19 +191,27 @@ export async function writeReplicaCache(page: Page, value: ReplicaCacheRecord):
|
||||
await page.evaluate(
|
||||
async ({ databaseName, storeName, nextRows }) => {
|
||||
const database = await new Promise<IDBDatabase>((resolve, reject) => {
|
||||
const request = indexedDB.open(databaseName, 1);
|
||||
const request = indexedDB.open(databaseName);
|
||||
request.addEventListener("success", () => resolve(request.result));
|
||||
request.addEventListener("error", () => reject(request.error));
|
||||
});
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
const transaction = database.transaction(storeName, "readwrite");
|
||||
const store = transaction.objectStore(storeName);
|
||||
store.clear();
|
||||
for (const row of nextRows) store.put(row);
|
||||
transaction.addEventListener("complete", () => resolve());
|
||||
transaction.addEventListener("error", () => reject(transaction.error));
|
||||
transaction.addEventListener("abort", () => reject(transaction.error));
|
||||
});
|
||||
try {
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
const transaction = database.transaction(storeName, "readwrite");
|
||||
const store = transaction.objectStore(storeName);
|
||||
store.clear();
|
||||
// The app budgets the cache on each row's recorded UTF-8 payload size.
|
||||
const encoder = new TextEncoder();
|
||||
for (const row of nextRows) {
|
||||
store.put({ ...row, payloadBytes: encoder.encode(row.payload).length });
|
||||
}
|
||||
transaction.addEventListener("complete", () => resolve());
|
||||
transaction.addEventListener("error", () => reject(transaction.error));
|
||||
transaction.addEventListener("abort", () => reject(transaction.error));
|
||||
});
|
||||
} finally {
|
||||
database.close();
|
||||
}
|
||||
},
|
||||
{ databaseName: DATABASE_NAME, storeName: STORE_NAME, nextRows: rows },
|
||||
);
|
||||
|
||||
@@ -173,8 +173,11 @@ export async function expectHostConnectingOrOffline(
|
||||
page: Page,
|
||||
options?: { timeout?: number },
|
||||
): Promise<void> {
|
||||
// A host that is still connecting shows the workspace loading state; one that failed says so.
|
||||
await expect(
|
||||
page.getByText(/^Connecting$|localhost is offline|Cannot reach localhost/i),
|
||||
page
|
||||
.getByTestId("workspace-loading")
|
||||
.or(page.getByText(/localhost is offline|Cannot reach localhost/i)),
|
||||
).toBeVisible({ timeout: options?.timeout ?? 30_000 });
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
// Install runtime polyfills before any other module evaluates. Keep this the first import.
|
||||
// oxlint-disable-next-line import/no-unassigned-import -- Polyfills install on import.
|
||||
import "./src/polyfills/install-early";
|
||||
import { keepNativeSplash } from "./src/native-splash";
|
||||
keepNativeSplash();
|
||||
|
||||
// Configure Unistyles before Expo Router pulls in any components using StyleSheet.
|
||||
import "./src/styles/unistyles";
|
||||
|
||||
+93
-13
@@ -1,11 +1,13 @@
|
||||
package sh.paseo.terminal
|
||||
|
||||
import android.os.Build
|
||||
import android.text.InputType
|
||||
import android.view.KeyCharacterMap
|
||||
import android.view.KeyEvent
|
||||
import android.view.View
|
||||
import android.view.inputmethod.EditorInfo
|
||||
import androidx.test.ext.junit.runners.AndroidJUnit4
|
||||
import androidx.test.filters.SdkSuppress
|
||||
import androidx.test.platform.app.InstrumentationRegistry
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
@@ -77,6 +79,15 @@ class TerminalInputConnectionTest {
|
||||
}
|
||||
}
|
||||
|
||||
/** Gboard commits each letter in its own batch edit when the editor disables suggestions. */
|
||||
private fun TerminalInputConnection.typeLikeGboard(text: String) {
|
||||
for (ch in text) {
|
||||
beginBatchEdit()
|
||||
commitText(ch.toString(), 1)
|
||||
endBatchEdit()
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun editorInfoDisablesSuggestionsFullscreenAndPersonalizedLearning() {
|
||||
instrumentation.runOnMainSync {
|
||||
@@ -100,13 +111,8 @@ class TerminalInputConnectionTest {
|
||||
@Test
|
||||
fun batchedCommitTextAndSetComposingTextDoNotDoubleCharacters() {
|
||||
withInputHarness { _, ic, _, terminal ->
|
||||
for (ch in listOf("a", "b", "c", "d")) {
|
||||
ic.beginBatchEdit()
|
||||
ic.commitText(ch, 1)
|
||||
ic.endBatchEdit()
|
||||
}
|
||||
ic.typeLikeGboard("abcd")
|
||||
assertEquals("abcd", terminal.rawStream)
|
||||
assertEquals("", ic.editable.toString())
|
||||
|
||||
// Coalesced setComposingText + finishComposingText inside one batch emits once.
|
||||
ic.beginBatchEdit()
|
||||
@@ -114,28 +120,96 @@ class TerminalInputConnectionTest {
|
||||
ic.finishComposingText()
|
||||
ic.endBatchEdit()
|
||||
assertEquals("abcdef", terminal.rawStream)
|
||||
assertEquals("", ic.editable.toString())
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun editorKeepsTheTypedLineUntilTerminalKeyBoundary() {
|
||||
withInputHarness { _, ic, _, terminal ->
|
||||
// IMEs address edits by offsets into the text they committed, so the editor must keep it.
|
||||
ic.typeLikeGboard("ab")
|
||||
assertEquals("ab", ic.getTextBeforeCursor(10, 0).toString())
|
||||
|
||||
// Enter leaves the shell line, so the editor starts the next line empty.
|
||||
ic.sendKeyEvent(KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_ENTER))
|
||||
ic.sendKeyEvent(KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_ENTER))
|
||||
assertEquals("", ic.getTextBeforeCursor(10, 0).toString())
|
||||
|
||||
ic.typeLikeGboard("helo")
|
||||
ic.beginBatchEdit()
|
||||
ic.setComposingRegion(0, 4)
|
||||
ic.commitText("hello ", 1)
|
||||
ic.endBatchEdit()
|
||||
assertEquals("ab\rhello ", terminal.applyToLine())
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun gboardArrowKeyStartsTheEditorOnAnEmptyLine() {
|
||||
withInputHarness { _, ic, _, terminal ->
|
||||
ic.typeLikeGboard("echo helo")
|
||||
// Gboard's editing panel sends arrows as key events. The shell cursor moves, so the
|
||||
// editor's copy of the line no longer matches where the next edit lands.
|
||||
ic.sendKeyEvent(KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DPAD_LEFT))
|
||||
ic.sendKeyEvent(KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_DPAD_LEFT))
|
||||
assertEquals("", ic.getTextBeforeCursor(10, 0).toString())
|
||||
assertEquals(listOf("ArrowLeft"), terminal.keys.map { it.key })
|
||||
assertEquals("echo helo", terminal.rawStream)
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun suggestionPickedThroughComposingRegionReplacesCommittedWord() {
|
||||
withInputHarness { _, ic, _, terminal ->
|
||||
// Gboard before Android 14 selects the committed word, then commits the suggestion.
|
||||
ic.typeLikeGboard("helo")
|
||||
ic.beginBatchEdit()
|
||||
ic.setComposingRegion(3, 4)
|
||||
ic.commitText("lo ", 1)
|
||||
ic.endBatchEdit()
|
||||
assertEquals("hello ", terminal.applyToLine())
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
@SdkSuppress(minSdkVersion = Build.VERSION_CODES.UPSIDE_DOWN_CAKE)
|
||||
fun gboardReplaceTextRewritesCommittedText() {
|
||||
// Gboard on Android 14+ picks suggestions and applies double-space period with replaceText,
|
||||
// addressing text it committed earlier. Offsets and texts below are the calls Gboard made live.
|
||||
fun assertReplacement(typed: String, start: Int, end: Int, replacement: String, line: String) {
|
||||
withInputHarness { _, ic, _, terminal ->
|
||||
ic.typeLikeGboard(typed)
|
||||
ic.beginBatchEdit()
|
||||
ic.replaceText(start, end, replacement, 1, null)
|
||||
ic.endBatchEdit()
|
||||
assertEquals("$typed -> $replacement", line, terminal.applyToLine())
|
||||
}
|
||||
}
|
||||
|
||||
assertReplacement("helo", 3, 4, "lo ", line = "hello ")
|
||||
assertReplacement("helo", 3, 4, "p ", line = "help ")
|
||||
assertReplacement("echo hello", 5, 10, "jello ", line = "echo jello ")
|
||||
assertReplacement("ab ", 2, 3, ". ", line = "ab. ")
|
||||
}
|
||||
|
||||
@Test
|
||||
fun backspaceWorksAcrossAllThreeImePaths() {
|
||||
withInputHarness { _, ic, _, terminal ->
|
||||
ic.commitText("abcd", 1)
|
||||
assertEquals("abcd", terminal.applyToLine())
|
||||
|
||||
// Path 1: deleteSurroundingText (empty editable after commit)
|
||||
// Path 1: deleteSurroundingText
|
||||
ic.deleteSurroundingText(0, 0)
|
||||
assertEquals("abcd", terminal.applyToLine())
|
||||
ic.deleteSurroundingText(1, 0)
|
||||
assertEquals("abc", terminal.applyToLine())
|
||||
|
||||
// Path 2: deleteSurroundingTextInCodePoints (empty editable)
|
||||
// Path 2: deleteSurroundingTextInCodePoints
|
||||
ic.deleteSurroundingTextInCodePoints(1, 0)
|
||||
assertEquals("ab", terminal.applyToLine())
|
||||
|
||||
// Path 2b: deleteSurroundingTextInCodePoints on surrogate-pair emoji in composing buffer
|
||||
ic.setComposingText("😀", 1)
|
||||
// Path 2b: deleteSurroundingTextInCodePoints removes a surrogate-pair emoji as one code point
|
||||
ic.commitText("😀", 1)
|
||||
assertEquals("ab😀", terminal.applyToLine())
|
||||
ic.deleteSurroundingTextInCodePoints(1, 0)
|
||||
assertEquals("ab", terminal.applyToLine())
|
||||
@@ -145,10 +219,16 @@ class TerminalInputConnectionTest {
|
||||
ic.sendKeyEvent(KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_DEL))
|
||||
assertEquals("a", terminal.applyToLine())
|
||||
|
||||
// Multi-char deleteSurroundingText on empty buffer
|
||||
// Multi-char deleteSurroundingText
|
||||
ic.commitText("xyz", 1)
|
||||
ic.deleteSurroundingText(2, 0)
|
||||
assertEquals("ax", terminal.applyToLine())
|
||||
|
||||
// After Enter the editor is empty, so Backspace still reaches text the shell already holds
|
||||
ic.sendKeyEvent(KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_ENTER))
|
||||
ic.deleteSurroundingText(1, 0)
|
||||
ic.deleteSurroundingTextInCodePoints(1, 0)
|
||||
assertEquals("\r\u007f\u007f", terminal.rawStream.takeLast(3))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -242,7 +322,7 @@ class TerminalInputConnectionTest {
|
||||
ic.commitText("the", 1)
|
||||
assertEquals("hellothe", terminal.applyToLine())
|
||||
|
||||
// Repeated clipboard paste of identical text works because editable clears after commit
|
||||
// Repeated clipboard paste of identical text appends both copies
|
||||
ic.commitText("echo ok", 1)
|
||||
ic.commitText("echo ok", 1)
|
||||
assertEquals("hellotheecho okecho ok", terminal.applyToLine())
|
||||
|
||||
+33
-48
@@ -22,9 +22,16 @@ internal data class TerminalKeyPayload(
|
||||
/**
|
||||
* Single authoritative IME + key stream for the Android native terminal.
|
||||
*
|
||||
* Keeps a private [SpannableStringBuilder] so Android IMEs can compose Hangul, Pinyin, and Latin
|
||||
* candidates normally, diffs the editable against what was last sent to the PTY once each batch
|
||||
* edit settles, and clears the editable as soon as no composing span remains.
|
||||
* The private [SpannableStringBuilder] holds the text the IME has typed on the current shell line,
|
||||
* committed and composing alike. IMEs keep their own copy of that text and edit it by offset:
|
||||
* Gboard picks a suggestion or applies double-space period by replacing text it committed
|
||||
* earlier. Once each batch edit settles, the editable is diffed against what the terminal already
|
||||
* holds and only the difference is sent, as rubouts plus the new suffix.
|
||||
*
|
||||
* A terminal key (Enter, Tab, Escape, arrows, control and hardware characters) changes the shell
|
||||
* line outside the IME, so it empties the editable and restarts the IME on the empty line.
|
||||
* Keys sent to the terminal without passing through this connection do not empty it: the
|
||||
* accessory bar, and the hardware arrows that `PaseoHardwareKeyboardModule` claims at window level.
|
||||
*/
|
||||
internal class TerminalInputConnection(
|
||||
private val targetView: View,
|
||||
@@ -196,6 +203,7 @@ internal class TerminalInputConnection(
|
||||
KeyEvent.KEYCODE_DPAD_LEFT,
|
||||
KeyEvent.KEYCODE_DPAD_RIGHT -> {
|
||||
deadAccent = 0
|
||||
flushAndClear()
|
||||
val name = when (keyCode) {
|
||||
KeyEvent.KEYCODE_DPAD_UP -> "ArrowUp"
|
||||
KeyEvent.KEYCODE_DPAD_DOWN -> "ArrowDown"
|
||||
@@ -342,57 +350,38 @@ internal class TerminalInputConnection(
|
||||
if (diff.isNotEmpty()) {
|
||||
out.append(normalizeLineEndings(diff))
|
||||
}
|
||||
lastSentText = currentText
|
||||
|
||||
val compStart = getComposingSpanStart(sharedEditable)
|
||||
val compEnd = getComposingSpanEnd(sharedEditable)
|
||||
val isComposing = compStart >= 0 && compEnd > compStart
|
||||
|
||||
if (!isComposing) {
|
||||
val hadText = sharedEditable.isNotEmpty()
|
||||
if (hadText || compStart >= 0) {
|
||||
clearEditableSilently()
|
||||
}
|
||||
lastSentText = ""
|
||||
if (hadText) {
|
||||
// The IME just advanced its cursor for the committed text; report the reset to 0, 0.
|
||||
forceUpdateSelection(0, 0, -1, -1)
|
||||
} else {
|
||||
notifySelectionIfChanged(0, 0, -1, -1)
|
||||
}
|
||||
} else {
|
||||
lastSentText = currentText
|
||||
val selStart = maxOf(0, Selection.getSelectionStart(sharedEditable))
|
||||
val selEnd = maxOf(0, Selection.getSelectionEnd(sharedEditable))
|
||||
notifySelectionIfChanged(selStart, selEnd, compStart, compEnd)
|
||||
var compStart = getComposingSpanStart(sharedEditable)
|
||||
var compEnd = getComposingSpanEnd(sharedEditable)
|
||||
if (compStart >= 0 && compEnd <= compStart) {
|
||||
// An empty composing span would make hardware arrows look like IME navigation.
|
||||
removeComposingSpans(sharedEditable)
|
||||
compStart = -1
|
||||
compEnd = -1
|
||||
}
|
||||
notifySelectionIfChanged(
|
||||
maxOf(0, Selection.getSelectionStart(sharedEditable)),
|
||||
maxOf(0, Selection.getSelectionEnd(sharedEditable)),
|
||||
compStart,
|
||||
compEnd,
|
||||
)
|
||||
|
||||
if (out.isNotEmpty()) {
|
||||
onInput(out.toString())
|
||||
}
|
||||
}
|
||||
|
||||
/** Sends pending IME text, then starts the IME on an empty line before a terminal key. */
|
||||
private fun flushAndClear() {
|
||||
batchEditDepth = 0
|
||||
val hadText = sharedEditable.isNotEmpty()
|
||||
val out = StringBuilder()
|
||||
if (pendingBackspaces > 0) {
|
||||
repeat(pendingBackspaces) { out.append('\u007f') }
|
||||
pendingBackspaces = 0
|
||||
}
|
||||
val currentText = sharedEditable.toString()
|
||||
val diff = computeDiff(lastSentText, currentText)
|
||||
if (diff.isNotEmpty()) {
|
||||
out.append(normalizeLineEndings(diff))
|
||||
}
|
||||
if (hadText || getComposingSpanStart(sharedEditable) >= 0) {
|
||||
clearEditableSilently()
|
||||
}
|
||||
lastSentText = ""
|
||||
if (hadText || lastSelStart != 0 || lastSelEnd != 0 || lastCompStart != -1 || lastCompEnd != -1) {
|
||||
forceUpdateSelection(0, 0, -1, -1)
|
||||
}
|
||||
if (out.isNotEmpty()) {
|
||||
onInput(out.toString())
|
||||
flush()
|
||||
if (sharedEditable.isEmpty()) return
|
||||
resetState()
|
||||
// The IME still holds the old line; updateSelection alone does not make Gboard reload it.
|
||||
val imm = targetView.context.getSystemService(InputMethodManager::class.java) ?: return
|
||||
if (imm.isActive(targetView)) {
|
||||
imm.restartInput(targetView)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -411,10 +400,6 @@ internal class TerminalInputConnection(
|
||||
) {
|
||||
return
|
||||
}
|
||||
forceUpdateSelection(selStart, selEnd, compStart, compEnd)
|
||||
}
|
||||
|
||||
private fun forceUpdateSelection(selStart: Int, selEnd: Int, compStart: Int, compEnd: Int) {
|
||||
lastSelStart = selStart
|
||||
lastSelEnd = selEnd
|
||||
lastCompStart = compStart
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
const { AndroidConfig, withAndroidStyles } = require("expo/config-plugins");
|
||||
|
||||
// The activity window shows under the splash while it fades out and until React
|
||||
// paints. Expo's AppTheme sets no window background, so Android paints the
|
||||
// AppCompat default (#303030 in dark mode, #fafafa in light mode) there.
|
||||
// expo-splash-screen already defines `splashscreen_background` for day and night,
|
||||
// so pointing the window at it keeps one colour from launch to the first screen.
|
||||
const WINDOW_BACKGROUND = "@color/splashscreen_background";
|
||||
|
||||
function withAndroidSplashWindowBackground(config) {
|
||||
return withAndroidStyles(config, (modConfig) => {
|
||||
modConfig.modResults = AndroidConfig.Styles.assignStylesValue(modConfig.modResults, {
|
||||
add: true,
|
||||
parent: AndroidConfig.Styles.getAppThemeGroup(),
|
||||
name: "android:windowBackground",
|
||||
value: WINDOW_BACKGROUND,
|
||||
});
|
||||
return modConfig;
|
||||
});
|
||||
}
|
||||
|
||||
module.exports = withAndroidSplashWindowBackground;
|
||||
@@ -43,6 +43,8 @@ export interface AgentProfilePickerRow {
|
||||
export interface AgentProfilePicker {
|
||||
rows: AgentProfilePickerRow[];
|
||||
applyProfile: (profileId: string) => void;
|
||||
/** What a picked profile configures: a running agent, or the draft of a new one. */
|
||||
target: AgentProfileApplyTarget["kind"];
|
||||
}
|
||||
|
||||
export interface UseAgentProfilePickerInput {
|
||||
@@ -166,7 +168,7 @@ export function useAgentProfilePicker(
|
||||
);
|
||||
|
||||
return useMemo(
|
||||
() => (isSupported && profiles !== null ? { rows, applyProfile } : null),
|
||||
[applyProfile, isSupported, profiles, rows],
|
||||
() => (isSupported && profiles !== null ? { rows, applyProfile, target: target.kind } : null),
|
||||
[applyProfile, isSupported, profiles, rows, target.kind],
|
||||
);
|
||||
}
|
||||
|
||||
@@ -603,14 +603,15 @@ describe("layoutStream", () => {
|
||||
splitIntoCards,
|
||||
);
|
||||
|
||||
const layout = layoutFor({
|
||||
platform,
|
||||
tail,
|
||||
timingIds: ["genui/a1/card", "genui/a2/card"],
|
||||
});
|
||||
const footerCardIds = tail
|
||||
.filter((item) => item.kind === "plugin" && item.itemKind === "genui-card")
|
||||
.map((item) => item.id);
|
||||
expect(footerCardIds).toHaveLength(2);
|
||||
|
||||
expect(footerOwners(layout)).toEqual(["genui/a1/card", "genui/a2/card"]);
|
||||
expect(findLayoutItem(layout, "genui/a1/card").completedFooter?.turnMetrics).toBe(
|
||||
const layout = layoutFor({ platform, tail, timingIds: footerCardIds });
|
||||
|
||||
expect(footerOwners(layout)).toEqual(footerCardIds);
|
||||
expect(findLayoutItem(layout, footerCardIds[0]).completedFooter?.turnMetrics).toBe(
|
||||
first.turnMetrics,
|
||||
);
|
||||
expect(layout.auxiliaryTurnFooter?.turnMetrics).toBe(metrics);
|
||||
|
||||
@@ -203,7 +203,9 @@ describe("stream presentation through installed plugins", () => {
|
||||
const source = rows(harness.source());
|
||||
|
||||
expect(source).toMatchObject([{ kind: "user_message", id: "prompt-1" }]);
|
||||
expect(rendered).toMatchObject([{ kind: "plugin", id: "probe-plugin/prompt-1/0" }]);
|
||||
expect(rendered).toMatchObject([
|
||||
{ kind: "plugin", source: { id: "prompt-1" }, pluginItemId: "prompt-1/0" },
|
||||
]);
|
||||
// The chat outline jumps to the source id; the row it lands on is the plugin's.
|
||||
expect(rendered.map(getStreamItemMessageId)).toEqual(["prompt-1"]);
|
||||
});
|
||||
@@ -611,7 +613,7 @@ it("folds work before a plugin-rendered reply and leaves the reply visible", ()
|
||||
expect(result.tail.map((item) => item.id)).toEqual([
|
||||
"prompt",
|
||||
"turn-summary:prompt",
|
||||
"probe-plugin/reply/0",
|
||||
JSON.stringify(["probe-plugin", "reply", "reply/0"]),
|
||||
]);
|
||||
expect(pluginData(result.tail)).toEqual([{ text: "$$x^2$$", phase: "complete" }]);
|
||||
});
|
||||
@@ -640,7 +642,7 @@ it("keeps streaming replies native, then folds work without losing manual expans
|
||||
expect(present(completed).tail.map((item) => item.id)).toEqual([
|
||||
"prompt",
|
||||
"turn-summary:prompt",
|
||||
"probe-plugin/reply/0",
|
||||
JSON.stringify(["probe-plugin", "reply", "reply/0"]),
|
||||
]);
|
||||
const expandedTurnHostIds = new Set(["prompt"]);
|
||||
const opened = present({ ...completed, expandedTurnHostIds });
|
||||
@@ -648,14 +650,16 @@ it("keeps streaming replies native, then folds work without losing manual expans
|
||||
"prompt",
|
||||
"turn-summary:prompt",
|
||||
"tool-one",
|
||||
"probe-plugin/reply/0",
|
||||
JSON.stringify(["probe-plugin", "reply", "reply/0"]),
|
||||
]);
|
||||
expect(opened.turns.nestedItemIds.has("probe-plugin/reply/0")).toBe(false);
|
||||
expect(opened.turns.nestedItemIds.has(JSON.stringify(["probe-plugin", "reply", "reply/0"]))).toBe(
|
||||
false,
|
||||
);
|
||||
expect(present({ ...completed, expandedTurnHostIds }).tail).toEqual(opened.tail);
|
||||
expect(present(completed).tail.map((item) => item.id)).toEqual([
|
||||
"prompt",
|
||||
"turn-summary:prompt",
|
||||
"probe-plugin/reply/0",
|
||||
JSON.stringify(["probe-plugin", "reply", "reply/0"]),
|
||||
]);
|
||||
});
|
||||
|
||||
@@ -679,7 +683,7 @@ it.each(["full", "collapseToolCalls"] as const)(
|
||||
expect(result.tail.map((item) => item.id)).toEqual([
|
||||
"prompt",
|
||||
"tool-one",
|
||||
"probe-plugin/reply/0",
|
||||
JSON.stringify(["probe-plugin", "reply", "reply/0"]),
|
||||
]);
|
||||
expect(result.turns.summaryRowsByHostId.size).toBe(0);
|
||||
},
|
||||
|
||||
@@ -26,8 +26,10 @@ import {
|
||||
} from "@legendapp/list/react-native";
|
||||
import { withUnistyles } from "react-native-unistyles";
|
||||
import { LoadingSpinner } from "@/components/ui/loading-spinner";
|
||||
import { LoadingState } from "@/components/ui/loading-state";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { useRetainedPanelActive } from "@/components/retained-panel";
|
||||
import { useNativeSplashHold } from "@/native-splash";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import type { StreamItem } from "@/types/stream";
|
||||
import type { Theme } from "@/styles/theme";
|
||||
@@ -761,6 +763,9 @@ function NativeStreamViewport(props: StreamRenderInput & { strategy: StreamStrat
|
||||
);
|
||||
}, [historyStartPaginationState, hasOlderHistory, retryHistoryStart, t]);
|
||||
|
||||
// The launch splash stays up until the visible conversation has placed its rows. A hidden first
|
||||
// fill means the cache had no history, so it waits on the host and shows its own loading state.
|
||||
useNativeSplashHold(isActive && !isListPlaced);
|
||||
const canExpandDrawDistance =
|
||||
drawDistance < NATIVE_STREAM_DRAW_DISTANCE &&
|
||||
isActive &&
|
||||
@@ -807,8 +812,8 @@ function NativeStreamViewport(props: StreamRenderInput & { strategy: StreamStrat
|
||||
<InitialDrawDistanceExpansion schedule={drawDistanceExpansion.schedule} />
|
||||
) : null}
|
||||
{!historyStartPaginationState.visible ? (
|
||||
<View pointerEvents="none" testID="agent-initial-fill" style={initialFillStyle}>
|
||||
<ThemedLoadingSpinner size="large" uniProps={foregroundMutedColorMapping} />
|
||||
<View pointerEvents="none" style={initialFillStyle}>
|
||||
<LoadingState testID="agent-initial-fill" title={t("agentPanel.states.loadingHistory")} />
|
||||
</View>
|
||||
) : null}
|
||||
</View>
|
||||
|
||||
@@ -19,6 +19,7 @@ import { flushSync } from "react-dom";
|
||||
import { withUnistyles } from "react-native-unistyles";
|
||||
import { useRetainedPanelActive } from "@/components/retained-panel";
|
||||
import { LoadingSpinner } from "@/components/ui/loading-spinner";
|
||||
import { LoadingState } from "@/components/ui/loading-state";
|
||||
import { useStableEvent } from "@/hooks/use-stable-event";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { getStreamItemMessageId, type StreamItem } from "@/types/stream";
|
||||
@@ -1719,8 +1720,8 @@ function WebStreamViewport(props: StreamRenderInput & { isMobileBreakpoint: bool
|
||||
</div>
|
||||
</div>
|
||||
{!historyStartPaginationState.visible ? (
|
||||
<div data-testid="agent-initial-fill" style={initialFillStyle}>
|
||||
<ThemedLoadingSpinner size="large" uniProps={foregroundMutedColorMapping} />
|
||||
<div style={initialFillStyle}>
|
||||
<LoadingState testID="agent-initial-fill" title={t("agentPanel.states.loadingHistory")} />
|
||||
</div>
|
||||
) : null}
|
||||
{scrollEnabled && !isMobileBreakpoint ? (
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { useHardwareKeyboardPresent } from "@/keyboard";
|
||||
import { LaunchScreen, useNativeSplashLaunchCommit } from "@/native-splash";
|
||||
import {
|
||||
WindowLayoutProvider,
|
||||
WindowLayoutActionsHost,
|
||||
@@ -82,7 +83,6 @@ 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;
|
||||
hasGivenUpWaitingForHost: boolean;
|
||||
isWaitingForHost: boolean;
|
||||
isWaitingForSetup: boolean;
|
||||
storeReady: boolean;
|
||||
startupBlocker: StartupBlocker;
|
||||
@@ -165,7 +165,7 @@ export interface HostRuntimeBootstrapState {
|
||||
const HostRuntimeBootstrapContext = createContext<HostRuntimeBootstrapState>({
|
||||
splashError: null,
|
||||
retry: () => {},
|
||||
hasGivenUpWaitingForHost: false,
|
||||
isWaitingForHost: true,
|
||||
isWaitingForSetup: false,
|
||||
storeReady: false,
|
||||
startupBlocker: { kind: "none" },
|
||||
@@ -262,7 +262,6 @@ function useDaemonStartIsRunning(): boolean {
|
||||
);
|
||||
}
|
||||
|
||||
const STARTUP_GIVE_UP_TIMEOUT_MS = 5_000;
|
||||
// How long the splash waits on top of host startup to learn whether setup opens. A slow host
|
||||
// lands on the home instead, and setup opens over it once it is decided.
|
||||
const STARTUP_SETUP_WAIT_TIMEOUT_MS = 3_000;
|
||||
@@ -284,20 +283,29 @@ function HostRuntimeBootstrapProvider({ children }: { children: ReactNode }) {
|
||||
return bindHostRuntimeAppState(store, AppState);
|
||||
}, []);
|
||||
|
||||
const [isWaitingForHost, setIsWaitingForHost] = useState(true);
|
||||
useEffect(() => {
|
||||
let isMounted = true;
|
||||
const store = getHostRuntimeStore();
|
||||
const daemonStartService = getDaemonStartService({ store });
|
||||
startHostRuntimeBootstrap({
|
||||
void startHostRuntimeBootstrap({
|
||||
store,
|
||||
daemonStartService,
|
||||
shouldStartDaemon: shouldStartBuiltInDaemon,
|
||||
}).then(() => {
|
||||
if (isMounted) {
|
||||
setIsWaitingForHost(false);
|
||||
}
|
||||
return;
|
||||
});
|
||||
return () => {
|
||||
isMounted = false;
|
||||
};
|
||||
}, []);
|
||||
|
||||
const anyOnlineHostServerId = useEarliestOnlineHostServerId();
|
||||
const daemonStartError = useDaemonStartLastError();
|
||||
const daemonStartIsRunning = useDaemonStartIsRunning();
|
||||
const [hasGivenUpWaitingForHost, setHasGivenUpWaitingForHost] = useState(false);
|
||||
const isDesktopRuntime = shouldUseDesktopDaemon();
|
||||
const startupBlocker = useMemo(
|
||||
() =>
|
||||
@@ -309,24 +317,6 @@ function HostRuntimeBootstrapProvider({ children }: { children: ReactNode }) {
|
||||
}),
|
||||
[anyOnlineHostServerId, daemonStartError, daemonStartIsRunning, isDesktopRuntime],
|
||||
);
|
||||
const shouldRunGiveUpTimer = shouldRunStartupGiveUpTimer({
|
||||
startupBlocker,
|
||||
anyOnlineHostServerId,
|
||||
hasGivenUpWaitingForHost,
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (!shouldRunGiveUpTimer) {
|
||||
return;
|
||||
}
|
||||
const handle = setTimeout(() => {
|
||||
setHasGivenUpWaitingForHost(true);
|
||||
}, STARTUP_GIVE_UP_TIMEOUT_MS);
|
||||
return () => {
|
||||
clearTimeout(handle);
|
||||
};
|
||||
}, [shouldRunGiveUpTimer]);
|
||||
|
||||
const isSetupDecisionPending = useIsSetupDecisionPending();
|
||||
const [hasGivenUpWaitingForSetup, setHasGivenUpWaitingForSetup] = useState(false);
|
||||
const isWaitingForSetup = isSetupDecisionPending && !hasGivenUpWaitingForSetup;
|
||||
@@ -357,12 +347,12 @@ function HostRuntimeBootstrapProvider({ children }: { children: ReactNode }) {
|
||||
() => ({
|
||||
splashError,
|
||||
retry,
|
||||
hasGivenUpWaitingForHost,
|
||||
isWaitingForHost,
|
||||
isWaitingForSetup,
|
||||
storeReady,
|
||||
startupBlocker,
|
||||
}),
|
||||
[splashError, retry, hasGivenUpWaitingForHost, isWaitingForSetup, storeReady, startupBlocker],
|
||||
[splashError, retry, isWaitingForHost, isWaitingForSetup, storeReady, startupBlocker],
|
||||
);
|
||||
|
||||
return (
|
||||
@@ -915,6 +905,7 @@ const ROOT_STACK_SCREEN_OWNED_APPEARANCE = ["settings/[section]"] as const;
|
||||
|
||||
function RootStack() {
|
||||
const storeReady = useStoreReady();
|
||||
useNativeSplashLaunchCommit();
|
||||
return (
|
||||
<ThemedStack
|
||||
screenOptions={ROOT_STACK_SCREEN_OPTIONS}
|
||||
@@ -1043,6 +1034,7 @@ function RootAppTree() {
|
||||
</AddHostProvider>
|
||||
</LucideProvider>
|
||||
</View>
|
||||
<LaunchScreen />
|
||||
</GestureHandlerRootView>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -24,16 +24,20 @@ export default function HostIndexRoute() {
|
||||
return <StartupSplashScreen />;
|
||||
}
|
||||
|
||||
// The loading screen stays up until the target route paints; a redirect alone renders nothing.
|
||||
return (
|
||||
<Redirect
|
||||
href={resolveHostIndexRoute({
|
||||
serverId,
|
||||
workspaceSelection,
|
||||
workspaceSelectionStatus: resolveWorkspaceSelectionStatus({
|
||||
hasHydratedWorkspaces,
|
||||
workspaceExists: workspaceSelectionExists,
|
||||
}),
|
||||
})}
|
||||
/>
|
||||
<>
|
||||
<StartupSplashScreen />
|
||||
<Redirect
|
||||
href={resolveHostIndexRoute({
|
||||
serverId,
|
||||
workspaceSelection,
|
||||
workspaceSelectionStatus: resolveWorkspaceSelectionStatus({
|
||||
hasHydratedWorkspaces,
|
||||
workspaceExists: workspaceSelectionExists,
|
||||
}),
|
||||
})}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -44,7 +44,7 @@ export default function Index() {
|
||||
workspaceExists: workspaceSelectionExists,
|
||||
}),
|
||||
isWorkspaceSelectionLoaded,
|
||||
hasGivenUpWaitingForHost: bootstrapState.hasGivenUpWaitingForHost,
|
||||
isWaitingForHost: bootstrapState.isWaitingForHost,
|
||||
isWaitingForSetup: bootstrapState.isWaitingForSetup,
|
||||
});
|
||||
|
||||
|
||||
@@ -60,6 +60,10 @@ export interface SheetHeaderSearch {
|
||||
testID?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* One step back inside the sheet, such as from a page to the one before it. Android Back takes
|
||||
* this step too, and closes the sheet only when the header has no back.
|
||||
*/
|
||||
export interface SheetHeaderBack {
|
||||
onPress: () => void;
|
||||
label?: string;
|
||||
@@ -738,10 +742,17 @@ export function AdaptiveModalSheet({
|
||||
}
|
||||
}, [visible]);
|
||||
|
||||
const headerBack = header?.back?.onPress;
|
||||
const handleBack = useCallback(() => {
|
||||
if (!headerBack) return false;
|
||||
headerBack();
|
||||
return true;
|
||||
}, [headerBack]);
|
||||
const { sheetRef, handleSheetChange, handleSheetDismiss } = useIsolatedBottomSheetVisibility({
|
||||
visible,
|
||||
isEnabled: isSheet,
|
||||
onClose,
|
||||
onBack: handleBack,
|
||||
});
|
||||
const [shouldRenderWeb, setShouldRenderWeb] = useState(visible);
|
||||
const [isWebClosing, setIsWebClosing] = useState(false);
|
||||
|
||||
@@ -1,10 +1,13 @@
|
||||
import React, { act } from "react";
|
||||
import React, { act, useCallback, useState } from "react";
|
||||
import { createRoot, type Root } from "react-dom/client";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { persistAttachmentFromBlob } from "@/attachments/service";
|
||||
import { SafeAreaProvider } from "react-native-safe-area-context";
|
||||
import { i18n } from "@/i18n/i18next";
|
||||
import { WindowLayoutProvider } from "@/window-layout";
|
||||
import { RetainedPanelActivity } from "@/components/retained-panel";
|
||||
import { RetainedChatContent as NativeChatContent } from "@/panels/retained-chat-content.native";
|
||||
import { RetainedChatContent as WebChatContent } from "@/panels/retained-chat-content.web";
|
||||
import { AttachmentLightbox, type ImageLightboxSource } from "./attachment-lightbox";
|
||||
|
||||
interface FrameSample {
|
||||
@@ -147,3 +150,48 @@ describe("AttachmentLightbox opening in the browser", () => {
|
||||
await expectOpeningPaintsOnlyTheFittedImage({ type: "uri", uri });
|
||||
});
|
||||
});
|
||||
|
||||
let openImage: (() => void) | null = null;
|
||||
|
||||
function ThreadWithImage({ uri }: { uri: string }) {
|
||||
const [source, setSource] = useState<ImageLightboxSource | null>(null);
|
||||
openImage = () => setSource({ type: "uri", uri });
|
||||
const close = useCallback(() => setSource(null), []);
|
||||
return <AttachmentLightbox source={source} onClose={close} />;
|
||||
}
|
||||
|
||||
function isLightboxShown(): boolean {
|
||||
return document.querySelector('[data-testid="attachment-lightbox-backdrop"]') !== null;
|
||||
}
|
||||
|
||||
describe("AttachmentLightbox when its chat leaves the screen", () => {
|
||||
for (const [platform, ChatContent] of [
|
||||
["web", WebChatContent],
|
||||
["native", NativeChatContent],
|
||||
] as const) {
|
||||
it(`closes on ${platform} when another session takes over, and stays closed on return`, async () => {
|
||||
const uri = URL.createObjectURL(await createPng(400, 300));
|
||||
const showThread = (active: boolean) =>
|
||||
root.render(
|
||||
<SafeAreaProvider>
|
||||
<WindowLayoutProvider>
|
||||
<RetainedPanelActivity active={active}>
|
||||
<ChatContent>
|
||||
<ThreadWithImage uri={uri} />
|
||||
</ChatContent>
|
||||
</RetainedPanelActivity>
|
||||
</WindowLayoutProvider>
|
||||
</SafeAreaProvider>,
|
||||
);
|
||||
await act(async () => showThread(true));
|
||||
await act(async () => openImage?.());
|
||||
expect(isLightboxShown()).toBe(true);
|
||||
|
||||
await act(async () => showThread(false));
|
||||
expect(isLightboxShown()).toBe(false);
|
||||
|
||||
await act(async () => showThread(true));
|
||||
expect(isLightboxShown()).toBe(false);
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
@@ -13,6 +13,7 @@ import {
|
||||
useAttachmentPreviewUrl,
|
||||
} from "@/attachments/use-attachment-preview-url";
|
||||
import { isNative } from "@/constants/platform";
|
||||
import { useRetainedPanelActive } from "@/components/retained-panel";
|
||||
import { SPACING } from "@/styles/theme";
|
||||
import { WindowChromeRootRegion } from "@/utils/desktop-window";
|
||||
import { ZoomableImage } from "@/components/zoomable-viewport/image";
|
||||
@@ -42,12 +43,21 @@ export function AttachmentLightbox({ source, onClose }: AttachmentLightboxProps)
|
||||
const contentSize = source?.type === "uri" ? source.contentSize : undefined;
|
||||
const [errored, setErrored] = useState(false);
|
||||
const failed = errored || image.status === "failed";
|
||||
const modalLayer = useGlobalOverlayLayer("modal", source !== null);
|
||||
const panelActive = useRetainedPanelActive();
|
||||
const open = source !== null && panelActive;
|
||||
const modalLayer = useGlobalOverlayLayer("modal", open);
|
||||
|
||||
useEffect(() => {
|
||||
setErrored(false);
|
||||
}, [metadata?.id, url]);
|
||||
|
||||
// The image belongs to the panel that opened it and closes for good when that panel leaves the
|
||||
// screen. On web the Modal portals out of the hidden panel, and the hidden chat is frozen on the
|
||||
// next commit, so the lightbox must also unmount in this inactive commit (see MenuSurface).
|
||||
useEffect(() => {
|
||||
if (source !== null && !panelActive) onClose();
|
||||
}, [onClose, panelActive, source]);
|
||||
|
||||
const handleOverlayKeyDown = useCallback(
|
||||
(event: KeyboardInputEvent) => {
|
||||
if (event.key !== "Escape") return false;
|
||||
@@ -60,7 +70,7 @@ export function AttachmentLightbox({ source, onClose }: AttachmentLightboxProps)
|
||||
);
|
||||
const setOverlayScope = useOverlayRegistration({
|
||||
keys: ["Escape"],
|
||||
active: source !== null,
|
||||
active: open,
|
||||
layer: modalLayer,
|
||||
onKeyDown: handleOverlayKeyDown,
|
||||
});
|
||||
@@ -79,7 +89,7 @@ export function AttachmentLightbox({ source, onClose }: AttachmentLightboxProps)
|
||||
|
||||
const handleImageError = useCallback(() => setErrored(true), []);
|
||||
|
||||
if (!source) {
|
||||
if (!open) {
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
@@ -84,6 +84,9 @@ export function DraggableListHandle({ testID, style, children }: DraggableListHa
|
||||
}
|
||||
|
||||
const SCROLL_ENABLED_FLEX_STYLE = { flex: 1 };
|
||||
// Viewports of rows a nestable list keeps rendered around the container's viewport: two above,
|
||||
// two below. FlatList's default of 21 would still render a long sidebar in full.
|
||||
const NESTED_WINDOW_SIZE = 5;
|
||||
|
||||
// A drop remounts every row between the drag's start and end slots (see the draggable-flatlist
|
||||
// patch), so state held inside a rendered row resets when a drop moves it. Keep state that must
|
||||
@@ -206,9 +209,12 @@ export function DraggableList<T>({
|
||||
showsVerticalScrollIndicator={showsVerticalScrollIndicator}
|
||||
scrollEnabled={scrollEnabled}
|
||||
// A list that doesn't scroll shows every row, so it renders them all in its first commit.
|
||||
// FlatList's default first render is 10 rows; a nested list remounted by a drop would paint
|
||||
// 10 rows, then grow on a later commit.
|
||||
initialNumToRender={scrollEnabled ? undefined : data.length}
|
||||
// FlatList's default first render is 10 rows; a list remounted by a drop would paint 10
|
||||
// rows, then grow on a later commit. A nestable list is the exception: its
|
||||
// NestableScrollContainer is a VirtualizedList, so it renders only the rows near that
|
||||
// container's viewport, and a hidden sidebar does not render rows nobody can see.
|
||||
initialNumToRender={scrollEnabled || nestable ? undefined : data.length}
|
||||
windowSize={nestable ? NESTED_WINDOW_SIZE : undefined}
|
||||
extraData={extraData}
|
||||
simultaneousHandlers={simultaneousHandlers}
|
||||
dragGestureHostPresented={gestureHostPresented}
|
||||
|
||||
@@ -12,6 +12,7 @@ import { useQuery } from "@tanstack/react-query";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import {
|
||||
FlatList,
|
||||
Keyboard,
|
||||
type LayoutChangeEvent,
|
||||
ListRenderItemInfo,
|
||||
Pressable,
|
||||
@@ -629,6 +630,8 @@ export function FileExplorerPane({
|
||||
if (!hasWorkspaceScope) {
|
||||
return;
|
||||
}
|
||||
// The preview opens over this pane, so the filter must give up the keyboard.
|
||||
Keyboard.dismiss();
|
||||
onOpenFile?.(entry.path);
|
||||
},
|
||||
[hasWorkspaceScope, onOpenFile],
|
||||
|
||||
@@ -4,8 +4,8 @@ import { FlatList, Text, View } from "react-native";
|
||||
import { StyleSheet, withUnistyles } from "react-native-unistyles";
|
||||
import { AlertTriangle, ChevronDown, Layers } from "lucide-react-native";
|
||||
import type { AgentProfilePickerRow } from "@/agent-profiles";
|
||||
import { IndependentScrollBoundary } from "@/components/ui/independent-scroll-boundary";
|
||||
import {
|
||||
IndependentScrollBoundary,
|
||||
MODEL_PICKER_ROW_HEIGHT,
|
||||
ModelBrowserLoadingState,
|
||||
ModelBrowserNoProviders,
|
||||
|
||||
@@ -12,7 +12,6 @@ import {
|
||||
import { useTranslation } from "react-i18next";
|
||||
import {
|
||||
FlatList,
|
||||
Platform,
|
||||
Pressable,
|
||||
ScrollView,
|
||||
Text,
|
||||
@@ -27,6 +26,10 @@ import {
|
||||
type StyleProp,
|
||||
type ViewStyle,
|
||||
} from "react-native";
|
||||
import {
|
||||
IndependentScrollBoundary,
|
||||
useIndependentScrollGesture,
|
||||
} from "@/components/ui/independent-scroll-boundary";
|
||||
import { Gesture, GestureDetector } from "react-native-gesture-handler";
|
||||
import { StyleSheet, withUnistyles } from "react-native-unistyles";
|
||||
import {
|
||||
@@ -209,10 +212,6 @@ function AgentProfilesEditAction({ onPress }: { onPress: () => void }) {
|
||||
);
|
||||
}
|
||||
|
||||
const IndependentScrollGestureContext = createContext<ReturnType<typeof Gesture.Native> | null>(
|
||||
null,
|
||||
);
|
||||
|
||||
interface ModelBrowserNavContextValue {
|
||||
activeKey: string | null;
|
||||
onActivateKey: (key: string) => void;
|
||||
@@ -616,7 +615,7 @@ function ModelBrowserPressable({
|
||||
onLayout,
|
||||
testID,
|
||||
}: ModelBrowserPressableProps) {
|
||||
const independentScrollGesture = useContext(IndependentScrollGestureContext);
|
||||
const independentScrollGesture = useIndependentScrollGesture();
|
||||
const [pressed, setPressed] = useState(false);
|
||||
// Android's scroll handler must keep the pointer stream until release so a
|
||||
// fling survives leaving the short viewport. A simultaneous Tap keeps rows
|
||||
@@ -1381,29 +1380,6 @@ function GroupedProviderRows({
|
||||
);
|
||||
}
|
||||
|
||||
export function IndependentScrollBoundary({ children }: { children: React.ReactElement }) {
|
||||
// Prevent the parent sheet from cancelling Android's native scroll when the
|
||||
// finger crosses this viewport; receiving ACTION_UP is what preserves fling.
|
||||
const nativeScrollGesture = useMemo(
|
||||
() =>
|
||||
Gesture.Native()
|
||||
.shouldActivateOnStart(true)
|
||||
.shouldCancelWhenOutside(false)
|
||||
.disallowInterruption(true),
|
||||
[],
|
||||
);
|
||||
|
||||
if (Platform.OS !== "android") {
|
||||
return children;
|
||||
}
|
||||
|
||||
return (
|
||||
<IndependentScrollGestureContext.Provider value={nativeScrollGesture}>
|
||||
<GestureDetector gesture={nativeScrollGesture}>{children}</GestureDetector>
|
||||
</IndependentScrollGestureContext.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
function resolveModelListRevealTarget({
|
||||
shouldRevealActive,
|
||||
hasActiveHeaderItem,
|
||||
|
||||
@@ -37,7 +37,7 @@ export type { SettingsRowHintStatus } from "./row-header";
|
||||
export { SettingsAddRow } from "./add-row";
|
||||
export { SettingsBackLink, SettingsDetailHeader } from "./detail-header";
|
||||
export { SettingsInfoTip } from "./headings/settings-info-tip";
|
||||
export { MenuSettingsRows } from "./row-density";
|
||||
export { ListSettingsRows, MenuSettingsRows } from "./row-density";
|
||||
|
||||
/**
|
||||
* What app screens can add to a plugin-facing row: an accessory beside the label, such as an info
|
||||
|
||||
@@ -1,7 +1,12 @@
|
||||
import { createContext, useContext, useMemo, type ReactNode } from "react";
|
||||
import type { StyleProp, TextStyle, ViewStyle } from "react-native";
|
||||
import { StyleSheet } from "react-native-unistyles";
|
||||
import { CONTROL_HEIGHTS, mapLayout, type ControlSize } from "@/components/ui/control-geometry";
|
||||
import {
|
||||
CONTROL_HEIGHTS,
|
||||
mapLayout,
|
||||
TOUCH_TARGET,
|
||||
type ControlSize,
|
||||
} from "@/components/ui/control-geometry";
|
||||
import { menuRowContentInset } from "@/components/ui/menu";
|
||||
|
||||
import { settingsStyles } from "@/styles/settings";
|
||||
@@ -12,7 +17,9 @@ import { settingsStyles } from "@/styles/settings";
|
||||
// - nested: rows revealed under a collapsible row belong to it, so they sit one step smaller than
|
||||
// the rows of the card: tighter padding, smaller text, smaller controls.
|
||||
// - menu: rows that share a menu surface with menu rows put their labels on the menu's label rail.
|
||||
type RowPlacement = "card" | "nested" | "menu";
|
||||
// - list: rows that share a sheet with list rows, such as radio choices and section headers, take
|
||||
// the list row's height so every row in the sheet lines up.
|
||||
type RowPlacement = "card" | "nested" | "menu" | "list";
|
||||
|
||||
const RowPlacementContext = createContext<RowPlacement>("card");
|
||||
|
||||
@@ -25,6 +32,11 @@ export function MenuSettingsRows({ children }: { children: ReactNode }) {
|
||||
return <RowPlacementContext.Provider value="menu">{children}</RowPlacementContext.Provider>;
|
||||
}
|
||||
|
||||
/** Settings rows rendered in a sheet of list rows, such as Agent settings. */
|
||||
export function ListSettingsRows({ children }: { children: ReactNode }) {
|
||||
return <RowPlacementContext.Provider value="list">{children}</RowPlacementContext.Provider>;
|
||||
}
|
||||
|
||||
export interface SettingsRowLayout {
|
||||
row: StyleProp<ViewStyle>;
|
||||
title: StyleProp<TextStyle>;
|
||||
@@ -49,6 +61,13 @@ function layoutFor(placement: RowPlacement): SettingsRowLayout {
|
||||
hint: settingsStyles.rowHint,
|
||||
controlSize: "md",
|
||||
};
|
||||
case "list":
|
||||
return {
|
||||
row: [settingsStyles.row, styles.listRow],
|
||||
title: settingsStyles.rowTitle,
|
||||
hint: settingsStyles.rowHint,
|
||||
controlSize: "md",
|
||||
};
|
||||
case "card":
|
||||
return {
|
||||
row: settingsStyles.row,
|
||||
@@ -72,6 +91,11 @@ const styles = StyleSheet.create((theme) => ({
|
||||
paddingVertical: theme.spacing[2],
|
||||
minHeight: mapLayout(CONTROL_HEIGHTS.sm, (height) => height + theme.spacing[2] * 2),
|
||||
},
|
||||
// A list row is a touch target tall on every input; a switch still fits inside its padding.
|
||||
listRow: {
|
||||
paddingVertical: theme.spacing[2],
|
||||
minHeight: TOUCH_TARGET,
|
||||
},
|
||||
nestedText: {
|
||||
fontSize: theme.fontSize.sm,
|
||||
},
|
||||
|
||||
@@ -2311,7 +2311,7 @@ function ProjectModeList({
|
||||
() =>
|
||||
parentGestureRef
|
||||
? ({
|
||||
// NestableScrollContainer forwards props to RNGH ScrollView. Keep
|
||||
// NestableScrollContainer forwards props to an RNGH FlatList. Keep
|
||||
// vertical scroll and sidebar close pan simultaneous: vertical
|
||||
// intent scrolls immediately, clear horizontal intent can still
|
||||
// activate close from inside the list.
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
import { createContext, useContext, useMemo, type ReactElement } from "react";
|
||||
import { Platform } from "react-native";
|
||||
import { Gesture, GestureDetector } from "react-native-gesture-handler";
|
||||
|
||||
const IndependentScrollGestureContext = createContext<ReturnType<typeof Gesture.Native> | null>(
|
||||
null,
|
||||
);
|
||||
|
||||
/** The native scroll gesture of the enclosing boundary, for gestures that must not cancel it. */
|
||||
export function useIndependentScrollGesture(): ReturnType<typeof Gesture.Native> | null {
|
||||
return useContext(IndependentScrollGestureContext);
|
||||
}
|
||||
|
||||
/**
|
||||
* Keeps a parent pan from interrupting an Android scroll and lets the list receive ACTION_UP
|
||||
* for the fling. With activation on start, child taps must join the native scroll gesture.
|
||||
* When activation waits for the scroll view to intercept a drag, ordinary pressables receive taps.
|
||||
*/
|
||||
export function IndependentScrollBoundary({
|
||||
children,
|
||||
activateOnStart = true,
|
||||
}: {
|
||||
children: ReactElement;
|
||||
activateOnStart?: boolean;
|
||||
}) {
|
||||
const nativeScrollGesture = useMemo(
|
||||
() =>
|
||||
Gesture.Native()
|
||||
.shouldActivateOnStart(activateOnStart)
|
||||
.shouldCancelWhenOutside(false)
|
||||
.disallowInterruption(true),
|
||||
[activateOnStart],
|
||||
);
|
||||
|
||||
if (Platform.OS !== "android") {
|
||||
return children;
|
||||
}
|
||||
|
||||
return (
|
||||
<IndependentScrollGestureContext.Provider value={nativeScrollGesture}>
|
||||
<GestureDetector gesture={nativeScrollGesture}>{children}</GestureDetector>
|
||||
</IndependentScrollGestureContext.Provider>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
import React, { act } from "react";
|
||||
import { createRoot, type Root } from "react-dom/client";
|
||||
import { afterEach, beforeEach, expect, it, vi } from "vitest";
|
||||
import { page } from "vitest/browser";
|
||||
import { i18n } from "@/i18n/i18next";
|
||||
import { LoadingSpinner } from "./loading-spinner";
|
||||
|
||||
let root: Root;
|
||||
let host: HTMLDivElement;
|
||||
|
||||
beforeEach(async () => {
|
||||
await i18n.changeLanguage("en");
|
||||
vi.stubGlobal("React", React);
|
||||
vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
|
||||
host = document.createElement("div");
|
||||
document.body.appendChild(host);
|
||||
root = createRoot(host);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
act(() => root.unmount());
|
||||
host.remove();
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
it("announces itself as loading when the caller gives no label", async () => {
|
||||
act(() => root.render(<LoadingSpinner color="#888888" />));
|
||||
|
||||
await expect.element(page.getByRole("progressbar", { name: "Loading..." })).toBeVisible();
|
||||
});
|
||||
|
||||
it("announces what is loading when the caller names it", async () => {
|
||||
act(() => root.render(<LoadingSpinner color="#888888" accessibilityLabel="Loading commits" />));
|
||||
|
||||
await expect.element(page.getByRole("progressbar", { name: "Loading commits" })).toBeVisible();
|
||||
});
|
||||
@@ -1,12 +1,29 @@
|
||||
import React from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { ActivityIndicator, type ActivityIndicatorProps } from "react-native";
|
||||
|
||||
interface LoadingSpinnerProps {
|
||||
color: string;
|
||||
size?: ActivityIndicatorProps["size"];
|
||||
style?: ActivityIndicatorProps["style"];
|
||||
/** What is loading. Screen readers announce "Loading" when this is absent. */
|
||||
accessibilityLabel?: string;
|
||||
}
|
||||
|
||||
export function LoadingSpinner({ color, size = "small", style }: LoadingSpinnerProps) {
|
||||
return <ActivityIndicator size={size} color={color} style={style} />;
|
||||
export function LoadingSpinner({
|
||||
color,
|
||||
size = "small",
|
||||
style,
|
||||
accessibilityLabel,
|
||||
}: LoadingSpinnerProps) {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<ActivityIndicator
|
||||
size={size}
|
||||
color={color}
|
||||
style={style}
|
||||
accessibilityRole="progressbar"
|
||||
accessibilityLabel={accessibilityLabel ?? t("common.loading")}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
import { Text, View } from "react-native";
|
||||
import { StyleSheet, withUnistyles } from "react-native-unistyles";
|
||||
import { LoadingSpinner } from "@/components/ui/loading-spinner";
|
||||
import type { Theme } from "@/styles/theme";
|
||||
|
||||
const ThemedLoadingSpinner = withUnistyles(LoadingSpinner);
|
||||
const foregroundMutedColorMapping = (theme: Theme) => ({
|
||||
color: theme.colors.foregroundMuted,
|
||||
});
|
||||
|
||||
/**
|
||||
* A screen or pane waiting for its content. Every wait shows the same spinner in the same place,
|
||||
* so a wait that changes what it is waiting for changes only the words under it.
|
||||
*/
|
||||
export function LoadingState({
|
||||
title,
|
||||
description,
|
||||
testID,
|
||||
}: {
|
||||
/** What the wait is for. Leave it out while the wait is too short to read. */
|
||||
title?: string;
|
||||
description?: string;
|
||||
testID?: string;
|
||||
}) {
|
||||
return (
|
||||
<View style={styles.container} testID={testID}>
|
||||
<ThemedLoadingSpinner
|
||||
size="small"
|
||||
uniProps={foregroundMutedColorMapping}
|
||||
accessibilityLabel={title}
|
||||
/>
|
||||
{title ? (
|
||||
<View style={styles.textStack}>
|
||||
<Text style={styles.title}>{title}</Text>
|
||||
{description ? <Text style={styles.description}>{description}</Text> : null}
|
||||
</View>
|
||||
) : null}
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create((theme) => ({
|
||||
container: {
|
||||
flex: 1,
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
gap: theme.spacing[3],
|
||||
paddingHorizontal: theme.spacing[6],
|
||||
},
|
||||
textStack: {
|
||||
alignItems: "center",
|
||||
gap: theme.spacing[2],
|
||||
maxWidth: 520,
|
||||
},
|
||||
title: {
|
||||
color: theme.colors.foreground,
|
||||
fontSize: theme.fontSize.base,
|
||||
fontWeight: theme.fontWeight.normal,
|
||||
textAlign: "center",
|
||||
},
|
||||
description: {
|
||||
color: theme.colors.foregroundMuted,
|
||||
fontSize: theme.fontSize.base,
|
||||
textAlign: "center",
|
||||
},
|
||||
}));
|
||||
@@ -88,7 +88,11 @@ export function AgentSettingsDrawer({
|
||||
}: AgentSettingsDrawerProps) {
|
||||
const { t } = useTranslation();
|
||||
const [page, setPage] = useState<AgentSheetPage>(AGENT_SHEET_HOME);
|
||||
const [profilesExpanded, setProfilesExpanded] = useState(false);
|
||||
// Profiles open on Home for a new agent, where a profile is the quickest way to configure it.
|
||||
// `null` until the user toggles the card in this opening.
|
||||
const [profilesToggled, setProfilesToggled] = useState<boolean | null>(null);
|
||||
const profilesExpanded =
|
||||
profilesToggled ?? (profiles?.target === "draft" && profiles.rows.length > 0);
|
||||
// Select pages search with this; the Model page keeps its own.
|
||||
const [pageQuery, setPageQuery] = useState("");
|
||||
const [pageSearchKey, setPageSearchKey] = useState(0);
|
||||
@@ -103,8 +107,8 @@ export function AgentSettingsDrawer({
|
||||
});
|
||||
|
||||
const toggleProfiles = useCallback(() => {
|
||||
setProfilesExpanded((expanded) => !expanded);
|
||||
}, []);
|
||||
setProfilesToggled(!profilesExpanded);
|
||||
}, [profilesExpanded]);
|
||||
|
||||
const goTo = useCallback((next: AgentSheetPage) => {
|
||||
Keyboard.dismiss();
|
||||
@@ -125,7 +129,7 @@ export function AgentSettingsDrawer({
|
||||
const close = useCallback(() => {
|
||||
Keyboard.dismiss();
|
||||
setPage(AGENT_SHEET_HOME);
|
||||
setProfilesExpanded(false);
|
||||
setProfilesToggled(null);
|
||||
setPageQuery("");
|
||||
modelPage.reset();
|
||||
onClose();
|
||||
|
||||
@@ -8,6 +8,7 @@ import type { AgentMode } from "@getpaseo/protocol/agent-types";
|
||||
import { getAgentModeOptionIcon } from "@/agent-controls/icons";
|
||||
import { formatAgentModeLabel } from "@/agent-controls/labels";
|
||||
import {
|
||||
ListSettingsRows,
|
||||
SettingsCard,
|
||||
SettingsDetailRow,
|
||||
SettingsSection,
|
||||
@@ -19,6 +20,7 @@ import { PressHighlight } from "@/components/ui/press-highlight";
|
||||
import { ScrollView as SheetScrollView } from "@/components/ui/scroll-view";
|
||||
import { SegmentedControl, type SegmentedControlOption } from "@/components/ui/segmented-control";
|
||||
import { SteppedSlider, type SteppedSliderOption } from "@/components/ui/stepped-slider";
|
||||
import { TOUCH_TARGET } from "@/components/ui/control-geometry";
|
||||
import { isNative } from "@/constants/platform";
|
||||
import { ICON_SIZE } from "@/styles/theme";
|
||||
import {
|
||||
@@ -85,17 +87,19 @@ export function AgentSheetHome({
|
||||
>
|
||||
{/* Themed insets sit on a View: the sheet scroller drops a themed contentContainerStyle on web. */}
|
||||
<View style={styles.content}>
|
||||
<View style={styles.block}>{topCard}</View>
|
||||
{blocks.map((block) => (
|
||||
<HomeBlock
|
||||
key={blockKey(block)}
|
||||
block={block}
|
||||
modeControl={modeControl}
|
||||
disabled={disabled}
|
||||
onOpenSelect={onOpenSelect}
|
||||
/>
|
||||
))}
|
||||
{footer}
|
||||
<ListSettingsRows>
|
||||
<View style={styles.block}>{topCard}</View>
|
||||
{blocks.map((block) => (
|
||||
<HomeBlock
|
||||
key={blockKey(block)}
|
||||
block={block}
|
||||
modeControl={modeControl}
|
||||
disabled={disabled}
|
||||
onOpenSelect={onOpenSelect}
|
||||
/>
|
||||
))}
|
||||
{footer}
|
||||
</ListSettingsRows>
|
||||
</View>
|
||||
</SheetScrollView>
|
||||
);
|
||||
@@ -663,7 +667,7 @@ const styles = StyleSheet.create((theme) => ({
|
||||
fontSize: theme.fontSize.base,
|
||||
},
|
||||
radioRow: {
|
||||
minHeight: 44,
|
||||
minHeight: TOUCH_TARGET,
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
paddingHorizontal: theme.spacing[4],
|
||||
|
||||
@@ -43,7 +43,7 @@ describe("schedule mutation cache updates", () => {
|
||||
const current: FetchAggregatedSchedulesResult = {
|
||||
status: "loaded",
|
||||
data: [schedule()],
|
||||
hostErrors: [],
|
||||
hostWarnings: [],
|
||||
};
|
||||
|
||||
const result = updateAggregatedSchedulesData(current, pauseSchedules);
|
||||
@@ -51,7 +51,7 @@ describe("schedule mutation cache updates", () => {
|
||||
expect(result).toEqual({
|
||||
status: "loaded",
|
||||
data: [schedule({ status: "paused" })],
|
||||
hostErrors: [],
|
||||
hostWarnings: [],
|
||||
});
|
||||
});
|
||||
|
||||
@@ -69,7 +69,7 @@ describe("schedule mutation cache updates", () => {
|
||||
const loaded: FetchAggregatedSchedulesResult = {
|
||||
status: "loaded",
|
||||
data: [schedule()],
|
||||
hostErrors: [],
|
||||
hostWarnings: [],
|
||||
};
|
||||
queryClient.setQueryData(connectingKey, connecting);
|
||||
queryClient.setQueryData(loadedKey, loaded);
|
||||
@@ -85,7 +85,7 @@ describe("schedule mutation cache updates", () => {
|
||||
expect(queryClient.getQueryData(loadedKey)).toEqual({
|
||||
status: "loaded",
|
||||
data: [schedule({ status: "paused" })],
|
||||
hostErrors: [],
|
||||
hostWarnings: [],
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -10,14 +10,14 @@ import {
|
||||
schedulesQueryBaseKey,
|
||||
type AggregateLoadState,
|
||||
type AggregatedSchedule,
|
||||
type ScheduleHostError,
|
||||
type ScheduleHostWarning,
|
||||
type ScheduleHostInput,
|
||||
} from "@/schedules/aggregated-schedules";
|
||||
|
||||
export type {
|
||||
AggregateLoadState,
|
||||
AggregatedSchedule,
|
||||
ScheduleHostError,
|
||||
ScheduleHostWarning,
|
||||
} from "@/schedules/aggregated-schedules";
|
||||
|
||||
export function schedulesQueryKey(serverIds: readonly string[]) {
|
||||
@@ -26,7 +26,7 @@ export function schedulesQueryKey(serverIds: readonly string[]) {
|
||||
|
||||
export interface UseSchedulesResult {
|
||||
loadState: AggregateLoadState<AggregatedSchedule>;
|
||||
hostErrors: ScheduleHostError[];
|
||||
hostWarnings: ScheduleHostWarning[];
|
||||
isError: boolean;
|
||||
error: Error | null;
|
||||
refetch: () => void;
|
||||
@@ -65,7 +65,7 @@ export function useSchedules(): UseSchedulesResult {
|
||||
|
||||
return {
|
||||
loadState,
|
||||
hostErrors: query.data?.status === "loaded" ? query.data.hostErrors : [],
|
||||
hostWarnings: query.data?.status === "loaded" ? query.data.hostWarnings : [],
|
||||
isError: query.isError,
|
||||
error: query.error,
|
||||
refetch: () => {
|
||||
|
||||
@@ -278,6 +278,8 @@ export const ar: TranslationResources = {
|
||||
failedToLoad: "فشل تحميل الوكيل",
|
||||
reconnecting: "جارٍ إعادة الاتصال",
|
||||
updating: "جارٍ تحديث الرسائل",
|
||||
loadingAgent: "جارٍ تحميل الوكيل",
|
||||
loadingHistory: "جارٍ تحميل سجل الوكيل",
|
||||
timelineSyncFailed: "تعذر تحديث سجل الوكيل.",
|
||||
timelineSyncRetrying: "جارٍ إعادة المحاولة…",
|
||||
archivingTitle: "وكيل الارشيف...",
|
||||
|
||||
@@ -276,6 +276,8 @@ export const en = {
|
||||
failedToLoad: "Failed to load agent",
|
||||
reconnecting: "Reconnecting",
|
||||
updating: "Updating messages",
|
||||
loadingAgent: "Loading agent",
|
||||
loadingHistory: "Loading agent history",
|
||||
timelineSyncFailed: "Couldn't refresh agent history.",
|
||||
timelineSyncRetrying: "Retrying…",
|
||||
archivingTitle: "Archiving agent...",
|
||||
|
||||
@@ -280,6 +280,8 @@ export const es: TranslationResources = {
|
||||
failedToLoad: "No se pudo cargar el agente",
|
||||
reconnecting: "Reconectando",
|
||||
updating: "Actualizando mensajes",
|
||||
loadingAgent: "Cargando agente",
|
||||
loadingHistory: "Cargando historial del agente",
|
||||
timelineSyncFailed: "No se pudo actualizar el historial del agente.",
|
||||
timelineSyncRetrying: "Reintentando…",
|
||||
archivingTitle: "Agente de archivo...",
|
||||
|
||||
@@ -281,6 +281,8 @@ export const fr: TranslationResources = {
|
||||
failedToLoad: "Impossible de charger l’agent",
|
||||
reconnecting: "Reconnexion…",
|
||||
updating: "Mise à jour des messages…",
|
||||
loadingAgent: "Chargement de l’agent",
|
||||
loadingHistory: "Chargement de l’historique de l’agent",
|
||||
timelineSyncFailed: "Impossible d’actualiser l’historique de l’agent.",
|
||||
timelineSyncRetrying: "Nouvelle tentative…",
|
||||
archivingTitle: "Archivage de l’agent…",
|
||||
|
||||
@@ -280,6 +280,8 @@ export const ja: TranslationResources = {
|
||||
failedToLoad: "エージェントの読み込みに失敗しました",
|
||||
reconnecting: "再接続中",
|
||||
updating: "メッセージを更新中",
|
||||
loadingAgent: "エージェントを読み込み中",
|
||||
loadingHistory: "エージェントの履歴を読み込み中",
|
||||
timelineSyncFailed: "エージェントの履歴を更新できませんでした。",
|
||||
timelineSyncRetrying: "再試行しています…",
|
||||
archivingTitle: "エージェントをアーカイブ中...",
|
||||
|
||||
@@ -278,6 +278,8 @@ export const ko: TranslationResources = {
|
||||
failedToLoad: "에이전트를 불러오지 못했습니다",
|
||||
reconnecting: "다시 연결하는 중",
|
||||
updating: "메시지 업데이트 중",
|
||||
loadingAgent: "에이전트 불러오는 중",
|
||||
loadingHistory: "에이전트 기록 불러오는 중",
|
||||
timelineSyncFailed: "에이전트 기록을 새로고침할 수 없습니다.",
|
||||
timelineSyncRetrying: "재시도 중…",
|
||||
archivingTitle: "에이전트 보관 중...",
|
||||
|
||||
@@ -279,6 +279,8 @@ export const ptBR: TranslationResources = {
|
||||
failedToLoad: "Falha ao carregar agente",
|
||||
reconnecting: "Reconectando",
|
||||
updating: "Atualizando mensagens",
|
||||
loadingAgent: "Carregando agente",
|
||||
loadingHistory: "Carregando histórico do agente",
|
||||
timelineSyncFailed: "Não foi possível atualizar o histórico do agente.",
|
||||
timelineSyncRetrying: "Tentando novamente…",
|
||||
archivingTitle: "Arquivando agente...",
|
||||
|
||||
@@ -280,6 +280,8 @@ export const ru: TranslationResources = {
|
||||
failedToLoad: "Не удалось загрузить агента",
|
||||
reconnecting: "Повторное подключение",
|
||||
updating: "Обновление сообщений",
|
||||
loadingAgent: "Загрузка агента",
|
||||
loadingHistory: "Загрузка истории агента",
|
||||
timelineSyncFailed: "Не удалось обновить историю агента.",
|
||||
timelineSyncRetrying: "Повторная попытка…",
|
||||
archivingTitle: "Агент перемещается в архив...",
|
||||
|
||||
@@ -278,6 +278,8 @@ export const zhCN: TranslationResources = {
|
||||
failedToLoad: "加载 Agent 失败",
|
||||
reconnecting: "正在重新连接",
|
||||
updating: "正在更新消息",
|
||||
loadingAgent: "正在加载代理",
|
||||
loadingHistory: "正在加载代理历史记录",
|
||||
timelineSyncFailed: "无法刷新代理历史记录。",
|
||||
timelineSyncRetrying: "正在重试…",
|
||||
archivingTitle: "正在归档 Agent...",
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
import { useEffect, useLayoutEffect } from "react";
|
||||
import { createNativeSplashController, type NativeSplashController } from "./internal/controller";
|
||||
import { launchSurface } from "./internal/launch-surface";
|
||||
|
||||
export { LaunchScreen } from "./internal/launch-surface";
|
||||
|
||||
// Guards against a screen that never releases its hold. A slow device places the first
|
||||
// conversation 2-4 s after the JS entry, so a shorter cap cuts in before it paints.
|
||||
const CAP_MS = 5_000;
|
||||
|
||||
let controller: NativeSplashController | null = null;
|
||||
let releaseLaunch: (() => void) | null = null;
|
||||
|
||||
/**
|
||||
* Call once at the JS entry. The launch surface (the native splash, or on Android the
|
||||
* `LaunchScreen` that replaces it) then covers the app until the root navigator has committed its
|
||||
* first screen and no screen holds it, and leaves from here alone.
|
||||
*/
|
||||
export function keepNativeSplash(): void {
|
||||
if (controller) return;
|
||||
launchSurface.keep();
|
||||
controller = createNativeSplashController(
|
||||
{
|
||||
hide: () => launchSurface.leave(),
|
||||
afterNextFrame: (callback) => {
|
||||
requestAnimationFrame(() => callback());
|
||||
},
|
||||
startTimer: (callback, ms) => {
|
||||
setTimeout(callback, ms);
|
||||
},
|
||||
},
|
||||
{ capMs: CAP_MS },
|
||||
);
|
||||
releaseLaunch = controller.hold();
|
||||
}
|
||||
|
||||
/** The root navigator's first commit ends the launch hold. Screens committed with it hold first. */
|
||||
export function useNativeSplashLaunchCommit(): void {
|
||||
useEffect(() => {
|
||||
releaseLaunch?.();
|
||||
releaseLaunch = null;
|
||||
}, []);
|
||||
}
|
||||
|
||||
/** Keeps the launch surface up while `active`, for a screen that has nothing to show yet. */
|
||||
export function useNativeSplashHold(active: boolean): void {
|
||||
useLayoutEffect(() => {
|
||||
if (!active) return;
|
||||
return controller?.hold();
|
||||
}, [active]);
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { createNativeSplashController } from "./controller";
|
||||
|
||||
function createFakeSplash() {
|
||||
const frames: Array<() => void> = [];
|
||||
const timers: Array<{ callback: () => void; ms: number }> = [];
|
||||
const splash = { hides: 0 };
|
||||
const controller = createNativeSplashController(
|
||||
{
|
||||
hide: () => {
|
||||
splash.hides += 1;
|
||||
},
|
||||
afterNextFrame: (callback) => {
|
||||
frames.push(callback);
|
||||
},
|
||||
startTimer: (callback, ms) => {
|
||||
timers.push({ callback, ms });
|
||||
},
|
||||
},
|
||||
{ capMs: 3_000 },
|
||||
);
|
||||
const runFrame = () => {
|
||||
for (const callback of frames.splice(0)) callback();
|
||||
};
|
||||
const runCap = () => {
|
||||
for (const timer of timers.splice(0)) timer.callback();
|
||||
};
|
||||
return { controller, splash, runFrame, runCap, timers };
|
||||
}
|
||||
|
||||
describe("native splash", () => {
|
||||
it("stays up while a screen holds it and hides a frame after the last release", () => {
|
||||
const { controller, splash, runFrame } = createFakeSplash();
|
||||
const releaseLaunch = controller.hold();
|
||||
const releaseScreen = controller.hold();
|
||||
|
||||
releaseLaunch();
|
||||
runFrame();
|
||||
expect(splash.hides).toBe(0);
|
||||
|
||||
releaseScreen();
|
||||
expect(splash.hides).toBe(0);
|
||||
runFrame();
|
||||
expect(splash.hides).toBe(1);
|
||||
});
|
||||
|
||||
it("stays up when the next screen takes the hold before the frame passes", () => {
|
||||
const { controller, splash, runFrame } = createFakeSplash();
|
||||
const releaseSplashRoute = controller.hold();
|
||||
|
||||
releaseSplashRoute();
|
||||
const releaseWorkspace = controller.hold();
|
||||
runFrame();
|
||||
expect(splash.hides).toBe(0);
|
||||
|
||||
releaseWorkspace();
|
||||
runFrame();
|
||||
expect(splash.hides).toBe(1);
|
||||
});
|
||||
|
||||
it("hides when the cap runs out even while a screen still holds it", () => {
|
||||
const { controller, splash, runCap, runFrame, timers } = createFakeSplash();
|
||||
const release = controller.hold();
|
||||
|
||||
expect(timers.map((timer) => timer.ms)).toEqual([3_000]);
|
||||
runCap();
|
||||
expect(splash.hides).toBe(1);
|
||||
|
||||
release();
|
||||
runFrame();
|
||||
expect(controller.hold()).toBeTypeOf("function");
|
||||
runFrame();
|
||||
expect(splash.hides).toBe(1);
|
||||
});
|
||||
|
||||
it("counts a repeated release once", () => {
|
||||
const { controller, splash, runFrame } = createFakeSplash();
|
||||
const first = controller.hold();
|
||||
controller.hold();
|
||||
|
||||
first();
|
||||
first();
|
||||
runFrame();
|
||||
expect(splash.hides).toBe(0);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,53 @@
|
||||
export interface NativeSplashPort {
|
||||
hide(): void;
|
||||
/** Runs the callback after the next frame, once the committed screen has been drawn. */
|
||||
afterNextFrame(callback: () => void): void;
|
||||
startTimer(callback: () => void, ms: number): void;
|
||||
}
|
||||
|
||||
export interface NativeSplashController {
|
||||
/** Keeps the splash up until the returned release runs. Holds after the hide do nothing. */
|
||||
hold(): () => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* The splash hides once, after a frame passes with nothing holding it, or when the cap runs out.
|
||||
* The frame wait lets a screen that replaces a holding screen in the same commit take over.
|
||||
*/
|
||||
export function createNativeSplashController(
|
||||
port: NativeSplashPort,
|
||||
options: { capMs: number },
|
||||
): NativeSplashController {
|
||||
let holds = 0;
|
||||
let hidden = false;
|
||||
let checkScheduled = false;
|
||||
|
||||
const hide = () => {
|
||||
if (hidden) return;
|
||||
hidden = true;
|
||||
port.hide();
|
||||
};
|
||||
|
||||
const hideIfReleased = () => {
|
||||
checkScheduled = false;
|
||||
if (holds === 0) hide();
|
||||
};
|
||||
|
||||
port.startTimer(hide, options.capMs);
|
||||
|
||||
return {
|
||||
hold() {
|
||||
if (hidden) return () => undefined;
|
||||
holds += 1;
|
||||
let released = false;
|
||||
return () => {
|
||||
if (released) return;
|
||||
released = true;
|
||||
holds -= 1;
|
||||
if (holds > 0 || hidden || checkScheduled) return;
|
||||
checkScheduled = true;
|
||||
port.afterNextFrame(hideIfReleased);
|
||||
};
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
import { useEffect, useState, useSyncExternalStore } from "react";
|
||||
import { useColorScheme, View } from "react-native";
|
||||
import Animated, { useAnimatedStyle, useSharedValue, withTiming } from "react-native-reanimated";
|
||||
import { scheduleOnRN } from "react-native-worklets";
|
||||
import { StyleSheet } from "react-native-unistyles";
|
||||
import * as SplashScreen from "expo-splash-screen";
|
||||
import { PaseoLogo } from "@/components/icons/paseo-logo";
|
||||
|
||||
// Android hands its splash to the app in a way the app cannot time: the system can show one app
|
||||
// frame before its copy of the splash draws, and a frame the app draws first can be empty. So the
|
||||
// native splash leaves as soon as React commits this screen, which looks the same as the splash,
|
||||
// and this screen covers the app until launch is done.
|
||||
|
||||
// The splash colours from the expo-splash-screen entry in app.config.js. Android picks them from
|
||||
// the system dark mode, not from the app theme.
|
||||
const SPLASH_BACKGROUND = { dark: "#000000", light: "#ffffff" } as const;
|
||||
// Android draws a splash icon without a background inside a 192dp circle.
|
||||
const ICON_CIRCLE_SIZE = 192;
|
||||
// The splash icon's glyph is 135dp wide, which the logo's glyph reaches at this SVG size.
|
||||
const LOGO_SIZE = 182;
|
||||
const EXIT_MS = 200;
|
||||
|
||||
let launchDone = false;
|
||||
const listeners = new Set<() => void>();
|
||||
|
||||
function subscribe(listener: () => void): () => void {
|
||||
listeners.add(listener);
|
||||
return () => listeners.delete(listener);
|
||||
}
|
||||
|
||||
function isLaunchDone(): boolean {
|
||||
return launchDone;
|
||||
}
|
||||
|
||||
/** Android: this screen covers the app until launch is done, then fades out. */
|
||||
export const launchSurface = {
|
||||
keep(): void {
|
||||
void SplashScreen.preventAutoHideAsync().catch(() => undefined);
|
||||
// The system's copy of the splash fades over this screen, which looks the same.
|
||||
SplashScreen.setOptions({ duration: 150, fade: true });
|
||||
},
|
||||
leave(): void {
|
||||
if (launchDone) return;
|
||||
launchDone = true;
|
||||
for (const listener of listeners) listener();
|
||||
},
|
||||
};
|
||||
|
||||
export function LaunchScreen() {
|
||||
const leaving = useSyncExternalStore(subscribe, isLaunchDone);
|
||||
const [gone, setGone] = useState(false);
|
||||
const scheme = useColorScheme() === "light" ? "light" : "dark";
|
||||
const opacity = useSharedValue(1);
|
||||
const fadeStyle = useAnimatedStyle(() => ({ opacity: opacity.value }));
|
||||
|
||||
useEffect(() => {
|
||||
SplashScreen.hide();
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (!leaving) return;
|
||||
opacity.value = withTiming(0, { duration: EXIT_MS }, (finished) => {
|
||||
if (finished) scheduleOnRN(setGone, true);
|
||||
});
|
||||
}, [leaving, opacity]);
|
||||
|
||||
if (gone) return null;
|
||||
return (
|
||||
<Animated.View
|
||||
pointerEvents={leaving ? "none" : "auto"}
|
||||
style={[styles.screen, { backgroundColor: SPLASH_BACKGROUND[scheme] }, fadeStyle]}
|
||||
>
|
||||
<View style={styles.iconCircle}>
|
||||
<View style={styles.logo}>
|
||||
<PaseoLogo size={LOGO_SIZE} color="#ffffff" />
|
||||
</View>
|
||||
</View>
|
||||
</Animated.View>
|
||||
);
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
screen: {
|
||||
position: "absolute",
|
||||
top: 0,
|
||||
left: 0,
|
||||
right: 0,
|
||||
bottom: 0,
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
},
|
||||
iconCircle: {
|
||||
width: ICON_CIRCLE_SIZE,
|
||||
height: ICON_CIRCLE_SIZE,
|
||||
borderRadius: ICON_CIRCLE_SIZE / 2,
|
||||
backgroundColor: "#000000",
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
},
|
||||
logo: {
|
||||
// Optical: the glyph sits right of the SVG's centre. The splash centres the glyph.
|
||||
transform: [{ translateX: -4 }],
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,20 @@
|
||||
import * as SplashScreen from "expo-splash-screen";
|
||||
|
||||
// iOS fades the native splash straight into the first screen.
|
||||
const FADE_MS = 150;
|
||||
|
||||
/** iOS and web: the native splash itself covers the app until launch is done. */
|
||||
export const launchSurface = {
|
||||
keep(): void {
|
||||
// Taking control stops expo-router from hiding the splash when navigation is ready.
|
||||
void SplashScreen.preventAutoHideAsync().catch(() => undefined);
|
||||
SplashScreen.setOptions({ duration: FADE_MS, fade: true });
|
||||
},
|
||||
leave(): void {
|
||||
SplashScreen.hide();
|
||||
},
|
||||
};
|
||||
|
||||
export function LaunchScreen(): null {
|
||||
return null;
|
||||
}
|
||||
@@ -4,7 +4,6 @@ import {
|
||||
resolveStartupNavigationReady,
|
||||
resolveHostIndexRoute,
|
||||
resolveStartupRoute,
|
||||
shouldRunStartupGiveUpTimer,
|
||||
startHostRuntimeBootstrap,
|
||||
bindHostRuntimeAppState,
|
||||
} from "./host-runtime-bootstrap";
|
||||
@@ -90,6 +89,41 @@ describe("startHostRuntimeBootstrap", () => {
|
||||
"decision:true",
|
||||
]);
|
||||
});
|
||||
|
||||
it("settles once the registry boot and the managed-daemon start have both finished", async () => {
|
||||
let resolveBoot!: () => void;
|
||||
let resolveDaemonStart!: (result: DaemonStartResult) => void;
|
||||
let settled = false;
|
||||
|
||||
const bootstrap = startHostRuntimeBootstrap({
|
||||
store: {
|
||||
boot: () =>
|
||||
new Promise<void>((resolve) => {
|
||||
resolveBoot = resolve;
|
||||
}),
|
||||
},
|
||||
daemonStartService: {
|
||||
startIfEnabled: () =>
|
||||
new Promise<DaemonStartResult>((resolve) => {
|
||||
resolveDaemonStart = resolve;
|
||||
}),
|
||||
},
|
||||
shouldStartDaemon: false,
|
||||
});
|
||||
void bootstrap.then(() => {
|
||||
settled = true;
|
||||
return;
|
||||
});
|
||||
|
||||
resolveBoot();
|
||||
await Promise.resolve();
|
||||
await Promise.resolve();
|
||||
expect(settled).toBe(false);
|
||||
|
||||
resolveDaemonStart({ ok: false, error: "daemon failed to start" });
|
||||
await bootstrap;
|
||||
expect(settled).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("startup blocking policy", () => {
|
||||
@@ -100,18 +134,11 @@ describe("startup blocking policy", () => {
|
||||
daemonStartError: null,
|
||||
};
|
||||
|
||||
it("runs the give-up timer when no startup blocker is active", () => {
|
||||
it("does not block navigation when no startup blocker is active", () => {
|
||||
const blocker = resolveStartupBlocker(noBlockerInput);
|
||||
|
||||
expect(blocker).toEqual({ kind: "none" });
|
||||
expect(resolveStartupNavigationReady({ startupBlocker: blocker })).toBe(true);
|
||||
expect(
|
||||
shouldRunStartupGiveUpTimer({
|
||||
startupBlocker: blocker,
|
||||
anyOnlineHostServerId: null,
|
||||
hasGivenUpWaitingForHost: false,
|
||||
}),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("blocks navigation while desktop is starting the managed daemon", () => {
|
||||
@@ -123,13 +150,6 @@ describe("startup blocking policy", () => {
|
||||
|
||||
expect(blocker).toEqual({ kind: "managed-daemon-starting" });
|
||||
expect(resolveStartupNavigationReady({ startupBlocker: blocker })).toBe(false);
|
||||
expect(
|
||||
shouldRunStartupGiveUpTimer({
|
||||
startupBlocker: blocker,
|
||||
anyOnlineHostServerId: null,
|
||||
hasGivenUpWaitingForHost: false,
|
||||
}),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("unblocks navigation when any host is online", () => {
|
||||
@@ -156,13 +176,6 @@ describe("startup blocking policy", () => {
|
||||
message: "daemon failed to start",
|
||||
});
|
||||
expect(resolveStartupNavigationReady({ startupBlocker: blocker })).toBe(true);
|
||||
expect(
|
||||
shouldRunStartupGiveUpTimer({
|
||||
startupBlocker: blocker,
|
||||
anyOnlineHostServerId: null,
|
||||
hasGivenUpWaitingForHost: false,
|
||||
}),
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -176,7 +189,7 @@ describe("resolveStartupRoute", () => {
|
||||
workspaceSelection: null,
|
||||
workspaceSelectionStatus: "unknown" as const,
|
||||
isWorkspaceSelectionLoaded: true,
|
||||
hasGivenUpWaitingForHost: false,
|
||||
isWaitingForHost: true,
|
||||
isWaitingForSetup: false,
|
||||
};
|
||||
const baseHostInput = {
|
||||
@@ -220,7 +233,7 @@ describe("resolveStartupRoute", () => {
|
||||
...baseIndexInput,
|
||||
hostRegistryStatus: "loading",
|
||||
workspaceSelection: { serverId: "server-1", workspaceId: "workspace-a" },
|
||||
hasGivenUpWaitingForHost: true,
|
||||
isWaitingForHost: false,
|
||||
}),
|
||||
).toEqual({ kind: "splash" });
|
||||
});
|
||||
@@ -265,7 +278,7 @@ describe("resolveStartupRoute", () => {
|
||||
...baseIndexInput,
|
||||
workspaceSelection: { serverId: "server-saved", workspaceId: "workspace-a" },
|
||||
hosts: [{ serverId: "server-next" }],
|
||||
hasGivenUpWaitingForHost: true,
|
||||
isWaitingForHost: false,
|
||||
}),
|
||||
).toEqual({ kind: "redirect", href: "/h/server-next" });
|
||||
});
|
||||
@@ -306,16 +319,25 @@ describe("resolveStartupRoute", () => {
|
||||
resolveStartupRoute({
|
||||
...baseIndexInput,
|
||||
hosts: [{ serverId: "server-saved" }],
|
||||
hasGivenUpWaitingForHost: true,
|
||||
isWaitingForHost: false,
|
||||
}),
|
||||
).toEqual({ kind: "redirect", href: "/h/server-saved" });
|
||||
});
|
||||
|
||||
it("shows welcome after root startup gives up and no host exists", () => {
|
||||
it("holds the splash while a startup host source can still add a host", () => {
|
||||
expect(
|
||||
resolveStartupRoute({
|
||||
...baseIndexInput,
|
||||
hasGivenUpWaitingForHost: true,
|
||||
isWaitingForHost: true,
|
||||
}),
|
||||
).toEqual({ kind: "splash" });
|
||||
});
|
||||
|
||||
it("shows welcome as soon as no host exists and none can still arrive", () => {
|
||||
expect(
|
||||
resolveStartupRoute({
|
||||
...baseIndexInput,
|
||||
isWaitingForHost: false,
|
||||
}),
|
||||
).toEqual({ kind: "redirect", href: "/welcome" });
|
||||
});
|
||||
|
||||
@@ -26,9 +26,15 @@ export interface StartHostRuntimeBootstrapInput {
|
||||
shouldStartDaemon: DaemonStartCondition;
|
||||
}
|
||||
|
||||
export function startHostRuntimeBootstrap(input: StartHostRuntimeBootstrapInput): void {
|
||||
/**
|
||||
* Starts every source that can add a host at launch: the registry boot with its connection probes,
|
||||
* and the managed daemon. Settles once none of them can still add one.
|
||||
*/
|
||||
export async function startHostRuntimeBootstrap(
|
||||
input: StartHostRuntimeBootstrapInput,
|
||||
): Promise<void> {
|
||||
const registryReady = input.store.boot();
|
||||
void input.daemonStartService.startIfEnabled({
|
||||
const daemonStart = input.daemonStartService.startIfEnabled({
|
||||
shouldStart: async () => {
|
||||
await registryReady;
|
||||
return typeof input.shouldStartDaemon === "boolean"
|
||||
@@ -36,6 +42,7 @@ export function startHostRuntimeBootstrap(input: StartHostRuntimeBootstrapInput)
|
||||
: input.shouldStartDaemon();
|
||||
},
|
||||
});
|
||||
await Promise.allSettled([registryReady, daemonStart]);
|
||||
}
|
||||
|
||||
const WELCOME_ROUTE: Href = "/welcome";
|
||||
@@ -76,20 +83,6 @@ export function resolveStartupNavigationReady(input: { startupBlocker: StartupBl
|
||||
return input.startupBlocker.kind !== "managed-daemon-starting";
|
||||
}
|
||||
|
||||
export function shouldRunStartupGiveUpTimer(input: {
|
||||
startupBlocker: StartupBlocker;
|
||||
anyOnlineHostServerId: string | null;
|
||||
hasGivenUpWaitingForHost: boolean;
|
||||
}): boolean {
|
||||
if (input.anyOnlineHostServerId) {
|
||||
return false;
|
||||
}
|
||||
if (input.hasGivenUpWaitingForHost) {
|
||||
return false;
|
||||
}
|
||||
return input.startupBlocker.kind === "none";
|
||||
}
|
||||
|
||||
export type StartupRegistryStatus = "loading" | "ready";
|
||||
|
||||
export interface IndexStartupRouteTarget {
|
||||
@@ -116,7 +109,8 @@ export interface ResolveIndexStartupRouteInput extends ResolveStartupRouteBaseIn
|
||||
workspaceSelection: ActiveWorkspaceSelection | null;
|
||||
workspaceSelectionStatus: WorkspaceSelectionStatus;
|
||||
isWorkspaceSelectionLoaded: boolean;
|
||||
hasGivenUpWaitingForHost: boolean;
|
||||
/** A startup host source can still add a host; see `startHostRuntimeBootstrap`. */
|
||||
isWaitingForHost: boolean;
|
||||
/** Setup may still open over the empty home; see `useIsSetupDecisionPending`. */
|
||||
isWaitingForSetup: boolean;
|
||||
}
|
||||
@@ -215,11 +209,11 @@ function resolveReadyIndexStartupRoute(input: ResolveIndexStartupRouteInput): St
|
||||
return { kind: "redirect", href: buildHostRootRoute(savedHostServerId) };
|
||||
}
|
||||
|
||||
if (input.hasGivenUpWaitingForHost) {
|
||||
return { kind: "redirect", href: WELCOME_ROUTE };
|
||||
if (input.isWaitingForHost) {
|
||||
return { kind: "splash" };
|
||||
}
|
||||
|
||||
return { kind: "splash" };
|
||||
return { kind: "redirect", href: WELCOME_ROUTE };
|
||||
}
|
||||
|
||||
function resolveReadyHostStartupRoute(input: ResolveHostStartupRouteInput): StartupRouteDecision {
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import { getHostRuntimeStore } from "@/runtime/host-runtime";
|
||||
import { useNativeSplashHold } from "@/native-splash";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { LoadingSpinner } from "@/components/ui/loading-spinner";
|
||||
import { LoadingState } from "@/components/ui/loading-state";
|
||||
import type { DaemonClient } from "@getpaseo/client/internal/daemon-client";
|
||||
import type { TFunction } from "i18next";
|
||||
import { SquarePen } from "lucide-react-native";
|
||||
@@ -97,6 +99,7 @@ import { ParentAgentCallout, useParentAgentId } from "@/subagents/parent";
|
||||
import { useCreateFlowStore } from "@/stores/create-flow-store";
|
||||
import { buildDraftStoreKey, generateDraftId } from "@/stores/draft-keys";
|
||||
import {
|
||||
selectAgentLoadingWait,
|
||||
selectAgentTimelineState,
|
||||
selectAgentTimelineTurnPresentation,
|
||||
type Agent,
|
||||
@@ -242,6 +245,7 @@ function AgentLoadErrorView({ message, onRetry }: { message: string; onRetry: ()
|
||||
|
||||
/** A draft has no agent to wait for; an agent shows its loading and error states until ready. */
|
||||
function renderConversationNonReadyView(args: {
|
||||
serverId: string;
|
||||
draft: DraftConversation | null;
|
||||
agentId: string | undefined;
|
||||
cwd: string | null;
|
||||
@@ -253,23 +257,25 @@ function renderConversationNonReadyView(args: {
|
||||
if (args.draft) {
|
||||
return null;
|
||||
}
|
||||
const nonReadyView = renderChatAgentNonReadyView(args);
|
||||
invariant(args.agentId, "agent id is defined when the conversation is not a draft");
|
||||
const nonReadyView = renderChatAgentNonReadyView({ ...args, agentId: args.agentId });
|
||||
if (nonReadyView) {
|
||||
return nonReadyView;
|
||||
}
|
||||
invariant(args.agentId, "agent id is defined when agent content is ready");
|
||||
invariant(args.effectiveAgent, "effectiveAgent is defined when the non-ready view is absent");
|
||||
invariant(args.cwd, "agent cwd is defined when agent content is ready");
|
||||
return null;
|
||||
}
|
||||
|
||||
function renderChatAgentNonReadyView(args: {
|
||||
serverId: string;
|
||||
agentId: string;
|
||||
viewState: AgentScreenViewState;
|
||||
effectiveAgent: AgentScreenAgent | null;
|
||||
t: TFunction;
|
||||
onRetryLoad: () => void;
|
||||
}): React.ReactElement | null {
|
||||
const { viewState, effectiveAgent, t, onRetryLoad } = args;
|
||||
const { serverId, agentId, viewState, effectiveAgent, t, onRetryLoad } = args;
|
||||
if (viewState.tag === "not_found") {
|
||||
return (
|
||||
<View style={styles.container} testID="agent-not-found">
|
||||
@@ -283,13 +289,7 @@ function renderChatAgentNonReadyView(args: {
|
||||
return <AgentLoadErrorView message={viewState.message} onRetry={onRetryLoad} />;
|
||||
}
|
||||
if (viewState.tag === "boot" || !effectiveAgent) {
|
||||
return (
|
||||
<View style={styles.container} testID="agent-loading">
|
||||
<View style={styles.errorContainer}>
|
||||
<ThemedLoadingSpinner size="large" uniProps={foregroundMutedColorMapping} />
|
||||
</View>
|
||||
</View>
|
||||
);
|
||||
return <AgentLoadingView serverId={serverId} agentId={agentId} />;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
@@ -647,13 +647,7 @@ function AgentPanelBody({
|
||||
: null;
|
||||
|
||||
if (target.kind === "agent" && !agent) {
|
||||
return (
|
||||
<View style={styles.container} testID="agent-loading">
|
||||
<View style={styles.errorContainer}>
|
||||
<ThemedLoadingSpinner size="large" uniProps={foregroundMutedColorMapping} />
|
||||
</View>
|
||||
</View>
|
||||
);
|
||||
return <AgentLoadingView serverId={serverId} agentId={target.agentId} />;
|
||||
}
|
||||
|
||||
return (
|
||||
@@ -669,6 +663,46 @@ function AgentPanelBody({
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* The pane's loading state, for its agent or the agent's history. A visible pane keeps the launch
|
||||
* splash up while the cache can still answer; after that it says what the host has yet to send.
|
||||
*/
|
||||
function AgentLoadingState({
|
||||
serverId,
|
||||
agentId,
|
||||
testID,
|
||||
}: {
|
||||
serverId: string;
|
||||
agentId: string;
|
||||
testID: string;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const isPaneVisible = useRetainedPanelActive();
|
||||
const wait = useSessionStore(
|
||||
useShallow((state) => selectAgentLoadingWait(state.sessions[serverId], agentId)),
|
||||
);
|
||||
useNativeSplashHold(isPaneVisible && wait.source === "cache");
|
||||
if (wait.source === "cache") return <LoadingState testID={testID} />;
|
||||
return (
|
||||
<LoadingState
|
||||
testID={testID}
|
||||
title={
|
||||
wait.waitingFor === "agent"
|
||||
? t("agentPanel.states.loadingAgent")
|
||||
: t("agentPanel.states.loadingHistory")
|
||||
}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function AgentLoadingView(props: { serverId: string; agentId: string }) {
|
||||
return (
|
||||
<View style={styles.container}>
|
||||
<AgentLoadingState {...props} testID="agent-loading" />
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
function ChatAgentContent({
|
||||
serverId,
|
||||
workspaceId,
|
||||
@@ -1003,6 +1037,7 @@ function ChatAgentContent({
|
||||
[tabId, target, workspaceId],
|
||||
);
|
||||
const nonReadyView = renderConversationNonReadyView({
|
||||
serverId,
|
||||
draft,
|
||||
agentId,
|
||||
cwd: agentState.cwd,
|
||||
@@ -1277,8 +1312,8 @@ const ChatAgentReadyContent = memo(function ChatAgentReadyContent({
|
||||
const dockOverlay = (
|
||||
<>
|
||||
{showHistorySyncOverlay ? (
|
||||
<View style={styles.historySyncOverlay} testID="agent-history-overlay">
|
||||
<ThemedLoadingSpinner size="large" uniProps={foregroundMutedColorMapping} />
|
||||
<View style={styles.historySyncOverlay}>
|
||||
<AgentLoadingState serverId={serverId} agentId={agentId} testID="agent-history-overlay" />
|
||||
</View>
|
||||
) : null}
|
||||
|
||||
|
||||
@@ -82,6 +82,69 @@ describe("plugin timeline projection", () => {
|
||||
expect(seen).toEqual(["Inspect files"]);
|
||||
});
|
||||
|
||||
it("keeps repeated plugin output IDs distinct across source messages", () => {
|
||||
const transform: TimelineItemTransform = ({ item }) => [
|
||||
{
|
||||
type: "plugin",
|
||||
id: "part-0",
|
||||
pluginId: "split",
|
||||
kind: "part",
|
||||
version: 1,
|
||||
data: { text: item.type === "assistant_message" ? item.text : "" },
|
||||
},
|
||||
];
|
||||
const first: StreamItem = {
|
||||
kind: "assistant_message",
|
||||
id: "message-1",
|
||||
text: "Short",
|
||||
timestamp: new Date("2026-01-01T00:00:00.000Z"),
|
||||
};
|
||||
const second: StreamItem = { ...first, id: "message-2", text: "A much longer reply" };
|
||||
const rows = projectPluginTimelineItems([first, second], transform);
|
||||
expect(new Set(rows.map((row) => row.id)).size).toBe(2);
|
||||
expect(rows).toMatchObject([
|
||||
{ source: { id: "message-1" }, pluginItemId: "part-0", data: { text: "Short" } },
|
||||
{
|
||||
source: { id: "message-2" },
|
||||
pluginItemId: "part-0",
|
||||
data: { text: "A much longer reply" },
|
||||
},
|
||||
]);
|
||||
const updated = projectPluginTimelineItems(
|
||||
[{ ...second, text: "Updated reply" }],
|
||||
transform,
|
||||
"streaming",
|
||||
);
|
||||
expect(updated[0].id).toBe(rows[1].id);
|
||||
const completed = projectPluginTimelineItems([{ ...second, text: "Final reply" }], transform);
|
||||
expect(completed[0].id).toBe(rows[1].id);
|
||||
const prepended = projectPluginTimelineItems(
|
||||
[{ ...first, id: "older-message" }, first, second],
|
||||
transform,
|
||||
);
|
||||
expect(prepended.slice(1).map((row) => row.id)).toEqual(rows.map((row) => row.id));
|
||||
});
|
||||
|
||||
it("keeps source and output ID separators unambiguous", () => {
|
||||
const rows = projectPluginTimelineItems(
|
||||
[
|
||||
{ ...thought("First"), id: "message/a" },
|
||||
{ ...thought("Second"), id: "message" },
|
||||
],
|
||||
({ sourceId }) => [
|
||||
{
|
||||
type: "plugin",
|
||||
id: sourceId === "message/a" ? "b" : "a/b",
|
||||
pluginId: "split",
|
||||
kind: "part",
|
||||
version: 1,
|
||||
data: null,
|
||||
},
|
||||
],
|
||||
);
|
||||
expect(rows[0].id).not.toBe(rows[1].id);
|
||||
});
|
||||
|
||||
it("does not expose mutable tool detail from stream state", () => {
|
||||
const detail = { type: "read" as const, filePath: "/repo/original.ts" };
|
||||
const source: StreamItem = {
|
||||
@@ -126,8 +189,8 @@ describe("plugin timeline projection", () => {
|
||||
expect(projectPluginTimelineItems([thought("First")], transform)).toMatchObject([
|
||||
{
|
||||
kind: "plugin",
|
||||
id: "inline-thinking/thought-1/0",
|
||||
source: { kind: "thought", id: "thought-1" },
|
||||
pluginItemId: "thought-1/0",
|
||||
data: { text: "First", phase: "streaming" },
|
||||
},
|
||||
]);
|
||||
@@ -214,10 +277,11 @@ describe("plugin timeline projection", () => {
|
||||
]);
|
||||
const filtered = projectPluginTimelineItems([source], () => []);
|
||||
|
||||
expect(exploded.map((item) => item.id)).toEqual([
|
||||
"split/thought-1/left",
|
||||
"split/thought-1/right",
|
||||
expect(exploded).toMatchObject([
|
||||
{ source: { id: "thought-1" }, pluginItemId: "thought-1/left" },
|
||||
{ source: { id: "thought-1" }, pluginItemId: "thought-1/right" },
|
||||
]);
|
||||
expect(new Set(exploded.map((item) => item.id)).size).toBe(2);
|
||||
expect(filtered).toEqual([]);
|
||||
});
|
||||
|
||||
@@ -254,13 +318,13 @@ describe("plugin timeline projection", () => {
|
||||
expect(projected).toMatchObject([
|
||||
{
|
||||
kind: "plugin",
|
||||
id: "genui/assistant-1/text",
|
||||
pluginItemId: "assistant-1/text",
|
||||
timelineCursor: { epoch: "e1", seq: 7 },
|
||||
turnId: "turn-1",
|
||||
},
|
||||
{
|
||||
kind: "plugin",
|
||||
id: "genui/assistant-1/card",
|
||||
pluginItemId: "assistant-1/card",
|
||||
timelineCursor: { epoch: "e1", seq: 7 },
|
||||
turnId: "turn-1",
|
||||
},
|
||||
|
||||
@@ -94,7 +94,9 @@ function transformSourceItem(
|
||||
return transformed.map((pluginItem) => {
|
||||
const projected: PluginTimelineStreamItem = {
|
||||
kind: "plugin",
|
||||
id: `${pluginItem.pluginId}/${pluginItem.id}`,
|
||||
// Output IDs are local to a source item. Encode each part so separators in
|
||||
// source or output IDs cannot alias another replacement.
|
||||
id: JSON.stringify([pluginItem.pluginId, item.id, pluginItem.id]),
|
||||
source: item,
|
||||
timestamp: item.timestamp,
|
||||
pluginId: pluginItem.pluginId,
|
||||
|
||||
@@ -15,6 +15,7 @@ import { SettingsRow, SettingsSection } from "@/components/settings";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { CheckboxRow } from "@/components/ui/checkbox";
|
||||
import { bySizing, TOUCH_TARGET } from "@/components/ui/control-geometry";
|
||||
import { IndependentScrollBoundary } from "@/components/ui/independent-scroll-boundary";
|
||||
import { ToolbarButton, paneContentToolbarIconSize } from "@/components/ui/pane-content-toolbar";
|
||||
import { SearchField } from "@/components/ui/search-field";
|
||||
import { useIsCompactFormFactor } from "@/constants/layout";
|
||||
@@ -232,14 +233,16 @@ export function ProviderModels({
|
||||
/>
|
||||
) : null}
|
||||
{/* A provider can report hundreds of models; the rest of the page stays in reach. */}
|
||||
<ScrollView
|
||||
// Android scrolls a ScrollView nested in the page or the sheet only with this flag.
|
||||
nestedScrollEnabled
|
||||
style={[styles.discoveredList, curating && settingsStyles.rowBorder]}
|
||||
testID="provider-discovered-models"
|
||||
>
|
||||
{discoveredBody}
|
||||
</ScrollView>
|
||||
<IndependentScrollBoundary activateOnStart={false}>
|
||||
<ScrollView
|
||||
// Android scrolls a ScrollView nested in the page or the sheet only with this flag.
|
||||
nestedScrollEnabled
|
||||
style={[styles.discoveredList, curating && settingsStyles.rowBorder]}
|
||||
testID="provider-discovered-models"
|
||||
>
|
||||
{discoveredBody}
|
||||
</ScrollView>
|
||||
</IndependentScrollBoundary>
|
||||
</View>
|
||||
</SettingsSection>
|
||||
) : null}
|
||||
|
||||
@@ -294,6 +294,75 @@ 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,7 +538,10 @@ export class DirectorySync {
|
||||
|
||||
private loadCachedDirectory(): Promise<void> {
|
||||
const checkpoints = this.checkpoints;
|
||||
if (!checkpoints) return Promise.resolve();
|
||||
if (!checkpoints) {
|
||||
useSessionStore.getState().markCachedDirectoryRestored(this.serverId);
|
||||
return Promise.resolve();
|
||||
}
|
||||
this.cacheLoad ??= (async () => {
|
||||
const revision = this.revision;
|
||||
const cached = await checkpoints.readDirectory(this.serverId);
|
||||
@@ -549,7 +552,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;
|
||||
}
|
||||
|
||||
|
||||
@@ -29,7 +29,8 @@ import {
|
||||
type HostRuntimeControllerDeps,
|
||||
type HostRuntimeStorage,
|
||||
} from "./host-runtime";
|
||||
import type { ReplicaRow, ReplicaRowStore } from "./replica-cache/row-store";
|
||||
import { replicaPayloadBytes } from "./replica-cache/payload-bytes";
|
||||
import type { ReplicaRow, ReplicaRowSize, ReplicaRowStore } from "./replica-cache/row-store";
|
||||
|
||||
import { subscriptionFixture } from "./subscription-fixture";
|
||||
import { readDesktopManagedLocalCredential } from "@/desktop/daemon/local-credential";
|
||||
@@ -640,12 +641,12 @@ function createMemoryReplicaRowStore(): ReplicaRowStore {
|
||||
(!acceptedIds || acceptedIds.has(row.id)),
|
||||
);
|
||||
},
|
||||
readAll: async () => {
|
||||
const hosts = new Map<string, ReplicaRow[]>();
|
||||
for (const row of rows.values()) {
|
||||
const hostRows = hosts.get(row.serverId) ?? [];
|
||||
hostRows.push(row);
|
||||
hosts.set(row.serverId, hostRows);
|
||||
readIndex: async () => {
|
||||
const hosts = new Map<string, ReplicaRowSize[]>();
|
||||
for (const { serverId, kind, id, payload } of rows.values()) {
|
||||
const hostRows = hosts.get(serverId) ?? [];
|
||||
hostRows.push({ serverId, kind, id, bytes: replicaPayloadBytes(payload) });
|
||||
hosts.set(serverId, hostRows);
|
||||
}
|
||||
return [...hosts].map(([serverId, hostRows]) => ({ serverId, rows: hostRows }));
|
||||
},
|
||||
@@ -3263,6 +3264,48 @@ 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" }],
|
||||
|
||||
@@ -2034,12 +2034,6 @@ 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 {
|
||||
@@ -2157,6 +2151,34 @@ 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;
|
||||
@@ -2178,25 +2200,7 @@ export class HostRuntimeStore {
|
||||
this.directorySyncByServer.get(oldServerId)?.dispose();
|
||||
this.directorySyncByServer.delete(oldServerId);
|
||||
this.timelineReplicaByServer.delete(oldServerId);
|
||||
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),
|
||||
}),
|
||||
);
|
||||
const directory = this.startDirectory(newServerId, controller);
|
||||
controller.adoptReconciledServerId(newServerId);
|
||||
const snapshot = controller.getSnapshot();
|
||||
this.clearHostReplica(oldServerId);
|
||||
@@ -2714,25 +2718,7 @@ export class HostRuntimeStore {
|
||||
});
|
||||
this.controllers.set(host.serverId, controller);
|
||||
useSessionStore.getState().initializeSession(host.serverId, null);
|
||||
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),
|
||||
}),
|
||||
);
|
||||
this.startDirectory(host.serverId, controller);
|
||||
const initialSnapshot = controller.getSnapshot();
|
||||
this.lastConnectionStatusByServer.set(host.serverId, initialSnapshot.connectionStatus);
|
||||
if (initialSnapshot.connectionStatus === "online") {
|
||||
|
||||
@@ -0,0 +1,128 @@
|
||||
import { getHeapSnapshot } from "node:v8";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { ReplicaCache } from ".";
|
||||
import { createSqliteReplicaRowStore, type ReplicaSqliteDriver } from "./row-store-sqlite";
|
||||
import { createNodeSqliteDriver } from "./row-store-sqlite.test-driver";
|
||||
|
||||
// The SQLite store keeps rows in native memory, so any payload string left on the JS heap after a
|
||||
// write or a cold start is one the cache itself holds on to.
|
||||
|
||||
const SERVER_ID = "cached-host";
|
||||
const OTHER_SERVER_ID = "other-host";
|
||||
const noLegacyCleanup = { clearLegacyCache: async () => undefined };
|
||||
|
||||
function openCache(driver: ReplicaSqliteDriver, maxBytes?: number): ReplicaCache {
|
||||
const cache = new ReplicaCache(createSqliteReplicaRowStore(driver, 1), {
|
||||
...noLegacyCleanup,
|
||||
...(maxBytes ? { maxBytes } : {}),
|
||||
});
|
||||
cache.setHosts([SERVER_ID, OTHER_SERVER_ID]);
|
||||
return cache;
|
||||
}
|
||||
|
||||
function timeline(agentId: string, text: string) {
|
||||
return {
|
||||
agentId,
|
||||
items: [
|
||||
{
|
||||
kind: "assistant_message" as const,
|
||||
id: "message-1",
|
||||
text,
|
||||
timestamp: new Date("2026-07-18T08:02:00.000Z"),
|
||||
timelineCursor: { epoch: "epoch-1", seq: 12 },
|
||||
},
|
||||
],
|
||||
range: { epoch: "epoch-1", startSeq: 1, endSeq: 12 },
|
||||
hasOlder: false,
|
||||
};
|
||||
}
|
||||
|
||||
// Built inside a function so the test keeps no reference to the transcript text once committed.
|
||||
function commitLargeTimeline(cache: ReplicaCache, serverId: string, marker: string): void {
|
||||
cache.commitTimeline(serverId, "agent-1", timeline("agent-1", marker + "x".repeat(1_000_000)));
|
||||
}
|
||||
|
||||
/** Sizes of serialized payload strings, retained on the JS heap, whose text contains the marker. */
|
||||
async function retainedPayloadStrings(marker: string): Promise<number[]> {
|
||||
const chunks: Buffer[] = [];
|
||||
// Taking a snapshot runs a full garbage collection first.
|
||||
for await (const chunk of getHeapSnapshot()) chunks.push(chunk as Buffer);
|
||||
const snapshot = JSON.parse(Buffer.concat(chunks).toString("utf8")) as {
|
||||
snapshot: { meta: { node_fields: string[]; node_types: [string[]] } };
|
||||
nodes: number[];
|
||||
strings: string[];
|
||||
};
|
||||
const fields = snapshot.snapshot.meta.node_fields;
|
||||
const types = snapshot.snapshot.meta.node_types[0];
|
||||
const typeField = fields.indexOf("type");
|
||||
const nameField = fields.indexOf("name");
|
||||
const sizeField = fields.indexOf("self_size");
|
||||
const sizes: number[] = [];
|
||||
for (let base = 0; base < snapshot.nodes.length; base += fields.length) {
|
||||
if (!types[snapshot.nodes[base + typeField]].includes("string")) continue;
|
||||
const name = snapshot.strings[snapshot.nodes[base + nameField]];
|
||||
// The transcript text itself starts with the marker; its JSON payload starts with "{".
|
||||
if (name.startsWith("{") && name.includes(marker)) {
|
||||
sizes.push(snapshot.nodes[base + sizeField]);
|
||||
}
|
||||
}
|
||||
return sizes;
|
||||
}
|
||||
|
||||
describe("ReplicaCache over SQLite", () => {
|
||||
it("does not keep written payloads on the JS heap", async () => {
|
||||
const marker = `written-${crypto.randomUUID()}`;
|
||||
const cache = openCache(createNodeSqliteDriver());
|
||||
commitLargeTimeline(cache, SERVER_ID, marker);
|
||||
await cache.flush();
|
||||
|
||||
expect(await retainedPayloadStrings(marker)).toEqual([]);
|
||||
expect((await cache.readTimeline(SERVER_ID, "agent-1"))?.items[0]).toMatchObject({
|
||||
text: expect.stringMatching(new RegExp(`^${marker}x{1000000}$`)),
|
||||
});
|
||||
}, 60_000);
|
||||
|
||||
it("does not load stored payloads onto the JS heap to index a cold start", async () => {
|
||||
const marker = `stored-${crypto.randomUUID()}`;
|
||||
const driver = createNodeSqliteDriver();
|
||||
const writer = openCache(driver);
|
||||
commitLargeTimeline(writer, SERVER_ID, marker);
|
||||
await writer.flush();
|
||||
|
||||
const cache = openCache(driver);
|
||||
// The first write indexes every stored row to enforce the budget.
|
||||
cache.commitTimeline(OTHER_SERVER_ID, "agent-1", timeline("agent-1", "small"));
|
||||
await cache.flush();
|
||||
|
||||
expect(await retainedPayloadStrings(marker)).toEqual([]);
|
||||
expect(await cache.readTimeline(SERVER_ID, "agent-1")).toBeDefined();
|
||||
}, 60_000);
|
||||
|
||||
it.each([
|
||||
{ budget: "exactly fits", slack: 0, evicted: false },
|
||||
{ budget: "is one byte short", slack: -1, evicted: true },
|
||||
])("enforces the budget in UTF-8 bytes after a cold start when it $budget", async (input) => {
|
||||
const driver = createNodeSqliteDriver();
|
||||
const writer = openCache(driver);
|
||||
writer.commitTimeline(SERVER_ID, "agent-1", timeline("agent-1", "é😀中".repeat(500)));
|
||||
writer.commitTimeline(OTHER_SERVER_ID, "agent-1", timeline("agent-1", "other"));
|
||||
await writer.flush();
|
||||
const storedBytes = await sumStoredPayloadBytes(driver);
|
||||
|
||||
const cache = openCache(driver, storedBytes + input.slack);
|
||||
// Same size as the stored row, so the projected total stays at the stored total.
|
||||
cache.commitTimeline(OTHER_SERVER_ID, "agent-1", timeline("agent-1", "OTHER"));
|
||||
await cache.flush();
|
||||
|
||||
expect((await cache.readTimeline(SERVER_ID, "agent-1")) === undefined).toBe(input.evicted);
|
||||
expect((await cache.readTimeline(OTHER_SERVER_ID, "agent-1"))?.items[0]).toMatchObject({
|
||||
text: "OTHER",
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
async function sumStoredPayloadBytes(driver: ReplicaSqliteDriver): Promise<number> {
|
||||
const connection = await driver.open();
|
||||
const rows = await connection.all<{ payload: string }>("SELECT payload FROM rows");
|
||||
return rows.reduce((total, row) => total + Buffer.byteLength(row.payload, "utf8"), 0);
|
||||
}
|
||||
@@ -13,7 +13,14 @@ import {
|
||||
} from "@/plugins/client-state/snapshots";
|
||||
import { ReplicaCache } from ".";
|
||||
import type { DirectoryCheckpoint } from "@/runtime/replica-cache";
|
||||
import type { ReplicaHostRows, ReplicaRow, ReplicaRowChanges, ReplicaRowStore } from "./row-store";
|
||||
import { replicaPayloadBytes } from "./payload-bytes";
|
||||
import type {
|
||||
ReplicaHostIndex,
|
||||
ReplicaRow,
|
||||
ReplicaRowChanges,
|
||||
ReplicaRowSize,
|
||||
ReplicaRowStore,
|
||||
} from "./row-store";
|
||||
|
||||
const SERVER_ID = "cached-host";
|
||||
|
||||
@@ -41,8 +48,8 @@ class MemoryStorage implements ReplicaRowStore {
|
||||
onRead: (() => void) | null = null;
|
||||
/** Throws once a read goes past this count, so a non-terminating read loop fails the test. */
|
||||
readLimit: number | null = null;
|
||||
/** Awaited before the store lists every row or deletes a host, so a test can interleave there. */
|
||||
beforeReadAll: (() => Promise<void>) | null = null;
|
||||
/** Awaited before the store indexes every row or deletes a host, so a test can interleave there. */
|
||||
beforeReadIndex: (() => Promise<void>) | null = null;
|
||||
beforeDeleteHost: (() => Promise<void>) | null = null;
|
||||
|
||||
private key(row: Pick<ReplicaRow, "serverId" | "kind" | "id">): string {
|
||||
@@ -74,13 +81,13 @@ class MemoryStorage implements ReplicaRowStore {
|
||||
);
|
||||
}
|
||||
|
||||
async readAll(): Promise<ReplicaHostRows[]> {
|
||||
await this.beforeReadAll?.();
|
||||
const hosts = new Map<string, ReplicaRow[]>();
|
||||
for (const row of this.rows.values()) {
|
||||
const rows = hosts.get(row.serverId) ?? [];
|
||||
rows.push(row);
|
||||
hosts.set(row.serverId, rows);
|
||||
async readIndex(): Promise<ReplicaHostIndex[]> {
|
||||
await this.beforeReadIndex?.();
|
||||
const hosts = new Map<string, ReplicaRowSize[]>();
|
||||
for (const { serverId, kind, id, payload } of this.rows.values()) {
|
||||
const rows = hosts.get(serverId) ?? [];
|
||||
rows.push({ serverId, kind, id, bytes: replicaPayloadBytes(payload) });
|
||||
hosts.set(serverId, rows);
|
||||
}
|
||||
return [...hosts].map(([serverId, rows]) => ({ serverId, rows }));
|
||||
}
|
||||
@@ -1143,7 +1150,7 @@ describe("ReplicaCache", () => {
|
||||
).toEqual(["agent", "checkpoint", "project", "workspace"]);
|
||||
});
|
||||
|
||||
it.each(["beforeReadAll", "beforeDeleteHost"] as const)(
|
||||
it.each(["beforeReadIndex", "beforeDeleteHost"] as const)(
|
||||
"stores no checkpoint for a host evicted after its update was queued (%s)",
|
||||
async (pausePoint) => {
|
||||
const storage = new MemoryStorage();
|
||||
|
||||
@@ -27,12 +27,14 @@ import {
|
||||
import type { UnsettledTurn } from "@/timeline/turn-liveness";
|
||||
import { normalizeAgentSnapshot } from "@/utils/agent-snapshots";
|
||||
import { clearLegacyReplicaCache } from "./legacy-cleanup";
|
||||
import { replicaPayloadBytes } from "./payload-bytes";
|
||||
import {
|
||||
REPLICA_SINGLETON_ROW_ID,
|
||||
type ReplicaRow,
|
||||
type ReplicaRowChanges,
|
||||
type ReplicaRowKey,
|
||||
type ReplicaRowKind,
|
||||
type ReplicaRowSize,
|
||||
type ReplicaRowStore,
|
||||
} from "./row-store";
|
||||
|
||||
@@ -869,31 +871,27 @@ function pendingRowKey(key: ReplicaRowKey): string {
|
||||
return `${key.serverId}\u0000${rowKey(key)}`;
|
||||
}
|
||||
|
||||
// Budget accounting runs over every stored row of a touched host on each persist. Rows are
|
||||
// immutable once stored, so their size is computed once. The count itself avoids the JS Buffer
|
||||
// polyfill, which materialises the whole byte array just to measure it.
|
||||
const rowBytesCache = new WeakMap<ReplicaRow, number>();
|
||||
// A write is sized twice, once to fit the budget and once when it is stored. Sizing walks the
|
||||
// whole payload, so each written row is measured once.
|
||||
const writtenRowSizes = new WeakMap<ReplicaRow, ReplicaRowSize>();
|
||||
|
||||
function utf8ByteLength(text: string): number {
|
||||
let bytes = 0;
|
||||
for (let index = 0; index < text.length; index += 1) {
|
||||
const code = text.charCodeAt(index);
|
||||
if (code < 0x80) bytes += 1;
|
||||
else if (code < 0x800) bytes += 2;
|
||||
else if (code >= 0xd800 && code <= 0xdbff) {
|
||||
bytes += 4;
|
||||
index += 1;
|
||||
} else bytes += 3;
|
||||
function rowSize(row: ReplicaRow): ReplicaRowSize {
|
||||
let size = writtenRowSizes.get(row);
|
||||
if (!size) {
|
||||
size = {
|
||||
serverId: row.serverId,
|
||||
kind: row.kind,
|
||||
id: row.id,
|
||||
bytes: replicaPayloadBytes(row.payload),
|
||||
};
|
||||
writtenRowSizes.set(row, size);
|
||||
}
|
||||
return bytes;
|
||||
return size;
|
||||
}
|
||||
|
||||
function rowBytes(row: ReplicaRow): number {
|
||||
let bytes = rowBytesCache.get(row);
|
||||
if (bytes === undefined) {
|
||||
bytes = utf8ByteLength(row.payload);
|
||||
rowBytesCache.set(row, bytes);
|
||||
}
|
||||
function sumBytes(rows: Iterable<ReplicaRowSize>): number {
|
||||
let bytes = 0;
|
||||
for (const row of rows) bytes += row.bytes;
|
||||
return bytes;
|
||||
}
|
||||
|
||||
@@ -980,7 +978,8 @@ function matchesReplicaRead(read: ReplicaRead, row: ReplicaRowKey): boolean {
|
||||
export class ReplicaCache {
|
||||
private readonly activeServerIds = new Set<string>();
|
||||
private readonly activeReads = new Set<ReplicaRead>();
|
||||
private readonly storedRows = new Map<string, Map<string, ReplicaRow>>();
|
||||
// Key and size of every stored row, by host. Payloads stay in the row store.
|
||||
private readonly storedRows = new Map<string, Map<string, ReplicaRowSize>>();
|
||||
private readonly hostBytes = new Map<string, number>();
|
||||
private readonly hostWriteOrder = new Map<string, true>();
|
||||
private pendingUpserts = new Map<string, StructuredReplicaUpsert>();
|
||||
@@ -1283,13 +1282,13 @@ export class ReplicaCache {
|
||||
this.invalidateHostReads(newServerId);
|
||||
const rows = this.storedRows.get(oldServerId);
|
||||
if (rows) {
|
||||
const newRows = this.storedRows.get(newServerId) ?? new Map<string, ReplicaRow>();
|
||||
const newRows = this.storedRows.get(newServerId) ?? new Map<string, ReplicaRowSize>();
|
||||
this.totalBytes -=
|
||||
(this.hostBytes.get(oldServerId) ?? 0) + (this.hostBytes.get(newServerId) ?? 0);
|
||||
this.storedRows.delete(oldServerId);
|
||||
for (const [key, row] of rows) newRows.set(key, { ...row, serverId: newServerId });
|
||||
this.storedRows.set(newServerId, newRows);
|
||||
const bytes = [...newRows.values()].reduce((sum, row) => sum + rowBytes(row), 0);
|
||||
const bytes = sumBytes(newRows.values());
|
||||
this.hostBytes.delete(oldServerId);
|
||||
this.hostBytes.set(newServerId, bytes);
|
||||
this.totalBytes += bytes;
|
||||
@@ -1529,17 +1528,17 @@ export class ReplicaCache {
|
||||
const previous = rows?.get(rowKey(key));
|
||||
if (previous) {
|
||||
rows?.delete(rowKey(key));
|
||||
this.adjustHostBytes(key.serverId, -rowBytes(previous));
|
||||
this.adjustHostBytes(key.serverId, -previous.bytes);
|
||||
}
|
||||
touchedServerIds.add(key.serverId);
|
||||
}
|
||||
for (const row of changes.upserts) {
|
||||
const rows = this.storedRows.get(row.serverId) ?? new Map<string, ReplicaRow>();
|
||||
const rows = this.storedRows.get(row.serverId) ?? new Map<string, ReplicaRowSize>();
|
||||
const previous = rows.get(rowKey(row));
|
||||
const previousBytes = previous ? rowBytes(previous) : 0;
|
||||
rows.set(rowKey(row), row);
|
||||
const size = rowSize(row);
|
||||
rows.set(rowKey(row), size);
|
||||
this.storedRows.set(row.serverId, rows);
|
||||
this.adjustHostBytes(row.serverId, rowBytes(row) - previousBytes);
|
||||
this.adjustHostBytes(row.serverId, size.bytes - (previous?.bytes ?? 0));
|
||||
touchedServerIds.add(row.serverId);
|
||||
}
|
||||
for (const serverId of touchedServerIds) {
|
||||
@@ -1568,7 +1567,7 @@ export class ReplicaCache {
|
||||
for (const key of changes.deletes) touchedServerIds.add(key.serverId);
|
||||
for (const row of changes.upserts) touchedServerIds.add(row.serverId);
|
||||
|
||||
const projectedRows = new Map<string, Map<string, ReplicaRow>>();
|
||||
const projectedRows = new Map<string, Map<string, ReplicaRowSize>>();
|
||||
const projectedBytes = new Map(this.hostBytes);
|
||||
for (const serverId of touchedServerIds) {
|
||||
projectedRows.set(serverId, new Map(this.storedRows.get(serverId)));
|
||||
@@ -1577,13 +1576,10 @@ export class ReplicaCache {
|
||||
projectedRows.get(key.serverId)?.delete(rowKey(key));
|
||||
}
|
||||
for (const row of changes.upserts) {
|
||||
projectedRows.get(row.serverId)?.set(rowKey(row), row);
|
||||
projectedRows.get(row.serverId)?.set(rowKey(row), rowSize(row));
|
||||
}
|
||||
for (const [serverId, rows] of projectedRows) {
|
||||
projectedBytes.set(
|
||||
serverId,
|
||||
[...rows.values()].reduce((sum, row) => sum + rowBytes(row), 0),
|
||||
);
|
||||
projectedBytes.set(serverId, sumBytes(rows.values()));
|
||||
}
|
||||
|
||||
const writeOrder = [...this.hostWriteOrder.keys()].filter(
|
||||
@@ -1656,7 +1652,7 @@ export class ReplicaCache {
|
||||
}
|
||||
|
||||
private ensureStoredIndex(): Promise<void> {
|
||||
this.storedIndexPromise ??= this.rowStore.readAll().then(async (hosts) => {
|
||||
this.storedIndexPromise ??= this.rowStore.readIndex().then(async (hosts) => {
|
||||
this.storedRows.clear();
|
||||
this.hostBytes.clear();
|
||||
this.hostWriteOrder.clear();
|
||||
@@ -1667,7 +1663,7 @@ export class ReplicaCache {
|
||||
continue;
|
||||
}
|
||||
const rows = new Map(host.rows.map((row) => [rowKey(row), row]));
|
||||
const bytes = host.rows.reduce((sum, row) => sum + rowBytes(row), 0);
|
||||
const bytes = sumBytes(host.rows);
|
||||
this.storedRows.set(host.serverId, rows);
|
||||
this.hostBytes.set(host.serverId, bytes);
|
||||
this.totalBytes += bytes;
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
// The size the row stores report for a payload. Counting avoids the JS Buffer polyfill, which
|
||||
// materialises the whole byte array just to measure it.
|
||||
export function replicaPayloadBytes(payload: string): number {
|
||||
let bytes = 0;
|
||||
for (let index = 0; index < payload.length; index += 1) {
|
||||
const code = payload.charCodeAt(index);
|
||||
if (code < 0x80) bytes += 1;
|
||||
else if (code < 0x800) bytes += 2;
|
||||
else if (code >= 0xd800 && code <= 0xdbff) {
|
||||
bytes += 4;
|
||||
index += 1;
|
||||
} else bytes += 3;
|
||||
}
|
||||
return bytes;
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
import { DatabaseSync, type SQLInputValue } from "node:sqlite";
|
||||
import type { ReplicaSqliteConnection, ReplicaSqliteDriver, SqliteValue } from "./row-store-sqlite";
|
||||
|
||||
/** Test driver over Node's built-in SQLite. Rows live in native memory, outside the JS heap. */
|
||||
export function createNodeSqliteDriver(): ReplicaSqliteDriver {
|
||||
const database = new DatabaseSync(":memory:");
|
||||
|
||||
function connection(): ReplicaSqliteConnection {
|
||||
return {
|
||||
async exec(sql) {
|
||||
database.exec(sql);
|
||||
},
|
||||
async run(sql, params = []) {
|
||||
database.prepare(sql).run(...(params as SQLInputValue[]));
|
||||
},
|
||||
async all<Row>(sql: string, params: readonly SqliteValue[] = []) {
|
||||
return database.prepare(sql).all(...(params as SQLInputValue[])) as Row[];
|
||||
},
|
||||
async transaction(operation) {
|
||||
database.exec("BEGIN IMMEDIATE");
|
||||
try {
|
||||
await operation(connection());
|
||||
database.exec("COMMIT");
|
||||
} catch (error) {
|
||||
database.exec("ROLLBACK");
|
||||
throw error;
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
async open() {
|
||||
return connection();
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -1,4 +1,10 @@
|
||||
import type { ReplicaHostRows, ReplicaRow, ReplicaRowChanges, ReplicaRowStore } from "./row-store";
|
||||
import type {
|
||||
ReplicaHostIndex,
|
||||
ReplicaRow,
|
||||
ReplicaRowChanges,
|
||||
ReplicaRowSize,
|
||||
ReplicaRowStore,
|
||||
} from "./row-store";
|
||||
|
||||
export type SqliteValue = string | number | null;
|
||||
|
||||
@@ -34,6 +40,13 @@ interface StoredMeta {
|
||||
value: string;
|
||||
}
|
||||
|
||||
interface StoredRowSize {
|
||||
server_id: string;
|
||||
kind: ReplicaRow["kind"];
|
||||
id: string;
|
||||
bytes: number;
|
||||
}
|
||||
|
||||
interface StoredRow {
|
||||
server_id: string;
|
||||
kind: ReplicaRow["kind"];
|
||||
@@ -89,18 +102,20 @@ export function createSqliteReplicaRowStore(
|
||||
}
|
||||
}
|
||||
|
||||
async function readAll(): Promise<ReplicaHostRows[]> {
|
||||
const storedRows = await getConnection().all<StoredRow>(
|
||||
"SELECT server_id, kind, id, payload FROM rows ORDER BY server_id, kind, id",
|
||||
async function readIndex(): Promise<ReplicaHostIndex[]> {
|
||||
// The database stores text as UTF-8, so the blob length is the payload's UTF-8 size.
|
||||
const storedRows = await getConnection().all<StoredRowSize>(
|
||||
`SELECT server_id, kind, id, length(CAST(payload AS BLOB)) AS bytes FROM rows
|
||||
ORDER BY server_id, kind, id`,
|
||||
);
|
||||
const hosts = new Map<string, ReplicaRow[]>();
|
||||
const hosts = new Map<string, ReplicaRowSize[]>();
|
||||
for (const storedRow of storedRows) {
|
||||
const rows = hosts.get(storedRow.server_id) ?? [];
|
||||
rows.push({
|
||||
serverId: storedRow.server_id,
|
||||
kind: storedRow.kind,
|
||||
id: storedRow.id,
|
||||
payload: storedRow.payload,
|
||||
bytes: storedRow.bytes,
|
||||
});
|
||||
hosts.set(storedRow.server_id, rows);
|
||||
}
|
||||
@@ -169,5 +184,5 @@ export function createSqliteReplicaRowStore(
|
||||
await getConnection().run("DELETE FROM rows");
|
||||
}
|
||||
|
||||
return { open, read, readAll, apply, deleteHost, renameHost, clear };
|
||||
return { open, read, readIndex, apply, deleteHost, renameHost, clear };
|
||||
}
|
||||
|
||||
@@ -8,6 +8,23 @@ export interface ReplicaRowStoreHarness {
|
||||
|
||||
export type CreateReplicaRowStoreHarness = () => Promise<ReplicaRowStoreHarness>;
|
||||
|
||||
const ALL_KINDS: ReplicaRow["kind"][] = ["agent", "checkpoint", "project", "timeline", "workspace"];
|
||||
|
||||
interface ReplicaHostRows {
|
||||
serverId: string;
|
||||
rows: ReplicaRow[];
|
||||
}
|
||||
|
||||
async function readEveryRow(store: ReplicaRowStore): Promise<ReplicaHostRows[]> {
|
||||
const hosts = await store.readIndex();
|
||||
return Promise.all(
|
||||
hosts.map(async (host) => ({
|
||||
serverId: host.serverId,
|
||||
rows: await store.read(host.serverId, ALL_KINDS),
|
||||
})),
|
||||
);
|
||||
}
|
||||
|
||||
function row(serverId: string, kind: ReplicaRow["kind"], id: string, payload: string): ReplicaRow {
|
||||
return { serverId, kind, id, payload };
|
||||
}
|
||||
@@ -27,7 +44,7 @@ export function runReplicaRowStoreContract(
|
||||
});
|
||||
|
||||
it("reads an empty store", async () => {
|
||||
expect(await store.readAll()).toEqual([]);
|
||||
expect(await readEveryRow(store)).toEqual([]);
|
||||
});
|
||||
|
||||
it("round-trips opaque payloads grouped by server", async () => {
|
||||
@@ -40,7 +57,7 @@ export function runReplicaRowStoreContract(
|
||||
deletes: [],
|
||||
});
|
||||
|
||||
expect(await store.readAll()).toEqual([
|
||||
expect(await readEveryRow(store)).toEqual([
|
||||
{
|
||||
serverId: "server-a",
|
||||
rows: [
|
||||
@@ -81,7 +98,7 @@ export function runReplicaRowStoreContract(
|
||||
deletes: [],
|
||||
});
|
||||
|
||||
expect(await store.readAll()).toEqual([
|
||||
expect(await readEveryRow(store)).toEqual([
|
||||
{
|
||||
serverId: "server-a",
|
||||
rows: [row("server-a", "agent", "agent-1", "new")],
|
||||
@@ -102,7 +119,7 @@ export function runReplicaRowStoreContract(
|
||||
deletes: [{ serverId: "server-a", kind: "agent", id: "same-id" }],
|
||||
});
|
||||
|
||||
expect(await store.readAll()).toEqual([
|
||||
expect(await readEveryRow(store)).toEqual([
|
||||
{
|
||||
serverId: "server-a",
|
||||
rows: [row("server-a", "workspace", "same-id", "workspace")],
|
||||
@@ -122,7 +139,7 @@ export function runReplicaRowStoreContract(
|
||||
deletes: [],
|
||||
}),
|
||||
).rejects.toBeInstanceOf(Error);
|
||||
expect(await store.readAll()).toEqual([]);
|
||||
expect(await readEveryRow(store)).toEqual([]);
|
||||
});
|
||||
|
||||
it("deletes every row belonging to one host", async () => {
|
||||
@@ -137,7 +154,7 @@ export function runReplicaRowStoreContract(
|
||||
|
||||
await store.deleteHost("server-a");
|
||||
|
||||
expect(await store.readAll()).toEqual([
|
||||
expect(await readEveryRow(store)).toEqual([
|
||||
{ serverId: "server-b", rows: [row("server-b", "agent", "agent-2", "b")] },
|
||||
]);
|
||||
});
|
||||
@@ -155,7 +172,7 @@ export function runReplicaRowStoreContract(
|
||||
|
||||
await store.renameHost("temporary", "canonical");
|
||||
|
||||
expect(await store.readAll()).toEqual([
|
||||
expect(await readEveryRow(store)).toEqual([
|
||||
{
|
||||
serverId: "canonical",
|
||||
rows: [
|
||||
@@ -178,7 +195,67 @@ export function runReplicaRowStoreContract(
|
||||
|
||||
await store.clear();
|
||||
|
||||
expect(await store.readAll()).toEqual([]);
|
||||
expect(await readEveryRow(store)).toEqual([]);
|
||||
});
|
||||
|
||||
it("indexes every row by key and UTF-8 payload size, without payloads", async () => {
|
||||
await store.apply({
|
||||
upserts: [
|
||||
row("server-b", "checkpoint", "singleton", '{"cursor":2}'),
|
||||
row("server-a", "timeline", "agent-1", "é😀中a"),
|
||||
row("server-a", "agent", "agent-1", "ascii"),
|
||||
],
|
||||
deletes: [],
|
||||
});
|
||||
|
||||
expect(await store.readIndex()).toEqual([
|
||||
{
|
||||
serverId: "server-a",
|
||||
rows: [
|
||||
{ serverId: "server-a", kind: "agent", id: "agent-1", bytes: 5 },
|
||||
{ serverId: "server-a", kind: "timeline", id: "agent-1", bytes: 10 },
|
||||
],
|
||||
},
|
||||
{
|
||||
serverId: "server-b",
|
||||
rows: [{ serverId: "server-b", kind: "checkpoint", id: "singleton", bytes: 12 }],
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("keeps indexed sizes in step with overwrites, deletes, directory writes, and renames", async () => {
|
||||
await store.apply({
|
||||
upserts: [
|
||||
row("temporary", "agent", "agent-1", "x".repeat(40)),
|
||||
row("temporary", "timeline", "agent-1", "short"),
|
||||
],
|
||||
deletes: [],
|
||||
});
|
||||
await store.apply(
|
||||
{
|
||||
upserts: [
|
||||
row("temporary", "agent", "agent-1", "ü".repeat(3)),
|
||||
row("temporary", "checkpoint", "singleton", '{"a":1}'),
|
||||
],
|
||||
deletes: [{ serverId: "temporary", kind: "timeline", id: "agent-1" }],
|
||||
},
|
||||
{ directoryBaselines: new Set(["temporary"]) },
|
||||
);
|
||||
await store.renameHost("temporary", "canonical");
|
||||
|
||||
expect(await store.readIndex()).toEqual([
|
||||
{
|
||||
serverId: "canonical",
|
||||
rows: [
|
||||
{ serverId: "canonical", kind: "agent", id: "agent-1", bytes: 6 },
|
||||
{ serverId: "canonical", kind: "checkpoint", id: "singleton", bytes: 7 },
|
||||
],
|
||||
},
|
||||
]);
|
||||
expect(await store.read("canonical", ["agent", "checkpoint"])).toEqual([
|
||||
row("canonical", "agent", "agent-1", "ü".repeat(3)),
|
||||
row("canonical", "checkpoint", "singleton", '{"a":1}'),
|
||||
]);
|
||||
});
|
||||
|
||||
it("wipes cached rows when the schema version changes on open", async () => {
|
||||
@@ -189,7 +266,7 @@ export function runReplicaRowStoreContract(
|
||||
|
||||
const upgradedStore = await harness.openWithSchemaVersion(2);
|
||||
|
||||
expect(await upgradedStore.readAll()).toEqual([]);
|
||||
expect(await readEveryRow(upgradedStore)).toEqual([]);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1,45 +1,6 @@
|
||||
import { DatabaseSync, type SQLInputValue } from "node:sqlite";
|
||||
import { runReplicaRowStoreContract } from "./row-store.contract";
|
||||
import {
|
||||
createSqliteReplicaRowStore,
|
||||
type ReplicaSqliteConnection,
|
||||
type ReplicaSqliteDriver,
|
||||
type SqliteValue,
|
||||
} from "./row-store-sqlite";
|
||||
|
||||
function createNodeSqliteDriver(): ReplicaSqliteDriver {
|
||||
const database = new DatabaseSync(":memory:");
|
||||
|
||||
function connection(): ReplicaSqliteConnection {
|
||||
return {
|
||||
async exec(sql) {
|
||||
database.exec(sql);
|
||||
},
|
||||
async run(sql, params = []) {
|
||||
database.prepare(sql).run(...(params as SQLInputValue[]));
|
||||
},
|
||||
async all<Row>(sql: string, params: readonly SqliteValue[] = []) {
|
||||
return database.prepare(sql).all(...(params as SQLInputValue[])) as Row[];
|
||||
},
|
||||
async transaction(operation) {
|
||||
database.exec("BEGIN IMMEDIATE");
|
||||
try {
|
||||
await operation(connection());
|
||||
database.exec("COMMIT");
|
||||
} catch (error) {
|
||||
database.exec("ROLLBACK");
|
||||
throw error;
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
async open() {
|
||||
return connection();
|
||||
},
|
||||
};
|
||||
}
|
||||
import { createSqliteReplicaRowStore } from "./row-store-sqlite";
|
||||
import { createNodeSqliteDriver } from "./row-store-sqlite.test-driver";
|
||||
|
||||
runReplicaRowStoreContract("SQLite", async () => {
|
||||
const driver = createNodeSqliteDriver();
|
||||
|
||||
@@ -9,11 +9,12 @@ import {
|
||||
} from "./row-store-sqlite";
|
||||
|
||||
export type {
|
||||
ReplicaHostRows,
|
||||
ReplicaHostIndex,
|
||||
ReplicaRow,
|
||||
ReplicaRowChanges,
|
||||
ReplicaRowKey,
|
||||
ReplicaRowKind,
|
||||
ReplicaRowSize,
|
||||
ReplicaRowStore,
|
||||
} from "./row-store";
|
||||
export { REPLICA_ROW_STORE_SCHEMA_VERSION, REPLICA_SINGLETON_ROW_ID } from "./row-store-schema";
|
||||
|
||||
@@ -23,9 +23,15 @@ export interface ReplicaRowApplyOptions {
|
||||
directoryBaselines?: ReadonlySet<string>;
|
||||
}
|
||||
|
||||
export interface ReplicaHostRows {
|
||||
// What a stored row costs without its payload: the cache budgets on this and never holds payloads.
|
||||
export interface ReplicaRowSize extends ReplicaRowKey {
|
||||
// UTF-8 byte length of the payload.
|
||||
bytes: number;
|
||||
}
|
||||
|
||||
export interface ReplicaHostIndex {
|
||||
serverId: string;
|
||||
rows: ReplicaRow[];
|
||||
rows: ReplicaRowSize[];
|
||||
}
|
||||
|
||||
export interface ReplicaRowStore {
|
||||
@@ -35,7 +41,8 @@ export interface ReplicaRowStore {
|
||||
kinds: readonly ReplicaRowKind[],
|
||||
ids?: readonly string[],
|
||||
): Promise<ReplicaRow[]>;
|
||||
readAll(): Promise<ReplicaHostRows[]>;
|
||||
// Every stored row's key and payload size, grouped by host, read without loading payloads.
|
||||
readIndex(): Promise<ReplicaHostIndex[]>;
|
||||
// Shared stores can reject directory deltas that no longer match their baseline.
|
||||
// Return the accepted changes when they differ from the requested changes.
|
||||
apply(
|
||||
|
||||
@@ -49,3 +49,29 @@ it("uses exact IndexedDB keys for targeted rows instead of scanning the host", a
|
||||
get.mockRestore();
|
||||
getAll.mockRestore();
|
||||
});
|
||||
|
||||
it("drops rows stored before payload sizes were indexed, so none escape the budget", async () => {
|
||||
const databaseName = `replica-row-store-unsized-${databaseSequence++}`;
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
// The store's first on-disk shape: rows without a recorded payload size.
|
||||
const request = fakeIndexedDb.open(databaseName, 1);
|
||||
request.addEventListener("upgradeneeded", () => {
|
||||
const rows = request.result.createObjectStore("rows", {
|
||||
keyPath: ["serverId", "kind", "id"],
|
||||
});
|
||||
request.result.createObjectStore("meta").put(1, "schema_version");
|
||||
rows.put({ serverId: "server-a", kind: "timeline", id: "agent-1", payload: "unsized" });
|
||||
});
|
||||
request.addEventListener("success", () => {
|
||||
request.result.close();
|
||||
resolve();
|
||||
});
|
||||
request.addEventListener("error", () => reject(request.error));
|
||||
});
|
||||
|
||||
const store = createIndexedDbReplicaRowStore({ databaseName, schemaVersion: 1 });
|
||||
await store.open();
|
||||
|
||||
expect(await store.readIndex()).toEqual([]);
|
||||
expect(await store.read("server-a", ["timeline"])).toEqual([]);
|
||||
});
|
||||
|
||||
@@ -1,38 +1,62 @@
|
||||
import { replicaPayloadBytes } from "./payload-bytes";
|
||||
import type {
|
||||
ReplicaHostRows,
|
||||
ReplicaHostIndex,
|
||||
ReplicaRow,
|
||||
ReplicaRowApplyOptions,
|
||||
ReplicaRowChanges,
|
||||
ReplicaRowKind,
|
||||
ReplicaRowSize,
|
||||
ReplicaRowStore,
|
||||
} from "./row-store";
|
||||
import { REPLICA_ROW_STORE_SCHEMA_VERSION, REPLICA_SINGLETON_ROW_ID } from "./row-store-schema";
|
||||
|
||||
export type {
|
||||
ReplicaHostRows,
|
||||
ReplicaHostIndex,
|
||||
ReplicaRow,
|
||||
ReplicaRowChanges,
|
||||
ReplicaRowKey,
|
||||
ReplicaRowKind,
|
||||
ReplicaRowSize,
|
||||
ReplicaRowStore,
|
||||
} from "./row-store";
|
||||
export { REPLICA_ROW_STORE_SCHEMA_VERSION, REPLICA_SINGLETON_ROW_ID } from "./row-store-schema";
|
||||
|
||||
const DATABASE_NAME = "paseo-replica-row-store";
|
||||
const DATABASE_VERSION = 1;
|
||||
const DATABASE_VERSION = 2;
|
||||
const ROWS_STORE = "rows";
|
||||
const PAYLOAD_BYTES_INDEX = "payloadBytes";
|
||||
const META_STORE = "meta";
|
||||
const SCHEMA_VERSION_KEY = "schema_version";
|
||||
const DIRECTORY_KINDS = ["agent", "checkpoint", "project", "workspace"] as const;
|
||||
|
||||
interface IndexedDbReplicaRow extends ReplicaRow {
|
||||
// Indexed, so the size index can be read with a key cursor that never loads payloads.
|
||||
payloadBytes: number;
|
||||
directoryRevision?: string;
|
||||
}
|
||||
|
||||
function withoutDirectoryRevision(row: IndexedDbReplicaRow): ReplicaRow {
|
||||
if (row.directoryRevision === undefined) return row;
|
||||
function toStoredRow(row: ReplicaRow, directoryRevision: string | undefined): IndexedDbReplicaRow {
|
||||
return {
|
||||
serverId: row.serverId,
|
||||
kind: row.kind,
|
||||
id: row.id,
|
||||
payload: row.payload,
|
||||
payloadBytes: replicaPayloadBytes(row.payload),
|
||||
...(directoryRevision ? { directoryRevision } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
function toReplicaRow(row: IndexedDbReplicaRow): ReplicaRow {
|
||||
return { serverId: row.serverId, kind: row.kind, id: row.id, payload: row.payload };
|
||||
}
|
||||
|
||||
function compareRowKeys(left: ReplicaRowSize, right: ReplicaRowSize): number {
|
||||
if (left.serverId !== right.serverId) return left.serverId < right.serverId ? -1 : 1;
|
||||
if (left.kind !== right.kind) return left.kind < right.kind ? -1 : 1;
|
||||
if (left.id !== right.id) return left.id < right.id ? -1 : 1;
|
||||
return 0;
|
||||
}
|
||||
|
||||
interface IndexedDbReplicaRowStoreOptions {
|
||||
databaseName: string;
|
||||
schemaVersion: number;
|
||||
@@ -84,8 +108,14 @@ async function openDatabase(databaseName: string): Promise<IDBDatabase> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const request = indexedDB.open(databaseName, DATABASE_VERSION);
|
||||
request.addEventListener("upgradeneeded", () => {
|
||||
if (!request.result.objectStoreNames.contains(ROWS_STORE)) {
|
||||
request.result.createObjectStore(ROWS_STORE, { keyPath: ["serverId", "kind", "id"] });
|
||||
const rows = request.result.objectStoreNames.contains(ROWS_STORE)
|
||||
? request.transaction!.objectStore(ROWS_STORE)
|
||||
: request.result.createObjectStore(ROWS_STORE, { keyPath: ["serverId", "kind", "id"] });
|
||||
if (!rows.indexNames.contains(PAYLOAD_BYTES_INDEX)) {
|
||||
// Rows stored before sizes were recorded would be missing from the index. The cache
|
||||
// refills from the daemon.
|
||||
rows.clear();
|
||||
rows.createIndex(PAYLOAD_BYTES_INDEX, "payloadBytes");
|
||||
}
|
||||
if (!request.result.objectStoreNames.contains(META_STORE)) {
|
||||
request.result.createObjectStore(META_STORE);
|
||||
@@ -144,17 +174,34 @@ export function createIndexedDbReplicaRowStore(
|
||||
}
|
||||
}
|
||||
|
||||
async function readAll(): Promise<ReplicaHostRows[]> {
|
||||
async function readIndex(): Promise<ReplicaHostIndex[]> {
|
||||
const transaction = getDatabase().transaction(ROWS_STORE, "readonly");
|
||||
const completion = transactionComplete(transaction);
|
||||
const rows = await requestResult<IndexedDbReplicaRow[]>(
|
||||
transaction.objectStore(ROWS_STORE).getAll(),
|
||||
);
|
||||
const rows: ReplicaRowSize[] = [];
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
const request = transaction
|
||||
.objectStore(ROWS_STORE)
|
||||
.index(PAYLOAD_BYTES_INDEX)
|
||||
.openKeyCursor();
|
||||
request.addEventListener("success", () => {
|
||||
const cursor = request.result;
|
||||
if (!cursor) {
|
||||
resolve();
|
||||
return;
|
||||
}
|
||||
const [serverId, kind, id] = cursor.primaryKey as [string, ReplicaRowKind, string];
|
||||
rows.push({ serverId, kind, id, bytes: cursor.key as number });
|
||||
cursor.continue();
|
||||
});
|
||||
request.addEventListener("error", () =>
|
||||
reject(request.error ?? new Error("Replica row store index read failed")),
|
||||
);
|
||||
});
|
||||
await completion;
|
||||
const hosts = new Map<string, ReplicaRow[]>();
|
||||
for (const row of rows) {
|
||||
const hosts = new Map<string, ReplicaRowSize[]>();
|
||||
for (const row of rows.sort(compareRowKeys)) {
|
||||
const hostRows = hosts.get(row.serverId) ?? [];
|
||||
hostRows.push(withoutDirectoryRevision(row));
|
||||
hostRows.push(row);
|
||||
hosts.set(row.serverId, hostRows);
|
||||
}
|
||||
return Array.from(hosts, ([serverId, hostRows]) => ({ serverId, rows: hostRows }));
|
||||
@@ -192,7 +239,7 @@ export function createIndexedDbReplicaRowStore(
|
||||
observeDirectoryRevision(serverId, checkpoint?.directoryRevision);
|
||||
}
|
||||
return rows
|
||||
.map(withoutDirectoryRevision)
|
||||
.map(toReplicaRow)
|
||||
.sort((left, right) =>
|
||||
left.kind === right.kind
|
||||
? left.id.localeCompare(right.id)
|
||||
@@ -222,7 +269,7 @@ export function createIndexedDbReplicaRowStore(
|
||||
for (const row of accepted.upserts) {
|
||||
const directoryRevision =
|
||||
row.kind === "checkpoint" ? nextRevisions.get(row.serverId) : undefined;
|
||||
await requestResult(rows.put(directoryRevision ? { ...row, directoryRevision } : row));
|
||||
await requestResult(rows.put(toStoredRow(row, directoryRevision)));
|
||||
}
|
||||
});
|
||||
for (const [serverId, revision] of nextRevisions) observeDirectoryRevision(serverId, revision);
|
||||
@@ -308,7 +355,7 @@ export function createIndexedDbReplicaRowStore(
|
||||
await runTransaction(getDatabase(), ROWS_STORE, async (transaction) => {
|
||||
const rows = transaction.objectStore(ROWS_STORE);
|
||||
const range = IDBKeyRange.bound([oldServerId], [oldServerId, []]);
|
||||
const oldRows = await requestResult<ReplicaRow[]>(rows.getAll(range));
|
||||
const oldRows = await requestResult<IndexedDbReplicaRow[]>(rows.getAll(range));
|
||||
for (const row of oldRows) {
|
||||
await requestResult(rows.put({ ...row, serverId: newServerId }));
|
||||
await requestResult(rows.delete([row.serverId, row.kind, row.id]));
|
||||
@@ -327,7 +374,7 @@ export function createIndexedDbReplicaRowStore(
|
||||
});
|
||||
}
|
||||
|
||||
return { open, read, readAll, apply, deleteHost, renameHost, clear };
|
||||
return { open, read, readIndex, apply, deleteHost, renameHost, clear };
|
||||
}
|
||||
|
||||
export function createReplicaRowStore(): ReplicaRowStore {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
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,
|
||||
@@ -28,6 +29,8 @@ 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,
|
||||
@@ -37,12 +40,31 @@ function makeRuntime(input: {
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
scheduleList: async () => ({ requestId: "test-request", schedules, error: null }),
|
||||
scheduleList: async () => {
|
||||
await input.beforeResponse?.();
|
||||
return { requestId: "test-request", schedules, error: input.errors?.[serverId] ?? 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({
|
||||
@@ -80,10 +102,10 @@ describe("fetchAggregatedSchedules load state", () => {
|
||||
}),
|
||||
});
|
||||
|
||||
expect(result).toEqual({ status: "loaded", data: [], hostErrors: [] });
|
||||
expect(result).toEqual({ status: "loaded", data: [], hostWarnings: [] });
|
||||
});
|
||||
|
||||
it("does not report loaded empty while another known host is still connecting", async () => {
|
||||
it("shows the empty result with a warning while another host is connecting", async () => {
|
||||
const result = await fetchAggregatedSchedules({
|
||||
hosts: [
|
||||
{ serverId: "host-a", serverName: "Host A" },
|
||||
@@ -100,7 +122,62 @@ describe("fetchAggregatedSchedules load state", () => {
|
||||
}),
|
||||
});
|
||||
|
||||
expect(result).toEqual({ status: "connecting" });
|
||||
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);
|
||||
});
|
||||
|
||||
it("loads reachable host data when another known host is still connecting", async () => {
|
||||
@@ -124,7 +201,13 @@ describe("fetchAggregatedSchedules load state", () => {
|
||||
expect(result).toEqual({
|
||||
status: "loaded",
|
||||
data: [{ ...schedule, serverId: "host-a", serverName: "Host A" }],
|
||||
hostErrors: [],
|
||||
hostWarnings: [
|
||||
{
|
||||
serverId: "host-b",
|
||||
serverName: "Host B",
|
||||
reason: "connecting",
|
||||
},
|
||||
],
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
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;
|
||||
|
||||
@@ -27,10 +26,8 @@ export interface AggregatedSchedule extends ScheduleSummary {
|
||||
serverName: string;
|
||||
}
|
||||
|
||||
export interface ScheduleHostError {
|
||||
serverId: string;
|
||||
serverName: string;
|
||||
message: string;
|
||||
export interface ScheduleHostWarning extends ScheduleHostInput {
|
||||
reason: "connecting" | "request-failed";
|
||||
}
|
||||
|
||||
export interface FetchAggregatedSchedulesConnectingResult {
|
||||
@@ -40,7 +37,7 @@ export interface FetchAggregatedSchedulesConnectingResult {
|
||||
export interface FetchAggregatedSchedulesResult {
|
||||
status: "loaded";
|
||||
data: AggregatedSchedule[];
|
||||
hostErrors: ScheduleHostError[];
|
||||
hostWarnings: ScheduleHostWarning[];
|
||||
}
|
||||
|
||||
export type FetchAggregatedSchedulesState =
|
||||
@@ -62,9 +59,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. 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.
|
||||
* 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.
|
||||
*/
|
||||
export async function fetchAggregatedSchedules(
|
||||
input: FetchAggregatedSchedulesInput,
|
||||
@@ -82,8 +79,9 @@ export async function fetchAggregatedSchedules(
|
||||
}
|
||||
|
||||
const schedules: AggregatedSchedule[] = [];
|
||||
const hostErrors: ScheduleHostError[] = [];
|
||||
const hostWarnings: ScheduleHostWarning[] = [];
|
||||
let connectedAttempts = 0;
|
||||
let failedAttempts = 0;
|
||||
|
||||
await Promise.all(
|
||||
input.hosts.map(async (host) => {
|
||||
@@ -91,6 +89,9 @@ 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;
|
||||
@@ -102,25 +103,18 @@ export async function fetchAggregatedSchedules(
|
||||
for (const schedule of payload.schedules) {
|
||||
schedules.push({ ...schedule, serverId: host.serverId, serverName: host.serverName });
|
||||
}
|
||||
} catch (error) {
|
||||
hostErrors.push({
|
||||
serverId: host.serverId,
|
||||
serverName: host.serverName,
|
||||
message: toErrorMessage(error),
|
||||
});
|
||||
} catch {
|
||||
failedAttempts += 1;
|
||||
hostWarnings.push({ ...host, reason: "request-failed" });
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
if (connectedAttempts > 0 && schedules.length === 0 && hostErrors.length === connectedAttempts) {
|
||||
if (connectedAttempts > 0 && failedAttempts === connectedAttempts) {
|
||||
throw new Error(ALL_SCHEDULE_HOSTS_FAILED_MESSAGE);
|
||||
}
|
||||
|
||||
if (schedules.length === 0 && hasSettlingHost) {
|
||||
return { status: "connecting" };
|
||||
}
|
||||
|
||||
return { status: "loaded", data: schedules, hostErrors };
|
||||
return { status: "loaded", data: schedules, hostWarnings };
|
||||
}
|
||||
|
||||
function isScheduleHostConnectionSettling(
|
||||
|
||||
@@ -25,7 +25,7 @@ import {
|
||||
useSchedules,
|
||||
type AggregateLoadState,
|
||||
type AggregatedSchedule,
|
||||
type ScheduleHostError,
|
||||
type ScheduleHostWarning,
|
||||
} 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, hostErrors, isError, refetch } = useSchedules();
|
||||
const { loadState, hostWarnings, 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}
|
||||
hostErrors={hostErrors}
|
||||
hostWarnings={hostWarnings}
|
||||
showLoadError={showLoadError}
|
||||
statusFilter={statusFilter}
|
||||
onStatusFilterChange={setStatusFilter}
|
||||
@@ -195,7 +195,7 @@ function SchedulesScreenContent(): ReactElement {
|
||||
function SchedulesScreenBody({
|
||||
rows,
|
||||
loadState,
|
||||
hostErrors,
|
||||
hostWarnings,
|
||||
showLoadError,
|
||||
statusFilter,
|
||||
onStatusFilterChange,
|
||||
@@ -209,7 +209,7 @@ function SchedulesScreenBody({
|
||||
}: {
|
||||
rows: ScheduleRowView[];
|
||||
loadState: AggregateLoadState<AggregatedSchedule>;
|
||||
hostErrors: ScheduleHostError[];
|
||||
hostWarnings: ScheduleHostWarning[];
|
||||
showLoadError: boolean;
|
||||
statusFilter: ScheduleBucket;
|
||||
onStatusFilterChange: (value: ScheduleBucket) => void;
|
||||
@@ -245,7 +245,7 @@ function SchedulesScreenBody({
|
||||
if (bodyState.kind === "empty") {
|
||||
return (
|
||||
<View style={styles.centered}>
|
||||
{hostErrors.length > 0 ? <ScheduleHostErrorsBanner errors={hostErrors} /> : null}
|
||||
{hostWarnings.length > 0 ? <ScheduleHostWarningsBanner warnings={hostWarnings} /> : null}
|
||||
<SchedulesEmptyState onCreate={onCreate} testID="schedules-empty" />
|
||||
</View>
|
||||
);
|
||||
@@ -294,7 +294,7 @@ function SchedulesScreenBody({
|
||||
keyboardShouldPersistTaps="handled"
|
||||
testID="schedules-list"
|
||||
>
|
||||
{hostErrors.length > 0 ? <ScheduleHostErrorsBanner errors={hostErrors} /> : null}
|
||||
{hostWarnings.length > 0 ? <ScheduleHostWarningsBanner warnings={hostWarnings} /> : null}
|
||||
{schedulesContent}
|
||||
</ScrollView>
|
||||
</View>
|
||||
@@ -334,13 +334,17 @@ function SchedulesEndedEmptyState(): ReactElement {
|
||||
);
|
||||
}
|
||||
|
||||
function ScheduleHostErrorsBanner({ errors }: { errors: ScheduleHostError[] }): ReactElement {
|
||||
function ScheduleHostWarningsBanner({
|
||||
warnings,
|
||||
}: {
|
||||
warnings: ScheduleHostWarning[];
|
||||
}): ReactElement {
|
||||
return (
|
||||
<View style={styles.errorsBannerWrap}>
|
||||
<View style={styles.errorsBanner} testID="schedules-host-errors">
|
||||
{errors.map((error) => (
|
||||
<Text key={error.serverId} style={styles.errorsBannerText}>
|
||||
{`${error.serverName}: Could not load schedules`}
|
||||
{warnings.map((warning) => (
|
||||
<Text key={warning.serverId} style={styles.errorsBannerText}>
|
||||
{`${warning.serverName}: ${warning.reason === "connecting" ? "Still connecting" : "Could not load schedules"}`}
|
||||
</Text>
|
||||
))}
|
||||
</View>
|
||||
|
||||
@@ -20,6 +20,7 @@ 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 {
|
||||
@@ -32,7 +33,9 @@ interface StartupSplashScreenProps {
|
||||
const GITHUB_ISSUE_URL = "https://github.com/getpaseo/paseo/issues/new";
|
||||
const DOCS_URL = "https://paseo.sh/docs";
|
||||
|
||||
const LOGO_SIZE = 96;
|
||||
// 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 SHIMMER_PEAK_WIDTH = 120;
|
||||
const SHIMMER_DURATION_MS = 1800;
|
||||
|
||||
@@ -273,6 +276,10 @@ 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,
|
||||
@@ -304,6 +311,7 @@ export function StartupSplashScreen({ bootstrapState }: StartupSplashScreenProps
|
||||
const [isLoadingLogs, setIsLoadingLogs] = useState(false);
|
||||
|
||||
const isError = bootstrapState !== undefined && bootstrapState.splashError !== null;
|
||||
useNativeSplashHold(!isError);
|
||||
|
||||
useEffect(() => {
|
||||
if (!isError) {
|
||||
@@ -385,7 +393,9 @@ export function StartupSplashScreen({ bootstrapState }: StartupSplashScreenProps
|
||||
return (
|
||||
<View testID="startup-splash" style={styles.container}>
|
||||
<TitlebarDragRegion />
|
||||
<LogoShimmer />
|
||||
<View style={styles.logo}>
|
||||
<LogoShimmer />
|
||||
</View>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -4,9 +4,14 @@ 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 type { WorkspaceRouteState } from "@/screens/workspace/workspace-route-state";
|
||||
import { useNativeSplashHold } from "@/native-splash";
|
||||
import type {
|
||||
WorkspaceLoadingSource,
|
||||
WorkspaceRouteState,
|
||||
} from "@/screens/workspace/workspace-route-state";
|
||||
import type { Theme } from "@/styles/theme";
|
||||
|
||||
const ThemedLoadingSpinner = withUnistyles(LoadingSpinner);
|
||||
@@ -28,7 +33,9 @@ export function renderWorkspaceRouteGate(input: {
|
||||
}): React.ReactNode {
|
||||
switch (input.state.kind) {
|
||||
case "loading":
|
||||
return <WorkspaceConnecting hostName={input.state.hostName} />;
|
||||
return (
|
||||
<WorkspaceLoading waitingFor={input.state.waitingFor} hostName={input.state.hostName} />
|
||||
);
|
||||
case "missing":
|
||||
return (
|
||||
<WorkspaceEmptyState
|
||||
@@ -86,26 +93,35 @@ 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 });
|
||||
}
|
||||
|
||||
function WorkspaceConnecting({ hostName }: { hostName: string }) {
|
||||
/**
|
||||
* 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;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
|
||||
useNativeSplashHold(waitingFor === "cache");
|
||||
if (waitingFor === "cache") return <LoadingState testID="workspace-loading" />;
|
||||
return (
|
||||
<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>
|
||||
<LoadingState
|
||||
testID="workspace-loading"
|
||||
title={
|
||||
waitingFor === "connection" ? t("workspace.route.connecting") : t("workspace.route.loading")
|
||||
}
|
||||
description={hostName}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -213,21 +229,14 @@ 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}>
|
||||
{state.connectionStatus === "connecting" || state.connectionStatus === "idle"
|
||||
? state.hostName
|
||||
: t("workspace.route.hostStatus", {
|
||||
status: formatConnectionStatus(state.connectionStatus),
|
||||
})}
|
||||
{t("workspace.route.hostStatus", {
|
||||
status: formatConnectionStatus(state.connectionStatus),
|
||||
})}
|
||||
</Text>
|
||||
{state.lastError ? (
|
||||
<Tooltip delayDuration={0} enabledOnDesktop enabledOnMobile={false}>
|
||||
@@ -242,16 +251,14 @@ function WorkspaceUnreachable({
|
||||
</Tooltip>
|
||||
) : null}
|
||||
</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 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>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -31,8 +31,9 @@ function createWorkspaceDescriptor(): WorkspaceDescriptor {
|
||||
|
||||
function resolve(input: {
|
||||
workspace?: WorkspaceDescriptor | null;
|
||||
connectionStatus?: "online" | "offline";
|
||||
connectionStatus?: "online" | "offline" | "connecting" | "idle";
|
||||
hasHydratedWorkspaces?: boolean;
|
||||
hasRestoredCachedDirectory?: boolean;
|
||||
recovery?: WorkspaceRecoveryModel;
|
||||
}) {
|
||||
return resolveWorkspaceRouteState({
|
||||
@@ -41,6 +42,7 @@ 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" },
|
||||
});
|
||||
}
|
||||
@@ -68,6 +70,32 @@ 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" }),
|
||||
@@ -79,14 +107,16 @@ describe("resolveWorkspaceRouteState", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("waits for workspace hydration and authoritative recovery inspection", () => {
|
||||
it("waits on the host 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",
|
||||
});
|
||||
});
|
||||
|
||||
@@ -412,7 +442,7 @@ describe("post-restore handoff state machine", () => {
|
||||
lastError: "closed",
|
||||
},
|
||||
{ kind: "unreachable", hostName: "Laptop", connectionStatus: "offline", lastError: "closed" },
|
||||
{ kind: "loading", hostName: "Laptop" },
|
||||
{ kind: "loading", hostName: "Laptop", waitingFor: "workspace" },
|
||||
{ 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: Exclude<HostRuntimeConnectionStatus, "online">;
|
||||
connectionStatus: Extract<HostRuntimeConnectionStatus, "offline" | "error">;
|
||||
lastError: string | null;
|
||||
}
|
||||
| { kind: "loading"; hostName: string }
|
||||
| { kind: "loading"; hostName: string; waitingFor: WorkspaceLoadingSource }
|
||||
| { kind: "missing"; hostName: string }
|
||||
| { kind: "needsHostUpgrade"; hostName: string }
|
||||
| {
|
||||
@@ -27,12 +27,20 @@ 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) {
|
||||
@@ -51,6 +59,15 @@ 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",
|
||||
@@ -61,7 +78,7 @@ export function resolveWorkspaceRouteState(input: {
|
||||
}
|
||||
|
||||
if (!input.hasHydratedWorkspaces) {
|
||||
return { kind: "loading", hostName: input.hostName };
|
||||
return { kind: "loading", hostName: input.hostName, waitingFor: "workspace" };
|
||||
}
|
||||
if (input.recovery.kind === "idle") {
|
||||
return { kind: "missing", hostName: input.hostName };
|
||||
@@ -69,7 +86,7 @@ export function resolveWorkspaceRouteState(input: {
|
||||
|
||||
switch (input.recovery.kind) {
|
||||
case "checking":
|
||||
return { kind: "loading", hostName: input.hostName };
|
||||
return { kind: "loading", hostName: input.hostName, waitingFor: "workspace" };
|
||||
case "needsHostUpgrade":
|
||||
return { kind: "needsHostUpgrade", hostName: input.hostName };
|
||||
case "recoverable":
|
||||
|
||||
@@ -22,7 +22,6 @@ 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";
|
||||
@@ -45,8 +44,7 @@ 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, withUnistyles } from "react-native-unistyles";
|
||||
import type { Theme } from "@/styles/theme";
|
||||
import { StyleSheet } from "react-native-unistyles";
|
||||
import invariant from "tiny-invariant";
|
||||
import { SidebarMenuToggle } from "@/components/headers/sidebar-menu-toggle";
|
||||
import { ScreenHeader } from "@/components/headers/screen-header";
|
||||
@@ -172,7 +170,10 @@ import {
|
||||
canSyncVisibleAgents,
|
||||
usePostRestoreWorkspaceRouteState,
|
||||
} from "@/screens/workspace/use-post-restore-handoff";
|
||||
import { renderWorkspaceRouteGate } from "@/screens/workspace/workspace-route-state-views";
|
||||
import {
|
||||
renderWorkspaceRouteGate,
|
||||
WorkspaceLoading,
|
||||
} from "@/screens/workspace/workspace-route-state-views";
|
||||
import { useWorkspaceRecovery } from "@/workspace-recovery/use-workspace-recovery";
|
||||
import type { WorkspaceRecoveryModel } from "@/workspace-recovery/model";
|
||||
import {
|
||||
@@ -275,10 +276,6 @@ 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;
|
||||
@@ -556,6 +553,8 @@ function parsePaneDirection(actionId: string): PaneDirection | null {
|
||||
interface RenderWorkspaceContentInput {
|
||||
isMissingWorkspaceDirectory: boolean;
|
||||
activeTabDescriptor: WorkspaceTabDescriptor | null;
|
||||
hostName: string;
|
||||
hasHydratedWorkspaceLayoutStore: boolean;
|
||||
hasHydratedAgents: boolean;
|
||||
hasLoadedTerminals: boolean;
|
||||
mountedFocusedPaneTabIds: string[];
|
||||
@@ -574,6 +573,8 @@ function renderWorkspaceContent(input: RenderWorkspaceContentInput): React.React
|
||||
const {
|
||||
isMissingWorkspaceDirectory,
|
||||
activeTabDescriptor,
|
||||
hostName,
|
||||
hasHydratedWorkspaceLayoutStore,
|
||||
hasHydratedAgents,
|
||||
hasLoadedTerminals,
|
||||
mountedFocusedPaneTabIds,
|
||||
@@ -594,12 +595,13 @@ 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 (
|
||||
<View style={styles.emptyState}>
|
||||
<ThemedLoadingSpinner uniProps={mutedColorMapping} />
|
||||
</View>
|
||||
);
|
||||
return <WorkspaceLoading waitingFor="workspace" hostName={hostName} />;
|
||||
}
|
||||
if (!activeTabDescriptor) {
|
||||
return (
|
||||
@@ -726,35 +728,44 @@ 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 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]);
|
||||
const hasRestoredCachedDirectory = useSessionStore(
|
||||
(state) => state.sessions[input.serverId]?.hasRestoredCachedDirectory ?? false,
|
||||
);
|
||||
return useMemo(
|
||||
() =>
|
||||
resolveWorkspaceRouteState({
|
||||
hostName,
|
||||
hostName: input.hostName,
|
||||
connectionStatus: hostSnapshot?.connectionStatus ?? "connecting",
|
||||
lastError: hostSnapshot?.lastError ?? null,
|
||||
workspace: input.workspace,
|
||||
hasHydratedWorkspaces: input.hasHydratedWorkspaces,
|
||||
hasRestoredCachedDirectory,
|
||||
recovery: input.recovery,
|
||||
}),
|
||||
[
|
||||
hostName,
|
||||
input.hostName,
|
||||
hostSnapshot?.connectionStatus,
|
||||
hostSnapshot?.lastError,
|
||||
input.workspace,
|
||||
input.hasHydratedWorkspaces,
|
||||
hasRestoredCachedDirectory,
|
||||
input.recovery,
|
||||
],
|
||||
);
|
||||
@@ -1262,8 +1273,10 @@ function WorkspaceScreenContent({
|
||||
serverId: normalizedServerId,
|
||||
workspaceId: normalizedWorkspaceId,
|
||||
});
|
||||
const hostName = useWorkspaceHostName(normalizedServerId);
|
||||
const workspaceRouteState = useResolvedWorkspaceRouteState({
|
||||
serverId: normalizedServerId,
|
||||
hostName,
|
||||
workspace: workspaceDescriptor,
|
||||
hasHydratedWorkspaces,
|
||||
recovery: workspaceRecovery.state,
|
||||
@@ -3144,6 +3157,8 @@ function WorkspaceScreenContent({
|
||||
const content = renderWorkspaceContent({
|
||||
isMissingWorkspaceDirectory,
|
||||
activeTabDescriptor,
|
||||
hostName,
|
||||
hasHydratedWorkspaceLayoutStore,
|
||||
hasHydratedAgents,
|
||||
hasLoadedTerminals: terminalsQuery.isSuccess,
|
||||
mountedFocusedPaneTabIds,
|
||||
|
||||
@@ -5,6 +5,7 @@ import type { WorkspaceDescriptorPayload } from "@getpaseo/protocol/messages";
|
||||
|
||||
import {
|
||||
normalizeWorkspaceDescriptor,
|
||||
selectAgentLoadingWait,
|
||||
selectAgentSentMessages,
|
||||
selectAgentTurnPresentation,
|
||||
selectAgentTimelineState,
|
||||
@@ -314,6 +315,44 @@ 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";
|
||||
|
||||
@@ -338,6 +338,37 @@ 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,
|
||||
@@ -484,6 +515,8 @@ 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;
|
||||
@@ -505,6 +538,7 @@ 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>;
|
||||
@@ -723,6 +757,8 @@ 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;
|
||||
@@ -747,6 +783,7 @@ function createInitialSessionState(
|
||||
hasHydratedAgents: false,
|
||||
hasHydratedWorkspaces: false,
|
||||
hasWorkspaceDirectorySnapshot: false,
|
||||
hasRestoredCachedDirectory: false,
|
||||
isPlayingAudio: false,
|
||||
focusedAgentId: null,
|
||||
focusedTerminalId: null,
|
||||
@@ -762,6 +799,7 @@ function createInitialSessionState(
|
||||
historySyncGeneration: 0,
|
||||
agentHistorySyncGeneration: new Map(),
|
||||
agentAuthoritativeHistoryApplied: new Map(),
|
||||
agentCachedTimelineRestored: new Map(),
|
||||
initializingAgents: new Map(),
|
||||
agents: new Map(),
|
||||
workspaceAgentActivity: new Map(),
|
||||
@@ -1363,6 +1401,7 @@ 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) {
|
||||
@@ -2026,6 +2065,36 @@ 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();
|
||||
|
||||
@@ -762,6 +762,29 @@ describe("terminal emulator runtime in a real browser", () => {
|
||||
expect(mounted.inputs).toEqual([]);
|
||||
});
|
||||
|
||||
// The daemon owns DEC 2031: it sends one ESC[?997;Nn per palette switch. A browser
|
||||
// report on top of that delivers the switch twice.
|
||||
it("does not emit a PTY input report when the theme changes under DEC 2031", async () => {
|
||||
await page.viewport(900, 600);
|
||||
const mounted = createTerminalHost({ width: 720, height: 360 });
|
||||
|
||||
await waitFor({ predicate: () => mounted.sizes.length > 0 });
|
||||
|
||||
const writeCommitted = (bytes: string) =>
|
||||
new Promise<void>((resolve) =>
|
||||
mounted.runtime.write({ data: terminalOutput(bytes), onCommitted: resolve }),
|
||||
);
|
||||
|
||||
mounted.runtime.setTheme({ theme: { background: "#ffffff", foreground: "#1a1a1e" } });
|
||||
await writeCommitted("\x1b[?2031h");
|
||||
mounted.runtime.setTheme({ theme: { background: "#181b1a", foreground: "#fafafa" } });
|
||||
mounted.runtime.setTheme({ theme: { background: "#ffffff", foreground: "#1a1a1e" } });
|
||||
await writeCommitted("\x1b]11;#000000\x07");
|
||||
await nextFrame();
|
||||
|
||||
expect(mounted.inputs).toEqual([]);
|
||||
});
|
||||
|
||||
it("replays snapshots without synchronously resetting the visible terminal", async () => {
|
||||
await page.viewport(900, 600);
|
||||
const mounted = createTerminalHost({ width: 720, height: 360 });
|
||||
|
||||
@@ -577,6 +577,10 @@ export class TerminalEmulatorRuntime {
|
||||
},
|
||||
scrollback: input.scrollback,
|
||||
theme: withOverviewRulerBorderHidden(input.theme),
|
||||
// The daemon owns DEC 2031 and DSR 996: it tracks the mode and reports each
|
||||
// palette switch once. xterm would otherwise send its own unsolicited
|
||||
// ESC[?997;Nn on every theme change, which no query suppression can catch.
|
||||
vtExtensions: { colorSchemeQuery: false },
|
||||
});
|
||||
const fitAddon = new FitAddon();
|
||||
let webglAddon: WebglAddon | null = null;
|
||||
|
||||
@@ -18,6 +18,7 @@ import { WorkspaceDirectoryReplica } from "@/runtime/directory-sync/workspace-re
|
||||
import type { CachedTimeline } from "@/runtime/replica-cache";
|
||||
import {
|
||||
normalizeWorkspaceDescriptor,
|
||||
hasRestoredCachedTimeline,
|
||||
selectAgentTimelineState,
|
||||
selectAgentTimelineTurnPresentation,
|
||||
selectAgentTurnPresentation,
|
||||
@@ -338,6 +339,67 @@ 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,4 +1,4 @@
|
||||
// Bundles @getpaseo/cli into a thin ESM entrypoint plus lazy code-split command chunks.
|
||||
// Bundles @getpaseo/cli into thin ESM entrypoints 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,6 +29,8 @@ 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,
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user