Compare commits

..
Author SHA1 Message Date
paseo-bot[bot] 765aec33e5 fix(desktop): keep Paseo window identity out of child processes (#12040)
Linux child processes inherited Paseo’s desktop file name and could appear under Paseo in the window manager. Strip launcher metadata when preparing the child environment so the desktop keeps its own identity.

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-12-05 14:43:15 +00:00
Mohamed Boudra 073743647a fix(app): keep a panel's render error inside that panel (#11338)
* fix(app): keep a panel's render error inside that panel

A render exception in any workspace panel, in the explorer or a split
pane, had no boundary between it and the root error boundary, so it
replaced the whole app with the root error screen. A workspace saved
with that panel selected took the app down again on every open.

The plugin surface boundary already contained errors for plugin
surfaces. Its error-catching core is now a shared RenderErrorBoundary,
and the panel host wraps every mounted panel in it. A failed panel
shows the error with a Retry button; the other panels, the chat, the
sidebar and workspace switching keep working. Plugin surfaces keep
their own "Plugin failed" state because their boundary sits inside the
panel and catches first.

* fix(app): contain panel render errors in every panel host

The boundary now lives in WorkspacePaneContent, so the compact center
pane and sheet tabs get it along with the explorer and split panes.

* test(app): cover panel render errors in a real browser

Replace the JSDOM tests with a browser test on WorkspacePaneContent, the
component every panel host mounts through.
2026-12-05 21:31:59 +07:00
Mohamed Boudra 6b3b349c8b refactor(app): name platform capabilities instead of branching on isNative/isWeb (#12144)
* refactor(app): name platform capabilities instead of branching on isNative/isWeb

Shared app code answers "does this target have a software keyboard / use
bottom sheets / hold-to-drag / haptics / desktop resource budgets / masked
effects" through named capabilities rather than raw platform checks. Each
capability evaluates to the same answer as the check it replaces on web,
Electron, iOS, and Android; no behavior changes on shipping targets.

- keyboard: hasSoftwareKeyboard, next to usesDesktopBindings and
  supportsConfigurableComposerSendKeys
- constants/presentation, resource-budget, touch-timing: resolvers with
  unit tests per target
- ResizeHandle selects its interaction from finePointer and isWeb
- LabelShimmer gates on supportsMaskedEffects

* fix(app): keep the workspace deck limit free of runtime platform imports

Playwright imports WORKSPACE_DECK_MAX_MOUNTED_WORKSPACES in plain Node, so its
module must not reach react-native. The resource budget now imports the
constant instead of the other way round.

* refactor(app): keep resource budget tables free of platform imports

The budget tables and resolver move to a platform-free module. The runtime
values stay in resource-budget.ts, and the workspace deck limit reads the
tables, so file viewing no longer depends on workspace screen code.
2026-12-05 21:31:09 +07:00
paseo-bot[bot]andOmer Cohen b1bb161133 fix(omp): preserve workspace prompts when appending Paseo instructions (#12037)
OMP's append flag overrides its automatic prompt file discovery. Add
Paseo's prompt through the existing extension after OMP resolves its
system prompt.

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
Co-authored-by: Omer Cohen <639682+omercnet@users.noreply.github.com>
2026-12-05 13:43:09 +00:00
Mohamed Boudra 2f1fc53cdb Load Codex composer skills inline, with attachments, and on busy turns (#12143)
* fix(codex): resolve composer skill mentions across turns, attachments, and steering

Composer autocomplete inserts enabled Codex skills as /name anywhere in a prompt, but Codex only loads a skill from structured skill input items and $name mentions at turn start. Previously, only a single leading /skill on a plain string prompt was translated; inline mentions, multiple skills, prompts carrying attachments, and steered sends reached Codex as literal /name text and never loaded the skill.

Add a dedicated Codex skill-mention resolver that scans only user text blocks with strict token boundaries (leaving file paths like /docs/api.md, images, chat_history, and text/file attachments untouched), skips skills/list when no candidate token exists, and unifies leading and inline skill resolution while keeping buildCommandPromptInput solely for /prompts:* custom prompts. In steerActiveTurn, return unavailable whenever a prompt mentions an enabled skill because codex-cli ignores skills on turn/steer, allowing AgentManager to replace the turn so the skill loads.

Fixes #5008

* fix(codex): preserve async question steering and resolve skills in custom prompts

Steer async question answers directly through submitTurnSteer so answers mentioning a /skill token still reach the running turn instead of failing with a turn-changed error, and run skill-mention resolution after expanding /prompts:* custom prompts so skills passed in custom-prompt arguments also load.

* fix(codex): keep saved prompt templates and late permission follow-ups literal

Resolve skill mentions only in user-supplied /prompts:* arguments instead of re-scanning the saved template body, and preserve synthetic permission follow-up prompts (late async question answers and plan approvals) verbatim on startTurn so they match active-turn steering behavior.
2026-12-05 20:31:13 +07:00
Mohamed Boudra 617ebbdb1a Deliver OpenCode v2 skills picked inline or while steering (#12142)
* fix(opencode): deliver OpenCode v2 skills inline and while steering

OpenCode v2 turns only matched a single leading /skill on idle dispatch and skipped slash resolution on steerActiveTurn, so inline /skill mentions, multiple skills, prompts with preceding attachments, and any skill sent while a turn was running reached OpenCode as literal text without a skills attachment.

Unify prompt preparation for dispatch and steerActiveTurn in OpenCode v2: scan user text blocks for /<skill-id> mentions with strict path-safe boundaries, attach structured skills with exact mention ranges (or fallback prose when no other user text remains), steer skills natively via delivery: 'steer', and return unavailable on steer for /compact, /summarize, and non-skill commands.

* fix(opencode): resolve skills in command args and ignore literal code

Address review findings on OpenCode v2 prompt preparation:
- Scan leading command arguments through the same skill-mention resolver and forward skills on session.command requests.
- Skip fenced code blocks and inline code spans when scanning user text for /skill mentions so shell paths inside code examples stay verbatim.

* fix(opencode): preserve subdirectory commands and attached chat history on compact

Let the OpenCode catalog match leading slash-separated command names (such as nested/docs) while keeping unmatched paths literal, and keep /compact or /summarize on the regular prompt path when attachments or chat history are present so they are never dropped.

* fix(opencode): keep leading command detection on original message boundary

Only match leading /compact, /summarize, or provider slash commands when the message starts with user text (segments[0].isUserText). Messages preceded by chat_history stay on the regular prompt path while still scanning user text blocks for /skill mentions.
2026-12-05 20:15:37 +07:00
paseo-bot[bot] c174f475c8 test(e2e): share one visit for Settings Appearance checks (#12141)
Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-12-05 12:36:07 +00:00
124 changed files with 3565 additions and 2595 deletions
@@ -19,12 +19,7 @@ import {
} from "../support/helpers/mock-agent";
import { getServerId } from "../support/helpers/server-id";
import { seedSavedSettingsHosts } from "../support/helpers/settings";
import {
expectPickerSelected,
selectWorkspaceIsolation,
submitNewWorkspaceEmpty,
} from "../support/helpers/new-workspace";
import { checkoutBranch } from "../support/helpers/workspace";
import { submitNewWorkspaceEmpty } from "../support/helpers/new-workspace";
const test = base.extend<{
seedForkWorkspace: (options: MockAgentOptions) => Promise<MockAgentWorkspace>;
@@ -181,9 +176,7 @@ test.describe("Assistant fork menu", () => {
title: "Assistant fork workspace",
initialPrompt: "emit 1 coalesced agent stream updates for assistant fork new workspace.",
model: "ten-second-stream",
repo: { withRemote: true, branches: ["main", "feature/fork-source"] },
});
checkoutBranch(session.cwd, "feature/fork-source");
await openAgentRoute(page, session);
await expectComposerVisible(page);
@@ -195,11 +188,6 @@ test.describe("Assistant fork menu", () => {
await expect(page).toHaveURL(/\/new\?.*draftId=/, { timeout: 30_000 });
await expectChatHistoryAttachment(page);
// A fork continues the source agent's work, so it starts from the branch that agent is
// on rather than the repository default a fresh workspace starts from.
await selectWorkspaceIsolation(page, "worktree");
await expectPickerSelected(page, "feature/fork-source");
await page.getByTestId("host-picker-trigger").click();
await page
.getByTestId("new-workspace-host-picker-option-secondary-assistant-fork-host")
@@ -272,10 +272,6 @@ test.afterEach(async () => {
test("Changes without a comparison base explains how to view pending changes", async ({ page }) => {
const workspace = await createWorkspaceWithManyTinyDiffs(2, "dev");
// A sole branch such as dev is the repository default. With several custom branches, no
// remote and a detached HEAD, nothing says which branch to compare against.
execFileSync("git", ["branch", "release"], { cwd: workspace.repoPath });
execFileSync("git", ["checkout", "--detach"], { cwd: workspace.repoPath, stdio: "ignore" });
await openWorkspaceChangesTree(page, workspace);
await expect(
page.getByText("Comparison base is unavailable. Select Uncommitted to view pending changes."),
@@ -588,33 +584,6 @@ test("Changes selects exact local and remote bases and retains the selection aft
);
});
test("Changes treats a worktree on the default branch as on its base and labels a local pin", async ({
page,
}, testInfo) => {
const workspace = await createWorktreeCheckedOutOnMain();
await openWorkspaceChangesTree(page, workspace);
const tree = page.getByTestId("changes-tree-panel").filter({ visible: true });
const picker = tree.getByTestId("workspace-base-branch-trigger");
await test.step("a worktree on main compares against origin and offers no feature actions", async () => {
await expect(picker).toHaveText("main");
await expectNoFeatureActions(page);
await page.screenshot({ path: testInfo.outputPath("on-base-worktree.png") });
});
await test.step("pinning local main reads as local next to origin", async () => {
await chooseBase(page, picker, "main");
await expect(picker).toHaveText("main (local)");
await expectNoFeatureActions(page);
await page.screenshot({ path: testInfo.outputPath("local-base-pinned.png") });
});
await test.step("pinning origin main drops the qualifier again", async () => {
await chooseBase(page, picker, "origin/main");
await expect(picker).toHaveText("main");
});
});
test("Changes lets a compact workspace change its base in a sheet", async ({ page }, testInfo) => {
const workspace = await createWorktreeWithCommittedDiff();
execFileSync("git", ["branch", "release"], { cwd: workspace.repoPath });
@@ -2303,27 +2272,6 @@ async function expectInSyncWithRemote(workspace: RemoteWorkspace): Promise<void>
}
// A clean main that is in sync with its remote has no git action, so the button is gone.
async function chooseBase(page: Page, picker: Locator, label: string): Promise<void> {
await picker.click();
await page
.getByTestId("combobox-desktop-container")
.getByRole("button", { name: label, exact: true })
.click();
}
// Merging, merging the base in and opening a PR only make sense on a branch off the base.
async function expectNoFeatureActions(page: Page): Promise<void> {
await expect(page.getByTestId("changes-primary-cta")).toHaveAccessibleName("Archive workspace", {
timeout: 30_000,
});
await page.getByTestId("changes-primary-cta-caret").click();
await expect(page.getByTestId("changes-primary-cta-menu")).toBeVisible();
for (const action of ["merge-branch", "merge-from-base", "pr"]) {
await expect(page.getByTestId(`changes-menu-${action}`)).toHaveCount(0);
}
await page.keyboard.press("Escape");
}
async function expectNoGitActionLeft(page: Page): Promise<void> {
await expect(page.getByTestId("changes-primary-cta")).toBeHidden({ timeout: 30_000 });
}
@@ -2469,34 +2417,6 @@ async function createWorktreeWithCommittedDiff(): Promise<DirtyWorkspace> {
return { id: created.workspace.id, repoPath: cwd };
}
// The user checks out the default branch itself in a worktree while the main checkout sits on
// other work, so the worktree is on its own base.
async function createWorktreeCheckedOutOnMain(): Promise<DirtyWorkspace> {
const repo = await createTempGitRepo("changes-on-base-", {
withRemote: true,
files: [{ path: "tracked.ts", content: "export const tracked = 1;\n" }],
});
const client = await connectSeedClient();
cleanupTasks.push({
run: async () => {
await client.close();
await repo.cleanup();
},
});
execFileSync("git", ["checkout", "-b", "unrelated"], { cwd: repo.path });
const created = await client.createWorkspace({
source: {
kind: "worktree",
cwd: repo.path,
action: "checkout",
refName: "main",
worktreeSlug: "on-main",
},
});
if (!created.workspace) throw new Error(created.error ?? "Failed to create worktree");
return { id: created.workspace.id, repoPath: created.workspace.workspaceDirectory };
}
async function createWorkspaceWithCommittedDiff(): Promise<DirtyWorkspace> {
const repo = await createTempGitRepo("changes-committed-", {
files: [{ path: "tracked.ts", content: "export const tracked = 1;\n" }],
+1 -30
View File
@@ -38,7 +38,6 @@ import {
submitNewWorkspacePrompt,
} from "../support/helpers/new-workspace";
import {
checkoutBranch,
commitLocalOnly,
createTempGitRepo,
readRepoRef,
@@ -817,34 +816,6 @@ test.describe("New workspace flow", () => {
}
});
test("branches off the repository default when the checkout is on a feature branch", async ({
page,
}) => {
const tempRepo = await createTempGitRepo("ref-default-feature-", {
withRemote: true,
branches: ["main", "feature/unrelated"],
});
try {
const originHead = readRepoRef(tempRepo.path, "refs/remotes/origin/main");
checkoutBranch(tempRepo.path, "feature/unrelated");
const featureHead = commitLocalOnly(tempRepo.path, "feature work");
const openedProject = await openWorktreeComposerForRepo(page, tempRepo.path);
await expectPickerSelected(page, "main");
const created = await createWorktreeAndRead(page, openedProject);
expect(created.branchInfo.hasAncestor(originHead)).toBe(true);
expect(created.branchInfo.hasAncestor(featureHead)).toBe(false);
expect(await readWorktreeBaseMetadata(created.workspaceDirectory)).toEqual({
baseRefName: "main",
baseRef: "refs/remotes/origin/main",
});
} finally {
await tempRepo.cleanup();
}
});
test("branches off the local ref when the local row is chosen explicitly", async ({
page,
}, testInfo) => {
@@ -893,7 +864,7 @@ test.describe("New workspace flow", () => {
// tracks gets its own row rather than silently sharing origin's. Two rows reading
// "main" is the ambiguity this whole change exists to remove.
await expectStartingRefRows(page, [
"main (upstream), default branch",
"main (upstream), upstream branch",
"main, origin branch",
]);
await expectPickerSelected(page, "main (upstream)");
@@ -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 }) => {
@@ -204,11 +204,6 @@ export async function trackForkUpstream(repoPath: string): Promise<string> {
.trim();
}
/** Leaves the checkout on `branch`, the way a user working on a feature has it. */
export function checkoutBranch(repoPath: string, branch: string): void {
execSync(`git checkout ${JSON.stringify(branch)}`, { cwd: repoPath, stdio: "ignore" });
}
export function readRepoRef(repoPath: string, ref: string): string {
return execSync(`git rev-parse ${JSON.stringify(ref)}`, { cwd: repoPath, stdio: "pipe" })
.toString()
@@ -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;
+10 -5
View File
@@ -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;
+40 -24
View File
@@ -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]);
+12 -7
View File
@@ -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,
});
+2 -1
View File
@@ -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 {
+18 -12
View File
@@ -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,
+3
View File
@@ -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";
-5
View File
@@ -471,7 +471,6 @@ interface ChangesPullRequestLinkModel extends Pick<PrHint, "forge" | "number" |
interface ChangesRepositoryToolbarModel {
baseRef: string | null;
hasRemote: boolean;
isWorktree: boolean;
branchName: string | null;
cwd: string;
@@ -500,7 +499,6 @@ interface ChangesHeaderProps {
interface BuildChangesHeaderModelInput {
baseRef: string | null;
hasRemote: boolean;
isWorktree: boolean;
branchName: string | null;
committedDescription?: string;
@@ -526,7 +524,6 @@ function buildChangesHeaderModel(input: BuildChangesHeaderModelInput): {
return {
repository: {
baseRef: input.baseRef,
hasRemote: input.hasRemote,
isWorktree: input.isWorktree,
branchName: input.branchName,
cwd: input.cwd,
@@ -675,7 +672,6 @@ function ChangesRepositoryToolbar({
workspaceId={model.workspaceId}
cwd={model.cwd}
baseRef={model.baseRef}
hasRemote={model.hasRemote}
/>
</>
) : null}
@@ -1898,7 +1894,6 @@ export function ChangesSurface({
() =>
buildChangesHeaderModel({
baseRef: baseRef ?? null,
hasRemote: status?.isGit === true && status.hasRemote,
isWorktree: isManagedWorktree(status),
branchName: currentBranchName,
committedDescription: committedDiffDescription,
+16 -110
View File
@@ -5,7 +5,8 @@ import { i18n } from "@/i18n/i18next";
import {
actionsWithoutPrimary,
buildGitActions,
readBaseBranchRelation,
isCurrentBranchBase,
canMergeIntoLocalBase,
readSyncRemotes,
readUpstreamState,
type BuildGitActionsInput,
@@ -228,106 +229,23 @@ describe("git-actions-policy", () => {
]);
});
it("reads whether the checkout is on its base from the branch the daemon resolves", () => {
// A worktree checked out on main, whose base is the origin/main it tracks.
expect(
readBaseBranchRelation({
currentBranch: "main",
baseRef: "refs/remotes/origin/main",
baseRefBranch: { branch: "main", remote: "origin", isCurrent: true },
}),
).toEqual({ isOnBaseBranch: true, canMergeLocally: false });
// A fork's main tracking upstream/main.
expect(
readBaseBranchRelation({
currentBranch: "main",
baseRef: "refs/remotes/upstream/main",
baseRefBranch: { branch: "main", remote: "upstream", isCurrent: true },
}),
).toEqual({ isOnBaseBranch: true, canMergeLocally: false });
expect(
readBaseBranchRelation({
currentBranch: "feature",
baseRef: "refs/remotes/origin/main",
baseRefBranch: { branch: "main", remote: "origin", isCurrent: false },
}),
).toEqual({ isOnBaseBranch: false, canMergeLocally: true });
// The daemon merges locally only into a local base or origin's branch.
expect(
readBaseBranchRelation({
currentBranch: "feature",
baseRef: "refs/remotes/upstream/main",
baseRefBranch: { branch: "main", remote: "upstream", isCurrent: false },
}),
).toEqual({ isOnBaseBranch: false, canMergeLocally: false });
// A release branch with no upstream only shares its name with the remote base.
expect(
readBaseBranchRelation({
currentBranch: "release",
baseRef: "refs/remotes/origin/release",
baseRefBranch: { branch: "release", remote: "origin", isCurrent: false },
}),
).toEqual({ isOnBaseBranch: false, canMergeLocally: false });
expect(
readBaseBranchRelation({
currentBranch: "feature",
baseRef: "refs/tags/v1",
baseRefBranch: null,
}),
).toEqual({ isOnBaseBranch: false, canMergeLocally: false });
});
it("reads exact local and remote base refs from daemons that predate the base branch", () => {
function legacy(currentBranch: string | null, baseRef: string) {
return readBaseBranchRelation({ currentBranch, baseRef });
}
expect(legacy("release", "refs/heads/release")).toEqual({
isOnBaseBranch: true,
canMergeLocally: false,
});
expect(legacy("release", "refs/remotes/origin/release").isOnBaseBranch).toBe(false);
expect(legacy("release", "release").isOnBaseBranch).toBe(true);
expect(legacy("release", "origin/release").isOnBaseBranch).toBe(true);
expect(legacy(null, "refs/heads/release").isOnBaseBranch).toBe(false);
expect(legacy("feature", "refs/remotes/origin/release").canMergeLocally).toBe(true);
expect(legacy("release", "refs/remotes/upstream/release").canMergeLocally).toBe(false);
});
it("offers no feature actions on a worktree checked out on its default branch", () => {
const actions = buildGitActions(
createInput({
isPaseoOwnedWorktree: true,
hasRemote: true,
...readBaseBranchRelation({
currentBranch: "main",
baseRef: "refs/remotes/origin/main",
baseRefBranch: { branch: "main", remote: "origin", isCurrent: true },
}),
baseRefLabel: "main",
aheadCount: 1,
behindBaseCount: 2,
aheadOfOrigin: 1,
behindOfOrigin: 2,
shipDefault: "merge",
}),
);
expect(actions.primary?.id).toBe("pull");
expect(actionsWithoutPrimary(actions).map((action) => action.id)).toEqual([
"push",
"pull-and-push",
"archive-workspace",
]);
it("distinguishes exact local and remote base refs and retains legacy names", () => {
expect(isCurrentBranchBase("release", "refs/heads/release")).toBe(true);
expect(isCurrentBranchBase("release", "refs/remotes/origin/release")).toBe(false);
expect(isCurrentBranchBase("release", "release")).toBe(true);
expect(isCurrentBranchBase("release", "origin/release")).toBe(true);
expect(isCurrentBranchBase(null, "refs/heads/release")).toBe(false);
expect(canMergeIntoLocalBase("release", "refs/heads/release")).toBe(false);
expect(canMergeIntoLocalBase("feature", "refs/remotes/origin/release")).toBe(true);
expect(canMergeIntoLocalBase("release", "refs/remotes/upstream/release")).toBe(false);
});
it("offers local merge when the selected local base starts with origin slash", () => {
const actions = buildGitActions(
createInput({
isPaseoOwnedWorktree: true,
...readBaseBranchRelation({
currentBranch: "release",
baseRef: "refs/heads/origin/release",
baseRefBranch: { branch: "origin/release", remote: null, isCurrent: false },
}),
isOnBaseBranch: isCurrentBranchBase("release", "refs/heads/origin/release"),
canMergeLocally: canMergeIntoLocalBase("release", "refs/heads/origin/release"),
baseRefLabel: "origin/release",
aheadCount: 1,
shipDefault: "merge",
@@ -341,11 +259,7 @@ describe("git-actions-policy", () => {
createInput({
isPaseoOwnedWorktree: true,
isOnBaseBranch: false,
canMergeLocally: readBaseBranchRelation({
currentBranch: "feature",
baseRef: "refs/remotes/upstream/release",
baseRefBranch: { branch: "release", remote: "upstream", isCurrent: false },
}).canMergeLocally,
canMergeLocally: canMergeIntoLocalBase("feature", "refs/remotes/upstream/release"),
baseRefLabel: "upstream/release",
aheadCount: 1,
behindBaseCount: 1,
@@ -363,11 +277,7 @@ describe("git-actions-policy", () => {
createInput({
isPaseoOwnedWorktree: true,
isOnBaseBranch: false,
canMergeLocally: readBaseBranchRelation({
currentBranch: "release",
baseRef: "refs/remotes/origin/release",
baseRefBranch: { branch: "release", remote: "origin", isCurrent: false },
}).canMergeLocally,
canMergeLocally: canMergeIntoLocalBase("release", "refs/remotes/origin/release"),
baseRefLabel: "release",
aheadCount: 1,
behindBaseCount: 1,
@@ -384,11 +294,7 @@ describe("git-actions-policy", () => {
const actions = buildGitActions(
createInput({
isPaseoOwnedWorktree: true,
isOnBaseBranch: readBaseBranchRelation({
currentBranch: "release",
baseRef: "refs/remotes/origin/release",
baseRefBranch: { branch: "release", remote: "origin", isCurrent: false },
}).isOnBaseBranch,
isOnBaseBranch: isCurrentBranchBase("release", "refs/remotes/origin/release"),
baseRefLabel: "release",
behindBaseCount: 1,
aheadOfOrigin: null,
+12 -43
View File
@@ -54,55 +54,22 @@ interface GitActionRuntimeState {
handler: () => void;
}
type CheckoutStatusPayload = CheckoutStatusResponse["payload"];
export interface BaseBranchRelation {
/** The checkout is on its base branch, so it has no feature to merge, update, or open a PR for. */
isOnBaseBranch: boolean;
/** Merge can go into the local branch the base stands for. */
canMergeLocally: boolean;
}
/** `baseRef` is the exact base ref (`baseRefExact`) once the status cache has normalized it. */
export function readBaseBranchRelation(
status: Pick<CheckoutStatusPayload, "currentBranch" | "baseRef" | "baseRefBranch">,
): BaseBranchRelation {
const { currentBranch, baseRefBranch } = status;
if (baseRefBranch === undefined) {
return readLegacyBaseBranchRelation(currentBranch, status.baseRef);
}
if (!currentBranch || !baseRefBranch) return { isOnBaseBranch: false, canMergeLocally: false };
return {
isOnBaseBranch: baseRefBranch.isCurrent,
// The daemon merges into a local branch it infers only from a local base or origin's branch.
canMergeLocally:
(baseRefBranch.remote === null || baseRefBranch.remote === "origin") &&
baseRefBranch.branch !== currentBranch,
};
}
// COMPAT(checkoutBaseRefBranch): added in v0.19.2, remove after 2027-06-05 once the daemon floor
// reports baseRefBranch. Older daemons send only the base ref, so its branch is read from the
// ref's spelling and a remote is assumed to be origin.
function readLegacyBaseBranchRelation(
currentBranch: string | null,
baseRef: string | null,
): BaseBranchRelation {
if (!currentBranch || !baseRef) return { isOnBaseBranch: false, canMergeLocally: false };
return {
isOnBaseBranch: isLegacyCurrentBranchBase(currentBranch, baseRef),
canMergeLocally: canMergeIntoLegacyLocalBase(currentBranch, baseRef),
};
}
function isLegacyCurrentBranchBase(currentBranch: string, baseRef: string): boolean {
export function isCurrentBranchBase(
currentBranch: string | null | undefined,
baseRef: string | null | undefined,
): boolean {
if (!currentBranch || !baseRef) return false;
if (baseRef.startsWith("refs/heads/")) return baseRef === `refs/heads/${currentBranch}`;
if (baseRef.startsWith("refs/")) return false;
// Older hosts send a display name, which cannot distinguish a local ref from its remote.
return currentBranch === baseRef.replace(/^origin\//, "");
}
function canMergeIntoLegacyLocalBase(currentBranch: string, baseRef: string): boolean {
export function canMergeIntoLocalBase(
currentBranch: string | null | undefined,
baseRef: string | null | undefined,
): boolean {
if (!currentBranch || !baseRef) return false;
if (baseRef.startsWith("refs/remotes/") && !baseRef.startsWith("refs/remotes/origin/")) {
return false;
}
@@ -110,6 +77,8 @@ function canMergeIntoLegacyLocalBase(currentBranch: string, baseRef: string): bo
return currentBranch !== localTarget;
}
type CheckoutStatusPayload = CheckoutStatusResponse["payload"];
export type GitUpstreamState = NonNullable<CheckoutStatusPayload["upstreamState"]>;
export function readUpstreamState(
+7 -4
View File
@@ -12,11 +12,11 @@ import { type CheckoutStatusPayload, useCheckoutStatusQuery } from "@/git/use-st
import { type CheckoutPrStatusPayload, useCheckoutPrStatusQuery } from "@/git/use-pr-status-query";
import {
buildGitActions,
isCurrentBranchBase,
canMergeIntoLocalBase,
narrowPullRequestState,
readBaseBranchRelation,
readSyncRemotes,
readUpstreamState,
type BaseBranchRelation,
type BuildGitActionsInput,
type GitAction,
type GitActions,
@@ -119,10 +119,10 @@ interface DeriveGitActionsStateArgs {
hasUncommittedChanges: boolean;
postShipArchiveSuggested: boolean;
isStatusLoading: boolean;
baseRef: string | undefined;
}
const NO_SYNC_REMOTES: SyncRemotes = { hasPullRemote: false, hasPushRemote: false };
const NOT_ON_A_BASE: BaseBranchRelation = { isOnBaseBranch: false, canMergeLocally: false };
interface DerivedGitActionsState extends SyncRemotes {
actionsDisabled: boolean;
@@ -173,6 +173,7 @@ function deriveGitActionsState(args: DeriveGitActionsStateArgs): DerivedGitActio
hasUncommittedChanges,
postShipArchiveSuggested,
isStatusLoading,
baseRef,
} = args;
const actionsDisabled = !isGit || Boolean(status?.error) || isStatusLoading;
const isPaseoOwnedWorktree = gitStatus?.isPaseoOwnedWorktree ?? false;
@@ -184,7 +185,8 @@ function deriveGitActionsState(args: DeriveGitActionsStateArgs): DerivedGitActio
...(gitStatus ? readSyncRemotes(gitStatus) : NO_SYNC_REMOTES),
upstream: gitStatus ? readUpstreamState(gitStatus) : "unknown",
isPaseoOwnedWorktree,
...(gitStatus ? readBaseBranchRelation(gitStatus) : NOT_ON_A_BASE),
isOnBaseBranch: isCurrentBranchBase(gitStatus?.currentBranch, baseRef),
canMergeLocally: canMergeIntoLocalBase(gitStatus?.currentBranch, baseRef),
shouldPromoteArchive: computeShouldPromoteArchive({
hasUncommittedChanges,
postShipArchiveSuggested,
@@ -640,6 +642,7 @@ export function useGitActions({
hasUncommittedChanges,
postShipArchiveSuggested,
isStatusLoading,
baseRef,
});
const {
actionsDisabled,
@@ -1,30 +0,0 @@
import { describe, expect, it } from "vitest";
import { workspaceBaseBranchLabel } from "./workspace-base-branch-label";
describe("workspaceBaseBranchLabel", () => {
it("marks a pinned local base when origin has a branch it could be confused with", () => {
expect(workspaceBaseBranchLabel("refs/heads/main", { hasRemote: true })).toBe("main (local)");
expect(workspaceBaseBranchLabel("refs/remotes/origin/main", { hasRemote: true })).toBe("main");
});
it("keeps a local base unmarked in a repository without origin", () => {
expect(workspaceBaseBranchLabel("refs/heads/main", { hasRemote: false })).toBe("main");
});
it("names the remote of a base on another remote", () => {
expect(workspaceBaseBranchLabel("refs/remotes/upstream/main", { hasRemote: true })).toBe(
"upstream/main",
);
});
it("keeps a local branch whose name starts with origin slash intact", () => {
expect(workspaceBaseBranchLabel("refs/heads/origin/release", { hasRemote: true })).toBe(
"origin/release (local)",
);
});
it("reads a legacy bare base name as is", () => {
expect(workspaceBaseBranchLabel("main", { hasRemote: true })).toBe("main");
});
});
@@ -1,18 +0,0 @@
/**
* How the Changes toolbar names a worktree's base. Origin's branches drop the "origin/" prefix, so
* a local base is marked "(local)" whenever the checkout has origin; otherwise a base pinned to
* local `main` reads the same as `origin/main`. Other remotes keep their name.
*/
export function workspaceBaseBranchLabel(
baseRef: string,
checkout: { hasRemote: boolean },
): string {
if (baseRef.startsWith("refs/heads/")) {
const name = baseRef.slice("refs/heads/".length);
return checkout.hasRemote ? `${name} (local)` : name;
}
const name = baseRef.startsWith("refs/remotes/")
? baseRef.slice("refs/remotes/".length)
: baseRef;
return name.startsWith("origin/") ? name.slice("origin/".length) : name;
}
@@ -14,15 +14,12 @@ import { useHostRuntimeClient, useHostRuntimeIsConnected } from "@/runtime/host-
import { useSessionStore } from "@/stores/session-store";
import { useDebouncedValue } from "@/hooks/use-debounced-value";
import { invalidateCheckoutGitQueriesForClient } from "./query-keys";
import { workspaceBaseBranchLabel } from "./workspace-base-branch-label";
interface Props {
serverId: string;
workspaceId?: string | null;
cwd: string;
baseRef: string;
/** The checkout has origin, so a local base needs telling apart from origin's branch. */
hasRemote: boolean;
}
const ThemedLoadingSpinner = withUnistyles(LoadingSpinner);
@@ -33,13 +30,7 @@ function refLabel(ref: string): string {
return ref.replace(/^refs\/(heads|remotes)\//, "");
}
export function WorkspaceBaseBranchPicker({
serverId,
workspaceId,
cwd,
baseRef,
hasRemote,
}: Props) {
export function WorkspaceBaseBranchPicker({ serverId, workspaceId, cwd, baseRef }: Props) {
const { t } = useTranslation();
const client = useHostRuntimeClient(serverId);
const connected = useHostRuntimeIsConnected(serverId);
@@ -86,7 +77,7 @@ export function WorkspaceBaseBranchPicker({
);
const error = mutation.error ?? branches.error;
const title = t("workspace.git.diff.baseBranch.title");
const label = workspaceBaseBranchLabel(baseRef, { hasRemote });
const label = refLabel(baseRef).replace(/^origin\//, "");
const { reset, mutate, isPending } = mutation;
const { refetch, isError } = branches;
+15 -6
View File
@@ -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;
+3
View File
@@ -2435,6 +2435,9 @@ export const ar: TranslationResources = {
archiveFinishedRetry: "إعادة المحاولة ({{failed}}/{{total}})",
},
panels: {
renderError: {
title: "تعذّر عرض هذه اللوحة",
},
draft: {
newAgent: "وكيل جديد",
creatingAgent: "وكيل الخلق",
+3
View File
@@ -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",
+3
View File
@@ -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",
+3
View File
@@ -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",
+3
View File
@@ -2461,6 +2461,9 @@ export const ja: TranslationResources = {
archiveFinishedRetry: "再試行 ({{failed}}/{{total}})",
},
panels: {
renderError: {
title: "このパネルを表示できません",
},
draft: {
newAgent: "新しいエージェント",
creatingAgent: "エージェントを作成中",
+3
View File
@@ -2452,6 +2452,9 @@ export const ko: TranslationResources = {
archiveFinishedRetry: "다시 시도 ({{failed}}/{{total}})",
},
panels: {
renderError: {
title: "이 패널을 표시할 수 없습니다",
},
draft: {
newAgent: "새 에이전트",
creatingAgent: "에이전트 생성 중",
+3
View File
@@ -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",
+3
View File
@@ -2477,6 +2477,9 @@ export const ru: TranslationResources = {
archiveFinishedRetry: "Повторить ({{failed}}/{{total}})",
},
panels: {
renderError: {
title: "Не удалось показать эту панель",
},
draft: {
newAgent: "Новый агент",
creatingAgent: "Создание агента",
+3
View File
@@ -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,
});
});
});
+5 -1
View File
@@ -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;
+2 -2
View File
@@ -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);
+3 -2
View File
@@ -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) => ({
@@ -322,10 +322,10 @@ const mainRow: BranchPickerDetail = {
describe("buildPickerOptionData", () => {
it("marks origin and keeps an ahead local main explicit", () => {
const baseItem = defaultBasePickerItem(
{ currentBranch: "main", upstreamRef: "refs/remotes/origin/main" },
"fresh",
);
const baseItem = defaultBasePickerItem({
currentBranch: "main",
upstreamRef: "refs/remotes/origin/main",
});
const data = buildPickerOptionData({ branchDetails: [mainRow], prItems: [], baseItem });
expect(data.options.map((option) => option.label)).toEqual(["main", "main (local)"]);
@@ -333,10 +333,10 @@ describe("buildPickerOptionData", () => {
});
it("adds and disambiguates a fork upstream absent from branch suggestions", () => {
const baseItem = defaultBasePickerItem(
{ currentBranch: "main", upstreamRef: "refs/remotes/upstream/main" },
"fresh",
);
const baseItem = defaultBasePickerItem({
currentBranch: "main",
upstreamRef: "refs/remotes/upstream/main",
});
const data = buildPickerOptionData({
branchDetails: [{ ...mainRow, localAhead: 0, localBehind: 0 }],
prItems: [],
@@ -348,7 +348,7 @@ describe("buildPickerOptionData", () => {
});
it("marks a visible row on an old daemon when local and origin are in sync", () => {
const baseItem = defaultBasePickerItem({ currentBranch: "main" }, "fresh");
const baseItem = defaultBasePickerItem({ currentBranch: "main" });
const data = buildPickerOptionData({
branchDetails: [{ ...mainRow, localAhead: 0, localBehind: 0 }],
prItems: [],
@@ -380,76 +380,33 @@ describe("buildPickerOptionData", () => {
});
describe("defaultBasePickerItem", () => {
it("starts a fresh workspace from the repository default while the checkout is on a feature branch", () => {
it("uses origin when the current branch tracks origin", () => {
expect(
defaultBasePickerItem(
{
currentBranch: "feature/unrelated",
upstreamRef: "refs/remotes/origin/feature/unrelated",
defaultBaseRef: "refs/remotes/origin/main",
},
"fresh",
),
defaultBasePickerItem({
currentBranch: "main",
upstreamRef: "refs/remotes/origin/main",
}),
).toMatchObject({ refName: "refs/remotes/origin/main", name: "main" });
});
it("starts a fresh workspace from the repository default on a detached HEAD", () => {
it("uses the exact non-origin upstream", () => {
expect(
defaultBasePickerItem(
{ currentBranch: null, defaultBaseRef: "refs/remotes/upstream/main" },
"fresh",
),
defaultBasePickerItem({
currentBranch: "main",
upstreamRef: "refs/remotes/upstream/main",
}),
).toMatchObject({ refName: "refs/remotes/upstream/main", name: "main" });
});
it("starts a fork from the source agent's local branch", () => {
expect(
defaultBasePickerItem(
{
currentBranch: "feature/agent",
upstreamRef: "refs/remotes/origin/feature/agent",
defaultBaseRef: "refs/remotes/origin/main",
},
"fork",
),
).toMatchObject({ refName: "refs/heads/feature/agent", name: "feature/agent" });
expect(
defaultBasePickerItem(
{ currentBranch: null, defaultBaseRef: "refs/remotes/origin/main" },
"fork",
),
).toBeNull();
it("keeps old-daemon behavior local", () => {
expect(defaultBasePickerItem({ currentBranch: "main" })).toMatchObject({
refName: "refs/heads/main",
name: "main",
});
});
describe("on a daemon that predates the repository default", () => {
it("uses origin when the current branch tracks origin", () => {
expect(
defaultBasePickerItem(
{ currentBranch: "main", upstreamRef: "refs/remotes/origin/main" },
"fresh",
),
).toMatchObject({ refName: "refs/remotes/origin/main", name: "main" });
});
it("uses the exact non-origin upstream", () => {
expect(
defaultBasePickerItem(
{ currentBranch: "main", upstreamRef: "refs/remotes/upstream/main" },
"fresh",
),
).toMatchObject({ refName: "refs/remotes/upstream/main", name: "main" });
});
it("keeps old-daemon behavior local", () => {
expect(defaultBasePickerItem({ currentBranch: "main" }, "fresh")).toMatchObject({
refName: "refs/heads/main",
name: "main",
});
});
it("has no default for detached HEAD", () => {
expect(defaultBasePickerItem({ currentBranch: null }, "fresh")).toBeNull();
});
it("has no default for detached HEAD", () => {
expect(defaultBasePickerItem({ currentBranch: null })).toBeNull();
});
});
@@ -137,12 +137,8 @@ export function buildBranchPickerItems(details: readonly BranchPickerDetail[]):
export interface BaseRefCheckoutStatus {
currentBranch: string | null;
upstreamRef?: string | null;
defaultBaseRef?: string | null;
}
/** A fresh workspace starts from the repository default; a fork continues the source agent's branch. */
export type WorkspaceStart = "fresh" | "fork";
// Display only. The exact ref is what every request carries; this is just how a ref reads in
// a row label, so "refs/remotes/origin/other-name" shows as "other-name".
export function branchNameFromRef(refName: string): string {
@@ -170,41 +166,25 @@ function refQualifier(refName: string): string | null {
// row, the trigger label, and the created ref all read this; computing it twice is how the
// picker once showed local main while branching off something else.
//
// A fresh workspace starts from the base the daemon creates worktrees from when none is named,
// whatever branch the checkout happens to be on, so the app and MCP, CLI, and schedules agree. A
// fork starts from the source agent's local branch, so it keeps the agent's unpushed commits.
export function defaultBasePickerItem(
status: BaseRefCheckoutStatus,
start: WorkspaceStart,
): PickerItem | null {
if (start === "fork") {
if (!status.currentBranch) return null;
return branchPickerItem(`refs/heads/${status.currentBranch}`, "local branch");
}
if (status.defaultBaseRef) {
return branchPickerItem(status.defaultBaseRef, "default branch");
}
return legacyDefaultBasePickerItem(status);
}
function branchPickerItem(refName: string, description: string): PickerItem {
// The row reads the ref, which can name a different branch than the one checked out.
const name = branchNameFromRef(refName);
return { kind: "branch", name, refName, accessibilityLabel: `${name}, ${description}` };
}
// COMPAT(checkoutDefaultBaseRef): added in v0.19.2, remove after 2027-06-05 once the daemon floor
// sends defaultBaseRef. Older daemons report no default, so the base follows the current branch:
// its upstream when it has one, because branching off the local ref silently carries unpushed
// commits into the new workspace.
function legacyDefaultBasePickerItem(status: BaseRefCheckoutStatus): PickerItem | null {
// The upstream wins when the branch has one, because branching off the local ref silently
// carries unpushed commits into the new workspace. The daemon sends the resolved ref rather
// than a remote name, so a fork tracking upstream/main branches from upstream/main.
export function defaultBasePickerItem(status: BaseRefCheckoutStatus): PickerItem | null {
const currentBranch = status.currentBranch;
if (!currentBranch) return null;
// COMPAT(checkoutUpstreamRef): added in v0.2.6, remove after 2027-02-01 once the daemon
// floor sends upstreamRef. Daemons that predate it omit the field, which lands on the
// local ref — the base those daemons always used.
if (status.upstreamRef) return branchPickerItem(status.upstreamRef, "upstream branch");
return branchPickerItem(`refs/heads/${currentBranch}`, "local branch");
const refName = status.upstreamRef ?? `refs/heads/${currentBranch}`;
// The upstream branch can be named differently from the local one, so the row reads the
// ref rather than the branch the user happens to be on.
const name = branchNameFromRef(refName);
return {
kind: "branch",
name,
refName,
accessibilityLabel: status.upstreamRef ? `${name}, upstream branch` : `${name}, local branch`,
};
}
export function pickerItemToCheckoutRequest(
@@ -1194,12 +1194,9 @@ export function NewWorkspaceScreen({
withConnectedClient,
});
const workspaceStart = forkDraftSetup ? "fork" : "fresh";
const baseItem = useMemo(
() =>
selectedItem ??
(checkoutStatus ? defaultBasePickerItem(checkoutStatus, workspaceStart) : null),
[checkoutStatus, selectedItem, workspaceStart],
() => selectedItem ?? (checkoutStatus ? defaultBasePickerItem(checkoutStatus) : null),
[checkoutStatus, selectedItem],
);
const { options, itemById, selectedOptionId }: PickerOptionData = useMemo(
() =>
@@ -1355,7 +1352,7 @@ export function NewWorkspaceScreen({
? checkoutRequestOrExplain(
() =>
setup.checkoutRequestFor(
selectedItem ?? defaultBasePickerItem(checkoutStatusForCreate, workspaceStart),
selectedItem ?? defaultBasePickerItem(checkoutStatusForCreate),
),
t,
)
@@ -1399,7 +1396,6 @@ export function NewWorkspaceScreen({
t,
withConnectedClient,
workingDirectory,
workspaceStart,
],
);
@@ -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";
}
+1 -4
View File
@@ -54,10 +54,7 @@ export function addRunOptions(cmd: Command): Command {
)
.option("--worktree-slug <slug>", "Managed worktree path slug")
.option("--new-branch <name>", "New branch name for branch-off mode")
.option(
"--base <ref>",
"Base ref for branch-off mode. A bare branch resolves remote-first; use refs/heads/<name> for local commits",
)
.option("--base <ref>", "Base ref for branch-off mode")
.option("--branch <name>", "Existing branch for checkout-branch mode")
.option("--pr-number <n>", "Pull request or change request number for checkout-pr mode")
.option("--forge <forge>", "Forge for checkout-pr mode")
+1 -4
View File
@@ -31,10 +31,7 @@ export function createWorkspaceCommand(): Command {
)
.option("--worktree-slug <slug>", "Managed worktree path slug")
.option("--new-branch <name>", "New branch name (--mode branch-off)")
.option(
"--base <ref>",
"Base ref (--mode branch-off). A bare branch resolves remote-first; use refs/heads/<name> for local commits",
)
.option("--base <ref>", "Base ref (--mode branch-off)")
.option("--branch <name>", "Existing branch (--mode checkout-branch)")
.option("--pr-number <n>", "Pull request or change request number (--mode checkout-pr)")
.option("--forge <forge>", "Forge for --mode checkout-pr (default: source checkout)")
+1 -1
View File
@@ -23,7 +23,7 @@ export function createWorktreeCommand(): Command {
.option("--new-branch <name>", "New branch name (--mode branch-off)")
.option(
"--base <ref>",
"Base ref for new branch (--mode branch-off, defaults to repo default). A bare branch resolves remote-first; use refs/heads/<name> for local commits",
"Base ref for new branch (--mode branch-off, defaults to repo default)",
)
.option("--branch <name>", "Existing branch to check out (--mode checkout-branch)")
.option("--pr-number <n>", "Pull request number (--mode checkout-pr)")
+2 -2
View File
@@ -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];
+2 -2
View File
@@ -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,
-17
View File
@@ -6269,23 +6269,6 @@ const CheckoutStatusCommonSchema = z.object({
requestId: z.string(),
baseRefExact: z.string().nullable().optional(),
comparisonBaseRef: z.string().nullable().optional(),
// The exact ref a worktree created from this repository starts from when no base is named:
// "refs/remotes/origin/main", "refs/remotes/upstream/main" on a fork whose main tracks upstream,
// or "refs/heads/main" without a remote. It does not follow currentBranch. Null when the
// repository has no default. Absent from daemons that predate it.
defaultBaseRef: z.string().nullable().optional(),
// The branch baseRefExact stands for, as the daemon resolves it. `remote` is the remote whose
// tracking ref the base is, or null for a local branch. `isCurrent` is true when currentBranch is
// the base: the local branch the base names, or a branch whose upstream is the remote base. Null
// for a tag or commit base. Absent from daemons that predate it.
baseRefBranch: z
.object({
branch: z.string(),
remote: z.string().nullable(),
isCurrent: z.boolean(),
})
.nullable()
.optional(),
// The full ref currentBranch tracks, as git resolves `<branch>@{upstream}`:
// "refs/remotes/origin/main", "refs/remotes/upstream/main" on a fork, or a
// "refs/heads/..." ref for a branch tracking a local branch. Null when there is no
@@ -110,70 +110,6 @@ describe("wire schemas never reject unknown keys", () => {
});
});
describe("checkout status base fields", () => {
function checkoutStatus(fields: Record<string, unknown>) {
return session({
type: "checkout_status_response",
payload: {
cwd: "/repo/.paseo/worktrees/on-main",
error: null,
requestId: "request-1",
isGit: true,
isPaseoOwnedWorktree: true,
repoRoot: "/repo/.paseo/worktrees/on-main",
mainRepoRoot: "/repo",
currentBranch: "main",
isDirty: false,
baseRef: "main",
baseRefExact: "refs/remotes/origin/main",
aheadBehind: null,
aheadOfOrigin: 0,
behindOfOrigin: 0,
hasRemote: true,
remoteUrl: "https://github.com/acme/repo.git",
...fields,
},
});
}
function payloadOf(envelope: unknown): Record<string, unknown> {
const parsed = WSOutboundMessageSchema.parse(envelope);
if (parsed.type !== "session" || parsed.message.type !== "checkout_status_response") {
throw new Error("expected a checkout status response");
}
return parsed.message.payload;
}
it("reads the default base and base branch a newer daemon reports", () => {
const envelope = checkoutStatus({
defaultBaseRef: "refs/remotes/origin/main",
baseRefBranch: { branch: "main", remote: "origin", isCurrent: true },
});
expect(validateWSOutboundMessage(envelope).success).toBe(true);
expect(payloadOf(envelope)).toMatchObject({
defaultBaseRef: "refs/remotes/origin/main",
baseRefBranch: { branch: "main", remote: "origin", isCurrent: true },
});
});
it("reads a status from a daemon that predates them", () => {
const envelope = checkoutStatus({});
expect(validateWSOutboundMessage(envelope).success).toBe(true);
const payload = payloadOf(envelope);
expect(payload.defaultBaseRef).toBeUndefined();
expect(payload.baseRefBranch).toBeUndefined();
});
it("reads a repository without a default and a tag base", () => {
const envelope = checkoutStatus({ defaultBaseRef: null, baseRefBranch: null });
expect(validateWSOutboundMessage(envelope).success).toBe(true);
expect(payloadOf(envelope)).toMatchObject({ defaultBaseRef: null, baseRefBranch: null });
});
});
describe("unknown list variants degrade to one skipped element", () => {
it("keeps a timeline page when one entry has an unknown item type", () => {
const result = validateWSOutboundMessage(
@@ -94,14 +94,18 @@ export class CreateAgentLifecycleDispatch {
placement.githubPrNumber = target.prNumber;
break;
}
return this.dependencies.createPaseoWorktreeWorkflow({
...placement,
background: input.background,
callerWorkspaceId: input.callerWorkspaceId,
firstAgentContext: input.firstAgentContext,
paseoHome: this.dependencies.paseoHome,
worktreesRoot: this.dependencies.worktreesRoot,
});
const base = target.mode === "branch-off" ? target.base : undefined;
return this.dependencies.createPaseoWorktreeWorkflow(
{
...placement,
background: input.background,
callerWorkspaceId: input.callerWorkspaceId,
firstAgentContext: input.firstAgentContext,
paseoHome: this.dependencies.paseoHome,
worktreesRoot: this.dependencies.worktreesRoot,
},
base ? { resolveDefaultBranch: async () => base } : undefined,
);
}
registerAutoArchiveIfRequested(input: {
@@ -527,6 +527,7 @@ function resolveChildAgentCwd(params: {
interface CreateMcpWorktreeOptions {
input: CreatePaseoWorktreeInput;
createPaseoWorktree: CreatePaseoWorktreeWorkflowFn | undefined;
resolveDefaultBranch?: (repoRoot: string) => Promise<string>;
}
async function createMcpWorktree(
@@ -536,7 +537,10 @@ async function createMcpWorktree(
if (!options.createPaseoWorktree) {
throw new Error("Paseo worktree service is not configured");
}
return await options.createPaseoWorktree(options.input);
return await options.createPaseoWorktree(
options.input,
options.resolveDefaultBranch ? { resolveDefaultBranch: options.resolveDefaultBranch } : {},
);
} catch (error) {
throw toWorktreeRequestError(error);
}
@@ -572,6 +576,7 @@ async function resolveMcpCwd(params: {
) {
throw new Error("baseBranch is required when creating a worktree");
}
const baseBranch = worktree.baseBranch;
const createdWorktree = await createMcpWorktree({
input: {
cwd: params.cwd,
@@ -579,7 +584,6 @@ async function resolveMcpCwd(params: {
worktreeSlug: worktree.worktreeName,
branchName: worktree.branchName,
refName: worktree.refName,
baseBranch: worktree.baseBranch,
action: worktree.action,
githubPrNumber: worktree.githubPrNumber,
firstAgentContext: { prompt: params.initialPrompt },
@@ -588,6 +592,7 @@ async function resolveMcpCwd(params: {
worktreesRoot: dependencies.worktreesRoot,
},
createPaseoWorktree: dependencies.createPaseoWorktree,
resolveDefaultBranch: baseBranch ? async () => baseBranch : undefined,
});
return {
resolvedCwd: createdWorktree.workspace.cwd,
@@ -869,13 +869,16 @@ function createPaseoWorktreeForMcpTest(options: {
generateWorkspaceName: options.generateWorkspaceName ?? (async () => null),
});
return async (input) => {
return async (input, serviceOptions) => {
const result = await createPaseoWorktreeWorkflow(
{
paseoHome: options.paseoHome,
createPaseoWorktree: (workflowInput) =>
createPaseoWorktree: (workflowInput, workflowOptions) =>
createPaseoWorktreeService(workflowInput, {
github,
...(workflowOptions?.resolveDefaultBranch
? { resolveDefaultBranch: workflowOptions.resolveDefaultBranch }
: {}),
workspaceGitService,
workspaceProvisioning,
}),
@@ -895,6 +898,7 @@ function createPaseoWorktreeForMcpTest(options: {
onScriptsChanged: null,
},
input,
serviceOptions,
);
options.broadcasts.push(result.workspace.workspaceId);
options.createdWorkspaceIds?.push(result.workspace.workspaceId);
@@ -6263,7 +6263,7 @@ describe("ACPAgentSession interrupt settlement and hung-cancel retirement (#3256
expect(pids).toEqual([firstPid]);
} finally {
await session.close();
await rm(dir, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 });
await rm(dir, { recursive: true, force: true });
}
});
@@ -6357,7 +6357,7 @@ describe("ACPAgentSession interrupt settlement and hung-cancel retirement (#3256
).toBe(true);
} finally {
await Promise.all(manager.listAgents().map((item) => manager.closeAgent(item.id)));
await rm(dir, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 });
await rm(dir, { recursive: true, force: true });
}
},
);
@@ -6405,7 +6405,7 @@ describe("ACPAgentSession interrupt settlement and hung-cancel retirement (#3256
);
} finally {
await session.close();
await rm(dir, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 });
await rm(dir, { recursive: true, force: true });
}
});
@@ -6457,7 +6457,7 @@ lines.on("line", (line) => {
await vi.waitFor(() => expect(isProcessAlive(pid)).toBe(false), { timeout: 3_000 });
} finally {
await session.close();
await rm(dir, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 });
await rm(dir, { recursive: true, force: true });
}
}, 15_000);
@@ -6548,7 +6548,7 @@ lines.on("line", (line) => {
);
} finally {
await session.close();
await rm(dir, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 });
await rm(dir, { recursive: true, force: true });
}
}, 15_000);
@@ -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();
}
}
@@ -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);
});
@@ -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 }
@@ -1637,14 +1637,7 @@ function createToolCatalog(
.min(1)
.optional()
.describe("New branch name for branch-off mode."),
baseBranch: z
.string()
.trim()
.min(1)
.optional()
.describe(
"Base ref for branch-off mode. Defaults to the repository default branch. A bare branch name resolves remote-first (origin/<name>); pass refs/heads/<name> to branch from local commits.",
),
baseBranch: z.string().trim().min(1).optional().describe("Base ref for branch-off mode."),
branch: z
.string()
.trim()
+8 -1
View File
@@ -1311,17 +1311,23 @@ async function assemblePaseoDaemon({
const createPaseoWorktreeForTools = async (
input: Parameters<typeof createPaseoWorktreeWorkflow>[1],
serviceOptions?: Parameters<typeof createPaseoWorktreeWorkflow>[2],
) => {
return createPaseoWorktreeWorkflow(
{
lifecycle: pluginRuntime,
paseoHome: config.paseoHome,
worktreesRoot: config.worktreesRoot,
createPaseoWorktree: async (workflowInput) => {
createPaseoWorktree: async (workflowInput, workflowOptions) => {
return createRegisteredPaseoWorktree(workflowInput, {
lifecycle: pluginRuntime,
worktreeManagers: pluginRuntime,
github,
...(workflowOptions?.resolveDefaultBranch
? {
resolveDefaultBranch: workflowOptions.resolveDefaultBranch,
}
: {}),
workspaceGitService,
workspaceProvisioning,
});
@@ -1352,6 +1358,7 @@ async function assemblePaseoDaemon({
onScriptsChanged: null,
},
input,
serviceOptions,
);
};
@@ -47,45 +47,6 @@ describe("checkout status projection", () => {
).toMatchObject({ forgeWeb: payload.forgeWeb });
});
test("publishes the repository default and the branch the worktree base stands for", () => {
const snapshot: WorkspaceGitRuntimeSnapshot = {
cwd: "/repo/.paseo/worktrees/on-main",
git: {
isGit: true,
repoRoot: "/repo/.paseo/worktrees/on-main",
mainRepoRoot: "/repo",
currentBranch: "main",
remoteUrl: "git@github.com:acme/repo.git",
isPaseoOwnedWorktree: true,
isDirty: false,
baseRef: "main",
baseRefExact: "refs/remotes/origin/main",
defaultBaseRef: "refs/remotes/origin/main",
baseRefBranch: { branch: "main", remote: "origin", isCurrent: true },
aheadBehind: null,
upstreamRef: "refs/remotes/origin/main",
aheadOfOrigin: 0,
behindOfOrigin: 0,
hasRemote: true,
diffStat: null,
},
forge: { featuresEnabled: true, authState: "authenticated", pullRequest: null, error: null },
};
const payload = buildCheckoutStatusPayloadFromSnapshot({
cwd: snapshot.cwd,
requestId: "req-1",
snapshot,
});
expect(
CheckoutStatusResponseSchema.parse({ type: "checkout_status_response", payload }).payload,
).toMatchObject({
defaultBaseRef: "refs/remotes/origin/main",
baseRefBranch: { branch: "main", remote: "origin", isCurrent: true },
});
});
test("includes repository identity fields on the PR status wire payload", () => {
const payload = normalizeCheckoutPrStatusPayload(
{
@@ -63,8 +63,6 @@ export function buildCheckoutStatusPayloadFromSnapshot({
baseRef: snapshot.git.baseRef,
baseRefExact: snapshot.git.baseRefExact,
comparisonBaseRef: snapshot.git.comparisonBaseRef,
defaultBaseRef: snapshot.git.defaultBaseRef,
baseRefBranch: snapshot.git.baseRefBranch,
aheadBehind: snapshot.git.aheadBehind ?? null,
upstreamRef: snapshot.git.upstreamRef ?? null,
aheadOfOrigin: snapshot.git.aheadOfOrigin ?? null,
@@ -92,8 +90,6 @@ export function buildCheckoutStatusPayloadFromSnapshot({
baseRef: snapshot.git.baseRef ?? null,
baseRefExact: snapshot.git.baseRefExact,
comparisonBaseRef: snapshot.git.comparisonBaseRef,
defaultBaseRef: snapshot.git.defaultBaseRef,
baseRefBranch: snapshot.git.baseRefBranch,
aheadBehind: snapshot.git.aheadBehind ?? null,
upstreamRef: snapshot.git.upstreamRef ?? null,
aheadOfOrigin: snapshot.git.aheadOfOrigin ?? null,
@@ -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" });
+16 -1
View File
@@ -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];

Some files were not shown because too many files have changed in this diff Show More