Compare commits

...
Author SHA1 Message Date
JIHUN LEEandClaude Opus 5.5 576d0320c8 Keep Android text at the window's density on Samsung DeX (#9995)
React Native 0.86 converts between px and dp with the density of the
phone's built-in display, while Fabric lays out at the window's density.
In a DeX window (240 dpi on a 360 dpi phone) every text box came out at
two thirds of the height its text needed, so the text was clipped.

Backport the rule from react/react-native#59087: right after React
Native reads the display (when it creates the root view and on each
configuration change), restore the window's density and keep only the
display's size. Remove once the app runs React Native 0.89 or later
with useWindowDensityForDisplayMetricsAndroid on.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 21:08:05 +00:00
paseo-bot[bot]andClaude Opus 5.5 c8e3d67e29 Wait for each plugin content subscription id before checking its release (#10012)
The plugin-buttons journey reads the details' event subscription id to
check that closing, crashing and disabling the content releases it. The
id arrives with the daemon's subscription response, after the details
render. The first open already waited for it; the reopens read it as
soon as the cached summary showed, so the id could still be empty and
the release poll then waited for an id that never exists.

Every read now waits for a non-empty id.

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 18:01:24 +00:00
95f2c7d16a Keep a Claude agent's process and background work when its effort level changes (#10008)
Changing the thinking level of a running Claude agent marked its query for a
restart. The next turn, mode change or model change then retired the Claude
process, which ended every background shell, workflow and subagent it ran with
"connection lost".

A move between two effort levels now goes to the running query through
applyFlagSettings({ effortLevel }), as Fast mode already does, and marks no
restart. Switching thinking off, to ultracode or back to the default still
restarts, because those change how the query is launched. If the running
process does not take the change, the old restart path runs, so the change is
never lost.


Row: app-built-from-one-set
Paseo: c6210e21-fc13-4dfa-adfc-43a050c7d75a

Co-authored-by: gilad-rubin <6134299+gilad-rubin@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 16:57:22 +00:00
14 changed files with 358 additions and 11 deletions
+8
View File
@@ -121,6 +121,14 @@ from `packages/app/android`:
These check terminal arrow ownership, held-key repeats and modifiers, and ordinary text-field editing.
Run the display density regression tests the same way:
```bash
./gradlew :paseo-display-metrics:connectedDebugAndroidTest --no-daemon --max-workers=2 -Dorg.gradle.parallel=false
```
These check that React Native sizes text at the window's density when the window is on another display, such as Samsung DeX.
### Diagnostic logs without ADB
In a dogfood build, open Android's Files app → Downloads → **Paseo diagnostics** and share all
+2
View File
@@ -7,6 +7,7 @@ const withAndroidProfileable = require("./plugins/with-android-profileable");
const withFdroidAutolinking = require("./plugins/with-fdroid-autolinking");
const withPasteInput = require("./plugins/with-paste-input");
const withAndroidScroll = require("./modules/paseo-scroll/app.plugin");
const withAndroidDisplayMetrics = require("./modules/paseo-display-metrics/app.plugin");
const { getNativeReleaseVersion } = require("./native-release-version");
const appVariant = process.env.APP_VARIANT ?? "production";
const isFdroidBuild = process.env.PASEO_FDROID_BUILD === "1";
@@ -146,6 +147,7 @@ export default {
"expo-router",
withPasteInput,
withAndroidScroll,
withAndroidDisplayMetrics,
[withAndroidAsyncStorageSize, 64],
...buildProfile.cameraPlugins,
withAndroidOptionalCamera,
@@ -198,6 +198,14 @@ async function expectDetails(page: Page) {
await expect(page.getByText("All systems operational", { exact: true })).toBeInViewport();
}
// The details render before the daemon answers their event subscription, and reopened
// details show the cached summary at once, so wait for the subscription id to arrive.
async function readContentObservation(page: Page): Promise<string> {
const observation = page.getByLabel("Content observation", { exact: true });
await expect(observation).not.toHaveText("");
return (await observation.textContent())!;
}
function workspaceMenuRow(page: Page, title: string): Locator {
return compactWorkspaceMenu(page).getByRole("menuitem", { name: title, exact: true });
}
@@ -354,14 +362,12 @@ export async function withButtonShowcase(
test.step("closing and crashing content release its owner while sibling buttons and app remain live", async () => {
await press(page, "Header status");
await expectDetails(page);
const observation = page.getByLabel("Content observation", { exact: true });
await expect(observation).not.toHaveText("");
const first = (await observation.textContent())!;
const first = await readContentObservation(page);
await press(page, "Close deployment details");
await expect.poll(() => released.has(first)).toBe(true);
await press(page, "Composer status");
await expectDetails(page);
const second = (await observation.textContent())!;
const second = await readContentObservation(page);
expect(second).not.toBe(first);
await workspace.client.renameProject(workspace.projectId, "Observer control");
await expect(page.getByText("Observed updates: 1", { exact: true })).toBeVisible();
@@ -373,7 +379,7 @@ export async function withButtonShowcase(
await page.keyboard.press("Escape");
await press(page, "Header status");
await expectDetails(page);
const recovered = (await observation.textContent())!;
const recovered = await readContentObservation(page);
expect([first, second]).not.toContain(recovered);
await showcase.setTitle("Healthy app after button failure");
await expect(page.getByTestId("workspace-header-title")).toHaveText(
@@ -687,9 +693,7 @@ export async function withButtonShowcase(
page,
page.getByRole("button", { name: "Close deployment details", exact: true }),
);
const observation = page.getByLabel("Content observation", { exact: true });
await expect(observation).not.toHaveText("");
const owner = (await observation.textContent())!;
const owner = await readContentObservation(page);
await showcase.disable();
await expect.poll(() => released.has(owner)).toBe(true);
await expect(
@@ -0,0 +1,2 @@
/android/.cxx/
/android/build/
@@ -0,0 +1,23 @@
apply plugin: 'com.android.library'
group = 'sh.paseo.displaymetrics'
version = '0.1.0'
def expoModulesCorePlugin = new File(project(":expo-modules-core").projectDir.absolutePath, "ExpoModulesCorePlugin.gradle")
apply from: expoModulesCorePlugin
applyKotlinExpoModulesCorePlugin()
useCoreDependencies()
useDefaultAndroidSdkVersions()
android {
namespace "sh.paseo.displaymetrics"
defaultConfig {
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
}
dependencies {
implementation "com.facebook.react:react-android"
androidTestImplementation 'androidx.test:runner:1.6.2'
androidTestImplementation 'androidx.test.ext:junit:1.2.1'
}
@@ -0,0 +1,86 @@
package sh.paseo.displaymetrics
import android.util.DisplayMetrics
import android.util.TypedValue
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.platform.app.InstrumentationRegistry
import com.facebook.react.uimanager.DisplayMetricsHolder
import com.facebook.react.uimanager.PixelUtil
import org.junit.After
import org.junit.Assert.assertEquals
import org.junit.Assert.assertSame
import org.junit.Assert.assertThrows
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
class PaseoDisplayMetricsTest {
private lateinit var display: DisplayMetrics
@Before
fun readDisplayLikeReactNative() {
DisplayMetricsHolder.initDisplayMetrics(InstrumentationRegistry.getInstrumentation().targetContext)
display = DisplayMetricsHolder.getScreenDisplayMetrics()
}
@After
fun forgetDisplay() {
DisplayMetricsHolder.setScreenDisplayMetrics(null)
}
@Test
fun reservesRoomForTextAtTheWindowDensity() {
// A DeX window at two thirds of the phone's density (240 dpi on a 360 dpi phone). React Native
// reads the font scale from the window but the density from the phone's display.
val window = windowAt(display.densityDpi * 2 / 3)
DisplayMetricsHolder.setScreenDisplayMetrics(
DisplayMetrics().apply {
setTo(display)
scaledDensity = window.scaledDensity
},
)
assertTrue(reservedTextPx(window) < drawnTextPx())
PaseoDisplayMetrics.syncWithWindow(window)
assertEquals(drawnTextPx(), reservedTextPx(window), 0.01f)
assertEquals(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 16f, window), drawnTextPx(), 0.01f)
val synced = DisplayMetricsHolder.getScreenDisplayMetrics()
assertEquals(window.densityDpi, synced.densityDpi)
assertEquals(display.widthPixels, synced.widthPixels)
assertEquals(display.heightPixels, synced.heightPixels)
}
@Test
fun leavesTheBuiltInDisplayAlone() {
PaseoDisplayMetrics.syncWithWindow(windowAt(display.densityDpi))
assertSame(display, DisplayMetricsHolder.getScreenDisplayMetrics())
}
@Test
fun waitsForReactNativeToReadTheDisplay() {
DisplayMetricsHolder.setScreenDisplayMetrics(null)
PaseoDisplayMetrics.syncWithWindow(windowAt(display.densityDpi / 2))
assertThrows(IllegalStateException::class.java) { DisplayMetricsHolder.getScreenDisplayMetrics() }
}
private fun windowAt(densityDpi: Int): DisplayMetrics =
DisplayMetrics().apply {
setTo(display)
this.densityDpi = densityDpi
density = densityDpi.toFloat() / DisplayMetrics.DENSITY_DEFAULT
scaledDensity = density * display.scaledDensity / display.density
}
/** A 16sp font as React Native draws it, in pixels. */
private fun drawnTextPx(): Float = PixelUtil.toPixelFromSP(16f)
/** The box React Native lays out for that font, once the window renders it in pixels. */
private fun reservedTextPx(window: DisplayMetrics): Float =
PixelUtil.toDIPFromPixel(drawnTextPx()) * window.density
}
@@ -0,0 +1,43 @@
package sh.paseo.displaymetrics
import android.app.Activity
import android.util.DisplayMetrics
import com.facebook.react.uimanager.DisplayMetricsHolder
/**
* React Native 0.86 converts between px and dp, and so sizes text, with the density of the
* device's built-in display, because `DisplayMetricsHolder` reads `Display.getRealMetrics()`.
* Fabric lays out at the window's density. On a display with another density, such as a Samsung
* DeX monitor, text boxes come out too small and clip their text.
*
* Backports react/react-native#59087 (`useWindowDensityForDisplayMetricsAndroid`): keep the
* window's density and take only the size from the display. Remove once the app runs React Native
* 0.89 or later with that flag on.
*/
object PaseoDisplayMetrics {
/** Call right after React Native reads the display, which it does again on each configuration change. */
@JvmStatic
fun syncWithWindow(activity: Activity) {
syncWithWindow(activity.resources.displayMetrics)
}
@JvmStatic
fun syncWithWindow(window: DisplayMetrics) {
val screen =
try {
DisplayMetricsHolder.getScreenDisplayMetrics()
} catch (_: IllegalStateException) {
// React Native hasn't read the display yet, so there is nothing to correct.
return
}
if (screen.densityDpi == window.densityDpi) return
DisplayMetricsHolder.setScreenDisplayMetrics(
DisplayMetrics().apply {
setTo(screen)
density = window.density
densityDpi = window.densityDpi
},
)
}
}
@@ -0,0 +1,35 @@
const { withMainActivity } = require("expo/config-plugins");
const ACTIVITY_CLASS = "class MainActivity : ReactActivity() {";
const SYNC = "sh.paseo.displaymetrics.PaseoDisplayMetrics.syncWithWindow(this)";
// React Native re-reads the built-in display's density when it creates the root view and on every
// configuration change, so the window's density has to be restored right after each `super` call.
const OVERRIDES = `
override fun onContentChanged() {
super.onContentChanged()
${SYNC}
}
override fun onConfigurationChanged(newConfig: android.content.res.Configuration) {
super.onConfigurationChanged(newConfig)
${SYNC}
}
`;
function configureDisplayMetricsActivity(contents) {
if (contents.includes(SYNC)) return contents;
if (
!contents.includes(ACTIVITY_CLASS) ||
/override fun on(ContentChanged|ConfigurationChanged)\(/.test(contents)
) {
throw new Error("Could not keep React Native text at the window's density in MainActivity");
}
return contents.replace(ACTIVITY_CLASS, `${ACTIVITY_CLASS}${OVERRIDES}`);
}
module.exports = (config) =>
withMainActivity(config, (mod) => {
mod.modResults.contents = configureDisplayMetricsActivity(mod.modResults.contents);
return mod;
});
module.exports.configureDisplayMetricsActivity = configureDisplayMetricsActivity;
@@ -0,0 +1,29 @@
import { describe, expect, it } from "vitest";
const { configureDisplayMetricsActivity } = require("./app.plugin");
const SYNC = "sh.paseo.displaymetrics.PaseoDisplayMetrics.syncWithWindow(this)";
describe("Android display metrics", () => {
it("restores the window's density after React Native reads the display", () => {
const source = "class MainActivity : ReactActivity() {\n}";
const result = configureDisplayMetricsActivity(source);
expect(result).toContain(`super.onContentChanged()\n ${SYNC}`);
expect(result).toContain(`super.onConfigurationChanged(newConfig)\n ${SYNC}`);
expect(configureDisplayMetricsActivity(result)).toBe(result);
});
it("fails prebuild when the template no longer has a place for the overrides", () => {
expect(() => configureDisplayMetricsActivity("changed template")).toThrow(
"Could not keep React Native text at the window's density",
);
});
it("fails prebuild rather than replace another plugin's configuration handler", () => {
const source =
"class MainActivity : ReactActivity() {\n override fun onConfigurationChanged(newConfig: Configuration) {}\n}";
expect(() => configureDisplayMetricsActivity(source)).toThrow(
"Could not keep React Native text at the window's density",
);
});
});
@@ -0,0 +1,6 @@
{
"platforms": ["android"],
"android": {
"modules": []
}
}
@@ -0,0 +1,5 @@
{
"name": "paseo-display-metrics",
"version": "0.1.0",
"private": true
}
@@ -123,7 +123,8 @@ test.each(["mode", "model", "commands"] as const)(
try {
await session.startTurn("Run the foreground command");
await running.promise;
expect(await session.setThinkingOption?.("medium")).toMatchObject({
// Ultracode is launched with the query, so the change waits for a restart.
expect(await session.setThinkingOption?.("ultracode")).toMatchObject({
message: "Thinking level applies next turn",
});
if (control === "mode") await session.setMode("acceptEdits");
@@ -149,7 +150,7 @@ test.each(["mode", "model", "commands"] as const)(
await session.startTurn("Run another command with the new thinking level");
queries[1].work.resolve();
expect(await terminal.promise).toBe("turn_completed");
expect(efforts).toEqual(["low", "medium"]);
expect(efforts).toEqual(["low", "xhigh"]);
} finally {
await session.close();
}
@@ -44,6 +44,7 @@ function createQueryMock(events: unknown[], options: QueryMockOptions = {}): Que
close: vi.fn(() => undefined),
setPermissionMode: vi.fn(async () => undefined),
setModel: vi.fn(async () => undefined),
applyFlagSettings: vi.fn(async () => undefined),
supportedModels: vi.fn(async () => [{ value: "opus", displayName: "Opus" }]),
supportedCommands: vi.fn(async () => []),
rewindFiles: vi.fn(async () => ({ canRewind: true })),
@@ -382,6 +383,84 @@ describe("Claude runtime exit", () => {
}
});
test("keeps the process and its background work when the effort level changes", async () => {
let capturedOptions: Options | undefined;
const child = createChildProcessStub();
const query = createQueryMock(BACKGROUND_SHELL_TURN_EVENTS, {
tail: new Promise<never>(() => undefined),
onReturn: () => child.emit("exit", 0, null),
});
const queryFactory = vi.fn(({ options }: ClaudeQueryInput) => {
capturedOptions = options;
return query;
});
vi.spyOn(spawnUtils, "spawnProcess").mockReturnValue(child);
const client = new ClaudeAgentClient({
logger: createTestLogger(),
queryFactory,
resolveBinary: async () => "/test/claude/bin",
});
const session = await client.createSession({
provider: "claude",
cwd: process.cwd(),
thinkingOptionId: "low",
});
try {
await session.run("start a background shell");
capturedOptions?.spawnClaudeCodeProcess?.(SPAWN_OPTIONS);
const events: AgentStreamEvent[] = [];
session.subscribe((event) => events.push(event));
await expect(session.setThinkingOption?.("high")).resolves.toBeUndefined();
// A pending restart would be carried out here.
await session.listCommands();
expect(query.applyFlagSettings).toHaveBeenCalledWith({ effortLevel: "high" });
expect(queryFactory).toHaveBeenCalledTimes(1);
expect(query.return).not.toHaveBeenCalled();
expect(child.killSignals).toEqual([]);
expect(events).not.toContainEqual(
expect.objectContaining({ type: "background_work", provider: "claude", items: null }),
);
} finally {
await session.close();
}
});
test("restarts with the new effort level when the running process does not take it", async () => {
const efforts: Options["effort"][] = [];
const queryFactory = vi.fn(({ options }: ClaudeQueryInput) => {
efforts.push(options.effort);
const query = createQueryMock(BACKGROUND_SHELL_TURN_EVENTS, {
tail: new Promise<never>(() => undefined),
});
vi.mocked(query.applyFlagSettings).mockRejectedValue(new Error("unsupported"));
return query;
});
vi.spyOn(spawnUtils, "spawnProcess").mockReturnValue(createChildProcessStub());
const client = new ClaudeAgentClient({
logger: createTestLogger(),
queryFactory,
resolveBinary: async () => "/test/claude/bin",
});
const session = await client.createSession({
provider: "claude",
cwd: process.cwd(),
thinkingOptionId: "low",
});
try {
await session.run("start a background shell");
await session.setThinkingOption?.("high");
await session.listCommands();
expect(efforts).toEqual(["low", "high"]);
} finally {
await session.close();
}
});
test("ignores background work a retired query reports after its restart", async () => {
let capturedOptions: Options | undefined;
let deliverLateEvent: ((event: unknown) => void) | undefined;
@@ -2859,6 +2859,7 @@ class ClaudeAgentSession implements AgentSession {
? thinkingOptionId
: null;
const previousThinkingOptionId = this.config.thinkingOptionId;
if (!normalizedThinkingOptionId || normalizedThinkingOptionId === "default") {
this.config.thinkingOptionId = undefined;
} else if (isClaudeThinkingOption(normalizedThinkingOptionId)) {
@@ -2867,12 +2868,35 @@ class ClaudeAgentSession implements AgentSession {
} else {
throw new Error(`Unknown thinking option: ${normalizedThinkingOptionId}`);
}
this.queryRestartNeeded = true;
if (!(await this.applyEffortToRunningQuery(previousThinkingOptionId))) {
this.queryRestartNeeded = true;
}
if (this.activeForegroundTurnId || this.autonomousTurn) {
return THINKING_APPLIES_NEXT_TURN_NOTICE;
}
}
// A move between two effort levels changes only the effort, which a running Claude process
// takes through flag settings, so the process and its background work stay. Switching thinking
// off, to ultracode or back to the default changes how the query is launched, so it still
// restarts the query. The recorded option feeds every later launch either way.
private async applyEffortToRunningQuery(
previousThinkingOptionId: string | undefined,
): Promise<boolean> {
const effort = this.config.thinkingOptionId;
if (!this.query || this.queryRestartNeeded) return false;
if (!isClaudeThinkingEffort(previousThinkingOptionId) || !isClaudeThinkingEffort(effort)) {
return false;
}
try {
await this.query.applyFlagSettings({ effortLevel: effort });
return true;
} catch (error) {
this.logger.warn({ err: error, effort }, "Claude did not take a live effort change");
return false;
}
}
async applyOptions(options: ProviderOptions): Promise<void> {
// Every option but Fast is read when the query is built, and replacing a started query would
// end its background work, so once it exists only Fast can change.