Compare commits

..
Author SHA1 Message Date
Mohamed Boudra 148bc0f174 fix(server): count a default-branch checkout against the ref Changes compares with
On the base branch the composer count always compared against origin/<branch>,
while the Changes diff now compares against the selected default. On a fork
whose default is upstream/main, the count included upstream commits the panel
excluded. Use the snapshot's remote comparison ref for the count, falling back
to origin/<branch> when there is none.
2026-12-05 15:38:37 +01:00
Mohamed Boudra 21d2d49a1b fix(server): keep upstream counts when the checked-out default branch moves
Since the snapshot resolves a comparison ref on the base branch, a checkout on
main has a comparison ref equal to its upstream. The ref refresh took that match
as license to reuse the base counts, but ahead/behind is deliberately null on
the base branch, so a fetch turned the upstream state into unknown and Changes
disabled Pull. Reuse the base counts only when the refresh produced them.
2026-12-05 15:33:07 +01:00
Mohamed Boudra 8ce2097629 fix(server): compare the base branch and detached HEAD against the selected default
The checkout snapshot skipped comparison resolution when the checkout sat on
its base branch or had no current branch. Status then re-resolved the display
name, so a fork whose default is upstream/main compared against origin/main
while reporting upstream/main as its default. Resolve the comparison ref once
whenever a base exists; ahead/behind and shortstat keep their own rule for
skipping counts on the base branch.
2026-12-05 15:27:57 +01:00
Mohamed Boudra 4c865ad3ee fix(server): compare an implicit base against the ref it selected
A checkout with no stored base reported its default as a ref, for
example refs/remotes/upstream/main, but turned it into the name "main"
and resolved that name again for the comparison and for Update from
base. When local main tracked a different remote than the one that
advertises the default, Changes compared against origin/main, counted
nothing behind, and Update from base left the upstream commits out.

With no stored base, the comparison and the base diff use the selected
ref. Update from base merges it when it is on a remote other than
origin, and keeps choosing the further-ahead of local and origin main
otherwise. Merging into the base and opening a PR still target the
branch name.
2026-12-05 15:19:34 +01:00
Mohamed Boudra 89156075d9 fix(server): update a fork from the base it compares against
A fork's feature checkout compared against upstream/main, which its local
main tracks, but Update from base still chose between local main and
origin/main, so it reported success without the upstream commits Changes
showed as missing. And a diff that named origin/main explicitly was
rerouted to upstream/main because the short ref was stripped to a bare
name before the tracking lookup.

Only a bare branch name now follows the remote branch its local branch
tracks, and both the comparison and Update from base use that rule.
2026-12-05 15:12:00 +01:00
Mohamed Boudra ca677c8ce9 test(app): give the no-comparison-base journey a checkout with no default
A sole local branch such as dev is now the repository default, so a
checkout on it compares against itself instead of reporting no base. Only
a detached HEAD among several custom branches with no remote leaves the
base unresolved.
2026-12-05 15:05:00 +01:00
Mohamed Boudra 45278bde21 fix(app): read the default base and base branch from the daemon
New Workspace guessed its starting ref from the checkout's upstream, so a
checkout on a feature branch preselected that feature branch, and the Git
actions regex-parsed the base ref, so a worktree checked out on main with
base refs/remotes/origin/main was treated as off its base and offered merge
and PR actions.

checkout_status now carries two optional fields from the base-ref owner:
defaultBaseRef (the ref a fresh worktree starts from) and baseRefBranch
(the branch the base stands for, its remote, and whether the checkout is
on it). A fork whose main tracks upstream/main resolves the same base for
status, diff and creation. Older apps ignore the fields; older daemons
leave them undefined and the app keeps its previous logic behind
COMPAT(checkoutDefaultBaseRef) and COMPAT(checkoutBaseRefBranch).

An agent fork still starts from the source agent's local branch. The
Changes base picker shows "main (local)" when the base is pinned to the
local branch of a checkout that has origin, since the label otherwise
drops "origin/" and both would read "main".
2026-12-05 14:56:23 +01:00
Mohamed Boudra c368daa82e fix(server): reject a blank base instead of branching from the default
A whitespace-only base was trimmed to empty and replaced with the
repository default before validation, so the request created a worktree
from a branch the caller did not choose. Only an omitted base defaults
now; a supplied one goes through the base validator, which rejects it
with "Base branch is required".
2026-12-05 13:55:24 +01:00
Mohamed Boudra cc939cdc09 fix(server): keep default base reads in the caller's Git lane
The read side resolves the repository default through the shared base
owner, which ran its Git reads with the global runner. An
observation-driven status refresh therefore submitted normal-priority
commands from the background lane. The owner now takes the caller's
runner, and checkout reads pass the one from their context.
2026-12-05 13:50:34 +01:00
Mohamed Boudra 638cf1e63b fix(server): compare against the only remote's default branch
A checkout whose only remote is not origin, on a feature branch with no
local default branch, reported its base as "main" but had no ahead or
behind count, and a base diff failed. The read side now names the
default from the same owner as creation, and a bare name that matches no
local or origin branch fell through to `git rev-parse main`, which Git
cannot resolve. Such a name now resolves the way a new worktree base
does, through the remote that has the branch.
2026-12-05 13:46:23 +01:00
Mohamed Boudra 98dd572bab refactor(server): resolve worktree bases through one conventional owner
Drop the custom fetch-refspec mapping. A base resolves through the
conventional refs/remotes/<remote>/<branch> layout, split on the longest
configured remote name, for creation, merge, and Create PR alike.

The read side now asks the same owner for the repository default branch,
by name, so a local checkout on that branch still reads as on base.

Base input is validated once at the edge:
- An empty base is rejected; callers that name none ask for the
  repository default and fail with "Unable to resolve repository default
  branch" when there is none.
- Ref expressions (@, a bare remote name, heads/..., remotes/...,
  revision suffixes) are rejected instead of freezing to a commit.
- The baseBranch alias applies only to a branch-off without a change
  request, so it can no longer replace a checkout target.

The MCP and CLI help now say a bare branch resolves remote-first and
that refs/heads/<name> branches from local commits.
2026-12-05 13:40:36 +01:00
Mohamed Boudra 47eb0ef98c test(server): retry temp dir cleanup after killing hung ACP children
On Windows a killed process can keep its working directory open for a moment
after it exits, so deleting the test directory right after the hung child is
killed failed with EBUSY. Cleanup now retries like the other process-owning
test suites.
2026-12-05 13:02:20 +01:00
Mohamed Boudra 84145a3a4c fix(server): target the fetched branch when creating a pull request
Create PR sent the tracking ref's own suffix as the forge target, so a base
stored as refs/remotes/origin/mirror/main (fetched from main) asked the forge
for mirror/main. Merge and Create PR now share one lookup of the branch a base
ref stands for, through the remote's fetch mapping; tag and commit bases are
refused before pushing.
2026-12-05 12:40:13 +01:00
Mohamed Boudra 309a6cf118 fix(server): find bare base branches through the fetch mapping
A bare base name found its remote copy by spelling the tracking ref
`refs/remotes/<remote>/<name>`, while refresh and merge read the fetch
mapping. With `release` fetched into `origin/integration`, creating from
bare `integration` started at `release` and merged into local `release`.
Lookup now asks the same fetch-mapping rule that pull request bases and
refresh use, so a tracking ref that holds another branch never stands in
for the branch the caller named.
2026-12-05 12:32:42 +01:00
Mohamed Boudra 8e0488bf75 fix(server): keep a local base whose upstream has another name
A bare base name resolved to its local branch's upstream whatever that
upstream was called. Git sets the upstream from the start point
(`git switch -c feature origin/main`), so `--base feature` started the
workspace at `origin/main` without the branch's commits, and merge into
base then targeted `main`. The upstream now stands in only when the
remote branch has the same name, which still covers fork clones whose
`main` tracks `upstream/main` and custom defaults like `dev` tracking
`origin/dev`.
2026-12-05 12:24:30 +01:00
Mohamed Boudra 4c8031704d fix(server): merge into the branch a tracking base actually fetches
Merge into base took the local target from the tracking ref's suffix.
Now that worktrees pin the tracking ref named by the fetch mapping, a
base such as `refs/remotes/origin/mirror/main` that fetches `main` merged
into a local `mirror/main` instead. The target now comes from the same
fetch-mapping lookup that refreshes the base, and merges still refuse
refs outside origin or refs several branches map to.

Test fixtures that wrote origin tracking refs without an origin remote
now configure one, since Git removes a remote's tracking refs with it.
2026-12-05 12:19:16 +01:00
Mohamed Boudra bfd5eef413 fix(server): resolve pull request branch-off bases like checkout
Branch off from a pull request built `refs/remotes/<remote>/<base>` and
force-fetched the target into it. With a renamed fetch mapping, that
pinned a ref Git never updates, or overwrote a tracking ref that the
fetch config assigns to another branch. Branch-off now uses the same
serving-remote resolution as checkout, so both pull request paths agree
on which ref tracks the base.
2026-12-05 12:11:02 +01:00
Mohamed Boudra 5a3a884377 fix(server): keep tag bases and mapped pull request bases working
Branch-only base resolution dropped the existing `--base <tag|sha>`
support. Tags and commits now resolve after every branch candidate
misses; they skip the remote refresh, compare by commit, and merge into
base refuses them.

Pull request checkout built `refs/remotes/<remote>/<base>` and refreshed
it as a tracking destination, so a custom fetch mapping such as
`release -> origin/main` force-fetched the wrong branch into the
comparison ref. Checkout now resolves the base from the serving remote's
fetch mapping. When the candidate tracking ref belongs to another remote
branch, checkout keeps only the base name and leaves that ref untouched.
2026-12-05 12:02:14 +01:00
Mohamed Boudra cc6fa498c3 fix(server): preserve worktree base tracking mappings
Use tracked custom defaults and remote fetch mappings, and fetch change request bases before recording them.
2026-12-05 12:02:14 +01:00
Mohamed BoudraandOrcun Simsek 580c75384c fix(server): create worktrees from fresh default bases
Resolve base inputs consistently before creation and persist the selected ref so comparisons follow the same branch. This is the server phase of the workspace base selection change.

Co-authored-by: Orcun Simsek <orcun@joyolabs.com>
2026-12-05 12:02:14 +01:00
124 changed files with 2595 additions and 3565 deletions
@@ -19,7 +19,12 @@ import {
} from "../support/helpers/mock-agent";
import { getServerId } from "../support/helpers/server-id";
import { seedSavedSettingsHosts } from "../support/helpers/settings";
import { submitNewWorkspaceEmpty } from "../support/helpers/new-workspace";
import {
expectPickerSelected,
selectWorkspaceIsolation,
submitNewWorkspaceEmpty,
} from "../support/helpers/new-workspace";
import { checkoutBranch } from "../support/helpers/workspace";
const test = base.extend<{
seedForkWorkspace: (options: MockAgentOptions) => Promise<MockAgentWorkspace>;
@@ -176,7 +181,9 @@ 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);
@@ -188,6 +195,11 @@ 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,6 +272,10 @@ 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."),
@@ -584,6 +588,33 @@ 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 });
@@ -2272,6 +2303,27 @@ 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 });
}
@@ -2417,6 +2469,34 @@ 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" }],
+30 -1
View File
@@ -38,6 +38,7 @@ import {
submitNewWorkspacePrompt,
} from "../support/helpers/new-workspace";
import {
checkoutBranch,
commitLocalOnly,
createTempGitRepo,
readRepoRef,
@@ -816,6 +817,34 @@ 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) => {
@@ -864,7 +893,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), upstream branch",
"main (upstream), default branch",
"main, origin branch",
]);
await expectPickerSelected(page, "main (upstream)");
@@ -112,25 +112,24 @@ test.describe("Settings sidebar scroll position", () => {
await expectSettingsSidebarScrollOffset(page, 0);
});
test("updates typography and normalizes font sizes in one Appearance visit", async ({ page }) => {
test("updates appearance without losing the detail scroll or form edits", 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);
});
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("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);
});
test("keeps the sidebar context through interface font changes", async ({ page }) => {
@@ -204,6 +204,11 @@ 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 { isWeb } from "@/constants/platform";
import { isNative, 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: workspaceDeckRetentionLimit,
maxMountedWorkspaces: resolveWorkspaceDeckRetentionLimit({ isNative }),
}),
[activeSelection, reconciliationNow, retainedSelections],
);
@@ -204,7 +204,7 @@ function WorkspaceDeck() {
currentEntries: current,
activeSelection,
now: Date.now(),
maxMountedWorkspaces: workspaceDeckRetentionLimit,
maxMountedWorkspaces: resolveWorkspaceDeckRetentionLimit({ isNative }),
}),
);
}, expirationDelay + 1);
@@ -56,7 +56,6 @@ 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";
@@ -992,7 +991,7 @@ export function CommandCenter() {
const bottomSheetListRef = useRef<BottomSheetFlatListMethods>(null);
const inputRef = useRef<EditingTextInputHandle>(null);
const bottomSheetInputRef = useRef<EditingTextInputHandle>(null);
const showBottomSheet = isCompact && usesCompactBottomSheet;
const showBottomSheet = isCompact && isNative;
const getInputHandle = useCallback(
() => (showBottomSheet ? bottomSheetInputRef.current : inputRef.current),
[showBottomSheet],
@@ -16,7 +16,6 @@ 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 {
@@ -53,7 +52,7 @@ export function DraggableListHandle({ testID, style, children }: DraggableListHa
delayMs: HANDLE_HOLD_MS,
slopPx: HANDLE_HOLD_SLOP_PX,
onArm: () => {
if (supportsTouchHaptics) void Haptics.selectionAsync().catch(() => {});
void Haptics.selectionAsync().catch(() => {});
drag();
},
})
@@ -3,7 +3,6 @@ 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";
@@ -61,8 +60,7 @@ export const LabelShimmer = memo(function LabelShimmer({
measurements,
}: LabelShimmerProps) {
const { rowSize } = measurements;
// Without an alpha-mask compositor the band would paint as a bare white bar.
const measured = supportsMaskedEffects && rowSize.width > 0 && rowSize.height > 0;
const measured = 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;
+5 -10
View File
@@ -61,13 +61,8 @@ 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 } from "@/constants/platform";
import { usesDesktopPopoverSpacing } from "@/constants/presentation";
import {
hasSoftwareKeyboard,
useHardwareKeyboardPresent,
type KeyboardInputEvent,
} from "@/keyboard";
import { isNative, isWeb } from "@/constants/platform";
import { useHardwareKeyboardPresent, type KeyboardInputEvent } from "@/keyboard";
import {
buildProviderQualifiedDescription,
buildSelectedTriggerLabel,
@@ -110,7 +105,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 = usesDesktopPopoverSpacing ? 36 : 44;
export const MODEL_PICKER_ROW_HEIGHT = isWeb ? 36 : 44;
export const MODEL_PICKER_HEADING_HEIGHT = 32;
const ThemedAlertTriangle = withUnistyles(AlertTriangle);
@@ -391,7 +386,7 @@ export function useModelBrowser({
selectedProvider,
selectedModel,
isLoading,
autoFocusSearch = !hasSoftwareKeyboard,
autoFocusSearch = isWeb,
profiles = null,
serverId = null,
}: ModelBrowserInput): ModelBrowserState {
@@ -1654,7 +1649,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 = hasSoftwareKeyboard ? "on-drag" : "none";
const MODEL_LIST_KEYBOARD_DISMISS_MODE = isNative ? "on-drag" : "none";
interface ModelBrowserKeyboardBinding {
view: ModelBrowserView;
@@ -1,52 +0,0 @@
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,8 +1,5 @@
import { describe, expect, it, vi } from "vitest";
import {
resolveResizeHandleInteraction,
startResizeHandleDrag,
} from "@/components/resize-handle-drag";
import { startResizeHandleDrag } from "@/components/resize-handle-drag";
describe("startResizeHandleDrag", () => {
it("previews pointer frames and commits only the final size", () => {
@@ -32,14 +29,3 @@ 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,24 +7,6 @@ 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;
+24 -40
View File
@@ -2,12 +2,7 @@ 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 {
resolveResizeHandleInteraction,
startResizeHandleDrag,
type ResizeHandleDrag,
} from "@/components/resize-handle-drag";
import { isWeb } from "@/constants/platform";
import { startResizeHandleDrag, type ResizeHandleDrag } from "@/components/resize-handle-drag";
import { usePointerCapabilities } from "@/hooks/pointer-capabilities";
import {
SIDEBAR_RESIZE_ACTIVATION_OFFSET,
@@ -53,7 +48,6 @@ 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);
@@ -231,12 +225,8 @@ export function ResizeHandle({
...(direction === "horizontal"
? { left: hitAreaAlignment === "end" ? 0 : -5 }
: { top: hitAreaAlignment === "end" ? 0 : -5 }),
...(isWeb
? {
cursor: direction === "horizontal" ? "col-resize" : "row-resize",
touchAction: "none",
}
: {}),
cursor: direction === "horizontal" ? "col-resize" : "row-resize",
touchAction: "none",
} as object,
],
[direction, hitAreaAlignment],
@@ -264,32 +254,6 @@ 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 && (
@@ -299,7 +263,27 @@ export function ResizeHandle({
testID={testID ? `${testID}-highlight` : undefined}
/>
)}
{separatorHitArea}
{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>
)}
</View>
);
}
@@ -1,7 +1,7 @@
import { useCallback, useEffect, useRef } from "react";
import type { GestureResponderEvent } from "react-native";
import * as Haptics from "expo-haptics";
import { supportsTouchHaptics, usesTouchLongPressHold } from "@/constants/touch-timing";
import { isWeb as platformIsWeb } from "@/constants/platform";
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 (!usesTouchLongPressHold || !drag) {
if (platformIsWeb || !drag) {
return;
}
@@ -86,7 +86,7 @@ export function useLongPressDragInteraction(input: {
dragArmedRef.current = true;
dragActivatedRef.current = true;
didLongPressRef.current = true;
if (supportsTouchHaptics) void Haptics.selectionAsync().catch(() => {});
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;
}
if (supportsTouchHaptics) void Haptics.selectionAsync().catch(() => {});
void Haptics.selectionAsync().catch(() => {});
openContextMenuAtStartPoint();
}, CONTEXT_MENU_DELAY_MS);
}, [clearTimers, drag, menuController, openContextMenuAtStartPoint]);
+7 -12
View File
@@ -22,7 +22,6 @@ 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";
@@ -90,6 +89,7 @@ import {
type TerminalResizeRequest,
} from "./terminal-resize-debouncer";
import { useIsCompactFormFactor } from "@/constants/layout";
import { isNative } from "@/constants/platform";
import { useKeyboardFocusSurface } from "@/keyboard";
import {
applyTerminalRendererReadyChange,
@@ -305,10 +305,7 @@ export function TerminalPane({
return trimmed.length > 0 ? trimmed : undefined;
}, [settings.monoFontFamily]);
const isMobile = useIsCompactFormFactor();
const showVirtualKeyBar = shouldShowTerminalVirtualKeyBar({
hasSoftwareKeyboard,
isCompact: isMobile,
});
const showVirtualKeyBar = shouldShowTerminalVirtualKeyBar({ isNative, isCompact: isMobile });
const [keyBarWidth, setKeyBarWidth] = useState(0);
const virtualKeyboardRows = resolveTerminalVirtualKeyboardRows({
isCompact: isMobile,
@@ -319,7 +316,7 @@ export function TerminalPane({
const swipeGesturesEnabled = isMobile;
const { shift: keyboardShift, style: keyboardPaddingStyle } = useKeyboardShiftStyle({
mode: "padding",
enabled: hasSoftwareKeyboard || isMobile,
enabled: isNative || isMobile,
});
const [keyboardInset, setKeyboardInset] = useState(0);
const [isKeyboardVisible, setIsKeyboardVisible] = useState(false);
@@ -611,7 +608,7 @@ export function TerminalPane({
const handleKeyboardChange = useCallback(
(nextShift: number) => {
setKeyboardInset(hasSoftwareKeyboard || isMobile ? nextShift : 0);
setKeyboardInset(isNative || isMobile ? nextShift : 0);
setIsKeyboardVisible(nextShift > 0);
pulseKeyboardRefits();
},
@@ -1183,10 +1180,10 @@ export function TerminalPane({
emulatorRef.current?.blur();
onOpenFileExplorer();
}, [swipeGesturesEnabled, onOpenFileExplorer]);
const showPasteAction = shouldShowTerminalPasteAction({ hasSoftwareKeyboard });
const showPasteAction = shouldShowTerminalPasteAction({ isNative });
const showFloatingCopyAction = shouldShowTerminalFloatingCopyAction({
hasSelection,
hasSoftwareKeyboard,
isNative,
});
const keyboardToggleIconColor = theme.colors.foregroundMuted;
@@ -1335,9 +1332,7 @@ export function TerminalPane({
<View
style={styles.keyboardRows}
onLayout={handleKeyBarLayout}
testID={
hasSoftwareKeyboard && !isMobile ? "terminal-virtual-keyboard-native-wide" : undefined
}
testID={isNative && !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 { hasSoftwareKeyboard } from "@/keyboard";
import { isWeb } from "@/constants/platform";
import { readMeasuredWidth } from "@/hooks/use-container-width";
import {
toolbarContentSlot,
@@ -186,7 +186,7 @@ export function CompactModelSheet({
selectedProvider,
selectedModel,
isLoading,
autoFocusSearch: !hasSoftwareKeyboard && !usesBottomSheet,
autoFocusSearch: isWeb && !usesBottomSheet,
profiles,
serverId,
});
+1 -2
View File
@@ -61,7 +61,6 @@ 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 {
@@ -255,7 +254,7 @@ function resolveKeyboardPriority(isMessageInputFocused: boolean): number {
}
function resolveIsDesktopWebBreakpoint(isMobile: boolean): boolean {
return !hasSoftwareKeyboard && !isMobile;
return isWeb && !isMobile;
}
function resolveCompactLayout(override: boolean | undefined, formFactor: boolean): boolean {
+12 -18
View File
@@ -82,11 +82,8 @@ 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, isWeb } from "@/constants/platform";
import { composerMinInputHeight } from "@/constants/presentation";
import { supportsTouchHaptics } from "@/constants/touch-timing";
import { getIsElectron, isNative, isWeb } from "@/constants/platform";
import { useIsCompactFormFactor } from "@/constants/layout";
import { useComposerKeyboardScope } from "@/composer/keyboard-scope";
import { RenderProfile } from "@/utils/render-profiler";
@@ -241,9 +238,11 @@ 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 = composerMinInputHeight;
const MIN_INPUT_HEIGHT = isWeb ? MIN_INPUT_HEIGHT_DESKTOP : MIN_INPUT_HEIGHT_MOBILE;
type WebTextInputKeyPressEvent = NativeSyntheticEvent<
TextInputKeyPressEventData & {
metaKey?: boolean;
@@ -1884,7 +1883,7 @@ export const MessageInput = forwardRef<MessageInputRef, MessageInputProps>(
});
const handleLongPressSend = useCallback(() => {
if (alternateSendAction && supportsTouchHaptics) {
if (alternateSendAction && isNative) {
void Haptics.impactAsync(Haptics.ImpactFeedbackStyle.Medium).catch(() => {});
}
handleAlternateSendAction();
@@ -1911,12 +1910,12 @@ export const MessageInput = forwardRef<MessageInputRef, MessageInputProps>(
[onSelectionChangeCallback],
);
const shouldHandleKeyPress = supportsConfigurableComposerSendKeys;
const shouldSubmitOnEnter = supportsConfigurableComposerSendKeys && !isCompact;
const shouldHandleWebKeyPress = isWeb;
const shouldSubmitOnEnter = isWeb && !isCompact;
const handleDesktopKeyPress = useCallback(
(event: WebTextInputKeyPressEvent) => {
if (!shouldHandleKeyPress) return;
if (!shouldHandleWebKeyPress) return;
handleDesktopKeyPressImpl(event, {
onKeyPressCallback,
input: getComposerInputSnapshot(
@@ -1936,7 +1935,7 @@ export const MessageInput = forwardRef<MessageInputRef, MessageInputProps>(
});
},
[
shouldHandleKeyPress,
shouldHandleWebKeyPress,
onKeyPressCallback,
shouldSubmitOnEnter,
sendShortcut,
@@ -2223,19 +2222,14 @@ export const MessageInput = forwardRef<MessageInputRef, MessageInputProps>(
editable={!isDictating && !isRealtimeVoiceForCurrentAgent && !disabled}
scrollEnabled={isComposerScrollEnabled}
autoFocus={false}
onKeyPress={shouldHandleKeyPress ? handleDesktopKeyPress : undefined}
onKeyPress={shouldHandleWebKeyPress ? handleDesktopKeyPress : undefined}
onSelectionChange={handleSelectionChange}
onPasteImages={onPasteImages}
onPasteError={handlePasteError}
fullscreen={isFullscreen}
compact={isCompact}
onRenderedLinesChange={setRenderedLines}
focusHintVisible={
!isFullscreen &&
supportsConfigurableComposerSendKeys &&
!isInputFocused &&
!hasLiveText
}
focusHintVisible={!isFullscreen && isWeb && !isInputFocused && !hasLiveText}
focusInputKeys={focusInputKeys}
focusHintLabel={t("composer.input.focusHint", {
shortcut: focusInputKeys ? formatShortcut(focusInputKeys[0], getShortcutOs()) : "",
@@ -2259,7 +2253,7 @@ export const MessageInput = forwardRef<MessageInputRef, MessageInputProps>(
isRealtimeVoiceForCurrentAgent,
disabled,
isComposerScrollEnabled,
shouldHandleKeyPress,
shouldHandleWebKeyPress,
handleDesktopKeyPress,
handleSelectionChange,
onPasteImages,
-3
View File
@@ -25,9 +25,6 @@ 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__);
@@ -1,25 +0,0 @@
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,
});
});
});
@@ -1,44 +0,0 @@
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;
@@ -1,26 +0,0 @@
// 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;
}
@@ -1,15 +0,0 @@
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 },
});
});
});
@@ -1,7 +0,0 @@
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;
@@ -1,15 +0,0 @@
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,
});
});
});
@@ -1,20 +0,0 @@
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 });
const presentation = selectSourcePresentation({ size, platform: isWeb ? "web" : "native" });
if (presentation === "unsupported") return <TooLargeTextFile size={size} />;
if (isWeb && size <= MAX_EDITABLE_BYTES) return <EditableTextFile {...props} />;
return <ReadonlyTextFile {...props} presentation={presentation} />;
@@ -11,11 +11,4 @@ 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,9 +1,6 @@
import { sourceFileBudgets } from "@/constants/resource-budget";
import { resolveResourceBudgets } from "@/constants/resource-budget-tables";
export const SOURCE_PRESENTATION_BUDGETS = {
web: resolveResourceBudgets({ isNative: false }).sourceFileBudgets,
native: resolveResourceBudgets({ isNative: true }).sourceFileBudgets,
web: { highlighted: 10 * 1024 * 1024, plain: 50 * 1024 * 1024 },
native: { highlighted: 1024 * 1024, plain: 10 * 1024 * 1024 },
} as const;
export type SourcePresentation = "highlighted" | "plain" | "unsupported";
@@ -11,9 +8,9 @@ export type SourcePlatform = keyof typeof SOURCE_PRESENTATION_BUDGETS;
export function selectSourcePresentation(input: {
size: number;
platform?: SourcePlatform;
platform: SourcePlatform;
}): SourcePresentation {
const budgets = input.platform ? SOURCE_PRESENTATION_BUDGETS[input.platform] : sourceFileBudgets;
const budgets = SOURCE_PRESENTATION_BUDGETS[input.platform];
if (input.size <= budgets.highlighted) return "highlighted";
if (input.size <= budgets.plain) return "plain";
return "unsupported";
+5
View File
@@ -471,6 +471,7 @@ interface ChangesPullRequestLinkModel extends Pick<PrHint, "forge" | "number" |
interface ChangesRepositoryToolbarModel {
baseRef: string | null;
hasRemote: boolean;
isWorktree: boolean;
branchName: string | null;
cwd: string;
@@ -499,6 +500,7 @@ interface ChangesHeaderProps {
interface BuildChangesHeaderModelInput {
baseRef: string | null;
hasRemote: boolean;
isWorktree: boolean;
branchName: string | null;
committedDescription?: string;
@@ -524,6 +526,7 @@ function buildChangesHeaderModel(input: BuildChangesHeaderModelInput): {
return {
repository: {
baseRef: input.baseRef,
hasRemote: input.hasRemote,
isWorktree: input.isWorktree,
branchName: input.branchName,
cwd: input.cwd,
@@ -672,6 +675,7 @@ function ChangesRepositoryToolbar({
workspaceId={model.workspaceId}
cwd={model.cwd}
baseRef={model.baseRef}
hasRemote={model.hasRemote}
/>
</>
) : null}
@@ -1894,6 +1898,7 @@ export function ChangesSurface({
() =>
buildChangesHeaderModel({
baseRef: baseRef ?? null,
hasRemote: status?.isGit === true && status.hasRemote,
isWorktree: isManagedWorktree(status),
branchName: currentBranchName,
committedDescription: committedDiffDescription,
+110 -16
View File
@@ -5,8 +5,7 @@ import { i18n } from "@/i18n/i18next";
import {
actionsWithoutPrimary,
buildGitActions,
isCurrentBranchBase,
canMergeIntoLocalBase,
readBaseBranchRelation,
readSyncRemotes,
readUpstreamState,
type BuildGitActionsInput,
@@ -229,23 +228,106 @@ describe("git-actions-policy", () => {
]);
});
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("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("offers local merge when the selected local base starts with origin slash", () => {
const actions = buildGitActions(
createInput({
isPaseoOwnedWorktree: true,
isOnBaseBranch: isCurrentBranchBase("release", "refs/heads/origin/release"),
canMergeLocally: canMergeIntoLocalBase("release", "refs/heads/origin/release"),
...readBaseBranchRelation({
currentBranch: "release",
baseRef: "refs/heads/origin/release",
baseRefBranch: { branch: "origin/release", remote: null, isCurrent: false },
}),
baseRefLabel: "origin/release",
aheadCount: 1,
shipDefault: "merge",
@@ -259,7 +341,11 @@ describe("git-actions-policy", () => {
createInput({
isPaseoOwnedWorktree: true,
isOnBaseBranch: false,
canMergeLocally: canMergeIntoLocalBase("feature", "refs/remotes/upstream/release"),
canMergeLocally: readBaseBranchRelation({
currentBranch: "feature",
baseRef: "refs/remotes/upstream/release",
baseRefBranch: { branch: "release", remote: "upstream", isCurrent: false },
}).canMergeLocally,
baseRefLabel: "upstream/release",
aheadCount: 1,
behindBaseCount: 1,
@@ -277,7 +363,11 @@ describe("git-actions-policy", () => {
createInput({
isPaseoOwnedWorktree: true,
isOnBaseBranch: false,
canMergeLocally: canMergeIntoLocalBase("release", "refs/remotes/origin/release"),
canMergeLocally: readBaseBranchRelation({
currentBranch: "release",
baseRef: "refs/remotes/origin/release",
baseRefBranch: { branch: "release", remote: "origin", isCurrent: false },
}).canMergeLocally,
baseRefLabel: "release",
aheadCount: 1,
behindBaseCount: 1,
@@ -294,7 +384,11 @@ describe("git-actions-policy", () => {
const actions = buildGitActions(
createInput({
isPaseoOwnedWorktree: true,
isOnBaseBranch: isCurrentBranchBase("release", "refs/remotes/origin/release"),
isOnBaseBranch: readBaseBranchRelation({
currentBranch: "release",
baseRef: "refs/remotes/origin/release",
baseRefBranch: { branch: "release", remote: "origin", isCurrent: false },
}).isOnBaseBranch,
baseRefLabel: "release",
behindBaseCount: 1,
aheadOfOrigin: null,
+43 -12
View File
@@ -54,22 +54,55 @@ interface GitActionRuntimeState {
handler: () => void;
}
export function isCurrentBranchBase(
currentBranch: string | null | undefined,
baseRef: string | null | undefined,
): boolean {
if (!currentBranch || !baseRef) return false;
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 {
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\//, "");
}
export function canMergeIntoLocalBase(
currentBranch: string | null | undefined,
baseRef: string | null | undefined,
): boolean {
if (!currentBranch || !baseRef) return false;
function canMergeIntoLegacyLocalBase(currentBranch: string, baseRef: string): boolean {
if (baseRef.startsWith("refs/remotes/") && !baseRef.startsWith("refs/remotes/origin/")) {
return false;
}
@@ -77,8 +110,6 @@ export function canMergeIntoLocalBase(
return currentBranch !== localTarget;
}
type CheckoutStatusPayload = CheckoutStatusResponse["payload"];
export type GitUpstreamState = NonNullable<CheckoutStatusPayload["upstreamState"]>;
export function readUpstreamState(
+4 -7
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,7 +173,6 @@ function deriveGitActionsState(args: DeriveGitActionsStateArgs): DerivedGitActio
hasUncommittedChanges,
postShipArchiveSuggested,
isStatusLoading,
baseRef,
} = args;
const actionsDisabled = !isGit || Boolean(status?.error) || isStatusLoading;
const isPaseoOwnedWorktree = gitStatus?.isPaseoOwnedWorktree ?? false;
@@ -185,8 +184,7 @@ function deriveGitActionsState(args: DeriveGitActionsStateArgs): DerivedGitActio
...(gitStatus ? readSyncRemotes(gitStatus) : NO_SYNC_REMOTES),
upstream: gitStatus ? readUpstreamState(gitStatus) : "unknown",
isPaseoOwnedWorktree,
isOnBaseBranch: isCurrentBranchBase(gitStatus?.currentBranch, baseRef),
canMergeLocally: canMergeIntoLocalBase(gitStatus?.currentBranch, baseRef),
...(gitStatus ? readBaseBranchRelation(gitStatus) : NOT_ON_A_BASE),
shouldPromoteArchive: computeShouldPromoteArchive({
hasUncommittedChanges,
postShipArchiveSuggested,
@@ -642,7 +640,6 @@ export function useGitActions({
hasUncommittedChanges,
postShipArchiveSuggested,
isStatusLoading,
baseRef,
});
const {
actionsDisabled,
@@ -0,0 +1,30 @@
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");
});
});
@@ -0,0 +1,18 @@
/**
* 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,12 +14,15 @@ 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);
@@ -30,7 +33,13 @@ function refLabel(ref: string): string {
return ref.replace(/^refs\/(heads|remotes)\//, "");
}
export function WorkspaceBaseBranchPicker({ serverId, workspaceId, cwd, baseRef }: Props) {
export function WorkspaceBaseBranchPicker({
serverId,
workspaceId,
cwd,
baseRef,
hasRemote,
}: Props) {
const { t } = useTranslation();
const client = useHostRuntimeClient(serverId);
const connected = useHostRuntimeIsConnected(serverId);
@@ -77,7 +86,7 @@ export function WorkspaceBaseBranchPicker({ serverId, workspaceId, cwd, baseRef
);
const error = mutation.error ?? branches.error;
const title = t("workspace.git.diff.baseBranch.title");
const label = refLabel(baseRef).replace(/^origin\//, "");
const label = workspaceBaseBranchLabel(baseRef, { hasRemote });
const { reset, mutate, isPending } = mutation;
const { refetch, isError } = branches;
+6 -15
View File
@@ -23,12 +23,7 @@ import {
isChecksHiddenByLegacyRowItem,
type SidebarRowItems,
} from "@/components/sidebar/display-preferences/row-items";
import {
initialContentFontSize,
initialUiBaseFontSize,
resolvePresentationCapabilities,
usesMobileContentFontMigration,
} from "@/constants/presentation";
import { isNative } from "@/constants/platform";
import {
DEFAULT_CONTENT_MAX_WIDTH,
FONT_SIZE,
@@ -65,19 +60,17 @@ 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 resolvePresentationCapabilities({ isNative: native, isWeb: !native })
.initialUiBaseFontSize;
return native ? 15 : FONT_SIZE.base;
}
export const DEFAULT_UI_BASE_FONT_SIZE = initialUiBaseFontSize;
export const DEFAULT_UI_BASE_FONT_SIZE = defaultUiBaseFontSize(isNative);
export const MIN_UI_BASE_FONT_SIZE = 10;
export const MAX_UI_BASE_FONT_SIZE = 21;
export function defaultContentFontSize(native: boolean): number {
return resolvePresentationCapabilities({ isNative: native, isWeb: !native })
.initialContentFontSize;
return native ? 16 : FONT_SIZE.content;
}
export const DEFAULT_CONTENT_FONT_SIZE = initialContentFontSize;
export const DEFAULT_CONTENT_FONT_SIZE = defaultContentFontSize(isNative);
export const MIN_CONTENT_FONT_SIZE = 10;
export const MAX_CONTENT_FONT_SIZE = 21;
export const DEFAULT_CODE_FONT_SIZE = 12; // == FONT_SIZE.code
@@ -417,9 +410,7 @@ 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: usesMobileContentFontMigration,
});
return await migrateAppSettings(read.settings, deps.storage, stored, { native: isNative });
} catch (error) {
console.error("[AppSettings] Failed to load settings:", error);
throw error;
-3
View File
@@ -2435,9 +2435,6 @@ export const ar: TranslationResources = {
archiveFinishedRetry: "إعادة المحاولة ({{failed}}/{{total}})",
},
panels: {
renderError: {
title: "تعذّر عرض هذه اللوحة",
},
draft: {
newAgent: "وكيل جديد",
creatingAgent: "وكيل الخلق",
-3
View File
@@ -2467,9 +2467,6 @@ 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,9 +2495,6 @@ 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,9 +2491,6 @@ 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,9 +2461,6 @@ export const ja: TranslationResources = {
archiveFinishedRetry: "再試行 ({{failed}}/{{total}})",
},
panels: {
renderError: {
title: "このパネルを表示できません",
},
draft: {
newAgent: "新しいエージェント",
creatingAgent: "エージェントを作成中",
-3
View File
@@ -2452,9 +2452,6 @@ export const ko: TranslationResources = {
archiveFinishedRetry: "다시 시도 ({{failed}}/{{total}})",
},
panels: {
renderError: {
title: "이 패널을 표시할 수 없습니다",
},
draft: {
newAgent: "새 에이전트",
creatingAgent: "에이전트 생성 중",
-3
View File
@@ -2477,9 +2477,6 @@ 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,9 +2477,6 @@ export const ru: TranslationResources = {
archiveFinishedRetry: "Повторить ({{failed}}/{{total}})",
},
panels: {
renderError: {
title: "Не удалось показать эту панель",
},
draft: {
newAgent: "Новый агент",
creatingAgent: "Создание агента",
-3
View File
@@ -2408,9 +2408,6 @@ export const zhCN: TranslationResources = {
archiveFinishedRetry: "重试 ({{failed}}/{{total}})",
},
panels: {
renderError: {
title: "无法显示此面板",
},
draft: {
newAgent: "新建 Agent",
creatingAgent: "正在创建 Agent",
@@ -1,7 +1,5 @@
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";
@@ -67,39 +65,4 @@ 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,
});
});
});
+1 -5
View File
@@ -11,11 +11,7 @@ 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 {
hasSoftwareKeyboard,
usesDesktopBindings,
supportsConfigurableComposerSendKeys,
} from "./internal/conventions";
export { usesDesktopBindings, supportsConfigurableComposerSendKeys } from "./internal/conventions";
export type { BrowserKeyboardPolicy } from "./internal/sources/electron-browser";
export { useHardwareKeyboardPresent } from "./availability";
export { readPressModifiers } from "./internal/press-modifiers";
@@ -1,4 +1,3 @@
export const usesDesktopBindings = true;
// Native composer Return retains its existing submit path in this feature.
export const supportsConfigurableComposerSendKeys = false;
export const hasSoftwareKeyboard = true;
@@ -1,4 +1,3 @@
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 { hasSoftwareKeyboard } from "@/keyboard";
import { isNative } from "@/constants/platform";
import {
usePanelStore,
type MobilePanelSelection,
@@ -138,7 +138,7 @@ export function MobilePanelsProvider({ children }: { children: ReactNode }) {
if (selection.revision !== revision || selection.target !== panel) {
return;
}
if (hasSoftwareKeyboard && panel !== "agent") {
if (isNative && panel !== "agent") {
Keyboard.dismiss();
}
settledPanel.setState(panel);
+2 -3
View File
@@ -57,8 +57,7 @@ import {
import type { WorkspaceComposerAttachment } from "@/attachments/types";
import { useWorkspaceAttachmentScopeKey } from "@/attachments/workspace-attachments-store";
import { COMPACT_CONTENT_WIDTH, useIsCompactFormFactor } from "@/constants/layout";
import { isWeb } from "@/constants/platform";
import { hasSoftwareKeyboard } from "@/keyboard";
import { isNative, isWeb } from "@/constants/platform";
import { useAgentAttentionClear } from "@/hooks/use-agent-attention-clear";
import { useAgentInputDraft, type AgentInputDraft } from "@/composer/draft/input-draft";
import {
@@ -1884,7 +1883,7 @@ function AgentComposer({
agentId={agentId}
serverId={serverId}
workspaceId={workspaceId}
blurOnSubmit={hasSoftwareKeyboard}
blurOnSubmit={isNative}
isPaneFocused={isPaneFocused}
textSource={agentInputDraft.textSource}
onChangeText={agentInputDraft.editText}
@@ -1,7 +1,6 @@
import type { ReactNode } from "react";
import React, { Component, type ErrorInfo, 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;
@@ -11,30 +10,42 @@ interface SurfaceErrorBoundaryProps {
renderError?(error: string): ReactNode;
}
export function SurfaceErrorBoundary({
children,
installation,
resetKey,
Surface,
renderError,
}: SurfaceErrorBoundaryProps) {
return (
<RenderErrorBoundary
resetKeys={[installation, resetKey, Surface]}
onError={warnSurfaceRenderFailed}
renderError={renderError ?? renderPluginFailed}
>
{children}
</RenderErrorBoundary>
);
interface SurfaceErrorBoundaryState {
error: string | null;
}
function renderPluginFailed(error: string) {
return <Text style={styles.errorText}>Plugin failed: {error}</Text>;
}
export class SurfaceErrorBoundary extends Component<
SurfaceErrorBoundaryProps,
SurfaceErrorBoundaryState
> {
state: SurfaceErrorBoundaryState = { error: null };
function warnSurfaceRenderFailed(error: unknown, componentStack: string | null | undefined): void {
console.warn("[Plugins] Surface render failed", error, componentStack);
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;
}
}
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",
});
const baseItem = defaultBasePickerItem(
{ currentBranch: "main", upstreamRef: "refs/remotes/origin/main" },
"fresh",
);
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",
});
const baseItem = defaultBasePickerItem(
{ currentBranch: "main", upstreamRef: "refs/remotes/upstream/main" },
"fresh",
);
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" });
const baseItem = defaultBasePickerItem({ currentBranch: "main" }, "fresh");
const data = buildPickerOptionData({
branchDetails: [{ ...mainRow, localAhead: 0, localBehind: 0 }],
prItems: [],
@@ -380,33 +380,76 @@ describe("buildPickerOptionData", () => {
});
describe("defaultBasePickerItem", () => {
it("uses origin when the current branch tracks origin", () => {
it("starts a fresh workspace from the repository default while the checkout is on a feature branch", () => {
expect(
defaultBasePickerItem({
currentBranch: "main",
upstreamRef: "refs/remotes/origin/main",
}),
defaultBasePickerItem(
{
currentBranch: "feature/unrelated",
upstreamRef: "refs/remotes/origin/feature/unrelated",
defaultBaseRef: "refs/remotes/origin/main",
},
"fresh",
),
).toMatchObject({ refName: "refs/remotes/origin/main", name: "main" });
});
it("uses the exact non-origin upstream", () => {
it("starts a fresh workspace from the repository default on a detached HEAD", () => {
expect(
defaultBasePickerItem({
currentBranch: "main",
upstreamRef: "refs/remotes/upstream/main",
}),
defaultBasePickerItem(
{ currentBranch: null, defaultBaseRef: "refs/remotes/upstream/main" },
"fresh",
),
).toMatchObject({ refName: "refs/remotes/upstream/main", name: "main" });
});
it("keeps old-daemon behavior local", () => {
expect(defaultBasePickerItem({ currentBranch: "main" })).toMatchObject({
refName: "refs/heads/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("has no default for detached HEAD", () => {
expect(defaultBasePickerItem({ currentBranch: null })).toBeNull();
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();
});
});
});
@@ -137,8 +137,12 @@ 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 {
@@ -166,25 +170,41 @@ 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.
//
// 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 {
// 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 {
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.
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`,
};
if (status.upstreamRef) return branchPickerItem(status.upstreamRef, "upstream branch");
return branchPickerItem(`refs/heads/${currentBranch}`, "local branch");
}
export function pickerItemToCheckoutRequest(
@@ -1194,9 +1194,12 @@ export function NewWorkspaceScreen({
withConnectedClient,
});
const workspaceStart = forkDraftSetup ? "fork" : "fresh";
const baseItem = useMemo(
() => selectedItem ?? (checkoutStatus ? defaultBasePickerItem(checkoutStatus) : null),
[checkoutStatus, selectedItem],
() =>
selectedItem ??
(checkoutStatus ? defaultBasePickerItem(checkoutStatus, workspaceStart) : null),
[checkoutStatus, selectedItem, workspaceStart],
);
const { options, itemById, selectedOptionId }: PickerOptionData = useMemo(
() =>
@@ -1352,7 +1355,7 @@ export function NewWorkspaceScreen({
? checkoutRequestOrExplain(
() =>
setup.checkoutRequestFor(
selectedItem ?? defaultBasePickerItem(checkoutStatusForCreate),
selectedItem ?? defaultBasePickerItem(checkoutStatusForCreate, workspaceStart),
),
t,
)
@@ -1396,6 +1399,7 @@ export function NewWorkspaceScreen({
t,
withConnectedClient,
workingDirectory,
workspaceStart,
],
);
@@ -4,6 +4,7 @@ import {
getNextWorkspaceDeckExpirationDelay,
orderWorkspaceSelectionsForStableRender,
reconcileRetainedWorkspaceSelections,
resolveWorkspaceDeckRetentionLimit,
resolveWorkspaceDeckEntries,
shouldKeepWorkspaceDeckEntryMounted,
WORKSPACE_DECK_INACTIVE_TTL_MS,
@@ -29,26 +30,21 @@ function retainedWorkspaceIds(
}
describe("reconcileRetainedWorkspaceSelections", () => {
it("retains only the active workspace when limited to one mounted workspace", () => {
it("retains only the active workspace on native", () => {
const entries = reconcileRetainedWorkspaceSelections({
currentEntries: [retained("A", null)],
activeSelection: workspace("B"),
now: 2,
maxMountedWorkspaces: 1,
maxMountedWorkspaces: resolveWorkspaceDeckRetentionLimit({ isNative: true }),
});
expect(retainedWorkspaceIds(entries)).toEqual(["B"]);
});
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 the desktop deck limit on web", () => {
expect(resolveWorkspaceDeckRetentionLimit({ isNative: false })).toBe(
WORKSPACE_DECK_MAX_MOUNTED_WORKSPACES,
);
});
it("retains inactive workspaces for ten minutes across app-wide routes", () => {
@@ -1,10 +1,6 @@
import { resolveResourceBudgets } from "../../constants/resource-budget-tables";
import type { ActiveWorkspaceSelection } from "@/stores/navigation-active-workspace-store";
// 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_MAX_MOUNTED_WORKSPACES = 10;
export const WORKSPACE_DECK_INACTIVE_TTL_MS = 10 * 60 * 1000;
export interface RetainedWorkspaceSelection {
@@ -12,6 +8,10 @@ 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;
@@ -1,136 +0,0 @@
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,12 +1,6 @@
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,
@@ -93,31 +87,6 @@ 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,
@@ -190,22 +159,10 @@ export function WorkspacePaneContent({
tabId={paneContextValue.tabId}
targetKey={JSON.stringify(paneContextValue.target)}
>
<RenderErrorBoundary
resetKeys={[key, paneContextValue.target, paneContextValue.state]}
onError={logPanelRenderError}
renderError={renderPanelError}
>
<Component key={key} />
</RenderErrorBoundary>
<Component key={key} />
</ComposerEditingScope>
</PaneFocusProvider>
</PaneProvider>
</RenderProfile>
);
}
const styles = StyleSheet.create((theme) => ({
renderError: {
padding: theme.spacing[4],
},
}));
@@ -45,19 +45,11 @@ function controlsByType(
}
describe("terminal virtual keyboard policy", () => {
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("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("selects the same controls in narrow and wide row arrangements", () => {
@@ -124,29 +116,29 @@ describe("terminal virtual keyboard policy", () => {
expect(controlIds()).not.toContain("terminal-copy");
});
it("shows Copy only as a software-keyboard selection affordance", () => {
it("shows Copy only as a native selection affordance", () => {
expect(
shouldShowTerminalFloatingCopyAction({
hasSelection: false,
hasSoftwareKeyboard: true,
isNative: true,
}),
).toBe(false);
expect(
shouldShowTerminalFloatingCopyAction({
hasSelection: true,
hasSoftwareKeyboard: false,
isNative: false,
}),
).toBe(false);
expect(
shouldShowTerminalFloatingCopyAction({
hasSelection: true,
hasSoftwareKeyboard: true,
isNative: true,
}),
).toBe(true);
});
it("keeps Paste gated to software-keyboard targets", () => {
expect(shouldShowTerminalPasteAction({ hasSoftwareKeyboard: true })).toBe(true);
expect(shouldShowTerminalPasteAction({ hasSoftwareKeyboard: false })).toBe(false);
it("keeps Paste native-gated", () => {
expect(shouldShowTerminalPasteAction({ isNative: true })).toBe(true);
expect(shouldShowTerminalPasteAction({ isNative: false })).toBe(false);
});
});
@@ -97,10 +97,10 @@ export function resolveTerminalVirtualKeyboardRows(input: {
}
export function shouldShowTerminalVirtualKeyBar(input: {
hasSoftwareKeyboard: boolean;
isNative: boolean;
isCompact: boolean;
}): boolean {
return input.hasSoftwareKeyboard || input.isCompact;
return input.isNative || input.isCompact;
}
export function getTerminalVirtualKeyboardControlId(
@@ -118,13 +118,13 @@ export function getTerminalVirtualKeyboardControlId(
}
}
export function shouldShowTerminalPasteAction(input: { hasSoftwareKeyboard: boolean }): boolean {
return input.hasSoftwareKeyboard;
export function shouldShowTerminalPasteAction(input: { isNative: boolean }): boolean {
return input.isNative;
}
export function shouldShowTerminalFloatingCopyAction(input: {
hasSelection: boolean;
hasSoftwareKeyboard: boolean;
isNative: boolean;
}): boolean {
return input.hasSoftwareKeyboard && input.hasSelection;
return input.isNative && input.hasSelection;
}
@@ -1,5 +1,5 @@
import { UnistylesRuntime } from "react-native-unistyles";
import { allowsInlineWorkspaceRename } from "@/constants/presentation";
import { isWeb } from "@/constants/platform";
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.
*
* Mobile native wide layouts keep the modal. Their sidebar rows are touch targets with a permanent
* 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 (!allowsInlineWorkspaceRename) return "modal";
if (!isWeb) return "modal";
const breakpoint = UnistylesRuntime.breakpoint;
return breakpoint === "lg" || breakpoint === "xl" ? "inline" : "modal";
}
+4 -1
View File
@@ -54,7 +54,10 @@ 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")
.option(
"--base <ref>",
"Base ref for branch-off mode. A bare branch resolves remote-first; use refs/heads/<name> for local commits",
)
.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")
+4 -1
View File
@@ -31,7 +31,10 @@ 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)")
.option(
"--base <ref>",
"Base ref (--mode branch-off). A bare branch resolves remote-first; use refs/heads/<name> for local commits",
)
.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)",
"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",
)
.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 { stripLinuxDesktopRuntimeEnv } from "@getpaseo/server/process";
import { stripAppImageRuntimeEnv } 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 };
stripLinuxDesktopRuntimeEnv(env, { platform });
stripAppImageRuntimeEnv(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 { stripLinuxDesktopRuntimeEnv } from "@getpaseo/server/process";
import { stripAppImageRuntimeEnv } 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];
}
stripLinuxDesktopRuntimeEnv(env, { platform });
stripAppImageRuntimeEnv(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 { stripLinuxDesktopRuntimeEnv } from "@getpaseo/server/process";
import { stripAppImageRuntimeEnv } 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;
stripLinuxDesktopRuntimeEnv(shellEnv, { platform: deps.platform });
stripAppImageRuntimeEnv(shellEnv, { platform: deps.platform });
deps.logger.info("[login-shell-env] start", {
shell,
+17
View File
@@ -6269,6 +6269,23 @@ 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,6 +110,70 @@ 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,18 +94,14 @@ export class CreateAgentLifecycleDispatch {
placement.githubPrNumber = target.prNumber;
break;
}
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,
);
return this.dependencies.createPaseoWorktreeWorkflow({
...placement,
background: input.background,
callerWorkspaceId: input.callerWorkspaceId,
firstAgentContext: input.firstAgentContext,
paseoHome: this.dependencies.paseoHome,
worktreesRoot: this.dependencies.worktreesRoot,
});
}
registerAutoArchiveIfRequested(input: {
@@ -527,7 +527,6 @@ function resolveChildAgentCwd(params: {
interface CreateMcpWorktreeOptions {
input: CreatePaseoWorktreeInput;
createPaseoWorktree: CreatePaseoWorktreeWorkflowFn | undefined;
resolveDefaultBranch?: (repoRoot: string) => Promise<string>;
}
async function createMcpWorktree(
@@ -537,10 +536,7 @@ async function createMcpWorktree(
if (!options.createPaseoWorktree) {
throw new Error("Paseo worktree service is not configured");
}
return await options.createPaseoWorktree(
options.input,
options.resolveDefaultBranch ? { resolveDefaultBranch: options.resolveDefaultBranch } : {},
);
return await options.createPaseoWorktree(options.input);
} catch (error) {
throw toWorktreeRequestError(error);
}
@@ -576,7 +572,6 @@ 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,
@@ -584,6 +579,7 @@ 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 },
@@ -592,7 +588,6 @@ async function resolveMcpCwd(params: {
worktreesRoot: dependencies.worktreesRoot,
},
createPaseoWorktree: dependencies.createPaseoWorktree,
resolveDefaultBranch: baseBranch ? async () => baseBranch : undefined,
});
return {
resolvedCwd: createdWorktree.workspace.cwd,
@@ -869,16 +869,13 @@ function createPaseoWorktreeForMcpTest(options: {
generateWorkspaceName: options.generateWorkspaceName ?? (async () => null),
});
return async (input, serviceOptions) => {
return async (input) => {
const result = await createPaseoWorktreeWorkflow(
{
paseoHome: options.paseoHome,
createPaseoWorktree: (workflowInput, workflowOptions) =>
createPaseoWorktree: (workflowInput) =>
createPaseoWorktreeService(workflowInput, {
github,
...(workflowOptions?.resolveDefaultBranch
? { resolveDefaultBranch: workflowOptions.resolveDefaultBranch }
: {}),
workspaceGitService,
workspaceProvisioning,
}),
@@ -898,7 +895,6 @@ 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 });
await rm(dir, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 });
}
});
@@ -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 });
await rm(dir, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 });
}
},
);
@@ -6405,7 +6405,7 @@ describe("ACPAgentSession interrupt settlement and hung-cancel retirement (#3256
);
} finally {
await session.close();
await rm(dir, { recursive: true, force: true });
await rm(dir, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 });
}
});
@@ -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 });
await rm(dir, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 });
}
}, 15_000);
@@ -6548,7 +6548,7 @@ lines.on("line", (line) => {
);
} finally {
await session.close();
await rm(dir, { recursive: true, force: true });
await rm(dir, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 });
}
}, 15_000);
@@ -498,182 +498,6 @@ 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"],
@@ -4290,326 +4114,6 @@ 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,13 +2,6 @@ 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,
@@ -28,6 +21,7 @@ import {
type AgentPermissionResponse,
type AgentPermissionResult,
type AgentProviderNotice,
type AgentPromptContentBlock,
type AgentPromptInput,
type AgentRunOptions,
type AgentRunResult,
@@ -3596,6 +3590,12 @@ 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,6 +3620,8 @@ function enabledCodexSkills(
return Array.from(skillsByName.values());
}
type CodexPromptContentBlock = AgentPromptContentBlock | CodexSkillPromptBlock;
type CodexPromptInput = string | CodexPromptContentBlock[];
interface CodexTextElement {
byteRange: {
start: number;
@@ -3950,7 +3952,6 @@ 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>;
@@ -4713,12 +4714,12 @@ export class CodexAppServerAgentSession implements AgentSession {
return null;
}
const parsed = this.parseSlashCommandInput(prompt);
if (!parsed || !parsed.commandName.startsWith("prompts:")) {
if (!parsed) {
return null;
}
try {
const prompts = await listCodexCustomPrompts(this.codexHome);
return prompts.some((command) => command.name === parsed.commandName) ? parsed : null;
const commands = await this.listCommands();
return commands.some((command) => command.name === parsed.commandName) ? parsed : null;
} catch (error) {
this.logger.warn(
{ err: error, commandName: parsed.commandName },
@@ -4732,30 +4733,31 @@ export class CodexAppServerAgentSession implements AgentSession {
commandName: string,
args?: string,
): Promise<CodexPromptInput> {
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;
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);
}
return [...resolvedArgs.skills, { type: "text", text: expandedBody }];
}
private async resolveMentionedSkills(
prompt: AgentPromptInput,
): Promise<ResolvedCodexSkillMentions> {
if (!hasCodexSkillMentionCandidate(prompt)) {
return { skills: [], prompt };
if (this.connectionState === "disconnected") {
await this.connect();
} else {
await this.loadSkills();
}
await this.loadSkills();
return resolveCodexSkillMentions(prompt, this.cachedSkills ?? []);
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}`;
}
private async buildTurnStartParams(
@@ -4951,19 +4953,10 @@ export class CodexAppServerAgentSession implements AgentSession {
throw new Error("Codex client not initialized");
}
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;
}
const slashCommand = await this.resolveSlashCommandInvocation(prompt);
const effectivePrompt = slashCommand
? await this.buildCommandPromptInput(slashCommand.commandName, slashCommand.args)
: prompt;
if (this.currentThreadId) {
await this.ensureThreadLoaded();
@@ -5019,44 +5012,16 @@ export class CodexAppServerAgentSession implements AgentSession {
}
}
private async canSteerPrompt(
async steerActiveTurn(
prompt: AgentPromptInput,
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> {
options: SteerActiveTurnOptions,
): Promise<SteerResult> {
const client = this.client;
const threadId = this.currentThreadId;
let nativeTurnId = this.currentTurnId;
const foregroundTurnId = this.activeForegroundTurnId;
if (!client || !threadId || foregroundTurnId !== expectedTurnId) {
return null;
if (!client || !threadId || foregroundTurnId !== options.expectedTurnId) {
return { status: "unavailable" };
}
const pendingIdentification = this.pendingForegroundTurnIdentification;
// The start acknowledgement precedes the notification that identifies the native
@@ -5064,29 +5029,23 @@ export class CodexAppServerAgentSession implements AgentSession {
if (!nativeTurnId && pendingIdentification?.foregroundTurnId === foregroundTurnId) {
nativeTurnId = await pendingIdentification.promise;
}
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> {
if (!nativeTurnId) {
return { status: "unavailable" };
}
if (await this.resolveSlashCommandInvocation(prompt)) return { status: "unavailable" };
if (!this.matchesSteerAdmission({ client, threadId, nativeTurnId, foregroundTurnId })) {
return { status: "unavailable" };
}
const input = await this.buildUserInput(prompt);
if (!this.matchesSteerAdmission(admission)) {
if (!this.matchesSteerAdmission({ client, threadId, nativeTurnId, foregroundTurnId })) {
return { status: "unavailable" };
}
try {
const response = await admission.client.request(
const response = await client.request(
"turn/steer",
{
threadId: admission.threadId,
expectedTurnId: admission.nativeTurnId,
threadId,
expectedTurnId: nativeTurnId,
input,
...(options.clientMessageId ? { clientUserMessageId: options.clientMessageId } : {}),
},
@@ -5095,7 +5054,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 !== admission.nativeTurnId) {
if (acknowledgedTurnId !== nativeTurnId) {
throw new Error("Codex returned an invalid steer acknowledgement");
}
if (options.clearPendingPermissions) {
@@ -5108,17 +5067,6 @@ 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;
@@ -5460,16 +5408,10 @@ export class CodexAppServerAgentSession implements AgentSession {
let followUpPrompt = prepared.prompt;
const expectedTurnId = this.activeForegroundTurnId;
if (prepared.prompt && expectedTurnId) {
// 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 };
const result = await this.steerActiveTurn(prepared.prompt, {
expectedTurnId,
clientMessageId: randomUUID(),
});
if (result.status !== "accepted") {
throw new Error("The active Codex turn changed. Retry sending your answer.");
}
@@ -5482,11 +5424,7 @@ export class CodexAppServerAgentSession implements AgentSession {
requestId,
resolution: response,
});
if (followUpPrompt) {
this.pendingLiteralFollowUpPrompt = followUpPrompt;
return { followUpPrompt };
}
return undefined;
return followUpPrompt ? { followUpPrompt } : undefined;
}
private handlePlanPermissionResponse(params: {
@@ -5505,7 +5443,6 @@ export class CodexAppServerAgentSession implements AgentSession {
this.resolvePlanPermission(requestId, response);
if (followUpPrompt) {
this.pendingLiteralFollowUpPrompt = followUpPrompt;
return { followUpPrompt };
}
}
@@ -460,137 +460,3 @@ 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();
}
});
@@ -1,169 +0,0 @@
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,
],
});
});
});
@@ -1,131 +0,0 @@
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 "./integration-extension.js";
} from "./background-work-extension.js";
import type { OmpRuntime, OmpRuntimeSession, OmpStartSessionInput } from "./runtime.js";
import { OmpMcpBridge, type OmpBridgedToolIdentity } from "./mcp-bridge.js";
import type {
@@ -3,11 +3,11 @@ import { pathToFileURL } from "node:url";
import { afterEach, beforeEach, describe, expect, test, vi, type Mock } from "vitest";
import {
createOmpIntegrationExtensionFile,
createOmpBackgroundWorkExtensionFile,
OMP_BACKGROUND_WORK_STATUS_KEY,
parseOmpBackgroundWorkStatus,
type OmpIntegrationExtensionFile,
} from "./integration-extension.js";
type OmpBackgroundWorkExtensionFile,
} from "./background-work-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: OmpIntegrationExtensionFile | undefined;
let extensionFile: OmpBackgroundWorkExtensionFile | undefined;
afterEach(async () => {
vi.useRealTimers();
@@ -49,7 +49,7 @@ afterEach(async () => {
});
async function installExtension(): Promise<FakeHost> {
extensionFile = await createOmpIntegrationExtensionFile();
extensionFile = await createOmpBackgroundWorkExtensionFile();
// 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 createOmpIntegrationExtensionFile();
const file = await createOmpBackgroundWorkExtensionFile();
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 createOmpIntegrationExtensionFile();
const file = await createOmpBackgroundWorkExtensionFile();
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 createOmpIntegrationExtensionFile();
const file = await createOmpBackgroundWorkExtensionFile();
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 OmpIntegrationExtensionFile {
export interface OmpBackgroundWorkExtensionFile {
path: string;
cleanup(): Promise<void>;
}
@@ -29,11 +29,10 @@ const statusSchema = z.object({
type OmpBackgroundJob = z.infer<typeof jobSchema>;
function renderExtension(systemPrompt: string | undefined): string {
return `const STATUS_KEY = ${JSON.stringify(OMP_BACKGROUND_WORK_STATUS_KEY)};
const EXTENSION_SOURCE = `const STATUS_KEY = ${JSON.stringify(OMP_BACKGROUND_WORK_STATUS_KEY)};
const POLL_INTERVAL_MS = 250;
export default function paseoIntegration(pi) {
export default function paseoBackgroundWork(pi) {
let ctx;
let timer;
let lastText;
@@ -73,34 +72,18 @@ export default function paseoIntegration(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 createOmpIntegrationExtensionFile(
systemPrompt?: string,
): Promise<OmpIntegrationExtensionFile> {
const dir = await mkdtemp(join(tmpdir(), "paseo-omp-integration-"));
const path = join(dir, "paseo-integration.mjs");
export async function createOmpBackgroundWorkExtensionFile(): Promise<OmpBackgroundWorkExtensionFile> {
const dir = await mkdtemp(join(tmpdir(), "paseo-omp-background-work-"));
const path = join(dir, "paseo-background-work.mjs");
const cleanup = () => rm(dir, { recursive: true, force: true });
try {
await writeFile(path, renderExtension(systemPrompt), { mode: 0o600 });
await writeFile(path, EXTENSION_SOURCE, { mode: 0o600 });
} catch (error) {
await cleanup();
throw error;
@@ -9,9 +9,9 @@ import {
type JsonlRpcLaunch,
} from "../jsonl-rpc-process.js";
import {
createOmpIntegrationExtensionFile,
type OmpIntegrationExtensionFile,
} from "./integration-extension.js";
createOmpBackgroundWorkExtensionFile,
type OmpBackgroundWorkExtensionFile,
} from "./background-work-extension.js";
import { establishOmpProtocol } from "./protocol-session.js";
import {
buildOmpLaunch,
@@ -75,16 +75,14 @@ export class OmpCliRuntime implements OmpRuntime {
}
async startSession(input: OmpStartSessionInput): Promise<OmpRuntimeSession> {
const integrationExtension = await createOmpIntegrationExtensionFile(
input.systemPrompt?.trim(),
);
const backgroundWorkExtension = await createOmpBackgroundWorkExtensionFile();
let env: Record<string, string>;
let process: JsonlRpcProcess;
try {
input.signal?.throwIfAborted();
({ env, process } = this.spawnOmp(input, integrationExtension.path));
({ env, process } = this.spawnOmp(input, backgroundWorkExtension.path));
} catch (error) {
await integrationExtension.cleanup();
await backgroundWorkExtension.cleanup();
throw error;
}
const handleAbort = () => void process.close(input.signal?.reason).catch(() => undefined);
@@ -95,11 +93,11 @@ export class OmpCliRuntime implements OmpRuntime {
requestTimeoutMs: this.options.requestTimeoutMs,
});
input.signal?.throwIfAborted();
return new OmpCliRuntimeSession(process, this.commandsRpcName, env, integrationExtension);
return new OmpCliRuntimeSession(process, this.commandsRpcName, env, backgroundWorkExtension);
} catch (error) {
const startupError = error instanceof Error ? error : new Error(String(error));
await process.close(startupError);
await integrationExtension.cleanup();
await backgroundWorkExtension.cleanup();
throw startupError;
} finally {
input.signal?.removeEventListener("abort", handleAbort);
@@ -151,7 +149,7 @@ class OmpCliRuntimeSession implements OmpRuntimeSession {
private readonly process: JsonlRpcProcess,
private readonly commandsRpcName: "get_available_commands",
private readonly launchEnvironment: Record<string, string>,
private readonly integrationExtension: OmpIntegrationExtensionFile,
private readonly backgroundWorkExtension: OmpBackgroundWorkExtensionFile,
) {
process.onMessage((message) => {
const event = parseOmpRuntimeEvent(message);
@@ -336,7 +334,7 @@ class OmpCliRuntimeSession implements OmpRuntimeSession {
try {
await this.process.close(new Error("OMP RPC session is closed"));
} finally {
await this.integrationExtension.cleanup();
await this.backgroundWorkExtension.cleanup();
}
}
@@ -27,6 +27,7 @@ export interface OmpRuntimeLaunch {
modeId?: string;
session?: string;
noSession?: boolean;
systemPrompt?: string;
extraArgs?: string[];
}
@@ -102,7 +103,8 @@ export function buildOmpLaunch(input: {
const argv = [...command];
const protocolMode = input.session.protocolMode ?? "rpc";
appendOmpLaunchArgs(argv, input.session, protocolMode);
const systemPrompt = input.session.systemPrompt?.trim();
appendOmpLaunchArgs(argv, input.session, protocolMode, systemPrompt);
return {
cwd: input.session.cwd,
@@ -121,6 +123,7 @@ export function buildOmpLaunch(input: {
modeId: input.session.modeId,
session: input.session.session,
noSession: input.session.noSession,
systemPrompt,
extraArgs: input.session.extraArgs,
};
}
@@ -129,6 +132,7 @@ function appendOmpLaunchArgs(
argv: string[],
session: OmpStartSessionInput,
protocolMode: "rpc" | "rpc-ui",
systemPrompt: string | undefined,
): void {
if (!hasModeFlag(argv)) {
argv.push("--mode", protocolMode);
@@ -147,6 +151,9 @@ 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 "../integration-extension.js";
import { OMP_BACKGROUND_WORK_STATUS_KEY } from "../background-work-extension.js";
type FakeOmpSubagentSubscriptionLevel = "off" | "progress" | "events";
type FakeOmpSubagentStatus = "pending" | "running" | "completed" | "failed" | "aborted";
@@ -3258,345 +3258,3 @@ 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();
}
});
});
@@ -1,226 +0,0 @@
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" } }],
});
});
});
@@ -1,430 +0,0 @@
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,11 +14,12 @@ 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";
@@ -234,6 +235,7 @@ 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;
@@ -241,12 +243,12 @@ export class SessionTurns {
const output =
options?.outputSchema === undefined ? undefined : structuredOutput(options.outputSchema);
const turn = this.createTurn(submitted, false, output);
void this.submit(turn, prompt, accept, options);
void this.submit(turn, input, accept, options);
return { turnId: turn.id };
}
private async submit(
turn: Turn,
prompt: AgentPromptInput,
input: ReturnType<SessionTurns["promptInput"]>,
accept: () => void,
options?: AgentRunOptions,
) {
@@ -263,7 +265,7 @@ export class SessionTurns {
} catch {
// Keep the cached baselineIdleTime if the pre-dispatch read fails transiently.
}
await this.dispatch(turn, prompt, options, turn.output);
await this.dispatch(input, options, turn.output);
if (this.turn !== turn) return;
turn.accepted = true;
this.revision += 1;
@@ -470,57 +472,65 @@ 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(
turn: Turn,
prompt: AgentPromptInput,
input: ReturnType<SessionTurns["promptInput"]>,
options?: AgentRunOptions,
output?: ReturnType<typeof structuredOutput>,
) {
const prepared = await this.preparePrompt(prompt);
if (this.turn !== turn) return;
if (prepared.kind === "compact") {
const command = input.text.match(/^\/([^\s]+)(?:\s+([\s\S]*))?$/);
if (command?.[1] === "compact" || command?.[1] === "summarize") {
await this.options.client().session.compact({ sessionID: this.options.id });
return;
}
if (prepared.kind === "command") {
const selected = command
? (await commands(this.options.client(), this.options.cwd)).find(
(item) => item.name === command[1],
)
: undefined;
if (selected && selected.kind !== "skill") {
await this.options.client().session.command({
sessionID: this.options.id,
name: prepared.name,
text: prepared.text,
files: prepared.files,
...(prepared.skills ? { skills: prepared.skills } : {}),
name: selected.name,
text: command?.[2] ?? "",
files: input.files,
});
return;
}
await this.options.client().session.prompt({
sessionID: this.options.id,
text: prepared.text,
files: prepared.files,
...(prepared.skills ? { skills: prepared.skills } : {}),
...input,
...(selected?.kind === "skill"
? {
skills: [{ id: selected.name }],
text: command?.[2] ?? `Use the ${selected.name} skill.`,
}
: {}),
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,
text: prepared.text,
files: prepared.files,
...(prepared.skills ? { skills: prepared.skills } : {}),
...this.promptInput(prompt),
delivery: "steer",
metadata: options.clientMessageId
? { paseoClientMessageId: options.clientMessageId }
@@ -1637,7 +1637,14 @@ 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."),
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.",
),
branch: z
.string()
.trim()
+1 -8
View File
@@ -1311,23 +1311,17 @@ 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, workflowOptions) => {
createPaseoWorktree: async (workflowInput) => {
return createRegisteredPaseoWorktree(workflowInput, {
lifecycle: pluginRuntime,
worktreeManagers: pluginRuntime,
github,
...(workflowOptions?.resolveDefaultBranch
? {
resolveDefaultBranch: workflowOptions.resolveDefaultBranch,
}
: {}),
workspaceGitService,
workspaceProvisioning,
});
@@ -1358,7 +1352,6 @@ async function assemblePaseoDaemon({
onScriptsChanged: null,
},
input,
serviceOptions,
);
};
@@ -47,6 +47,45 @@ 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,6 +63,8 @@ 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,
@@ -90,6 +92,8 @@ 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", () => {
describe("daemonLaunchEnvironment AppImage sanitization", () => {
const appDir = "/tmp/.mount_Paseo-abcdef";
test("strips AppImage runtime variables in both managed and deployment modes", () => {
@@ -47,40 +47,6 @@ describe("daemonLaunchEnvironment", () => {
}
});
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 { stripLinuxDesktopRuntimeEnv } from "./paseo-env.js";
import { stripAppImageRuntimeEnv } 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;
stripLinuxDesktopRuntimeEnv(env, { platform: input.platform });
stripAppImageRuntimeEnv(env, { platform: input.platform });
env.PASEO_HOME = input.home;
if (input.desktopManaged) env.PASEO_DESKTOP_MANAGED = "1";
return env;
@@ -159,25 +159,17 @@ 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 startScriptedModel(options: {
askHtml?: string;
onSystemPrompt?: (text: string) => void;
}): Promise<ScriptedModel> {
async function startScriptedAskModel(html: string): 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 (options.askHtml !== undefined && !toolMessage && offersAsk) {
if (!toolMessage && offersAsk) {
response.write(
sseChunk(
{
@@ -187,7 +179,7 @@ async function startScriptedModel(options: {
index: 0,
id: "call_ask_1",
type: "function",
function: { name: "ask", arguments: JSON.stringify({ html: options.askHtml }) },
function: { name: "ask", arguments: JSON.stringify({ html }) },
},
],
},
@@ -390,41 +382,6 @@ 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 () => {
@@ -595,7 +552,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 startScriptedModel({ askHtml: COLOR_FORM });
const model = await startScriptedAskModel(COLOR_FORM);
const harness = await createHarness({
ompHome: createOfflineOmpHome({ baseUrl: model.baseUrl }),
});
@@ -635,7 +592,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 startScriptedModel({ askHtml: COLOR_FORM });
const model = await startScriptedAskModel(COLOR_FORM);
const harness = await createHarness({
ompHome: createOfflineOmpHome({ baseUrl: model.baseUrl, askTimeoutSeconds: 2 }),
});
@@ -66,15 +66,6 @@ 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" });
+1 -16
View File
@@ -89,21 +89,6 @@ 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 };
}
@@ -116,7 +101,7 @@ function buildExternalProcessEnv(
for (const key of RUNTIME_CONTROL_ENV_KEYS) {
delete sanitized[key];
}
stripLinuxDesktopRuntimeEnv(sanitized);
stripAppImageRuntimeEnv(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