Compare commits

..
Author SHA1 Message Date
paseo-bot[bot] 59a21245bd Let Muse sessions finish closing when a child read ends
Releasing an outstanding child read during host shutdown must not report a runtime failure to the adapter that is already closing the session.
2026-11-20 11:11:43 +00:00
paseo-bot[bot] 6b1311d3b2 Keep Muse child projection within the parent session lifetime
Check the parent again after reading a child. Closing a parent while that read is in flight no longer publishes an event for a parent the runtime has removed.
2026-11-20 11:05:19 +00:00
paseo-bot[bot]andGeorge b9196fa259 test(muse): exercise child history replay without a live setup turn
Seed a historical child after closing an empty session so the replay
regression reaches resume even when live subagent projection is broken.
Both paths now fail independently with the reported negotiation error.

Co-authored-by: George <90179633+georgepullen@users.noreply.github.com>
2026-11-20 10:41:32 +00:00
George c086c8a5ad test(plugins): launch fake muse through the provider command override 2026-11-20 10:41:32 +00:00
George af2498ae99 test(plugins): cover muse subsession negotiation through PluginRuntime 2026-11-20 10:41:31 +00:00
George 5a16dd0c13 docs(plugins): require session.subsession negotiation before opening a child 2026-11-20 10:41:31 +00:00
George a85695679a test(muse-provider): reach the subsession gate with a child-bearing fixture 2026-11-20 10:41:31 +00:00
George e7245e0883 fix(muse-provider): negotiate session.subsession and gate child projection 2026-11-20 10:41:31 +00:00
36dffc9503 feat(plugin): let plugin navigation focus the destination host in the sidebar (#5574)
* feat(plugin): let plugin navigation focus the destination host in the sidebar

Plugins that link across hosts open agents and workspaces with
navigation.openAgent and navigation.openWorkspace, but the sidebar keeps its
host, project and label filters, so the destination can be hidden. Plugins
can't change those client-side filters.

Add an opt-in focusHost flag. With focusHost: true the client selects only the
destination host in the sidebar and clears project and label filters that
could hide it, keeping the grouping mode. Calls without the flag are
unchanged, and navigation.supportsFocusHost lets plugins detect support.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Normalize plugin navigation host IDs

* Preserve sidebar filters for removed hosts

* Focus the host returned by plugin navigation

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Mohamed Boudra <boudra.moha@gmail.com>
2026-11-20 17:28:19 +07:00
Mohamed Boudra d78cc90e4d Install bundled orchestration skills for Antigravity (#10273)
* feat(skills): install bundled orchestration skills for Antigravity

Antigravity CLI (`agy`), App, and IDE do not scan `~/.agents/skills` or
`~/.claude/skills` globally; they discover global skills one level deep
from `~/.gemini/config/skills/<skill>/SKILL.md`. Gemini CLI already
discovers `~/.agents/skills`, so targeting `~/.gemini/config/skills`
only (instead of `~/.gemini/skills`) avoids duplicate skill entries in
both Gemini CLI and `agy`.

Appends `antigravityDir` at root index 3 in skill transactions so any
in-flight pre-upgrade transaction manifest retains its existing backup
indices, and includes `antigravityDir` in legacy Codex alias checks so
symlinked roots are not retired.

* fix(skills): unify install roots and keep rollback/updates resilient to unwritable targets

- Replace separate per-target fields on SkillTargets with an ordered
  `installDirs` list plus `codexDir`, deriving status, sync, removal,
  legacy Codex alias checks, and transaction root indexing from one
  source while preserving pre-upgrade backup indices 0–2 (`codexDir` at
  index 2, additional install roots at index 3+).
- Skip unreadable `add` entries with no backup during transaction
  rollback so an ENOTDIR/EACCES parent under `~/.gemini` does not fail
  rollback and leave a stuck transaction blocking later skills calls.
- Ignore `ENOTDIR` in `removeSkill` (a skill cannot exist below a
  regular file).
- Continue syncing remaining skills and install roots in `syncSkills`
  before throwing the first error so an unwritable `~/.gemini` does not
  block startup auto-updates from reaching `~/.agents` and `~/.claude`.

* fix(skills): finish removing reachable skills during uninstall when one root is unreadable

Continue across every target root in `removeSkill` and every managed
skill in `uninstallSkills` before throwing the first error (matching
`syncSkills`), while still reporting `EACCES` rather than ignoring it.

* test(agent): synchronize stale-session retry before checking cleared run

Replace the racy `setTimeout(0)` in `agent-manager.test.ts` with a
deferred gate on `resumeSession`. Under CI load, `setTimeout(0)` could
fire after the immediate retry had already resumed and started its new
in-flight run, causing `hasInFlightRun(agent.id)` to read `true`.
2026-11-20 15:32:14 +07:00
Mohamed Boudra 0f57c2b4c7 Prevent duplicate slash-command entries from breaking composer autocomplete (#10275)
* fix(commands): deduplicate provider slash commands by name

Antigravity ACP emits both its built-in slash commands and discovered skills in one available_commands_update without deduplicating colliding names (such as a local plan skill alongside built-in /plan). Both entries flowed through plugin ACP, plugin-provider, and mergeSlashCommandSources into Autocomplete's FlatList, triggering React's duplicate key error on .$plan.

Enforce unique command names (first-wins) at the plugin ACP, plugin provider, core ACP, and Codex boundaries so every daemon consumer gets a valid catalog, and claim provider command names in mergeSlashCommandSources and inline skill filtering so the app stays safe against older daemons.

* refactor(commands): enforce unique command names at daemon and app boundaries

Move slash-command deduplication from six per-provider and per-consumer copies to the two single boundaries: handleListCommandsRequest in packages/server/src/server/session.ts (covering live agents and drafts for every provider) and fetchAgentCommands in packages/app/src/agent-commands/use-query.ts (covering all app consumers, including against older daemons).

* chore(app): tag app-side command deduplication as a COMPAT shim
2026-11-20 15:12:21 +07:00
Mohamed Boudra ddd7aff9be Keep the composer and chat column aligned with the chat outline rail (#10277)
* fix(app): keep composer and chat column on the outline rail

Previously only WebStreamViewport reserved the 44px chat outline gutter and clamped right gutter on wide web panes (>= 918px), leaving the composer, floating track bar, and callouts at symmetric 16px padding. On Full width, on Wide (1200px) below 1320px pane width, and on Default (820px) between 918px and 939px, the composer extended off the timeline's vertical rail.

Move outline gutter ownership to a platform-split chat-rail module mounted at the chat pane surface. On web it measures the pane width once against the 918px threshold and publishes the shared left and clamped right gutters via CSS custom properties so composer, tracks, and callouts stay aligned with zero resize re-renders or dynamic Unistyles rules, while native stays a zero-hook pass-through. Removing direct outline measurement from AgentStreamView also stops ProviderSubagentPanel from reserving space for an outline it never renders.

* fix(app): keep outline prompt index across 918px crossings and exclude draft error from fullscreen rail
2026-11-20 14:37:32 +07:00
Mohamed Boudra 7eec266f50 fix(usage): keep window shorthands visible in sidebar usage row (#10274)
* fix(usage): keep window shorthands visible in sidebar usage row

Antigravity usage windows emitted full group names and raw period strings (for example "Gemini Models weekly") in shortLabel, which pushed the measured labels row past the maximum sidebar width. On the app side, choosePinnedUsageLayout dropped every window on the row straight to bare percentages whenever any scoped short label overflowed the row.

Normalize Antigravity shortLabel periods (weekly -> wk, monthly -> mo) and shorten group prefixes, and add a compact period-shorthand tier between full labels and bare percentages in PinnedUsageTrigger so tight sidebar rows keep shorthands like 5h and wk visible instead of collapsing to percentages alone.

* test(usage): expect compact shorthands in usage modal sidebar summary

With the compact period-shorthand tier between full labels and bare percentages, three Weekly windows now render as "31% wk", "20% wk", "12% wk" in the 320px sidebar instead of dropping to bare percentages.
2026-11-20 13:58:45 +07:00
110 changed files with 2291 additions and 5578 deletions
+7 -5
View File
@@ -186,11 +186,13 @@ Terminal activity contributes to the workspace status bucket **per `workspaceId`
Single file, validated with `PersistedConfigSchema`.
`agents.skills.selection` is the daemon host's orchestration-skill preference. Missing means
`{ mode: "all" }`. Installed state is not persisted; the daemon derives it from the shared
`~/.agents/skills` and Claude skill directories and keeps config plus filesystem convergence behind
one serialized owner. Codex discovers the shared directory. Updates retire unchanged files from
Paseo-managed copies in `~/.codex/skills`, preserving user edits and untracked files.
`agents.skills.selection` stores the orchestration-skill preference for the daemon host, and a
missing value defaults to `{ mode: "all" }`. The daemon does not persist installed state. It
derives installed state from `~/.agents/skills`, `~/.claude/skills`, and `~/.gemini/config/skills`,
and serializes configuration and filesystem convergence through one owner. Codex and Gemini CLI
discover `~/.agents/skills`, while Antigravity discovers `~/.gemini/config/skills`. Updates retire
unchanged files from Paseo-managed copies in `~/.codex/skills` and preserve user edits and
untracked files.
`paseo reload` reads and validates this file once inside the daemon. That snapshot drives resolution,
classification, application, and reload bookkeeping. `DaemonConfigStore` owns applying runtime-safe
-12
View File
@@ -471,18 +471,6 @@ Workspace records decide ownership, including explicit non-ownership after recov
ownership checks prefer the marker-verified worktree root over the legacy
path shape: a plugin can place a worktree several directories below the default worktrees root.
A plugin can also take over worktree creation, removal, and restoration with
`server.registerWorktreeManager({ create, remove?, restore? })`. It runs after
`worktree.create.before` and before `worktree.create.after`, with a 120-second timeout matching Git
worktree commands. Paseo snapshots existing worktree paths before calling `create` so a manager
cannot adopt a pre-existing directory as Paseo-owned, verifies Git worktree postconditions, records
`worktreeManagerPluginId` in `paseo/worktree.json` and on the workspace record,
and skips first-agent branch auto-rename. Removal saves `refs/paseo/kept-commits/<sha>` before
calling the owning plugin's `remove`, and `create`, `remove`, and `restore` carry `untrusted` for fork
change requests; `remove` and `restore` fall back to built-in Git when the plugin declines or is disabled. See the
[worktree managers reference](../public-docs/plugins/reference.md#worktree-managers) and
`plugin-examples/worktrunk`.
Emit from the operation owner, not a client subscription. Provider history replay must not trigger
live hooks. Notifications must not be awaited inside agent mutations: a handler can send a prompt
or answer a permission through its own daemon session. Awaiting it there deadlocks that command.
+24 -1
View File
@@ -10,16 +10,19 @@ import {
expectColumnAtLeftGutter,
expectColumnClearOfOutline,
expectContentColumnWidth,
expectSharedHorizontalRail,
} from "../support/helpers/content-width";
import { openFileExplorer, openFileFromExplorer } from "../support/helpers/file-explorer";
import { openAgentRoute, seedMockAgentWorkspace } from "../support/helpers/mock-agent";
const ULTRAWIDE_VIEWPORT = { width: 2560, height: 1080 };
const DESKTOP_VIEWPORT = { width: 1440, height: 900 };
const TRANSITION_VIEWPORT = { width: 1250, height: 900 };
const DEFAULT_COLUMN = { min: 800, max: 820 };
const WIDE_COLUMN = { min: 1180, max: 1200 };
const FULL_COLUMN = { min: 2000, max: ULTRAWIDE_VIEWPORT.width };
test("resizes mounted chat content and leaves room for the outline at full width", async ({
test("resizes mounted chat content and keeps timeline and composer on one rail beside the outline", async ({
page,
}) => {
test.setTimeout(120_000);
@@ -37,26 +40,46 @@ test("resizes mounted chat content and leaves room for the outline at full width
await openAgentRoute(page, agent);
await expectChatOutlinePrompts(page, 2);
const reply = page.getByTestId("assistant-message").first();
const turnFooter = page.getByTestId("turn-footer").first();
const composer = page.getByTestId("message-input-root");
await expectContentColumnWidth(reply, DEFAULT_COLUMN);
await expectSharedHorizontalRail(turnFooter, composer);
const originalReply = await reply.elementHandle();
// In the transition band (pane ~930px >= 918px, < 820 + 120), Default clears the outline on one rail.
await page.setViewportSize(TRANSITION_VIEWPORT);
await expectColumnClearOfOutline(composer, chatOutlineRail(page));
await expectSharedHorizontalRail(turnFooter, composer);
await page.setViewportSize(ULTRAWIDE_VIEWPORT);
await chooseContentWidth(page, "Wide");
await expectContentColumnWidth(reply, WIDE_COLUMN);
await expectContentColumnWidth(composer, WIDE_COLUMN);
await expectSharedHorizontalRail(turnFooter, composer);
// At 1440px (pane ~1120px < 1200 + 120), Wide clears the outline and keeps timeline and composer aligned.
await page.setViewportSize(DESKTOP_VIEWPORT);
await expectColumnClearOfOutline(composer, chatOutlineRail(page));
await expectSharedHorizontalRail(turnFooter, composer);
await page.setViewportSize(ULTRAWIDE_VIEWPORT);
await chooseContentWidth(page, "Full");
await expectContentColumnWidth(reply, FULL_COLUMN);
await expectContentColumnWidth(composer, FULL_COLUMN);
await expectColumnClearOfOutline(reply, chatOutlineRail(page));
await expectColumnClearOfOutline(composer, chatOutlineRail(page));
await expectSharedHorizontalRail(turnFooter, composer);
await disableChatOutline(page);
await expectNoChatOutline(page);
await expectColumnAtLeftGutter(page, reply);
await expectColumnAtLeftGutter(page, composer);
await expectSharedHorizontalRail(turnFooter, composer);
await chooseContentWidth(page, "Default");
await expectContentColumnWidth(reply, DEFAULT_COLUMN);
await expectContentColumnWidth(composer, DEFAULT_COLUMN);
await expectSharedHorizontalRail(turnFooter, composer);
expect(await originalReply?.evaluate((node) => node.isConnected)).toBe(true);
} finally {
await agent.cleanup();
+2 -2
View File
@@ -233,8 +233,8 @@ test.describe("usage modal", () => {
],
});
await gotoAppShell(page);
// Three windows leave no room for labels in the summary, so it reads percents.
await expectPinnedUsage(page, ["31%", "20%", "12%"]);
// Three Weekly labels overflow the summary, so it falls back to compact shorthands.
await expectPinnedUsage(page, ["31% wk", "20% wk", "12% wk"]);
await openUsageFromItem(page);
await expectUsageCardOrder(page, ["alpha:a", "beta:home", "beta:work"]);
@@ -40,6 +40,7 @@ import {
usageModal,
installTallUsageSource,
} from "../support/helpers/usage-sidebar-item";
import { seedDockedSidebarWidth } from "../support/helpers/sidebar-footer-overflow";
import { seedSidebarFooterPreferences } from "../support/helpers/sidebar-nav-settings";
import { waitForSettledPosition } from "../support/helpers/sheet-layout";
import { createTempGitRepo } from "../support/helpers/workspace";
@@ -577,3 +578,97 @@ test("visible usage summary requests reports on load", async ({ page }) => {
await expectPinnedUsage(page, ["31% 5h", "54% wk", "7% 5h", "12% wk"]);
expect(usage.listRequests()).toHaveLength(1);
});
test("sidebar usage falls back to period shorthands before dropping all labels", async ({
page,
}) => {
test.setTimeout(120_000);
const [claude, codex] = claudeAndCodexReports();
const fetchedAt = new Date().toISOString();
await installUsageReportsFixture(page, {
lists: [
() => [
{
...codex!,
report: {
status: "available",
windows: [
{ id: "weekly", label: "Weekly", shortLabel: "wk", summary: true, usedPct: 97 },
],
},
},
{
...claude!,
report: {
status: "available",
windows: [
{ id: "five_hour", label: "Session", shortLabel: "5h", summary: true, usedPct: 100 },
{ id: "weekly", label: "Weekly", shortLabel: "wk", summary: true, usedPct: 14 },
{
id: "weekly_model_opus",
label: "Weekly · Opus",
shortLabel: "wk Opus",
summary: true,
usedPct: 22,
},
],
},
},
{
id: "antigravity:default",
account: {},
fetchedAt,
sourceId: "antigravity",
sourceLabel: "Antigravity",
report: {
status: "available",
windows: [
{
id: "gemini-weekly",
label: "Gemini Models · Weekly",
shortLabel: "Gemini wk",
summary: true,
usedPct: 6,
},
{
id: "gemini-5h",
label: "Gemini Models · 5h",
shortLabel: "Gemini 5h",
summary: true,
usedPct: 20,
},
],
},
},
],
],
});
await seedSidebarFooterPreferences(page, [{ key: "usage", visible: true }]);
await seedDockedSidebarWidth(page, 432);
await page.setViewportSize(WIDE);
await gotoAppShell(page);
await expectPinnedUsage(page, ["6% wk", "20% 5h", "100% 5h", "14% wk", "22% wk", "97% wk"]);
const handle = page.getByTestId("left-sidebar-resize-handle");
const dragSidebarTo = async (targetX: number) => {
const box = (await handle.boundingBox())!;
await page.mouse.move(box.x + box.width / 2, box.y + box.height / 2);
await page.mouse.down();
await page.mouse.move(targetX, box.y + box.height / 2, { steps: 10 });
await page.mouse.up();
};
await dragSidebarTo(600);
await expectPinnedUsage(page, [
"6% Gemini wk",
"20% Gemini 5h",
"100% 5h",
"14% wk",
"22% wk Opus",
"97% wk",
]);
await dragSidebarTo(300);
await expectPinnedUsage(page, ["6%", "20%", "100%", "14%", "22%", "97%"]);
});
@@ -22,7 +22,7 @@ type AgentSkillsClient = Pick<
"close" | "connect" | "getAgentSkillsStatus" | "saveAgentSkillsSelection"
>;
export type SkillTargetName = "agents" | "claude";
export type SkillTargetName = "agents" | "claude" | "antigravity";
export interface AgentSkillsSandbox {
available: string[];
@@ -64,6 +64,7 @@ export async function startAgentSkillsSandbox(): Promise<AgentSkillsSandbox> {
const targets = {
agents: path.join(home, ".agents", "skills"),
claude: path.join(home, ".claude", "skills"),
antigravity: path.join(home, ".gemini", "config", "skills"),
};
const codexSkillsDir = path.join(home, ".codex", "skills");
@@ -51,3 +51,18 @@ export async function expectColumnAtLeftGutter(page: Page, column: Locator): Pro
})
.toBeLessThanOrEqual(24);
}
/** Checks that two column surfaces sit on the same left and right vertical rails. */
export async function expectSharedHorizontalRail(first: Locator, second: Locator): Promise<void> {
await expect(first).toBeVisible({ timeout: 30_000 });
await expect(second).toBeVisible({ timeout: 30_000 });
await expect
.poll(async () => {
const [a, b] = await Promise.all([first.boundingBox(), second.boundingBox()]);
if (!a || !b) return Infinity;
const leftDelta = Math.abs(a.x - b.x);
const rightDelta = Math.abs(a.x + a.width - (b.x + b.width));
return Math.max(leftDelta, rightDelta);
})
.toBeLessThanOrEqual(1);
}
@@ -196,7 +196,7 @@ export interface SetupHost {
/**
* An isolated host whose only agent history is the Claude sessions given here, so suggestions
* never depend on the machine running the test. Its HOME is a scratch folder, so the skills setup
* installs never land in the real ~/.agents, ~/.claude or ~/.codex. `withBrokenProvider` adds a
* installs never land in the real ~/.agents, ~/.claude, ~/.codex, or ~/.gemini/config. `withBrokenProvider` adds a
* provider that cannot start.
*/
export async function startSetupHost(
@@ -66,4 +66,23 @@ describe("fetchAgentCommands", () => {
expect(client.calls).toEqual([{ agentId: "agent-1", draftConfig: undefined }]);
});
it("deduplicates duplicate command names from the daemon, keeping the first entry", async () => {
const client = createClient(
commandsPayload([
{ name: "goal", description: "Run until goal is finished", argumentHint: "" },
{ name: "plan", description: "Plan carefully before executing a task.", argumentHint: "" },
{ name: "plan", description: "Local plan skill description", argumentHint: "" },
{ name: "review", description: "Review changes", argumentHint: "" },
]),
);
const commands = await fetchAgentCommands({ client, agentId: "agent-1" });
expect(commands).toEqual([
{ name: "goal", description: "Run until goal is finished", argumentHint: "" },
{ name: "plan", description: "Plan carefully before executing a task.", argumentHint: "" },
{ name: "review", description: "Review changes", argumentHint: "" },
]);
});
});
+13 -1
View File
@@ -37,6 +37,18 @@ export interface AgentCommandsClient {
listCommands(options: ListAgentCommandsOptions): ReturnType<DaemonClient["listCommands"]>;
}
// COMPAT(dedupeListCommands): added in v0.17.0, remove after 2027-05-20 once daemon floor >= v0.17.0.
function dedupeSlashCommands(commands: readonly AgentSlashCommand[]): AgentSlashCommand[] {
const seen = new Set<string>();
const unique: AgentSlashCommand[] = [];
for (const command of commands) {
if (seen.has(command.name)) continue;
seen.add(command.name);
unique.push(command);
}
return unique;
}
export async function fetchAgentCommands(input: {
client: AgentCommandsClient;
agentId: string;
@@ -47,7 +59,7 @@ export async function fetchAgentCommands(input: {
draftConfig: input.draftConfig,
});
if (response.error) throw new Error(response.error);
return response.commands as AgentSlashCommand[];
return dedupeSlashCommands(response.commands as AgentSlashCommand[]);
}
interface UseAgentCommandsQueryOptions {
@@ -0,0 +1,7 @@
import { SPACING } from "@/styles/theme";
// Outline rail geometry shared between the rail overlay and the chat pane's column rail.
export const CHAT_OUTLINE_RAIL_WIDTH = 36;
export const CHAT_OUTLINE_RAIL_LEFT = SPACING[2];
export const CHAT_OUTLINE_MIN_PANEL_WIDTH = 918;
export const CHAT_OUTLINE_GUTTER_INSET = CHAT_OUTLINE_RAIL_LEFT + CHAT_OUTLINE_RAIL_WIDTH;
@@ -11,7 +11,3 @@ export interface ChatOutlineRailProps {
export function ChatOutlineRail(_props: ChatOutlineRailProps): null {
return null;
}
export function useChatOutlineRailLayout(_enabled: boolean) {
return { onLayout: undefined, inset: 0 };
}
@@ -2,19 +2,17 @@ import { memo, useCallback, useEffect, useMemo, useState, useSyncExternalStore }
import { Pressable, Text, View, type PointerEvent as RNPointerEvent } from "react-native";
import { StyleSheet } from "react-native-unistyles";
import { useReducedMotion } from "react-native-reanimated";
import { useContainerWidthBelow } from "@/hooks/use-container-width";
import { SPACING } from "@/styles/theme";
import { inlineUnistylesStyle } from "@/styles/unistyles-inline-style";
import { CHAT_OUTLINE_RAIL_LEFT, CHAT_OUTLINE_RAIL_WIDTH } from "./geometry";
import { createChatOutlineHoverIntent } from "./hover-intent";
import { promptTickMagnification } from "./model";
import type { ChatOutlineRailProps } from "./rail";
// Hover tracking lives on the rail and the slots, never on the Pressable inside them:
// magnifying a slot must not move the box the pointer is resting on. See docs/hover.md.
const RAIL_WIDTH = 36;
const RAIL_LEFT = SPACING[2];
const RAIL_WIDTH = CHAT_OUTLINE_RAIL_WIDTH;
const RAIL_LEFT = CHAT_OUTLINE_RAIL_LEFT;
const SLOT_HEIGHT = 8;
const MIN_PANEL_WIDTH = 918;
const RESTING_PILL_HEIGHT = 2;
const MAGNIFIED_PILL_HEIGHT = 4;
const RESTING_PILL_WIDTH = 10;
@@ -24,11 +22,6 @@ const PREVIEW_WIDTH = 260;
const PREVIEW_HEIGHT = 48;
const PREVIEW_GAP = 4;
export function useChatOutlineRailLayout(enabled: boolean) {
const { onLayout, isBelow } = useContainerWidthBelow(MIN_PANEL_WIDTH);
return { onLayout, inset: enabled && !isBelow ? RAIL_LEFT + RAIL_WIDTH : 0 };
}
export const ChatOutlineRail = memo(function ChatOutlineRail({
prompts,
activePrompt,
@@ -40,6 +40,7 @@ import {
type HistoryStartSettleScheduler,
} from "./history-start-settle-scheduler";
import { useChatFindSelectedMessageId } from "@/agent-stream/chat-find";
import { CHAT_COLUMN_BASE_GUTTER, resolveChatColumnGutters } from "@/chat-rail/gutters";
import { useScrollToMessage } from "./use-scroll-to-message.web";
interface CreateWebStreamStrategyInput {
@@ -1228,21 +1229,20 @@ function WebStreamViewport(props: StreamRenderInput & { isMobileBreakpoint: bool
]);
const contentContainerStyle = useMemo((): CSSProperties => {
const gutter = isMobileBreakpoint ? 8 : 16;
const leftGutter = gutter + outlineInset;
// Balance the outline gutter using only the space the capped column has left over.
const rightGutter =
outlineInset > 0 && contentMaxWidth !== undefined
? `clamp(${gutter}px, calc(100% - ${leftGutter + contentMaxWidth}px), ${leftGutter}px)`
: gutter;
const gutter = isMobileBreakpoint ? 8 : CHAT_COLUMN_BASE_GUTTER;
const { paddingLeft, paddingRight } = resolveChatColumnGutters({
gutter,
outlineInset,
contentMaxWidth,
});
return {
display: "flex",
flexDirection: "column",
minHeight: "100%",
paddingTop: CONTENT_PADDING_TOP_PX,
paddingBottom: 16,
paddingLeft: leftGutter,
paddingRight: rightGutter,
paddingLeft,
paddingRight,
boxSizing: "border-box",
};
}, [contentMaxWidth, isMobileBreakpoint, outlineInset]);
+9 -17
View File
@@ -80,8 +80,9 @@ import { resolveStreamRenderStrategy } from "./strategy-resolver";
import { type StreamSegmentRenderers, type StreamViewportHandle } from "./strategy";
import { renderStreamRow, type RenderStreamItem } from "./stream-row";
import { type NearBottom, useIsNearBottom, useNearBottom } from "./near-bottom";
import { ChatOutlineRail, useChatOutlineRailLayout } from "@/agent-stream/chat-outline/rail";
import { ChatOutlineRail } from "@/agent-stream/chat-outline/rail";
import { useChatOutline } from "@/agent-stream/chat-outline/use-chat-outline";
import { CHAT_COLUMN_RAIL_DATASET, useChatOutlineRail } from "@/chat-rail";
import { getHostRuntimeStore } from "@/runtime/host-runtime";
import { planTimelineTailFetch } from "@/timeline/timeline-sync-plan";
import {
@@ -322,7 +323,7 @@ function ScrollToBottomButton({
);
if (isNearBottom && !isTimelineDetached) return null;
return (
<View style={containerStyle} pointerEvents="box-none">
<View style={containerStyle} dataSet={CHAT_COLUMN_RAIL_DATASET} pointerEvents="box-none">
<Animated.View entering={scrollIndicatorFadeIn} exiting={scrollIndicatorFadeOut}>
<Pressable
style={stylesheet.scrollToBottomButton}
@@ -365,7 +366,6 @@ const AgentStreamViewComponent = forwardRef<AgentStreamViewHandle, AgentStreamVi
const { t } = useTranslation();
const autoExpandReasoning = useSettings((settings) => settings.autoExpandReasoning);
const chatDisplay = useSettings((settings) => settings.chatDisplay);
const chatOutlineEnabled = useSettings((settings) => settings.chatOutlineEnabled);
const contentMaxWidth = useSettings(resolveContentMaxWidth);
const viewportRef = useRef<StreamViewportHandle | null>(null);
const pendingClientMessageIds = useMemo(
@@ -404,10 +404,6 @@ const AgentStreamViewComponent = forwardRef<AgentStreamViewHandle, AgentStreamVi
(state) =>
state.sessions[resolvedServerId]?.serverInfo?.features?.agentForkContextCursor === true,
);
const supportsChatOutline = useSessionStore(
(state) =>
state.sessions[resolvedServerId]?.serverInfo?.features?.agentTimelinePromptIndex === true,
);
const timelineEpoch = useSessionStore(
(state) => state.sessions[resolvedServerId]?.agentTimelineCursor.get(agentId)?.epoch ?? null,
);
@@ -617,22 +613,21 @@ const AgentStreamViewComponent = forwardRef<AgentStreamViewHandle, AgentStreamVi
mountedHistoryMessageIds.has(messageId) || liveHeadMessageIds.has(messageId),
};
}, [baseRenderModel.segments.liveHead, mountedHistoryMessageIds]);
const outlineEnabled = supportsChatOutline && chatOutlineEnabled;
const outlineRail = useChatOutlineRail();
const outlineInset = outlineRail.inset;
const chatOutline = useChatOutline({
agentId,
serverId: resolvedServerId,
timelineEpoch,
tail: effectiveStreamItems,
head: effectiveStreamHead,
enabled: outlineEnabled,
enabled: outlineRail.enabled,
viewportRef,
onJumpError: handleTimelineHistoryLoadError,
mountedHistoryMessageIds,
revealLoadedMessage: revealLoadedHistory,
});
const outlineLayout = useChatOutlineRailLayout(outlineEnabled);
useImperativeHandle(
ref,
() => ({
@@ -1176,10 +1171,7 @@ const AgentStreamViewComponent = forwardRef<AgentStreamViewHandle, AgentStreamVi
visibleMessageIds={mountedMessageIds}
>
<ToolCallSheetProvider>
<AssistantSelectionCopySurface
style={stylesheet.container}
onLayout={outlineLayout.onLayout}
>
<AssistantSelectionCopySurface style={stylesheet.container}>
<MessageOuterSpacingProvider disableOuterSpacing>
<ToolCallExpansionContext.Provider value={toolCallExpansion}>
<UserMessageExpansionContext.Provider value={userMessageExpansion}>
@@ -1208,12 +1200,12 @@ const AgentStreamViewComponent = forwardRef<AgentStreamViewHandle, AgentStreamVi
baseListContentContainerStyle: stylesheet.listContentContainer,
forwardListContentContainerStyle: stylesheet.forwardListContentContainer,
contentMaxWidth,
outlineInset: outlineLayout.inset,
outlineInset,
})}
</UserMessageExpansionContext.Provider>
</ToolCallExpansionContext.Provider>
</MessageOuterSpacingProvider>
{outlineLayout.inset > 0 && chatOutline.prompts.length >= 2 ? (
{outlineInset > 0 && chatOutline.prompts.length >= 2 ? (
<ChatOutlineRail
prompts={chatOutline.prompts}
activePrompt={chatOutline.activePrompt}
@@ -1,20 +1,14 @@
import type { ReactNode } from "react";
import { View, type LayoutChangeEvent, type StyleProp, type ViewStyle } from "react-native";
import { View, type StyleProp, type ViewStyle } from "react-native";
interface AssistantSelectionCopySurfaceProps {
children: ReactNode;
style?: StyleProp<ViewStyle>;
onLayout?: (event: LayoutChangeEvent) => void;
}
export function AssistantSelectionCopySurface({
children,
style,
onLayout,
}: AssistantSelectionCopySurfaceProps) {
return (
<View style={style} onLayout={onLayout}>
{children}
</View>
);
return <View style={style}>{children}</View>;
}
@@ -1,11 +1,10 @@
import { useCallback, type ClipboardEvent, type CSSProperties, type ReactNode } from "react";
import { View, type LayoutChangeEvent, type StyleProp, type ViewStyle } from "react-native";
import { View, type StyleProp, type ViewStyle } from "react-native";
import { createAssistantSelectionClipboardContent } from "./content.web";
interface AssistantSelectionCopySurfaceProps {
children: ReactNode;
style?: StyleProp<ViewStyle>;
onLayout?: (event: LayoutChangeEvent) => void;
}
const DISPLAY_CONTENTS: CSSProperties = { display: "contents" };
@@ -13,7 +12,6 @@ const DISPLAY_CONTENTS: CSSProperties = { display: "contents" };
export function AssistantSelectionCopySurface({
children,
style,
onLayout,
}: AssistantSelectionCopySurfaceProps) {
const handleCopy = useCallback((event: ClipboardEvent<HTMLDivElement>) => {
const content = createAssistantSelectionClipboardContent(window.getSelection());
@@ -28,9 +26,7 @@ export function AssistantSelectionCopySurface({
return (
<div onCopy={handleCopy} style={DISPLAY_CONTENTS}>
<View style={style} onLayout={onLayout}>
{children}
</View>
<View style={style}>{children}</View>
</div>
);
}
@@ -0,0 +1,77 @@
import { describe, expect, it } from "vitest";
import { CHAT_OUTLINE_GUTTER_INSET } from "@/agent-stream/chat-outline/geometry";
import { CHAT_COLUMN_BASE_GUTTER, resolveChatColumnGutters } from "./gutters";
import {
CHAT_COLUMN_RAIL_DATASET as NATIVE_CHAT_COLUMN_RAIL_DATASET,
ChatColumnRailSurface as NativeChatColumnRailSurface,
useChatOutlineRail as useNativeChatOutlineRail,
} from "./index.native";
import { CHAT_COLUMN_RAIL_DATASET as WEB_CHAT_COLUMN_RAIL_DATASET } from "./index.web";
describe("resolveChatColumnGutters", () => {
it("uses symmetric base gutters when no outline inset is reserved", () => {
expect(
resolveChatColumnGutters({
gutter: CHAT_COLUMN_BASE_GUTTER,
outlineInset: 0,
contentMaxWidth: 820,
}),
).toEqual({ paddingLeft: 16, paddingRight: 16 });
expect(
resolveChatColumnGutters({
gutter: CHAT_COLUMN_BASE_GUTTER,
outlineInset: 0,
contentMaxWidth: undefined,
}),
).toEqual({ paddingLeft: 16, paddingRight: 16 });
});
it("reserves only the left outline gutter when content width is Full", () => {
expect(
resolveChatColumnGutters({
gutter: CHAT_COLUMN_BASE_GUTTER,
outlineInset: CHAT_OUTLINE_GUTTER_INSET,
contentMaxWidth: undefined,
}),
).toEqual({ paddingLeft: 60, paddingRight: 16 });
});
it("balances capped columns with a clamped right gutter from the remaining width", () => {
expect(
resolveChatColumnGutters({
gutter: CHAT_COLUMN_BASE_GUTTER,
outlineInset: CHAT_OUTLINE_GUTTER_INSET,
contentMaxWidth: 820,
}),
).toEqual({
paddingLeft: 60,
paddingRight: "clamp(16px, calc(100% - 880px), 60px)",
});
expect(
resolveChatColumnGutters({
gutter: CHAT_COLUMN_BASE_GUTTER,
outlineInset: CHAT_OUTLINE_GUTTER_INSET,
contentMaxWidth: 1200,
}),
).toEqual({
paddingLeft: 60,
paddingRight: "clamp(16px, calc(100% - 1260px), 60px)",
});
});
});
describe("native and web chat-rail boundaries", () => {
it("keeps native as a zero-overhead pass-through with no dataset or outline inset", () => {
const sentinel = "child";
expect(NATIVE_CHAT_COLUMN_RAIL_DATASET).toBeUndefined();
expect(useNativeChatOutlineRail()).toEqual({ enabled: false, inset: 0 });
expect(NativeChatColumnRailSurface({ serverId: "srv-1", children: sentinel })).toBe(sentinel);
});
it("tags web rail lanes with a frozen dataset reference", () => {
expect(WEB_CHAT_COLUMN_RAIL_DATASET).toEqual({ chatRailLane: "true" });
expect(Object.isFrozen(WEB_CHAT_COLUMN_RAIL_DATASET)).toBe(true);
});
});
+30
View File
@@ -0,0 +1,30 @@
import { SPACING } from "@/styles/theme";
export const CHAT_COLUMN_BASE_GUTTER = SPACING[4];
export interface ChatColumnGutters {
paddingLeft: number;
paddingRight: number | string;
}
/**
* Horizontal padding for a chat column on web.
*
* When the chat outline reserves `outlineInset` on the left, a capped column matches
* that inset on the right using only the horizontal slack left over after fitting
* `contentMaxWidth`. Default and Wide stay centered while the pane has room, shift
* smoothly away from the outline as the pane narrows, and fall back to the base gutter
* on the right when uncapped (`Full`) or tight.
*/
export function resolveChatColumnGutters(input: {
gutter: number;
outlineInset: number;
contentMaxWidth: number | undefined;
}): ChatColumnGutters {
const paddingLeft = input.gutter + input.outlineInset;
const paddingRight =
input.outlineInset > 0 && input.contentMaxWidth !== undefined
? `clamp(${input.gutter}px, calc(100% - ${paddingLeft + input.contentMaxWidth}px), ${paddingLeft}px)`
: input.gutter;
return { paddingLeft, paddingRight };
}
@@ -0,0 +1,39 @@
import type { ReactNode } from "react";
export interface ChatColumnRailSurfaceProps {
serverId: string;
children: ReactNode;
}
export interface ChatOutlineRailState {
/** Whether the chat outline feature is enabled for this pane (independent of pane width). */
readonly enabled: boolean;
/** Left gutter inset currently reserved for the outline rail (`0` or `44` on web). */
readonly inset: number;
}
const DISABLED_CHAT_OUTLINE_RAIL: ChatOutlineRailState = Object.freeze({
enabled: false,
inset: 0,
});
/**
* Marker for chat surfaces (composer, track bar, callouts) that share the pane's
* horizontal column rail. On web, an active `ChatColumnRailSurface` applies the
* pane's outline-aware gutters via CSS custom properties without re-rendering
* children. Native never reserves an outline gutter, so this is undefined.
*/
export const CHAT_COLUMN_RAIL_DATASET: Record<string, string> | undefined = undefined;
/**
* Native pass-through: the chat outline is a wide-layout web affordance, so native
* renders no wrapper view, registers no subscriptions, and reserves no outline inset.
*/
export function ChatColumnRailSurface({ children }: ChatColumnRailSurfaceProps) {
return children;
}
/** Chat outline state for this pane (always disabled with 0 inset on native). */
export function useChatOutlineRail(): ChatOutlineRailState {
return DISABLED_CHAT_OUTLINE_RAIL;
}
+7
View File
@@ -0,0 +1,7 @@
export {
CHAT_COLUMN_RAIL_DATASET,
ChatColumnRailSurface,
useChatOutlineRail,
type ChatColumnRailSurfaceProps,
type ChatOutlineRailState,
} from "./index.native";
+143
View File
@@ -0,0 +1,143 @@
import {
createContext,
useContext,
useLayoutEffect,
useMemo,
useRef,
useState,
type CSSProperties,
} from "react";
import {
CHAT_OUTLINE_GUTTER_INSET,
CHAT_OUTLINE_MIN_PANEL_WIDTH,
} from "@/agent-stream/chat-outline/geometry";
import { resolveContentMaxWidth, useSettings } from "@/hooks/use-settings";
import { useSessionStore } from "@/stores/session-store";
import { CHAT_COLUMN_BASE_GUTTER, resolveChatColumnGutters } from "./gutters";
import type { ChatColumnRailSurfaceProps, ChatOutlineRailState } from "./index";
export type { ChatColumnRailSurfaceProps, ChatOutlineRailState };
const STYLE_ID = "paseo-chat-column-rail";
// React Native Web turns `dataSet={{ chatRailLane: "true" }}` into `data-chat-rail-lane="true"`.
// When the enclosing pane reserves an outline gutter, every tagged rail consumer receives
// the same horizontal gutters in the browser's layout pass without re-rendering React subtrees
// or growing Unistyles' CSS registry.
const RAIL_RULE =
'[data-chat-rail-active="true"] [data-chat-rail-lane="true"]{padding-left:var(--paseo-chat-rail-left)!important;padding-right:var(--paseo-chat-rail-right)!important;}';
const BASE_SURFACE_STYLE: CSSProperties = {
display: "flex",
flexDirection: "column",
flex: 1,
minWidth: 0,
minHeight: 0,
};
const DISABLED_CHAT_OUTLINE_RAIL: ChatOutlineRailState = Object.freeze({
enabled: false,
inset: 0,
});
const ChatOutlineRailContext = createContext<ChatOutlineRailState>(DISABLED_CHAT_OUTLINE_RAIL);
export const CHAT_COLUMN_RAIL_DATASET: Record<string, string> | undefined = Object.freeze({
chatRailLane: "true",
});
function ensureChatColumnRailStyle(): void {
if (typeof document === "undefined") return;
if (document.getElementById(STYLE_ID)) return;
const style = document.createElement("style");
style.id = STYLE_ID;
style.textContent = RAIL_RULE;
document.head.appendChild(style);
}
function cssLength(value: number | string): string {
return typeof value === "number" ? `${value}px` : value;
}
/**
* Pane-level owner of the chat column rail on web.
*
* Measures the pane width once against `CHAT_OUTLINE_MIN_PANEL_WIDTH` (ignoring 0px
* measurements from hidden retained tabs) and publishes the resolved horizontal gutters
* via CSS custom properties to the composer, track bar, and callouts. Only the outline
* enabled flag and reserved inset (`0` or `44`) enter React context for `AgentStreamView`.
*/
export function ChatColumnRailSurface({ serverId, children }: ChatColumnRailSurfaceProps) {
const surfaceRef = useRef<HTMLDivElement | null>(null);
const [isBelow, setIsBelow] = useState(true);
const chatOutlineEnabled = useSettings((settings) => settings.chatOutlineEnabled);
const contentMaxWidth = useSettings(resolveContentMaxWidth);
const supportsChatOutline = useSessionStore(
(state) => state.sessions[serverId]?.serverInfo?.features?.agentTimelinePromptIndex === true,
);
useLayoutEffect(() => {
const node = surfaceRef.current;
if (!node) return;
const update = (width: number) => {
// Retained inactive tabs sit under `display: none` and report 0; ignore them.
if (width <= 0) return;
const next = width < CHAT_OUTLINE_MIN_PANEL_WIDTH;
setIsBelow((current) => (current === next ? current : next));
};
update(node.getBoundingClientRect().width);
if (typeof ResizeObserver === "undefined") return;
const observer = new ResizeObserver((entries) => {
const width =
entries[entries.length - 1]?.contentRect.width ?? node.getBoundingClientRect().width;
update(width);
});
observer.observe(node);
return () => observer.disconnect();
}, []);
const enabled = supportsChatOutline && chatOutlineEnabled;
const inset = enabled && !isBelow ? CHAT_OUTLINE_GUTTER_INSET : 0;
useLayoutEffect(() => {
if (inset > 0) {
ensureChatColumnRailStyle();
}
}, [inset]);
const outlineRail = useMemo<ChatOutlineRailState>(
() => (enabled ? { enabled, inset } : DISABLED_CHAT_OUTLINE_RAIL),
[enabled, inset],
);
const surfaceStyle = useMemo((): CSSProperties => {
if (inset === 0) {
return BASE_SURFACE_STYLE;
}
const gutters = resolveChatColumnGutters({
gutter: CHAT_COLUMN_BASE_GUTTER,
outlineInset: inset,
contentMaxWidth,
});
return {
...BASE_SURFACE_STYLE,
"--paseo-chat-rail-left": cssLength(gutters.paddingLeft),
"--paseo-chat-rail-right": cssLength(gutters.paddingRight),
} as CSSProperties;
}, [contentMaxWidth, inset]);
return (
<ChatOutlineRailContext.Provider value={outlineRail}>
<div
ref={surfaceRef}
style={surfaceStyle}
data-chat-rail-active={inset > 0 ? "true" : undefined}
>
{children}
</div>
</ChatOutlineRailContext.Provider>
);
}
export function useChatOutlineRail(): ChatOutlineRailState {
return useContext(ChatOutlineRailContext);
}
@@ -2,6 +2,7 @@ import { useCallback, useState } from "react";
import { View, Text } from "react-native";
import { useTranslation } from "react-i18next";
import { StyleSheet } from "react-native-unistyles";
import { CHAT_COLUMN_RAIL_DATASET } from "@/chat-rail";
import { FOOTER_HEIGHT } from "@/constants/layout";
import { useHostRuntimeClient, useHostRuntimeIsConnected } from "@/runtime/host-runtime";
import { KeyboardTranslateView } from "@/keyboard/shift";
@@ -35,7 +36,7 @@ export function ArchivedAgentCallout({ serverId, agentId }: ArchivedAgentCallout
return (
<KeyboardTranslateView style={styles.container}>
<View style={styles.inputAreaContainer}>
<View style={styles.inputAreaContainer} dataSet={CHAT_COLUMN_RAIL_DATASET}>
<View style={styles.inputAreaContent}>
<View style={styles.calloutStack}>
<View style={styles.callout}>
@@ -4,6 +4,7 @@ import type { JsonValue } from "@getpaseo/protocol/agent-types";
import { Keyboard, StyleSheet as RNStyleSheet, Text, View } from "react-native";
import { useTranslation } from "react-i18next";
import { StyleSheet } from "react-native-unistyles";
import { CHAT_COLUMN_RAIL_DATASET } from "@/chat-rail";
import { useContainerWidthBelow } from "@/hooks/use-container-width";
import invariant from "tiny-invariant";
import { Composer } from "@/composer";
@@ -536,14 +537,17 @@ export function WorkspaceDraftComposer({
return (
<View style={animatedStaticStyles.inputAreaWrapper} onLayout={onInputAreaLayout}>
{formErrorMessage ? (
<View style={styles.formErrorRow}>
<View
style={styles.formErrorRow}
dataSet={isComposerFullscreen ? undefined : CHAT_COLUMN_RAIL_DATASET}
>
<View style={styles.formError}>
<Text style={styles.errorText}>{formErrorMessage}</Text>
</View>
</View>
) : null}
{importPillPress && !isComposerFullscreen ? (
<View style={styles.importPillRow}>
<View style={styles.importPillRow} dataSet={CHAT_COLUMN_RAIL_DATASET}>
<View style={styles.importPillContent}>
<ComposerImportPill onPress={importPillPress} />
</View>
+5 -1
View File
@@ -30,6 +30,7 @@ import {
} from "react";
import { useTranslation } from "react-i18next";
import { StyleSheet, withUnistyles } from "react-native-unistyles";
import { CHAT_COLUMN_RAIL_DATASET } from "@/chat-rail";
import { useIsCompactFormFactor } from "@/constants/layout";
import {
controlSizingForLayout,
@@ -2575,7 +2576,10 @@ function ComposerContentImpl({
>
<AttachmentLightbox source={lightboxSource} onClose={handleLightboxClose} />
{/* Input area */}
<View style={inputAreaContainerStyle}>
<View
style={inputAreaContainerStyle}
dataSet={isFullscreen ? undefined : CHAT_COLUMN_RAIL_DATASET}
>
<View style={inputAreaContentStyle}>
{isFullscreen ? null : queueList}
{!isFullscreen && sendErrorNode}
+2 -1
View File
@@ -21,6 +21,7 @@ import {
useHorizontalScrollBoundary,
} from "@/components/ui/horizontal-scroll-boundary";
import { STATUS_RING_HALO_INSET } from "@/components/status-ring/geometry";
import { CHAT_COLUMN_RAIL_DATASET } from "@/chat-rail";
import { isWeb } from "@/constants/platform";
import { usePanelAwareHorizontalScrollGesture } from "@/mobile-panels/gestures";
import { getStatusDotColor } from "@/utils/status-dot-color";
@@ -45,7 +46,7 @@ export function ComposerTrackBar({ children }: { children: ReactNode }): ReactEl
const scrollGesture = usePanelAwareHorizontalScrollGesture();
const scrollBoundary = useHorizontalScrollBoundary();
return (
<View style={styles.bar} pointerEvents="box-none">
<View style={styles.bar} dataSet={CHAT_COLUMN_RAIL_DATASET} pointerEvents="box-none">
<View style={styles.trackViewport} pointerEvents="box-none">
<GestureDetector gesture={scrollGesture}>
<Animated.ScrollView
+3 -2
View File
@@ -2892,7 +2892,8 @@ export const ar: TranslationResources = {
updateAvailable: "التحديث متاح",
updateTitle: "تحديث مهارات Paseo ؟",
uninstallTitle: "إلغاء تثبيت مهارات Paseo ؟",
uninstallMessage: "يزيل جميع مهارات تنسيق Paseo من ~/.agents ، ~/.claude ، ~/.codex.",
uninstallMessage:
"يزيل جميع مهارات تنسيق Paseo من ~/.agents و~/.claude و~/.codex و~/.gemini/config.",
choose: "اختيار المهارات",
chooseAll: "كل المهارات",
chooseAllHint: "أبقِ جميع المهارات المرفقة مثبتة، بما فيها ما يُضاف لاحقًا.",
@@ -2900,7 +2901,7 @@ export const ar: TranslationResources = {
chooseEmpty: "لا تتضمن هذه النسخة أي مهارات.",
removeTitle: "إزالة المهارات غير المحددة؟",
removeMessage:
"سيتم حذف {{skills}} من ~/.agents و~/.claude و~/.codex. كما يُحذف كل ما أضفته داخل مجلدات المهارات تلك.",
"سيتم حذف {{skills}} من ~/.agents و~/.claude و~/.codex و~/.gemini/config. كما يُحذف كل ما أضفته داخل مجلدات المهارات تلك.",
saveFailed: "تعذر حفظ اختيار المهارات.",
statusFailed: "غير قادر على التحقق من حالة مهارات التنسيق.",
updateFailed: "غير قادر على تحديث مهارات التنسيق.",
+2 -2
View File
@@ -2994,7 +2994,7 @@ export const en = {
updateTitle: "Update Paseo skills?",
uninstallTitle: "Uninstall Paseo skills?",
uninstallMessage:
"Removes all Paseo orchestration skills from ~/.agents, ~/.claude, ~/.codex on this host.",
"Removes all Paseo orchestration skills from ~/.agents, ~/.claude, ~/.codex, and ~/.gemini/config on this host.",
choose: "Choose skills",
chooseAll: "All skills",
chooseAllHint: "Keep every bundled skill installed, including ones added later.",
@@ -3002,7 +3002,7 @@ export const en = {
chooseEmpty: "This host bundles no skills.",
removeTitle: "Remove deselected skills?",
removeMessage:
"{{skills}} will be deleted from ~/.agents, ~/.claude, and ~/.codex on this host. Anything you added inside those skill folders is deleted too.",
"{{skills}} will be deleted from ~/.agents, ~/.claude, ~/.codex, and ~/.gemini/config on this host. Anything you added inside those skill folders is deleted too.",
saveFailed: "Could not save your skill selection.",
actions: {
update: "Update",
+2 -2
View File
@@ -2916,7 +2916,7 @@ export const es: TranslationResources = {
updateTitle: "¿Actualizar las habilidades dePaseo?",
uninstallTitle: "¿Desinstalar las habilidadesPaseo?",
uninstallMessage:
"Elimina todas las habilidades de orquestaciónPaseode ~/.agents, ~/.claude, ~/.codex.",
"Elimina todas las habilidades de orquestación Paseo de ~/.agents, ~/.claude, ~/.codex y ~/.gemini/config.",
choose: "Elegir habilidades",
chooseAll: "Todas las habilidades",
chooseAllHint:
@@ -2925,7 +2925,7 @@ export const es: TranslationResources = {
chooseEmpty: "Esta versión no incluye habilidades.",
removeTitle: "¿Eliminar las habilidades deseleccionadas?",
removeMessage:
"{{skills}} se eliminarán de ~/.agents, ~/.claude y ~/.codex. También se elimina todo lo que hayas añadido dentro de esas carpetas de habilidades.",
"{{skills}} se eliminarán de ~/.agents, ~/.claude, ~/.codex y ~/.gemini/config. También se elimina todo lo que hayas añadido dentro de esas carpetas de habilidades.",
saveFailed: "No se pudo guardar tu selección de habilidades.",
statusFailed: "No se puede comprobar el estado de las habilidades de orquestación.",
updateFailed: "No se pueden actualizar las habilidades de orquestación.",
+2 -2
View File
@@ -2919,7 +2919,7 @@ export const fr: TranslationResources = {
updateTitle: "Mettre à jour les skills Paseo ?",
uninstallTitle: "Désinstaller les skills Paseo ?",
uninstallMessage:
"Supprime tous les skills d’orchestration Paseo de ~/.agents, ~/.claude et ~/.codex sur cet hôte.",
"Supprime tous les skills d’orchestration Paseo de ~/.agents, ~/.claude, ~/.codex et ~/.gemini/config sur cet hôte.",
choose: "Choisir les skills",
chooseAll: "Tous les skills",
chooseAllHint:
@@ -2928,7 +2928,7 @@ export const fr: TranslationResources = {
chooseEmpty: "Cet hôte ne fournit aucun skill.",
removeTitle: "Supprimer les skills décochés ?",
removeMessage:
"{{skills}} seront supprimés de ~/.agents, ~/.claude et ~/.codex sur cet hôte. Tout ce que vous avez ajouté dans ces dossiers de skills sera également supprimé.",
"{{skills}} seront supprimés de ~/.agents, ~/.claude, ~/.codex et ~/.gemini/config sur cet hôte. Tout ce que vous avez ajouté dans ces dossiers de skills sera également supprimé.",
saveFailed: "Impossible d’enregistrer votre sélection de skills.",
statusFailed: "Impossible de vérifier l’état des skills d’orchestration.",
updateFailed: "Impossible de mettre à jour les skills d’orchestration.",
+2 -2
View File
@@ -2884,7 +2884,7 @@ export const ja: TranslationResources = {
updateTitle: "Paseoスキルを更新しますか?",
uninstallTitle: "Paseoスキルをアンインストールしますか?",
uninstallMessage:
"~/.agents、~/.claude、~/.codexからすべてのPaseoオーケストレーションスキルを削除します。",
"~/.agents、~/.claude、~/.codex、~/.gemini/configからすべてのPaseoオーケストレーションスキルを削除します。",
choose: "スキルを選択",
chooseAll: "すべてのスキル",
chooseAllHint:
@@ -2893,7 +2893,7 @@ export const ja: TranslationResources = {
chooseEmpty: "このビルドにはスキルが含まれていません。",
removeTitle: "選択を外したスキルを削除しますか?",
removeMessage:
"{{skills}} を ~/.agents、~/.claude、~/.codex から削除します。それらのスキルフォルダー内に追加したものもすべて削除されます。",
"{{skills}} を ~/.agents、~/.claude、~/.codex、~/.gemini/config から削除します。それらのスキルフォルダー内に追加したものもすべて削除されます。",
saveFailed: "スキルの選択を保存できませんでした。",
statusFailed: "オーケストレーションスキルのステータスを確認できません。",
updateFailed: "オーケストレーションスキルを更新できません。",
+2 -2
View File
@@ -2871,7 +2871,7 @@ export const ko: TranslationResources = {
updateTitle: "Paseo 스킬을 업데이트할까요?",
uninstallTitle: "Paseo 스킬을 제거할까요?",
uninstallMessage:
"~/.agents, ~/.claude, ~/.codex에서 모든 Paseo 오케스트레이션 스킬을 제거합니다.",
"~/.agents, ~/.claude, ~/.codex, ~/.gemini/config에서 모든 Paseo 오케스트레이션 스킬을 제거합니다.",
choose: "스킬 선택",
chooseAll: "모든 스킬",
chooseAllHint: "나중에 추가되는 항목을 포함하여 모든 번들 스킬을 설치된 상태로 유지합니다.",
@@ -2879,7 +2879,7 @@ export const ko: TranslationResources = {
chooseEmpty: "이 빌드에는 번들 스킬이 없습니다.",
removeTitle: "선택 해제한 스킬을 제거할까요?",
removeMessage:
"{{skills}}는 ~/.agents, ~/.claude 및 ~/.codex에서 삭제됩니다. 해당 스킬 폴더 안에 추가한 모든 항목도 삭제됩니다.",
"{{skills}}는 ~/.agents, ~/.claude, ~/.codex 및 ~/.gemini/config에서 삭제됩니다. 해당 스킬 폴더 안에 추가한 모든 항목도 삭제됩니다.",
saveFailed: "선택한 스킬을 저장하지 못했습니다.",
statusFailed: "오케스트레이션 스킬 상태를 확인할 수 없습니다.",
updateFailed: "오케스트레이션 스킬을 업데이트할 수 없습니다.",
+2 -2
View File
@@ -2897,7 +2897,7 @@ export const ptBR: TranslationResources = {
updateTitle: "Atualizar Paseo skills?",
uninstallTitle: "Desinstalar Paseo skills?",
uninstallMessage:
"Remove todas as skills de orquestração do Paseo de ~/.agents, ~/.claude e ~/.codex.",
"Remove todas as skills de orquestração do Paseo de ~/.agents, ~/.claude, ~/.codex e ~/.gemini/config.",
choose: "Escolher skills",
chooseAll: "Todas as skills",
chooseAllHint:
@@ -2906,7 +2906,7 @@ export const ptBR: TranslationResources = {
chooseEmpty: "Esta versão não inclui skills.",
removeTitle: "Remover as skills desmarcadas?",
removeMessage:
"{{skills}} serão excluídas de ~/.agents, ~/.claude e ~/.codex. Tudo o que você adicionou dentro dessas pastas de skills também é excluído.",
"{{skills}} serão excluídas de ~/.agents, ~/.claude, ~/.codex e ~/.gemini/config. Tudo o que você adicionou dentro dessas pastas de skills também é excluído.",
saveFailed: "Não foi possível salvar sua seleção de skills.",
statusFailed: "Não foi possível verificar o status das skills de orquestração.",
updateFailed: "Não foi possível atualizar as skills de orquestração.",
+2 -2
View File
@@ -2909,7 +2909,7 @@ export const ru: TranslationResources = {
updateTitle: "Обновить навыки Paseo?",
uninstallTitle: "Удалить навыки Paseo?",
uninstallMessage:
"Удаляет все навыки оркестрации Paseo из ~/.agents, ~/.claude и ~/.codex на этом хосте.",
"Удаляет все навыки оркестрации Paseo из ~/.agents, ~/.claude, ~/.codex и ~/.gemini/config на этом хосте.",
choose: "Выбрать навыки",
chooseAll: "Все навыки",
chooseAllHint: "Устанавливать все встроенные навыки, включая добавленные позже.",
@@ -2917,7 +2917,7 @@ export const ru: TranslationResources = {
chooseEmpty: "На этом хосте нет встроенных навыков.",
removeTitle: "Удалить снятые навыки?",
removeMessage:
"{{skills}} будут удалены из ~/.agents, ~/.claude и ~/.codex на этом хосте. Всё, что вы добавили в эти папки навыков, тоже будет удалено.",
"{{skills}} будут удалены из ~/.agents, ~/.claude, ~/.codex и ~/.gemini/config на этом хосте. Всё, что вы добавили в эти папки навыков, тоже будет удалено.",
saveFailed: "Не удалось сохранить выбор навыков.",
statusFailed: "Не удалось проверить состояние навыков оркестрации.",
updateFailed: "Не удалось обновить навыки оркестрации.",
+3 -2
View File
@@ -2826,7 +2826,8 @@ export const zhCN: TranslationResources = {
updateAvailable: "有更新可用",
updateTitle: "更新 Paseo skills?",
uninstallTitle: "卸载 Paseo skills?",
uninstallMessage: "会从 ~/.agents、~/.claude、~/.codex 移除所有 Paseo 编排 skills。",
uninstallMessage:
"会从 ~/.agents、~/.claude、~/.codex、~/.gemini/config 移除所有 Paseo 编排 skills。",
choose: "选择 skills",
chooseAll: "全部 skills",
chooseAllHint: "保持安装所有内置 skills,包括以后新增的。",
@@ -2834,7 +2835,7 @@ export const zhCN: TranslationResources = {
chooseEmpty: "此版本未内置 skills。",
removeTitle: "移除取消勾选的 skills?",
removeMessage:
"将从 ~/.agents、~/.claude、~/.codex 中删除 {{skills}}。你在这些 skill 文件夹里添加的内容也会一并删除。",
"将从 ~/.agents、~/.claude、~/.codex、~/.gemini/config 中删除 {{skills}}。你在这些 skill 文件夹里添加的内容也会一并删除。",
saveFailed: "无法保存你的 skills 选择。",
statusFailed: "无法检查编排 skills 状态。",
updateFailed: "无法更新编排 skills。",
+14 -5
View File
@@ -22,6 +22,7 @@ import { shallow, useShallow } from "zustand/shallow";
import { useStoreWithEqualityFn } from "zustand/traditional";
import { useAgentStreamTail } from "@/agent-stream/use-agent-stream-tail";
import { AgentStreamView, type AgentStreamViewHandle } from "@/agent-stream/view";
import { CHAT_COLUMN_RAIL_DATASET, ChatColumnRailSurface } from "@/chat-rail";
import { ArchivedAgentCallout } from "@/components/archived-agent-callout";
import { ComposerDock } from "@/composer/dock";
import { FileDropZone } from "@/components/file-drop/file-drop-zone";
@@ -1267,7 +1268,11 @@ const ChatAgentReadyContent = memo(function ChatAgentReadyContent({
);
const dock = (
<ChatSurface disabled={isArchivingCurrentAgent} fullscreen={isComposerFullscreen}>
<ChatSurface
serverId={serverId}
disabled={isArchivingCurrentAgent}
fullscreen={isComposerFullscreen}
>
{dockContent}
{composerSection}
{dockOverlay}
@@ -1337,10 +1342,12 @@ function wrapAgentCommandProvider({
}
function ChatSurface({
serverId,
children,
disabled,
fullscreen,
}: {
serverId: string;
children: [ReactNode, ReactNode, ReactNode];
disabled: boolean;
fullscreen: boolean;
@@ -1349,9 +1356,11 @@ function ChatSurface({
// closes everything the chat opened.
return (
<OverlayDismissalScope>
<FileDropZone style={styles.container} disabled={disabled}>
<ComposerDock fullscreen={fullscreen}>{children}</ComposerDock>
</FileDropZone>
<ChatColumnRailSurface serverId={serverId}>
<FileDropZone style={styles.container} disabled={disabled}>
<ComposerDock fullscreen={fullscreen}>{children}</ComposerDock>
</FileDropZone>
</ChatColumnRailSurface>
</OverlayDismissalScope>
);
}
@@ -1365,7 +1374,7 @@ function TimelineSyncErrorCallout({
}) {
const { t } = useTranslation();
return (
<View style={styles.timelineSyncCalloutRail}>
<View style={styles.timelineSyncCalloutRail} dataSet={CHAT_COLUMN_RAIL_DATASET}>
<View style={styles.timelineSyncCalloutContent}>
<View style={styles.timelineSyncCallout} testID="agent-timeline-sync-error">
<Text style={styles.timelineSyncCalloutText}>
@@ -1,24 +1,39 @@
import type { PluginSurfaceProps } from "@getpaseo/plugin/client";
import type { NavigateToWorkspaceInput } from "@/stores/navigation-active-workspace-store";
import { parseServerIdFromPathname } from "@/utils/host-routes";
import { isHttpUrl } from "@/utils/http-url";
interface HostNavigationOwner {
browserAvailable: boolean;
openAgent(input: { serverId: string; agentId: string }): void;
openWorkspace(input: NavigateToWorkspaceInput): void;
isHostRegistered(serverId: string): boolean;
openAgent(input: { serverId: string; agentId: string }): string;
openWorkspace(input: NavigateToWorkspaceInput): string;
resolveWorkspace(input: { serverId: string; workspaceId: string }): string | null;
createBrowser(input: { initialUrl: string }): { browserId: string };
focusHost(serverId: string): void;
}
export function createPluginHostNavigation(
serverId: string,
owner: HostNavigationOwner,
): NonNullable<PluginSurfaceProps["navigation"]> {
const focusRouteHost = (route: string) => {
const destinationServerId = parseServerIdFromPathname(route);
if (destinationServerId && owner.isHostRegistered(destinationServerId)) {
owner.focusHost(destinationServerId);
}
};
return {
openAgent: ({ agentId, serverId: targetServerId }) =>
owner.openAgent({ serverId: targetServerId ?? serverId, agentId }),
openWorkspace: ({ workspaceId, serverId: targetServerId }) =>
owner.openWorkspace({ serverId: targetServerId ?? serverId, workspaceId }),
supportsFocusHost: true,
openAgent: ({ agentId, serverId: targetServerId, focusHost }) => {
const route = owner.openAgent({ serverId: targetServerId ?? serverId, agentId });
if (focusHost) focusRouteHost(route);
},
openWorkspace: ({ workspaceId, serverId: targetServerId, focusHost }) => {
const route = owner.openWorkspace({ serverId: targetServerId ?? serverId, workspaceId });
if (focusHost) focusRouteHost(route);
},
openBrowser: owner.browserAvailable
? ({ url, workspaceId, serverId: targetServerId }) => {
if (!isHttpUrl(url)) throw new Error("Only absolute HTTP(S) URLs are supported.");
@@ -1,25 +1,58 @@
import { describe, expect, it } from "vitest";
import { buildHostAgentDetailRoute, buildHostWorkspaceRoute } from "@/utils/host-routes";
import { createPluginHostNavigation } from "./host-navigation-model";
import { useSidebarViewStore } from "../stores/sidebar-view-store";
describe("plugin host navigation", () => {
function setup(electron = true) {
const destinations: unknown[] = [];
const browsers: string[] = [];
const focusedHosts: string[] = [];
const workspaces = new Set(["selected:one", "remote:two"]);
const navigation = createPluginHostNavigation("selected", {
browserAvailable: electron,
isHostRegistered: (serverId: string) => serverId === "selected" || serverId === "remote",
resolveWorkspace: ({ serverId, workspaceId }) =>
workspaces.has(`${serverId}:${workspaceId}`) ? workspaceId : null,
openAgent: (input) => destinations.push(input),
openWorkspace: (input) => destinations.push(input),
openAgent: (input) => {
destinations.push(input);
return buildHostAgentDetailRoute(input.serverId, input.agentId);
},
openWorkspace: (input) => {
destinations.push(input);
return buildHostWorkspaceRoute(input.serverId, input.workspaceId);
},
focusHost: (serverId) => {
focusedHosts.push(serverId);
useSidebarViewStore.getState().focusHost(serverId);
},
createBrowser: ({ initialUrl }) => {
browsers.push(initialUrl);
return { browserId: `browser-${browsers.length}` };
},
});
return { navigation, destinations, browsers, workspaces };
return { navigation, destinations, browsers, workspaces, focusedHosts };
}
it("focuses the destination host and clears filters that could hide its workspace", () => {
useSidebarViewStore.setState({
groupMode: "status",
hostFilters: ["selected", "other"],
projectFilters: ["old-project"],
labelFilter: { labels: ["urgent"] },
});
const { navigation, destinations, focusedHosts } = setup(false);
navigation.openAgent({ serverId: "remote", agentId: "agent-2", focusHost: true });
expect(focusedHosts).toEqual(["remote"]);
expect(destinations).toEqual([{ serverId: "remote", agentId: "agent-2" }]);
expect(useSidebarViewStore.getState()).toMatchObject({
groupMode: "status",
hostFilters: ["remote"],
projectFilters: [],
labelFilter: { labels: [] },
});
});
it("creates and focuses a local browser in the selected or explicit host workspace", () => {
const { navigation, destinations, browsers } = setup();
navigation.openBrowser!({ url: "https://example.com/one", workspaceId: "one" });
@@ -43,6 +76,110 @@ describe("plugin host navigation", () => {
]);
});
it("can return from a remote workspace to the installation host without toggling it off", () => {
const { navigation, destinations, focusedHosts } = setup();
navigation.openWorkspace({ serverId: "remote", workspaceId: "two", focusHost: true });
navigation.openWorkspace({ workspaceId: "one", focusHost: true });
navigation.openWorkspace({ workspaceId: "one", focusHost: true });
expect(focusedHosts).toEqual(["remote", "selected", "selected"]);
expect(destinations).toEqual([
{ serverId: "remote", workspaceId: "two" },
{ serverId: "selected", workspaceId: "one" },
{ serverId: "selected", workspaceId: "one" },
]);
expect(useSidebarViewStore.getState().hostFilters).toEqual(["selected"]);
});
it("focuses the host in the returned route for padded host IDs", () => {
const { navigation, destinations, focusedHosts } = setup();
navigation.openAgent({ serverId: " remote ", agentId: "agent-2", focusHost: true });
navigation.openWorkspace({ serverId: " selected ", workspaceId: "one", focusHost: true });
expect(destinations).toEqual([
{ serverId: " remote ", agentId: "agent-2" },
{ serverId: " selected ", workspaceId: "one" },
]);
expect(focusedHosts).toEqual(["remote", "selected"]);
expect(useSidebarViewStore.getState().hostFilters).toEqual(["selected"]);
});
it("leaves existing sidebar filters alone unless explicitly requested", () => {
useSidebarViewStore.setState({
hostFilters: ["remote"],
projectFilters: ["pinned-project"],
labelFilter: { labels: ["urgent"] },
});
const { navigation, destinations, focusedHosts } = setup();
navigation.openAgent({ agentId: "agent-1", serverId: " remote " });
navigation.openWorkspace({ workspaceId: "one", serverId: " selected ", focusHost: false });
expect(destinations).toEqual([
{ serverId: " remote ", agentId: "agent-1" },
{ serverId: " selected ", workspaceId: "one" },
]);
expect(focusedHosts).toEqual([]);
expect(useSidebarViewStore.getState()).toMatchObject({
hostFilters: ["remote"],
projectFilters: ["pinned-project"],
labelFilter: { labels: ["urgent"] },
});
expect(navigation.supportsFocusHost).toBe(true);
});
it("preserves sidebar filters when the navigation route has no destination", () => {
const filters = {
hostFilters: ["selected"],
projectFilters: ["pinned-project"],
labelFilter: { labels: ["urgent"] },
};
useSidebarViewStore.setState(filters);
const { navigation } = setup();
navigation.openAgent({ serverId: "remote", agentId: " ", focusHost: true });
navigation.openWorkspace({ serverId: "remote", workspaceId: "", focusHost: true });
expect(useSidebarViewStore.getState()).toMatchObject(filters);
});
it("preserves sidebar filters when the destination host has been removed", () => {
const filters = {
hostFilters: ["selected"],
projectFilters: ["pinned-project"],
labelFilter: { labels: ["urgent"] },
};
useSidebarViewStore.setState(filters);
const { navigation, destinations } = setup();
navigation.openAgent({ serverId: "removed", agentId: "agent-2", focusHost: true });
navigation.openWorkspace({ serverId: "removed", workspaceId: "two", focusHost: true });
expect(useSidebarViewStore.getState()).toMatchObject(filters);
expect(destinations).toEqual([
{ serverId: "removed", agentId: "agent-2" },
{ serverId: "removed", workspaceId: "two" },
]);
});
it("does not change the filter when navigation rejects the target", () => {
const focusedHosts: string[] = [];
const unavailable = () => {
throw new Error("Target unavailable");
};
const navigation = createPluginHostNavigation("selected", {
browserAvailable: false,
isHostRegistered: () => true,
resolveWorkspace: () => null,
openAgent: unavailable,
openWorkspace: unavailable,
createBrowser: unavailable,
focusHost: (serverId) => focusedHosts.push(serverId),
});
expect(() => navigation.openAgent({ agentId: "missing", focusHost: true })).toThrow(
"Target unavailable",
);
expect(() => navigation.openWorkspace({ workspaceId: "missing", focusHost: true })).toThrow(
"Target unavailable",
);
expect(focusedHosts).toEqual([]);
});
it("refuses unknown or removed workspaces before creating browser records", () => {
const { navigation, destinations, browsers, workspaces } = setup();
expect(() =>
@@ -4,10 +4,12 @@ import { resolveWorkspaceMapKeyByIdentity } from "@/utils/workspace-identity";
import { useMemo } from "react";
import { navigateToWorkspace } from "@/stores/navigation-active-workspace-store";
import { navigateToAgent } from "@/utils/navigate-to-agent";
import { getHostRuntimeStore } from "@/runtime/host-runtime";
import { getIsElectron } from "@/constants/platform";
import { createWorkspaceBrowser } from "@/desktop/browser/store";
import { createPluginHostNavigation } from "./host-navigation-model";
import { useSidebarViewStore } from "@/stores/sidebar-view-store";
export function usePluginHostNavigation(
serverId: string,
@@ -16,9 +18,14 @@ export function usePluginHostNavigation(
() =>
createPluginHostNavigation(serverId, {
browserAvailable: getIsElectron(),
isHostRegistered: (targetServerId) =>
getHostRuntimeStore()
.getHosts()
.some((host) => host.serverId === targetServerId),
openAgent: navigateToAgent,
openWorkspace: navigateToWorkspace,
createBrowser: createWorkspaceBrowser,
focusHost: (targetServerId) => useSidebarViewStore.getState().focusHost(targetServerId),
resolveWorkspace: ({ serverId: targetServerId, workspaceId }) =>
resolveWorkspaceMapKeyByIdentity({
workspaces: useSessionStore.getState().sessions[targetServerId]?.workspaces,
@@ -69,6 +69,7 @@ interface SidebarViewStoreState {
setWorkspaceSort: (sort: WorkspaceSort) => void;
toggleHostFilter: (serverId: string) => void;
clearHostFilters: () => void;
focusHost: (serverId: string) => void;
toggleProjectFilter: (viewKey: string) => void;
clearProjectFilters: () => void;
toggleLabelFilter: (name: string) => void;
@@ -205,6 +206,9 @@ export const useSidebarViewStore = create<SidebarViewStoreState>()(
toggleHostFilter: (serverId) =>
set((state) => ({ hostFilters: toggleFilterEntry(state.hostFilters, serverId) })),
clearHostFilters: () => set({ hostFilters: [] }),
// An explicit navigation target must not be hidden by another host's facets.
focusHost: (serverId) =>
set({ hostFilters: [serverId], projectFilters: [], labelFilter: emptyLabelFilter() }),
toggleProjectFilter: (viewKey) =>
set((state) => ({ projectFilters: toggleFilterEntry(state.projectFilters, viewKey) })),
clearProjectFilters: () => set({ projectFilters: [] }),
@@ -3,6 +3,7 @@ import { Text, View } from "react-native";
import { useTranslation } from "react-i18next";
import { CornerUpLeft } from "lucide-react-native";
import { StyleSheet, withUnistyles } from "react-native-unistyles";
import { CHAT_COLUMN_RAIL_DATASET } from "@/chat-rail";
import { StatusIcon } from "@/components/status-icon";
import { Button } from "@/components/ui/button";
import { FOOTER_HEIGHT } from "@/constants/layout";
@@ -37,7 +38,7 @@ export function ParentAgentCallout({
const parent = useParentAgent(serverId, parentAgentId);
return (
<View style={styles.rail}>
<View style={styles.rail} dataSet={CHAT_COLUMN_RAIL_DATASET}>
<View style={styles.callout} testID="parent-agent-callout">
<StatusIcon statusBucket={parent.statusBucket} size={ICON_SIZE} backdrop="surface1">
<ThemedParentIcon icon={parent.icon} size={ICON_SIZE} uniProps={foregroundColorMapping} />
+65 -1
View File
@@ -53,7 +53,7 @@ function preferences(
}
describe("choosePinnedUsageLayout", () => {
const widths = { labelsWidth: 200, percentsWidth: 120, windowCount: 2 };
const widths = { labelsWidth: 200, compactWidth: 200, percentsWidth: 120, windowCount: 2 };
it("shows meters only when every window's meter fits beside the labels", () => {
expect(choosePinnedUsageLayout({ ...widths, available: 240 })).toBe("meters");
@@ -64,11 +64,27 @@ describe("choosePinnedUsageLayout", () => {
expect(choosePinnedUsageLayout({ ...widths, available: 199 })).toBe("percents");
});
it("uses compact period shorthands when full labels overflow but compact labels fit", () => {
const scoped = { labelsWidth: 485, compactWidth: 388, percentsWidth: 268, windowCount: 6 };
expect(choosePinnedUsageLayout({ ...scoped, available: 485 })).toBe("labels");
expect(choosePinnedUsageLayout({ ...scoped, available: 399 })).toBe("compact");
expect(choosePinnedUsageLayout({ ...scoped, available: 388 })).toBe("compact");
expect(choosePinnedUsageLayout({ ...scoped, available: 387 })).toBe("percents");
});
it("skips compact mode when no window has a compact label", () => {
const noPeriod = { labelsWidth: 220, compactWidth: 120, percentsWidth: 120, windowCount: 2 };
expect(choosePinnedUsageLayout({ ...noPeriod, available: 180 })).toBe("percents");
});
it("shows labels until the widths are measured", () => {
expect(choosePinnedUsageLayout({ ...widths, available: null })).toBe("labels");
expect(choosePinnedUsageLayout({ ...widths, available: 999, labelsWidth: null })).toBe(
"labels",
);
expect(choosePinnedUsageLayout({ ...widths, available: 999, compactWidth: null })).toBe(
"labels",
);
});
});
@@ -145,6 +161,7 @@ describe("resolvePinnedUsage", () => {
key: "claude:default/five-hour",
label: "Claude Session 31% used",
shortLabel: "5h",
compactLabel: "5h",
percent: 31,
percentText: "31%",
tone: "default",
@@ -153,6 +170,7 @@ describe("resolvePinnedUsage", () => {
key: "claude:default/weekly",
label: "Claude Weekly 80% used",
shortLabel: "wk",
compactLabel: "wk",
percent: 80,
percentText: "80%",
tone: "warning",
@@ -216,6 +234,52 @@ describe("resolvePinnedUsage", () => {
const items = windows([opencode], preferences(null));
expect(items.map((item) => item.shortLabel)).toEqual([""]);
expect(items.map((item) => item.compactLabel)).toEqual([""]);
});
it("extracts bare period tokens as compact labels for scoped or verbose short labels", () => {
const mixed = report({
sourceId: "mixed",
sourceLabel: "Mixed",
windows: [
{ id: "a", label: "Session", shortLabel: "5h", summary: true, usedPct: 10 },
{ id: "b", label: "Weekly · Opus", shortLabel: "wk Opus", summary: true, usedPct: 20 },
{
id: "c",
label: "Code review · Weekly",
shortLabel: "Code review wk",
summary: true,
usedPct: 30,
},
{
id: "d",
label: "Gemini Models · Weekly",
shortLabel: "Gemini Models weekly",
summary: true,
usedPct: 40,
},
{
id: "e",
label: "Gemini Models · 5h",
shortLabel: "Gemini Models 5h",
summary: true,
usedPct: 50,
},
{ id: "f", label: "Monthly", shortLabel: "Monthly", summary: true, usedPct: 60 },
{ id: "g", label: "Premium requests", summary: true, usedPct: 70 },
],
});
const items = windows([mixed], preferences(null));
expect(items.map((item) => [item.shortLabel, item.compactLabel])).toEqual([
["5h", "5h"],
["wk Opus", "wk"],
["Code review wk", "wk"],
["Gemini Models weekly", "wk"],
["Gemini Models 5h", "5h"],
["Monthly", "mo"],
["Premium requests", ""],
]);
});
it("formats the share left when the user reads usage as remaining", () => {
+49 -6
View File
@@ -18,6 +18,8 @@ export interface PinnedUsageWindow {
label: string;
/** The window's short name ("5h"), empty for none, or its label when the source sends none. */
shortLabel: string;
/** Bare period token ("5h", "wk", "mo") used when full short labels overflow the sidebar row. */
compactLabel: string;
/** The share shown, under the user's used/remaining preference. */
percent: number;
percentText: string;
@@ -34,28 +36,66 @@ export interface PinnedUsageSource {
}
/** How much of each window the one-line summary has room for. */
export type PinnedUsageLayout = "meters" | "labels" | "percents";
export type PinnedUsageLayout = "meters" | "labels" | "compact" | "percents";
// A meter narrower than this is a sliver that reads as noise rather than a share.
export const MIN_METER_WIDTH = 16;
/** The space between a meter and its text. */
export const METER_GAP = 4;
const DURATION_TOKEN_PATTERN = /^\d+[smhd]$/i;
function normalizePeriodToken(token: string): string | null {
const lower = token.toLowerCase();
if (lower === "wk" || lower === "weekly") return "wk";
if (lower === "mo" || lower === "monthly") return "mo";
if (DURATION_TOKEN_PATTERN.test(token)) return lower;
return null;
}
/**
* Extracts a bare period token ("5h", "wk", "mo") from a window's short label so tight sidebar
* rows can keep shorthands visible instead of dropping every label when one window is scoped.
*/
function compactShortLabel(shortLabel: string): string {
const trimmed = shortLabel.trim();
if (trimmed === "") return "";
const exact = normalizePeriodToken(trimmed);
if (exact !== null) return exact;
const parts = trimmed.split(/\s+/);
if (parts.length > 1) {
const first = normalizePeriodToken(parts[0]!);
if (first !== null) return first;
const last = normalizePeriodToken(parts[parts.length - 1]!);
if (last !== null) return last;
}
return "";
}
/**
* The richest layout that fits on one line: every window's meter, else its short label, else its
* percent alone. Meters are all or none; a line never mixes them. Until the widths are known it
* shows labels, which never flashes meters that turn out not to fit.
* bare period shorthand, else its percent alone. Meters are all or none; a line never mixes them.
* Until the widths are known it shows labels, which never flashes meters that turn out not to fit.
*/
export function choosePinnedUsageLayout(input: {
available: number | null;
labelsWidth: number | null;
compactWidth: number | null;
percentsWidth: number | null;
windowCount: number;
}): PinnedUsageLayout {
const { available, labelsWidth, percentsWidth, windowCount } = input;
if (available === null || labelsWidth === null || percentsWidth === null) return "labels";
const { available, labelsWidth, compactWidth, percentsWidth, windowCount } = input;
if (
available === null ||
labelsWidth === null ||
compactWidth === null ||
percentsWidth === null
) {
return "labels";
}
if (labelsWidth + windowCount * (MIN_METER_WIDTH + METER_GAP) <= available) return "meters";
if (labelsWidth <= available) return "labels";
if (compactWidth <= available && compactWidth > percentsWidth) return "compact";
return percentsWidth < labelsWidth ? "percents" : "labels";
}
@@ -85,10 +125,13 @@ export function resolvePinnedUsage(
.map((window) => {
const percent = displayPercent(window, preferences.displayAs) ?? 0;
const percentText = formatPct(percent);
const shortLabel =
window.shortLabel ?? formatProviderUsageLabel(window.id, window.label, t);
return {
key: `${entry.id}/${window.id}`,
label: `${describe(entry, formatProviderUsageLabel(window.id, window.label, t))} ${formatDisplayPct(percent, preferences.displayAs, undefined, t)}`,
shortLabel: window.shortLabel ?? formatProviderUsageLabel(window.id, window.label, t),
shortLabel,
compactLabel: compactShortLabel(shortLabel),
percent,
percentText,
tone: windowTone(window),
+19 -5
View File
@@ -29,6 +29,7 @@ import {
resolvePinnedUsage,
type PinnedUsageLayout,
type PinnedUsageSource,
type PinnedUsageWindow,
} from "./pinned";
import { UsageModal } from "./usage-modal";
@@ -123,8 +124,8 @@ function layoutWidth(event: LayoutChangeEvent): number {
/**
* One line: each account's icon, then per window a meter and "31% 5h". Off-screen copies measure
* the line with labels and with percents alone; the richest layout that fits is shown, and what
* it leaves out takes no space at all.
* the line with full labels, bare period shorthands, and percents alone; the richest layout that
* fits is shown, and what it leaves out takes no space at all.
*/
function PinnedUsageTrigger({
label,
@@ -139,6 +140,7 @@ function PinnedUsageTrigger({
}) {
const [available, setAvailable] = useState<number | null>(null);
const [labelsWidth, setLabelsWidth] = useState<number | null>(null);
const [compactWidth, setCompactWidth] = useState<number | null>(null);
const [percentsWidth, setPercentsWidth] = useState<number | null>(null);
const handleAvailableLayout = useCallback((event: LayoutChangeEvent) => {
setAvailable(layoutWidth(event));
@@ -146,12 +148,16 @@ function PinnedUsageTrigger({
const handleLabelsLayout = useCallback((event: LayoutChangeEvent) => {
setLabelsWidth(layoutWidth(event));
}, []);
const handleCompactLayout = useCallback((event: LayoutChangeEvent) => {
setCompactWidth(layoutWidth(event));
}, []);
const handlePercentsLayout = useCallback((event: LayoutChangeEvent) => {
setPercentsWidth(layoutWidth(event));
}, []);
const layout = choosePinnedUsageLayout({
available,
labelsWidth,
compactWidth,
percentsWidth,
windowCount: sources.reduce((count, source) => count + source.windows.length, 0),
});
@@ -177,6 +183,9 @@ function PinnedUsageTrigger({
<View style={styles.measured} onLayout={handleLabelsLayout}>
<PinnedUsageLine sources={sources} layout="labels" measuring />
</View>
<View style={styles.measured} onLayout={handleCompactLayout}>
<PinnedUsageLine sources={sources} layout="compact" measuring />
</View>
<View style={styles.measured} onLayout={handlePercentsLayout}>
<PinnedUsageLine sources={sources} layout="percents" measuring />
</View>
@@ -185,6 +194,12 @@ function PinnedUsageTrigger({
);
}
function windowSuffix(window: PinnedUsageWindow, layout: PinnedUsageLayout): string {
if (layout === "percents") return "";
if (layout === "compact") return window.compactLabel;
return window.shortLabel;
}
/**
* The line's items as direct children of one row, so every meter shares the leftover width
* equally.
@@ -215,6 +230,7 @@ function PinnedUsageLine({
</View>
{source.windows.map((window, windowIndex) => {
const leadStyle = windowIndex === 0 ? styles.iconGap : styles.windowGap;
const suffix = windowSuffix(window, layout);
return (
<Fragment key={window.key}>
{layout === "meters" ? (
@@ -228,9 +244,7 @@ function PinnedUsageLine({
testID={measuring ? undefined : "sidebar-usage-pinned-window"}
>
{window.percentText}
{layout === "percents" || window.shortLabel === "" ? null : (
<Text style={styles.windowLabel}>{` ${window.shortLabel}`}</Text>
)}
{suffix === "" ? null : <Text style={styles.windowLabel}>{` ${suffix}`}</Text>}
</Text>
</Fragment>
);
@@ -1,5 +1,4 @@
import { describe, expect, it } from "vitest";
import { runCreateCommandWithDeps } from "./create.js";
import { buildCreateWorktreeRequest, type WorktreeCreateOptions } from "./create-input.js";
const REPO = "/tmp/repo";
@@ -78,52 +77,3 @@ describe("buildCreateWorktreeRequest", () => {
});
});
});
it("uses the explicit worktree creation RPC and returns the created worktree details", async () => {
const result = await runCreateCommandWithDeps(
{
daemonTarget: { kind: "endpoint", host: "example.test:12345" },
mode: "branch-off",
newBranch: "topic",
base: "main",
cwd: REPO,
},
{
connectToDaemon: async () => ({
createPaseoWorktree: async (input) => {
expect(input).toEqual({
cwd: REPO,
worktreeSlug: "topic",
action: "branch-off",
refName: "main",
});
return {
workspace: {
id: "wks_topic",
projectId: "project",
projectDisplayName: "Repo",
projectRootPath: REPO,
workspaceDirectory: `${REPO}/topic`,
projectKind: "git",
workspaceKind: "worktree",
name: "topic",
status: "idle",
statusEnteredAt: null,
activityAt: null,
archivingAt: null,
scripts: [],
},
error: null,
requestId: "worktree-create",
};
},
close: async () => {},
}),
},
);
expect(result.data).toEqual({
name: "topic",
branchName: "topic",
worktreePath: `${REPO}/topic`,
});
});
+1 -12
View File
@@ -26,22 +26,11 @@ function cmdError(code: string, message: string, details?: string): CommandError
export async function runCreateCommand(
options: WorktreeCreateOptions,
_command: Command,
): Promise<SingleResult<WorktreeCreateResult>> {
return runCreateCommandWithDeps(options, { connectToDaemon });
}
export async function runCreateCommandWithDeps(
options: WorktreeCreateOptions,
deps: {
connectToDaemon(
options: Parameters<typeof connectToDaemon>[0],
): Promise<Pick<Awaited<ReturnType<typeof connectToDaemon>>, "createPaseoWorktree" | "close">>;
},
): Promise<SingleResult<WorktreeCreateResult>> {
const cwd = options.cwd ?? process.cwd();
const request = buildCreateWorktreeRequest(options, cwd);
const client = await deps.connectToDaemon({ target: options.daemonTarget });
const client = await connectToDaemon({ target: options.daemonTarget });
try {
const response = await client.createPaseoWorktree(request);
-100
View File
@@ -1623,106 +1623,6 @@ test("defaults session RPC waiters to sixty seconds", async () => {
await expect(responsePromise).rejects.toThrow("No response to fetch_agent_request after 60000ms");
});
test.each([
[
"archive_workspace_request",
(client: DaemonClient) => client.archiveWorkspace("workspace-1"),
(requestId: string) => ({
type: "archive_workspace_response" as const,
payload: {
requestId,
workspaceId: "workspace-1",
archivedAt: "2026-01-01T00:00:00.000Z",
error: null,
},
}),
],
[
"paseo_worktree_archive_request",
(client: DaemonClient) => client.archivePaseoWorktree({ worktreePath: "/repo/worktree" }),
(requestId: string) => ({
type: "paseo_worktree_archive_response" as const,
payload: { requestId, success: true, removedAgents: [], error: null },
}),
],
[
"workspace.recovery.restore.request",
(client: DaemonClient) => client.restoreWorkspace("workspace-1"),
(requestId: string) => ({
type: "workspace.recovery.restore.response" as const,
payload: { requestId, workspaceId: "workspace-1", accepted: true, error: null },
}),
],
[
"workspace.archive.undo.request",
(client: DaemonClient) => client.undoWorkspaceArchive("workspace-1"),
(requestId: string) => ({
type: "workspace.archive.undo.response" as const,
payload: { requestId, workspaceId: "workspace-1", accepted: true, error: null },
}),
],
[
"open_project_request",
(client: DaemonClient) => client.openProject("/repo/worktree"),
(requestId: string) => ({
type: "open_project_response" as const,
payload: { requestId, workspace: null, error: null },
}),
],
[
"create_paseo_worktree_request",
(client: DaemonClient) => client.createPaseoWorktree({ cwd: "/repo", worktreeSlug: "topic" }),
(requestId: string) => ({
type: "create_paseo_worktree_response" as const,
payload: { requestId, workspace: null, error: null, setupTerminalId: null },
}),
],
] as const)(
"waits on %s across queued and bounded daemon stages until response or disconnect",
async (_type, run, buildResponse) => {
useHeartbeatClock();
const transport = createMockTransport();
const client = new DaemonClient({
url: "ws://test",
clientId: "worktree-lifecycle-wait-test",
logger: createMockLogger(),
reconnect: { enabled: false },
transportFactory: () => transport.transport,
});
clients.push(client);
const connecting = client.connect();
transport.triggerOpen();
await connecting;
const pending = run(client);
const sentFrame = JSON.parse(assertStr(transport.sent.at(-1))) as {
message: { requestId: string };
};
let settled = false;
void pending.then(
() => {
settled = true;
return undefined;
},
() => {
settled = true;
return undefined;
},
);
await vi.advanceTimersByTimeAsync(200_000);
await Promise.resolve();
expect(settled).toBe(false);
transport.triggerMessage(wrapSessionMessage(buildResponse(sentFrame.message.requestId)));
await expect(pending).resolves.not.toThrow();
const disconnected = run(client);
transport.triggerClose({ code: 1006, reason: "gone" });
await expect(disconnected).rejects.toMatchObject({ code: "DAEMON_CONNECTION_LOST" });
},
);
test("honors explicit fetchAgent timeout below the session RPC default", async () => {
useHeartbeatClock();
const logger = createMockLogger();
+3 -19
View File
@@ -3188,9 +3188,6 @@ export class DaemonClient {
cwd,
},
responseType: "open_project_response",
// Opening a path whose checkout is currently archiving waits on the daemon checkout gate;
// wait for the terminal response or transport disconnect instead of timing out while queued.
timeout: 0,
});
}
@@ -3322,9 +3319,6 @@ export class DaemonClient {
workspaceId,
},
responseType: "archive_workspace_response",
// Archive may wait for a queued checkout operation and then run teardown/manager removal,
// each bounded on the daemon; wait for the terminal response or transport disconnect.
timeout: 0,
});
}
@@ -3847,9 +3841,7 @@ export class DaemonClient {
type: "workspace.recovery.restore.request",
workspaceId,
},
// Restore may wait behind an active archive/removal before running a bounded restore stage;
// wait for the terminal response or transport disconnect instead of timing out mid-workflow.
timeout: 0,
timeout: 150_000,
});
if (!payload.accepted) {
throw new Error(payload.error ?? "Workspace recovery was rejected by the host");
@@ -3865,9 +3857,8 @@ export class DaemonClient {
type: "workspace.archive.undo.request",
workspaceId,
},
// Undo may wait for an in-flight archive to settle and then recreate the worktree;
// wait for the terminal response or transport disconnect.
timeout: 0,
// Undoing a finished worktree archive recreates the worktree, like recovery does.
timeout: 150_000,
});
if (!payload.accepted) {
throw new Error(payload.error ?? "The host could not undo the workspace archive");
@@ -5448,9 +5439,6 @@ export class DaemonClient {
...(input.scope !== undefined ? { scope: input.scope } : {}),
},
responseType: "paseo_worktree_archive_response",
// Archive may wait for a queued checkout operation and then run teardown/manager removal,
// each bounded on the daemon; wait for the terminal response or transport disconnect.
timeout: 0,
});
}
@@ -5474,10 +5462,6 @@ export class DaemonClient {
...(input.githubPrNumber !== undefined ? { githubPrNumber: input.githubPrNumber } : {}),
},
responseType: "create_paseo_worktree_response",
// Every daemon stage (before hooks, shared 120s manager budget, Git, after hooks) enforces
// its own deadline, and transport heartbeats/close reject if the host drops, so wait for the
// terminal worktree response instead of aborting prematurely mid-workflow.
timeout: 0,
});
}
-72
View File
@@ -589,75 +589,3 @@ describe("sidebar data SDK boundary", () => {
).toEqual([]);
});
});
describe("worktree manager SDK boundary", () => {
it("types create, remove, and restore handlers with discriminated results and cleanup", () => {
expect(
typeErrors(`
import type {
PluginServerContext,
WorktreeManagerRegistration,
PluginWorktreeCreateInput,
PluginWorktreeCreateResult,
PluginWorktreeRemoveRequest,
PluginWorktreeRemoveResult,
PluginWorktreeRestoreRequest,
PluginWorktreeRestoreResult,
} from "@getpaseo/plugin/server";
export default function contribute(server: PluginServerContext) {
const manager: WorktreeManagerRegistration = {
async create(request: PluginWorktreeCreateInput, { paseo, signal }) {
const untrusted: boolean = request.untrusted;
const headSha: string | undefined = request.headSha;
void headSha;
// @ts-expect-error untrusted is read-only
request.untrusted = true;
// @ts-expect-error headSha is read-only
request.headSha = "deadbeef";
if (request.kind === "branch-off") {
const start: string = request.startPoint ?? request.baseRef;
// @ts-expect-error startPoint is read-only
request.startPoint = "other";
if (!start || untrusted) return;
}
if (signal.aborted) return;
void paseo;
const result: PluginWorktreeCreateResult = { type: "created", path: request.path };
return result;
},
async remove(request: PluginWorktreeRemoveRequest, { signal }) {
const reason: "archive" | "rollback" = request.reason;
const force: boolean = request.force;
const untrusted: boolean = request.untrusted;
// @ts-expect-error remove request fields are read-only
request.path = "/other";
if (!reason || !force || untrusted || signal.aborted) return;
const result: PluginWorktreeRemoveResult = { type: "removed" };
return result;
},
async restore(request: PluginWorktreeRestoreRequest) {
const untrusted: boolean = request.untrusted;
void untrusted;
if (request.target.type === "commit") return;
if (request.target.type === "from-base") {
const base: string = request.target.baseRef;
void base;
}
const result: PluginWorktreeRestoreResult = { type: "restored", path: request.path };
return result;
},
};
const dispose: () => void = server.registerWorktreeManager(manager);
server.registerWorktreeManager({
// @ts-expect-error create result requires discriminant
async create() {
return { path: "/tmp/wt" };
},
});
return dispose;
}
`),
).toEqual([]);
});
});
+10 -1
View File
@@ -49,16 +49,25 @@ export interface PluginHostProps {
interface PluginNavigableHostProps extends PluginHostProps {
/** Client-owned navigation. Undefined on older hosts; hide dependent affordances when absent. */
readonly navigation?: {
/** This client supports the focusHost option on agent/workspace navigation. */
readonly supportsFocusHost?: boolean;
/** Present only on Electron. The browser runs locally; serverId selects workspace ownership. */
readonly openBrowser?: (input: {
readonly url: string;
readonly workspaceId: string;
readonly serverId?: string;
}) => void;
readonly openAgent: (input: { readonly agentId: string; readonly serverId?: string }) => void;
readonly openAgent: (input: {
readonly agentId: string;
readonly serverId?: string;
/** Select only the destination host in the sidebar and clear project/label filters. */
readonly focusHost?: boolean;
}) => void;
readonly openWorkspace: (input: {
readonly workspaceId: string;
readonly serverId?: string;
/** Select only the destination host in the sidebar and clear project/label filters. */
readonly focusHost?: boolean;
}) => void;
};
}
-2
View File
@@ -5,7 +5,6 @@ import type { PluginCleanup } from "../contracts.js";
import type { ProviderRegistration } from "./provider.js";
import type { UsageSourceRegistration } from "./usage.js";
import type { PluginLifecycleRegistration } from "./lifecycle.js";
import type { WorktreeManagerRegistration } from "./worktree.js";
export interface PluginHandlerContext {
paseo: PaseoApi;
@@ -65,7 +64,6 @@ export interface PluginServerContext extends PluginLifecycleRegistration {
): void;
registerProvider(provider: ProviderRegistration): void;
registerUsageSource(source: UsageSourceRegistration): void;
registerWorktreeManager(manager: WorktreeManagerRegistration): () => void;
}
export type PluginServerContribution = (server: PluginServerContext) => PluginCleanup;
-11
View File
@@ -35,14 +35,3 @@ export { spawnProcess, execCommand, terminateProcess } from "./process.js";
export { defineAgentTool } from "./agent-tools.js";
export type { AgentToolDefinition, AgentToolResult, AgentToolContext } from "./agent-tools.js";
export type {
PluginWorktreeContext,
PluginWorktreeCreateInput,
PluginWorktreeCreateResult,
PluginWorktreeRemoveRequest,
PluginWorktreeRemoveResult,
PluginWorktreeRestoreTarget,
PluginWorktreeRestoreRequest,
PluginWorktreeRestoreResult,
WorktreeManagerRegistration,
} from "./worktree.js";
+1 -6
View File
@@ -37,12 +37,7 @@ export type PluginWorktreeCreateRequest = {
slug: string;
path: string;
} & (
| {
kind: "branch-off";
baseRef: string;
/** Where the new branch starts when that is not `baseRef`, such as a fork's head. */
readonly startPoint?: string;
}
| { kind: "branch-off"; baseRef: string }
| { kind: "checkout-branch" }
| {
kind: "checkout-change-request";
-69
View File
@@ -1,69 +0,0 @@
import type { PluginHookContext, PluginWorktreeCreateRequest } from "./lifecycle.js";
/** Context passed to worktree manager callbacks. */
export type PluginWorktreeContext = PluginHookContext;
/** Resolved creation request handed to a worktree manager after `worktree.create.before`. */
export type PluginWorktreeCreateInput = PluginWorktreeCreateRequest & {
/** True when the worktree comes from an untrusted source such as a fork change request; skip repository-defined hooks. */
readonly untrusted: boolean;
/** Resolved remote head commit SHA for change-request checkouts when available. */
readonly headSha?: string;
};
/** Return `{ type: "created", path }` to claim creation, or `undefined` to decline. */
export interface PluginWorktreeCreateResult {
type: "created";
path: string;
}
export interface PluginWorktreeRemoveRequest {
readonly repoRoot: string | null;
readonly path: string;
readonly branch: string | null;
readonly reason: "archive" | "rollback";
readonly force: boolean;
/** True when the worktree came from an untrusted source such as a fork change request; skip repository-defined hooks. */
readonly untrusted: boolean;
}
/** Return `{ type: "removed" }` after removing the worktree, or `undefined` to fall back to Git. */
export interface PluginWorktreeRemoveResult {
type: "removed";
}
export type PluginWorktreeRestoreTarget =
| { readonly type: "branch"; readonly branch: string }
| { readonly type: "commit"; readonly commit: string }
| { readonly type: "from-base"; readonly branch: string; readonly baseRef: string };
export interface PluginWorktreeRestoreRequest {
readonly repoRoot: string;
/** Recorded path the worktree must be restored to. */
readonly path: string;
readonly target: PluginWorktreeRestoreTarget;
readonly baseRef: string | null;
/** True when the worktree came from an untrusted source such as a fork change request; skip repository-defined hooks. */
readonly untrusted: boolean;
}
/** Return `{ type: "restored", path }` after recreating the worktree, or `undefined` to fall back to Git. */
export interface PluginWorktreeRestoreResult {
type: "restored";
path: string;
}
export interface WorktreeManagerRegistration {
create(
request: PluginWorktreeCreateInput,
context: PluginWorktreeContext,
): Promise<PluginWorktreeCreateResult | void>;
remove?(
request: PluginWorktreeRemoveRequest,
context: PluginWorktreeContext,
): Promise<PluginWorktreeRemoveResult | void>;
restore?(
request: PluginWorktreeRestoreRequest,
context: PluginWorktreeContext,
): Promise<PluginWorktreeRestoreResult | void>;
}
+1 -1
View File
@@ -90,7 +90,7 @@
"speech:transcribe:local": "tsx scripts/transcribe-local-wav.ts",
"test": "npm run test:unit && npm run test:integration",
"test:unit": "vitest run --fileParallelism --exclude \"**/*.e2e.test.ts\"",
"test:integration": "vitest run --maxWorkers=1 src/server/git-filename-diffs.e2e.test.ts src/server/daemon-e2e/checkout-diff-content.e2e.test.ts src/server/daemon-e2e/create-agent-mode.e2e.test.ts src/server/daemon-e2e/filesystem.e2e.test.ts src/server/daemon-e2e/file-download.e2e.test.ts src/server/daemon-e2e/cli-logs-follow.e2e.test.ts src/server/creation/creation.e2e.test.ts src/server/daemon-e2e/creation-status.e2e.test.ts src/server/daemon-e2e/persisted-creation-caller.e2e.test.ts src/server/daemon-e2e/terminal-workspace-sdk.e2e.test.ts src/server/daemon-e2e/terminal-worker-lifecycle.e2e.test.ts src/server/workspace-create-worktree-source.e2e.test.ts src/server/daemon-e2e/models.e2e.test.ts src/server/daemon-e2e/live-preferences.e2e.test.ts src/server/daemon-e2e/oversized-message.e2e.test.ts src/server/agent/model-catalog.e2e.test.ts src/server/plugins/plugin-paseo-api.e2e.test.ts src/server/plugins/usage-sources.e2e.test.ts src/server/plugins/lifecycle.e2e.test.ts src/server/plugins/worktree-manager.e2e.test.ts src/server/connected-hosts/hosts.e2e.test.ts src/server/owned-subscriptions.e2e.test.ts && vitest run --maxWorkers=1 src/server/agent/providers/omp/history.e2e.test.ts src/server/daemon-e2e/git-operations.e2e.test.ts src/server/session.create-agent-worktree-autoarchive.e2e.test.ts src/server/agent/providers/opencode-bridge.local.e2e.test.ts src/server/daemon-e2e/relay-transport.e2e.test.ts -t \"merges into|creates a worktree and auto-archives both|versioned runtime|oversized attachments|connected hosts|password-protected daemon refuses|replays selected OMP history\"",
"test:integration": "vitest run --maxWorkers=1 src/server/git-filename-diffs.e2e.test.ts src/server/daemon-e2e/checkout-diff-content.e2e.test.ts src/server/daemon-e2e/create-agent-mode.e2e.test.ts src/server/daemon-e2e/filesystem.e2e.test.ts src/server/daemon-e2e/file-download.e2e.test.ts src/server/daemon-e2e/cli-logs-follow.e2e.test.ts src/server/creation/creation.e2e.test.ts src/server/daemon-e2e/creation-status.e2e.test.ts src/server/daemon-e2e/persisted-creation-caller.e2e.test.ts src/server/daemon-e2e/terminal-workspace-sdk.e2e.test.ts src/server/daemon-e2e/terminal-worker-lifecycle.e2e.test.ts src/server/workspace-create-worktree-source.e2e.test.ts src/server/daemon-e2e/models.e2e.test.ts src/server/daemon-e2e/live-preferences.e2e.test.ts src/server/daemon-e2e/oversized-message.e2e.test.ts src/server/agent/model-catalog.e2e.test.ts src/server/plugins/plugin-paseo-api.e2e.test.ts src/server/plugins/usage-sources.e2e.test.ts src/server/plugins/lifecycle.e2e.test.ts src/server/connected-hosts/hosts.e2e.test.ts src/server/owned-subscriptions.e2e.test.ts && vitest run --maxWorkers=1 src/server/agent/providers/omp/history.e2e.test.ts src/server/daemon-e2e/git-operations.e2e.test.ts src/server/session.create-agent-worktree-autoarchive.e2e.test.ts src/server/agent/providers/opencode-bridge.local.e2e.test.ts src/server/daemon-e2e/relay-transport.e2e.test.ts -t \"merges into|creates a worktree and auto-archives both|versioned runtime|oversized attachments|connected hosts|password-protected daemon refuses|replays selected OMP history\"",
"test:hub-cli-contract": "vitest run --maxWorkers=1 src/server/hub/hub-cli-contract.test.ts",
"test:integration:all": "npm run test:e2e",
"test:integration:real": "vitest run real.e2e.test.ts",
@@ -10175,6 +10175,8 @@ test("a sender's start wait follows its prompt across a stale-session retry", as
test("a sender's start wait follows its prompt when the session is stale before the wait begins", async () => {
const workdir = mkdtempSync(join(tmpdir(), "agent-manager-immediate-stale-start-"));
const resumeEntered = deferred<void>();
const releaseResume = deferred<void>();
class StaleStartSession extends TestAgentSession {
override async startTurn(): Promise<{ turnId: string }> {
throw new StaleProviderSessionError("stale-bridge");
@@ -10184,6 +10186,15 @@ test("a sender's start wait follows its prompt when the session is stale before
override async createSession(config: AgentSessionConfig): Promise<AgentSession> {
return new StaleStartSession(config);
}
override async resumeSession(
handle: AgentPersistenceHandle,
config?: Partial<AgentSessionConfig>,
): Promise<AgentSession> {
resumeEntered.resolve();
await releaseResume.promise;
return await super.resumeSession(handle, config);
}
}
const client = new StaleStartClient();
const storage = new AgentStorage(join(workdir, "agents"), logger);
@@ -10196,9 +10207,11 @@ test("a sender's start wait follows its prompt when the session is stale before
runOptions: { clientMessageId: "immediate-stale-start" },
});
// The stale start has failed and been cleared before the sender begins waiting.
await new Promise((resolve) => setTimeout(resolve, 0));
await resumeEntered.promise;
expect(manager.hasInFlightRun(agent.id)).toBe(false);
await expect(dispatchStarted(dispatch)).resolves.toBeUndefined();
const senderWait = dispatchStarted(dispatch);
releaseResume.resolve();
await expect(senderWait).resolves.toBeUndefined();
await client.waitForRetryStart();
expect(manager.getTimeline(agent.id).filter((item) => item.type === "user_message")).toEqual([
expect.objectContaining({
@@ -10207,6 +10220,7 @@ test("a sender's start wait follows its prompt when the session is stale before
}),
]);
} finally {
releaseResume.resolve();
manager.prepareForShutdown();
await Promise.all(manager.listAgents().map((agent) => manager.closeAgent(agent.id)));
await manager.flushForShutdown();
@@ -4,11 +4,7 @@ import type pino from "pino";
import type { ForgeService } from "../../services/forge-service.js";
import { isPaseoOwnedWorktreeCwd } from "../../utils/worktree.js";
import {
archiveByScope,
type ActiveWorkspaceRef,
type ArchiveDependencies,
} from "../workspace-archive-service.js";
import { archiveByScope, type ActiveWorkspaceRef } from "../workspace-archive-service.js";
import type {
CreatePaseoWorktreeWorkflowFn,
CreatePaseoWorktreeWorkflowResult,
@@ -21,15 +17,10 @@ import type {
} from "../messages.js";
import type { AgentManager, AgentSubscriber, SubscribeOptions } from "./agent-manager.js";
import type { AgentStorage } from "./agent-storage.js";
import type { PluginWorktreeManagerRuntime } from "../plugins/runtime.js";
interface CreateAgentLifecycleDispatchDependencies {
paseoHome: string;
worktreesRoot?: string;
worktreeManagers?: Pick<PluginWorktreeManagerRuntime, "removeWorktree">;
workspaceArchiveOperations?: ArchiveDependencies["workspaceArchiveOperations"];
getWorkspace?: ArchiveDependencies["getWorkspace"];
isCheckoutUntrusted?: ArchiveDependencies["isCheckoutUntrusted"];
agentManager: AgentManager;
agentStorage: AgentStorage;
github: ForgeService;
@@ -193,15 +184,11 @@ export class CreateAgentLifecycleDispatch {
{
paseoHome: this.dependencies.paseoHome,
paseoWorktreesBaseRoot: this.dependencies.worktreesRoot,
worktreeManagers: this.dependencies.worktreeManagers,
workspaceArchiveOperations: this.dependencies.workspaceArchiveOperations,
github: this.dependencies.github,
workspaceGitService: this.dependencies.workspaceGitService,
agentManager: this.dependencies.agentManager,
agentStorage: this.dependencies.agentStorage,
findWorkspaceIdForCwd: this.dependencies.findWorkspaceIdForCwd,
getWorkspace: this.dependencies.getWorkspace,
isCheckoutUntrusted: this.dependencies.isCheckoutUntrusted,
listActiveWorkspaces: this.dependencies.listActiveWorkspaces,
archiveWorkspaceRecord: this.dependencies.archiveWorkspaceRecord,
emitWorkspaceUpdatesForWorkspaceIds: this.dependencies.emitWorkspaceUpdatesForWorkspaceIds,
@@ -139,9 +139,6 @@ export interface PaseoToolHostDependencies {
"getSnapshot" | "listWorktrees" | "resolveRepoRoot" | "invalidateWorktrees"
>;
findWorkspaceIdForCwd?: ArchiveDependencies["findWorkspaceIdForCwd"];
worktreeManagers?: ArchiveDependencies["worktreeManagers"];
workspaceArchiveOperations?: ArchiveDependencies["workspaceArchiveOperations"];
isCheckoutUntrusted?: ArchiveDependencies["isCheckoutUntrusted"];
listActiveWorkspaces?: ArchiveDependencies["listActiveWorkspaces"];
archiveWorkspaceRecord?: ArchiveDependencies["archiveWorkspaceRecord"];
emitWorkspaceUpdatesForWorkspaceIds?: ArchiveDependencies["emitWorkspaceUpdatesForWorkspaceIds"];
@@ -3412,17 +3409,11 @@ function archiveWorktreeDependencies(
return {
paseoHome: options.paseoHome,
paseoWorktreesBaseRoot: options.worktreesRoot,
worktreeManagers: options.worktreeManagers,
workspaceArchiveOperations: options.workspaceArchiveOperations,
isCheckoutUntrusted: options.isCheckoutUntrusted,
github: options.github,
workspaceGitService: options.workspaceGitService,
agentManager: context.agentManager,
agentStorage: context.agentStorage,
findWorkspaceIdForCwd: options.findWorkspaceIdForCwd,
...(options.workspaceRegistry
? { getWorkspace: (workspaceId: string) => options.workspaceRegistry!.get(workspaceId) }
: {}),
listActiveWorkspaces: options.listActiveWorkspaces,
archiveWorkspaceRecord: options.archiveWorkspaceRecord,
emitWorkspaceUpdatesForWorkspaceIds: options.emitWorkspaceUpdatesForWorkspaceIds,
@@ -6,7 +6,6 @@ import type { DaemonConfigStore } from "../daemon-config-store.js";
import {
archiveByScope,
type ActiveWorkspaceRef,
type ArchiveDependencies,
killTerminalsForWorkspace,
} from "../workspace-archive-service.js";
import type {
@@ -17,15 +16,10 @@ import type { ForgeService } from "../../services/forge-service.js";
import type { TerminalManager } from "../../terminal/terminal-manager.js";
import { isPaseoOwnedWorktreeCwd } from "../../utils/worktree.js";
import type { WorkspaceArchiveContext } from "../workspace-registry.js";
import type { PluginWorktreeManagerRuntime } from "../plugins/runtime.js";
export interface AutoArchiveArchiveOptions {
paseoHome: string;
paseoWorktreesBaseRoot?: string;
worktreeManagers?: Pick<PluginWorktreeManagerRuntime, "removeWorktree">;
workspaceArchiveOperations?: ArchiveDependencies["workspaceArchiveOperations"];
getWorkspace?: ArchiveDependencies["getWorkspace"];
isCheckoutUntrusted?: ArchiveDependencies["isCheckoutUntrusted"];
daemonConfigStore: DaemonConfigStore;
workspaceGitService: WorkspaceGitServiceImpl;
github: ForgeService;
@@ -105,15 +99,11 @@ export async function archiveIfSafe(input: {
{
paseoHome: options.paseoHome,
paseoWorktreesBaseRoot: options.paseoWorktreesBaseRoot,
worktreeManagers: options.worktreeManagers,
workspaceArchiveOperations: options.workspaceArchiveOperations,
github: options.github,
workspaceGitService: options.workspaceGitService,
agentManager: options.agentManager,
agentStorage: options.agentStorage,
findWorkspaceIdForCwd: options.findWorkspaceIdForCwd,
getWorkspace: options.getWorkspace,
isCheckoutUntrusted: options.isCheckoutUntrusted,
listActiveWorkspaces: options.listActiveWorkspaces,
archiveWorkspaceRecord: (workspaceIdToArchive, archivedAt) =>
options.archiveWorkspaceRecord(
+1 -27
View File
@@ -181,7 +181,6 @@ import {
killTerminalsForWorkspace,
type ActiveWorkspaceRef,
} from "./workspace-archive-service.js";
import { WorkspaceArchiveOperations } from "./workspace-archive-operations.js";
import { setupAutoArchiveOnMerge } from "./auto-archive-on-merge/index.js";
import { wrapSessionMessage, type SessionOutboundMessage } from "./messages.js";
import type { TerminalManager } from "../terminal/terminal-manager.js";
@@ -212,10 +211,7 @@ import { ScriptHealthMonitor } from "./script-health-monitor.js";
import { createScriptStatusEmitter } from "./script-status-projection.js";
import { WorkspaceScriptRuntimeStore } from "./workspace-script-runtime-store.js";
import { createWorkspaceScriptsService } from "./session/workspace-scripts/workspace-scripts-service.js";
import {
assertWorkspaceAutomationAllowedForWorkspace,
isCheckoutUntrusted,
} from "./workspace-automation-gate.js";
import { assertWorkspaceAutomationAllowedForWorkspace } from "./workspace-automation-gate.js";
import { spawnWorkspaceScript } from "./worktree-bootstrap.js";
import {
createManagedProcessRegistry,
@@ -744,7 +740,6 @@ export async function createPaseoDaemon(
});
const scriptRuntimeStore = new WorkspaceScriptRuntimeStore();
const workspaceSetupRuntime = new WorkspaceSetupRuntime();
const workspaceArchiveOperations = new WorkspaceArchiveOperations();
let configuredHostnames = config.hostnames ?? config.allowedHosts;
let appBaseUrl = config.appBaseUrl ?? "https://app.paseo.sh";
daemonConfigStore.onFieldChange("hostnames", (value) => {
@@ -1165,8 +1160,6 @@ export async function createPaseoDaemon(
worktreeRoot: workspace.worktreeRoot,
isPaseoOwnedWorktree: workspace.isPaseoOwnedWorktree,
mainRepoRoot: workspace.mainRepoRoot,
worktreeManagerPluginId: workspace.worktreeManagerPluginId,
untrustedSource: workspace.untrustedSource,
}));
};
const markWorkspaceArchivingExternal = (workspaceIds: Iterable<string>, archivingAt: string) => {
@@ -1225,8 +1218,6 @@ export async function createPaseoDaemon(
setupAutoArchiveOnMerge({
paseoHome: config.paseoHome,
paseoWorktreesBaseRoot: config.worktreesRoot,
worktreeManagers: pluginRuntime,
workspaceArchiveOperations,
daemonConfigStore,
workspaceGitService,
github,
@@ -1235,8 +1226,6 @@ export async function createPaseoDaemon(
terminalManager,
logger,
findWorkspaceIdForCwd: findWorkspaceIdForCwdExternal,
getWorkspace: (workspaceId) => workspaceRegistry.get(workspaceId),
isCheckoutUntrusted: (checkoutPath) => isCheckoutUntrusted(workspaceRegistry, checkoutPath),
listActiveWorkspaces: listActiveWorkspacesExternal,
getAutoArchivedChangeRequestUrl: async (workspaceId) =>
(await workspaceRegistry.get(workspaceId))?.autoArchivedChangeRequestUrl ?? null,
@@ -1257,7 +1246,6 @@ export async function createPaseoDaemon(
createPaseoWorktree: async (workflowInput, workflowOptions) => {
return createRegisteredPaseoWorktree(workflowInput, {
lifecycle: pluginRuntime,
worktreeManagers: pluginRuntime,
github,
...(workflowOptions?.resolveDefaultBranch
? {
@@ -1318,8 +1306,6 @@ export async function createPaseoDaemon(
{
paseoHome: config.paseoHome,
paseoWorktreesBaseRoot: config.worktreesRoot,
worktreeManagers: pluginRuntime,
workspaceArchiveOperations,
github,
workspaceGitService,
agentManager,
@@ -1337,7 +1323,6 @@ export async function createPaseoDaemon(
stopWorkspaceSetup: (workspaceIdToStop) => workspaceSetupRuntime.stop(workspaceIdToStop),
assertWorkspaceAutomationAllowed: (guardedWorkspaceId) =>
assertWorkspaceAutomationAllowedForWorkspace(workspaceRegistry, guardedWorkspaceId),
isCheckoutUntrusted: (checkoutPath) => isCheckoutUntrusted(workspaceRegistry, checkoutPath),
sessionLogger: logger,
},
{ scope: { kind: "workspace", workspaceId }, requestId },
@@ -1345,10 +1330,6 @@ export async function createPaseoDaemon(
const hubAgentLifecycle = new CreateAgentLifecycleDispatch({
paseoHome: config.paseoHome,
worktreesRoot: config.worktreesRoot,
worktreeManagers: pluginRuntime,
workspaceArchiveOperations,
getWorkspace: (workspaceId) => workspaceRegistry.get(workspaceId),
isCheckoutUntrusted: (checkoutPath) => isCheckoutUntrusted(workspaceRegistry, checkoutPath),
agentManager,
agentStorage,
github,
@@ -1447,8 +1428,6 @@ export async function createPaseoDaemon(
{
paseoHome: config.paseoHome,
paseoWorktreesBaseRoot: config.worktreesRoot,
worktreeManagers: pluginRuntime,
workspaceArchiveOperations,
github,
workspaceGitService,
agentManager,
@@ -1472,7 +1451,6 @@ export async function createPaseoDaemon(
stopWorkspaceSetup: (workspaceIdToStop) => workspaceSetupRuntime.stop(workspaceIdToStop),
assertWorkspaceAutomationAllowed: (guardedWorkspaceId) =>
assertWorkspaceAutomationAllowedForWorkspace(workspaceRegistry, guardedWorkspaceId),
isCheckoutUntrusted: (checkoutPath) => isCheckoutUntrusted(workspaceRegistry, checkoutPath),
sessionLogger: logger,
},
{
@@ -1599,9 +1577,6 @@ export async function createPaseoDaemon(
daemonConfigStore,
github,
workspaceGitService,
worktreeManagers: pluginRuntime,
workspaceArchiveOperations,
isCheckoutUntrusted: (checkoutPath) => isCheckoutUntrusted(workspaceRegistry, checkoutPath),
findWorkspaceIdForCwd: findWorkspaceIdForCwdExternal,
listActiveWorkspaces: listActiveWorkspacesExternal,
archiveWorkspaceRecord: (workspaceId, archivedAt) =>
@@ -1949,7 +1924,6 @@ export async function createPaseoDaemon(
pluginRuntime,
orchestrationSkills,
workspaceLabelService,
workspaceArchiveOperations,
);
pluginRuntime.bindPaseoSessionHost(wsServer);
await pluginRuntime.start();
@@ -22,9 +22,16 @@ import type { SkillSelectionStore } from "./selection-store";
import { createSkillsController, type SkillsController } from "./controller";
import { beginSkillsTransaction } from "./transaction";
interface TestSkillTargets extends SkillTargets {
agentsDir: string;
claudeDir: string;
antigravityDir: string;
installDirs: string[];
}
interface Harness {
root: string;
targets: SkillTargets;
targets: TestSkillTargets;
controller: SkillsController;
selectionStore: SkillSelectionStore;
}
@@ -33,11 +40,17 @@ const BUNDLED_SKILLS = ["paseo", "paseo-advisor", "paseo-loop"];
async function makeHarness(selectionStore?: SkillSelectionStore): Promise<Harness> {
const root = await mkdtemp(path.join(os.tmpdir(), "paseo-skills-controller-"));
const targets: SkillTargets = {
const agentsDir = path.join(root, "home", ".agents", "skills");
const claudeDir = path.join(root, "home", ".claude", "skills");
const codexDir = path.join(root, "home", ".codex", "skills");
const antigravityDir = path.join(root, "home", ".gemini", "config", "skills");
const targets: TestSkillTargets = {
sourceDir: path.join(root, "bundle"),
agentsDir: path.join(root, "home", ".agents", "skills"),
claudeDir: path.join(root, "home", ".claude", "skills"),
codexDir: path.join(root, "home", ".codex", "skills"),
installDirs: [agentsDir, claudeDir, antigravityDir],
agentsDir,
claudeDir,
codexDir,
antigravityDir,
};
for (const name of BUNDLED_SKILLS) {
await mkdir(path.join(targets.sourceDir, name), { recursive: true });
@@ -146,17 +159,26 @@ async function installedSkills(dir: string): Promise<string[]> {
.sort();
}
async function installedEverywhere(targets: SkillTargets): Promise<string[][]> {
return Promise.all([targets.agentsDir, targets.claudeDir, targets.codexDir].map(installedSkills));
async function installedEverywhere(targets: TestSkillTargets): Promise<string[][]> {
return Promise.all(
[targets.agentsDir, targets.claudeDir, targets.codexDir, targets.antigravityDir].map(
installedSkills,
),
);
}
async function writeUserFile(
targets: SkillTargets,
targets: TestSkillTargets,
skill: string,
relativePath: string,
contents: string,
): Promise<void> {
for (const dir of [targets.agentsDir, targets.claudeDir, targets.codexDir]) {
for (const dir of [
targets.agentsDir,
targets.claudeDir,
targets.codexDir,
targets.antigravityDir,
]) {
const file = path.join(dir, skill, relativePath);
await mkdir(path.dirname(file), { recursive: true });
await writeFile(file, contents);
@@ -164,30 +186,33 @@ async function writeUserFile(
}
async function readUserFile(
targets: SkillTargets,
targets: TestSkillTargets,
skill: string,
relativePath: string,
): Promise<Array<string | null>> {
return Promise.all(
[targets.agentsDir, targets.claudeDir, targets.codexDir].map((dir) =>
[targets.agentsDir, targets.claudeDir, targets.codexDir, targets.antigravityDir].map((dir) =>
readFile(path.join(dir, skill, relativePath), "utf8").catch(() => null),
),
);
}
/** Anything the transaction staged and failed to clean up sits beside the skills tree. */
async function backupArtifacts(targets: SkillTargets): Promise<string[][]> {
async function backupArtifacts(targets: TestSkillTargets): Promise<string[][]> {
return Promise.all(
[targets.agentsDir, targets.claudeDir, targets.codexDir].map(async (dir) => {
const parentEntries = await readdir(path.dirname(dir)).catch(() => []);
const rootEntries = await readdir(dir).catch(() => []);
return [
...parentEntries.filter(
(entry) => entry !== path.basename(dir) && !entry.startsWith(".paseo-skills-recovered-"),
),
...rootEntries.filter((entry) => entry.startsWith(".paseo-skills-transaction-")),
].sort();
}),
[targets.agentsDir, targets.claudeDir, targets.codexDir, targets.antigravityDir].map(
async (dir) => {
const parentEntries = await readdir(path.dirname(dir)).catch(() => []);
const rootEntries = await readdir(dir).catch(() => []);
return [
...parentEntries.filter(
(entry) =>
entry !== path.basename(dir) && !entry.startsWith(".paseo-skills-recovered-"),
),
...rootEntries.filter((entry) => entry.startsWith(".paseo-skills-transaction-")),
].sort();
},
),
);
}
@@ -203,14 +228,14 @@ async function waitForTransactionDirectory(parent: string): Promise<void> {
}
/** Puts a regular file where the agents skills tree goes, so convergence fails with ENOTDIR. */
async function blockAgentsDir(targets: SkillTargets): Promise<void> {
async function blockAgentsDir(targets: TestSkillTargets): Promise<void> {
await rm(targets.agentsDir, { recursive: true, force: true });
await mkdir(path.dirname(targets.agentsDir), { recursive: true });
await writeFile(targets.agentsDir, "not a directory");
}
async function isInstalled(targets: SkillTargets, name: string): Promise<boolean> {
const dirs = [targets.agentsDir, targets.claudeDir];
async function isInstalled(targets: TestSkillTargets, name: string): Promise<boolean> {
const dirs = [targets.agentsDir, targets.claudeDir, targets.antigravityDir];
const present = await Promise.all(
dirs.map((dir) =>
access(path.join(dir, name))
@@ -251,7 +276,7 @@ describe("skills controller", () => {
selection: { mode: "custom", skills: ["paseo", "paseo-loop"] },
},
);
expect(await installedEverywhere(harness.targets)).toEqual([[], [], []]);
expect(await installedEverywhere(harness.targets)).toEqual([[], [], [], []]);
});
let harness: Harness;
@@ -299,6 +324,7 @@ describe("skills controller", () => {
"keep this",
"keep this",
"keep this",
"keep this",
]);
});
@@ -455,13 +481,15 @@ describe("skills controller", () => {
["paseo", "paseo-loop"],
["paseo", "paseo-loop"],
["paseo-loop"],
["paseo", "paseo-loop"],
]);
expect(await readUserFile(readOnly.targets, "paseo-loop", "notes/mine.md")).toEqual([
"hand written",
"hand written",
"hand written",
"hand written",
]);
expect(await backupArtifacts(readOnly.targets)).toEqual([[], [], []]);
expect(await backupArtifacts(readOnly.targets)).toEqual([[], [], [], []]);
await rm(readOnly.root, { recursive: true, force: true });
});
@@ -482,6 +510,7 @@ describe("skills controller", () => {
"keep this",
"keep this",
"keep this",
"keep this",
]);
await rm(readOnly.root, { recursive: true, force: true });
});
@@ -506,6 +535,7 @@ describe("skills controller", () => {
"keep this",
"keep this",
"keep this",
"keep this",
]);
await rm(readOnly.root, { recursive: true, force: true });
});
@@ -534,11 +564,13 @@ describe("skills controller", () => {
"restore this",
"restore this",
"restore this",
"restore this",
]);
expect(await readUserFile(readOnly.targets, "paseo-loop", "notes/concurrent.md")).toEqual([
"keep this",
"keep this",
"keep this",
"keep this",
]);
await rm(readOnly.root, { recursive: true, force: true });
});
@@ -562,6 +594,7 @@ describe("skills controller", () => {
"keep this",
"keep this",
"keep this",
"keep this",
]);
expect(await isInstalled(harness.targets, "paseo-loop")).toBe(true);
});
@@ -580,6 +613,7 @@ describe("skills controller", () => {
harness.targets.agentsDir,
harness.targets.claudeDir,
harness.targets.codexDir,
harness.targets.antigravityDir,
].map((root) => path.join(root, "paseo-loop"));
for (const live of livePaths) await chmod(live, 0o700);
const before = await Promise.all(livePaths.map(lstat));
@@ -591,7 +625,7 @@ describe("skills controller", () => {
const after = await Promise.all(livePaths.map(lstat));
expect(after.map((entry) => entry.ino)).toEqual(before.map((entry) => entry.ino));
expect(after.map((entry) => entry.mode & 0o777)).toEqual([0o700, 0o700, 0o700]);
expect(after.map((entry) => entry.mode & 0o777)).toEqual([0o700, 0o700, 0o700, 0o700]);
},
);
@@ -622,8 +656,9 @@ describe("skills controller", () => {
"paseo-loop-v1",
"paseo-loop-v1",
null,
"paseo-loop-v1",
]);
expect(await backupArtifacts(harness.targets)).toEqual([[], [], []]);
expect(await backupArtifacts(harness.targets)).toEqual([[], [], [], []]);
await expect(harness.controller.status()).resolves.toMatchObject({ selection: previous });
});
@@ -656,8 +691,9 @@ describe("skills controller", () => {
"keep this",
"keep this",
null,
"keep this",
]);
expect(await backupArtifacts(harness.targets)).toEqual([[], [], []]);
expect(await backupArtifacts(harness.targets)).toEqual([[], [], [], []]);
await expect(harness.controller.status()).resolves.toMatchObject({ selection: previous });
});
@@ -693,7 +729,7 @@ describe("skills controller", () => {
expect(
await readFile(path.join(harness.targets.codexDir, recovered!, "notes", "mine.md"), "utf8"),
).toBe("staged notes");
expect(await backupArtifacts(harness.targets)).toEqual([[], [], []]);
expect(await backupArtifacts(harness.targets)).toEqual([[], [], [], []]);
await expect(harness.controller.status()).resolves.toMatchObject({ selection: previous });
});
@@ -732,8 +768,9 @@ describe("skills controller", () => {
null,
"keep this",
"keep this",
"keep this",
]);
expect(await backupArtifacts(harness.targets)).toEqual([[], [], []]);
expect(await backupArtifacts(harness.targets)).toEqual([[], [], [], []]);
await expect(harness.controller.status()).resolves.toMatchObject({ selection: previous });
});
@@ -775,7 +812,7 @@ describe("skills controller", () => {
expect(await readFile(entry!.livePath, "utf8")).toBe("external replacement");
expect(await readFile(path.join(recovered, "notes", "mine.md"), "utf8")).toBe("captured notes");
expect(await backupArtifacts(harness.targets)).toEqual([[], [], []]);
expect(await backupArtifacts(harness.targets)).toEqual([[], [], [], []]);
});
it("preserves a directory that replaces a captured file before recovery", async () => {
@@ -806,7 +843,7 @@ describe("skills controller", () => {
expect(
await readFile(path.join(path.dirname(harness.targets.agentsDir), recovered!), "utf8"),
).toBe("captured file");
expect(await backupArtifacts(harness.targets)).toEqual([[], [], []]);
expect(await backupArtifacts(harness.targets)).toEqual([[], [], [], []]);
});
it.skipIf(process.platform !== "linux")(
@@ -815,6 +852,7 @@ describe("skills controller", () => {
const crossFilesystemRoot = await mkdtemp("/dev/shm/paseo-skills-controller-");
try {
harness.targets.claudeDir = path.join(crossFilesystemRoot, "skills");
harness.targets.installDirs[1] = harness.targets.claudeDir;
const previous: SkillSelection = {
mode: "custom",
skills: ["paseo", "paseo-loop"],
@@ -926,6 +964,7 @@ describe("skills controller", () => {
readOnly.targets.agentsDir,
readOnly.targets.claudeDir,
readOnly.targets.codexDir,
readOnly.targets.antigravityDir,
]) {
const notes = path.join(root, "paseo-loop", "notes");
await mkdir(notes, { recursive: true });
@@ -946,6 +985,7 @@ describe("skills controller", () => {
readOnly.targets.agentsDir,
readOnly.targets.claudeDir,
readOnly.targets.codexDir,
readOnly.targets.antigravityDir,
]) {
const restored = path.join(root, "paseo-loop", "notes", "latest.md");
expect((await lstat(restored)).isSymbolicLink()).toBe(true);
@@ -970,6 +1010,7 @@ describe("skills controller", () => {
readOnly.targets.agentsDir,
readOnly.targets.claudeDir,
readOnly.targets.codexDir,
readOnly.targets.antigravityDir,
]) {
await chmod(path.join(root, "paseo-loop", "hooks", "run.sh"), 0o751);
}
@@ -987,6 +1028,7 @@ describe("skills controller", () => {
readOnly.targets.agentsDir,
readOnly.targets.claudeDir,
readOnly.targets.codexDir,
readOnly.targets.antigravityDir,
]) {
const restored = await lstat(path.join(root, "paseo-loop", "hooks", "run.sh"));
expect(restored.mode & 0o777).toBe(0o751);
@@ -998,7 +1040,7 @@ describe("skills controller", () => {
it("leaves no backup artifacts behind after a successful save", async () => {
await harness.controller.save({ mode: "custom", skills: ["paseo"] });
expect(await backupArtifacts(harness.targets)).toEqual([[], [], []]);
expect(await backupArtifacts(harness.targets)).toEqual([[], [], [], []]);
});
it.skipIf(process.platform === "win32")(
@@ -1025,7 +1067,7 @@ describe("skills controller", () => {
expect(outcome.ok).toBe(true);
expect(await gated.store.get()).toEqual(next);
await blocked.controller.status();
expect(await backupArtifacts(blocked.targets)).toEqual([[], [], []]);
expect(await backupArtifacts(blocked.targets)).toEqual([[], [], [], []]);
await rm(blocked.root, { recursive: true, force: true });
},
);
@@ -1061,6 +1103,7 @@ describe("skills controller", () => {
harness.targets.agentsDir,
harness.targets.claudeDir,
harness.targets.codexDir,
harness.targets.antigravityDir,
]) {
await rm(path.join(root, "paseo-loop"), { recursive: true, force: true });
}
@@ -1071,8 +1114,9 @@ describe("skills controller", () => {
"hand written",
"hand written",
"hand written",
"hand written",
]);
expect(await backupArtifacts(harness.targets)).toEqual([[], [], []]);
expect(await backupArtifacts(harness.targets)).toEqual([[], [], [], []]);
});
it("does not roll back an interrupted transaction after the selection committed", async () => {
@@ -1092,6 +1136,7 @@ describe("skills controller", () => {
harness.targets.agentsDir,
harness.targets.claudeDir,
harness.targets.codexDir,
harness.targets.antigravityDir,
]) {
await rm(path.join(root, "paseo-loop"), { recursive: true, force: true });
}
@@ -1101,7 +1146,7 @@ describe("skills controller", () => {
expect(snapshot.selection).toEqual(next);
expect(await isInstalled(harness.targets, "paseo-loop")).toBe(false);
expect(await backupArtifacts(harness.targets)).toEqual([[], [], []]);
expect(await backupArtifacts(harness.targets)).toEqual([[], [], [], []]);
});
it("asks for confirmation naming the directories a save would delete", async () => {
@@ -1119,6 +1164,7 @@ describe("skills controller", () => {
["paseo", "paseo-advisor", "paseo-loop"],
["paseo", "paseo-advisor", "paseo-loop"],
["paseo-advisor"],
["paseo", "paseo-advisor", "paseo-loop"],
]);
expect(result.selection).toEqual({ mode: "custom", skills: ["paseo", "paseo-loop"] });
});
@@ -1134,7 +1180,12 @@ describe("skills controller", () => {
expect(result.confirmationRequired).toBeNull();
expect(result.selection).toEqual({ mode: "custom", skills: ["paseo"] });
expect(await installedEverywhere(harness.targets)).toEqual([["paseo"], ["paseo"], []]);
expect(await installedEverywhere(harness.targets)).toEqual([
["paseo"],
["paseo"],
[],
["paseo"],
]);
});
it("asks again when another directory appears before the retry", async () => {
@@ -1154,6 +1205,7 @@ describe("skills controller", () => {
["paseo", "paseo-advisor", "paseo-chat", "paseo-loop"],
["paseo", "paseo-advisor", "paseo-chat", "paseo-loop"],
["paseo-chat"],
["paseo", "paseo-advisor", "paseo-chat", "paseo-loop"],
]);
});
@@ -1175,6 +1227,7 @@ describe("skills controller", () => {
"hand written",
"hand written",
"hand written",
"hand written",
]);
});
@@ -1182,7 +1235,12 @@ describe("skills controller", () => {
const result = await harness.controller.save({ mode: "custom", skills: ["paseo"] });
expect(result.confirmationRequired).toBeNull();
expect(await installedEverywhere(harness.targets)).toEqual([["paseo"], ["paseo"], []]);
expect(await installedEverywhere(harness.targets)).toEqual([
["paseo"],
["paseo"],
[],
["paseo"],
]);
});
it("preserves a regular file at a skill path when save convergence fails", async () => {
@@ -1195,6 +1253,131 @@ describe("skills controller", () => {
expect(await readFile(collision, "utf8")).toBe("keep this file");
});
it("rolls back earlier targets when writing to Antigravity fails", async () => {
await mkdir(harness.targets.antigravityDir, { recursive: true });
const collision = path.join(harness.targets.antigravityDir, "paseo");
await writeFile(collision, "keep this file");
await expect(harness.controller.save({ mode: "custom", skills: ["paseo"] })).rejects.toThrow();
expect(await readFile(collision, "utf8")).toBe("keep this file");
expect(await installedEverywhere(harness.targets)).toEqual([[], [], [], []]);
expect(await backupArtifacts(harness.targets)).toEqual([[], [], [], []]);
});
it("rolls back cleanly without locking later calls when an Antigravity parent is a file", async () => {
const geminiConfig = path.dirname(harness.targets.antigravityDir);
await mkdir(path.dirname(geminiConfig), { recursive: true });
await writeFile(geminiConfig, "not a directory");
await expect(harness.controller.save({ mode: "custom", skills: ["paseo"] })).rejects.toThrow();
expect(await readFile(geminiConfig, "utf8")).toBe("not a directory");
expect(await installedEverywhere(harness.targets)).toEqual([[], [], [], []]);
expect(await backupArtifacts(harness.targets)).toEqual([[], [], [], []]);
await expect(harness.controller.status()).resolves.toMatchObject({
state: "not-installed",
selection: { mode: "all" },
});
await expect(harness.controller.uninstall()).resolves.toMatchObject({
state: "not-installed",
});
});
it.skipIf(process.platform === "win32" || process.getuid?.() === 0)(
"rolls back cleanly and still updates other targets when ~/.gemini is unwritable",
async () => {
const geminiHome = path.dirname(path.dirname(harness.targets.antigravityDir));
await mkdir(geminiHome, { recursive: true });
await chmod(geminiHome, 0o000);
try {
await expect(
harness.controller.save({ mode: "custom", skills: ["paseo"] }),
).rejects.toThrow();
expect(await installedEverywhere(harness.targets)).toEqual([[], [], [], []]);
expect(await backupArtifacts(harness.targets)).toEqual([[], [], [], []]);
await expect(harness.controller.status()).resolves.toMatchObject({
state: "not-installed",
selection: { mode: "all" },
});
} finally {
await chmod(geminiHome, 0o755);
}
// Install v1 everywhere, remove ~/.gemini/config so ~/.gemini (0555) blocks
// Antigravity writes with EACCES, then upgrade bundle to v2 and autoUpdate.
await harness.controller.install();
await rm(path.dirname(harness.targets.antigravityDir), { recursive: true, force: true });
for (const name of BUNDLED_SKILLS) {
await writeFile(path.join(harness.targets.sourceDir, name, "SKILL.md"), `${name}-v2`);
}
await chmod(geminiHome, 0o555);
try {
await expect(harness.controller.autoUpdate()).rejects.toThrow();
for (const root of [harness.targets.agentsDir, harness.targets.claudeDir]) {
for (const name of BUNDLED_SKILLS) {
expect(await readFile(path.join(root, name, "SKILL.md"), "utf8")).toBe(`${name}-v2`);
}
}
} finally {
await chmod(geminiHome, 0o755);
}
// With ~/.gemini unreadable (0000), uninstall still removes every skill from healthy targets.
await chmod(geminiHome, 0o000);
try {
await expect(harness.controller.uninstall()).rejects.toThrow();
expect(await installedSkills(harness.targets.agentsDir)).toEqual([]);
expect(await installedSkills(harness.targets.claudeDir)).toEqual([]);
} finally {
await chmod(geminiHome, 0o755);
}
},
);
it("recovers a pre-upgrade transaction manifest that recorded codex at root index 2", async () => {
const previous: SkillSelection = { mode: "custom", skills: ["paseo"] };
const next: SkillSelection = { mode: "all" };
await harness.controller.save(previous);
const transactionDir = path.join(
path.dirname(harness.targets.agentsDir),
".paseo-skills-transaction-legacy-codex-index",
);
const codexBackup = path.join(transactionDir, "backup", "2", "paseo");
await mkdir(path.join(codexBackup, "notes"), { recursive: true });
await writeFile(path.join(codexBackup, "notes", "codex.md"), "restored codex note");
await writeFile(
path.join(transactionDir, "transaction.json"),
`${JSON.stringify(
{
owner: "paseo-skills-transaction",
version: 1,
phase: "converging",
previousSelection: previous,
nextSelection: next,
entries: [
{
livePath: path.join(harness.targets.codexDir, "paseo"),
kind: "update",
backupPath: path.join("backup", "2", "paseo"),
},
],
},
null,
2,
)}\n`,
);
await harness.controller.status();
expect(
await readFile(path.join(harness.targets.codexDir, "paseo", "notes", "codex.md"), "utf8"),
).toBe("restored codex note");
expect(await backupArtifacts(harness.targets)).toEqual([[], [], [], []]);
});
it("serializes startup convergence with an interactive save", async () => {
await harness.controller.install();
// Startup finds drift it wants to repair while the user narrows the
@@ -1214,7 +1397,12 @@ describe("skills controller", () => {
]);
expect(saved.selection).toEqual({ mode: "custom", skills: ["paseo"] });
expect(await installedEverywhere(harness.targets)).toEqual([["paseo"], ["paseo"], []]);
expect(await installedEverywhere(harness.targets)).toEqual([
["paseo"],
["paseo"],
[],
["paseo"],
]);
expect(await harness.controller.status()).toEqual({
state: "up-to-date",
ops: [],
@@ -1247,6 +1435,7 @@ describe("skills controller", () => {
"keep this",
"keep this",
"keep this",
"keep this",
]);
});
});
@@ -21,18 +21,31 @@ function only(...skills: string[]): SkillSelection {
return { mode: "custom", skills };
}
interface TestSkillTargets extends SkillTargets {
agentsDir: string;
claudeDir: string;
antigravityDir: string;
installDirs: string[];
}
interface Sandbox {
root: string;
targets: SkillTargets;
targets: TestSkillTargets;
}
async function makeSandbox(): Promise<Sandbox> {
const root = await fs.mkdtemp(path.join(os.tmpdir(), "paseo-skills-"));
const targets: SkillTargets = {
const agentsDir = path.join(root, "home", ".agents", "skills");
const claudeDir = path.join(root, "home", ".claude", "skills");
const codexDir = path.join(root, "home", ".codex", "skills");
const antigravityDir = path.join(root, "home", ".gemini", "config", "skills");
const targets: TestSkillTargets = {
sourceDir: path.join(root, "bundle"),
agentsDir: path.join(root, "home", ".agents", "skills"),
claudeDir: path.join(root, "home", ".claude", "skills"),
codexDir: path.join(root, "home", ".codex", "skills"),
installDirs: [agentsDir, claudeDir, antigravityDir],
agentsDir,
claudeDir,
codexDir,
antigravityDir,
};
await fs.mkdir(targets.sourceDir, { recursive: true });
return { root, targets };
@@ -63,7 +76,7 @@ async function writeOnDiskSkill(
}
async function writeOnDiskSkillToAllTargets(
targets: SkillTargets,
targets: TestSkillTargets,
name: string,
files: Record<string, string>,
): Promise<void> {
@@ -71,6 +84,7 @@ async function writeOnDiskSkillToAllTargets(
writeOnDiskSkill(targets.agentsDir, name, files),
writeOnDiskSkill(targets.claudeDir, name, files),
writeOnDiskSkill(targets.codexDir, name, files),
writeOnDiskSkill(targets.antigravityDir, name, files),
]);
}
@@ -86,9 +100,9 @@ async function pathExists(p: string): Promise<boolean> {
.catch(() => false);
}
async function installedIn(targets: SkillTargets, name: string): Promise<boolean[]> {
async function installedIn(targets: TestSkillTargets, name: string): Promise<boolean[]> {
return Promise.all(
[targets.agentsDir, targets.claudeDir, targets.codexDir].map((dir) =>
[targets.agentsDir, targets.claudeDir, targets.codexDir, targets.antigravityDir].map((dir) =>
pathExists(path.join(dir, name)),
),
);
@@ -196,6 +210,10 @@ describe("getSkillsStatus", () => {
"SKILL.md": "paseo-v1",
"hooks/guard.sh": "user guard",
});
await writeOnDiskSkill(sandbox.targets.antigravityDir, "paseo", {
"SKILL.md": "paseo-v1",
"notes/local.md": "user notes",
});
const status = await getSkillsStatus(sandbox.targets, ALL_SKILLS);
@@ -212,6 +230,7 @@ describe("getSkillsStatus", () => {
await writeOnDiskSkill(sandbox.targets.agentsDir, "paseo", { "SKILL.md": "stale" });
await writeOnDiskSkill(sandbox.targets.claudeDir, "paseo", { "SKILL.md": "paseo-v1" });
await writeOnDiskSkill(sandbox.targets.codexDir, "paseo", { "SKILL.md": "paseo-v1" });
await writeOnDiskSkill(sandbox.targets.antigravityDir, "paseo", { "SKILL.md": "paseo-v1" });
await writeOnDiskSkillToAllTargets(sandbox.targets, "paseo-loop", { "SKILL.md": "loop-v1" });
const status = await getSkillsStatus(sandbox.targets, ALL_SKILLS);
@@ -228,6 +247,8 @@ describe("getSkillsStatus", () => {
await writeOnDiskSkill(sandbox.targets.claudeDir, "paseo-loop", { "SKILL.md": "loop-v1" });
await writeOnDiskSkill(sandbox.targets.codexDir, "paseo", { "SKILL.md": "paseo-v1" });
await writeOnDiskSkill(sandbox.targets.codexDir, "paseo-loop", { "SKILL.md": "loop-v1" });
await writeOnDiskSkill(sandbox.targets.antigravityDir, "paseo", { "SKILL.md": "paseo-v1" });
await writeOnDiskSkill(sandbox.targets.antigravityDir, "paseo-loop", { "SKILL.md": "loop-v1" });
const status = await getSkillsStatus(sandbox.targets, ALL_SKILLS);
@@ -235,6 +256,35 @@ describe("getSkillsStatus", () => {
expect(status.ops).toEqual([{ kind: "update", name: "paseo" }]);
});
it("returns drift when Antigravity is missing or stale", async () => {
await writeCurrentBundle(sandbox.targets.sourceDir);
await writeOnDiskSkill(sandbox.targets.agentsDir, "paseo", { "SKILL.md": "paseo-v1" });
await writeOnDiskSkill(sandbox.targets.agentsDir, "paseo-loop", { "SKILL.md": "loop-v1" });
await writeOnDiskSkill(sandbox.targets.claudeDir, "paseo", { "SKILL.md": "paseo-v1" });
await writeOnDiskSkill(sandbox.targets.claudeDir, "paseo-loop", { "SKILL.md": "loop-v1" });
await writeOnDiskSkill(sandbox.targets.antigravityDir, "paseo", { "SKILL.md": "stale" });
const status = await getSkillsStatus(sandbox.targets, ALL_SKILLS);
expect(status.state).toBe("drift");
expect(status.ops).toEqual([
{ kind: "update", name: "paseo" },
{ kind: "add", name: "paseo-loop" },
]);
});
it("returns not-installed when only user-personal skills exist in Antigravity", async () => {
await writeCurrentBundle(sandbox.targets.sourceDir);
await writeOnDiskSkill(sandbox.targets.antigravityDir, "my-agy-skill", {
"SKILL.md": "user-agy",
});
const status = await getSkillsStatus(sandbox.targets, ALL_SKILLS);
expect(status.state).toBe("not-installed");
expect(status.installed).toEqual([]);
});
it("returns drift with add ops for the bundled skills missing from disk", async () => {
await writeCurrentBundle(sandbox.targets.sourceDir);
await writeOnDiskSkillToAllTargets(sandbox.targets, "paseo", { "SKILL.md": "paseo-v1" });
@@ -262,6 +312,7 @@ describe("getSkillsStatus", () => {
await writeOnDiskSkill(sandbox.targets.agentsDir, "paseo", { "SKILL.md": "stale" });
await writeOnDiskSkill(sandbox.targets.claudeDir, "paseo", { "SKILL.md": "paseo-v1" });
await writeOnDiskSkill(sandbox.targets.codexDir, "paseo", { "SKILL.md": "paseo-v1" });
await writeOnDiskSkill(sandbox.targets.antigravityDir, "paseo", { "SKILL.md": "paseo-v1" });
await writeOnDiskSkill(sandbox.targets.agentsDir, "paseo-chat", { "SKILL.md": "chat-old" });
const status = await getSkillsStatus(sandbox.targets, ALL_SKILLS);
@@ -299,9 +350,14 @@ describe("custom skill selection", () => {
available: ["paseo", "paseo-advisor", "paseo-loop"],
installed: ["paseo", "paseo-loop"],
});
expect(await installedIn(sandbox.targets, "paseo")).toEqual([true, true, false]);
expect(await installedIn(sandbox.targets, "paseo-loop")).toEqual([true, true, false]);
expect(await installedIn(sandbox.targets, "paseo-advisor")).toEqual([false, false, false]);
expect(await installedIn(sandbox.targets, "paseo")).toEqual([true, true, false, true]);
expect(await installedIn(sandbox.targets, "paseo-loop")).toEqual([true, true, false, true]);
expect(await installedIn(sandbox.targets, "paseo-advisor")).toEqual([
false,
false,
false,
false,
]);
});
it("reports up-to-date while an unselected bundled skill is absent", async () => {
@@ -323,9 +379,14 @@ describe("custom skill selection", () => {
const status = await installSkills(sandbox.targets, only("paseo"));
expect(status.state).toBe("up-to-date");
expect(await installedIn(sandbox.targets, "paseo")).toEqual([true, true, false]);
expect(await installedIn(sandbox.targets, "paseo-loop")).toEqual([false, false, false]);
expect(await installedIn(sandbox.targets, "paseo-advisor")).toEqual([false, false, false]);
expect(await installedIn(sandbox.targets, "paseo")).toEqual([true, true, false, true]);
expect(await installedIn(sandbox.targets, "paseo-loop")).toEqual([false, false, false, false]);
expect(await installedIn(sandbox.targets, "paseo-advisor")).toEqual([
false,
false,
false,
false,
]);
});
it("reports a delete op for a deselected skill before it is applied", async () => {
@@ -339,12 +400,21 @@ describe("custom skill selection", () => {
it("leaves unrelated user skills untouched", async () => {
await writeOnDiskSkill(sandbox.targets.agentsDir, "unslop", { "SKILL.md": "user-unslop" });
await writeOnDiskSkill(sandbox.targets.antigravityDir, "custom-agy", {
"SKILL.md": "user-agy",
});
await installSkills(sandbox.targets, only("paseo"));
expect(
await fs.readFile(path.join(sandbox.targets.agentsDir, "unslop", "SKILL.md"), "utf-8"),
).toBe("user-unslop");
expect(
await fs.readFile(
path.join(sandbox.targets.antigravityDir, "custom-agy", "SKILL.md"),
"utf-8",
),
).toBe("user-agy");
});
it("treats an empty custom selection as no managed skills installed", async () => {
@@ -358,8 +428,8 @@ describe("custom skill selection", () => {
available: ["paseo", "paseo-advisor", "paseo-loop"],
installed: [],
});
expect(await installedIn(sandbox.targets, "paseo")).toEqual([false, false, false]);
expect(await installedIn(sandbox.targets, "paseo-loop")).toEqual([false, false, false]);
expect(await installedIn(sandbox.targets, "paseo")).toEqual([false, false, false, false]);
expect(await installedIn(sandbox.targets, "paseo-loop")).toEqual([false, false, false, false]);
});
it("ignores selected names that the bundle does not ship", async () => {
@@ -371,7 +441,7 @@ describe("custom skill selection", () => {
available: ["paseo", "paseo-advisor", "paseo-loop"],
installed: ["paseo"],
});
expect(await installedIn(sandbox.targets, "not-a-skill")).toEqual([false, false, false]);
expect(await installedIn(sandbox.targets, "not-a-skill")).toEqual([false, false, false, false]);
});
it("still deletes legacy skill names that are not selectable", async () => {
@@ -381,7 +451,12 @@ describe("custom skill selection", () => {
await installSkills(sandbox.targets, only("paseo"));
expect(await installedIn(sandbox.targets, "paseo-orchestrator")).toEqual([false, false, false]);
expect(await installedIn(sandbox.targets, "paseo-orchestrator")).toEqual([
false,
false,
false,
false,
]);
});
});
@@ -396,9 +471,12 @@ describe("installSkills / updateSkills", () => {
await fs.rm(sandbox.root, { recursive: true, force: true });
});
it("installs into shared and Claude roots without duplicating Codex discovery", async () => {
it("installs into shared, Claude, and Antigravity roots without duplicating Codex discovery", async () => {
await writeCurrentBundle(sandbox.targets.sourceDir);
await writeOnDiskSkill(sandbox.targets.agentsDir, "unslop", { "SKILL.md": "user-unslop" });
await writeOnDiskSkill(sandbox.targets.antigravityDir, "custom-agy", {
"SKILL.md": "user-agy",
});
const status = await installSkills(sandbox.targets, ALL_SKILLS);
@@ -409,15 +487,25 @@ describe("installSkills / updateSkills", () => {
installed: ["paseo", "paseo-loop"],
});
for (const name of ["paseo", "paseo-loop"]) {
const expected = name === "paseo" ? "paseo-v1" : "loop-v1";
expect(
await fs.readFile(path.join(sandbox.targets.agentsDir, name, "SKILL.md"), "utf-8"),
).toBe(name === "paseo" ? "paseo-v1" : "loop-v1");
).toBe(expected);
expect(await pathExists(path.join(sandbox.targets.codexDir, name, "SKILL.md"))).toBe(false);
expect(await pathExists(path.join(sandbox.targets.claudeDir, name))).toBe(true);
expect(
await fs.readFile(path.join(sandbox.targets.antigravityDir, name, "SKILL.md"), "utf-8"),
).toBe(expected);
}
expect(
await fs.readFile(path.join(sandbox.targets.agentsDir, "unslop", "SKILL.md"), "utf-8"),
).toBe("user-unslop");
expect(
await fs.readFile(
path.join(sandbox.targets.antigravityDir, "custom-agy", "SKILL.md"),
"utf-8",
),
).toBe("user-agy");
});
it("retires unchanged managed Codex copies while preserving personal files", async () => {
@@ -469,14 +557,23 @@ describe("installSkills / updateSkills", () => {
});
it.each([
{ alias: "codex", target: "agents" },
{ alias: "codex", target: "claude" },
{ alias: "claude", target: "codex" },
{ alias: "codex", target: "agents", expected: [true, true, true, true] },
{ alias: "codex", target: "claude", expected: [true, true, true, true] },
{ alias: "claude", target: "codex", expected: [true, true, true, true] },
{ alias: "codex", target: "antigravity", expected: [true, true, true, true] },
{ alias: "antigravity", target: "codex", expected: [true, true, true, true] },
{ alias: "antigravity", target: "agents", expected: [true, true, false, true] },
{ alias: "antigravity", target: "claude", expected: [true, true, false, true] },
] as const)(
"keeps installed skills when the $alias root links to the $target root",
async ({ alias, target }) => {
async ({ alias, target, expected }) => {
await writeCurrentBundle(sandbox.targets.sourceDir);
const rootOf = { agents: "agentsDir", claude: "claudeDir", codex: "codexDir" } as const;
const rootOf = {
agents: "agentsDir",
claude: "claudeDir",
codex: "codexDir",
antigravity: "antigravityDir",
} as const;
const aliasRoot = sandbox.targets[rootOf[alias]];
const targetRoot = sandbox.targets[rootOf[target]];
await fs.mkdir(targetRoot, { recursive: true });
@@ -488,12 +585,36 @@ describe("installSkills / updateSkills", () => {
expect(installed.state).toBe("up-to-date");
expect(updated.state).toBe("up-to-date");
expect((await fs.lstat(aliasRoot)).isSymbolicLink()).toBe(true);
for (const name of ["paseo", "paseo-loop"]) {
expect(await installedIn(sandbox.targets, name)).toEqual([true, true, true]);
expect(await installedIn(sandbox.targets, name)).toEqual([...expected]);
}
},
);
it("keeps an installed skill when its Antigravity directory links to the shared copy", async () => {
await writeCurrentBundle(sandbox.targets.sourceDir);
await fs.mkdir(path.join(sandbox.targets.agentsDir, "paseo"), { recursive: true });
await fs.mkdir(sandbox.targets.antigravityDir, { recursive: true });
await fs.symlink(
path.join(sandbox.targets.agentsDir, "paseo"),
path.join(sandbox.targets.antigravityDir, "paseo"),
"dir",
);
const installed = await installSkills(sandbox.targets, ALL_SKILLS);
const updated = await autoUpdateInstalledSkills(sandbox.targets, ALL_SKILLS);
expect(installed.state).toBe("up-to-date");
expect(updated.state).toBe("up-to-date");
expect(
(await fs.lstat(path.join(sandbox.targets.antigravityDir, "paseo"))).isSymbolicLink(),
).toBe(true);
expect(
await fs.readFile(path.join(sandbox.targets.antigravityDir, "paseo", "SKILL.md"), "utf8"),
).toBe("paseo-v1");
});
it("keeps an installed skill when its Codex directory links to the shared copy", async () => {
await writeCurrentBundle(sandbox.targets.sourceDir);
await fs.mkdir(path.join(sandbox.targets.agentsDir, "paseo"), { recursive: true });
@@ -604,6 +725,15 @@ describe("installSkills / updateSkills", () => {
expect(
await fs.readFile(path.join(sandbox.targets.claudeDir, "paseo-loop", "SKILL.md"), "utf-8"),
).toBe("loop-v1");
expect(
await fs.readFile(path.join(sandbox.targets.antigravityDir, "paseo", "SKILL.md"), "utf-8"),
).toBe("paseo-v1");
expect(
await fs.readFile(
path.join(sandbox.targets.antigravityDir, "paseo-loop", "SKILL.md"),
"utf-8",
),
).toBe("loop-v1");
});
it("auto-updates drifted installed skills", async () => {
@@ -626,6 +756,9 @@ describe("installSkills / updateSkills", () => {
"utf-8",
),
).toBe("user guard");
expect(
await fs.readFile(path.join(sandbox.targets.antigravityDir, "paseo", "SKILL.md"), "utf-8"),
).toBe("paseo-v1");
});
it("does not auto-install skills on a clean machine", async () => {
@@ -642,7 +775,7 @@ describe("installSkills / updateSkills", () => {
available: ["paseo", "paseo-loop"],
installed: [],
});
expect(await installedIn(sandbox.targets, "paseo")).toEqual([false, false, false]);
expect(await installedIn(sandbox.targets, "paseo")).toEqual([false, false, false, false]);
});
it("is idempotent — running install twice keeps state at up-to-date", async () => {
@@ -667,24 +800,51 @@ describe("uninstallSkills", () => {
await fs.rm(sandbox.root, { recursive: true, force: true });
});
it("removes every Paseo skill from all three targets and preserves user dirs", async () => {
it("removes every Paseo skill from all targets and preserves user dirs and symlinks", async () => {
await writeCurrentBundle(sandbox.targets.sourceDir);
await installSkills(sandbox.targets, ALL_SKILLS);
for (const name of ["unslop", "tdd", "devbox"]) {
await writeOnDiskSkill(sandbox.targets.agentsDir, name, { "SKILL.md": `user-${name}` });
}
await writeOnDiskSkill(sandbox.targets.antigravityDir, "user-agy-skill", {
"SKILL.md": "user-agy",
});
const linkedSource = path.join(sandbox.root, "external-user-skill");
await writeFiles(linkedSource, { "SKILL.md": "linked-user-skill" });
await fs.symlink(
linkedSource,
path.join(sandbox.targets.antigravityDir, "linked-user-skill"),
"dir",
);
const status = await uninstallSkills(sandbox.targets, ALL_SKILLS);
expect(status.state).toBe("not-installed");
for (const name of ["paseo", "paseo-loop", ...LEGACY_SKILL_NAMES]) {
expect(await installedIn(sandbox.targets, name)).toEqual([false, false, false]);
expect(await installedIn(sandbox.targets, name)).toEqual([false, false, false, false]);
}
for (const name of ["unslop", "tdd", "devbox"]) {
expect(
await fs.readFile(path.join(sandbox.targets.agentsDir, name, "SKILL.md"), "utf-8"),
).toBe(`user-${name}`);
}
expect(
await fs.readFile(
path.join(sandbox.targets.antigravityDir, "user-agy-skill", "SKILL.md"),
"utf-8",
),
).toBe("user-agy");
expect(
(
await fs.lstat(path.join(sandbox.targets.antigravityDir, "linked-user-skill"))
).isSymbolicLink(),
).toBe(true);
expect(
await fs.readFile(
path.join(sandbox.targets.antigravityDir, "linked-user-skill", "SKILL.md"),
"utf-8",
),
).toBe("linked-user-skill");
});
it("is a no-op when nothing is installed", async () => {
@@ -695,12 +855,13 @@ describe("uninstallSkills", () => {
expect(status.state).toBe("not-installed");
});
it("cleans up legacy skill names that linger in agents, claude, and codex", async () => {
it("cleans up legacy skill names that linger in agents, claude, codex, and antigravity", async () => {
await writeCurrentBundle(sandbox.targets.sourceDir);
for (const dir of [
sandbox.targets.agentsDir,
sandbox.targets.claudeDir,
sandbox.targets.codexDir,
sandbox.targets.antigravityDir,
]) {
await writeOnDiskSkill(dir, "paseo-chat", { "SKILL.md": "chat-old" });
}
@@ -708,6 +869,6 @@ describe("uninstallSkills", () => {
const status = await uninstallSkills(sandbox.targets, ALL_SKILLS);
expect(status.state).toBe("not-installed");
expect(await installedIn(sandbox.targets, "paseo-chat")).toEqual([false, false, false]);
expect(await installedIn(sandbox.targets, "paseo-chat")).toEqual([false, false, false, false]);
});
});
@@ -35,8 +35,12 @@ export interface SkillsStatus {
export interface SkillTargets {
sourceDir: string;
agentsDir: string;
claudeDir: string;
/**
* Ordered active install roots. Append new roots to the end so transaction
* backup indices remain stable across daemon upgrades.
*/
installDirs: readonly string[];
/** Legacy dedicated Codex root, retired on sync unless it aliases an install root. */
codexDir: string;
}
@@ -163,13 +167,11 @@ export async function getSkillsStatus(
): Promise<SkillsStatus> {
const available = await listBundledSkills(targets.sourceDir);
const names = managedSkillNames(available);
const [bundle, agentsDisk, claudeDisk, codexDisk] = await Promise.all([
const [bundle, codexDisk, ...disks] = await Promise.all([
hashSkills(targets.sourceDir, available),
hashSkills(targets.agentsDir, names),
hashSkills(targets.claudeDir, names),
hashSkills(targets.codexDir, names),
...targets.installDirs.map((root) => hashSkills(root, names)),
]);
const disks = [agentsDisk, claudeDisk];
const desired = resolveDesiredSkills(selection, available);
const ops = diff(bundle, disks, names, desired);
for (const name of codexDisk.keys()) {
@@ -203,8 +205,7 @@ async function applySkills(
if (writes.length > 0) {
await syncSkills({
sourceDir: targets.sourceDir,
agentsDir: targets.agentsDir,
claudeDir: targets.claudeDir,
installDirs: targets.installDirs,
codexDir: targets.codexDir,
skillNames: writes,
});
@@ -213,8 +214,7 @@ async function applySkills(
for (const op of status.ops) {
if (op.kind !== "delete") continue;
await removeSkill(op.name, {
agentsDir: targets.agentsDir,
claudeDir: targets.claudeDir,
installDirs: targets.installDirs,
codexDir: targets.codexDir,
});
}
@@ -259,12 +259,21 @@ export async function uninstallSkills(
selection: SkillSelection,
): Promise<SkillsStatus> {
const available = await listBundledSkills(targets.sourceDir);
let hasError = false;
let firstError: unknown = null;
for (const name of managedSkillNames(available)) {
await removeSkill(name, {
agentsDir: targets.agentsDir,
claudeDir: targets.claudeDir,
codexDir: targets.codexDir,
});
try {
await removeSkill(name, {
installDirs: targets.installDirs,
codexDir: targets.codexDir,
});
} catch (error) {
if (!hasError) {
hasError = true;
firstError = error;
}
}
}
if (hasError) throw firstError;
return getSkillsStatus(targets, selection);
}
@@ -45,8 +45,11 @@ describe("orchestration skill paths", () => {
const home = os.homedir();
expect(resolveSkillTargets()).toMatchObject({
agentsDir: path.join(home, ".agents", "skills"),
claudeDir: path.join(home, ".claude", "skills"),
installDirs: [
path.join(home, ".agents", "skills"),
path.join(home, ".claude", "skills"),
path.join(home, ".gemini", "config", "skills"),
],
codexDir: path.join(home, ".codex", "skills"),
});
});
@@ -17,8 +17,13 @@ export function resolveBundledSkillsDir(moduleUrl: string | URL = import.meta.ur
export function resolveSkillTargets(home: string = os.homedir()): SkillTargets {
return {
sourceDir: resolveBundledSkillsDir(),
agentsDir: path.join(home, ".agents", "skills"),
claudeDir: path.join(home, ".claude", "skills"),
// Append new install roots to the end — transaction backups reference roots
// by index, so existing positions must remain stable across upgrades.
installDirs: [
path.join(home, ".agents", "skills"),
path.join(home, ".claude", "skills"),
path.join(home, ".gemini", "config", "skills"),
],
codexDir: path.join(home, ".codex", "skills"),
};
}
@@ -10,6 +10,8 @@ interface Sandbox {
agentsDir: string;
claudeDir: string;
codexDir: string;
antigravityDir: string;
installDirs: string[];
}
async function makeSandbox(): Promise<Sandbox> {
@@ -18,8 +20,10 @@ async function makeSandbox(): Promise<Sandbox> {
const agentsDir = path.join(root, "home", ".agents", "skills");
const claudeDir = path.join(root, "home", ".claude", "skills");
const codexDir = path.join(root, "home", ".codex", "skills");
const antigravityDir = path.join(root, "home", ".gemini", "config", "skills");
const installDirs = [agentsDir, claudeDir, antigravityDir];
await fs.mkdir(sourceDir, { recursive: true });
return { root, sourceDir, agentsDir, claudeDir, codexDir };
return { root, sourceDir, agentsDir, claudeDir, codexDir, antigravityDir, installDirs };
}
async function writeBundleSkill(
@@ -57,8 +61,7 @@ describe("syncSkills", () => {
const result = await syncSkills({
sourceDir: sandbox.sourceDir,
agentsDir: sandbox.agentsDir,
claudeDir: sandbox.claudeDir,
installDirs: sandbox.installDirs,
codexDir: sandbox.codexDir,
skillNames: ["paseo"],
});
@@ -75,6 +78,11 @@ describe("syncSkills", () => {
"utf-8",
);
expect(claudeContent).toBe("new paseo content");
const antigravityContent = await fs.readFile(
path.join(sandbox.antigravityDir, "paseo", "SKILL.md"),
"utf-8",
);
expect(antigravityContent).toBe("new paseo content");
await expect(fs.stat(path.join(sandbox.codexDir, "paseo", "SKILL.md"))).rejects.toMatchObject({
code: "ENOENT",
});
@@ -88,8 +96,7 @@ describe("syncSkills", () => {
await syncSkills({
sourceDir: sandbox.sourceDir,
agentsDir: sandbox.agentsDir,
claudeDir: sandbox.claudeDir,
installDirs: sandbox.installDirs,
codexDir: sandbox.codexDir,
skillNames: ["paseo-committee"],
});
@@ -115,6 +122,15 @@ describe("syncSkills", () => {
expect(await fs.readFile(path.join(claudeSkillDir, "references", "roles.md"), "utf-8")).toBe(
"roles content",
);
const antigravitySkillDir = path.join(sandbox.antigravityDir, "paseo-committee");
expect((await fs.lstat(antigravitySkillDir)).isDirectory()).toBe(true);
expect(await fs.readFile(path.join(antigravitySkillDir, "SKILL.md"), "utf-8")).toBe(
"committee content",
);
expect(
await fs.readFile(path.join(antigravitySkillDir, "references", "roles.md"), "utf-8"),
).toBe("roles content");
});
it("leaves on-disk skills not in the bundle untouched", async () => {
@@ -122,16 +138,21 @@ describe("syncSkills", () => {
const customSkill = path.join(sandbox.agentsDir, "user-custom-skill");
await fs.mkdir(customSkill, { recursive: true });
await fs.writeFile(path.join(customSkill, "SKILL.md"), "user content");
const antigravityCustomSkill = path.join(sandbox.antigravityDir, "user-antigravity-skill");
await fs.mkdir(antigravityCustomSkill, { recursive: true });
await fs.writeFile(path.join(antigravityCustomSkill, "SKILL.md"), "antigravity user content");
await syncSkills({
sourceDir: sandbox.sourceDir,
agentsDir: sandbox.agentsDir,
claudeDir: sandbox.claudeDir,
installDirs: sandbox.installDirs,
codexDir: sandbox.codexDir,
skillNames: ["paseo"],
});
expect(await fs.readFile(path.join(customSkill, "SKILL.md"), "utf-8")).toBe("user content");
expect(await fs.readFile(path.join(antigravityCustomSkill, "SKILL.md"), "utf-8")).toBe(
"antigravity user content",
);
});
it("removes stale files previously written to managed skill dirs", async () => {
@@ -143,8 +164,7 @@ describe("syncSkills", () => {
await syncSkills({
sourceDir: sandbox.sourceDir,
agentsDir: sandbox.agentsDir,
claudeDir: sandbox.claudeDir,
installDirs: sandbox.installDirs,
codexDir: sandbox.codexDir,
skillNames: ["paseo"],
});
@@ -154,8 +174,7 @@ describe("syncSkills", () => {
await syncSkills({
sourceDir: sandbox.sourceDir,
agentsDir: sandbox.agentsDir,
claudeDir: sandbox.claudeDir,
installDirs: sandbox.installDirs,
codexDir: sandbox.codexDir,
skillNames: ["paseo"],
});
@@ -163,6 +182,12 @@ describe("syncSkills", () => {
expect(await fs.readFile(path.join(onDiskSkill, "SKILL.md"), "utf-8")).toBe("new");
await expect(fs.access(path.join(onDiskSkill, "references", "stale.md"))).rejects.toThrow();
await expect(fs.access(path.join(onDiskSkill, "references"))).rejects.toThrow();
const antigravitySkill = path.join(sandbox.antigravityDir, "paseo");
expect(await fs.readFile(path.join(antigravitySkill, "SKILL.md"), "utf-8")).toBe("new");
await expect(
fs.access(path.join(antigravitySkill, "references", "stale.md")),
).rejects.toThrow();
await expect(fs.access(path.join(antigravitySkill, "references"))).rejects.toThrow();
});
it("preserves user-added files in managed skill dirs", async () => {
@@ -172,11 +197,14 @@ describe("syncSkills", () => {
await fs.writeFile(path.join(onDiskSkill, "SKILL.md"), "old");
await fs.writeFile(path.join(onDiskSkill, "my-context.md"), "user context");
await fs.writeFile(path.join(onDiskSkill, "references", "notes.md"), "user notes");
const antigravitySkill = path.join(sandbox.antigravityDir, "paseo");
await fs.mkdir(path.join(antigravitySkill, "references"), { recursive: true });
await fs.writeFile(path.join(antigravitySkill, "SKILL.md"), "old");
await fs.writeFile(path.join(antigravitySkill, "my-context.md"), "antigravity user context");
await syncSkills({
sourceDir: sandbox.sourceDir,
agentsDir: sandbox.agentsDir,
claudeDir: sandbox.claudeDir,
installDirs: sandbox.installDirs,
codexDir: sandbox.codexDir,
skillNames: ["paseo"],
});
@@ -188,6 +216,10 @@ describe("syncSkills", () => {
expect(await fs.readFile(path.join(onDiskSkill, "references", "notes.md"), "utf-8")).toBe(
"user notes",
);
expect(await fs.readFile(path.join(antigravitySkill, "SKILL.md"), "utf-8")).toBe("new");
expect(await fs.readFile(path.join(antigravitySkill, "my-context.md"), "utf-8")).toBe(
"antigravity user context",
);
});
it.skipIf(process.platform === "win32")(
@@ -208,8 +240,39 @@ describe("syncSkills", () => {
await expect(
syncSkills({
sourceDir: sandbox.sourceDir,
agentsDir: sandbox.agentsDir,
claudeDir: sandbox.claudeDir,
installDirs: sandbox.installDirs,
codexDir: sandbox.codexDir,
skillNames: ["paseo"],
}),
).rejects.toThrow("Cannot sync through symbolic link");
expect(await fs.readFile(path.join(onDiskSkill, "SKILL.md"), "utf-8")).toBe("old skill");
expect(await fs.readFile(path.join(externalReferences, "guide.md"), "utf-8")).toBe(
"external guide",
);
expect((await fs.lstat(path.join(onDiskSkill, "references"))).isSymbolicLink()).toBe(true);
},
);
it.skipIf(process.platform === "win32")(
"rejects managed paths that would write through a symlink in Antigravity",
async () => {
await writeBundleSkill(sandbox.sourceDir, "paseo", {
"SKILL.md": "new skill",
"references/guide.md": "new guide",
});
const onDiskSkill = path.join(sandbox.antigravityDir, "paseo");
const externalReferences = path.join(sandbox.root, "external-antigravity-references");
await fs.mkdir(onDiskSkill, { recursive: true });
await fs.mkdir(externalReferences, { recursive: true });
await fs.writeFile(path.join(onDiskSkill, "SKILL.md"), "old skill");
await fs.writeFile(path.join(externalReferences, "guide.md"), "external guide");
await fs.symlink(externalReferences, path.join(onDiskSkill, "references"), "dir");
await expect(
syncSkills({
sourceDir: sandbox.sourceDir,
installDirs: sandbox.installDirs,
codexDir: sandbox.codexDir,
skillNames: ["paseo"],
}),
@@ -231,8 +294,7 @@ describe("syncSkills", () => {
const first = await syncSkills({
sourceDir: sandbox.sourceDir,
agentsDir: sandbox.agentsDir,
claudeDir: sandbox.claudeDir,
installDirs: sandbox.installDirs,
codexDir: sandbox.codexDir,
skillNames: ["paseo"],
});
@@ -240,8 +302,7 @@ describe("syncSkills", () => {
const second = await syncSkills({
sourceDir: sandbox.sourceDir,
agentsDir: sandbox.agentsDir,
claudeDir: sandbox.claudeDir,
installDirs: sandbox.installDirs,
codexDir: sandbox.codexDir,
skillNames: ["paseo"],
});
@@ -255,8 +316,7 @@ describe("syncSkills", () => {
const errors: Array<{ name: string; error: unknown }> = [];
const result = await syncSkills({
sourceDir: sandbox.sourceDir,
agentsDir: sandbox.agentsDir,
claudeDir: sandbox.claudeDir,
installDirs: sandbox.installDirs,
codexDir: sandbox.codexDir,
skillNames: ["paseo", "paseo-removed"],
onSkillError: (name, error) => errors.push({ name, error }),
@@ -278,8 +338,7 @@ describe("syncSkills", () => {
await syncSkills({
sourceDir: sandbox.sourceDir,
agentsDir: sandbox.agentsDir,
claudeDir: sandbox.claudeDir,
installDirs: sandbox.installDirs,
codexDir: sandbox.codexDir,
skillNames: ["paseo", "paseo-deprecated"],
});
@@ -293,8 +352,7 @@ describe("syncSkills", () => {
const errors: string[] = [];
const result = await syncSkills({
sourceDir: missingSourceDir,
agentsDir: sandbox.agentsDir,
claudeDir: sandbox.claudeDir,
installDirs: sandbox.installDirs,
codexDir: sandbox.codexDir,
skillNames: ["paseo"],
onSkillError: (skillName) => errors.push(skillName),
@@ -313,8 +371,7 @@ describe("syncSkills", () => {
const errors: string[] = [];
const result = await syncSkills({
sourceDir: sandbox.sourceDir,
agentsDir: sandbox.agentsDir,
claudeDir: sandbox.claudeDir,
installDirs: sandbox.installDirs,
codexDir: sandbox.codexDir,
skillNames: ["paseo"],
onSkillError: (skillName) => errors.push(skillName),
@@ -336,32 +393,30 @@ describe("removeSkill", () => {
await fs.rm(sandbox.root, { recursive: true, force: true });
});
it("removes the skill from all three targets when present", async () => {
it("removes the skill from all targets when present", async () => {
await writeBundleSkill(sandbox.sourceDir, "paseo", { "SKILL.md": "content" });
await syncSkills({
sourceDir: sandbox.sourceDir,
agentsDir: sandbox.agentsDir,
claudeDir: sandbox.claudeDir,
installDirs: sandbox.installDirs,
codexDir: sandbox.codexDir,
skillNames: ["paseo"],
});
await removeSkill("paseo", {
agentsDir: sandbox.agentsDir,
claudeDir: sandbox.claudeDir,
installDirs: sandbox.installDirs,
codexDir: sandbox.codexDir,
});
await expect(fs.access(path.join(sandbox.agentsDir, "paseo"))).rejects.toThrow();
await expect(fs.access(path.join(sandbox.claudeDir, "paseo"))).rejects.toThrow();
await expect(fs.access(path.join(sandbox.codexDir, "paseo"))).rejects.toThrow();
await expect(fs.access(path.join(sandbox.antigravityDir, "paseo"))).rejects.toThrow();
});
it("does not throw when targets are missing", async () => {
await expect(
removeSkill("does-not-exist", {
agentsDir: sandbox.agentsDir,
claudeDir: sandbox.claudeDir,
installDirs: sandbox.installDirs,
codexDir: sandbox.codexDir,
}),
).resolves.toBeUndefined();
@@ -4,8 +4,7 @@ import path from "node:path";
export interface SkillSyncOptions {
sourceDir: string;
agentsDir: string;
claudeDir: string;
installDirs: readonly string[];
codexDir: string;
skillNames: readonly string[];
onSkillError?: (skillName: string, error: unknown) => void;
@@ -171,20 +170,29 @@ async function syncDirectoryFiles(srcDir: string, dstDir: string): Promise<numbe
}
export interface RemoveSkillTargets {
agentsDir: string;
claudeDir: string;
installDirs: readonly string[];
codexDir: string;
}
export async function removeSkill(skillName: string, targets: RemoveSkillTargets): Promise<void> {
const paths = [
path.join(targets.agentsDir, skillName),
path.join(targets.claudeDir, skillName),
path.join(targets.codexDir, skillName),
];
const paths = [...targets.installDirs, targets.codexDir].map((root) =>
path.join(root, skillName),
);
let hasError = false;
let firstError: unknown = null;
for (const p of paths) {
await fs.rm(p, { recursive: true, force: true });
try {
await fs.rm(p, { recursive: true, force: true });
} catch (error) {
// If an ancestor is a regular file, no skill directory can exist below it.
if ((error as NodeJS.ErrnoException).code === "ENOTDIR") continue;
if (!hasError) {
hasError = true;
firstError = error;
}
}
}
if (hasError) throw firstError;
}
async function isSameDirectory(a: string, b: string): Promise<boolean> {
@@ -194,7 +202,7 @@ async function isSameDirectory(a: string, b: string): Promise<boolean> {
/**
* Codex also discovers .agents/skills, so its dedicated copy is a leftover. When
* the Codex skill directory resolves to the shared or Claude copy, it is that
* the Codex skill directory resolves to an active install target, it is that
* copy, and retiring it would delete the install.
*/
export async function isLegacyCodexCopy(
@@ -202,7 +210,7 @@ export async function isLegacyCodexCopy(
targets: RemoveSkillTargets,
): Promise<boolean> {
const codexSkillDir = path.join(targets.codexDir, skillName);
for (const root of [targets.agentsDir, targets.claudeDir]) {
for (const root of targets.installDirs) {
if (await isSameDirectory(codexSkillDir, path.join(root, skillName))) return false;
}
return true;
@@ -234,6 +242,8 @@ async function retireManagedSkill(dstDir: string): Promise<number> {
export async function syncSkills(options: SkillSyncOptions): Promise<SkillSyncResult> {
let changedFiles = 0;
let processedSkills = 0;
let hasError = false;
let firstError: unknown = null;
for (const skillName of options.skillNames) {
const bundleSkillDir = path.join(options.sourceDir, skillName);
@@ -241,28 +251,47 @@ export async function syncSkills(options: SkillSyncOptions): Promise<SkillSyncRe
const bundleStat = await fs.stat(bundleSkillDir).catch(() => null);
if (!bundleStat?.isDirectory()) continue;
try {
changedFiles += await syncDirectoryFiles(
bundleSkillDir,
path.join(options.agentsDir, skillName),
);
let skillFailed = false;
let skillError: unknown = null;
changedFiles += await syncDirectoryFiles(
bundleSkillDir,
path.join(options.claudeDir, skillName),
);
// Retain user edits to the old dedicated Codex copy.
if (await isLegacyCodexCopy(skillName, options)) {
changedFiles += await retireManagedSkill(path.join(options.codexDir, skillName));
// Attempt every install root for every skill before throwing so one
// unwritable target does not stop updates from reaching healthy targets.
for (const installDir of options.installDirs) {
try {
changedFiles += await syncDirectoryFiles(bundleSkillDir, path.join(installDir, skillName));
} catch (error) {
if (!skillFailed) {
skillFailed = true;
skillError = error;
}
}
}
if (!skillFailed) {
try {
// Retain user edits to the old dedicated Codex copy.
if (await isLegacyCodexCopy(skillName, options)) {
changedFiles += await retireManagedSkill(path.join(options.codexDir, skillName));
}
} catch (error) {
skillFailed = true;
skillError = error;
}
}
if (skillFailed) {
if (options.onSkillError) {
options.onSkillError(skillName, skillError);
} else if (!hasError) {
hasError = true;
firstError = skillError;
}
} else {
processedSkills++;
} catch (error) {
if (!options.onSkillError) throw error;
options.onSkillError(skillName, error);
}
}
if (hasError) throw firstError;
return { changedFiles, processedSkills };
}
@@ -128,13 +128,28 @@ function selectionsEqual(left: SkillSelection, right: SkillSelection): boolean {
);
}
/**
* Ordered roots for transaction capture and recovery. Pre-0.17 manifests
* recorded `[agents, claude, codex]` at indices 0–2, so `codexDir` stays at
* index 2 and newer install roots follow at index 3+.
*/
function skillRoots(targets: SkillTargets): string[] {
const [agentsDir, claudeDir, ...additionalInstallDirs] = targets.installDirs;
return [
...(agentsDir ? [agentsDir] : []),
...(claudeDir ? [claudeDir] : []),
targets.codexDir,
...additionalInstallDirs,
];
}
async function validateEntries(
targets: SkillTargets,
transactionDir: string,
entries: CapturedDirectory[],
): Promise<boolean> {
const names = new Set(await listManagedSkillNames(targets.sourceDir));
const roots = [targets.agentsDir, targets.claudeDir, targets.codexDir];
const roots = skillRoots(targets);
return entries.every((entry) => {
const rootIndex = roots.findIndex((root) => path.dirname(entry.livePath) === root);
if (rootIndex === -1) return false;
@@ -409,6 +424,10 @@ async function restore(
continue;
}
const liveInfo = await lstat(entry.livePath).catch(() => null);
// An add entry with no backup and no readable live path wrote nothing here
// (absent, under a file, or under an unreadable parent). Skipping avoids
// failing rollback with ENOTDIR/EACCES and leaving a stuck transaction.
if (liveInfo === null && backup === null) continue;
if (liveInfo !== null && !(await isDirectory(entry.livePath))) {
// Add/update rollback has the same conflict state as delete rollback. A
// recreated file or file symlink belongs to the external writer; preserve
@@ -441,11 +460,7 @@ async function restore(
}
function transactionParents(targets: SkillTargets): string[] {
return [
...new Set(
[targets.agentsDir, targets.claudeDir, targets.codexDir].map((root) => path.dirname(root)),
),
];
return [...new Set(skillRoots(targets).map((root) => path.dirname(root)))];
}
/**
@@ -493,7 +508,7 @@ export async function beginSkillsTransaction(
nextSelection: SkillSelection,
ops: readonly SkillOp[],
): Promise<SkillsTransaction> {
const roots = [targets.agentsDir, targets.claudeDir, targets.codexDir];
const roots = skillRoots(targets);
const seenRoots = new Set<string>();
const uniqueRoots: Array<{ root: string; rootIndex: number }> = [];
for (const [rootIndex, root] of roots.entries()) {
@@ -1,6 +1,5 @@
import type { JsonValue } from "@getpaseo/protocol/agent-types";
import type { PluginLifecycle } from "./plugins/lifecycle/index.js";
import type { PluginWorktreeManagerRuntime } from "./plugins/runtime.js";
import { stat } from "node:fs/promises";
import { resolve } from "node:path";
@@ -64,10 +63,6 @@ export interface AttemptFirstAgentBranchAutoNameResult {
export interface CreatePaseoWorktreeDeps extends CreateWorktreeCoreDeps {
lifecycle?: Pick<PluginLifecycle, "wait" | "before">;
worktreeManagers?: Pick<
PluginWorktreeManagerRuntime,
"hasWorktreeManager" | "createWorktree" | "removeWorktree"
>;
workspaceGitService: WorkspaceGitService;
workspaceProvisioning: Pick<WorkspaceProvisioningService, "createWorkspaceForWorktree">;
}
@@ -119,13 +114,22 @@ async function createPaseoWorktreeWithPriority(
worktreeRoot: createdWorktree.worktree.worktreePath,
branch: createdWorktree.worktree.branchName || null,
baseBranch: createdWorktree.worktree.comparisonBaseRef,
worktreeManagerPluginId: createdWorktree.worktree.worktreeManagerPluginId ?? null,
title: input.title?.trim() || resolveFirstAgentPromptTitle(input.firstAgentContext),
metadata: input.metadata,
expectsInitialAgent: Boolean(input.firstAgentContext),
background: input.background,
callerWorkspaceId: input.callerWorkspaceId,
untrustedSource: createdWorktree.untrustedSource,
...(createdWorktree.intent.kind === "checkout-change-request" &&
createdWorktree.intent.headRepository
? {
untrustedSource: {
kind: "change_request" as const,
forge: createdWorktree.intent.forge,
number: createdWorktree.intent.changeRequestNumber,
headRepository: createdWorktree.intent.headRepository,
},
}
: {}),
});
deps.github.invalidate({ cwd: createdWorktree.worktree.worktreePath });
@@ -148,10 +152,6 @@ async function createPaseoWorktreeWithPriority(
teardownCwds: [],
paseoHome: input.paseoHome,
worktreesBaseRoot: input.worktreesRoot,
worktreeManagers: deps.worktreeManagers,
worktreeManagerPluginId: createdWorktree.worktree.worktreeManagerPluginId ?? null,
removeReason: "rollback",
untrusted: Boolean(createdWorktree.untrustedSource),
},
error,
);
@@ -286,10 +286,6 @@ async function maybeMarkFirstAgentBranchAutoNameEligible(options: {
if (!createdWorktree.created || createdWorktree.intent.kind !== "branch-off") {
return;
}
// A worktree manager plugin owns branch and directory naming, so skip silent renames.
if (createdWorktree.worktree.worktreeManagerPluginId) {
return;
}
// A branch the caller named is their choice; only a placeholder slug is replaced.
if (input.branchName !== undefined) {
return;
+1 -30
View File
@@ -24,7 +24,7 @@ import { type ManagedPluginCandidate, ManagedPluginSources } from "./managed-sou
import { readPluginManifest } from "./manifest.js";
import { expandTilde } from "../../utils/path.js";
import { runPluginBuild } from "./preparation.js";
import { PluginRuntime, type PluginWorktreeManagerRuntime } from "./runtime.js";
import { PluginRuntime } from "./runtime.js";
import type { PluginRuntimeSubscription } from "./runtime-subscription.js";
import { BuiltinPluginLoader, type BuiltinPlugin } from "./builtin/index.js";
import type {
@@ -50,10 +50,6 @@ interface PluginRuntimePort {
drainEvents?: PluginRuntime["drainEvents"];
before?: PluginLifecycle["before"];
wait?: PluginLifecycle["wait"];
hasWorktreeManager?: PluginWorktreeManagerRuntime["hasWorktreeManager"];
createWorktree?: PluginWorktreeManagerRuntime["createWorktree"];
removeWorktree?: PluginWorktreeManagerRuntime["removeWorktree"];
restoreWorktree?: PluginWorktreeManagerRuntime["restoreWorktree"];
catalog: PluginRuntime["catalog"];
invoke(pluginId: string, method: string, input: unknown): Promise<unknown>;
startSubscription: PluginRuntime["startSubscription"];
@@ -196,31 +192,6 @@ export class PluginService {
return request;
};
readonly hasWorktreeManager: PluginWorktreeManagerRuntime["hasWorktreeManager"] = (options) => {
return this.runtime.hasWorktreeManager?.(options) ?? false;
};
readonly createWorktree: PluginWorktreeManagerRuntime["createWorktree"] = async (
request,
options,
) => {
return (await this.runtime.createWorktree?.(request, options)) ?? null;
};
readonly removeWorktree: PluginWorktreeManagerRuntime["removeWorktree"] = async (
request,
options,
) => {
return (await this.runtime.removeWorktree?.(request, options)) ?? null;
};
readonly restoreWorktree: PluginWorktreeManagerRuntime["restoreWorktree"] = async (
request,
options,
) => {
return (await this.runtime.restoreWorktree?.(request, options)) ?? null;
};
subscribeSettings(listener: (pluginId: string, settingsId: string) => void): () => void {
this.settingsListeners.add(listener);
return () => this.settingsListeners.delete(listener);
@@ -57,12 +57,7 @@ const changeRequestFields = {
};
const worktreeRequestSchema = z.discriminatedUnion("kind", [
z
.object({
...worktreeRequestFields,
kind: z.literal("branch-off"),
baseRef: z.string().min(1),
startPoint: z.string().min(1).optional(),
})
.object({ ...worktreeRequestFields, kind: z.literal("branch-off"), baseRef: z.string().min(1) })
.strict(),
z
.object({
@@ -244,28 +239,6 @@ function changesSessionOpenTarget(previous: SessionOpenRequest, next: SessionOpe
);
}
type WorktreeBeforeRequest = z.infer<(typeof beforeSchemas)["worktree.create.before"]>;
function validateWorktreeBeforeResult(
previous: WorktreeBeforeRequest,
next: WorktreeBeforeRequest,
): WorktreeBeforeRequest {
if (previous.repoRoot !== next.repoRoot || previous.sourceCheckout !== next.sourceCheckout) {
throw new Error("worktree.create.before hooks cannot change repoRoot or sourceCheckout");
}
if (previous.kind === "branch-off" && next.kind === "branch-off") {
if (next.startPoint !== undefined && next.startPoint !== previous.startPoint) {
throw new Error("worktree.create.before hooks cannot change startPoint");
}
if (next.startPoint === undefined && previous.startPoint !== undefined) {
return { ...next, startPoint: previous.startPoint };
}
} else if (next.kind === "branch-off" && next.startPoint !== undefined) {
throw new Error("worktree.create.before hooks cannot change startPoint");
}
return next;
}
export async function validateBeforeResult<Name extends keyof PluginWireBeforeRequests>(
name: Name,
input: PluginWireBeforeRequests[Name],
@@ -307,7 +280,9 @@ export async function validateBeforeResult<Name extends keyof PluginWireBeforeRe
if (name === "worktree.create.before") {
const previous = beforeSchemas["worktree.create.before"].parse(input);
const next = beforeSchemas["worktree.create.before"].parse(result);
return validateWorktreeBeforeResult(previous, next) as PluginWireBeforeRequests[Name];
if (previous.repoRoot !== next.repoRoot || previous.sourceCheckout !== next.sourceCheckout) {
throw new Error("worktree.create.before hooks cannot change repoRoot or sourceCheckout");
}
}
return result;
}
@@ -45,11 +45,6 @@ export interface PluginUsageSourceMetadata {
icon?: string;
}
export interface PluginWorktreeManagerCapabilities {
hasRemove: boolean;
hasRestore: boolean;
}
export type PluginProcessRequest =
| { type: "tool.call"; requestId: string; agent: PluginHookAgent; name: string; input: unknown }
| { type: "tool.cancel"; requestId: string }
@@ -89,10 +84,6 @@ export type PluginProcessRequest =
}
| { type: "hook"; requestId: string; name: string; input: unknown }
| { type: "hook.cancel"; requestId: string }
| { type: "worktree.create"; requestId: string; request: unknown }
| { type: "worktree.remove"; requestId: string; request: unknown }
| { type: "worktree.restore"; requestId: string; request: unknown }
| { type: "worktree.cancel"; requestId: string }
| { type: "usage.fetch"; requestId: string; sourceId: string; input: unknown }
| { type: "usage.discover"; requestId: string; sourceId: string; scope: UsageScope }
| { type: "invoke"; requestId: string; method: string; input: unknown }
@@ -124,10 +115,6 @@ export type PluginProcessRequest =
export type PluginProcessMessage =
| { type: "settings.changed"; settingsId: string }
| { type: "hooks.changed"; hooks: string[] }
| {
type: "worktree_manager.changed";
worktreeManager: PluginWorktreeManagerCapabilities | null;
}
| {
type: "ready";
methods: string[];
@@ -135,7 +122,6 @@ export type PluginProcessMessage =
providers: PluginProviderMetadata[];
usageSources?: PluginUsageSourceMetadata[];
hooks?: string[];
worktreeManager?: PluginWorktreeManagerCapabilities | null;
}
| { type: "result"; requestId: string; output: unknown }
| { type: "error"; requestId: string; error: string }
@@ -163,12 +149,6 @@ export type PluginProcessMessage =
| { type: "paseo_close" };
const hooksSchema = z.array(z.string());
const worktreeManagerCapabilitiesSchema = z
.object({
hasRemove: z.boolean(),
hasRestore: z.boolean(),
})
.strict();
const providerMetadataSchema = z
.object({
@@ -314,14 +294,6 @@ export const PluginProcessRequestSchema: z.ZodType<PluginProcessRequest> = z.dis
})
.strict(),
z.object({ type: z.literal("hook.cancel"), requestId: z.string() }).strict(),
z
.object({
type: z.enum(["worktree.create", "worktree.remove", "worktree.restore"]),
requestId: z.string().min(1),
request: z.unknown(),
})
.strict(),
z.object({ type: z.literal("worktree.cancel"), requestId: z.string().min(1) }).strict(),
z
.object({
type: z.literal("usage.fetch"),
@@ -384,12 +356,6 @@ export const PluginProcessMessageSchema: z.ZodType<PluginProcessMessage> = z.dis
[
z.object({ type: z.literal("settings.changed"), settingsId: z.string() }).strict(),
z.object({ type: z.literal("hooks.changed"), hooks: hooksSchema }).strict(),
z
.object({
type: z.literal("worktree_manager.changed"),
worktreeManager: worktreeManagerCapabilitiesSchema.nullable(),
})
.strict(),
z
.object({
type: z.literal("ready"),
@@ -398,7 +364,6 @@ export const PluginProcessMessageSchema: z.ZodType<PluginProcessMessage> = z.dis
providers: z.array(providerMetadataSchema),
usageSources: z.array(usageSourceMetadataSchema).optional(),
hooks: hooksSchema.optional(),
worktreeManager: worktreeManagerCapabilitiesSchema.nullable().optional(),
})
.strict(),
z
@@ -16,10 +16,6 @@ import type {
PluginHandlerContext,
PluginServerContext,
PluginServerContribution,
PluginWorktreeCreateInput,
PluginWorktreeRemoveRequest,
PluginWorktreeRestoreRequest,
WorktreeManagerRegistration,
} from "@getpaseo/plugin/server";
import { assertPluginWireValue } from "@getpaseo/protocol/binary-frames/index";
import {
@@ -119,8 +115,6 @@ export function createPluginWorker(options: {
const subscriptions = new PluginSubscriptionHandlers({ send, sendAndWait });
const providers = new Map<string, ProviderRegistration>();
const usageSources = new Map<string, UsageSourceRegistration>();
let worktreeManager: WorktreeManagerRegistration | null = null;
const worktreeRequests = new Map<string, AbortController>();
const providerConnections = new Map<
string,
{ connection: ProviderConnection; unsubscribe: () => void; closing?: Promise<void> }
@@ -234,36 +228,6 @@ export function createPluginWorker(options: {
usageSources.set(id, { ...source, id });
}
function worktreeManagerCapabilities() {
if (!worktreeManager) return null;
return {
hasRemove: worktreeManager.remove !== undefined,
hasRestore: worktreeManager.restore !== undefined,
};
}
function registerWorktreeManager(manager: WorktreeManagerRegistration): () => void {
if (!manager || typeof manager.create !== "function") {
throw new Error("Plugin worktree manager must implement create()");
}
if (manager.remove !== undefined && typeof manager.remove !== "function") {
throw new Error("Invalid remove callback for plugin worktree manager");
}
if (manager.restore !== undefined && typeof manager.restore !== "function") {
throw new Error("Invalid restore callback for plugin worktree manager");
}
if (worktreeManager !== null) {
throw new Error("Plugin already registered a worktree manager");
}
worktreeManager = manager;
send({ type: "worktree_manager.changed", worktreeManager: worktreeManagerCapabilities() });
return () => {
if (worktreeManager !== manager) return;
worktreeManager = null;
send({ type: "worktree_manager.changed", worktreeManager: null });
};
}
function providerMetadata(provider: ProviderRegistration) {
return {
id: provider.id,
@@ -469,7 +433,6 @@ export function createPluginWorker(options: {
handle,
registerProvider,
registerUsageSource,
registerWorktreeManager,
registerSettings,
addHook: hooks.addHook,
on: hooks.on,
@@ -496,7 +459,6 @@ export function createPluginWorker(options: {
methods: [...handlers.keys()].sort(),
subscriptions: subscriptions.catalog(),
hooks: hooks.catalog(),
worktreeManager: worktreeManagerCapabilities(),
providers: [...providers.values()]
.sort((left, right) => left.id.localeCompare(right.id))
.map(providerMetadata),
@@ -516,8 +478,6 @@ export function createPluginWorker(options: {
for (const pending of pendingProviderConnections.values()) pending.tombstoned = true;
for (const request of installationRequests.values())
request.abort(new Error("Plugin is stopping"));
for (const request of worktreeRequests.values()) request.abort(new Error("Plugin is stopping"));
worktreeManager = null;
const currentCleanup = cleanup;
cleanup = null;
try {
@@ -559,9 +519,6 @@ export function createPluginWorker(options: {
message.type === "provider.catalog_key" ||
message.type === "usage.fetch" ||
message.type === "usage.discover" ||
message.type === "worktree.create" ||
message.type === "worktree.remove" ||
message.type === "worktree.restore" ||
message.type === "subscribe"
) {
send({ type: "error", requestId: message.requestId, error: "Plugin is stopping" });
@@ -747,10 +704,6 @@ export function createPluginWorker(options: {
handleHookMessage(message);
return;
}
if (isWorktreeMessage(message)) {
handleWorktreeMessage(message);
return;
}
if (message.type === "invoke") invoke(message);
else handleSubscriptionMessage(message);
}
@@ -816,88 +769,6 @@ export function createPluginWorker(options: {
): message is Extract<PluginProcessRequest, { type: "hook" | "hook.cancel" }> {
return message.type === "hook" || message.type === "hook.cancel";
}
function isWorktreeMessage(
message: PluginProcessRequest,
): message is Extract<
PluginProcessRequest,
{ type: "worktree.create" | "worktree.remove" | "worktree.restore" | "worktree.cancel" }
> {
return (
message.type === "worktree.create" ||
message.type === "worktree.remove" ||
message.type === "worktree.restore" ||
message.type === "worktree.cancel"
);
}
function handleWorktreeMessage(
message: Extract<
PluginProcessRequest,
{ type: "worktree.create" | "worktree.remove" | "worktree.restore" | "worktree.cancel" }
>,
): void {
if (message.type === "worktree.cancel") {
worktreeRequests.get(message.requestId)?.abort(new Error("Worktree request canceled"));
return;
}
if (!paseo) {
send({
type: "error",
requestId: message.requestId,
error: "Plugin Paseo API is unavailable",
});
return;
}
const manager = worktreeManager;
if (!manager) {
send({
type: "error",
requestId: message.requestId,
error: "Plugin has no registered worktree manager",
});
return;
}
const controller = new AbortController();
worktreeRequests.set(message.requestId, controller);
const context = { paseo, signal: controller.signal };
void (async () => {
if (message.type === "worktree.create") {
return (
(await manager.create(
structuredClone(message.request) as PluginWorktreeCreateInput,
context,
)) ?? null
);
}
if (message.type === "worktree.remove") {
if (!manager.remove) {
throw new Error("Plugin worktree manager does not implement remove");
}
return (
(await manager.remove(
structuredClone(message.request) as PluginWorktreeRemoveRequest,
context,
)) ?? null
);
}
if (!manager.restore) {
throw new Error("Plugin worktree manager does not implement restore");
}
return (
(await manager.restore(
structuredClone(message.request) as PluginWorktreeRestoreRequest,
context,
)) ?? null
);
})()
.then(
(output) => send({ type: "result", requestId: message.requestId, output }),
(error) =>
send({ type: "error", requestId: message.requestId, error: describeError(error) }),
)
.finally(() => worktreeRequests.delete(message.requestId));
}
return { shutdown };
}
@@ -6,7 +6,12 @@ import { PassThrough } from "node:stream";
import path from "node:path";
import { fileURLToPath } from "node:url";
import pino from "pino";
import type { ProviderEvent, ProviderRegistration } from "@getpaseo/plugin/server/provider";
import {
PROVIDER_CAPABILITIES,
type ProviderEvent,
type ProviderPrompt,
type ProviderRegistration,
} from "@getpaseo/plugin/server/provider";
import { afterEach, describe, expect, it, vi } from "vitest";
import type { AgentStreamEvent } from "../agent/agent-sdk-types.js";
import { PluginAgentClientRegistry } from "../agent/plugin-provider.js";
@@ -358,6 +363,232 @@ register(${JSON.stringify(guardUrl)});`;
await adapters.shutdown();
await runtime.stopAll();
});
// The muse provider runs against a fake MSP host (injected through the
// provider's command override), but everything above it is real: the plugin
// subprocess, PluginRuntime's capability enforcement, and the
// PluginAgentClientRegistry path an agent actually uses. On a muse build
// that does not negotiate `session.subsession`, the daemon fails the whole
// provider connection when the child is projected, so both tests fail
// before the fix.
async function startMuseRuntime() {
const fakeMuse = fileURLToPath(
new URL("../../../../../plugins/muse-provider/test/fake-muse.mjs", import.meta.url),
);
const directory = fileURLToPath(
new URL("../../../../../plugins/muse-provider/", import.meta.url),
);
const runtime = createTestRuntime({}, undefined, "0.11.0");
await runtime.startPlugin("muse-provider", directory);
const [metadata] = runtime.getProviderRegistrations("muse-provider");
expect(metadata).toBeDefined();
return { runtime, metadata: metadata!, fakeMuse };
}
async function startMuseClient(extraEnv: Record<string, string>) {
const { runtime, metadata, fakeMuse } = await startMuseRuntime();
const adapters = new PluginAgentClientRegistry(pino({ level: "silent" }));
adapters.replace([
{
...adaptRuntimeProvider(runtime, "muse-provider", metadata),
command: metadata.command,
},
]);
const client = adapters.definitions()[metadata.id]!.createClient(pino({ level: "silent" }), {
command: { mode: "replace", argv: [process.execPath, fakeMuse] },
env: { MUSE_TEST_SCENARIO: "subagent", MUSE_TEST_CHILD: "tool", ...extraEnv },
});
return { runtime, adapters, client };
}
function hasSettledTurn(events: readonly AgentStreamEvent[]): boolean {
return events.some((event) => event.type === "turn_completed" || event.type === "turn_failed");
}
// Asserting on the settled turn (rather than polling only for completion)
// puts the provider's failure — e.g. "Provider parent session did not
// negotiate session.subsession" — in the test output.
async function expectTurnCompleted(events: readonly AgentStreamEvent[]): Promise<void> {
await expect.poll(() => hasSettledTurn(events)).toBe(true);
expect(events.filter((event) => event.type === "turn_failed")).toEqual([]);
expect(hasCompletedAgentTurn(events)).toBe(true);
}
function hasSubagentTimeline(events: readonly AgentStreamEvent[]): boolean {
return events.some(
(event) =>
event.type === "provider_subagent" &&
event.event.type === "timeline" &&
event.event.item.type === "assistant_message" &&
event.event.item.text.includes("SUBAGENT_PHASE0_OK"),
);
}
it("projects a muse subagent through PluginRuntime without failing the connection", async () => {
const { runtime, adapters, client } = await startMuseClient({});
try {
const events: AgentStreamEvent[] = [];
const session = await client.createSession({ provider: "muse", cwd: process.cwd() });
session.subscribe((event) => events.push(event));
await session.startTurn("dispatch a subagent", { clientMessageId: "muse-live" });
await expectTurnCompleted(events);
expect(hasSubagentTimeline(events)).toBe(true);
// The connection survives: a fresh session on the same provider opens
// and completes a turn instead of hitting a dead cached connection.
const second = await client.createSession({ provider: "muse", cwd: process.cwd() });
const secondEvents: AgentStreamEvent[] = [];
second.subscribe((event) => secondEvents.push(event));
await second.startTurn("again", { clientMessageId: "muse-live-2" });
await expectTurnCompleted(secondEvents);
await second.close();
await session.close();
} finally {
await adapters.shutdown();
await runtime.stopAll();
}
});
it("replays a muse subagent from history on resume without failing the connection", async () => {
const historyDirectory = await mkdtemp(path.join(tmpdir(), "paseo-muse-history-"));
temporaryDirectories.push(historyDirectory);
const { runtime, adapters, client } = await startMuseClient({
MUSE_TEST_HISTORY: path.join(historyDirectory, "native-history.ndjson"),
});
try {
const first = await client.createSession({ provider: "muse", cwd: process.cwd() });
const persistence = first.describePersistence();
expect(persistence).not.toBeNull();
await first.close();
// Seed old history without running a live subagent first, so this test
// reaches resume even when live child projection is broken.
await writeFile(
path.join(historyDirectory, "native-history.ndjson"),
JSON.stringify({
itemId: "historical-subagent",
revision: 1,
kind: "toolCall",
status: "completed",
tool: "subagent_spawn",
childSessionId: "fixture-child",
}) + "\n",
);
const resumed = await client.resumeSession(persistence!, { cwd: process.cwd() });
const resumedEvents: AgentStreamEvent[] = [];
resumed.subscribe((event) => resumedEvents.push(event));
// History replayed during resume is exposed through streamHistory.
const replayed: AgentStreamEvent[] = [];
for await (const event of resumed.streamHistory()) replayed.push(event);
expect(hasSubagentTimeline(replayed)).toBe(true);
await resumed.startTurn("continue", { clientMessageId: "muse-resumed" });
await expectTurnCompleted(resumedEvents);
await resumed.close();
} finally {
await adapters.shutdown();
await runtime.stopAll();
}
});
it("keeps other Muse sessions live when a parent closes during a child read", async () => {
const directory = await mkdtemp(path.join(tmpdir(), "paseo-muse-child-read-"));
temporaryDirectories.push(directory);
const requests = path.join(directory, "requests.ndjson");
const release = path.join(directory, "release");
const { runtime, metadata, fakeMuse } = await startMuseRuntime();
try {
const connection = await runtime.connectProvider("muse-provider", metadata.id, {
versions: [1],
capabilities: PROVIDER_CAPABILITIES,
launch: {
command: process.execPath,
args: [fakeMuse],
env: {
MUSE_TEST_SCENARIO: "subagent",
MUSE_TEST_CHILD: "tool",
MUSE_TEST_REQUESTS: requests,
MUSE_TEST_CHILD_READ_RELEASE: release,
},
},
});
const events: ProviderEvent[] = [];
connection.onEvent((event) => events.push(event));
for (const sessionId of ["closing", "sibling"]) {
await connection.send({
type: "session.open",
requestId: `open-${sessionId}`,
sessionId,
history: "skip",
config: { cwd: process.cwd(), env: {}, mcpServers: {}, settings: {}, persist: true },
});
await expect
.poll(() => events, { timeout: 5000 })
.toContainEqual(expect.objectContaining({ type: "session.ready", sessionId }));
}
const prompt: ProviderPrompt = {
clientMessageId: "spawn-child",
delivery: "auto",
input: { type: "message", content: [{ type: "text", text: "spawn a child" }] },
};
await connection.send({ type: "session.prompt", sessionId: "closing", prompt });
await expect
.poll(() => readFile(requests, "utf8"), { timeout: 5000 })
.toContain('"method":"session/read"');
// send() resolves after the runtime has accepted the close and removed
// the parent from its session table, while the child read is still pending.
await connection.send({
type: "session.close",
requestId: "close-parent",
sessionId: "closing",
});
await writeFile(release, "");
const closeSettled = (event: ProviderEvent) =>
(event.type === "request.completed" && event.requestId === "close-parent") ||
(event.type === "session.runtime_failed" && event.sessionId === "sibling");
await expect.poll(() => events.some(closeSettled), { timeout: 5000 }).toBe(true);
expect(
events.filter(
(event) => event.type === "session.runtime_failed" && event.sessionId === "sibling",
),
).toEqual([]);
expect(events).toContainEqual({ type: "request.completed", requestId: "close-parent" });
await connection.send({ type: "session.prompt", sessionId: "sibling", prompt });
await expect
.poll(() => events, { timeout: 5000 })
.toContainEqual(
expect.objectContaining({
type: "session.turn",
sessionId: "sibling",
state: "completed",
}),
);
} finally {
await writeFile(release, "");
await runtime.stopAll();
}
});
it("closes a Muse agent when the host exits without answering a child read", async () => {
const directory = await mkdtemp(path.join(tmpdir(), "paseo-muse-close-"));
temporaryDirectories.push(directory);
const requests = path.join(directory, "requests.ndjson");
const { runtime, adapters, client } = await startMuseClient({
MUSE_TEST_HANG: "session/read",
MUSE_TEST_REQUESTS: requests,
});
try {
const session = await client.createSession({ provider: "muse", cwd: process.cwd() });
await session.startTurn("spawn a child", { clientMessageId: "close-with-pending-read" });
await expect
.poll(() => readFile(requests, "utf8"), { timeout: 5000 })
.toContain('"method":"session/read"');
await expect(session.close()).resolves.toBeUndefined();
} finally {
await adapters.shutdown();
await runtime.stopAll();
}
});
it("runs a provider connection through the real plugin subprocess boundary", async () => {
const directory = await createPlugin(
+3 -174
View File
@@ -18,15 +18,7 @@ import {
type ProviderStatus,
type ProviderStatusRequest,
} from "@getpaseo/plugin/server/provider";
import type {
PluginHookEvents,
PluginHookAgent,
AgentToolResult,
PluginWorktreeCreateInput,
PluginWorktreeRemoveRequest,
PluginWorktreeRestoreRequest,
} from "@getpaseo/plugin/server";
import { z } from "zod";
import type { PluginHookEvents, PluginHookAgent, AgentToolResult } from "@getpaseo/plugin/server";
import { validateBeforeRequest, validateBeforeResult } from "./lifecycle/index.js";
import { fork } from "node:child_process";
import path from "node:path";
@@ -50,7 +42,6 @@ import type {
PluginProcessRequest,
PluginProviderMetadata,
PluginUsageSourceMetadata,
PluginWorktreeManagerCapabilities,
} from "./plugin-process-protocol.js";
import { PluginProcessMessageSchema } from "./plugin-process-protocol.js";
import {
@@ -62,40 +53,7 @@ import { InternalPluginChild } from "./internal-child.js";
import { evaluateBundle } from "./bundle-evaluator.js";
const REQUEST_TIMEOUT_MS = 30_000;
const WORKTREE_MANAGER_TIMEOUT_MS = 120_000;
const TOOL_CALL_TIMEOUT_MS = 10 * 60_000;
const worktreeCreateResultSchema = z
.object({ type: z.literal("created"), path: z.string().min(1) })
.strict()
.nullable();
const worktreeRemoveResultSchema = z
.object({ type: z.literal("removed") })
.strict()
.nullable();
const worktreeRestoreResultSchema = z
.object({ type: z.literal("restored"), path: z.string().min(1) })
.strict()
.nullable();
export interface PluginWorktreeManagerRuntime {
hasWorktreeManager(options?: {
operation?: "create" | "remove" | "restore";
preferredPluginId?: string;
}): boolean;
createWorktree(
request: PluginWorktreeCreateInput,
options?: { signal?: AbortSignal },
): Promise<{ pluginId: string; path: string } | null>;
removeWorktree(
request: PluginWorktreeRemoveRequest,
options?: { preferredPluginId?: string; signal?: AbortSignal },
): Promise<{ pluginId: string } | null>;
restoreWorktree(
request: PluginWorktreeRestoreRequest,
options?: { preferredPluginId?: string; signal?: AbortSignal },
): Promise<{ pluginId: string; path: string } | null>;
}
const MAX_LOG_ENTRIES = 500;
const MAX_LOG_BYTES = 256 * 1024;
const MAX_LOG_LINE_BYTES = 16 * 1024;
@@ -129,8 +87,6 @@ interface PluginRequestOptions {
signal?: AbortSignal;
/** Receives `provider.installation.report` messages for the request. */
report?: (report: ProviderUpdateReport) => void;
/** Overrides the default per-message timeout (e.g. shared budget across serial worktree managers). */
timeoutMs?: number;
}
interface LoadedPlugin {
@@ -144,7 +100,6 @@ interface LoadedPlugin {
subscriptionMethods: ReadonlySet<string>;
subscriptions: Map<string, BufferedPluginSubscription>;
hooks: string[];
worktreeManager: PluginWorktreeManagerCapabilities | null;
providers: readonly PluginProviderMetadata[];
usageSources: readonly PluginUsageSourceMetadata[];
child: PluginChild | null;
@@ -338,17 +293,8 @@ function isInstallationRequest(message: PluginProcessRequest): boolean {
);
}
function isWorktreeManagerRequest(message: PluginProcessRequest): boolean {
return (
message.type === "worktree.create" ||
message.type === "worktree.remove" ||
message.type === "worktree.restore"
);
}
function requestTimeoutMs(message: PluginProcessRequest): number | null {
if (message.type === "tool.call") return TOOL_CALL_TIMEOUT_MS;
if (isWorktreeManagerRequest(message)) return WORKTREE_MANAGER_TIMEOUT_MS;
// An updater runs as long as it needs; daemon shutdown aborts it.
if (message.type === "provider.installation.update") return null;
return REQUEST_TIMEOUT_MS;
@@ -806,112 +752,6 @@ export class PluginRuntime {
return request;
}
hasWorktreeManager(options?: {
operation?: "create" | "remove" | "restore";
preferredPluginId?: string;
}): boolean {
const operation = options?.operation ?? "create";
const supports = (manager: PluginWorktreeManagerCapabilities | null): boolean => {
if (!manager) return false;
if (operation === "remove") return manager.hasRemove;
if (operation === "restore") return manager.hasRestore;
return true;
};
if (options?.preferredPluginId) {
return supports(this.plugins.get(options.preferredPluginId)?.worktreeManager ?? null);
}
for (const loaded of this.plugins.values()) {
if (supports(loaded.worktreeManager)) return true;
}
return false;
}
async createWorktree(
request: PluginWorktreeCreateInput,
options?: { signal?: AbortSignal },
): Promise<{ pluginId: string; path: string } | null> {
const plugins = [...this.plugins.values()]
.filter((plugin) => plugin.worktreeManager !== null)
.sort((left, right) => left.id.localeCompare(right.id));
// Share one 120s budget across the full serial manager chain so clients waiting on
// create_paseo_worktree_request (150s) never time out while the daemon is still running managers.
const deadline = Date.now() + WORKTREE_MANAGER_TIMEOUT_MS;
for (const loaded of plugins) {
const remainingMs = deadline - Date.now();
if (remainingMs <= 0) {
throw new Error(
`Plugin ${loaded.id} worktree.create failed: Plugin RPC timed out: ${loaded.id}.worktree.create`,
);
}
try {
const raw = await this.request(
loaded,
{ type: "worktree.create", requestId: randomUUID(), request },
{ signal: options?.signal, timeoutMs: remainingMs },
);
const parsed = worktreeCreateResultSchema.parse(raw ?? null);
if (parsed !== null) {
return { pluginId: loaded.id, path: parsed.path };
}
} catch (error) {
throw new Error(`Plugin ${loaded.id} worktree.create failed: ${describeError(error)}`, {
cause: error,
});
}
}
return null;
}
async removeWorktree(
request: PluginWorktreeRemoveRequest,
options?: { preferredPluginId?: string; signal?: AbortSignal },
): Promise<{ pluginId: string } | null> {
if (!options?.preferredPluginId) return null;
const loaded = this.plugins.get(options.preferredPluginId);
if (!loaded?.worktreeManager?.hasRemove) return null;
try {
const raw = await this.request(
loaded,
{ type: "worktree.remove", requestId: randomUUID(), request },
{ signal: options.signal },
);
const parsed = worktreeRemoveResultSchema.parse(raw ?? null);
if (parsed !== null) {
return { pluginId: loaded.id };
}
return null;
} catch (error) {
throw new Error(`Plugin ${loaded.id} worktree.remove failed: ${describeError(error)}`, {
cause: error,
});
}
}
async restoreWorktree(
request: PluginWorktreeRestoreRequest,
options?: { preferredPluginId?: string; signal?: AbortSignal },
): Promise<{ pluginId: string; path: string } | null> {
if (!options?.preferredPluginId) return null;
const loaded = this.plugins.get(options.preferredPluginId);
if (!loaded?.worktreeManager?.hasRestore) return null;
try {
const raw = await this.request(
loaded,
{ type: "worktree.restore", requestId: randomUUID(), request },
{ signal: options.signal },
);
const parsed = worktreeRestoreResultSchema.parse(raw ?? null);
if (parsed !== null) {
return { pluginId: loaded.id, path: parsed.path };
}
return null;
} catch (error) {
throw new Error(`Plugin ${loaded.id} worktree.restore failed: ${describeError(error)}`, {
cause: error,
});
}
}
async getProviderCatalogCacheKey(
pluginId: string,
providerId: string,
@@ -1013,14 +853,12 @@ export class PluginRuntime {
loaded.pending.delete(requestId);
if (message.type === "tool.call")
void send(child, { type: "tool.cancel", requestId }).catch(() => {});
if (isWorktreeManagerRequest(message))
void send(child, { type: "worktree.cancel", requestId }).catch(() => {});
if (isInstallationRequest(message))
void send(child, { type: "provider.installation.cancel", requestId }).catch(() => {});
signal?.removeEventListener("abort", cancel);
reject(signal?.reason ?? new Error("Plugin request canceled"));
reject(signal?.reason ?? new Error("Tool call canceled"));
};
const timeoutMs = options.timeoutMs ?? requestTimeoutMs(message);
const timeoutMs = requestTimeoutMs(message);
const timeout =
timeoutMs === null
? undefined
@@ -1032,9 +870,6 @@ export class PluginRuntime {
if (message.type === "hook") {
void send(child, { type: "hook.cancel", requestId }).catch(() => {});
}
if (isWorktreeManagerRequest(message)) {
void send(child, { type: "worktree.cancel", requestId }).catch(() => {});
}
// The handler may still start after the daemon gave up on it.
if (message.type === "subscribe") {
const { subscriptionId } = message;
@@ -1100,7 +935,6 @@ export class PluginRuntime {
subscriptionMethods: new Set(),
subscriptions: new Map(),
hooks: [],
worktreeManager: null,
providers: [],
usageSources: [],
child: null,
@@ -1233,7 +1067,6 @@ export class PluginRuntime {
subscriptionMethods: new Set(ready.subscriptions ?? []),
subscriptions: new Map(),
hooks: ready.hooks ?? [],
worktreeManager: ready.worktreeManager ?? null,
providers: ready.providers ?? [],
usageSources: ready.usageSources ?? [],
child,
@@ -1323,10 +1156,6 @@ export class PluginRuntime {
}
return;
}
if (message.type === "worktree_manager.changed") {
loaded.worktreeManager = message.worktreeManager;
return;
}
if (message.type === "settings.changed") {
this.dependencies.onSettingsChanged?.(loaded.id, message.settingsId);
return;
File diff suppressed because it is too large Load Diff
@@ -1,25 +1,10 @@
import type { ForgeService, PullRequestCheckoutTarget } from "../services/forge-service.js";
import type { WorktreeCheckoutRef, WorktreeSource } from "../utils/worktree.js";
import type { UntrustedWorkspaceSource } from "./workspace-automation-gate.js";
export type WorktreeCreationIntent = Exclude<
WorktreeSource,
{ kind: "restore" | "restore-from-base" | "restore-commit" }
> & { untrustedSource?: UntrustedWorkspaceSource };
export function worktreeUntrustedSource(
intent: WorktreeCreationIntent,
): UntrustedWorkspaceSource | undefined {
if (intent.kind === "checkout-change-request" && intent.headRepository) {
return {
kind: "change_request",
forge: intent.forge,
number: intent.changeRequestNumber,
headRepository: intent.headRepository,
};
}
return intent.untrustedSource;
}
>;
export interface ResolveWorktreeCreationIntentInput {
worktreeSlug?: string;
@@ -171,11 +156,7 @@ async function fetchChangeRequestHead(params: {
changeRequest: { number: number; forge?: string };
repoRoot: string;
deps: ResolveWorktreeCreationIntentDeps;
}): Promise<{
baseBranch: string;
startPoint: string;
untrustedSource?: UntrustedWorkspaceSource;
}> {
}): Promise<{ baseBranch: string; startPoint: string }> {
const { input, changeRequest, repoRoot, deps } = params;
assertCheckoutSourceMatchesResolvedForge(changeRequest, deps);
const checkout = await resolvePrCheckoutIntent({
@@ -184,7 +165,6 @@ async function fetchChangeRequestHead(params: {
repoRoot,
deps,
});
const untrustedSource = worktreeUntrustedSource(checkout);
const startPoint = `refs/paseo/change-requests/${changeRequest.number}`;
const remote = await deps.fetchRef({
repoRoot,
@@ -200,10 +180,10 @@ async function fetchChangeRequestHead(params: {
sources: [{ remoteName: remote, remoteRef: `refs/heads/${baseName}` }],
destination: baseBranch,
});
return { baseBranch, startPoint, untrustedSource };
return { baseBranch, startPoint };
} catch {
// Without the remote's copy, the base resolves as any base branch name does.
return { baseBranch: baseName, startPoint, untrustedSource };
return { baseBranch: baseName, startPoint };
}
}
+74 -8
View File
@@ -529,10 +529,6 @@ test("routes plugin requests and releases its owned catalog subscription on clea
return request;
},
emit: () => {},
hasWorktreeManager: () => false,
createWorktree: async () => null,
removeWorktree: async () => null,
restoreWorktree: async () => null,
listPlugins: async () => [plugin],
getLogs: () => [
{
@@ -674,10 +670,6 @@ test("leaves out the client bundles a catalog request already holds", async () =
const pluginRuntime: NonNullable<SessionOptions["pluginRuntime"]> = {
before: async (_name, request) => request,
emit: () => {},
hasWorktreeManager: () => false,
createWorktree: async () => null,
removeWorktree: async () => null,
restoreWorktree: async () => null,
listPlugins: async () => [],
getLogs: () => [],
installDirectory: async () => {
@@ -6669,3 +6661,77 @@ test("does not publish internal agents' background work to subscribed clients",
await new Promise<void>((resolve) => setImmediate(resolve));
expect(messages.some((message) => message.type === "agent.background_work.update")).toBe(false);
});
test("deduplicates repeated command names in list_commands_response for live agents and drafts", async () => {
const duplicateCommands = [
{
name: "goal",
description: "Run until goal is finished",
argumentHint: "",
kind: "command" as const,
},
{
name: "plan",
description: "Plan carefully before executing a task.",
argumentHint: "",
kind: "command" as const,
},
{
name: "plan",
description: "Local plan skill description",
argumentHint: "",
kind: "skill" as const,
},
];
const expected = [duplicateCommands[0], duplicateCommands[1]];
const liveMessages: SessionOutboundMessage[] = [];
const liveSession = createSessionForTest({
messages: liveMessages,
agentManager: {
waitForAgentClose: async () => undefined,
getAgent: () =>
({
id: "agent-1",
session: { listCommands: async () => duplicateCommands },
}) as never,
},
});
await liveSession.handleMessage({
type: "list_commands_request",
agentId: "agent-1",
requestId: "req-live",
});
expect(findByType(liveMessages, "list_commands_response")).toMatchObject({
payload: {
agentId: "agent-1",
requestId: "req-live",
error: null,
commands: expected,
},
});
const draftMessages: SessionOutboundMessage[] = [];
const draftSession = createSessionForTest({
messages: draftMessages,
agentManager: {
getAgent: () => undefined,
listDraftCommands: async () => duplicateCommands,
},
agentStorage: { get: async () => null },
});
await draftSession.handleMessage({
type: "list_commands_request",
agentId: "draft-1",
requestId: "req-draft",
draftConfig: { provider: "antigravity", cwd: "/tmp/repo" },
});
expect(findByType(draftMessages, "list_commands_response")).toMatchObject({
payload: {
agentId: "draft-1",
requestId: "req-draft",
error: null,
commands: expected,
},
});
});
+61 -166
View File
@@ -113,7 +113,6 @@ import {
assertWorkspaceAutomationAllowedForWorkspace,
clearWorkspaceAutomationBlock,
formatWorkspaceAutomationBlockedMessage,
isCheckoutUntrusted,
} from "./workspace-automation-gate.js";
import {
WorkspaceLabelError,
@@ -247,12 +246,7 @@ import {
matchesAgentUpdatesFilter,
type AgentUpdatesService,
} from "./session/agent-updates/agent-updates-service.js";
import {
createRealpathAwarePathMatcher,
expandTilde,
isRealpathInsideRoot,
normalizePathForIdentity,
} from "../utils/path.js";
import { expandTilde } from "../utils/path.js";
import {
searchDirectoryEntries,
WORKSPACE_SEARCH_HIDDEN_DIRECTORIES,
@@ -293,11 +287,7 @@ import {
handleWorkspaceSetupStatusRequest as handleWorkspaceSetupStatusRequestMessage,
handleWorkspaceSetupRunRequest as handleWorkspaceSetupRunRequestMessage,
} from "./worktree-session.js";
import {
archiveByScope,
resolveWorkspaceBackingPath,
type ActiveWorkspaceRef,
} from "./workspace-archive-service.js";
import { archiveByScope, type ActiveWorkspaceRef } from "./workspace-archive-service.js";
import {
WorkspaceArchiveOperations,
type WorkspaceArchiveUndoInput,
@@ -539,10 +529,6 @@ export interface SessionOptions {
wait: import("./plugins/lifecycle/index.js").PluginLifecycle["wait"];
before: import("./plugins/lifecycle/index.js").PluginLifecycle["before"];
emit: import("./plugins/lifecycle/index.js").PluginLifecycle["emit"];
hasWorktreeManager: import("./plugins/runtime.js").PluginWorktreeManagerRuntime["hasWorktreeManager"];
createWorktree: import("./plugins/runtime.js").PluginWorktreeManagerRuntime["createWorktree"];
removeWorktree: import("./plugins/runtime.js").PluginWorktreeManagerRuntime["removeWorktree"];
restoreWorktree: import("./plugins/runtime.js").PluginWorktreeManagerRuntime["restoreWorktree"];
listPlugins(): Promise<import("@getpaseo/protocol/messages").PluginListItem[]>;
getLogs(pluginId: string): import("@getpaseo/protocol/messages").PluginLogEntry[];
installDirectory(input: {
@@ -1048,34 +1034,12 @@ export class Session {
this.workspaceRecovery = createWorkspaceRecoveryService({
paseoHome: this.paseoHome,
worktreesRoot: this.worktreesRoot,
worktreeManagers: this.pluginRuntime,
getWorkspace: (workspaceId) => this.workspaceRegistry.get(workspaceId),
getProject: (projectId) => this.projectRegistry.get(projectId),
isDirectory: (path) => this.filesystem.isDirectory(path),
unarchiveWorkspace: async (workspace) => {
await this.workspaceProvisioning.ensureWorkspaceRecordUnarchived(workspace);
},
isCheckoutUntrusted: (checkoutPath) =>
isCheckoutUntrusted(this.workspaceRegistry, checkoutPath),
syncCheckoutWorktreeManager: async ({
worktreeRoot,
worktreeManagerPluginId,
excludeWorkspaceId,
}) => {
const matchesCheckout = createRealpathAwarePathMatcher(worktreeRoot);
const workspaces = await this.workspaceRegistry.listAll();
const timestamp = new Date().toISOString();
for (const candidate of workspaces) {
if (candidate.workspaceId === excludeWorkspaceId) continue;
if (!matchesCheckout(candidate.worktreeRoot ?? candidate.cwd)) continue;
if ((candidate.worktreeManagerPluginId ?? null) === worktreeManagerPluginId) continue;
const { worktreeManagerPluginId: _previous, ...withoutManager } = candidate;
const updated: PersistedWorkspaceRecord = worktreeManagerPluginId
? { ...withoutManager, worktreeManagerPluginId, updatedAt: timestamp }
: { ...withoutManager, updatedAt: timestamp };
await this.workspaceRegistry.upsert(updated);
}
},
});
this.diffSession = new DiffSession(checkoutDiffManager.streams, this.sessionLogger);
this.checkoutSession = new CheckoutSession({
@@ -1287,15 +1251,9 @@ export class Session {
),
logger: this.sessionLogger,
});
this.workspaceArchiveOperations = resolveWorkspaceArchiveOperations(workspaceArchiveOperations);
this.createAgentLifecycleDispatch = new CreateAgentLifecycleDispatch({
paseoHome: this.paseoHome,
worktreesRoot: this.worktreesRoot,
worktreeManagers: this.pluginRuntime,
workspaceArchiveOperations: this.workspaceArchiveOperations,
getWorkspace: (workspaceId) => this.workspaceRegistry.get(workspaceId),
isCheckoutUntrusted: (checkoutPath) =>
isCheckoutUntrusted(this.workspaceRegistry, checkoutPath),
agentManager: this.agentManager,
agentStorage: this.agentStorage,
github: this.github,
@@ -1334,6 +1292,7 @@ export class Session {
},
);
this.workspaceSetupRuntime = resolveWorkspaceSetupRuntime(workspaceSetupRuntime);
this.workspaceArchiveOperations = resolveWorkspaceArchiveOperations(workspaceArchiveOperations);
this.getDaemonTcpPort = getDaemonTcpPort ?? null;
this.getDaemonTcpHost = getDaemonTcpHost ?? null;
this.serviceProxyPublicBaseUrl = serviceProxyPublicBaseUrl ?? null;
@@ -5644,7 +5603,7 @@ export class Session {
: null;
if (agent?.session?.listCommands) {
const commands = await agent.session.listCommands();
const commands = dedupeSlashCommands(await agent.session.listCommands());
this.emit({
type: "list_commands_response",
payload: {
@@ -5668,7 +5627,9 @@ export class Session {
: {}),
};
const commands = await this.agentManager.listDraftCommands(sessionConfig);
const commands = dedupeSlashCommands(
await this.agentManager.listDraftCommands(sessionConfig),
);
this.emit({
type: "list_commands_response",
payload: {
@@ -5821,14 +5782,11 @@ export class Session {
{
paseoHome: this.paseoHome,
paseoWorktreesBaseRoot: this.worktreesRoot,
worktreeManagers: this.pluginRuntime,
workspaceArchiveOperations: this.workspaceArchiveOperations,
github: this.github,
workspaceGitService: this.workspaceGitService,
agentManager: this.agentManager,
agentStorage: this.agentStorage,
findWorkspaceIdForCwd: (cwd) => this.findWorkspaceIdForCwd(cwd),
getWorkspace: (workspaceId) => this.workspaceRegistry.get(workspaceId),
listActiveWorkspaces: () => this.listActiveWorkspaceRefs(),
archiveWorkspaceRecord: (workspaceId, archivedAt) =>
this.archiveWorkspaceRecord(workspaceId, archivedAt),
@@ -5840,8 +5798,6 @@ export class Session {
clearWorkspaceArchiving: (workspaceIds) => this.clearWorkspaceArchiving(workspaceIds),
killTerminalsForWorkspace: (workspaceId) =>
this.terminalController.killTerminalsForWorkspace(workspaceId),
isCheckoutUntrusted: (checkoutPath) =>
isCheckoutUntrusted(this.workspaceRegistry, checkoutPath),
sessionLogger: this.sessionLogger,
},
msg,
@@ -6547,60 +6503,9 @@ export class Session {
};
}
private async withWorkspaceCheckout<T>(workspaceId: string, run: () => Promise<T>): Promise<T> {
const workspace = await this.workspaceRegistry.get(workspaceId);
if (!workspace) {
return run();
}
const checkoutPath = await resolveWorkspaceBackingPath(workspace, {
paseoHome: this.paseoHome,
paseoWorktreesBaseRoot: this.worktreesRoot,
});
return this.workspaceArchiveOperations.withCheckout(checkoutPath, run);
}
private async withCheckoutForDirectory<T>(cwd: string, run: () => Promise<T>): Promise<T> {
const normalizedCwd = resolve(cwd);
const matchesCwd = createRealpathAwarePathMatcher(normalizedCwd);
const workspaces = await this.workspaceRegistry.listAll();
let matchingWorkspace = workspaces.find((workspace) => matchesCwd(workspace.cwd));
if (!matchingWorkspace) {
let bestDepth = -1;
for (const workspace of workspaces) {
if (
workspace.worktreeRoot !== null &&
isRealpathInsideRoot(workspace.worktreeRoot, normalizedCwd)
) {
const depth = normalizePathForIdentity(workspace.worktreeRoot).length;
if (depth > bestDepth) {
bestDepth = depth;
matchingWorkspace = workspace;
}
}
}
}
let checkoutPath = normalizedCwd;
if (matchingWorkspace) {
checkoutPath = await resolveWorkspaceBackingPath(matchingWorkspace, {
paseoHome: this.paseoHome,
paseoWorktreesBaseRoot: this.worktreesRoot,
});
} else {
const checkout = await this.workspaceGitService.getCheckout(normalizedCwd);
if (checkout.isGit && checkout.worktreeRoot) {
checkoutPath = resolve(checkout.worktreeRoot);
}
}
return this.workspaceArchiveOperations.withCheckout(checkoutPath, run);
}
private async restoreWorkspaceAndEmit(workspaceId: string): Promise<void> {
await this.workspaceArchiveOperations.restore(workspaceId, () =>
this.withWorkspaceCheckout(workspaceId, async () => {
await this.workspaceRecovery.restore(workspaceId);
await this.publishRecoveredWorkspace(workspaceId);
}),
);
await this.workspaceRecovery.restore(workspaceId);
await this.publishRecoveredWorkspace(workspaceId);
}
private async publishRecoveredWorkspace(workspaceId: string): Promise<void> {
@@ -6647,7 +6552,6 @@ export class Session {
): Promise<CreatePaseoWorktreeResult> {
const result = await createPaseoWorktree(input, {
lifecycle: this.pluginRuntime,
worktreeManagers: this.pluginRuntime,
github: this.github,
...(options?.resolveDefaultBranch
? { resolveDefaultBranch: options.resolveDefaultBranch }
@@ -6678,8 +6582,6 @@ export class Session {
worktreeRoot: workspace.worktreeRoot,
isPaseoOwnedWorktree: workspace.isPaseoOwnedWorktree,
mainRepoRoot: workspace.mainRepoRoot,
worktreeManagerPluginId: workspace.worktreeManagerPluginId,
untrustedSource: workspace.untrustedSource,
}));
}
@@ -7534,29 +7436,24 @@ export class Session {
}
const cwd = expandTilde(request.source.path);
const directoryExists = await this.filesystem.isDirectory(cwd).catch(() => false);
if (!directoryExists) {
throw new SessionRequestError("directory_not_found", `Directory not found: ${cwd}`);
}
const explicitTitle = request.title?.trim() || null;
const promptTitle = resolveFirstAgentPromptTitle(request.firstAgentContext);
const backgroundIntent = await this.workspaceBackgroundIntent(
request.background,
request.callerAgentId,
const workspace = await this.workspaceProvisioning.createWorkspaceForDirectory(
cwd,
explicitTitle ?? promptTitle,
request.source.projectId,
{
expectsInitialAgent: Boolean(request.firstAgentContext),
workspaceId,
metadata: request.metadata,
...(await this.workspaceBackgroundIntent(request.background, request.callerAgentId)),
},
);
const workspace = await this.withCheckoutForDirectory(cwd, async () => {
const directoryExists = await this.filesystem.isDirectory(cwd).catch(() => false);
if (!directoryExists) {
throw new SessionRequestError("directory_not_found", `Directory not found: ${cwd}`);
}
return this.workspaceProvisioning.createWorkspaceForDirectory(
cwd,
explicitTitle ?? promptTitle,
request.source.projectId,
{
expectsInitialAgent: Boolean(request.firstAgentContext),
workspaceId,
metadata: request.metadata,
...backgroundIntent,
},
);
});
await this.syncWorkspaceGitObserverForWorkspace(workspace);
const descriptor = await this.describeWorkspaceRecord(workspace);
await this.emitCreatedWorkspaceUpdate(
@@ -7638,41 +7535,34 @@ export class Session {
): Promise<void> {
const requestedCwd = request.cwd;
const cwd = expandTilde(requestedCwd);
const directoryExists = await this.filesystem.isDirectory(cwd).catch(() => false);
if (!directoryExists) {
this.sessionLogger.info(
{ requestedCwd, resolvedCwd: cwd, reason: "directory_not_found" },
"Open project rejected",
);
this.emit({
type: "open_project_response",
payload: {
requestId: request.requestId,
workspace: null,
error: `Directory not found: ${cwd}`,
errorCode: "directory_not_found",
},
});
return;
}
try {
const opened = await this.withCheckoutForDirectory(cwd, async () => {
const directoryExists = await this.filesystem.isDirectory(cwd).catch(() => false);
if (!directoryExists) {
return null;
}
const projectsBefore = new Map<string, PersistedProjectRecord>();
for (const project of await this.projectRegistry.list()) {
projectsBefore.set(project.projectId, project);
}
const workspacesBefore = new Map<string, PersistedWorkspaceRecord>();
for (const workspaceRecord of await this.workspaceRegistry.listActive()) {
workspacesBefore.set(workspaceRecord.workspaceId, workspaceRecord);
}
const workspace = await this.workspaceProvisioning.findOrCreateWorkspaceForDirectory(cwd);
return { workspace, projectsBefore, workspacesBefore };
});
if (!opened) {
this.sessionLogger.info(
{ requestedCwd, resolvedCwd: cwd, reason: "directory_not_found" },
"Open project rejected",
);
this.emit({
type: "open_project_response",
payload: {
requestId: request.requestId,
workspace: null,
error: `Directory not found: ${cwd}`,
errorCode: "directory_not_found",
},
});
return;
const projectsBefore = new Map<string, PersistedProjectRecord>();
for (const project of await this.projectRegistry.list()) {
projectsBefore.set(project.projectId, project);
}
const { workspace, projectsBefore, workspacesBefore } = opened;
const workspacesBefore = new Map<string, PersistedWorkspaceRecord>();
for (const workspaceRecord of await this.workspaceRegistry.listActive()) {
workspacesBefore.set(workspaceRecord.workspaceId, workspaceRecord);
}
const workspace = await this.workspaceProvisioning.findOrCreateWorkspaceForDirectory(cwd);
const project = await this.projectRegistry.get(workspace.projectId);
await this.syncWorkspaceGitObserverForWorkspace(workspace);
const descriptor = await this.describeWorkspaceRecord(workspace);
@@ -8240,8 +8130,6 @@ export class Session {
{
paseoHome: this.paseoHome,
paseoWorktreesBaseRoot: this.worktreesRoot,
worktreeManagers: this.pluginRuntime,
workspaceArchiveOperations: this.workspaceArchiveOperations,
github: this.github,
workspaceGitService: this.workspaceGitService,
agentManager: this.agentManager,
@@ -8258,8 +8146,6 @@ export class Session {
clearWorkspaceArchiving: (workspaceIds) => this.clearWorkspaceArchiving(workspaceIds),
assertWorkspaceAutomationAllowed: (workspaceId) =>
assertWorkspaceAutomationAllowedForWorkspace(this.workspaceRegistry, workspaceId),
isCheckoutUntrusted: (checkoutPath) =>
isCheckoutUntrusted(this.workspaceRegistry, checkoutPath),
killTerminalsForWorkspace: (workspaceId) =>
this.terminalController.killTerminalsForWorkspace(workspaceId),
stopWorkspaceSetup: (workspaceId) => this.workspaceSetupRuntime.stop(workspaceId),
@@ -8322,9 +8208,7 @@ export class Session {
): Promise<void> {
try {
await this.workspaceArchiveOperations.undo(request.workspaceId, (input) =>
this.withWorkspaceCheckout(request.workspaceId, () =>
this.restoreArchivedWorkspaceAndAgents(request.workspaceId, input),
),
this.restoreArchivedWorkspaceAndAgents(request.workspaceId, input),
);
this.emit({
type: "workspace.archive.undo.response",
@@ -9732,3 +9616,14 @@ function createHostSession(options: SessionOptions, session: Session): Connected
function hostSource(options: SessionOptions): string {
return options.sourceId ?? "owner";
}
function dedupeSlashCommands<T extends { name: string }>(commands: readonly T[]): T[] {
const seen = new Set<string>();
const unique: T[] = [];
for (const command of commands) {
if (seen.has(command.name)) continue;
seen.add(command.name);
unique.push(command);
}
return unique;
}
@@ -52,7 +52,6 @@ export interface CreateWorktreeWorkspaceInput {
worktreeRoot: string;
branch: string | null;
baseBranch: string | null;
worktreeManagerPluginId?: string | null;
title: string | null;
metadata?: Record<string, JsonValue>;
expectsInitialAgent?: boolean;
@@ -274,23 +273,14 @@ export function createWorkspaceProvisioningService(deps: {
checkout.isGit && checkout.isPaseoOwnedWorktree
? await readPaseoWorktreeMetadata(checkout.worktreeRoot ?? normalizedCwd)
: null;
const checkoutRoot = checkout.worktreeRoot ?? normalizedCwd;
const matchesCheckout = createRealpathAwarePathMatcher(checkoutRoot);
const inheritedUntrustedSource = (await workspaceRegistry.listAll()).find(
(candidate) =>
Boolean(candidate.untrustedSource) &&
matchesCheckout(candidate.worktreeRoot ?? candidate.cwd),
)?.untrustedSource;
const timestamp = new Date().toISOString();
const workspace = createPersistedWorkspaceRecord({
workspaceId: context?.workspaceId ?? generateWorkspaceId(),
projectId: project.projectId,
...initialWorkspacePlacement({ source: "checkout", cwd: normalizedCwd, checkout }),
baseBranch: baseMetadata?.baseRef ?? baseMetadata?.baseRefName ?? null,
worktreeManagerPluginId: baseMetadata?.worktreeManagerPluginId ?? null,
title: title?.trim() || null,
metadata: context?.metadata,
...(inheritedUntrustedSource ? { untrustedSource: inheritedUntrustedSource } : {}),
createdAt: timestamp,
updatedAt: timestamp,
...(await resolveCreationMetadata(context)),
@@ -330,7 +320,6 @@ export function createWorkspaceProvisioningService(deps: {
baseBranch: input.baseBranch,
mainRepoRoot: repoRoot,
}),
worktreeManagerPluginId: input.worktreeManagerPluginId ?? null,
title: input.title,
metadata: input.metadata,
createdAt: timestamp,
@@ -9,11 +9,8 @@ import {
isPaseoOwnedWorktreeCwd,
mapWorkspaceCwdToWorktree,
rollbackCreatedPaseoWorktree,
runPluginWorktreeManagerCheckout,
type WorktreeSource,
} from "../../../utils/worktree.js";
import type { PluginWorktreeManagerRuntime } from "../../plugins/runtime.js";
import type { PluginWorktreeRestoreTarget } from "@getpaseo/plugin/server";
import { WorktreeRequestError, toWorktreeRequestError } from "../../worktree-errors.js";
import {
resolveWorkspaceDisplayName,
@@ -67,20 +64,10 @@ type UnavailableRecoveryState = Extract<WorkspaceRecoveryState, { kind: "unavail
export function createWorkspaceRecoveryService(deps: {
paseoHome: string;
worktreesRoot?: string;
worktreeManagers?: Pick<
PluginWorktreeManagerRuntime,
"hasWorktreeManager" | "restoreWorktree" | "removeWorktree"
>;
getWorkspace: (workspaceId: string) => Promise<PersistedWorkspaceRecord | null>;
getProject: (projectId: string) => Promise<PersistedProjectRecord | null>;
isDirectory: (path: string) => Promise<boolean>;
unarchiveWorkspace: (workspace: PersistedWorkspaceRecord) => Promise<void>;
isCheckoutUntrusted?: (checkoutPath: string) => Promise<boolean>;
syncCheckoutWorktreeManager?: (input: {
worktreeRoot: string;
worktreeManagerPluginId: string | null;
excludeWorkspaceId: string;
}) => Promise<void>;
}): WorkspaceRecoveryService {
async function resolveRecovery(
workspaceId: string,
@@ -153,32 +140,17 @@ export function createWorkspaceRecoveryService(deps: {
throw new Error(resolved.message);
}
let workspaceToUnarchive = resolved.workspace;
let recreated: { worktreePath: string; pluginId: string | null } | null = null;
if (resolved.kind === "restore") {
recreated = await recreateArchivedWorktree(resolved.workspace, resolved.sourceRepoRoot);
if ((resolved.workspace.worktreeManagerPluginId ?? null) !== recreated.pluginId) {
const { worktreeManagerPluginId: _previous, ...withoutManager } = resolved.workspace;
workspaceToUnarchive = recreated.pluginId
? { ...withoutManager, worktreeManagerPluginId: recreated.pluginId }
: withoutManager;
}
}
await deps.unarchiveWorkspace(workspaceToUnarchive);
if (recreated) {
await deps.syncCheckoutWorktreeManager?.({
worktreeRoot: recreated.worktreePath,
worktreeManagerPluginId: recreated.pluginId,
excludeWorkspaceId: workspaceId,
});
await recreateArchivedWorktree(resolved.workspace, resolved.sourceRepoRoot);
}
await deps.unarchiveWorkspace(resolved.workspace);
return { workspaceId, action: resolved.kind };
}
async function recreateArchivedWorktree(
workspace: PersistedWorkspaceRecord,
sourceRepoRoot: string,
): Promise<{ worktreePath: string; pluginId: string | null }> {
): Promise<void> {
let source: WorktreeSource;
const checkout = parseWorkspaceHead(workspace);
if (checkout.kind === "branch") {
@@ -222,22 +194,18 @@ export function createWorkspaceRecoveryService(deps: {
hasRecordedWorktreePath = ownership.allowed;
}
const untrusted =
Boolean(workspace.untrustedSource) ||
Boolean(await deps.isCheckoutUntrusted?.(previousWorktreePath));
let recreatedWorktreePath: string;
let restoredByPluginId: string | null = null;
try {
const restored = await recreateWorktreeCheckout({
workspace,
sourceRepoRoot,
const result = await createWorktree({
cwd: sourceRepoRoot,
worktreeSlug: basename(previousWorktreePath),
source,
previousWorktreePath,
hasRecordedWorktreePath,
untrusted,
paseoHome: deps.paseoHome,
worktreesRoot: deps.worktreesRoot,
...(hasRecordedWorktreePath ? { worktreePath: previousWorktreePath } : {}),
});
recreatedWorktreePath = restored.worktreePath;
restoredByPluginId = restored.pluginId;
recreatedWorktreePath = result.worktreePath;
} catch (error) {
throw toWorktreeRequestError(error);
}
@@ -268,98 +236,15 @@ export function createWorkspaceRecoveryService(deps: {
teardownCwds: [],
paseoHome: deps.paseoHome,
worktreesBaseRoot: deps.worktreesRoot,
worktreeManagers: deps.worktreeManagers,
worktreeManagerPluginId: restoredByPluginId,
removeReason: "rollback",
untrusted,
},
error,
);
}
return { worktreePath: recreatedWorktreePath, pluginId: restoredByPluginId };
}
async function recreateWorktreeCheckout(options: {
workspace: PersistedWorkspaceRecord;
sourceRepoRoot: string;
source: Extract<WorktreeSource, { kind: "restore" | "restore-commit" | "restore-from-base" }>;
previousWorktreePath: string;
hasRecordedWorktreePath: boolean;
untrusted: boolean;
}): Promise<{ worktreePath: string; pluginId: string | null }> {
const {
workspace,
sourceRepoRoot,
source,
previousWorktreePath,
hasRecordedWorktreePath,
untrusted,
} = options;
const managerPluginId = workspace.worktreeManagerPluginId;
if (managerPluginId && hasRecordedWorktreePath && deps.worktreeManagers) {
const adopted = await runPluginWorktreeManagerCheckout({
cwd: sourceRepoRoot,
source,
operation: "restore",
preferredPluginId: managerPluginId,
untrusted,
paseoHome: deps.paseoHome,
worktreesBaseRoot: deps.worktreesRoot,
worktreeManagers: deps.worktreeManagers,
run: () =>
deps.worktreeManagers!.restoreWorktree(
{
repoRoot: sourceRepoRoot,
path: previousWorktreePath,
target: restoreTargetFromWorktreeSource(source),
baseRef: workspace.baseBranch,
untrusted,
},
{ preferredPluginId: managerPluginId },
),
verifyValidatedPath: (validatedPath, pluginId) => {
if (!createRealpathAwarePathMatcher(previousWorktreePath)(validatedPath)) {
throw new WorktreeRequestError({
code: "unknown",
message: `Plugin ${pluginId} restored worktree to ${validatedPath}, expected ${previousWorktreePath}`,
});
}
},
});
if (adopted) {
return {
worktreePath: adopted.worktreePath,
pluginId: adopted.worktreeManagerPluginId ?? managerPluginId,
};
}
}
const result = await createWorktree({
cwd: sourceRepoRoot,
worktreeSlug: basename(previousWorktreePath),
source,
paseoHome: deps.paseoHome,
worktreesRoot: deps.worktreesRoot,
...(hasRecordedWorktreePath ? { worktreePath: previousWorktreePath } : {}),
});
return { worktreePath: result.worktreePath, pluginId: null };
}
return { inspect, restore };
}
function restoreTargetFromWorktreeSource(
source: Extract<WorktreeSource, { kind: "restore" | "restore-commit" | "restore-from-base" }>,
): PluginWorktreeRestoreTarget {
if (source.kind === "restore") {
return { type: "branch", branch: source.branchName };
}
if (source.kind === "restore-commit") {
return { type: "commit", commit: source.commit };
}
return { type: "from-base", branch: source.branchName, baseRef: source.baseRef };
}
async function resolveRecoveryBase(repoRoot: string, recordedBase: string | null): Promise<string> {
if (recordedBase) {
try {
+3 -11
View File
@@ -70,12 +70,6 @@ import type { HubRelationshipManagement } from "./hub/relationship-controller.js
import { WorkspaceSetupObservation } from "./workspace-setup-observation.js";
import { WorkspaceSetupRuntime } from "./workspace-setup-runtime.js";
import { WorkspaceArchiveOperations } from "./workspace-archive-operations.js";
function resolveWorkspaceArchiveOperations(
operations: WorkspaceArchiveOperations | undefined,
): WorkspaceArchiveOperations {
return operations ?? new WorkspaceArchiveOperations();
}
import type { HubExecutionAgents } from "./hub/daemon-executions.js";
import type { AgentProvider } from "./agent/agent-sdk-types.js";
import { ProviderSnapshotManager } from "./agent/provider-snapshot-manager.js";
@@ -624,9 +618,9 @@ export class VoiceAssistantWebSocketServer {
private readonly voiceCallerContexts = new Map<string, VoiceCallerContext>();
private readonly workspaceSetupObservation = new WorkspaceSetupObservation();
private readonly workspaceSetupRuntime: WorkspaceSetupRuntime;
// One lane per workspace and per checkout across the daemon, so archive, undo, and restore
// from any client or background caller coordinate through one boundary.
private readonly workspaceArchiveOperations: WorkspaceArchiveOperations;
// One lane per workspace across every connection, so an undo from any client can cancel an
// archive another connection started.
private readonly workspaceArchiveOperations = new WorkspaceArchiveOperations();
private readonly providerSnapshotManager: ProviderSnapshotManager;
private onLifecycleIntent!: ((intent: SessionLifecycleIntent) => void) | null;
private onBranchChanged!:
@@ -717,11 +711,9 @@ export class VoiceAssistantWebSocketServer {
pluginRuntime?: SessionOptions["pluginRuntime"],
orchestrationSkills?: SessionOptions["orchestrationSkills"],
workspaceLabelService?: WorkspaceLabelService,
workspaceArchiveOperations?: WorkspaceArchiveOperations,
) {
this.logger = logger.child({ module: "websocket-server" });
this.workspaceSetupRuntime = workspaceSetupRuntime;
this.workspaceArchiveOperations = resolveWorkspaceArchiveOperations(workspaceArchiveOperations);
this.advertiseDaemonStatusRpc = wsConfig.daemonStatusRpc !== false;
this.advertiseRelayConfig = wsConfig.relayConfig !== false;
this.connectionLifecycle = wsConfig.startPaused === true ? "starting" : "accepting";
@@ -273,146 +273,4 @@ describe("WorkspaceArchiveOperations", () => {
kind: "archived",
});
});
test("concurrent restores join the in-flight restore and share its outcome", async () => {
const operations = new WorkspaceArchiveOperations();
let release!: () => void;
const gate = new Promise<void>((resolve) => {
release = resolve;
});
let calls = 0;
const first = operations.restore("ws", async () => {
calls += 1;
await gate;
throw new Error("restore setup failed");
});
const second = operations.restore("ws", async () => {
calls += 1;
});
release();
await expect(first).rejects.toThrow("restore setup failed");
await expect(second).rejects.toThrow("restore setup failed");
expect(calls).toBe(1);
await operations.restore("ws", async () => {
calls += 1;
});
expect(calls).toBe(2);
});
test("undo after a restore queued behind a running archive still aborts the archive and shares the undo outcome", async () => {
const operations = new WorkspaceArchiveOperations();
const archive = parkedArchive(["agent-a"]);
const order: string[] = [];
let restoreCalls = 0;
const archiveDone = operations.archive("ws", async (signal) => {
try {
return await archive.run(signal);
} finally {
order.push("archive stopped");
}
});
await archive.started;
const restoreDone = operations.restore("ws", async () => {
restoreCalls += 1;
order.push("restore");
});
expect(archive.aborted).toBe(false);
const undoDone = operations.undo("ws", async ({ archivedAt }) => {
order.push(`undo:${archivedAt}`);
});
expect(archive.aborted).toBe(true);
archive.release();
await expect(archiveDone).resolves.toEqual({ kind: "canceled", archivedAt: "stamp" });
await Promise.all([restoreDone, undoDone]);
expect(restoreCalls).toBe(0);
expect(order).toEqual(["archive stopped", "undo:stamp"]);
});
test("restore queued behind a running archive waits without aborting it when no undo arrives", async () => {
const operations = new WorkspaceArchiveOperations();
const archive = parkedArchive(["agent-a"]);
const order: string[] = [];
const archiveDone = operations.archive("ws", async (signal) => {
const result = await archive.run(signal);
order.push("archived");
return result;
});
await archive.started;
const restoreDone = operations.restore("ws", async () => {
order.push("restored");
});
expect(archive.aborted).toBe(false);
archive.release();
await expect(archiveDone).resolves.toMatchObject({ kind: "archived" });
await restoreDone;
expect(order).toEqual(["archived", "restored"]);
});
test("undo after restore has already started joins the running restore", async () => {
const operations = new WorkspaceArchiveOperations();
await operations.archive("ws", async () => archived(["agent-a"]));
const restoreGate = deferred();
let restoreCalls = 0;
let undoCalls = 0;
const restoreDone = operations.restore("ws", async () => {
restoreCalls += 1;
await restoreGate.promise;
});
// Flush microtask so restore has moved past any settled archive check.
await Promise.resolve();
const undoDone = operations.undo("ws", async () => {
undoCalls += 1;
});
restoreGate.resolve();
await Promise.all([restoreDone, undoDone]);
expect(restoreCalls).toBe(1);
expect(undoCalls).toBe(0);
});
test("withCheckout serializes operations on the same checkout path while allowing independent checkouts in parallel", async () => {
const operations = new WorkspaceArchiveOperations();
const firstGate = deferred();
const firstStarted = deferred();
const order: string[] = [];
const first = operations.withCheckout("/tmp/paseo-checkout-a", async () => {
order.push("a1-start");
firstStarted.resolve();
await firstGate.promise;
order.push("a1-end");
return "first";
});
await firstStarted.promise;
const second = operations.withCheckout("/tmp/paseo-checkout-a/", async () => {
order.push("a2");
return "second";
});
const other = operations.withCheckout("/tmp/paseo-checkout-b", async () => {
order.push("b");
return "other";
});
await expect(other).resolves.toBe("other");
expect(order).toEqual(["a1-start", "b"]);
firstGate.resolve();
await expect(first).resolves.toBe("first");
await expect(second).resolves.toBe("second");
expect(order).toEqual(["a1-start", "b", "a1-end", "a2"]);
});
});
@@ -1,6 +1,3 @@
import { resolve } from "node:path";
import { normalizePathForIdentity } from "../utils/path.js";
import { type ArchiveResult, WorkspaceArchiveCanceledError } from "./workspace-archive-service.js";
export type WorkspaceArchiveOutcome =
@@ -11,42 +8,23 @@ export interface WorkspaceArchiveUndoInput {
archivedAt?: string;
}
interface PendingArchive {
controller: AbortController;
done: Promise<WorkspaceArchiveOutcome>;
}
type LaneEntry =
| { kind: "archiving"; controller: AbortController; done: Promise<WorkspaceArchiveOutcome> }
| {
kind: "restoring";
pendingArchive: PendingArchive | null;
supersededBy: Promise<void> | null;
done: Promise<void>;
}
| { kind: "undoing"; done: Promise<void> };
/**
* Daemon-wide coordinator for workspace archive, undo, and restore operations.
* One lane per workspace for archive and its undo, shared by every session on the daemon.
*
* Per-workspace lanes:
* - An archive while one runs joins it.
* - An undo while an archive runs (including when a restore queued behind it) aborts the archive,
* waits for it to stop, then restores.
* - A restore while an archive runs waits for the archive without aborting it, then restores.
* - An archive while an undo or restore runs waits for it, then archives.
* - A duplicate undo or restore while recovery runs joins it.
* - An undo while an archive runs aborts it, waits for it to stop, then restores.
* - An archive while an undo runs waits for the undo, then archives.
* - An undo while an undo runs joins it.
*
* Per-checkout gates:
* - Any archive or recovery mutating the same backing checkout directory (including CLI worktree
* archives covering multiple workspace records, background auto-archives, and sibling workspaces
* sharing one checkout) serializes through `withCheckout` so a restore cannot inspect or unarchive
* a checkout while an archive is still deleting it.
* - Lock order is strictly workspace lane -> checkout gate, preventing deadlocks.
* Each call claims the lane synchronously, so whichever request arrives last decides the
* workspace's final state no matter how the earlier work interleaves.
*/
export class WorkspaceArchiveOperations {
private readonly lanes = new Map<string, LaneEntry>();
private readonly checkoutGates = new Map<string, Promise<void>>();
archive(
workspaceId: string,
@@ -79,92 +57,16 @@ export class WorkspaceArchiveOperations {
if (current?.kind === "undoing") {
return current.done;
}
if (current?.kind === "restoring" && current.pendingArchive === null) {
return current.done;
}
let pendingArchive: PendingArchive | null = null;
if (current?.kind === "archiving") {
pendingArchive = { controller: current.controller, done: current.done };
} else if (current?.kind === "restoring") {
pendingArchive = current.pendingArchive;
}
pendingArchive?.controller.abort();
current?.controller.abort();
const done = (async () => {
const outcome = pendingArchive ? await pendingArchive.done.catch(() => undefined) : undefined;
const outcome =
current?.kind === "archiving" ? await current.done.catch(() => undefined) : undefined;
await restore({ archivedAt: outcome?.kind === "canceled" ? outcome.archivedAt : undefined });
})();
if (current?.kind === "restoring") {
current.supersededBy = done;
}
this.claim(workspaceId, { kind: "undoing", done });
return done;
}
/**
* Run a workspace recovery restore on the per-workspace lane so concurrent restores
* across daemon sessions share one outcome and wait for checkout + validation to settle.
* When queued behind an in-flight archive, the archive stays cancelable by a subsequent undo.
*/
restore(workspaceId: string, run: () => Promise<void>): Promise<void> {
const current = this.lanes.get(workspaceId);
if (current?.kind === "undoing" || current?.kind === "restoring") {
return current.done;
}
const pendingArchive: PendingArchive | null =
current?.kind === "archiving" ? { controller: current.controller, done: current.done } : null;
const entry: Extract<LaneEntry, { kind: "restoring" }> = {
kind: "restoring",
pendingArchive,
supersededBy: null,
done: Promise.resolve(),
};
entry.done = (async () => {
if (pendingArchive) {
await settled(pendingArchive.done);
entry.pendingArchive = null;
if (entry.supersededBy) {
await entry.supersededBy;
return;
}
} else {
await settled(current?.done);
}
await run();
})();
this.claim(workspaceId, entry);
return entry.done;
}
/**
* Serialize mutations touching the same backing checkout directory across all daemon callers
* (UI archive, CLI worktree archive, background auto-archive, undo, and recovery restore).
*/
withCheckout<T>(checkoutPath: string, run: () => Promise<T>): Promise<T> {
const key = normalizePathForIdentity(resolve(checkoutPath));
const previous = this.checkoutGates.get(key);
let release!: () => void;
const current = new Promise<void>((resolveGate) => {
release = resolveGate;
});
const gate = previous ? previous.then(() => current) : current;
this.checkoutGates.set(key, gate);
const cleanup = () => {
if (this.checkoutGates.get(key) === gate) {
this.checkoutGates.delete(key);
}
};
void gate.then(cleanup, cleanup);
return (async () => {
await settled(previous);
try {
return await run();
} finally {
release();
}
})();
}
private claim(workspaceId: string, entry: LaneEntry): void {
this.lanes.set(workspaceId, entry);
const release = () => {
@@ -1290,54 +1290,3 @@ test("a canceled archive with no matching agents leaves earlier closed agents ar
});
expect(restored).toEqual([]);
});
test("archiving an outer worktree preserves an active nested checkout and its uncommitted files", async () => {
const { repoDir } = createGitRepo();
const rootDir = path.dirname(repoDir);
const outerPath = path.join(rootDir, "worktrees", "team");
const innerPath = path.join(outerPath, "topic");
mkdirSync(path.dirname(outerPath), { recursive: true });
execFileSync("git", ["worktree", "add", "-b", "team", outerPath], {
cwd: repoDir,
stdio: "pipe",
});
execFileSync("git", ["worktree", "add", "-b", "topic", innerPath], {
cwd: repoDir,
stdio: "pipe",
});
const dirtyFile = path.join(innerPath, "uncommitted.txt");
writeFileSync(dirtyFile, "keep-inner");
const activeWorkspaces: ActiveWorkspaceRef[] = [
{
workspaceId: "ws-team",
cwd: outerPath,
kind: "worktree",
worktreeRoot: outerPath,
isPaseoOwnedWorktree: true,
mainRepoRoot: repoDir,
},
{
workspaceId: "ws-topic",
cwd: innerPath,
kind: "worktree",
worktreeRoot: innerPath,
isPaseoOwnedWorktree: true,
mainRepoRoot: repoDir,
},
];
const deps = createArchiveDeps({
paseoHome: rootDir,
activeWorkspaces,
});
const result = await archiveByScope(deps, {
scope: { kind: "workspace", workspaceId: "ws-team" },
requestId: "archive-outer",
});
expect(result.archivedWorkspaceIds).toEqual(["ws-team"]);
expect(result.removedDirectory).toBe(false);
expect(existsSync(outerPath)).toBe(true);
expect(readFileSync(dirtyFile, "utf8")).toBe("keep-inner");
});
@@ -19,26 +19,19 @@ import type {
WorkspaceArchiveContext,
WorkspaceRegistry,
} from "./workspace-registry.js";
import { createRealpathAwarePathMatcher, isRealpathInsideRoot } from "../utils/path.js";
import { createRealpathAwarePathMatcher } from "../utils/path.js";
import { runWithGitCommandPriority } from "../utils/run-git-command.js";
import { WorkspaceAutomationBlockedError } from "./workspace-automation-gate.js";
import type { PluginWorktreeManagerRuntime } from "./plugins/runtime.js";
import type { WorkspaceArchiveOperations } from "./workspace-archive-operations.js";
export type ActiveWorkspaceRef = Pick<
PersistedWorkspaceRecord,
"workspaceId" | "cwd" | "kind" | "worktreeRoot" | "isPaseoOwnedWorktree" | "mainRepoRoot"
> & {
worktreeManagerPluginId?: string | null;
untrustedSource?: PersistedWorkspaceRecord["untrustedSource"];
};
>;
export interface ArchiveDependencies {
paseoHome?: string;
// Base directory that may hold worktrees across repositories.
paseoWorktreesBaseRoot?: string;
worktreeManagers?: Pick<PluginWorktreeManagerRuntime, "removeWorktree">;
workspaceArchiveOperations?: Pick<WorkspaceArchiveOperations, "withCheckout">;
github: ForgeService;
workspaceGitService: Pick<WorkspaceGitService, "getSnapshot" | "invalidateWorktrees">;
agentManager: Pick<AgentManager, "listAgents" | "getAgent" | "archiveAgent" | "archiveSnapshot">;
@@ -60,7 +53,6 @@ export interface ArchiveDependencies {
killTerminalsForWorkspace: (workspaceId: string) => Promise<void>;
stopWorkspaceSetup?: (workspaceId: string) => Promise<void>;
assertWorkspaceAutomationAllowed?: (workspaceId: string) => Promise<void>;
isCheckoutUntrusted?: (checkoutPath: string) => Promise<boolean>;
sessionLogger?: Logger;
}
@@ -127,8 +119,6 @@ interface BackingDirectory {
registryProven: boolean;
mainRepoRoot: string | null;
paseoWorktreesRoot: string | null;
worktreeManagerPluginId: string | null;
untrusted: boolean;
}
interface ArchiveTarget {
@@ -152,13 +142,6 @@ export async function resolveWorkspaceIdAtPath(
return dependencies.findWorkspaceIdForCwd(targetPath);
}
export async function resolveWorkspaceBackingPath(
workspace: ActiveWorkspaceRef,
dependencies: Pick<ArchiveDependencies, "paseoHome" | "paseoWorktreesBaseRoot">,
): Promise<string> {
return (await resolveWorkspaceBackingDirectory(workspace, dependencies)).path;
}
// Resolves the in-scope record set, tears each down
// (agents + terminals + record), then removes the backing directory iff it is
// Paseo-owned AND no active workspace still references it.
@@ -181,98 +164,69 @@ async function archiveByScopeWithPriority(
};
checkpoint();
const runArchive = async (): Promise<ArchiveResult> => {
checkpoint();
const target = await resolveArchiveTarget(dependencies, request.scope);
const targetWorkspaceIds = target.workspaceIds;
const target = await resolveArchiveTarget(dependencies, request.scope);
const targetWorkspaceIds = target.workspaceIds;
await stopWorkspaceSetups(dependencies, target.setupWorkspaceIds, request.requestId);
checkpoint();
await stopWorkspaceSetups(dependencies, target.setupWorkspaceIds, request.requestId);
checkpoint();
if (targetWorkspaceIds.length > 0) {
dependencies.markWorkspaceArchiving(targetWorkspaceIds, new Date().toISOString());
}
let removedDirectory = false;
let directoryLeftBehind: ArchiveResult["directoryLeftBehind"];
try {
if (targetWorkspaceIds.length > 0) {
dependencies.markWorkspaceArchiving(targetWorkspaceIds, new Date().toISOString());
await dependencies.emitWorkspaceUpdatesForWorkspaceIds(targetWorkspaceIds);
}
checkpoint();
let removedDirectory = false;
let directoryLeftBehind: ArchiveResult["directoryLeftBehind"];
const { archivedAgents, archivedWorkspaceIds } = await archiveTargetRecords(
dependencies,
targetWorkspaceIds,
{ requestId: request.requestId, checkpoint, archivedAt },
);
checkpoint();
try {
if (targetWorkspaceIds.length > 0) {
await dependencies.emitWorkspaceUpdatesForWorkspaceIds(targetWorkspaceIds);
}
checkpoint();
const { archivedAgents, archivedWorkspaceIds } = await archiveTargetRecords(
dependencies,
targetWorkspaceIds,
{ requestId: request.requestId, checkpoint, archivedAt },
);
checkpoint();
if (target.backing?.mainRepoRoot) {
try {
await dependencies.workspaceGitService.getSnapshot(target.backing.mainRepoRoot, {
force: true,
reason: "archive-worktree",
});
} catch (error) {
dependencies.sessionLogger?.warn(
{ err: error, cwd: target.backing.mainRepoRoot, requestId: request.requestId },
"Failed to force-refresh workspace git snapshot after archiving",
);
}
}
if (target.backing !== null) {
const removal = await maybeRemoveDirectory(
dependencies,
{ requestId: request.requestId, checkpoint },
target,
archivedWorkspaceIds,
if (target.backing?.mainRepoRoot) {
try {
await dependencies.workspaceGitService.getSnapshot(target.backing.mainRepoRoot, {
force: true,
reason: "archive-worktree",
});
} catch (error) {
dependencies.sessionLogger?.warn(
{ err: error, cwd: target.backing.mainRepoRoot, requestId: request.requestId },
"Failed to force-refresh workspace git snapshot after archiving",
);
removedDirectory = removal.removedDirectory;
directoryLeftBehind = removal.directoryLeftBehind;
}
}
return {
archivedAgentIds: Array.from(archivedAgents),
if (target.backing !== null) {
const removal = await maybeRemoveDirectory(
dependencies,
{ requestId: request.requestId, checkpoint },
target,
archivedWorkspaceIds,
removedDirectory,
...(directoryLeftBehind ? { directoryLeftBehind } : {}),
};
} finally {
if (targetWorkspaceIds.length > 0) {
dependencies.clearWorkspaceArchiving(targetWorkspaceIds);
await dependencies.emitWorkspaceUpdatesForWorkspaceIds(targetWorkspaceIds);
}
}
};
const checkoutPath = dependencies.workspaceArchiveOperations
? await resolveArchiveCheckoutPath(dependencies, request.scope)
: null;
if (dependencies.workspaceArchiveOperations && checkoutPath) {
return dependencies.workspaceArchiveOperations.withCheckout(checkoutPath, runArchive);
}
return runArchive();
}
async function resolveArchiveCheckoutPath(
dependencies: ArchiveDependencies,
scope: ArchiveScope,
): Promise<string | null> {
if (scope.kind === "workspace") {
const record =
(await dependencies.getWorkspace?.(scope.workspaceId)) ??
(await dependencies.listActiveWorkspaces()).find(
(workspace) => workspace.workspaceId === scope.workspaceId,
);
if (!record) {
return null;
removedDirectory = removal.removedDirectory;
directoryLeftBehind = removal.directoryLeftBehind;
}
return {
archivedAgentIds: Array.from(archivedAgents),
archivedWorkspaceIds,
removedDirectory,
...(directoryLeftBehind ? { directoryLeftBehind } : {}),
};
} finally {
if (targetWorkspaceIds.length > 0) {
dependencies.clearWorkspaceArchiving(targetWorkspaceIds);
await dependencies.emitWorkspaceUpdatesForWorkspaceIds(targetWorkspaceIds);
}
return resolveWorkspaceBackingPath(record, dependencies);
}
return (await resolveBackingDirectory(scope.targetPath, dependencies)).path;
}
async function resolveArchiveTarget(
@@ -359,8 +313,6 @@ async function resolveWorkspaceBackingDirectory(
workspace: ActiveWorkspaceRef,
dependencies: Pick<ArchiveDependencies, "paseoHome" | "paseoWorktreesBaseRoot">,
): Promise<BackingDirectory> {
const worktreeManagerPluginId = workspace.worktreeManagerPluginId ?? null;
const untrusted = Boolean(workspace.untrustedSource);
if (workspace.isPaseoOwnedWorktree === false) {
return {
path: resolve(workspace.worktreeRoot ?? workspace.cwd),
@@ -369,8 +321,6 @@ async function resolveWorkspaceBackingDirectory(
registryProven: false,
mainRepoRoot: workspace.mainRepoRoot ?? null,
paseoWorktreesRoot: null,
worktreeManagerPluginId,
untrusted,
};
}
if (workspace.isPaseoOwnedWorktree && workspace.worktreeRoot && workspace.mainRepoRoot) {
@@ -381,8 +331,6 @@ async function resolveWorkspaceBackingDirectory(
registryProven: true,
mainRepoRoot: workspace.mainRepoRoot,
paseoWorktreesRoot: null,
worktreeManagerPluginId,
untrusted,
};
}
if (workspace.kind !== "worktree") {
@@ -393,8 +341,6 @@ async function resolveWorkspaceBackingDirectory(
registryProven: false,
mainRepoRoot: workspace.mainRepoRoot ?? null,
paseoWorktreesRoot: null,
worktreeManagerPluginId,
untrusted,
};
}
@@ -404,12 +350,7 @@ async function resolveWorkspaceBackingDirectory(
workspace.worktreeRoot ?? workspace.cwd,
dependencies,
);
return {
...backing,
mainRepoRoot: workspace.mainRepoRoot ?? backing.mainRepoRoot,
worktreeManagerPluginId: worktreeManagerPluginId ?? backing.worktreeManagerPluginId,
untrusted: untrusted || backing.untrusted,
};
return { ...backing, mainRepoRoot: workspace.mainRepoRoot ?? backing.mainRepoRoot };
}
async function resolveBackingDirectory(
@@ -428,8 +369,6 @@ async function resolveBackingDirectory(
registryProven: false,
mainRepoRoot: ownership.repoRoot ?? null,
paseoWorktreesRoot: ownership.worktreeRoot ?? null,
worktreeManagerPluginId: null,
untrusted: false,
};
}
@@ -514,16 +453,11 @@ async function maybeRemoveDirectory(
teardownTarget.workspaceId === null || archivedWorkspaceIdSet.has(teardownTarget.workspaceId),
);
let untrustedBacking =
backing.untrusted || Boolean(await dependencies.isCheckoutUntrusted?.(backing.path));
try {
const allowedTeardownTargets = await filterAllowedTeardownTargets(
dependencies,
teardownTargets,
);
if (allowedTeardownTargets.length < teardownTargets.length) {
untrustedBacking = true;
}
for (const teardownTarget of uniqueTeardownTargets(allowedTeardownTargets)) {
request.checkpoint();
await runWorktreeTeardownCommands({
@@ -567,10 +501,6 @@ async function maybeRemoveDirectory(
paseoHome: dependencies.paseoHome,
worktreesBaseRoot: dependencies.paseoWorktreesBaseRoot,
registryProven: backing.registryProven,
worktreeManagers: dependencies.worktreeManagers,
worktreeManagerPluginId: backing.worktreeManagerPluginId,
removeReason: "archive",
untrusted: untrustedBacking,
});
dependencies.workspaceGitService.invalidateWorktrees();
dependencies.github.invalidate({ cwd: backing.path });
@@ -689,7 +619,7 @@ export async function archiveWorkspaceContents(
}
// True when, after archiving
// the in-scope records, no active workspace still points at or inside targetDir. Derived
// the in-scope records, no active workspace still points at targetDir. Derived
// from records each call — no stored counter.
async function isDirectoryUnreferenced(
activeWorkspaces: ActiveWorkspaceRef[],
@@ -702,13 +632,7 @@ async function isDirectoryUnreferenced(
for (const workspace of activeWorkspaces) {
if (archivedWorkspaceIds.has(workspace.workspaceId)) continue;
const backingDirectory = await resolveWorkspaceBackingDirectory(workspace, dependencies);
if (
matchesTarget(backingDirectory.path) ||
isRealpathInsideRoot(target, backingDirectory.path) ||
isRealpathInsideRoot(target, workspace.cwd)
) {
return false;
}
if (matchesTarget(backingDirectory.path)) return false;
}
return true;
}
@@ -1,4 +1,3 @@
import { createRealpathAwarePathMatcher } from "../utils/path.js";
import type { WorkspaceRegistry } from "./workspace-registry.js";
export interface UntrustedWorkspaceSource {
@@ -35,44 +34,17 @@ export async function assertWorkspaceAutomationAllowedForWorkspace(
assertWorkspaceAutomationAllowed(workspace.untrustedSource);
}
export async function isCheckoutUntrusted(
registry: Pick<WorkspaceRegistry, "listAll">,
checkoutPath: string,
): Promise<boolean> {
const matchesCheckout = createRealpathAwarePathMatcher(checkoutPath);
const workspaces = await registry.listAll();
return workspaces.some(
(workspace) =>
Boolean(workspace.untrustedSource) &&
matchesCheckout(workspace.worktreeRoot ?? workspace.cwd),
);
}
export async function clearWorkspaceAutomationBlock(
registry: Pick<WorkspaceRegistry, "update" | "listAll">,
registry: Pick<WorkspaceRegistry, "update">,
workspaceId: string,
): Promise<boolean> {
let cleared = false;
const timestamp = new Date().toISOString();
const workspace = await registry.update(workspaceId, (record) => {
if (!record.untrustedSource) return record;
cleared = true;
const { untrustedSource: _removed, ...trusted } = record;
return { ...trusted, updatedAt: timestamp };
return { ...trusted, updatedAt: new Date().toISOString() };
});
if (!workspace) throw new Error(`Workspace not found: ${workspaceId}`);
const checkoutPath = workspace.worktreeRoot ?? workspace.cwd;
const matchesCheckout = createRealpathAwarePathMatcher(checkoutPath);
const siblings = await registry.listAll();
for (const sibling of siblings) {
if (sibling.workspaceId === workspaceId || !sibling.untrustedSource) continue;
if (!matchesCheckout(sibling.worktreeRoot ?? sibling.cwd)) continue;
await registry.update(sibling.workspaceId, (record) => {
if (!record.untrustedSource) return record;
cleared = true;
const { untrustedSource: _removed, ...trusted } = record;
return { ...trusted, updatedAt: timestamp };
});
}
return cleared;
}
@@ -88,7 +88,6 @@ const PersistedWorkspaceRecordSchema = z.object({
.transform((value) => value ?? null),
isPaseoOwnedWorktree: z.boolean().default(false),
mainRepoRoot: z.string().nullable().default(null),
worktreeManagerPluginId: z.string().min(1).optional(),
createdAt: z.string(),
updatedAt: z.string(),
archivedAt: z.string().nullable(),
@@ -699,7 +698,6 @@ export function createPersistedWorkspaceRecord(input: {
baseBranch?: string | null;
isPaseoOwnedWorktree?: boolean;
mainRepoRoot?: string | null;
worktreeManagerPluginId?: string | null;
createdAt: string;
updatedAt: string;
archivedAt?: string | null;
@@ -710,7 +708,7 @@ export function createPersistedWorkspaceRecord(input: {
untrustedSource?: UntrustedWorkspaceSource;
background?: boolean;
}): PersistedWorkspaceRecord {
const { background, worktreeManagerPluginId, ...rest } = input;
const { background, ...rest } = input;
return PersistedWorkspaceRecordSchema.parse({
...rest,
background: background ?? false,
@@ -720,7 +718,6 @@ export function createPersistedWorkspaceRecord(input: {
baseBranch: input.baseBranch ?? null,
isPaseoOwnedWorktree: input.isPaseoOwnedWorktree ?? false,
mainRepoRoot: input.mainRepoRoot ?? null,
...(worktreeManagerPluginId ? { worktreeManagerPluginId } : {}),
archivedAt: input.archivedAt ?? null,
autoArchivedChangeRequestUrl: input.autoArchivedChangeRequestUrl ?? null,
pinnedAt: input.pinnedAt ?? null,
@@ -25,15 +25,9 @@ import {
readPaseoWorktreeMetadata,
} from "../utils/worktree-metadata.js";
import { validateBeforeRequest, validateBeforeResult } from "./plugins/lifecycle/index.js";
import {
isPaseoOwnedWorktreeCwd,
listGitWorktrees,
listPaseoWorktrees,
UnknownBranchError,
} from "../utils/worktree.js";
import { UnknownBranchError } from "../utils/worktree.js";
import { createWorktreeCore as createCoreWorktree } from "./worktree-core.js";
import { isPlatform } from "../test-utils/platform.js";
import { createWithWorktrunk } from "../../../../plugin-examples/worktrunk/server/wt.js";
function createGitHubServiceStub(): ForgeService {
return {
@@ -1041,87 +1035,6 @@ describe.skipIf(isPlatform("win32"))("worktree-core POSIX-only", () => {
expect(getBranchUpstream(result.worktree.worktreePath)).toBeNull();
});
test.each([true, false])(
"checks out the fetched PR head with local branch collision=%s",
async (collision) => {
const { tempDir, repoDir, remoteDir, paseoHome } = createSameRepoGitHubPrRemoteRepo();
cleanupPaths.push(tempDir);
const branch = "daemon-shutdown-diagnostics";
const cached = execFileSync("git", ["rev-parse", "main"], {
cwd: repoDir,
encoding: "utf8",
}).trim();
if (collision) execFileSync("git", ["branch", "-f", branch, cached], { cwd: repoDir });
const expected = execFileSync(
"git",
["--git-dir", remoteDir, "rev-parse", "refs/pull/1790/head"],
{ encoding: "utf8" },
).trim();
expect(cached).not.toBe(expected);
const wt = path.join(tempDir, "wt");
writeFileSync(
wt,
`#!/bin/sh
if [ "$3" = remove ]; then
exec git -C "$2" worktree remove --force "$2-pr-checkout"
fi
repo="$2"
shift 2
branch=""
base=""
while [ "$#" -gt 0 ]; do
case "$1" in
--create) branch="$2"; shift 2 ;;
--base) base="$2"; shift 2 ;;
*) shift ;;
esac
done
git -C "$repo" worktree add --quiet -b "$branch" "$repo-pr-checkout" "$base" || exit $?
printf '{"action":"created","path":"%s","branch":"%s","created_branch":true}\\n' "$repo-pr-checkout" "$branch"
printf 'setup' > "$repo-pr-checkout/.worktrunk-setup"
`,
{ mode: 0o755 },
);
const previous = process.env.WORKTRUNK_BIN;
process.env.WORKTRUNK_BIN = wt;
try {
const result = await createCoreWorktree(
{ cwd: repoDir, action: "checkout", refName: branch, githubPrNumber: 1790, paseoHome },
{
...createCoreDeps(),
worktreeManagers: {
hasWorktreeManager: () => true,
createWorktree: async (request) => {
const managed = await createWithWorktrunk(request, new AbortController().signal);
return managed ? { pluginId: "worktrunk", path: managed.path } : null;
},
removeWorktree: async () => null,
},
},
);
expect(
execFileSync("git", ["rev-parse", "HEAD"], {
cwd: result.worktree.worktreePath,
encoding: "utf8",
}).trim(),
).toBe(expected);
expect(
execFileSync("git", ["rev-parse", `refs/heads/${branch}`], {
cwd: repoDir,
encoding: "utf8",
}).trim(),
).toBe(collision ? cached : expected);
expect(existsSync(path.join(result.worktree.worktreePath, ".worktrunk-setup"))).toBe(
!collision,
);
} finally {
if (previous === undefined) delete process.env.WORKTRUNK_BIN;
else process.env.WORKTRUNK_BIN = previous;
}
},
);
test("pushes a deduplicated same-repo GitHub PR branch to the PR head", async () => {
const { tempDir, repoDir, remoteDir, paseoHome } = createSameRepoGitHubPrRemoteRepo();
cleanupPaths.push(tempDir);
@@ -1554,454 +1467,6 @@ printf 'setup' > "$repo-pr-checkout/.worktrunk-setup"
expect(getBranchUpstream(second.worktree.worktreePath)).toBe("paseo-pr-526/main");
});
test("rejects and rolls back a managed fork PR checkout whose HEAD is behind the current PR head", async () => {
const { tempDir, repoDir, headRemoteDir, paseoHome } = createForkGitHubPrRemoteRepo();
cleanupPaths.push(tempDir);
const staleBranch = "archived-fork-pr-526";
const staleWorktreePath = path.join(tempDir, "stale-fork-pr");
git(repoDir, "branch", staleBranch, "main");
const github = {
...createGitHubServiceStub(),
getPullRequestCheckoutTarget: async () => ({
number: 526,
baseRefName: "main",
headRefName: "main",
headOwnerLogin: "therainisme",
headRepositorySshUrl: headRemoteDir,
headRepositoryUrl: headRemoteDir,
isCrossRepository: true,
}),
};
await expect(
createCoreWorktree(
{
cwd: repoDir,
worktreeSlug: "fork-pr-stale",
action: "checkout",
githubPrNumber: 526,
refName: "main",
paseoHome,
},
{
...createCoreDeps({ github }),
worktreeManagers: {
hasWorktreeManager: () => true,
createWorktree: async () => {
git(repoDir, "worktree", "add", staleWorktreePath, staleBranch);
return { pluginId: "stale-manager", path: staleWorktreePath };
},
removeWorktree: async () => null,
},
},
),
).rejects.toThrow("expected change request head");
expect(existsSync(staleWorktreePath)).toBe(false);
});
test("fails before calling the manager when the remote PR ref cannot be fetched", async () => {
const { tempDir, repoDir, headRemoteDir, paseoHome } = createForkGitHubPrRemoteRepo();
cleanupPaths.push(tempDir);
let managerCalled = false;
git(repoDir, "remote", "set-url", "origin", path.join(tempDir, "missing-remote.git"));
const github = {
...createGitHubServiceStub(),
getPullRequestCheckoutTarget: async () => ({
number: 526,
baseRefName: "main",
headRefName: "main",
headOwnerLogin: "therainisme",
headRepositorySshUrl: headRemoteDir,
headRepositoryUrl: headRemoteDir,
isCrossRepository: true,
}),
};
await expect(
createCoreWorktree(
{
cwd: repoDir,
worktreeSlug: "fork-pr-offline",
action: "checkout",
githubPrNumber: 526,
refName: "main",
paseoHome,
},
{
...createCoreDeps({ github }),
worktreeManagers: {
hasWorktreeManager: () => true,
createWorktree: async () => {
managerCalled = true;
return null;
},
removeWorktree: async () => null,
},
},
),
).rejects.toThrow("Unable to fetch change request refs");
expect(managerCalled).toBe(false);
});
test("accepts a managed fork PR checkout matching the pre-fetched headSha even after multiple mid-setup pushes", async () => {
const { tempDir, repoDir, headRemoteDir, paseoHome } = createForkGitHubPrRemoteRepo();
cleanupPaths.push(tempDir);
const baseRemoteDir = path.join(tempDir, "base.git");
const initialPrHead = git(repoDir, "ls-remote", "origin", "refs/pull/526/head").split(
/\s+/,
)[0];
const managedPath = path.join(tempDir, "mid-push-fork-pr");
const github = {
...createGitHubServiceStub(),
getPullRequestCheckoutTarget: async () => ({
number: 526,
baseRefName: "main",
headRefName: "main",
headOwnerLogin: "therainisme",
headRepositorySshUrl: headRemoteDir,
headRepositoryUrl: headRemoteDir,
isCrossRepository: true,
}),
};
const pushCommit = (message: string) => {
const headCloneDir = path.join(tempDir, "therainisme-clone");
writeFileSync(path.join(headCloneDir, "README.md"), `${message}\n`);
git(headCloneDir, "add", "README.md");
git(headCloneDir, "-c", "commit.gpgsign=false", "commit", "-m", message);
const head = git(headCloneDir, "rev-parse", "HEAD");
git(headCloneDir, "push", "origin", "main");
execFileSync("git", [`--git-dir=${baseRemoteDir}`, "fetch", headRemoteDir, "main"], {
stdio: "pipe",
});
execFileSync(
"git",
[`--git-dir=${baseRemoteDir}`, "update-ref", "refs/pull/526/head", head],
{ stdio: "pipe" },
);
};
const result = await createCoreWorktree(
{
cwd: repoDir,
worktreeSlug: "fork-pr-mid-push",
action: "checkout",
githubPrNumber: 526,
refName: "main",
paseoHome,
},
{
...createCoreDeps({ github }),
worktreeManagers: {
hasWorktreeManager: () => true,
createWorktree: async (request) => {
expect(request.headSha).toBe(initialPrHead);
// Two pushes happen while the manager creates the worktree from request.headSha.
pushCommit("mid-setup push B");
git(repoDir, "worktree", "add", "-b", "pr-526-snap", managedPath, request.headSha!);
pushCommit("mid-setup push C");
return { pluginId: "mid-push-manager", path: managedPath };
},
removeWorktree: async () => null,
},
},
);
expect(git(result.worktree.worktreePath, "rev-parse", "HEAD")).toBe(initialPrHead);
});
test("configures fork push remote on a managed Worktrunk PR checkout so Push updates the fork branch", async () => {
const { tempDir, repoDir, headRemoteDir, paseoHome } = createForkGitHubPrRemoteRepo();
cleanupPaths.push(tempDir);
const baseRemoteDir = path.join(tempDir, "base.git");
const wt = path.join(tempDir, "fake-wt-fork-push");
writeFileSync(
wt,
`#!/bin/sh
repo="$2"
shift 2
branch=""
base=""
while [ "$#" -gt 0 ]; do
case "$1" in
--create) branch="$2"; shift 2 ;;
--base) base="$2"; shift 2 ;;
*) shift ;;
esac
done
git -C "$repo" worktree add --quiet -b "$branch" "$repo-fork-managed" "$base" || exit $?
printf '{"action":"created","path":"%s","branch":"%s","created_branch":true}\\n' "$repo-fork-managed" "$branch"
`,
{ mode: 0o755 },
);
const github = {
...createGitHubServiceStub(),
getPullRequestCheckoutTarget: async () => ({
number: 526,
baseRefName: "main",
headRefName: "main",
headOwnerLogin: "therainisme",
headRepositorySshUrl: headRemoteDir,
headRepositoryUrl: headRemoteDir,
isCrossRepository: true,
}),
};
const previous = process.env.WORKTRUNK_BIN;
process.env.WORKTRUNK_BIN = wt;
try {
const result = await createCoreWorktree(
{
cwd: repoDir,
worktreeSlug: "fork-pr-managed-push",
action: "checkout",
githubPrNumber: 526,
refName: "main",
paseoHome,
},
{
...createCoreDeps({ github }),
worktreeManagers: {
hasWorktreeManager: () => true,
createWorktree: async (request) => {
const managed = await createWithWorktrunk(request, new AbortController().signal);
return managed ? { pluginId: "worktrunk", path: managed.path } : null;
},
removeWorktree: async () => null,
},
},
);
expect(result.worktree.worktreeManagerPluginId).toBe("worktrunk");
expect(result.worktree.branchName).toBe("therainisme/main");
writeFileSync(path.join(result.worktree.worktreePath, "README.md"), "pushed from wt\n");
git(result.worktree.worktreePath, "add", "README.md");
git(
result.worktree.worktreePath,
"-c",
"commit.gpgsign=false",
"commit",
"-m",
"managed fork commit",
);
const pushedSha = git(result.worktree.worktreePath, "rev-parse", "HEAD");
await pushCurrentBranch(result.worktree.worktreePath);
expect(
execFileSync("git", [`--git-dir=${headRemoteDir}`, "rev-parse", "refs/heads/main"], {
encoding: "utf8",
}).trim(),
).toBe(pushedSha);
expect(
execFileSync(
"git",
[`--git-dir=${baseRemoteDir}`, "for-each-ref", "refs/heads/therainisme/main"],
{ encoding: "utf8" },
).trim(),
).toBe("");
} finally {
if (previous === undefined) delete process.env.WORKTRUNK_BIN;
else process.env.WORKTRUNK_BIN = previous;
}
});
test("falls back to built-in Git without calling managers when Git rejects worktree list -z", async () => {
const { tempDir, repoDir, paseoHome } = createGitRepo();
cleanupPaths.push(tempDir);
const trailingSpaceWorktree = path.join(tempDir, "detached space ");
git(repoDir, "worktree", "add", "--detach", trailingSpaceWorktree, "main");
writeFileSync(path.join(trailingSpaceWorktree, "keep.txt"), "do not delete\n");
const realGit = execFileSync("which", ["git"], { encoding: "utf8" }).trim();
const shimDir = path.join(tempDir, "legacy-git-bin");
mkdirSync(shimDir, { recursive: true });
writeFileSync(
path.join(shimDir, "git"),
`#!/bin/sh
for arg in "$@"; do
if [ "$arg" = "-z" ]; then
echo 'error: unknown switch -z' >&2
exit 129
fi
done
exec "${realGit}" "$@"
`,
{ mode: 0o755 },
);
let managerCalled = false;
const previousPath = process.env.PATH;
process.env.PATH = `${shimDir}:${previousPath ?? ""}`;
try {
const result = await createCoreWorktree(
{
cwd: repoDir,
worktreeSlug: "legacy-git-fallback",
action: "branch-off",
branchName: "legacy-git-fallback",
paseoHome,
},
{
...createCoreDeps(),
worktreeManagers: {
hasWorktreeManager: () => true,
createWorktree: async () => {
managerCalled = true;
return { pluginId: "bad-manager", path: trailingSpaceWorktree };
},
removeWorktree: async () => null,
},
},
);
expect(managerCalled).toBe(false);
expect(result.worktree.branchName).toBe("legacy-git-fallback");
expect(result.worktree.worktreeManagerPluginId).toBeUndefined();
expect(readFileSync(path.join(trailingSpaceWorktree, "keep.txt"), "utf8")).toBe(
"do not delete\n",
);
} finally {
if (previousPath === undefined) delete process.env.PATH;
else process.env.PATH = previousPath;
}
});
test("protects pre-existing and discovers newly managed worktrees whose paths contain a line break", async () => {
const { tempDir, repoDir, paseoHome } = createGitRepo();
cleanupPaths.push(tempDir);
const newlineWorktree = path.join(tempDir, "manual\nworktree");
git(repoDir, "worktree", "add", "-b", "newline-branch", newlineWorktree, "main");
writeFileSync(path.join(newlineWorktree, "keep.txt"), "uncommitted\n");
await expect(
createCoreWorktree(
{
cwd: repoDir,
worktreeSlug: "newline-hijack",
action: "branch-off",
branchName: "newline-hijack",
paseoHome,
},
{
...createCoreDeps(),
worktreeManagers: {
hasWorktreeManager: () => true,
createWorktree: async () => ({
pluginId: "bad-manager",
path: newlineWorktree,
}),
removeWorktree: async () => null,
},
},
),
).rejects.toThrow("already-existing worktree");
expect(readFileSync(path.join(newlineWorktree, "keep.txt"), "utf8")).toBe("uncommitted\n");
expect(await readPaseoWorktreeMetadata(newlineWorktree)).toBeNull();
// A newly created managed worktree inside a directory containing a line break must remain
// visible to discovery and marker-based ownership checks.
const managedNewlineDir = path.join(tempDir, "parent\nbreak", "managed-wt");
mkdirSync(path.dirname(managedNewlineDir), { recursive: true });
const created = await createCoreWorktree(
{
cwd: repoDir,
worktreeSlug: "newline-managed",
action: "branch-off",
branchName: "newline-managed",
paseoHome,
},
{
...createCoreDeps(),
worktreeManagers: {
hasWorktreeManager: () => true,
createWorktree: async (request) => {
git(repoDir, "worktree", "add", "-b", request.branch, managedNewlineDir, "main");
return { pluginId: "newline-manager", path: managedNewlineDir };
},
removeWorktree: async () => null,
},
},
);
const expectedPath = realpathSync(managedNewlineDir);
expect(created.worktree.worktreePath).toBe(expectedPath);
const allGitWorktrees = await listGitWorktrees({ cwd: repoDir });
expect(allGitWorktrees.map((entry) => entry.path)).toContain(expectedPath);
const paseoWorktrees = await listPaseoWorktrees({ cwd: repoDir, paseoHome });
expect(paseoWorktrees.map((entry) => entry.path)).toContain(expectedPath);
const ownership = await isPaseoOwnedWorktreeCwd(expectedPath, { paseoHome });
expect(ownership.allowed).toBe(true);
expect(ownership.worktreePath).toBe(expectedPath);
});
test("declines a Worktrunk fork PR checkout when the archived local branch already exists so Git checks out the latest PR head", async () => {
const { tempDir, repoDir, headRemoteDir, paseoHome } = createForkGitHubPrRemoteRepo();
cleanupPaths.push(tempDir);
const archivedBranch = "therainisme/main";
const archivedTip = git(repoDir, "rev-parse", "main");
git(repoDir, "branch", archivedBranch, archivedTip);
const latestPrHead = git(repoDir, "ls-remote", "origin", "refs/pull/526/head").split(
/\s+/,
)[0];
expect(latestPrHead).not.toBe(archivedTip);
const wt = path.join(tempDir, "fake-wt-fork-pr");
writeFileSync(
wt,
`#!/bin/sh
echo "wt should not be invoked when local branch already exists" >&2
exit 1
`,
{ mode: 0o755 },
);
const github = {
...createGitHubServiceStub(),
getPullRequestCheckoutTarget: async () => ({
number: 526,
baseRefName: "main",
headRefName: "main",
headOwnerLogin: "therainisme",
headRepositorySshUrl: headRemoteDir,
headRepositoryUrl: headRemoteDir,
isCrossRepository: true,
}),
};
const previous = process.env.WORKTRUNK_BIN;
process.env.WORKTRUNK_BIN = wt;
try {
const result = await createCoreWorktree(
{
cwd: repoDir,
worktreeSlug: "fork-pr-reopen",
action: "checkout",
githubPrNumber: 526,
refName: "main",
paseoHome,
},
{
...createCoreDeps({ github }),
worktreeManagers: {
hasWorktreeManager: () => true,
createWorktree: async (request) => {
expect(request.untrusted).toBe(true);
expect(request.headSha).toBe(latestPrHead);
const managed = await createWithWorktrunk(request, new AbortController().signal);
return managed ? { pluginId: "worktrunk", path: managed.path } : null;
},
removeWorktree: async () => null,
},
},
);
expect(git(result.worktree.worktreePath, "rev-parse", "HEAD")).toBe(latestPrHead);
expect(git(repoDir, "rev-parse", `refs/heads/${archivedBranch}`)).toBe(archivedTip);
} finally {
if (previous === undefined) delete process.env.WORKTRUNK_BIN;
else process.env.WORKTRUNK_BIN = previous;
}
});
test("throws a typed error for an unknown checkout branch", async () => {
const { tempDir, repoDir, paseoHome } = createGitRepo();
cleanupPaths.push(tempDir);
@@ -2183,26 +1648,9 @@ exit 1
branchName: "follow-up",
paseoHome,
},
{
...createCoreDeps({ github }),
worktreeManagers: {
hasWorktreeManager: () => true,
async createWorktree(request) {
expect(request.untrusted).toBe(true);
return null;
},
async removeWorktree() {
return null;
},
},
},
createCoreDeps({ github }),
);
expect(result.untrustedSource).toMatchObject({
kind: "change_request",
forge: "github",
number: 526,
});
const readme = readFileSync(path.join(result.worktree.worktreePath, "README.md"), "utf8");
// The fork's branch is not in this repository, so a pull request from the new branch goes
// into the fork pull request's base, compared as the remote has it now.
+1 -73
View File
@@ -1,19 +1,12 @@
import type {
PluginWorktreeCreateInput,
PluginWorktreeCreateRequest,
} from "@getpaseo/plugin/server";
import type { PluginWorktreeCreateRequest } from "@getpaseo/plugin/server";
import type { PluginLifecycle } from "./plugins/lifecycle/index.js";
import type { PluginWorktreeManagerRuntime } from "./plugins/runtime.js";
import { createNameId } from "mnemonic-id";
import type { ForgeService } from "../services/forge-service.js";
import {
createWorktree,
fetchFirstAvailableRef,
prepareWorktreeBranchOff,
type PreparedWorktreeBranchOff,
resolveDefaultWorktreePath,
runPluginWorktreeManagerCheckout,
slugify,
validateBranchSlug,
type CreatedWorktree,
@@ -23,14 +16,11 @@ import {
type ResolveWorktreeCreationIntentInput,
UnsupportedForgeCheckoutTargetError,
type WorktreeCreationIntent,
worktreeUntrustedSource,
} from "./resolve-worktree-creation-intent.js";
import type { ChangeRequestCheckoutSource, FirstAgentContext } from "@getpaseo/protocol/messages";
import type { WorkspaceGitService } from "./workspace-git-service.js";
import { runGitCommand, runWithGitCommandPriority } from "../utils/run-git-command.js";
import type { UntrustedWorkspaceSource } from "./workspace-automation-gate.js";
export interface CreateWorktreeCoreInput {
cwd: string;
worktreeSlug?: string;
@@ -46,10 +36,6 @@ export interface CreateWorktreeCoreInput {
export interface CreateWorktreeCoreDeps {
lifecycle?: Pick<PluginLifecycle, "before">;
worktreeManagers?: Pick<
PluginWorktreeManagerRuntime,
"hasWorktreeManager" | "createWorktree" | "removeWorktree"
>;
github: ForgeService;
workspaceGitService?: Pick<
WorkspaceGitService,
@@ -61,7 +47,6 @@ export interface CreateWorktreeCoreDeps {
export interface CreateWorktreeCoreResult {
worktree: CreatedWorktree;
intent: WorktreeCreationIntent;
untrustedSource?: UntrustedWorkspaceSource;
repoRoot: string;
created: boolean;
}
@@ -161,28 +146,8 @@ async function createWorktreeCoreWithPriority(
const transformed = deps.lifecycle
? await deps.lifecycle.before("worktree.create.before", request)
: request;
const originalUntrustedSource = worktreeUntrustedSource(intent);
normalizedSlug = validateWorktreeSlug(transformed.slug);
intent = creationIntentFromRequest(transformed, intent);
const untrustedSource = originalUntrustedSource ?? worktreeUntrustedSource(intent);
const { worktree: managedWorktree, preparedBranchOff } = await tryCreateWithWorktreeManager({
repoRoot,
transformed,
intent,
untrusted: Boolean(untrustedSource),
input,
deps,
});
if (managedWorktree) {
return {
worktree: managedWorktree,
intent,
untrustedSource,
repoRoot,
created: true,
};
}
return {
worktree: await createWorktree({
@@ -190,51 +155,15 @@ async function createWorktreeCoreWithPriority(
worktreeSlug: normalizedSlug,
worktreePath: transformed.path,
source: intent,
preparedBranchOff,
paseoHome: input.paseoHome,
worktreesRoot: input.worktreesRoot,
}),
intent,
untrustedSource,
repoRoot,
created: true,
};
}
async function tryCreateWithWorktreeManager(options: {
repoRoot: string;
transformed: PluginWorktreeCreateRequest;
intent: WorktreeCreationIntent;
untrusted: boolean;
input: Pick<CreateWorktreeCoreInput, "paseoHome" | "worktreesRoot">;
deps: Pick<CreateWorktreeCoreDeps, "worktreeManagers">;
}): Promise<{ worktree: CreatedWorktree | null; preparedBranchOff?: PreparedWorktreeBranchOff }> {
const { repoRoot, transformed, intent, untrusted, input, deps } = options;
let preparedBranchOff: PreparedWorktreeBranchOff | undefined;
const worktree = await runPluginWorktreeManagerCheckout({
cwd: repoRoot,
source: intent,
operation: "create",
untrusted,
paseoHome: input.paseoHome,
worktreesBaseRoot: input.worktreesRoot,
worktreeManagers: deps.worktreeManagers,
run: async ({ changeRequestHeadSha }) => {
let request: PluginWorktreeCreateInput = {
...transformed,
untrusted,
...(changeRequestHeadSha ? { headSha: changeRequestHeadSha } : {}),
};
if (request.kind === "branch-off" && intent.kind === "branch-off") {
preparedBranchOff = await prepareWorktreeBranchOff(repoRoot, intent);
request = { ...request, baseRef: preparedBranchOff.baseRef };
}
return deps.worktreeManagers!.createWorktree(request);
},
});
return { worktree, preparedBranchOff };
}
function describeCreationRequest(
intent: WorktreeCreationIntent,
placement: Pick<PluginWorktreeCreateRequest, "repoRoot" | "sourceCheckout" | "slug" | "path">,
@@ -245,7 +174,6 @@ function describeCreationRequest(
kind: intent.kind,
branch: intent.branchName,
baseRef: intent.baseBranch,
...(intent.startPoint ? { startPoint: intent.startPoint } : {}),
};
if (intent.kind === "checkout-branch")
return { ...placement, kind: intent.kind, branch: intent.branchName };
+1 -21
View File
@@ -78,7 +78,7 @@ export function isPathInsideRoot(root: string, candidate: string): boolean {
}
export function normalizePathForIdentity(value: string): string {
const canonicalPath = resolveNearestExistingAncestorRealpath(value);
const canonicalPath = resolveRealpathVariants(value)[0] ?? value;
return normalizePathForComparison(canonicalPath, looksLikeDefiniteWindowsPath(canonicalPath));
}
@@ -150,26 +150,6 @@ function resolveRealpathVariants(value: string): string[] {
return variants;
}
function resolveNearestExistingAncestorRealpath(value: string): string {
if (process.platform !== "win32" && looksLikeDefiniteWindowsPath(value)) {
return value;
}
const tail: string[] = [];
let current = value;
while (true) {
const resolved = resolveRealpathVariants(current)[0];
if (resolved) {
return tail.length === 0 ? resolved : nodePath.join(resolved, ...tail.toReversed());
}
const parent = nodePath.dirname(current);
if (parent === current) {
return value;
}
tail.push(nodePath.basename(current));
current = parent;
}
}
function shouldCompareAsWindows(left: string, right: string): boolean {
return looksLikeDefiniteWindowsPath(left) || looksLikeDefiniteWindowsPath(right);
}
@@ -22,7 +22,6 @@ const PaseoWorktreeMetadataV1Schema = z.object({
baseRefName: z.string().min(1),
baseRef: z.string().min(1).optional(),
changeRequestLookupTarget: ChangeRequestLookupTargetSchema.optional(),
worktreeManagerPluginId: z.string().min(1).optional(),
});
const PaseoWorktreeMetadataV2Schema = z.object({
@@ -30,7 +29,6 @@ const PaseoWorktreeMetadataV2Schema = z.object({
baseRefName: z.string().min(1),
baseRef: z.string().min(1).optional(),
changeRequestLookupTarget: ChangeRequestLookupTargetSchema.optional(),
worktreeManagerPluginId: z.string().min(1).optional(),
firstAgentBranchAutoName: z
.discriminatedUnion("status", [
z.object({
@@ -229,7 +227,6 @@ export async function writePaseoWorktreeMetadata(
baseRefName: string;
baseRef?: string;
changeRequestLookupTarget?: PaseoWorktreeChangeRequestHint;
worktreeManagerPluginId?: string;
},
): Promise<void> {
return mutateMetadata(worktreeRoot, async (root) => {
@@ -247,9 +244,6 @@ export async function writePaseoWorktreeMetadata(
...(options.changeRequestLookupTarget
? { changeRequestLookupTarget: options.changeRequestLookupTarget }
: {}),
...(options.worktreeManagerPluginId
? { worktreeManagerPluginId: options.worktreeManagerPluginId }
: {}),
};
await writePaseoWorktreeMetadataFile(root, metadata);
});
+2 -4
View File
@@ -47,10 +47,8 @@ async function pathExists(path: string): Promise<boolean> {
export async function validateWorktreePath(options: {
candidate: string;
repoPath: string;
/** The worktree manager already created the destination, so it is expected to exist. */
allowExistingPath?: boolean;
}): Promise<string> {
const { candidate, repoPath, allowExistingPath = false } = options;
const { candidate, repoPath } = options;
if (!isAbsolute(candidate)) {
throw new Error(
`Worktree hook returned a relative path '${candidate}'; it must be an absolute path`,
@@ -81,7 +79,7 @@ export async function validateWorktreePath(options: {
if (relativeToCandidate !== null && relativeToCandidate !== "") {
throw new Error(`Worktree hook returned an ancestor of the repository: ${normalized}`);
}
if (!allowExistingPath && ((await pathExists(normalized)) || (await pathExists(candidate)))) {
if ((await pathExists(normalized)) || (await pathExists(candidate))) {
throw new Error(
`Worktree hook returned a path that already exists: ${normalized}. Paseo creates the returned path.`,
);
File diff suppressed because it is too large Load Diff
-20
View File
@@ -1,20 +0,0 @@
# Worktrunk plugin example
Delegates Paseo worktree creation, removal, and restoration to [Worktrunk](https://worktrunk.dev) (`wt`), and updates `wt list` activity markers (`🤖` / `💬`) as agents run.
## What it does
- **Create:** routes branch-off, branch checkout, and change-request (PR/MR) creation through `wt switch --no-cd --format=json` (using Paseo's fetched `headSha` for PR/MR checkouts, and `--no-hooks` on untrusted fork checkouts) so Worktrunk controls placement, branch setup, and `pre-start` / `post-start` hooks. Local branch collisions decline and fall back to Paseo's Git checkout.
- **Remove:** routes archive and creation rollback through `wt remove --foreground --no-delete-branch --yes` so Worktrunk runs `pre-remove` and `post-remove` hooks while keeping the branch for Paseo's restore flow.
- **Restore:** routes archived worktree restoration through `wt switch --path <recorded-path>` for branch restores, and falls back to Paseo for detached-commit restores.
- **Activity markers:** sets `🤖` when an agent turn starts, `💬` when a turn ends or awaits permission, and clears the marker on close or archive. Background helpers are skipped.
## Prerequisites
Install Worktrunk (`wt`, or `git-wt.exe` on Windows) on `PATH`, or set `WORKTRUNK_BIN` in the daemon environment.
## Install
```bash
paseo plugin install /absolute/path/to/plugin-examples/worktrunk
```
-44
View File
@@ -1,44 +0,0 @@
import type { PluginServerContext } from "@getpaseo/plugin/server";
import {
WAITING_MARKER,
WORKING_MARKER,
createWithWorktrunk,
removeWithWorktrunk,
restoreWithWorktrunk,
setActivityMarker,
} from "./server/wt.js";
export default function contribute(server: PluginServerContext) {
const cleanups = [
server.registerWorktreeManager({
create: (request, { signal }) => createWithWorktrunk(request, signal),
remove: (request, { signal }) => removeWithWorktrunk(request, signal),
restore: (request, { signal }) => restoreWithWorktrunk(request, signal),
}),
server.addHook("agent.turn.before", async ({ agent }, { signal }) => {
if (agent.background) return;
await setActivityMarker(agent.cwd, WORKING_MARKER, signal);
}),
server.addHook("agent.turn.after", async ({ agent }, { signal }) => {
if (agent.background) return;
await setActivityMarker(agent.cwd, WAITING_MARKER, signal);
}),
server.addHook("agent.permission.before", async ({ agent }, { signal }) => {
if (agent.background) return;
await setActivityMarker(agent.cwd, WAITING_MARKER, signal);
}),
server.addHook("agent.close.after", async ({ agent }, { signal }) => {
if (agent.background) return;
await setActivityMarker(agent.cwd, null, signal);
}),
server.addHook("agent.archive.after", async ({ agent }, { signal }) => {
if (agent.background) return;
await setActivityMarker(agent.cwd, null, signal);
}),
];
return () => {
for (const cleanup of cleanups) cleanup();
};
}
@@ -1,6 +0,0 @@
{
"id": "worktrunk",
"name": "Worktrunk",
"description": "Manage Git worktrees and agent activity markers through Worktrunk (wt).",
"requirements": { "paseo": ">=0.17.0" }
}
-317
View File
@@ -1,317 +0,0 @@
import { lstatSync } from "node:fs";
import { readFile, writeFile } from "node:fs/promises";
import { delimiter, join } from "node:path";
import {
execCommand,
type PluginWorktreeCreateInput,
type PluginWorktreeRemoveRequest,
type PluginWorktreeRestoreRequest,
} from "@getpaseo/plugin/server";
const MAX_OUTPUT_BYTES = 16 * 1024 * 1024;
const CREATED_BRANCH_FILE = "paseo-worktrunk-created-branch";
export const WORKING_MARKER = "🤖";
export const WAITING_MARKER = "💬";
interface SwitchJsonOutput {
path: string;
action?: string;
branch?: string;
createdBranch: boolean;
}
/**
* Resolve the Worktrunk CLI executable.
* Honors `WORKTRUNK_BIN` first; on Windows prefers `git-wt.exe` and skips the
* WindowsApps alias that points to Windows Terminal.
*/
export function resolveWorktrunkBin(): string | null {
const configured = process.env.WORKTRUNK_BIN?.trim();
if (configured) return configured;
if (process.platform !== "win32") return "wt";
const dirs = (process.env.PATH ?? "").split(delimiter).filter(Boolean);
const findOnPath = (name: string) =>
dirs
.map((dir) => join(dir, name))
.find((candidate) => {
try {
lstatSync(candidate);
return true;
} catch {
return false;
}
});
if (findOnPath("git-wt.exe")) return "git-wt.exe";
const wt = findOnPath("wt.exe");
return wt && !/[\\/]WindowsApps[\\/]/i.test(wt) ? "wt" : null;
}
async function runWt(
args: string[],
options: { cwd?: string; signal?: AbortSignal } = {},
): Promise<string> {
const bin = resolveWorktrunkBin();
if (!bin) {
throw new Error(
"Worktrunk CLI not found on PATH. Install wt (or git-wt.exe on Windows) or set WORKTRUNK_BIN.",
);
}
try {
const { stdout } = await execCommand(bin, args, {
cwd: options.cwd,
signal: options.signal,
maxBuffer: MAX_OUTPUT_BYTES,
});
return stdout;
} catch (error) {
const stderr = (error as { stderr?: string }).stderr?.trim();
throw new Error(stderr || (error instanceof Error ? error.message : String(error)), {
cause: error,
});
}
}
function tryParseSwitchOutput(stdout: string | undefined): SwitchJsonOutput | null {
if (!stdout?.trim()) return null;
try {
const parsed = JSON.parse(stdout) as {
path?: unknown;
action?: unknown;
branch?: unknown;
created_branch?: unknown;
from_remote?: unknown;
};
if (typeof parsed.path !== "string" || parsed.path.length === 0) return null;
return {
path: parsed.path,
// Worktrunk sets from_remote when switch creates a branch that tracks a remote.
createdBranch:
parsed.created_branch === true ||
(typeof parsed.from_remote === "string" && parsed.from_remote.length > 0),
...(typeof parsed.branch === "string" && parsed.branch ? { branch: parsed.branch } : {}),
...(typeof parsed.action === "string" ? { action: parsed.action } : {}),
};
} catch {
return null;
}
}
function parseSwitchOutput(stdout: string): SwitchJsonOutput {
const parsed = tryParseSwitchOutput(stdout);
if (!parsed) {
throw new Error("wt switch --format=json output did not include a worktree path");
}
return parsed;
}
function hookFlags(untrusted: boolean): string[] {
// Never approve repository-defined hooks on untrusted checkouts such as fork PRs.
return untrusted ? ["--no-hooks"] : ["--yes"];
}
export function buildCreateArgs(request: PluginWorktreeCreateInput): string[] | null {
const common = [
"-C",
request.repoRoot,
"switch",
"--no-cd",
...hookFlags(request.untrusted),
"--format=json",
];
switch (request.kind) {
case "branch-off":
return [
...common,
"--create",
request.branch,
"--base",
request.startPoint ?? request.baseRef,
];
case "checkout-branch":
return [...common, request.branch];
case "checkout-change-request":
case "checkout-github-pr":
if (!request.headSha) return null;
return [...common, "--create", request.branch, "--base", request.headSha];
}
}
function failedSwitchOutput(error: unknown): SwitchJsonOutput | null {
// Worktrunk reports the checkout and whether it created the branch even if a hook fails.
const stdout =
error instanceof Error && error.cause && typeof error.cause === "object"
? (error.cause as { stdout?: string }).stdout
: undefined;
return tryParseSwitchOutput(stdout);
}
async function createdBranchFile(worktreePath: string): Promise<string> {
const { stdout } = await execCommand("git", ["rev-parse", "--absolute-git-dir"], {
cwd: worktreePath,
});
return join(stdout.trim(), CREATED_BRANCH_FILE);
}
async function cleanupPartiallyCreatedWorktree(
repoRoot: string,
output: SwitchJsonOutput | null,
): Promise<void> {
if (output?.action !== "created") return;
await runWt([
"-C",
repoRoot,
"remove",
"--foreground",
"--no-delete-branch",
"--no-hooks",
"--force",
output.path,
]);
if (output.createdBranch && output.branch) {
await execCommand("git", ["branch", "-D", "--", output.branch], { cwd: repoRoot });
}
}
async function recordCreatedBranch(repoRoot: string, output: SwitchJsonOutput): Promise<void> {
if (output.action !== "created" || !output.createdBranch || !output.branch) return;
try {
// The linked worktree owns this record until removal. An archive keeps the branch.
await writeFile(await createdBranchFile(output.path), output.branch, { flag: "wx" });
} catch (error) {
await cleanupPartiallyCreatedWorktree(repoRoot, output).catch(() => {});
throw error;
}
}
async function hasLocalBranch(
repoRoot: string,
branch: string,
signal: AbortSignal,
): Promise<boolean> {
const ref = `refs/heads/${branch}`;
const { stdout } = await execCommand("git", ["for-each-ref", "--format=%(refname)", ref], {
cwd: repoRoot,
signal,
});
return stdout.trim().split(/\r?\n/).includes(ref);
}
export async function createWithWorktrunk(
request: PluginWorktreeCreateInput,
signal: AbortSignal,
): Promise<{ type: "created"; path: string } | undefined> {
const args = buildCreateArgs(request);
if (!args) return undefined;
// With a local branch collision, decline so Paseo's Git checkout allocates a unique branch
// name without disturbing the existing local branch.
const createsLocalBranch =
request.kind === "branch-off" ||
request.kind === "checkout-change-request" ||
request.kind === "checkout-github-pr";
if (createsLocalBranch && (await hasLocalBranch(request.repoRoot, request.branch, signal))) {
return undefined;
}
let stdout: string;
try {
stdout = await runWt(args, { signal });
} catch (error) {
await cleanupPartiallyCreatedWorktree(request.repoRoot, failedSwitchOutput(error)).catch(
() => {},
);
throw error;
}
const output = parseSwitchOutput(stdout);
// If Worktrunk switched to an already-existing checkout instead of creating one,
// decline so Paseo falls back to Git (which creates a unique branch).
if (output.action !== undefined && output.action !== "created") {
return undefined;
}
await recordCreatedBranch(request.repoRoot, output);
return { type: "created", path: output.path };
}
export async function removeWithWorktrunk(
request: PluginWorktreeRemoveRequest,
signal: AbortSignal,
): Promise<{ type: "removed" }> {
// Run from the main repository root when available and skip repository hooks for
// untrusted workspaces (or when repoRoot is unknown) so fork PRs cannot run hooks.
const runDir = request.repoRoot ?? request.path;
const skipHooks = request.untrusted || request.repoRoot === null;
const args = [
"-C",
runDir,
"remove",
"--foreground",
"--no-delete-branch",
...hookFlags(skipHooks),
...(request.force ? ["--force"] : []),
request.path,
];
const createdBranch =
request.reason === "rollback" && request.repoRoot && request.branch
? await createdBranchFile(request.path)
.then((file) => readFile(file, "utf8"))
.catch(() => null)
: null;
await runWt(args, { signal });
if (createdBranch && createdBranch === request.branch && request.repoRoot) {
await execCommand("git", ["branch", "-D", "--", createdBranch], { cwd: request.repoRoot });
}
return { type: "removed" };
}
export async function restoreWithWorktrunk(
request: PluginWorktreeRestoreRequest,
signal: AbortSignal,
): Promise<{ type: "restored"; path: string } | undefined> {
if (request.target.type === "commit") {
// Detached-commit restores fall back to Paseo's built-in Git restore.
return undefined;
}
const common = [
"-C",
request.repoRoot,
"switch",
"--path",
request.path,
"--no-cd",
...hookFlags(request.untrusted),
"--format=json",
];
const args =
request.target.type === "branch"
? [...common, request.target.branch]
: [...common, "--create", request.target.branch, "--base", request.target.baseRef];
let stdout: string;
try {
stdout = await runWt(args, { signal });
} catch (error) {
await cleanupPartiallyCreatedWorktree(request.repoRoot, failedSwitchOutput(error)).catch(
() => {},
);
throw error;
}
const output = parseSwitchOutput(stdout);
await recordCreatedBranch(request.repoRoot, output);
return { type: "restored", path: output.path };
}
export async function setActivityMarker(
cwd: string,
marker: string | null,
signal: AbortSignal,
): Promise<void> {
const args =
marker === null
? ["config", "state", "marker", "clear"]
: ["config", "state", "marker", "set", marker];
try {
await runWt(args, { cwd, signal });
} catch {
// Activity markers are best-effort and must not disrupt agent sessions.
}
}
@@ -65,9 +65,46 @@ it("discovers the resolved account and maps the CLI's quota buckets", async () =
expect(await source.fetch(accounts[0]!.input)).toMatchObject({
status: "available",
windows: [
{ id: "gemini-5h", usedPct: 75, remainingPct: 25, resetsAt: "2026-11-19T14:25:08Z" },
{ id: "gemini-weekly", usedPct: expect.closeTo(30), summary: true },
{ id: "disabled", usedPct: null, remainingPct: null },
{
id: "gemini-5h",
shortLabel: "5h",
usedPct: 75,
remainingPct: 25,
resetsAt: "2026-11-19T14:25:08Z",
},
{ id: "gemini-weekly", shortLabel: "wk", usedPct: expect.closeTo(30), summary: true },
{ id: "disabled", shortLabel: "wk", usedPct: null, remainingPct: null },
],
});
});
it("uses compact group and period shorthands when multiple groups are reported", async () => {
const directory = await mkdtemp(path.join(tmpdir(), "paseo-antigravity-usage-"));
directories.push(directory);
const cli = path.join(directory, "cli.cjs");
await writeFile(
cli,
`
console.log(JSON.stringify({ status: 'SUCCESS', command: { name: 'usage', data: { groups: [
{ name: 'Gemini Models', buckets: [
{ id: 'gemini-weekly', name: 'Weekly Limit Remaining', window: 'weekly', remaining_fraction: 0.9 },
{ id: 'gemini-5h', name: 'Five Hour Limit Remaining', window: '5h', remaining_fraction: 0.8 }
] },
{ name: 'Claude and GPT models', buckets: [
{ id: '3p-weekly', name: 'Weekly Limit Remaining', window: 'weekly', remaining_fraction: 1 }
] }
] } } }));
`,
);
const launch = { command: process.execPath, args: [cli, "acp"], env: { HOME: directory } };
const source = new Usage().registration();
const [account] = await source.discover({ kind: "global", launch });
expect(await source.fetch(account!.input)).toMatchObject({
status: "available",
windows: [
{ id: "gemini-weekly", shortLabel: "Gemini wk" },
{ id: "gemini-5h", shortLabel: "Gemini 5h" },
{ id: "3p-weekly", shortLabel: "Claude and GPT wk" },
],
});
});
+26 -2
View File
@@ -48,6 +48,28 @@ function accountKey(env: ProviderLaunch["env"]): string {
);
}
function shortWindow(window: string): string {
const trimmed = window.trim();
const normalized = trimmed.toLowerCase();
if (normalized === "weekly") return "wk";
if (normalized === "monthly") return "mo";
return trimmed;
}
function shortGroupName(name: string): string {
return name
.trim()
.replace(/\s+models$/i, "")
.trim();
}
function formatShortLabel(groupName: string, window: string, includeGroup: boolean): string {
const period = shortWindow(window);
if (!includeGroup) return period;
const scope = shortGroupName(groupName);
return scope ? `${scope} ${period}` : period;
}
export class Usage {
private readonly launches = new Map<string, ProviderLaunch>();
@@ -94,7 +116,9 @@ export class Usage {
throw new Error(data.error || data.response || `agy usage returned ${data.status}`);
}
if (!data.command) throw new Error("agy did not return usage data");
const windows = data.command.data.groups.flatMap((group) =>
const groups = data.command.data.groups;
const includeGroup = groups.length > 1;
const windows = groups.flatMap((group) =>
group.buckets.flatMap((bucket) => {
if (!bucket.disabled && bucket.remaining_fraction == null) return [];
const used = bucket.disabled ? null : (1 - bucket.remaining_fraction!) * 100;
@@ -102,7 +126,7 @@ export class Usage {
windowFromUsedPct({
id: bucket.id,
label: `${group.name} · ${bucket.name}${bucket.disabled ? " · Disabled" : ""}`,
shortLabel: `${group.name} ${bucket.window}`,
shortLabel: formatShortLabel(group.name, bucket.window, includeGroup),
summary: !bucket.disabled && bucket.window === "weekly",
utilizationPct: used,
resetsAt: bucket.disabled ? null : bucket.reset_time,

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