mirror of
https://github.com/getpaseo/paseo.git
synced 2026-12-05 14:45:25 +00:00
Compare commits
7
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
765aec33e5 | ||
|
|
073743647a | ||
|
|
6b3b349c8b | ||
|
|
b1bb161133 | ||
|
|
2f1fc53cdb | ||
|
|
617ebbdb1a | ||
|
|
c174f475c8 |
@@ -112,24 +112,25 @@ test.describe("Settings sidebar scroll position", () => {
|
||||
await expectSettingsSidebarScrollOffset(page, 0);
|
||||
});
|
||||
|
||||
test("updates appearance without losing the detail scroll or form edits", async ({ page }) => {
|
||||
test("updates typography and normalizes font sizes in one Appearance visit", async ({ page }) => {
|
||||
await gotoAppShell(page);
|
||||
await openSettings(page);
|
||||
await openSettingsSection(page, "appearance");
|
||||
const { offset, keywordColor } = await revealSettingsSyntaxTheme(page);
|
||||
await changeSettingsSyntaxTheme(page, "Dracula");
|
||||
await expectSettingsDetailScrollOffset(page, offset);
|
||||
await expectSettingsSyntaxColorChanged(page, keywordColor);
|
||||
await changeSettingsTypography(page);
|
||||
});
|
||||
|
||||
test("shows normalized font sizes after committing out-of-range and empty values", async ({
|
||||
page,
|
||||
}) => {
|
||||
await gotoAppShell(page);
|
||||
await openSettings(page);
|
||||
await openSettingsSection(page, "appearance");
|
||||
await normalizeSettingsFontSizes(page);
|
||||
await test.step("change the syntax theme without losing the detail scroll", async () => {
|
||||
const { offset, keywordColor } = await revealSettingsSyntaxTheme(page);
|
||||
await changeSettingsSyntaxTheme(page, "Dracula");
|
||||
await expectSettingsDetailScrollOffset(page, offset);
|
||||
await expectSettingsSyntaxColorChanged(page, keywordColor);
|
||||
});
|
||||
|
||||
await test.step("apply valid font edits to Settings and the preview", async () => {
|
||||
await changeSettingsTypography(page);
|
||||
});
|
||||
|
||||
await test.step("normalize out-of-range and empty font sizes on commit", async () => {
|
||||
await normalizeSettingsFontSizes(page);
|
||||
});
|
||||
});
|
||||
|
||||
test("keeps the sidebar context through interface font changes", async ({ page }) => {
|
||||
|
||||
@@ -20,11 +20,11 @@ import {
|
||||
getWorkspaceSelectionKey,
|
||||
orderWorkspaceSelectionsForStableRender,
|
||||
reconcileRetainedWorkspaceSelections,
|
||||
resolveWorkspaceDeckRetentionLimit,
|
||||
type RetainedWorkspaceSelection,
|
||||
resolveWorkspaceDeckEntries,
|
||||
shouldKeepWorkspaceDeckEntryMounted,
|
||||
} from "@/screens/workspace/workspace-deck-retention";
|
||||
import { workspaceDeckRetentionLimit } from "@/constants/resource-budget";
|
||||
import {
|
||||
decodeWorkspaceIdFromPathSegment,
|
||||
parseWorkspaceOpenIntent,
|
||||
@@ -35,7 +35,7 @@ import {
|
||||
stripHostWorkspaceRouteEchoSearchFromBrowserUrlAfterCommit,
|
||||
} from "@/utils/host-route-browser";
|
||||
import { prepareWorkspaceTab } from "@/utils/prepare-workspace-tab";
|
||||
import { isNative, isWeb } from "@/constants/platform";
|
||||
import { isWeb } from "@/constants/platform";
|
||||
import { RenderProfile } from "@/utils/render-profiler";
|
||||
|
||||
function getParamValue(value: string | string[] | undefined): string {
|
||||
@@ -167,7 +167,7 @@ function WorkspaceDeck() {
|
||||
currentEntries: retainedSelections,
|
||||
activeSelection,
|
||||
now: reconciliationNow,
|
||||
maxMountedWorkspaces: resolveWorkspaceDeckRetentionLimit({ isNative }),
|
||||
maxMountedWorkspaces: workspaceDeckRetentionLimit,
|
||||
}),
|
||||
[activeSelection, reconciliationNow, retainedSelections],
|
||||
);
|
||||
@@ -204,7 +204,7 @@ function WorkspaceDeck() {
|
||||
currentEntries: current,
|
||||
activeSelection,
|
||||
now: Date.now(),
|
||||
maxMountedWorkspaces: resolveWorkspaceDeckRetentionLimit({ isNative }),
|
||||
maxMountedWorkspaces: workspaceDeckRetentionLimit,
|
||||
}),
|
||||
);
|
||||
}, expirationDelay + 1);
|
||||
|
||||
@@ -56,6 +56,7 @@ import {
|
||||
} from "@/components/ui/isolated-bottom-sheet-modal";
|
||||
import { useIsCompactFormFactor } from "@/constants/layout";
|
||||
import { isNative, isWeb } from "@/constants/platform";
|
||||
import { usesCompactBottomSheet } from "@/constants/presentation";
|
||||
import { useAggregatedAgents, type AggregatedAgent } from "@/hooks/use-aggregated-agents";
|
||||
import { useProjects } from "@/hooks/use-projects";
|
||||
import { useTimeAgo } from "@/hooks/use-time-ago";
|
||||
@@ -991,7 +992,7 @@ export function CommandCenter() {
|
||||
const bottomSheetListRef = useRef<BottomSheetFlatListMethods>(null);
|
||||
const inputRef = useRef<EditingTextInputHandle>(null);
|
||||
const bottomSheetInputRef = useRef<EditingTextInputHandle>(null);
|
||||
const showBottomSheet = isCompact && isNative;
|
||||
const showBottomSheet = isCompact && usesCompactBottomSheet;
|
||||
const getInputHandle = useCallback(
|
||||
() => (showBottomSheet ? bottomSheetInputRef.current : inputRef.current),
|
||||
[showBottomSheet],
|
||||
|
||||
@@ -16,6 +16,7 @@ import DraggableFlatList, {
|
||||
import type { GestureType } from "react-native-gesture-handler";
|
||||
import { useUnistyles } from "react-native-unistyles";
|
||||
import { useContentDrag } from "@/components/ui/content-drag";
|
||||
import { supportsTouchHaptics } from "@/constants/touch-timing";
|
||||
import { createDragHold } from "./drag-reorder/drag-hold";
|
||||
import { movedItemKey } from "./drag-reorder/native-drop";
|
||||
import type {
|
||||
@@ -52,7 +53,7 @@ export function DraggableListHandle({ testID, style, children }: DraggableListHa
|
||||
delayMs: HANDLE_HOLD_MS,
|
||||
slopPx: HANDLE_HOLD_SLOP_PX,
|
||||
onArm: () => {
|
||||
void Haptics.selectionAsync().catch(() => {});
|
||||
if (supportsTouchHaptics) void Haptics.selectionAsync().catch(() => {});
|
||||
drag();
|
||||
},
|
||||
})
|
||||
|
||||
@@ -3,6 +3,7 @@ import { Animated, StyleSheet, Text, View } from "react-native";
|
||||
import MaskedView from "@react-native-masked-view/masked-view";
|
||||
import Svg, { Defs, Rect, Stop, LinearGradient as SvgLinearGradient } from "react-native-svg";
|
||||
import { useIndicatorMotion } from "@/components/indicator-motion";
|
||||
import { supportsMaskedEffects } from "@/constants/platform";
|
||||
import { sharedIndicatorClock, useRunningClock } from "@/components/indicator-motion/clock";
|
||||
import { type LabelShimmerProps, getRowSweep, getShimmerCycle } from "./sweep";
|
||||
|
||||
@@ -60,7 +61,8 @@ export const LabelShimmer = memo(function LabelShimmer({
|
||||
measurements,
|
||||
}: LabelShimmerProps) {
|
||||
const { rowSize } = measurements;
|
||||
const measured = rowSize.width > 0 && rowSize.height > 0;
|
||||
// Without an alpha-mask compositor the band would paint as a bare white bar.
|
||||
const measured = supportsMaskedEffects && rowSize.width > 0 && rowSize.height > 0;
|
||||
const motion = useIndicatorMotion();
|
||||
// A held band stays on the clock, so it keeps its place and its pass.
|
||||
const sweeping = motion !== "resting" && measured;
|
||||
|
||||
@@ -61,8 +61,13 @@ import type { EditingTextInputHandle } from "@/components/ui/text-input";
|
||||
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
|
||||
import { useProviderIcon } from "@/components/provider-icons";
|
||||
import { useIsCompactFormFactor } from "@/constants/layout";
|
||||
import { isNative, isWeb } from "@/constants/platform";
|
||||
import { useHardwareKeyboardPresent, type KeyboardInputEvent } from "@/keyboard";
|
||||
import { isNative } from "@/constants/platform";
|
||||
import { usesDesktopPopoverSpacing } from "@/constants/presentation";
|
||||
import {
|
||||
hasSoftwareKeyboard,
|
||||
useHardwareKeyboardPresent,
|
||||
type KeyboardInputEvent,
|
||||
} from "@/keyboard";
|
||||
import {
|
||||
buildProviderQualifiedDescription,
|
||||
buildSelectedTriggerLabel,
|
||||
@@ -105,7 +110,7 @@ const DESKTOP_PROVIDER_VIEW_BASE_HEIGHT = 80;
|
||||
const DESKTOP_MODEL_ROW_HEIGHT = 40;
|
||||
|
||||
/** Fixed picker row heights so virtualized lists can mount directly at the selected row via `getItemLayout`. */
|
||||
export const MODEL_PICKER_ROW_HEIGHT = isWeb ? 36 : 44;
|
||||
export const MODEL_PICKER_ROW_HEIGHT = usesDesktopPopoverSpacing ? 36 : 44;
|
||||
export const MODEL_PICKER_HEADING_HEIGHT = 32;
|
||||
|
||||
const ThemedAlertTriangle = withUnistyles(AlertTriangle);
|
||||
@@ -386,7 +391,7 @@ export function useModelBrowser({
|
||||
selectedProvider,
|
||||
selectedModel,
|
||||
isLoading,
|
||||
autoFocusSearch = isWeb,
|
||||
autoFocusSearch = !hasSoftwareKeyboard,
|
||||
profiles = null,
|
||||
serverId = null,
|
||||
}: ModelBrowserInput): ModelBrowserState {
|
||||
@@ -1649,7 +1654,7 @@ function ModelSearchEmptyState() {
|
||||
// React Native Web blurs the focused input on every scroll in "on-drag" mode, including wheel
|
||||
// scrolls and the scroll that reveals an arrowed-to row. That moves focus out of search, so
|
||||
// typing stops and Enter lands on the header's Back button. Only a native keyboard needs it.
|
||||
const MODEL_LIST_KEYBOARD_DISMISS_MODE = isNative ? "on-drag" : "none";
|
||||
const MODEL_LIST_KEYBOARD_DISMISS_MODE = hasSoftwareKeyboard ? "on-drag" : "none";
|
||||
|
||||
interface ModelBrowserKeyboardBinding {
|
||||
view: ModelBrowserView;
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
import { Component, type ErrorInfo, type ReactNode } from "react";
|
||||
|
||||
interface RenderErrorBoundaryProps {
|
||||
children: ReactNode;
|
||||
/** A caught error is cleared when any of these values change, so new content renders. */
|
||||
resetKeys: readonly unknown[];
|
||||
/** The error state shown in place of the children. `retry` renders the children again. */
|
||||
renderError(error: string, retry: () => void): ReactNode;
|
||||
onError(error: unknown, componentStack: string | null | undefined): void;
|
||||
}
|
||||
|
||||
interface RenderErrorBoundaryState {
|
||||
error: string | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Keeps a render error inside one surface. Without it the error reaches the root boundary,
|
||||
* which replaces the whole app.
|
||||
*/
|
||||
export class RenderErrorBoundary extends Component<
|
||||
RenderErrorBoundaryProps,
|
||||
RenderErrorBoundaryState
|
||||
> {
|
||||
state: RenderErrorBoundaryState = { error: null };
|
||||
|
||||
static getDerivedStateFromError(error: unknown): RenderErrorBoundaryState {
|
||||
return { error: error instanceof Error ? error.message : String(error) };
|
||||
}
|
||||
|
||||
componentDidCatch(error: unknown, info: ErrorInfo): void {
|
||||
this.props.onError(error, info.componentStack);
|
||||
}
|
||||
|
||||
componentDidUpdate(previous: RenderErrorBoundaryProps): void {
|
||||
if (this.state.error !== null && resetKeysChanged(previous.resetKeys, this.props.resetKeys)) {
|
||||
this.retry();
|
||||
}
|
||||
}
|
||||
|
||||
retry = (): void => {
|
||||
this.setState({ error: null });
|
||||
};
|
||||
|
||||
render() {
|
||||
if (this.state.error !== null) return this.props.renderError(this.state.error, this.retry);
|
||||
return this.props.children;
|
||||
}
|
||||
}
|
||||
|
||||
function resetKeysChanged(previous: readonly unknown[], next: readonly unknown[]): boolean {
|
||||
return previous.length !== next.length || previous.some((key, index) => key !== next[index]);
|
||||
}
|
||||
@@ -1,5 +1,8 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { startResizeHandleDrag } from "@/components/resize-handle-drag";
|
||||
import {
|
||||
resolveResizeHandleInteraction,
|
||||
startResizeHandleDrag,
|
||||
} from "@/components/resize-handle-drag";
|
||||
|
||||
describe("startResizeHandleDrag", () => {
|
||||
it("previews pointer frames and commits only the final size", () => {
|
||||
@@ -29,3 +32,14 @@ describe("startResizeHandleDrag", () => {
|
||||
expect(commit.mock.calls[0]?.[0][1]).toBeCloseTo(0.4, 10);
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveResizeHandleInteraction", () => {
|
||||
it("uses DOM pointer events only on fine-pointer web targets, gesture pan on fine-pointer non-web targets, and touch grip on touch targets", () => {
|
||||
expect(resolveResizeHandleInteraction({ finePointer: true, isWeb: true })).toBe("web-pointer");
|
||||
expect(resolveResizeHandleInteraction({ finePointer: true, isWeb: false })).toBe(
|
||||
"native-pointer",
|
||||
);
|
||||
expect(resolveResizeHandleInteraction({ finePointer: false, isWeb: false })).toBe("touch");
|
||||
expect(resolveResizeHandleInteraction({ finePointer: false, isWeb: true })).toBe("touch");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -7,6 +7,24 @@ interface StartResizeHandleDragInput {
|
||||
commit: (sizes: number[]) => void;
|
||||
}
|
||||
|
||||
export type ResizeHandleInteraction = "web-pointer" | "native-pointer" | "touch";
|
||||
|
||||
/**
|
||||
* Selects how the resize bar is hit-tested and dragged: thin pointer bar with DOM events on a
|
||||
* fine-pointer web target, thin pointer bar with gesture pan on a fine-pointer non-web target, and a
|
||||
* wide touch target with a grip pill otherwise.
|
||||
*/
|
||||
export function resolveResizeHandleInteraction({
|
||||
finePointer,
|
||||
isWeb,
|
||||
}: {
|
||||
finePointer: boolean;
|
||||
isWeb: boolean;
|
||||
}): ResizeHandleInteraction {
|
||||
if (!finePointer) return "touch";
|
||||
return isWeb ? "web-pointer" : "native-pointer";
|
||||
}
|
||||
|
||||
export interface ResizeHandleDrag {
|
||||
move: (deltaRatio: number) => void;
|
||||
finish: () => void;
|
||||
|
||||
@@ -2,7 +2,12 @@ import { useCallback, useMemo, useRef, useState } from "react";
|
||||
import { View, type PointerEvent as RNPointerEvent } from "react-native";
|
||||
import { Gesture, GestureDetector } from "react-native-gesture-handler";
|
||||
import { StyleSheet, useUnistyles } from "react-native-unistyles";
|
||||
import { startResizeHandleDrag, type ResizeHandleDrag } from "@/components/resize-handle-drag";
|
||||
import {
|
||||
resolveResizeHandleInteraction,
|
||||
startResizeHandleDrag,
|
||||
type ResizeHandleDrag,
|
||||
} from "@/components/resize-handle-drag";
|
||||
import { isWeb } from "@/constants/platform";
|
||||
import { usePointerCapabilities } from "@/hooks/pointer-capabilities";
|
||||
import {
|
||||
SIDEBAR_RESIZE_ACTIVATION_OFFSET,
|
||||
@@ -48,6 +53,7 @@ export function ResizeHandle({
|
||||
}: ResizeHandleProps) {
|
||||
const { theme } = useUnistyles();
|
||||
const { finePointer } = usePointerCapabilities();
|
||||
const interaction = resolveResizeHandleInteraction({ finePointer, isWeb });
|
||||
const pointerStatesRef = useRef(new Map<number, PointerState>());
|
||||
const touchStateRef = useRef<PointerState | null>(null);
|
||||
const cursorBeforeDragRef = useRef<string | null>(null);
|
||||
@@ -225,8 +231,12 @@ export function ResizeHandle({
|
||||
...(direction === "horizontal"
|
||||
? { left: hitAreaAlignment === "end" ? 0 : -5 }
|
||||
: { top: hitAreaAlignment === "end" ? 0 : -5 }),
|
||||
cursor: direction === "horizontal" ? "col-resize" : "row-resize",
|
||||
touchAction: "none",
|
||||
...(isWeb
|
||||
? {
|
||||
cursor: direction === "horizontal" ? "col-resize" : "row-resize",
|
||||
touchAction: "none",
|
||||
}
|
||||
: {}),
|
||||
} as object,
|
||||
],
|
||||
[direction, hitAreaAlignment],
|
||||
@@ -254,6 +264,32 @@ export function ResizeHandle({
|
||||
[direction, highlighted, theme.colors.foreground],
|
||||
);
|
||||
|
||||
const ariaOrientation = direction === "horizontal" ? "vertical" : "horizontal";
|
||||
const separatorHitArea =
|
||||
interaction === "web-pointer" ? (
|
||||
<View
|
||||
role="separator"
|
||||
aria-orientation={ariaOrientation}
|
||||
style={hitAreaStyle}
|
||||
onPointerDown={handlePointerDown}
|
||||
onPointerEnter={handlePointerEnter}
|
||||
onPointerLeave={handlePointerLeave}
|
||||
/>
|
||||
) : (
|
||||
<GestureDetector gesture={touchGesture}>
|
||||
<View
|
||||
role="separator"
|
||||
aria-orientation={ariaOrientation}
|
||||
collapsable={false}
|
||||
style={interaction === "native-pointer" ? hitAreaStyle : touchHitAreaStyle}
|
||||
onPointerEnter={interaction === "native-pointer" ? handlePointerEnter : undefined}
|
||||
onPointerLeave={interaction === "native-pointer" ? handlePointerLeave : undefined}
|
||||
>
|
||||
{interaction === "touch" ? <View pointerEvents="none" style={touchGripStyle} /> : null}
|
||||
</View>
|
||||
</GestureDetector>
|
||||
);
|
||||
|
||||
return (
|
||||
<View style={handleStyle} testID={testID}>
|
||||
{highlighted && (
|
||||
@@ -263,27 +299,7 @@ export function ResizeHandle({
|
||||
testID={testID ? `${testID}-highlight` : undefined}
|
||||
/>
|
||||
)}
|
||||
{finePointer ? (
|
||||
<View
|
||||
role="separator"
|
||||
aria-orientation={direction === "horizontal" ? "vertical" : "horizontal"}
|
||||
style={hitAreaStyle}
|
||||
onPointerDown={handlePointerDown}
|
||||
onPointerEnter={handlePointerEnter}
|
||||
onPointerLeave={handlePointerLeave}
|
||||
/>
|
||||
) : (
|
||||
<GestureDetector gesture={touchGesture}>
|
||||
<View
|
||||
role="separator"
|
||||
aria-orientation={direction === "horizontal" ? "vertical" : "horizontal"}
|
||||
collapsable={false}
|
||||
style={touchHitAreaStyle}
|
||||
>
|
||||
<View pointerEvents="none" style={touchGripStyle} />
|
||||
</View>
|
||||
</GestureDetector>
|
||||
)}
|
||||
{separatorHitArea}
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { useCallback, useEffect, useRef } from "react";
|
||||
import type { GestureResponderEvent } from "react-native";
|
||||
import * as Haptics from "expo-haptics";
|
||||
import { isWeb as platformIsWeb } from "@/constants/platform";
|
||||
import { supportsTouchHaptics, usesTouchLongPressHold } from "@/constants/touch-timing";
|
||||
import { decideLongPressMove } from "@/utils/sidebar-gesture-arbitration";
|
||||
import type { useContextMenu } from "@/components/ui/context-menu";
|
||||
|
||||
@@ -59,7 +59,7 @@ export function useLongPressDragInteraction(input: {
|
||||
|
||||
const armTimers = useCallback(() => {
|
||||
clearTimers();
|
||||
if (platformIsWeb || !drag) {
|
||||
if (!usesTouchLongPressHold || !drag) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -86,7 +86,7 @@ export function useLongPressDragInteraction(input: {
|
||||
dragArmedRef.current = true;
|
||||
dragActivatedRef.current = true;
|
||||
didLongPressRef.current = true;
|
||||
void Haptics.selectionAsync().catch(() => {});
|
||||
if (supportsTouchHaptics) void Haptics.selectionAsync().catch(() => {});
|
||||
drag();
|
||||
}, DRAG_ARM_DELAY_MS);
|
||||
|
||||
@@ -109,7 +109,7 @@ export function useLongPressDragInteraction(input: {
|
||||
if (distance > CONTEXT_MENU_STATIONARY_SLOP_PX) {
|
||||
return;
|
||||
}
|
||||
void Haptics.selectionAsync().catch(() => {});
|
||||
if (supportsTouchHaptics) void Haptics.selectionAsync().catch(() => {});
|
||||
openContextMenuAtStartPoint();
|
||||
}, CONTEXT_MENU_DELAY_MS);
|
||||
}, [clearTimers, drag, menuController, openContextMenuAtStartPoint]);
|
||||
|
||||
@@ -22,6 +22,7 @@ import {
|
||||
} from "@getpaseo/protocol/terminal-input-mode";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { useHostRuntimeClient, useHostRuntimeIsConnected } from "@/runtime/host-runtime";
|
||||
import { hasSoftwareKeyboard } from "@/keyboard";
|
||||
import { useKeyboardShiftStyle } from "@/keyboard/shift";
|
||||
import { useAppActivelyVisible } from "@/hooks/use-app-visible";
|
||||
import { useStableEvent } from "@/hooks/use-stable-event";
|
||||
@@ -89,7 +90,6 @@ import {
|
||||
type TerminalResizeRequest,
|
||||
} from "./terminal-resize-debouncer";
|
||||
import { useIsCompactFormFactor } from "@/constants/layout";
|
||||
import { isNative } from "@/constants/platform";
|
||||
import { useKeyboardFocusSurface } from "@/keyboard";
|
||||
import {
|
||||
applyTerminalRendererReadyChange,
|
||||
@@ -305,7 +305,10 @@ export function TerminalPane({
|
||||
return trimmed.length > 0 ? trimmed : undefined;
|
||||
}, [settings.monoFontFamily]);
|
||||
const isMobile = useIsCompactFormFactor();
|
||||
const showVirtualKeyBar = shouldShowTerminalVirtualKeyBar({ isNative, isCompact: isMobile });
|
||||
const showVirtualKeyBar = shouldShowTerminalVirtualKeyBar({
|
||||
hasSoftwareKeyboard,
|
||||
isCompact: isMobile,
|
||||
});
|
||||
const [keyBarWidth, setKeyBarWidth] = useState(0);
|
||||
const virtualKeyboardRows = resolveTerminalVirtualKeyboardRows({
|
||||
isCompact: isMobile,
|
||||
@@ -316,7 +319,7 @@ export function TerminalPane({
|
||||
const swipeGesturesEnabled = isMobile;
|
||||
const { shift: keyboardShift, style: keyboardPaddingStyle } = useKeyboardShiftStyle({
|
||||
mode: "padding",
|
||||
enabled: isNative || isMobile,
|
||||
enabled: hasSoftwareKeyboard || isMobile,
|
||||
});
|
||||
const [keyboardInset, setKeyboardInset] = useState(0);
|
||||
const [isKeyboardVisible, setIsKeyboardVisible] = useState(false);
|
||||
@@ -608,7 +611,7 @@ export function TerminalPane({
|
||||
|
||||
const handleKeyboardChange = useCallback(
|
||||
(nextShift: number) => {
|
||||
setKeyboardInset(isNative || isMobile ? nextShift : 0);
|
||||
setKeyboardInset(hasSoftwareKeyboard || isMobile ? nextShift : 0);
|
||||
setIsKeyboardVisible(nextShift > 0);
|
||||
pulseKeyboardRefits();
|
||||
},
|
||||
@@ -1180,10 +1183,10 @@ export function TerminalPane({
|
||||
emulatorRef.current?.blur();
|
||||
onOpenFileExplorer();
|
||||
}, [swipeGesturesEnabled, onOpenFileExplorer]);
|
||||
const showPasteAction = shouldShowTerminalPasteAction({ isNative });
|
||||
const showPasteAction = shouldShowTerminalPasteAction({ hasSoftwareKeyboard });
|
||||
const showFloatingCopyAction = shouldShowTerminalFloatingCopyAction({
|
||||
hasSelection,
|
||||
isNative,
|
||||
hasSoftwareKeyboard,
|
||||
});
|
||||
const keyboardToggleIconColor = theme.colors.foregroundMuted;
|
||||
|
||||
@@ -1332,7 +1335,9 @@ export function TerminalPane({
|
||||
<View
|
||||
style={styles.keyboardRows}
|
||||
onLayout={handleKeyBarLayout}
|
||||
testID={isNative && !isMobile ? "terminal-virtual-keyboard-native-wide" : undefined}
|
||||
testID={
|
||||
hasSoftwareKeyboard && !isMobile ? "terminal-virtual-keyboard-native-wide" : undefined
|
||||
}
|
||||
>
|
||||
{virtualKeyboardRows.map((row) => (
|
||||
<View
|
||||
|
||||
@@ -21,7 +21,7 @@ import { ComposerToolbarGlyph } from "@/composer/agent-controls/glyph";
|
||||
import { resolveModelTriggerLabels } from "@/composer/agent-controls/layout";
|
||||
import type { ProviderSelectorProvider } from "@/provider-selection/provider-selection";
|
||||
import { useIsCompactFormFactor } from "@/constants/layout";
|
||||
import { isWeb } from "@/constants/platform";
|
||||
import { hasSoftwareKeyboard } from "@/keyboard";
|
||||
import { readMeasuredWidth } from "@/hooks/use-container-width";
|
||||
import {
|
||||
toolbarContentSlot,
|
||||
@@ -186,7 +186,7 @@ export function CompactModelSheet({
|
||||
selectedProvider,
|
||||
selectedModel,
|
||||
isLoading,
|
||||
autoFocusSearch: isWeb && !usesBottomSheet,
|
||||
autoFocusSearch: !hasSoftwareKeyboard && !usesBottomSheet,
|
||||
profiles,
|
||||
serverId,
|
||||
});
|
||||
|
||||
@@ -61,6 +61,7 @@ import {
|
||||
toolbarSlot,
|
||||
} from "@/components/ui/control-geometry";
|
||||
import { usePanelStore, type MobilePanelView } from "@/stores/panel-store";
|
||||
import { hasSoftwareKeyboard } from "@/keyboard";
|
||||
import { usePointerCapabilities } from "@/hooks/pointer-capabilities";
|
||||
import { useShallow } from "zustand/shallow";
|
||||
import {
|
||||
@@ -254,7 +255,7 @@ function resolveKeyboardPriority(isMessageInputFocused: boolean): number {
|
||||
}
|
||||
|
||||
function resolveIsDesktopWebBreakpoint(isMobile: boolean): boolean {
|
||||
return isWeb && !isMobile;
|
||||
return !hasSoftwareKeyboard && !isMobile;
|
||||
}
|
||||
|
||||
function resolveCompactLayout(override: boolean | undefined, formFactor: boolean): boolean {
|
||||
|
||||
@@ -82,8 +82,11 @@ import { useIosHardwareKeyboardSubmit } from "@/hooks/use-ios-hardware-keyboard-
|
||||
import { formatShortcut, type ShortcutKey } from "@/utils/format-shortcut";
|
||||
import { getShortcutOs } from "@/utils/shortcut-platform";
|
||||
import type { MessageInputKeyboardActionKind } from "@/keyboard/actions";
|
||||
import { supportsConfigurableComposerSendKeys } from "@/keyboard";
|
||||
import { isImeComposingKeyboardEvent } from "@/utils/keyboard-ime";
|
||||
import { getIsElectron, isNative, isWeb } from "@/constants/platform";
|
||||
import { getIsElectron, isWeb } from "@/constants/platform";
|
||||
import { composerMinInputHeight } from "@/constants/presentation";
|
||||
import { supportsTouchHaptics } from "@/constants/touch-timing";
|
||||
import { useIsCompactFormFactor } from "@/constants/layout";
|
||||
import { useComposerKeyboardScope } from "@/composer/keyboard-scope";
|
||||
import { RenderProfile } from "@/utils/render-profiler";
|
||||
@@ -238,11 +241,9 @@ export interface MessageInputRef {
|
||||
getNativeElement?: () => HTMLElement | null;
|
||||
}
|
||||
|
||||
const MIN_INPUT_HEIGHT_MOBILE = 30;
|
||||
const MIN_INPUT_HEIGHT_DESKTOP = 46;
|
||||
const DEFAULT_MAX_INPUT_HEIGHT = 160;
|
||||
const MAX_INPUT_VIEWPORT_RATIO = 0.5;
|
||||
const MIN_INPUT_HEIGHT = isWeb ? MIN_INPUT_HEIGHT_DESKTOP : MIN_INPUT_HEIGHT_MOBILE;
|
||||
const MIN_INPUT_HEIGHT = composerMinInputHeight;
|
||||
type WebTextInputKeyPressEvent = NativeSyntheticEvent<
|
||||
TextInputKeyPressEventData & {
|
||||
metaKey?: boolean;
|
||||
@@ -1883,7 +1884,7 @@ export const MessageInput = forwardRef<MessageInputRef, MessageInputProps>(
|
||||
});
|
||||
|
||||
const handleLongPressSend = useCallback(() => {
|
||||
if (alternateSendAction && isNative) {
|
||||
if (alternateSendAction && supportsTouchHaptics) {
|
||||
void Haptics.impactAsync(Haptics.ImpactFeedbackStyle.Medium).catch(() => {});
|
||||
}
|
||||
handleAlternateSendAction();
|
||||
@@ -1910,12 +1911,12 @@ export const MessageInput = forwardRef<MessageInputRef, MessageInputProps>(
|
||||
[onSelectionChangeCallback],
|
||||
);
|
||||
|
||||
const shouldHandleWebKeyPress = isWeb;
|
||||
const shouldSubmitOnEnter = isWeb && !isCompact;
|
||||
const shouldHandleKeyPress = supportsConfigurableComposerSendKeys;
|
||||
const shouldSubmitOnEnter = supportsConfigurableComposerSendKeys && !isCompact;
|
||||
|
||||
const handleDesktopKeyPress = useCallback(
|
||||
(event: WebTextInputKeyPressEvent) => {
|
||||
if (!shouldHandleWebKeyPress) return;
|
||||
if (!shouldHandleKeyPress) return;
|
||||
handleDesktopKeyPressImpl(event, {
|
||||
onKeyPressCallback,
|
||||
input: getComposerInputSnapshot(
|
||||
@@ -1935,7 +1936,7 @@ export const MessageInput = forwardRef<MessageInputRef, MessageInputProps>(
|
||||
});
|
||||
},
|
||||
[
|
||||
shouldHandleWebKeyPress,
|
||||
shouldHandleKeyPress,
|
||||
onKeyPressCallback,
|
||||
shouldSubmitOnEnter,
|
||||
sendShortcut,
|
||||
@@ -2222,14 +2223,19 @@ export const MessageInput = forwardRef<MessageInputRef, MessageInputProps>(
|
||||
editable={!isDictating && !isRealtimeVoiceForCurrentAgent && !disabled}
|
||||
scrollEnabled={isComposerScrollEnabled}
|
||||
autoFocus={false}
|
||||
onKeyPress={shouldHandleWebKeyPress ? handleDesktopKeyPress : undefined}
|
||||
onKeyPress={shouldHandleKeyPress ? handleDesktopKeyPress : undefined}
|
||||
onSelectionChange={handleSelectionChange}
|
||||
onPasteImages={onPasteImages}
|
||||
onPasteError={handlePasteError}
|
||||
fullscreen={isFullscreen}
|
||||
compact={isCompact}
|
||||
onRenderedLinesChange={setRenderedLines}
|
||||
focusHintVisible={!isFullscreen && isWeb && !isInputFocused && !hasLiveText}
|
||||
focusHintVisible={
|
||||
!isFullscreen &&
|
||||
supportsConfigurableComposerSendKeys &&
|
||||
!isInputFocused &&
|
||||
!hasLiveText
|
||||
}
|
||||
focusInputKeys={focusInputKeys}
|
||||
focusHintLabel={t("composer.input.focusHint", {
|
||||
shortcut: focusInputKeys ? formatShortcut(focusInputKeys[0], getShortcutOs()) : "",
|
||||
@@ -2253,7 +2259,7 @@ export const MessageInput = forwardRef<MessageInputRef, MessageInputProps>(
|
||||
isRealtimeVoiceForCurrentAgent,
|
||||
disabled,
|
||||
isComposerScrollEnabled,
|
||||
shouldHandleWebKeyPress,
|
||||
shouldHandleKeyPress,
|
||||
handleDesktopKeyPress,
|
||||
handleSelectionChange,
|
||||
onPasteImages,
|
||||
|
||||
@@ -25,6 +25,9 @@ export const isWeb = Platform.OS === "web";
|
||||
/** iOS or Android — the JS runtime is React Native. */
|
||||
export const isNative = Platform.OS !== "web";
|
||||
|
||||
/** Platforms with an alpha-mask compositor for decorative shimmer effects. */
|
||||
export const supportsMaskedEffects = ["web", "ios", "android"].includes(Platform.OS);
|
||||
|
||||
/** Development build/runtime — true in Metro dev bundles, false in production. */
|
||||
export const isDev = Boolean((globalThis as { __DEV__?: boolean }).__DEV__);
|
||||
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { resolvePresentationCapabilities } from "./presentation";
|
||||
|
||||
describe("presentation capabilities per target", () => {
|
||||
it("resolves mobile and desktop presentation answers for iOS, Android, web, and Electron", () => {
|
||||
expect(resolvePresentationCapabilities({ isNative: true, isWeb: false })).toEqual({
|
||||
allowsInlineWorkspaceRename: false,
|
||||
usesCompactBottomSheet: true,
|
||||
usesDesktopPopoverSpacing: false,
|
||||
initialUiBaseFontSize: 15,
|
||||
initialContentFontSize: 16,
|
||||
usesMobileContentFontMigration: true,
|
||||
composerMinInputHeight: 30,
|
||||
});
|
||||
expect(resolvePresentationCapabilities({ isNative: false, isWeb: true })).toEqual({
|
||||
allowsInlineWorkspaceRename: true,
|
||||
usesCompactBottomSheet: false,
|
||||
usesDesktopPopoverSpacing: true,
|
||||
initialUiBaseFontSize: 14,
|
||||
initialContentFontSize: 15,
|
||||
usesMobileContentFontMigration: false,
|
||||
composerMinInputHeight: 46,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,44 @@
|
||||
import { FONT_SIZE } from "@/styles/theme";
|
||||
import { isNative, isWeb } from "./platform";
|
||||
|
||||
export interface PresentationCapabilities {
|
||||
/** Wide sidebar rows rename in place instead of opening a rename modal. */
|
||||
allowsInlineWorkspaceRename: boolean;
|
||||
/** Compact screens present bottom sheets (`SheetFlatList` / Gorhom modal) instead of dialogs. */
|
||||
usesCompactBottomSheet: boolean;
|
||||
/** Popover lists use tight desktop row padding instead of touch-sheet spacing. */
|
||||
usesDesktopPopoverSpacing: boolean;
|
||||
/** Initial UI font size (pt) when no user preference is saved. */
|
||||
initialUiBaseFontSize: number;
|
||||
/** Initial chat content font size (pt) when no user preference is saved. */
|
||||
initialContentFontSize: number;
|
||||
/** Whether legacy 15 pt persisted content size migrates up to the mobile 16 pt default. */
|
||||
usesMobileContentFontMigration: boolean;
|
||||
/** Minimum multiline composer input height (pt). */
|
||||
composerMinInputHeight: number;
|
||||
}
|
||||
|
||||
export function resolvePresentationCapabilities(input: {
|
||||
isNative: boolean;
|
||||
isWeb: boolean;
|
||||
}): PresentationCapabilities {
|
||||
return {
|
||||
allowsInlineWorkspaceRename: input.isWeb,
|
||||
usesCompactBottomSheet: input.isNative,
|
||||
usesDesktopPopoverSpacing: input.isWeb,
|
||||
initialUiBaseFontSize: input.isNative ? 15 : FONT_SIZE.base,
|
||||
initialContentFontSize: input.isNative ? 16 : FONT_SIZE.content,
|
||||
usesMobileContentFontMigration: input.isNative,
|
||||
composerMinInputHeight: input.isWeb ? 46 : 30,
|
||||
};
|
||||
}
|
||||
|
||||
const CAPABILITIES = resolvePresentationCapabilities({ isNative, isWeb });
|
||||
|
||||
export const allowsInlineWorkspaceRename = CAPABILITIES.allowsInlineWorkspaceRename;
|
||||
export const usesCompactBottomSheet = CAPABILITIES.usesCompactBottomSheet;
|
||||
export const usesDesktopPopoverSpacing = CAPABILITIES.usesDesktopPopoverSpacing;
|
||||
export const initialUiBaseFontSize = CAPABILITIES.initialUiBaseFontSize;
|
||||
export const initialContentFontSize = CAPABILITIES.initialContentFontSize;
|
||||
export const usesMobileContentFontMigration = CAPABILITIES.usesMobileContentFontMigration;
|
||||
export const composerMinInputHeight = CAPABILITIES.composerMinInputHeight;
|
||||
@@ -0,0 +1,26 @@
|
||||
// Platform-free: Playwright imports this through workspace-deck-retention in plain Node.
|
||||
|
||||
export interface SourceFileBudgets {
|
||||
readonly highlighted: number;
|
||||
readonly plain: number;
|
||||
}
|
||||
|
||||
export interface PlatformResourceBudgets {
|
||||
readonly workspaceDeckRetentionLimit: number;
|
||||
readonly sourceFileBudgets: SourceFileBudgets;
|
||||
}
|
||||
|
||||
const MOBILE_RESOURCE_BUDGETS: PlatformResourceBudgets = {
|
||||
workspaceDeckRetentionLimit: 1,
|
||||
sourceFileBudgets: { highlighted: 1024 * 1024, plain: 10 * 1024 * 1024 },
|
||||
};
|
||||
|
||||
const WEB_RESOURCE_BUDGETS: PlatformResourceBudgets = {
|
||||
workspaceDeckRetentionLimit: 10,
|
||||
sourceFileBudgets: { highlighted: 10 * 1024 * 1024, plain: 50 * 1024 * 1024 },
|
||||
};
|
||||
|
||||
/** Native phones use mobile memory budgets; web and Electron use desktop budgets. */
|
||||
export function resolveResourceBudgets(input: { isNative: boolean }): PlatformResourceBudgets {
|
||||
return input.isNative ? MOBILE_RESOURCE_BUDGETS : WEB_RESOURCE_BUDGETS;
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { resolveResourceBudgets } from "./resource-budget-tables";
|
||||
|
||||
describe("resource budget per target", () => {
|
||||
it("resolves mobile and desktop resource budget limits for iOS, Android, web, and Electron", () => {
|
||||
expect(resolveResourceBudgets({ isNative: true })).toEqual({
|
||||
workspaceDeckRetentionLimit: 1,
|
||||
sourceFileBudgets: { highlighted: 1024 * 1024, plain: 10 * 1024 * 1024 },
|
||||
});
|
||||
expect(resolveResourceBudgets({ isNative: false })).toEqual({
|
||||
workspaceDeckRetentionLimit: 10,
|
||||
sourceFileBudgets: { highlighted: 10 * 1024 * 1024, plain: 50 * 1024 * 1024 },
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,7 @@
|
||||
import { isNative } from "./platform";
|
||||
import { resolveResourceBudgets } from "./resource-budget-tables";
|
||||
|
||||
const RESOURCE_BUDGETS = resolveResourceBudgets({ isNative });
|
||||
|
||||
export const workspaceDeckRetentionLimit = RESOURCE_BUDGETS.workspaceDeckRetentionLimit;
|
||||
export const sourceFileBudgets = RESOURCE_BUDGETS.sourceFileBudgets;
|
||||
@@ -0,0 +1,15 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { resolveTouchTiming } from "./touch-timing";
|
||||
|
||||
describe("touch timing per target", () => {
|
||||
it("enables touch timing and haptics only on iOS and Android, not on web or Electron", () => {
|
||||
expect(resolveTouchTiming({ isNative: true })).toEqual({
|
||||
supportsTouchHaptics: true,
|
||||
usesTouchLongPressHold: true,
|
||||
});
|
||||
expect(resolveTouchTiming({ isNative: false })).toEqual({
|
||||
supportsTouchHaptics: false,
|
||||
usesTouchLongPressHold: false,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,20 @@
|
||||
import { isNative } from "./platform";
|
||||
|
||||
export interface TouchTimingCapabilities {
|
||||
/** Fire tactile `expo-haptics` feedback on touch interactions. */
|
||||
supportsTouchHaptics: boolean;
|
||||
/** Require a stationary long-press delay to arm drag or open context menus. */
|
||||
usesTouchLongPressHold: boolean;
|
||||
}
|
||||
|
||||
export function resolveTouchTiming(input: { isNative: boolean }): TouchTimingCapabilities {
|
||||
return {
|
||||
supportsTouchHaptics: input.isNative,
|
||||
usesTouchLongPressHold: input.isNative,
|
||||
};
|
||||
}
|
||||
|
||||
const TOUCH_TIMING = resolveTouchTiming({ isNative });
|
||||
|
||||
export const supportsTouchHaptics = TOUCH_TIMING.supportsTouchHaptics;
|
||||
export const usesTouchLongPressHold = TOUCH_TIMING.usesTouchLongPressHold;
|
||||
@@ -73,7 +73,7 @@ type TextFilePanelProps = BuiltinFilePanelProps & {
|
||||
*/
|
||||
export function TextFilePanel(props: TextFilePanelProps) {
|
||||
const size = props.file.size;
|
||||
const presentation = selectSourcePresentation({ size, platform: isWeb ? "web" : "native" });
|
||||
const presentation = selectSourcePresentation({ size });
|
||||
if (presentation === "unsupported") return <TooLargeTextFile size={size} />;
|
||||
if (isWeb && size <= MAX_EDITABLE_BYTES) return <EditableTextFile {...props} />;
|
||||
return <ReadonlyTextFile {...props} presentation={presentation} />;
|
||||
|
||||
@@ -11,4 +11,11 @@ describe("selectSourcePresentation", () => {
|
||||
expect(selectSourcePresentation({ platform, size: budgets.plain + 1 })).toBe("unsupported");
|
||||
});
|
||||
}
|
||||
|
||||
it("defaults to the target resource budget limits when no platform override is passed", () => {
|
||||
const webBudgets = SOURCE_PRESENTATION_BUDGETS.web;
|
||||
expect(selectSourcePresentation({ size: webBudgets.highlighted })).toBe("highlighted");
|
||||
expect(selectSourcePresentation({ size: webBudgets.highlighted + 1 })).toBe("plain");
|
||||
expect(selectSourcePresentation({ size: webBudgets.plain + 1 })).toBe("unsupported");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
import { sourceFileBudgets } from "@/constants/resource-budget";
|
||||
import { resolveResourceBudgets } from "@/constants/resource-budget-tables";
|
||||
|
||||
export const SOURCE_PRESENTATION_BUDGETS = {
|
||||
web: { highlighted: 10 * 1024 * 1024, plain: 50 * 1024 * 1024 },
|
||||
native: { highlighted: 1024 * 1024, plain: 10 * 1024 * 1024 },
|
||||
web: resolveResourceBudgets({ isNative: false }).sourceFileBudgets,
|
||||
native: resolveResourceBudgets({ isNative: true }).sourceFileBudgets,
|
||||
} as const;
|
||||
|
||||
export type SourcePresentation = "highlighted" | "plain" | "unsupported";
|
||||
@@ -8,9 +11,9 @@ export type SourcePlatform = keyof typeof SOURCE_PRESENTATION_BUDGETS;
|
||||
|
||||
export function selectSourcePresentation(input: {
|
||||
size: number;
|
||||
platform: SourcePlatform;
|
||||
platform?: SourcePlatform;
|
||||
}): SourcePresentation {
|
||||
const budgets = SOURCE_PRESENTATION_BUDGETS[input.platform];
|
||||
const budgets = input.platform ? SOURCE_PRESENTATION_BUDGETS[input.platform] : sourceFileBudgets;
|
||||
if (input.size <= budgets.highlighted) return "highlighted";
|
||||
if (input.size <= budgets.plain) return "plain";
|
||||
return "unsupported";
|
||||
|
||||
@@ -23,7 +23,12 @@ import {
|
||||
isChecksHiddenByLegacyRowItem,
|
||||
type SidebarRowItems,
|
||||
} from "@/components/sidebar/display-preferences/row-items";
|
||||
import { isNative } from "@/constants/platform";
|
||||
import {
|
||||
initialContentFontSize,
|
||||
initialUiBaseFontSize,
|
||||
resolvePresentationCapabilities,
|
||||
usesMobileContentFontMigration,
|
||||
} from "@/constants/presentation";
|
||||
import {
|
||||
DEFAULT_CONTENT_MAX_WIDTH,
|
||||
FONT_SIZE,
|
||||
@@ -60,17 +65,19 @@ export const DEFAULT_TERMINAL_SCROLLBACK_LINES = 10_000;
|
||||
export const MIN_TERMINAL_SCROLLBACK_LINES = 0;
|
||||
export const MAX_TERMINAL_SCROLLBACK_LINES = 1_000_000;
|
||||
export function defaultUiBaseFontSize(native: boolean): number {
|
||||
return native ? 15 : FONT_SIZE.base;
|
||||
return resolvePresentationCapabilities({ isNative: native, isWeb: !native })
|
||||
.initialUiBaseFontSize;
|
||||
}
|
||||
|
||||
export const DEFAULT_UI_BASE_FONT_SIZE = defaultUiBaseFontSize(isNative);
|
||||
export const DEFAULT_UI_BASE_FONT_SIZE = initialUiBaseFontSize;
|
||||
export const MIN_UI_BASE_FONT_SIZE = 10;
|
||||
export const MAX_UI_BASE_FONT_SIZE = 21;
|
||||
export function defaultContentFontSize(native: boolean): number {
|
||||
return native ? 16 : FONT_SIZE.content;
|
||||
return resolvePresentationCapabilities({ isNative: native, isWeb: !native })
|
||||
.initialContentFontSize;
|
||||
}
|
||||
|
||||
export const DEFAULT_CONTENT_FONT_SIZE = defaultContentFontSize(isNative);
|
||||
export const DEFAULT_CONTENT_FONT_SIZE = initialContentFontSize;
|
||||
export const MIN_CONTENT_FONT_SIZE = 10;
|
||||
export const MAX_CONTENT_FONT_SIZE = 21;
|
||||
export const DEFAULT_CODE_FONT_SIZE = 12; // == FONT_SIZE.code
|
||||
@@ -410,7 +417,9 @@ export async function loadAppSettingsFromStorage(deps: SettingsDeps): Promise<Ap
|
||||
await writeAppSettings(deps.storage, read.stored, read.settings);
|
||||
}
|
||||
const { needsWrite: _needsWrite, ...stored } = read.stored;
|
||||
return await migrateAppSettings(read.settings, deps.storage, stored, { native: isNative });
|
||||
return await migrateAppSettings(read.settings, deps.storage, stored, {
|
||||
native: usesMobileContentFontMigration,
|
||||
});
|
||||
} catch (error) {
|
||||
console.error("[AppSettings] Failed to load settings:", error);
|
||||
throw error;
|
||||
|
||||
@@ -2435,6 +2435,9 @@ export const ar: TranslationResources = {
|
||||
archiveFinishedRetry: "إعادة المحاولة ({{failed}}/{{total}})",
|
||||
},
|
||||
panels: {
|
||||
renderError: {
|
||||
title: "تعذّر عرض هذه اللوحة",
|
||||
},
|
||||
draft: {
|
||||
newAgent: "وكيل جديد",
|
||||
creatingAgent: "وكيل الخلق",
|
||||
|
||||
@@ -2467,6 +2467,9 @@ export const en = {
|
||||
archiveFinishedRetry: "Retry ({{failed}}/{{total}})",
|
||||
},
|
||||
panels: {
|
||||
renderError: {
|
||||
title: "Unable to show this panel",
|
||||
},
|
||||
draft: {
|
||||
newAgent: "New Agent",
|
||||
creatingAgent: "Creating agent",
|
||||
|
||||
@@ -2495,6 +2495,9 @@ export const es: TranslationResources = {
|
||||
archiveFinishedRetry: "Reintentar ({{failed}}/{{total}})",
|
||||
},
|
||||
panels: {
|
||||
renderError: {
|
||||
title: "No se puede mostrar este panel",
|
||||
},
|
||||
draft: {
|
||||
newAgent: "Nuevo agente",
|
||||
creatingAgent: "Agente creador",
|
||||
|
||||
@@ -2491,6 +2491,9 @@ export const fr: TranslationResources = {
|
||||
archiveFinishedRetry: "Réessayer ({{failed}}/{{total}})",
|
||||
},
|
||||
panels: {
|
||||
renderError: {
|
||||
title: "Impossible d'afficher ce panneau",
|
||||
},
|
||||
draft: {
|
||||
newAgent: "Nouvel agent",
|
||||
creatingAgent: "Création de l’agent",
|
||||
|
||||
@@ -2461,6 +2461,9 @@ export const ja: TranslationResources = {
|
||||
archiveFinishedRetry: "再試行 ({{failed}}/{{total}})",
|
||||
},
|
||||
panels: {
|
||||
renderError: {
|
||||
title: "このパネルを表示できません",
|
||||
},
|
||||
draft: {
|
||||
newAgent: "新しいエージェント",
|
||||
creatingAgent: "エージェントを作成中",
|
||||
|
||||
@@ -2452,6 +2452,9 @@ export const ko: TranslationResources = {
|
||||
archiveFinishedRetry: "다시 시도 ({{failed}}/{{total}})",
|
||||
},
|
||||
panels: {
|
||||
renderError: {
|
||||
title: "이 패널을 표시할 수 없습니다",
|
||||
},
|
||||
draft: {
|
||||
newAgent: "새 에이전트",
|
||||
creatingAgent: "에이전트 생성 중",
|
||||
|
||||
@@ -2477,6 +2477,9 @@ export const ptBR: TranslationResources = {
|
||||
archiveFinishedRetry: "Tentar novamente ({{failed}}/{{total}})",
|
||||
},
|
||||
panels: {
|
||||
renderError: {
|
||||
title: "Não foi possível exibir este painel",
|
||||
},
|
||||
draft: {
|
||||
newAgent: "Novo Agente",
|
||||
creatingAgent: "Criando agente",
|
||||
|
||||
@@ -2477,6 +2477,9 @@ export const ru: TranslationResources = {
|
||||
archiveFinishedRetry: "Повторить ({{failed}}/{{total}})",
|
||||
},
|
||||
panels: {
|
||||
renderError: {
|
||||
title: "Не удалось показать эту панель",
|
||||
},
|
||||
draft: {
|
||||
newAgent: "Новый агент",
|
||||
creatingAgent: "Создание агента",
|
||||
|
||||
@@ -2408,6 +2408,9 @@ export const zhCN: TranslationResources = {
|
||||
archiveFinishedRetry: "重试 ({{failed}}/{{total}})",
|
||||
},
|
||||
panels: {
|
||||
renderError: {
|
||||
title: "无法显示此面板",
|
||||
},
|
||||
draft: {
|
||||
newAgent: "新建 Agent",
|
||||
creatingAgent: "正在创建 Agent",
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { createHardwareKeyboardPresence } from "./internal/hardware-presence";
|
||||
import * as webConventions from "./internal/conventions.web";
|
||||
import { createWebHardwareKeyboardPresence } from "./internal/presence.web";
|
||||
import { buildEffectiveBindings } from "./keyboard-shortcuts";
|
||||
import { createKeyboardPipeline } from "./internal/pipeline";
|
||||
import { createOverlayRegistry } from "./internal/overlays";
|
||||
@@ -65,4 +67,39 @@ describe("hardware keyboard availability", () => {
|
||||
expect(actions).toEqual(["command-center.toggle"]);
|
||||
pipeline.dispose();
|
||||
});
|
||||
|
||||
it("answers keyboard presence and conventions per target", async () => {
|
||||
const nativeConventions = (await import(
|
||||
new URL("./internal/conventions.ts", import.meta.url).href
|
||||
)) as typeof webConventions & { usesDesktopBindings: boolean };
|
||||
const { hardwareKeyboardPresence: nativePresence } = (await import(
|
||||
new URL("./internal/presence.ts", import.meta.url).href
|
||||
)) as { hardwareKeyboardPresence: { getSnapshot(): boolean } };
|
||||
|
||||
expect(nativePresence.getSnapshot()).toBe(false);
|
||||
expect(
|
||||
createWebHardwareKeyboardPresence({ matches: true } as MediaQueryList, null).getSnapshot(),
|
||||
).toBe(true);
|
||||
expect(
|
||||
createWebHardwareKeyboardPresence({ matches: false } as MediaQueryList, null).getSnapshot(),
|
||||
).toBe(false);
|
||||
|
||||
expect({
|
||||
usesDesktopBindings: nativeConventions.usesDesktopBindings,
|
||||
supportsConfigurableComposerSendKeys: nativeConventions.supportsConfigurableComposerSendKeys,
|
||||
hasSoftwareKeyboard: nativeConventions.hasSoftwareKeyboard,
|
||||
}).toEqual({
|
||||
usesDesktopBindings: true,
|
||||
supportsConfigurableComposerSendKeys: false,
|
||||
hasSoftwareKeyboard: true,
|
||||
});
|
||||
|
||||
expect({
|
||||
supportsConfigurableComposerSendKeys: webConventions.supportsConfigurableComposerSendKeys,
|
||||
hasSoftwareKeyboard: webConventions.hasSoftwareKeyboard,
|
||||
}).toEqual({
|
||||
supportsConfigurableComposerSendKeys: true,
|
||||
hasSoftwareKeyboard: false,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -11,7 +11,11 @@ export { hasFocusedTextInput, registerFocusedTextInput } from "./internal/focuse
|
||||
export { useKeyboardFocusSurface } from "./internal/use-focus-surface";
|
||||
export { subscribeHardwareKeyboard } from "./internal/sources/hardware";
|
||||
export type { HardwareKeyboardEvent } from "./internal/sources/hardware";
|
||||
export { usesDesktopBindings, supportsConfigurableComposerSendKeys } from "./internal/conventions";
|
||||
export {
|
||||
hasSoftwareKeyboard,
|
||||
usesDesktopBindings,
|
||||
supportsConfigurableComposerSendKeys,
|
||||
} from "./internal/conventions";
|
||||
export type { BrowserKeyboardPolicy } from "./internal/sources/electron-browser";
|
||||
export { useHardwareKeyboardPresent } from "./availability";
|
||||
export { readPressModifiers } from "./internal/press-modifiers";
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
export const usesDesktopBindings = true;
|
||||
// Native composer Return retains its existing submit path in this feature.
|
||||
export const supportsConfigurableComposerSendKeys = false;
|
||||
export const hasSoftwareKeyboard = true;
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { isElectronRuntime } from "@/desktop/host";
|
||||
export const usesDesktopBindings = isElectronRuntime();
|
||||
export const supportsConfigurableComposerSendKeys = true;
|
||||
export const hasSoftwareKeyboard = false;
|
||||
|
||||
@@ -28,7 +28,7 @@ import { useSafeAreaInsets } from "react-native-safe-area-context";
|
||||
import { scheduleOnRN, scheduleOnUI } from "react-native-worklets";
|
||||
import { resolveDesktopSidebarWidth } from "@/components/desktop-sidebar-layout";
|
||||
import { useIsCompactFormFactor } from "@/constants/layout";
|
||||
import { isNative } from "@/constants/platform";
|
||||
import { hasSoftwareKeyboard } from "@/keyboard";
|
||||
import {
|
||||
usePanelStore,
|
||||
type MobilePanelSelection,
|
||||
@@ -138,7 +138,7 @@ export function MobilePanelsProvider({ children }: { children: ReactNode }) {
|
||||
if (selection.revision !== revision || selection.target !== panel) {
|
||||
return;
|
||||
}
|
||||
if (isNative && panel !== "agent") {
|
||||
if (hasSoftwareKeyboard && panel !== "agent") {
|
||||
Keyboard.dismiss();
|
||||
}
|
||||
settledPanel.setState(panel);
|
||||
|
||||
@@ -57,7 +57,8 @@ import {
|
||||
import type { WorkspaceComposerAttachment } from "@/attachments/types";
|
||||
import { useWorkspaceAttachmentScopeKey } from "@/attachments/workspace-attachments-store";
|
||||
import { COMPACT_CONTENT_WIDTH, useIsCompactFormFactor } from "@/constants/layout";
|
||||
import { isNative, isWeb } from "@/constants/platform";
|
||||
import { isWeb } from "@/constants/platform";
|
||||
import { hasSoftwareKeyboard } from "@/keyboard";
|
||||
import { useAgentAttentionClear } from "@/hooks/use-agent-attention-clear";
|
||||
import { useAgentInputDraft, type AgentInputDraft } from "@/composer/draft/input-draft";
|
||||
import {
|
||||
@@ -1883,7 +1884,7 @@ function AgentComposer({
|
||||
agentId={agentId}
|
||||
serverId={serverId}
|
||||
workspaceId={workspaceId}
|
||||
blurOnSubmit={isNative}
|
||||
blurOnSubmit={hasSoftwareKeyboard}
|
||||
isPaneFocused={isPaneFocused}
|
||||
textSource={agentInputDraft.textSource}
|
||||
onChangeText={agentInputDraft.editText}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import React, { Component, type ErrorInfo, type ReactNode } from "react";
|
||||
import type { ReactNode } from "react";
|
||||
import { Text } from "react-native";
|
||||
import { StyleSheet } from "react-native-unistyles";
|
||||
import { RenderErrorBoundary } from "@/components/render-error-boundary";
|
||||
|
||||
interface SurfaceErrorBoundaryProps {
|
||||
children: ReactNode;
|
||||
@@ -10,42 +11,30 @@ interface SurfaceErrorBoundaryProps {
|
||||
renderError?(error: string): ReactNode;
|
||||
}
|
||||
|
||||
interface SurfaceErrorBoundaryState {
|
||||
error: string | null;
|
||||
export function SurfaceErrorBoundary({
|
||||
children,
|
||||
installation,
|
||||
resetKey,
|
||||
Surface,
|
||||
renderError,
|
||||
}: SurfaceErrorBoundaryProps) {
|
||||
return (
|
||||
<RenderErrorBoundary
|
||||
resetKeys={[installation, resetKey, Surface]}
|
||||
onError={warnSurfaceRenderFailed}
|
||||
renderError={renderError ?? renderPluginFailed}
|
||||
>
|
||||
{children}
|
||||
</RenderErrorBoundary>
|
||||
);
|
||||
}
|
||||
|
||||
export class SurfaceErrorBoundary extends Component<
|
||||
SurfaceErrorBoundaryProps,
|
||||
SurfaceErrorBoundaryState
|
||||
> {
|
||||
state: SurfaceErrorBoundaryState = { error: null };
|
||||
function renderPluginFailed(error: string) {
|
||||
return <Text style={styles.errorText}>Plugin failed: {error}</Text>;
|
||||
}
|
||||
|
||||
static getDerivedStateFromError(error: unknown): SurfaceErrorBoundaryState {
|
||||
return { error: error instanceof Error ? error.message : String(error) };
|
||||
}
|
||||
|
||||
componentDidCatch(error: Error, info: ErrorInfo): void {
|
||||
console.warn("[Plugins] Surface render failed", error, info.componentStack);
|
||||
}
|
||||
|
||||
componentDidUpdate(previous: SurfaceErrorBoundaryProps): void {
|
||||
if (
|
||||
this.state.error &&
|
||||
(previous.installation !== this.props.installation ||
|
||||
previous.resetKey !== this.props.resetKey ||
|
||||
previous.Surface !== this.props.Surface)
|
||||
) {
|
||||
this.setState({ error: null });
|
||||
}
|
||||
}
|
||||
|
||||
render() {
|
||||
if (this.state.error) {
|
||||
if (this.props.renderError) return this.props.renderError(this.state.error);
|
||||
return <Text style={styles.errorText}>Plugin failed: {this.state.error}</Text>;
|
||||
}
|
||||
return this.props.children;
|
||||
}
|
||||
function warnSurfaceRenderFailed(error: unknown, componentStack: string | null | undefined): void {
|
||||
console.warn("[Plugins] Surface render failed", error, componentStack);
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create((theme) => ({
|
||||
|
||||
@@ -4,7 +4,6 @@ import {
|
||||
getNextWorkspaceDeckExpirationDelay,
|
||||
orderWorkspaceSelectionsForStableRender,
|
||||
reconcileRetainedWorkspaceSelections,
|
||||
resolveWorkspaceDeckRetentionLimit,
|
||||
resolveWorkspaceDeckEntries,
|
||||
shouldKeepWorkspaceDeckEntryMounted,
|
||||
WORKSPACE_DECK_INACTIVE_TTL_MS,
|
||||
@@ -30,21 +29,26 @@ function retainedWorkspaceIds(
|
||||
}
|
||||
|
||||
describe("reconcileRetainedWorkspaceSelections", () => {
|
||||
it("retains only the active workspace on native", () => {
|
||||
it("retains only the active workspace when limited to one mounted workspace", () => {
|
||||
const entries = reconcileRetainedWorkspaceSelections({
|
||||
currentEntries: [retained("A", null)],
|
||||
activeSelection: workspace("B"),
|
||||
now: 2,
|
||||
maxMountedWorkspaces: resolveWorkspaceDeckRetentionLimit({ isNative: true }),
|
||||
maxMountedWorkspaces: 1,
|
||||
});
|
||||
|
||||
expect(retainedWorkspaceIds(entries)).toEqual(["B"]);
|
||||
});
|
||||
|
||||
it("retains the desktop deck limit on web", () => {
|
||||
expect(resolveWorkspaceDeckRetentionLimit({ isNative: false })).toBe(
|
||||
WORKSPACE_DECK_MAX_MOUNTED_WORKSPACES,
|
||||
);
|
||||
it("retains up to the configured limit when higher", () => {
|
||||
const entries = reconcileRetainedWorkspaceSelections({
|
||||
currentEntries: [retained("A", null)],
|
||||
activeSelection: workspace("B"),
|
||||
now: 2,
|
||||
maxMountedWorkspaces: WORKSPACE_DECK_MAX_MOUNTED_WORKSPACES,
|
||||
});
|
||||
|
||||
expect(retainedWorkspaceIds(entries)).toEqual(["B", "A"]);
|
||||
});
|
||||
|
||||
it("retains inactive workspaces for ten minutes across app-wide routes", () => {
|
||||
|
||||
@@ -1,6 +1,10 @@
|
||||
import { resolveResourceBudgets } from "../../constants/resource-budget-tables";
|
||||
import type { ActiveWorkspaceSelection } from "@/stores/navigation-active-workspace-store";
|
||||
|
||||
export const WORKSPACE_DECK_MAX_MOUNTED_WORKSPACES = 10;
|
||||
// Relative import: Playwright loads this file in plain Node, without the `@/` alias or react-native.
|
||||
export const WORKSPACE_DECK_MAX_MOUNTED_WORKSPACES = resolveResourceBudgets({
|
||||
isNative: false,
|
||||
}).workspaceDeckRetentionLimit;
|
||||
export const WORKSPACE_DECK_INACTIVE_TTL_MS = 10 * 60 * 1000;
|
||||
|
||||
export interface RetainedWorkspaceSelection {
|
||||
@@ -8,10 +12,6 @@ export interface RetainedWorkspaceSelection {
|
||||
inactiveSince: number | null;
|
||||
}
|
||||
|
||||
export function resolveWorkspaceDeckRetentionLimit(input: { isNative: boolean }): number {
|
||||
return input.isNative ? 1 : WORKSPACE_DECK_MAX_MOUNTED_WORKSPACES;
|
||||
}
|
||||
|
||||
interface ReconcileRetainedWorkspaceSelectionsInput {
|
||||
currentEntries: RetainedWorkspaceSelection[];
|
||||
activeSelection: ActiveWorkspaceSelection | null;
|
||||
|
||||
@@ -0,0 +1,136 @@
|
||||
import { act } from "@testing-library/react";
|
||||
import React from "react";
|
||||
import { createRoot, type Root } from "react-dom/client";
|
||||
import { Text } from "react-native";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { definePanel, registerPanel } from "@/panels/panel-registry";
|
||||
import {
|
||||
buildWorkspacePaneContentModel,
|
||||
WorkspacePaneContent,
|
||||
} from "@/screens/workspace/workspace-pane-content";
|
||||
import type { WorkspaceTabDescriptor } from "@/screens/workspace/workspace-tabs-types";
|
||||
|
||||
Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });
|
||||
|
||||
let panelFails = false;
|
||||
let panelMounts = 0;
|
||||
|
||||
function TestPanel() {
|
||||
React.useEffect(() => {
|
||||
panelMounts += 1;
|
||||
}, []);
|
||||
if (panelFails) throw new Error("Panel exploded");
|
||||
return <Text>Panel content</Text>;
|
||||
}
|
||||
|
||||
// The workspace screen registers the real panels; this one stands in for each kind the tests open.
|
||||
for (const kind of ["agent", "draft"] as const) {
|
||||
registerPanel(
|
||||
definePanel(kind, {
|
||||
component: TestPanel,
|
||||
useDescriptor: () => {
|
||||
throw new Error("The test panel has no descriptor");
|
||||
},
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
const draftTab: WorkspaceTabDescriptor = {
|
||||
key: "tab-a",
|
||||
tabId: "tab-a",
|
||||
kind: "draft",
|
||||
target: { kind: "draft", draftId: "draft-a" },
|
||||
};
|
||||
const agentTab: WorkspaceTabDescriptor = {
|
||||
key: "tab-a",
|
||||
tabId: "tab-a",
|
||||
kind: "agent",
|
||||
target: { kind: "agent", agentId: "agent-a" },
|
||||
};
|
||||
|
||||
function buildContent(tab: WorkspaceTabDescriptor) {
|
||||
return buildWorkspacePaneContentModel({
|
||||
tab,
|
||||
normalizedServerId: "server-a",
|
||||
normalizedWorkspaceId: "workspace-a",
|
||||
host: "main",
|
||||
onOpenTab: vi.fn(),
|
||||
onOpenPreferredTarget: vi.fn(),
|
||||
onOpenTargetToSide: vi.fn(),
|
||||
onCloseCurrentTab: vi.fn(),
|
||||
onRetargetCurrentTab: vi.fn(),
|
||||
onSetCurrentTabState: vi.fn(),
|
||||
onOpenWorkspaceFile: vi.fn(),
|
||||
onOpenImportSheet: vi.fn(),
|
||||
});
|
||||
}
|
||||
|
||||
function byTestId(container: HTMLElement, testID: string): HTMLElement | null {
|
||||
return container.querySelector(`[data-testid="${testID}"]`);
|
||||
}
|
||||
|
||||
// Every host (explorer, split pane, compact center, sheet) mounts panels through
|
||||
// WorkspacePaneContent, so its boundary keeps a panel's render error from reaching the root screen.
|
||||
describe("WorkspacePaneContent when the panel throws while rendering", () => {
|
||||
let root: Root;
|
||||
let container: HTMLDivElement;
|
||||
|
||||
function show(tab: WorkspaceTabDescriptor) {
|
||||
act(() =>
|
||||
root.render(
|
||||
<>
|
||||
<Text>Sibling</Text>
|
||||
<WorkspacePaneContent content={buildContent(tab)} isPaneFocused isWorkspaceFocused />
|
||||
</>,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
panelFails = false;
|
||||
panelMounts = 0;
|
||||
container = document.createElement("div");
|
||||
document.body.appendChild(container);
|
||||
root = createRoot(container);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
act(() => root.unmount());
|
||||
container.remove();
|
||||
});
|
||||
|
||||
it("shows the error in place of the panel and retries on demand", () => {
|
||||
panelFails = true;
|
||||
show(agentTab);
|
||||
|
||||
expect(container.textContent).toContain("Sibling");
|
||||
expect(byTestId(container, "panel-render-error")?.textContent).toContain("Panel exploded");
|
||||
|
||||
panelFails = false;
|
||||
act(() => byTestId(container, "panel-render-error-retry")?.click());
|
||||
|
||||
expect(byTestId(container, "panel-render-error")).toBeNull();
|
||||
expect(container.textContent).toContain("Panel content");
|
||||
expect(container.textContent).toContain("Sibling");
|
||||
});
|
||||
|
||||
it("clears the error when the tab is retargeted", () => {
|
||||
panelFails = true;
|
||||
show(draftTab);
|
||||
expect(byTestId(container, "panel-render-error")).not.toBeNull();
|
||||
|
||||
panelFails = false;
|
||||
show(agentTab);
|
||||
|
||||
expect(byTestId(container, "panel-render-error")).toBeNull();
|
||||
expect(container.textContent).toContain("Panel content");
|
||||
});
|
||||
|
||||
it("keeps a healthy panel mounted when its tab is retargeted in place", () => {
|
||||
show(draftTab);
|
||||
show(agentTab);
|
||||
|
||||
expect(container.textContent).toContain("Panel content");
|
||||
expect(panelMounts).toBe(1);
|
||||
});
|
||||
});
|
||||
@@ -1,6 +1,12 @@
|
||||
import { ComposerEditingScope } from "@/composer/editing-session";
|
||||
import React, { useMemo, type ComponentType } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { View } from "react-native";
|
||||
import { StyleSheet } from "react-native-unistyles";
|
||||
import invariant from "tiny-invariant";
|
||||
import { RenderErrorBoundary } from "@/components/render-error-boundary";
|
||||
import { Alert } from "@/components/ui/alert";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
createPaneFocusContextValue,
|
||||
PaneFocusProvider,
|
||||
@@ -87,6 +93,31 @@ export interface WorkspacePaneContentProps {
|
||||
onFocusPane?: () => void;
|
||||
}
|
||||
|
||||
function logPanelRenderError(error: unknown, componentStack: string | null | undefined): void {
|
||||
console.error("[WorkspacePanel] Render failed", error, componentStack);
|
||||
}
|
||||
|
||||
function renderPanelError(error: string, retry: () => void) {
|
||||
return <PanelRenderError error={error} onRetry={retry} />;
|
||||
}
|
||||
|
||||
function PanelRenderError({ error, onRetry }: { error: string; onRetry: () => void }) {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<View style={styles.renderError} testID="panel-render-error">
|
||||
<Alert variant="error" title={t("panels.renderError.title")} description={error}>
|
||||
<Button variant="outline" size="sm" onPress={onRetry} testID="panel-render-error-retry">
|
||||
{t("common.actions.retry")}
|
||||
</Button>
|
||||
</Alert>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Mounts one panel with its pane context. A render error stays inside the panel, so every host
|
||||
* (explorer, split pane, compact center, sheet) keeps the rest of the app alive.
|
||||
*/
|
||||
export function WorkspacePaneContent({
|
||||
content,
|
||||
isWorkspaceFocused,
|
||||
@@ -159,10 +190,22 @@ export function WorkspacePaneContent({
|
||||
tabId={paneContextValue.tabId}
|
||||
targetKey={JSON.stringify(paneContextValue.target)}
|
||||
>
|
||||
<Component key={key} />
|
||||
<RenderErrorBoundary
|
||||
resetKeys={[key, paneContextValue.target, paneContextValue.state]}
|
||||
onError={logPanelRenderError}
|
||||
renderError={renderPanelError}
|
||||
>
|
||||
<Component key={key} />
|
||||
</RenderErrorBoundary>
|
||||
</ComposerEditingScope>
|
||||
</PaneFocusProvider>
|
||||
</PaneProvider>
|
||||
</RenderProfile>
|
||||
);
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create((theme) => ({
|
||||
renderError: {
|
||||
padding: theme.spacing[4],
|
||||
},
|
||||
}));
|
||||
|
||||
@@ -45,11 +45,19 @@ function controlsByType(
|
||||
}
|
||||
|
||||
describe("terminal virtual keyboard policy", () => {
|
||||
it("keeps terminal controls on wide native touch screens with either IME state", () => {
|
||||
expect(shouldShowTerminalVirtualKeyBar({ isNative: true, isCompact: false })).toBe(true);
|
||||
expect(shouldShowTerminalVirtualKeyBar({ isNative: true, isCompact: true })).toBe(true);
|
||||
expect(shouldShowTerminalVirtualKeyBar({ isNative: false, isCompact: true })).toBe(true);
|
||||
expect(shouldShowTerminalVirtualKeyBar({ isNative: false, isCompact: false })).toBe(false);
|
||||
it("keeps terminal controls on wide software-keyboard screens and compact windows", () => {
|
||||
expect(shouldShowTerminalVirtualKeyBar({ hasSoftwareKeyboard: true, isCompact: false })).toBe(
|
||||
true,
|
||||
);
|
||||
expect(shouldShowTerminalVirtualKeyBar({ hasSoftwareKeyboard: true, isCompact: true })).toBe(
|
||||
true,
|
||||
);
|
||||
expect(shouldShowTerminalVirtualKeyBar({ hasSoftwareKeyboard: false, isCompact: true })).toBe(
|
||||
true,
|
||||
);
|
||||
expect(shouldShowTerminalVirtualKeyBar({ hasSoftwareKeyboard: false, isCompact: false })).toBe(
|
||||
false,
|
||||
);
|
||||
});
|
||||
|
||||
it("selects the same controls in narrow and wide row arrangements", () => {
|
||||
@@ -116,29 +124,29 @@ describe("terminal virtual keyboard policy", () => {
|
||||
expect(controlIds()).not.toContain("terminal-copy");
|
||||
});
|
||||
|
||||
it("shows Copy only as a native selection affordance", () => {
|
||||
it("shows Copy only as a software-keyboard selection affordance", () => {
|
||||
expect(
|
||||
shouldShowTerminalFloatingCopyAction({
|
||||
hasSelection: false,
|
||||
isNative: true,
|
||||
hasSoftwareKeyboard: true,
|
||||
}),
|
||||
).toBe(false);
|
||||
expect(
|
||||
shouldShowTerminalFloatingCopyAction({
|
||||
hasSelection: true,
|
||||
isNative: false,
|
||||
hasSoftwareKeyboard: false,
|
||||
}),
|
||||
).toBe(false);
|
||||
expect(
|
||||
shouldShowTerminalFloatingCopyAction({
|
||||
hasSelection: true,
|
||||
isNative: true,
|
||||
hasSoftwareKeyboard: true,
|
||||
}),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("keeps Paste native-gated", () => {
|
||||
expect(shouldShowTerminalPasteAction({ isNative: true })).toBe(true);
|
||||
expect(shouldShowTerminalPasteAction({ isNative: false })).toBe(false);
|
||||
it("keeps Paste gated to software-keyboard targets", () => {
|
||||
expect(shouldShowTerminalPasteAction({ hasSoftwareKeyboard: true })).toBe(true);
|
||||
expect(shouldShowTerminalPasteAction({ hasSoftwareKeyboard: false })).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -97,10 +97,10 @@ export function resolveTerminalVirtualKeyboardRows(input: {
|
||||
}
|
||||
|
||||
export function shouldShowTerminalVirtualKeyBar(input: {
|
||||
isNative: boolean;
|
||||
hasSoftwareKeyboard: boolean;
|
||||
isCompact: boolean;
|
||||
}): boolean {
|
||||
return input.isNative || input.isCompact;
|
||||
return input.hasSoftwareKeyboard || input.isCompact;
|
||||
}
|
||||
|
||||
export function getTerminalVirtualKeyboardControlId(
|
||||
@@ -118,13 +118,13 @@ export function getTerminalVirtualKeyboardControlId(
|
||||
}
|
||||
}
|
||||
|
||||
export function shouldShowTerminalPasteAction(input: { isNative: boolean }): boolean {
|
||||
return input.isNative;
|
||||
export function shouldShowTerminalPasteAction(input: { hasSoftwareKeyboard: boolean }): boolean {
|
||||
return input.hasSoftwareKeyboard;
|
||||
}
|
||||
|
||||
export function shouldShowTerminalFloatingCopyAction(input: {
|
||||
hasSelection: boolean;
|
||||
isNative: boolean;
|
||||
hasSoftwareKeyboard: boolean;
|
||||
}): boolean {
|
||||
return input.isNative && input.hasSelection;
|
||||
return input.hasSoftwareKeyboard && input.hasSelection;
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { UnistylesRuntime } from "react-native-unistyles";
|
||||
import { isWeb } from "@/constants/platform";
|
||||
import { allowsInlineWorkspaceRename } from "@/constants/presentation";
|
||||
|
||||
export type WorkspaceRenameSurface = "inline" | "modal";
|
||||
|
||||
@@ -7,11 +7,11 @@ export type WorkspaceRenameSurface = "inline" | "modal";
|
||||
* Read when a rename starts rather than subscribed to: the surface is chosen once per rename, and
|
||||
* a subscription would re-render every sidebar row on each breakpoint change.
|
||||
*
|
||||
* Native wide layouts keep the modal. Their sidebar rows are touch targets with a permanent
|
||||
* Mobile native wide layouts keep the modal. Their sidebar rows are touch targets with a permanent
|
||||
* kebab, and the iPad overlay-dismissal flows drive the modal.
|
||||
*/
|
||||
export function resolveWorkspaceRenameSurface(): WorkspaceRenameSurface {
|
||||
if (!isWeb) return "modal";
|
||||
if (!allowsInlineWorkspaceRename) return "modal";
|
||||
const breakpoint = UnistylesRuntime.breakpoint;
|
||||
return breakpoint === "lg" || breakpoint === "xl" ? "inline" : "modal";
|
||||
}
|
||||
|
||||
@@ -6,7 +6,7 @@ import {
|
||||
validatePort,
|
||||
validateSshHost,
|
||||
} from "@getpaseo/protocol/ssh-transport";
|
||||
import { stripAppImageRuntimeEnv } from "@getpaseo/server/process";
|
||||
import { stripLinuxDesktopRuntimeEnv } from "@getpaseo/server/process";
|
||||
|
||||
export interface SshProxyTarget {
|
||||
host: string;
|
||||
@@ -59,7 +59,7 @@ export function buildSshSpawnEnv(
|
||||
platform: NodeJS.Platform = process.platform,
|
||||
): NodeJS.ProcessEnv {
|
||||
const env = { ...baseEnv };
|
||||
stripAppImageRuntimeEnv(env, { platform });
|
||||
stripLinuxDesktopRuntimeEnv(env, { platform });
|
||||
return env;
|
||||
}
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@ import { existsSync as nodeExistsSync, readdirSync as nodeReaddirSync } from "no
|
||||
import { readFile } from "node:fs/promises";
|
||||
import os from "node:os";
|
||||
import path, { posix, win32 } from "node:path";
|
||||
import { stripAppImageRuntimeEnv } from "@getpaseo/server/process";
|
||||
import { stripLinuxDesktopRuntimeEnv } from "@getpaseo/server/process";
|
||||
import { app, shell } from "electron";
|
||||
|
||||
import type {
|
||||
@@ -53,7 +53,7 @@ function createExternalProcessEnv(
|
||||
for (const key of RUNTIME_CONTROL_ENV_KEYS) {
|
||||
delete env[key];
|
||||
}
|
||||
stripAppImageRuntimeEnv(env, { platform });
|
||||
stripLinuxDesktopRuntimeEnv(env, { platform });
|
||||
for (const [key, value] of Object.entries(env)) {
|
||||
if (value === undefined) {
|
||||
delete env[key];
|
||||
|
||||
@@ -7,7 +7,7 @@ import { spawnSync as defaultSpawnSync } from "node:child_process";
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { userInfo as defaultUserInfo } from "node:os";
|
||||
import { basename } from "node:path";
|
||||
import { stripAppImageRuntimeEnv } from "@getpaseo/server/process";
|
||||
import { stripLinuxDesktopRuntimeEnv } from "@getpaseo/server/process";
|
||||
import defaultLog from "electron-log/main";
|
||||
|
||||
const DEFAULT_RESOLVE_TIMEOUT_MS = 30_000;
|
||||
@@ -410,7 +410,7 @@ function resolveShellEnv({ deps, timeoutMs }: ResolveShellEnvInput): ResolvedShe
|
||||
delete shellEnv.PASEO_NODE_ENV;
|
||||
delete shellEnv.PASEO_DESKTOP_MANAGED;
|
||||
delete shellEnv.PASEO_SUPERVISED;
|
||||
stripAppImageRuntimeEnv(shellEnv, { platform: deps.platform });
|
||||
stripLinuxDesktopRuntimeEnv(shellEnv, { platform: deps.platform });
|
||||
|
||||
deps.logger.info("[login-shell-env] start", {
|
||||
shell,
|
||||
|
||||
@@ -498,6 +498,182 @@ describe("Codex active-turn steering admission", () => {
|
||||
appServer.assertNoErrors();
|
||||
});
|
||||
|
||||
test("returns unavailable when a steered prompt mentions an enabled Codex skill inline", async () => {
|
||||
const appServer = createFakeCodexAppServer({
|
||||
"skills/list": () => ({
|
||||
data: [
|
||||
{
|
||||
cwd: "/workspace/project",
|
||||
skills: [
|
||||
{
|
||||
name: "marker-skill",
|
||||
description: "Marker skill.",
|
||||
path: "/workspace/skills/marker-skill/SKILL.md",
|
||||
},
|
||||
],
|
||||
errors: [],
|
||||
},
|
||||
],
|
||||
}),
|
||||
"turn/steer": () => ({ turn: { id: "native-A" } }),
|
||||
});
|
||||
const { session, paseoTurnId } = await startPublicSteeringSession(appServer);
|
||||
try {
|
||||
await expect(
|
||||
session.steerActiveTurn!("Answer briefly. /marker-skill", {
|
||||
expectedTurnId: paseoTurnId,
|
||||
}),
|
||||
).resolves.toEqual({ status: "unavailable" });
|
||||
expect(appServer.requests().filter((request) => request.method === "turn/steer")).toEqual([]);
|
||||
appServer.assertNoErrors();
|
||||
} finally {
|
||||
await session.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("returns unavailable when a steered prompt with attachments mentions an enabled Codex skill", async () => {
|
||||
const appServer = createFakeCodexAppServer({
|
||||
"skills/list": () => ({
|
||||
data: [
|
||||
{
|
||||
cwd: "/workspace/project",
|
||||
skills: [
|
||||
{
|
||||
name: "marker-skill",
|
||||
description: "Marker skill.",
|
||||
path: "/workspace/skills/marker-skill/SKILL.md",
|
||||
},
|
||||
],
|
||||
errors: [],
|
||||
},
|
||||
],
|
||||
}),
|
||||
"turn/steer": () => ({ turn: { id: "native-A" } }),
|
||||
});
|
||||
const { session, paseoTurnId } = await startPublicSteeringSession(appServer);
|
||||
try {
|
||||
await expect(
|
||||
session.steerActiveTurn!(
|
||||
[
|
||||
{
|
||||
type: "text",
|
||||
mimeType: "text/plain",
|
||||
contextKind: "chat_history",
|
||||
text: "Earlier turn context",
|
||||
},
|
||||
{ type: "text", text: "Check this with /marker-skill." },
|
||||
],
|
||||
{ expectedTurnId: paseoTurnId },
|
||||
),
|
||||
).resolves.toEqual({ status: "unavailable" });
|
||||
expect(appServer.requests().filter((request) => request.method === "turn/steer")).toEqual([]);
|
||||
appServer.assertNoErrors();
|
||||
} finally {
|
||||
await session.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("steers normally without listing skills when the prompt only contains a file path", async () => {
|
||||
const appServer = createFakeCodexAppServer({
|
||||
"skills/list": () => ({
|
||||
data: [
|
||||
{
|
||||
cwd: "/workspace/project",
|
||||
skills: [
|
||||
{
|
||||
name: "docs",
|
||||
description: "Docs skill.",
|
||||
path: "/workspace/skills/docs/SKILL.md",
|
||||
},
|
||||
],
|
||||
errors: [],
|
||||
},
|
||||
],
|
||||
}),
|
||||
"turn/steer": () => ({ turn: { id: "native-A" } }),
|
||||
});
|
||||
const { session, paseoTurnId } = await startPublicSteeringSession(appServer);
|
||||
const skillListsBeforeSteer = appServer
|
||||
.requests()
|
||||
.filter((request) => request.method === "skills/list").length;
|
||||
try {
|
||||
await expect(
|
||||
session.steerActiveTurn!("Check /docs/api.md next", {
|
||||
expectedTurnId: paseoTurnId,
|
||||
}),
|
||||
).resolves.toEqual({ status: "accepted" });
|
||||
expect(
|
||||
appServer.requests().filter((request) => request.method === "skills/list").length,
|
||||
).toBe(skillListsBeforeSteer);
|
||||
expect(appServer.requests().find((request) => request.method === "turn/steer")).toMatchObject(
|
||||
{
|
||||
params: {
|
||||
input: [{ type: "text", text: "Check /docs/api.md next", text_elements: [] }],
|
||||
},
|
||||
},
|
||||
);
|
||||
appServer.assertNoErrors();
|
||||
} finally {
|
||||
await session.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("does not steer B when A completes while skill lookup is pending", async () => {
|
||||
const skillLookup = deferred<{ data: [] }>();
|
||||
const skillLookupEntered = deferred<void>();
|
||||
let holdSkillLookup = false;
|
||||
const appServer = createFakeCodexAppServer({
|
||||
"skills/list": () => {
|
||||
if (!holdSkillLookup) {
|
||||
return { data: [] };
|
||||
}
|
||||
skillLookupEntered.resolve();
|
||||
return skillLookup.promise;
|
||||
},
|
||||
"turn/steer": () => ({ turn: { id: "native-B" } }),
|
||||
});
|
||||
const { session, paseoTurnId } = await startPublicSteeringSession(appServer);
|
||||
holdSkillLookup = true;
|
||||
try {
|
||||
const steer = session.steerActiveTurn!("Check /unknown-token", {
|
||||
expectedTurnId: paseoTurnId,
|
||||
clientMessageId: "steer-skill-race",
|
||||
});
|
||||
await skillLookupEntered.promise;
|
||||
appServer.completeTurn({ threadId: "thread-1" });
|
||||
await new Promise<void>((resolve) => setImmediate(resolve));
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
const startedB = await session.startTurn("second");
|
||||
appServer.startsTurn({ threadId: "thread-1", turnId: "native-B" });
|
||||
await new Promise<void>((resolve) => setImmediate(resolve));
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
skillLookup.resolve({ data: [] });
|
||||
|
||||
await expect(steer).resolves.toEqual({ status: "unavailable" });
|
||||
expect(startedB.turnId).not.toBe(paseoTurnId);
|
||||
expect(appServer.requests().filter((request) => request.method === "turn/steer")).toEqual([]);
|
||||
appServer.assertNoErrors();
|
||||
} finally {
|
||||
await session.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("returns unavailable when steering a built-in /compact command", async () => {
|
||||
const appServer = createFakeCodexAppServer({
|
||||
"turn/steer": () => ({ turn: { id: "native-A" } }),
|
||||
});
|
||||
const { session, paseoTurnId } = await startPublicSteeringSession(appServer);
|
||||
try {
|
||||
await expect(
|
||||
session.steerActiveTurn!("/compact", { expectedTurnId: paseoTurnId }),
|
||||
).resolves.toEqual({ status: "unavailable" });
|
||||
expect(appServer.requests().filter((request) => request.method === "turn/steer")).toEqual([]);
|
||||
appServer.assertNoErrors();
|
||||
} finally {
|
||||
await session.close();
|
||||
}
|
||||
});
|
||||
|
||||
test.each([
|
||||
["method unavailable", -32601, "method not found", undefined, "unavailable"],
|
||||
["no active turn", -32600, "no active turn to steer", undefined, "unavailable"],
|
||||
@@ -4114,6 +4290,326 @@ describe("Codex app-server provider", () => {
|
||||
);
|
||||
});
|
||||
|
||||
test("resolves inline, repeated, and punctuated Codex skill mentions into app-server skill input", async () => {
|
||||
const appServer = createFakeCodexAppServer({
|
||||
"skills/list": () => ({
|
||||
data: [
|
||||
{
|
||||
cwd: "/workspace/project",
|
||||
skills: [
|
||||
{
|
||||
name: "marker-skill",
|
||||
description: "Marker skill.",
|
||||
path: "/workspace/skills/marker-skill/SKILL.md",
|
||||
},
|
||||
{
|
||||
name: "second-skill",
|
||||
description: "Second skill.",
|
||||
path: "/workspace/skills/second-skill/SKILL.md",
|
||||
},
|
||||
],
|
||||
errors: [],
|
||||
},
|
||||
],
|
||||
}),
|
||||
});
|
||||
const session = new CodexAppServerAgentSession(
|
||||
createConfig({ cwd: "/workspace/project" }),
|
||||
null,
|
||||
createTestLogger(),
|
||||
async () => appServer.child,
|
||||
);
|
||||
try {
|
||||
await session.startTurn(
|
||||
"Answer briefly using /marker-skill, then /second-skill. Re-check /marker-skill!",
|
||||
);
|
||||
|
||||
const turnStart = appServer.requests().find((request) => request.method === "turn/start");
|
||||
expect(turnStart?.params).toEqual(
|
||||
expect.objectContaining({
|
||||
input: [
|
||||
{
|
||||
type: "skill",
|
||||
name: "marker-skill",
|
||||
path: "/workspace/skills/marker-skill/SKILL.md",
|
||||
},
|
||||
{
|
||||
type: "skill",
|
||||
name: "second-skill",
|
||||
path: "/workspace/skills/second-skill/SKILL.md",
|
||||
},
|
||||
{
|
||||
type: "text",
|
||||
text: "Answer briefly using $marker-skill, then $second-skill. Re-check $marker-skill!",
|
||||
text_elements: [],
|
||||
},
|
||||
],
|
||||
}),
|
||||
);
|
||||
appServer.assertNoErrors();
|
||||
} finally {
|
||||
await session.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("resolves Codex skill mentions in prompts carrying attachments without touching chat_history or attachment text", async () => {
|
||||
const appServer = createFakeCodexAppServer({
|
||||
"skills/list": () => ({
|
||||
data: [
|
||||
{
|
||||
cwd: "/workspace/project",
|
||||
skills: [
|
||||
{
|
||||
name: "marker-skill",
|
||||
description: "Marker skill.",
|
||||
path: "/workspace/skills/marker-skill/SKILL.md",
|
||||
},
|
||||
{
|
||||
name: "history-skill",
|
||||
description: "History skill.",
|
||||
path: "/workspace/skills/history-skill/SKILL.md",
|
||||
},
|
||||
],
|
||||
errors: [],
|
||||
},
|
||||
],
|
||||
}),
|
||||
});
|
||||
const session = new CodexAppServerAgentSession(
|
||||
createConfig({ cwd: "/workspace/project" }),
|
||||
null,
|
||||
createTestLogger(),
|
||||
async () => appServer.child,
|
||||
);
|
||||
try {
|
||||
await session.startTurn([
|
||||
{
|
||||
type: "text",
|
||||
mimeType: "text/plain",
|
||||
contextKind: "chat_history",
|
||||
text: "Previous conversation mentioned /history-skill",
|
||||
},
|
||||
{
|
||||
type: "text",
|
||||
text: "/marker-skill inspect this screenshot",
|
||||
},
|
||||
{
|
||||
type: "image",
|
||||
mimeType: "image/png",
|
||||
data: ONE_BY_ONE_PNG_BASE64,
|
||||
},
|
||||
{
|
||||
type: "text",
|
||||
mimeType: "text/plain",
|
||||
title: "Snippet",
|
||||
text: "Attached note mentioning /history-skill",
|
||||
},
|
||||
]);
|
||||
|
||||
const turnStart = appServer.requests().find((request) => request.method === "turn/start");
|
||||
const input = (turnStart?.params as { input?: Array<Record<string, unknown>> })?.input ?? [];
|
||||
const localImage = input.find((item) => item.type === "localImage");
|
||||
try {
|
||||
expect(input).toEqual([
|
||||
{
|
||||
type: "skill",
|
||||
name: "marker-skill",
|
||||
path: "/workspace/skills/marker-skill/SKILL.md",
|
||||
},
|
||||
{
|
||||
type: "text",
|
||||
text: "Previous conversation mentioned /history-skill",
|
||||
text_elements: [],
|
||||
},
|
||||
{
|
||||
type: "text",
|
||||
text: "$marker-skill inspect this screenshot",
|
||||
text_elements: [],
|
||||
},
|
||||
{
|
||||
type: "localImage",
|
||||
path: expect.any(String),
|
||||
},
|
||||
{
|
||||
type: "text",
|
||||
text: "Attached note mentioning /history-skill",
|
||||
text_elements: [],
|
||||
},
|
||||
]);
|
||||
appServer.assertNoErrors();
|
||||
} finally {
|
||||
if (typeof localImage?.path === "string") {
|
||||
rmSync(localImage.path, { force: true });
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
await session.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("leaves file paths like /docs/api.md untouched and skips skills/list when no mention candidate exists", async () => {
|
||||
const appServer = createFakeCodexAppServer({
|
||||
"skills/list": () => ({
|
||||
data: [
|
||||
{
|
||||
cwd: "/workspace/project",
|
||||
skills: [
|
||||
{
|
||||
name: "docs",
|
||||
description: "Docs skill.",
|
||||
path: "/workspace/skills/docs/SKILL.md",
|
||||
},
|
||||
],
|
||||
errors: [],
|
||||
},
|
||||
],
|
||||
}),
|
||||
});
|
||||
const session = new CodexAppServerAgentSession(
|
||||
createConfig({ cwd: "/workspace/project" }),
|
||||
null,
|
||||
createTestLogger(),
|
||||
async () => appServer.child,
|
||||
);
|
||||
try {
|
||||
await session.connect();
|
||||
const skillListsBeforeTurn = appServer
|
||||
.requests()
|
||||
.filter((request) => request.method === "skills/list").length;
|
||||
|
||||
await session.startTurn("Check /docs/api.md before replying.");
|
||||
|
||||
expect(
|
||||
appServer.requests().filter((request) => request.method === "skills/list").length,
|
||||
).toBe(skillListsBeforeTurn);
|
||||
const turnStart = appServer.requests().find((request) => request.method === "turn/start");
|
||||
expect(turnStart?.params).toEqual(
|
||||
expect.objectContaining({
|
||||
input: [
|
||||
{
|
||||
type: "text",
|
||||
text: "Check /docs/api.md before replying.",
|
||||
text_elements: [],
|
||||
},
|
||||
],
|
||||
}),
|
||||
);
|
||||
appServer.assertNoErrors();
|
||||
} finally {
|
||||
await session.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("does not resolve disabled Codex skills mentioned inline", async () => {
|
||||
const appServer = createFakeCodexAppServer({
|
||||
"skills/list": () => ({
|
||||
data: [
|
||||
{
|
||||
cwd: "/workspace/project",
|
||||
skills: [
|
||||
{
|
||||
name: "disabled-skill",
|
||||
description: "Disabled skill.",
|
||||
path: "/workspace/skills/disabled-skill/SKILL.md",
|
||||
enabled: false,
|
||||
},
|
||||
],
|
||||
errors: [],
|
||||
},
|
||||
],
|
||||
}),
|
||||
});
|
||||
const session = new CodexAppServerAgentSession(
|
||||
createConfig({ cwd: "/workspace/project" }),
|
||||
null,
|
||||
createTestLogger(),
|
||||
async () => appServer.child,
|
||||
);
|
||||
try {
|
||||
await session.startTurn("Use /disabled-skill please.");
|
||||
|
||||
const turnStart = appServer.requests().find((request) => request.method === "turn/start");
|
||||
expect(turnStart?.params).toEqual(
|
||||
expect.objectContaining({
|
||||
input: [
|
||||
{
|
||||
type: "text",
|
||||
text: "Use /disabled-skill please.",
|
||||
text_elements: [],
|
||||
},
|
||||
],
|
||||
}),
|
||||
);
|
||||
appServer.assertNoErrors();
|
||||
} finally {
|
||||
await session.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("resolves Codex skill mentions in /prompts:* arguments while keeping saved template text literal", async () => {
|
||||
const codexHome = await mkdtemp(path.join(tmpdir(), "codex-custom-prompt-skill-"));
|
||||
mkdirSync(path.join(codexHome, "prompts"), { recursive: true });
|
||||
writeFileSync(
|
||||
path.join(codexHome, "prompts", "review.md"),
|
||||
"---\ndescription: Review with args\n---\n\nKeep /docs literal and review: $ARGUMENTS\n",
|
||||
"utf8",
|
||||
);
|
||||
const appServer = createFakeCodexAppServer({
|
||||
"skills/list": () => ({
|
||||
data: [
|
||||
{
|
||||
cwd: "/workspace/project",
|
||||
skills: [
|
||||
{
|
||||
name: "marker-skill",
|
||||
description: "Marker skill.",
|
||||
path: "/workspace/skills/marker-skill/SKILL.md",
|
||||
},
|
||||
{
|
||||
name: "docs",
|
||||
description: "Docs skill.",
|
||||
path: "/workspace/skills/docs/SKILL.md",
|
||||
},
|
||||
],
|
||||
errors: [],
|
||||
},
|
||||
],
|
||||
}),
|
||||
});
|
||||
const session = new CodexAppServerAgentSession(
|
||||
createConfig({ cwd: "/workspace/project" }),
|
||||
null,
|
||||
createTestLogger(),
|
||||
async () => appServer.child,
|
||||
{ codexHome },
|
||||
);
|
||||
try {
|
||||
await session.startTurn("/prompts:review Use /marker-skill.");
|
||||
|
||||
const turnStart = appServer.requests().find((request) => request.method === "turn/start");
|
||||
expect(turnStart?.params).toEqual(
|
||||
expect.objectContaining({
|
||||
input: [
|
||||
{
|
||||
type: "skill",
|
||||
name: "marker-skill",
|
||||
path: "/workspace/skills/marker-skill/SKILL.md",
|
||||
},
|
||||
{
|
||||
type: "text",
|
||||
text: expect.stringContaining("Keep /docs literal and review: Use $marker-skill."),
|
||||
text_elements: [],
|
||||
},
|
||||
],
|
||||
}),
|
||||
);
|
||||
appServer.assertNoErrors();
|
||||
} finally {
|
||||
await session.close();
|
||||
rmSync(codexHome, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("lists project skill commands when app-server receives the project cwd in cwds", async () => {
|
||||
const commands = await listCommandsFromFakeCodex([
|
||||
{
|
||||
|
||||
@@ -2,6 +2,13 @@ import type { ProviderOptions } from "@getpaseo/protocol/agent-types";
|
||||
import { applyProviderOptionsPatch } from "../option-controls.js";
|
||||
import { assertChangesAreLive, validateProviderOptions } from "../provider-options.js";
|
||||
import { CodexBackgroundInventory } from "./codex/background-inventory.js";
|
||||
import {
|
||||
type CodexPromptInput,
|
||||
type CodexSkillPromptBlock,
|
||||
hasCodexSkillMentionCandidate,
|
||||
resolveCodexSkillMentions,
|
||||
type ResolvedCodexSkillMentions,
|
||||
} from "./codex/skill-mentions.js";
|
||||
import {
|
||||
AgentTurnStartCanceledError,
|
||||
getAgentStreamEventTurnId,
|
||||
@@ -21,7 +28,6 @@ import {
|
||||
type AgentPermissionResponse,
|
||||
type AgentPermissionResult,
|
||||
type AgentProviderNotice,
|
||||
type AgentPromptContentBlock,
|
||||
type AgentPromptInput,
|
||||
type AgentRunOptions,
|
||||
type AgentRunResult,
|
||||
@@ -3590,12 +3596,6 @@ async function readCodexConfiguredDefaults(
|
||||
return mergeCodexConfiguredDefaults(savedConfigDefaults, configReadDefaults);
|
||||
}
|
||||
|
||||
interface CodexSkillPromptBlock {
|
||||
type: "skill";
|
||||
name: string;
|
||||
path: string;
|
||||
}
|
||||
|
||||
function enabledCodexSkills(
|
||||
entries: unknown[],
|
||||
): Array<{ name: string; description: string; path: string }> {
|
||||
@@ -3620,8 +3620,6 @@ function enabledCodexSkills(
|
||||
return Array.from(skillsByName.values());
|
||||
}
|
||||
|
||||
type CodexPromptContentBlock = AgentPromptContentBlock | CodexSkillPromptBlock;
|
||||
type CodexPromptInput = string | CodexPromptContentBlock[];
|
||||
interface CodexTextElement {
|
||||
byteRange: {
|
||||
start: number;
|
||||
@@ -3952,6 +3950,7 @@ export class CodexAppServerAgentSession implements AgentSession {
|
||||
name: string;
|
||||
} | null = null;
|
||||
private cachedSkills: Array<{ name: string; description: string; path: string }> | null = null;
|
||||
private pendingLiteralFollowUpPrompt: string | null = null;
|
||||
|
||||
private readonly usageSessionKey = randomUUID();
|
||||
private readonly harnessEnvironment: Record<string, string>;
|
||||
@@ -4714,12 +4713,12 @@ export class CodexAppServerAgentSession implements AgentSession {
|
||||
return null;
|
||||
}
|
||||
const parsed = this.parseSlashCommandInput(prompt);
|
||||
if (!parsed) {
|
||||
if (!parsed || !parsed.commandName.startsWith("prompts:")) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
const commands = await this.listCommands();
|
||||
return commands.some((command) => command.name === parsed.commandName) ? parsed : null;
|
||||
const prompts = await listCodexCustomPrompts(this.codexHome);
|
||||
return prompts.some((command) => command.name === parsed.commandName) ? parsed : null;
|
||||
} catch (error) {
|
||||
this.logger.warn(
|
||||
{ err: error, commandName: parsed.commandName },
|
||||
@@ -4733,31 +4732,30 @@ export class CodexAppServerAgentSession implements AgentSession {
|
||||
commandName: string,
|
||||
args?: string,
|
||||
): Promise<CodexPromptInput> {
|
||||
if (commandName.startsWith("prompts:")) {
|
||||
const promptName = commandName.slice("prompts:".length);
|
||||
const promptPath = path.join(this.codexHome, "prompts", `${promptName}.md`);
|
||||
const raw = await fs.readFile(promptPath, "utf8");
|
||||
const parsed = parseFrontMatter(raw);
|
||||
return expandCodexCustomPrompt(parsed.body, args);
|
||||
const promptName = commandName.slice("prompts:".length);
|
||||
const promptPath = path.join(this.codexHome, "prompts", `${promptName}.md`);
|
||||
const raw = await fs.readFile(promptPath, "utf8");
|
||||
const parsed = parseFrontMatter(raw);
|
||||
const resolvedArgs = args ? await this.resolveMentionedSkills(args) : null;
|
||||
const expandedArgs =
|
||||
resolvedArgs && resolvedArgs.skills.length > 0 && Array.isArray(resolvedArgs.prompt)
|
||||
? (resolvedArgs.prompt.find((block) => block.type === "text")?.text ?? args)
|
||||
: args;
|
||||
const expandedBody = expandCodexCustomPrompt(parsed.body, expandedArgs);
|
||||
if (!resolvedArgs || resolvedArgs.skills.length === 0) {
|
||||
return expandedBody;
|
||||
}
|
||||
return [...resolvedArgs.skills, { type: "text", text: expandedBody }];
|
||||
}
|
||||
|
||||
if (this.connectionState === "disconnected") {
|
||||
await this.connect();
|
||||
} else {
|
||||
await this.loadSkills();
|
||||
private async resolveMentionedSkills(
|
||||
prompt: AgentPromptInput,
|
||||
): Promise<ResolvedCodexSkillMentions> {
|
||||
if (!hasCodexSkillMentionCandidate(prompt)) {
|
||||
return { skills: [], prompt };
|
||||
}
|
||||
const skill = this.cachedSkills?.find((entry) => entry.name === commandName);
|
||||
if (skill) {
|
||||
const trimmedArgs = args?.trim() ?? "";
|
||||
const text = trimmedArgs ? `$${skill.name} ${trimmedArgs}` : `$${skill.name}`;
|
||||
const input: CodexPromptContentBlock[] = [
|
||||
{ type: "skill", name: skill.name, path: skill.path },
|
||||
{ type: "text", text },
|
||||
];
|
||||
return input;
|
||||
}
|
||||
|
||||
return args ? `$${commandName} ${args}` : `$${commandName}`;
|
||||
await this.loadSkills();
|
||||
return resolveCodexSkillMentions(prompt, this.cachedSkills ?? []);
|
||||
}
|
||||
|
||||
private async buildTurnStartParams(
|
||||
@@ -4953,10 +4951,19 @@ export class CodexAppServerAgentSession implements AgentSession {
|
||||
throw new Error("Codex client not initialized");
|
||||
}
|
||||
|
||||
const slashCommand = await this.resolveSlashCommandInvocation(prompt);
|
||||
const effectivePrompt = slashCommand
|
||||
? await this.buildCommandPromptInput(slashCommand.commandName, slashCommand.args)
|
||||
: prompt;
|
||||
const isLiteralFollowUp =
|
||||
typeof prompt === "string" &&
|
||||
this.pendingLiteralFollowUpPrompt !== null &&
|
||||
prompt === this.pendingLiteralFollowUpPrompt;
|
||||
this.pendingLiteralFollowUpPrompt = null;
|
||||
|
||||
let effectivePrompt: CodexPromptInput = prompt;
|
||||
if (!isLiteralFollowUp) {
|
||||
const slashCommand = await this.resolveSlashCommandInvocation(prompt);
|
||||
effectivePrompt = slashCommand
|
||||
? await this.buildCommandPromptInput(slashCommand.commandName, slashCommand.args)
|
||||
: (await this.resolveMentionedSkills(prompt)).prompt;
|
||||
}
|
||||
|
||||
if (this.currentThreadId) {
|
||||
await this.ensureThreadLoaded();
|
||||
@@ -5012,16 +5019,44 @@ export class CodexAppServerAgentSession implements AgentSession {
|
||||
}
|
||||
}
|
||||
|
||||
async steerActiveTurn(
|
||||
private async canSteerPrompt(
|
||||
prompt: AgentPromptInput,
|
||||
options: SteerActiveTurnOptions,
|
||||
): Promise<SteerResult> {
|
||||
admission: {
|
||||
client: CodexAppServerClientLike;
|
||||
threadId: string;
|
||||
nativeTurnId: string;
|
||||
foregroundTurnId: string;
|
||||
},
|
||||
): Promise<boolean> {
|
||||
if (this.tryHandleOutOfBand(prompt)) {
|
||||
return false;
|
||||
}
|
||||
if (await this.resolveSlashCommandInvocation(prompt)) {
|
||||
return false;
|
||||
}
|
||||
if (!this.matchesSteerAdmission(admission)) {
|
||||
return false;
|
||||
}
|
||||
// Codex app-server only resolves skills at turn start (turn/steer ignores skill items and
|
||||
// $skill mentions), so fall back to turn replacement whenever a steered prompt mentions a skill.
|
||||
if ((await this.resolveMentionedSkills(prompt)).skills.length > 0) {
|
||||
return false;
|
||||
}
|
||||
return this.matchesSteerAdmission(admission);
|
||||
}
|
||||
|
||||
private async resolveSteerAdmission(expectedTurnId: string): Promise<{
|
||||
client: CodexAppServerClientLike;
|
||||
threadId: string;
|
||||
nativeTurnId: string;
|
||||
foregroundTurnId: string;
|
||||
} | null> {
|
||||
const client = this.client;
|
||||
const threadId = this.currentThreadId;
|
||||
let nativeTurnId = this.currentTurnId;
|
||||
const foregroundTurnId = this.activeForegroundTurnId;
|
||||
if (!client || !threadId || foregroundTurnId !== options.expectedTurnId) {
|
||||
return { status: "unavailable" };
|
||||
if (!client || !threadId || foregroundTurnId !== expectedTurnId) {
|
||||
return null;
|
||||
}
|
||||
const pendingIdentification = this.pendingForegroundTurnIdentification;
|
||||
// The start acknowledgement precedes the notification that identifies the native
|
||||
@@ -5029,23 +5064,29 @@ export class CodexAppServerAgentSession implements AgentSession {
|
||||
if (!nativeTurnId && pendingIdentification?.foregroundTurnId === foregroundTurnId) {
|
||||
nativeTurnId = await pendingIdentification.promise;
|
||||
}
|
||||
if (!nativeTurnId) {
|
||||
return { status: "unavailable" };
|
||||
}
|
||||
if (await this.resolveSlashCommandInvocation(prompt)) return { status: "unavailable" };
|
||||
if (!this.matchesSteerAdmission({ client, threadId, nativeTurnId, foregroundTurnId })) {
|
||||
return { status: "unavailable" };
|
||||
}
|
||||
return nativeTurnId ? { client, threadId, nativeTurnId, foregroundTurnId } : null;
|
||||
}
|
||||
|
||||
private async submitTurnSteer(
|
||||
prompt: AgentPromptInput,
|
||||
options: SteerActiveTurnOptions,
|
||||
admission: {
|
||||
client: CodexAppServerClientLike;
|
||||
threadId: string;
|
||||
nativeTurnId: string;
|
||||
foregroundTurnId: string;
|
||||
},
|
||||
): Promise<SteerResult> {
|
||||
const input = await this.buildUserInput(prompt);
|
||||
if (!this.matchesSteerAdmission({ client, threadId, nativeTurnId, foregroundTurnId })) {
|
||||
if (!this.matchesSteerAdmission(admission)) {
|
||||
return { status: "unavailable" };
|
||||
}
|
||||
try {
|
||||
const response = await client.request(
|
||||
const response = await admission.client.request(
|
||||
"turn/steer",
|
||||
{
|
||||
threadId,
|
||||
expectedTurnId: nativeTurnId,
|
||||
threadId: admission.threadId,
|
||||
expectedTurnId: admission.nativeTurnId,
|
||||
input,
|
||||
...(options.clientMessageId ? { clientUserMessageId: options.clientMessageId } : {}),
|
||||
},
|
||||
@@ -5054,7 +5095,7 @@ export class CodexAppServerAgentSession implements AgentSession {
|
||||
const record = toObjectRecord(response);
|
||||
const turn = record ? toObjectRecord(record.turn) : null;
|
||||
const acknowledgedTurnId = nonEmptyString(record?.turnId) ?? nonEmptyString(turn?.id);
|
||||
if (acknowledgedTurnId !== nativeTurnId) {
|
||||
if (acknowledgedTurnId !== admission.nativeTurnId) {
|
||||
throw new Error("Codex returned an invalid steer acknowledgement");
|
||||
}
|
||||
if (options.clearPendingPermissions) {
|
||||
@@ -5067,6 +5108,17 @@ export class CodexAppServerAgentSession implements AgentSession {
|
||||
}
|
||||
}
|
||||
|
||||
async steerActiveTurn(
|
||||
prompt: AgentPromptInput,
|
||||
options: SteerActiveTurnOptions,
|
||||
): Promise<SteerResult> {
|
||||
const admission = await this.resolveSteerAdmission(options.expectedTurnId);
|
||||
if (!admission || !(await this.canSteerPrompt(prompt, admission))) {
|
||||
return { status: "unavailable" };
|
||||
}
|
||||
return this.submitTurnSteer(prompt, options, admission);
|
||||
}
|
||||
|
||||
private matchesSteerAdmission(admission: {
|
||||
client: CodexAppServerClientLike;
|
||||
threadId: string;
|
||||
@@ -5408,10 +5460,16 @@ export class CodexAppServerAgentSession implements AgentSession {
|
||||
let followUpPrompt = prepared.prompt;
|
||||
const expectedTurnId = this.activeForegroundTurnId;
|
||||
if (prepared.prompt && expectedTurnId) {
|
||||
const result = await this.steerActiveTurn(prepared.prompt, {
|
||||
expectedTurnId,
|
||||
clientMessageId: randomUUID(),
|
||||
});
|
||||
// Async question answers are structured replies to the active turn, not composer slash
|
||||
// prompts, so steer them directly without composer command/skill interception.
|
||||
const admission = await this.resolveSteerAdmission(expectedTurnId);
|
||||
const result = admission
|
||||
? await this.submitTurnSteer(
|
||||
prepared.prompt,
|
||||
{ expectedTurnId, clientMessageId: randomUUID() },
|
||||
admission,
|
||||
)
|
||||
: { status: "unavailable" as const };
|
||||
if (result.status !== "accepted") {
|
||||
throw new Error("The active Codex turn changed. Retry sending your answer.");
|
||||
}
|
||||
@@ -5424,7 +5482,11 @@ export class CodexAppServerAgentSession implements AgentSession {
|
||||
requestId,
|
||||
resolution: response,
|
||||
});
|
||||
return followUpPrompt ? { followUpPrompt } : undefined;
|
||||
if (followUpPrompt) {
|
||||
this.pendingLiteralFollowUpPrompt = followUpPrompt;
|
||||
return { followUpPrompt };
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
private handlePlanPermissionResponse(params: {
|
||||
@@ -5443,6 +5505,7 @@ export class CodexAppServerAgentSession implements AgentSession {
|
||||
|
||||
this.resolvePlanPermission(requestId, response);
|
||||
if (followUpPrompt) {
|
||||
this.pendingLiteralFollowUpPrompt = followUpPrompt;
|
||||
return { followUpPrompt };
|
||||
}
|
||||
}
|
||||
|
||||
@@ -460,3 +460,137 @@ test("restores unanswered questions and does not reopen answered questions on du
|
||||
await resumed.session.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("steers an async answer containing an enabled Codex skill token without failing", async () => {
|
||||
const appServer = createFakeCodexAppServer({
|
||||
"skills/list": () => ({
|
||||
data: [
|
||||
{
|
||||
cwd: tmpdir(),
|
||||
skills: [
|
||||
{
|
||||
name: "marker-skill",
|
||||
description: "Marker skill.",
|
||||
path: "/workspace/skills/marker-skill/SKILL.md",
|
||||
},
|
||||
],
|
||||
errors: [],
|
||||
},
|
||||
],
|
||||
}),
|
||||
"turn/steer": () => ({ turnId: "native-turn" }),
|
||||
});
|
||||
const session = new CodexAppServerAgentSession(
|
||||
{ provider: "codex", cwd: tmpdir(), model: "gpt-5.4", modeId: "full-access" },
|
||||
null,
|
||||
createTestLogger(),
|
||||
async () => appServer.child,
|
||||
);
|
||||
try {
|
||||
await session.startTurn("Ask me a question.");
|
||||
const started = waitForNextEvent(session, "turn_started");
|
||||
appServer.startsTurn({ threadId: "thread-1", turnId: "native-turn" });
|
||||
await started;
|
||||
const shown = waitForTimelineToolCall(session, questionItem.id);
|
||||
appServer.child.stdout.write(
|
||||
JSON.stringify({
|
||||
method: "item/completed",
|
||||
params: { threadId: "thread-1", turnId: "native-turn", item: questionItem },
|
||||
}) + "\n",
|
||||
);
|
||||
await shown;
|
||||
const [permission] = session.getPendingPermissions();
|
||||
expect(permission).toBeDefined();
|
||||
|
||||
await session.respondToPermission(permission!.id, {
|
||||
behavior: "allow",
|
||||
updatedInput: { answers: { "0": "Use /marker-skill" } },
|
||||
});
|
||||
|
||||
expect(session.getPendingPermissions()).toEqual([]);
|
||||
expect(appServer.requests().filter((request) => request.method === "turn/steer")).toMatchObject(
|
||||
[
|
||||
{
|
||||
params: {
|
||||
expectedTurnId: "native-turn",
|
||||
input: [{ type: "text", text: expect.stringContaining("Use /marker-skill") }],
|
||||
},
|
||||
},
|
||||
],
|
||||
);
|
||||
appServer.assertNoErrors();
|
||||
} finally {
|
||||
await session.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("keeps a late async answer containing an enabled Codex skill token literal on the follow-up turn", async () => {
|
||||
const appServer = createFakeCodexAppServer({
|
||||
"skills/list": () => ({
|
||||
data: [
|
||||
{
|
||||
cwd: tmpdir(),
|
||||
skills: [
|
||||
{
|
||||
name: "marker-skill",
|
||||
description: "Marker skill.",
|
||||
path: "/workspace/skills/marker-skill/SKILL.md",
|
||||
},
|
||||
],
|
||||
errors: [],
|
||||
},
|
||||
],
|
||||
}),
|
||||
});
|
||||
const session = new CodexAppServerAgentSession(
|
||||
{ provider: "codex", cwd: tmpdir(), model: "gpt-5.4", modeId: "full-access" },
|
||||
null,
|
||||
createTestLogger(),
|
||||
async () => appServer.child,
|
||||
);
|
||||
try {
|
||||
await session.startTurn("Ask me a question.");
|
||||
const started = waitForNextEvent(session, "turn_started");
|
||||
appServer.startsTurn({ threadId: "thread-1", turnId: "native-turn" });
|
||||
await started;
|
||||
const shown = waitForTimelineToolCall(session, questionItem.id);
|
||||
appServer.child.stdout.write(
|
||||
JSON.stringify({
|
||||
method: "item/completed",
|
||||
params: { threadId: "thread-1", turnId: "native-turn", item: questionItem },
|
||||
}) + "\n",
|
||||
);
|
||||
await shown;
|
||||
const completed = waitForNextEvent(session, "turn_completed");
|
||||
appServer.completeTurn({ threadId: "thread-1" });
|
||||
await completed;
|
||||
|
||||
const [permission] = session.getPendingPermissions();
|
||||
expect(permission).toBeDefined();
|
||||
const result = await session.respondToPermission(permission!.id, {
|
||||
behavior: "allow",
|
||||
updatedInput: { answers: { "0": "Show /marker-skill in the example." } },
|
||||
});
|
||||
expect(result?.followUpPrompt).toBe(
|
||||
"Answers to your questions:\n\nWhich color?\nShow /marker-skill in the example.",
|
||||
);
|
||||
|
||||
await session.startTurn(result!.followUpPrompt!);
|
||||
|
||||
const turnStarts = appServer.requests().filter((request) => request.method === "turn/start");
|
||||
expect(turnStarts[turnStarts.length - 1]?.params).toEqual(
|
||||
expect.objectContaining({
|
||||
input: [
|
||||
{
|
||||
type: "text",
|
||||
text: "Answers to your questions:\n\nWhich color?\nShow /marker-skill in the example.",
|
||||
text_elements: [],
|
||||
},
|
||||
],
|
||||
}),
|
||||
);
|
||||
appServer.assertNoErrors();
|
||||
} finally {
|
||||
await session.close();
|
||||
}
|
||||
});
|
||||
|
||||
@@ -0,0 +1,169 @@
|
||||
import { describe, expect, test } from "vitest";
|
||||
import type { AgentPromptContentBlock } from "../../agent-sdk-types.js";
|
||||
import {
|
||||
type CodexSkillDescriptor,
|
||||
hasCodexSkillMentionCandidate,
|
||||
resolveCodexSkillMentions,
|
||||
} from "./skill-mentions.js";
|
||||
|
||||
const SKILLS: CodexSkillDescriptor[] = [
|
||||
{ name: "marker-skill", path: "/workspace/.agents/skills/marker-skill/SKILL.md" },
|
||||
{ name: "second-skill", path: "/workspace/.agents/skills/second-skill/SKILL.md" },
|
||||
{ name: "docs", path: "/workspace/.agents/skills/docs/SKILL.md" },
|
||||
];
|
||||
|
||||
describe("hasCodexSkillMentionCandidate", () => {
|
||||
test("detects leading, inline, and punctuated slash candidates in user text", () => {
|
||||
expect(hasCodexSkillMentionCandidate("/marker-skill")).toBe(true);
|
||||
expect(hasCodexSkillMentionCandidate("Use /marker-skill.")).toBe(true);
|
||||
expect(hasCodexSkillMentionCandidate("Check /docs/api.md then /marker-skill")).toBe(true);
|
||||
expect(
|
||||
hasCodexSkillMentionCandidate([
|
||||
{
|
||||
type: "text",
|
||||
mimeType: "text/plain",
|
||||
contextKind: "chat_history",
|
||||
text: "No candidate here",
|
||||
},
|
||||
{ type: "text", text: "Now run /marker-skill!" },
|
||||
]),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
test("returns false for plain text, file paths, URLs, bare slashes, and non-user blocks", () => {
|
||||
expect(hasCodexSkillMentionCandidate("Answer briefly: what is 2+2?")).toBe(false);
|
||||
expect(hasCodexSkillMentionCandidate("Read /docs/api.md before replying")).toBe(false);
|
||||
expect(hasCodexSkillMentionCandidate("Read /docs/api.md.")).toBe(false);
|
||||
expect(hasCodexSkillMentionCandidate("See https://example.com/marker-skill")).toBe(false);
|
||||
expect(hasCodexSkillMentionCandidate("Path foo/marker-skill")).toBe(false);
|
||||
expect(hasCodexSkillMentionCandidate("Ratio a/b and bare / or /.")).toBe(false);
|
||||
expect(
|
||||
hasCodexSkillMentionCandidate([
|
||||
{
|
||||
type: "text",
|
||||
mimeType: "text/plain",
|
||||
contextKind: "chat_history",
|
||||
text: "Prior message used /marker-skill",
|
||||
},
|
||||
{
|
||||
type: "text",
|
||||
mimeType: "text/plain",
|
||||
title: "Note",
|
||||
text: "Attached snippet with /marker-skill",
|
||||
},
|
||||
{
|
||||
type: "image",
|
||||
mimeType: "image/png",
|
||||
data: "AAAA",
|
||||
},
|
||||
{
|
||||
type: "github_issue",
|
||||
mimeType: "application/github-issue",
|
||||
number: 5008,
|
||||
title: "Fix /marker-skill",
|
||||
url: "https://github.com/getpaseo/paseo/issues/5008",
|
||||
},
|
||||
]),
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveCodexSkillMentions", () => {
|
||||
test("resolves leading, inline, multiple, deduplicated, and punctuated mentions", () => {
|
||||
expect(resolveCodexSkillMentions("/marker-skill Answer briefly.", SKILLS)).toEqual({
|
||||
skills: [{ type: "skill", name: "marker-skill", path: SKILLS[0]!.path }],
|
||||
prompt: [
|
||||
{ type: "skill", name: "marker-skill", path: SKILLS[0]!.path },
|
||||
{ type: "text", text: "$marker-skill Answer briefly." },
|
||||
],
|
||||
});
|
||||
|
||||
expect(
|
||||
resolveCodexSkillMentions(
|
||||
"Use /second-skill, then /marker-skill; finally (/second-skill or /marker-skill!).",
|
||||
SKILLS,
|
||||
),
|
||||
).toEqual({
|
||||
skills: [
|
||||
{ type: "skill", name: "second-skill", path: SKILLS[1]!.path },
|
||||
{ type: "skill", name: "marker-skill", path: SKILLS[0]!.path },
|
||||
],
|
||||
prompt: [
|
||||
{ type: "skill", name: "second-skill", path: SKILLS[1]!.path },
|
||||
{ type: "skill", name: "marker-skill", path: SKILLS[0]!.path },
|
||||
{
|
||||
type: "text",
|
||||
text: "Use $second-skill, then $marker-skill; finally (/second-skill or $marker-skill!).",
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
expect(
|
||||
resolveCodexSkillMentions(
|
||||
"Try /marker-skill? /second-skill: [use /docs] {and /docs}",
|
||||
SKILLS,
|
||||
),
|
||||
).toEqual({
|
||||
skills: [
|
||||
{ type: "skill", name: "marker-skill", path: SKILLS[0]!.path },
|
||||
{ type: "skill", name: "second-skill", path: SKILLS[1]!.path },
|
||||
{ type: "skill", name: "docs", path: SKILLS[2]!.path },
|
||||
],
|
||||
prompt: [
|
||||
{ type: "skill", name: "marker-skill", path: SKILLS[0]!.path },
|
||||
{ type: "skill", name: "second-skill", path: SKILLS[1]!.path },
|
||||
{ type: "skill", name: "docs", path: SKILLS[2]!.path },
|
||||
{
|
||||
type: "text",
|
||||
text: "Try $marker-skill? $second-skill: [use $docs] {and $docs}",
|
||||
},
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
test("never corrupts file paths, extensions, suffixes, or unknown slash tokens", () => {
|
||||
const prompt =
|
||||
"Check /docs/api.md, /docs/api.md., /docs.md, /docs-extra, /docs_v2, path/docs, and /unknown.";
|
||||
const result = resolveCodexSkillMentions(prompt, SKILLS);
|
||||
expect(result).toEqual({ skills: [], prompt });
|
||||
expect(result.prompt).toBe(prompt);
|
||||
});
|
||||
|
||||
test("scans only user text blocks and leaves images, chat_history, and attachments untouched", () => {
|
||||
const chatHistory: AgentPromptContentBlock = {
|
||||
type: "text",
|
||||
mimeType: "text/plain",
|
||||
contextKind: "chat_history",
|
||||
text: "History mentioned /docs",
|
||||
};
|
||||
const textAttachment: AgentPromptContentBlock = {
|
||||
type: "text",
|
||||
mimeType: "text/plain",
|
||||
title: "Pasted text",
|
||||
text: "Attachment mentioned /second-skill",
|
||||
};
|
||||
const image: AgentPromptContentBlock = {
|
||||
type: "image",
|
||||
mimeType: "image/png",
|
||||
data: "AAAA",
|
||||
};
|
||||
const blocks: AgentPromptContentBlock[] = [
|
||||
chatHistory,
|
||||
{ type: "text", text: "Please run /marker-skill on /docs/api.md." },
|
||||
image,
|
||||
textAttachment,
|
||||
];
|
||||
|
||||
const result = resolveCodexSkillMentions(blocks, SKILLS);
|
||||
expect(result).toEqual({
|
||||
skills: [{ type: "skill", name: "marker-skill", path: SKILLS[0]!.path }],
|
||||
prompt: [
|
||||
{ type: "skill", name: "marker-skill", path: SKILLS[0]!.path },
|
||||
chatHistory,
|
||||
{ type: "text", text: "Please run $marker-skill on /docs/api.md." },
|
||||
image,
|
||||
textAttachment,
|
||||
],
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,131 @@
|
||||
import type { AgentPromptContentBlock, AgentPromptInput } from "../../agent-sdk-types.js";
|
||||
|
||||
export interface CodexSkillDescriptor {
|
||||
name: string;
|
||||
path: string;
|
||||
}
|
||||
|
||||
export interface CodexSkillPromptBlock {
|
||||
type: "skill";
|
||||
name: string;
|
||||
path: string;
|
||||
}
|
||||
|
||||
export type CodexPromptContentBlock = AgentPromptContentBlock | CodexSkillPromptBlock;
|
||||
export type CodexPromptInput = string | CodexPromptContentBlock[];
|
||||
|
||||
export interface ResolvedCodexSkillMentions {
|
||||
skills: CodexSkillPromptBlock[];
|
||||
prompt: CodexPromptInput;
|
||||
}
|
||||
|
||||
// Match a whitespace- or start-delimited `/token` across the full non-whitespace token so a
|
||||
// trailing path segment like `/docs/api.md` or extension like `/docs.md` never matches `/docs`.
|
||||
const SLASH_TOKEN_PATTERN = /(^|\s)\/(\S+)/g;
|
||||
const TRAILING_BOUNDARY_PUNCTUATION_PATTERN = /[.,!?;:)\]}]+$/;
|
||||
const DISALLOWED_CANDIDATE_CHARS_PATTERN = /[/"']/;
|
||||
|
||||
function isUserTextBlock(block: AgentPromptContentBlock): block is { type: "text"; text: string } {
|
||||
return block.type === "text" && !("contextKind" in block) && !("mimeType" in block);
|
||||
}
|
||||
|
||||
function parseSlashMentionToken(rawToken: string): { name: string; trailing: string } | null {
|
||||
const trailingMatch = TRAILING_BOUNDARY_PUNCTUATION_PATTERN.exec(rawToken);
|
||||
const name = trailingMatch ? rawToken.slice(0, trailingMatch.index) : rawToken;
|
||||
const trailing = trailingMatch ? trailingMatch[0] : "";
|
||||
if (name.length === 0 || DISALLOWED_CANDIDATE_CHARS_PATTERN.test(name)) {
|
||||
return null;
|
||||
}
|
||||
return { name, trailing };
|
||||
}
|
||||
|
||||
function textHasSlashMentionCandidate(text: string): boolean {
|
||||
if (!text.includes("/")) {
|
||||
return false;
|
||||
}
|
||||
for (const match of text.matchAll(SLASH_TOKEN_PATTERN)) {
|
||||
const rawToken = match[2];
|
||||
if (rawToken && parseSlashMentionToken(rawToken)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
export function hasCodexSkillMentionCandidate(prompt: AgentPromptInput): boolean {
|
||||
if (typeof prompt === "string") {
|
||||
return textHasSlashMentionCandidate(prompt);
|
||||
}
|
||||
return prompt.some((block) => isUserTextBlock(block) && textHasSlashMentionCandidate(block.text));
|
||||
}
|
||||
|
||||
export function resolveCodexSkillMentions(
|
||||
prompt: AgentPromptInput,
|
||||
skills: ReadonlyArray<CodexSkillDescriptor>,
|
||||
): ResolvedCodexSkillMentions {
|
||||
if (skills.length === 0 || !hasCodexSkillMentionCandidate(prompt)) {
|
||||
return { skills: [], prompt };
|
||||
}
|
||||
|
||||
const skillsByName = new Map<string, CodexSkillDescriptor>();
|
||||
for (const skill of skills) {
|
||||
if (!skillsByName.has(skill.name)) {
|
||||
skillsByName.set(skill.name, skill);
|
||||
}
|
||||
}
|
||||
|
||||
const mentioned = new Map<string, CodexSkillPromptBlock>();
|
||||
const rewriteUserText = (text: string): string => {
|
||||
if (!text.includes("/")) {
|
||||
return text;
|
||||
}
|
||||
return text.replace(SLASH_TOKEN_PATTERN, (fullMatch, prefix: string, rawToken: string) => {
|
||||
const parsed = parseSlashMentionToken(rawToken);
|
||||
if (!parsed) {
|
||||
return fullMatch;
|
||||
}
|
||||
const skill = skillsByName.get(parsed.name);
|
||||
if (!skill) {
|
||||
return fullMatch;
|
||||
}
|
||||
if (!mentioned.has(skill.name)) {
|
||||
mentioned.set(skill.name, {
|
||||
type: "skill",
|
||||
name: skill.name,
|
||||
path: skill.path,
|
||||
});
|
||||
}
|
||||
return `${prefix}$${skill.name}${parsed.trailing}`;
|
||||
});
|
||||
};
|
||||
|
||||
if (typeof prompt === "string") {
|
||||
const rewrittenText = rewriteUserText(prompt);
|
||||
if (mentioned.size === 0) {
|
||||
return { skills: [], prompt };
|
||||
}
|
||||
const skillBlocks = Array.from(mentioned.values());
|
||||
return {
|
||||
skills: skillBlocks,
|
||||
prompt: [...skillBlocks, { type: "text", text: rewrittenText }],
|
||||
};
|
||||
}
|
||||
|
||||
const rewrittenBlocks = prompt.map((block): AgentPromptContentBlock => {
|
||||
if (!isUserTextBlock(block)) {
|
||||
return block;
|
||||
}
|
||||
const rewrittenText = rewriteUserText(block.text);
|
||||
return rewrittenText === block.text ? block : { ...block, text: rewrittenText };
|
||||
});
|
||||
|
||||
if (mentioned.size === 0) {
|
||||
return { skills: [], prompt };
|
||||
}
|
||||
|
||||
const skillBlocks = Array.from(mentioned.values());
|
||||
return {
|
||||
skills: skillBlocks,
|
||||
prompt: [...skillBlocks, ...rewrittenBlocks],
|
||||
};
|
||||
}
|
||||
@@ -94,7 +94,7 @@ import {
|
||||
isOmpBackgroundJobKillOutput,
|
||||
ompBackgroundJobKillCommand,
|
||||
parseOmpBackgroundWorkStatus,
|
||||
} from "./background-work-extension.js";
|
||||
} from "./integration-extension.js";
|
||||
import type { OmpRuntime, OmpRuntimeSession, OmpStartSessionInput } from "./runtime.js";
|
||||
import { OmpMcpBridge, type OmpBridgedToolIdentity } from "./mcp-bridge.js";
|
||||
import type {
|
||||
|
||||
@@ -9,9 +9,9 @@ import {
|
||||
type JsonlRpcLaunch,
|
||||
} from "../jsonl-rpc-process.js";
|
||||
import {
|
||||
createOmpBackgroundWorkExtensionFile,
|
||||
type OmpBackgroundWorkExtensionFile,
|
||||
} from "./background-work-extension.js";
|
||||
createOmpIntegrationExtensionFile,
|
||||
type OmpIntegrationExtensionFile,
|
||||
} from "./integration-extension.js";
|
||||
import { establishOmpProtocol } from "./protocol-session.js";
|
||||
import {
|
||||
buildOmpLaunch,
|
||||
@@ -75,14 +75,16 @@ export class OmpCliRuntime implements OmpRuntime {
|
||||
}
|
||||
|
||||
async startSession(input: OmpStartSessionInput): Promise<OmpRuntimeSession> {
|
||||
const backgroundWorkExtension = await createOmpBackgroundWorkExtensionFile();
|
||||
const integrationExtension = await createOmpIntegrationExtensionFile(
|
||||
input.systemPrompt?.trim(),
|
||||
);
|
||||
let env: Record<string, string>;
|
||||
let process: JsonlRpcProcess;
|
||||
try {
|
||||
input.signal?.throwIfAborted();
|
||||
({ env, process } = this.spawnOmp(input, backgroundWorkExtension.path));
|
||||
({ env, process } = this.spawnOmp(input, integrationExtension.path));
|
||||
} catch (error) {
|
||||
await backgroundWorkExtension.cleanup();
|
||||
await integrationExtension.cleanup();
|
||||
throw error;
|
||||
}
|
||||
const handleAbort = () => void process.close(input.signal?.reason).catch(() => undefined);
|
||||
@@ -93,11 +95,11 @@ export class OmpCliRuntime implements OmpRuntime {
|
||||
requestTimeoutMs: this.options.requestTimeoutMs,
|
||||
});
|
||||
input.signal?.throwIfAborted();
|
||||
return new OmpCliRuntimeSession(process, this.commandsRpcName, env, backgroundWorkExtension);
|
||||
return new OmpCliRuntimeSession(process, this.commandsRpcName, env, integrationExtension);
|
||||
} catch (error) {
|
||||
const startupError = error instanceof Error ? error : new Error(String(error));
|
||||
await process.close(startupError);
|
||||
await backgroundWorkExtension.cleanup();
|
||||
await integrationExtension.cleanup();
|
||||
throw startupError;
|
||||
} finally {
|
||||
input.signal?.removeEventListener("abort", handleAbort);
|
||||
@@ -149,7 +151,7 @@ class OmpCliRuntimeSession implements OmpRuntimeSession {
|
||||
private readonly process: JsonlRpcProcess,
|
||||
private readonly commandsRpcName: "get_available_commands",
|
||||
private readonly launchEnvironment: Record<string, string>,
|
||||
private readonly backgroundWorkExtension: OmpBackgroundWorkExtensionFile,
|
||||
private readonly integrationExtension: OmpIntegrationExtensionFile,
|
||||
) {
|
||||
process.onMessage((message) => {
|
||||
const event = parseOmpRuntimeEvent(message);
|
||||
@@ -334,7 +336,7 @@ class OmpCliRuntimeSession implements OmpRuntimeSession {
|
||||
try {
|
||||
await this.process.close(new Error("OMP RPC session is closed"));
|
||||
} finally {
|
||||
await this.backgroundWorkExtension.cleanup();
|
||||
await this.integrationExtension.cleanup();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+8
-8
@@ -3,11 +3,11 @@ import { pathToFileURL } from "node:url";
|
||||
import { afterEach, beforeEach, describe, expect, test, vi, type Mock } from "vitest";
|
||||
|
||||
import {
|
||||
createOmpBackgroundWorkExtensionFile,
|
||||
createOmpIntegrationExtensionFile,
|
||||
OMP_BACKGROUND_WORK_STATUS_KEY,
|
||||
parseOmpBackgroundWorkStatus,
|
||||
type OmpBackgroundWorkExtensionFile,
|
||||
} from "./background-work-extension.js";
|
||||
type OmpIntegrationExtensionFile,
|
||||
} from "./integration-extension.js";
|
||||
|
||||
interface FakeJob {
|
||||
id: string;
|
||||
@@ -40,7 +40,7 @@ const sleepJobStatus = JSON.stringify({
|
||||
jobs: [{ id: "bg_1", type: "bash", label: "sleep 45", command: "sleep 45" }],
|
||||
});
|
||||
|
||||
let extensionFile: OmpBackgroundWorkExtensionFile | undefined;
|
||||
let extensionFile: OmpIntegrationExtensionFile | undefined;
|
||||
|
||||
afterEach(async () => {
|
||||
vi.useRealTimers();
|
||||
@@ -49,7 +49,7 @@ afterEach(async () => {
|
||||
});
|
||||
|
||||
async function installExtension(): Promise<FakeHost> {
|
||||
extensionFile = await createOmpBackgroundWorkExtensionFile();
|
||||
extensionFile = await createOmpIntegrationExtensionFile();
|
||||
// The extension path is a runtime temp file, so it can only be loaded dynamically.
|
||||
const module = (await import(pathToFileURL(extensionFile.path).href)) as ExtensionModule;
|
||||
const handlers = new Map<string, FakeHandler>();
|
||||
@@ -90,7 +90,7 @@ function publishedTexts(setStatus: Mock): string[] {
|
||||
|
||||
describe("OMP background work extension file", () => {
|
||||
test("writes a module that exports the extension function", async () => {
|
||||
const file = await createOmpBackgroundWorkExtensionFile();
|
||||
const file = await createOmpIntegrationExtensionFile();
|
||||
try {
|
||||
// The generated module lives at a runtime temp path, so it can only be loaded dynamically.
|
||||
const module = (await import(pathToFileURL(file.path).href)) as ExtensionModule;
|
||||
@@ -104,7 +104,7 @@ describe("OMP background work extension file", () => {
|
||||
test.skipIf(process.platform === "win32")(
|
||||
"writes the module readable by its owner only",
|
||||
async () => {
|
||||
const file = await createOmpBackgroundWorkExtensionFile();
|
||||
const file = await createOmpIntegrationExtensionFile();
|
||||
try {
|
||||
expect(statSync(file.path).mode & 0o777).toBe(0o600);
|
||||
} finally {
|
||||
@@ -114,7 +114,7 @@ describe("OMP background work extension file", () => {
|
||||
);
|
||||
|
||||
test("cleanup removes the private directory", async () => {
|
||||
const file = await createOmpBackgroundWorkExtensionFile();
|
||||
const file = await createOmpIntegrationExtensionFile();
|
||||
await file.cleanup();
|
||||
expect(existsSync(file.path)).toBe(false);
|
||||
});
|
||||
+24
-7
@@ -7,7 +7,7 @@ import type { AgentBackgroundWorkInput } from "../../background-work/index.js";
|
||||
|
||||
export const OMP_BACKGROUND_WORK_STATUS_KEY = "paseo:background-work";
|
||||
|
||||
export interface OmpBackgroundWorkExtensionFile {
|
||||
export interface OmpIntegrationExtensionFile {
|
||||
path: string;
|
||||
cleanup(): Promise<void>;
|
||||
}
|
||||
@@ -29,10 +29,11 @@ const statusSchema = z.object({
|
||||
|
||||
type OmpBackgroundJob = z.infer<typeof jobSchema>;
|
||||
|
||||
const EXTENSION_SOURCE = `const STATUS_KEY = ${JSON.stringify(OMP_BACKGROUND_WORK_STATUS_KEY)};
|
||||
function renderExtension(systemPrompt: string | undefined): string {
|
||||
return `const STATUS_KEY = ${JSON.stringify(OMP_BACKGROUND_WORK_STATUS_KEY)};
|
||||
const POLL_INTERVAL_MS = 250;
|
||||
|
||||
export default function paseoBackgroundWork(pi) {
|
||||
export default function paseoIntegration(pi) {
|
||||
let ctx;
|
||||
let timer;
|
||||
let lastText;
|
||||
@@ -72,18 +73,34 @@ export default function paseoBackgroundWork(pi) {
|
||||
timer.unref?.();
|
||||
}
|
||||
|
||||
${
|
||||
systemPrompt
|
||||
? `// Let OMP discover its own APPEND_SYSTEM.md before adding Paseo's instructions.
|
||||
pi.on("before_agent_start", (event) => {
|
||||
const append = ${JSON.stringify(systemPrompt)};
|
||||
return {
|
||||
systemPrompt: Array.isArray(event.systemPrompt)
|
||||
? [...event.systemPrompt, append]
|
||||
: event.systemPrompt + "\\n\\n" + append,
|
||||
};
|
||||
});`
|
||||
: ""
|
||||
}
|
||||
pi.on("session_start", (_event, sessionCtx) => start(sessionCtx));
|
||||
pi.on("session_switch", (_event, sessionCtx) => start(sessionCtx));
|
||||
pi.on("session_shutdown", () => stop());
|
||||
}
|
||||
`;
|
||||
}
|
||||
|
||||
export async function createOmpBackgroundWorkExtensionFile(): Promise<OmpBackgroundWorkExtensionFile> {
|
||||
const dir = await mkdtemp(join(tmpdir(), "paseo-omp-background-work-"));
|
||||
const path = join(dir, "paseo-background-work.mjs");
|
||||
export async function createOmpIntegrationExtensionFile(
|
||||
systemPrompt?: string,
|
||||
): Promise<OmpIntegrationExtensionFile> {
|
||||
const dir = await mkdtemp(join(tmpdir(), "paseo-omp-integration-"));
|
||||
const path = join(dir, "paseo-integration.mjs");
|
||||
const cleanup = () => rm(dir, { recursive: true, force: true });
|
||||
try {
|
||||
await writeFile(path, EXTENSION_SOURCE, { mode: 0o600 });
|
||||
await writeFile(path, renderExtension(systemPrompt), { mode: 0o600 });
|
||||
} catch (error) {
|
||||
await cleanup();
|
||||
throw error;
|
||||
@@ -27,7 +27,6 @@ export interface OmpRuntimeLaunch {
|
||||
modeId?: string;
|
||||
session?: string;
|
||||
noSession?: boolean;
|
||||
systemPrompt?: string;
|
||||
extraArgs?: string[];
|
||||
}
|
||||
|
||||
@@ -103,8 +102,7 @@ export function buildOmpLaunch(input: {
|
||||
const argv = [...command];
|
||||
|
||||
const protocolMode = input.session.protocolMode ?? "rpc";
|
||||
const systemPrompt = input.session.systemPrompt?.trim();
|
||||
appendOmpLaunchArgs(argv, input.session, protocolMode, systemPrompt);
|
||||
appendOmpLaunchArgs(argv, input.session, protocolMode);
|
||||
|
||||
return {
|
||||
cwd: input.session.cwd,
|
||||
@@ -123,7 +121,6 @@ export function buildOmpLaunch(input: {
|
||||
modeId: input.session.modeId,
|
||||
session: input.session.session,
|
||||
noSession: input.session.noSession,
|
||||
systemPrompt,
|
||||
extraArgs: input.session.extraArgs,
|
||||
};
|
||||
}
|
||||
@@ -132,7 +129,6 @@ function appendOmpLaunchArgs(
|
||||
argv: string[],
|
||||
session: OmpStartSessionInput,
|
||||
protocolMode: "rpc" | "rpc-ui",
|
||||
systemPrompt: string | undefined,
|
||||
): void {
|
||||
if (!hasModeFlag(argv)) {
|
||||
argv.push("--mode", protocolMode);
|
||||
@@ -151,9 +147,6 @@ function appendOmpLaunchArgs(
|
||||
} else if (session.session) {
|
||||
argv.push("--session", session.session);
|
||||
}
|
||||
if (systemPrompt) {
|
||||
argv.push("--append-system-prompt", systemPrompt);
|
||||
}
|
||||
}
|
||||
|
||||
function hasModeFlag(argv: string[]): boolean {
|
||||
|
||||
@@ -20,7 +20,7 @@ import type {
|
||||
OmpThinkingLevel,
|
||||
} from "../rpc-types.js";
|
||||
import { buildOmpLaunch } from "../runtime.js";
|
||||
import { OMP_BACKGROUND_WORK_STATUS_KEY } from "../background-work-extension.js";
|
||||
import { OMP_BACKGROUND_WORK_STATUS_KEY } from "../integration-extension.js";
|
||||
|
||||
type FakeOmpSubagentSubscriptionLevel = "off" | "progress" | "events";
|
||||
type FakeOmpSubagentStatus = "pending" | "running" | "completed" | "failed" | "aborted";
|
||||
|
||||
@@ -3258,3 +3258,345 @@ describe("OpenCode v2 rewind", () => {
|
||||
expect(stages).toEqual([expect.objectContaining({ messageID: "msg_1", files: true })]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("OpenCode v2 slash commands and skill mentions", () => {
|
||||
function createSkillHarness() {
|
||||
const harness = new V2Harness();
|
||||
const location = { directory: "/tmp/project" };
|
||||
let commandListCalls = 0;
|
||||
let skillListCalls = 0;
|
||||
harness.api.command.list = async () => {
|
||||
commandListCalls += 1;
|
||||
return {
|
||||
location,
|
||||
data: [{ name: "review", description: "Review changes", source: "command" }],
|
||||
} as unknown as Awaited<ReturnType<V2Api["command"]["list"]>>;
|
||||
};
|
||||
harness.api.skill.list = async () => {
|
||||
skillListCalls += 1;
|
||||
return {
|
||||
location,
|
||||
data: [
|
||||
{ id: "grill-with-docs", description: "Grill with docs" },
|
||||
{ id: "review-docs", description: "Review docs" },
|
||||
{ id: "docs", description: "Docs skill" },
|
||||
{ id: "mcp:check", description: "MCP skill with colon" },
|
||||
],
|
||||
} as unknown as Awaited<ReturnType<V2Api["skill"]["list"]>>;
|
||||
};
|
||||
const sentPrompts: Array<Parameters<V2Api["session"]["prompt"]>[0]> = [];
|
||||
const sentCommands: Array<Parameters<V2Api["session"]["command"]>[0]> = [];
|
||||
const sentCompacts: Array<Parameters<V2Api["session"]["compact"]>[0]> = [];
|
||||
const origPrompt = harness.prompt;
|
||||
harness.prompt = async (input, options) => {
|
||||
sentPrompts.push(input);
|
||||
await origPrompt(input, options);
|
||||
};
|
||||
harness.api.session.command = async (input) => {
|
||||
sentCommands.push(input);
|
||||
if (harness.autoComplete) harness.finishExecution();
|
||||
};
|
||||
harness.api.session.compact = async (input) => {
|
||||
sentCompacts.push(input);
|
||||
if (harness.autoComplete) harness.finishExecution();
|
||||
};
|
||||
return {
|
||||
harness,
|
||||
sentPrompts,
|
||||
sentCommands,
|
||||
sentCompacts,
|
||||
get commandListCalls() {
|
||||
return commandListCalls;
|
||||
},
|
||||
get skillListCalls() {
|
||||
return skillListCalls;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
test("resolves inline skill mention on idle turn with @mention and exact offset", async () => {
|
||||
const h = createSkillHarness();
|
||||
const client = new OpenCodeV2AgentClient({
|
||||
logger: createTestLogger(),
|
||||
runtime: h.harness.runtime,
|
||||
});
|
||||
const session = await client.createSession({ provider: "opencode", cwd: "/tmp/project" });
|
||||
try {
|
||||
await session.run("Answer briefly: what is 2+2? /grill-with-docs");
|
||||
expect(h.sentPrompts).toHaveLength(1);
|
||||
const sent = h.sentPrompts[0]!;
|
||||
expect(sent.text).toBe("Answer briefly: what is 2+2? @grill-with-docs");
|
||||
expect(sent.skills).toEqual([
|
||||
{
|
||||
id: "grill-with-docs",
|
||||
mention: { start: 29, end: 45, text: "@grill-with-docs" },
|
||||
},
|
||||
]);
|
||||
expect(sent.text.slice(29, 45)).toBe("@grill-with-docs");
|
||||
} finally {
|
||||
await session.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("resolves leading skill with prose, standalone skill, and trailing-space-only skill", async () => {
|
||||
const h = createSkillHarness();
|
||||
const client = new OpenCodeV2AgentClient({
|
||||
logger: createTestLogger(),
|
||||
runtime: h.harness.runtime,
|
||||
});
|
||||
const session = await client.createSession({ provider: "opencode", cwd: "/tmp/project" });
|
||||
try {
|
||||
await session.run("/grill-with-docs check the plan");
|
||||
expect(h.sentPrompts[0]).toMatchObject({
|
||||
text: "@grill-with-docs check the plan",
|
||||
skills: [
|
||||
{
|
||||
id: "grill-with-docs",
|
||||
mention: { start: 0, end: 16, text: "@grill-with-docs" },
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
await session.run("/grill-with-docs ");
|
||||
expect(h.sentPrompts[1]).toMatchObject({
|
||||
text: "Use the grill-with-docs skill.",
|
||||
skills: [{ id: "grill-with-docs" }],
|
||||
});
|
||||
} finally {
|
||||
await session.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("resolves multiple skills, punctuation boundaries, colon IDs, and deduplicates by id", async () => {
|
||||
const h = createSkillHarness();
|
||||
const client = new OpenCodeV2AgentClient({
|
||||
logger: createTestLogger(),
|
||||
runtime: h.harness.runtime,
|
||||
});
|
||||
const session = await client.createSession({ provider: "opencode", cwd: "/tmp/project" });
|
||||
try {
|
||||
await session.run(
|
||||
"Use /grill-with-docs, /mcp:check. Then /review-docs! Repeat /grill-with-docs.",
|
||||
);
|
||||
const sent = h.sentPrompts[0]!;
|
||||
expect(sent.text).toBe(
|
||||
"Use @grill-with-docs, @mcp:check. Then @review-docs! Repeat @grill-with-docs.",
|
||||
);
|
||||
expect(sent.skills).toEqual([
|
||||
{ id: "grill-with-docs", mention: { start: 4, end: 20, text: "@grill-with-docs" } },
|
||||
{ id: "mcp:check", mention: { start: 22, end: 32, text: "@mcp:check" } },
|
||||
{ id: "review-docs", mention: { start: 39, end: 51, text: "@review-docs" } },
|
||||
]);
|
||||
for (const skill of sent.skills ?? []) {
|
||||
expect(sent.text.slice(skill.mention!.start, skill.mention!.end)).toBe(skill.mention!.text);
|
||||
}
|
||||
} finally {
|
||||
await session.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("resolves skills alongside attachments without scanning chat_history or text attachments", async () => {
|
||||
const h = createSkillHarness();
|
||||
const client = new OpenCodeV2AgentClient({
|
||||
logger: createTestLogger(),
|
||||
runtime: h.harness.runtime,
|
||||
});
|
||||
const session = await client.createSession({ provider: "opencode", cwd: "/tmp/project" });
|
||||
try {
|
||||
await session.run([
|
||||
{
|
||||
type: "text",
|
||||
mimeType: "text/plain",
|
||||
contextKind: "chat_history",
|
||||
text: "Previous chat mentioned /review-docs",
|
||||
},
|
||||
{ type: "text", text: "/grill-with-docs inspect this image" },
|
||||
{ type: "image", mimeType: "image/png", data: "AAAA" },
|
||||
{
|
||||
type: "text",
|
||||
mimeType: "text/plain",
|
||||
text: "Attached note with /docs",
|
||||
},
|
||||
]);
|
||||
const sent = h.sentPrompts[0]!;
|
||||
expect(sent.files).toEqual([{ uri: "data:image/png;base64,AAAA" }]);
|
||||
expect(sent.text).toContain("Previous chat mentioned /review-docs");
|
||||
expect(sent.text).toContain("Attached note with /docs");
|
||||
expect(sent.text).toContain("@grill-with-docs inspect this image");
|
||||
expect(sent.skills).toHaveLength(1);
|
||||
const [skill] = sent.skills!;
|
||||
expect(skill?.id).toBe("grill-with-docs");
|
||||
expect(sent.text.slice(skill!.mention!.start, skill!.mention!.end)).toBe("@grill-with-docs");
|
||||
} finally {
|
||||
await session.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("leaves file paths untouched and skips command lookup when no slash mention candidate exists", async () => {
|
||||
const h = createSkillHarness();
|
||||
const client = new OpenCodeV2AgentClient({
|
||||
logger: createTestLogger(),
|
||||
runtime: h.harness.runtime,
|
||||
});
|
||||
const session = await client.createSession({ provider: "opencode", cwd: "/tmp/project" });
|
||||
try {
|
||||
await session.run("Compare /docs/api.md and src/docs/index.ts with /docs.ts");
|
||||
expect(h.sentPrompts[0]?.text).toBe(
|
||||
"Compare /docs/api.md and src/docs/index.ts with /docs.ts",
|
||||
);
|
||||
expect(h.sentPrompts[0]?.skills).toBeUndefined();
|
||||
// /docs.ts is a single-segment candidate so lookup ran once; /docs/api.md alone skips lookup.
|
||||
const callsBeforePathOnly = h.skillListCalls;
|
||||
await session.run("Read /docs/api.md and packages/app/index.ts");
|
||||
expect(h.skillListCalls).toBe(callsBeforePathOnly);
|
||||
expect(h.sentPrompts[1]?.text).toBe("Read /docs/api.md and packages/app/index.ts");
|
||||
expect(h.sentPrompts[1]?.skills).toBeUndefined();
|
||||
} finally {
|
||||
await session.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("attaches skills selected inside leading command arguments and ignores code blocks", async () => {
|
||||
const h = createSkillHarness();
|
||||
const client = new OpenCodeV2AgentClient({
|
||||
logger: createTestLogger(),
|
||||
runtime: h.harness.runtime,
|
||||
});
|
||||
const session = await client.createSession({ provider: "opencode", cwd: "/tmp/project" });
|
||||
try {
|
||||
await session.run("/review src/index.ts /docs");
|
||||
expect(h.sentCommands).toEqual([
|
||||
{
|
||||
sessionID: "session",
|
||||
name: "review",
|
||||
text: "src/index.ts @docs",
|
||||
files: [],
|
||||
skills: [{ id: "docs", mention: { start: 13, end: 18, text: "@docs" } }],
|
||||
},
|
||||
]);
|
||||
|
||||
const fenced = "Explain:\n```sh\nls /docs\n```";
|
||||
await session.run(fenced);
|
||||
expect(h.sentPrompts[0]?.text).toBe(fenced);
|
||||
expect(h.sentPrompts[0]?.skills).toBeUndefined();
|
||||
} finally {
|
||||
await session.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("steers leading and inline skills natively into a running turn", async () => {
|
||||
const h = createSkillHarness();
|
||||
h.harness.autoComplete = false;
|
||||
const client = new OpenCodeV2AgentClient({
|
||||
logger: createTestLogger(),
|
||||
runtime: h.harness.runtime,
|
||||
});
|
||||
const session = await client.createSession({ provider: "opencode", cwd: "/tmp/project" });
|
||||
try {
|
||||
const { turnId } = await session.startTurn("Work");
|
||||
await expect.poll(() => h.harness.prompts).toEqual(["Work"]);
|
||||
|
||||
await expect(
|
||||
session.steerActiveTurn!("/grill-with-docs the plan", { expectedTurnId: turnId }),
|
||||
).resolves.toEqual({ status: "accepted" });
|
||||
expect(h.sentPrompts[1]).toMatchObject({
|
||||
text: "@grill-with-docs the plan",
|
||||
skills: [
|
||||
{
|
||||
id: "grill-with-docs",
|
||||
mention: { start: 0, end: 16, text: "@grill-with-docs" },
|
||||
},
|
||||
],
|
||||
delivery: "steer",
|
||||
});
|
||||
|
||||
await expect(
|
||||
session.steerActiveTurn!("Also apply /review-docs.", { expectedTurnId: turnId }),
|
||||
).resolves.toEqual({ status: "accepted" });
|
||||
expect(h.sentPrompts[2]).toMatchObject({
|
||||
text: "Also apply @review-docs.",
|
||||
skills: [
|
||||
{
|
||||
id: "review-docs",
|
||||
mention: { start: 11, end: 23, text: "@review-docs" },
|
||||
},
|
||||
],
|
||||
delivery: "steer",
|
||||
});
|
||||
} finally {
|
||||
await session.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("returns unavailable on steer for /compact, /summarize, and provider commands", async () => {
|
||||
const h = createSkillHarness();
|
||||
h.harness.autoComplete = false;
|
||||
const client = new OpenCodeV2AgentClient({
|
||||
logger: createTestLogger(),
|
||||
runtime: h.harness.runtime,
|
||||
});
|
||||
const session = await client.createSession({ provider: "opencode", cwd: "/tmp/project" });
|
||||
try {
|
||||
const { turnId } = await session.startTurn("Work");
|
||||
await expect.poll(() => h.harness.prompts).toEqual(["Work"]);
|
||||
|
||||
await expect(
|
||||
session.steerActiveTurn!("/compact", { expectedTurnId: turnId }),
|
||||
).resolves.toEqual({ status: "unavailable" });
|
||||
await expect(
|
||||
session.steerActiveTurn!(" /summarize ", { expectedTurnId: turnId }),
|
||||
).resolves.toEqual({ status: "unavailable" });
|
||||
await expect(
|
||||
session.steerActiveTurn!("/review now", { expectedTurnId: turnId }),
|
||||
).resolves.toEqual({ status: "unavailable" });
|
||||
expect(h.sentPrompts).toHaveLength(1);
|
||||
expect(h.sentCommands).toHaveLength(0);
|
||||
expect(h.sentCompacts).toHaveLength(0);
|
||||
} finally {
|
||||
await session.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("returns unavailable when the active turn ends during async skill resolution on steer", async () => {
|
||||
const h = createSkillHarness();
|
||||
h.harness.autoComplete = false;
|
||||
let releaseSkills!: () => void;
|
||||
const origSkillList = h.harness.api.skill.list;
|
||||
h.harness.api.skill.list = async (input) => {
|
||||
await new Promise<void>((resolve) => {
|
||||
releaseSkills = resolve;
|
||||
});
|
||||
return origSkillList(input);
|
||||
};
|
||||
const client = new OpenCodeV2AgentClient({
|
||||
logger: createTestLogger(),
|
||||
runtime: h.harness.runtime,
|
||||
});
|
||||
const session = await client.createSession({ provider: "opencode", cwd: "/tmp/project" });
|
||||
try {
|
||||
let completed = false;
|
||||
const unsubscribe = session.subscribe((event) => {
|
||||
if (event.type === "turn_completed") completed = true;
|
||||
});
|
||||
try {
|
||||
const { turnId } = await session.startTurn("Work");
|
||||
await expect.poll(() => h.harness.prompts).toEqual(["Work"]);
|
||||
|
||||
const steering = session.steerActiveTurn!("Use /grill-with-docs", {
|
||||
expectedTurnId: turnId,
|
||||
});
|
||||
await expect.poll(() => Boolean(releaseSkills)).toBe(true);
|
||||
h.harness.finishExecution();
|
||||
await expect.poll(() => completed).toBe(true);
|
||||
releaseSkills();
|
||||
|
||||
await expect(steering).resolves.toEqual({ status: "unavailable" });
|
||||
expect(h.sentPrompts).toHaveLength(1);
|
||||
} finally {
|
||||
unsubscribe();
|
||||
}
|
||||
} finally {
|
||||
await session.close();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,226 @@
|
||||
import { describe, expect, test } from "vitest";
|
||||
import type { AgentSlashCommand } from "../../../agent-sdk-types.js";
|
||||
import { prepareOpenCodePrompt } from "./prompt-input.js";
|
||||
|
||||
const COMMANDS: readonly AgentSlashCommand[] = [
|
||||
{ name: "compact", description: "Compact", argumentHint: "", kind: "command" },
|
||||
{ name: "summarize", description: "Summarize", argumentHint: "", kind: "command" },
|
||||
{ name: "review", description: "Review", argumentHint: "", kind: "command" },
|
||||
{ name: "nested/docs", description: "Nested command", argumentHint: "", kind: "command" },
|
||||
{ name: "docs", description: "Docs skill", argumentHint: "", kind: "skill" },
|
||||
{ name: "grill-with-docs", description: "Grill", argumentHint: "", kind: "skill" },
|
||||
{ name: "mcp:tool", description: "MCP skill", argumentHint: "", kind: "skill" },
|
||||
];
|
||||
|
||||
describe("prepareOpenCodePrompt", () => {
|
||||
test("recognizes compact and summarize without loading commands", async () => {
|
||||
let loads = 0;
|
||||
const load = async () => {
|
||||
loads += 1;
|
||||
return COMMANDS;
|
||||
};
|
||||
|
||||
expect(await prepareOpenCodePrompt("/compact", load)).toEqual({ kind: "compact" });
|
||||
expect(await prepareOpenCodePrompt(" /summarize now ", load)).toEqual({ kind: "compact" });
|
||||
expect(loads).toBe(0);
|
||||
});
|
||||
|
||||
test("dispatches leading non-skill slash commands with args and attachments", async () => {
|
||||
const result = await prepareOpenCodePrompt(
|
||||
[
|
||||
{ type: "text", text: " /review src/index.ts" },
|
||||
{ type: "image", mimeType: "image/png", data: "BBBB" },
|
||||
],
|
||||
async () => COMMANDS,
|
||||
);
|
||||
expect(result).toEqual({
|
||||
kind: "command",
|
||||
name: "review",
|
||||
text: "src/index.ts",
|
||||
files: [{ uri: "data:image/png;base64,BBBB" }],
|
||||
});
|
||||
});
|
||||
|
||||
test("skips loading commands when user text has no slash mention candidate", async () => {
|
||||
let loads = 0;
|
||||
const load = async () => {
|
||||
loads += 1;
|
||||
return COMMANDS;
|
||||
};
|
||||
|
||||
expect(await prepareOpenCodePrompt("Inspect /docs/api.md and a/docs/b", load)).toEqual({
|
||||
kind: "prompt",
|
||||
text: "Inspect /docs/api.md and a/docs/b",
|
||||
files: [],
|
||||
});
|
||||
expect(loads).toBe(0);
|
||||
});
|
||||
|
||||
test("rewrites standalone single and multiple skills to fallback prose", async () => {
|
||||
expect(await prepareOpenCodePrompt(" /grill-with-docs ", async () => COMMANDS)).toEqual({
|
||||
kind: "prompt",
|
||||
text: "Use the grill-with-docs skill.",
|
||||
files: [],
|
||||
skills: [{ id: "grill-with-docs" }],
|
||||
});
|
||||
|
||||
expect(
|
||||
await prepareOpenCodePrompt(
|
||||
"/grill-with-docs /mcp:tool /grill-with-docs",
|
||||
async () => COMMANDS,
|
||||
),
|
||||
).toEqual({
|
||||
kind: "prompt",
|
||||
text: "Use the grill-with-docs, mcp:tool skills.",
|
||||
files: [],
|
||||
skills: [{ id: "grill-with-docs" }, { id: "mcp:tool" }],
|
||||
});
|
||||
});
|
||||
|
||||
test("preserves punctuation boundaries and rejects path or word continuations", async () => {
|
||||
const result = await prepareOpenCodePrompt(
|
||||
"Use /docs, /mcp:tool. Keep /docs/api.md, /docs.ts, foo/docs, and /unknown.",
|
||||
async () => COMMANDS,
|
||||
);
|
||||
expect(result).toEqual({
|
||||
kind: "prompt",
|
||||
text: "Use @docs, @mcp:tool. Keep /docs/api.md, /docs.ts, foo/docs, and /unknown.",
|
||||
files: [],
|
||||
skills: [
|
||||
{ id: "docs", mention: { start: 4, end: 9, text: "@docs" } },
|
||||
{ id: "mcp:tool", mention: { start: 11, end: 20, text: "@mcp:tool" } },
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
test("keeps fallback text alongside preceding chat_history attachment", async () => {
|
||||
const result = await prepareOpenCodePrompt(
|
||||
[
|
||||
{
|
||||
type: "text",
|
||||
mimeType: "text/plain",
|
||||
contextKind: "chat_history",
|
||||
text: "History with /docs",
|
||||
},
|
||||
{ type: "text", text: "/grill-with-docs " },
|
||||
],
|
||||
async () => COMMANDS,
|
||||
);
|
||||
expect(result).toEqual({
|
||||
kind: "prompt",
|
||||
text: "History with /docs\nUse the grill-with-docs skill.",
|
||||
files: [],
|
||||
skills: [{ id: "grill-with-docs" }],
|
||||
});
|
||||
});
|
||||
|
||||
test("resolves skill mentions inside leading command arguments", async () => {
|
||||
const result = await prepareOpenCodePrompt("/review src/index.ts /docs", async () => COMMANDS);
|
||||
expect(result).toEqual({
|
||||
kind: "command",
|
||||
name: "review",
|
||||
text: "src/index.ts @docs",
|
||||
files: [],
|
||||
skills: [{ id: "docs", mention: { start: 13, end: 18, text: "@docs" } }],
|
||||
});
|
||||
|
||||
const skillOnlyArg = await prepareOpenCodePrompt("/review /docs", async () => COMMANDS);
|
||||
expect(skillOnlyArg).toEqual({
|
||||
kind: "command",
|
||||
name: "review",
|
||||
text: "@docs",
|
||||
files: [],
|
||||
skills: [{ id: "docs", mention: { start: 0, end: 5, text: "@docs" } }],
|
||||
});
|
||||
});
|
||||
|
||||
test("preserves literal paths inside fenced code blocks and inline code spans", async () => {
|
||||
let loads = 0;
|
||||
const load = async () => {
|
||||
loads += 1;
|
||||
return COMMANDS;
|
||||
};
|
||||
|
||||
const fencedOnly = "Explain this command:\n```sh\nls /docs\n```";
|
||||
expect(await prepareOpenCodePrompt(fencedOnly, load)).toEqual({
|
||||
kind: "prompt",
|
||||
text: fencedOnly,
|
||||
files: [],
|
||||
});
|
||||
expect(loads).toBe(0);
|
||||
|
||||
const inlineCodeOnly = "Run `ls /docs` or `ls`/docs";
|
||||
expect(await prepareOpenCodePrompt(inlineCodeOnly, load)).toEqual({
|
||||
kind: "prompt",
|
||||
text: inlineCodeOnly,
|
||||
files: [],
|
||||
});
|
||||
expect(loads).toBe(0);
|
||||
|
||||
const mixed = "Explain `ls /docs` and:\n```sh\nls /docs\n```\nThen use /docs.";
|
||||
const mixedResult = await prepareOpenCodePrompt(mixed, load);
|
||||
expect(mixedResult).toEqual({
|
||||
kind: "prompt",
|
||||
text: "Explain `ls /docs` and:\n```sh\nls /docs\n```\nThen use @docs.",
|
||||
files: [],
|
||||
skills: [{ id: "docs", mention: { start: 52, end: 57, text: "@docs" } }],
|
||||
});
|
||||
});
|
||||
|
||||
test("dispatches slash-separated subdirectory commands while keeping unmatched leading paths literal", async () => {
|
||||
expect(await prepareOpenCodePrompt("/nested/docs details /docs", async () => COMMANDS)).toEqual(
|
||||
{
|
||||
kind: "command",
|
||||
name: "nested/docs",
|
||||
text: "details @docs",
|
||||
files: [],
|
||||
skills: [{ id: "docs", mention: { start: 8, end: 13, text: "@docs" } }],
|
||||
},
|
||||
);
|
||||
|
||||
expect(await prepareOpenCodePrompt("/docs/api.md", async () => COMMANDS)).toEqual({
|
||||
kind: "prompt",
|
||||
text: "/docs/api.md",
|
||||
files: [],
|
||||
});
|
||||
});
|
||||
|
||||
test("preserves the regular prompt path when chat history precedes /compact or a provider command", async () => {
|
||||
const compactResult = await prepareOpenCodePrompt(
|
||||
[
|
||||
{
|
||||
type: "text",
|
||||
mimeType: "text/plain",
|
||||
contextKind: "chat_history",
|
||||
text: "Previous conversation transcript",
|
||||
},
|
||||
{ type: "text", text: "/compact" },
|
||||
],
|
||||
async () => COMMANDS,
|
||||
);
|
||||
expect(compactResult).toEqual({
|
||||
kind: "prompt",
|
||||
text: "Previous conversation transcript\n/compact",
|
||||
files: [],
|
||||
});
|
||||
|
||||
const commandResult = await prepareOpenCodePrompt(
|
||||
[
|
||||
{
|
||||
type: "text",
|
||||
mimeType: "text/plain",
|
||||
contextKind: "chat_history",
|
||||
text: "Earlier conversation about README.md",
|
||||
},
|
||||
{ type: "text", text: "/review src/index.ts /docs" },
|
||||
],
|
||||
async () => COMMANDS,
|
||||
);
|
||||
expect(commandResult).toEqual({
|
||||
kind: "prompt",
|
||||
text: "Earlier conversation about README.md\n/review src/index.ts @docs",
|
||||
files: [],
|
||||
skills: [{ id: "docs", mention: { start: 58, end: 63, text: "@docs" } }],
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,430 @@
|
||||
import type { AgentPromptInput, AgentSlashCommand } from "../../../agent-sdk-types.js";
|
||||
import { renderPromptAttachmentAsText } from "../../../prompt-attachments.js";
|
||||
|
||||
export interface OpenCodeSkillMention {
|
||||
start: number;
|
||||
end: number;
|
||||
text: string;
|
||||
}
|
||||
|
||||
export interface OpenCodeSkillAttachment {
|
||||
id: string;
|
||||
mention?: OpenCodeSkillMention;
|
||||
}
|
||||
|
||||
export type PreparedOpenCodePrompt =
|
||||
| { kind: "compact" }
|
||||
| {
|
||||
kind: "command";
|
||||
name: string;
|
||||
text: string;
|
||||
files: Array<{ uri: string }>;
|
||||
skills?: OpenCodeSkillAttachment[];
|
||||
}
|
||||
| {
|
||||
kind: "prompt";
|
||||
text: string;
|
||||
files: Array<{ uri: string }>;
|
||||
skills?: OpenCodeSkillAttachment[];
|
||||
};
|
||||
|
||||
interface PromptSegment {
|
||||
text: string;
|
||||
isUserText: boolean;
|
||||
}
|
||||
|
||||
interface TextPiece {
|
||||
text: string;
|
||||
isCode: boolean;
|
||||
precededByBoundary: boolean;
|
||||
}
|
||||
|
||||
interface MatchedSegment {
|
||||
text: string;
|
||||
hasOtherProse: boolean;
|
||||
mentions: Array<{ id: string; start: number; end: number; text: string }>;
|
||||
}
|
||||
|
||||
type RewrittenSegment = PromptSegment & { mentions?: MatchedSegment["mentions"] };
|
||||
|
||||
const LEADING_SLASH_COMMAND = /^\/([^\s]+)(?:\s+([\s\S]*))?$/;
|
||||
const SLASH_TOKEN = /(^|\s)\/([^\s]+)/g;
|
||||
const TRAILING_PUNCTUATION = /[.,!?;:)\]}]+$/;
|
||||
const OPENING_FENCE = /^ {0,3}(`{3,}|~{3,})/;
|
||||
|
||||
function splitPrompt(prompt: AgentPromptInput): {
|
||||
segments: PromptSegment[];
|
||||
files: Array<{ uri: string }>;
|
||||
} {
|
||||
if (typeof prompt === "string") {
|
||||
return { segments: [{ text: prompt, isUserText: true }], files: [] };
|
||||
}
|
||||
const segments: PromptSegment[] = [];
|
||||
const files: Array<{ uri: string }> = [];
|
||||
for (const part of prompt) {
|
||||
if (part.type === "image") {
|
||||
files.push({ uri: `data:${part.mimeType};base64,${part.data}` });
|
||||
} else if (part.type === "text") {
|
||||
segments.push({
|
||||
text: part.text,
|
||||
isUserText: !("mimeType" in part) && !("contextKind" in part),
|
||||
});
|
||||
} else {
|
||||
segments.push({ text: renderPromptAttachmentAsText(part), isUserText: false });
|
||||
}
|
||||
}
|
||||
return { segments, files };
|
||||
}
|
||||
|
||||
function joinSegments(segments: readonly PromptSegment[]): string {
|
||||
return segments.map((segment) => segment.text).join("\n");
|
||||
}
|
||||
|
||||
function findFenceClose(text: string, from: number, char: string, minLength: number): number {
|
||||
let cursor = from;
|
||||
while (cursor < text.length) {
|
||||
const newline = text.indexOf("\n", cursor);
|
||||
const lineEnd = newline === -1 ? text.length : newline;
|
||||
const line = text.slice(cursor, lineEnd).replace(/\r$/, "");
|
||||
const closeMatch = line.match(/^ {0,3}(`{3,}|~{3,})[ \t]*$/);
|
||||
if (closeMatch && closeMatch[1]![0] === char && closeMatch[1]!.length >= minLength) {
|
||||
return newline === -1 ? text.length : newline + 1;
|
||||
}
|
||||
if (newline === -1) return text.length;
|
||||
cursor = newline + 1;
|
||||
}
|
||||
return text.length;
|
||||
}
|
||||
|
||||
function findInlineCodeEnd(text: string, from: number, tickCount: number): number {
|
||||
let cursor = from;
|
||||
while (cursor < text.length) {
|
||||
const tick = text.indexOf("`", cursor);
|
||||
if (tick === -1) return -1;
|
||||
let runEnd = tick + 1;
|
||||
while (runEnd < text.length && text[runEnd] === "`") runEnd += 1;
|
||||
if (runEnd - tick === tickCount) return runEnd;
|
||||
cursor = runEnd;
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
function splitProseAndCode(text: string): TextPiece[] {
|
||||
const pieces: TextPiece[] = [];
|
||||
let proseStart = 0;
|
||||
let i = 0;
|
||||
|
||||
const pushProse = (end: number) => {
|
||||
if (end <= proseStart) return;
|
||||
pieces.push({
|
||||
text: text.slice(proseStart, end),
|
||||
isCode: false,
|
||||
precededByBoundary: proseStart === 0 || /\s/.test(text[proseStart - 1]!),
|
||||
});
|
||||
};
|
||||
|
||||
while (i < text.length) {
|
||||
const atLineStart = i === 0 || text[i - 1] === "\n";
|
||||
if (atLineStart) {
|
||||
const newline = text.indexOf("\n", i);
|
||||
const lineEnd = newline === -1 ? text.length : newline;
|
||||
const opening = text.slice(i, lineEnd).match(OPENING_FENCE);
|
||||
const fence = opening?.[1];
|
||||
const infoString = opening ? text.slice(i + opening[0].length, lineEnd) : "";
|
||||
if (fence && (fence[0] !== "`" || !infoString.includes("`"))) {
|
||||
pushProse(i);
|
||||
const bodyStart = newline === -1 ? text.length : newline + 1;
|
||||
const fenceEnd = findFenceClose(text, bodyStart, fence[0]!, fence.length);
|
||||
pieces.push({ text: text.slice(i, fenceEnd), isCode: true, precededByBoundary: true });
|
||||
i = fenceEnd;
|
||||
proseStart = i;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
if (text[i] === "`") {
|
||||
let runEnd = i + 1;
|
||||
while (runEnd < text.length && text[runEnd] === "`") runEnd += 1;
|
||||
const closeEnd = findInlineCodeEnd(text, runEnd, runEnd - i);
|
||||
if (closeEnd !== -1) {
|
||||
pushProse(i);
|
||||
pieces.push({ text: text.slice(i, closeEnd), isCode: true, precededByBoundary: false });
|
||||
i = closeEnd;
|
||||
proseStart = i;
|
||||
continue;
|
||||
}
|
||||
i = runEnd;
|
||||
continue;
|
||||
}
|
||||
|
||||
i += 1;
|
||||
}
|
||||
|
||||
pushProse(text.length);
|
||||
return pieces;
|
||||
}
|
||||
|
||||
function hasSlashCandidate(segments: readonly PromptSegment[]): boolean {
|
||||
for (const segment of segments) {
|
||||
if (!segment.isUserText || !segment.text.includes("/")) continue;
|
||||
for (const piece of splitProseAndCode(segment.text)) {
|
||||
if (piece.isCode || !piece.text.includes("/")) continue;
|
||||
SLASH_TOKEN.lastIndex = 0;
|
||||
for (
|
||||
let match = SLASH_TOKEN.exec(piece.text);
|
||||
match !== null;
|
||||
match = SLASH_TOKEN.exec(piece.text)
|
||||
) {
|
||||
if (match.index === 0 && match[1] === "" && !piece.precededByBoundary) continue;
|
||||
const rawToken = match[2] ?? "";
|
||||
// Multi-segment tokens such as `/docs/api.md` are file paths, never slash names.
|
||||
if (rawToken.includes("/")) continue;
|
||||
if (rawToken.replace(TRAILING_PUNCTUATION, "").length > 0) return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
function matchSkillToken(
|
||||
rawToken: string,
|
||||
skillIds: ReadonlySet<string>,
|
||||
): { id: string; trailing: string } | null {
|
||||
if (rawToken.includes("/")) return null;
|
||||
if (skillIds.has(rawToken)) return { id: rawToken, trailing: "" };
|
||||
const stripped = rawToken.replace(TRAILING_PUNCTUATION, "");
|
||||
if (stripped.length > 0 && stripped.length < rawToken.length && skillIds.has(stripped)) {
|
||||
return { id: stripped, trailing: rawToken.slice(stripped.length) };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function rewriteUserSegment(text: string, skillIds: ReadonlySet<string>): MatchedSegment {
|
||||
let rewritten = "";
|
||||
let outsideMatches = "";
|
||||
let hasCode = false;
|
||||
const mentions: MatchedSegment["mentions"] = [];
|
||||
|
||||
for (const piece of splitProseAndCode(text)) {
|
||||
if (piece.isCode) {
|
||||
rewritten += piece.text;
|
||||
hasCode = true;
|
||||
continue;
|
||||
}
|
||||
|
||||
let cursor = 0;
|
||||
SLASH_TOKEN.lastIndex = 0;
|
||||
for (
|
||||
let match = SLASH_TOKEN.exec(piece.text);
|
||||
match !== null;
|
||||
match = SLASH_TOKEN.exec(piece.text)
|
||||
) {
|
||||
const prefix = match[1] ?? "";
|
||||
if (match.index === 0 && prefix === "" && !piece.precededByBoundary) continue;
|
||||
const rawToken = match[2] ?? "";
|
||||
const resolved = matchSkillToken(rawToken, skillIds);
|
||||
if (!resolved) continue;
|
||||
|
||||
const tokenStart = match.index + prefix.length;
|
||||
const tokenEnd = match.index + match[0].length;
|
||||
const before = piece.text.slice(cursor, tokenStart);
|
||||
rewritten += before;
|
||||
outsideMatches += before;
|
||||
|
||||
const mentionText = `@${resolved.id}`;
|
||||
const mentionStart = rewritten.length;
|
||||
rewritten += mentionText;
|
||||
const mentionEnd = rewritten.length;
|
||||
rewritten += resolved.trailing;
|
||||
outsideMatches += resolved.trailing;
|
||||
|
||||
mentions.push({ id: resolved.id, start: mentionStart, end: mentionEnd, text: mentionText });
|
||||
cursor = tokenEnd;
|
||||
}
|
||||
|
||||
const tail = piece.text.slice(cursor);
|
||||
rewritten += tail;
|
||||
outsideMatches += tail;
|
||||
}
|
||||
|
||||
return {
|
||||
text: rewritten,
|
||||
hasOtherProse: hasCode || outsideMatches.trim().length > 0,
|
||||
mentions,
|
||||
};
|
||||
}
|
||||
|
||||
function fallbackSkillPromptText(ids: readonly string[]): string {
|
||||
if (ids.length === 1) return `Use the ${ids[0]} skill.`;
|
||||
return `Use the ${ids.join(", ")} skills.`;
|
||||
}
|
||||
|
||||
function buildFallbackSkillContent(rewrittenSegments: readonly RewrittenSegment[]): {
|
||||
text: string;
|
||||
skills: OpenCodeSkillAttachment[];
|
||||
} {
|
||||
const uniqueIds: string[] = [];
|
||||
const seen = new Set<string>();
|
||||
for (const segment of rewrittenSegments) {
|
||||
for (const mention of segment.mentions ?? []) {
|
||||
if (seen.has(mention.id)) continue;
|
||||
seen.add(mention.id);
|
||||
uniqueIds.push(mention.id);
|
||||
}
|
||||
}
|
||||
let fallbackInserted = false;
|
||||
const outputParts: string[] = [];
|
||||
for (const segment of rewrittenSegments) {
|
||||
if (!segment.isUserText) {
|
||||
outputParts.push(segment.text);
|
||||
} else if (!fallbackInserted) {
|
||||
outputParts.push(fallbackSkillPromptText(uniqueIds));
|
||||
fallbackInserted = true;
|
||||
}
|
||||
}
|
||||
return {
|
||||
text: outputParts.join("\n"),
|
||||
skills: uniqueIds.map((id) => ({ id })),
|
||||
};
|
||||
}
|
||||
|
||||
function buildMentionedSkillContent(rewrittenSegments: readonly RewrittenSegment[]): {
|
||||
text: string;
|
||||
skills: OpenCodeSkillAttachment[];
|
||||
} {
|
||||
const skills: OpenCodeSkillAttachment[] = [];
|
||||
const seen = new Set<string>();
|
||||
const outputParts: string[] = [];
|
||||
let offset = 0;
|
||||
|
||||
for (const segment of rewrittenSegments) {
|
||||
if (outputParts.length > 0) offset += 1;
|
||||
for (const mention of segment.mentions ?? []) {
|
||||
if (seen.has(mention.id)) continue;
|
||||
seen.add(mention.id);
|
||||
skills.push({
|
||||
id: mention.id,
|
||||
mention: {
|
||||
start: offset + mention.start,
|
||||
end: offset + mention.end,
|
||||
text: mention.text,
|
||||
},
|
||||
});
|
||||
}
|
||||
outputParts.push(segment.text);
|
||||
offset += segment.text.length;
|
||||
}
|
||||
|
||||
return {
|
||||
text: outputParts.join("\n"),
|
||||
skills,
|
||||
};
|
||||
}
|
||||
|
||||
function resolveSkillContent(
|
||||
segments: readonly PromptSegment[],
|
||||
skillIds: ReadonlySet<string>,
|
||||
options: { allowFallback: boolean },
|
||||
): { text: string; skills?: OpenCodeSkillAttachment[] } {
|
||||
if (skillIds.size === 0) {
|
||||
return { text: joinSegments(segments) };
|
||||
}
|
||||
|
||||
const rewrittenSegments: RewrittenSegment[] = [];
|
||||
let matchedAnySkill = false;
|
||||
let hasUserProse = false;
|
||||
|
||||
for (const segment of segments) {
|
||||
if (!segment.isUserText) {
|
||||
rewrittenSegments.push(segment);
|
||||
continue;
|
||||
}
|
||||
const result = rewriteUserSegment(segment.text, skillIds);
|
||||
if (result.mentions.length > 0) matchedAnySkill = true;
|
||||
if (result.hasOtherProse) hasUserProse = true;
|
||||
rewrittenSegments.push({ text: result.text, isUserText: true, mentions: result.mentions });
|
||||
}
|
||||
|
||||
if (!matchedAnySkill) {
|
||||
return { text: joinSegments(segments) };
|
||||
}
|
||||
|
||||
if (!hasUserProse && options.allowFallback) {
|
||||
return buildFallbackSkillContent(rewrittenSegments);
|
||||
}
|
||||
return buildMentionedSkillContent(rewrittenSegments);
|
||||
}
|
||||
|
||||
function stripLeadingCommandFromSegments(
|
||||
segments: readonly PromptSegment[],
|
||||
commandName: string,
|
||||
): PromptSegment[] {
|
||||
const prefixPattern = new RegExp(
|
||||
`^\\s*/${commandName.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}(?:\\s+)?`,
|
||||
);
|
||||
const result: PromptSegment[] = [];
|
||||
let stripped = false;
|
||||
for (const segment of segments) {
|
||||
if (!segment.isUserText || stripped) {
|
||||
if (segment.text.length > 0) result.push(segment);
|
||||
continue;
|
||||
}
|
||||
if (segment.text.trim().length === 0) continue;
|
||||
const remainder = segment.text.replace(prefixPattern, "");
|
||||
stripped = true;
|
||||
if (remainder.length > 0) result.push({ text: remainder, isUserText: true });
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
export async function prepareOpenCodePrompt(
|
||||
prompt: AgentPromptInput,
|
||||
loadCommands: () => Promise<readonly AgentSlashCommand[]>,
|
||||
): Promise<PreparedOpenCodePrompt> {
|
||||
const { segments, files } = splitPrompt(prompt);
|
||||
const userText = segments
|
||||
.filter((segment) => segment.isUserText)
|
||||
.map((segment) => segment.text)
|
||||
.join("\n")
|
||||
.trim();
|
||||
|
||||
// Only treat a leading /command or /compact as a slash command when the message starts with
|
||||
// user text. Preceding attachments (such as chat_history) keep the regular prompt path while
|
||||
// still scanning user text blocks for skill mentions.
|
||||
const leading = segments[0]?.isUserText ? userText.match(LEADING_SLASH_COMMAND) : null;
|
||||
if (leading?.[1] === "compact" || leading?.[1] === "summarize") {
|
||||
return { kind: "compact" };
|
||||
}
|
||||
|
||||
if (!leading && !hasSlashCandidate(segments)) {
|
||||
return { kind: "prompt", text: joinSegments(segments), files };
|
||||
}
|
||||
|
||||
const available = await loadCommands();
|
||||
const skillIds = new Set(
|
||||
available.filter((item) => item.kind === "skill").map((item) => item.name),
|
||||
);
|
||||
|
||||
if (leading) {
|
||||
const selected = available.find((item) => item.name === leading[1]);
|
||||
if (selected && selected.kind !== "skill") {
|
||||
const commandSegments = stripLeadingCommandFromSegments(segments, selected.name);
|
||||
const content = resolveSkillContent(commandSegments, skillIds, { allowFallback: false });
|
||||
return {
|
||||
kind: "command",
|
||||
name: selected.name,
|
||||
text: content.text,
|
||||
files,
|
||||
...(content.skills ? { skills: content.skills } : {}),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
const content = resolveSkillContent(segments, skillIds, { allowFallback: true });
|
||||
return {
|
||||
kind: "prompt",
|
||||
text: content.text,
|
||||
files,
|
||||
...(content.skills ? { skills: content.skills } : {}),
|
||||
};
|
||||
}
|
||||
@@ -14,12 +14,11 @@ import type {
|
||||
|
||||
import { toDiagnosticErrorMessage } from "../../diagnostic-utils.js";
|
||||
|
||||
import { renderPromptAttachmentAsText } from "../../../prompt-attachments.js";
|
||||
|
||||
import { usageFromV2 } from "./mapping.js";
|
||||
import { latestTurnMetrics } from "./metrics.js";
|
||||
|
||||
import { commands } from "./commands.js";
|
||||
import { prepareOpenCodePrompt } from "./prompt-input.js";
|
||||
|
||||
import type { V2Api } from "./api.js";
|
||||
|
||||
@@ -235,7 +234,6 @@ export class SessionTurns {
|
||||
await this.stopping;
|
||||
if (this.options.signal.aborted) throw new Error("OpenCode session is closed");
|
||||
if (this.turn) throw new Error("OpenCode session already has an active turn");
|
||||
const input = this.promptInput(prompt);
|
||||
let accept!: () => void;
|
||||
const submitted = new Promise<void>((resolve) => {
|
||||
accept = resolve;
|
||||
@@ -243,12 +241,12 @@ export class SessionTurns {
|
||||
const output =
|
||||
options?.outputSchema === undefined ? undefined : structuredOutput(options.outputSchema);
|
||||
const turn = this.createTurn(submitted, false, output);
|
||||
void this.submit(turn, input, accept, options);
|
||||
void this.submit(turn, prompt, accept, options);
|
||||
return { turnId: turn.id };
|
||||
}
|
||||
private async submit(
|
||||
turn: Turn,
|
||||
input: ReturnType<SessionTurns["promptInput"]>,
|
||||
prompt: AgentPromptInput,
|
||||
accept: () => void,
|
||||
options?: AgentRunOptions,
|
||||
) {
|
||||
@@ -265,7 +263,7 @@ export class SessionTurns {
|
||||
} catch {
|
||||
// Keep the cached baselineIdleTime if the pre-dispatch read fails transiently.
|
||||
}
|
||||
await this.dispatch(input, options, turn.output);
|
||||
await this.dispatch(turn, prompt, options, turn.output);
|
||||
if (this.turn !== turn) return;
|
||||
turn.accepted = true;
|
||||
this.revision += 1;
|
||||
@@ -472,65 +470,57 @@ export class SessionTurns {
|
||||
if (this.turn === turn) this.fail(new Error(toDiagnosticErrorMessage(error)));
|
||||
}
|
||||
}
|
||||
private preparePrompt(prompt: AgentPromptInput) {
|
||||
return prepareOpenCodePrompt(prompt, () => commands(this.options.client(), this.options.cwd));
|
||||
}
|
||||
private async dispatch(
|
||||
input: ReturnType<SessionTurns["promptInput"]>,
|
||||
turn: Turn,
|
||||
prompt: AgentPromptInput,
|
||||
options?: AgentRunOptions,
|
||||
output?: ReturnType<typeof structuredOutput>,
|
||||
) {
|
||||
const command = input.text.match(/^\/([^\s]+)(?:\s+([\s\S]*))?$/);
|
||||
if (command?.[1] === "compact" || command?.[1] === "summarize") {
|
||||
const prepared = await this.preparePrompt(prompt);
|
||||
if (this.turn !== turn) return;
|
||||
if (prepared.kind === "compact") {
|
||||
await this.options.client().session.compact({ sessionID: this.options.id });
|
||||
return;
|
||||
}
|
||||
const selected = command
|
||||
? (await commands(this.options.client(), this.options.cwd)).find(
|
||||
(item) => item.name === command[1],
|
||||
)
|
||||
: undefined;
|
||||
if (selected && selected.kind !== "skill") {
|
||||
if (prepared.kind === "command") {
|
||||
await this.options.client().session.command({
|
||||
sessionID: this.options.id,
|
||||
name: selected.name,
|
||||
text: command?.[2] ?? "",
|
||||
files: input.files,
|
||||
name: prepared.name,
|
||||
text: prepared.text,
|
||||
files: prepared.files,
|
||||
...(prepared.skills ? { skills: prepared.skills } : {}),
|
||||
});
|
||||
return;
|
||||
}
|
||||
await this.options.client().session.prompt({
|
||||
sessionID: this.options.id,
|
||||
...input,
|
||||
...(selected?.kind === "skill"
|
||||
? {
|
||||
skills: [{ id: selected.name }],
|
||||
text: command?.[2] ?? `Use the ${selected.name} skill.`,
|
||||
}
|
||||
: {}),
|
||||
text: prepared.text,
|
||||
files: prepared.files,
|
||||
...(prepared.skills ? { skills: prepared.skills } : {}),
|
||||
metadata: {
|
||||
...(options?.clientMessageId ? { paseoClientMessageId: options.clientMessageId } : {}),
|
||||
...(output ? { paseoOutputSchema: output.schema } : {}),
|
||||
},
|
||||
});
|
||||
}
|
||||
private promptInput(prompt: AgentPromptInput) {
|
||||
if (typeof prompt === "string") return { text: prompt, files: [] };
|
||||
const text: string[] = [];
|
||||
const files: Array<{ uri: string }> = [];
|
||||
for (const part of prompt) {
|
||||
if (part.type === "text") text.push(part.text);
|
||||
else if (part.type === "image")
|
||||
files.push({ uri: `data:${part.mimeType};base64,${part.data}` });
|
||||
else text.push(renderPromptAttachmentAsText(part));
|
||||
}
|
||||
return { text: text.join("\n"), files };
|
||||
}
|
||||
async steerActiveTurn(
|
||||
prompt: AgentPromptInput,
|
||||
options: SteerActiveTurnOptions,
|
||||
): Promise<SteerResult> {
|
||||
if (this.turn?.id !== options.expectedTurnId || this.stopping) return { status: "unavailable" };
|
||||
const prepared = await this.preparePrompt(prompt);
|
||||
// Commands (including compact/summarize) cannot be steered into a running turn; let
|
||||
// AgentManager replace the turn so dispatch() executes them. Skills steer natively.
|
||||
if (prepared.kind !== "prompt") return { status: "unavailable" };
|
||||
if (this.turn?.id !== options.expectedTurnId || this.stopping) return { status: "unavailable" };
|
||||
await this.options.client().session.prompt({
|
||||
sessionID: this.options.id,
|
||||
...this.promptInput(prompt),
|
||||
text: prepared.text,
|
||||
files: prepared.files,
|
||||
...(prepared.skills ? { skills: prepared.skills } : {}),
|
||||
delivery: "steer",
|
||||
metadata: options.clientMessageId
|
||||
? { paseoClientMessageId: options.clientMessageId }
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { describe, expect, test } from "vitest";
|
||||
import { daemonLaunchEnvironment } from "./config-environment.js";
|
||||
|
||||
describe("daemonLaunchEnvironment AppImage sanitization", () => {
|
||||
describe("daemonLaunchEnvironment", () => {
|
||||
const appDir = "/tmp/.mount_Paseo-abcdef";
|
||||
|
||||
test("strips AppImage runtime variables in both managed and deployment modes", () => {
|
||||
@@ -47,6 +47,40 @@ describe("daemonLaunchEnvironment AppImage sanitization", () => {
|
||||
}
|
||||
});
|
||||
|
||||
test.each(["Paseo.desktop", "paseo-desktop.desktop"])(
|
||||
"keeps the desktop identity %s out of a Linux managed daemon",
|
||||
(identity) => {
|
||||
const inputEnv = {
|
||||
CHROME_DESKTOP: identity,
|
||||
PASEO_DESKTOP_SANDBOX_REASON: "user namespaces available",
|
||||
PATH: "/usr/bin",
|
||||
};
|
||||
const result = daemonLaunchEnvironment({
|
||||
env: inputEnv,
|
||||
home: "/home/user/.paseo",
|
||||
mode: "managed",
|
||||
desktopManaged: true,
|
||||
platform: "linux",
|
||||
});
|
||||
|
||||
expect(result.CHROME_DESKTOP).toBeUndefined();
|
||||
expect(result.PASEO_DESKTOP_SANDBOX_REASON).toBeUndefined();
|
||||
expect(result.PATH).toBe("/usr/bin");
|
||||
expect(result.PASEO_DESKTOP_MANAGED).toBe("1");
|
||||
expect(inputEnv.CHROME_DESKTOP).toBe(identity);
|
||||
},
|
||||
);
|
||||
|
||||
test("preserves an unrelated Chromium desktop identity", () => {
|
||||
const result = daemonLaunchEnvironment({
|
||||
env: { CHROME_DESKTOP: "chromium.desktop" },
|
||||
home: "/home/user/.paseo",
|
||||
mode: "deployment",
|
||||
platform: "linux",
|
||||
});
|
||||
expect(result.CHROME_DESKTOP).toBe("chromium.desktop");
|
||||
});
|
||||
|
||||
test("preserves user ARGV0 without APPIMAGE or APPDIR", () => {
|
||||
const result = daemonLaunchEnvironment({
|
||||
env: {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { stripAppImageRuntimeEnv } from "./paseo-env.js";
|
||||
import { stripLinuxDesktopRuntimeEnv } from "./paseo-env.js";
|
||||
|
||||
// Daemon configuration inputs. General provider credentials and executable/runtime
|
||||
// controls remain available to managed launches and their agent processes.
|
||||
@@ -90,7 +90,7 @@ export function daemonLaunchEnvironment(input: {
|
||||
}
|
||||
delete env.PASEO_HOST;
|
||||
delete env.PASEO_DESKTOP_MANAGED;
|
||||
stripAppImageRuntimeEnv(env, { platform: input.platform });
|
||||
stripLinuxDesktopRuntimeEnv(env, { platform: input.platform });
|
||||
env.PASEO_HOME = input.home;
|
||||
if (input.desktopManaged) env.PASEO_DESKTOP_MANAGED = "1";
|
||||
return env;
|
||||
|
||||
@@ -159,17 +159,25 @@ function sseChunk(delta: Record<string, unknown>, finishReason: string | null):
|
||||
* An OpenAI-compatible model that calls OMP's `ask` tool once with `html`, then
|
||||
* replies with the tool's result so the test can read what OMP received.
|
||||
*/
|
||||
async function startScriptedAskModel(html: string): Promise<ScriptedModel> {
|
||||
async function startScriptedModel(options: {
|
||||
askHtml?: string;
|
||||
onSystemPrompt?: (text: string) => void;
|
||||
}): Promise<ScriptedModel> {
|
||||
const server: Server = createServer((request, response) => {
|
||||
void readBody(request).then((body) => {
|
||||
const payload = JSON.parse(body || "{}") as {
|
||||
tools?: Array<{ function?: { name?: string } }>;
|
||||
messages?: Array<{ role?: string; content?: unknown }>;
|
||||
};
|
||||
const systemPrompt = payload.messages
|
||||
?.filter((message) => message.role === "system")
|
||||
.map((message) => message.content)
|
||||
.join("\n");
|
||||
options.onSystemPrompt?.(systemPrompt ?? "");
|
||||
const toolMessage = payload.messages?.find((message) => message.role === "tool");
|
||||
const offersAsk = payload.tools?.some((tool) => tool.function?.name === "ask") ?? false;
|
||||
response.writeHead(200, { "content-type": "text/event-stream" });
|
||||
if (!toolMessage && offersAsk) {
|
||||
if (options.askHtml !== undefined && !toolMessage && offersAsk) {
|
||||
response.write(
|
||||
sseChunk(
|
||||
{
|
||||
@@ -179,7 +187,7 @@ async function startScriptedAskModel(html: string): Promise<ScriptedModel> {
|
||||
index: 0,
|
||||
id: "call_ask_1",
|
||||
type: "function",
|
||||
function: { name: "ask", arguments: JSON.stringify({ html }) },
|
||||
function: { name: "ask", arguments: JSON.stringify({ html: options.askHtml }) },
|
||||
},
|
||||
],
|
||||
},
|
||||
@@ -382,6 +390,41 @@ async function contextWindowUsedTokens(client: DaemonClient, agentId: string) {
|
||||
}
|
||||
|
||||
describe("daemon E2E (real OMP)", () => {
|
||||
test(
|
||||
"appends Paseo instructions to the discovered OMP workspace prompt",
|
||||
async () => {
|
||||
const prompts: string[] = [];
|
||||
const model = await startScriptedModel({ onSystemPrompt: (text) => prompts.push(text) });
|
||||
try {
|
||||
const harness = await createHarness({
|
||||
ompHome: createOfflineOmpHome({ baseUrl: model.baseUrl }),
|
||||
});
|
||||
try {
|
||||
const configDir = path.join(harness.cwd, ".omp");
|
||||
mkdirSync(configDir);
|
||||
writeFileSync(path.join(configDir, "APPEND_SYSTEM.md"), "OMP_WORKSPACE_PROMPT");
|
||||
const agent = await harness.client.createAgent({
|
||||
cwd: harness.cwd,
|
||||
title: "system prompts",
|
||||
provider: "omp",
|
||||
model: "offline/offline-1",
|
||||
systemPrompt: "PASEO_APPEND_PROMPT",
|
||||
});
|
||||
await harness.client.sendMessage(agent.id, "Say hi.");
|
||||
const finish = await harness.client.waitForFinish(agent.id, TIMEOUT_MS);
|
||||
expect(finish.status).toBe("idle");
|
||||
expect(prompts).toEqual([expect.stringContaining("PASEO_APPEND_PROMPT")]);
|
||||
expect(prompts[0]?.includes("OMP_WORKSPACE_PROMPT")).toBe(true);
|
||||
} finally {
|
||||
await closeHarness(harness);
|
||||
}
|
||||
} finally {
|
||||
await model.close();
|
||||
}
|
||||
},
|
||||
TIMEOUT_MS,
|
||||
);
|
||||
|
||||
test(
|
||||
"an idle out-of-band follow-up starts a turn",
|
||||
async () => {
|
||||
@@ -552,7 +595,7 @@ describe("daemon E2E (real OMP)", () => {
|
||||
"an OMP 19.1+ HTML ask form is answered from the question card",
|
||||
async (context) => {
|
||||
await skipUnlessOmpSendsForms(context);
|
||||
const model = await startScriptedAskModel(COLOR_FORM);
|
||||
const model = await startScriptedModel({ askHtml: COLOR_FORM });
|
||||
const harness = await createHarness({
|
||||
ompHome: createOfflineOmpHome({ baseUrl: model.baseUrl }),
|
||||
});
|
||||
@@ -592,7 +635,7 @@ describe("daemon E2E (real OMP)", () => {
|
||||
"an OMP 19.1+ HTML ask that times out in OMP closes its question card",
|
||||
async (context) => {
|
||||
await skipUnlessOmpSendsForms(context);
|
||||
const model = await startScriptedAskModel(COLOR_FORM);
|
||||
const model = await startScriptedModel({ askHtml: COLOR_FORM });
|
||||
const harness = await createHarness({
|
||||
ompHome: createOfflineOmpHome({ baseUrl: model.baseUrl, askTimeoutSeconds: 2 }),
|
||||
});
|
||||
|
||||
@@ -66,6 +66,15 @@ describe("paseo env contract", () => {
|
||||
expect(env.PATH).toBe("/custom/bin");
|
||||
});
|
||||
|
||||
test.runIf(process.platform === "linux")("strips Paseo desktop metadata after overlays", () => {
|
||||
const env = createExternalProcessEnv(baseEnv, {
|
||||
CHROME_DESKTOP: "Paseo.desktop",
|
||||
PASEO_DESKTOP_SANDBOX_REASON: "user namespaces available",
|
||||
});
|
||||
expect(env.CHROME_DESKTOP).toBeUndefined();
|
||||
expect(env.PASEO_DESKTOP_SANDBOX_REASON).toBeUndefined();
|
||||
});
|
||||
|
||||
test("applies non-control overlays to external process env", () => {
|
||||
const env = createExternalProcessEnv(baseEnv, { PATH: "/custom/bin" }, { CUSTOM: "value" });
|
||||
|
||||
|
||||
@@ -89,6 +89,21 @@ export function stripAppImageRuntimeEnv(
|
||||
}
|
||||
}
|
||||
|
||||
/** Keep Linux launcher metadata in the desktop process that owns it. */
|
||||
export function stripLinuxDesktopRuntimeEnv(
|
||||
env: ProcessEnvRecord,
|
||||
options?: { platform?: NodeJS.Platform },
|
||||
): void {
|
||||
const platform = options?.platform ?? process.platform;
|
||||
if (platform !== "linux") return;
|
||||
|
||||
if (env.CHROME_DESKTOP === "Paseo.desktop" || env.CHROME_DESKTOP === "paseo-desktop.desktop") {
|
||||
delete env.CHROME_DESKTOP;
|
||||
}
|
||||
delete env.PASEO_DESKTOP_SANDBOX_REASON;
|
||||
stripAppImageRuntimeEnv(env, { platform });
|
||||
}
|
||||
|
||||
function buildInternalProcessEnv<T extends ProcessEnvRecord>(baseEnv: T): T {
|
||||
return { ...baseEnv };
|
||||
}
|
||||
@@ -101,7 +116,7 @@ function buildExternalProcessEnv(
|
||||
for (const key of RUNTIME_CONTROL_ENV_KEYS) {
|
||||
delete sanitized[key];
|
||||
}
|
||||
stripAppImageRuntimeEnv(sanitized);
|
||||
stripLinuxDesktopRuntimeEnv(sanitized);
|
||||
for (const [key, value] of Object.entries(sanitized)) {
|
||||
if (value === undefined) {
|
||||
delete sanitized[key];
|
||||
|
||||
@@ -7,10 +7,11 @@ import {
|
||||
import {
|
||||
createExternalCommandProcessEnv,
|
||||
stripAppImageRuntimeEnv,
|
||||
stripLinuxDesktopRuntimeEnv,
|
||||
type ProcessEnvRecord,
|
||||
} from "../server/paseo-env.js";
|
||||
|
||||
export { stripAppImageRuntimeEnv };
|
||||
export { stripAppImageRuntimeEnv, stripLinuxDesktopRuntimeEnv };
|
||||
|
||||
interface ExternalEnvOptions {
|
||||
baseEnv?: ProcessEnvRecord;
|
||||
|
||||
Reference in New Issue
Block a user