Compare commits

..
Author SHA1 Message Date
monarchmaisuriya 9f80c5e1a0 fix(claude): settle the first tool call after a compaction
Claude Code now sends the compaction summary as a user message marked
isSynthetic. The synthetic check returned before the one-shot compacting
flag was cleared, so the flag stayed set and swallowed the next user
message: the first tool result after the compaction. That call stayed
running and was later shown as Canceled when the idle runtime was
collected.

Skip the summary by what it is (synthetic, or isCompactSummary in older
streams) instead of by position, and drop the compacting flag, which
nothing else reads.

Co-authored-by: monarchmaisuriya <monarchmaisuriya7600@gmail.com>
2026-11-29 08:16:26 +00:00
71 changed files with 459 additions and 1777 deletions
+1 -6
View File
@@ -601,12 +601,7 @@ 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 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
before a requested cache row can paint. The row store is not encrypted. A cached timeline can contain
source code, prompts, and tool output; encrypted-at-rest storage is a separate security decision.
### Saved hosts
+1 -1
View File
@@ -1 +1 @@
sha256-34bUBmRmjekbUSp93597GLTmSWKt23TCHaK3ViXG+iU=
sha256-aal9eR571blWuL7CZt1LR+KfA4QPJ0ivVl/GSTWy93o=
@@ -1,13 +0,0 @@
import {
expectBuiltinPluginSettings,
openBuiltinPluginSettings,
test,
} from "../support/helpers/builtin-plugin-settings";
test("a built-in plugin's settings link opens its screen", async ({
page,
builtinSettingsHost,
}) => {
await openBuiltinPluginSettings(page, builtinSettingsHost);
await expectBuiltinPluginSettings(page);
});
@@ -28,9 +28,7 @@ import {
} from "../support/helpers/composer";
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";
@@ -324,7 +322,6 @@ test.describe("Cross-provider model search", () => {
const modelRowButton = page.getByTestId("agent-controls-model");
await expect(profilesToggle).toBeVisible();
await expect(page.getByTestId("agent-controls-profiles-list")).toHaveCount(0);
await waitForSettledPosition(profilesToggle);
const profilesBox = await profilesToggle.boundingBox();
const modelBox = await modelRowButton.boundingBox();
expect(profilesBox && modelBox && profilesBox.y < modelBox.y).toBe(true);
@@ -347,18 +344,6 @@ test.describe("Cross-provider model search", () => {
expect(Math.abs(expandedBox!.y - collapsedBox!.y)).toBeLessThanOrEqual(1);
expect(Math.abs(expandedBox!.height - collapsedBox!.height)).toBeLessThanOrEqual(1);
// Search dock matches the collapsed provider card's outer rails, height, and text rail.
const searchContainer = page.getByTestId("model-search-all-input-container");
const searchInput = page.getByTestId("model-search-all-input");
const searchBox = await searchContainer.boundingBox();
const searchInputBox = await searchInput.boundingBox();
const collapsedCardBox = await readCollapsedCardGeometry(collapsedHeader);
expect(searchBox && searchInputBox && collapsedCardBox).toBeTruthy();
expect(Math.abs(searchBox!.x - collapsedCardBox!.cardX)).toBeLessThanOrEqual(1);
expect(Math.abs(searchBox!.width - collapsedCardBox!.cardWidth)).toBeLessThanOrEqual(1);
expect(Math.abs(searchBox!.height - collapsedCardBox!.cardHeight)).toBeLessThanOrEqual(1);
expect(Math.abs(searchInputBox!.x - collapsedCardBox!.labelX)).toBeLessThanOrEqual(2);
// Return Home, expand Profiles in place, and apply the profile.
await page.getByTestId("sheet-header-back").click();
await profilesToggle.click();
@@ -466,97 +451,8 @@ test.describe("Cross-provider model search", () => {
await provider.restore();
}
});
test("compact single-provider picker keeps its header fixed and scrolls to the last model row", async ({
page,
}) => {
const extraModels = Array.from({ length: 24 }, (_, index) => ({
id: `extra-scroll-${String(index).padStart(2, "0")}`,
label: `Extra scroll model ${String(index).padStart(2, "0")}`,
description: `Extra row ${index}`,
}));
const client = await connectDaemonClient<DaemonClient>({
clientIdPrefix: "single-provider-scroll",
});
const workspace = await seedMockAgentWorkspace({
repoPrefix: "single-provider-scroll-",
title: "Single provider scroll",
model: "ten-second-stream",
modeId: "load-test",
});
try {
await client.patchDaemonConfig({
providers: {
mock: {
additionalModels: extraModels,
},
},
});
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-model")).toBeVisible();
await page.getByTestId("agent-controls-model").click();
const list = page.getByTestId("compact-model-list");
await expect(list).toBeVisible();
const header = page.getByTestId("model-provider-section-mock");
await expect(header).toBeVisible();
const headerBox = await header.boundingBox();
expect(headerBox).toBeTruthy();
expect(headerBox!.height).toBeGreaterThanOrEqual(16);
// Scroll to the bottom of the lone provider's list and confirm the final row is fully in view.
await list.evaluate((node) => {
node.scrollTop = node.scrollHeight;
});
const lastRow = page.getByTestId("model-row-mock-extra-scroll-23");
await expect(lastRow).toBeVisible();
const listBox = await list.boundingBox();
const lastRowBox = await lastRow.boundingBox();
expect(listBox && lastRowBox).toBeTruthy();
expect(lastRowBox!.y + lastRowBox!.height).toBeLessThanOrEqual(
listBox!.y + listBox!.height + 1,
);
await lastRow.click();
await expect(page.getByTestId("agent-controls-model")).toContainText("Extra scroll model 23");
} finally {
await client
.patchDaemonConfig({
providers: {
mock: {
additionalModels: [],
},
},
})
.catch(() => undefined);
await client.close().catch(() => undefined);
await workspace.cleanup();
}
});
});
async function readCollapsedCardGeometry(collapsedHeader: ReturnType<Page["getByTestId"]>) {
return collapsedHeader.evaluate((node) => {
// Walk up from the press overlay to the SettingsCard container (2px taller for borders).
const header = node.parentElement;
const card = header?.parentElement?.parentElement;
const rect = card?.getBoundingClientRect();
const label = header?.querySelector('[dir="auto"]');
const labelRect = label?.getBoundingClientRect();
return rect && labelRect
? {
cardX: rect.x,
cardWidth: rect.width,
cardHeight: rect.height,
labelX: labelRect.x,
}
: null;
});
}
async function startScrollSampling(page: Page, listTestId: string): Promise<void> {
await page.evaluate((testId) => {
const samples: number[] = [];
@@ -15,9 +15,6 @@ import {
expectBothConsecutiveTools,
trackPluginChatRecovery,
reconnectPluginChat,
withRepeatedOutputTimeline,
readOldestPluginReplacement,
expectOldestPluginReplacementReadable,
} from "../support/helpers/plugin-timeline";
for (const width of [1100, 390]) {
@@ -85,15 +82,3 @@ 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);
});
});
@@ -118,14 +118,10 @@ 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
.getByTestId("sidebar-pinned-section")
.locator(
`[data-testid="${firstWorkspaceTestId}"], [data-testid="${secondProjectWorkspaceTestId}"]`,
),
page.locator(
`[data-testid="${firstWorkspaceTestId}"], [data-testid="${secondProjectWorkspaceTestId}"]`,
),
pressWorkspaceRow,
);
} finally {
@@ -392,8 +392,6 @@ 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, {
@@ -430,10 +428,6 @@ 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);
}
@@ -1,34 +0,0 @@
import { BuiltinPluginLoader } from "../../../../server/src/server/plugins/builtin/index.js";
import { createTestPaseoDaemon } from "../../../../server/src/server/test-utils/paseo-daemon.js";
import { DaemonClient } from "../../../../server/src/server/test-utils/daemon-client.js";
import assert from "node:assert/strict";
import pino from "pino";
const [, , root, origin, paseoHomeRoot, daemonVersion] = process.argv;
const daemon = await createTestPaseoDaemon({
corsAllowedOrigins: [origin!],
paseoHomeRoot,
daemonVersion,
logger: pino({ level: "error" }),
builtinPlugins: new BuiltinPluginLoader(root, ["builtin-settings"]),
});
const client = new DaemonClient({
appVersion: daemonVersion,
url: `ws://127.0.0.1:${daemon.port}/ws`,
});
try {
await client.connect();
const plugin = (await client.getPluginCatalog()).find(({ id }) => id === "builtin-settings");
assert.ok(plugin?.clientBundle, JSON.stringify(await client.getPluginLogs("builtin-settings")));
assert.deepEqual(await client.listPlugins(), []);
process.send!({ serverId: client.getLastServerInfoMessage()!.serverId, port: daemon.port });
await new Promise<void>((resolve) => {
process.once("disconnect", resolve);
process.once("SIGTERM", resolve);
});
} finally {
await client.close();
await daemon.close();
}
@@ -1,60 +0,0 @@
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,9 +18,6 @@ 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
# Android Back steps from Model back to Agent settings, then closes the sheet.
# Reopen, dismiss the nested model browser, then dismiss its restored parent.
press "id=\"combined-model-selector\""
wait "id=\"agent-controls-model\"" 10000
press "id=\"agent-controls-model\""
wait "id=\"model-search-all-input\"" 10000
back
wait stable 300 5000
gesture pan 540 790 0 960 500
wait "id=\"agent-controls-model\"" 3000
back
gesture pan 540 790 0 960 500
wait "id=\"combined-model-selector\"" 3000
close
@@ -627,8 +627,7 @@ export async function expectProfilesEditLink(page: Page): Promise<void> {
exact: true,
});
await expect(edit).toBeVisible();
await expect(edit).toHaveText("");
await expect(edit.locator("svg")).toBeVisible();
await expect(edit).toHaveText("Edit");
}
/** With no profiles, the Profiles entry offers to create one instead of listing any. */
@@ -1,77 +0,0 @@
import { mkdir, writeFile } from "node:fs/promises";
import path from "node:path";
import { once } from "node:events";
import { spawnTsx, killProcessTree } from "./spawn-node";
import appPackage from "../../../package.json";
import { expect, test as base, type Page } from "../fixtures";
import { gotoAppShell } from "./app";
import { addConnectedHostAndReload } from "./hosts";
import { pluginRequirements } from "./plugin-fixture";
const pluginId = "builtin-settings";
const screenId = "general";
const settingsText = "Built-in settings body";
export const test = base.extend<{ builtinSettingsHost: { serverId: string; port: number } }>({
builtinSettingsHost: async ({ baseURL }, provide, testInfo) => {
const root = testInfo.outputPath("builtin-plugins");
const directory = path.join(root, pluginId);
await mkdir(directory, { recursive: true });
await writeFile(
path.join(directory, "paseo-plugin.json"),
JSON.stringify({ id: pluginId, requirements: pluginRequirements }),
);
await writeFile(
path.join(directory, "index.client.tsx"),
`import React from "react";
import { Text } from "react-native";
export default function contribute(client) {
client.addSettingsScreen({
id: "${screenId}",
title: "General",
icon: "SlidersHorizontal",
Component: () => <Text>${settingsText}</Text>,
});
return () => {};
}`,
);
await writeFile(
path.join(directory, "index.server.ts"),
"export default function contribute() { return () => {}; }",
);
const daemon = spawnTsx(
path.resolve(__dirname, "../../fixtures/builtin-settings/daemon.mts"),
[root, new URL(baseURL!).origin, testInfo.outputPath("daemon"), appPackage.version],
{ stdio: ["ignore", "inherit", "inherit", "ipc"] },
);
try {
const [host] = await Promise.race([
once(daemon, "message") as Promise<[{ serverId: string; port: number }]>,
once(daemon, "exit").then(([code]) => {
throw new Error(`Built-in settings daemon exited with code ${code}`);
}),
]);
await provide(host);
} finally {
await killProcessTree(daemon);
}
},
});
export async function openBuiltinPluginSettings(
page: Page,
host: { serverId: string; port: number },
) {
await gotoAppShell(page);
await addConnectedHostAndReload(page, {
...host,
label: "Built-in settings host",
destination: `/settings/hosts/${host.serverId}/plugins/${pluginId}/${screenId}`,
});
}
export async function expectBuiltinPluginSettings(page: Page) {
await expect(page.getByText(settingsText, { exact: true })).toBeVisible();
await expect(page.getByRole("switch", { name: /: Disable$/ })).toHaveCount(0);
}
+4 -14
View File
@@ -76,24 +76,15 @@ export async function addOfflineHostsAndReload(
export async function addConnectedHostAndReload(
page: Page,
input: {
serverId: string;
label: string;
port: number;
primaryLabel?: string;
destination?: string;
},
input: { serverId: string; label: string; port: number; primaryLabel?: string },
): Promise<void> {
await addConnectedHostsAndReload(page, [input], {
primaryLabel: input.primaryLabel,
destination: input.destination,
});
await addConnectedHostsAndReload(page, [input], { primaryLabel: input.primaryLabel });
}
export async function addConnectedHostsAndReload(
page: Page,
inputs: Array<{ serverId: string; label: string; port: number }>,
options?: { primaryLabel?: string; destination?: string },
options?: { primaryLabel?: string },
): Promise<void> {
const connectedHosts = inputs.map((input) =>
buildSeededHost({
@@ -132,8 +123,7 @@ export async function addConnectedHostsAndReload(
},
);
if (options?.destination) await page.goto(options.destination);
else await page.reload();
await page.reload();
}
export async function waitForConnectedHost(
@@ -7,7 +7,6 @@ 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";
@@ -374,81 +373,3 @@ 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,24 +61,18 @@ async function readRows(input: {
storeName: string;
}): Promise<ReplicaRowRecord[]> {
const database = await new Promise<IDBDatabase>((resolve, reject) => {
// The app owns the database version; open whatever version it created.
const request = indexedDB.open(input.databaseName);
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();
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 {
@@ -191,27 +185,19 @@ 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);
const request = indexedDB.open(databaseName, 1);
request.addEventListener("success", () => resolve(request.result));
request.addEventListener("error", () => reject(request.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();
}
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));
});
},
{ databaseName: DATABASE_NAME, storeName: STORE_NAME, nextRows: rows },
);
@@ -1,13 +1,11 @@
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
@@ -79,15 +77,6 @@ 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 {
@@ -111,8 +100,13 @@ class TerminalInputConnectionTest {
@Test
fun batchedCommitTextAndSetComposingTextDoNotDoubleCharacters() {
withInputHarness { _, ic, _, terminal ->
ic.typeLikeGboard("abcd")
for (ch in listOf("a", "b", "c", "d")) {
ic.beginBatchEdit()
ic.commitText(ch, 1)
ic.endBatchEdit()
}
assertEquals("abcd", terminal.rawStream)
assertEquals("", ic.editable.toString())
// Coalesced setComposingText + finishComposingText inside one batch emits once.
ic.beginBatchEdit()
@@ -120,96 +114,28 @@ 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
// Path 1: deleteSurroundingText (empty editable after commit)
ic.deleteSurroundingText(0, 0)
assertEquals("abcd", terminal.applyToLine())
ic.deleteSurroundingText(1, 0)
assertEquals("abc", terminal.applyToLine())
// Path 2: deleteSurroundingTextInCodePoints
// Path 2: deleteSurroundingTextInCodePoints (empty editable)
ic.deleteSurroundingTextInCodePoints(1, 0)
assertEquals("ab", terminal.applyToLine())
// Path 2b: deleteSurroundingTextInCodePoints removes a surrogate-pair emoji as one code point
ic.commitText("😀", 1)
// Path 2b: deleteSurroundingTextInCodePoints on surrogate-pair emoji in composing buffer
ic.setComposingText("😀", 1)
assertEquals("ab😀", terminal.applyToLine())
ic.deleteSurroundingTextInCodePoints(1, 0)
assertEquals("ab", terminal.applyToLine())
@@ -219,16 +145,10 @@ class TerminalInputConnectionTest {
ic.sendKeyEvent(KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_DEL))
assertEquals("a", terminal.applyToLine())
// Multi-char deleteSurroundingText
// Multi-char deleteSurroundingText on empty buffer
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))
}
}
@@ -322,7 +242,7 @@ class TerminalInputConnectionTest {
ic.commitText("the", 1)
assertEquals("hellothe", terminal.applyToLine())
// Repeated clipboard paste of identical text appends both copies
// Repeated clipboard paste of identical text works because editable clears after commit
ic.commitText("echo ok", 1)
ic.commitText("echo ok", 1)
assertEquals("hellotheecho okecho ok", terminal.applyToLine())
@@ -22,16 +22,9 @@ internal data class TerminalKeyPayload(
/**
* Single authoritative IME + key stream for the Android native terminal.
*
* 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.
* 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.
*/
internal class TerminalInputConnection(
private val targetView: View,
@@ -203,7 +196,6 @@ 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"
@@ -350,38 +342,57 @@ internal class TerminalInputConnection(
if (diff.isNotEmpty()) {
out.append(normalizeLineEndings(diff))
}
lastSentText = currentText
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
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)
}
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
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)
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())
}
}
@@ -400,6 +411,10 @@ 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
+7 -8
View File
@@ -603,15 +603,14 @@ describe("layoutStream", () => {
splitIntoCards,
);
const footerCardIds = tail
.filter((item) => item.kind === "plugin" && item.itemKind === "genui-card")
.map((item) => item.id);
expect(footerCardIds).toHaveLength(2);
const layout = layoutFor({
platform,
tail,
timingIds: ["genui/a1/card", "genui/a2/card"],
});
const layout = layoutFor({ platform, tail, timingIds: footerCardIds });
expect(footerOwners(layout)).toEqual(footerCardIds);
expect(findLayoutItem(layout, footerCardIds[0]).completedFooter?.turnMetrics).toBe(
expect(footerOwners(layout)).toEqual(["genui/a1/card", "genui/a2/card"]);
expect(findLayoutItem(layout, "genui/a1/card").completedFooter?.turnMetrics).toBe(
first.turnMetrics,
);
expect(layout.auxiliaryTurnFooter?.turnMetrics).toBe(metrics);
@@ -203,9 +203,7 @@ 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", source: { id: "prompt-1" }, pluginItemId: "prompt-1/0" },
]);
expect(rendered).toMatchObject([{ kind: "plugin", id: "probe-plugin/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"]);
});
@@ -613,7 +611,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",
JSON.stringify(["probe-plugin", "reply", "reply/0"]),
"probe-plugin/reply/0",
]);
expect(pluginData(result.tail)).toEqual([{ text: "$$x^2$$", phase: "complete" }]);
});
@@ -642,7 +640,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",
JSON.stringify(["probe-plugin", "reply", "reply/0"]),
"probe-plugin/reply/0",
]);
const expandedTurnHostIds = new Set(["prompt"]);
const opened = present({ ...completed, expandedTurnHostIds });
@@ -650,16 +648,14 @@ it("keeps streaming replies native, then folds work without losing manual expans
"prompt",
"turn-summary:prompt",
"tool-one",
JSON.stringify(["probe-plugin", "reply", "reply/0"]),
"probe-plugin/reply/0",
]);
expect(opened.turns.nestedItemIds.has(JSON.stringify(["probe-plugin", "reply", "reply/0"]))).toBe(
false,
);
expect(opened.turns.nestedItemIds.has("probe-plugin/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",
JSON.stringify(["probe-plugin", "reply", "reply/0"]),
"probe-plugin/reply/0",
]);
});
@@ -683,7 +679,7 @@ it.each(["full", "collapseToolCalls"] as const)(
expect(result.tail.map((item) => item.id)).toEqual([
"prompt",
"tool-one",
JSON.stringify(["probe-plugin", "reply", "reply/0"]),
"probe-plugin/reply/0",
]);
expect(result.turns.summaryRowsByHostId.size).toBe(0);
},
@@ -60,10 +60,6 @@ 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;
@@ -742,17 +738,10 @@ 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);
@@ -14,7 +14,6 @@ import {
import { ModelProviderGlyph, useSelectedModelLabels } from "@/components/model-browser";
import { DesktopModelPicker, type ModelPickerActions } from "@/components/model-browser-panes";
import {
getSheetSearchFooterStyle,
MobileModelPageView,
SheetSearchDock,
useMobileModelPage,
@@ -314,7 +313,6 @@ function CompactCombinedModelSelector({
snapPoints={SHEET_SNAP_POINTS}
scrollable={false}
footer={footer}
footerContainerStyle={getSheetSearchFooterStyle()}
keyboard={keyboard}
contentStyle={styles.sheetBody}
testID="model-selector-sheet"
@@ -12,7 +12,6 @@ import { useQuery } from "@tanstack/react-query";
import { useTranslation } from "react-i18next";
import {
FlatList,
Keyboard,
type LayoutChangeEvent,
ListRenderItemInfo,
Pressable,
@@ -630,8 +629,6 @@ 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],
@@ -2,7 +2,7 @@ import { useCallback, useMemo, useRef, useState, type ReactElement, type ReactNo
import { useTranslation } from "react-i18next";
import { FlatList, Text, View } from "react-native";
import { StyleSheet, withUnistyles } from "react-native-unistyles";
import { AlertTriangle, ChevronDown, Layers } from "lucide-react-native";
import { AlertTriangle, ChevronDown, Layers, Pencil } from "lucide-react-native";
import type { AgentProfilePickerRow } from "@/agent-profiles";
import {
IndependentScrollBoundary,
@@ -16,7 +16,6 @@ import {
} from "@/components/model-browser";
import {
CustomizeProviderButton,
EditProfilesButton,
ModelPickerItemRow,
type ModelPickerActions,
} from "@/components/model-browser-panes";
@@ -35,6 +34,7 @@ import {
type MobileProviderSection,
} from "@/components/mobile-model-page-view";
import { SettingsCard } from "@/components/settings";
import { Button } from "@/components/ui/button";
import { LoadingSpinner } from "@/components/ui/loading-spinner";
import { PressHighlight } from "@/components/ui/press-highlight";
import {
@@ -46,7 +46,6 @@ import { SearchField } from "@/components/ui/search-field";
import { isNative, isWeb } from "@/constants/platform";
import type { ProviderSelectorProvider } from "@/provider-selection/provider-selection";
import { ICON_SIZE, type Theme } from "@/styles/theme";
import { settingsStyles } from "@/styles/settings";
import { inlineUnistylesStyle } from "@/styles/unistyles-inline-style";
/**
@@ -159,7 +158,6 @@ export function SheetSearchDock({
placeholder={placeholder}
clearAccessibilityLabel={t("providerCatalog.clearSearch")}
fullWidth
variant="card"
testID={testID}
clearTestID={testID ? `${testID}-clear` : undefined}
/>
@@ -265,21 +263,6 @@ export function MobileModelPageView({
),
[renderItem],
);
const singleProviderSection =
projection.kind === "browse" && !projection.showSectionHeaders
? projection.sections[0]
: undefined;
const singleProviderHeader = useMemo(
() =>
singleProviderSection?.kind === "provider" ? (
<ProviderSectionHeader
section={singleProviderSection}
serverId={serverId}
collapsible={false}
/>
) : undefined,
[serverId, singleProviderSection],
);
if (projection.kind === "noProviders") {
return (
@@ -313,8 +296,12 @@ export function MobileModelPageView({
);
}
if (!projection.showSectionHeaders) {
const section = projection.sections[0];
return (
<SheetListCard header={singleProviderHeader} testID="mobile-model-page">
<SheetListCard testID="mobile-model-page">
{section?.kind === "provider" ? (
<ProviderSectionHeader section={section} serverId={serverId} collapsible={false} />
) : null}
{projection.body ? (
<SectionBody
body={projection.body}
@@ -410,8 +397,18 @@ export function CollapsibleProfilesCard({
[],
);
const trailingAction = useMemo(
() => (expanded && onEditProfiles ? <EditProfilesButton onPress={onEditProfiles} /> : null),
[expanded, onEditProfiles],
() =>
expanded && onEditProfiles ? (
<Button
variant="ghost"
size="sm"
leftIcon={Pencil}
onPress={onEditProfiles}
accessibilityLabel={t("modelSelector.editProfilesLabel")}
testID="model-profiles-edit"
/>
) : null,
[expanded, onEditProfiles, t],
);
const viewportHeight = computeBoundedListHeight(items.length);
@@ -494,25 +491,12 @@ function AccordionSectionCard({
/**
* An inset card holding one sheet list, on the same rail as the browse sections' cards. It grows
* with the list, then the list scrolls inside it while its optional header stays fixed.
* with the list, then the list scrolls inside it.
*/
function SheetListCard({
header,
children,
testID,
}: {
header?: ReactNode;
children: ReactNode;
testID?: string;
}) {
function SheetListCard({ children, testID }: { children: ReactNode; testID?: string }) {
return (
<View style={styles.listCardPage} testID={testID}>
<View style={[settingsStyles.card, styles.listCard]}>
{header ? <View style={styles.listCardHeader}>{header}</View> : null}
<View style={[header ? settingsStyles.rowBorder : undefined, styles.listCardBody]}>
{children}
</View>
</View>
<SettingsCard shrink>{children}</SettingsCard>
</View>
);
}
@@ -607,8 +591,18 @@ function ProfilesSectionHeader({
[],
);
const trailing = useMemo(
() => (expanded && onEditProfiles ? <EditProfilesButton onPress={onEditProfiles} /> : null),
[expanded, onEditProfiles],
() =>
expanded && onEditProfiles ? (
<Button
variant="ghost"
size="sm"
leftIcon={Pencil}
onPress={onEditProfiles}
accessibilityLabel={t("modelSelector.editProfilesLabel")}
testID="model-profiles-edit"
/>
) : null,
[expanded, onEditProfiles, t],
);
return (
<CollapsibleSectionHeader
@@ -704,7 +698,7 @@ function SectionBody({
onRetryProvider: ModelPickerActions["onRetryProvider"];
isRetryingProvider: boolean;
}) {
const frameStyle = fill ? styles.fillState : styles.fixedViewport;
const frameStyle = fill ? styles.page : styles.fixedViewport;
if (body.kind === "providerLoading") {
return (
<View style={[frameStyle, styles.centered]}>
@@ -790,12 +784,8 @@ function SectionItemList({
return [styles.boundedViewport, inlineUnistylesStyle({ height: viewportHeight })];
}, [fill, viewportHeight]);
// A lone provider's list is the sheet's own scroller, so it must integrate with the bottom sheet
// gesture handler (SheetFlatList); an accordion list scrolls independently inside SheetScrollView.
const ListComponent = fill ? SheetFlatList : FlatList;
return (
<ListComponent
<FlatList
ref={listRef}
data={items}
renderItem={renderItem}
@@ -808,7 +798,7 @@ function SectionItemList({
keyboardShouldPersistTaps="handled"
keyboardDismissMode={KEYBOARD_DISMISS_MODE}
showsVerticalScrollIndicator
nestedScrollEnabled={!fill}
nestedScrollEnabled
testID={testID}
/>
);
@@ -826,20 +816,6 @@ const styles = StyleSheet.create((theme) => ({
paddingTop: theme.spacing[2],
paddingBottom: theme.spacing[2],
},
listCard: {
flexShrink: 1,
minHeight: 0,
},
listCardHeader: {
flexShrink: 0,
},
listCardBody: {
flexShrink: 1,
minHeight: 0,
},
fillState: {
minHeight: MOBILE_EXPANDED_PROVIDER_HEIGHT,
},
sections: {
paddingHorizontal: theme.spacing[4],
paddingTop: theme.spacing[2],
@@ -915,14 +891,4 @@ const styles = StyleSheet.create((theme) => ({
flex: 1,
flexDirection: "row",
},
searchFooter: {
// Matches the card inset (`styles.sections` / `styles.listCardPage`) so the search box shares
// its outer left and right rails with the provider cards above it.
paddingHorizontal: theme.spacing[4],
},
}));
/** Read at render time rather than module scope (docs/unistyles.md). */
export function getSheetSearchFooterStyle() {
return styles.searchFooter;
}
@@ -603,6 +603,7 @@ function ListPane({
onActivate: (key: string) => void;
actions: ModelPickerActions;
}) {
const { t } = useTranslation();
const { pane, activeKey } = projection;
const entries = useListEntries(pane);
const profiledLookup = useMemo(
@@ -628,7 +629,17 @@ function ListPane({
if (entry.kind === "heading") {
let headingAction: ReactNode = null;
if (entry.action?.kind === "editProfiles" && actions.onEditProfiles) {
headingAction = <EditProfilesButton onPress={actions.onEditProfiles} />;
headingAction = (
<Button
variant="ghost"
size="sm"
onPress={actions.onEditProfiles}
accessibilityLabel={t("modelSelector.editProfilesLabel")}
testID="model-profiles-edit"
>
{t("modelSelector.editProfiles")}
</Button>
);
} else if (entry.action?.kind === "customizeProvider" && serverId) {
headingAction = (
<CustomizeProviderButton
@@ -669,6 +680,7 @@ function ListPane({
selectedModel,
selectedProvider,
serverId,
t,
],
);
@@ -785,7 +797,17 @@ function ListPaneHeader({
<Text style={styles.paneTitle} numberOfLines={1}>
{t("modelSelector.profiles")}
</Text>
{onEditProfiles ? <EditProfilesButton onPress={onEditProfiles} /> : null}
{onEditProfiles ? (
<Button
variant="ghost"
size="sm"
onPress={onEditProfiles}
accessibilityLabel={t("modelSelector.editProfilesLabel")}
testID="model-profiles-edit"
>
{t("modelSelector.editProfiles")}
</Button>
) : null}
</View>
);
}
@@ -806,20 +828,6 @@ function ListPaneHeader({
);
}
export function EditProfilesButton({ onPress }: { onPress: () => void }) {
const { t } = useTranslation();
return (
<Button
variant="ghost"
size="sm"
leftIcon={Pencil}
onPress={onPress}
accessibilityLabel={t("modelSelector.editProfilesLabel")}
testID="model-profiles-edit"
/>
);
}
export function CustomizeProviderButton({
serverId,
providerId,
@@ -1,52 +0,0 @@
import { Component, type ErrorInfo, type ReactNode } from "react";
interface RenderErrorBoundaryProps {
children: ReactNode;
/** A caught error is cleared when any of these values change, so new content renders. */
resetKeys: readonly unknown[];
/** The error state shown in place of the children. `retry` renders the children again. */
renderError(error: string, retry: () => void): ReactNode;
onError(error: unknown, componentStack: string | null | undefined): void;
}
interface RenderErrorBoundaryState {
error: string | null;
}
/**
* Keeps a render error inside one surface. Without it the error reaches the root boundary,
* which replaces the whole app.
*/
export class RenderErrorBoundary extends Component<
RenderErrorBoundaryProps,
RenderErrorBoundaryState
> {
state: RenderErrorBoundaryState = { error: null };
static getDerivedStateFromError(error: unknown): RenderErrorBoundaryState {
return { error: error instanceof Error ? error.message : String(error) };
}
componentDidCatch(error: unknown, info: ErrorInfo): void {
this.props.onError(error, info.componentStack);
}
componentDidUpdate(previous: RenderErrorBoundaryProps): void {
if (this.state.error !== null && resetKeysChanged(previous.resetKeys, this.props.resetKeys)) {
this.retry();
}
}
retry = (): void => {
this.setState({ error: null });
};
render() {
if (this.state.error !== null) return this.props.renderError(this.state.error, this.retry);
return this.props.children;
}
}
function resetKeysChanged(previous: readonly unknown[], next: readonly unknown[]): boolean {
return previous.length !== next.length || previous.some((key, index) => key !== next[index]);
}
+15 -3
View File
@@ -56,13 +56,25 @@ interface AppSettingsRowProps extends Omit<SettingsRowProps, "hint">, AppRowExtr
hint?: ReactNode;
}
export function SettingsCard({ children, testID }: { children: ReactNode; testID?: string }) {
/** Lets a card and its rows shrink below their content, so a list inside can scroll. */
const SHRINK = { flexShrink: 1, minHeight: 0 } as const;
export function SettingsCard({
children,
testID,
shrink = false,
}: {
children: ReactNode;
testID?: string;
/** The card shrinks to fit a parent with a bounded height, and a list inside it scrolls. */
shrink?: boolean;
}) {
return (
<View style={settingsStyles.card} testID={testID}>
<View style={[settingsStyles.card, shrink && SHRINK]} testID={testID}>
{Children.toArray(children).map((child, index) => (
<View
key={isValidElement(child) ? child.key : index}
style={index ? settingsStyles.rowBorder : undefined}
style={[index ? settingsStyles.rowBorder : undefined, shrink && SHRINK]}
>
{child}
</View>
@@ -89,7 +89,9 @@ const styles = StyleSheet.create((theme: Theme) => ({
top: 0,
bottom: 0,
width: INDENT_GUIDE_WIDTH,
backgroundColor: theme.colors.treeGuide,
// Translucent ink, not `border`: a solid line that colour disappears into a hovered row's fill.
backgroundColor: theme.colors.foregroundExtraMuted,
opacity: theme.opacity[50],
},
chevron: {
width: WORKSPACE_TREE_ICON_SIZE,
@@ -7,7 +7,7 @@ import {
} from "react-native";
import { Search, X } from "lucide-react-native";
import { StyleSheet, withUnistyles } from "react-native-unistyles";
import { ICON_SIZE, type Theme } from "@/styles/theme";
import type { Theme } from "@/styles/theme";
import {
EditingTextInput as TextInput,
type EditingTextInputHandle,
@@ -35,11 +35,6 @@ export interface SearchFieldProps {
fullWidth?: boolean;
/** `sm` heads a list in tight chrome such as a sidebar pane. */
size?: "sm" | "md";
/**
* `card` matches a compact `SettingsCard` row's height, corner radius, horizontal inset, and
* leading glyph rail so a docked sheet search aligns with the cards above it.
*/
variant?: "default" | "card";
/** Escape empties the field. Off where Escape already closes the surface around it. */
clearOnEscape?: boolean;
testID?: string;
@@ -61,7 +56,6 @@ export function SearchField({
clearAccessibilityLabel,
fullWidth = false,
size = "md",
variant = "default",
clearOnEscape = false,
testID,
clearTestID,
@@ -85,21 +79,17 @@ export function SearchField({
if (value === "" && inputRef.current?.getText()) inputRef.current.replaceText("");
}, [value]);
const small = size === "sm";
const card = variant === "card";
const leadingIcon = <ThemedSearch size={ICON_SIZE.sm} uniProps={mutedColorMapping} />;
return (
<View
testID={testID ? `${testID}-container` : undefined}
style={[
styles.field,
small && styles.fieldSmall,
card && styles.fieldCard,
fullWidth && styles.fieldFullWidth,
isFocused && styles.fieldFocused,
]}
>
{card ? <View style={styles.leadingSlot}>{leadingIcon}</View> : leadingIcon}
<ThemedSearch size={14} uniProps={mutedColorMapping} />
<ThemedTextInput
testID={testID}
ref={inputRef}
@@ -122,9 +112,8 @@ export function SearchField({
accessibilityRole="button"
accessibilityLabel={clearAccessibilityLabel}
hitSlop={8}
style={card ? styles.clearSlot : undefined}
>
<ThemedX size={ICON_SIZE.sm} uniProps={mutedColorMapping} />
<ThemedX size={14} uniProps={mutedColorMapping} />
</Pressable>
) : null}
</View>
@@ -153,25 +142,6 @@ const styles = StyleSheet.create((theme) => ({
paddingVertical: 0,
paddingHorizontal: theme.spacing[1.5],
},
fieldCard: {
// Matches a collapsed SettingsCard row: 44pt inner row height + 1px top/bottom border = 46pt.
height: 46,
paddingVertical: 0,
paddingHorizontal: { xs: theme.spacing[4], md: theme.spacing[3] },
borderRadius: theme.borderRadius.lg,
},
leadingSlot: {
width: 16,
alignItems: "center",
justifyContent: "center",
},
clearSlot: {
width: ICON_SIZE.sm,
height: ICON_SIZE.sm,
marginRight: -theme.spacing[1],
alignItems: "center",
justifyContent: "center",
},
fieldFullWidth: {
maxWidth: "100%",
},
@@ -13,7 +13,6 @@ import { ModelProviderGlyph } from "@/components/model-browser";
import type { ModelPickerActions } from "@/components/model-browser-panes";
import {
CollapsibleProfilesCard,
getSheetSearchFooterStyle,
MobileModelPageView,
SheetSearchDock,
useMobileModelPage,
@@ -353,7 +352,6 @@ export function AgentSettingsDrawer({
snapPoints={SNAP_POINTS}
scrollable={false}
footer={footer}
footerContainerStyle={getSheetSearchFooterStyle()}
keyboard={keyboard}
contentStyle={styles.sheetBody}
contextBridge={contextBridge}
-3
View File
@@ -2183,9 +2183,6 @@ export const ar: TranslationResources = {
archiveFinishedRetry: "إعادة المحاولة ({{failed}}/{{total}})",
},
panels: {
renderError: {
title: "تعذّر عرض هذه اللوحة",
},
draft: {
newAgent: "وكيل جديد",
creatingAgent: "وكيل الخلق",
-3
View File
@@ -2213,9 +2213,6 @@ export const en = {
archiveFinishedRetry: "Retry ({{failed}}/{{total}})",
},
panels: {
renderError: {
title: "Unable to show this panel",
},
draft: {
newAgent: "New Agent",
creatingAgent: "Creating agent",
-3
View File
@@ -2239,9 +2239,6 @@ export const es: TranslationResources = {
archiveFinishedRetry: "Reintentar ({{failed}}/{{total}})",
},
panels: {
renderError: {
title: "No se puede mostrar este panel",
},
draft: {
newAgent: "Nuevo agente",
creatingAgent: "Agente creador",
-3
View File
@@ -2236,9 +2236,6 @@ export const fr: TranslationResources = {
archiveFinishedRetry: "Réessayer ({{failed}}/{{total}})",
},
panels: {
renderError: {
title: "Impossible d'afficher ce panneau",
},
draft: {
newAgent: "Nouvel agent",
creatingAgent: "Création de l’agent",
-3
View File
@@ -2206,9 +2206,6 @@ export const ja: TranslationResources = {
archiveFinishedRetry: "再試行 ({{failed}}/{{total}})",
},
panels: {
renderError: {
title: "このパネルを表示できません",
},
draft: {
newAgent: "新しいエージェント",
creatingAgent: "エージェントを作成中",
-3
View File
@@ -2195,9 +2195,6 @@ export const ko: TranslationResources = {
archiveFinishedRetry: "다시 시도 ({{failed}}/{{total}})",
},
panels: {
renderError: {
title: "이 패널을 표시할 수 없습니다",
},
draft: {
newAgent: "새 에이전트",
creatingAgent: "에이전트 생성 중",
-3
View File
@@ -2223,9 +2223,6 @@ export const ptBR: TranslationResources = {
archiveFinishedRetry: "Tentar novamente ({{failed}}/{{total}})",
},
panels: {
renderError: {
title: "Não foi possível exibir este painel",
},
draft: {
newAgent: "Novo Agente",
creatingAgent: "Criando agente",
-3
View File
@@ -2223,9 +2223,6 @@ export const ru: TranslationResources = {
archiveFinishedRetry: "Повторить ({{failed}}/{{total}})",
},
panels: {
renderError: {
title: "Не удалось показать эту панель",
},
draft: {
newAgent: "Новый агент",
creatingAgent: "Создание агента",
-3
View File
@@ -2160,9 +2160,6 @@ export const zhCN: TranslationResources = {
archiveFinishedRetry: "重试 ({{failed}}/{{total}})",
},
panels: {
renderError: {
title: "无法显示此面板",
},
draft: {
newAgent: "新建 Agent",
creatingAgent: "正在创建 Agent",
@@ -27,12 +27,8 @@ import { StatusBadge } from "@/components/ui/status-badge";
import { Switch } from "@/components/ui/switch";
import { useIsCompactFormFactor } from "@/constants/layout";
import { useToast } from "@/contexts/toast-api-context";
import { useHostRuntimeClient, useHostRuntimeIsConnected } from "@/runtime/host-runtime";
import {
useInstalledPlugin,
usePluginCatalogStatus,
usePluginEvaluationError,
} from "@/plugins/registry";
import { useHostRuntimeClient } from "@/runtime/host-runtime";
import { useInstalledPlugin, usePluginEvaluationError } from "@/plugins/registry";
import { pluginDisplayName } from "@/plugins/plugin-list";
import { PluginSettingsContent } from "@/plugins/settings";
import { usePluginActions, type PluginAction } from "./actions";
@@ -280,6 +276,8 @@ interface PluginPageModel {
error?: string;
/** Why the last update failed, while the update is still offered. The installed version keeps running. */
updateError?: string;
/** The plugin's own settings screen, shown inline. */
screenId?: string;
overview?: string;
}
@@ -303,10 +301,12 @@ function usePluginPageModel({
const directory = usePluginDirectory(serverId);
const meta = useListingMeta();
const pluginId = plugin?.id ?? "";
const installedPlugin = useInstalledPlugin(serverId, pluginId);
const evaluationError = usePluginEvaluationError(serverId, pluginId);
const pluginOperation = usePluginOperation(serverId, pluginId);
const updates = usePluginUpdates(serverId);
const text = listing ? listingText(listing, i18n.language) : undefined;
const requestedScreen = subject.kind === "installed" ? subject.screenId : undefined;
return {
name: plugin ? pluginDisplayName(plugin) : (text?.name ?? subjectId(subject)),
description: text?.description ?? plugin?.description,
@@ -316,22 +316,11 @@ function usePluginPageModel({
authorAvatar: listing && listingAuthorAvatar(listing),
error: plugin ? (evaluationError ?? plugin.error) : failedError(installOperation),
updateError: failedUpdateError(pluginOperation, updates.data, pluginId),
screenId: plugin ? (requestedScreen ?? installedPlugin?.settingsScreens[0]?.id) : undefined,
overview: detail && listingOverview(detail, i18n.language),
};
}
function usePluginPageSettings(
serverId: string,
subject: PluginPageSubject,
plugin: PluginListItem | undefined,
) {
const pluginId = subject.kind === "installed" ? subject.pluginId : (plugin?.id ?? "");
const installedPlugin = useInstalledPlugin(serverId, pluginId);
const requestedScreen = subject.kind === "installed" ? subject.screenId : undefined;
const screenId = requestedScreen ?? installedPlugin?.settingsScreens[0]?.id;
return (plugin || installedPlugin) && screenId ? { pluginId, screenId } : undefined;
}
function subjectId(subject: PluginPageSubject): string {
return subject.kind === "listing" ? subject.listingId : subject.pluginId;
}
@@ -419,9 +408,6 @@ export function PluginPage({
const { t } = useTranslation();
const compact = useIsCompactFormFactor();
const { plugin, listingId, listing, detail, loading } = useResolvedPlugin(serverId, subject);
const settings = usePluginPageSettings(serverId, subject, plugin);
const catalogStatus = usePluginCatalogStatus(serverId);
const connected = useHostRuntimeIsConnected(serverId);
const installOperation = usePluginOperation(serverId, listingId);
const model = usePluginPageModel({
serverId,
@@ -450,20 +436,14 @@ export function PluginPage({
<SettingsBackLink label={t("settings.plugins.screens.backToPlugins")} onPress={onBack} />
</View>
);
const waitingForSettings =
subject.kind === "installed" &&
!plugin &&
!settings &&
connected &&
catalogStatus === "loading";
if (loading || waitingForSettings)
if (loading)
return (
<View>
{back}
<PluginPageSkeleton />
</View>
);
if (!plugin && !listing && !settings)
if (!plugin && !listing)
return (
<Alert
size="sm"
@@ -506,7 +486,6 @@ export function PluginPage({
listing={listing}
overviewLoading={detail.isLoading}
model={model}
settings={settings}
/>
{installTarget ? (
<InstallPluginSheet serverId={serverId} target={installTarget} onClose={closeInstall} />
@@ -521,14 +500,12 @@ function PluginPageBody({
listing,
overviewLoading,
model,
settings,
}: {
serverId: string;
plugin?: PluginListItem;
listing?: PluginListing;
overviewLoading: boolean;
model: PluginPageModel;
settings?: { pluginId: string; screenId: string };
}) {
const { t } = useTranslation();
return (
@@ -546,9 +523,9 @@ function PluginPageBody({
</View>
) : null}
{listing ? <MediaStrip urls={listingImages(listing)} /> : null}
{settings ? (
{plugin && model.screenId ? (
// The plugin's settings screen brings its own sections.
<PluginSettingsContent serverId={serverId} {...settings} />
<PluginSettingsContent serverId={serverId} pluginId={plugin.id} screenId={model.screenId} />
) : null}
{model.overview || (listing && overviewLoading) ? (
<SettingsSection title={t("settings.plugins.gallery.sections.overview")}>
@@ -1,7 +1,6 @@
import type { ReactNode } from "react";
import React, { Component, type ErrorInfo, type ReactNode } from "react";
import { Text } from "react-native";
import { StyleSheet } from "react-native-unistyles";
import { RenderErrorBoundary } from "@/components/render-error-boundary";
interface SurfaceErrorBoundaryProps {
children: ReactNode;
@@ -11,30 +10,42 @@ interface SurfaceErrorBoundaryProps {
renderError?(error: string): ReactNode;
}
export function SurfaceErrorBoundary({
children,
installation,
resetKey,
Surface,
renderError,
}: SurfaceErrorBoundaryProps) {
return (
<RenderErrorBoundary
resetKeys={[installation, resetKey, Surface]}
onError={warnSurfaceRenderFailed}
renderError={renderError ?? renderPluginFailed}
>
{children}
</RenderErrorBoundary>
);
interface SurfaceErrorBoundaryState {
error: string | null;
}
function renderPluginFailed(error: string) {
return <Text style={styles.errorText}>Plugin failed: {error}</Text>;
}
export class SurfaceErrorBoundary extends Component<
SurfaceErrorBoundaryProps,
SurfaceErrorBoundaryState
> {
state: SurfaceErrorBoundaryState = { error: null };
function warnSurfaceRenderFailed(error: unknown, componentStack: string | null | undefined): void {
console.warn("[Plugins] Surface render failed", error, componentStack);
static getDerivedStateFromError(error: unknown): SurfaceErrorBoundaryState {
return { error: error instanceof Error ? error.message : String(error) };
}
componentDidCatch(error: Error, info: ErrorInfo): void {
console.warn("[Plugins] Surface render failed", error, info.componentStack);
}
componentDidUpdate(previous: SurfaceErrorBoundaryProps): void {
if (
this.state.error &&
(previous.installation !== this.props.installation ||
previous.resetKey !== this.props.resetKey ||
previous.Surface !== this.props.Surface)
) {
this.setState({ error: null });
}
}
render() {
if (this.state.error) {
if (this.props.renderError) return this.props.renderError(this.state.error);
return <Text style={styles.errorText}>Plugin failed: {this.state.error}</Text>;
}
return this.props.children;
}
}
const styles = StyleSheet.create((theme) => ({
@@ -82,69 +82,6 @@ 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 = {
@@ -189,8 +126,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" },
},
]);
@@ -277,11 +214,10 @@ describe("plugin timeline projection", () => {
]);
const filtered = projectPluginTimelineItems([source], () => []);
expect(exploded).toMatchObject([
{ source: { id: "thought-1" }, pluginItemId: "thought-1/left" },
{ source: { id: "thought-1" }, pluginItemId: "thought-1/right" },
expect(exploded.map((item) => item.id)).toEqual([
"split/thought-1/left",
"split/thought-1/right",
]);
expect(new Set(exploded.map((item) => item.id)).size).toBe(2);
expect(filtered).toEqual([]);
});
@@ -318,13 +254,13 @@ describe("plugin timeline projection", () => {
expect(projected).toMatchObject([
{
kind: "plugin",
pluginItemId: "assistant-1/text",
id: "genui/assistant-1/text",
timelineCursor: { epoch: "e1", seq: 7 },
turnId: "turn-1",
},
{
kind: "plugin",
pluginItemId: "assistant-1/card",
id: "genui/assistant-1/card",
timelineCursor: { epoch: "e1", seq: 7 },
turnId: "turn-1",
},
@@ -94,9 +94,7 @@ function transformSourceItem(
return transformed.map((pluginItem) => {
const projected: PluginTimelineStreamItem = {
kind: "plugin",
// 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]),
id: `${pluginItem.pluginId}/${pluginItem.id}`,
source: item,
timestamp: item.timestamp,
pluginId: pluginItem.pluginId,
@@ -29,8 +29,7 @@ import {
type HostRuntimeControllerDeps,
type HostRuntimeStorage,
} from "./host-runtime";
import { replicaPayloadBytes } from "./replica-cache/payload-bytes";
import type { ReplicaRow, ReplicaRowSize, ReplicaRowStore } from "./replica-cache/row-store";
import type { ReplicaRow, ReplicaRowStore } from "./replica-cache/row-store";
import { subscriptionFixture } from "./subscription-fixture";
import { readDesktopManagedLocalCredential } from "@/desktop/daemon/local-credential";
@@ -641,12 +640,12 @@ function createMemoryReplicaRowStore(): ReplicaRowStore {
(!acceptedIds || acceptedIds.has(row.id)),
);
},
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);
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);
}
return [...hosts].map(([serverId, hostRows]) => ({ serverId, rows: hostRows }));
},
@@ -1,128 +0,0 @@
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,14 +13,7 @@ import {
} from "@/plugins/client-state/snapshots";
import { ReplicaCache } from ".";
import type { DirectoryCheckpoint } from "@/runtime/replica-cache";
import { replicaPayloadBytes } from "./payload-bytes";
import type {
ReplicaHostIndex,
ReplicaRow,
ReplicaRowChanges,
ReplicaRowSize,
ReplicaRowStore,
} from "./row-store";
import type { ReplicaHostRows, ReplicaRow, ReplicaRowChanges, ReplicaRowStore } from "./row-store";
const SERVER_ID = "cached-host";
@@ -48,8 +41,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 indexes every row or deletes a host, so a test can interleave there. */
beforeReadIndex: (() => Promise<void>) | null = null;
/** Awaited before the store lists every row or deletes a host, so a test can interleave there. */
beforeReadAll: (() => Promise<void>) | null = null;
beforeDeleteHost: (() => Promise<void>) | null = null;
private key(row: Pick<ReplicaRow, "serverId" | "kind" | "id">): string {
@@ -81,13 +74,13 @@ class MemoryStorage implements ReplicaRowStore {
);
}
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);
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);
}
return [...hosts].map(([serverId, rows]) => ({ serverId, rows }));
}
@@ -1150,7 +1143,7 @@ describe("ReplicaCache", () => {
).toEqual(["agent", "checkpoint", "project", "workspace"]);
});
it.each(["beforeReadIndex", "beforeDeleteHost"] as const)(
it.each(["beforeReadAll", "beforeDeleteHost"] as const)(
"stores no checkpoint for a host evicted after its update was queued (%s)",
async (pausePoint) => {
const storage = new MemoryStorage();
+37 -33
View File
@@ -27,14 +27,12 @@ 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";
@@ -871,27 +869,31 @@ function pendingRowKey(key: ReplicaRowKey): string {
return `${key.serverId}\u0000${rowKey(key)}`;
}
// 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>();
// 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>();
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);
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;
}
return size;
return bytes;
}
function sumBytes(rows: Iterable<ReplicaRowSize>): number {
let bytes = 0;
for (const row of rows) bytes += row.bytes;
function rowBytes(row: ReplicaRow): number {
let bytes = rowBytesCache.get(row);
if (bytes === undefined) {
bytes = utf8ByteLength(row.payload);
rowBytesCache.set(row, bytes);
}
return bytes;
}
@@ -978,8 +980,7 @@ function matchesReplicaRead(read: ReplicaRead, row: ReplicaRowKey): boolean {
export class ReplicaCache {
private readonly activeServerIds = new Set<string>();
private readonly activeReads = new Set<ReplicaRead>();
// 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 storedRows = new Map<string, Map<string, ReplicaRow>>();
private readonly hostBytes = new Map<string, number>();
private readonly hostWriteOrder = new Map<string, true>();
private pendingUpserts = new Map<string, StructuredReplicaUpsert>();
@@ -1282,13 +1283,13 @@ export class ReplicaCache {
this.invalidateHostReads(newServerId);
const rows = this.storedRows.get(oldServerId);
if (rows) {
const newRows = this.storedRows.get(newServerId) ?? new Map<string, ReplicaRowSize>();
const newRows = this.storedRows.get(newServerId) ?? new Map<string, ReplicaRow>();
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 = sumBytes(newRows.values());
const bytes = [...newRows.values()].reduce((sum, row) => sum + rowBytes(row), 0);
this.hostBytes.delete(oldServerId);
this.hostBytes.set(newServerId, bytes);
this.totalBytes += bytes;
@@ -1528,17 +1529,17 @@ export class ReplicaCache {
const previous = rows?.get(rowKey(key));
if (previous) {
rows?.delete(rowKey(key));
this.adjustHostBytes(key.serverId, -previous.bytes);
this.adjustHostBytes(key.serverId, -rowBytes(previous));
}
touchedServerIds.add(key.serverId);
}
for (const row of changes.upserts) {
const rows = this.storedRows.get(row.serverId) ?? new Map<string, ReplicaRowSize>();
const rows = this.storedRows.get(row.serverId) ?? new Map<string, ReplicaRow>();
const previous = rows.get(rowKey(row));
const size = rowSize(row);
rows.set(rowKey(row), size);
const previousBytes = previous ? rowBytes(previous) : 0;
rows.set(rowKey(row), row);
this.storedRows.set(row.serverId, rows);
this.adjustHostBytes(row.serverId, size.bytes - (previous?.bytes ?? 0));
this.adjustHostBytes(row.serverId, rowBytes(row) - previousBytes);
touchedServerIds.add(row.serverId);
}
for (const serverId of touchedServerIds) {
@@ -1567,7 +1568,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, ReplicaRowSize>>();
const projectedRows = new Map<string, Map<string, ReplicaRow>>();
const projectedBytes = new Map(this.hostBytes);
for (const serverId of touchedServerIds) {
projectedRows.set(serverId, new Map(this.storedRows.get(serverId)));
@@ -1576,10 +1577,13 @@ export class ReplicaCache {
projectedRows.get(key.serverId)?.delete(rowKey(key));
}
for (const row of changes.upserts) {
projectedRows.get(row.serverId)?.set(rowKey(row), rowSize(row));
projectedRows.get(row.serverId)?.set(rowKey(row), row);
}
for (const [serverId, rows] of projectedRows) {
projectedBytes.set(serverId, sumBytes(rows.values()));
projectedBytes.set(
serverId,
[...rows.values()].reduce((sum, row) => sum + rowBytes(row), 0),
);
}
const writeOrder = [...this.hostWriteOrder.keys()].filter(
@@ -1652,7 +1656,7 @@ export class ReplicaCache {
}
private ensureStoredIndex(): Promise<void> {
this.storedIndexPromise ??= this.rowStore.readIndex().then(async (hosts) => {
this.storedIndexPromise ??= this.rowStore.readAll().then(async (hosts) => {
this.storedRows.clear();
this.hostBytes.clear();
this.hostWriteOrder.clear();
@@ -1663,7 +1667,7 @@ export class ReplicaCache {
continue;
}
const rows = new Map(host.rows.map((row) => [rowKey(row), row]));
const bytes = sumBytes(host.rows);
const bytes = host.rows.reduce((sum, row) => sum + rowBytes(row), 0);
this.storedRows.set(host.serverId, rows);
this.hostBytes.set(host.serverId, bytes);
this.totalBytes += bytes;
@@ -1,15 +0,0 @@
// 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;
}
@@ -1,37 +0,0 @@
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,10 +1,4 @@
import type {
ReplicaHostIndex,
ReplicaRow,
ReplicaRowChanges,
ReplicaRowSize,
ReplicaRowStore,
} from "./row-store";
import type { ReplicaHostRows, ReplicaRow, ReplicaRowChanges, ReplicaRowStore } from "./row-store";
export type SqliteValue = string | number | null;
@@ -40,13 +34,6 @@ interface StoredMeta {
value: string;
}
interface StoredRowSize {
server_id: string;
kind: ReplicaRow["kind"];
id: string;
bytes: number;
}
interface StoredRow {
server_id: string;
kind: ReplicaRow["kind"];
@@ -102,20 +89,18 @@ export function createSqliteReplicaRowStore(
}
}
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`,
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",
);
const hosts = new Map<string, ReplicaRowSize[]>();
const hosts = new Map<string, ReplicaRow[]>();
for (const storedRow of storedRows) {
const rows = hosts.get(storedRow.server_id) ?? [];
rows.push({
serverId: storedRow.server_id,
kind: storedRow.kind,
id: storedRow.id,
bytes: storedRow.bytes,
payload: storedRow.payload,
});
hosts.set(storedRow.server_id, rows);
}
@@ -184,5 +169,5 @@ export function createSqliteReplicaRowStore(
await getConnection().run("DELETE FROM rows");
}
return { open, read, readIndex, apply, deleteHost, renameHost, clear };
return { open, read, readAll, apply, deleteHost, renameHost, clear };
}
@@ -8,23 +8,6 @@ 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 };
}
@@ -44,7 +27,7 @@ export function runReplicaRowStoreContract(
});
it("reads an empty store", async () => {
expect(await readEveryRow(store)).toEqual([]);
expect(await store.readAll()).toEqual([]);
});
it("round-trips opaque payloads grouped by server", async () => {
@@ -57,7 +40,7 @@ export function runReplicaRowStoreContract(
deletes: [],
});
expect(await readEveryRow(store)).toEqual([
expect(await store.readAll()).toEqual([
{
serverId: "server-a",
rows: [
@@ -98,7 +81,7 @@ export function runReplicaRowStoreContract(
deletes: [],
});
expect(await readEveryRow(store)).toEqual([
expect(await store.readAll()).toEqual([
{
serverId: "server-a",
rows: [row("server-a", "agent", "agent-1", "new")],
@@ -119,7 +102,7 @@ export function runReplicaRowStoreContract(
deletes: [{ serverId: "server-a", kind: "agent", id: "same-id" }],
});
expect(await readEveryRow(store)).toEqual([
expect(await store.readAll()).toEqual([
{
serverId: "server-a",
rows: [row("server-a", "workspace", "same-id", "workspace")],
@@ -139,7 +122,7 @@ export function runReplicaRowStoreContract(
deletes: [],
}),
).rejects.toBeInstanceOf(Error);
expect(await readEveryRow(store)).toEqual([]);
expect(await store.readAll()).toEqual([]);
});
it("deletes every row belonging to one host", async () => {
@@ -154,7 +137,7 @@ export function runReplicaRowStoreContract(
await store.deleteHost("server-a");
expect(await readEveryRow(store)).toEqual([
expect(await store.readAll()).toEqual([
{ serverId: "server-b", rows: [row("server-b", "agent", "agent-2", "b")] },
]);
});
@@ -172,7 +155,7 @@ export function runReplicaRowStoreContract(
await store.renameHost("temporary", "canonical");
expect(await readEveryRow(store)).toEqual([
expect(await store.readAll()).toEqual([
{
serverId: "canonical",
rows: [
@@ -195,67 +178,7 @@ export function runReplicaRowStoreContract(
await store.clear();
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}'),
]);
expect(await store.readAll()).toEqual([]);
});
it("wipes cached rows when the schema version changes on open", async () => {
@@ -266,7 +189,7 @@ export function runReplicaRowStoreContract(
const upgradedStore = await harness.openWithSchemaVersion(2);
expect(await readEveryRow(upgradedStore)).toEqual([]);
expect(await upgradedStore.readAll()).toEqual([]);
});
});
}
@@ -1,6 +1,45 @@
import { DatabaseSync, type SQLInputValue } from "node:sqlite";
import { runReplicaRowStoreContract } from "./row-store.contract";
import { createSqliteReplicaRowStore } from "./row-store-sqlite";
import { createNodeSqliteDriver } from "./row-store-sqlite.test-driver";
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();
},
};
}
runReplicaRowStoreContract("SQLite", async () => {
const driver = createNodeSqliteDriver();
@@ -9,12 +9,11 @@ import {
} from "./row-store-sqlite";
export type {
ReplicaHostIndex,
ReplicaHostRows,
ReplicaRow,
ReplicaRowChanges,
ReplicaRowKey,
ReplicaRowKind,
ReplicaRowSize,
ReplicaRowStore,
} from "./row-store";
export { REPLICA_ROW_STORE_SCHEMA_VERSION, REPLICA_SINGLETON_ROW_ID } from "./row-store-schema";
@@ -23,15 +23,9 @@ export interface ReplicaRowApplyOptions {
directoryBaselines?: ReadonlySet<string>;
}
// 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 {
export interface ReplicaHostRows {
serverId: string;
rows: ReplicaRowSize[];
rows: ReplicaRow[];
}
export interface ReplicaRowStore {
@@ -41,8 +35,7 @@ export interface ReplicaRowStore {
kinds: readonly ReplicaRowKind[],
ids?: readonly string[],
): Promise<ReplicaRow[]>;
// Every stored row's key and payload size, grouped by host, read without loading payloads.
readIndex(): Promise<ReplicaHostIndex[]>;
readAll(): Promise<ReplicaHostRows[]>;
// 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,29 +49,3 @@ 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,62 +1,38 @@
import { replicaPayloadBytes } from "./payload-bytes";
import type {
ReplicaHostIndex,
ReplicaHostRows,
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 {
ReplicaHostIndex,
ReplicaHostRows,
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 = 2;
const DATABASE_VERSION = 1;
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 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 {
function withoutDirectoryRevision(row: IndexedDbReplicaRow): ReplicaRow {
if (row.directoryRevision === undefined) return row;
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;
@@ -108,14 +84,8 @@ async function openDatabase(databaseName: string): Promise<IDBDatabase> {
return new Promise((resolve, reject) => {
const request = indexedDB.open(databaseName, DATABASE_VERSION);
request.addEventListener("upgradeneeded", () => {
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(ROWS_STORE)) {
request.result.createObjectStore(ROWS_STORE, { keyPath: ["serverId", "kind", "id"] });
}
if (!request.result.objectStoreNames.contains(META_STORE)) {
request.result.createObjectStore(META_STORE);
@@ -174,34 +144,17 @@ export function createIndexedDbReplicaRowStore(
}
}
async function readIndex(): Promise<ReplicaHostIndex[]> {
async function readAll(): Promise<ReplicaHostRows[]> {
const transaction = getDatabase().transaction(ROWS_STORE, "readonly");
const completion = transactionComplete(transaction);
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")),
);
});
const rows = await requestResult<IndexedDbReplicaRow[]>(
transaction.objectStore(ROWS_STORE).getAll(),
);
await completion;
const hosts = new Map<string, ReplicaRowSize[]>();
for (const row of rows.sort(compareRowKeys)) {
const hosts = new Map<string, ReplicaRow[]>();
for (const row of rows) {
const hostRows = hosts.get(row.serverId) ?? [];
hostRows.push(row);
hostRows.push(withoutDirectoryRevision(row));
hosts.set(row.serverId, hostRows);
}
return Array.from(hosts, ([serverId, hostRows]) => ({ serverId, rows: hostRows }));
@@ -239,7 +192,7 @@ export function createIndexedDbReplicaRowStore(
observeDirectoryRevision(serverId, checkpoint?.directoryRevision);
}
return rows
.map(toReplicaRow)
.map(withoutDirectoryRevision)
.sort((left, right) =>
left.kind === right.kind
? left.id.localeCompare(right.id)
@@ -269,7 +222,7 @@ export function createIndexedDbReplicaRowStore(
for (const row of accepted.upserts) {
const directoryRevision =
row.kind === "checkpoint" ? nextRevisions.get(row.serverId) : undefined;
await requestResult(rows.put(toStoredRow(row, directoryRevision)));
await requestResult(rows.put(directoryRevision ? { ...row, directoryRevision } : row));
}
});
for (const [serverId, revision] of nextRevisions) observeDirectoryRevision(serverId, revision);
@@ -355,7 +308,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<IndexedDbReplicaRow[]>(rows.getAll(range));
const oldRows = await requestResult<ReplicaRow[]>(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]));
@@ -374,7 +327,7 @@ export function createIndexedDbReplicaRowStore(
});
}
return { open, read, readIndex, apply, deleteHost, renameHost, clear };
return { open, read, readAll, apply, deleteHost, renameHost, clear };
}
export function createReplicaRowStore(): ReplicaRowStore {
@@ -1,131 +0,0 @@
/**
* @vitest-environment jsdom
*/
import { act } from "@testing-library/react";
import React from "react";
import { createRoot, type Root } from "react-dom/client";
import { Text, View } from "react-native";
import { afterEach, describe, expect, it, vi } from "vitest";
import { definePanel, registerPanel } from "@/panels/panel-registry";
import { buildWorkspacePaneContentModel } from "@/screens/workspace/workspace-pane-content";
import { WorkspacePanelHost } from "@/screens/workspace/workspace-panel-host";
import type { WorkspaceTabDescriptor } from "@/screens/workspace/workspace-tabs-types";
let panelFails = true;
function FailingPanel() {
if (panelFails) throw new Error("Changes exploded");
return <Text>Changes recovered</Text>;
}
function HealthyPanel() {
return <Text>Draft panel</Text>;
}
// The workspace screen registers the real panels; these stand in for the two kinds the test opens.
registerPanel(
definePanel("agent", {
component: FailingPanel,
useDescriptor: () => {
throw new Error("The test panel has no descriptor");
},
}),
);
registerPanel(
definePanel("draft", {
component: HealthyPanel,
useDescriptor: () => {
throw new Error("The test panel has no descriptor");
},
}),
);
const failingTab: WorkspaceTabDescriptor = {
key: "agent_agent-a",
tabId: "agent_agent-a",
kind: "agent",
target: { kind: "agent", agentId: "agent-a" },
};
const healthyTab: WorkspaceTabDescriptor = {
key: "draft_draft-a",
tabId: "draft_draft-a",
kind: "draft",
target: { kind: "draft", draftId: "draft-a" },
};
function buildContent({ tab }: { paneId: string; tab: WorkspaceTabDescriptor }) {
return buildWorkspacePaneContentModel({
tab,
normalizedServerId: "server-a",
normalizedWorkspaceId: "workspace-a",
host: "main",
onOpenTab: vi.fn(),
onOpenPreferredTarget: vi.fn(),
onOpenTargetToSide: vi.fn(),
onCloseCurrentTab: vi.fn(),
onRetargetCurrentTab: vi.fn(),
onSetCurrentTabState: vi.fn(),
onOpenWorkspaceFile: vi.fn(),
onOpenImportSheet: vi.fn(),
});
}
function Workspace({ activeTabId }: { activeTabId: string }) {
return (
<View>
<Text>Sidebar</Text>
<WorkspacePanelHost
paneId="pane-a"
tabs={[failingTab, healthyTab]}
activeTabId={activeTabId}
normalizedServerId="server-a"
normalizedWorkspaceId="workspace-a"
isWorkspaceFocused
isPaneFocused
buildPaneContentModel={buildContent}
/>
</View>
);
}
function byTestId(container: HTMLElement, testID: string): HTMLElement | null {
return container.querySelector(`[data-testid="${testID}"]`);
}
describe("WorkspacePanelHost", () => {
let root: Root | null = null;
let container: HTMLElement | null = null;
afterEach(() => {
if (root) act(() => root?.unmount());
root = null;
container?.remove();
container = null;
panelFails = true;
vi.restoreAllMocks();
});
it("keeps a panel's render error inside that panel and retries it", () => {
vi.spyOn(console, "error").mockImplementation(() => undefined);
vi.spyOn(console, "warn").mockImplementation(() => undefined);
container = document.createElement("div");
document.body.appendChild(container);
root = createRoot(container);
act(() => root?.render(<Workspace activeTabId={failingTab.tabId} />));
expect(container.textContent).toContain("Sidebar");
expect(byTestId(container, "panel-render-error")?.textContent).toContain("Changes exploded");
act(() => root?.render(<Workspace activeTabId={healthyTab.tabId} />));
expect(container.textContent).toContain("Draft panel");
panelFails = false;
act(() => root?.render(<Workspace activeTabId={failingTab.tabId} />));
const retry = byTestId(container, "panel-render-error-retry");
expect(retry).not.toBeNull();
act(() => retry?.click());
expect(byTestId(container, "panel-render-error")).toBeNull();
expect(container.textContent).toContain("Changes recovered");
expect(container.textContent).toContain("Sidebar");
});
});
@@ -1,11 +1,5 @@
import { memo, useCallback, useEffect, useMemo, useRef } from "react";
import { useTranslation } from "react-i18next";
import { View } from "react-native";
import { StyleSheet } from "react-native-unistyles";
import { RenderErrorBoundary } from "@/components/render-error-boundary";
import { RetainedPanel } from "@/components/retained-panel";
import { Alert } from "@/components/ui/alert";
import { Button } from "@/components/ui/button";
import { useModifiedPanelTabIds } from "@/panels/panel-instance-attributes";
import {
WorkspacePaneContent,
@@ -58,44 +52,17 @@ const MountedTab = memo(function MountedTab({
return (
<RenderProfile id={`DesktopMountedTab:${tab.kind}:${tab.tabId}`}>
<RetainedPanel active={visible}>
<RenderErrorBoundary
resetKeys={[tab]}
onError={logPanelRenderError}
renderError={renderPanelError}
>
<WorkspacePaneContent
content={content}
isWorkspaceFocused={isWorkspaceFocused}
isPaneFocused={interactive}
onFocusPane={onFocusPane ? handleFocusPane : undefined}
/>
</RenderErrorBoundary>
<WorkspacePaneContent
content={content}
isWorkspaceFocused={isWorkspaceFocused}
isPaneFocused={interactive}
onFocusPane={onFocusPane ? handleFocusPane : undefined}
/>
</RetainedPanel>
</RenderProfile>
);
});
function logPanelRenderError(error: unknown, componentStack: string | null | undefined): void {
console.error("[WorkspacePanel] Render failed", error, componentStack);
}
function renderPanelError(error: string, retry: () => void) {
return <PanelRenderError error={error} onRetry={retry} />;
}
function PanelRenderError({ error, onRetry }: { error: string; onRetry: () => void }) {
const { t } = useTranslation();
return (
<View style={styles.renderError} testID="panel-render-error">
<Alert variant="error" title={t("panels.renderError.title")} description={error}>
<Button variant="outline" size="sm" onPress={onRetry} testID="panel-render-error-retry">
{t("common.actions.retry")}
</Button>
</Alert>
</View>
);
}
function useStableTabs(tabs: WorkspaceTabDescriptor[]) {
const cacheRef = useRef(new Map<string, WorkspaceTabDescriptor>());
const stableTabs = useMemo(() => {
@@ -169,9 +136,3 @@ export function WorkspacePanelHost({
);
});
}
const styles = StyleSheet.create((theme) => ({
renderError: {
padding: theme.spacing[4],
},
}));
+1 -14
View File
@@ -10,7 +10,7 @@
* A ratio keeps the step equally visible on every base; a lightness delta disappears near black.
* The numbers come from the default themes: Paseo dark and Light.
*/
import { contrastRatio, mixHexColors, stepContrast, translucentStep } from "@/utils/color";
import { contrastRatio, mixHexColors, stepContrast } from "@/utils/color";
export type ColorScheme = "light" | "dark";
@@ -19,11 +19,6 @@ const SURFACE_STATE_STEPS = {
light: { hover: 1.15, selected: 1.35 },
} as const;
// The 1px line under each open folder in a tree, measured on the sidebar. It starts above the
// selected fill so a hovered row does not swallow it. Light needs the larger step to read as the
// same weight.
const TREE_GUIDE_STEPS = { dark: 1.35, light: 1.47 } as const;
// Fills for chips, bubbles, tracks and secondary buttons, as `surface3` and `surface4`.
const NEUTRAL_FILL_STEPS = {
dark: { surface3: 1.8, surface4: 2.5 },
@@ -58,14 +53,6 @@ export function deriveSurfaceStates(
};
}
/**
* Translucent, because trees also sit on the page, workspace panes and sheets. A solid color picked
* for the sidebar fades on those.
*/
export function deriveTreeGuide(sidebar: string, foreground: string, scheme: ColorScheme): string {
return translucentStep(sidebar, foreground, TREE_GUIDE_STEPS[scheme]);
}
/** The neutral fills that sit on the page background. */
export function deriveNeutralFills(
background: string,
+1 -28
View File
@@ -1,7 +1,7 @@
import { describe, expect, it } from "vitest";
import type { PluginThemeContribution } from "@getpaseo/plugin";
import { buildPluginTheme } from "@/plugins/themes";
import { contrastRatio, mixHexColors } from "@/utils/color";
import { contrastRatio } from "@/utils/color";
import { THEME_OPTIONS, type Theme } from "./theme";
// Palettes of the plugin themes users run into: Catppuccin (the e2e fixture) and
@@ -92,21 +92,10 @@ const SELECTED_TEXT_FLOOR = 2.5;
const NEUTRAL_FILL_STEP = 1.2;
const NEUTRAL_FILL_TEXT_FLOOR = 3;
const TERTIARY_TEXT_FLOOR = 2.5;
// A tree guide is one quiet line in every theme. Trees also sit on the page, a workspace pane and
// a hovered row, and the line has to stay a line on all of them.
const TREE_GUIDE_STEP = { dark: 1.35, light: 1.47 };
const TREE_GUIDE_FLOOR = 1.18;
// The bright hues are dim on a cream or white background by design; the floor only has to catch a
// color that disappears.
const TERMINAL_COLOR_FLOOR = 1.5;
/** The color a translucent `rgba()` token shows once painted over `surface`. */
function paintedOver(surface: string, token: string): string {
const [r, g, b, alpha] = (token.match(/[\d.]+/g) ?? []).map(Number);
const ink = `#${[r, g, b].map((channel) => channel.toString(16).padStart(2, "0")).join("")}`;
return mixHexColors(surface, ink, alpha);
}
it("keeps Solarized Dark's selected workspace timestamp readable", () => {
const { colors } = buildPluginTheme(SOLARIZED_DARK);
expect(
@@ -129,22 +118,6 @@ describe.each(themes)("$name", ({ theme }) => {
).toBeGreaterThanOrEqual(SELECTED_OVER_HOVER_STEP);
});
it("draws tree guides at the same strength on the sidebar", () => {
const painted = paintedOver(colors.surfaceSidebar, colors.treeGuide);
expect(contrastRatio(colors.surfaceSidebar, painted)).toBeCloseTo(
TREE_GUIDE_STEP[theme.colorScheme],
1,
);
});
it.each(["surfaceSidebarHover", "surface0", "surfaceWorkspace"] as const)(
"keeps tree guides visible on %s",
(surface) => {
const painted = paintedOver(colors[surface], colors.treeGuide);
expect(contrastRatio(colors[surface], painted)).toBeGreaterThanOrEqual(TREE_GUIDE_FLOOR);
},
);
it("keeps the selected row's title readable", () => {
const onSidebar = contrastRatio(colors.foreground, colors.surfaceSidebar);
const onSelected = contrastRatio(colors.foreground, colors.surfaceSidebarSelected);
+1 -3
View File
@@ -1,7 +1,7 @@
import { Platform, type ViewStyle } from "react-native";
import { isWeb } from "@/constants/platform";
import { darkHighlightColors, lightHighlightColors } from "@getpaseo/highlight";
import { deriveSurfaceStates, deriveTreeGuide } from "./derive-colors";
import { deriveSurfaceStates } from "./derive-colors";
export const baseColors = {
// Base colors
@@ -276,7 +276,6 @@ export function buildLightSemanticColors(tint: LightThemeConfig) {
surfaceSidebarSelected: tint.surfaceSidebarSelected ?? sidebarStates.selected,
foregroundSidebarHover: tint.foregroundSidebarHover ?? tint.foregroundExtraMuted,
foregroundSidebarSelected: tint.foregroundSidebarSelected ?? tint.foregroundExtraMuted,
treeGuide: deriveTreeGuide(tint.surfaceSidebar, tint.foreground, "light"),
surfaceWorkspace: tint.surface0,
interactionHighlight: "rgba(0, 0, 0, 0.06)",
@@ -405,7 +404,6 @@ export function buildDarkSemanticColors(tint: DarkThemeConfig) {
surfaceSidebarSelected: tint.surfaceSidebarSelected ?? sidebarStates.selected,
foregroundSidebarHover: tint.foregroundSidebarHover ?? tint.foregroundExtraMuted,
foregroundSidebarSelected: tint.foregroundSidebarSelected ?? tint.foregroundExtraMuted,
treeGuide: deriveTreeGuide(tint.surfaceSidebar, foreground, "dark"),
surfaceWorkspace: tint.surface1,
interactionHighlight: "rgba(255, 255, 255, 0.08)",
@@ -762,29 +762,6 @@ 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,10 +577,6 @@ 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;
-16
View File
@@ -159,22 +159,6 @@ export function stepContrast(hex: string, toward: string, ratio: number): string
return `#${channels.join("")}`;
}
/**
* `ink` made translucent enough to sit at `ratio` WCAG contrast from `surface` once painted on it.
* Unlike `stepContrast`, the result follows whatever it is painted over, so it keeps its weight on
* neighbouring surfaces too.
*/
export function translucentStep(surface: string, ink: string, ratio: number): string {
let low = 0;
let high = 1;
for (let step = 0; step < 8; step += 1) {
const middle = (low + high) / 2;
if (contrastRatio(surface, mixHexColors(surface, ink, middle)) < ratio) low = middle;
else high = middle;
}
return hexColorWithAlpha(mixHexColors(ink, ink, 0), Number(high.toFixed(3)));
}
/** Blends `hex` toward `toward` by `amount` (0 keeps `hex`, 1 is `toward`) in sRGB. */
export function mixHexColors(hex: string, toward: string, amount: number): string {
const from = requireRgb(hex);
+2 -19
View File
@@ -2,7 +2,6 @@ import type { Command } from "commander";
import type { AgentPermissionRequest } from "@getpaseo/protocol/agent-types";
import type { AgentSnapshotPayload } from "@getpaseo/protocol/messages";
import { connectToDaemon } from "../../utils/client.js";
import { fetchAllAgents, type AgentDirectoryClient } from "../../utils/agent-directory.js";
import type { CommandOptions, ListResult, OutputSchema, CommandError } from "../../output/index.js";
/** Permission list item for display */
@@ -57,23 +56,6 @@ export function listPendingPermissions(agents: AgentSnapshotPayload[]): PermitLs
};
}
export interface PermitAgentsClient extends AgentDirectoryClient {
supportsBackgroundWorkspaces(): boolean;
}
/**
* Read every agent that can hold a pending permission: all pages, and background agents too,
* since unattended workers are the ones most likely to be waiting on a prompt.
*/
export function fetchPermitAgents(client: PermitAgentsClient): Promise<AgentSnapshotPayload[]> {
return fetchAllAgents(client, {
filter: {
includeArchived: true,
...(client.supportsBackgroundWorkspaces() ? { includeBackground: true } : {}),
},
});
}
export interface PermitLsOptions extends CommandOptions {
host?: string;
}
@@ -85,7 +67,8 @@ export async function runLsCommand(
const client = await connectToDaemon({ target: options.daemonTarget });
try {
const agents = await fetchPermitAgents(client);
const agentsPayload = await client.fetchAgents({ filter: { includeArchived: true } });
const agents = agentsPayload.entries.map((entry) => entry.agent);
await client.close();
return listPendingPermissions(agents);
@@ -3,7 +3,7 @@ import type { AgentSnapshotPayload } from "@getpaseo/protocol/messages";
import { describe, expect, it } from "vitest";
import { render } from "../../output/render.js";
import { permitResponseSchema, toPermissionResponseItem } from "./allow.js";
import { fetchPermitAgents, listPendingPermissions } from "./ls.js";
import { listPendingPermissions } from "./ls.js";
const agentId = "2d85f428-fdaf-4d98-906f-c583de2b805f";
@@ -43,45 +43,3 @@ describe("permit allow and deny output", () => {
expect(answered.map((item) => item.requestId)).toEqual([writeRequest.id]);
});
});
describe("permit ls agent directory read", () => {
function fakeClient(pages: AgentSnapshotPayload[][], supportsBackground: boolean) {
const calls: unknown[] = [];
return {
calls,
supportsBackgroundWorkspaces: () => supportsBackground,
async fetchAgents(options?: unknown) {
calls.push(options);
const index = calls.length - 1;
return {
entries: (pages[index] ?? []).map((entry) => ({ agent: entry })),
pageInfo: { nextCursor: index + 1 < pages.length ? `cursor-${index + 1}` : null },
};
},
};
}
it("includes background agents and reads past the first page", async () => {
const backgroundAgent = {
id: "7b0e3f52-9d1c-4f0a-8a59-0f1d2e3c4b5a",
pendingPermissions: [writeRequest],
} as AgentSnapshotPayload;
const client = fakeClient([[{ id: agentId } as AgentSnapshotPayload], [backgroundAgent]], true);
const result = listPendingPermissions(await fetchPermitAgents(client));
expect(result.data.map((item) => item.agentId)).toEqual([backgroundAgent.id]);
expect(client.calls).toEqual([
expect.objectContaining({ filter: { includeArchived: true, includeBackground: true } }),
expect.objectContaining({ page: expect.objectContaining({ cursor: "cursor-1" }) }),
]);
});
it("leaves background out on hosts without background workspaces", async () => {
const client = fakeClient([[agent]], false);
await fetchPermitAgents(client);
expect(client.calls).toEqual([expect.objectContaining({ filter: { includeArchived: true } })]);
});
});
@@ -4508,6 +4508,70 @@ describe("ClaudeAgentSession context window usage", () => {
}
});
test("settles the first tool call after a compaction whose summary is synthetic", async () => {
// Claude Code 2.1.330 sends the compaction summary as a user message marked isSynthetic
// (seen live after /compact), so it is skipped before it can consume the compaction state.
const session = await createSessionForTurns([
[
createCompactingStatus(),
createCompactBoundary({ compact_metadata: { trigger: "auto", pre_tokens: 167_000 } }),
{
type: "user",
parent_tool_use_id: null,
isSynthetic: true,
message: {
role: "user",
content: "This session is being continued from a previous conversation.",
},
uuid: "compact-summary-1",
session_id: "session-1",
},
{
type: "assistant",
parent_tool_use_id: null,
message: {
role: "assistant",
content: [
{
type: "tool_use",
id: "toolu-after-compact",
name: "Bash",
input: { command: "ls" },
},
],
},
uuid: "assistant-after-compact",
session_id: "session-1",
},
{
type: "user",
parent_tool_use_id: null,
message: {
role: "user",
content: [{ type: "tool_result", tool_use_id: "toolu-after-compact", content: "a.go" }],
},
uuid: "tool-result-after-compact",
session_id: "session-1",
},
createSuccessResult(),
],
]);
try {
const events = await collectStreamEvents(session, "keep working");
const statuses = events.flatMap((event) =>
event.type === "timeline" &&
event.item.type === "tool_call" &&
event.item.callId === "toolu-after-compact"
? [event.item.status]
: [],
);
expect(statuses).toEqual(["running", "completed"]);
} finally {
await session.close();
}
});
test("reports the plan mode Claude enters on its own with EnterPlanMode", async () => {
// Claude Code announces a mode it switched to itself as a status message
// carrying the new permissionMode, right after the EnterPlanMode tool call.
@@ -2698,7 +2698,6 @@ class ClaudeAgentSession implements AgentSession {
private lastOptionsModel: string | null = null;
private lastRuntimeModel: string | null = null;
private readonly resultMeter = new ClaudeResultMeter();
private compacting = false;
private compactionMarkerOpen = false;
private queryPumpPromise: Promise<void> | null = null;
private queryRestartNeeded = false;
@@ -5468,7 +5467,6 @@ class ClaudeAgentSession implements AgentSession {
}
const status = toObjectRecord(message)?.status;
if (status === "compacting") {
this.compacting = true;
// Claude Code repeats this status every 30 seconds until the compaction
// finishes. Each repeat used to open its own marker, and the app only ever
// resolves one of them, so the rest stayed on "Compacting..." forever.
@@ -5554,11 +5552,10 @@ class ClaudeAgentSession implements AgentSession {
message: Extract<SDKMessage, { type: "user" }>,
events: AgentStreamEvent[],
): Promise<void> {
if (isSyntheticUserEntry(message)) {
return;
}
if (this.compacting) {
this.compacting = false;
// The compaction summary is skipped by what it is, never by being the next user message:
// Claude marks it synthetic (isCompactSummary in older streams), and a position-based skip
// swallowed the first tool result after every compaction instead.
if (isSyntheticUserEntry(message) || toObjectRecord(message)?.isCompactSummary === true) {
return;
}
const messageId =
@@ -2015,30 +2015,6 @@ describe("PiRpcAgentSession", () => {
expect(pi.latestSession().closeCalls).toBe(1);
});
test("reports a rejected Pi capture prompt without an unhandled rejection", async () => {
const pi = new FakePi();
const session = await createClient(pi).resumeSession(
{
provider: "pi",
sessionId: "pi-session-1",
nativeHandle: "/tmp/native-pi-session",
metadata: { cwd: tmpdir() },
},
{},
undefined,
{ purpose: "history" },
);
onTestFinished(() => session.close());
const runtime = pi.latestSession();
const error = new Error("Capture prompt rejected");
runtime.holdNextPrompt();
const assertion = expect(session.streamHistory().next()).rejects.toThrow(error);
await runtime.failHeldPrompt(error);
await assertion;
expect(runtime.closeCalls).toBe(1);
});
test("keeps an interactive Pi runtime open after replaying history", async () => {
const pi = new FakePi();
const session = await createClient(pi).resumeSession({
@@ -2017,16 +2017,13 @@ export class PiRpcAgentSession implements AgentSession {
}
private waitForExtensionResult(requestId: string): Promise<unknown> {
const result = new Promise<unknown>((resolve, reject) => {
return new Promise((resolve, reject) => {
const timer = setTimeout(() => {
this.pendingExtensionResults.delete(requestId);
reject(new Error(`Pi extension result timed out for request ${requestId}`));
}, this.extensionTimeoutMs);
this.pendingExtensionResults.set(requestId, { resolve, reject, timer });
});
// The prompt can fail before the caller awaits the extension result.
void result.catch(() => undefined);
return result;
}
private resolveExtensionResult(requestId: string, result: unknown): void {
@@ -2672,19 +2672,11 @@ it.each([false, true])(
process.stdout.write(Array.from({ length: count }, nextRow).join(""));
}
process.stdout.write("READY\\r\\n");
// A PTY can split one input write across reads (ConPTY does on Windows),
// so match commands against everything read so far, not one chunk.
let input = "";
process.stdin.on("data", data => {
input += data.toString();
if (input.includes("BURST")) {
input = "";
if(data.toString().includes("BURST")) {
for (let i = 0; i < 4000; i++) process.stdout.write(nextRow());
process.stdout.write("BURST-DONE\\r\\n");
} else if (input.includes("AFTER-CATCH-UP")) {
input = "";
process.stdout.write("ECHO:AFTER-CATCH-UP\\r\\n");
}
} else process.stdout.write("ECHO:" + data.toString() + "\\r\\n");
});
setInterval(()=>{},1000);
`),