mirror of
https://github.com/getpaseo/paseo.git
synced 2026-11-17 22:05:06 +00:00
Compare commits
5
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
576d0320c8 | ||
|
|
c8e3d67e29 | ||
|
|
95f2c7d16a | ||
|
|
2c2385f362 | ||
|
|
7f0fe57c48 |
@@ -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
|
||||
|
||||
@@ -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'
|
||||
}
|
||||
+86
@@ -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
|
||||
}
|
||||
+43
@@ -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
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
import path from "node:path";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { buildWorkspaceSource } from "./create.js";
|
||||
|
||||
@@ -8,6 +9,49 @@ describe("workspace create source", () => {
|
||||
).toEqual({ kind: "directory", path: "/tmp/project", projectId: "project-1" });
|
||||
});
|
||||
|
||||
it("resolves a relative path against the directory the command runs in", () => {
|
||||
const daemonTarget = { kind: "instance" as const, home: "/tmp/paseo-home" };
|
||||
expect(buildWorkspaceSource({ daemonTarget, isolation: "local", path: "." })).toEqual({
|
||||
kind: "directory",
|
||||
path: process.cwd(),
|
||||
});
|
||||
expect(
|
||||
buildWorkspaceSource({ daemonTarget, isolation: "worktree", path: "../sibling" }),
|
||||
).toEqual({
|
||||
kind: "worktree",
|
||||
cwd: path.resolve(process.cwd(), "../sibling"),
|
||||
action: "branch-off",
|
||||
});
|
||||
});
|
||||
|
||||
it("sends a relative path to an explicit daemon endpoint as written", () => {
|
||||
const daemonTarget = { kind: "endpoint" as const, host: "other-box:6767" };
|
||||
expect(buildWorkspaceSource({ daemonTarget, isolation: "local", path: "repo" })).toEqual({
|
||||
kind: "directory",
|
||||
path: "repo",
|
||||
});
|
||||
});
|
||||
|
||||
it("passes an absolute path from another operating system through unchanged", () => {
|
||||
expect(buildWorkspaceSource({ isolation: "local", path: "C:\\repos\\project" })).toEqual({
|
||||
kind: "directory",
|
||||
path: "C:\\repos\\project",
|
||||
});
|
||||
});
|
||||
|
||||
it("leaves a home-relative path for the daemon to expand", () => {
|
||||
const daemonTarget = { kind: "instance" as const, home: "/tmp/paseo-home" };
|
||||
expect(buildWorkspaceSource({ daemonTarget, isolation: "local", path: "~/repo" })).toEqual({
|
||||
kind: "directory",
|
||||
path: "~/repo",
|
||||
});
|
||||
expect(buildWorkspaceSource({ daemonTarget, isolation: "worktree", path: "~" })).toEqual({
|
||||
kind: "worktree",
|
||||
cwd: "~",
|
||||
action: "branch-off",
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps branch names separate from managed worktree slugs", () => {
|
||||
expect(
|
||||
buildWorkspaceSource({
|
||||
|
||||
@@ -1,6 +1,10 @@
|
||||
import { isAbsolute as isPosixAbsolute } from "node:path/posix";
|
||||
import { isAbsolute as isWindowsAbsolute } from "node:path/win32";
|
||||
import { resolve } from "node:path";
|
||||
import type { Command } from "commander";
|
||||
import { connectToDaemon, getDaemonHost } from "../../utils/client.js";
|
||||
import { resolveCallerAgentId } from "../../utils/caller-agent.js";
|
||||
import type { DaemonTarget } from "../../utils/daemon-target.js";
|
||||
import type { CommandError, CommandOptions, SingleResult } from "../../output/index.js";
|
||||
import { toWorkspaceRow, workspaceSchema, type WorkspaceRow } from "./shared.js";
|
||||
|
||||
@@ -121,12 +125,26 @@ function buildWorktreeWorkspaceSource(options: WorkspaceCreateOptions, path: str
|
||||
}
|
||||
}
|
||||
|
||||
// A relative --path names a directory relative to where the command runs, so
|
||||
// it is made absolute here for a local daemon, which would otherwise resolve
|
||||
// it against its own working directory. For an explicit endpoint the path is
|
||||
// sent as written, the same rule as resolveRepositoryDirectory. An absolute
|
||||
// path can target a daemon on a different operating system, and the daemon
|
||||
// expands a leading ~ to its own home directory.
|
||||
function resolveCallerPath(input: string, daemonTarget: DaemonTarget): string {
|
||||
const isHomeRelative = input === "~" || input.startsWith("~/");
|
||||
if (isHomeRelative || isPosixAbsolute(input) || isWindowsAbsolute(input)) return input;
|
||||
return daemonTarget.kind === "instance" ? resolve(input) : input;
|
||||
}
|
||||
|
||||
export function buildWorkspaceSource(options: WorkspaceCreateOptions) {
|
||||
const callerPath =
|
||||
options.path === undefined ? undefined : resolveCallerPath(options.path, options.daemonTarget);
|
||||
if (options.isolation === "local") {
|
||||
return buildLocalWorkspaceSource(options, options.path ?? process.cwd());
|
||||
return buildLocalWorkspaceSource(options, callerPath ?? process.cwd());
|
||||
}
|
||||
if (options.isolation === "worktree") {
|
||||
const sourcePath = options.path ?? (options.project ? undefined : process.cwd());
|
||||
const sourcePath = callerPath ?? (options.project ? undefined : process.cwd());
|
||||
return buildWorktreeWorkspaceSource(options, sourcePath);
|
||||
}
|
||||
throw new Error(`Unsupported workspace isolation: ${String(options.isolation)}`);
|
||||
|
||||
@@ -3473,6 +3473,101 @@ test("cancelAgentRun succeeds when the provider queues completion before rejecti
|
||||
}
|
||||
});
|
||||
|
||||
test.each([
|
||||
{ binding: "foreground", agentId: "00000000-0000-4000-8000-000000000307" },
|
||||
{ binding: "autonomous", agentId: "00000000-0000-4000-8000-000000000308" },
|
||||
] as const)(
|
||||
"cancelAgentRun settles a $binding run bound to an already finalized turn",
|
||||
async ({ binding, agentId }) => {
|
||||
const fixture = await createControlledInterruptFixture({
|
||||
name: `interrupt-finalized-${binding}`,
|
||||
agentId,
|
||||
turnId: "finalized-turn",
|
||||
interrupt: async () => {},
|
||||
});
|
||||
|
||||
try {
|
||||
await fixture.startForegroundRun();
|
||||
await expect(fixture.manager.cancelAgentRun(fixture.agentId)).resolves.toEqual({
|
||||
status: "settled",
|
||||
});
|
||||
|
||||
if (binding === "foreground") {
|
||||
await fixture.startForegroundRun();
|
||||
} else {
|
||||
const running = waitForAgentLifecycle(fixture.manager, fixture.agentId, "running");
|
||||
fixture.session.pushEvent({
|
||||
type: "turn_started",
|
||||
provider: "codex",
|
||||
turnId: "finalized-turn",
|
||||
});
|
||||
await running;
|
||||
}
|
||||
|
||||
const cancellation = await Promise.race([
|
||||
fixture.manager.cancelAgentRun(fixture.agentId),
|
||||
new Promise<"pending">((resolve) => setTimeout(() => resolve("pending"), 3_000)),
|
||||
]);
|
||||
expect(cancellation).toEqual({ status: "settled" });
|
||||
expect(fixture.manager.getAgent(fixture.agentId)).toMatchObject({
|
||||
lifecycle: "idle",
|
||||
activeForegroundTurnId: null,
|
||||
});
|
||||
|
||||
await expect(fixture.manager.cancelAgentRun(fixture.agentId)).resolves.toEqual({
|
||||
status: "not_running",
|
||||
});
|
||||
await fixture.startForegroundRun();
|
||||
expect(fixture.manager.getAgent(fixture.agentId)).toMatchObject({
|
||||
lifecycle: "running",
|
||||
activeForegroundTurnId: "finalized-turn",
|
||||
});
|
||||
} finally {
|
||||
await fixture.cleanup();
|
||||
}
|
||||
},
|
||||
10_000,
|
||||
);
|
||||
|
||||
test("the provider's terminal for a run bound to an already finalized turn settles the run", async () => {
|
||||
const fixture = await createControlledInterruptFixture({
|
||||
name: "interrupt-finalized-provider-terminal",
|
||||
agentId: "00000000-0000-4000-8000-000000000309",
|
||||
turnId: "finalized-provider-terminal-turn",
|
||||
interrupt: async () => {},
|
||||
});
|
||||
|
||||
try {
|
||||
await fixture.startForegroundRun();
|
||||
await expect(fixture.manager.cancelAgentRun(fixture.agentId)).resolves.toEqual({
|
||||
status: "settled",
|
||||
});
|
||||
|
||||
await fixture.startForegroundRun();
|
||||
const idle = waitForAgentLifecycle(fixture.manager, fixture.agentId, "idle");
|
||||
fixture.session.pushEvent({
|
||||
type: "turn_completed",
|
||||
provider: "codex",
|
||||
turnId: "finalized-provider-terminal-turn",
|
||||
});
|
||||
const settlement = await Promise.race([
|
||||
idle.then(() => "idle" as const),
|
||||
new Promise<"pending">((resolve) => setTimeout(() => resolve("pending"), 1_000)),
|
||||
]);
|
||||
|
||||
expect(settlement).toBe("idle");
|
||||
expect(fixture.manager.getAgent(fixture.agentId)).toMatchObject({
|
||||
lifecycle: "idle",
|
||||
activeForegroundTurnId: null,
|
||||
});
|
||||
await expect(fixture.manager.cancelAgentRun(fixture.agentId)).resolves.toEqual({
|
||||
status: "not_running",
|
||||
});
|
||||
} finally {
|
||||
await fixture.cleanup();
|
||||
}
|
||||
}, 10_000);
|
||||
|
||||
test("listProviderAvailability uses registered client keys, including custom providers", async () => {
|
||||
const customClient: AgentClient = {
|
||||
provider: "zai",
|
||||
|
||||
@@ -5132,7 +5132,8 @@ export class AgentManager {
|
||||
if (
|
||||
eventTurnId &&
|
||||
isTurnTerminalEvent(event) &&
|
||||
this.runs.hasFinalizedTurn(agent, eventTurnId)
|
||||
this.runs.hasFinalizedTurn(agent, eventTurnId) &&
|
||||
this.runs.getTurnId(agent.id) !== eventTurnId
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -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.
|
||||
|
||||
Reference in New Issue
Block a user