mirror of
https://github.com/getpaseo/paseo.git
synced 2026-12-01 04:36:26 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
acb88673ab | ||
|
|
b08a0bc6ce | ||
|
|
d7404733f6 | ||
|
|
0d215ecf29 | ||
|
|
df45627da5 | ||
|
|
5343d72939 | ||
|
|
990721e134 | ||
|
|
b1677e58d8 |
+21
-5
@@ -301,9 +301,10 @@ translation scope is React context and does not cross it (Gotcha 7). It returns:
|
||||
height with it; never animate height per frame.
|
||||
|
||||
Do not measure an anchor with `measureInWindow` and correct it by the keyboard
|
||||
shift. On iOS the translate view uses the native driver, and `measureInWindow`
|
||||
includes its transform only when the view happened to re-render since the
|
||||
keyboard moved. Both results were observed, so any correction double-lifts the
|
||||
shift. On iOS the translate view uses the native driver, which moves the view
|
||||
without updating the shadow tree. The translate view commits the resting lift to
|
||||
the shadow tree once the keyboard settles, so `measureInWindow` includes the lift
|
||||
at rest and misses it while the keyboard moves. Any correction double-lifts the
|
||||
popover or leaves it behind the keyboard. `measureAtRest` measures through
|
||||
Fabric's transform-free `measureLayout` instead. Re-measure when `isMoving`
|
||||
settles; the composer's resting position changes as the draft grows.
|
||||
@@ -315,8 +316,8 @@ the anchor's rect against the layer and commits the placement with `flushSync`,
|
||||
which runs after layout and before paint. On native a Reanimated frame callback
|
||||
reads only the anchor's height on the UI thread and holds its bottom edge at
|
||||
the rest measurement. A height carries no transform. On iOS the absolute
|
||||
position does not reliably include one: the keyboard lift runs on the native
|
||||
driver and reaches the shadow tree only when the view re-renders. The
|
||||
position does not include one while the keyboard moves: the lift runs on the
|
||||
native driver and reaches the shadow tree only at rest. The
|
||||
fixed-bottom model is wrong for the centered New workspace composer on tablets,
|
||||
which grows around its middle, and for width or x changes. The popover is off
|
||||
there by half the growth, or by the old width, until the next rest measurement.
|
||||
@@ -324,6 +325,21 @@ Keep the portal's `KeyboardTranslateView` host-sized with
|
||||
`pointerEvents="box-none"` and position the popover inside it, so the popover
|
||||
moves without leaving its parent's bounds (Gotcha 1).
|
||||
|
||||
The resting commit also keeps touches working. Pressability measures a
|
||||
`Pressable`'s press region in the shadow tree. If the region stays at the
|
||||
unlifted position, a tap that drifts a few points leaves it and the press is
|
||||
dropped. This hit every control in the dock: Send, attach, and the model selector.
|
||||
|
||||
`Combobox` positions its native popover with floating-ui against the window, and
|
||||
the software keyboard covers part of the window. It adds the settled keyboard
|
||||
height (`useSettledKeyboardHeight`) to its bottom collision padding. The height
|
||||
changes on `keyboardDidShow` and `keyboardDidHide`, at the end of the move. The new
|
||||
padding re-measures the anchor on the next frame, when the resting lift is in the
|
||||
shadow tree, so the popover follows an anchor that rides the keyboard.
|
||||
Opening the model picker moves focus to its search input, and the keyboard hides
|
||||
and shows again on the way. A height that changes at `keyboardWillShow` instead
|
||||
measures the trigger before it lifts and leaves the popover over the keyboard.
|
||||
|
||||
The provider also reconciles iOS from the controller's native `onEnd` event.
|
||||
The controller's stock iOS shared values update at move start and during an
|
||||
interactive move, but not at the terminal event, so JS contention can otherwise
|
||||
|
||||
@@ -127,7 +127,10 @@ With a Codex draft selected, set `_SCENARIO=growth` on a 402pt-wide iPhone to
|
||||
check live wrapping, shrinking, the 12pt anchor gap, and command insertion. Set
|
||||
`_SCENARIO=previews` on an SE-sized iPhone to check long and short descriptions
|
||||
under an eight-line draft, selection with the keyboard shown and hidden, and
|
||||
file mentions. These scenarios only need `_SERVER_ID` and `_WORKSPACE_ID`;
|
||||
file mentions. Set `_SCENARIO=controls` to tap the attach button and the model
|
||||
selector with a 3pt drag while the keyboard is open, then check that a wide
|
||||
layout's model popover clears both the trigger and the keyboard. Run it on an
|
||||
iPhone and on the iPhone Duo unfolded. These scenarios only need `_SERVER_ID` and `_WORKSPACE_ID`;
|
||||
`_UDID` selects an exact simulator and `_ARTIFACTS_DIR` overrides the output path.
|
||||
|
||||
The Android sidebar scroll-retention flow requires a connected host with enough
|
||||
|
||||
@@ -248,41 +248,47 @@ async function readSettledFrameBorder(page: Page): Promise<string> {
|
||||
});
|
||||
}
|
||||
|
||||
test("the composer frame shows hover and focus", async ({ page }) => {
|
||||
const agent = await seedMockAgentWorkspace({
|
||||
repoPrefix: "composer-frame-focus-",
|
||||
title: "Composer frame focus",
|
||||
// `borderAccent` at rest, `surface4` while focused: greys in both themes, never the accent.
|
||||
const FRAME_BORDERS = {
|
||||
dark: { rest: "rgb(47, 53, 52)", focus: "rgb(89, 91, 91)" },
|
||||
light: { rest: "rgb(236, 236, 241)", focus: "rgb(212, 212, 216)" },
|
||||
} as const;
|
||||
|
||||
for (const colorScheme of ["dark", "light"] as const) {
|
||||
test(`the composer frame takes a neutral border on focus in the ${colorScheme} theme`, async ({
|
||||
page,
|
||||
}) => {
|
||||
const agent = await seedMockAgentWorkspace({
|
||||
repoPrefix: "composer-frame-focus-",
|
||||
title: "Composer frame focus",
|
||||
});
|
||||
const borders = FRAME_BORDERS[colorScheme];
|
||||
|
||||
try {
|
||||
await page.emulateMedia({ colorScheme });
|
||||
await openAgentRoute(page, agent);
|
||||
const composer = composerLocator(page);
|
||||
await expectComposerVisible(page);
|
||||
await page.mouse.move(0, 0);
|
||||
await blurComposerInput(page);
|
||||
expect(await readSettledFrameBorder(page)).toBe(borders.rest);
|
||||
|
||||
await composer.click();
|
||||
await page.mouse.move(0, 0);
|
||||
await expectComposerFocused(page);
|
||||
expect(await readSettledFrameBorder(page)).toBe(borders.focus);
|
||||
|
||||
await blurComposerInput(page);
|
||||
expect(await readSettledFrameBorder(page)).toBe(borders.rest);
|
||||
|
||||
// Hover alone leaves the frame at rest, so the border only ever means focus.
|
||||
await composer.hover();
|
||||
expect(await readSettledFrameBorder(page)).toBe(borders.rest);
|
||||
} finally {
|
||||
await agent.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
try {
|
||||
await openAgentRoute(page, agent);
|
||||
const composer = composerLocator(page);
|
||||
await expectComposerVisible(page);
|
||||
await page.mouse.move(0, 0);
|
||||
await blurComposerInput(page);
|
||||
const rest = await readSettledFrameBorder(page);
|
||||
|
||||
await composer.hover();
|
||||
const hover = await readSettledFrameBorder(page);
|
||||
expect(hover).not.toBe(rest);
|
||||
|
||||
await composer.click();
|
||||
await page.mouse.move(0, 0);
|
||||
await expectComposerFocused(page);
|
||||
const focus = await readSettledFrameBorder(page);
|
||||
expect(focus).not.toBe(rest);
|
||||
expect(focus).not.toBe(hover);
|
||||
|
||||
await composer.hover();
|
||||
expect(await readSettledFrameBorder(page)).toBe(focus);
|
||||
|
||||
await page.mouse.move(0, 0);
|
||||
await blurComposerInput(page);
|
||||
expect(await readSettledFrameBorder(page)).toBe(rest);
|
||||
} finally {
|
||||
await agent.cleanup();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
async function waitForAnimationFrames(page: Page, count: number): Promise<void> {
|
||||
await page.evaluate(async (frames) => {
|
||||
|
||||
@@ -753,6 +753,10 @@ test.describe("CodeMirror workspace file editing", () => {
|
||||
const imagePath = path.join(workspace.repoPath, "pixel.png");
|
||||
await writeFile(markdownPath, "# First heading\n", "utf8");
|
||||
await writeFile(imagePath, RED_PIXEL);
|
||||
await writeFile(
|
||||
path.join(workspace.repoPath, "shape.svg"),
|
||||
await readFile(path.resolve(__dirname, "../mobile/fixtures/native-preview.svg")),
|
||||
);
|
||||
await workspace.navigateTo();
|
||||
await openWorkspaceFile(page, "notes.md");
|
||||
|
||||
@@ -800,6 +804,11 @@ test.describe("CodeMirror workspace file editing", () => {
|
||||
const initialSource = await image.getAttribute("src");
|
||||
await writeFile(imagePath, BLUE_PIXEL);
|
||||
await expect.poll(() => image.getAttribute("src")).not.toBe(initialSource);
|
||||
|
||||
await openWorkspaceFile(page, "shape.svg");
|
||||
await expect(imageCanvas).toBeVisible();
|
||||
await expect(image).toBeVisible();
|
||||
await expect(image).toHaveJSProperty("naturalWidth", 240);
|
||||
});
|
||||
|
||||
test("renders local relative images inside Markdown preview", async ({ page, withWorkspace }) => {
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
# Native SVG preview regression
|
||||
|
||||
Copy `../fixtures/native-preview.svg`, `../fixtures/native-preview-viewbox.svg`, and
|
||||
`../../../assets/images/icon.png` into a workspace on a test daemon. In the Android
|
||||
or iOS app, connect to that daemon, open the workspace's Files tab, and tap
|
||||
`native-preview.svg`. The SVG should show a yellow circle on a green rectangle.
|
||||
|
||||
With that preview open, run:
|
||||
|
||||
```sh
|
||||
agent-device test packages/app/e2e/mobile/agent-device/native-svg-preview.android.ad \
|
||||
--metro-port <port> --artifacts-dir .artifacts/svg-preview
|
||||
```
|
||||
|
||||
Run it again with `native-preview-viewbox.svg` open to cover SVG dimensions
|
||||
inferred from `viewBox`, then with the PNG open to check raster images. Close and
|
||||
reopen the SVG and rerun to cover cached file previews. Use English app language
|
||||
for the zoom button selectors. The scripts are discovered by `npm run test:e2e:mobile`; the iOS counterpart is
|
||||
`native-svg-preview.ios.ad`. They reopen the installed app with its current
|
||||
preview and leave the daemon connection unchanged.
|
||||
|
||||
Before the fix the SVG remains blank and the canvas wait fails. The PNG passes.
|
||||
The replay checks successful native dimension decoding and zoom/reset controls;
|
||||
visually verify the circle and rectangle as well.
|
||||
@@ -0,0 +1,11 @@
|
||||
context platform=android timeout=60000 retries=0
|
||||
env APP_ID=sh.paseo.debug
|
||||
|
||||
open "${APP_ID}"
|
||||
wait "id=\"image-file-preview-canvas\"" 10000
|
||||
wait "role=button label=\"Zoom in\"" 10000
|
||||
press "role=button label=\"Zoom in\""
|
||||
wait "role=button label=\"Reset view\" enabled=true" 10000
|
||||
press "role=button label=\"Reset view\""
|
||||
wait "role=button label=\"Reset view\" enabled=false" 10000
|
||||
close
|
||||
@@ -0,0 +1,11 @@
|
||||
context platform=ios timeout=60000 retries=0
|
||||
env APP_ID=sh.paseo.debug
|
||||
|
||||
open "${APP_ID}"
|
||||
wait "id=\"image-file-preview-canvas\"" 10000
|
||||
wait "role=button label=\"Zoom in\"" 10000
|
||||
press "role=button label=\"Zoom in\""
|
||||
wait "role=button label=\"Reset view\" enabled=true" 10000
|
||||
press "role=button label=\"Reset view\""
|
||||
wait "role=button label=\"Reset view\" enabled=false" 10000
|
||||
close
|
||||
@@ -317,6 +317,80 @@ async function runBoundedPreview() {
|
||||
await runCase("preview", "files", fileCase);
|
||||
}
|
||||
|
||||
// A finger drifts a few points during a tap, so tap the composer's controls with a
|
||||
// short drag while the keyboard is open. The model picker must open, and on a wide
|
||||
// layout its popover must end above the keyboard.
|
||||
function dragTap(rect) {
|
||||
ad(
|
||||
"gesture",
|
||||
"pan",
|
||||
String(Math.round(rect.x + rect.width / 2)),
|
||||
String(Math.round(rect.y + rect.height / 2)),
|
||||
"0",
|
||||
"3",
|
||||
"120",
|
||||
);
|
||||
}
|
||||
|
||||
// Waits until the keyboard is shown and the node with `id` stops moving.
|
||||
async function settledWithKeyboard(name, id) {
|
||||
let previousTop;
|
||||
return waitFor(name, (snap) => {
|
||||
const node = nodeById(snap, id);
|
||||
if (!node || !keyboardShown(snap)) return false;
|
||||
const stable = node.rect.y === previousTop;
|
||||
previousTop = node.rect.y;
|
||||
return stable;
|
||||
});
|
||||
}
|
||||
|
||||
const keyboardTop = (snap) =>
|
||||
snap.data.nodes.find((node) => node.type === "Keyboard" && node.rect).rect.y;
|
||||
|
||||
async function runControlTaps() {
|
||||
await clearInput("controls");
|
||||
const attach = nodeById(
|
||||
await settledWithKeyboard("controls-attach-before", "message-input-root"),
|
||||
"message-input-attach-button",
|
||||
);
|
||||
dragTap(attach.rect);
|
||||
// Wide layouts show the attachment menu as a popover and phones as a sheet; both list the items.
|
||||
await waitFor("controls-attach-menu", (snap) =>
|
||||
Boolean(nodeById(snap, "message-input-attachment-menu-item-file")),
|
||||
);
|
||||
process.stdout.write("PASS drag tap on attach opened the attachment menu\n");
|
||||
// The open menu hides the composer from accessibility. Its backdrop covers the top-left corner.
|
||||
ad("press", "20", "120");
|
||||
await waitFor("controls-attach-closed", (snap) => Boolean(nodeById(snap, "message-input-root")));
|
||||
await clearInput("controls-model");
|
||||
|
||||
const trigger = nodeById(
|
||||
await settledWithKeyboard("controls-model-before", "message-input-root"),
|
||||
"combined-model-selector",
|
||||
);
|
||||
dragTap(trigger.rect);
|
||||
const sheetOpen = (snap) =>
|
||||
snap.data.nodes.some((node) => node.type === "Button" && node.label === "Close");
|
||||
const opened = await waitFor(
|
||||
"controls-model-picker",
|
||||
(snap) => Boolean(nodeById(snap, "combobox-desktop-container")) || sheetOpen(snap),
|
||||
);
|
||||
process.stdout.write("PASS drag tap on the model selector opened the picker\n");
|
||||
if (!nodeById(opened, "combobox-desktop-container")) return;
|
||||
const settled = await settledWithKeyboard("controls-model-popover", "combobox-desktop-container");
|
||||
const frame = nodeById(settled, "combobox-desktop-container").rect;
|
||||
const bottom = frame.y + frame.height;
|
||||
const covered = frame.y < trigger.rect.y + trigger.rect.height && bottom > trigger.rect.y;
|
||||
if (covered || bottom > keyboardTop(settled) + 1) {
|
||||
throw new Error(
|
||||
`Model popover spans ${Math.round(frame.y)}-${Math.round(bottom)}; it must clear the trigger at ${Math.round(trigger.rect.y)} and the keyboard at ${Math.round(keyboardTop(settled))}`,
|
||||
);
|
||||
}
|
||||
process.stdout.write(
|
||||
`PASS model popover ${Math.round(frame.y)}-${Math.round(bottom)} clears the trigger and the keyboard\n`,
|
||||
);
|
||||
}
|
||||
|
||||
if (scenario !== "all") {
|
||||
ad(
|
||||
"open",
|
||||
@@ -328,6 +402,7 @@ if (scenario !== "all") {
|
||||
await waitFor("draft", (snap) => Boolean(nodeById(snap, "message-input-root")), 60_000);
|
||||
if (scenario === "growth") await runLiveGrowth();
|
||||
else if (scenario === "previews") await runBoundedPreview();
|
||||
else if (scenario === "controls") await runControlTaps();
|
||||
else throw new Error(`Unknown scenario: ${scenario}`);
|
||||
process.stdout.write(`Composer ${scenario} regression passed. Artifacts: ${artifactsDir}\n`);
|
||||
process.exit(0);
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 240 160"><rect width="240" height="160" fill="#08a040"/><circle cx="120" cy="80" r="50" fill="#ffcc00"/></svg>
|
||||
|
After Width: | Height: | Size: 164 B |
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="240" height="160" viewBox="0 0 240 160"><rect width="240" height="160" fill="#08a040"/><circle cx="120" cy="80" r="50" fill="#ffcc00"/></svg>
|
||||
|
After Width: | Height: | Size: 188 B |
@@ -1,4 +1,5 @@
|
||||
import { useOverlayRegistration, type KeyboardInputEvent } from "@/keyboard";
|
||||
import { useSettledKeyboardHeight } from "@/keyboard/shift";
|
||||
import { Modal } from "@/components/ui/modal";
|
||||
import {
|
||||
useCallback,
|
||||
@@ -943,19 +944,34 @@ function maybePinDesktopOptionsToBottom(
|
||||
|
||||
interface FloatingMiddlewareInput {
|
||||
collisionPadding: number;
|
||||
keyboardHeight: number;
|
||||
isDesktopAboveSearch: boolean;
|
||||
setAvailableSize: FloatingSizeSetters["setAvailableSize"];
|
||||
setReferenceWidth: FloatingSizeSetters["setReferenceWidth"];
|
||||
}
|
||||
|
||||
function buildFloatingMiddleware(input: FloatingMiddlewareInput) {
|
||||
const { collisionPadding, isDesktopAboveSearch, setAvailableSize, setReferenceWidth } = input;
|
||||
const {
|
||||
collisionPadding,
|
||||
keyboardHeight,
|
||||
isDesktopAboveSearch,
|
||||
setAvailableSize,
|
||||
setReferenceWidth,
|
||||
} = input;
|
||||
// The native popover's boundary is the window, which the software keyboard covers. The keyboard
|
||||
// height changes once the keyboard settles, so this also re-measures an anchor that rides it.
|
||||
const padding = {
|
||||
top: collisionPadding,
|
||||
left: collisionPadding,
|
||||
right: collisionPadding,
|
||||
bottom: collisionPadding + keyboardHeight,
|
||||
};
|
||||
return [
|
||||
floatingOffset(isWeb ? 5 : 4),
|
||||
...(isWeb ? [] : [flip({ padding: collisionPadding })]),
|
||||
...(isDesktopAboveSearch ? [] : [shift({ padding: collisionPadding })]),
|
||||
...(isWeb ? [] : [flip({ padding })]),
|
||||
...(isDesktopAboveSearch ? [] : [shift({ padding })]),
|
||||
floatingSize({
|
||||
padding: collisionPadding,
|
||||
padding,
|
||||
apply({ availableWidth, availableHeight, rects }) {
|
||||
updateAvailableSize(setAvailableSize, availableWidth, availableHeight);
|
||||
updateReferenceWidth(setReferenceWidth, rects.reference.width);
|
||||
@@ -1496,16 +1512,18 @@ export function Combobox({
|
||||
useResetSearchOnOpen(isOpen, setSearchQueryWithCallback, bumpSearchResetKey);
|
||||
|
||||
const collisionPadding = useMemo(computeCollisionPadding, []);
|
||||
const keyboardHeight = useSettledKeyboardHeight();
|
||||
|
||||
const middleware = useMemo(
|
||||
() =>
|
||||
buildFloatingMiddleware({
|
||||
collisionPadding,
|
||||
keyboardHeight,
|
||||
isDesktopAboveSearch,
|
||||
setAvailableSize,
|
||||
setReferenceWidth,
|
||||
}),
|
||||
[collisionPadding, isDesktopAboveSearch],
|
||||
[collisionPadding, isDesktopAboveSearch, keyboardHeight],
|
||||
);
|
||||
|
||||
const { refs, floatingStyles, update } = useFloating({
|
||||
|
||||
@@ -1,16 +1,13 @@
|
||||
import { Image } from "react-native";
|
||||
import { Image } from "expo-image";
|
||||
import type { ViewportSize } from "./geometry";
|
||||
|
||||
/** Resolves the image's natural size; rejects when the image cannot load or has no size. */
|
||||
export function measureImage(uri: string): Promise<ViewportSize> {
|
||||
return new Promise((resolve, reject) => {
|
||||
Image.getSize(
|
||||
uri,
|
||||
(width, height) => {
|
||||
if (width > 0 && height > 0) resolve({ width, height });
|
||||
else reject(new Error("Image has no size"));
|
||||
},
|
||||
reject,
|
||||
);
|
||||
});
|
||||
/**
|
||||
* Resolves the image's natural size; rejects when the image cannot load or has no size. Decodes
|
||||
* with Expo Image, the same decoder that draws the image: React Native's `Image.getSize` cannot
|
||||
* decode SVG on Android or iOS.
|
||||
*/
|
||||
export async function measureImage(uri: string): Promise<ViewportSize> {
|
||||
const { width, height } = await Image.loadAsync(uri);
|
||||
if (width > 0 && height > 0) return { width, height };
|
||||
throw new Error("Image has no size");
|
||||
}
|
||||
|
||||
@@ -1,11 +1,15 @@
|
||||
import { useCallback, useEffect, useMemo, useState } from "react";
|
||||
import { Image, View, type StyleProp, type ViewStyle } from "react-native";
|
||||
import { StyleSheet } from "react-native-unistyles";
|
||||
import { Image } from "expo-image";
|
||||
import { View, type StyleProp, type ViewStyle } from "react-native";
|
||||
import { StyleSheet, withUnistyles } from "react-native-unistyles";
|
||||
import type { ViewportFitOptions, ViewportSize } from "./geometry";
|
||||
import { measureImage } from "./image-size";
|
||||
import { ZoomableViewport } from "./index";
|
||||
import type { ZoomableViewportAction } from "./types";
|
||||
|
||||
// Expo Image draws SVG as well as raster images; React Native's Image cannot draw SVG on native.
|
||||
const ViewportImage = withUnistyles(Image);
|
||||
|
||||
interface ZoomableImageProps {
|
||||
uri: string;
|
||||
accessibilityLabel?: string;
|
||||
@@ -77,12 +81,12 @@ export function ZoomableImage({
|
||||
testID={testID}
|
||||
wheelActivation={wheelActivation}
|
||||
>
|
||||
<Image
|
||||
// Android fades a freshly decoded image in over 300ms; it appears with its toolbar instead.
|
||||
fadeDuration={0}
|
||||
<ViewportImage
|
||||
// No transition, so the image appears together with its toolbar.
|
||||
transition={null}
|
||||
contentFit="contain"
|
||||
onError={onError}
|
||||
onLoad={handleLoad}
|
||||
resizeMode="contain"
|
||||
source={source}
|
||||
style={styles.image}
|
||||
testID={`${testID}-image`}
|
||||
|
||||
@@ -110,7 +110,6 @@ import {
|
||||
applyDictationTranscript,
|
||||
computeCanStartDictation,
|
||||
resolveAlternateSendAction,
|
||||
resolveComposerFramePhase,
|
||||
resolveComposerSurfacePresentation,
|
||||
resolveComposerSurfaceText,
|
||||
resolveMessageInputEnterAction,
|
||||
@@ -1369,8 +1368,6 @@ export const MessageInput = forwardRef<MessageInputRef, MessageInputProps>(
|
||||
const dictationToggleKeys = useShortcutKeys("dictation-toggle");
|
||||
const focusInputKeys = useShortcutKeys("focus-message-input");
|
||||
const [isInputFocused, setIsInputFocused] = useState(false);
|
||||
// Only the frame's pointer events set it, so hover stays a web thing; see docs/hover.md.
|
||||
const [isInputHovered, setIsInputHovered] = useState(false);
|
||||
useKeyboardFocusSurface("message-input", isInputFocused && isPaneFocused);
|
||||
// Web text is DOM-owned between deferred draft publications. The action button only needs
|
||||
// this boundary, so publish empty/non-empty transitions without rerendering for every key.
|
||||
@@ -2041,30 +2038,22 @@ export const MessageInput = forwardRef<MessageInputRef, MessageInputProps>(
|
||||
void handleStopRealtimeVoice();
|
||||
}, [handleStopRealtimeVoice]);
|
||||
|
||||
const handleInputWrapperPointerEnter = useCallback(() => setIsInputHovered(true), []);
|
||||
const handleInputWrapperPointerLeave = useCallback(() => setIsInputHovered(false), []);
|
||||
const framePhase = resolveComposerFramePhase({
|
||||
hovered: isInputHovered,
|
||||
focused: isInputFocused,
|
||||
readOnly,
|
||||
disabled,
|
||||
});
|
||||
const showFocusBorder = isInputFocused && !readOnly && !disabled;
|
||||
const inputWrapperCombinedStyle = useMemo(
|
||||
() => [
|
||||
styles.inputWrapper,
|
||||
Platform.OS !== "ios" && isCompact && !isFullscreen && styles.inputWrapperCompact,
|
||||
readOnly && styles.inputWrapperReadOnly,
|
||||
framePhase === "hover" && styles.inputWrapperHovered,
|
||||
framePhase === "active" && styles.inputWrapperFocused,
|
||||
showFocusBorder && styles.inputWrapperFocused,
|
||||
inputWrapperStyle,
|
||||
{ opacity: surfacePresentation.input.opacity },
|
||||
],
|
||||
[
|
||||
framePhase,
|
||||
inputWrapperStyle,
|
||||
isCompact,
|
||||
isFullscreen,
|
||||
readOnly,
|
||||
showFocusBorder,
|
||||
surfacePresentation.input.opacity,
|
||||
],
|
||||
);
|
||||
@@ -2414,8 +2403,6 @@ export const MessageInput = forwardRef<MessageInputRef, MessageInputProps>(
|
||||
onExit={exitFullscreen}
|
||||
inputWrapperRef={inputWrapperRef}
|
||||
inputWrapperStyle={inputWrapperCombinedStyle}
|
||||
onInputWrapperPointerEnter={handleInputWrapperPointerEnter}
|
||||
onInputWrapperPointerLeave={handleInputWrapperPointerLeave}
|
||||
inputPointerEvents={surfacePresentation.input.pointerEvents}
|
||||
attachmentSlot={attachmentSlot}
|
||||
showFullscreenButton={shouldShowFullscreenControl(
|
||||
@@ -2470,14 +2457,10 @@ const styles = StyleSheet.create((theme: Theme) => ({
|
||||
inputWrapperReadOnly: {
|
||||
borderStyle: "dotted",
|
||||
},
|
||||
// The rest border is already the `borderAccent` that `controlHover` gives other inputs, so
|
||||
// hover steps up one surface; focus takes the accent, like their focus ring. Colour only:
|
||||
// the border width stays put, so the frame never shifts under the pointer.
|
||||
inputWrapperHovered: {
|
||||
borderColor: theme.colors.surface4,
|
||||
},
|
||||
// A neutral step up from the resting `borderAccent`, never the accent. There is no hover
|
||||
// step: `surface3` is fainter than the resting border in the pure black theme.
|
||||
inputWrapperFocused: {
|
||||
borderColor: theme.colors.accent,
|
||||
borderColor: theme.colors.surface4,
|
||||
},
|
||||
// The band the fullscreen glyph sits in is the input's own padding, so a tap
|
||||
// anywhere in it (under the glyph, or where the glyph would be) is a tap on the
|
||||
|
||||
@@ -37,8 +37,6 @@ export function ComposerInputPresentation({
|
||||
onExit,
|
||||
inputWrapperRef,
|
||||
inputWrapperStyle,
|
||||
onInputWrapperPointerEnter,
|
||||
onInputWrapperPointerLeave,
|
||||
inputPointerEvents,
|
||||
attachmentSlot,
|
||||
showFullscreenButton,
|
||||
@@ -55,9 +53,6 @@ export function ComposerInputPresentation({
|
||||
onExit: () => void;
|
||||
inputWrapperRef: Ref<View>;
|
||||
inputWrapperStyle: ViewProps["style"];
|
||||
/** Hover tracking for the frame's border; the frame is a plain View, per docs/hover.md. */
|
||||
onInputWrapperPointerEnter: () => void;
|
||||
onInputWrapperPointerLeave: () => void;
|
||||
inputPointerEvents: ViewProps["pointerEvents"];
|
||||
attachmentSlot: ReactNode;
|
||||
showFullscreenButton: boolean;
|
||||
@@ -112,8 +107,6 @@ export function ComposerInputPresentation({
|
||||
ref={inputWrapperRef}
|
||||
style={fullscreen ? styles.fullscreenInputWrapper : inputWrapperStyle}
|
||||
pointerEvents={inputPointerEvents}
|
||||
onPointerEnter={onInputWrapperPointerEnter}
|
||||
onPointerLeave={onInputWrapperPointerLeave}
|
||||
>
|
||||
{fullscreen ? null : attachmentSlot}
|
||||
<View style={fullscreen ? styles.fullscreenTextSurface : styles.inlineTextSurface}>
|
||||
|
||||
@@ -4,7 +4,6 @@ import {
|
||||
computeCanStartDictation,
|
||||
type MessageInputEnterContext,
|
||||
resolveActiveSendBehavior,
|
||||
resolveComposerFramePhase,
|
||||
resolveComposerSurfacePresentation,
|
||||
resolveComposerSurfaceText,
|
||||
resolveGlyphRailOffset,
|
||||
@@ -615,23 +614,3 @@ describe("fullscreen glyph rail", () => {
|
||||
expect(offset + inkInset).toBeCloseTo(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe("composer frame phase", () => {
|
||||
const rest = { hovered: false, focused: false, readOnly: false, disabled: false };
|
||||
|
||||
it("shows the focus border while the editor has focus, hovered or not", () => {
|
||||
expect(resolveComposerFramePhase({ ...rest, focused: true })).toBe("active");
|
||||
expect(resolveComposerFramePhase({ ...rest, focused: true, hovered: true })).toBe("active");
|
||||
});
|
||||
|
||||
it("shows the hover border only while the pointer is over an unfocused frame", () => {
|
||||
expect(resolveComposerFramePhase({ ...rest, hovered: true })).toBe("hover");
|
||||
expect(resolveComposerFramePhase(rest)).toBe("rest");
|
||||
});
|
||||
|
||||
it("keeps a read-only or disabled frame at rest", () => {
|
||||
const engaged = { ...rest, hovered: true, focused: true };
|
||||
expect(resolveComposerFramePhase({ ...engaged, readOnly: true })).toBe("rest");
|
||||
expect(resolveComposerFramePhase({ ...engaged, disabled: true })).toBe("rest");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -3,10 +3,6 @@ import type { DaemonClient } from "@getpaseo/client/internal/daemon-client";
|
||||
import type { ActiveTurnBehavior } from "@getpaseo/protocol/messages";
|
||||
import type { MessagePayload, TextReplacement } from "@/composer/types";
|
||||
import type { MessageInputKeyboardActionKind } from "@/keyboard/actions";
|
||||
import {
|
||||
getControlInteractionPhase,
|
||||
type ControlInteractionPhase,
|
||||
} from "@/components/ui/control-geometry";
|
||||
|
||||
export type SendBehavior = ActiveTurnBehavior | "queue";
|
||||
|
||||
@@ -250,23 +246,6 @@ export function resolveGlyphRailOffset(input: {
|
||||
return -inkInset;
|
||||
}
|
||||
|
||||
/**
|
||||
* The composer frame follows the phases of the app's other inputs: focus wins over hover, and
|
||||
* a frame you can't type into (read-only, disabled) stays at rest.
|
||||
*/
|
||||
export function resolveComposerFramePhase(input: {
|
||||
hovered: boolean;
|
||||
focused: boolean;
|
||||
readOnly: boolean;
|
||||
disabled: boolean;
|
||||
}): ControlInteractionPhase {
|
||||
return getControlInteractionPhase({
|
||||
hovered: input.hovered,
|
||||
focused: input.focused,
|
||||
disabled: input.readOnly || input.disabled,
|
||||
});
|
||||
}
|
||||
|
||||
export function resolveComposerSurfaceText(
|
||||
liveText: string,
|
||||
replacement: TextReplacement,
|
||||
|
||||
@@ -514,6 +514,16 @@ describe("keyboard-shortcuts", () => {
|
||||
event: { key: "w", code: "KeyW", ctrlKey: true },
|
||||
context: { isMac: false, usesDesktopBindings: true, focusScope: "terminal" },
|
||||
},
|
||||
{
|
||||
name: "leaves Ctrl+W to the command center search field on non-mac desktop",
|
||||
event: { key: "w", code: "KeyW", ctrlKey: true },
|
||||
context: {
|
||||
isMac: false,
|
||||
usesDesktopBindings: true,
|
||||
focusScope: "command-center",
|
||||
commandCenterOpen: true,
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "does not switch tabs with Alt+Shift+] on mac desktop (Cmd+Shift+] only)",
|
||||
event: { key: "’", code: "BracketRight", altKey: true, shiftKey: true },
|
||||
|
||||
@@ -2,3 +2,4 @@ export { KeyboardShiftProvider, useKeyboardShiftStyle } from "./internal/provide
|
||||
export { useKeyboardShift } from "./internal/context";
|
||||
export { KeyboardTranslateView } from "./internal/translate";
|
||||
export { useKeyboardAnchor } from "./internal/anchor";
|
||||
export { useSettledKeyboardHeight } from "./internal/settled-height";
|
||||
|
||||
@@ -11,8 +11,8 @@ export function measureInWindow(element: View): Promise<WindowRect> {
|
||||
/**
|
||||
* The element's window rect with `frame`'s own transform left out. Whether
|
||||
* `measureInWindow` includes a transform depends on the driver: Reanimated commits
|
||||
* it to the shadow tree, RN's native driver commits it only when the view happens
|
||||
* to re-render. Fabric's `measureLayout` and a view's `measure` origin ignore
|
||||
* it to the shadow tree every frame, the iOS translate view commits it only once the
|
||||
* keyboard settles. Fabric's `measureLayout` and a view's `measure` origin ignore
|
||||
* transforms. The frame's parent must not move with the keyboard; the composer dock
|
||||
* is the only anchor host, and its parent is the stationary dock viewport.
|
||||
*/
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { KeyboardController, KeyboardEvents } from "react-native-keyboard-controller";
|
||||
|
||||
/**
|
||||
* The software keyboard's height once it has finished moving, or 0 while it is hidden.
|
||||
*
|
||||
* Views that ride the keyboard, like the composer, reach their final place only when the keyboard
|
||||
* settles. Measure against them after this value changes, not when the keyboard starts to move.
|
||||
*/
|
||||
export function useSettledKeyboardHeight(): number {
|
||||
const [height, setHeight] = useState(readSettledHeight);
|
||||
useEffect(() => {
|
||||
const subscriptions = [
|
||||
KeyboardEvents.addListener("keyboardDidShow", (event) => setHeight(event.height)),
|
||||
KeyboardEvents.addListener("keyboardDidHide", () => setHeight(0)),
|
||||
];
|
||||
setHeight(readSettledHeight());
|
||||
return () => {
|
||||
for (const subscription of subscriptions) subscription.remove();
|
||||
};
|
||||
}, []);
|
||||
return height;
|
||||
}
|
||||
|
||||
function readSettledHeight(): number {
|
||||
return KeyboardController.isVisible() ? KeyboardController.state().height : 0;
|
||||
}
|
||||
@@ -1,9 +1,12 @@
|
||||
import { useMemo, useEffect, useRef, type ReactNode } from "react";
|
||||
import { useCallback, useMemo, useEffect, useRef, type ReactNode } from "react";
|
||||
import { Animated, useAnimatedValue, type View, type ViewProps } from "react-native";
|
||||
import { useKeyboardAnimation } from "react-native-keyboard-controller";
|
||||
import { useAnimatedReaction } from "react-native-reanimated";
|
||||
import { useSafeAreaInsets } from "react-native-safe-area-context";
|
||||
import { KeyboardTranslationContext } from "./context";
|
||||
import { scheduleOnRN } from "react-native-worklets";
|
||||
import { KeyboardTranslationContext, useKeyboardShift } from "./context";
|
||||
import { useKeyboardTranslationScope } from "./measure";
|
||||
import { resolveKeyboardLift } from "./policy";
|
||||
|
||||
interface KeyboardTranslateViewProps extends ViewProps {
|
||||
children: ReactNode;
|
||||
@@ -73,6 +76,25 @@ export function KeyboardTranslateView({
|
||||
);
|
||||
const scope = useKeyboardTranslationScope(frameRef, translation);
|
||||
|
||||
// The native driver moves the view without telling the shadow tree, and Pressability
|
||||
// measures its press region there. With a stale region, a touch that drifts a few
|
||||
// points leaves it and the press is dropped. Commit the lift once the keyboard settles.
|
||||
const { layoutShift, isMoving } = useKeyboardShift();
|
||||
const commitRestingLift = useCallback(
|
||||
(shift: number) => {
|
||||
const lift = resolveKeyboardLift({ shift, ...translation });
|
||||
frameRef.current?.setNativeProps({ transform: [{ translateY: -lift }] });
|
||||
},
|
||||
[translation],
|
||||
);
|
||||
useAnimatedReaction(
|
||||
() => (isMoving.value ? null : layoutShift.value),
|
||||
(restingShift) => {
|
||||
if (restingShift !== null) scheduleOnRN(commitRestingLift, restingShift);
|
||||
},
|
||||
[commitRestingLift],
|
||||
);
|
||||
|
||||
return (
|
||||
<Animated.View ref={frameRef} style={[style, keyboardStyle]} {...props}>
|
||||
<KeyboardTranslationContext.Provider value={scope}>
|
||||
|
||||
@@ -7,7 +7,10 @@ import {
|
||||
} from "@/stores/session-store";
|
||||
import type { StreamItem } from "@/types/stream";
|
||||
import { normalizeAgentSnapshot } from "@/utils/agent-snapshots";
|
||||
import { createPluginWorkspaceSnapshot } from "@/plugins/client-state/snapshots";
|
||||
import {
|
||||
createPluginAgentSnapshot,
|
||||
createPluginWorkspaceSnapshot,
|
||||
} from "@/plugins/client-state/snapshots";
|
||||
import { ReplicaCache } from ".";
|
||||
import type { DirectoryCheckpoint } from "@/runtime/replica-cache";
|
||||
import type { ReplicaHostRows, ReplicaRow, ReplicaRowChanges, ReplicaRowStore } from "./row-store";
|
||||
@@ -158,6 +161,7 @@ function agent(id = "agent-1"): Agent {
|
||||
persistence: null,
|
||||
title: "Cached agent",
|
||||
labels: {},
|
||||
metadata: {},
|
||||
},
|
||||
SERVER_ID,
|
||||
),
|
||||
@@ -1433,3 +1437,40 @@ it("retains workspace metadata across replica-cache reload and invalidates pre-m
|
||||
projects: checkpoint.projects,
|
||||
});
|
||||
});
|
||||
|
||||
it("restores agent metadata for plugins when the directory cache reopens", async () => {
|
||||
const storage = new MemoryStorage();
|
||||
const writer = createCache(storage);
|
||||
const baseline = directory();
|
||||
const metadata = { "plugin.waiting": { kind: "plan", at: "2026-07-18T08:02:00.000Z" } };
|
||||
baseline.agents.set("agent-1", { ...agent(), metadata });
|
||||
commitDirectory(writer, SERVER_ID, baseline);
|
||||
await writer.flush();
|
||||
|
||||
const restored = await createCache(storage).readDirectory(SERVER_ID);
|
||||
expect(
|
||||
createPluginAgentSnapshot(restored.agents.get("agent-1")!, "workspace-1").metadata,
|
||||
).toEqual(metadata);
|
||||
expect(restored.checkpoint).toEqual(baseline.checkpoint);
|
||||
});
|
||||
|
||||
it("discards the agent cursor when a pre-metadata agent row is restored", async () => {
|
||||
const storage = new MemoryStorage();
|
||||
const writer = createCache(storage);
|
||||
const baseline = directory({
|
||||
agents: { generation: "g", afterSeq: 12 },
|
||||
projects: { generation: "g", afterSeq: 4 },
|
||||
});
|
||||
commitDirectory(writer, SERVER_ID, baseline);
|
||||
await writer.flush();
|
||||
|
||||
const key = `${SERVER_ID}:agent:agent-1`;
|
||||
const row = storage.rows.get(key)!;
|
||||
const legacyPayload = JSON.parse(row.payload) as { snapshot: Record<string, unknown> };
|
||||
delete legacyPayload.snapshot.metadata;
|
||||
storage.rows.set(key, { ...row, payload: JSON.stringify(legacyPayload) });
|
||||
|
||||
const restored = await createCache(storage).readDirectory(SERVER_ID);
|
||||
expect(restored.checkpoint).toEqual({ projects: baseline.checkpoint.projects });
|
||||
expect(restored.agents.size).toBe(0);
|
||||
});
|
||||
|
||||
@@ -257,6 +257,8 @@ const StoredAgentSnapshotSchema = z.strictObject({
|
||||
lastError: z.string().optional(),
|
||||
title: z.string().nullable(),
|
||||
labels: z.record(z.string(), z.string()),
|
||||
// Require metadata so older rows invalidate the agent cursor and refetch from the daemon.
|
||||
metadata: z.record(z.string(), z.unknown() as z.ZodType<JsonValue>),
|
||||
// Optional: clients without background_agents never received a background agent to cache.
|
||||
background: z.boolean().optional(),
|
||||
requiresAttention: z.boolean().optional(),
|
||||
@@ -705,6 +707,7 @@ function serializeAgent(agent: Agent): StoredAgent {
|
||||
...(agent.lastError ? { lastError: agent.lastError } : {}),
|
||||
title: agent.title,
|
||||
labels: agent.labels,
|
||||
metadata: agent.metadata ?? {},
|
||||
...(agent.background ? { background: true } : {}),
|
||||
requiresAttention: agent.requiresAttention ?? false,
|
||||
backgroundWork: agent.backgroundWork,
|
||||
|
||||
@@ -14,6 +14,12 @@ const tsgoEntry = path.join(
|
||||
"bin/tsgo.js",
|
||||
);
|
||||
|
||||
it("the test environment loads Expo Image", async () => {
|
||||
const { Image } = await import("expo-image");
|
||||
|
||||
expect(Image).toEqual(expect.any(Function));
|
||||
});
|
||||
|
||||
it("the test configuration typechecks with Expo's generated environment declaration", () => {
|
||||
const fixtureDir = mkdtempSync(path.join(appDir, ".vitest-expo-env-"));
|
||||
try {
|
||||
|
||||
@@ -19,6 +19,23 @@ const resolvePackageEntry = (packageName: string) => {
|
||||
|
||||
export default defineConfig({
|
||||
plugins: [
|
||||
{
|
||||
name: "bundle-expo-runtime",
|
||||
// Expo initializes import.meta through a literal require of TypeScript.
|
||||
// Bundle that boundary so Node need not resolve Metro's extensionless require.
|
||||
async transform(_source, id) {
|
||||
if (!id.endsWith("/expo/src/winter/runtime.ts")) return;
|
||||
const result = await build({
|
||||
entryPoints: [id],
|
||||
bundle: true,
|
||||
format: "esm",
|
||||
platform: "neutral",
|
||||
define: { __DEV__: "false" },
|
||||
write: false,
|
||||
});
|
||||
return { code: result.outputFiles[0].text, map: null };
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "markdown-wasm-commonjs-export",
|
||||
transform(source, id) {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { expect, test } from "vitest";
|
||||
import { expect, test, vi } from "vitest";
|
||||
import { CLIENT_CAPS } from "@getpaseo/protocol/client-capabilities";
|
||||
import { DaemonClient, type DaemonTransport } from "./daemon-client";
|
||||
|
||||
@@ -1052,3 +1052,41 @@ test("subscribeFile returns its initial version without calling the change callb
|
||||
await h.client.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("findWorkspace works across legacy pre-workspaceMultiplicity daemons", async () => {
|
||||
const h = connection({ ownedSubscriptions: false, workspaceMultiplicity: false });
|
||||
try {
|
||||
const connecting = h.client.connect();
|
||||
h.open();
|
||||
await connecting;
|
||||
const finding = h.client.findWorkspace("/second");
|
||||
const firstReq = h.sent.at(-1)!.message!;
|
||||
expect(firstReq.type).toBe("fetch_agents_request");
|
||||
h.receive({
|
||||
type: "fetch_agents_response",
|
||||
payload: {
|
||||
requestId: firstReq.requestId,
|
||||
entries: [legacyAgent({ id: "a1", cwd: "/first" })],
|
||||
pageInfo: { hasMore: true, nextCursor: "page-2", prevCursor: null },
|
||||
},
|
||||
});
|
||||
await vi.waitFor(() =>
|
||||
expect(h.sent.filter((frame) => frame.message?.type === "fetch_agents_request")).toHaveLength(
|
||||
2,
|
||||
),
|
||||
);
|
||||
const secondReq = h.sent.at(-1)!.message!;
|
||||
h.receive({
|
||||
type: "fetch_agents_response",
|
||||
payload: {
|
||||
requestId: secondReq.requestId,
|
||||
entries: [legacyAgent({ id: "a2", cwd: "/second" })],
|
||||
pageInfo: { hasMore: false, nextCursor: null, prevCursor: "page-2" },
|
||||
},
|
||||
});
|
||||
const found = await finding;
|
||||
expect(found).toMatchObject({ id: "/second", workspaceDirectory: "/second" });
|
||||
} finally {
|
||||
await h.client.close();
|
||||
}
|
||||
});
|
||||
|
||||
@@ -3101,7 +3101,9 @@ export class DaemonClientCore {
|
||||
workspaceId: string,
|
||||
options?: { requestId?: string },
|
||||
): Promise<FetchWorkspacesEntry | null> {
|
||||
const filter = this.supportsBackgroundWorkspaces() ? { includeBackground: true } : {};
|
||||
const filter = this.supportsBackgroundWorkspaces()
|
||||
? { query: workspaceId, includeBackground: true }
|
||||
: { query: workspaceId };
|
||||
let cursor: string | undefined;
|
||||
let requestId = options?.requestId;
|
||||
do {
|
||||
|
||||
@@ -10899,3 +10899,137 @@ test("disposing a route before its deferred close does not reopen it on origin r
|
||||
expect(opened).not.toHaveBeenCalled();
|
||||
expect(closed).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
describe("findWorkspace", () => {
|
||||
function makeWorkspaceEntry(id: string, overrides?: Partial<Record<string, unknown>>) {
|
||||
return {
|
||||
id,
|
||||
projectId: "prj_1",
|
||||
projectDisplayName: "Project 1",
|
||||
projectRootPath: "/tmp/project",
|
||||
workspaceDirectory: `/tmp/project/${id}`,
|
||||
projectKind: "git",
|
||||
workspaceKind: "local_checkout",
|
||||
name: id,
|
||||
archivingAt: null,
|
||||
status: "done",
|
||||
activityAt: null,
|
||||
diffStat: null,
|
||||
gitRuntime: null,
|
||||
githubRuntime: null,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
test("sends filter.query with includeBackground when supported and paginates to the exact id match", async () => {
|
||||
const logger = createMockLogger();
|
||||
const mock = createMockTransport();
|
||||
const client = new DaemonClient({
|
||||
url: "ws://test",
|
||||
clientId: "clsk_unit_test",
|
||||
logger,
|
||||
reconnect: { enabled: false },
|
||||
transportFactory: () => mock.transport,
|
||||
});
|
||||
clients.push(client);
|
||||
|
||||
const connectPromise = client.connect();
|
||||
mock.triggerOpen({
|
||||
features: { workspaceMultiplicity: true, backgroundWorkspaces: true },
|
||||
});
|
||||
await connectPromise;
|
||||
|
||||
const targetId = "wks_target";
|
||||
const finding = client.findWorkspace(targetId, { requestId: "req-find-1" });
|
||||
|
||||
const firstRequest = parseSentFrame(mock.sent[0]);
|
||||
expect(firstRequest).toMatchObject({
|
||||
type: "fetch_workspaces_request",
|
||||
requestId: "req-find-1",
|
||||
filter: { query: targetId, includeBackground: true },
|
||||
page: { limit: 200 },
|
||||
});
|
||||
|
||||
// First page returns a workspace whose name contains targetId, plus a next cursor.
|
||||
mock.triggerMessage(
|
||||
wrapSessionMessage({
|
||||
type: "fetch_workspaces_response",
|
||||
payload: {
|
||||
requestId: "req-find-1",
|
||||
entries: [makeWorkspaceEntry("wks_other", { name: `notes-${targetId}` })],
|
||||
emptyProjects: [],
|
||||
pageInfo: { nextCursor: "cursor-page-2", prevCursor: null, hasMore: true },
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
await vi.waitFor(() => expect(mock.sent).toHaveLength(2));
|
||||
const secondRequest = parseSentFrame(mock.sent[1]);
|
||||
expect(secondRequest).toMatchObject({
|
||||
type: "fetch_workspaces_request",
|
||||
filter: { query: targetId, includeBackground: true },
|
||||
page: { limit: 200, cursor: "cursor-page-2" },
|
||||
});
|
||||
expect(secondRequest.requestId).not.toBe("req-find-1");
|
||||
|
||||
const targetEntry = makeWorkspaceEntry(targetId, { background: true });
|
||||
mock.triggerMessage(
|
||||
wrapSessionMessage({
|
||||
type: "fetch_workspaces_response",
|
||||
payload: {
|
||||
requestId: secondRequest.requestId,
|
||||
entries: [targetEntry],
|
||||
emptyProjects: [],
|
||||
pageInfo: { nextCursor: null, prevCursor: "cursor-page-2", hasMore: false },
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
const found = await finding;
|
||||
expect(found).toMatchObject({ id: targetId, background: true });
|
||||
});
|
||||
|
||||
test("sends filter.query without includeBackground on hosts that lack backgroundWorkspaces", async () => {
|
||||
const logger = createMockLogger();
|
||||
const mock = createMockTransport();
|
||||
const client = new DaemonClient({
|
||||
url: "ws://test",
|
||||
clientId: "clsk_unit_test",
|
||||
logger,
|
||||
reconnect: { enabled: false },
|
||||
transportFactory: () => mock.transport,
|
||||
});
|
||||
clients.push(client);
|
||||
|
||||
const connectPromise = client.connect();
|
||||
mock.triggerOpen({
|
||||
features: { workspaceMultiplicity: true },
|
||||
});
|
||||
await connectPromise;
|
||||
|
||||
const targetId = "wks_older";
|
||||
const finding = client.findWorkspace(targetId);
|
||||
|
||||
const request = parseSentFrame(mock.sent[0]);
|
||||
expect(request).toMatchObject({
|
||||
type: "fetch_workspaces_request",
|
||||
filter: { query: targetId },
|
||||
page: { limit: 200 },
|
||||
});
|
||||
expect(request.filter).not.toHaveProperty("includeBackground");
|
||||
|
||||
mock.triggerMessage(
|
||||
wrapSessionMessage({
|
||||
type: "fetch_workspaces_response",
|
||||
payload: {
|
||||
requestId: request.requestId,
|
||||
entries: [makeWorkspaceEntry(targetId)],
|
||||
emptyProjects: [],
|
||||
pageInfo: { nextCursor: null, prevCursor: null, hasMore: false },
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
await expect(finding).resolves.toMatchObject({ id: targetId });
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
#!/usr/bin/env node
|
||||
|
||||
import { spawn } from "node:child_process";
|
||||
import { execFileSync, spawn } from "node:child_process";
|
||||
import fs from "node:fs";
|
||||
import { createServer } from "node:http";
|
||||
import net from "node:net";
|
||||
@@ -363,6 +363,43 @@ async function openBrowserWorkspace(page, workspaceKey) {
|
||||
await expect(page.getByTestId(`workspace-deck-entry-${workspaceKey}`)).toBeVisible();
|
||||
}
|
||||
|
||||
async function verifyCloseTabShortcut({ page, inspectorPort, workspaceKey }) {
|
||||
await openBrowserWorkspace(page, workspaceKey);
|
||||
const workspace = page.getByTestId(`workspace-deck-entry-${workspaceKey}`);
|
||||
await workspace.getByTestId("workspace-new-tab-button").filter({ visible: true }).first().click();
|
||||
await page.getByTestId("workspace-new-tab-menu-agent").filter({ visible: true }).first().click();
|
||||
const draft = workspace
|
||||
.locator('[data-testid^="workspace-tab-draft_"]')
|
||||
.filter({ visible: true });
|
||||
await expect(draft).toBeVisible();
|
||||
|
||||
// Send the key through X11 so Electron can handle it as a native menu accelerator.
|
||||
const { DISPLAY, XAUTHORITY } = await evaluateDesktopWindow(
|
||||
inspectorPort,
|
||||
"win.focus(); win.webContents.focus(); return { DISPLAY: process.env.DISPLAY, XAUTHORITY: process.env.XAUTHORITY };",
|
||||
);
|
||||
assert(DISPLAY && XAUTHORITY, "Ctrl+W regression requires the private Xvfb display");
|
||||
const pressCloseTabShortcut = () =>
|
||||
execFileSync("xdotool", ["key", "--clearmodifiers", "ctrl+w"], {
|
||||
env: { ...process.env, DISPLAY, XAUTHORITY },
|
||||
});
|
||||
|
||||
// Command Center disables the workspace close-tab binding.
|
||||
await page.getByTestId("sidebar-search").click();
|
||||
const commandCenterInput = page.getByTestId("command-center-input");
|
||||
await expect(commandCenterInput).toBeFocused();
|
||||
pressCloseTabShortcut();
|
||||
await expect(commandCenterInput).toBeVisible();
|
||||
await expect(draft).toBeVisible();
|
||||
await page.keyboard.press("Escape");
|
||||
await expect(commandCenterInput).toBeHidden();
|
||||
|
||||
pressCloseTabShortcut();
|
||||
await expect(draft).toHaveCount(0);
|
||||
await expect(workspace).toBeVisible();
|
||||
console.log("Ctrl+W closed the workspace tab and kept the desktop window open.");
|
||||
}
|
||||
|
||||
async function openSecondDesktopWindow(page) {
|
||||
const nextWindow = page.context().waitForEvent("page", { timeout: timeoutMs });
|
||||
await page.evaluate(() => window.paseoDesktop.window.openNew());
|
||||
@@ -1429,7 +1466,7 @@ async function main() {
|
||||
process.execPath,
|
||||
devRunner,
|
||||
`--inspect=127.0.0.1:${inspectorPort}`,
|
||||
...(process.platform === "linux" ? ["--no-sandbox"] : []),
|
||||
...(process.platform === "linux" ? ["--no-sandbox", "--ozone-platform=x11"] : []),
|
||||
];
|
||||
const desktopCommand = process.platform === "linux" ? "xvfb-run" : desktopArgs.shift();
|
||||
const desktopCommandArgs =
|
||||
@@ -1521,6 +1558,14 @@ async function main() {
|
||||
return;
|
||||
}
|
||||
|
||||
if (process.platform === "linux") {
|
||||
await verifyCloseTabShortcut({
|
||||
page,
|
||||
inspectorPort,
|
||||
workspaceKey: `${status.serverId}:${workspaceIds[0]}`,
|
||||
});
|
||||
}
|
||||
|
||||
const adaptiveTheme = await runAdaptiveThemeRegression(artifactDir);
|
||||
await runAppearanceFontSizeRegression(page);
|
||||
|
||||
|
||||
@@ -1,5 +1,13 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { reloadActiveBrowserOrWindow } from "./menu.js";
|
||||
import { buildApplicationMenuTemplate, reloadActiveBrowserOrWindow } from "./menu.js";
|
||||
|
||||
it.runIf(process.platform !== "darwin")("keeps the Window > Close action without Ctrl+W", () => {
|
||||
const template = buildApplicationMenuTemplate({ onNewWindow: () => {} }, false);
|
||||
const windowMenu = template.find((item) => item.label === "Window");
|
||||
const closeItem = windowMenu?.submenu?.find((item) => item.role === "close");
|
||||
|
||||
expect(closeItem).toMatchObject({ role: "close", accelerator: "", registerAccelerator: false });
|
||||
});
|
||||
|
||||
class FakeWebContents {
|
||||
public readonly reloads: string[] = [];
|
||||
|
||||
@@ -64,12 +64,18 @@ export function reloadActiveBrowserOrWindow({
|
||||
win.webContents.reload();
|
||||
}
|
||||
|
||||
function buildApplicationMenuTemplate(
|
||||
export function buildApplicationMenuTemplate(
|
||||
options: ApplicationMenuOptions,
|
||||
capturing: boolean,
|
||||
): Electron.MenuItemConstructorOptions[] {
|
||||
const isMac = process.platform === "darwin";
|
||||
const zoomEnabled = !capturing;
|
||||
const closeWindowItem: Electron.MenuItemConstructorOptions = { role: "close" };
|
||||
if (!isMac) {
|
||||
// Electron's Close role defaults to Ctrl+W, which Paseo uses to close tabs.
|
||||
closeWindowItem.accelerator = "";
|
||||
closeWindowItem.registerAccelerator = false;
|
||||
}
|
||||
|
||||
return [
|
||||
...(isMac
|
||||
@@ -175,7 +181,7 @@ function buildApplicationMenuTemplate(
|
||||
{ role: "zoom" },
|
||||
...(isMac
|
||||
? [{ type: "separator" as const }, { role: "front" as const }]
|
||||
: [{ role: "close" as const }]),
|
||||
: [closeWindowItem]),
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
@@ -54,6 +54,27 @@ function createQueryMock(events: unknown[], options: QueryMockOptions = {}): Que
|
||||
} as Query;
|
||||
}
|
||||
|
||||
function createAcknowledgingQuery(prompt: ClaudeQueryInput["prompt"], events: unknown[]): Query {
|
||||
if (typeof prompt === "string") throw new Error("Expected a streaming prompt");
|
||||
const submitted = prompt[Symbol.asyncIterator]().next();
|
||||
const query = createQueryMock([
|
||||
{ ...(events[0] as object), claude_code_version: "2.1.310" },
|
||||
...events.slice(1),
|
||||
]);
|
||||
const nextEvent = query.next.bind(query);
|
||||
let acknowledged = false;
|
||||
query.next = async () => {
|
||||
if (acknowledged) return nextEvent();
|
||||
acknowledged = true;
|
||||
const { value } = await submitted;
|
||||
return {
|
||||
done: false,
|
||||
value: { type: "command_lifecycle", command_uuid: value.uuid, state: "started" },
|
||||
} as Awaited<ReturnType<Query["next"]>>;
|
||||
};
|
||||
return query;
|
||||
}
|
||||
|
||||
function createChildProcessStub(): ChildProcess & { killSignals: (NodeJS.Signals | number)[] } {
|
||||
const child = new EventEmitter() as ChildProcess & {
|
||||
killSignals: (NodeJS.Signals | number)[];
|
||||
@@ -186,11 +207,42 @@ describe("Claude runtime exit", () => {
|
||||
}
|
||||
});
|
||||
|
||||
test("fails a running workflow when its idle Claude runtime exits", async () => {
|
||||
test("stays quiet when the idle process exits cleanly with nothing running", async () => {
|
||||
let capturedOptions: Options | undefined;
|
||||
const queryFactory = vi.fn(({ options }: ClaudeQueryInput) => {
|
||||
const queryFactory = vi.fn(({ options, prompt }: ClaudeQueryInput) => {
|
||||
capturedOptions = options;
|
||||
return createQueryMock(RUNNING_WORKFLOW_TURN_EVENTS);
|
||||
return createAcknowledgingQuery(prompt, COMPLETED_TURN_EVENTS);
|
||||
});
|
||||
const child = createChildProcessStub();
|
||||
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() });
|
||||
|
||||
try {
|
||||
await session.run("first turn");
|
||||
await expect.poll(() => session.canStopRuntime?.()).toBe(true);
|
||||
capturedOptions?.spawnClaudeCodeProcess?.(SPAWN_OPTIONS);
|
||||
|
||||
const events: AgentStreamEvent[] = [];
|
||||
session.subscribe((event) => events.push(event));
|
||||
|
||||
child.emit("exit", 0, null);
|
||||
|
||||
expect(events.some((event) => event.type === "turn_failed")).toBe(false);
|
||||
} finally {
|
||||
await session.close();
|
||||
}
|
||||
});
|
||||
|
||||
test.each([0, 1])("fails a running workflow on idle exit with code %i", async (code) => {
|
||||
let capturedOptions: Options | undefined;
|
||||
const queryFactory = vi.fn(({ options, prompt }: ClaudeQueryInput) => {
|
||||
capturedOptions = options;
|
||||
return createAcknowledgingQuery(prompt, RUNNING_WORKFLOW_TURN_EVENTS);
|
||||
});
|
||||
const child = createChildProcessStub();
|
||||
vi.spyOn(spawnUtils, "spawnProcess").mockReturnValue(child);
|
||||
@@ -205,9 +257,11 @@ describe("Claude runtime exit", () => {
|
||||
|
||||
try {
|
||||
await session.run("run a workflow in the background");
|
||||
await expect.poll(() => session.canStopRuntime?.()).toBe(true);
|
||||
capturedOptions?.spawnClaudeCodeProcess?.(SPAWN_OPTIONS);
|
||||
child.emit("exit", 1, null);
|
||||
child.emit("exit", code, null);
|
||||
|
||||
expect(events.some((event) => event.type === "turn_failed")).toBe(true);
|
||||
const workflowUpserts = events
|
||||
.filter((event) => event.type === "provider_subagent")
|
||||
.map((event) => event.event)
|
||||
@@ -348,11 +402,11 @@ describe("Claude runtime exit", () => {
|
||||
}
|
||||
});
|
||||
|
||||
test("reports the failure before it empties background work when the idle process dies", async () => {
|
||||
test.each([0, 1])("reports idle exit code %i before clearing background work", async (code) => {
|
||||
let capturedOptions: Options | undefined;
|
||||
const queryFactory = vi.fn(({ options }: ClaudeQueryInput) => {
|
||||
const queryFactory = vi.fn(({ options, prompt }: ClaudeQueryInput) => {
|
||||
capturedOptions = options;
|
||||
return createQueryMock(BACKGROUND_SHELL_TURN_EVENTS);
|
||||
return createAcknowledgingQuery(prompt, BACKGROUND_SHELL_TURN_EVENTS);
|
||||
});
|
||||
const child = createChildProcessStub();
|
||||
vi.spyOn(spawnUtils, "spawnProcess").mockReturnValue(child);
|
||||
@@ -364,12 +418,17 @@ describe("Claude runtime exit", () => {
|
||||
const session = await client.createSession({ provider: "claude", cwd: process.cwd() });
|
||||
|
||||
try {
|
||||
await session.run("start a background shell");
|
||||
capturedOptions?.spawnClaudeCodeProcess?.(SPAWN_OPTIONS);
|
||||
const events: AgentStreamEvent[] = [];
|
||||
session.subscribe((event) => events.push(event));
|
||||
await session.run("start a background shell");
|
||||
await expect
|
||||
.poll(() => events)
|
||||
.toContainEqual(expect.objectContaining({ type: "turn_completed" }));
|
||||
expect(await session.canStopRuntime?.()).toBe(false);
|
||||
capturedOptions?.spawnClaudeCodeProcess?.(SPAWN_OPTIONS);
|
||||
events.length = 0;
|
||||
|
||||
child.emit("exit", 1, null);
|
||||
child.emit("exit", code, null);
|
||||
|
||||
// A watcher that sees the work end first takes the idle child for settled.
|
||||
expect(
|
||||
|
||||
@@ -3470,6 +3470,10 @@ class ClaudeAgentSession implements AgentSession {
|
||||
}
|
||||
|
||||
async canStopRuntime(): Promise<boolean> {
|
||||
return this.isRuntimeSafeToStop();
|
||||
}
|
||||
|
||||
private isRuntimeSafeToStop(): boolean {
|
||||
return (
|
||||
!this.activeForegroundTurnId &&
|
||||
!this.autonomousTurn &&
|
||||
@@ -4660,6 +4664,22 @@ class ClaudeAgentSession implements AgentSession {
|
||||
return;
|
||||
}
|
||||
this.childProcess = null;
|
||||
if (
|
||||
code === 0 &&
|
||||
signal === null &&
|
||||
this.isRuntimeSafeToStop() &&
|
||||
!this.notificationTurnId &&
|
||||
!this.taskProtocolSource.hasRunningTasks()
|
||||
) {
|
||||
this.query = null;
|
||||
this.input = null;
|
||||
this.failRunningRuntimeTasks();
|
||||
this.logger.info(
|
||||
{ agentId: this.agentId, pid: child.pid },
|
||||
"Claude runtime exited cleanly while idle",
|
||||
);
|
||||
return;
|
||||
}
|
||||
this.logger.warn(
|
||||
{ agentId: this.agentId, pid: child.pid, code, signal },
|
||||
"Claude runtime exited unexpectedly",
|
||||
|
||||
@@ -319,6 +319,13 @@ export class ClaudeTaskProtocolSource {
|
||||
return observations;
|
||||
}
|
||||
|
||||
hasRunningTasks(): boolean {
|
||||
for (const id of this.declaredIds) {
|
||||
if (this.lastStatusById.get(id) === "running") return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/** A lost Claude process terminates every task it owned, including backgrounded workflows. */
|
||||
failRunningTasks(): SubagentObservation[] {
|
||||
const observations: SubagentObservation[] = [];
|
||||
|
||||
@@ -1432,6 +1432,8 @@ export class Session {
|
||||
listProviderSubagentActivity: async () => this.agentManager.listProviderSubagentActivity(),
|
||||
listTerminalActivityContributions: () => this.listTerminalActivityContributions(),
|
||||
isProviderVisibleToClient: (provider) => this.isProviderVisibleToClient(provider),
|
||||
resolveWorkspaceName: (workspace, nameOptions) =>
|
||||
this.resolveWorkspaceDescriptorName(workspace, nameOptions),
|
||||
buildWorkspaceDescriptor: (input) => this.buildWorkspaceDescriptor(input),
|
||||
});
|
||||
|
||||
@@ -6435,7 +6437,7 @@ export class Session {
|
||||
worktreeSlug,
|
||||
projectKind: (resolvedProjectRecord?.kind ?? "directory") === "git" ? "git" : "non_git",
|
||||
workspaceKind: workspace.kind,
|
||||
name: resolveWorkspaceDisplayName(workspace),
|
||||
name: this.resolveWorkspaceDescriptorName(workspace, { includeGitData: false }),
|
||||
title: workspace.title,
|
||||
pinnedAt: workspace.pinnedAt,
|
||||
...(workspace.labels && workspace.labels.length > 0 ? { labels: workspace.labels } : {}),
|
||||
@@ -6495,12 +6497,9 @@ export class Session {
|
||||
return base;
|
||||
}
|
||||
|
||||
const checkout = checkoutLiteFromGitSnapshot(workspace.cwd, snapshot.git);
|
||||
const displayName = deriveWorkspaceDisplayName({ cwd: workspace.cwd, checkout });
|
||||
|
||||
return {
|
||||
...base,
|
||||
name: resolveWorkspaceName({ title: workspace.title, derivedDisplayName: displayName }),
|
||||
name: this.resolveWorkspaceDescriptorName(workspace, { includeGitData: true, snapshot }),
|
||||
diffStat: snapshot.git.diffStat ?? null,
|
||||
gitRuntime: this.buildWorkspaceGitRuntimePayload(snapshot) ?? undefined,
|
||||
githubRuntime: this.buildWorkspaceGitHubRuntimePayload(snapshot),
|
||||
@@ -6563,6 +6562,27 @@ export class Session {
|
||||
};
|
||||
}
|
||||
|
||||
private resolveWorkspaceDescriptorName(
|
||||
workspace: PersistedWorkspaceRecord,
|
||||
options: { includeGitData: boolean; snapshot?: WorkspaceGitRuntimeSnapshot | null },
|
||||
): string {
|
||||
if (workspace.title != null) {
|
||||
return workspace.title;
|
||||
}
|
||||
if (options.includeGitData && workspace.kind !== "directory") {
|
||||
const snapshot =
|
||||
options.snapshot !== undefined
|
||||
? options.snapshot
|
||||
: this.workspaceRuntimeStore.get(workspace.cwd);
|
||||
if (snapshot) {
|
||||
const checkout = checkoutLiteFromGitSnapshot(workspace.cwd, snapshot.git);
|
||||
const displayName = deriveWorkspaceDisplayName({ cwd: workspace.cwd, checkout });
|
||||
return resolveWorkspaceName({ title: workspace.title, derivedDisplayName: displayName });
|
||||
}
|
||||
}
|
||||
return resolveWorkspaceDisplayName(workspace);
|
||||
}
|
||||
|
||||
private async buildWorkspaceDescriptor(input: {
|
||||
workspace: PersistedWorkspaceRecord;
|
||||
projectRecord?: PersistedProjectRecord | null;
|
||||
|
||||
@@ -11066,3 +11066,118 @@ test("newer workspace update supersedes an older pending update during multi-wor
|
||||
await session.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test("fetch_workspaces_request pre-filters without building unrelated descriptors and still matches live git branch names", async () => {
|
||||
const root = mkdtempSync(path.join(tmpdir(), "paseo-prefilter-"));
|
||||
const targetDir = path.join(root, "target");
|
||||
const unrelatedDir = path.join(root, "unrelated");
|
||||
mkdirSync(targetDir, { recursive: true });
|
||||
mkdirSync(unrelatedDir, { recursive: true });
|
||||
writeFileSync(
|
||||
path.join(targetDir, "paseo.json"),
|
||||
JSON.stringify({ scripts: { dev: { command: "echo ok" } } }),
|
||||
);
|
||||
// Make unrelated workspace's paseo.json invalid JSON so any read would log a parse failure.
|
||||
writeFileSync(path.join(unrelatedDir, "paseo.json"), "{ invalid json");
|
||||
|
||||
const workspaceRuntimeStore = createWorkspaceRuntimeStore();
|
||||
workspaceRuntimeStore.set(
|
||||
createWorkspaceRuntimeSnapshot(targetDir, {
|
||||
git: { currentBranch: "feature/live-branch-only" },
|
||||
}),
|
||||
);
|
||||
const warnings: Array<Record<string, unknown>> = [];
|
||||
const emitted: SessionOutboundMessage[] = [];
|
||||
const project = createPersistedProjectRecord({
|
||||
projectId: "prj_prefilter",
|
||||
rootPath: root,
|
||||
kind: "git",
|
||||
displayName: "prefilter",
|
||||
createdAt: "2026-03-01T12:00:00.000Z",
|
||||
updatedAt: "2026-03-01T12:00:00.000Z",
|
||||
});
|
||||
const targetWorkspace = createPersistedWorkspaceRecord({
|
||||
workspaceId: "wks_target_only",
|
||||
projectId: project.projectId,
|
||||
cwd: targetDir,
|
||||
kind: "local_checkout",
|
||||
displayName: "persisted-main",
|
||||
createdAt: "2026-03-01T12:00:00.000Z",
|
||||
updatedAt: "2026-03-01T12:00:00.000Z",
|
||||
});
|
||||
const unrelatedWorkspace = createPersistedWorkspaceRecord({
|
||||
workspaceId: "wks_unrelated_other",
|
||||
projectId: project.projectId,
|
||||
cwd: unrelatedDir,
|
||||
kind: "local_checkout",
|
||||
displayName: "other",
|
||||
createdAt: "2026-03-01T12:00:00.000Z",
|
||||
updatedAt: "2026-03-01T12:00:00.000Z",
|
||||
});
|
||||
|
||||
const session = asTestSession(
|
||||
createSessionForWorkspaceTests({
|
||||
workspaceRuntimeStore,
|
||||
onMessage: (message) => emitted.push(message),
|
||||
}),
|
||||
);
|
||||
const origWarn = session.sessionLogger.warn.bind(session.sessionLogger);
|
||||
session.sessionLogger.warn = ((...args: unknown[]) => {
|
||||
warnings.push({ args });
|
||||
return (origWarn as (...a: unknown[]) => unknown)(...args);
|
||||
}) as typeof session.sessionLogger.warn;
|
||||
session.listAgentPayloads = async () => [];
|
||||
session.projectRegistry.list = async () => [project];
|
||||
session.projectRegistry.get = async (id: string) => (id === project.projectId ? project : null);
|
||||
session.workspaceRegistry.listAll = session.workspaceRegistry.listActive = async () => [
|
||||
targetWorkspace,
|
||||
unrelatedWorkspace,
|
||||
];
|
||||
session.workspaceRegistry.get = async (id: string) =>
|
||||
[targetWorkspace, unrelatedWorkspace].find((w) => w.workspaceId === id) ?? null;
|
||||
|
||||
const builtWorkspaceIds: string[] = [];
|
||||
const origBuildDescriptor = session.buildWorkspaceDescriptor.bind(session);
|
||||
session.buildWorkspaceDescriptor = async (input: {
|
||||
workspace: PersistedWorkspaceRecord;
|
||||
projectRecord?: PersistedProjectRecord | null;
|
||||
includeGitData: boolean;
|
||||
}) => {
|
||||
builtWorkspaceIds.push(input.workspace.workspaceId);
|
||||
return origBuildDescriptor(input);
|
||||
};
|
||||
|
||||
try {
|
||||
// 1. Single-ID lookup must build ONLY wks_target_only and never touch unrelatedDir.
|
||||
await session.handleMessage({
|
||||
type: "fetch_workspaces_request",
|
||||
requestId: "req-single-id",
|
||||
filter: { query: targetWorkspace.workspaceId, includeBackground: true },
|
||||
});
|
||||
const byIdResponse = findByType(emitted, "fetch_workspaces_response");
|
||||
expect(byIdResponse?.payload.entries.map((entry) => entry.id)).toEqual([
|
||||
targetWorkspace.workspaceId,
|
||||
]);
|
||||
expect(builtWorkspaceIds).toEqual([targetWorkspace.workspaceId]);
|
||||
expect(warnings).toEqual([]);
|
||||
|
||||
// 2. Query matching the live git branch name (not persisted displayName) must still find it
|
||||
// without building the unrelated workspace.
|
||||
emitted.length = 0;
|
||||
builtWorkspaceIds.length = 0;
|
||||
await session.handleMessage({
|
||||
type: "fetch_workspaces_request",
|
||||
requestId: "req-live-branch",
|
||||
filter: { query: "live-branch-only" },
|
||||
});
|
||||
const byBranchResponse = findByType(emitted, "fetch_workspaces_response");
|
||||
expect(byBranchResponse?.payload.entries.map((entry) => [entry.id, entry.name])).toEqual([
|
||||
[targetWorkspace.workspaceId, "feature/live-branch-only"],
|
||||
]);
|
||||
expect(builtWorkspaceIds).toEqual([targetWorkspace.workspaceId]);
|
||||
expect(warnings).toEqual([]);
|
||||
} finally {
|
||||
await session.cleanup();
|
||||
rmSync(root, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
@@ -5,6 +5,7 @@ import type { HeapProfiler } from "node:inspector";
|
||||
import {
|
||||
FileBackedWorkspaceRegistry,
|
||||
createPersistedWorkspaceRecord,
|
||||
resolveWorkspaceDisplayName,
|
||||
} from "./workspace-registry.js";
|
||||
import { mkdtemp, rm, mkdir, writeFile } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
@@ -100,6 +101,7 @@ class WorkspaceStatus {
|
||||
listProviderSubagentActivity: async () => this.providerSubagents,
|
||||
listTerminalActivityContributions: async () => this.terminals,
|
||||
isProviderVisibleToClient: () => true,
|
||||
resolveWorkspaceName: (workspace) => resolveWorkspaceDisplayName(workspace),
|
||||
buildWorkspaceDescriptor: async ({ workspace }) => ({
|
||||
id: workspace.workspaceId,
|
||||
projectId: workspace.projectId,
|
||||
@@ -645,6 +647,7 @@ describe("WorkspaceDirectory empty projects", () => {
|
||||
listProviderSubagentActivity: async () => [],
|
||||
listTerminalActivityContributions: async () => [],
|
||||
isProviderVisibleToClient: () => true,
|
||||
resolveWorkspaceName: (workspace) => resolveWorkspaceDisplayName(workspace),
|
||||
buildWorkspaceDescriptor: async ({ workspace }) => ({
|
||||
id: workspace.workspaceId,
|
||||
projectId: workspace.projectId,
|
||||
@@ -764,6 +767,197 @@ describe("WorkspaceDirectory empty projects", () => {
|
||||
expect(shown.entries.map((entry) => entry.id)).toEqual(["ws-internal"]);
|
||||
expect(shown.emptyProjects).toEqual([]);
|
||||
});
|
||||
|
||||
test("pre-filters active persisted records before building descriptors on single-id, projectId, and default listings", async () => {
|
||||
const builtWorkspaceIds: string[] = [];
|
||||
const agentQueryWorkspaceIds: Array<string[] | undefined> = [];
|
||||
const promptQueryWorkspaceIds: Array<string[] | undefined> = [];
|
||||
const projects = [
|
||||
project({ projectId: "prj_alpha" }),
|
||||
project({ projectId: "prj_beta" }),
|
||||
project({ projectId: "prj_empty" }),
|
||||
];
|
||||
const workspaces: PersistedWorkspaceRecord[] = [
|
||||
createPersistedWorkspaceRecord({
|
||||
workspaceId: "wks_alpha_1",
|
||||
projectId: "prj_alpha",
|
||||
cwd: "/workspace/alpha-1",
|
||||
kind: "local_checkout",
|
||||
displayName: "main",
|
||||
title: "Payments API",
|
||||
createdAt: NOW,
|
||||
updatedAt: NOW,
|
||||
}),
|
||||
createPersistedWorkspaceRecord({
|
||||
workspaceId: "wks_alpha_bg",
|
||||
projectId: "prj_alpha",
|
||||
cwd: "/workspace/alpha-bg",
|
||||
kind: "directory",
|
||||
displayName: "helper-bg",
|
||||
createdAt: NOW,
|
||||
updatedAt: NOW,
|
||||
background: true,
|
||||
}),
|
||||
createPersistedWorkspaceRecord({
|
||||
workspaceId: "wks_alpha_bg_sub",
|
||||
projectId: "prj_alpha",
|
||||
cwd: "/workspace/alpha-bg-sub",
|
||||
kind: "directory",
|
||||
displayName: "helper-bg-sub",
|
||||
createdAt: NOW,
|
||||
updatedAt: NOW,
|
||||
background: true,
|
||||
}),
|
||||
createPersistedWorkspaceRecord({
|
||||
workspaceId: "wks_beta_1",
|
||||
projectId: "prj_beta",
|
||||
cwd: "/workspace/beta-1",
|
||||
kind: "local_checkout",
|
||||
displayName: "feature/search",
|
||||
createdAt: NOW,
|
||||
updatedAt: NOW,
|
||||
}),
|
||||
];
|
||||
|
||||
const directory = new WorkspaceDirectory({
|
||||
getArchivingAt: () => null,
|
||||
logger: createTestLogger(),
|
||||
projectRegistry: { list: async () => projects },
|
||||
workspaceRegistry: {
|
||||
listActive: async () => workspaces.filter((w) => !w.archivedAt),
|
||||
get: async (id) => workspaces.find((w) => w.workspaceId === id) ?? null,
|
||||
},
|
||||
listAgentPayloads: async (workspaceIds) => {
|
||||
agentQueryWorkspaceIds.push(workspaceIds ? Array.from(workspaceIds) : undefined);
|
||||
return [];
|
||||
},
|
||||
workspaceLastUserMessageTimes: async (workspaceIds) => {
|
||||
promptQueryWorkspaceIds.push(workspaceIds ? Array.from(workspaceIds) : undefined);
|
||||
return new Map();
|
||||
},
|
||||
listProviderSubagentActivity: async () => [],
|
||||
listTerminalActivityContributions: async () => [],
|
||||
isProviderVisibleToClient: () => true,
|
||||
resolveWorkspaceName: (workspace) => resolveWorkspaceDisplayName(workspace),
|
||||
buildWorkspaceDescriptor: async ({ workspace }) => {
|
||||
builtWorkspaceIds.push(workspace.workspaceId);
|
||||
return {
|
||||
id: workspace.workspaceId,
|
||||
projectId: workspace.projectId,
|
||||
projectDisplayName: workspace.projectId,
|
||||
projectCustomName: null,
|
||||
projectRootPath: `/workspace/${workspace.projectId}`,
|
||||
workspaceDirectory: workspace.cwd,
|
||||
projectKind: "git",
|
||||
workspaceKind: workspace.kind,
|
||||
background: workspace.background,
|
||||
name: resolveWorkspaceDisplayName(workspace),
|
||||
archivingAt: null,
|
||||
status: "done",
|
||||
activityAt: null,
|
||||
diffStat: null,
|
||||
gitRuntime: null,
|
||||
githubRuntime: null,
|
||||
};
|
||||
},
|
||||
});
|
||||
|
||||
// 1. Single-ID lookup (with includeBackground): builds ONLY the matching workspace.
|
||||
builtWorkspaceIds.length = 0;
|
||||
agentQueryWorkspaceIds.length = 0;
|
||||
promptQueryWorkspaceIds.length = 0;
|
||||
const single = await directory.listFetchEntries({
|
||||
type: "fetch_workspaces_request",
|
||||
requestId: "r-single",
|
||||
filter: { query: "wks_beta_1", includeBackground: true },
|
||||
});
|
||||
expect(single.entries.map((e) => e.id)).toEqual(["wks_beta_1"]);
|
||||
expect(builtWorkspaceIds).toEqual(["wks_beta_1"]);
|
||||
expect(agentQueryWorkspaceIds).toEqual([["wks_beta_1"]]);
|
||||
expect(promptQueryWorkspaceIds).toEqual([["wks_beta_1"]]);
|
||||
|
||||
// 2. Exact background workspace ID lookup without includeBackground:
|
||||
// builds ONLY that exact background workspace (excludes wks_alpha_bg_sub).
|
||||
builtWorkspaceIds.length = 0;
|
||||
const exactBg = await directory.listFetchEntries({
|
||||
type: "fetch_workspaces_request",
|
||||
requestId: "r-exact-bg",
|
||||
filter: { query: "wks_alpha_bg" },
|
||||
});
|
||||
expect(exactBg.entries.map((e) => e.id)).toEqual(["wks_alpha_bg"]);
|
||||
expect(builtWorkspaceIds).toEqual(["wks_alpha_bg"]);
|
||||
|
||||
// 3. projectId filter: builds ONLY visible workspaces in that project and scopes emptyProjects.
|
||||
builtWorkspaceIds.length = 0;
|
||||
const byProject = await directory.listFetchEntries({
|
||||
type: "fetch_workspaces_request",
|
||||
requestId: "r-project",
|
||||
filter: { projectId: "prj_alpha" },
|
||||
});
|
||||
expect(byProject.entries.map((e) => e.id)).toEqual(["wks_alpha_1"]);
|
||||
expect(builtWorkspaceIds).toEqual(["wks_alpha_1"]);
|
||||
expect(byProject.emptyProjects).toEqual([]);
|
||||
|
||||
// 4. Default listing (no includeBackground): skips building hidden background workspaces.
|
||||
builtWorkspaceIds.length = 0;
|
||||
const visibleOnly = await directory.listFetchEntries({
|
||||
type: "fetch_workspaces_request",
|
||||
requestId: "r-default",
|
||||
});
|
||||
expect(visibleOnly.entries.map((e) => e.id).sort()).toEqual(["wks_alpha_1", "wks_beta_1"]);
|
||||
expect(builtWorkspaceIds.sort()).toEqual(["wks_alpha_1", "wks_beta_1"]);
|
||||
expect(visibleOnly.emptyProjects.map((p) => p.projectId)).toEqual(["prj_empty"]);
|
||||
|
||||
// 5. Substring search by title, displayName, and projectId (case-insensitive, trimmed).
|
||||
builtWorkspaceIds.length = 0;
|
||||
const byTitle = await directory.listFetchEntries({
|
||||
type: "fetch_workspaces_request",
|
||||
requestId: "r-title",
|
||||
filter: { query: " PAYMENTS " },
|
||||
});
|
||||
expect(byTitle.entries.map((e) => e.id)).toEqual(["wks_alpha_1"]);
|
||||
expect(builtWorkspaceIds).toEqual(["wks_alpha_1"]);
|
||||
|
||||
builtWorkspaceIds.length = 0;
|
||||
const byProjectIdQuery = await directory.listFetchEntries({
|
||||
type: "fetch_workspaces_request",
|
||||
requestId: "r-prj-query",
|
||||
filter: { query: "BETA" },
|
||||
});
|
||||
expect(byProjectIdQuery.entries.map((e) => e.id)).toEqual(["wks_beta_1"]);
|
||||
expect(builtWorkspaceIds).toEqual(["wks_beta_1"]);
|
||||
|
||||
// 6. Unmatched query builds zero descriptors.
|
||||
builtWorkspaceIds.length = 0;
|
||||
const none = await directory.listFetchEntries({
|
||||
type: "fetch_workspaces_request",
|
||||
requestId: "r-none",
|
||||
filter: { query: "wks_does_not_exist" },
|
||||
});
|
||||
expect(none.entries).toEqual([]);
|
||||
expect(builtWorkspaceIds).toEqual([]);
|
||||
|
||||
// 7. Pagination & sorting remain intact across pre-filtered results.
|
||||
const page1 = await directory.listFetchEntries({
|
||||
type: "fetch_workspaces_request",
|
||||
requestId: "r-page-1",
|
||||
sort: [{ key: "name", direction: "asc" }],
|
||||
page: { limit: 1 },
|
||||
});
|
||||
expect(page1.entries.map((e) => e.id)).toEqual(["wks_beta_1"]);
|
||||
expect(page1.pageInfo.hasMore).toBe(true);
|
||||
expect(page1.emptyProjects.map((p) => p.projectId)).toEqual(["prj_empty"]);
|
||||
|
||||
const page2 = await directory.listFetchEntries({
|
||||
type: "fetch_workspaces_request",
|
||||
requestId: "r-page-2",
|
||||
sort: [{ key: "name", direction: "asc" }],
|
||||
page: { limit: 1, cursor: page1.pageInfo.nextCursor! },
|
||||
});
|
||||
expect(page2.entries.map((e) => e.id)).toEqual(["wks_alpha_1"]);
|
||||
expect(page2.pageInfo.hasMore).toBe(false);
|
||||
expect(page2.emptyProjects).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
test("Git observation targets exclude archived records without hydrating app descriptors", async () => {
|
||||
@@ -809,6 +1003,7 @@ test("Git observation targets exclude archived records without hydrating app des
|
||||
workspaceLastUserMessageTimes: unexpectedHydration,
|
||||
listProviderSubagentActivity: unexpectedHydration,
|
||||
listTerminalActivityContributions: unexpectedHydration,
|
||||
resolveWorkspaceName: (w) => resolveWorkspaceDisplayName(w),
|
||||
buildWorkspaceDescriptor: unexpectedHydration,
|
||||
isProviderVisibleToClient: () => true,
|
||||
});
|
||||
@@ -990,6 +1185,7 @@ test("scoped descriptor builds allocate independently of archived history", asyn
|
||||
listProviderSubagentActivity: async () => [],
|
||||
listTerminalActivityContributions: async () => [],
|
||||
isProviderVisibleToClient: () => true,
|
||||
resolveWorkspaceName: (workspace) => resolveWorkspaceDisplayName(workspace),
|
||||
buildWorkspaceDescriptor: async ({ workspace }) => ({
|
||||
id: workspace.workspaceId,
|
||||
projectId: "p",
|
||||
|
||||
@@ -89,6 +89,10 @@ export interface WorkspaceDirectoryDeps {
|
||||
Array<{ cwd: string; workspaceId?: string; activity: TerminalActivity | null }>
|
||||
>;
|
||||
isProviderVisibleToClient(provider: string): boolean;
|
||||
resolveWorkspaceName(
|
||||
workspace: PersistedWorkspaceRecord,
|
||||
options: { includeGitData: boolean },
|
||||
): string;
|
||||
buildWorkspaceDescriptor(input: {
|
||||
workspace: PersistedWorkspaceRecord;
|
||||
projectRecord?: PersistedProjectRecord | null;
|
||||
@@ -172,6 +176,43 @@ function activeWorkspaceRecords(
|
||||
);
|
||||
}
|
||||
|
||||
function matchesWorkspaceFilterFields(input: {
|
||||
id: string;
|
||||
projectId: string;
|
||||
background: boolean;
|
||||
getName: () => string;
|
||||
filter: FetchWorkspacesRequestFilter | undefined;
|
||||
}): boolean {
|
||||
const { id, projectId, background, getName, filter } = input;
|
||||
if (background && filter?.includeBackground !== true && filter?.query !== id) {
|
||||
return false;
|
||||
}
|
||||
if (!filter) {
|
||||
return true;
|
||||
}
|
||||
|
||||
const projectIdFilter = filter.projectId?.trim();
|
||||
if (projectIdFilter && projectIdFilter.length > 0) {
|
||||
if (projectId !== projectIdFilter) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
const queryFilter = filter.query?.trim();
|
||||
if (queryFilter && queryFilter.length > 0) {
|
||||
const query = queryFilter.toLocaleLowerCase();
|
||||
if (
|
||||
!id.toLocaleLowerCase().includes(query) &&
|
||||
!projectId.toLocaleLowerCase().includes(query) &&
|
||||
!getName().toLocaleLowerCase().includes(query)
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
export class WorkspaceDirectory {
|
||||
/**
|
||||
* Per-workspace last-seen winning bucket + entered-at. Persists across
|
||||
@@ -211,17 +252,10 @@ export class WorkspaceDirectory {
|
||||
workspaceIds?: Iterable<string>;
|
||||
}): Promise<Map<string, WorkspaceDescriptorPayload>> {
|
||||
const requestedIds = options.workspaceIds ? new Set(options.workspaceIds) : undefined;
|
||||
const [
|
||||
agents,
|
||||
lastUserMessageTimes,
|
||||
providerSubagentActivity,
|
||||
persistedWorkspaces,
|
||||
persistedProjects,
|
||||
terminalContributions,
|
||||
] = await Promise.all([
|
||||
this.deps.listAgentPayloads(requestedIds),
|
||||
this.deps.workspaceLastUserMessageTimes(requestedIds),
|
||||
this.deps.listProviderSubagentActivity(),
|
||||
if (requestedIds && requestedIds.size === 0) {
|
||||
return new Map();
|
||||
}
|
||||
const [persistedWorkspaces, persistedProjects] = await Promise.all([
|
||||
requestedIds
|
||||
? Promise.all(Array.from(requestedIds, (id) => this.deps.workspaceRegistry.get(id))).then(
|
||||
(records) =>
|
||||
@@ -229,23 +263,47 @@ export class WorkspaceDirectory {
|
||||
)
|
||||
: this.deps.workspaceRegistry.listActive(),
|
||||
this.deps.projectRegistry.list(),
|
||||
this.deps.listTerminalActivityContributions(),
|
||||
]);
|
||||
const activeRecords = activeWorkspaceRecords(persistedWorkspaces, persistedProjects).filter(
|
||||
(workspace) => !this.deps.workspaceRegistry.isPublicationDeferred?.(workspace.workspaceId),
|
||||
);
|
||||
return this.buildDescriptorsForRecords({
|
||||
activeRecords,
|
||||
persistedProjects,
|
||||
includeGitData: options.includeGitData,
|
||||
requestedIds,
|
||||
});
|
||||
}
|
||||
|
||||
private async buildDescriptorsForRecords(options: {
|
||||
activeRecords: PersistedWorkspaceRecord[];
|
||||
persistedProjects: PersistedProjectRecord[];
|
||||
includeGitData: boolean;
|
||||
requestedIds: Set<string> | undefined;
|
||||
}): Promise<Map<string, WorkspaceDescriptorPayload>> {
|
||||
const { activeRecords, persistedProjects, includeGitData, requestedIds } = options;
|
||||
const includedWorkspaces = activeRecords.filter(
|
||||
(workspace) => !requestedIds || requestedIds.has(workspace.workspaceId),
|
||||
);
|
||||
if (includedWorkspaces.length === 0) {
|
||||
return new Map();
|
||||
}
|
||||
|
||||
const [agents, lastUserMessageTimes, providerSubagentActivity, terminalContributions] =
|
||||
await Promise.all([
|
||||
this.deps.listAgentPayloads(requestedIds),
|
||||
this.deps.workspaceLastUserMessageTimes(requestedIds),
|
||||
this.deps.listProviderSubagentActivity(),
|
||||
this.deps.listTerminalActivityContributions(),
|
||||
]);
|
||||
|
||||
const activeProjects = new Map(
|
||||
persistedProjects
|
||||
.filter((project) => !project.archivedAt)
|
||||
.map((project) => [project.projectId, project] as const),
|
||||
);
|
||||
const activeRecords = activeWorkspaceRecords(persistedWorkspaces, persistedProjects).filter(
|
||||
(workspace) => !this.deps.workspaceRegistry.isPublicationDeferred?.(workspace.workspaceId),
|
||||
);
|
||||
const descriptorsByWorkspaceId = new Map<string, WorkspaceDescriptorPayload>();
|
||||
const workspaceIds = requestedIds ? new Set(requestedIds) : null;
|
||||
const activeWorkspaceIds = new Set(activeRecords.map((workspace) => workspace.workspaceId));
|
||||
const includedWorkspaces = activeRecords.filter(
|
||||
(workspace) => !workspaceIds || workspaceIds.has(workspace.workspaceId),
|
||||
);
|
||||
const activeRecordsByWorkspaceId = new Map(
|
||||
activeRecords.map((workspace) => [workspace.workspaceId, workspace] as const),
|
||||
);
|
||||
@@ -254,7 +312,7 @@ export class WorkspaceDirectory {
|
||||
this.deps.buildWorkspaceDescriptor({
|
||||
workspace,
|
||||
projectRecord: activeProjects.get(workspace.projectId) ?? null,
|
||||
includeGitData: options.includeGitData,
|
||||
includeGitData,
|
||||
}),
|
||||
),
|
||||
);
|
||||
@@ -576,6 +634,14 @@ export class WorkspaceDirectory {
|
||||
this.deps.workspaceRegistry.listActive(),
|
||||
this.deps.projectRegistry.list(),
|
||||
]);
|
||||
return this.emptyProjectsFromRecords(persistedWorkspaces, persistedProjects, options);
|
||||
}
|
||||
|
||||
private emptyProjectsFromRecords(
|
||||
persistedWorkspaces: PersistedWorkspaceRecord[],
|
||||
persistedProjects: PersistedProjectRecord[],
|
||||
options?: { includeBackground?: boolean },
|
||||
): WorkspaceProjectDescriptor[] {
|
||||
// A project whose only workspaces are hidden reads as empty to that caller.
|
||||
const projectIdsWithActiveWorkspaces = new Set(
|
||||
persistedWorkspaces
|
||||
@@ -632,37 +698,63 @@ export class WorkspaceDirectory {
|
||||
);
|
||||
}
|
||||
|
||||
private matchesRecordFilter(input: {
|
||||
workspace: PersistedWorkspaceRecord;
|
||||
filter: FetchWorkspacesRequestFilter | undefined;
|
||||
}): boolean {
|
||||
const { workspace, filter } = input;
|
||||
return matchesWorkspaceFilterFields({
|
||||
id: workspace.workspaceId,
|
||||
projectId: workspace.projectId,
|
||||
background: workspace.background === true,
|
||||
getName: () => this.deps.resolveWorkspaceName(workspace, { includeGitData: true }),
|
||||
filter,
|
||||
});
|
||||
}
|
||||
|
||||
matchesFilter(input: {
|
||||
workspace: WorkspaceDescriptorPayload;
|
||||
filter: FetchWorkspacesRequestFilter | undefined;
|
||||
}): boolean {
|
||||
const { workspace, filter } = input;
|
||||
if (
|
||||
workspace.background &&
|
||||
filter?.includeBackground !== true &&
|
||||
filter?.query !== workspace.id
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
if (!filter) {
|
||||
return true;
|
||||
}
|
||||
return matchesWorkspaceFilterFields({
|
||||
id: workspace.id,
|
||||
projectId: workspace.projectId,
|
||||
background: workspace.background === true,
|
||||
getName: () => workspace.name,
|
||||
filter,
|
||||
});
|
||||
}
|
||||
|
||||
if (filter.projectId && filter.projectId.trim().length > 0) {
|
||||
if (workspace.projectId !== filter.projectId.trim()) {
|
||||
return false;
|
||||
}
|
||||
private async listCandidateDescriptors(input: {
|
||||
activeRecords: PersistedWorkspaceRecord[];
|
||||
persistedProjects: PersistedProjectRecord[];
|
||||
filter: FetchWorkspacesRequestFilter | undefined;
|
||||
}): Promise<WorkspaceDescriptorPayload[]> {
|
||||
const { activeRecords, persistedProjects, filter } = input;
|
||||
const candidateRecords = activeRecords.filter((workspace) =>
|
||||
this.matchesRecordFilter({ workspace, filter }),
|
||||
);
|
||||
if (candidateRecords.length === 0) {
|
||||
return [];
|
||||
}
|
||||
|
||||
if (filter.query && filter.query.trim().length > 0) {
|
||||
const query = filter.query.trim().toLocaleLowerCase();
|
||||
const haystacks = [workspace.name, workspace.projectId, workspace.id];
|
||||
if (!haystacks.some((value) => value.toLocaleLowerCase().includes(query))) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
const isScoped =
|
||||
Boolean(filter?.projectId?.trim()) ||
|
||||
Boolean(filter?.query?.trim()) ||
|
||||
candidateRecords.length < activeRecords.length;
|
||||
const requestedIds = isScoped
|
||||
? new Set(candidateRecords.map((workspace) => workspace.workspaceId))
|
||||
: undefined;
|
||||
return Array.from(
|
||||
(
|
||||
await this.buildDescriptorsForRecords({
|
||||
activeRecords: candidateRecords,
|
||||
persistedProjects,
|
||||
includeGitData: true,
|
||||
requestedIds,
|
||||
})
|
||||
).values(),
|
||||
);
|
||||
}
|
||||
|
||||
async listFetchEntries(request: FetchWorkspacesRequestMessage): Promise<{
|
||||
@@ -672,8 +764,19 @@ export class WorkspaceDirectory {
|
||||
}> {
|
||||
const filter = request.filter;
|
||||
const sort = this.pager.normalizeSort(request.sort);
|
||||
let entries = await this.listDescriptors();
|
||||
const listedCount = entries.length;
|
||||
const [persistedWorkspaces, persistedProjects] = await Promise.all([
|
||||
this.deps.workspaceRegistry.listActive(),
|
||||
this.deps.projectRegistry.list(),
|
||||
]);
|
||||
const activeRecords = activeWorkspaceRecords(persistedWorkspaces, persistedProjects).filter(
|
||||
(workspace) => !this.deps.workspaceRegistry.isPublicationDeferred?.(workspace.workspaceId),
|
||||
);
|
||||
const listedCount = activeRecords.length;
|
||||
let entries = await this.listCandidateDescriptors({
|
||||
activeRecords,
|
||||
persistedProjects,
|
||||
filter,
|
||||
});
|
||||
entries = entries.filter((workspace) => this.matchesFilter({ workspace, filter }));
|
||||
const filteredCount = entries.length;
|
||||
entries.sort((left, right) => this.pager.compare(left, right, sort));
|
||||
@@ -699,9 +802,9 @@ export class WorkspaceDirectory {
|
||||
const projectIdFilter = filter?.projectId?.trim();
|
||||
const emptyProjects = cursorToken
|
||||
? []
|
||||
: (await this.listEmptyProjects({ includeBackground: filter?.includeBackground })).filter(
|
||||
(project) => !projectIdFilter || project.projectId === projectIdFilter,
|
||||
);
|
||||
: this.emptyProjectsFromRecords(persistedWorkspaces, persistedProjects, {
|
||||
includeBackground: filter?.includeBackground,
|
||||
}).filter((project) => !projectIdFilter || project.projectId === projectIdFilter);
|
||||
|
||||
this.deps.logger.debug(
|
||||
{
|
||||
|
||||
@@ -653,6 +653,39 @@ describe("createTerminal", () => {
|
||||
expect(session.getExitInfo()).toEqual(exitInfo);
|
||||
});
|
||||
|
||||
it.runIf(isPlatform("win32"))(
|
||||
"starts a ConPTY program when the event loop stalls past five seconds after spawn",
|
||||
async () => {
|
||||
// node-pty reports the ConPTY output worker ready by a worker message, and failed the
|
||||
// spawn with exit code -1 when that message came after 5 s. A loaded runner delays it
|
||||
// that long; blocking the event loop for 6 s makes the delay certain. Spawning and
|
||||
// blocking inside a check-phase callback makes the next loop iteration start with the
|
||||
// timers phase, so the old 5 s timer always runs before the worker message is delivered.
|
||||
const child = await new Promise<pty.IPty>((resolve) => {
|
||||
setImmediate(() => {
|
||||
const spawned = pty.spawn(process.execPath, ["-e", "process.stdout.write('STARTED')"], {
|
||||
cols: 80,
|
||||
rows: 24,
|
||||
cwd: realpathSync(tmpdir()),
|
||||
});
|
||||
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 6000);
|
||||
resolve(spawned);
|
||||
});
|
||||
});
|
||||
let output = "";
|
||||
child.onData((data) => {
|
||||
output += data;
|
||||
});
|
||||
const exited = new Promise<number>((resolve) => {
|
||||
child.onExit(({ exitCode }) => resolve(exitCode));
|
||||
});
|
||||
|
||||
expect(await exited).toBe(0);
|
||||
expect(output).toContain("STARTED");
|
||||
},
|
||||
30_000,
|
||||
);
|
||||
|
||||
it("retains the final lines after output far exceeds the recent-output char cap", async () => {
|
||||
// Emit many small chunks whose total length is well past the 16000-char
|
||||
// recent-output cap, so the chunk-trimming path runs repeatedly. The final
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
diff --git a/node_modules/node-pty/lib/windowsPtyAgent.js b/node_modules/node-pty/lib/windowsPtyAgent.js
|
||||
index 90ffd8f..d9567b1 100644
|
||||
--- a/node_modules/node-pty/lib/windowsPtyAgent.js
|
||||
+++ b/node_modules/node-pty/lib/windowsPtyAgent.js
|
||||
@@ -21,7 +21,10 @@ var conptyNative;
|
||||
* has started.
|
||||
*/
|
||||
var FLUSH_DATA_INTERVAL = 1000;
|
||||
-var CONNECTION_TIMEOUT = 5000;
|
||||
+// Paseo: the output worker is a worker thread that reports ready by message. A busy event loop
|
||||
+// or a loaded machine can delay that message past 5 s, and the spawn then fails with exit
|
||||
+// code -1 before the program starts. Wait 30 s instead; a worker that fails still errors at once.
|
||||
+var CONNECTION_TIMEOUT = 30000;
|
||||
var defaultWindowsPtyAgentOptions = {
|
||||
connectionTimeout: CONNECTION_TIMEOUT,
|
||||
conoutConnectionFactory: function (conoutPipeName, useConptyDll) { return new windowsConoutConnection_1.ConoutConnection(conoutPipeName, useConptyDll); }
|
||||
@@ -123,6 +123,14 @@ const patchedPackages = [
|
||||
patchPrefix: "@opencode-ai+sdk+",
|
||||
cwd: "packages/server",
|
||||
},
|
||||
// Windows: wait 30 s instead of 5 s for the ConPTY output worker to report ready. A loaded
|
||||
// machine delays that message past 5 s, and the program then exits with code -1 before it
|
||||
// starts. Upstream keeps 5 s through 1.2.0-beta.18; keep while the server uses node-pty.
|
||||
{
|
||||
nodeModulesPath: "packages/server/node_modules/node-pty",
|
||||
patchPrefix: "node-pty+",
|
||||
cwd: "packages/server",
|
||||
},
|
||||
];
|
||||
|
||||
const installedPackages = patchedPackages.filter(({ nodeModulesPath }) =>
|
||||
|
||||
Reference in New Issue
Block a user