mirror of
https://github.com/getpaseo/paseo.git
synced 2026-11-26 02:05:31 +00:00
Compare commits
13
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7f3e197c0d | ||
|
|
1d9ca6cb12 | ||
|
|
1bd9b4673d | ||
|
|
c9159df62a | ||
|
|
d154df3165 | ||
|
|
0a3fed0643 | ||
|
|
fd2f885afd | ||
|
|
988cf4bec8 | ||
|
|
a6a9d0b8c7 | ||
|
|
b71b4d584a | ||
|
|
c9a7d523f8 | ||
|
|
ca514b34a7 | ||
|
|
efb65d7b82 |
+7
-2
@@ -582,12 +582,17 @@ host, kinds, and ids. Opening a cached workspace uses exact workspace and projec
|
||||
directory scan. One invalid row is deleted and returned as a miss without affecting other rows.
|
||||
An invalid directory row and its affected checkpoint cursor are repaired in one transaction, so a
|
||||
later launch cannot accept a checkpoint for a partial baseline. Directory changes and their
|
||||
checkpoint are also applied in one transaction. Reads wait for accepted changes to reach storage,
|
||||
checkpoint are also applied in one transaction. A stored checkpoint carries a version. When a writer
|
||||
bug could have stored a checkpoint without its directory, bump the version: older checkpoints are
|
||||
rejected on read, cached rows still paint, and each host re-syncs its directory once. Reads wait for
|
||||
accepted changes to reach storage,
|
||||
then retry only when a requested row changes during the read. Unrelated agent streams do not
|
||||
invalidate the read. Directory baseline replacements and host removal or renaming still invalidate
|
||||
the affected reads.
|
||||
|
||||
The cache is capped at 32 MiB and evicts whole hosts in least-recently-written order. Budget
|
||||
The cache is capped at 32 MiB and evicts whole hosts in least-recently-written order. After an
|
||||
eviction, only a baseline replacement stores that host's directory again. Mutations queued around
|
||||
the eviction are dropped when they are written, so a checkpoint never outlives its rows. Budget
|
||||
bookkeeping may scan opaque row sizes during a deferred write, never during host registry startup or
|
||||
before a requested cache row can paint. The row store is not encrypted. A cached timeline can contain
|
||||
source code, prompts, and tool output; encrypted-at-rest storage is a separate security decision.
|
||||
|
||||
@@ -471,6 +471,18 @@ 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.
|
||||
|
||||
@@ -0,0 +1,149 @@
|
||||
import { test, expect, type Page } from "../support/fixtures";
|
||||
import { gotoAppShell } from "../support/helpers/app";
|
||||
import { seedWorkspace, type SeededWorkspace } from "../support/helpers/seed-client";
|
||||
import { selectSidebarStatusGrouping } from "../support/helpers/sidebar";
|
||||
import {
|
||||
createGatedTeardown,
|
||||
pressArchiveShortcut,
|
||||
workspaceRow,
|
||||
} from "../support/helpers/workspace-archive-undo";
|
||||
|
||||
// The archive shortcut used to be registered by the sidebar row itself, so it did nothing whenever
|
||||
// the row was unmounted — a collapsed project section being the common case. It now lives in a
|
||||
// single always-mounted handler keyed on the active route selection, like the pin shortcut.
|
||||
// Returns the workspace route, so the test can assert archiving redirected off it.
|
||||
async function openWorkspace(page: Page, workspaceId: string): Promise<string> {
|
||||
const row = workspaceRow(page, workspaceId);
|
||||
await expect(row).toBeVisible({ timeout: 30_000 });
|
||||
await row.click();
|
||||
await expect(page).toHaveURL((url) => url.pathname.endsWith(`/workspace/${workspaceId}`), {
|
||||
timeout: 30_000,
|
||||
});
|
||||
return page.url();
|
||||
}
|
||||
|
||||
async function collapseProjectSection(page: Page, project: SeededWorkspace): Promise<void> {
|
||||
const header = page
|
||||
.locator('[data-testid^="sidebar-project-row-"]')
|
||||
.filter({ hasText: project.projectDisplayName });
|
||||
await expect(header).toHaveCount(1, { timeout: 30_000 });
|
||||
|
||||
await header.click();
|
||||
await expect(workspaceRow(page, project.workspaceId)).toHaveCount(0, { timeout: 10_000 });
|
||||
}
|
||||
|
||||
async function collapseStatusGroupContaining(page: Page, workspaceId: string): Promise<void> {
|
||||
const rows = page
|
||||
.locator('[data-testid^="sidebar-status-group-rows-"]')
|
||||
.filter({ has: workspaceRow(page, workspaceId) });
|
||||
await expect(rows).toHaveCount(1, { timeout: 30_000 });
|
||||
|
||||
const rowsTestId = await rows.getAttribute("data-testid");
|
||||
const bucket = rowsTestId?.replace("sidebar-status-group-rows-", "");
|
||||
expect(bucket).toBeTruthy();
|
||||
|
||||
await page.getByTestId(`sidebar-status-group-${bucket}`).click();
|
||||
await expect(workspaceRow(page, workspaceId)).toHaveCount(0, { timeout: 10_000 });
|
||||
}
|
||||
|
||||
async function expectArchived(page: Page, workspace: SeededWorkspace, workspaceUrl: string) {
|
||||
await expect(page).not.toHaveURL(workspaceUrl);
|
||||
await expect
|
||||
.poll(async () => {
|
||||
const { entries } = await workspace.client.fetchWorkspaces();
|
||||
return entries.some((entry) => entry.id === workspace.workspaceId);
|
||||
})
|
||||
.toBe(false);
|
||||
}
|
||||
|
||||
test.describe("Archive workspace shortcut", () => {
|
||||
test("archives the active workspace while its row is rendered", async ({ page }) => {
|
||||
const workspace = await seedWorkspace({ repoPrefix: "archive-shortcut-expanded-" });
|
||||
|
||||
try {
|
||||
await gotoAppShell(page);
|
||||
const workspaceUrl = await openWorkspace(page, workspace.workspaceId);
|
||||
|
||||
await pressArchiveShortcut(page);
|
||||
|
||||
await expectArchived(page, workspace, workspaceUrl);
|
||||
} finally {
|
||||
await workspace.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test("archives the active workspace while its project section is collapsed", async ({ page }) => {
|
||||
const workspace = await seedWorkspace({ repoPrefix: "archive-shortcut-collapsed-" });
|
||||
|
||||
try {
|
||||
await gotoAppShell(page);
|
||||
const workspaceUrl = await openWorkspace(page, workspace.workspaceId);
|
||||
await collapseProjectSection(page, workspace);
|
||||
|
||||
await pressArchiveShortcut(page);
|
||||
|
||||
await expectArchived(page, workspace, workspaceUrl);
|
||||
} finally {
|
||||
await workspace.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test("archives the active workspace while its status group is collapsed", async ({ page }) => {
|
||||
const workspace = await seedWorkspace({ repoPrefix: "archive-shortcut-status-" });
|
||||
|
||||
try {
|
||||
await gotoAppShell(page);
|
||||
const workspaceUrl = await openWorkspace(page, workspace.workspaceId);
|
||||
await selectSidebarStatusGrouping(page);
|
||||
await expect(page.getByTestId("sidebar-status-list-scroll")).toBeVisible({
|
||||
timeout: 10_000,
|
||||
});
|
||||
await collapseStatusGroupContaining(page, workspace.workspaceId);
|
||||
|
||||
await pressArchiveShortcut(page);
|
||||
|
||||
await expectArchived(page, workspace, workspaceUrl);
|
||||
} finally {
|
||||
await workspace.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test("archives a different workspace while the first worktree is still tearing down", async ({
|
||||
page,
|
||||
}) => {
|
||||
const teardown = createGatedTeardown();
|
||||
const project = await seedWorkspace({
|
||||
repoPrefix: "archive-shortcut-teardown-",
|
||||
repo: { paseoConfig: teardown.paseoConfig },
|
||||
});
|
||||
const next = await seedWorkspace({ repoPrefix: "archive-shortcut-next-" });
|
||||
|
||||
try {
|
||||
const { workspace: worktree, error } = await project.client.createWorkspace({
|
||||
source: {
|
||||
kind: "worktree",
|
||||
cwd: project.repoPath,
|
||||
worktreeSlug: "archive-shortcut-teardown",
|
||||
},
|
||||
});
|
||||
if (!worktree) throw new Error(error ?? "Could not seed the worktree");
|
||||
await gotoAppShell(page);
|
||||
|
||||
await test.step("start the first archive and wait for its teardown", async () => {
|
||||
await openWorkspace(page, worktree.id);
|
||||
await pressArchiveShortcut(page);
|
||||
await teardown.expectStarted();
|
||||
});
|
||||
|
||||
await test.step("archive the second workspace before the first archive finishes", async () => {
|
||||
const workspaceUrl = await openWorkspace(page, next.workspaceId);
|
||||
await pressArchiveShortcut(page);
|
||||
await expectArchived(page, next, workspaceUrl);
|
||||
});
|
||||
} finally {
|
||||
teardown.release();
|
||||
await project.cleanup();
|
||||
await next.cleanup();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -206,13 +206,14 @@ async function simulateDamagedLegacyDirectoryCache(
|
||||
return;
|
||||
}
|
||||
const stored = JSON.parse(checkpoint.payload);
|
||||
// Accept either writer so this fixture also reproduces on the unfixed client.
|
||||
const cursors = stored.version === 1 ? stored.cursors : stored;
|
||||
if (!cursors.workspaces?.generation) {
|
||||
// Read the cursors from whichever version wrote them, then store them as version 1:
|
||||
// the format whose writer could keep a checkpoint after evicting the rows it describes.
|
||||
const cursors = typeof stored.version === "number" ? stored.cursors : stored;
|
||||
if (!cursors?.workspaces?.generation) {
|
||||
transaction.abort();
|
||||
return;
|
||||
}
|
||||
store.put({ ...checkpoint, payload: JSON.stringify(cursors) });
|
||||
store.put({ ...checkpoint, payload: JSON.stringify({ version: 1, cursors }) });
|
||||
for (const row of rows) {
|
||||
if (
|
||||
row.serverId === serverId &&
|
||||
|
||||
@@ -318,6 +318,37 @@ test.describe("Workspace archive undo", () => {
|
||||
}
|
||||
});
|
||||
|
||||
test("archives a restored workspace while its undo is queued", async ({ page }) => {
|
||||
const teardown = createGatedTeardown();
|
||||
const repo = await createTempGitRepo("archive-undo-archive-", {
|
||||
paseoConfig: teardown.paseoConfig,
|
||||
});
|
||||
|
||||
try {
|
||||
await openProjectViaDaemon(client, repo.path);
|
||||
const worktree = await createWorktreeViaDaemon(client, {
|
||||
cwd: repo.path,
|
||||
slug: "archive-undo-archive",
|
||||
});
|
||||
worktreeDirectories.add(worktree.workspaceDirectory);
|
||||
await gotoAppShell(page);
|
||||
await archiveFromRowButton(page, worktree.workspaceId);
|
||||
await teardown.expectStarted();
|
||||
|
||||
await undoButton(page).click();
|
||||
await workspaceRow(page, worktree.workspaceId).click();
|
||||
await expect(page).toHaveURL(new RegExp(`/workspace/${worktree.workspaceId}$`));
|
||||
|
||||
await pressArchiveShortcut(page);
|
||||
await expectWorkspaceAbsentFromSidebar(page, worktree.workspaceId);
|
||||
teardown.release();
|
||||
await expectDirectoryPresence(worktree.workspaceDirectory, false);
|
||||
} finally {
|
||||
teardown.release();
|
||||
await repo.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test("Cmd/Ctrl+Z without an archive to undo leaves the sidebar alone", async ({ page }) => {
|
||||
const worktree = await seedWorktree(page, "archive-undo-none");
|
||||
|
||||
|
||||
@@ -20,6 +20,7 @@ import {
|
||||
} from "../support/helpers/sidebar";
|
||||
import { createTempGitRepo } from "../support/helpers/workspace";
|
||||
import {
|
||||
pressArchiveShortcut,
|
||||
rowArchiveButton,
|
||||
undoButton,
|
||||
workspaceRow,
|
||||
@@ -98,6 +99,18 @@ async function clickRowArchiveButton(page: Page, workspaceId: string): Promise<v
|
||||
await rowArchiveButton(page, workspaceId).click();
|
||||
}
|
||||
|
||||
async function cycleThemeAndWaitForSidebar(page: Page, workspaceId: string): Promise<void> {
|
||||
const rowBeforeThemeChange = await workspaceRow(page, workspaceId).elementHandle();
|
||||
if (!rowBeforeThemeChange)
|
||||
throw new Error("The workspace row must be mounted before cycling the theme");
|
||||
await page.keyboard.press("ControlOrMeta+Alt+t");
|
||||
await expect
|
||||
.poll(() => rowBeforeThemeChange.evaluate((element) => element.isConnected), {
|
||||
message: "the sidebar remounts after the theme changes",
|
||||
})
|
||||
.toBe(false);
|
||||
}
|
||||
|
||||
interface SessionEnvelope {
|
||||
type?: unknown;
|
||||
message?: {
|
||||
@@ -211,18 +224,28 @@ async function relayDaemon(
|
||||
* Holds the app's next checkout status request for `directory` once armed, so a test can act
|
||||
* while the archive waits for the host's answer.
|
||||
*/
|
||||
async function holdCheckoutStatusRequest(page: Page, directory: string) {
|
||||
async function holdCheckoutStatusRequest(
|
||||
page: Page,
|
||||
worktree: { workspaceDirectory: string; workspaceId: string },
|
||||
) {
|
||||
let armed = false;
|
||||
let held: (() => void) | null = null;
|
||||
let archiveRequests = 0;
|
||||
await page.routeWebSocket(daemonWsRoutePattern(), (browser) => {
|
||||
const server = browser.connectToServer();
|
||||
browser.onMessage((message) => {
|
||||
const request = typeof message === "string" ? parseSessionEnvelope(message)?.message : null;
|
||||
if (
|
||||
request?.type === "archive_workspace_request" &&
|
||||
request.workspaceId === worktree.workspaceId
|
||||
) {
|
||||
archiveRequests += 1;
|
||||
}
|
||||
if (
|
||||
armed &&
|
||||
!held &&
|
||||
request?.type === "checkout_status_request" &&
|
||||
request.cwd === directory
|
||||
request.cwd === worktree.workspaceDirectory
|
||||
) {
|
||||
held = () => server.send(message);
|
||||
return;
|
||||
@@ -236,6 +259,7 @@ async function holdCheckoutStatusRequest(page: Page, directory: string) {
|
||||
armed = true;
|
||||
},
|
||||
waitForHeld: () => expect.poll(() => held !== null).toBe(true),
|
||||
archiveRequests: () => archiveRequests,
|
||||
release: () => {
|
||||
if (!held) throw new Error("No checkout status request is held");
|
||||
held();
|
||||
@@ -388,7 +412,7 @@ test.describe("Workspace archive risk warning for worktree backing", () => {
|
||||
): Promise<string> {
|
||||
const serverId = getServerId();
|
||||
const worktree = await createWorktree(slug);
|
||||
const statusRequest = await holdCheckoutStatusRequest(page, worktree.workspaceDirectory);
|
||||
const statusRequest = await holdCheckoutStatusRequest(page, worktree);
|
||||
await openSidebarRow(page, worktree.workspaceId);
|
||||
await workspaceRow(page, worktree.workspaceId).click();
|
||||
await expectAppRoute(page, buildHostWorkspaceRoute(serverId, worktree.workspaceId));
|
||||
@@ -432,6 +456,82 @@ test.describe("Workspace archive risk warning for worktree backing", () => {
|
||||
await expectAppRoute(page, openedRoute);
|
||||
});
|
||||
|
||||
async function openWorktreeWithCheckoutHeld(page: Page, slug: string) {
|
||||
const worktree = await createWorktree(slug);
|
||||
const statusRequest = await holdCheckoutStatusRequest(page, worktree);
|
||||
// Opening the workspace can start a checkout read that the archive reuses.
|
||||
statusRequest.arm();
|
||||
await openSidebarRow(page, worktree.workspaceId);
|
||||
await workspaceRow(page, worktree.workspaceId).click();
|
||||
await expectAppRoute(page, buildHostWorkspaceRoute(getServerId(), worktree.workspaceId));
|
||||
return { worktree, statusRequest };
|
||||
}
|
||||
|
||||
test("the archive shortcut works in another workspace while a checkout check is pending", async ({
|
||||
page,
|
||||
}) => {
|
||||
const { worktree, statusRequest } = await openWorktreeWithCheckoutHeld(
|
||||
page,
|
||||
"archive-risk-switch-shortcut",
|
||||
);
|
||||
|
||||
await pressArchiveShortcut(page);
|
||||
await statusRequest.waitForHeld();
|
||||
try {
|
||||
const otherWorkspaceId = worktree.project.workspaceId;
|
||||
await workspaceRow(page, otherWorkspaceId).click();
|
||||
await expectAppRoute(page, buildHostWorkspaceRoute(getServerId(), otherWorkspaceId));
|
||||
|
||||
await pressArchiveShortcut(page);
|
||||
await expect.poll(() => hostListsWorkspace(otherWorkspaceId)).toBe(false);
|
||||
} finally {
|
||||
statusRequest.release();
|
||||
}
|
||||
await expect.poll(() => hostListsWorkspace(worktree.workspaceId)).toBe(false);
|
||||
});
|
||||
|
||||
test("the row button and shortcut send one archive for the same worktree", async ({ page }) => {
|
||||
const { worktree, statusRequest } = await openWorktreeWithCheckoutHeld(
|
||||
page,
|
||||
"archive-risk-repeat-shortcut",
|
||||
);
|
||||
|
||||
await clickRowArchiveButton(page, worktree.workspaceId);
|
||||
await statusRequest.waitForHeld();
|
||||
try {
|
||||
await pressArchiveShortcut(page);
|
||||
} finally {
|
||||
statusRequest.release();
|
||||
}
|
||||
|
||||
await expect.poll(() => hostListsWorkspace(worktree.workspaceId)).toBe(false);
|
||||
expect(statusRequest.archiveRequests()).toBe(1);
|
||||
});
|
||||
|
||||
test("keeps the newly opened workspace after a theme change during an archive check", async ({
|
||||
page,
|
||||
}) => {
|
||||
const { worktree, statusRequest } = await openWorktreeWithCheckoutHeld(
|
||||
page,
|
||||
"archive-risk-theme",
|
||||
);
|
||||
|
||||
await pressArchiveShortcut(page);
|
||||
await statusRequest.waitForHeld();
|
||||
const otherWorkspaceId = worktree.project.workspaceId;
|
||||
const otherRoute = buildHostWorkspaceRoute(getServerId(), otherWorkspaceId);
|
||||
try {
|
||||
await cycleThemeAndWaitForSidebar(page, otherWorkspaceId);
|
||||
await workspaceRow(page, otherWorkspaceId).click();
|
||||
await expectAppRoute(page, otherRoute);
|
||||
} finally {
|
||||
statusRequest.release();
|
||||
}
|
||||
|
||||
await expect.poll(() => hostListsWorkspace(worktree.workspaceId)).toBe(false);
|
||||
await expectAppRoute(page, otherRoute);
|
||||
});
|
||||
|
||||
test("archiving the open worktree from its git actions leaves it for a new workspace", async ({
|
||||
page,
|
||||
}) => {
|
||||
|
||||
@@ -54,6 +54,7 @@ import { WindowSidebarMenuToggle } from "@/components/headers/sidebar-menu-toggl
|
||||
import { DesktopWindowControls } from "@/components/desktop/window-controls";
|
||||
import { SidebarModelProvider } from "@/components/sidebar/sidebar-model";
|
||||
import { WorkspacePinShortcutHandler } from "@/components/workspace-pin-shortcut-handler";
|
||||
import { WorkspaceArchiveShortcutHandler } from "@/components/workspace-archive-shortcut-handler";
|
||||
import { WorkspaceRenameHost } from "@/components/workspace-rename-host";
|
||||
import { WorkspaceArchiveUndoShortcutHost } from "@/workspace/archive-undo";
|
||||
import { WorkspaceExplorerOpenGesture } from "@/mobile-panels/explorer-open-gesture";
|
||||
@@ -537,6 +538,7 @@ function AppContainer({ children, chromeEnabled: chromeEnabledOverride }: AppCon
|
||||
<View style={layoutStyles.surfaceFill}>
|
||||
{workspaceChrome}
|
||||
<AddHostFlowHost />
|
||||
<WorkspaceArchiveShortcutHandler />
|
||||
<AppearanceStyleBoundary>
|
||||
{!isCompactLayout && appChromeLayout.sidebarToggleOwner === "window" ? (
|
||||
<WindowChromeRegion corners="top-left">
|
||||
|
||||
@@ -128,7 +128,6 @@ import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip
|
||||
import { Shortcut } from "@/components/ui/shortcut";
|
||||
import type { ShortcutKey } from "@/utils/format-shortcut";
|
||||
import { useShortcutKeys } from "@/hooks/use-shortcut-keys";
|
||||
import { useKeyboardActionHandler } from "@/hooks/use-keyboard-action-handler";
|
||||
import { useWorkspaceReadState } from "@/hooks/use-workspace-read-state";
|
||||
import type { PrHint } from "@/git/use-pr-status-query";
|
||||
import {
|
||||
@@ -1298,17 +1297,6 @@ function WorkspaceRowWithMenu({
|
||||
});
|
||||
}, [markUnread, toast]);
|
||||
|
||||
useKeyboardActionHandler({
|
||||
handlerId: `workspace-archive-${workspace.workspaceKey}`,
|
||||
actions: ["workspace.archive"],
|
||||
enabled: selected && !isArchiving,
|
||||
priority: 0,
|
||||
handle: () => {
|
||||
handleArchive();
|
||||
return true;
|
||||
},
|
||||
});
|
||||
|
||||
return (
|
||||
<>
|
||||
<WorkspaceRowInner
|
||||
|
||||
@@ -42,7 +42,6 @@ import { redirectIfArchivingActiveWorkspace } from "@/utils/sidebar-workspace-ar
|
||||
import { useWorkspaceArchive } from "@/workspace/use-workspace-archive";
|
||||
import type { ShortcutKey } from "@/utils/format-shortcut";
|
||||
import { useShortcutKeys } from "@/hooks/use-shortcut-keys";
|
||||
import { useKeyboardActionHandler } from "@/hooks/use-keyboard-action-handler";
|
||||
import { useWorkspaceReadState } from "@/hooks/use-workspace-read-state";
|
||||
import {
|
||||
SidebarWorkspaceRowFrame,
|
||||
@@ -702,17 +701,6 @@ function StatusWorkspaceRowWithMenu({
|
||||
});
|
||||
}, [markUnread, toast]);
|
||||
|
||||
useKeyboardActionHandler({
|
||||
handlerId: `workspace-archive-${workspace.workspaceKey}`,
|
||||
actions: ["workspace.archive"],
|
||||
enabled: selected && !isArchiving,
|
||||
priority: 0,
|
||||
handle: () => {
|
||||
handleArchive();
|
||||
return true;
|
||||
},
|
||||
});
|
||||
|
||||
return (
|
||||
<>
|
||||
<StatusWorkspaceRowInner
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
import { useGlobalWorkspaceArchiveAction } from "@/hooks/use-global-workspace-archive-action";
|
||||
|
||||
// Headless host for the archive shortcut, kept out of the root layout for the same reason as
|
||||
// WorkspacePinShortcutHandler: the hook subscribes to the active workspace's fields.
|
||||
export function WorkspaceArchiveShortcutHandler() {
|
||||
useGlobalWorkspaceArchiveAction();
|
||||
return null;
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
import { useCallback } from "react";
|
||||
import { useKeyboardActionHandler } from "@/hooks/use-keyboard-action-handler";
|
||||
import type { KeyboardActionId } from "@/keyboard/keyboard-action-dispatcher";
|
||||
import { useActiveWorkspaceSelection } from "@/stores/navigation-active-workspace-store";
|
||||
import { useWorkspaceFields } from "@/stores/session-store-hooks";
|
||||
import { redirectIfArchivingActiveWorkspace } from "@/utils/sidebar-workspace-archive-redirect";
|
||||
import { useWorkspaceArchive } from "@/workspace/use-workspace-archive";
|
||||
import { isWorkspaceListed, type WorkspaceArchiveTarget } from "@/workspace/workspace-archive";
|
||||
|
||||
const WORKSPACE_ARCHIVE_ACTIONS: readonly KeyboardActionId[] = ["workspace.archive"];
|
||||
|
||||
// The archive shortcut used to live on the sidebar row, so it did nothing whenever the row was not
|
||||
// rendered — a collapsed project or status group, a collapsed Pinned section, or focus mode. Like
|
||||
// the pin shortcut (see use-global-workspace-pin-action.ts), it is one registration keyed on the
|
||||
// active route selection.
|
||||
export function useGlobalWorkspaceArchiveAction() {
|
||||
const selection = useActiveWorkspaceSelection();
|
||||
const serverId = selection?.serverId ?? null;
|
||||
const routeWorkspaceId = selection?.workspaceId ?? null;
|
||||
// `id` is the descriptor id, not the route id; see use-global-workspace-pin-action.ts.
|
||||
const fields = useWorkspaceFields(serverId, routeWorkspaceId, (workspace) => ({
|
||||
id: workspace.id,
|
||||
workspaceKind: workspace.workspaceKind,
|
||||
workspaceDirectory: workspace.workspaceDirectory,
|
||||
name: workspace.name,
|
||||
archivingAt: workspace.archivingAt,
|
||||
diffStat: workspace.diffStat,
|
||||
}));
|
||||
|
||||
// useWorkspaceArchive calls the latest render's callback, so `activeWorkspaceId` is whatever is
|
||||
// routed when the archive starts, after any confirmation. It is the descriptor id, which is what
|
||||
// the redirect compares against.
|
||||
const activeWorkspaceId = fields?.id ?? null;
|
||||
const redirectAfterArchive = useCallback(
|
||||
(workspace: WorkspaceArchiveTarget) => {
|
||||
redirectIfArchivingActiveWorkspace({
|
||||
...workspace,
|
||||
activeWorkspaceSelection:
|
||||
serverId && activeWorkspaceId ? { serverId, workspaceId: activeWorkspaceId } : null,
|
||||
});
|
||||
},
|
||||
[activeWorkspaceId, serverId],
|
||||
);
|
||||
|
||||
const archiveController = useWorkspaceArchive({
|
||||
serverId: serverId ?? "",
|
||||
workspaceId: fields?.id ?? "",
|
||||
workspaceKind: fields?.workspaceKind ?? "directory",
|
||||
workspaceDirectory: fields?.workspaceDirectory ?? "",
|
||||
name: fields?.name ?? "",
|
||||
diffStat: fields?.diffStat,
|
||||
onArchiveStarted: redirectAfterArchive,
|
||||
});
|
||||
|
||||
const canArchive = fields !== null && fields.archivingAt === null;
|
||||
|
||||
const handle = useCallback(() => {
|
||||
if (!canArchive || !serverId) {
|
||||
return false;
|
||||
}
|
||||
// Archiving hides its target immediately. Read the store in case the shortcut
|
||||
// runs again before React renders that update.
|
||||
if (!isWorkspaceListed({ serverId, workspaceId: fields.id })) {
|
||||
return false;
|
||||
}
|
||||
archiveController.archive();
|
||||
return true;
|
||||
}, [archiveController, canArchive, fields, serverId]);
|
||||
|
||||
useKeyboardActionHandler({
|
||||
handlerId: "workspace-archive-global",
|
||||
actions: WORKSPACE_ARCHIVE_ACTIONS,
|
||||
enabled: canArchive,
|
||||
priority: 0,
|
||||
handle,
|
||||
});
|
||||
}
|
||||
@@ -10,7 +10,10 @@ import type {
|
||||
DaemonClient,
|
||||
WorkspaceLabelListPayload,
|
||||
} from "@getpaseo/client/internal/daemon-client";
|
||||
import type { SessionOutboundMessage } from "@getpaseo/protocol/messages";
|
||||
import type {
|
||||
SessionOutboundMessage,
|
||||
WorkspaceDescriptorPayload,
|
||||
} from "@getpaseo/protocol/messages";
|
||||
import {
|
||||
normalizeProjectDescriptor,
|
||||
normalizeWorkspaceDescriptor,
|
||||
@@ -1667,6 +1670,187 @@ it("fills every cached workspace beneath live updates received during the SQLite
|
||||
database.close();
|
||||
});
|
||||
|
||||
/**
|
||||
* A host whose cache was damaged before the eviction fix: workspaces survived, project rows did not,
|
||||
* and a version 1 checkpoint still claims the project directory is current. The daemon holds
|
||||
* projects A and B; renaming A is its update at `renameSeq`.
|
||||
*/
|
||||
async function createDamagedLegacyProjectDirectory(serverId: string, renameSeq: number) {
|
||||
serverIds.add(serverId);
|
||||
const { cache, database, storage, reopen, holdRead } = createSqliteCache();
|
||||
cache.setHosts([serverId]);
|
||||
const workspacePayload = (id: string, projectId: string): WorkspaceDescriptorPayload => ({
|
||||
id,
|
||||
projectId,
|
||||
projectDisplayName: projectId,
|
||||
projectRootPath: `/repo/${projectId}`,
|
||||
workspaceDirectory: `/repo/${projectId}`,
|
||||
projectKind: "git",
|
||||
workspaceKind: "local_checkout",
|
||||
name: id,
|
||||
status: "done",
|
||||
statusEnteredAt: null,
|
||||
activityAt: null,
|
||||
archivingAt: null,
|
||||
diffStat: null,
|
||||
scripts: [],
|
||||
});
|
||||
const project = (projectId: string, projectDisplayName: string) => ({
|
||||
projectId,
|
||||
projectDisplayName,
|
||||
projectRootPath: `/repo/${projectId}`,
|
||||
projectKind: "git" as const,
|
||||
});
|
||||
const workspaceEntries = [workspacePayload("wa", "A"), workspacePayload("wb", "B")];
|
||||
cache.replaceDirectoryBaseline(serverId, {
|
||||
agents: new Map(),
|
||||
workspaces: new Map(
|
||||
workspaceEntries.map((entry) => [entry.id, normalizeWorkspaceDescriptor(entry)]),
|
||||
),
|
||||
projects: new Map(),
|
||||
});
|
||||
await cache.flush();
|
||||
await storage.apply({
|
||||
deletes: [],
|
||||
upserts: [
|
||||
{
|
||||
serverId,
|
||||
kind: "checkpoint",
|
||||
id: "singleton",
|
||||
payload: JSON.stringify({
|
||||
version: 1,
|
||||
cursors: { projects: { generation: "g", afterSeq: renameSeq - 1 } },
|
||||
}),
|
||||
},
|
||||
],
|
||||
});
|
||||
const reopened = reopen();
|
||||
reopened.setHosts([serverId]);
|
||||
const client = new FakeDirectoryClient();
|
||||
let failNextProjectRequest = false;
|
||||
client.listProjects = async (options?: unknown): Promise<ProjectListResult> => {
|
||||
client.lastProjectOptions = options;
|
||||
if (failNextProjectRequest) {
|
||||
failNextProjectRequest = false;
|
||||
throw new Error("Request timed out");
|
||||
}
|
||||
const resumesAfterRename =
|
||||
(options as { sync?: { afterSeq?: number } } | undefined)?.sync?.afterSeq === renameSeq;
|
||||
return resumesAfterRename
|
||||
? {
|
||||
requestId: "projects",
|
||||
projects: [],
|
||||
sync: { generation: "g", headSeq: renameSeq, mode: "changes", removals: [] },
|
||||
}
|
||||
: {
|
||||
requestId: "projects",
|
||||
projects: [project("A", "Renamed"), project("B", "B")],
|
||||
sync: { generation: "g", headSeq: renameSeq, mode: "snapshot", removals: [] },
|
||||
};
|
||||
};
|
||||
client.fetchWorkspaces = async (): Promise<WorkspaceFetchResult> => ({
|
||||
requestId: "workspaces",
|
||||
entries: workspaceEntries,
|
||||
emptyProjects: [],
|
||||
pageInfo: { hasMore: false, nextCursor: null, prevCursor: null },
|
||||
sync: { generation: "g", headSeq: 2, mode: "snapshot", removals: [] },
|
||||
});
|
||||
const directory = new DirectorySync(
|
||||
serverId,
|
||||
{
|
||||
onAgentStoppedRunning: () => {},
|
||||
markAgentLoading: () => {},
|
||||
markAgentReady: () => {},
|
||||
markAgentError: () => {},
|
||||
},
|
||||
reopened,
|
||||
);
|
||||
const store = useSessionStore.getState();
|
||||
store.initializeSession(serverId, client as unknown as DaemonClient, 1);
|
||||
store.updateSessionServerInfo(serverId, {
|
||||
serverId,
|
||||
hostname: null,
|
||||
version: "test",
|
||||
features: { workspaceMultiplicity: true, directorySync: true, projectList: true },
|
||||
});
|
||||
directory.connectionChanged({
|
||||
client: client as unknown as DaemonClient,
|
||||
status: "online",
|
||||
source: { clientGeneration: 1, connectionEpoch: 1 },
|
||||
});
|
||||
return {
|
||||
client,
|
||||
directory,
|
||||
holdRead,
|
||||
failNextProjectRequest: () => {
|
||||
failNextProjectRequest = true;
|
||||
},
|
||||
renameProjectA: () =>
|
||||
client.emit({
|
||||
type: "project.update",
|
||||
payload: {
|
||||
kind: "upsert",
|
||||
project: project("A", "Renamed"),
|
||||
generation: "g",
|
||||
seq: renameSeq,
|
||||
},
|
||||
}),
|
||||
sessionProjectIds: () =>
|
||||
[...useSessionStore.getState().sessions[serverId].projects.keys()].sort(),
|
||||
persistedProjectIds: async () => {
|
||||
await reopened.flush();
|
||||
const restarted = reopen();
|
||||
restarted.setHosts([serverId]);
|
||||
return [...(await restarted.readDirectory(serverId)).projects.keys()].sort();
|
||||
},
|
||||
close: async () => {
|
||||
directory.dispose();
|
||||
await reopened.flush();
|
||||
database.close();
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
it("re-syncs every project when a project update lands while an untrusted cache loads", async () => {
|
||||
const damaged = await createDamagedLegacyProjectDirectory("untrusted-checkpoint-race", 6);
|
||||
try {
|
||||
let renamed = false;
|
||||
damaged.holdRead(async () => {
|
||||
if (renamed) return;
|
||||
renamed = true;
|
||||
damaged.renameProjectA();
|
||||
});
|
||||
|
||||
damaged.directory.setDemand({}, true);
|
||||
await damaged.directory.refreshDemand();
|
||||
|
||||
expect(renamed).toBe(true);
|
||||
expect(damaged.client.lastProjectOptions).toEqual({ sync: {} });
|
||||
expect(damaged.sessionProjectIds()).toEqual(["A", "B"]);
|
||||
expect(await damaged.persistedProjectIds()).toEqual(["A", "B"]);
|
||||
} finally {
|
||||
await damaged.close();
|
||||
}
|
||||
});
|
||||
|
||||
it("re-syncs every project when a project update lands after the first sync fails", async () => {
|
||||
const damaged = await createDamagedLegacyProjectDirectory("failed-first-sync", 3);
|
||||
try {
|
||||
damaged.failNextProjectRequest();
|
||||
damaged.directory.setDemand({}, true);
|
||||
await expect(damaged.directory.refreshDemand()).rejects.toThrow("Request timed out");
|
||||
|
||||
damaged.renameProjectA();
|
||||
await damaged.directory.refreshDemand();
|
||||
|
||||
expect(damaged.client.lastProjectOptions).toEqual({ sync: {} });
|
||||
expect(damaged.sessionProjectIds()).toEqual(["A", "B"]);
|
||||
expect(await damaged.persistedProjectIds()).toEqual(["A", "B"]);
|
||||
} finally {
|
||||
await damaged.close();
|
||||
}
|
||||
});
|
||||
|
||||
function createWorkspaceLabelDirectory(serverId: string) {
|
||||
const { client, directory } = createDirectory(serverId, { workspaceLabels: true });
|
||||
const store = useSessionStore.getState();
|
||||
|
||||
@@ -288,7 +288,7 @@ export class DirectorySync {
|
||||
this.revision += 1;
|
||||
if (this.agentTransactions.record(source, delta)) return;
|
||||
this.agents.applyDelta(delta);
|
||||
this.noteLiveCursor("agents", delta);
|
||||
if (this.extendsRefreshedBaseline(source)) this.noteLiveCursor("agents", delta);
|
||||
this.persistCheckpoint();
|
||||
}
|
||||
|
||||
@@ -300,7 +300,7 @@ export class DirectorySync {
|
||||
this.workspaceRevision += 1;
|
||||
if (this.workspaceTransactions.record(source, delta)) return;
|
||||
this.applyWorkspaceDelta(delta);
|
||||
if (delta.kind !== "script_status")
|
||||
if (delta.kind !== "script_status" && this.extendsRefreshedBaseline(source))
|
||||
this.noteLiveCursor(
|
||||
"projectId" in delta || "project" in delta ? "projects" : "workspaces",
|
||||
delta,
|
||||
@@ -308,6 +308,20 @@ export class DirectorySync {
|
||||
this.persistCheckpoint();
|
||||
}
|
||||
|
||||
/**
|
||||
* A live event's sequence covers everything before it only when a refresh completed on the
|
||||
* subscriptions that delivered it. Before that (first sync still pending or failed) or after
|
||||
* they lapse, the client may have missed earlier changes, so the event updates rows but leaves
|
||||
* the cursor where the next refresh can still fetch what was missed.
|
||||
*/
|
||||
private extendsRefreshedBaseline(source: DirectorySourceToken): boolean {
|
||||
const refreshed = this.satisfiedDemandSource;
|
||||
return (
|
||||
refreshed?.clientGeneration === source.clientGeneration &&
|
||||
refreshed.connectionEpoch === source.connectionEpoch
|
||||
);
|
||||
}
|
||||
|
||||
private observeDirectoryEvents(): void {
|
||||
if (this.eventSubscription) return;
|
||||
const { client, source } = this.requireOnline();
|
||||
@@ -566,24 +580,16 @@ export class DirectorySync {
|
||||
input: { subscribe?: boolean } | undefined,
|
||||
loadDirectoryCache: boolean,
|
||||
): Promise<void> {
|
||||
if (loadDirectoryCache) await this.loadCachedDirectory();
|
||||
if (loadDirectoryCache) {
|
||||
this.primeWorkspaceTransactionForCacheLoad();
|
||||
await this.loadCachedDirectory();
|
||||
}
|
||||
const onlineConnection = this.getOnlineConnection();
|
||||
if (!onlineConnection) return;
|
||||
const { client, source } = onlineConnection;
|
||||
const transaction = this.workspaceTransactions.begin(source, () => {
|
||||
const baseline = this.workspaces.snapshot();
|
||||
return {
|
||||
workspaces: new Map(baseline.workspaces),
|
||||
projects: new Map(baseline.projects),
|
||||
// Cache hydration can advance the live replica while these requests await responses.
|
||||
// Every page must use the cursors belonging to the maps captured here.
|
||||
requestCursors: { ...this.cursors },
|
||||
syncCursors: {},
|
||||
syncModes: {},
|
||||
touchedWorkspaceIds: new Set(),
|
||||
touchedProjectIds: new Set(),
|
||||
};
|
||||
});
|
||||
const transaction = this.workspaceTransactions.begin(source, () =>
|
||||
this.createWorkspaceRefreshSnapshot(),
|
||||
);
|
||||
try {
|
||||
await this.waitForSessionMetadata(client, source);
|
||||
const serverInfo = useSessionStore.getState().sessions[this.serverId]?.serverInfo;
|
||||
@@ -807,6 +813,31 @@ export class DirectorySync {
|
||||
}));
|
||||
}
|
||||
|
||||
// Updates that arrive before a refresh completes have no trusted baseline to advance from.
|
||||
// Holding them keeps their cursor out of the cache until the refresh they are applied over.
|
||||
private primeWorkspaceTransactionForCacheLoad(): void {
|
||||
const connection = this.getOnlineConnection();
|
||||
if (!connection) return;
|
||||
this.workspaceTransactions.begin(connection.source, () =>
|
||||
this.createWorkspaceRefreshSnapshot(),
|
||||
);
|
||||
}
|
||||
|
||||
private createWorkspaceRefreshSnapshot(): WorkspaceRefreshSnapshot {
|
||||
const baseline = this.workspaces.snapshot();
|
||||
return {
|
||||
workspaces: new Map(baseline.workspaces),
|
||||
projects: new Map(baseline.projects),
|
||||
// Cache hydration can advance the live replica while these requests await responses.
|
||||
// Every page must use the cursors belonging to the maps captured here.
|
||||
requestCursors: { ...this.cursors },
|
||||
syncCursors: {},
|
||||
syncModes: {},
|
||||
touchedWorkspaceIds: new Set(),
|
||||
touchedProjectIds: new Set(),
|
||||
};
|
||||
}
|
||||
|
||||
private supportsDirectorySync(): boolean {
|
||||
return (
|
||||
useSessionStore.getState().sessions[this.serverId]?.serverInfo?.features?.directorySync ===
|
||||
|
||||
@@ -37,6 +37,9 @@ class MemoryStorage implements ReplicaRowStore {
|
||||
onRead: (() => void) | null = null;
|
||||
/** Throws once a read goes past this count, so a non-terminating read loop fails the test. */
|
||||
readLimit: number | null = null;
|
||||
/** Awaited before the store lists every row or deletes a host, so a test can interleave there. */
|
||||
beforeReadAll: (() => Promise<void>) | null = null;
|
||||
beforeDeleteHost: (() => Promise<void>) | null = null;
|
||||
|
||||
private key(row: Pick<ReplicaRow, "serverId" | "kind" | "id">): string {
|
||||
return `${row.serverId}:${row.kind}:${row.id}`;
|
||||
@@ -68,6 +71,7 @@ class MemoryStorage implements ReplicaRowStore {
|
||||
}
|
||||
|
||||
async readAll(): Promise<ReplicaHostRows[]> {
|
||||
await this.beforeReadAll?.();
|
||||
const hosts = new Map<string, ReplicaRow[]>();
|
||||
for (const row of this.rows.values()) {
|
||||
const rows = hosts.get(row.serverId) ?? [];
|
||||
@@ -91,6 +95,7 @@ class MemoryStorage implements ReplicaRowStore {
|
||||
}
|
||||
|
||||
async deleteHost(serverId: string): Promise<void> {
|
||||
await this.beforeDeleteHost?.();
|
||||
for (const [key, row] of this.rows) if (row.serverId === serverId) this.rows.delete(key);
|
||||
}
|
||||
|
||||
@@ -436,40 +441,49 @@ describe("ReplicaCache", () => {
|
||||
await expectLegacyWorkspaceRefresh(cached);
|
||||
});
|
||||
|
||||
it("rejects pre-baseline-fix checkpoints without discarding cached rows or timelines", async () => {
|
||||
const storage = new MemoryStorage();
|
||||
const writer = createCache(storage);
|
||||
const baseline = directory();
|
||||
writer.replaceDirectoryBaseline(SERVER_ID, baseline);
|
||||
writer.commitTimeline(SERVER_ID, "agent-1", timeline());
|
||||
await writer.flush();
|
||||
await storage.apply({
|
||||
deletes: [],
|
||||
upserts: [
|
||||
{
|
||||
serverId: SERVER_ID,
|
||||
kind: "checkpoint",
|
||||
id: "singleton",
|
||||
payload: JSON.stringify(baseline.checkpoint),
|
||||
},
|
||||
],
|
||||
});
|
||||
it.each([
|
||||
["before the baseline fix", (checkpoint: DirectoryCheckpoint): unknown => checkpoint],
|
||||
[
|
||||
"before the eviction fix",
|
||||
(checkpoint: DirectoryCheckpoint): unknown => ({ version: 1, cursors: checkpoint }),
|
||||
],
|
||||
])(
|
||||
"rejects checkpoints written %s without discarding cached rows or timelines",
|
||||
async (_era, legacyPayload) => {
|
||||
const storage = new MemoryStorage();
|
||||
const writer = createCache(storage);
|
||||
const baseline = directory();
|
||||
writer.replaceDirectoryBaseline(SERVER_ID, baseline);
|
||||
writer.commitTimeline(SERVER_ID, "agent-1", timeline());
|
||||
await writer.flush();
|
||||
await storage.apply({
|
||||
deletes: [],
|
||||
upserts: [
|
||||
{
|
||||
serverId: SERVER_ID,
|
||||
kind: "checkpoint",
|
||||
id: "singleton",
|
||||
payload: JSON.stringify(legacyPayload(baseline.checkpoint)),
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
const reader = createCache(storage);
|
||||
const restored = await reader.readDirectory(SERVER_ID);
|
||||
expect(restored.checkpoint).toBeUndefined();
|
||||
expect([...restored.workspaces.keys()]).toEqual([...baseline.workspaces.keys()]);
|
||||
expect([...restored.projects.keys()]).toEqual([...baseline.projects.keys()]);
|
||||
expect([...restored.agents.keys()]).toEqual([...baseline.agents.keys()]);
|
||||
expect(await reader.readTimeline(SERVER_ID, "agent-1")).toEqual(timeline());
|
||||
expect(await storage.read(SERVER_ID, ["checkpoint"])).toEqual([]);
|
||||
const reader = createCache(storage);
|
||||
const restored = await reader.readDirectory(SERVER_ID);
|
||||
expect(restored.checkpoint).toBeUndefined();
|
||||
expect([...restored.workspaces.keys()]).toEqual([...baseline.workspaces.keys()]);
|
||||
expect([...restored.projects.keys()]).toEqual([...baseline.projects.keys()]);
|
||||
expect([...restored.agents.keys()]).toEqual([...baseline.agents.keys()]);
|
||||
expect(await reader.readTimeline(SERVER_ID, "agent-1")).toEqual(timeline());
|
||||
expect(await storage.read(SERVER_ID, ["checkpoint"])).toEqual([]);
|
||||
|
||||
reader.replaceDirectoryBaseline(SERVER_ID, baseline);
|
||||
await reader.flush();
|
||||
expect((await createCache(storage).readDirectory(SERVER_ID)).checkpoint).toEqual(
|
||||
baseline.checkpoint,
|
||||
);
|
||||
});
|
||||
reader.replaceDirectoryBaseline(SERVER_ID, baseline);
|
||||
await reader.flush();
|
||||
expect((await createCache(storage).readDirectory(SERVER_ID)).checkpoint).toEqual(
|
||||
baseline.checkpoint,
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
it("does nothing until an owner explicitly commits data", async () => {
|
||||
const storage = new MemoryStorage();
|
||||
@@ -1102,6 +1116,113 @@ describe("ReplicaCache", () => {
|
||||
).toEqual(["agent", "checkpoint", "project", "workspace"]);
|
||||
});
|
||||
|
||||
it.each(["beforeReadAll", "beforeDeleteHost"] as const)(
|
||||
"stores no checkpoint for a host evicted after its update was queued (%s)",
|
||||
async (pausePoint) => {
|
||||
const storage = new MemoryStorage();
|
||||
const previousSession = new ReplicaCache(storage, noLegacyCleanup);
|
||||
previousSession.setHosts([SERVER_ID, "other-host"]);
|
||||
previousSession.replaceDirectoryBaseline(SERVER_ID, directory());
|
||||
previousSession.replaceDirectoryBaseline("other-host", directory());
|
||||
await previousSession.flush();
|
||||
|
||||
const cache = new ReplicaCache(storage, { ...noLegacyCleanup, maxBytes: 8_192 });
|
||||
cache.setHosts([SERVER_ID, "other-host"]);
|
||||
const paused = deferred();
|
||||
const resume = deferred();
|
||||
storage[pausePoint] = async () => {
|
||||
storage[pausePoint] = null;
|
||||
paused.resolve();
|
||||
await resume.promise;
|
||||
};
|
||||
// Larger than the whole budget, so this persist evicts both hosts.
|
||||
cache.commitTimeline(SERVER_ID, "agent-1", timeline("x".repeat(16_384)));
|
||||
const eviction = cache.flush();
|
||||
await paused.promise;
|
||||
cache.commitDirectoryMutations(SERVER_ID, [], { agents: { generation: "g", afterSeq: 13 } });
|
||||
resume.resolve();
|
||||
await eviction;
|
||||
await cache.flush();
|
||||
|
||||
const restored = await createCache(storage).readDirectory(SERVER_ID);
|
||||
expect(restored.agents.size).toBe(0);
|
||||
expect(restored.checkpoint).toBeUndefined();
|
||||
},
|
||||
);
|
||||
|
||||
it("stores no checkpoint for a host evicted while a malformed row is repaired", async () => {
|
||||
const { storage } = await cacheWithoutBackgroundVisibility();
|
||||
const reader = createCache(storage, 8_192);
|
||||
storage.onRead = () => {
|
||||
if (!storage.reads.at(-1)?.kinds.includes("checkpoint")) return;
|
||||
storage.onRead = null;
|
||||
// Larger than the whole budget, so this persist evicts the host before the repair writes.
|
||||
reader.commitTimeline(SERVER_ID, "agent-1", timeline("x".repeat(16_384)));
|
||||
void reader.flush();
|
||||
};
|
||||
|
||||
expect(await reader.readWorkspace(SERVER_ID, "workspace-1")).toBeUndefined();
|
||||
await reader.flush();
|
||||
|
||||
const restored = await createCache(storage).readDirectory(SERVER_ID);
|
||||
expect(restored.projects.size).toBe(0);
|
||||
expect(restored.checkpoint).toBeUndefined();
|
||||
});
|
||||
|
||||
it("repairs a malformed row's cursor when the overlapping eviction fails", async () => {
|
||||
const { storage } = await cacheWithoutBackgroundVisibility();
|
||||
const reader = createCache(storage, 8_192);
|
||||
storage.onRead = () => {
|
||||
if (!storage.reads.at(-1)?.kinds.includes("checkpoint")) return;
|
||||
storage.onRead = null;
|
||||
storage.beforeDeleteHost = async () => {
|
||||
storage.beforeDeleteHost = null;
|
||||
throw new Error("Eviction aborted");
|
||||
};
|
||||
reader.commitTimeline(SERVER_ID, "agent-1", timeline("x".repeat(16_384)));
|
||||
void reader.flush();
|
||||
};
|
||||
|
||||
expect(await reader.readWorkspace(SERVER_ID, "workspace-1")).toBeUndefined();
|
||||
// A newer timeline fits the budget, so no later eviction clears the checkpoint.
|
||||
reader.commitTimeline(SERVER_ID, "agent-1", timeline());
|
||||
await reader.flush();
|
||||
|
||||
const restored = await createCache(storage).readDirectory(SERVER_ID);
|
||||
expect(restored.workspaces.size).toBe(0);
|
||||
expect(restored.checkpoint).toEqual({
|
||||
agents: { generation: "g", afterSeq: 12 },
|
||||
projects: { generation: "g", afterSeq: 4 },
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps an update queued behind the baseline that rebuilds an evicted host", async () => {
|
||||
const storage = new MemoryStorage();
|
||||
const cache = new ReplicaCache(storage, { ...noLegacyCleanup, maxBytes: 2_500 });
|
||||
cache.setHosts([SERVER_ID, "other-host"]);
|
||||
const baseline = directory();
|
||||
cache.replaceDirectoryBaseline(SERVER_ID, baseline);
|
||||
await cache.flush();
|
||||
cache.replaceDirectoryBaseline("other-host", baseline);
|
||||
await cache.flush();
|
||||
expect((await cache.readDirectory(SERVER_ID)).agents.size).toBe(0);
|
||||
|
||||
const renamed = { ...agent(), title: "Renamed agent" };
|
||||
cache.replaceDirectoryBaseline(SERVER_ID, baseline);
|
||||
cache.commitDirectoryMutations(
|
||||
SERVER_ID,
|
||||
[{ kind: "agent", type: "upsert", id: renamed.id, value: renamed }],
|
||||
{ agents: { generation: "g", afterSeq: 13 } },
|
||||
);
|
||||
await cache.flush();
|
||||
cache.commitDirectoryMutations(SERVER_ID, [], { agents: { generation: "g", afterSeq: 14 } });
|
||||
await cache.flush();
|
||||
|
||||
const restored = await createCache(storage).readDirectory(SERVER_ID);
|
||||
expect(restored.checkpoint).toEqual({ agents: { generation: "g", afterSeq: 14 } });
|
||||
expect(restored.agents.get(renamed.id)?.title).toBe("Renamed agent");
|
||||
});
|
||||
|
||||
it("runs legacy cleanup once when storage is first used", async () => {
|
||||
const storage = new MemoryStorage();
|
||||
const cache = new ReplicaCache(storage, {
|
||||
|
||||
@@ -397,15 +397,19 @@ const DirectoryCheckpointSchema = z.strictObject({
|
||||
agents: DirectoryCursorSchema.optional(),
|
||||
});
|
||||
|
||||
// Old checkpoints could describe a baseline that an overlapping refresh had discarded.
|
||||
// Revalidate directory contents once without evicting cached rows or timelines.
|
||||
// A checkpoint is trusted only when this version wrote it. Earlier writers could store one for a
|
||||
// directory the cache no longer held: unversioned ones after an overlapping refresh, version 1
|
||||
// after an eviction. Rejecting them revalidates directory contents once without evicting cached
|
||||
// rows or timelines.
|
||||
const DIRECTORY_CHECKPOINT_VERSION = 2;
|
||||
|
||||
const StoredDirectoryCheckpointSchema = z.strictObject({
|
||||
version: z.literal(1),
|
||||
version: z.literal(DIRECTORY_CHECKPOINT_VERSION),
|
||||
cursors: DirectoryCheckpointSchema,
|
||||
});
|
||||
|
||||
function serializeDirectoryCheckpoint(cursors: DirectoryCheckpoint) {
|
||||
return { version: 1 as const, cursors };
|
||||
return { version: DIRECTORY_CHECKPOINT_VERSION, cursors };
|
||||
}
|
||||
|
||||
function deserializeDirectoryCheckpoint(payload: string): DirectoryCheckpoint {
|
||||
@@ -968,6 +972,7 @@ export class ReplicaCache {
|
||||
private pendingUpserts = new Map<string, StructuredReplicaUpsert>();
|
||||
private pendingDeletes = new Map<string, ReplicaRowKey>();
|
||||
private pendingBaselines = new Set<string>();
|
||||
// Hosts whose stored directory was evicted. Only a baseline stores their directory again.
|
||||
private readonly invalidatedHosts = new Set<string>();
|
||||
private readonly maxBytes: number;
|
||||
private totalBytes = 0;
|
||||
@@ -1109,11 +1114,7 @@ export class ReplicaCache {
|
||||
private async deleteInvalidRow(row: ReplicaRow): Promise<void> {
|
||||
const invalidEntity = directoryEntityForRow(row);
|
||||
if (!invalidEntity) {
|
||||
const changes = { upserts: [], deletes: [row] } satisfies ReplicaRowChanges;
|
||||
await this.queueOperation(async () => {
|
||||
await this.rowStore.apply(changes);
|
||||
this.applyStoredChanges(changes);
|
||||
});
|
||||
await this.applyRepair(row.serverId, { upserts: [], deletes: [row] });
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -1144,10 +1145,7 @@ export class ReplicaCache {
|
||||
]
|
||||
: [],
|
||||
};
|
||||
await this.queueOperation(async () => {
|
||||
await this.rowStore.apply(changes);
|
||||
this.applyStoredChanges(changes);
|
||||
});
|
||||
await this.applyRepair(row.serverId, changes);
|
||||
}
|
||||
|
||||
private async repairInvalidDirectoryRows(
|
||||
@@ -1170,9 +1168,16 @@ export class ReplicaCache {
|
||||
]
|
||||
: [],
|
||||
};
|
||||
await this.queueOperation(async () => {
|
||||
await this.rowStore.apply(changes);
|
||||
this.applyStoredChanges(changes);
|
||||
await this.applyRepair(serverId, changes);
|
||||
}
|
||||
|
||||
// A repair is queued behind writes that can evict its host. If one did, the host has no
|
||||
// directory left for the repaired checkpoint to describe, so only the deletes still apply.
|
||||
private applyRepair(serverId: string, changes: ReplicaRowChanges): Promise<void> {
|
||||
return this.queueOperation(async () => {
|
||||
const applied = this.invalidatedHosts.has(serverId) ? { ...changes, upserts: [] } : changes;
|
||||
await this.rowStore.apply(applied);
|
||||
this.applyStoredChanges(applied);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1182,7 +1187,6 @@ export class ReplicaCache {
|
||||
checkpoint?: DirectoryCheckpoint,
|
||||
): void {
|
||||
if (!this.activeServerIds.has(serverId)) return;
|
||||
if (this.invalidatedHosts.has(serverId)) return;
|
||||
for (const mutation of mutations) {
|
||||
if (mutation.type === "delete") {
|
||||
this.queueEntityDelete(serverId, mutation.kind, mutation.id);
|
||||
@@ -1412,9 +1416,17 @@ export class ReplicaCache {
|
||||
}
|
||||
|
||||
private materializePendingChanges(pending: PendingReplicaChanges): ReplicaRowChanges {
|
||||
const deletes = new Map(pending.deletes.map((row) => [pendingRowKey(row), row]));
|
||||
// Decided here, inside the serialized write, because eviction happens there too. A mutation
|
||||
// queued before its host was evicted would otherwise store a checkpoint without its directory.
|
||||
const isStorable = (row: ReplicaRowKey): boolean =>
|
||||
row.kind === "timeline" ||
|
||||
!this.invalidatedHosts.has(row.serverId) ||
|
||||
pending.baselines.has(row.serverId);
|
||||
const deletes = new Map(
|
||||
pending.deletes.filter(isStorable).map((row) => [pendingRowKey(row), row]),
|
||||
);
|
||||
const upserts: ReplicaRow[] = [];
|
||||
for (const upsert of pending.upserts) {
|
||||
for (const upsert of pending.upserts.filter(isStorable)) {
|
||||
const row = this.materializeUpsert(upsert);
|
||||
if (row) upserts.push(row);
|
||||
else deletes.set(pendingRowKey(upsert), upsert);
|
||||
@@ -1563,8 +1575,10 @@ export class ReplicaCache {
|
||||
projectedTotal -= bytes;
|
||||
projectedBytes.delete(serverId);
|
||||
evicted.add(serverId);
|
||||
this.invalidatedHosts.add(serverId);
|
||||
if (this.storedRows.has(serverId)) await this.rowStore.deleteHost(serverId);
|
||||
// Only after the delete commits: a failed eviction leaves the rows stored, and writers that
|
||||
// check this set must keep their checkpoint in step with those rows.
|
||||
this.invalidatedHosts.add(serverId);
|
||||
this.removeStoredHost(serverId);
|
||||
}
|
||||
|
||||
|
||||
@@ -92,13 +92,14 @@ test("visible catch-up settles before hidden open chats start fetching", async (
|
||||
world.sync.dispose();
|
||||
});
|
||||
|
||||
test("a failed visible catch-up releases hidden chats without bypassing its error", async () => {
|
||||
test("a failed visible catch-up with a parked gap releases hidden chats without retrying", async () => {
|
||||
const world = new TimelineWorld();
|
||||
world.openedEarlier(["a-hidden"]);
|
||||
world.sync.replaceVisibleAgentIds("pane", ["z-visible"]);
|
||||
world.sync.setConnected(true);
|
||||
(await world.nextMembership()).succeed();
|
||||
const visible = await world.nextFetch("z-visible");
|
||||
world.sync.recoverGap("z-visible", { epoch: "epoch-z-visible", endSeq: 1 });
|
||||
world.expectNoPendingFetch();
|
||||
visible.fail("temporarily unavailable");
|
||||
const hidden = await world.nextFetch("a-hidden");
|
||||
@@ -127,6 +128,63 @@ test("switching chats promotes the newly visible catch-up while another visible
|
||||
world.sync.dispose();
|
||||
});
|
||||
|
||||
test("reconnect drains hidden chats two at a time after the visible chat settles", async () => {
|
||||
const world = new TimelineWorld();
|
||||
const hidden = Array.from({ length: 15 }, (_, index) => `hidden-${10 + index}`);
|
||||
world.openedEarlier(hidden);
|
||||
world.show("pane", ["visible"]);
|
||||
world.sync.setConnected(true);
|
||||
(await world.nextMembership()).succeed();
|
||||
const beforeDisconnect = await world.nextFetch("visible");
|
||||
world.sync.setConnected(false);
|
||||
beforeDisconnect.respond({ hasNewer: false });
|
||||
world.sync.setConnected(true);
|
||||
(await world.nextMembership()).succeed();
|
||||
const visible = await world.nextFetch("visible");
|
||||
world.expectNoPendingFetch();
|
||||
visible.respond({ hasNewer: false });
|
||||
const first = await world.nextFetch(hidden[0]);
|
||||
let current = await world.nextFetch(hidden[1]);
|
||||
world.expectNoPendingFetch();
|
||||
|
||||
first.fail("timeline request timed out");
|
||||
for (const agentId of hidden.slice(2)) {
|
||||
const next = await world.nextFetch(agentId);
|
||||
world.expectNoPendingFetch();
|
||||
current.respond({ hasNewer: false });
|
||||
current = next;
|
||||
}
|
||||
current.respond({ hasNewer: false });
|
||||
await vi.waitFor(() => {
|
||||
expect(world.sync.getAgentTimelineStatus(hidden[0])).toBe("error");
|
||||
for (const agentId of hidden.slice(1)) {
|
||||
expect(world.sync.getAgentTimelineStatus(agentId)).toBe("ready");
|
||||
}
|
||||
});
|
||||
world.expectNoPendingFetch();
|
||||
world.sync.dispose();
|
||||
});
|
||||
|
||||
test("focusing a queued chat starts it while both hidden catch-ups are running", async () => {
|
||||
const world = new TimelineWorld();
|
||||
world.openedEarlier(["hidden-a", "hidden-b", "next-visible"]);
|
||||
world.show("pane", ["visible"]);
|
||||
world.sync.setConnected(true);
|
||||
(await world.nextMembership()).succeed();
|
||||
(await world.nextFetch("visible")).respond({ hasNewer: false });
|
||||
const first = await world.nextFetch("hidden-a");
|
||||
const second = await world.nextFetch("hidden-b");
|
||||
world.expectNoPendingFetch();
|
||||
|
||||
world.show("pane", ["next-visible"]);
|
||||
expect(world.pendingFetchCount).toBe(1);
|
||||
(await world.nextFetch("next-visible")).respond({ hasNewer: false });
|
||||
await vi.waitFor(() => expect(world.sync.getAgentTimelineStatus("next-visible")).toBe("ready"));
|
||||
first.respond({ hasNewer: false });
|
||||
second.respond({ hasNewer: false });
|
||||
world.sync.dispose();
|
||||
});
|
||||
|
||||
class TimelineWorld {
|
||||
constructor(
|
||||
private readonly observeMembership?: ViewedTimelineSyncPorts["observe"],
|
||||
@@ -441,7 +499,7 @@ test("a gap absorbed by a running tail is recovered after the tail completes", a
|
||||
await vi.waitFor(() => expect(world.sync.getAgentTimelineStatus("agent-a")).toBe("ready"));
|
||||
});
|
||||
|
||||
test("a gap parked behind a running tail resumes after the rows that tail applied", async () => {
|
||||
test("a parked gap pages forward from the coverage established by the running tail", async () => {
|
||||
const world = new TimelineWorld();
|
||||
world.sync.setConnected(true);
|
||||
world.sync.replaceVisibleAgentIds("workspace", ["agent-a"]);
|
||||
@@ -460,7 +518,13 @@ test("a gap parked behind a running tail resumes after the rows that tail applie
|
||||
projection: "projected",
|
||||
wholeTurns: true,
|
||||
});
|
||||
recovery.respond({ hasNewer: false, seq: 7 });
|
||||
recovery.respond({ hasNewer: true, seq: 47 });
|
||||
const followUp = await world.nextFetch("agent-a");
|
||||
expect(followUp.request).toMatchObject({
|
||||
direction: "after",
|
||||
cursor: { epoch: "epoch-agent-a", seq: 47 },
|
||||
});
|
||||
followUp.respond({ hasNewer: false, seq: 55 });
|
||||
await vi.waitFor(() => expect(world.sync.getAgentTimelineStatus("agent-a")).toBe("ready"));
|
||||
world.sync.dispose();
|
||||
});
|
||||
@@ -941,14 +1005,51 @@ test("redeclaring unchanged visibility does not bypass catch-up error", async ()
|
||||
await world.nextError();
|
||||
|
||||
world.sync.replaceVisibleAgentIds("workspace", ["agent-a"]);
|
||||
world.sync.setActive(false);
|
||||
world.sync.setActive(true);
|
||||
|
||||
world.expectNoPendingMembership();
|
||||
world.expectNoPendingFetch();
|
||||
expect(world.sync.getAgentTimelineStatus("agent-a")).toBe("error");
|
||||
});
|
||||
|
||||
test.each(["refocusing", "foregrounding"])(
|
||||
"%s retries a timed-out visible timeline once",
|
||||
async (trigger) => {
|
||||
const world = new TimelineWorld();
|
||||
world.show("pane", ["agent-a"]);
|
||||
world.sync.setConnected(true);
|
||||
(await world.nextMembership()).succeed();
|
||||
(await world.nextFetch("agent-a")).fail("timeline request timed out");
|
||||
await world.nextError();
|
||||
expect(world.sync.getAgentTimelineStatus("agent-a")).toBe("error");
|
||||
|
||||
const revisit = () => {
|
||||
if (trigger === "refocusing") {
|
||||
world.show("pane", []);
|
||||
world.show("pane", ["agent-a"]);
|
||||
} else {
|
||||
world.sync.setActive(false);
|
||||
world.sync.setActive(true);
|
||||
}
|
||||
};
|
||||
revisit();
|
||||
expect(world.pendingFetchCount).toBe(1);
|
||||
expect(world.sync.getAgentTimelineStatus("agent-a")).toBe("pending");
|
||||
(await world.nextFetch("agent-a")).fail("timeline request timed out again");
|
||||
await vi.waitFor(() => expect(world.errors).toHaveLength(2));
|
||||
expect(world.sync.getAgentTimelineStatus("agent-a")).toBe("error");
|
||||
world.show("pane", ["agent-a"]);
|
||||
world.sync.setActive(true);
|
||||
world.expectNoPendingFetch();
|
||||
|
||||
revisit();
|
||||
(await world.nextFetch("agent-a")).respond({ hasNewer: false });
|
||||
await vi.waitFor(() => expect(world.sync.getAgentTimelineStatus("agent-a")).toBe("ready"));
|
||||
expect(world.sync.getAgentTimelineError("agent-a")).toBeNull();
|
||||
world.expectNoPendingMembership();
|
||||
world.sync.dispose();
|
||||
},
|
||||
);
|
||||
|
||||
test("a manual retry that fails returns to the error state", async () => {
|
||||
const world = new TimelineWorld();
|
||||
world.sync.setConnected(true);
|
||||
@@ -968,6 +1069,37 @@ test("a manual retry that fails returns to the error state", async () => {
|
||||
await vi.waitFor(() => expect(world.sync.getAgentTimelineStatus("agent-a")).toBe("error"));
|
||||
});
|
||||
|
||||
test("refocusing during a membership update retries a reconnect without replaying the backlog", async () => {
|
||||
const world = freshnessWorld();
|
||||
world.cursors.set("agent-a", { epoch: "epoch-agent-a", endSeq: 42 });
|
||||
world.show("pane", ["agent-a"]);
|
||||
world.sync.setConnected(true);
|
||||
(await world.nextMembership()).succeed({ "agent-a": "current" });
|
||||
await vi.waitFor(() => expect(world.sync.getAgentTimelineStatus("agent-a")).toBe("ready"));
|
||||
|
||||
world.sync.setConnected(false);
|
||||
world.sync.setConnected(true);
|
||||
(await world.nextMembership()).succeed({ "agent-a": "behind" });
|
||||
const failed = await world.nextFetch("agent-a");
|
||||
expect(failed.request.direction).toBe("after");
|
||||
failed.fail("timeline request timed out");
|
||||
await world.nextError();
|
||||
|
||||
world.show("pane", ["agent-b"]);
|
||||
const membership = await world.nextMembership();
|
||||
world.show("pane", ["agent-a"]);
|
||||
expect(world.pendingFetchCount).toBe(1);
|
||||
const retry = await world.nextFetch("agent-a");
|
||||
expect(retry.request).toEqual(failed.request);
|
||||
membership.succeed();
|
||||
retry.respond({ hasNewer: true, seq: 82 });
|
||||
const tail = await world.nextFetch("agent-a");
|
||||
expect(tail.request.direction).toBe("tail");
|
||||
tail.respond({ hasNewer: false });
|
||||
await vi.waitFor(() => expect(world.sync.getAgentTimelineStatus("agent-a")).toBe("ready"));
|
||||
world.sync.dispose();
|
||||
});
|
||||
|
||||
test("gap recovery supersedes completed catch-up and pages through the current tail", async () => {
|
||||
const world = new TimelineWorld();
|
||||
world.sync.setConnected(true);
|
||||
|
||||
@@ -545,12 +545,27 @@ export function createViewedTimelineOwner(input: {
|
||||
};
|
||||
}
|
||||
|
||||
const MAX_HIDDEN_CATCH_UPS = 2;
|
||||
|
||||
type CatchUpStatus = "running" | "complete" | "error";
|
||||
|
||||
interface CatchUpRequest {
|
||||
page: ProjectedTimelineForwardFetchPlan;
|
||||
kind: "resume" | "gap";
|
||||
}
|
||||
|
||||
interface CatchUpState {
|
||||
generation: number;
|
||||
status: CatchUpStatus;
|
||||
request?: ProjectedTimelineForwardFetchPlan;
|
||||
request?: CatchUpRequest;
|
||||
}
|
||||
|
||||
function planCatchUpRequest(
|
||||
request: CatchUpRequest | undefined,
|
||||
applied: { epoch: string; endSeq: number } | undefined,
|
||||
): CatchUpRequest {
|
||||
if (!request) return { page: planTimelineResumeFetch(applied), kind: "resume" };
|
||||
return { ...request, page: planTimelineCatchUpPastApplied(request.page, applied) };
|
||||
}
|
||||
|
||||
function isSameCatchUpRequest(
|
||||
@@ -573,11 +588,11 @@ function decideCatchUp(input: {
|
||||
if (input.supersede) {
|
||||
if (
|
||||
input.current.status === "running" &&
|
||||
isSameCatchUpRequest(input.current.request, input.request)
|
||||
isSameCatchUpRequest(input.current.request?.page, input.request)
|
||||
) {
|
||||
return "keep";
|
||||
}
|
||||
if (input.current.status === "running" && input.current.request?.direction === "tail") {
|
||||
if (input.current.status === "running" && input.current.request?.page.direction === "tail") {
|
||||
return "keep-and-park";
|
||||
}
|
||||
return "replace";
|
||||
@@ -597,9 +612,11 @@ export function createViewedTimelineSync(ports: ViewedTimelineSyncPorts): Viewed
|
||||
const sources = new Map<string, string[]>();
|
||||
const catchUps = new Map<string, CatchUpState>();
|
||||
const catchUpGenerations = new Map<string, number>();
|
||||
// Authoritative fetch owed but not runnable yet: disconnected, unacknowledged, or parked.
|
||||
// Fetches can outlive their catch-up generation when superseded or when a tab closes.
|
||||
const inFlightCatchUps = new Set<{ agentId: string }>();
|
||||
// Authoritative fetch owed but not runnable yet: disconnected, unacknowledged, or queued.
|
||||
// Membership acknowledgement and catch-up completion drain parked requests.
|
||||
const pendingCatchUps = new Map<string, ProjectedTimelineForwardFetchPlan>();
|
||||
const pendingCatchUps = new Map<string, CatchUpRequest>();
|
||||
const visibilityCatchUpPending = new Set<string>();
|
||||
const visibilityCatchUpErrors = new Map<string, string>();
|
||||
// A user-initiated retry owes a pending state until it settles.
|
||||
@@ -723,16 +740,16 @@ export function createViewedTimelineSync(ports: ViewedTimelineSyncPorts): Viewed
|
||||
const fetchUntilCurrent = async (
|
||||
agentId: string,
|
||||
generation: number,
|
||||
request: ProjectedTimelineForwardFetchPlan,
|
||||
request: CatchUpRequest,
|
||||
fallbackToLatestTailOnOverflow: boolean,
|
||||
): Promise<void> => {
|
||||
if (!ownsCatchUp(agentId, generation)) return;
|
||||
|
||||
try {
|
||||
const page = await ports.fetchPage(agentId, request);
|
||||
const page = await ports.fetchPage(agentId, request.page);
|
||||
if (!ownsCatchUp(agentId, generation)) return;
|
||||
if (page.hasNewer && page.endCursor) {
|
||||
if (fallbackToLatestTailOnOverflow) {
|
||||
if (request.page.direction === "after" && fallbackToLatestTailOnOverflow) {
|
||||
await ports.fetchLatestTail(agentId);
|
||||
if (!ownsCatchUp(agentId, generation)) return;
|
||||
catchUps.set(agentId, { generation, status: "complete" });
|
||||
@@ -742,10 +759,13 @@ export function createViewedTimelineSync(ports: ViewedTimelineSyncPorts): Viewed
|
||||
await fetchUntilCurrent(
|
||||
agentId,
|
||||
generation,
|
||||
planTimelineCatchUpPastApplied(
|
||||
planTimelineCatchUpAfter(page.endCursor),
|
||||
ports.readCursor(agentId),
|
||||
),
|
||||
{
|
||||
...request,
|
||||
page: planTimelineCatchUpPastApplied(
|
||||
planTimelineCatchUpAfter(page.endCursor),
|
||||
ports.readCursor(agentId),
|
||||
),
|
||||
},
|
||||
false,
|
||||
);
|
||||
return;
|
||||
@@ -754,20 +774,15 @@ export function createViewedTimelineSync(ports: ViewedTimelineSyncPorts): Viewed
|
||||
throw new Error(`Timeline page for ${agentId} hasNewer without an end cursor`);
|
||||
}
|
||||
catchUps.set(agentId, { generation, status: "complete" });
|
||||
const pendingCatchUp = pendingCatchUps.get(agentId);
|
||||
if (pendingCatchUp) {
|
||||
startCatchUp(agentId, { request: pendingCatchUp, supersede: true });
|
||||
return;
|
||||
}
|
||||
setVisibilityCatchUpReady(agentId);
|
||||
if (!pendingCatchUps.has(agentId)) setVisibilityCatchUpReady(agentId);
|
||||
} catch (error) {
|
||||
if (catchUps.get(agentId)?.generation === generation) {
|
||||
// The parked follow-up belongs to the failed attempt. A retry owns the next request.
|
||||
pendingCatchUps.delete(agentId);
|
||||
catchUps.set(agentId, { generation, status: "error", request });
|
||||
setVisibilityCatchUpError([agentId], error);
|
||||
ports.reportError(error);
|
||||
}
|
||||
} finally {
|
||||
startAcknowledgedCatchUps();
|
||||
}
|
||||
};
|
||||
|
||||
@@ -798,23 +813,29 @@ export function createViewedTimelineSync(ports: ViewedTimelineSyncPorts): Viewed
|
||||
);
|
||||
};
|
||||
|
||||
const hiddenCatchUpSlotsAreFull = (agentId: string) => {
|
||||
const visible = new Set(visibleAgentIds());
|
||||
if (visible.has(agentId)) return false;
|
||||
let hidden = 0;
|
||||
for (const attempt of inFlightCatchUps) {
|
||||
if (!visible.has(attempt.agentId)) hidden += 1;
|
||||
}
|
||||
return hidden >= MAX_HIDDEN_CATCH_UPS;
|
||||
};
|
||||
|
||||
const startCatchUp = (
|
||||
agentId: string,
|
||||
options: {
|
||||
request?: ProjectedTimelineForwardFetchPlan;
|
||||
request?: CatchUpRequest;
|
||||
supersede?: boolean;
|
||||
} = {},
|
||||
) => {
|
||||
const { request, supersede = false } = options;
|
||||
if (freshnessChecks.has(agentId)) {
|
||||
if (request) pendingCatchUps.set(agentId, request);
|
||||
return;
|
||||
}
|
||||
if (!canCatchUp(agentId)) {
|
||||
if (request) pendingCatchUps.set(agentId, request);
|
||||
return;
|
||||
}
|
||||
if (shouldWaitForVisibleCatchUp(agentId)) {
|
||||
if (
|
||||
freshnessChecks.has(agentId) ||
|
||||
!canCatchUp(agentId) ||
|
||||
shouldWaitForVisibleCatchUp(agentId)
|
||||
) {
|
||||
if (request) pendingCatchUps.set(agentId, request);
|
||||
return;
|
||||
}
|
||||
@@ -824,11 +845,9 @@ export function createViewedTimelineSync(ports: ViewedTimelineSyncPorts): Viewed
|
||||
return;
|
||||
}
|
||||
const applied = ports.readCursor(agentId);
|
||||
const nextRequest = request
|
||||
? planTimelineCatchUpPastApplied(request, applied)
|
||||
: planTimelineResumeFetch(applied);
|
||||
const nextRequest = planCatchUpRequest(request, applied);
|
||||
const current = catchUps.get(agentId);
|
||||
const decision = decideCatchUp({ current, request: nextRequest, supersede });
|
||||
const decision = decideCatchUp({ current, request: nextRequest.page, supersede });
|
||||
if (decision === "keep-and-park") {
|
||||
pendingCatchUps.set(agentId, nextRequest);
|
||||
return;
|
||||
@@ -836,18 +855,31 @@ export function createViewedTimelineSync(ports: ViewedTimelineSyncPorts): Viewed
|
||||
if (decision === "keep") {
|
||||
return;
|
||||
}
|
||||
if (hiddenCatchUpSlotsAreFull(agentId)) {
|
||||
if (request) pendingCatchUps.set(agentId, request);
|
||||
return;
|
||||
}
|
||||
const generation = (catchUpGenerations.get(agentId) ?? 0) + 1;
|
||||
catchUpGenerations.set(agentId, generation);
|
||||
catchUps.set(agentId, { generation, status: "running", request: nextRequest });
|
||||
pendingCatchUps.delete(agentId);
|
||||
// A gap recovery pages forward to keep the coverage it extends. Without coverage there is
|
||||
// nothing to keep, so an overflowing page falls back to the latest tail, as a resume does.
|
||||
const attempt = { agentId };
|
||||
inFlightCatchUps.add(attempt);
|
||||
if (current?.status === "error" && !manualRetries.has(agentId)) {
|
||||
visibilityCatchUpErrors.delete(agentId);
|
||||
markCatchUpOwed(agentId);
|
||||
notifyListeners();
|
||||
}
|
||||
// A queued gap uses the coverage available when its fetch starts.
|
||||
void fetchUntilCurrent(
|
||||
agentId,
|
||||
generation,
|
||||
nextRequest,
|
||||
nextRequest.direction === "after" && (request === undefined || applied === undefined),
|
||||
);
|
||||
nextRequest.kind === "resume" || !applied,
|
||||
).finally(() => {
|
||||
inFlightCatchUps.delete(attempt);
|
||||
startAcknowledgedCatchUps();
|
||||
});
|
||||
};
|
||||
|
||||
const startAcknowledgedCatchUps = () => {
|
||||
@@ -859,9 +891,8 @@ export function createViewedTimelineSync(ports: ViewedTimelineSyncPorts): Viewed
|
||||
for (const agentId of ordered) {
|
||||
const pendingCatchUp = pendingCatchUps.get(agentId);
|
||||
const current = catchUps.get(agentId);
|
||||
// Completion of a different chat must not bypass a failed chat's error or
|
||||
// supersede an in-flight tail that owns its parked gap recovery.
|
||||
if (current && !(current.status === "complete" && pendingCatchUp)) continue;
|
||||
// A running tail owns its parked gap. A failed catch-up can only have a queued retry.
|
||||
if (current?.status === "running" || (current && !pendingCatchUp)) continue;
|
||||
startCatchUp(agentId, {
|
||||
request: pendingCatchUp,
|
||||
supersede: Boolean(pendingCatchUp),
|
||||
@@ -869,6 +900,13 @@ export function createViewedTimelineSync(ports: ViewedTimelineSyncPorts): Viewed
|
||||
}
|
||||
};
|
||||
|
||||
const retryFailedCatchUp = (agentId: string) => {
|
||||
const catchUp = catchUps.get(agentId);
|
||||
if (catchUp?.status === "error") {
|
||||
startCatchUp(agentId, { request: catchUp.request, supersede: true });
|
||||
}
|
||||
};
|
||||
|
||||
const membershipIsSettled = (requested: string[]) =>
|
||||
!membershipNeedsRetry &&
|
||||
!freshnessCheckOwed &&
|
||||
@@ -975,9 +1013,7 @@ export function createViewedTimelineSync(ports: ViewedTimelineSyncPorts): Viewed
|
||||
void reconcileMembership();
|
||||
return;
|
||||
}
|
||||
if (catchUp?.status === "error") {
|
||||
startCatchUp(agentId, { request: catchUp.request, supersede: true });
|
||||
}
|
||||
retryFailedCatchUp(agentId);
|
||||
};
|
||||
|
||||
const commitDesiredMembership = (
|
||||
@@ -1068,11 +1104,17 @@ export function createViewedTimelineSync(ports: ViewedTimelineSyncPorts): Viewed
|
||||
publishVisibleMembership();
|
||||
},
|
||||
replaceVisibleAgentIds(sourceId, agentIds) {
|
||||
const previouslyVisible = new Set(visibleAgentIds());
|
||||
const normalized = normalizeAgentIds(agentIds);
|
||||
if (normalized.length === 0) sources.delete(sourceId);
|
||||
else sources.set(sourceId, normalized);
|
||||
rememberOpenedAgentIds(normalized);
|
||||
publishVisibleMembership();
|
||||
if (active) {
|
||||
for (const agentId of normalized) {
|
||||
if (!previouslyVisible.has(agentId)) retryFailedCatchUp(agentId);
|
||||
}
|
||||
}
|
||||
startAcknowledgedCatchUps();
|
||||
},
|
||||
setActive(nextActive) {
|
||||
@@ -1085,7 +1127,10 @@ export function createViewedTimelineSync(ports: ViewedTimelineSyncPorts): Viewed
|
||||
}
|
||||
const canCheck = connected && ports.canCheckFreshness();
|
||||
for (const agentId of visibleAgentIds()) {
|
||||
if (visibilityCatchUpErrors.has(agentId)) continue;
|
||||
if (visibilityCatchUpErrors.has(agentId)) {
|
||||
retryFailedCatchUp(agentId);
|
||||
continue;
|
||||
}
|
||||
markCatchUpOwed(agentId);
|
||||
if (
|
||||
canCheck &&
|
||||
@@ -1132,7 +1177,10 @@ export function createViewedTimelineSync(ports: ViewedTimelineSyncPorts): Viewed
|
||||
recoverGap(agentId, cursor) {
|
||||
if (!isDesired(agentId) || catchUps.get(agentId)?.status === "error") return;
|
||||
startCatchUp(agentId, {
|
||||
request: planTimelineCatchUpAfter({ epoch: cursor.epoch, seq: cursor.endSeq }),
|
||||
request: {
|
||||
page: planTimelineCatchUpAfter({ epoch: cursor.epoch, seq: cursor.endSeq }),
|
||||
kind: "gap",
|
||||
},
|
||||
supersede: true,
|
||||
});
|
||||
},
|
||||
|
||||
@@ -14,6 +14,7 @@ import { buildWorkspaceTabPersistenceKey } from "@/workspace-tabs/model";
|
||||
import { archiveWorkspaceWithUndo, supportsWorkspaceArchiveUndo } from "@/workspace/archive-undo";
|
||||
import {
|
||||
archiveWorkspaceOptimistically,
|
||||
runWorkspaceArchiveAttempt,
|
||||
type WorkspaceArchiveTarget,
|
||||
} from "@/workspace/workspace-archive";
|
||||
|
||||
@@ -56,7 +57,6 @@ export function useWorkspaceArchive(input: ArchiveWorkspaceInput): WorkspaceArch
|
||||
} = input;
|
||||
const { t } = useTranslation();
|
||||
const toast = useToast();
|
||||
const confirmingRef = useRef(false);
|
||||
// The archive starts after the host answers and you confirm. By then you may have opened another
|
||||
// workspace, so the redirect reads the selection from the latest render.
|
||||
const onArchiveStartedRef = useRef(onArchiveStarted);
|
||||
@@ -119,26 +119,12 @@ export function useWorkspaceArchive(input: ArchiveWorkspaceInput): WorkspaceArch
|
||||
}, [diffStat, name, serverId, t, toast, warningLabels, workspaceDirectory]);
|
||||
|
||||
const archive = useCallback(() => {
|
||||
// A second press while the host answers or the warning is open would ask twice.
|
||||
if (confirmingRef.current) {
|
||||
return;
|
||||
}
|
||||
void (async () => {
|
||||
if (workspaceKind === "worktree") {
|
||||
confirmingRef.current = true;
|
||||
let confirmed: boolean;
|
||||
try {
|
||||
confirmed = await confirmWorktreeArchive();
|
||||
} finally {
|
||||
confirmingRef.current = false;
|
||||
}
|
||||
if (!confirmed) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
await archiveWorkspaceRecord();
|
||||
})();
|
||||
}, [archiveWorkspaceRecord, confirmWorktreeArchive, workspaceKind]);
|
||||
void runWorkspaceArchiveAttempt({
|
||||
workspace: { serverId, workspaceId },
|
||||
confirm: workspaceKind === "worktree" ? confirmWorktreeArchive : undefined,
|
||||
archive: archiveWorkspaceRecord,
|
||||
});
|
||||
}, [archiveWorkspaceRecord, confirmWorktreeArchive, serverId, workspaceId, workspaceKind]);
|
||||
|
||||
return {
|
||||
archive,
|
||||
|
||||
@@ -17,6 +17,30 @@ export interface WorkspaceArchiveTarget {
|
||||
workspaceId: string;
|
||||
}
|
||||
|
||||
const pendingArchiveAttempts = new Set<string>();
|
||||
|
||||
/** Checks and starts one archive at a time for a workspace. */
|
||||
export async function runWorkspaceArchiveAttempt(input: {
|
||||
workspace: WorkspaceArchiveTarget;
|
||||
confirm?: () => Promise<boolean>;
|
||||
archive: () => Promise<void>;
|
||||
}): Promise<void> {
|
||||
const { serverId, workspaceId } = input.workspace;
|
||||
const key = JSON.stringify([serverId, workspaceId]);
|
||||
if (pendingArchiveAttempts.has(key)) return;
|
||||
|
||||
pendingArchiveAttempts.add(key);
|
||||
try {
|
||||
if (input.confirm && !(await input.confirm())) return;
|
||||
if (!isWorkspaceListed(input.workspace)) return;
|
||||
// Archive hides the row synchronously. Undo can restore it and start a new
|
||||
// archive while the previous daemon request is still settling.
|
||||
return input.archive();
|
||||
} finally {
|
||||
pendingArchiveAttempts.delete(key);
|
||||
}
|
||||
}
|
||||
|
||||
interface WorkspaceArchiveClient {
|
||||
archiveWorkspace: (workspaceId: string) => Promise<{ error: string | null; canceled?: boolean }>;
|
||||
}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { runCreateCommandWithDeps } from "./create.js";
|
||||
import { buildCreateWorktreeRequest, type WorktreeCreateOptions } from "./create-input.js";
|
||||
|
||||
const REPO = "/tmp/repo";
|
||||
@@ -77,3 +78,52 @@ 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`,
|
||||
});
|
||||
});
|
||||
|
||||
@@ -26,11 +26,22 @@ 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 connectToDaemon({ target: options.daemonTarget });
|
||||
const client = await deps.connectToDaemon({ target: options.daemonTarget });
|
||||
|
||||
try {
|
||||
const response = await client.createPaseoWorktree(request);
|
||||
|
||||
@@ -1623,6 +1623,106 @@ 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();
|
||||
|
||||
@@ -3188,6 +3188,9 @@ 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,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -3319,6 +3322,9 @@ 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,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -3841,7 +3847,9 @@ export class DaemonClient {
|
||||
type: "workspace.recovery.restore.request",
|
||||
workspaceId,
|
||||
},
|
||||
timeout: 150_000,
|
||||
// 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,
|
||||
});
|
||||
if (!payload.accepted) {
|
||||
throw new Error(payload.error ?? "Workspace recovery was rejected by the host");
|
||||
@@ -3857,8 +3865,9 @@ export class DaemonClient {
|
||||
type: "workspace.archive.undo.request",
|
||||
workspaceId,
|
||||
},
|
||||
// Undoing a finished worktree archive recreates the worktree, like recovery does.
|
||||
timeout: 150_000,
|
||||
// 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,
|
||||
});
|
||||
if (!payload.accepted) {
|
||||
throw new Error(payload.error ?? "The host could not undo the workspace archive");
|
||||
@@ -5439,6 +5448,9 @@ 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,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -5462,6 +5474,10 @@ 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,
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -589,3 +589,75 @@ 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([]);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -38,6 +38,7 @@ import {
|
||||
requireProviderCapabilities,
|
||||
type ProviderCatalog,
|
||||
type ProviderCapability,
|
||||
type ProviderCommand,
|
||||
type ProviderConfigState,
|
||||
type ProviderConnectRequest,
|
||||
type ProviderConnection,
|
||||
@@ -89,6 +90,9 @@ export async function createAcpProviderConnection(
|
||||
if (probe.agentCapabilities.loadSession) {
|
||||
supportedCapabilities.push("session.persistence");
|
||||
}
|
||||
if (options.acpOptions?.deferTurnOnRunningTools) {
|
||||
supportedCapabilities.push("prompt.steer");
|
||||
}
|
||||
await probe.close();
|
||||
const capabilities = negotiateProviderCapabilities(request.capabilities, supportedCapabilities);
|
||||
const listeners = new Set<(event: ProviderEvent) => void>();
|
||||
@@ -214,10 +218,13 @@ async function dispatch(input: ProviderInput, state: AcpConnectionState): Promis
|
||||
await mutateSession(session, () => session.runtime.prompt(input));
|
||||
return;
|
||||
}
|
||||
case "session.interrupt":
|
||||
await requireSession(state, input.sessionId).runtime.interrupt();
|
||||
case "session.interrupt": {
|
||||
const session = requireSession(state, input.sessionId);
|
||||
const retired = await session.runtime.interrupt();
|
||||
state.emit({ type: "request.completed", requestId: input.requestId });
|
||||
if (retired) retireSession(state, input.sessionId);
|
||||
return;
|
||||
}
|
||||
case "session.permission":
|
||||
requireSession(state, input.sessionId).runtime.respondToPermission(
|
||||
input.permissionId,
|
||||
@@ -304,6 +311,12 @@ async function listSessions(
|
||||
}
|
||||
}
|
||||
|
||||
function retireSession(state: AcpConnectionState, sessionId: string): void {
|
||||
if (state.sessions.delete(sessionId)) {
|
||||
state.emit({ type: "session.closed", sessionId });
|
||||
}
|
||||
}
|
||||
|
||||
async function openSession(
|
||||
input: Extract<ProviderInput, { type: "session.open" }>,
|
||||
state: AcpConnectionState,
|
||||
@@ -317,6 +330,7 @@ async function openSession(
|
||||
cwd: input.config.cwd,
|
||||
env: input.config.env,
|
||||
emit: state.emit,
|
||||
onRetired: () => retireSession(state, input.sessionId),
|
||||
});
|
||||
try {
|
||||
const capabilities = await runtime.open(input, state.capabilities);
|
||||
@@ -358,6 +372,7 @@ interface StartRuntimeOptions {
|
||||
cwd?: string;
|
||||
env: Readonly<Record<string, string>>;
|
||||
emit(event: ProviderEvent): void;
|
||||
onRetired?: () => void;
|
||||
}
|
||||
|
||||
interface PendingPermission {
|
||||
@@ -366,6 +381,33 @@ interface PendingPermission {
|
||||
resolve(response: RequestPermissionResponse): void;
|
||||
}
|
||||
|
||||
type DeferredTurnOutcome =
|
||||
| { type: "complete"; terminalizeTools: boolean }
|
||||
| { type: "cancel" }
|
||||
| { type: "fail"; error: { message: string } };
|
||||
|
||||
interface DeferredTurnState {
|
||||
timer: ReturnType<typeof setTimeout> | null;
|
||||
resolve(outcome: DeferredTurnOutcome): void;
|
||||
}
|
||||
|
||||
type DeferredReplyState = "idle" | "open" | "settled_with_open_tools" | "settled";
|
||||
|
||||
interface ActivePrompt {
|
||||
turnId: string;
|
||||
settled: Promise<void>;
|
||||
cancelling: boolean;
|
||||
wirePromptsInFlight: number;
|
||||
wirePromptLane: Promise<void>;
|
||||
lastPromptResponseWireSeq: number | null;
|
||||
crossedEndTurn: boolean;
|
||||
replyState: DeferredReplyState;
|
||||
deferred: DeferredTurnState | null;
|
||||
}
|
||||
|
||||
const DEFAULT_DEFERRED_SETTLE_DELAY_MS = 500;
|
||||
const DEFAULT_DEFERRED_QUIET_LIMIT_MS = 120_000;
|
||||
|
||||
class AcpRuntime {
|
||||
readonly connection: ClientSideConnection;
|
||||
agentCapabilities: AgentCapabilities = {};
|
||||
@@ -374,6 +416,8 @@ class AcpRuntime {
|
||||
private emit: (event: ProviderEvent) => void;
|
||||
private readonly messages = new Map<string, string>();
|
||||
private readonly toolCalls = new Map<string, AcpToolCallSnapshot>();
|
||||
private readonly liveOpenToolIds = new Set<string>();
|
||||
private readonly canceledToolCallIds = new Set<string>();
|
||||
// Running tool rows published by transformers; the turn's terminal closes any left open.
|
||||
private readonly vendorToolCalls = new Map<string, ToolCallTimelineItem>();
|
||||
private readonly pendingCompactions = new Set<string>();
|
||||
@@ -401,21 +445,33 @@ class AcpRuntime {
|
||||
private replayWindow: "replay" | "skip" | null = null;
|
||||
private lastLoadUpdateAt = 0;
|
||||
private closing = false;
|
||||
private closePromise: Promise<void> | null = null;
|
||||
private deferredRetirement: Promise<boolean> | null = null;
|
||||
private deferredFinalized = false;
|
||||
private processFailed = false;
|
||||
private configTransaction = false;
|
||||
private stagedTransformerConfig: ProviderConfigState | null = null;
|
||||
private readonly closeConnector: () => Promise<void>;
|
||||
private readonly closeConnector: (options?: {
|
||||
force?: boolean;
|
||||
timeoutMs?: number;
|
||||
}) => Promise<void>;
|
||||
private readonly whenConnectorClosed: () => Promise<void> | null;
|
||||
private notificationLane: Promise<void> = Promise.resolve();
|
||||
private incomingWireSeq = 0;
|
||||
private readonly sessionUpdateWireSeqs: number[] = [];
|
||||
private autoAccept = false;
|
||||
private activePrompt: { turnId: string; settled: Promise<void>; cancelling: boolean } | null =
|
||||
null;
|
||||
private activePrompt: ActivePrompt | null = null;
|
||||
private lastUsage: ProviderUsage = {};
|
||||
|
||||
static async start(options: StartRuntimeOptions): Promise<AcpRuntime> {
|
||||
let child: ChildProcessWithoutNullStreams | null = null;
|
||||
let spawnFailure: Promise<never> | null = null;
|
||||
let stream: Stream;
|
||||
let closeConnector = async () => {};
|
||||
let closeConnector: (options?: {
|
||||
force?: boolean;
|
||||
timeoutMs?: number;
|
||||
}) => Promise<void> = async () => {};
|
||||
let whenConnectorClosed: () => Promise<void> | null = () => null;
|
||||
if (options.options.command) {
|
||||
// COMPAT(pluginProviderLaunch): added in v0.10.0, remove after 2027-03-29 once plugin host floor >= v0.10.0.
|
||||
// Standalone callers and older hosts do not send a daemon-resolved launch.
|
||||
@@ -438,8 +494,9 @@ class AcpRuntime {
|
||||
const owned = ownConnectorStream(await options.options.connector());
|
||||
stream = owned.stream;
|
||||
closeConnector = owned.close;
|
||||
whenConnectorClosed = owned.whenClosed;
|
||||
}
|
||||
const runtime = new AcpRuntime(stream, child, closeConnector, options);
|
||||
const runtime = new AcpRuntime(stream, child, closeConnector, whenConnectorClosed, options);
|
||||
try {
|
||||
const initialize = withTimeout(
|
||||
runtime.call(
|
||||
@@ -466,41 +523,51 @@ class AcpRuntime {
|
||||
private constructor(
|
||||
stream: Stream,
|
||||
child: ChildProcessWithoutNullStreams | null,
|
||||
closeConnector: () => Promise<void>,
|
||||
closeConnector: (options?: { force?: boolean; timeoutMs?: number }) => Promise<void>,
|
||||
whenConnectorClosed: () => Promise<void> | null,
|
||||
private readonly options: StartRuntimeOptions,
|
||||
) {
|
||||
this.child = child;
|
||||
this.closeConnector = closeConnector;
|
||||
this.whenConnectorClosed = whenConnectorClosed;
|
||||
this.emit = options.emit;
|
||||
this.transformers = options.options.transformers ?? [];
|
||||
const client: Client = {
|
||||
requestPermission: (request) => this.requestPermission(request),
|
||||
sessionUpdate: (notification) =>
|
||||
this.enqueueNotification(() => this.sessionUpdate(notification)),
|
||||
sessionUpdate: (notification) => {
|
||||
const wireSeq = this.sessionUpdateWireSeqs.shift() ?? ++this.incomingWireSeq;
|
||||
return this.enqueueNotification(() => this.sessionUpdate(notification, wireSeq));
|
||||
},
|
||||
};
|
||||
this.connection = new ClientSideConnection(
|
||||
() => client,
|
||||
routeVendorNotifications(stream, (method, params) => this.vendorNotification(method, params)),
|
||||
routeIncomingMessages(
|
||||
stream,
|
||||
(method, params) => this.vendorNotification(method, params),
|
||||
(message) => this.observeWireMessage(message),
|
||||
),
|
||||
);
|
||||
if (!child) void this.connection.closed.then(() => this.handleUnexpectedTransportClose());
|
||||
child?.on("error", (error) => {
|
||||
const message = describeError(error);
|
||||
this.processFailed = true;
|
||||
this.settlePendingWork();
|
||||
this.settlePendingWork(message);
|
||||
if (this.closing || !this.nativeSessionId) return;
|
||||
this.emit({
|
||||
type: "session.runtime_failed",
|
||||
sessionId: this.options.boundarySessionId,
|
||||
error: { message: describeError(error) },
|
||||
error: { message },
|
||||
});
|
||||
});
|
||||
child?.once("close", (code, signal) => {
|
||||
if (this.closing || this.processFailed || !this.nativeSessionId) return;
|
||||
const message = `ACP process exited (${signal ?? code ?? "unknown"})`;
|
||||
this.processFailed = true;
|
||||
this.settlePendingWork();
|
||||
this.settlePendingWork(message);
|
||||
this.emit({
|
||||
type: "session.runtime_failed",
|
||||
sessionId: this.options.boundarySessionId,
|
||||
error: { message: `ACP process exited (${signal ?? code ?? "unknown"})` },
|
||||
error: { message },
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -609,10 +676,31 @@ class AcpRuntime {
|
||||
}
|
||||
|
||||
async prompt(input: Extract<ProviderInput, { type: "session.prompt" }>): Promise<void> {
|
||||
if (this.closing || this.processFailed || this.deferredRetirement) {
|
||||
throw new Error("ACP session is closed");
|
||||
}
|
||||
if (input.prompt.delivery === "steer") {
|
||||
this.steerDeferredPrompt(input);
|
||||
return;
|
||||
}
|
||||
const active = this.activePrompt;
|
||||
if (active) {
|
||||
await this.interrupt();
|
||||
if (active.deferred && active.wirePromptsInFlight === 0) {
|
||||
// Wire session/prompt already resolved; finish the deferred turn without sending
|
||||
// session/cancel so running background tools stay alive into the follow-up turn.
|
||||
this.finishDeferredTurn(active, { type: "complete", terminalizeTools: false });
|
||||
} else {
|
||||
const retired = await this.interrupt();
|
||||
if (retired) {
|
||||
// Notify caller that the session closed before failing the replacement prompt.
|
||||
this.options.onRetired?.();
|
||||
throw new Error("ACP session retired after stopping deferred background work");
|
||||
}
|
||||
}
|
||||
await active.settled;
|
||||
if (this.closing || this.processFailed || this.deferredRetirement) {
|
||||
throw new Error("ACP session is closed");
|
||||
}
|
||||
}
|
||||
const prompt = toAcpPrompt(input.prompt);
|
||||
this.replayWindow = null;
|
||||
@@ -643,6 +731,17 @@ class AcpRuntime {
|
||||
turnId,
|
||||
state: "started",
|
||||
});
|
||||
const activePrompt: ActivePrompt = {
|
||||
turnId,
|
||||
settled: Promise.resolve(),
|
||||
cancelling: false,
|
||||
wirePromptsInFlight: 1,
|
||||
wirePromptLane: Promise.resolve(),
|
||||
lastPromptResponseWireSeq: null,
|
||||
crossedEndTurn: false,
|
||||
replyState: "idle",
|
||||
deferred: null,
|
||||
};
|
||||
// The SDK dispatches notifications without awaiting them, so the prompt response can resolve
|
||||
// while earlier session updates are still queued. Apply them before the turn ends.
|
||||
const settled = this.call(
|
||||
@@ -650,6 +749,7 @@ class AcpRuntime {
|
||||
).then(
|
||||
async (response): Promise<void> => {
|
||||
await this.drainNotifications();
|
||||
activePrompt.wirePromptsInFlight -= 1;
|
||||
if (response.usage) {
|
||||
this.lastUsage = {
|
||||
...this.lastUsage,
|
||||
@@ -665,47 +765,95 @@ class AcpRuntime {
|
||||
});
|
||||
}
|
||||
const state = response.stopReason === "cancelled" ? "canceled" : "completed";
|
||||
this.fallbackChunkIds.clear();
|
||||
this.terminalizeTransientItems(state);
|
||||
this.finishTurnPermissions(turnId);
|
||||
this.emit({
|
||||
type: "session.turn",
|
||||
sessionId: this.options.boundarySessionId,
|
||||
turnId,
|
||||
state,
|
||||
});
|
||||
if (response.stopReason === "end_turn" && this.shouldDeferTurn(activePrompt)) {
|
||||
await this.settleDeferredPrompt(activePrompt);
|
||||
return undefined;
|
||||
}
|
||||
this.finishPromptTurn(turnId, state);
|
||||
return undefined;
|
||||
},
|
||||
async (error): Promise<void> => {
|
||||
await this.drainNotifications();
|
||||
this.fallbackChunkIds.clear();
|
||||
this.terminalizeTransientItems("failed");
|
||||
this.finishTurnPermissions(turnId);
|
||||
this.emit({
|
||||
type: "session.turn",
|
||||
sessionId: this.options.boundarySessionId,
|
||||
turnId,
|
||||
state: "failed",
|
||||
error: { message: describeError(error) },
|
||||
});
|
||||
activePrompt.wirePromptsInFlight -= 1;
|
||||
this.finishPromptTurn(turnId, "failed", { message: describeError(error) });
|
||||
return undefined;
|
||||
},
|
||||
);
|
||||
this.activePrompt = { turnId, settled, cancelling: false };
|
||||
activePrompt.settled = settled;
|
||||
this.activePrompt = activePrompt;
|
||||
void settled.finally(() => {
|
||||
if (this.activePrompt?.turnId === turnId) this.activePrompt = null;
|
||||
});
|
||||
}
|
||||
|
||||
async interrupt(): Promise<void> {
|
||||
async interrupt(): Promise<boolean> {
|
||||
if (this.deferredRetirement) return this.deferredRetirement;
|
||||
const active = this.activePrompt;
|
||||
const deferredTurnId = active?.deferred ? active.turnId : null;
|
||||
if (active && deferredTurnId) {
|
||||
const retirement = this.retireDeferredTurn(active, deferredTurnId).catch((error) => {
|
||||
if (this.deferredRetirement === retirement) this.deferredRetirement = null;
|
||||
throw error;
|
||||
});
|
||||
this.deferredRetirement = retirement;
|
||||
return retirement;
|
||||
}
|
||||
if (active) active.cancelling = true;
|
||||
try {
|
||||
await this.call(this.connection.cancel({ sessionId: this.nativeSessionId }));
|
||||
} finally {
|
||||
// An agent may wait for its outstanding permission replies before ending the prompt.
|
||||
if (active) this.finishTurnPermissions(active.turnId);
|
||||
if (active) {
|
||||
this.finishTurnPermissions(active.turnId);
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private finalizeDeferredTurn(deferredTurnId: string, emitRetired: boolean): void {
|
||||
if (this.deferredFinalized) return;
|
||||
this.deferredFinalized = true;
|
||||
this.finishPromptTurn(deferredTurnId, "canceled", undefined, {
|
||||
suppressTrailingToolEcho: true,
|
||||
});
|
||||
if (emitRetired) this.options.onRetired?.();
|
||||
}
|
||||
|
||||
private async retireDeferredTurn(active: ActivePrompt, deferredTurnId: string): Promise<boolean> {
|
||||
active.cancelling = true;
|
||||
// Record open tools owned by Stop before writing session/cancel so any failure
|
||||
// update arriving during cancel preserves their canceled state.
|
||||
for (const id of this.liveOpenToolIds) this.canceledToolCallIds.add(id);
|
||||
let cancelTimedOut = false;
|
||||
if (!this.closing) {
|
||||
try {
|
||||
await withTimeout(
|
||||
this.call(this.connection.cancel({ sessionId: this.nativeSessionId })),
|
||||
1_000,
|
||||
`ACP session ${this.nativeSessionId} did not accept cancel`,
|
||||
);
|
||||
} catch {
|
||||
cancelTimedOut = true;
|
||||
} finally {
|
||||
// An agent may wait for its outstanding permission replies before ending the prompt.
|
||||
this.finishTurnPermissions(active.turnId);
|
||||
}
|
||||
}
|
||||
// ACP v1 has no response or end boundary for session/cancel once session/prompt
|
||||
// already returned. Close the process first while the turn still appears running,
|
||||
// then emit the canceled turn synchronously before request.completed and session.closed
|
||||
// so queued work and config changes immediately observe the retired session.
|
||||
try {
|
||||
await this.close({ force: cancelTimedOut, timeoutMs: 1_000 });
|
||||
} catch (error) {
|
||||
void this.whenConnectorClosed()?.then(
|
||||
() => this.finalizeDeferredTurn(deferredTurnId, true),
|
||||
() => undefined,
|
||||
);
|
||||
throw error;
|
||||
}
|
||||
this.finalizeDeferredTurn(deferredTurnId, false);
|
||||
return true;
|
||||
}
|
||||
|
||||
listSessions(cwd?: string) {
|
||||
@@ -758,6 +906,7 @@ class AcpRuntime {
|
||||
sessionId: this.options.boundarySessionId,
|
||||
permissionId,
|
||||
});
|
||||
if (this.activePrompt?.deferred) this.scheduleDeferredSettle();
|
||||
}
|
||||
|
||||
async configure(
|
||||
@@ -833,11 +982,20 @@ class AcpRuntime {
|
||||
await this.close();
|
||||
}
|
||||
|
||||
async close(): Promise<void> {
|
||||
if (this.closing) return;
|
||||
close(options?: { force?: boolean; timeoutMs?: number }): Promise<void> {
|
||||
if (this.closePromise) return this.closePromise;
|
||||
this.closing = true;
|
||||
const promise = this.closeInternal(options).catch((error) => {
|
||||
if (this.closePromise === promise) this.closePromise = null;
|
||||
throw error;
|
||||
});
|
||||
this.closePromise = promise;
|
||||
return promise;
|
||||
}
|
||||
|
||||
private async closeInternal(options?: { force?: boolean; timeoutMs?: number }): Promise<void> {
|
||||
this.settlePendingWork();
|
||||
await this.closeConnector();
|
||||
await this.closeConnector(options);
|
||||
const child = this.child;
|
||||
if (!child || this.processFailed) return;
|
||||
if (child.exitCode !== null || child.signalCode !== null) return;
|
||||
@@ -1066,6 +1224,7 @@ class AcpRuntime {
|
||||
const permissionId = `permission:${request.toolCall.toolCallId}`;
|
||||
return new Promise((resolve) => {
|
||||
this.permissions.set(permissionId, { request, resolve, turnId: this.activePrompt?.turnId });
|
||||
if (this.activePrompt?.deferred) this.scheduleDeferredSettle();
|
||||
this.emit({
|
||||
type: "session.permission",
|
||||
sessionId: this.options.boundarySessionId,
|
||||
@@ -1085,7 +1244,31 @@ class AcpRuntime {
|
||||
});
|
||||
}
|
||||
|
||||
private sessionUpdate(notification: SessionNotification): void {
|
||||
private observeWireMessage(message: unknown): void {
|
||||
if (typeof message !== "object" || message === null) return;
|
||||
const record = message as Record<string, unknown>;
|
||||
if (record.method === "session/update") {
|
||||
this.sessionUpdateWireSeqs.push(++this.incomingWireSeq);
|
||||
return;
|
||||
}
|
||||
if (
|
||||
!("method" in record) &&
|
||||
"id" in record &&
|
||||
typeof record.result === "object" &&
|
||||
record.result !== null &&
|
||||
typeof (record.result as Record<string, unknown>).stopReason === "string" &&
|
||||
this.activePrompt &&
|
||||
this.activePrompt.lastPromptResponseWireSeq === null
|
||||
) {
|
||||
this.activePrompt.lastPromptResponseWireSeq = ++this.incomingWireSeq;
|
||||
}
|
||||
}
|
||||
|
||||
private isPostWirePrompt(active: ActivePrompt, wireSeq: number): boolean {
|
||||
return active.lastPromptResponseWireSeq !== null && wireSeq > active.lastPromptResponseWireSeq;
|
||||
}
|
||||
|
||||
private sessionUpdate(notification: SessionNotification, wireSeq: number): void {
|
||||
if (notification.sessionId !== this.nativeSessionId) return;
|
||||
if (this.replayWindow) this.lastLoadUpdateAt = performance.now();
|
||||
if (this.replayWindow === "skip") {
|
||||
@@ -1096,7 +1279,7 @@ class AcpRuntime {
|
||||
update.sessionUpdate === "current_mode_update" ||
|
||||
update.sessionUpdate === "usage_update"
|
||||
) {
|
||||
this.reduceStateUpdate(update);
|
||||
this.reduceStateUpdate(update, wireSeq);
|
||||
}
|
||||
return;
|
||||
}
|
||||
@@ -1107,10 +1290,10 @@ class AcpRuntime {
|
||||
this.reduceUserMessageChunk(notification.update);
|
||||
return;
|
||||
}
|
||||
this.reduceUpdate(notification.update);
|
||||
this.reduceUpdate(notification.update, wireSeq);
|
||||
}
|
||||
|
||||
private reduceUpdate(update: SessionUpdate): void {
|
||||
private reduceUpdate(update: SessionUpdate, wireSeq: number): void {
|
||||
if (
|
||||
update.sessionUpdate === "agent_message_chunk" ||
|
||||
update.sessionUpdate === "agent_thought_chunk" ||
|
||||
@@ -1144,15 +1327,16 @@ class AcpRuntime {
|
||||
: {}),
|
||||
},
|
||||
});
|
||||
this.noteDeferredChunk(update.sessionUpdate, wireSeq);
|
||||
return;
|
||||
}
|
||||
if (update.sessionUpdate === "tool_call" || update.sessionUpdate === "tool_call_update") {
|
||||
if (update.sessionUpdate === "tool_call") this.fallbackChunkIds.clear();
|
||||
this.reduceToolCall(update);
|
||||
this.reduceToolCall(update, wireSeq);
|
||||
return;
|
||||
}
|
||||
if (update.sessionUpdate === "plan") this.fallbackChunkIds.clear();
|
||||
this.reduceStateUpdate(update);
|
||||
this.reduceStateUpdate(update, wireSeq);
|
||||
}
|
||||
|
||||
// Historical user messages arrive only as replayed chunks; a live prompt
|
||||
@@ -1196,7 +1380,7 @@ class AcpRuntime {
|
||||
return id;
|
||||
}
|
||||
|
||||
private reduceStateUpdate(update: SessionUpdate): void {
|
||||
private reduceStateUpdate(update: SessionUpdate, wireSeq: number): void {
|
||||
if (update.sessionUpdate === "plan") {
|
||||
this.emit({
|
||||
type: "timeline.item",
|
||||
@@ -1215,11 +1399,18 @@ class AcpRuntime {
|
||||
return;
|
||||
}
|
||||
if (update.sessionUpdate === "available_commands_update") {
|
||||
const commands = update.availableCommands.map((command) => ({
|
||||
name: command.name,
|
||||
description: command.description,
|
||||
argumentHint: command.input?.hint,
|
||||
}));
|
||||
const context = { sessionId: this.options.boundarySessionId };
|
||||
const commands = update.availableCommands.map((command) => {
|
||||
let entry: ProviderCommand = {
|
||||
name: command.name,
|
||||
description: command.description,
|
||||
argumentHint: command.input?.hint,
|
||||
};
|
||||
for (const transformer of this.transformers) {
|
||||
entry = transformer.command?.(entry, context) ?? entry;
|
||||
}
|
||||
return entry;
|
||||
});
|
||||
this.emit({ type: "session.commands", sessionId: this.options.boundarySessionId, commands });
|
||||
this.receivedInitialCommands = true;
|
||||
this.commandWaiter?.();
|
||||
@@ -1253,6 +1444,7 @@ class AcpRuntime {
|
||||
sessionId: this.options.boundarySessionId,
|
||||
usage: this.lastUsage,
|
||||
});
|
||||
this.noteDeferredUsageUpdate(wireSeq);
|
||||
return;
|
||||
}
|
||||
if (update.sessionUpdate === "compaction_update") {
|
||||
@@ -1267,12 +1459,20 @@ class AcpRuntime {
|
||||
status: update.status === "completed" ? "completed" : "loading",
|
||||
},
|
||||
});
|
||||
if (this.activePrompt?.deferred) this.scheduleDeferredSettle();
|
||||
}
|
||||
}
|
||||
|
||||
private terminalizeTransientItems(state: "completed" | "failed" | "canceled"): void {
|
||||
private terminalizeTransientItems(
|
||||
state: "completed" | "failed" | "canceled",
|
||||
options?: { preserveQualifyingOpenTools?: boolean; suppressTrailingToolEcho?: boolean },
|
||||
): void {
|
||||
const preserve = options?.preserveQualifyingOpenTools === true;
|
||||
for (const [id, snapshot] of this.toolCalls) {
|
||||
if (snapshot.status !== "pending" && snapshot.status !== "in_progress") continue;
|
||||
if (preserve && this.liveOpenToolIds.has(id) && this.toolKeepsTurnOpen(snapshot)) continue;
|
||||
this.liveOpenToolIds.delete(id);
|
||||
if (options?.suppressTrailingToolEcho) this.canceledToolCallIds.add(id);
|
||||
const completed: AcpToolCallSnapshot = {
|
||||
...snapshot,
|
||||
status: state === "completed" ? "completed" : "failed",
|
||||
@@ -1302,18 +1502,42 @@ class AcpRuntime {
|
||||
this.pendingCompactions.clear();
|
||||
}
|
||||
|
||||
private reduceToolCall(update: ToolCall | ToolCallUpdate): void {
|
||||
private reduceToolCall(
|
||||
update: Extract<SessionUpdate, { sessionUpdate: "tool_call" | "tool_call_update" }>,
|
||||
wireSeq: number,
|
||||
): void {
|
||||
if (
|
||||
update.sessionUpdate === "tool_call_update" &&
|
||||
this.canceledToolCallIds.has(update.toolCallId)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
if (update.sessionUpdate === "tool_call") {
|
||||
this.canceledToolCallIds.delete(update.toolCallId);
|
||||
}
|
||||
const current = this.toolCalls.get(update.toolCallId);
|
||||
const wasOpenQualifying =
|
||||
current !== undefined &&
|
||||
this.liveOpenToolIds.has(current.id) &&
|
||||
this.toolKeepsTurnOpen(current);
|
||||
let snapshot = mergeToolCallSnapshot(update, current);
|
||||
const context = { sessionId: this.options.boundarySessionId };
|
||||
for (const transformer of this.transformers)
|
||||
snapshot = transformer.toolCall?.(snapshot, context) ?? snapshot;
|
||||
this.toolCalls.set(snapshot.id, snapshot);
|
||||
const isOpen = snapshot.status === "pending" || snapshot.status === "in_progress";
|
||||
if (this.replayWindow === null) {
|
||||
if (isOpen) this.liveOpenToolIds.add(snapshot.id);
|
||||
else this.liveOpenToolIds.delete(snapshot.id);
|
||||
}
|
||||
this.emit({
|
||||
type: "timeline.item",
|
||||
sessionId: this.options.boundarySessionId,
|
||||
item: toolTimelineItem(snapshot),
|
||||
});
|
||||
const isOpenQualifying =
|
||||
this.liveOpenToolIds.has(snapshot.id) && this.toolKeepsTurnOpen(snapshot);
|
||||
this.noteDeferredToolTransition(wasOpenQualifying, isOpenQualifying, isOpen, snapshot, wireSeq);
|
||||
}
|
||||
|
||||
private vendorNotification(method: string, params: unknown): void {
|
||||
@@ -1376,25 +1600,306 @@ class AcpRuntime {
|
||||
|
||||
private handleUnexpectedTransportClose(): void {
|
||||
if (this.closing || this.processFailed) return;
|
||||
const message = "ACP transport closed unexpectedly";
|
||||
this.processFailed = true;
|
||||
this.settlePendingWork();
|
||||
this.settlePendingWork(message);
|
||||
if (!this.nativeSessionId) return;
|
||||
this.emit({
|
||||
type: "session.runtime_failed",
|
||||
sessionId: this.options.boundarySessionId,
|
||||
error: { message: "ACP transport closed unexpectedly" },
|
||||
error: { message },
|
||||
});
|
||||
}
|
||||
|
||||
private settlePendingWork(): void {
|
||||
private settlePendingWork(failureMessage?: string): void {
|
||||
for (const permission of this.permissions.values()) {
|
||||
permission.resolve({ outcome: { outcome: "cancelled" } });
|
||||
}
|
||||
this.permissions.clear();
|
||||
if (this.activePrompt?.deferred) {
|
||||
this.finishDeferredTurn(
|
||||
this.activePrompt,
|
||||
failureMessage ? { type: "fail", error: { message: failureMessage } } : { type: "cancel" },
|
||||
);
|
||||
}
|
||||
this.commandWaiter?.();
|
||||
this.commandWaiter = null;
|
||||
}
|
||||
|
||||
private finishPromptTurn(
|
||||
turnId: string,
|
||||
state: "completed" | "failed" | "canceled",
|
||||
error?: { message: string },
|
||||
options?: { preserveQualifyingOpenTools?: boolean; suppressTrailingToolEcho?: boolean },
|
||||
): void {
|
||||
this.fallbackChunkIds.clear();
|
||||
this.terminalizeTransientItems(state, options);
|
||||
this.finishTurnPermissions(turnId);
|
||||
if (state === "failed") {
|
||||
this.emit({
|
||||
type: "session.turn",
|
||||
sessionId: this.options.boundarySessionId,
|
||||
turnId,
|
||||
state,
|
||||
error: error ?? { message: "ACP turn failed" },
|
||||
});
|
||||
return;
|
||||
}
|
||||
this.emit({
|
||||
type: "session.turn",
|
||||
sessionId: this.options.boundarySessionId,
|
||||
turnId,
|
||||
state,
|
||||
});
|
||||
}
|
||||
|
||||
private steerDeferredPrompt(input: Extract<ProviderInput, { type: "session.prompt" }>): void {
|
||||
const active = this.activePrompt;
|
||||
const deferred = active?.deferred;
|
||||
if (!active || !deferred || active.cancelling || this.closing || this.processFailed) {
|
||||
this.emit({
|
||||
type: "session.prompt_result",
|
||||
sessionId: this.options.boundarySessionId,
|
||||
clientMessageId: input.prompt.clientMessageId,
|
||||
result: {
|
||||
type: "failed",
|
||||
error: {
|
||||
message: "ACP session can only steer while waiting on deferred background tools",
|
||||
},
|
||||
},
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (input.prompt.clearPendingPermissions) {
|
||||
this.finishTurnPermissions(active.turnId);
|
||||
}
|
||||
const prompt = toAcpPrompt(input.prompt);
|
||||
active.wirePromptsInFlight += 1;
|
||||
this.scheduleDeferredSettle();
|
||||
this.replayWindow = null;
|
||||
this.fallbackChunkIds.clear();
|
||||
this.emit({
|
||||
type: "timeline.item",
|
||||
sessionId: this.options.boundarySessionId,
|
||||
item: {
|
||||
type: "user_message",
|
||||
id: input.prompt.clientMessageId,
|
||||
text: prompt
|
||||
.filter((part) => part.type === "text")
|
||||
.map((part) => part.text)
|
||||
.join("\n"),
|
||||
clientMessageId: input.prompt.clientMessageId,
|
||||
},
|
||||
});
|
||||
this.emit({
|
||||
type: "session.prompt_result",
|
||||
sessionId: this.options.boundarySessionId,
|
||||
clientMessageId: input.prompt.clientMessageId,
|
||||
result: { type: "steer", turnId: active.turnId },
|
||||
});
|
||||
const runSteer = async (): Promise<void> => {
|
||||
try {
|
||||
if (
|
||||
this.closing ||
|
||||
this.processFailed ||
|
||||
active.cancelling ||
|
||||
active.deferred !== deferred
|
||||
) {
|
||||
return;
|
||||
}
|
||||
this.fallbackChunkIds.clear();
|
||||
active.lastPromptResponseWireSeq = null;
|
||||
if (active.replyState === "settled_with_open_tools") active.replyState = "idle";
|
||||
const response = await this.call(
|
||||
this.connection.prompt({ sessionId: this.nativeSessionId, prompt }),
|
||||
);
|
||||
await this.drainNotifications();
|
||||
if (this.closing || this.deferredRetirement || active.deferred !== deferred) return;
|
||||
if (response.usage) {
|
||||
this.lastUsage = {
|
||||
...this.lastUsage,
|
||||
inputTokens: response.usage.inputTokens,
|
||||
outputTokens: response.usage.outputTokens,
|
||||
cachedInputTokens: response.usage.cachedReadTokens ?? undefined,
|
||||
};
|
||||
this.emit({
|
||||
type: "session.usage",
|
||||
sessionId: this.options.boundarySessionId,
|
||||
turnId: active.turnId,
|
||||
usage: this.lastUsage,
|
||||
});
|
||||
}
|
||||
if (response.stopReason === "cancelled") {
|
||||
this.finishDeferredTurn(active, { type: "cancel" });
|
||||
return;
|
||||
}
|
||||
if (response.stopReason !== "end_turn" && active.wirePromptsInFlight === 1) {
|
||||
this.finishDeferredTurn(active, { type: "complete", terminalizeTools: true });
|
||||
}
|
||||
} catch (error) {
|
||||
await this.drainNotifications();
|
||||
if (this.closing || this.deferredRetirement || active.deferred !== deferred) return;
|
||||
if (this.processFailed) {
|
||||
this.finishDeferredTurn(active, {
|
||||
type: "fail",
|
||||
error: { message: describeError(error) },
|
||||
});
|
||||
} else {
|
||||
this.emit({
|
||||
type: "session.notice",
|
||||
sessionId: this.options.boundarySessionId,
|
||||
notice: {
|
||||
id: `acp:steer-error:${input.prompt.clientMessageId}`,
|
||||
severity: "error",
|
||||
title: "Follow-up prompt failed",
|
||||
description: describeError(error),
|
||||
},
|
||||
});
|
||||
}
|
||||
} finally {
|
||||
if (active.lastPromptResponseWireSeq === null) {
|
||||
active.lastPromptResponseWireSeq = this.incomingWireSeq;
|
||||
}
|
||||
active.wirePromptsInFlight -= 1;
|
||||
this.scheduleDeferredSettle();
|
||||
}
|
||||
};
|
||||
active.wirePromptLane = active.wirePromptLane.then(runSteer);
|
||||
}
|
||||
|
||||
private async settleDeferredPrompt(active: ActivePrompt): Promise<void> {
|
||||
this.fallbackChunkIds.clear();
|
||||
const outcome = await new Promise<DeferredTurnOutcome>((resolve) => {
|
||||
active.deferred = { timer: null, resolve };
|
||||
this.scheduleDeferredSettle();
|
||||
});
|
||||
if (this.closing || this.deferredRetirement) return;
|
||||
if (outcome.type === "fail") {
|
||||
this.finishPromptTurn(active.turnId, "failed", outcome.error);
|
||||
return;
|
||||
}
|
||||
this.finishPromptTurn(
|
||||
active.turnId,
|
||||
outcome.type === "cancel" ? "canceled" : "completed",
|
||||
undefined,
|
||||
{
|
||||
preserveQualifyingOpenTools: outcome.type === "complete" && !outcome.terminalizeTools,
|
||||
suppressTrailingToolEcho: outcome.type === "cancel",
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
private toolKeepsTurnOpen(snapshot: AcpToolCallSnapshot): boolean {
|
||||
const defer = this.options.options.acpOptions?.deferTurnOnRunningTools;
|
||||
if (!defer) return false;
|
||||
return defer.keepsTurnOpen ? defer.keepsTurnOpen(snapshot) : true;
|
||||
}
|
||||
|
||||
private hasQualifyingOpenTools(): boolean {
|
||||
for (const id of this.liveOpenToolIds) {
|
||||
const snapshot = this.toolCalls.get(id);
|
||||
if (snapshot && this.toolKeepsTurnOpen(snapshot)) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private hasDeferredBlockers(): boolean {
|
||||
return (
|
||||
(this.activePrompt?.wirePromptsInFlight ?? 0) > 0 ||
|
||||
this.hasQualifyingOpenTools() ||
|
||||
this.permissions.size > 0 ||
|
||||
this.pendingCompactions.size > 0
|
||||
);
|
||||
}
|
||||
|
||||
private shouldDeferTurn(active: ActivePrompt): boolean {
|
||||
if (!this.options.options.acpOptions?.deferTurnOnRunningTools) return false;
|
||||
if (active.cancelling || this.closing || this.processFailed) return false;
|
||||
return this.hasQualifyingOpenTools() || active.crossedEndTurn;
|
||||
}
|
||||
|
||||
private finishDeferredTurn(active: ActivePrompt, outcome: DeferredTurnOutcome): void {
|
||||
const deferred = active.deferred;
|
||||
if (!deferred) return;
|
||||
if (deferred.timer) clearTimeout(deferred.timer);
|
||||
active.deferred = null;
|
||||
deferred.resolve(outcome);
|
||||
}
|
||||
|
||||
private noteDeferredToolTransition(
|
||||
wasOpenQualifying: boolean,
|
||||
isOpenQualifying: boolean,
|
||||
isOpen: boolean,
|
||||
snapshot: AcpToolCallSnapshot,
|
||||
wireSeq: number,
|
||||
): void {
|
||||
const active = this.activePrompt;
|
||||
if (!active || wasOpenQualifying === isOpenQualifying) return;
|
||||
if (!active.deferred && !this.isPostWirePrompt(active, wireSeq)) return;
|
||||
if (!active.deferred && wasOpenQualifying && !isOpen && this.toolKeepsTurnOpen(snapshot)) {
|
||||
active.crossedEndTurn = true;
|
||||
}
|
||||
if (isOpenQualifying) active.replyState = "idle";
|
||||
if (active.deferred) this.scheduleDeferredSettle();
|
||||
}
|
||||
|
||||
private noteDeferredChunk(
|
||||
kind: "agent_message_chunk" | "agent_thought_chunk",
|
||||
wireSeq: number,
|
||||
): void {
|
||||
const active = this.activePrompt;
|
||||
if (!active || !this.isPostWirePrompt(active, wireSeq)) return;
|
||||
if (kind === "agent_message_chunk") active.replyState = "open";
|
||||
else if (active.replyState !== "open") active.replyState = "idle";
|
||||
if (active.deferred) this.scheduleDeferredSettle();
|
||||
}
|
||||
|
||||
private noteDeferredUsageUpdate(wireSeq: number): void {
|
||||
const active = this.activePrompt;
|
||||
if (!active || !this.isPostWirePrompt(active, wireSeq) || active.replyState !== "open") return;
|
||||
active.replyState = this.hasQualifyingOpenTools() ? "settled_with_open_tools" : "settled";
|
||||
if (active.deferred) this.scheduleDeferredSettle();
|
||||
}
|
||||
|
||||
private scheduleDeferredSettle(): void {
|
||||
const active = this.activePrompt;
|
||||
const deferred = active?.deferred;
|
||||
const config = this.options.options.acpOptions?.deferTurnOnRunningTools;
|
||||
if (!active || !deferred || !config || active.cancelling) return;
|
||||
if (deferred.timer) {
|
||||
clearTimeout(deferred.timer);
|
||||
deferred.timer = null;
|
||||
}
|
||||
if (this.hasDeferredBlockers()) return;
|
||||
const settled =
|
||||
active.replyState === "settled" || active.replyState === "settled_with_open_tools";
|
||||
const delayMs = settled
|
||||
? (config.settleDelayMs ?? DEFAULT_DEFERRED_SETTLE_DELAY_MS)
|
||||
: (config.quietLimitMs ?? DEFAULT_DEFERRED_QUIET_LIMIT_MS);
|
||||
deferred.timer = setTimeout(() => {
|
||||
deferred.timer = null;
|
||||
void this.trySettleDeferredTurn(active, deferred);
|
||||
}, delayMs);
|
||||
}
|
||||
|
||||
private async trySettleDeferredTurn(
|
||||
active: ActivePrompt,
|
||||
deferred: DeferredTurnState,
|
||||
): Promise<void> {
|
||||
await this.drainNotifications();
|
||||
if (
|
||||
this.closing ||
|
||||
this.processFailed ||
|
||||
active.cancelling ||
|
||||
active.deferred !== deferred ||
|
||||
deferred.timer !== null ||
|
||||
this.hasDeferredBlockers()
|
||||
) {
|
||||
return;
|
||||
}
|
||||
this.finishDeferredTurn(active, { type: "complete", terminalizeTools: true });
|
||||
}
|
||||
|
||||
private waitForInitialCommands(): Promise<void> {
|
||||
if (this.receivedInitialCommands) return Promise.resolve();
|
||||
const timeoutMs = this.options.options.acpOptions?.initialCommandsTimeoutMs ?? 1_000;
|
||||
@@ -1421,9 +1926,10 @@ class AcpRuntime {
|
||||
}
|
||||
}
|
||||
|
||||
function routeVendorNotifications(
|
||||
function routeIncomingMessages(
|
||||
stream: Stream,
|
||||
receive: (method: string, params: unknown) => void,
|
||||
receiveVendor: (method: string, params: unknown) => void,
|
||||
observeWire: (message: unknown) => void,
|
||||
): Stream {
|
||||
const clientMethods = new Set<string>(Object.values(CLIENT_METHODS));
|
||||
return {
|
||||
@@ -1435,11 +1941,14 @@ function routeVendorNotifications(
|
||||
// The SDK dispatches extensions asynchronously and can resolve a later response first.
|
||||
// Run synchronous vendor transforms in wire order, inside the configuration transaction.
|
||||
try {
|
||||
receive(message.method, message.params);
|
||||
receiveVendor(message.method, message.params);
|
||||
} catch (error) {
|
||||
console.error("Error handling ACP vendor notification", error);
|
||||
}
|
||||
} else controller.enqueue(message);
|
||||
} else {
|
||||
observeWire(message);
|
||||
controller.enqueue(message);
|
||||
}
|
||||
},
|
||||
}),
|
||||
),
|
||||
@@ -1470,11 +1979,12 @@ function permissionOptionBehavior(
|
||||
|
||||
function ownConnectorStream(source: Stream): {
|
||||
stream: Stream;
|
||||
close(): Promise<void>;
|
||||
close(options?: { force?: boolean; timeoutMs?: number }): Promise<void>;
|
||||
whenClosed(): Promise<void> | null;
|
||||
} {
|
||||
const reader = source.readable.getReader();
|
||||
const writer = source.writable.getWriter();
|
||||
let closed = false;
|
||||
let closing: Promise<void> | null = null;
|
||||
const stream: Stream = {
|
||||
readable: new ReadableStream({
|
||||
async pull(controller) {
|
||||
@@ -1496,13 +2006,29 @@ function ownConnectorStream(source: Stream): {
|
||||
};
|
||||
return {
|
||||
stream,
|
||||
async close() {
|
||||
if (closed) return;
|
||||
closed = true;
|
||||
await Promise.allSettled([
|
||||
reader.cancel(new Error("Paseo closed the ACP connector")),
|
||||
writer.close(),
|
||||
]);
|
||||
whenClosed: () => closing,
|
||||
async close(options?: { force?: boolean; timeoutMs?: number }) {
|
||||
if (!closing) {
|
||||
const closeWrite = options?.force
|
||||
? writer.abort(new Error("Paseo aborted the ACP connector"))
|
||||
: writer.close();
|
||||
closing = Promise.allSettled([
|
||||
reader.cancel(new Error("Paseo closed the ACP connector")),
|
||||
closeWrite,
|
||||
]).then((results) => {
|
||||
if (options?.timeoutMs === undefined) return undefined;
|
||||
const rejected = results.find(
|
||||
(result): result is PromiseRejectedResult => result.status === "rejected",
|
||||
);
|
||||
if (rejected) throw rejected.reason;
|
||||
return undefined;
|
||||
});
|
||||
}
|
||||
if (options?.timeoutMs !== undefined) {
|
||||
await withTimeout(closing, options.timeoutMs, "ACP connector did not close");
|
||||
} else {
|
||||
await closing.catch(() => undefined);
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -53,6 +53,18 @@ export interface AcpOptions {
|
||||
initialCommandsTimeoutMs?: number;
|
||||
/** Allow delayed session/load updates before publishing the session as ready. */
|
||||
loadReplayQuietPeriodMs?: number;
|
||||
/**
|
||||
* Keep a turn open after `end_turn` while qualifying tool calls are still running,
|
||||
* settling once those tools finish and the agent finishes its follow-up reply.
|
||||
*/
|
||||
deferTurnOnRunningTools?: {
|
||||
/** Delay after `usage_update` closes a follow-up reply before settling. Defaults to 500ms. */
|
||||
settleDelayMs?: number;
|
||||
/** Quiet limit after qualifying tools finish if no reply settles via `usage_update`. Defaults to 120_000ms. */
|
||||
quietLimitMs?: number;
|
||||
/** Predicate deciding whether an open tool call keeps the turn open. Defaults to all running tools. */
|
||||
keepsTurnOpen?: (toolCall: AcpToolCallSnapshot) => boolean;
|
||||
};
|
||||
/** An unattended mode that approves ACP allow-once requests in the specified native mode. */
|
||||
autoAcceptMode?: {
|
||||
mode: Omit<ProviderMode, "isUnattended">;
|
||||
@@ -124,6 +136,8 @@ export interface AcpTransformer {
|
||||
configure?(change: AcpConfigChange, context: AcpConfigureContext): Promise<"handled" | "pass">;
|
||||
/** Rewrites every session config snapshot before Paseo sees it. */
|
||||
config?(state: ProviderConfigState, context: AcpContext): ProviderConfigState;
|
||||
/** Rewrites each advertised ACP slash command before Paseo sees it. */
|
||||
command?(command: ProviderCommand, context: AcpContext): ProviderCommand;
|
||||
notification?(
|
||||
notification: { method: string; params: JsonValue },
|
||||
context: AcpContext,
|
||||
|
||||
@@ -5,6 +5,7 @@ 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;
|
||||
@@ -64,6 +65,7 @@ export interface PluginServerContext extends PluginLifecycleRegistration {
|
||||
): void;
|
||||
registerProvider(provider: ProviderRegistration): void;
|
||||
registerUsageSource(source: UsageSourceRegistration): void;
|
||||
registerWorktreeManager(manager: WorktreeManagerRegistration): () => void;
|
||||
}
|
||||
|
||||
export type PluginServerContribution = (server: PluginServerContext) => PluginCleanup;
|
||||
|
||||
@@ -35,3 +35,14 @@ 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";
|
||||
|
||||
@@ -37,7 +37,12 @@ export type PluginWorktreeCreateRequest = {
|
||||
slug: string;
|
||||
path: string;
|
||||
} & (
|
||||
| { kind: "branch-off"; baseRef: 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: "checkout-branch" }
|
||||
| {
|
||||
kind: "checkout-change-request";
|
||||
|
||||
@@ -488,6 +488,7 @@ export interface ProviderCommand {
|
||||
name: string;
|
||||
description: string;
|
||||
argumentHint?: string;
|
||||
kind?: "command" | "skill";
|
||||
}
|
||||
|
||||
export interface ProviderError {
|
||||
@@ -1214,7 +1215,12 @@ const noticeSchema = z
|
||||
})
|
||||
.strip();
|
||||
const commandSchema = z
|
||||
.object({ name: idSchema, description: z.string(), argumentHint: z.string().optional() })
|
||||
.object({
|
||||
name: idSchema,
|
||||
description: z.string(),
|
||||
argumentHint: z.string().optional(),
|
||||
kind: z.enum(["command", "skill"]).optional(),
|
||||
})
|
||||
.strip();
|
||||
const usageSchema = z
|
||||
.object({
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
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>;
|
||||
}
|
||||
@@ -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/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/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: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",
|
||||
|
||||
@@ -9542,6 +9542,76 @@ test("onAgentAttention is not called for delegated child agents", async () => {
|
||||
expect(attentionCalls).toEqual([]);
|
||||
});
|
||||
|
||||
test.each(["read", "unread"])(
|
||||
"waits for a delegated agent before reporting a finish (earlier attention is %s)",
|
||||
async (attentionState) => {
|
||||
const workdir = mkdtempSync(join(tmpdir(), "agent-manager-delegated-finish-"));
|
||||
const config = { provider: "codex", cwd: workdir } as const;
|
||||
const client = new SessionRecordingAgentClient();
|
||||
const finishes: Array<{ agentId: string; attentionTimestamp: Date | null }> = [];
|
||||
const manager = new AgentManager({
|
||||
clients: { codex: client },
|
||||
registry: new AgentStorage(join(workdir, "agents"), logger),
|
||||
logger,
|
||||
onAgentAttention: ({ agentId, reason, attentionTimestamp }) => {
|
||||
if (reason === "finished") finishes.push({ agentId, attentionTimestamp });
|
||||
},
|
||||
});
|
||||
const parent = await manager.createAgent(config, undefined, { workspaceId: undefined });
|
||||
const child = await manager.createAgent(config, undefined, {
|
||||
labels: { [PARENT_AGENT_ID_LABEL]: parent.id },
|
||||
workspaceId: undefined,
|
||||
});
|
||||
onTestFinished(async () => {
|
||||
await manager.closeAgent(child.id);
|
||||
await manager.closeAgent(parent.id);
|
||||
await manager.flush();
|
||||
rmSync(workdir, { recursive: true, force: true });
|
||||
});
|
||||
const [parentSession, childSession] = client.sessions;
|
||||
|
||||
async function completeParentTurn(turnId: string) {
|
||||
const running = waitForAgentLifecycle(manager, parent.id, "running");
|
||||
parentSession.pushEvent({ type: "turn_started", provider: "codex", turnId });
|
||||
await running;
|
||||
const idle = waitForAgentLifecycle(manager, parent.id, "idle");
|
||||
parentSession.pushEvent({ type: "turn_completed", provider: "codex", turnId });
|
||||
await idle;
|
||||
}
|
||||
|
||||
if (attentionState === "unread") {
|
||||
await completeParentTurn("earlier-parent-finish");
|
||||
}
|
||||
const earlierFinishes = [...finishes];
|
||||
const earlierAttention = manager.getAgent(parent.id)?.attention;
|
||||
const childRunning = waitForAgentLifecycle(manager, child.id, "running");
|
||||
const childTurn = { provider: "codex", turnId: "child-turn" } as const;
|
||||
childSession.pushEvent({ ...childTurn, type: "turn_started" });
|
||||
await childRunning;
|
||||
|
||||
await completeParentTurn("parent-handles-child-update");
|
||||
expect(finishes).toEqual(earlierFinishes);
|
||||
expect(manager.getAgent(parent.id)?.attention).toEqual(earlierAttention);
|
||||
|
||||
const childIdle = waitForAgentLifecycle(manager, child.id, "idle");
|
||||
childSession.pushEvent({ ...childTurn, type: "turn_completed" });
|
||||
await childIdle;
|
||||
await completeParentTurn("parent-handles-child-finish");
|
||||
|
||||
expect(finishes).toEqual([
|
||||
...earlierFinishes,
|
||||
{
|
||||
agentId: parent.id,
|
||||
attentionTimestamp: earlierFinishes[0]?.attentionTimestamp ?? expect.any(Date),
|
||||
},
|
||||
]);
|
||||
expect(manager.getAgent(parent.id)?.attention).toMatchObject({
|
||||
requiresAttention: true,
|
||||
attentionReason: "finished",
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
test("clearAgentAttention on errored agent stays cleared until a new error transition", async () => {
|
||||
const workdir = mkdtempSync(join(tmpdir(), "agent-manager-attention-error-"));
|
||||
const storagePath = join(workdir, "agents");
|
||||
|
||||
@@ -881,6 +881,7 @@ export class AgentManager {
|
||||
>();
|
||||
private readonly collectingRuntimes = new Set<string>();
|
||||
private readonly lifecycleMutationTails = new Map<string, Promise<void>>();
|
||||
private readonly pendingCancellations = new Map<string, Promise<unknown>>();
|
||||
private readonly agentStreamCoalescer: AgentStreamCoalescer;
|
||||
private mcpBaseUrl: string | null;
|
||||
private readonly mcpAuthToken: string | null;
|
||||
@@ -2463,80 +2464,83 @@ export class AgentManager {
|
||||
// reload or close; providers do no sequencing of their own.
|
||||
|
||||
async setAgentMode(agentId: string, modeId: string): Promise<AgentProviderNotice | null> {
|
||||
return this.runLifecycleMutation(agentId, async () => {
|
||||
const agent = await this.ensureInteractiveSessionUnlocked(agentId);
|
||||
const notice = (await agent.session.setMode(modeId)) ?? null;
|
||||
await this.drainSessionEvents(agentId);
|
||||
const currentMode = (await agent.session.getCurrentMode()) ?? modeId;
|
||||
agent.config.modeId = currentMode ?? undefined;
|
||||
agent.currentModeId = currentMode;
|
||||
// Update runtimeInfo to reflect the new mode
|
||||
if (agent.runtimeInfo) {
|
||||
agent.runtimeInfo = { ...agent.runtimeInfo, modeId: currentMode };
|
||||
}
|
||||
this.touchUpdatedAt(agent);
|
||||
this.emitState(agent);
|
||||
return notice;
|
||||
});
|
||||
return this.runLifecycleMutation(agentId, () =>
|
||||
this.withLiveInteractiveSessionUnlocked(agentId, async (agent) => {
|
||||
const notice = (await agent.session.setMode(modeId)) ?? null;
|
||||
await this.drainSessionEvents(agentId);
|
||||
const currentMode = (await agent.session.getCurrentMode()) ?? modeId;
|
||||
agent.config.modeId = currentMode ?? undefined;
|
||||
agent.currentModeId = currentMode;
|
||||
// Update runtimeInfo to reflect the new mode
|
||||
if (agent.runtimeInfo) {
|
||||
agent.runtimeInfo = { ...agent.runtimeInfo, modeId: currentMode };
|
||||
}
|
||||
this.touchUpdatedAt(agent);
|
||||
this.emitState(agent);
|
||||
return notice;
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
async setAgentModel(agentId: string, modelId: string | null): Promise<void> {
|
||||
return this.runLifecycleMutation(agentId, async () => {
|
||||
const agent = await this.ensureInteractiveSessionUnlocked(agentId);
|
||||
const normalizedModelId =
|
||||
typeof modelId === "string" && modelId.trim().length > 0 ? modelId : null;
|
||||
return this.runLifecycleMutation(agentId, () =>
|
||||
this.withLiveInteractiveSessionUnlocked(agentId, async (agent) => {
|
||||
const normalizedModelId =
|
||||
typeof modelId === "string" && modelId.trim().length > 0 ? modelId : null;
|
||||
|
||||
const selection = await agent.session.setModel?.(normalizedModelId);
|
||||
await this.drainSessionEvents(agentId);
|
||||
const selection = await agent.session.setModel?.(normalizedModelId);
|
||||
await this.drainSessionEvents(agentId);
|
||||
|
||||
// A reset clears the preference even when the provider retains its active model.
|
||||
let effectiveModelId = normalizedModelId;
|
||||
if (normalizedModelId !== null && selection) effectiveModelId = selection.model;
|
||||
// A reset clears the preference even when the provider retains its active model.
|
||||
let effectiveModelId = normalizedModelId;
|
||||
if (normalizedModelId !== null && selection) effectiveModelId = selection.model;
|
||||
|
||||
agent.config.model = effectiveModelId ?? undefined;
|
||||
if (agent.runtimeInfo) {
|
||||
agent.runtimeInfo = { ...agent.runtimeInfo, model: effectiveModelId };
|
||||
}
|
||||
this.refreshSessionPersistence(agent);
|
||||
this.touchUpdatedAt(agent);
|
||||
this.emitState(agent);
|
||||
});
|
||||
agent.config.model = effectiveModelId ?? undefined;
|
||||
if (agent.runtimeInfo) {
|
||||
agent.runtimeInfo = { ...agent.runtimeInfo, model: effectiveModelId };
|
||||
}
|
||||
this.refreshSessionPersistence(agent);
|
||||
this.touchUpdatedAt(agent);
|
||||
this.emitState(agent);
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
async setAgentThinkingOption(
|
||||
agentId: string,
|
||||
thinkingOptionId: string | null,
|
||||
): Promise<AgentProviderNotice | null> {
|
||||
return this.runLifecycleMutation(agentId, async () => {
|
||||
const agent = await this.ensureInteractiveSessionUnlocked(agentId);
|
||||
const normalizedThinkingOptionId =
|
||||
typeof thinkingOptionId === "string" && thinkingOptionId.trim().length > 0
|
||||
? thinkingOptionId
|
||||
: null;
|
||||
return this.runLifecycleMutation(agentId, () =>
|
||||
this.withLiveInteractiveSessionUnlocked(agentId, async (agent) => {
|
||||
const normalizedThinkingOptionId =
|
||||
typeof thinkingOptionId === "string" && thinkingOptionId.trim().length > 0
|
||||
? thinkingOptionId
|
||||
: null;
|
||||
|
||||
let notice: AgentProviderNotice | null = null;
|
||||
if (agent.session.setThinkingOption) {
|
||||
notice = (await agent.session.setThinkingOption(normalizedThinkingOptionId)) ?? null;
|
||||
}
|
||||
await this.drainSessionEvents(agentId);
|
||||
let notice: AgentProviderNotice | null = null;
|
||||
if (agent.session.setThinkingOption) {
|
||||
notice = (await agent.session.setThinkingOption(normalizedThinkingOptionId)) ?? null;
|
||||
}
|
||||
await this.drainSessionEvents(agentId);
|
||||
|
||||
let effectiveThinkingOptionId = normalizedThinkingOptionId;
|
||||
const runtimeInfo = await agent.session.getRuntimeInfo();
|
||||
if (runtimeInfo.thinkingOptionId !== undefined) {
|
||||
effectiveThinkingOptionId = runtimeInfo.thinkingOptionId;
|
||||
}
|
||||
let effectiveThinkingOptionId = normalizedThinkingOptionId;
|
||||
const runtimeInfo = await agent.session.getRuntimeInfo();
|
||||
if (runtimeInfo.thinkingOptionId !== undefined) {
|
||||
effectiveThinkingOptionId = runtimeInfo.thinkingOptionId;
|
||||
}
|
||||
|
||||
agent.config.thinkingOptionId = effectiveThinkingOptionId ?? undefined;
|
||||
if (agent.runtimeInfo) {
|
||||
agent.runtimeInfo = {
|
||||
...agent.runtimeInfo,
|
||||
thinkingOptionId: effectiveThinkingOptionId,
|
||||
};
|
||||
}
|
||||
this.touchUpdatedAt(agent);
|
||||
this.emitState(agent);
|
||||
return notice;
|
||||
});
|
||||
agent.config.thinkingOptionId = effectiveThinkingOptionId ?? undefined;
|
||||
if (agent.runtimeInfo) {
|
||||
agent.runtimeInfo = {
|
||||
...agent.runtimeInfo,
|
||||
thinkingOptionId: effectiveThinkingOptionId,
|
||||
};
|
||||
}
|
||||
this.touchUpdatedAt(agent);
|
||||
this.emitState(agent);
|
||||
return notice;
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -2546,42 +2550,45 @@ export class AgentManager {
|
||||
* one step once the provider accepts. Patches to one agent run one at a time, in arrival order.
|
||||
*/
|
||||
async setAgentOptions(agentId: string, requested: ProviderOptionsPatch): Promise<void> {
|
||||
return this.runLifecycleMutation(agentId, async () => {
|
||||
const agent = await this.ensureInteractiveSessionUnlocked(agentId);
|
||||
const patch = this.convertLegacyOptions(agent.provider, requested);
|
||||
let ended: ProviderOptionsPatch = {};
|
||||
let sent: ProviderOptionsPatch = {};
|
||||
if (Object.keys(patch).length > 0) {
|
||||
// A provider that cannot apply options to a running agent must not store them either.
|
||||
if (!agent.session.applyOptions) {
|
||||
throw new ProviderOptionsValidationError(
|
||||
agent.provider,
|
||||
Object.keys(patch).map((key) => ({
|
||||
path: [key],
|
||||
message: "cannot change on a running session; it applies when the agent is opened",
|
||||
})),
|
||||
return this.runLifecycleMutation(agentId, () =>
|
||||
this.withLiveInteractiveSessionUnlocked(agentId, async (agent) => {
|
||||
const patch = this.convertLegacyOptions(agent.provider, requested);
|
||||
let ended: ProviderOptionsPatch = {};
|
||||
let sent: ProviderOptionsPatch = {};
|
||||
if (Object.keys(patch).length > 0) {
|
||||
// A provider that cannot apply options to a running agent must not store them either.
|
||||
if (!agent.session.applyOptions) {
|
||||
throw new ProviderOptionsValidationError(
|
||||
agent.provider,
|
||||
Object.keys(patch).map((key) => ({
|
||||
path: [key],
|
||||
message: "cannot change on a running session; it applies when the agent is opened",
|
||||
})),
|
||||
);
|
||||
}
|
||||
const set = Object.fromEntries(
|
||||
Object.entries(patch).filter(([, value]) => value != null),
|
||||
);
|
||||
const resolved = this.effectiveOptionsFor(agent.provider, set);
|
||||
sent = Object.fromEntries(Object.keys(patch).map((key) => [key, resolved[key] ?? null]));
|
||||
const modelBefore = agent.runtimeInfo?.model;
|
||||
ended = (await agent.session.applyOptions(sent)) ?? {};
|
||||
// Changes the provider made on its own while applying are older than its final answer.
|
||||
await this.drainSessionEvents(agentId);
|
||||
await this.refreshRuntimeInfo(agent, { emit: false });
|
||||
// An option can choose the model too, as an fx connection does. Reopening the agent on
|
||||
// the earlier preference would send that model to the new connection.
|
||||
const modelAfter = agent.runtimeInfo?.model;
|
||||
if (agent.config.model && modelAfter && modelAfter !== modelBefore) {
|
||||
agent.config.model = modelAfter;
|
||||
}
|
||||
}
|
||||
const set = Object.fromEntries(Object.entries(patch).filter(([, value]) => value != null));
|
||||
const resolved = this.effectiveOptionsFor(agent.provider, set);
|
||||
sent = Object.fromEntries(Object.keys(patch).map((key) => [key, resolved[key] ?? null]));
|
||||
const modelBefore = agent.runtimeInfo?.model;
|
||||
ended = (await agent.session.applyOptions(sent)) ?? {};
|
||||
// Changes the provider made on its own while applying are older than its final answer.
|
||||
await this.drainSessionEvents(agentId);
|
||||
await this.refreshRuntimeInfo(agent, { emit: false });
|
||||
// An option can choose the model too, as an fx connection does. Reopening the agent on
|
||||
// the earlier preference would send that model to the new connection.
|
||||
const modelAfter = agent.runtimeInfo?.model;
|
||||
if (agent.config.model && modelAfter && modelAfter !== modelBefore) {
|
||||
agent.config.model = modelAfter;
|
||||
}
|
||||
}
|
||||
this.storeOptionsPatch({ agent, patch: { ...patch, ...ended } });
|
||||
this.updateEffectiveOptions({ agent, sent, reported: ended });
|
||||
this.touchUpdatedAt(agent);
|
||||
this.emitState(agent);
|
||||
});
|
||||
this.storeOptionsPatch({ agent, patch: { ...patch, ...ended } });
|
||||
this.updateEffectiveOptions({ agent, sent, reported: ended });
|
||||
this.touchUpdatedAt(agent);
|
||||
this.emitState(agent);
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
/** The config as the opened session left it: its own difference from the options it was given. */
|
||||
@@ -3267,6 +3274,33 @@ export class AgentManager {
|
||||
return this.requireSessionAgent(agentId);
|
||||
}
|
||||
|
||||
/** Inside the agent's lane: transparently reopens a retired plugin session before applying config. */
|
||||
private async withLiveInteractiveSessionUnlocked<T>(
|
||||
agentId: string,
|
||||
operation: (agent: ActiveManagedAgent) => Promise<T>,
|
||||
): Promise<T> {
|
||||
const pendingCancellation = this.pendingCancellations.get(agentId);
|
||||
if (pendingCancellation) {
|
||||
await this.waitWithTimeout({
|
||||
operation: pendingCancellation.then(
|
||||
() => undefined,
|
||||
() => undefined,
|
||||
),
|
||||
timeoutMs: this.rescueTimeouts.interruptSessionMs,
|
||||
});
|
||||
}
|
||||
const agent = await this.ensureInteractiveSessionUnlocked(agentId);
|
||||
try {
|
||||
return await operation(agent);
|
||||
} catch (error) {
|
||||
if (!isStaleProviderSessionError(error)) throw error;
|
||||
await this.runs.getPendingRun(agentId)?.settledPromise.catch(() => undefined);
|
||||
if (this.hasInFlightRun(agentId)) throw error;
|
||||
await this.trackAgentRegistrationOperation(this.reloadAgentSessionInternal(agentId));
|
||||
return await operation(this.requireSessionAgent(agentId));
|
||||
}
|
||||
}
|
||||
|
||||
private async *streamAfterHistoryLoad(
|
||||
agentId: string,
|
||||
prompt: AgentPromptInput,
|
||||
@@ -3925,10 +3959,18 @@ export class AgentManager {
|
||||
}
|
||||
|
||||
async cancelAgentRun(agentId: string): Promise<AgentRunCancellationResult> {
|
||||
return this.runForegroundMutation(agentId, () => {
|
||||
const cancellation = this.runForegroundMutation(agentId, () => {
|
||||
this.requireSessionAgent(agentId).pendingReplacement = false;
|
||||
return this.cancelAgentRunNow(agentId);
|
||||
});
|
||||
this.pendingCancellations.set(agentId, cancellation);
|
||||
try {
|
||||
return await cancellation;
|
||||
} finally {
|
||||
if (this.pendingCancellations.get(agentId) === cancellation) {
|
||||
this.pendingCancellations.delete(agentId);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async cancelAgentRunNow(agentId: string): Promise<AgentRunCancellationResult> {
|
||||
@@ -5878,7 +5920,10 @@ export class AgentManager {
|
||||
return;
|
||||
}
|
||||
|
||||
const finished = previousStatus === "running" && currentStatus === "idle";
|
||||
const finished =
|
||||
previousStatus === "running" &&
|
||||
currentStatus === "idle" &&
|
||||
(isDelegatedAgent(agent) || !this.hasBusyChildAgent(agent.id));
|
||||
if (agent.attention.requiresAttention) {
|
||||
// The unread finish stays the same; the notifier knows whether the user was told about it.
|
||||
if (finished && agent.attention.attentionReason === "finished") {
|
||||
@@ -5897,6 +5942,15 @@ export class AgentManager {
|
||||
}
|
||||
}
|
||||
|
||||
private hasBusyChildAgent(agentId: string): boolean {
|
||||
for (const child of this.agents.values()) {
|
||||
if (isAgentBusy(child.lifecycle) && getParentAgentIdFromLabels(child.labels) === agentId) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// The failed state is only shown while error attention is unread, so every new failure raises
|
||||
// it, including one that keeps the lifecycle at "error". An error outranks an unread finish,
|
||||
// which would otherwise make the failure look green.
|
||||
|
||||
@@ -4,7 +4,11 @@ import type pino from "pino";
|
||||
|
||||
import type { ForgeService } from "../../services/forge-service.js";
|
||||
import { isPaseoOwnedWorktreeCwd } from "../../utils/worktree.js";
|
||||
import { archiveByScope, type ActiveWorkspaceRef } from "../workspace-archive-service.js";
|
||||
import {
|
||||
archiveByScope,
|
||||
type ActiveWorkspaceRef,
|
||||
type ArchiveDependencies,
|
||||
} from "../workspace-archive-service.js";
|
||||
import type {
|
||||
CreatePaseoWorktreeWorkflowFn,
|
||||
CreatePaseoWorktreeWorkflowResult,
|
||||
@@ -17,10 +21,15 @@ 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;
|
||||
@@ -184,11 +193,15 @@ 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,
|
||||
|
||||
@@ -6,6 +6,7 @@ import { createIdleRuntimeCleanup } from "./idle-runtime-cleanup/index.js";
|
||||
import { relative } from "node:path";
|
||||
import { execFileSync } from "node:child_process";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { runAcpProvider, type AcpStreamMessage } from "@getpaseo/plugin/server/acp";
|
||||
import type {
|
||||
ProviderConnection,
|
||||
ProviderLaunch,
|
||||
@@ -13,6 +14,7 @@ import type {
|
||||
ProviderInput,
|
||||
ProviderRegistration,
|
||||
} from "@getpaseo/plugin/server/provider";
|
||||
import { sendPreparedPromptToAgent } from "./agent-prompt.js";
|
||||
import { setImmediate as nextTurn } from "node:timers/promises";
|
||||
import { describe, expect, test } from "vitest";
|
||||
import { createTestLogger } from "../../test-utils/test-logger.js";
|
||||
@@ -256,6 +258,38 @@ function eventsOfType(events: AgentStreamEvent[], type: AgentStreamEvent["type"]
|
||||
return events.filter((event) => event.type === type);
|
||||
}
|
||||
|
||||
test("preserves skills in a plugin session's command list", async () => {
|
||||
const harness = createProviderHarness();
|
||||
const registry = new PluginAgentClientRegistry(createTestLogger());
|
||||
registry.replace([harness.registration]);
|
||||
const session = await registry.clients()[harness.registration.id]!.createSession({
|
||||
provider: harness.registration.id,
|
||||
cwd: tmpdir(),
|
||||
});
|
||||
try {
|
||||
const open = harness.inputs.find((input) => input.type === "session.open")!;
|
||||
harness.emit({
|
||||
type: "session.commands",
|
||||
sessionId: open.sessionId,
|
||||
commands: [
|
||||
{ name: "compact", description: "Compact the conversation" },
|
||||
{ name: "diagnose", description: "Diagnose a bug", kind: "skill" },
|
||||
],
|
||||
});
|
||||
await expect(session.listCommands!()).resolves.toEqual([
|
||||
{
|
||||
name: "compact",
|
||||
description: "Compact the conversation",
|
||||
argumentHint: "",
|
||||
kind: "command",
|
||||
},
|
||||
{ name: "diagnose", description: "Diagnose a bug", argumentHint: "", kind: "skill" },
|
||||
]);
|
||||
} finally {
|
||||
await session.close();
|
||||
}
|
||||
});
|
||||
|
||||
function createRewindProviderHarness(
|
||||
options: {
|
||||
reuseAnswerId?: boolean;
|
||||
@@ -2814,3 +2848,592 @@ test("resumes a goose session saved by the generic ACP provider", async () => {
|
||||
await plugins.shutdown();
|
||||
}
|
||||
});
|
||||
|
||||
test("preserves a deferred ACP background job on steer and cancels it on explicit Stop through AgentManager", async () => {
|
||||
const logger = createTestLogger();
|
||||
const home = await mkdtemp(join(tmpdir(), "paseo-acp-deferred-daemon-"));
|
||||
const storage = new AgentStorage(join(home, "agents"), logger);
|
||||
let cancelCount = 0;
|
||||
let promptCount = 0;
|
||||
let currentMode = "default";
|
||||
let notifyAgent: ((message: AcpStreamMessage) => void) | null = null;
|
||||
let holdNextPrompt: ((release: () => void) => void) | null = null;
|
||||
const modeConfig = () => [
|
||||
{
|
||||
id: "mode",
|
||||
name: "Mode",
|
||||
category: "mode",
|
||||
type: "select",
|
||||
currentValue: currentMode,
|
||||
options: [
|
||||
{ value: "default", name: "Default" },
|
||||
{ value: "plan", name: "Plan" },
|
||||
],
|
||||
},
|
||||
];
|
||||
const registration = runAcpProvider({
|
||||
id: "deferred-acp-daemon",
|
||||
label: "Deferred ACP Daemon",
|
||||
acpOptions: {
|
||||
deferTurnOnRunningTools: { settleDelayMs: 25, quietLimitMs: 1_000 },
|
||||
},
|
||||
connector() {
|
||||
let controller!: ReadableStreamDefaultController<AcpStreamMessage>;
|
||||
const readable = new ReadableStream<AcpStreamMessage>({
|
||||
start(ctrl) {
|
||||
controller = ctrl;
|
||||
},
|
||||
});
|
||||
const send = (message: AcpStreamMessage) => controller.enqueue(message);
|
||||
notifyAgent = send;
|
||||
const writable = new WritableStream<AcpStreamMessage>({
|
||||
write(message) {
|
||||
if (!("method" in message)) return;
|
||||
if (message.method === "session/cancel") {
|
||||
cancelCount += 1;
|
||||
return;
|
||||
}
|
||||
if (!("id" in message)) return;
|
||||
if (message.method === "initialize") {
|
||||
send({
|
||||
jsonrpc: "2.0",
|
||||
id: message.id,
|
||||
result: { protocolVersion: 1, agentCapabilities: { loadSession: true } },
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (message.method === "session/new") {
|
||||
send({
|
||||
jsonrpc: "2.0",
|
||||
id: message.id,
|
||||
result: { sessionId: "acp-s1", configOptions: modeConfig() },
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (message.method === "session/load") {
|
||||
send({ jsonrpc: "2.0", id: message.id, result: { configOptions: modeConfig() } });
|
||||
return;
|
||||
}
|
||||
if (message.method === "session/set_config_option") {
|
||||
const params = message.params as { value?: string } | undefined;
|
||||
if (typeof params?.value === "string") currentMode = params.value;
|
||||
send({ jsonrpc: "2.0", id: message.id, result: { configOptions: modeConfig() } });
|
||||
return;
|
||||
}
|
||||
if (message.method === "session/prompt") {
|
||||
promptCount += 1;
|
||||
if (promptCount === 1) {
|
||||
send({
|
||||
jsonrpc: "2.0",
|
||||
method: "session/update",
|
||||
params: {
|
||||
sessionId: "acp-s1",
|
||||
update: {
|
||||
sessionUpdate: "tool_call",
|
||||
toolCallId: "bg-job-1",
|
||||
name: "run_command",
|
||||
title: "Background job",
|
||||
status: "in_progress",
|
||||
},
|
||||
},
|
||||
});
|
||||
} else if (promptCount === 2) {
|
||||
send({
|
||||
jsonrpc: "2.0",
|
||||
method: "session/update",
|
||||
params: {
|
||||
sessionId: "acp-s1",
|
||||
update: {
|
||||
sessionUpdate: "agent_message_chunk",
|
||||
content: { type: "text", text: "Steered reply" },
|
||||
},
|
||||
},
|
||||
});
|
||||
} else {
|
||||
send({
|
||||
jsonrpc: "2.0",
|
||||
method: "session/update",
|
||||
params: {
|
||||
sessionId: "acp-s1",
|
||||
update: {
|
||||
sessionUpdate: "tool_call",
|
||||
toolCallId: "bg-job-2",
|
||||
name: "run_command",
|
||||
title: "Cancelable job",
|
||||
status: "in_progress",
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
if (holdNextPrompt) {
|
||||
const hook = holdNextPrompt;
|
||||
holdNextPrompt = null;
|
||||
hook(() =>
|
||||
send({ jsonrpc: "2.0", id: message.id, result: { stopReason: "cancelled" } }),
|
||||
);
|
||||
return;
|
||||
}
|
||||
send({ jsonrpc: "2.0", id: message.id, result: { stopReason: "end_turn" } });
|
||||
return;
|
||||
}
|
||||
if (message.method === "session/close") {
|
||||
send({ jsonrpc: "2.0", id: message.id, result: {} });
|
||||
}
|
||||
},
|
||||
});
|
||||
return { readable, writable };
|
||||
},
|
||||
});
|
||||
const plugins = new PluginAgentClientRegistry(logger);
|
||||
plugins.replace([registration]);
|
||||
const manager = new AgentManager({ clients: plugins.clients(), registry: storage, logger });
|
||||
try {
|
||||
const agent = await manager.createAgent({ provider: registration.id, cwd: home }, undefined, {
|
||||
workspaceId: undefined,
|
||||
});
|
||||
const first = await sendPreparedPromptToAgent({
|
||||
agentManager: manager,
|
||||
agentStorage: storage,
|
||||
agentId: agent.id,
|
||||
prompt: "start background job",
|
||||
logger,
|
||||
});
|
||||
expect(first.disposition).toBe("turn_started");
|
||||
if (first.disposition === "turn_started") await first.started;
|
||||
await new Promise((resolve) => setTimeout(resolve, 40));
|
||||
expect(manager.getAgent(agent.id)?.lifecycle).toBe("running");
|
||||
|
||||
// Follow-up steer through AgentManager preserves the background job without session/cancel.
|
||||
const followUp = await sendPreparedPromptToAgent({
|
||||
agentManager: manager,
|
||||
agentStorage: storage,
|
||||
agentId: agent.id,
|
||||
prompt: "still working?",
|
||||
activeTurnBehavior: "steer",
|
||||
logger,
|
||||
});
|
||||
expect(followUp.disposition).toBe("steered");
|
||||
expect(cancelCount).toBe(0);
|
||||
await new Promise((resolve) => setTimeout(resolve, 40));
|
||||
expect(manager.getAgent(agent.id)?.lifecycle).toBe("running");
|
||||
|
||||
// Completing the job + reply + usage_update settles the turn cleanly.
|
||||
notifyAgent!({
|
||||
jsonrpc: "2.0",
|
||||
method: "session/update",
|
||||
params: {
|
||||
sessionId: "acp-s1",
|
||||
update: { sessionUpdate: "tool_call_update", toolCallId: "bg-job-1", status: "completed" },
|
||||
},
|
||||
});
|
||||
notifyAgent!({
|
||||
jsonrpc: "2.0",
|
||||
method: "session/update",
|
||||
params: {
|
||||
sessionId: "acp-s1",
|
||||
update: {
|
||||
sessionUpdate: "agent_message_chunk",
|
||||
content: { type: "text", text: "Background job finished." },
|
||||
},
|
||||
},
|
||||
});
|
||||
notifyAgent!({
|
||||
jsonrpc: "2.0",
|
||||
method: "session/update",
|
||||
params: {
|
||||
sessionId: "acp-s1",
|
||||
update: { sessionUpdate: "usage_update", used: 120, size: 1000 },
|
||||
},
|
||||
});
|
||||
await expect.poll(() => manager.getAgent(agent.id)?.lifecycle, { timeout: 3_000 }).toBe("idle");
|
||||
expect(cancelCount).toBe(0);
|
||||
|
||||
// Start a second deferred job, send two steers while steer 1 waits on ACP, and press Stop.
|
||||
let heldSteerResponse: (() => void) | null = null;
|
||||
const second = await sendPreparedPromptToAgent({
|
||||
agentManager: manager,
|
||||
agentStorage: storage,
|
||||
agentId: agent.id,
|
||||
prompt: "start cancelable job",
|
||||
logger,
|
||||
});
|
||||
if (second.disposition === "turn_started") await second.started;
|
||||
await new Promise((resolve) => setTimeout(resolve, 40));
|
||||
expect(manager.getAgent(agent.id)?.lifecycle).toBe("running");
|
||||
|
||||
// Hold the next steer prompt so Stop races with a queued second steer.
|
||||
holdNextPrompt = (release) => {
|
||||
heldSteerResponse = release;
|
||||
};
|
||||
const steerOne = await sendPreparedPromptToAgent({
|
||||
agentManager: manager,
|
||||
agentStorage: storage,
|
||||
agentId: agent.id,
|
||||
prompt: "held steer 1",
|
||||
activeTurnBehavior: "steer",
|
||||
logger,
|
||||
});
|
||||
expect(steerOne.disposition).toBe("steered");
|
||||
const steerTwo = await sendPreparedPromptToAgent({
|
||||
agentManager: manager,
|
||||
agentStorage: storage,
|
||||
agentId: agent.id,
|
||||
prompt: "queued steer 2",
|
||||
activeTurnBehavior: "steer",
|
||||
logger,
|
||||
});
|
||||
expect(steerTwo.disposition).toBe("steered");
|
||||
await expect.poll(() => heldSteerResponse).not.toBeNull();
|
||||
const promptsBeforeStop = promptCount;
|
||||
|
||||
// Stop must send session/cancel immediately, retire the deferred session cleanly,
|
||||
// and never dispatch the queued steer 2 to ACP.
|
||||
await manager.cancelAgentRun(agent.id);
|
||||
expect(cancelCount).toBe(1);
|
||||
await expect.poll(() => manager.getAgent(agent.id)?.lifecycle, { timeout: 3_000 }).toBe("idle");
|
||||
expect(promptCount).toBe(promptsBeforeStop);
|
||||
|
||||
// Changing mode immediately after stopping a deferred turn must transparently reopen the session.
|
||||
await manager.setAgentMode(agent.id, "plan");
|
||||
expect(manager.getAgent(agent.id)?.currentModeId).toBe("plan");
|
||||
expect(currentMode).toBe("plan");
|
||||
} finally {
|
||||
await Promise.all(manager.listAgents().map((item) => manager.closeAgent(item.id)));
|
||||
await plugins.shutdown();
|
||||
await storage.flush();
|
||||
await rm(home, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("reopens cleanly for mode changes and follow-up sends initiated while Stop is closing a slow ACP process", async () => {
|
||||
const logger = createTestLogger();
|
||||
const home = await mkdtemp(join(tmpdir(), "paseo-acp-slow-stop-"));
|
||||
const storage = new AgentStorage(join(home, "agents"), logger);
|
||||
const script = join(home, "slow-stop-agent.cjs");
|
||||
const { writeFile } = await import("node:fs/promises");
|
||||
await writeFile(
|
||||
script,
|
||||
`
|
||||
const { createInterface } = require("node:readline");
|
||||
const send = (msg) => process.stdout.write(JSON.stringify({ jsonrpc: "2.0", ...msg }) + "\\n");
|
||||
let mode = "default";
|
||||
const configOptions = () => [{
|
||||
id: "mode", name: "Mode", category: "mode", type: "select", currentValue: mode,
|
||||
options: [{ value: "default", name: "Default" }, { value: "plan", name: "Plan" }],
|
||||
}];
|
||||
process.on("SIGTERM", () => {
|
||||
setTimeout(() => process.exit(0), 250);
|
||||
});
|
||||
createInterface({ input: process.stdin }).on("line", (line) => {
|
||||
const msg = JSON.parse(line);
|
||||
if (msg.method === "initialize") {
|
||||
send({ id: msg.id, result: { protocolVersion: 1, agentCapabilities: { loadSession: true } } });
|
||||
} else if (msg.method === "session/new") {
|
||||
send({ id: msg.id, result: { sessionId: "slow-s1", configOptions: configOptions() } });
|
||||
} else if (msg.method === "session/load") {
|
||||
send({ id: msg.id, result: { configOptions: configOptions() } });
|
||||
} else if (msg.method === "session/set_config_option") {
|
||||
if (msg.params && typeof msg.params.value === "string") mode = msg.params.value;
|
||||
send({ id: msg.id, result: { configOptions: configOptions() } });
|
||||
} else if (msg.method === "session/prompt") {
|
||||
const text = msg.params?.prompt?.[0]?.text ?? "";
|
||||
if (text.includes("start bg")) {
|
||||
send({ method: "session/update", params: { sessionId: "slow-s1", update: {
|
||||
sessionUpdate: "tool_call", toolCallId: "slow-bg-1", name: "run_command",
|
||||
title: "Slow bg job", status: "in_progress",
|
||||
} } });
|
||||
} else {
|
||||
send({ method: "session/update", params: { sessionId: "slow-s1", update: {
|
||||
sessionUpdate: "agent_message_chunk", content: { type: "text", text: "After stop reply" },
|
||||
} } });
|
||||
}
|
||||
send({ id: msg.id, result: { stopReason: "end_turn" } });
|
||||
} else if (msg.method === "session/close") {
|
||||
send({ id: msg.id, result: {} });
|
||||
}
|
||||
});
|
||||
`,
|
||||
);
|
||||
const registration = runAcpProvider({
|
||||
id: "slow-stop-acp",
|
||||
label: "Slow Stop ACP",
|
||||
command: [process.execPath, script],
|
||||
acpOptions: {
|
||||
deferTurnOnRunningTools: { settleDelayMs: 25, quietLimitMs: 1_000 },
|
||||
},
|
||||
});
|
||||
const plugins = new PluginAgentClientRegistry(logger);
|
||||
plugins.replace([registration]);
|
||||
const manager = new AgentManager({ clients: plugins.clients(), registry: storage, logger });
|
||||
try {
|
||||
const agent = await manager.createAgent({ provider: registration.id, cwd: home }, undefined, {
|
||||
workspaceId: undefined,
|
||||
});
|
||||
const first = await sendPreparedPromptToAgent({
|
||||
agentManager: manager,
|
||||
agentStorage: storage,
|
||||
agentId: agent.id,
|
||||
prompt: "start bg",
|
||||
logger,
|
||||
});
|
||||
if (first.disposition === "turn_started") await first.started;
|
||||
await new Promise((resolve) => setTimeout(resolve, 40));
|
||||
expect(manager.getAgent(agent.id)?.lifecycle).toBe("running");
|
||||
|
||||
// Start Stop (takes 250ms to terminate the child on SIGTERM) and trigger a mode change mid-shutdown.
|
||||
const stopPromise = manager.cancelAgentRun(agent.id);
|
||||
await new Promise((resolve) => setTimeout(resolve, 50));
|
||||
const modePromise = manager.setAgentMode(agent.id, "plan");
|
||||
await Promise.all([stopPromise, modePromise]);
|
||||
expect(manager.getAgent(agent.id)?.currentModeId).toBe("plan");
|
||||
expect(manager.getAgent(agent.id)?.lifecycle).toBe("idle");
|
||||
|
||||
// A follow-up prompt immediately after Stop + mode change succeeds cleanly.
|
||||
const next = await sendPreparedPromptToAgent({
|
||||
agentManager: manager,
|
||||
agentStorage: storage,
|
||||
agentId: agent.id,
|
||||
prompt: "fresh prompt",
|
||||
logger,
|
||||
});
|
||||
expect(next.disposition).toBe("turn_started");
|
||||
if (next.disposition === "turn_started") await next.started;
|
||||
await expect.poll(() => manager.getAgent(agent.id)?.lifecycle, { timeout: 3_000 }).toBe("idle");
|
||||
} finally {
|
||||
await Promise.all(manager.listAgents().map((item) => manager.closeAgent(item.id)));
|
||||
await plugins.shutdown();
|
||||
await storage.flush();
|
||||
await rm(home, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("does not block mode changes after a plugin refuses Stop by ignoring session.interrupt", async () => {
|
||||
const logger = createTestLogger();
|
||||
let currentMode = "code";
|
||||
const harness = createProviderHarness({
|
||||
async handleInput(input, emit) {
|
||||
if (input.type === "session.open") {
|
||||
emit({
|
||||
type: "session.opened",
|
||||
requestId: input.requestId,
|
||||
sessionId: input.sessionId,
|
||||
capabilities: ["prompt.message", "session.interrupt", "session.configure"],
|
||||
restoration: "core",
|
||||
title: input.config.title,
|
||||
cwd: input.config.cwd,
|
||||
});
|
||||
emit({
|
||||
type: "session.config",
|
||||
sessionId: input.sessionId,
|
||||
config: {
|
||||
mode: currentMode,
|
||||
modes: [
|
||||
{ id: "code", label: "Code" },
|
||||
{ id: "plan", label: "Plan" },
|
||||
],
|
||||
models: [],
|
||||
thinkingOptions: [],
|
||||
},
|
||||
});
|
||||
emit({ type: "session.ready", requestId: input.requestId, sessionId: input.sessionId });
|
||||
return true;
|
||||
}
|
||||
if (input.type === "session.prompt") {
|
||||
emit({
|
||||
type: "session.prompt_result",
|
||||
sessionId: input.sessionId,
|
||||
clientMessageId: input.prompt.clientMessageId,
|
||||
result: { type: "turn", turnId: "hung-turn" },
|
||||
});
|
||||
emit({
|
||||
type: "session.turn",
|
||||
sessionId: input.sessionId,
|
||||
turnId: "hung-turn",
|
||||
state: "started",
|
||||
});
|
||||
return true;
|
||||
}
|
||||
if (input.type === "session.interrupt") {
|
||||
// Intentionally never acknowledge session.interrupt.
|
||||
return true;
|
||||
}
|
||||
if (input.type === "session.configure") {
|
||||
if (input.changes.mode) currentMode = input.changes.mode;
|
||||
emit({
|
||||
type: "session.config",
|
||||
sessionId: input.sessionId,
|
||||
config: {
|
||||
mode: currentMode,
|
||||
modes: [
|
||||
{ id: "code", label: "Code" },
|
||||
{ id: "plan", label: "Plan" },
|
||||
],
|
||||
models: [],
|
||||
thinkingOptions: [],
|
||||
},
|
||||
});
|
||||
emit({ type: "request.completed", requestId: input.requestId });
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
},
|
||||
});
|
||||
const plugins = new PluginAgentClientRegistry(logger);
|
||||
plugins.replace([harness.registration]);
|
||||
const registry = buildProviderRegistry(logger, { pluginProviders: plugins.definitions() });
|
||||
const manager = new AgentManager({
|
||||
logger,
|
||||
clients: { "plugin-direct": registry["plugin-direct"].createClient(logger) },
|
||||
providerDefinitions: { "plugin-direct": registry["plugin-direct"] },
|
||||
rescueTimeouts: { interruptSessionMs: 50 },
|
||||
});
|
||||
try {
|
||||
const agent = await manager.createAgent(
|
||||
{ provider: "plugin-direct", cwd: tmpdir() },
|
||||
undefined,
|
||||
{ workspaceId: undefined },
|
||||
);
|
||||
const stream = manager.streamAgent(agent.id, "start");
|
||||
void stream.next();
|
||||
await expect
|
||||
.poll(() => manager.getAgent(agent.id)?.lifecycle, { timeout: 2_000 })
|
||||
.toBe("running");
|
||||
|
||||
const cancelResult = await manager.cancelAgentRun(agent.id);
|
||||
expect(cancelResult.status).toBe("refused");
|
||||
|
||||
// Settings change must not hang behind the unacknowledged session.interrupt.
|
||||
await manager.setAgentMode(agent.id, "plan");
|
||||
expect(manager.getAgent(agent.id)?.currentModeId).toBe("plan");
|
||||
} finally {
|
||||
await Promise.all(manager.listAgents().map((item) => manager.closeAgent(item.id)));
|
||||
await plugins.shutdown();
|
||||
}
|
||||
});
|
||||
|
||||
test("bounds settings wait when Stop is queued behind an unanswered steer", async () => {
|
||||
const logger = createTestLogger();
|
||||
let currentMode = "code";
|
||||
let releaseSteer: (() => void) | null = null;
|
||||
const harness = createProviderHarness({
|
||||
capabilities: ["prompt.message", "prompt.steer", "session.interrupt", "session.configure"],
|
||||
async handleInput(input, emit) {
|
||||
if (input.type === "session.open") {
|
||||
emit({
|
||||
type: "session.opened",
|
||||
requestId: input.requestId,
|
||||
sessionId: input.sessionId,
|
||||
capabilities: [
|
||||
"prompt.message",
|
||||
"prompt.steer",
|
||||
"session.interrupt",
|
||||
"session.configure",
|
||||
],
|
||||
restoration: "core",
|
||||
title: input.config.title,
|
||||
cwd: input.config.cwd,
|
||||
});
|
||||
emit({
|
||||
type: "session.config",
|
||||
sessionId: input.sessionId,
|
||||
config: {
|
||||
mode: currentMode,
|
||||
modes: [
|
||||
{ id: "code", label: "Code" },
|
||||
{ id: "plan", label: "Plan" },
|
||||
],
|
||||
models: [],
|
||||
thinkingOptions: [],
|
||||
},
|
||||
});
|
||||
emit({ type: "session.ready", requestId: input.requestId, sessionId: input.sessionId });
|
||||
return true;
|
||||
}
|
||||
if (input.type === "session.prompt") {
|
||||
if (input.prompt.delivery === "steer") {
|
||||
releaseSteer = () =>
|
||||
emit({
|
||||
type: "session.prompt_result",
|
||||
sessionId: input.sessionId,
|
||||
clientMessageId: input.prompt.clientMessageId,
|
||||
result: { type: "steer", turnId: "steer-turn" },
|
||||
});
|
||||
return true;
|
||||
}
|
||||
emit({
|
||||
type: "session.prompt_result",
|
||||
sessionId: input.sessionId,
|
||||
clientMessageId: input.prompt.clientMessageId,
|
||||
result: { type: "turn", turnId: "steer-turn" },
|
||||
});
|
||||
emit({
|
||||
type: "session.turn",
|
||||
sessionId: input.sessionId,
|
||||
turnId: "steer-turn",
|
||||
state: "started",
|
||||
});
|
||||
return true;
|
||||
}
|
||||
if (input.type === "session.interrupt") {
|
||||
return true;
|
||||
}
|
||||
if (input.type === "session.configure") {
|
||||
if (input.changes.mode) currentMode = input.changes.mode;
|
||||
emit({
|
||||
type: "session.config",
|
||||
sessionId: input.sessionId,
|
||||
config: {
|
||||
mode: currentMode,
|
||||
modes: [
|
||||
{ id: "code", label: "Code" },
|
||||
{ id: "plan", label: "Plan" },
|
||||
],
|
||||
models: [],
|
||||
thinkingOptions: [],
|
||||
},
|
||||
});
|
||||
emit({ type: "request.completed", requestId: input.requestId });
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
},
|
||||
});
|
||||
const plugins = new PluginAgentClientRegistry(logger);
|
||||
plugins.replace([harness.registration]);
|
||||
const registry = buildProviderRegistry(logger, { pluginProviders: plugins.definitions() });
|
||||
const manager = new AgentManager({
|
||||
logger,
|
||||
clients: { "plugin-direct": registry["plugin-direct"].createClient(logger) },
|
||||
providerDefinitions: { "plugin-direct": registry["plugin-direct"] },
|
||||
rescueTimeouts: { interruptSessionMs: 50 },
|
||||
});
|
||||
try {
|
||||
const agent = await manager.createAgent(
|
||||
{ provider: "plugin-direct", cwd: tmpdir() },
|
||||
undefined,
|
||||
{ workspaceId: undefined },
|
||||
);
|
||||
const stream = manager.streamAgent(agent.id, "start");
|
||||
void stream.next();
|
||||
await expect
|
||||
.poll(() => manager.getAgent(agent.id)?.lifecycle, { timeout: 2_000 })
|
||||
.toBe("running");
|
||||
|
||||
// Start an unanswered steer, queue Stop behind it, then change mode.
|
||||
const steerPromise = manager.steerAgentRun(agent.id, "unanswered steer").catch(() => undefined);
|
||||
await new Promise((resolve) => setTimeout(resolve, 20));
|
||||
const stopPromise = manager.cancelAgentRun(agent.id);
|
||||
await new Promise((resolve) => setTimeout(resolve, 10));
|
||||
|
||||
// Mode change must complete within the bounded interrupt timeout even while Stop is queued.
|
||||
await manager.setAgentMode(agent.id, "plan");
|
||||
expect(manager.getAgent(agent.id)?.currentModeId).toBe("plan");
|
||||
|
||||
releaseSteer?.();
|
||||
await Promise.all([steerPromise, stopPromise]);
|
||||
} finally {
|
||||
releaseSteer?.();
|
||||
await Promise.all(manager.listAgents().map((item) => manager.closeAgent(item.id)));
|
||||
await plugins.shutdown();
|
||||
}
|
||||
});
|
||||
|
||||
@@ -19,6 +19,7 @@ import {
|
||||
type ProviderLaunch,
|
||||
requireProviderCapabilities,
|
||||
type ProviderCapability,
|
||||
type ProviderCommand,
|
||||
type ProviderConfigChanges,
|
||||
type ProviderConfigState,
|
||||
type ProviderConnection,
|
||||
@@ -663,7 +664,7 @@ class ProviderRuntimeSession {
|
||||
private closedByProvider = false;
|
||||
private closePromise: Promise<void> | null = null;
|
||||
config: ProviderConfigState = { models: [], modes: [], thinkingOptions: [] };
|
||||
commands: Array<{ name: string; description: string; argumentHint?: string }> = [];
|
||||
commands: ProviderCommand[] = [];
|
||||
persistence: ProviderPersistence | null = null;
|
||||
|
||||
constructor(
|
||||
@@ -739,6 +740,7 @@ class ProviderRuntimeSession {
|
||||
}
|
||||
|
||||
async configure(changes: ProviderConfigChanges): Promise<void> {
|
||||
if (this.terminal) throw new StaleProviderSessionError(this.id);
|
||||
const input: Extract<ProviderInput, { type: "session.configure" }> = {
|
||||
type: "session.configure",
|
||||
requestId: randomUUID(),
|
||||
@@ -1500,7 +1502,7 @@ class PluginAgentSession implements AgentSession {
|
||||
return this.bridge.commands.map((command) => ({
|
||||
...command,
|
||||
argumentHint: command.argumentHint ?? "",
|
||||
kind: "command",
|
||||
kind: command.kind ?? "command",
|
||||
}));
|
||||
}
|
||||
|
||||
|
||||
@@ -99,6 +99,74 @@ describe("ClaudeAgentSession persisted history load", () => {
|
||||
rmSync(tempRoot, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
test("resumes many records within a chunk-sized event-loop turn budget", async () => {
|
||||
const count = 3_072;
|
||||
const text = "🙂".repeat(128);
|
||||
const entries = Array.from({ length: count }, (_, index) =>
|
||||
JSON.stringify({ type: "assistant", message: { content: `${index}:${text}` } }),
|
||||
);
|
||||
entries.splice(count / 2, 0, JSON.stringify({ type: "system", subtype: "compact_boundary" }));
|
||||
mkdirSync(path.dirname(transcriptPath()), { recursive: true });
|
||||
writeFileSync(transcriptPath(), entries.join("\n"));
|
||||
|
||||
let turns = 0;
|
||||
let ticker: NodeJS.Immediate;
|
||||
function tick() {
|
||||
turns++;
|
||||
const deadline = performance.now() + 2;
|
||||
while (performance.now() < deadline) {}
|
||||
ticker = setImmediate(tick);
|
||||
}
|
||||
ticker = setImmediate(tick);
|
||||
|
||||
const session = await resume().finally(() => clearImmediate(ticker));
|
||||
|
||||
try {
|
||||
const messages = [];
|
||||
for await (const event of session.streamHistory()) {
|
||||
if (event.type === "timeline" && event.item.type === "assistant_message") {
|
||||
messages.push(event.item.text);
|
||||
}
|
||||
}
|
||||
expect(messages).toEqual(Array.from({ length: count }, (_, index) => `${index}:${text}`));
|
||||
expect(turns).toBeLessThan(count);
|
||||
} finally {
|
||||
await session.close();
|
||||
}
|
||||
}, 30_000);
|
||||
|
||||
test("yields during replay of a dense window with an expensive consumer", async () => {
|
||||
const file = transcriptPath();
|
||||
const count = 500;
|
||||
const record = JSON.stringify({ type: "assistant", message: { content: "saved reply" } });
|
||||
mkdirSync(path.dirname(file), { recursive: true });
|
||||
writeFileSync(file, (record + "\n").repeat(count));
|
||||
|
||||
await withClaudeReplayHistory(file, async (history) => {
|
||||
let turns = 0;
|
||||
let ticker: NodeJS.Immediate | undefined;
|
||||
function tick() {
|
||||
turns++;
|
||||
ticker = setImmediate(tick);
|
||||
}
|
||||
|
||||
let entries = 0;
|
||||
try {
|
||||
for await (const _entry of history.parentEntries) {
|
||||
// Start counting after the read so only yields within the window count.
|
||||
ticker ??= setImmediate(tick);
|
||||
const deadline = performance.now() + 1;
|
||||
while (performance.now() < deadline) {}
|
||||
entries++;
|
||||
}
|
||||
} finally {
|
||||
if (ticker) clearImmediate(ticker);
|
||||
}
|
||||
expect(entries).toBe(count);
|
||||
expect(turns).toBeGreaterThanOrEqual(20);
|
||||
});
|
||||
});
|
||||
|
||||
test("serves unrelated health requests while resuming 32 MiB of ordered history", async () => {
|
||||
const startedAt = performance.now();
|
||||
mkdirSync(path.dirname(transcriptPath()), { recursive: true });
|
||||
@@ -700,6 +768,75 @@ describe("ClaudeAgentSession persisted history load", () => {
|
||||
},
|
||||
);
|
||||
|
||||
test.each(["return", "throw"])(
|
||||
"replays oversized records and closes every source after callback %s",
|
||||
async (exit) => {
|
||||
const parent = transcriptPath();
|
||||
const directory = path.join(parent.slice(0, -".jsonl".length), "subagents");
|
||||
const child = path.join(directory, "agent-child.jsonl");
|
||||
const workflow = path.join(directory, "workflows", "wf_test", "agent-child.jsonl");
|
||||
const notification = {
|
||||
type: "system",
|
||||
subtype: "task_notification",
|
||||
task_id: "task-id",
|
||||
status: "completed",
|
||||
};
|
||||
const result = {
|
||||
type: "user",
|
||||
message: {
|
||||
content: [
|
||||
{ type: "tool_result", tool_use_id: "tool-id", content: "é".repeat(600 * 1024) },
|
||||
],
|
||||
},
|
||||
};
|
||||
const parentRecords = [notification, result, notification];
|
||||
const childRecords = parentRecords.map((entry) => ({
|
||||
...entry,
|
||||
isSidechain: true,
|
||||
agentId: "child",
|
||||
}));
|
||||
mkdirSync(path.dirname(workflow), { recursive: true });
|
||||
writeFileSync(parent, parentRecords.map((entry) => JSON.stringify(entry)).join("\n"));
|
||||
writeFileSync(child, childRecords.map((entry) => JSON.stringify(entry)).join("\n"));
|
||||
writeFileSync(workflow, childRecords.map((entry) => JSON.stringify(entry)).join("\n"));
|
||||
|
||||
const sources: AsyncIterable<unknown>[] = [];
|
||||
const failure = new Error("consumer failed");
|
||||
const replay = withClaudeReplayHistory(parent, async (history) => {
|
||||
const parentEntries = await Array.fromAsync(history.parentEntries);
|
||||
const firstId = expect.stringMatching(/^task_notification_.*_1$/);
|
||||
const secondId = expect.stringMatching(/^task_notification_.*_2$/);
|
||||
expect(parentEntries).toEqual([
|
||||
{ ...notification, notificationId: firstId },
|
||||
result,
|
||||
{ ...notification, notificationId: secondId },
|
||||
]);
|
||||
const [first, , last] = parentEntries;
|
||||
const childEntries = history.subagents[0]!.entries;
|
||||
const workflowEntries = history.workflowEntriesByRunId.get("wf_test")!;
|
||||
sources.push(history.parentEntries, childEntries, workflowEntries);
|
||||
const expectedChildEntries = [
|
||||
{ ...childRecords[0], notificationId: first!.notificationId },
|
||||
childRecords[1],
|
||||
{ ...childRecords[2], notificationId: last!.notificationId },
|
||||
];
|
||||
expect(await Array.fromAsync(childEntries)).toEqual(expectedChildEntries);
|
||||
expect(await Array.fromAsync(workflowEntries)).toEqual(expectedChildEntries);
|
||||
expect(await Array.fromAsync(history.parentEntries)).toEqual(parentEntries);
|
||||
if (exit === "throw") throw failure;
|
||||
});
|
||||
if (exit === "throw") await expect(replay).rejects.toBe(failure);
|
||||
else await replay;
|
||||
|
||||
// Reading again probes whether replay released each descriptor when the callback ended.
|
||||
for (const source of sources) {
|
||||
await expect(source[Symbol.asyncIterator]().next()).rejects.toMatchObject({
|
||||
code: "EBADF",
|
||||
});
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
// chmod does not remove read access on Windows, or for root.
|
||||
test.skipIf(process.platform === "win32" || process.getuid?.() === 0)(
|
||||
"logs a warning with the error when Claude's project folders cannot be listed",
|
||||
|
||||
@@ -878,11 +878,12 @@ describe("ClaudeAgentSession persisted subagent replay", () => {
|
||||
const text = "é🙂".repeat(30_000);
|
||||
const historyDir = claudeProjectDirSync(cwd, { configDir });
|
||||
mkdirSync(historyDir, { recursive: true });
|
||||
const first = parentEntry([{ type: "text", text }]);
|
||||
// Put the first byte of é at the end of a 1 MiB read.
|
||||
const padding = " ".repeat(1024 * 1024 - 1 - first.indexOf(text));
|
||||
writeFileSync(
|
||||
path.join(historyDir, "replay-session.jsonl"),
|
||||
parentEntry([{ type: "text", text }]) +
|
||||
"\r\nnot json\r\n" +
|
||||
parentEntry([{ type: "text", text: "final row" }]),
|
||||
padding + first + "\r\nnot json\r\n" + parentEntry([{ type: "text", text: "final row" }]),
|
||||
);
|
||||
const events = await replayEvents();
|
||||
expect(events.filter((event) => event.type === "timeline").map((event) => event.item)).toEqual([
|
||||
|
||||
+28
@@ -41,6 +41,34 @@ function parentEntries(
|
||||
}
|
||||
|
||||
describe("Claude workflow replay", () => {
|
||||
it("skips parent history when there are no workflow summaries", async () => {
|
||||
const entries = {
|
||||
[Symbol.iterator](): Iterator<ClaudeWorkflowParentEntry> {
|
||||
throw new Error("parent history must not be read");
|
||||
},
|
||||
};
|
||||
await expect(
|
||||
observeReplayWorkflows({ workflows: [], parentEntries: entries }),
|
||||
).resolves.toEqual([]);
|
||||
});
|
||||
|
||||
it("links workflow results from a single traversal, including results before their calls", async () => {
|
||||
const [call, result] = parentEntries();
|
||||
const entries = (async function* () {
|
||||
yield result!;
|
||||
yield call!;
|
||||
})();
|
||||
const observations = await observeReplayWorkflows({
|
||||
workflows: [{ runId: RUN_ID, status: "completed" }],
|
||||
parentEntries: entries,
|
||||
});
|
||||
expect(observations).toEqual([
|
||||
{ kind: "declared", id: TOOL_CALL_ID, toolCallId: TOOL_CALL_ID, title: "Workflow" },
|
||||
{ kind: "subtitle", id: TOOL_CALL_ID, subtitle: "Workflow" },
|
||||
{ kind: "status", id: TOOL_CALL_ID, status: "completed" },
|
||||
]);
|
||||
});
|
||||
|
||||
it("parses the persisted run summary observed from Claude Code 2.1.220", async () => {
|
||||
expect(
|
||||
parseClaudeWorkflowRun(
|
||||
|
||||
+16
-15
@@ -55,7 +55,9 @@ export async function observeReplayWorkflows(input: {
|
||||
>;
|
||||
convertEntry?: (entry: ClaudeReplayEntry) => AgentTimelineItem[] | Promise<AgentTimelineItem[]>;
|
||||
}): Promise<SubagentObservation[]> {
|
||||
const toolCallIdByRunId = await readWorkflowLinks(input.parentEntries);
|
||||
if (input.workflows.length === 0) return [];
|
||||
const runIds = new Set(input.workflows.map((workflow) => workflow.runId));
|
||||
const toolCallIdByRunId = await readWorkflowLinks(input.parentEntries, runIds);
|
||||
const observations: SubagentObservation[] = [];
|
||||
|
||||
for (const workflow of input.workflows) {
|
||||
@@ -155,34 +157,33 @@ async function observeWorkflowTimeline(input: {
|
||||
|
||||
async function readWorkflowLinks(
|
||||
entries: Iterable<ClaudeWorkflowParentEntry> | AsyncIterable<ClaudeWorkflowParentEntry>,
|
||||
runIds: ReadonlySet<string>,
|
||||
): Promise<Map<string, string>> {
|
||||
const workflowToolCallIds = new Set<string>();
|
||||
const toolCallIdByRunId = new Map<string, string>();
|
||||
|
||||
for await (const entry of entries) {
|
||||
const content = entry.message?.content;
|
||||
if (!Array.isArray(content)) continue;
|
||||
for (const value of content) {
|
||||
const block = toRecord(value);
|
||||
if (block?.type !== "tool_use" || block.name !== "Workflow") continue;
|
||||
const id = readString(block.id);
|
||||
if (id) workflowToolCallIds.add(id);
|
||||
}
|
||||
}
|
||||
const results: { runId: string; toolCallId: string }[] = [];
|
||||
|
||||
for await (const entry of entries) {
|
||||
const content = entry.message?.content;
|
||||
if (!Array.isArray(content)) continue;
|
||||
for (const value of content) {
|
||||
const block = toRecord(value);
|
||||
if (block?.type === "tool_use" && block.name === "Workflow") {
|
||||
const id = readString(block.id);
|
||||
if (id) workflowToolCallIds.add(id);
|
||||
}
|
||||
if (block?.type !== "tool_result") continue;
|
||||
const toolCallId = readString(block.tool_use_id);
|
||||
if (!toolCallId || !workflowToolCallIds.has(toolCallId)) continue;
|
||||
if (!toolCallId) continue;
|
||||
const runId = readRunId(block.content);
|
||||
if (runId) toolCallIdByRunId.set(runId, toolCallId);
|
||||
if (runId && runIds.has(runId)) results.push({ runId, toolCallId });
|
||||
}
|
||||
}
|
||||
|
||||
// Resolve IDs in result order after all calls are known, even if a result precedes its call.
|
||||
const toolCallIdByRunId = new Map<string, string>();
|
||||
for (const { runId, toolCallId } of results) {
|
||||
if (workflowToolCallIds.has(toolCallId)) toolCallIdByRunId.set(runId, toolCallId);
|
||||
}
|
||||
return toolCallIdByRunId;
|
||||
}
|
||||
|
||||
|
||||
@@ -13,6 +13,10 @@ import {
|
||||
type ClaudeWorkflowRun,
|
||||
} from "./subagents/workflow-replay-source.js";
|
||||
|
||||
const READ_CHUNK_BYTES = 1024 * 1024;
|
||||
// Async iteration between reads uses microtasks, including work inside the consumer.
|
||||
const REPLAY_SLICE_MS = 10;
|
||||
|
||||
interface TranscriptEntry extends ClaudeReplayEntry {
|
||||
isSidechain?: unknown;
|
||||
}
|
||||
@@ -43,13 +47,18 @@ async function* locatedRecords(
|
||||
let pieces: Buffer[] = [];
|
||||
let length = 0;
|
||||
while (remaining > 0) {
|
||||
const buffer = Buffer.allocUnsafe(Math.min(64 * 1024, remaining));
|
||||
const buffer = Buffer.allocUnsafe(Math.min(READ_CHUNK_BYTES, remaining));
|
||||
const { bytesRead: count } = await fd.read(buffer, 0, buffer.length, null);
|
||||
if (count === 0) break;
|
||||
remaining -= count;
|
||||
let sliceStartedAt = performance.now();
|
||||
let start = 0;
|
||||
let end: number;
|
||||
while ((end = buffer.indexOf(10, start)) !== -1 && end < count) {
|
||||
if (performance.now() - sliceStartedAt >= REPLAY_SLICE_MS) {
|
||||
await setImmediate();
|
||||
sliceStartedAt = performance.now();
|
||||
}
|
||||
pieces.push(buffer.subarray(start, end));
|
||||
length += end - start;
|
||||
const entry = parseRecord(Buffer.concat(pieces, length).toString("utf8"));
|
||||
@@ -65,8 +74,6 @@ async function* locatedRecords(
|
||||
if (entry) yield { entry, location };
|
||||
start = end + 1;
|
||||
}
|
||||
// Bound parsing work as well as IO; microtasks alone do not service timers or sockets.
|
||||
await setImmediate();
|
||||
if (start < count) {
|
||||
pieces.push(buffer.subarray(start, count));
|
||||
length += count - start;
|
||||
@@ -96,27 +103,52 @@ function indexedRecords(
|
||||
},
|
||||
};
|
||||
async function* readEntries(): AsyncGenerator<TranscriptEntry> {
|
||||
const chunk = Buffer.allocUnsafe(READ_CHUNK_BYTES);
|
||||
let window: { file: string; offset: number; bytes: Buffer } | undefined;
|
||||
let sliceStartedAt = performance.now();
|
||||
for (const location of locations) {
|
||||
const fd = descriptors.get(location.file)!;
|
||||
const buffer = Buffer.allocUnsafe(location.length);
|
||||
let read = 0;
|
||||
while (read < buffer.length) {
|
||||
const { bytesRead: count } = await fd.read(
|
||||
buffer,
|
||||
read,
|
||||
buffer.length - read,
|
||||
location.offset + read,
|
||||
);
|
||||
if (count === 0)
|
||||
throw new Error(`Claude transcript was truncated during replay: ${location.file}`);
|
||||
read += count;
|
||||
if (
|
||||
window?.file !== location.file ||
|
||||
location.offset < window.offset ||
|
||||
location.offset + location.length > window.offset + window.bytes.length
|
||||
) {
|
||||
const fd = descriptors.get(location.file)!;
|
||||
const buffer = location.length > chunk.length ? Buffer.allocUnsafe(location.length) : chunk;
|
||||
// Read ahead from the next indexed record. The index still owns selection and order,
|
||||
// including sparse sidechains and workflow records sorted across files.
|
||||
window = {
|
||||
file: location.file,
|
||||
offset: location.offset,
|
||||
bytes: await readRecordWindow(fd, buffer, location),
|
||||
};
|
||||
sliceStartedAt = performance.now();
|
||||
}
|
||||
const entry = parseRecord(buffer.toString("utf8"));
|
||||
if (performance.now() - sliceStartedAt >= REPLAY_SLICE_MS) {
|
||||
await setImmediate();
|
||||
sliceStartedAt = performance.now();
|
||||
}
|
||||
const start = location.offset - window.offset;
|
||||
const entry = parseRecord(window.bytes.toString("utf8", start, start + location.length));
|
||||
if (entry) yield entry;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function readRecordWindow(
|
||||
fd: FileHandle,
|
||||
buffer: Buffer,
|
||||
location: RecordLocation,
|
||||
): Promise<Buffer> {
|
||||
let read = 0;
|
||||
while (read < location.length) {
|
||||
const { bytesRead } = await fd.read(buffer, read, buffer.length - read, location.offset + read);
|
||||
if (bytesRead === 0)
|
||||
throw new Error(`Claude transcript was truncated during replay: ${location.file}`);
|
||||
read += bytesRead;
|
||||
}
|
||||
return buffer.subarray(0, read);
|
||||
}
|
||||
|
||||
function isToolResult(entry: TranscriptEntry): boolean {
|
||||
return (
|
||||
Array.isArray(entry.message?.content) &&
|
||||
|
||||
@@ -1,4 +1,13 @@
|
||||
import { existsSync, rmSync, statSync } from "node:fs";
|
||||
import {
|
||||
existsSync,
|
||||
mkdtempSync,
|
||||
readFileSync,
|
||||
rmSync,
|
||||
statSync,
|
||||
symlinkSync,
|
||||
writeFileSync,
|
||||
} from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { describe, expect, test } from "vitest";
|
||||
|
||||
@@ -22,3 +31,30 @@ describe.skipIf(process.platform === "win32")("materializeProviderImage", () =>
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
test.skipIf(process.platform === "win32")(
|
||||
"replaces a cached attachment directory turned into a symlink",
|
||||
async () => {
|
||||
const image = { data: "c3ltbGluayByZWdyZXNzaW9u", mimeType: "image/png" };
|
||||
const first = await materializeProviderImage(image);
|
||||
const dir = path.dirname(first.path);
|
||||
const target = mkdtempSync(path.join(os.tmpdir(), "paseo-image-symlink-test-"));
|
||||
let replacement: string | undefined;
|
||||
try {
|
||||
rmSync(dir, { recursive: true });
|
||||
// Populate the target to exercise validation before accepting a cache hit.
|
||||
writeFileSync(path.join(target, path.basename(first.path)), "symlink target");
|
||||
symlinkSync(target, dir, "dir");
|
||||
|
||||
const second = await materializeProviderImage(image);
|
||||
replacement = path.dirname(second.path);
|
||||
expect(replacement).not.toBe(dir);
|
||||
expect(path.basename(replacement)).toMatch(/^paseo-attachments-/);
|
||||
expect(readFileSync(second.path, "utf8")).toBe("symlink regression");
|
||||
} finally {
|
||||
if (replacement && replacement !== dir) rmSync(replacement, { recursive: true });
|
||||
rmSync(dir, { recursive: true, force: true });
|
||||
rmSync(target, { recursive: true, force: true });
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { AsyncLocalStorage, createHook } from "node:async_hooks";
|
||||
import { existsSync, rmSync, statSync, readFileSync } from "node:fs";
|
||||
import path from "node:path";
|
||||
import MarkdownIt from "markdown-it";
|
||||
@@ -211,7 +212,7 @@ test("64 MiB materialization leaves the event loop responsive and preserves byte
|
||||
});
|
||||
|
||||
test("preserves base64 decoding across whitespace and chunk boundaries", async () => {
|
||||
const bytes = Buffer.alloc(512 * 1024, 123);
|
||||
const bytes = Buffer.alloc(1024 * 1024, 123);
|
||||
const base64 = bytes.toString("base64");
|
||||
const data = base64.match(/.{1,77}/g)!.join("\n");
|
||||
const result = await materializeProviderImage({ data, mimeType: "image/png" });
|
||||
@@ -247,3 +248,114 @@ test("simultaneous requests for the same content share the published file", asyn
|
||||
expect(results[0]).toEqual(results[1]);
|
||||
expect(readFileSync(results[0].path).toString()).toBe("concurrent dedupe fixture");
|
||||
});
|
||||
|
||||
test("a small image finishes before an earlier distinct 64 MiB image", async () => {
|
||||
const largeData = Buffer.alloc(64 * 1024 * 1024, 42).toString("base64");
|
||||
const smallData = Buffer.from("live image during large replay").toString("base64");
|
||||
const completionOrder: string[] = [];
|
||||
const large = materializeProviderImage({ data: largeData, mimeType: "image/png" }).then(
|
||||
(image) => {
|
||||
completionOrder.push("large");
|
||||
return image;
|
||||
},
|
||||
);
|
||||
const small = materializeProviderImage({ data: smallData, mimeType: "image/png" }).then(
|
||||
(image) => {
|
||||
completionOrder.push("small");
|
||||
return image;
|
||||
},
|
||||
);
|
||||
const images = await Promise.all([large, small]);
|
||||
for (const image of images) rmSync(image.path, { force: true });
|
||||
expect(completionOrder).toEqual(["small", "large"]);
|
||||
});
|
||||
|
||||
test("publishing small distinct images stays within eight event-loop turns per image", async () => {
|
||||
const count = 20;
|
||||
const materializing = new AsyncLocalStorage<boolean>();
|
||||
let turn = 0;
|
||||
let lastActiveTurn = -1;
|
||||
let activeTurns = 0;
|
||||
const hook = createHook({
|
||||
before() {
|
||||
// A spinning immediate can tick many times while a filesystem worker is
|
||||
// still running. Count only turns that advance the materializations.
|
||||
if (materializing.getStore() && turn !== lastActiveTurn) {
|
||||
lastActiveTurn = turn;
|
||||
activeTurns++;
|
||||
}
|
||||
},
|
||||
});
|
||||
let probe = setImmediate(function tick() {
|
||||
turn++;
|
||||
probe = setImmediate(tick);
|
||||
});
|
||||
const images: string[] = [];
|
||||
hook.enable();
|
||||
try {
|
||||
await materializing.run(true, async () => {
|
||||
for (let index = 0; index < count; index++) {
|
||||
const data = Buffer.from(`small attachment ${index}`).toString("base64");
|
||||
const image = await materializeProviderImage({ data, mimeType: "image/png" });
|
||||
images.push(image.path);
|
||||
}
|
||||
});
|
||||
} finally {
|
||||
hook.disable();
|
||||
clearImmediate(probe);
|
||||
for (const image of images) rmSync(image, { force: true });
|
||||
}
|
||||
expect(activeTurns).toBeLessThanOrEqual(8 * count);
|
||||
});
|
||||
|
||||
test("six concurrent 8 MiB images share the main-thread CPU budget", async () => {
|
||||
const inputs = Array.from({ length: 6 }, (_, index) => ({
|
||||
data: Buffer.alloc(8 * 1024 * 1024, index + 1).toString("base64"),
|
||||
mimeType: "image/png",
|
||||
}));
|
||||
const threadCpuMs = () => {
|
||||
const { user, system } = process.threadCpuUsage();
|
||||
return (user + system) / 1000;
|
||||
};
|
||||
let previous = threadCpuMs();
|
||||
let longest = 0;
|
||||
const probe = setInterval(() => {
|
||||
const now = threadCpuMs();
|
||||
longest = Math.max(longest, now - previous);
|
||||
previous = now;
|
||||
}, 1);
|
||||
try {
|
||||
const images = await Promise.all(inputs.map(materializeProviderImage));
|
||||
await new Promise((resolve) => setTimeout(resolve, 5));
|
||||
for (const image of images) rmSync(image.path, { force: true });
|
||||
expect(longest).toBeLessThan(50);
|
||||
} finally {
|
||||
clearInterval(probe);
|
||||
}
|
||||
});
|
||||
|
||||
test("a busy event loop does not spend the image decode budget", async () => {
|
||||
const count = 8;
|
||||
let turns = 0;
|
||||
let probe = setImmediate(function tick() {
|
||||
turns++;
|
||||
// Simulate unrelated work that exceeds a 10 ms decode slice.
|
||||
const end = performance.now() + 20;
|
||||
while (performance.now() < end) {
|
||||
// Keep this event-loop turn busy.
|
||||
}
|
||||
probe = setImmediate(tick);
|
||||
});
|
||||
const paths: string[] = [];
|
||||
try {
|
||||
for (let index = 0; index < count; index++) {
|
||||
const data = Buffer.from(`attachment on a busy loop ${index}`).toString("base64");
|
||||
const image = await materializeProviderImage({ data, mimeType: "image/png" });
|
||||
paths.push(image.path);
|
||||
}
|
||||
} finally {
|
||||
clearImmediate(probe);
|
||||
for (const image of paths) rmSync(image, { force: true });
|
||||
}
|
||||
expect(turns).toBeLessThanOrEqual(7 * count);
|
||||
});
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import { createHash, randomUUID } from "node:crypto";
|
||||
import * as fs from "node:fs/promises";
|
||||
import { setImmediate } from "node:timers/promises";
|
||||
import os from "node:os";
|
||||
@@ -23,28 +23,26 @@ const PROVIDER_IMAGE_ATTACHMENT_DIR_PREFIX = `${PROVIDER_IMAGE_ATTACHMENT_DIR}-`
|
||||
const PRIVATE_ATTACHMENT_DIR_MODE = 0o700;
|
||||
const MATERIALIZED_IMAGE_FILE_MODE = 0o600;
|
||||
|
||||
let materializedImageAttachmentDir: string | null = null;
|
||||
// Serialize materializations: one decoder and one file operation at a time, including
|
||||
// concurrent history replay and live turns. A rejected operation must not poison the queue.
|
||||
let pendingMaterialization: Promise<unknown> = Promise.resolve();
|
||||
let attachmentDirectory: Promise<string> | undefined;
|
||||
const pendingWrites = new Map<string, Promise<MaterializedProviderImage>>();
|
||||
|
||||
async function getMaterializedImageAttachmentDir(): Promise<string> {
|
||||
if (materializedImageAttachmentDir) {
|
||||
try {
|
||||
const stats = await fs.lstat(materializedImageAttachmentDir);
|
||||
if (stats.isDirectory()) {
|
||||
await fs.chmod(materializedImageAttachmentDir, PRIVATE_ATTACHMENT_DIR_MODE);
|
||||
return materializedImageAttachmentDir;
|
||||
}
|
||||
} catch {
|
||||
/* Temp storage may have been removed between turns. */
|
||||
}
|
||||
}
|
||||
materializedImageAttachmentDir = await fs.mkdtemp(
|
||||
path.join(os.tmpdir(), PROVIDER_IMAGE_ATTACHMENT_DIR_PREFIX),
|
||||
);
|
||||
await fs.chmod(materializedImageAttachmentDir, PRIVATE_ATTACHMENT_DIR_MODE);
|
||||
return materializedImageAttachmentDir;
|
||||
function getMaterializedImageAttachmentDir(): Promise<string> {
|
||||
attachmentDirectory ??= createAttachmentDirectory().catch((error) => {
|
||||
attachmentDirectory = undefined;
|
||||
throw error;
|
||||
});
|
||||
return attachmentDirectory;
|
||||
}
|
||||
|
||||
async function createAttachmentDirectory(): Promise<string> {
|
||||
const dir = await fs.mkdtemp(path.join(os.tmpdir(), PROVIDER_IMAGE_ATTACHMENT_DIR_PREFIX));
|
||||
await fs.chmod(dir, PRIVATE_ATTACHMENT_DIR_MODE);
|
||||
return dir;
|
||||
}
|
||||
|
||||
function isMissingPath(error: unknown): boolean {
|
||||
const code = (error as NodeJS.ErrnoException).code;
|
||||
return code === "ENOENT" || code === "ENOTDIR";
|
||||
}
|
||||
|
||||
function getImageExtension(mimeType: string): string {
|
||||
@@ -69,18 +67,18 @@ function getImageExtension(mimeType: string): string {
|
||||
// 128 MiB admits the measured 64 MiB fixture with headroom while bounding disk
|
||||
// and decoding per image. This is materialization admission, not a wire schema limit.
|
||||
export const MAX_PROVIDER_IMAGE_BYTES = 128 * 1024 * 1024;
|
||||
const BASE64_CHUNK_CHARACTERS = 256 * 1024; // Multiple of four; decode units stay aligned.
|
||||
const BASE64_CHUNK_CHARACTERS = 1024 * 1024; // Multiple of four; decode units stay aligned.
|
||||
const DECODE_SLICE_MS = 10;
|
||||
let decodeBudgetMs = DECODE_SLICE_MS;
|
||||
let pendingDecodeYield: Promise<void> | undefined;
|
||||
|
||||
export function materializeProviderImage(image: {
|
||||
data: string;
|
||||
mimeType: string | null;
|
||||
}): Promise<MaterializedProviderImage> {
|
||||
const result = pendingMaterialization.then(() => materializeImage(image));
|
||||
pendingMaterialization = result.catch(() => {});
|
||||
return result;
|
||||
async function refillDecodeBudget(): Promise<void> {
|
||||
await setImmediate();
|
||||
decodeBudgetMs = DECODE_SLICE_MS;
|
||||
pendingDecodeYield = undefined;
|
||||
}
|
||||
|
||||
async function materializeImage(image: {
|
||||
export async function materializeProviderImage(image: {
|
||||
data: string;
|
||||
mimeType: string | null;
|
||||
}): Promise<MaterializedProviderImage> {
|
||||
@@ -103,32 +101,74 @@ async function materializeImage(image: {
|
||||
}
|
||||
const hash = createHash("sha256");
|
||||
for await (const bytes of decodeImage(data)) hash.update(bytes);
|
||||
const dir = await getMaterializedImageAttachmentDir();
|
||||
const filePath = path.join(dir, `${hash.digest("hex")}.${getImageExtension(mimeType)}`);
|
||||
const filename = `${hash.digest("hex")}.${getImageExtension(mimeType)}`;
|
||||
const directory = getMaterializedImageAttachmentDir();
|
||||
const dir = await directory;
|
||||
try {
|
||||
await fs.stat(filePath);
|
||||
return { path: filePath };
|
||||
return await materializeInDirectory(dir, filename, data);
|
||||
} catch (error) {
|
||||
if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
|
||||
if (!isMissingPath(error)) throw error;
|
||||
// Other requests may have already replaced the directory after the same deletion.
|
||||
if (attachmentDirectory === directory) attachmentDirectory = undefined;
|
||||
const replacement = await getMaterializedImageAttachmentDir();
|
||||
return materializeInDirectory(replacement, filename, data);
|
||||
}
|
||||
}
|
||||
|
||||
const staging = await fs.mkdtemp(path.join(dir, ".pending-"));
|
||||
const stagingPath = path.join(staging, "image");
|
||||
function materializeInDirectory(
|
||||
dir: string,
|
||||
filename: string,
|
||||
data: string,
|
||||
): Promise<MaterializedProviderImage> {
|
||||
const filePath = path.join(dir, filename);
|
||||
const pending = pendingWrites.get(filePath);
|
||||
if (pending) return pending;
|
||||
|
||||
const write = publishImage(dir, filePath, data).finally(() => {
|
||||
pendingWrites.delete(filePath);
|
||||
});
|
||||
pendingWrites.set(filePath, write);
|
||||
return write;
|
||||
}
|
||||
|
||||
async function publishImage(
|
||||
dir: string,
|
||||
filePath: string,
|
||||
data: string,
|
||||
): Promise<MaterializedProviderImage> {
|
||||
const [directory, existing] = await Promise.allSettled([fs.lstat(dir), fs.stat(filePath)]);
|
||||
if (directory.status === "rejected") throw directory.reason;
|
||||
const stats = directory.value;
|
||||
const uid = process.platform === "win32" ? undefined : process.getuid?.();
|
||||
if (
|
||||
!stats.isDirectory() ||
|
||||
(uid !== undefined && (stats.uid !== uid || (stats.mode & 0o077) !== 0))
|
||||
) {
|
||||
throw Object.assign(new Error("Private image attachment directory is unavailable"), {
|
||||
code: "ENOENT",
|
||||
});
|
||||
}
|
||||
if (existing.status === "fulfilled") return { path: filePath };
|
||||
if (!isMissingPath(existing.reason)) throw existing.reason;
|
||||
|
||||
const stagingPath = path.join(dir, `.pending-${randomUUID()}`);
|
||||
const file = await fs.open(stagingPath, "wx", MATERIALIZED_IMAGE_FILE_MODE);
|
||||
try {
|
||||
await fs.chmod(staging, PRIVATE_ATTACHMENT_DIR_MODE);
|
||||
const file = await fs.open(stagingPath, "wx", MATERIALIZED_IMAGE_FILE_MODE);
|
||||
try {
|
||||
// Restore owner permissions if the umask masked them at open.
|
||||
await file.chmod(MATERIALIZED_IMAGE_FILE_MODE);
|
||||
// Decode again only for a new hash. This bounds retained memory to one chunk
|
||||
// and performs no writes at all for repeated content, including history replay.
|
||||
// Decode again only for new content, retaining one chunk at a time.
|
||||
for await (const bytes of decodeImage(data)) await file.writeFile(bytes);
|
||||
} finally {
|
||||
await file.close();
|
||||
}
|
||||
await fs.rename(stagingPath, filePath);
|
||||
return { path: filePath };
|
||||
} finally {
|
||||
await fs.rm(staging, { recursive: true, force: true });
|
||||
} catch (error) {
|
||||
await fs.unlink(stagingPath).catch((cleanupError) => {
|
||||
if (!isMissingPath(cleanupError)) throw cleanupError;
|
||||
});
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -136,6 +176,13 @@ async function* decodeImage(data: string): AsyncGenerator<Buffer> {
|
||||
let carry = "";
|
||||
let decodedBytes = 0;
|
||||
for (let offset = 0; offset < data.length; offset += BASE64_CHUNK_CHARACTERS) {
|
||||
let pause = pendingDecodeYield;
|
||||
while (pause) {
|
||||
await pause;
|
||||
pause = pendingDecodeYield;
|
||||
}
|
||||
// Charge synchronous work across decoders. File I/O and idle time leave the budget intact.
|
||||
const startedAt = performance.now();
|
||||
// Buffer.from ignores non-base64 characters. Carry incomplete quartets so
|
||||
// line-wrapped payloads decode identically across chunk boundaries.
|
||||
const chunk =
|
||||
@@ -144,12 +191,13 @@ async function* decodeImage(data: string): AsyncGenerator<Buffer> {
|
||||
const finalChunk = offset + BASE64_CHUNK_CHARACTERS >= data.length || chunk.includes("=");
|
||||
const end = finalChunk ? chunk.length : chunk.length - (chunk.length % 4);
|
||||
const bytes = Buffer.from(chunk.slice(0, end), "base64");
|
||||
decodeBudgetMs -= performance.now() - startedAt;
|
||||
if (decodeBudgetMs <= 0) pendingDecodeYield = refillDecodeBudget();
|
||||
carry = chunk.slice(end);
|
||||
decodedBytes += bytes.length;
|
||||
if (decodedBytes > MAX_PROVIDER_IMAGE_BYTES)
|
||||
throw new Error("Image attachment exceeds size limit");
|
||||
yield bytes;
|
||||
await setImmediate();
|
||||
if (finalChunk) break;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -139,6 +139,9 @@ 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"];
|
||||
@@ -3415,11 +3418,17 @@ 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,6 +6,7 @@ import type { DaemonConfigStore } from "../daemon-config-store.js";
|
||||
import {
|
||||
archiveByScope,
|
||||
type ActiveWorkspaceRef,
|
||||
type ArchiveDependencies,
|
||||
killTerminalsForWorkspace,
|
||||
} from "../workspace-archive-service.js";
|
||||
import type {
|
||||
@@ -16,10 +17,15 @@ 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;
|
||||
@@ -99,11 +105,15 @@ 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(
|
||||
|
||||
@@ -184,6 +184,7 @@ 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";
|
||||
@@ -214,7 +215,10 @@ 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 } from "./workspace-automation-gate.js";
|
||||
import {
|
||||
assertWorkspaceAutomationAllowedForWorkspace,
|
||||
isCheckoutUntrusted,
|
||||
} from "./workspace-automation-gate.js";
|
||||
import { spawnWorkspaceScript } from "./worktree-bootstrap.js";
|
||||
import {
|
||||
createManagedProcessRegistry,
|
||||
@@ -743,6 +747,7 @@ 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) => {
|
||||
@@ -1166,6 +1171,8 @@ 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) => {
|
||||
@@ -1224,6 +1231,8 @@ export async function createPaseoDaemon(
|
||||
setupAutoArchiveOnMerge({
|
||||
paseoHome: config.paseoHome,
|
||||
paseoWorktreesBaseRoot: config.worktreesRoot,
|
||||
worktreeManagers: pluginRuntime,
|
||||
workspaceArchiveOperations,
|
||||
daemonConfigStore,
|
||||
workspaceGitService,
|
||||
github,
|
||||
@@ -1232,6 +1241,8 @@ 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,
|
||||
@@ -1252,6 +1263,7 @@ export async function createPaseoDaemon(
|
||||
createPaseoWorktree: async (workflowInput, workflowOptions) => {
|
||||
return createRegisteredPaseoWorktree(workflowInput, {
|
||||
lifecycle: pluginRuntime,
|
||||
worktreeManagers: pluginRuntime,
|
||||
github,
|
||||
...(workflowOptions?.resolveDefaultBranch
|
||||
? {
|
||||
@@ -1312,6 +1324,8 @@ export async function createPaseoDaemon(
|
||||
{
|
||||
paseoHome: config.paseoHome,
|
||||
paseoWorktreesBaseRoot: config.worktreesRoot,
|
||||
worktreeManagers: pluginRuntime,
|
||||
workspaceArchiveOperations,
|
||||
github,
|
||||
workspaceGitService,
|
||||
agentManager,
|
||||
@@ -1329,6 +1343,7 @@ 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 },
|
||||
@@ -1336,6 +1351,10 @@ 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,
|
||||
@@ -1434,6 +1453,8 @@ export async function createPaseoDaemon(
|
||||
{
|
||||
paseoHome: config.paseoHome,
|
||||
paseoWorktreesBaseRoot: config.worktreesRoot,
|
||||
worktreeManagers: pluginRuntime,
|
||||
workspaceArchiveOperations,
|
||||
github,
|
||||
workspaceGitService,
|
||||
agentManager,
|
||||
@@ -1457,6 +1478,7 @@ export async function createPaseoDaemon(
|
||||
stopWorkspaceSetup: (workspaceIdToStop) => workspaceSetupRuntime.stop(workspaceIdToStop),
|
||||
assertWorkspaceAutomationAllowed: (guardedWorkspaceId) =>
|
||||
assertWorkspaceAutomationAllowedForWorkspace(workspaceRegistry, guardedWorkspaceId),
|
||||
isCheckoutUntrusted: (checkoutPath) => isCheckoutUntrusted(workspaceRegistry, checkoutPath),
|
||||
sessionLogger: logger,
|
||||
},
|
||||
{
|
||||
@@ -1583,6 +1605,9 @@ export async function createPaseoDaemon(
|
||||
daemonConfigStore,
|
||||
github,
|
||||
workspaceGitService,
|
||||
worktreeManagers: pluginRuntime,
|
||||
workspaceArchiveOperations,
|
||||
isCheckoutUntrusted: (checkoutPath) => isCheckoutUntrusted(workspaceRegistry, checkoutPath),
|
||||
findWorkspaceIdForCwd: findWorkspaceIdForCwdExternal,
|
||||
listActiveWorkspaces: listActiveWorkspacesExternal,
|
||||
archiveWorkspaceRecord: (workspaceId, archivedAt) =>
|
||||
@@ -1930,6 +1955,7 @@ export async function createPaseoDaemon(
|
||||
pluginRuntime,
|
||||
orchestrationSkills,
|
||||
workspaceLabelService,
|
||||
workspaceArchiveOperations,
|
||||
);
|
||||
pluginRuntime.bindPaseoSessionHost(wsServer);
|
||||
await pluginRuntime.start();
|
||||
|
||||
@@ -2,6 +2,7 @@ import { mkdir, mkdtemp, rename, rm, writeFile } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { basename, dirname, join, sep } from "node:path";
|
||||
import { afterEach, expect, test, vi } from "vitest";
|
||||
import { createWatcherLivenessCanary } from "../watcher-liveness-canary.js";
|
||||
import {
|
||||
createFileObserver,
|
||||
type FileChange,
|
||||
@@ -167,12 +168,17 @@ test("survives atomic replacement and remains observable", async () => {
|
||||
const root = await createRoot();
|
||||
const target = join(root, "target.txt");
|
||||
await writeFile(target, "before");
|
||||
const canary = createWatcherLivenessCanary(root);
|
||||
const events: FileChange[] = [];
|
||||
const subscription = await subscribeToFileChanges(root, (error, batch) => {
|
||||
expect(error).toBeNull();
|
||||
events.push(...batch);
|
||||
events.push(...canary.filterEvents(batch));
|
||||
});
|
||||
|
||||
// macOS starts delivering native events asynchronously after subscription.
|
||||
await canary.verify();
|
||||
events.length = 0;
|
||||
|
||||
const replacement = join(root, "replacement.txt");
|
||||
await writeFile(replacement, "after");
|
||||
await rename(replacement, target);
|
||||
|
||||
@@ -2,6 +2,7 @@ import { mkdtemp, rm, writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { tmpdir } from "node:os";
|
||||
import { expect, test } from "vitest";
|
||||
import { createWatcherLivenessCanary } from "../watcher-liveness-canary.js";
|
||||
import type { FileChange } from "./index.js";
|
||||
import { createNativeRecursiveBackend } from "./internal/native-recursive.js";
|
||||
import { createObserverPaths } from "./internal/paths.js";
|
||||
@@ -9,6 +10,7 @@ import { createObserverPaths } from "./internal/paths.js";
|
||||
test("the recursive watcher remembers newly announced files before reconciliation", async () => {
|
||||
const root = await mkdtemp(join(tmpdir(), "paseo-observer-native-"));
|
||||
const paths = createObserverPaths(process.platform);
|
||||
const canary = createWatcherLivenessCanary(root);
|
||||
const changes: FileChange[] = [];
|
||||
let active = true;
|
||||
const backend = createNativeRecursiveBackend(
|
||||
@@ -34,7 +36,7 @@ test("the recursive watcher remembers newly announced files before reconciliatio
|
||||
isIgnored: () => false,
|
||||
isPathInside: paths.isInside,
|
||||
queueEvent: (type, path) => {
|
||||
changes.push({ type, path });
|
||||
changes.push(...canary.filterEvents([{ type, path }]));
|
||||
},
|
||||
fail: (error) => {
|
||||
throw error;
|
||||
@@ -44,6 +46,9 @@ test("the recursive watcher remembers newly announced files before reconciliatio
|
||||
);
|
||||
try {
|
||||
await backend.start();
|
||||
await canary.verify();
|
||||
// Reconcile the removed probe before counting the files announced by the test.
|
||||
await backend.updateIgnore();
|
||||
const path = join(root, "new.txt");
|
||||
await writeFile(path, "created");
|
||||
await expect
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
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";
|
||||
|
||||
@@ -63,6 +64,10 @@ 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">;
|
||||
}
|
||||
@@ -114,22 +119,13 @@ 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,
|
||||
...(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,
|
||||
},
|
||||
}
|
||||
: {}),
|
||||
untrustedSource: createdWorktree.untrustedSource,
|
||||
});
|
||||
|
||||
deps.github.invalidate({ cwd: createdWorktree.worktree.worktreePath });
|
||||
@@ -152,6 +148,10 @@ 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,6 +286,10 @@ 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;
|
||||
|
||||
@@ -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 } from "./runtime.js";
|
||||
import { PluginRuntime, type PluginWorktreeManagerRuntime } from "./runtime.js";
|
||||
import type { PluginRuntimeSubscription } from "./runtime-subscription.js";
|
||||
import { BuiltinPluginLoader, type BuiltinPlugin } from "./builtin/index.js";
|
||||
import type {
|
||||
@@ -50,6 +50,10 @@ 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"];
|
||||
@@ -192,6 +196,31 @@ 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,7 +57,12 @@ const changeRequestFields = {
|
||||
};
|
||||
const worktreeRequestSchema = z.discriminatedUnion("kind", [
|
||||
z
|
||||
.object({ ...worktreeRequestFields, kind: z.literal("branch-off"), baseRef: z.string().min(1) })
|
||||
.object({
|
||||
...worktreeRequestFields,
|
||||
kind: z.literal("branch-off"),
|
||||
baseRef: z.string().min(1),
|
||||
startPoint: z.string().min(1).optional(),
|
||||
})
|
||||
.strict(),
|
||||
z
|
||||
.object({
|
||||
@@ -239,6 +244,28 @@ 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],
|
||||
@@ -280,9 +307,7 @@ 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);
|
||||
if (previous.repoRoot !== next.repoRoot || previous.sourceCheckout !== next.sourceCheckout) {
|
||||
throw new Error("worktree.create.before hooks cannot change repoRoot or sourceCheckout");
|
||||
}
|
||||
return validateWorktreeBeforeResult(previous, next) as PluginWireBeforeRequests[Name];
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
@@ -45,6 +45,11 @@ 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 }
|
||||
@@ -84,6 +89,10 @@ 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 }
|
||||
@@ -115,6 +124,10 @@ 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[];
|
||||
@@ -122,6 +135,7 @@ export type PluginProcessMessage =
|
||||
providers: PluginProviderMetadata[];
|
||||
usageSources?: PluginUsageSourceMetadata[];
|
||||
hooks?: string[];
|
||||
worktreeManager?: PluginWorktreeManagerCapabilities | null;
|
||||
}
|
||||
| { type: "result"; requestId: string; output: unknown }
|
||||
| { type: "error"; requestId: string; error: string }
|
||||
@@ -149,6 +163,12 @@ 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({
|
||||
@@ -294,6 +314,14 @@ 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"),
|
||||
@@ -356,6 +384,12 @@ 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"),
|
||||
@@ -364,6 +398,7 @@ 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,6 +16,10 @@ import type {
|
||||
PluginHandlerContext,
|
||||
PluginServerContext,
|
||||
PluginServerContribution,
|
||||
PluginWorktreeCreateInput,
|
||||
PluginWorktreeRemoveRequest,
|
||||
PluginWorktreeRestoreRequest,
|
||||
WorktreeManagerRegistration,
|
||||
} from "@getpaseo/plugin/server";
|
||||
import { assertPluginWireValue } from "@getpaseo/protocol/binary-frames/index";
|
||||
import {
|
||||
@@ -115,6 +119,8 @@ 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> }
|
||||
@@ -228,6 +234,36 @@ 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,
|
||||
@@ -433,6 +469,7 @@ export function createPluginWorker(options: {
|
||||
handle,
|
||||
registerProvider,
|
||||
registerUsageSource,
|
||||
registerWorktreeManager,
|
||||
registerSettings,
|
||||
addHook: hooks.addHook,
|
||||
on: hooks.on,
|
||||
@@ -459,6 +496,7 @@ 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),
|
||||
@@ -478,6 +516,8 @@ 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 {
|
||||
@@ -519,6 +559,9 @@ 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" });
|
||||
@@ -704,6 +747,10 @@ export function createPluginWorker(options: {
|
||||
handleHookMessage(message);
|
||||
return;
|
||||
}
|
||||
if (isWorktreeMessage(message)) {
|
||||
handleWorktreeMessage(message);
|
||||
return;
|
||||
}
|
||||
if (message.type === "invoke") invoke(message);
|
||||
else handleSubscriptionMessage(message);
|
||||
}
|
||||
@@ -769,6 +816,88 @@ 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 };
|
||||
}
|
||||
|
||||
|
||||
@@ -257,6 +257,59 @@ afterEach(async () => {
|
||||
});
|
||||
|
||||
describe("PluginRuntime", () => {
|
||||
it("reports a spent create budget without blaming a manager it did not call", async () => {
|
||||
const first = await createPlugin(
|
||||
"first-manager",
|
||||
`import { existsSync, writeFileSync } from "node:fs";
|
||||
import path from "node:path";
|
||||
|
||||
export default function contribute(server) {
|
||||
return server.registerWorktreeManager({
|
||||
async create({ path: directory }, { signal }) {
|
||||
writeFileSync(path.join(directory, "started"), "");
|
||||
while (!existsSync(path.join(directory, "decline"))) {
|
||||
signal.throwIfAborted();
|
||||
await new Promise((resolve) => setTimeout(resolve, 20));
|
||||
}
|
||||
},
|
||||
});
|
||||
}`,
|
||||
);
|
||||
const second = await createPlugin(
|
||||
"second-manager",
|
||||
`export default function contribute(server) {
|
||||
return server.registerWorktreeManager({
|
||||
async create() { throw new Error("Second manager was called"); },
|
||||
});
|
||||
}`,
|
||||
);
|
||||
const runtime = createTestRuntime();
|
||||
try {
|
||||
await runtime.startPlugin("first-manager", first);
|
||||
await runtime.startPlugin("second-manager", second);
|
||||
// Advance the deadline clock while real subprocess IPC and timers keep running.
|
||||
vi.useFakeTimers({ toFake: ["Date"] });
|
||||
const creation = runtime.createWorktree({
|
||||
kind: "branch-off",
|
||||
repoRoot: first,
|
||||
sourceCheckout: first,
|
||||
branch: "topic",
|
||||
slug: "topic",
|
||||
path: first,
|
||||
baseRef: "main",
|
||||
untrusted: false,
|
||||
});
|
||||
const failure = creation.catch((error: unknown) => error);
|
||||
await expect.poll(() => readTextIfPresent(path.join(first, "started"))).toBe("");
|
||||
vi.setSystemTime(Date.now() + 120_000);
|
||||
await writeFile(path.join(first, "decline"), "");
|
||||
expect(await failure).toMatchObject({ message: "Worktree creation manager budget expired" });
|
||||
} finally {
|
||||
vi.useRealTimers();
|
||||
await runtime.stopAll();
|
||||
}
|
||||
});
|
||||
|
||||
it.each([
|
||||
{ specifier: "@getpaseo/plugin", moduleDirectory: "shared" },
|
||||
{ specifier: "@getpaseo/plugin", moduleDirectory: "server" },
|
||||
|
||||
@@ -18,7 +18,15 @@ import {
|
||||
type ProviderStatus,
|
||||
type ProviderStatusRequest,
|
||||
} from "@getpaseo/plugin/server/provider";
|
||||
import type { PluginHookEvents, PluginHookAgent, AgentToolResult } from "@getpaseo/plugin/server";
|
||||
import type {
|
||||
PluginHookEvents,
|
||||
PluginHookAgent,
|
||||
AgentToolResult,
|
||||
PluginWorktreeCreateInput,
|
||||
PluginWorktreeRemoveRequest,
|
||||
PluginWorktreeRestoreRequest,
|
||||
} from "@getpaseo/plugin/server";
|
||||
import { z } from "zod";
|
||||
import { validateBeforeRequest, validateBeforeResult } from "./lifecycle/index.js";
|
||||
import { fork } from "node:child_process";
|
||||
import path from "node:path";
|
||||
@@ -42,6 +50,7 @@ import type {
|
||||
PluginProcessRequest,
|
||||
PluginProviderMetadata,
|
||||
PluginUsageSourceMetadata,
|
||||
PluginWorktreeManagerCapabilities,
|
||||
} from "./plugin-process-protocol.js";
|
||||
import { PluginProcessMessageSchema } from "./plugin-process-protocol.js";
|
||||
import {
|
||||
@@ -53,7 +62,40 @@ 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;
|
||||
@@ -87,6 +129,8 @@ 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 {
|
||||
@@ -100,6 +144,7 @@ interface LoadedPlugin {
|
||||
subscriptionMethods: ReadonlySet<string>;
|
||||
subscriptions: Map<string, BufferedPluginSubscription>;
|
||||
hooks: string[];
|
||||
worktreeManager: PluginWorktreeManagerCapabilities | null;
|
||||
providers: readonly PluginProviderMetadata[];
|
||||
usageSources: readonly PluginUsageSourceMetadata[];
|
||||
child: PluginChild | null;
|
||||
@@ -293,8 +338,17 @@ 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;
|
||||
@@ -752,6 +806,109 @@ 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));
|
||||
// All create callbacks share one timeout budget.
|
||||
const deadline = Date.now() + WORKTREE_MANAGER_TIMEOUT_MS;
|
||||
for (const loaded of plugins) {
|
||||
const remainingMs = deadline - Date.now();
|
||||
if (remainingMs <= 0) {
|
||||
throw new Error("Worktree creation manager budget expired");
|
||||
}
|
||||
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,
|
||||
@@ -853,12 +1010,14 @@ 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("Tool call canceled"));
|
||||
reject(signal?.reason ?? new Error("Plugin request canceled"));
|
||||
};
|
||||
const timeoutMs = requestTimeoutMs(message);
|
||||
const timeoutMs = options.timeoutMs ?? requestTimeoutMs(message);
|
||||
const timeout =
|
||||
timeoutMs === null
|
||||
? undefined
|
||||
@@ -870,6 +1029,9 @@ 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;
|
||||
@@ -935,6 +1097,7 @@ export class PluginRuntime {
|
||||
subscriptionMethods: new Set(),
|
||||
subscriptions: new Map(),
|
||||
hooks: [],
|
||||
worktreeManager: null,
|
||||
providers: [],
|
||||
usageSources: [],
|
||||
child: null,
|
||||
@@ -1067,6 +1230,7 @@ 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,
|
||||
@@ -1156,6 +1320,10 @@ 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,10 +1,25 @@
|
||||
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;
|
||||
@@ -156,7 +171,11 @@ async function fetchChangeRequestHead(params: {
|
||||
changeRequest: { number: number; forge?: string };
|
||||
repoRoot: string;
|
||||
deps: ResolveWorktreeCreationIntentDeps;
|
||||
}): Promise<{ baseBranch: string; startPoint: string }> {
|
||||
}): Promise<{
|
||||
baseBranch: string;
|
||||
startPoint: string;
|
||||
untrustedSource?: UntrustedWorkspaceSource;
|
||||
}> {
|
||||
const { input, changeRequest, repoRoot, deps } = params;
|
||||
assertCheckoutSourceMatchesResolvedForge(changeRequest, deps);
|
||||
const checkout = await resolvePrCheckoutIntent({
|
||||
@@ -165,6 +184,7 @@ async function fetchChangeRequestHead(params: {
|
||||
repoRoot,
|
||||
deps,
|
||||
});
|
||||
const untrustedSource = worktreeUntrustedSource(checkout);
|
||||
const startPoint = `refs/paseo/change-requests/${changeRequest.number}`;
|
||||
const remote = await deps.fetchRef({
|
||||
repoRoot,
|
||||
@@ -180,10 +200,10 @@ async function fetchChangeRequestHead(params: {
|
||||
sources: [{ remoteName: remote, remoteRef: `refs/heads/${baseName}` }],
|
||||
destination: baseBranch,
|
||||
});
|
||||
return { baseBranch, startPoint };
|
||||
return { baseBranch, startPoint, untrustedSource };
|
||||
} catch {
|
||||
// Without the remote's copy, the base resolves as any base branch name does.
|
||||
return { baseBranch: baseName, startPoint };
|
||||
return { baseBranch: baseName, startPoint, untrustedSource };
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -529,6 +529,10 @@ 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: () => [
|
||||
{
|
||||
@@ -670,6 +674,10 @@ 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 () => {
|
||||
|
||||
@@ -113,6 +113,7 @@ import {
|
||||
assertWorkspaceAutomationAllowedForWorkspace,
|
||||
clearWorkspaceAutomationBlock,
|
||||
formatWorkspaceAutomationBlockedMessage,
|
||||
isCheckoutUntrusted,
|
||||
} from "./workspace-automation-gate.js";
|
||||
import {
|
||||
WorkspaceLabelError,
|
||||
@@ -246,7 +247,12 @@ import {
|
||||
matchesAgentUpdatesFilter,
|
||||
type AgentUpdatesService,
|
||||
} from "./session/agent-updates/agent-updates-service.js";
|
||||
import { expandTilde } from "../utils/path.js";
|
||||
import {
|
||||
createRealpathAwarePathMatcher,
|
||||
expandTilde,
|
||||
isRealpathInsideRoot,
|
||||
normalizePathForIdentity,
|
||||
} from "../utils/path.js";
|
||||
import {
|
||||
searchDirectoryEntries,
|
||||
WORKSPACE_SEARCH_HIDDEN_DIRECTORIES,
|
||||
@@ -287,7 +293,11 @@ import {
|
||||
handleWorkspaceSetupStatusRequest as handleWorkspaceSetupStatusRequestMessage,
|
||||
handleWorkspaceSetupRunRequest as handleWorkspaceSetupRunRequestMessage,
|
||||
} from "./worktree-session.js";
|
||||
import { archiveByScope, type ActiveWorkspaceRef } from "./workspace-archive-service.js";
|
||||
import {
|
||||
archiveByScope,
|
||||
resolveWorkspaceBackingPath,
|
||||
type ActiveWorkspaceRef,
|
||||
} from "./workspace-archive-service.js";
|
||||
import {
|
||||
WorkspaceArchiveOperations,
|
||||
type WorkspaceArchiveUndoInput,
|
||||
@@ -529,6 +539,10 @@ 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: {
|
||||
@@ -1034,12 +1048,34 @@ 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({
|
||||
@@ -1251,9 +1287,15 @@ 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,
|
||||
@@ -1292,7 +1334,6 @@ export class Session {
|
||||
},
|
||||
);
|
||||
this.workspaceSetupRuntime = resolveWorkspaceSetupRuntime(workspaceSetupRuntime);
|
||||
this.workspaceArchiveOperations = resolveWorkspaceArchiveOperations(workspaceArchiveOperations);
|
||||
this.getDaemonTcpPort = getDaemonTcpPort ?? null;
|
||||
this.getDaemonTcpHost = getDaemonTcpHost ?? null;
|
||||
this.serviceProxyPublicBaseUrl = serviceProxyPublicBaseUrl ?? null;
|
||||
@@ -5782,11 +5823,14 @@ 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),
|
||||
@@ -5798,6 +5842,8 @@ export class Session {
|
||||
clearWorkspaceArchiving: (workspaceIds) => this.clearWorkspaceArchiving(workspaceIds),
|
||||
killTerminalsForWorkspace: (workspaceId) =>
|
||||
this.terminalController.killTerminalsForWorkspace(workspaceId),
|
||||
isCheckoutUntrusted: (checkoutPath) =>
|
||||
isCheckoutUntrusted(this.workspaceRegistry, checkoutPath),
|
||||
sessionLogger: this.sessionLogger,
|
||||
},
|
||||
msg,
|
||||
@@ -6503,9 +6549,60 @@ 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.workspaceRecovery.restore(workspaceId);
|
||||
await this.publishRecoveredWorkspace(workspaceId);
|
||||
await this.workspaceArchiveOperations.restore(workspaceId, () =>
|
||||
this.withWorkspaceCheckout(workspaceId, async () => {
|
||||
await this.workspaceRecovery.restore(workspaceId);
|
||||
await this.publishRecoveredWorkspace(workspaceId);
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
private async publishRecoveredWorkspace(workspaceId: string): Promise<void> {
|
||||
@@ -6552,6 +6649,7 @@ export class Session {
|
||||
): Promise<CreatePaseoWorktreeResult> {
|
||||
const result = await createPaseoWorktree(input, {
|
||||
lifecycle: this.pluginRuntime,
|
||||
worktreeManagers: this.pluginRuntime,
|
||||
github: this.github,
|
||||
...(options?.resolveDefaultBranch
|
||||
? { resolveDefaultBranch: options.resolveDefaultBranch }
|
||||
@@ -6582,6 +6680,8 @@ export class Session {
|
||||
worktreeRoot: workspace.worktreeRoot,
|
||||
isPaseoOwnedWorktree: workspace.isPaseoOwnedWorktree,
|
||||
mainRepoRoot: workspace.mainRepoRoot,
|
||||
worktreeManagerPluginId: workspace.worktreeManagerPluginId,
|
||||
untrustedSource: workspace.untrustedSource,
|
||||
}));
|
||||
}
|
||||
|
||||
@@ -7436,24 +7536,29 @@ 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 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 backgroundIntent = 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(
|
||||
@@ -7535,34 +7640,41 @@ 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 projectsBefore = new Map<string, PersistedProjectRecord>();
|
||||
for (const project of await this.projectRegistry.list()) {
|
||||
projectsBefore.set(project.projectId, project);
|
||||
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 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 { workspace, projectsBefore, workspacesBefore } = opened;
|
||||
const project = await this.projectRegistry.get(workspace.projectId);
|
||||
await this.syncWorkspaceGitObserverForWorkspace(workspace);
|
||||
const descriptor = await this.describeWorkspaceRecord(workspace);
|
||||
@@ -8130,6 +8242,8 @@ export class Session {
|
||||
{
|
||||
paseoHome: this.paseoHome,
|
||||
paseoWorktreesBaseRoot: this.worktreesRoot,
|
||||
worktreeManagers: this.pluginRuntime,
|
||||
workspaceArchiveOperations: this.workspaceArchiveOperations,
|
||||
github: this.github,
|
||||
workspaceGitService: this.workspaceGitService,
|
||||
agentManager: this.agentManager,
|
||||
@@ -8146,6 +8260,8 @@ 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),
|
||||
@@ -8208,7 +8324,9 @@ export class Session {
|
||||
): Promise<void> {
|
||||
try {
|
||||
await this.workspaceArchiveOperations.undo(request.workspaceId, (input) =>
|
||||
this.restoreArchivedWorkspaceAndAgents(request.workspaceId, input),
|
||||
this.withWorkspaceCheckout(request.workspaceId, () =>
|
||||
this.restoreArchivedWorkspaceAndAgents(request.workspaceId, input),
|
||||
),
|
||||
);
|
||||
this.emit({
|
||||
type: "workspace.archive.undo.response",
|
||||
|
||||
+11
@@ -52,6 +52,7 @@ export interface CreateWorktreeWorkspaceInput {
|
||||
worktreeRoot: string;
|
||||
branch: string | null;
|
||||
baseBranch: string | null;
|
||||
worktreeManagerPluginId?: string | null;
|
||||
title: string | null;
|
||||
metadata?: Record<string, JsonValue>;
|
||||
expectsInitialAgent?: boolean;
|
||||
@@ -273,14 +274,23 @@ 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)),
|
||||
@@ -320,6 +330,7 @@ export function createWorkspaceProvisioningService(deps: {
|
||||
baseBranch: input.baseBranch,
|
||||
mainRepoRoot: repoRoot,
|
||||
}),
|
||||
worktreeManagerPluginId: input.worktreeManagerPluginId ?? null,
|
||||
title: input.title,
|
||||
metadata: input.metadata,
|
||||
createdAt: timestamp,
|
||||
|
||||
+126
-11
@@ -9,8 +9,11 @@ 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,
|
||||
@@ -64,10 +67,20 @@ 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,
|
||||
@@ -140,17 +153,32 @@ 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") {
|
||||
await recreateArchivedWorktree(resolved.workspace, resolved.sourceRepoRoot);
|
||||
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 deps.unarchiveWorkspace(resolved.workspace);
|
||||
return { workspaceId, action: resolved.kind };
|
||||
}
|
||||
|
||||
async function recreateArchivedWorktree(
|
||||
workspace: PersistedWorkspaceRecord,
|
||||
sourceRepoRoot: string,
|
||||
): Promise<void> {
|
||||
): Promise<{ worktreePath: string; pluginId: string | null }> {
|
||||
let source: WorktreeSource;
|
||||
const checkout = parseWorkspaceHead(workspace);
|
||||
if (checkout.kind === "branch") {
|
||||
@@ -194,18 +222,22 @@ 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 result = await createWorktree({
|
||||
cwd: sourceRepoRoot,
|
||||
worktreeSlug: basename(previousWorktreePath),
|
||||
const restored = await recreateWorktreeCheckout({
|
||||
workspace,
|
||||
sourceRepoRoot,
|
||||
source,
|
||||
|
||||
paseoHome: deps.paseoHome,
|
||||
worktreesRoot: deps.worktreesRoot,
|
||||
...(hasRecordedWorktreePath ? { worktreePath: previousWorktreePath } : {}),
|
||||
previousWorktreePath,
|
||||
hasRecordedWorktreePath,
|
||||
untrusted,
|
||||
});
|
||||
recreatedWorktreePath = result.worktreePath;
|
||||
recreatedWorktreePath = restored.worktreePath;
|
||||
restoredByPluginId = restored.pluginId;
|
||||
} catch (error) {
|
||||
throw toWorktreeRequestError(error);
|
||||
}
|
||||
@@ -236,15 +268,98 @@ 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 {
|
||||
|
||||
@@ -70,6 +70,12 @@ 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";
|
||||
@@ -618,9 +624,9 @@ export class VoiceAssistantWebSocketServer {
|
||||
private readonly voiceCallerContexts = new Map<string, VoiceCallerContext>();
|
||||
private readonly workspaceSetupObservation = new WorkspaceSetupObservation();
|
||||
private readonly workspaceSetupRuntime: WorkspaceSetupRuntime;
|
||||
// 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();
|
||||
// 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;
|
||||
private readonly providerSnapshotManager: ProviderSnapshotManager;
|
||||
private onLifecycleIntent!: ((intent: SessionLifecycleIntent) => void) | null;
|
||||
private onBranchChanged!:
|
||||
@@ -711,9 +717,11 @@ 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,4 +273,146 @@ 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,3 +1,6 @@
|
||||
import { resolve } from "node:path";
|
||||
|
||||
import { normalizePathForIdentity } from "../utils/path.js";
|
||||
import { type ArchiveResult, WorkspaceArchiveCanceledError } from "./workspace-archive-service.js";
|
||||
|
||||
export type WorkspaceArchiveOutcome =
|
||||
@@ -8,23 +11,42 @@ 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> };
|
||||
|
||||
/**
|
||||
* One lane per workspace for archive and its undo, shared by every session on the daemon.
|
||||
* Daemon-wide coordinator for workspace archive, undo, and restore operations.
|
||||
*
|
||||
* Per-workspace lanes:
|
||||
* - An archive while one 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.
|
||||
* - 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.
|
||||
*
|
||||
* Each call claims the lane synchronously, so whichever request arrives last decides the
|
||||
* workspace's final state no matter how the earlier work interleaves.
|
||||
* 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.
|
||||
*/
|
||||
export class WorkspaceArchiveOperations {
|
||||
private readonly lanes = new Map<string, LaneEntry>();
|
||||
private readonly checkoutGates = new Map<string, Promise<void>>();
|
||||
|
||||
archive(
|
||||
workspaceId: string,
|
||||
@@ -57,16 +79,92 @@ export class WorkspaceArchiveOperations {
|
||||
if (current?.kind === "undoing") {
|
||||
return current.done;
|
||||
}
|
||||
current?.controller.abort();
|
||||
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();
|
||||
const done = (async () => {
|
||||
const outcome =
|
||||
current?.kind === "archiving" ? await current.done.catch(() => undefined) : undefined;
|
||||
const outcome = pendingArchive ? await pendingArchive.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,3 +1290,59 @@ test("a canceled archive with no matching agents leaves earlier closed agents ar
|
||||
});
|
||||
expect(restored).toEqual([]);
|
||||
});
|
||||
|
||||
test.each(["outer", "inner"])(
|
||||
"archive keeps nested workspace when %s is managed",
|
||||
async (managed) => {
|
||||
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,
|
||||
worktreeManagerPluginId: managed === "outer" ? "manager" : null,
|
||||
isPaseoOwnedWorktree: true,
|
||||
mainRepoRoot: repoDir,
|
||||
},
|
||||
{
|
||||
workspaceId: "ws-topic",
|
||||
cwd: innerPath,
|
||||
kind: "worktree",
|
||||
worktreeRoot: innerPath,
|
||||
worktreeManagerPluginId: managed === "inner" ? "manager" : null,
|
||||
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,19 +19,26 @@ import type {
|
||||
WorkspaceArchiveContext,
|
||||
WorkspaceRegistry,
|
||||
} from "./workspace-registry.js";
|
||||
import { createRealpathAwarePathMatcher } from "../utils/path.js";
|
||||
import { createRealpathAwarePathMatcher, isRealpathInsideRoot } 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">;
|
||||
@@ -53,6 +60,7 @@ 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;
|
||||
}
|
||||
|
||||
@@ -119,6 +127,8 @@ interface BackingDirectory {
|
||||
registryProven: boolean;
|
||||
mainRepoRoot: string | null;
|
||||
paseoWorktreesRoot: string | null;
|
||||
worktreeManagerPluginId: string | null;
|
||||
untrusted: boolean;
|
||||
}
|
||||
|
||||
interface ArchiveTarget {
|
||||
@@ -142,6 +152,13 @@ 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.
|
||||
@@ -164,69 +181,98 @@ async function archiveByScopeWithPriority(
|
||||
};
|
||||
|
||||
checkpoint();
|
||||
const target = await resolveArchiveTarget(dependencies, request.scope);
|
||||
const targetWorkspaceIds = target.workspaceIds;
|
||||
const runArchive = async (): Promise<ArchiveResult> => {
|
||||
checkpoint();
|
||||
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) {
|
||||
await dependencies.emitWorkspaceUpdatesForWorkspaceIds(targetWorkspaceIds);
|
||||
dependencies.markWorkspaceArchiving(targetWorkspaceIds, new Date().toISOString());
|
||||
}
|
||||
checkpoint();
|
||||
|
||||
const { archivedAgents, archivedWorkspaceIds } = await archiveTargetRecords(
|
||||
dependencies,
|
||||
targetWorkspaceIds,
|
||||
{ requestId: request.requestId, checkpoint, archivedAt },
|
||||
);
|
||||
checkpoint();
|
||||
let removedDirectory = false;
|
||||
let directoryLeftBehind: ArchiveResult["directoryLeftBehind"];
|
||||
|
||||
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",
|
||||
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,
|
||||
);
|
||||
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);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
if (target.backing !== null) {
|
||||
const removal = await maybeRemoveDirectory(
|
||||
dependencies,
|
||||
{ requestId: request.requestId, checkpoint },
|
||||
target,
|
||||
archivedWorkspaceIds,
|
||||
);
|
||||
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);
|
||||
}
|
||||
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;
|
||||
}
|
||||
return resolveWorkspaceBackingPath(record, dependencies);
|
||||
}
|
||||
return (await resolveBackingDirectory(scope.targetPath, dependencies)).path;
|
||||
}
|
||||
|
||||
async function resolveArchiveTarget(
|
||||
@@ -313,6 +359,8 @@ 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),
|
||||
@@ -321,6 +369,8 @@ async function resolveWorkspaceBackingDirectory(
|
||||
registryProven: false,
|
||||
mainRepoRoot: workspace.mainRepoRoot ?? null,
|
||||
paseoWorktreesRoot: null,
|
||||
worktreeManagerPluginId,
|
||||
untrusted,
|
||||
};
|
||||
}
|
||||
if (workspace.isPaseoOwnedWorktree && workspace.worktreeRoot && workspace.mainRepoRoot) {
|
||||
@@ -331,6 +381,8 @@ async function resolveWorkspaceBackingDirectory(
|
||||
registryProven: true,
|
||||
mainRepoRoot: workspace.mainRepoRoot,
|
||||
paseoWorktreesRoot: null,
|
||||
worktreeManagerPluginId,
|
||||
untrusted,
|
||||
};
|
||||
}
|
||||
if (workspace.kind !== "worktree") {
|
||||
@@ -341,6 +393,8 @@ async function resolveWorkspaceBackingDirectory(
|
||||
registryProven: false,
|
||||
mainRepoRoot: workspace.mainRepoRoot ?? null,
|
||||
paseoWorktreesRoot: null,
|
||||
worktreeManagerPluginId,
|
||||
untrusted,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -350,7 +404,12 @@ async function resolveWorkspaceBackingDirectory(
|
||||
workspace.worktreeRoot ?? workspace.cwd,
|
||||
dependencies,
|
||||
);
|
||||
return { ...backing, mainRepoRoot: workspace.mainRepoRoot ?? backing.mainRepoRoot };
|
||||
return {
|
||||
...backing,
|
||||
mainRepoRoot: workspace.mainRepoRoot ?? backing.mainRepoRoot,
|
||||
worktreeManagerPluginId: worktreeManagerPluginId ?? backing.worktreeManagerPluginId,
|
||||
untrusted: untrusted || backing.untrusted,
|
||||
};
|
||||
}
|
||||
|
||||
async function resolveBackingDirectory(
|
||||
@@ -369,6 +428,8 @@ async function resolveBackingDirectory(
|
||||
registryProven: false,
|
||||
mainRepoRoot: ownership.repoRoot ?? null,
|
||||
paseoWorktreesRoot: ownership.worktreeRoot ?? null,
|
||||
worktreeManagerPluginId: null,
|
||||
untrusted: false,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -453,11 +514,16 @@ 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({
|
||||
@@ -481,7 +547,7 @@ async function maybeRemoveDirectory(
|
||||
if (
|
||||
!(await isDirectoryUnreferenced(
|
||||
remainingActive,
|
||||
backing.path,
|
||||
backing,
|
||||
new Set(archivedWorkspaceIds),
|
||||
dependencies,
|
||||
))
|
||||
@@ -501,6 +567,10 @@ 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 });
|
||||
@@ -618,21 +688,28 @@ export async function archiveWorkspaceContents(
|
||||
return archivedAgents;
|
||||
}
|
||||
|
||||
// True when, after archiving
|
||||
// the in-scope records, no active workspace still points at targetDir. Derived
|
||||
// from records each call — no stored counter.
|
||||
// Active workspaces on the same checkout keep it alive. A manager can place
|
||||
// a checkout anywhere, so also protect nested workspaces when either checkout
|
||||
// is manager-owned.
|
||||
async function isDirectoryUnreferenced(
|
||||
activeWorkspaces: ActiveWorkspaceRef[],
|
||||
targetDir: string,
|
||||
targetDirectory: BackingDirectory,
|
||||
archivedWorkspaceIds: ReadonlySet<string>,
|
||||
dependencies: Pick<ArchiveDependencies, "paseoHome" | "paseoWorktreesBaseRoot">,
|
||||
): Promise<boolean> {
|
||||
const target = resolve(targetDir);
|
||||
const target = targetDirectory.path;
|
||||
const matchesTarget = createRealpathAwarePathMatcher(target);
|
||||
for (const workspace of activeWorkspaces) {
|
||||
if (archivedWorkspaceIds.has(workspace.workspaceId)) continue;
|
||||
const backingDirectory = await resolveWorkspaceBackingDirectory(workspace, dependencies);
|
||||
if (matchesTarget(backingDirectory.path)) return false;
|
||||
if (
|
||||
(targetDirectory.worktreeManagerPluginId || backingDirectory.worktreeManagerPluginId) &&
|
||||
(isRealpathInsideRoot(target, backingDirectory.path) ||
|
||||
isRealpathInsideRoot(target, workspace.cwd))
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { createRealpathAwarePathMatcher } from "../utils/path.js";
|
||||
import type { WorkspaceRegistry } from "./workspace-registry.js";
|
||||
|
||||
export interface UntrustedWorkspaceSource {
|
||||
@@ -34,17 +35,44 @@ 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">,
|
||||
registry: Pick<WorkspaceRegistry, "update" | "listAll">,
|
||||
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: new Date().toISOString() };
|
||||
return { ...trusted, updatedAt: timestamp };
|
||||
});
|
||||
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,6 +88,7 @@ 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(),
|
||||
@@ -698,6 +699,7 @@ export function createPersistedWorkspaceRecord(input: {
|
||||
baseBranch?: string | null;
|
||||
isPaseoOwnedWorktree?: boolean;
|
||||
mainRepoRoot?: string | null;
|
||||
worktreeManagerPluginId?: string | null;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
archivedAt?: string | null;
|
||||
@@ -708,7 +710,7 @@ export function createPersistedWorkspaceRecord(input: {
|
||||
untrustedSource?: UntrustedWorkspaceSource;
|
||||
background?: boolean;
|
||||
}): PersistedWorkspaceRecord {
|
||||
const { background, ...rest } = input;
|
||||
const { background, worktreeManagerPluginId, ...rest } = input;
|
||||
return PersistedWorkspaceRecordSchema.parse({
|
||||
...rest,
|
||||
background: background ?? false,
|
||||
@@ -718,6 +720,7 @@ 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,9 +25,15 @@ import {
|
||||
readPaseoWorktreeMetadata,
|
||||
} from "../utils/worktree-metadata.js";
|
||||
import { validateBeforeRequest, validateBeforeResult } from "./plugins/lifecycle/index.js";
|
||||
import { UnknownBranchError } from "../utils/worktree.js";
|
||||
import {
|
||||
isPaseoOwnedWorktreeCwd,
|
||||
listGitWorktrees,
|
||||
listPaseoWorktrees,
|
||||
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 {
|
||||
@@ -1035,6 +1041,87 @@ 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);
|
||||
@@ -1467,6 +1554,454 @@ describe.skipIf(isPlatform("win32"))("worktree-core POSIX-only", () => {
|
||||
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);
|
||||
@@ -1648,9 +2183,26 @@ describe.skipIf(isPlatform("win32"))("worktree-core POSIX-only", () => {
|
||||
branchName: "follow-up",
|
||||
paseoHome,
|
||||
},
|
||||
createCoreDeps({ github }),
|
||||
{
|
||||
...createCoreDeps({ github }),
|
||||
worktreeManagers: {
|
||||
hasWorktreeManager: () => true,
|
||||
async createWorktree(request) {
|
||||
expect(request.untrusted).toBe(true);
|
||||
return null;
|
||||
},
|
||||
async removeWorktree() {
|
||||
return null;
|
||||
},
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
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,12 +1,19 @@
|
||||
import type { PluginWorktreeCreateRequest } from "@getpaseo/plugin/server";
|
||||
import type {
|
||||
PluginWorktreeCreateInput,
|
||||
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,
|
||||
@@ -16,11 +23,14 @@ 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;
|
||||
@@ -36,6 +46,10 @@ export interface CreateWorktreeCoreInput {
|
||||
|
||||
export interface CreateWorktreeCoreDeps {
|
||||
lifecycle?: Pick<PluginLifecycle, "before">;
|
||||
worktreeManagers?: Pick<
|
||||
PluginWorktreeManagerRuntime,
|
||||
"hasWorktreeManager" | "createWorktree" | "removeWorktree"
|
||||
>;
|
||||
github: ForgeService;
|
||||
workspaceGitService?: Pick<
|
||||
WorkspaceGitService,
|
||||
@@ -47,6 +61,7 @@ export interface CreateWorktreeCoreDeps {
|
||||
export interface CreateWorktreeCoreResult {
|
||||
worktree: CreatedWorktree;
|
||||
intent: WorktreeCreationIntent;
|
||||
untrustedSource?: UntrustedWorkspaceSource;
|
||||
repoRoot: string;
|
||||
created: boolean;
|
||||
}
|
||||
@@ -146,8 +161,28 @@ 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({
|
||||
@@ -155,15 +190,51 @@ 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">,
|
||||
@@ -174,6 +245,7 @@ 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 };
|
||||
|
||||
@@ -78,7 +78,7 @@ export function isPathInsideRoot(root: string, candidate: string): boolean {
|
||||
}
|
||||
|
||||
export function normalizePathForIdentity(value: string): string {
|
||||
const canonicalPath = resolveRealpathVariants(value)[0] ?? value;
|
||||
const canonicalPath = resolveNearestExistingAncestorRealpath(value);
|
||||
return normalizePathForComparison(canonicalPath, looksLikeDefiniteWindowsPath(canonicalPath));
|
||||
}
|
||||
|
||||
@@ -150,6 +150,26 @@ 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,6 +22,7 @@ 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({
|
||||
@@ -29,6 +30,7 @@ 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({
|
||||
@@ -227,6 +229,7 @@ export async function writePaseoWorktreeMetadata(
|
||||
baseRefName: string;
|
||||
baseRef?: string;
|
||||
changeRequestLookupTarget?: PaseoWorktreeChangeRequestHint;
|
||||
worktreeManagerPluginId?: string;
|
||||
},
|
||||
): Promise<void> {
|
||||
return mutateMetadata(worktreeRoot, async (root) => {
|
||||
@@ -244,6 +247,9 @@ export async function writePaseoWorktreeMetadata(
|
||||
...(options.changeRequestLookupTarget
|
||||
? { changeRequestLookupTarget: options.changeRequestLookupTarget }
|
||||
: {}),
|
||||
...(options.worktreeManagerPluginId
|
||||
? { worktreeManagerPluginId: options.worktreeManagerPluginId }
|
||||
: {}),
|
||||
};
|
||||
await writePaseoWorktreeMetadataFile(root, metadata);
|
||||
});
|
||||
|
||||
@@ -47,24 +47,24 @@ 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 } = options;
|
||||
const { candidate, repoPath, allowExistingPath = false } = options;
|
||||
if (!isAbsolute(candidate)) {
|
||||
throw new Error(
|
||||
`Worktree hook returned a relative path '${candidate}'; it must be an absolute path`,
|
||||
);
|
||||
throw new Error(`The returned path is relative: ${candidate}. Use an absolute path.`);
|
||||
}
|
||||
const normalized = await normalizeCandidatePath(candidate);
|
||||
const normalizedRepoPath = await normalizeAbsolute(repoPath);
|
||||
|
||||
if (normalized === parse(normalized).root) {
|
||||
throw new Error("Worktree hook returned the filesystem root, which is not allowed");
|
||||
throw new Error("The filesystem root cannot be a worktree destination");
|
||||
}
|
||||
if (normalized === (await normalizeAbsolute(homedir()))) {
|
||||
throw new Error("Worktree hook returned the user's home directory, which is not allowed");
|
||||
throw new Error("The user's home directory cannot be a worktree destination");
|
||||
}
|
||||
if (normalized === normalizedRepoPath) {
|
||||
throw new Error("Worktree hook returned the repository root itself, which is not allowed");
|
||||
throw new Error("The repository root cannot be a worktree destination");
|
||||
}
|
||||
if (
|
||||
[normalized, resolve(candidate)].some((path) =>
|
||||
@@ -73,15 +73,15 @@ export async function validateWorktreePath(options: {
|
||||
.some((part) => (process.platform === "win32" ? part.toLowerCase() : part) === ".git"),
|
||||
)
|
||||
) {
|
||||
throw new Error(`Worktree hook returned a path inside a .git directory: ${normalized}`);
|
||||
throw new Error(`The returned path is inside a .git directory: ${normalized}`);
|
||||
}
|
||||
const relativeToCandidate = getRelativePathInsideRoot(normalized, normalizedRepoPath);
|
||||
if (relativeToCandidate !== null && relativeToCandidate !== "") {
|
||||
throw new Error(`Worktree hook returned an ancestor of the repository: ${normalized}`);
|
||||
throw new Error(`The returned path is an ancestor of the repository: ${normalized}`);
|
||||
}
|
||||
if ((await pathExists(normalized)) || (await pathExists(candidate))) {
|
||||
if (!allowExistingPath && ((await pathExists(normalized)) || (await pathExists(candidate)))) {
|
||||
throw new Error(
|
||||
`Worktree hook returned a path that already exists: ${normalized}. Paseo creates the returned path.`,
|
||||
`The returned path already exists: ${normalized}. Paseo creates the returned path.`,
|
||||
);
|
||||
}
|
||||
return normalized;
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -109,6 +109,63 @@ test("switches language on the same page, keeping the query and then every link"
|
||||
await expect(page.locator("html")).toHaveAttribute("lang", "en");
|
||||
});
|
||||
|
||||
async function openHubDoc(page: Page, prefix: string, slug: string, heading: string) {
|
||||
await page.goto(`${prefix}/docs/hub/${slug}`);
|
||||
await expect(page.getByRole("heading", { name: heading, level: 1 })).toBeVisible();
|
||||
}
|
||||
|
||||
async function expectHubDocRedirect(
|
||||
page: Page,
|
||||
prefix: string,
|
||||
legacySlug: string,
|
||||
slug: string,
|
||||
heading: string,
|
||||
) {
|
||||
await page.goto(`${prefix}/docs/hub/${legacySlug}`);
|
||||
await expect(page).toHaveURL(`${prefix}/docs/hub/${slug}`);
|
||||
await expect(page.getByRole("heading", { name: heading, level: 1 })).toBeVisible();
|
||||
}
|
||||
|
||||
for (const { locale, prefix, linear, linearApp, webhooks, triggers, reference } of [
|
||||
{
|
||||
locale: "English",
|
||||
prefix: "",
|
||||
linear: "Linear triggers",
|
||||
linearApp: "Linear for Hub",
|
||||
webhooks: "Inbound webhooks",
|
||||
triggers: "Triggers",
|
||||
reference: "Trigger YAML reference",
|
||||
},
|
||||
{
|
||||
locale: "Simplified Chinese",
|
||||
prefix: "/zh-CN",
|
||||
linear: "Linear 触发器",
|
||||
linearApp: "为 Hub 配置 Linear",
|
||||
webhooks: "入站 webhook",
|
||||
triggers: "触发器",
|
||||
reference: "触发器 YAML 参考",
|
||||
},
|
||||
]) {
|
||||
test(`opens ${locale} Hub guides and redirects legacy bookmarks`, async ({ page }) => {
|
||||
await test.step("opens direct links to the new guides", async () => {
|
||||
await openHubDoc(page, prefix, "triggers/linear", linear);
|
||||
await openHubDoc(page, prefix, "self-hosting/linear-app", linearApp);
|
||||
await openHubDoc(page, prefix, "triggers/webhooks", webhooks);
|
||||
});
|
||||
|
||||
await test.step("redirects legacy guides within the same language", async () => {
|
||||
await expectHubDocRedirect(page, prefix, "workflows", "triggers", triggers);
|
||||
await expectHubDocRedirect(
|
||||
page,
|
||||
prefix,
|
||||
"configuration/hub-yml",
|
||||
"configuration/reference",
|
||||
reference,
|
||||
);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
test("shows the language as an abbreviation and lists every language by name", async ({ page }) => {
|
||||
await page.goto("/docs/cli#running-agents");
|
||||
const button = languageButton(page);
|
||||
|
||||
@@ -166,6 +166,14 @@ export function getLegacyDocsRedirect(pathname: string): string | undefined {
|
||||
const provider = /^\/docs\/(claude-code|codex|muse-code)(\.md)?\/?$/.exec(pathname);
|
||||
if (provider) return `/docs/supported-providers/${provider[1]}${provider[2] ?? ""}`;
|
||||
|
||||
// Legacy Hub stepped-workflow docs moved to self-contained trigger docs and YAML reference.
|
||||
const hubLegacy = /^\/docs\/hub\/(workflows|configuration\/hub-yml)(\.md)?\/?$/.exec(pathname);
|
||||
if (hubLegacy) {
|
||||
const target =
|
||||
hubLegacy[1] === "workflows" ? "/docs/hub/triggers" : "/docs/hub/configuration/reference";
|
||||
return `${target}${hubLegacy[2] ?? ""}`;
|
||||
}
|
||||
|
||||
const match =
|
||||
/^\/docs\/plugins\/v0\.[78](?:(\.md)|\/(index|reference|providers|migration)(\.md)?)?\/?$/.exec(
|
||||
pathname,
|
||||
|
||||
@@ -2,12 +2,13 @@ import { readFile, readdir } from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
import YAML from "yaml";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { getDoc, getDocs, getLegacyDocsRedirect, parseHeadings } from "./docs";
|
||||
|
||||
const repositoryRoot = path.resolve(import.meta.dirname, "../../..");
|
||||
const hubDocs = path.join(repositoryRoot, "public-docs", "hub");
|
||||
|
||||
describe("Hub public documentation examples", () => {
|
||||
it("parses every Hub YAML example and keeps resource maps canonical", async () => {
|
||||
it("parses every Hub YAML example and keeps trigger documents canonical", async () => {
|
||||
const files = [
|
||||
...(await markdownFiles(hubDocs)),
|
||||
path.join(repositoryRoot, "public-docs", "cli.md"),
|
||||
@@ -24,6 +25,9 @@ describe("Hub public documentation examples", () => {
|
||||
expect(parsed, `${label} must not teach monolithic triggers`).not.toHaveProperty(
|
||||
"triggers",
|
||||
);
|
||||
expect(parsed, `${label} must not teach legacy stepped workflows`).not.toHaveProperty(
|
||||
"steps",
|
||||
);
|
||||
if (Object.hasOwn(parsed, "environments")) {
|
||||
expect(isRecord(parsed["environments"]), `${label} environments`).toBe(true);
|
||||
}
|
||||
@@ -35,18 +39,75 @@ describe("Hub public documentation examples", () => {
|
||||
expect(exampleCount).toBeGreaterThan(20);
|
||||
});
|
||||
|
||||
it("does not teach removed Hub authoring paths or composition fields", async () => {
|
||||
it("does not teach removed Hub authoring paths or legacy stepped workflows", async () => {
|
||||
const markdown = (
|
||||
await Promise.all((await markdownFiles(hubDocs)).map((file) => readFile(file, "utf8")))
|
||||
).join("\n");
|
||||
|
||||
expect(markdown).not.toContain(".paseo/partials/");
|
||||
expect(markdown).not.toContain(".paseo/workflows/");
|
||||
expect(markdown).not.toContain(".paseo/hub.yml");
|
||||
expect(markdown).not.toMatch(/^triggers:/mu);
|
||||
expect(markdown).not.toMatch(/^steps:/mu);
|
||||
expect(markdown).not.toMatch(/^\s+allow_outputs:/mu);
|
||||
expect(markdown).not.toMatch(/^\s+uses:/mu);
|
||||
expect(markdown).not.toContain("paseo hub deploy [file]");
|
||||
});
|
||||
|
||||
it.each(["en", "zh-CN"] as const)(
|
||||
"resolves every internal /docs/hub link and heading anchor in %s",
|
||||
(locale) => {
|
||||
const docs = getDocs(locale);
|
||||
const headingsByHref = new Map(docs.map((doc) => [doc.href, headingIds(doc.content)]));
|
||||
const hubPages = docs.filter(
|
||||
(doc) => doc.href === "/docs/hub" || doc.href.startsWith("/docs/hub/"),
|
||||
);
|
||||
expect(hubPages.length).toBeGreaterThanOrEqual(25);
|
||||
|
||||
const broken: string[] = [];
|
||||
for (const doc of hubPages) {
|
||||
for (const match of doc.content.matchAll(/\]\((\/docs\/hub[^)\s]*)\)/gu)) {
|
||||
const target = match[1] ?? "";
|
||||
const [rawPath, hash] = target.split("#");
|
||||
const cleanPath = (rawPath ?? "").replace(/\/$/u, "");
|
||||
const headings = headingsByHref.get(cleanPath);
|
||||
if (!headings) {
|
||||
broken.push(`${doc.sourcePath} -> missing page ${target}`);
|
||||
} else if (hash && !headings.has(hash)) {
|
||||
broken.push(`${doc.sourcePath} -> missing anchor ${target}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
expect(broken).toEqual([]);
|
||||
},
|
||||
);
|
||||
|
||||
it("redirects removed legacy Hub workflow and hub-yml paths to current pages", () => {
|
||||
const redirects = [
|
||||
["/docs/hub/workflows", "/docs/hub/triggers"],
|
||||
["/docs/hub/configuration/hub-yml", "/docs/hub/configuration/reference"],
|
||||
] as const;
|
||||
|
||||
for (const [legacyPath, targetPath] of redirects) {
|
||||
expect(getDoc(targetPath.slice("/docs/".length), "en")).toBeDefined();
|
||||
expect(getDoc(targetPath.slice("/docs/".length), "zh-CN")).toBeDefined();
|
||||
for (const extension of ["", ".md"]) {
|
||||
expect(getLegacyDocsRedirect(`${legacyPath}${extension}`)).toBe(
|
||||
`${targetPath}${extension}`,
|
||||
);
|
||||
expect(getLegacyDocsRedirect(`${legacyPath}${extension}/`)).toBe(
|
||||
`${targetPath}${extension}`,
|
||||
);
|
||||
expect(getLegacyDocsRedirect(`${targetPath}${extension}`)).toBeUndefined();
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
function headingIds(content: string): Set<string> {
|
||||
return new Set(parseHeadings(content).map((heading) => heading.id));
|
||||
}
|
||||
|
||||
function yamlFences(markdown: string): readonly string[] {
|
||||
return [...markdown.matchAll(/```yaml\s*\n([\s\S]*?)```/gu)].map((match) => match[1] ?? "");
|
||||
}
|
||||
|
||||
@@ -50,7 +50,7 @@ Distribution: native apps for Mac, Windows, Linux, iOS, and Android; web app; Ho
|
||||
path: "/hub",
|
||||
title: "Paseo Hub",
|
||||
description:
|
||||
"Connect daemons and run GitHub, Slack, Discord, and Linear workflows through the hosted service or your own deployment.",
|
||||
"Connect daemons and automate agents from GitHub, Linear, Slack, Discord, schedules, and webhooks through the hosted service or your own deployment.",
|
||||
},
|
||||
{
|
||||
path: "/blog",
|
||||
@@ -104,7 +104,7 @@ Paseo 支持 Claude Code、Codex、GitHub Copilot、OpenCode、Pi、Antigravity
|
||||
path: "/hub",
|
||||
title: "Paseo Hub",
|
||||
description:
|
||||
"连接 daemon,通过托管服务或你自己的部署运行 GitHub、Slack、Discord 和 Linear 工作流。",
|
||||
"连接 daemon,通过托管服务或你自己的部署,使用 GitHub、Linear、Slack、Discord、定时任务和 webhook 自动化运行 Agent。",
|
||||
},
|
||||
{ path: "/blog", title: "博客", description: "Paseo 团队的动态和技术文章。" },
|
||||
{ path: "/privacy", title: "隐私", description: "隐私政策。" },
|
||||
|
||||
@@ -28,17 +28,28 @@ index 73466dd..8440ac9 100644
|
||||
|
||||
auto textSize = textLayoutManager_
|
||||
diff --git a/node_modules/@mattermost/react-native-paste-input/android/src/main/java/com/mattermost/pasteinputtext/PasteInputEditText.kt b/node_modules/@mattermost/react-native-paste-input/android/src/main/java/com/mattermost/pasteinputtext/PasteInputEditText.kt
|
||||
index 9e429b8..1d10014 100644
|
||||
index 1794b53..eca5e57 100644
|
||||
--- a/node_modules/@mattermost/react-native-paste-input/android/src/main/java/com/mattermost/pasteinputtext/PasteInputEditText.kt
|
||||
+++ b/node_modules/@mattermost/react-native-paste-input/android/src/main/java/com/mattermost/pasteinputtext/PasteInputEditText.kt
|
||||
@@ -36,2 +36,2 @@ class PasteInputEditText(context: ThemedReactContext) : ReactEditText(context) {
|
||||
@@ -33,8 +33,8 @@ class PasteInputEditText(context: ThemedReactContext) : ReactEditText(context) {
|
||||
return mOnPasteListener
|
||||
}
|
||||
|
||||
- override fun onCreateInputConnection(outAttrs: EditorInfo): InputConnection {
|
||||
- val ic = super.onCreateInputConnection(outAttrs)
|
||||
+ override fun onCreateInputConnection(outAttrs: EditorInfo): InputConnection? {
|
||||
+ val ic = super.onCreateInputConnection(outAttrs) ?: return null
|
||||
@@ -58 +58 @@ class PasteInputEditText(context: ThemedReactContext) : ReactEditText(context) {
|
||||
|
||||
EditorInfoCompat.setContentMimeTypes(outAttrs, arrayOf("*/*"))
|
||||
|
||||
@@ -55,6 +55,6 @@ class PasteInputEditText(context: ThemedReactContext) : ReactEditText(context) {
|
||||
true
|
||||
}
|
||||
|
||||
- return InputConnectionCompat.createWrapper(ic!!, outAttrs, callback)
|
||||
+ return InputConnectionCompat.createWrapper(ic, outAttrs, callback)
|
||||
}
|
||||
}
|
||||
diff --git a/node_modules/@mattermost/react-native-paste-input/lib/commonjs/PasteInput.js b/node_modules/@mattermost/react-native-paste-input/lib/commonjs/PasteInput.js
|
||||
index 51b9dfa..501badf 100644
|
||||
--- a/node_modules/@mattermost/react-native-paste-input/lib/commonjs/PasteInput.js
|
||||
@@ -108,10 +119,18 @@ index 51b9dfa..501badf 100644
|
||||
// For Android, PasteTextInput already handles everything internally
|
||||
// Just need to adapt the onPaste callback format
|
||||
diff --git a/node_modules/@mattermost/react-native-paste-input/lib/commonjs/PasteTextInput.js b/node_modules/@mattermost/react-native-paste-input/lib/commonjs/PasteTextInput.js
|
||||
index 5119e65..287216a 100644
|
||||
index 5119e65..77c3aea 100644
|
||||
--- a/node_modules/@mattermost/react-native-paste-input/lib/commonjs/PasteTextInput.js
|
||||
+++ b/node_modules/@mattermost/react-native-paste-input/lib/commonjs/PasteTextInput.js
|
||||
@@ -52,6 +52,7 @@ function InternalTextInput(props) {
|
||||
@@ -16,7 +16,6 @@ var _nullthrows = _interopRequireDefault(require("nullthrows"));
|
||||
var _jsxRuntime = require("react/jsx-runtime");
|
||||
function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
|
||||
function _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function (e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, default: e }; if (null === e || "object" != typeof e && "function" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (const t in e) "default" !== t && {}.hasOwnProperty.call(e, t) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, t)) && (i.get || i.set) ? o(f, t, i) : f[t] = e[t]); return f; })(e, t); }
|
||||
-const emptyFunctionThatReturnsTrue = () => true;
|
||||
function useMergeRefs(...refs) {
|
||||
return React.useCallback(current => {
|
||||
for (const ref of refs) {
|
||||
@@ -52,6 +51,7 @@ function InternalTextInput(props) {
|
||||
end: propsSelection.end ?? propsSelection.start
|
||||
}, [propsSelection]);
|
||||
const [mostRecentEventCount, setMostRecentEventCount] = React.useState(0);
|
||||
@@ -119,7 +138,7 @@ index 5119e65..287216a 100644
|
||||
const [lastNativeText, setLastNativeText] = React.useState(props.value);
|
||||
const [lastNativeSelectionState, setLastNativeSelection] = React.useState({
|
||||
selection: {
|
||||
@@ -103,7 +104,12 @@ function InternalTextInput(props) {
|
||||
@@ -103,7 +103,12 @@ function InternalTextInput(props) {
|
||||
Object.assign(instance, {
|
||||
clear() {
|
||||
if (inputRef.current != null) {
|
||||
@@ -133,7 +152,7 @@ index 5119e65..287216a 100644
|
||||
}
|
||||
},
|
||||
isFocused() {
|
||||
@@ -114,12 +120,12 @@ function InternalTextInput(props) {
|
||||
@@ -114,12 +119,12 @@ function InternalTextInput(props) {
|
||||
},
|
||||
setSelection(start, end) {
|
||||
if (inputRef.current != null) {
|
||||
@@ -148,7 +167,7 @@ index 5119e65..287216a 100644
|
||||
const ref = useMergeRefs(setLocalRef, props.forwardedRef);
|
||||
const _onChange = event => {
|
||||
const currentText = event.nativeEvent.text;
|
||||
@@ -128,6 +134,7 @@ function InternalTextInput(props) {
|
||||
@@ -128,6 +133,7 @@ function InternalTextInput(props) {
|
||||
if (inputRef.current == null) {
|
||||
return;
|
||||
}
|
||||
@@ -156,6 +175,14 @@ index 5119e65..287216a 100644
|
||||
setLastNativeText(currentText);
|
||||
setMostRecentEventCount(event.nativeEvent.eventCount);
|
||||
};
|
||||
@@ -294,7 +300,6 @@ function InternalTextInput(props) {
|
||||
onPaste: _onPaste,
|
||||
onScroll: _onScroll,
|
||||
onSelectionChange: _onSelectionChange,
|
||||
- onSelectionChangeShouldSetResponder: emptyFunctionThatReturnsTrue,
|
||||
placeholder: placeholder,
|
||||
style: _style,
|
||||
text: text,
|
||||
diff --git a/node_modules/@mattermost/react-native-paste-input/lib/module/PasteInput.js b/node_modules/@mattermost/react-native-paste-input/lib/module/PasteInput.js
|
||||
index 75fe015..1d3cd64 100644
|
||||
--- a/node_modules/@mattermost/react-native-paste-input/lib/module/PasteInput.js
|
||||
@@ -225,10 +252,18 @@ index 75fe015..1d3cd64 100644
|
||||
// For Android, PasteTextInput already handles everything internally
|
||||
// Just need to adapt the onPaste callback format
|
||||
diff --git a/node_modules/@mattermost/react-native-paste-input/lib/module/PasteTextInput.js b/node_modules/@mattermost/react-native-paste-input/lib/module/PasteTextInput.js
|
||||
index 39bd607..f2b1d2f 100644
|
||||
index 39bd607..832dcc2 100644
|
||||
--- a/node_modules/@mattermost/react-native-paste-input/lib/module/PasteTextInput.js
|
||||
+++ b/node_modules/@mattermost/react-native-paste-input/lib/module/PasteTextInput.js
|
||||
@@ -46,6 +46,7 @@ function InternalTextInput(props) {
|
||||
@@ -10,7 +10,6 @@ import usePressability from 'react-native/Libraries/Pressability/usePressability
|
||||
import flattenStyle from 'react-native/Libraries/StyleSheet/flattenStyle';
|
||||
import nullthrows from 'nullthrows';
|
||||
import { jsx as _jsx } from "react/jsx-runtime";
|
||||
-const emptyFunctionThatReturnsTrue = () => true;
|
||||
function useMergeRefs(...refs) {
|
||||
return React.useCallback(current => {
|
||||
for (const ref of refs) {
|
||||
@@ -46,6 +45,7 @@ function InternalTextInput(props) {
|
||||
end: propsSelection.end ?? propsSelection.start
|
||||
}, [propsSelection]);
|
||||
const [mostRecentEventCount, setMostRecentEventCount] = React.useState(0);
|
||||
@@ -236,7 +271,7 @@ index 39bd607..f2b1d2f 100644
|
||||
const [lastNativeText, setLastNativeText] = React.useState(props.value);
|
||||
const [lastNativeSelectionState, setLastNativeSelection] = React.useState({
|
||||
selection: {
|
||||
@@ -97,7 +98,12 @@ function InternalTextInput(props) {
|
||||
@@ -97,7 +97,12 @@ function InternalTextInput(props) {
|
||||
Object.assign(instance, {
|
||||
clear() {
|
||||
if (inputRef.current != null) {
|
||||
@@ -250,7 +285,7 @@ index 39bd607..f2b1d2f 100644
|
||||
}
|
||||
},
|
||||
isFocused() {
|
||||
@@ -108,12 +114,12 @@ function InternalTextInput(props) {
|
||||
@@ -108,12 +113,12 @@ function InternalTextInput(props) {
|
||||
},
|
||||
setSelection(start, end) {
|
||||
if (inputRef.current != null) {
|
||||
@@ -265,7 +300,7 @@ index 39bd607..f2b1d2f 100644
|
||||
const ref = useMergeRefs(setLocalRef, props.forwardedRef);
|
||||
const _onChange = event => {
|
||||
const currentText = event.nativeEvent.text;
|
||||
@@ -122,6 +128,7 @@ function InternalTextInput(props) {
|
||||
@@ -122,6 +127,7 @@ function InternalTextInput(props) {
|
||||
if (inputRef.current == null) {
|
||||
return;
|
||||
}
|
||||
@@ -273,6 +308,14 @@ index 39bd607..f2b1d2f 100644
|
||||
setLastNativeText(currentText);
|
||||
setMostRecentEventCount(event.nativeEvent.eventCount);
|
||||
};
|
||||
@@ -288,7 +294,6 @@ function InternalTextInput(props) {
|
||||
onPaste: _onPaste,
|
||||
onScroll: _onScroll,
|
||||
onSelectionChange: _onSelectionChange,
|
||||
- onSelectionChangeShouldSetResponder: emptyFunctionThatReturnsTrue,
|
||||
placeholder: placeholder,
|
||||
style: _style,
|
||||
text: text,
|
||||
diff --git a/node_modules/@mattermost/react-native-paste-input/src/PasteInput.tsx b/node_modules/@mattermost/react-native-paste-input/src/PasteInput.tsx
|
||||
index 12befab..0d23ca5 100644
|
||||
--- a/node_modules/@mattermost/react-native-paste-input/src/PasteInput.tsx
|
||||
@@ -342,10 +385,19 @@ index 12befab..0d23ca5 100644
|
||||
// For Android, PasteTextInput already handles everything internally
|
||||
// Just need to adapt the onPaste callback format
|
||||
diff --git a/node_modules/@mattermost/react-native-paste-input/src/PasteTextInput.tsx b/node_modules/@mattermost/react-native-paste-input/src/PasteTextInput.tsx
|
||||
index dcc4a2b..1156458 100644
|
||||
index dcc4a2b..7d10e11 100644
|
||||
--- a/node_modules/@mattermost/react-native-paste-input/src/PasteTextInput.tsx
|
||||
+++ b/node_modules/@mattermost/react-native-paste-input/src/PasteTextInput.tsx
|
||||
@@ -84,6 +84,7 @@ function InternalTextInput(props: PasteInputProps): React.ReactNode {
|
||||
@@ -27,8 +27,6 @@ import usePressability from 'react-native/Libraries/Pressability/usePressability
|
||||
import flattenStyle from 'react-native/Libraries/StyleSheet/flattenStyle';
|
||||
import nullthrows from 'nullthrows';
|
||||
|
||||
-const emptyFunctionThatReturnsTrue = () => true;
|
||||
-
|
||||
function useMergeRefs<Instance>(
|
||||
...refs: ReadonlyArray<React.ForwardedRef<Instance> | null | undefined>
|
||||
): (arg0: Instance | null) => void {
|
||||
@@ -84,6 +82,7 @@ function InternalTextInput(props: PasteInputProps): React.ReactNode {
|
||||
|
||||
const [mostRecentEventCount, setMostRecentEventCount] =
|
||||
React.useState<number>(0);
|
||||
@@ -353,7 +405,7 @@ index dcc4a2b..1156458 100644
|
||||
const [lastNativeText, setLastNativeText] = React.useState<
|
||||
string | undefined
|
||||
>(props.value);
|
||||
@@ -181,13 +182,24 @@ function InternalTextInput(props: PasteInputProps): React.ReactNode {
|
||||
@@ -181,13 +180,24 @@ function InternalTextInput(props: PasteInputProps): React.ReactNode {
|
||||
if (inputRef.current != null) {
|
||||
Commands.setTextAndSelection(
|
||||
inputRef.current,
|
||||
@@ -379,7 +431,7 @@ index dcc4a2b..1156458 100644
|
||||
isFocused(): boolean {
|
||||
return (
|
||||
TextInputState.currentlyFocusedInput() ===
|
||||
@@ -203,7 +215,7 @@ function InternalTextInput(props: PasteInputProps): React.ReactNode {
|
||||
@@ -203,7 +213,7 @@ function InternalTextInput(props: PasteInputProps): React.ReactNode {
|
||||
if (inputRef.current != null) {
|
||||
Commands.setTextAndSelection(
|
||||
inputRef.current,
|
||||
@@ -388,7 +440,7 @@ index dcc4a2b..1156458 100644
|
||||
null,
|
||||
start,
|
||||
end
|
||||
@@ -213,7 +225,7 @@ function InternalTextInput(props: PasteInputProps): React.ReactNode {
|
||||
@@ -213,7 +223,7 @@ function InternalTextInput(props: PasteInputProps): React.ReactNode {
|
||||
});
|
||||
}
|
||||
},
|
||||
@@ -397,7 +449,7 @@ index dcc4a2b..1156458 100644
|
||||
);
|
||||
|
||||
const ref = useMergeRefs<PasteTextInputInstance>(
|
||||
@@ -232,6 +244,7 @@ function InternalTextInput(props: PasteInputProps): React.ReactNode {
|
||||
@@ -232,6 +242,7 @@ function InternalTextInput(props: PasteInputProps): React.ReactNode {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -405,3 +457,11 @@ index dcc4a2b..1156458 100644
|
||||
setLastNativeText(currentText);
|
||||
setMostRecentEventCount(event.nativeEvent.eventCount);
|
||||
};
|
||||
@@ -445,7 +456,6 @@ function InternalTextInput(props: PasteInputProps): React.ReactNode {
|
||||
onPaste={_onPaste}
|
||||
onScroll={_onScroll}
|
||||
onSelectionChange={_onSelectionChange}
|
||||
- onSelectionChangeShouldSetResponder={emptyFunctionThatReturnsTrue}
|
||||
placeholder={placeholder}
|
||||
style={_style}
|
||||
text={text}
|
||||
|
||||
@@ -0,0 +1,223 @@
|
||||
diff --git a/node_modules/react-native/Libraries/Renderer/implementations/ReactFabric-dev.js b/node_modules/react-native/Libraries/Renderer/implementations/ReactFabric-dev.js
|
||||
index daab0e3..d3a629c 100644
|
||||
--- a/node_modules/react-native/Libraries/Renderer/implementations/ReactFabric-dev.js
|
||||
+++ b/node_modules/react-native/Libraries/Renderer/implementations/ReactFabric-dev.js
|
||||
@@ -16214,12 +16214,21 @@ __DEV__ &&
|
||||
else if (
|
||||
"topTouchEnd" === topLevelType ||
|
||||
"topTouchCancel" === topLevelType
|
||||
- )
|
||||
- if (
|
||||
- (nativeEvent.changedTouches.forEach(recordTouchEnd),
|
||||
- (touchHistory.numberActiveTouches = nativeEvent.touches.length),
|
||||
- 1 === touchHistory.numberActiveTouches)
|
||||
- ) {
|
||||
+ ) {
|
||||
+ nativeEvent.changedTouches.forEach(recordTouchEnd);
|
||||
+ touchHistory.numberActiveTouches = nativeEvent.touches.length;
|
||||
+ if (0 === touchHistory.numberActiveTouches) {
|
||||
+ for (
|
||||
+ topLevelType = 0;
|
||||
+ topLevelType < touchBank.length;
|
||||
+ topLevelType++
|
||||
+ )
|
||||
+ if (
|
||||
+ ((nativeEvent = touchBank[topLevelType]),
|
||||
+ null != nativeEvent && nativeEvent.touchActive)
|
||||
+ )
|
||||
+ nativeEvent.touchActive = !1;
|
||||
+ } else if (1 === touchHistory.numberActiveTouches) {
|
||||
for (
|
||||
topLevelType = 0;
|
||||
topLevelType < touchBank.length;
|
||||
@@ -16236,6 +16245,7 @@ __DEV__ &&
|
||||
(null != topLevelType && topLevelType.touchActive) ||
|
||||
console.error("Cannot find single active touch.");
|
||||
}
|
||||
+ }
|
||||
},
|
||||
touchHistory: touchHistory
|
||||
},
|
||||
@@ -16314,12 +16324,18 @@ __DEV__ &&
|
||||
nativeEvent,
|
||||
nativeEventTarget
|
||||
) {
|
||||
- if (isStartish(topLevelType)) trackedTouchCount += 1;
|
||||
+ if (isStartish(topLevelType))
|
||||
+ trackedTouchCount =
|
||||
+ nativeEvent && Array.isArray(nativeEvent.touches)
|
||||
+ ? nativeEvent.touches.length
|
||||
+ : trackedTouchCount + 1;
|
||||
else if (
|
||||
"topTouchEnd" === topLevelType ||
|
||||
"topTouchCancel" === topLevelType
|
||||
)
|
||||
- if (0 <= trackedTouchCount) --trackedTouchCount;
|
||||
+ if (nativeEvent && Array.isArray(nativeEvent.touches))
|
||||
+ trackedTouchCount = nativeEvent.touches.length;
|
||||
+ else if (0 <= trackedTouchCount) --trackedTouchCount;
|
||||
else
|
||||
return (
|
||||
console.warn(
|
||||
diff --git a/node_modules/react-native/Libraries/Renderer/implementations/ReactFabric-prod.js b/node_modules/react-native/Libraries/Renderer/implementations/ReactFabric-prod.js
|
||||
index 2625bf6..3d85e32 100644
|
||||
--- a/node_modules/react-native/Libraries/Renderer/implementations/ReactFabric-prod.js
|
||||
+++ b/node_modules/react-native/Libraries/Renderer/implementations/ReactFabric-prod.js
|
||||
@@ -546,12 +546,21 @@ var instrumentationCallback,
|
||||
else if (
|
||||
"topTouchEnd" === topLevelType ||
|
||||
"topTouchCancel" === topLevelType
|
||||
- )
|
||||
- if (
|
||||
- (nativeEvent.changedTouches.forEach(recordTouchEnd),
|
||||
- (touchHistory.numberActiveTouches = nativeEvent.touches.length),
|
||||
- 1 === touchHistory.numberActiveTouches)
|
||||
- )
|
||||
+ ) {
|
||||
+ nativeEvent.changedTouches.forEach(recordTouchEnd);
|
||||
+ touchHistory.numberActiveTouches = nativeEvent.touches.length;
|
||||
+ if (0 === touchHistory.numberActiveTouches) {
|
||||
+ for (
|
||||
+ topLevelType = 0;
|
||||
+ topLevelType < touchBank.length;
|
||||
+ topLevelType++
|
||||
+ )
|
||||
+ if (
|
||||
+ ((nativeEvent = touchBank[topLevelType]),
|
||||
+ null != nativeEvent && nativeEvent.touchActive)
|
||||
+ )
|
||||
+ nativeEvent.touchActive = !1;
|
||||
+ } else if (1 === touchHistory.numberActiveTouches)
|
||||
for (
|
||||
topLevelType = 0;
|
||||
topLevelType < touchBank.length;
|
||||
@@ -564,6 +573,7 @@ var instrumentationCallback,
|
||||
touchHistory.indexOfSingleActiveTouch = topLevelType;
|
||||
break;
|
||||
}
|
||||
+ }
|
||||
},
|
||||
touchHistory: touchHistory
|
||||
};
|
||||
@@ -745,12 +755,18 @@ var ResponderEventPlugin = {
|
||||
nativeEvent,
|
||||
nativeEventTarget
|
||||
) {
|
||||
- if (isStartish(topLevelType)) trackedTouchCount += 1;
|
||||
+ if (isStartish(topLevelType))
|
||||
+ trackedTouchCount =
|
||||
+ nativeEvent && Array.isArray(nativeEvent.touches)
|
||||
+ ? nativeEvent.touches.length
|
||||
+ : trackedTouchCount + 1;
|
||||
else if (
|
||||
"topTouchEnd" === topLevelType ||
|
||||
"topTouchCancel" === topLevelType
|
||||
)
|
||||
- if (0 <= trackedTouchCount) --trackedTouchCount;
|
||||
+ if (nativeEvent && Array.isArray(nativeEvent.touches))
|
||||
+ trackedTouchCount = nativeEvent.touches.length;
|
||||
+ else if (0 <= trackedTouchCount) --trackedTouchCount;
|
||||
else return null;
|
||||
ResponderTouchHistoryStore.recordTouchTrack(topLevelType, nativeEvent);
|
||||
if (
|
||||
diff --git a/node_modules/react-native/Libraries/Renderer/implementations/ReactFabric-profiling.js b/node_modules/react-native/Libraries/Renderer/implementations/ReactFabric-profiling.js
|
||||
index 544c754..4d5ec08 100644
|
||||
--- a/node_modules/react-native/Libraries/Renderer/implementations/ReactFabric-profiling.js
|
||||
+++ b/node_modules/react-native/Libraries/Renderer/implementations/ReactFabric-profiling.js
|
||||
@@ -611,12 +611,21 @@ var instrumentationCallback,
|
||||
else if (
|
||||
"topTouchEnd" === topLevelType ||
|
||||
"topTouchCancel" === topLevelType
|
||||
- )
|
||||
- if (
|
||||
- (nativeEvent.changedTouches.forEach(recordTouchEnd),
|
||||
- (touchHistory.numberActiveTouches = nativeEvent.touches.length),
|
||||
- 1 === touchHistory.numberActiveTouches)
|
||||
- )
|
||||
+ ) {
|
||||
+ nativeEvent.changedTouches.forEach(recordTouchEnd);
|
||||
+ touchHistory.numberActiveTouches = nativeEvent.touches.length;
|
||||
+ if (0 === touchHistory.numberActiveTouches) {
|
||||
+ for (
|
||||
+ topLevelType = 0;
|
||||
+ topLevelType < touchBank.length;
|
||||
+ topLevelType++
|
||||
+ )
|
||||
+ if (
|
||||
+ ((nativeEvent = touchBank[topLevelType]),
|
||||
+ null != nativeEvent && nativeEvent.touchActive)
|
||||
+ )
|
||||
+ nativeEvent.touchActive = !1;
|
||||
+ } else if (1 === touchHistory.numberActiveTouches)
|
||||
for (
|
||||
topLevelType = 0;
|
||||
topLevelType < touchBank.length;
|
||||
@@ -629,6 +638,7 @@ var instrumentationCallback,
|
||||
touchHistory.indexOfSingleActiveTouch = topLevelType;
|
||||
break;
|
||||
}
|
||||
+ }
|
||||
},
|
||||
touchHistory: touchHistory
|
||||
};
|
||||
@@ -810,12 +820,18 @@ var ResponderEventPlugin = {
|
||||
nativeEvent,
|
||||
nativeEventTarget
|
||||
) {
|
||||
- if (isStartish(topLevelType)) trackedTouchCount += 1;
|
||||
+ if (isStartish(topLevelType))
|
||||
+ trackedTouchCount =
|
||||
+ nativeEvent && Array.isArray(nativeEvent.touches)
|
||||
+ ? nativeEvent.touches.length
|
||||
+ : trackedTouchCount + 1;
|
||||
else if (
|
||||
"topTouchEnd" === topLevelType ||
|
||||
"topTouchCancel" === topLevelType
|
||||
)
|
||||
- if (0 <= trackedTouchCount) --trackedTouchCount;
|
||||
+ if (nativeEvent && Array.isArray(nativeEvent.touches))
|
||||
+ trackedTouchCount = nativeEvent.touches.length;
|
||||
+ else if (0 <= trackedTouchCount) --trackedTouchCount;
|
||||
else return null;
|
||||
ResponderTouchHistoryStore.recordTouchTrack(topLevelType, nativeEvent);
|
||||
if (
|
||||
diff --git a/node_modules/react-native/src/private/renderer/events/ReactNativeResponder.js b/node_modules/react-native/src/private/renderer/events/ReactNativeResponder.js
|
||||
index da29336..7167a2f 100644
|
||||
--- a/node_modules/react-native/src/private/renderer/events/ReactNativeResponder.js
|
||||
+++ b/node_modules/react-native/src/private/renderer/events/ReactNativeResponder.js
|
||||
@@ -560,9 +560,13 @@ export function processResponderEvent(
|
||||
): void {
|
||||
// Track touch count
|
||||
if (isStartish(topLevelType)) {
|
||||
- trackedTouchCount += 1;
|
||||
+ trackedTouchCount = Array.isArray(nativeEvent.touches)
|
||||
+ ? nativeEvent.touches.length
|
||||
+ : trackedTouchCount + 1;
|
||||
} else if (isEndish(topLevelType)) {
|
||||
- if (trackedTouchCount >= 0) {
|
||||
+ if (Array.isArray(nativeEvent.touches)) {
|
||||
+ trackedTouchCount = nativeEvent.touches.length;
|
||||
+ } else if (trackedTouchCount >= 0) {
|
||||
trackedTouchCount -= 1;
|
||||
} else {
|
||||
if (__DEV__) {
|
||||
diff --git a/node_modules/react-native/src/private/renderer/events/ResponderTouchHistoryStore.js b/node_modules/react-native/src/private/renderer/events/ResponderTouchHistoryStore.js
|
||||
index c0b4d12..b4aab95 100644
|
||||
--- a/node_modules/react-native/src/private/renderer/events/ResponderTouchHistoryStore.js
|
||||
+++ b/node_modules/react-native/src/private/renderer/events/ResponderTouchHistoryStore.js
|
||||
@@ -234,7 +234,14 @@ const ResponderTouchHistoryStore = {
|
||||
} else if (isEndish(topLevelType)) {
|
||||
nativeEvent.changedTouches.forEach(recordTouchEnd);
|
||||
touchHistory.numberActiveTouches = nativeEvent.touches.length;
|
||||
- if (touchHistory.numberActiveTouches === 1) {
|
||||
+ if (touchHistory.numberActiveTouches === 0) {
|
||||
+ for (let i = 0; i < touchBank.length; i++) {
|
||||
+ const touchTrackToCheck = touchBank[i];
|
||||
+ if (touchTrackToCheck != null && touchTrackToCheck.touchActive) {
|
||||
+ touchTrackToCheck.touchActive = false;
|
||||
+ }
|
||||
+ }
|
||||
+ } else if (touchHistory.numberActiveTouches === 1) {
|
||||
for (let i = 0; i < touchBank.length; i++) {
|
||||
const touchTrackToCheck = touchBank[i];
|
||||
if (touchTrackToCheck != null && touchTrackToCheck.touchActive) {
|
||||
@@ -152,92 +152,18 @@ index 8d78aea..b84d19e 100644
|
||||
viewGroup: ViewGroup,
|
||||
coords: FloatArray,
|
||||
diff --git a/node_modules/react-native-gesture-handler/android/src/main/java/com/swmansion/gesturehandler/react/RNGestureHandlerRootHelper.kt b/node_modules/react-native-gesture-handler/android/src/main/java/com/swmansion/gesturehandler/react/RNGestureHandlerRootHelper.kt
|
||||
index 629c155..2efd508 100644
|
||||
index 629c155..dc0790d 100644
|
||||
--- a/node_modules/react-native-gesture-handler/android/src/main/java/com/swmansion/gesturehandler/react/RNGestureHandlerRootHelper.kt
|
||||
+++ b/node_modules/react-native-gesture-handler/android/src/main/java/com/swmansion/gesturehandler/react/RNGestureHandlerRootHelper.kt
|
||||
@@ -19,7 +19,9 @@ class RNGestureHandlerRootHelper(private val context: ReactContext, wrappedView:
|
||||
@@ -19,6 +19,7 @@ class RNGestureHandlerRootHelper(private val context: ReactContext, wrappedView:
|
||||
private val jsGestureHandler: GestureHandler?
|
||||
val rootView: ViewGroup
|
||||
private var shouldIntercept = false
|
||||
+ private var wasIntercepting = false
|
||||
private var passingTouch = false
|
||||
+ private var lastTouch: MotionEvent? = null
|
||||
|
||||
init {
|
||||
UiThreadUtil.assertOnUiThread()
|
||||
@@ -47,6 +49,7 @@ class RNGestureHandlerRootHelper(private val context: ReactContext, wrappedView:
|
||||
}
|
||||
|
||||
fun tearDown() {
|
||||
+ clearLastTouch()
|
||||
Log.i(
|
||||
ReactConstants.TAG,
|
||||
"[GESTURE HANDLER] Tearing down gesture handler registered for root view $rootView",
|
||||
@@ -90,17 +93,46 @@ class RNGestureHandlerRootHelper(private val context: ReactContext, wrappedView:
|
||||
|
||||
override fun onCancel() {
|
||||
shouldIntercept = true
|
||||
- val time = SystemClock.uptimeMillis()
|
||||
- val event = MotionEvent.obtain(time, time, MotionEvent.ACTION_CANCEL, 0f, 0f, 0).apply {
|
||||
- action = MotionEvent.ACTION_CANCEL
|
||||
- }
|
||||
if (rootView is RootView) {
|
||||
- rootView.onChildStartedNativeGesture(rootView, event)
|
||||
+ val cancel = createReactCancelEvent()
|
||||
+ try {
|
||||
+ rootView.onChildStartedNativeGesture(rootView, cancel)
|
||||
+ } finally {
|
||||
+ cancel.recycle()
|
||||
+ clearLastTouch()
|
||||
+ }
|
||||
}
|
||||
- event.recycle()
|
||||
}
|
||||
}
|
||||
|
||||
+ private fun clearLastTouch() {
|
||||
+ lastTouch?.recycle()
|
||||
+ lastTouch = null
|
||||
+ }
|
||||
+
|
||||
+ private fun createReactCancelEvent(): MotionEvent {
|
||||
+ val now = SystemClock.uptimeMillis()
|
||||
+ val touch = lastTouch ?: return MotionEvent.obtain(now, now, MotionEvent.ACTION_CANCEL, 0f, 0f, 0)
|
||||
+ // The enclosing React root already dispatched this event before it reached the
|
||||
+ // gesture handler. A POINTER_UP is still in MotionEvent but already ended in JS.
|
||||
+ val lifted = if (touch.actionMasked == MotionEvent.ACTION_POINTER_UP) touch.actionIndex else -1
|
||||
+ val count = touch.pointerCount - if (lifted >= 0) 1 else 0
|
||||
+ val properties = Array(count) { MotionEvent.PointerProperties() }
|
||||
+ val coords = Array(count) { MotionEvent.PointerCoords() }
|
||||
+ var index = 0
|
||||
+ for (pointer in 0 until touch.pointerCount) {
|
||||
+ if (pointer == lifted) continue
|
||||
+ touch.getPointerProperties(pointer, properties[index])
|
||||
+ touch.getPointerCoords(pointer, coords[index])
|
||||
+ index++
|
||||
+ }
|
||||
+ return MotionEvent.obtain(
|
||||
+ touch.downTime, now, MotionEvent.ACTION_CANCEL, count, properties, coords,
|
||||
+ touch.metaState, touch.buttonState, touch.xPrecision, touch.yPrecision,
|
||||
+ touch.deviceId, touch.edgeFlags, touch.source, touch.flags,
|
||||
+ )
|
||||
+ }
|
||||
+
|
||||
fun requestDisallowInterceptTouchEvent() {
|
||||
// If this method gets called it means that some native view is attempting to grab lock for
|
||||
// touch event delivery. In that case we cancel all gesture recognizers
|
||||
@@ -115,9 +147,25 @@ class RNGestureHandlerRootHelper(private val context: ReactContext, wrappedView:
|
||||
// We mark `mPassingTouch` before we get into `mOrchestrator.onTouchEvent` so that we can tell
|
||||
// if `requestDisallow` has been called as a result of a normal gesture handling process or
|
||||
// as a result of one of the gesture handlers activating
|
||||
+ // Keep the stream for recognizers that activate between events (e.g. long press).
|
||||
+ // Once native handling begins, React no longer receives the remaining touches.
|
||||
+ if (!event.isHoverAction() && (!shouldIntercept || event.actionMasked == MotionEvent.ACTION_DOWN)) {
|
||||
+ clearLastTouch()
|
||||
+ if (event.actionMasked != MotionEvent.ACTION_UP && event.actionMasked != MotionEvent.ACTION_CANCEL) {
|
||||
+ lastTouch = MotionEvent.obtainNoHistory(event)
|
||||
+ }
|
||||
+ }
|
||||
@@ -118,6 +119,14 @@ class RNGestureHandlerRootHelper(private val context: ReactContext, wrappedView:
|
||||
passingTouch = true
|
||||
orchestrator!!.onTouchEvent(event)
|
||||
passingTouch = false
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
# 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
|
||||
|
||||
Use [Worktrunk v0.82.0](https://github.com/max-sixty/worktrunk/releases/tag/v0.82.0) with Git 2.43.0 or later on the daemon host.
|
||||
|
||||
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
|
||||
```
|
||||
@@ -0,0 +1,44 @@
|
||||
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();
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"id": "worktrunk",
|
||||
"name": "Worktrunk",
|
||||
"description": "Manage Git worktrees and agent activity markers through Worktrunk (wt).",
|
||||
"requirements": { "paseo": ">=0.17.0" }
|
||||
}
|
||||
@@ -0,0 +1,317 @@
|
||||
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.
|
||||
}
|
||||
}
|
||||
@@ -39,6 +39,73 @@ it("reports a CLI without the acp subcommand as unavailable", async () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("publishes Antigravity skills separately from built-in commands", async () => {
|
||||
const { directory, launch } = await launchAgent(`
|
||||
const { createInterface } = require("node:readline");
|
||||
const send = (message) => process.stdout.write(JSON.stringify({ jsonrpc: "2.0", ...message }) + "\\n");
|
||||
createInterface({ input: process.stdin }).on("line", (line) => {
|
||||
const { id, method } = JSON.parse(line);
|
||||
if (method === "initialize") {
|
||||
send({ id, result: { protocolVersion: 1 } });
|
||||
}
|
||||
if (method === "session/new") {
|
||||
send({ id, result: { sessionId: "native" } });
|
||||
send({ method: "session/update", params: { sessionId: "native", update: {
|
||||
sessionUpdate: "available_commands_update",
|
||||
availableCommands: ["goal", "compact", "schedule", "browser", "plan", "grill-me",
|
||||
"teamwork", "learn", "boost", "agy-customizations", "antigravity-guide", "diagnose"]
|
||||
.map(name => ({ name, description: name })),
|
||||
} } });
|
||||
}
|
||||
});
|
||||
`);
|
||||
const connection = await createAntigravityProvider().connect({
|
||||
launch,
|
||||
versions: [1],
|
||||
capabilities: [],
|
||||
});
|
||||
const events: ProviderEvent[] = [];
|
||||
connection.onEvent((event) => events.push(event));
|
||||
try {
|
||||
await connection.send({
|
||||
type: "session.open",
|
||||
requestId: "new",
|
||||
sessionId: "test",
|
||||
history: "skip",
|
||||
config: { cwd: directory, env: {}, mcpServers: {}, settings: {}, persist: false },
|
||||
});
|
||||
await expect
|
||||
.poll(() =>
|
||||
events.find(
|
||||
(event) => event.type === "session.commands" || event.type === "request.failed",
|
||||
),
|
||||
)
|
||||
.toMatchObject({ type: "session.commands" });
|
||||
await expect
|
||||
.poll(() => events.find((event) => event.type === "session.commands")?.commands)
|
||||
.toEqual([
|
||||
...[
|
||||
"goal",
|
||||
"compact",
|
||||
"schedule",
|
||||
"browser",
|
||||
"plan",
|
||||
"grill-me",
|
||||
"teamwork",
|
||||
"learn",
|
||||
"boost",
|
||||
].map((name) => ({ name, description: name, kind: "command" })),
|
||||
...["agy-customizations", "antigravity-guide", "diagnose"].map((name) => ({
|
||||
name,
|
||||
description: name,
|
||||
kind: "skill",
|
||||
})),
|
||||
]);
|
||||
} finally {
|
||||
await connection.close();
|
||||
}
|
||||
});
|
||||
|
||||
it.each([true, false])(
|
||||
"loads a saved stream-JSON session with ACP system prompt support %s",
|
||||
async (supportsSystemPrompt) => {
|
||||
@@ -213,3 +280,156 @@ describe("installation", () => {
|
||||
).resolves.toEqual({ status: "not_installed" });
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps a turn open for backgrounded run_command calls but not IsDaemon commands", async () => {
|
||||
const { directory, launch } = await launchAgent(`
|
||||
const { createInterface } = require("node:readline");
|
||||
const send = (message) => process.stdout.write(JSON.stringify({ jsonrpc: "2.0", ...message }) + "\\n");
|
||||
let turn = 0;
|
||||
createInterface({ input: process.stdin }).on("line", (line) => {
|
||||
const { id, method, params } = JSON.parse(line);
|
||||
switch (method) {
|
||||
case "initialize":
|
||||
send({ id, result: { protocolVersion: 1, agentCapabilities: {} } });
|
||||
break;
|
||||
case "session/new":
|
||||
send({ id, result: { sessionId: "agy-session", configOptions: [
|
||||
{ id: "mode", name: "Mode", category: "mode", type: "select", currentValue: "default",
|
||||
options: [{ value: "default", name: "Default" }] },
|
||||
] } });
|
||||
break;
|
||||
case "session/prompt":
|
||||
turn += 1;
|
||||
if (turn === 1) {
|
||||
send({ method: "session/update", params: { sessionId: params.sessionId, update: {
|
||||
sessionUpdate: "tool_call", toolCallId: "daemon-1", name: "run_command",
|
||||
title: "Dev server", status: "in_progress", rawInput: { CommandLine: "npm run dev", IsDaemon: true },
|
||||
} } });
|
||||
send({ id, result: { stopReason: "end_turn" } });
|
||||
} else {
|
||||
send({ method: "session/update", params: { sessionId: params.sessionId, update: {
|
||||
sessionUpdate: "tool_call", toolCallId: "bg-1", name: "run_command",
|
||||
title: "Background build", status: "in_progress", rawInput: { CommandLine: "sleep 1" },
|
||||
} } });
|
||||
send({ id, result: { stopReason: "end_turn" } });
|
||||
setTimeout(() => {
|
||||
send({ method: "session/update", params: { sessionId: params.sessionId, update: {
|
||||
sessionUpdate: "tool_call_update", toolCallId: "bg-1", status: "completed",
|
||||
} } });
|
||||
send({ method: "session/update", params: { sessionId: params.sessionId, update: {
|
||||
sessionUpdate: "agent_message_chunk", content: { type: "text", text: "Build finished." },
|
||||
} } });
|
||||
send({ method: "session/update", params: { sessionId: params.sessionId, update: {
|
||||
sessionUpdate: "usage_update", used: 50, size: 1000,
|
||||
} } });
|
||||
}, 80);
|
||||
}
|
||||
break;
|
||||
case "session/close":
|
||||
send({ id, result: {} });
|
||||
break;
|
||||
}
|
||||
});
|
||||
`);
|
||||
const provider = createAntigravityProvider();
|
||||
const connection = await provider.connect({
|
||||
launch,
|
||||
versions: [1],
|
||||
capabilities: ["prompt.message"],
|
||||
});
|
||||
const events: ProviderEvent[] = [];
|
||||
connection.onEvent((event) => events.push(event));
|
||||
try {
|
||||
await connection.send({
|
||||
type: "session.open",
|
||||
requestId: "open-1",
|
||||
sessionId: "agy-test",
|
||||
history: "skip",
|
||||
config: {
|
||||
cwd: directory,
|
||||
env: {},
|
||||
mcpServers: {},
|
||||
settings: {},
|
||||
persist: false,
|
||||
},
|
||||
});
|
||||
await expect
|
||||
.poll(() => events.find((event) => event.type === "session.ready"), { timeout: 3_000 })
|
||||
.toBeDefined();
|
||||
|
||||
// Turn 1: IsDaemon: true completes immediately on end_turn.
|
||||
await connection.send({
|
||||
type: "session.prompt",
|
||||
sessionId: "agy-test",
|
||||
prompt: {
|
||||
clientMessageId: "daemon-turn",
|
||||
delivery: "auto",
|
||||
input: { type: "message", content: [{ type: "text", text: "start dev server" }] },
|
||||
},
|
||||
});
|
||||
await expect
|
||||
.poll(
|
||||
() =>
|
||||
events.find(
|
||||
(event) =>
|
||||
event.type === "session.turn" &&
|
||||
event.turnId === "acp:daemon-turn" &&
|
||||
event.state === "completed",
|
||||
),
|
||||
{ timeout: 3_000 },
|
||||
)
|
||||
.toBeDefined();
|
||||
|
||||
// Turn 2: non-daemon background command keeps turn open until completion + reply + usage_update.
|
||||
await connection.send({
|
||||
type: "session.prompt",
|
||||
sessionId: "agy-test",
|
||||
prompt: {
|
||||
clientMessageId: "bg-turn",
|
||||
delivery: "auto",
|
||||
input: { type: "message", content: [{ type: "text", text: "run build" }] },
|
||||
},
|
||||
});
|
||||
await expect
|
||||
.poll(
|
||||
() =>
|
||||
events.find(
|
||||
(event) =>
|
||||
event.type === "timeline.item" &&
|
||||
event.item.type === "tool_call" &&
|
||||
event.item.id === "bg-1" &&
|
||||
event.item.status === "running",
|
||||
),
|
||||
{ timeout: 3_000 },
|
||||
)
|
||||
.toBeDefined();
|
||||
expect(
|
||||
events.some(
|
||||
(event) =>
|
||||
event.type === "session.turn" &&
|
||||
event.turnId === "acp:bg-turn" &&
|
||||
event.state === "completed",
|
||||
),
|
||||
).toBe(false);
|
||||
await expect
|
||||
.poll(
|
||||
() =>
|
||||
events.find(
|
||||
(event) =>
|
||||
event.type === "session.turn" &&
|
||||
event.turnId === "acp:bg-turn" &&
|
||||
event.state === "completed",
|
||||
),
|
||||
{ timeout: 3_000 },
|
||||
)
|
||||
.toBeDefined();
|
||||
expect(events).toContainEqual(
|
||||
expect.objectContaining({
|
||||
type: "timeline.item",
|
||||
item: expect.objectContaining({ type: "assistant_message", text: "Build finished." }),
|
||||
}),
|
||||
);
|
||||
} finally {
|
||||
await connection.close();
|
||||
}
|
||||
});
|
||||
|
||||
@@ -17,7 +17,23 @@ const systemPromptCapability = z.object({
|
||||
|
||||
const fileWrite = z.object({ Path: z.string(), Content: z.string().optional() });
|
||||
|
||||
// agy 1.5.13 advertises these built-in commands and its invocable skills in one ACP list.
|
||||
const builtInCommands = new Set([
|
||||
"goal",
|
||||
"compact",
|
||||
"schedule",
|
||||
"browser",
|
||||
"plan",
|
||||
"grill-me",
|
||||
"teamwork",
|
||||
"learn",
|
||||
"boost",
|
||||
]);
|
||||
|
||||
const antigravity: AcpTransformer = {
|
||||
command(command) {
|
||||
return { ...command, kind: builtInCommands.has(command.name) ? "command" : "skill" };
|
||||
},
|
||||
toolCall(call) {
|
||||
if (call.name === "write_file") {
|
||||
const input = fileWrite.safeParse(call.input);
|
||||
@@ -95,6 +111,16 @@ export function createAntigravityProvider(): ProviderRegistration {
|
||||
acpOptions: {
|
||||
waitForInitialCommands: true,
|
||||
loadReplayQuietPeriodMs: 200,
|
||||
// COMPAT(antigravityAcpV1DeferredTurn): added in v0.18.0, remove once Antigravity CLI supports ACP v2 state_update.
|
||||
deferTurnOnRunningTools: {
|
||||
keepsTurnOpen(toolCall) {
|
||||
const input = toolCall.input;
|
||||
if (typeof input === "object" && input !== null && !Array.isArray(input)) {
|
||||
return input.IsDaemon !== true;
|
||||
}
|
||||
return true;
|
||||
},
|
||||
},
|
||||
autoAcceptMode: {
|
||||
mode: {
|
||||
id: "full-access",
|
||||
|
||||
+16
-8
@@ -447,21 +447,29 @@ paseo hub deploy -p <project> # Deploy an existing legacy project bundle
|
||||
paseo hub logout # Remove the active stored CLI login
|
||||
```
|
||||
|
||||
Run deploy from the repository root. By default it reads every direct `.paseo/triggers/*.yml` file in deterministic path order. It validates all triggers before installing them one at a time. If an installation fails after earlier ones succeeded, the error lists the installed files. `--dry-run` only validates; it does not create or activate revisions.
|
||||
Run `paseo hub deploy` from the repository root. By default, it reads every direct `.paseo/triggers/*.yml` file in deterministic path order and validates all triggers before installing them one at a time.
|
||||
|
||||
Pass `-p, --project <slug>` for an existing legacy bundle: `.paseo/hub.yml`, direct `.paseo/workflows/*.yml` files, and referenced workflow partials. See [Deploy from the CLI](/docs/hub/configuration#deploy-from-the-cli).
|
||||
If an installation fails after earlier ones succeeded, the error lists the installed files. `--dry-run` validates without creating or activating revisions. Pass `-p, --project <slug>` for an existing legacy project bundle.
|
||||
|
||||
`login` opens the Hub approval page and stores a durable organization-scoped CLI credential under `PASEO_HOME`. In an interactive terminal it offers to connect this daemon, then separately asks whether to allow Hub automations to run agents. Connection defaults to yes; execution permission defaults to no. It then links to Hub's **Triggers** page and prints `paseo hub init` for setup as code. `--json` and non-TTY login remain login-only and never prompt. The stored login is separate from the daemon relationship created by `connect`.
|
||||
`paseo hub login` opens the Hub approval page and stores an organization-scoped CLI credential under `PASEO_HOME`. In an interactive terminal, it offers to connect this daemon (default yes) and separately asks whether to grant `hub.execute` (default no).
|
||||
|
||||
`init` requires a TTY. It signs in and connects the daemon as needed, then lists the organization's app connections that can back a starter trigger. One usable connection is selected automatically; with several, you choose a **Trigger connection**. If none is ready, setup sends you to **Hub → Apps** and stops before selecting an agent or writing files.
|
||||
`--json` and non-TTY logins never prompt. The stored CLI login stays separate from the daemon relationship created by `connect`.
|
||||
|
||||
Setup asks which agent provider, model, and mode to run. Providers must be enabled and expose both a selectable model and an execution mode. Suggested model and mode entries are the daemon's defaults; a mode is still selected explicitly when there is no default. Hub validates the choice against the daemon before deploying, and accepts only Claude, Codex, and OpenCode for its unattended runs. `deploy` applies the same checks, so it needs the named daemon connected. Setup then asks for the identity allowed to trigger the bot: a GitHub username, Slack member ID, or Discord user ID. It validates the trigger, writes `.paseo/triggers/<provider>-help.yml`, and asks whether to deploy. Replacing that file requires confirmation; existing legacy bundles and other trigger files are preserved. See the [generated starter trigger](/docs/hub/configuration#generated-starter-trigger).
|
||||
`paseo hub init` requires a TTY, signs in and connects the daemon as needed, and selects a ready integration (or sends you to **Hub → Apps** if none is ready). It then prompts for an enabled provider on your daemon that exposes both a selectable model and at least one execution mode.
|
||||
|
||||
Interactive logout checks the same-origin daemon relationship and asks whether to disconnect before deleting the login. Declining removes only the login. JSON and noninteractive logout never prompt or disconnect implicitly; `--disconnect-daemon` is the explicit automation path, and `--force` applies to that daemon disconnection. If a requested disconnection fails, the login is preserved.
|
||||
Providers that report zero execution modes (such as Pi) are filtered out by `paseo hub init`, but can still be configured in the Hub dashboard or in `.paseo/triggers/*.yml` and deployed with `paseo hub deploy`.
|
||||
|
||||
Every command resolves and normalizes its destination before Hub or daemon work. Origin precedence is an explicit command origin or `--hub`, then `PASEO_HUB_URL`, then the active stored login origin, then the hosted default `https://hub.paseo.sh`. The hosted default never overrides an active login. Credential precedence is `--api-key <secret>`, then `PASEO_HUB_API_KEY`, then a stored login for the exact resolved origin. A stored credential is never sent to a different origin. API keys passed through flags or the environment are not stored.
|
||||
Setup next asks for the allowed sender identity (GitHub username, Slack member ID, or Discord user ID), validates the trigger against the connected daemon, writes `.paseo/triggers/<provider>-help.yml`, and asks whether to deploy. Replacing an existing starter file requires confirmation while preserving other trigger files. See the [generated starter trigger](/docs/hub/configuration#generated-starter-trigger).
|
||||
|
||||
Human output reports the resolved destination before each action. JSON output keeps stdout machine-readable and includes the normalized Hub origin. Bundle diagnostics identify paths without printing configuration contents or credentials.
|
||||
Interactive `paseo hub logout` checks for a daemon connected to the same Hub and asks whether to disconnect it before deleting the login. JSON and non-interactive logouts never prompt or disconnect unless you pass `--disconnect-daemon` (with optional `--force`). If disconnection fails, the login stays intact.
|
||||
|
||||
Every Hub command resolves its destination and credentials in order:
|
||||
|
||||
- Origin precedence: explicit `[url]` or `--hub`, then `PASEO_HUB_URL`, then the active stored login, then `https://hub.paseo.sh`.
|
||||
- Credential precedence: `--api-key <secret>`, then `PASEO_HUB_API_KEY`, then a stored login matching the exact resolved origin.
|
||||
- API keys passed via flags or environment variables are never written to disk, and stored credentials are never sent to another origin.
|
||||
|
||||
Human output prints the resolved destination before each action, while `--json` writes machine-readable output including the normalized Hub origin. Diagnostics name file paths without printing contents or credentials.
|
||||
|
||||
See [Daemons in Hub](/docs/hub/daemons), [Hub configuration](/docs/hub/configuration), and the [Hub public API](/docs/hub/api).
|
||||
|
||||
|
||||
@@ -426,21 +426,29 @@ paseo hub deploy -p <project> # Deploy an existing legacy project bundle
|
||||
paseo hub logout # Remove the active stored CLI login
|
||||
```
|
||||
|
||||
请在仓库根目录运行 deploy。它默认按确定的路径顺序读取所有直接位于 `.paseo/triggers/` 下的 `*.yml` 文件。它会先校验所有触发器,再逐个安装。如果在前面的安装成功之后某个安装失败,错误信息会列出已安装的文件。`--dry-run` 只做校验;它不会创建或激活修订。
|
||||
请在仓库根目录运行 `paseo hub deploy`。它默认按确定的路径顺序读取所有直接位于 `.paseo/triggers/*.yml` 下的文件,并在逐个安装前先校验全部触发器。
|
||||
|
||||
对于已有的旧版文件包,传入 `-p, --project <slug>`:包括 `.paseo/hub.yml`、直接位于 `.paseo/workflows/` 下的 `*.yml` 文件,以及被引用的 workflow 片段。见[从 CLI 部署](/docs/hub/configuration#deploy-from-the-cli)。
|
||||
如果在前面的安装成功之后某个安装失败,错误信息会列出已安装的文件。`--dry-run` 只做校验,不会创建或激活版本。对于已有的旧版项目文件包,请传入 `-p, --project <slug>`。
|
||||
|
||||
`login` 会打开 Hub 的批准页面,并在 `PASEO_HOME` 下保存一个持久的、组织范围的 CLI 凭据。在交互式终端中,它会提议连接这个 daemon,然后单独询问是否允许 Hub 自动化在这里运行 Agent。连接默认为是;执行权限默认为否。随后它会链接到 Hub 的 **Triggers** 页面,并输出 `paseo hub init`,以便用代码完成设置。`--json` 和非 TTY 的登录只执行登录,从不提示。保存的登录与 `connect` 创建的 daemon 关系是分开的。
|
||||
`paseo hub login` 会打开 Hub 批准页面,并在 `PASEO_HOME` 下保存组织级 CLI 凭据。在交互式终端中,它会询问是否连接此 daemon(默认为是),并单独询问是否授予 `hub.execute`(默认为否)。
|
||||
|
||||
`init` 需要 TTY。它会根据需要登录并连接 daemon,然后列出组织中可以支撑入门触发器的应用连接。只有一个可用连接时会自动选中;有多个时,由你选择一个 **Trigger connection**。如果没有任何连接就绪,设置会引导你前往 **Hub → Apps**,并在选择 Agent 或写入文件之前停止。
|
||||
`--json` 和非 TTY 登录不会提示。保存的 CLI 登录与 `connect` 创建的 daemon 关系相互独立。
|
||||
|
||||
设置会询问要运行哪个 Agent Provider、模型和模式。Provider 必须已启用,并且同时提供可选择的模型和执行模式。建议的模型和模式条目是 daemon 的默认值;没有默认值时仍需显式选择模式。Hub 在部署前会对照 daemon 校验这项选择,并且其无人值守的运行只接受 Claude、Codex 和 OpenCode。`deploy` 会执行相同的检查,因此需要指定的 daemon 已连接。随后设置会询问允许触发机器人的身份:GitHub 用户名、Slack 成员 ID 或 Discord 用户 ID。它会校验触发器,写入 `.paseo/triggers/<provider>-help.yml`,并询问是否部署。替换该文件需要确认;已有的旧版文件包和其他触发器文件会被保留。见[生成的入门触发器](/docs/hub/configuration#generated-starter-trigger)。
|
||||
`paseo hub init` 需要 TTY,按需登录并连接 daemon,并选择就绪的集成(若无可用集成则引导至 **Hub → Apps**)。随后它会提示你选择 daemon 上已启用、且同时提供可选模型和至少一个执行模式的 Provider。
|
||||
|
||||
交互式退出会检查同一地址的 daemon 关系,并在删除登录之前询问是否断开。选择否时只删除登录。JSON 和非交互式的退出从不提示,也不会隐式断开;`--disconnect-daemon` 是供自动化使用的显式方式,`--force` 作用于该 daemon 断开操作。如果请求的断开失败,登录会被保留。
|
||||
不提供执行模式的 Provider(例如 Pi)会被 `paseo hub init` 过滤掉,但仍可在 Hub 控制台或 `.paseo/triggers/*.yml` 中配置并通过 `paseo hub deploy` 部署。
|
||||
|
||||
每个命令在执行 Hub 或 daemon 工作之前,都会解析并规范化它的目标。地址的优先级依次为:显式的命令地址或 `--hub`、`PASEO_HUB_URL`、当前保存的登录地址,最后是托管版默认地址 `https://hub.paseo.sh`。托管版默认地址从不会覆盖当前的登录。凭据的优先级依次为:`--api-key <secret>`、`PASEO_HUB_API_KEY`,然后是与解析出的地址完全匹配的已保存登录。保存的凭据从不会发送到其他地址。通过参数或环境变量传入的 API 密钥不会被保存。
|
||||
接着设置会询问允许的发送者身份(GitHub 用户名、Slack 成员 ID 或 Discord 用户 ID),对照已连接的 daemon 校验触发器,写入 `.paseo/triggers/<provider>-help.yml` 并询问是否部署。替换已有入门文件需要确认,同时保留其他触发器文件。见[生成的入门触发器](/docs/hub/configuration#generated-starter-trigger)。
|
||||
|
||||
人类可读的输出会在每个操作之前报告解析出的目标。JSON 输出让 stdout 保持机器可读,并包含规范化后的 Hub 地址。文件包诊断会指出路径,但不会输出配置内容或凭据。
|
||||
交互式 `paseo hub logout` 会检查连接到同一 Hub 的 daemon,并在删除登录前询问是否断开。JSON 和非交互式退出不会提示或断开,除非传入 `--disconnect-daemon`(可配合 `--force`)。如果断开失败,登录凭据会保留。
|
||||
|
||||
每个 Hub 命令都按顺序解析目标和凭据:
|
||||
|
||||
- 地址优先级:显式 `[url]` 或 `--hub`、`PASEO_HUB_URL`、当前已保存的登录,最后是 `https://hub.paseo.sh`。
|
||||
- 凭据优先级:`--api-key <secret>`、`PASEO_HUB_API_KEY`,然后是与精确解析地址匹配的已保存登录。
|
||||
- 通过参数或环境变量传入的 API 密钥永远不会写入磁盘,已保存的凭据也不会发送到其他地址。
|
||||
|
||||
人类可读输出会在每个操作前打印解析出的目标,而 `--json` 会输出包含规范化 Hub 地址的机器可读结果。诊断信息仅指出文件路径,不输出文件内容或凭据。
|
||||
|
||||
见 [Hub 中的 daemon](/docs/hub/daemons)、[Hub 配置](/docs/hub/configuration)和 [Hub 公开 API](/docs/hub/api)。
|
||||
|
||||
|
||||
+22
-32
@@ -1,53 +1,43 @@
|
||||
---
|
||||
title: Hub activity
|
||||
description: Read what Hub did with an event, tell a filtered event from an unrouted one, and debug a trigger that did nothing.
|
||||
description: Inspect trigger runs, distinguish filtered events from unrouted ones, and debug a trigger that did not run.
|
||||
nav: Activity
|
||||
order: 72
|
||||
order: 75
|
||||
category: Hub
|
||||
---
|
||||
|
||||
# Hub activity
|
||||
|
||||
Every event Hub accepts is recorded, whether or not it ran anything. That record is how you debug a trigger.
|
||||
Hub records every accepted event, whether or not it started a run. Use **Activity** and **Integrations** to inspect deliveries and debug triggers.
|
||||
|
||||
## Where to look
|
||||
|
||||
**Project → Activity** lists routed trigger runs and their execution state.
|
||||
**Activity** lists recent trigger runs for the organization. Each row shows the trigger, provider, source, status, and when Hub received the event.
|
||||
|
||||
**Connections → Known unrouted events** is the organization-level view of accepted provider events that did not start a configured trigger. Hub records one of four bounded reasons:
|
||||
**Integrations → Known unrouted events** shows the 50 most recent accepted provider events that did not start a run. Hub records one of four reasons:
|
||||
|
||||
| Reason | Meaning |
|
||||
| --------------------------- | ------------------------------------------------------------ |
|
||||
| `no_project_route` | No project route is configured for the event |
|
||||
| `no_trigger_for_source` | No configured trigger handles that event source |
|
||||
| `trigger_filters_rejected` | A trigger handles the source, but its filters rejected it |
|
||||
| `configuration_unavailable` | A relevant configuration or connection could not be resolved |
|
||||
| `no_project_route` | No enabled route matched the event's integration or resource |
|
||||
| `no_trigger_for_source` | No enabled trigger handles that event source |
|
||||
| `trigger_filters_rejected` | A trigger matched the source, but its filters rejected it |
|
||||
| `configuration_unavailable` | A referenced trigger or integration could not be resolved |
|
||||
|
||||
## Nothing happened when I mentioned the bot
|
||||
## Nothing happened when an event arrived
|
||||
|
||||
Work down this list.
|
||||
Check these items in order:
|
||||
|
||||
1. **Is the event in the project's Activity?** If not, check **Connections → Known unrouted events** and use its reason to distinguish routing, source, filter, and configuration failures.
|
||||
2. **Is the event anywhere at all?** If not, the event never reached Hub. Check the provider's own delivery log: GitHub's App → Advanced → Recent Deliveries, or Slack's Event Subscriptions page. Then check that the app is subscribed to that event type.
|
||||
3. **Is your user in `from_users`?** This is the most common cause. GitHub uses your login; Slack and Discord use the user ID, not the display name. See [find your Slack IDs](/docs/hub/triggers/slack#find-your-slack-ids) and [find your Discord IDs](/docs/hub/triggers/discord#find-your-discord-ids).
|
||||
4. **Did the invocation match?** On GitHub, `contains` must appear in the comment body. On Slack and Discord the bot must be mentioned, and `pattern` or its legacy `contains` alias must prefix the text after the mention.
|
||||
5. **Is the configuration you think is active actually active?** The Configuration tab shows the active revision and the last sync attempt. A failed push leaves the old revision serving.
|
||||
6. **Is the daemon connected?** An offline daemon fails dispatch with `daemon_not_connected`.
|
||||
7. **Did it run and stop early?** Compare the execution with the step's authored `idle_timeout` and `max_runtime`, and the workflow's `max_runtime`. All three limits are explicit in the workflow.
|
||||
8. **Did it run, but deliver nothing?** Check the step's prompt. An agent that is not told to call `hub.reply` and `hub.finish_execution` can answer in its own transcript and never report back. See [Tell the agent which tool to call](/docs/hub/workflows#tell-the-agent-which-tool-to-call).
|
||||
1. Open **Activity**. If the event is missing there, check **Integrations → Known unrouted events** and read the recorded reason.
|
||||
2. If the event is missing from both views, use the provider delivery log to see whether Hub accepted it. For GitHub, open **App → Advanced → Recent Deliveries**. If the provider sent no delivery, make sure that the integration subscribes to the event type.
|
||||
3. Verify `from_users`. GitHub uses login names, while Linear, Slack, and Discord use user IDs ([Linear](/docs/hub/triggers/linear#filters-and-linear-uuids), [Slack](/docs/hub/triggers/slack#find-your-slack-ids), [Discord](/docs/hub/triggers/discord#find-your-discord-ids)).
|
||||
4. Verify text filters (`contains`, `pattern`, and GitHub `exclude_contains`). On Slack and Discord, the message must mention the bot and any `pattern` must follow the mention.
|
||||
5. Verify that the trigger is enabled under **Triggers**.
|
||||
6. Verify that the target daemon is connected under **Daemons** and holds the `hub.execute` permission.
|
||||
7. If the run started and stopped early, compare its duration against `max_runtime`, `idle_timeout`, and `startup_timeout`.
|
||||
8. If the run finished without posting back, check `run.prompt`. The prompt must tell the agent to call `reply` (or `slack_post` / `discord_post`) and `finish_execution`.
|
||||
|
||||
## Sync failures
|
||||
## Webhook and schedule runs
|
||||
|
||||
The Configuration tab shows the latest sync state:
|
||||
Runs started by inbound webhooks appear in **Activity** under `webhook.received`. If an HTTP `POST` returns an error status (`400`, `401`, `403`, `409`, `413`, or `429`), see [Inbound webhooks](/docs/hub/triggers/webhooks#request-limits-and-responses).
|
||||
|
||||
| State | What to do |
|
||||
| ----------------------- | ------------------------------------------------------------------------ |
|
||||
| Fetch failed | The file is missing at that commit, or the App can't read the repository |
|
||||
| Invalid | Validation failed, or the config names something unreachable |
|
||||
| Superseded push ignored | A newer commit already moved the branch head; nothing is wrong |
|
||||
|
||||
"Names something unreachable" is usually a repository the installation doesn't cover, a daemon that was renamed, or a connection slug that no longer exists. See [How Hub works](/docs/hub/concepts).
|
||||
|
||||
## Nothing is retried
|
||||
|
||||
Hub does not queue events. A dispatch that fails because the daemon was offline stays failed, so trigger it again once the daemon is back.
|
||||
Scheduled runs appear in **Activity** under `schedule.tick`. While a scheduled run is still active, Hub skips newly due occurrences for that trigger until the active run completes or fails.
|
||||
|
||||
@@ -1,51 +1,41 @@
|
||||
---
|
||||
title: Hub 活动
|
||||
description: 查看 Hub 如何处理一个事件,区分被过滤和未路由的事件,并排查没有任何反应的触发器。
|
||||
description: 查看触发器运行记录、区分被过滤事件与未路由事件,以及排查未触发的问题。
|
||||
nav: 活动
|
||||
---
|
||||
|
||||
# Hub 活动 {#hub-activity}
|
||||
|
||||
Hub 接受的每个事件都会被记录,无论它是否运行了任何内容。这份记录就是你排查触发器的依据。
|
||||
Hub 会记录每一次已接受的事件,无论它是否启动了运行。使用 **Activity** 和 **Integrations** 查看投递并排查触发器。
|
||||
|
||||
## 在哪里查看 {#where-to-look}
|
||||
|
||||
**Project → Activity** 列出已路由的触发器运行及其执行状态。
|
||||
**Activity** 列出组织最近的触发器运行记录。每行显示触发器、Provider、来源、状态和 Hub 收到事件的时间。
|
||||
|
||||
**Connections → Known unrouted events** 是组织级视图,列出已接受但没有启动任何已配置触发器的 Provider 事件。Hub 会记录以下四种原因之一:
|
||||
**Integrations → Known unrouted events** 显示 Hub 最近接受但未启动运行的 50 条 Provider 事件。Hub 记录以下四种原因之一:
|
||||
|
||||
| 原因 | 含义 |
|
||||
| --------------------------- | -------------------------------------------- |
|
||||
| `no_project_route` | 没有为该事件配置项目路由 |
|
||||
| `no_trigger_for_source` | 没有已配置的触发器处理该事件来源 |
|
||||
| `trigger_filters_rejected` | 有触发器处理该来源,但它的过滤器拒绝了该事件 |
|
||||
| `configuration_unavailable` | 无法解析相关的配置或连接 |
|
||||
| 原因 | 含义 |
|
||||
| --------------------------- | -------------------------------------- |
|
||||
| `no_project_route` | 没有已启用的路由匹配该事件的集成或资源 |
|
||||
| `no_trigger_for_source` | 没有已启用的触发器处理该事件来源 |
|
||||
| `trigger_filters_rejected` | 有触发器处理该来源,但被过滤条件拒绝 |
|
||||
| `configuration_unavailable` | 无法解析引用的触发器或集成 |
|
||||
|
||||
## 我提及了机器人,但什么都没发生 {#nothing-happened-when-i-mentioned-the-bot}
|
||||
## 事件到达后没有任何反应 {#nothing-happened-when-an-event-arrived}
|
||||
|
||||
按这个列表逐项排查。
|
||||
按以下顺序排查:
|
||||
|
||||
1. **事件是否出现在项目的 Activity 中?** 如果没有,请查看 **Connections → Known unrouted events**,根据其中的原因区分路由、来源、过滤器和配置方面的失败。
|
||||
2. **事件是否出现在任何地方?** 如果没有,说明事件从未到达 Hub。请查看 Provider 自己的投递日志:GitHub 的 App → Advanced → Recent Deliveries,或 Slack 的 Event Subscriptions 页面。然后确认应用订阅了该事件类型。
|
||||
3. **你的用户是否在 `from_users` 中?** 这是最常见的原因。GitHub 使用你的登录名;Slack 和 Discord 使用用户 ID,而不是显示名称。参见[查找 Slack ID](/docs/hub/triggers/slack#find-your-slack-ids) 和[查找 Discord ID](/docs/hub/triggers/discord#find-your-discord-ids)。
|
||||
4. **调用是否匹配?** 在 GitHub 上,评论正文中必须出现 `contains`。在 Slack 和 Discord 上,必须提及机器人,并且提及之后的文本必须以 `pattern`(或其旧别名 `contains`)开头。
|
||||
5. **你以为生效的配置是否真的生效?** Configuration 标签页显示当前生效的版本和上一次同步尝试。推送失败时,旧版本会继续生效。
|
||||
6. **daemon 是否已连接?** daemon 离线时派发会失败,并报告 `daemon_not_connected`。
|
||||
7. **是否运行了但提前停止?** 把这次执行与 step 中编写的 `idle_timeout`、`max_runtime` 以及 workflow 的 `max_runtime` 进行比较。这三个限制都在 workflow 中显式声明。
|
||||
8. **是否运行了但什么都没投递?** 检查 step 的提示词。没有被告知调用 `hub.reply` 和 `hub.finish_execution` 的 Agent,可能只在自己的对话记录中回答,而从不回报。参见[告诉 Agent 调用哪个工具](/docs/hub/workflows#tell-the-agent-which-tool-to-call)。
|
||||
1. 打开 **Activity**。如果事件未出现在那里,请检查 **Integrations → Known unrouted events** 并查看记录的原因。
|
||||
2. 如果两处都找不到该事件,请查看 Provider 的投递日志,确认 Hub 是否接受了该事件。对于 GitHub,请打开 **App → Advanced → Recent Deliveries**。如果 Provider 没有发送该事件,请确认集成已订阅对应的事件类型。
|
||||
3. 检查 `from_users`。GitHub 使用登录名,Linear、Slack 和 Discord 使用用户 ID(参见 [Linear](/docs/hub/triggers/linear#filters-and-linear-uuids)、[Slack](/docs/hub/triggers/slack#find-your-slack-ids)、[Discord](/docs/hub/triggers/discord#find-your-discord-ids))。
|
||||
4. 检查文本过滤条件(`contains`、`pattern` 以及 GitHub 的 `exclude_contains`)。在 Slack 和 Discord 上,消息必须提及机器人,且任何 `pattern` 都必须紧跟在提及之后。
|
||||
5. 在 **Triggers** 下确认触发器已启用。
|
||||
6. 在 **Daemons** 下确认目标 daemon 已连接并拥有 `hub.execute` 权限。
|
||||
7. 如果运行已启动但提前停止,请将其持续时间与 `max_runtime`、`idle_timeout` 和 `startup_timeout` 进行对比。
|
||||
8. 如果运行已完成但没有回复,请检查 `run.prompt`。提示词必须明确告诉 Agent 调用 `reply`(或 `slack_post` / `discord_post`)和 `finish_execution`。
|
||||
|
||||
## 同步失败 {#sync-failures}
|
||||
## Webhook 与定时运行 {#webhook-and-schedule-runs}
|
||||
|
||||
Configuration 标签页显示最近的同步状态:
|
||||
由入站 webhook 启动的运行会以 `webhook.received` 出现在 **Activity** 中。如果 HTTP `POST` 返回错误状态码(`400`、`401`、`403`、`409`、`413` 或 `429`),参见[入站 webhook](/docs/hub/triggers/webhooks#request-limits-and-responses)。
|
||||
|
||||
| 状态 | 处理方式 |
|
||||
| ----------------------- | ---------------------------------------- |
|
||||
| Fetch failed | 该提交中缺少文件,或者 App 无法读取仓库 |
|
||||
| Invalid | 校验失败,或者配置引用了无法访问的内容 |
|
||||
| Superseded push ignored | 更新的提交已经移动了分支头;没有任何问题 |
|
||||
|
||||
“引用了无法访问的内容”通常是指安装未覆盖的仓库、已被重命名的 daemon,或已不存在的连接 slug。参见 [Hub 工作原理](/docs/hub/concepts)。
|
||||
|
||||
## 不会重试 {#nothing-is-retried}
|
||||
|
||||
Hub 不会让事件排队。因 daemon 离线而失败的派发会一直保持失败,所以请在 daemon 恢复后重新触发。
|
||||
定时运行会以 `schedule.tick` 出现在 **Activity** 中。当某次定时运行仍在进行时,Hub 会跳过该触发器新到期的计划,直到当前运行完成或失败。
|
||||
|
||||
+59
-174
@@ -1,56 +1,46 @@
|
||||
---
|
||||
title: Hub public API
|
||||
description: Use organization credentials to install triggers, manage legacy configuration, dispatch runs, and enroll daemons.
|
||||
description: Authenticate with organization credentials to validate and install triggers, rotate webhook secrets, dispatch manual runs, and enroll daemons.
|
||||
nav: Public API
|
||||
order: 79
|
||||
order: 83
|
||||
category: Hub
|
||||
---
|
||||
|
||||
# Hub public API
|
||||
|
||||
The Hub public API lets automation operate on triggers, projects, and daemons in one
|
||||
organization. Set the Hub origin in `PASEO_HUB_URL` below, for example
|
||||
`https://hub.example.com`.
|
||||
The Hub public API lets scripts and CI pipelines manage triggers, webhook secrets, manual runs, and daemon enrollment for one organization. Set `PASEO_HUB_URL` to your Hub origin, such as `https://hub.example.com`.
|
||||
|
||||
## API reference
|
||||
|
||||
- [Interactive API reference](https://hub.paseo.sh/api/reference)
|
||||
- [OpenAPI 3.1 document](https://hub.paseo.sh/api/openapi.json)
|
||||
|
||||
These are the canonical reference endpoints for the hosted Paseo Hub. A self-hosted Hub exposes the same `/api/reference` and `/api/openapi.json` paths on its own origin.
|
||||
A self-hosted Hub serves the same `/api/reference` and `/api/openapi.json` endpoints on its own origin.
|
||||
|
||||
## Authentication
|
||||
|
||||
Run `paseo hub login [origin]` for interactive CLI access. After browser approval, Paseo stores a durable, revocable organization credential under `PASEO_HOME` for that exact origin. Without an explicit origin, the CLI uses `PASEO_HUB_URL`, then the active stored login, then `https://hub.paseo.sh`.
|
||||
For interactive CLI access, run `paseo hub login [origin]`. Paseo stores a revocable organization credential under `PASEO_HOME` for that exact origin.
|
||||
|
||||
For automation, create an organization API key from the Hub dashboard under **API keys**. Both credential types are bearer tokens:
|
||||
For automation, create an organization API key in Hub under **Settings → API keys**. Send either credential as a Bearer token:
|
||||
|
||||
```http
|
||||
Authorization: Bearer paseo_pk_...
|
||||
Content-Type: application/json
|
||||
```
|
||||
|
||||
API keys are organization-scoped. The organization that owns the key determines
|
||||
which projects and daemon enrollment tokens it can reach; there is no
|
||||
organization ID to add to these requests. A project slug from another
|
||||
organization is not accessible through the key.
|
||||
API keys are scoped to one organization and one or more selected scopes:
|
||||
|
||||
Each key has one or more selectable scopes:
|
||||
| Scope | Operations permitted |
|
||||
| ------------------------ | ---------------------------------------------------------------- |
|
||||
| `configuration:validate` | List triggers, list resolvable resources, and validate triggers. |
|
||||
| `configuration:install` | Install triggers and create or rotate trigger webhook secrets. |
|
||||
| `runs:dispatch` | Dispatch a configured `manual.run` trigger. |
|
||||
| `daemons:enroll` | Issue a short-lived daemon enrollment token. |
|
||||
| `projects:read` | List projects in the organization. |
|
||||
|
||||
| Scope | Operation |
|
||||
| ------------------------ | --------------------------------------------------------------------- |
|
||||
| `projects:read` | List active projects in the organization. |
|
||||
| `configuration:validate` | Validate triggers or legacy configuration without changing Hub state. |
|
||||
| `configuration:install` | Install triggers or replace a legacy project's configuration. |
|
||||
| `runs:dispatch` | Dispatch a configured manual trigger for a project. |
|
||||
| `daemons:enroll` | Issue a short-lived daemon enrollment token. |
|
||||
API keys do not grant dashboard sign-in and cannot manage integrations or organization members.
|
||||
|
||||
API keys do not grant dashboard access. They cannot manage connections,
|
||||
projects, or organization members.
|
||||
|
||||
CLI credentials have the current CLI operation scopes and remain revocable independently of daemon relationships. `paseo hub logout` deletes the active local CLI credential; it does not revoke or disconnect the daemon identity.
|
||||
|
||||
API failures use RFC 9457 problem details. Missing, invalid, or revoked credentials return `401` with `application/problem+json`:
|
||||
API errors return RFC 9457 `application/problem+json` with an `X-Request-ID` header. Missing, invalid, or revoked credentials return `401` with `WWW-Authenticate: Bearer`:
|
||||
|
||||
```json
|
||||
{
|
||||
@@ -63,23 +53,23 @@ API failures use RFC 9457 problem details. Missing, invalid, or revoked credenti
|
||||
}
|
||||
```
|
||||
|
||||
A valid key without the scope required by an endpoint returns `403` in the same format.
|
||||
A valid credential missing the required scope returns `403` in the same format.
|
||||
|
||||
## Trigger validation and installation
|
||||
## Trigger list, validation, and installation
|
||||
|
||||
`paseo hub deploy --dry-run` validates each `.paseo/triggers/*.yml` file through `POST /api/v1/triggers/validate`. `paseo hub deploy` validates all files first, then installs each through `POST /api/v1/triggers/install`.
|
||||
- `GET /api/v1/triggers` (`configuration:validate`) lists active organization triggers and their deployable YAML documents.
|
||||
- `POST /api/v1/triggers/validate` (`configuration:validate`) validates one self-contained trigger YAML document without changing Hub state.
|
||||
- `POST /api/v1/triggers/install` (`configuration:install`) validates and installs one trigger, creating or updating it by its YAML `name`.
|
||||
|
||||
Both endpoints accept one self-contained document:
|
||||
`POST /api/v1/triggers/validate` and `POST /api/v1/triggers/install` accept the same JSON request body:
|
||||
|
||||
```json
|
||||
{
|
||||
"yaml": "name: manual-task\nenabled: true\non:\n manual.run: {}\nrun:\n target: { daemon: my-macbook, cwd: /workspace }\n agent: { provider: codex, model: gpt-5, mode: full-access }\n prompt: Complete the task and call hub.finish_execution.\n max_runtime: 1h\n idle_timeout: 5m\n"
|
||||
"yaml": "name: manual-task\nenabled: true\non:\n manual.run: {}\nrun:\n target: { daemon: my-macbook, cwd: /workspace }\n agent: { provider: codex, mode: full-access }\n prompt: |\n Complete the task and call finish_execution.\n ${{ paseo.prompt }}\n max_runtime: 1h\n idle_timeout: 5m\n"
|
||||
}
|
||||
```
|
||||
|
||||
Use a daemon slug and agent runtime available in your organization. Both operations ask the named daemon to check the agent, so it has to be connected and hold `hub.execute`; an agent it cannot run is a field issue rather than a failed first run. See [Saving checks the agent against the daemon](/docs/hub/triggers#saving-checks-the-agent-against-the-daemon). Validation requires `configuration:validate` and returns `200` with `{ "name": "manual-task", "valid": true }`.
|
||||
|
||||
Installation requires `configuration:install`. It creates or updates the organization's trigger by the YAML `name` and returns `201`:
|
||||
Both endpoints ask the target daemon to validate `run.agent`, so that daemon must be connected and hold `hub.execute`. Validation returns `200` with `{ "name": "manual-task", "valid": true }`. Installation returns `201`:
|
||||
|
||||
```json
|
||||
{
|
||||
@@ -91,143 +81,64 @@ Installation requires `configuration:install`. It creates or updates the organiz
|
||||
}
|
||||
```
|
||||
|
||||
Invalid YAML or an unknown organization resource returns `422` with field issues. Each installation is a separate request; a later failure does not undo earlier successful installs. See [Deploy from the CLI](/docs/hub/configuration#deploy-from-the-cli).
|
||||
Invalid YAML, unknown integrations, or rejected agent settings return `422` with field issues. `paseo hub deploy --dry-run` and `paseo hub deploy` call these endpoints for `.paseo/triggers/*.yml`.
|
||||
|
||||
## Project list
|
||||
## Webhook secrets
|
||||
|
||||
`GET /api/v1/projects` returns active projects in the bearer credential's organization. `paseo hub projects` renders the projects as a table. With `--json`, it returns `{ "origin": "...", "projects": [...] }` so even an empty result records the resolved Hub.
|
||||
|
||||
```json
|
||||
{
|
||||
"projects": [
|
||||
{
|
||||
"id": "00000000-0000-4000-8000-000000000000",
|
||||
"slug": "my-project",
|
||||
"name": "My project"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
## Legacy configuration validation
|
||||
|
||||
`POST /api/v1/configurations/validate` accepts the same `projectSlug` and complete `files` bundle as configuration install. It performs the same compilation and resource resolution without recording a revision or changing the active configuration.
|
||||
|
||||
On success, Hub returns `200`:
|
||||
|
||||
```json
|
||||
{
|
||||
"projectSlug": "my-project",
|
||||
"valid": true
|
||||
}
|
||||
```
|
||||
|
||||
`paseo hub deploy --project <slug> --dry-run` calls this endpoint with the identical locally resolved payload that a deployment would send.
|
||||
|
||||
## Legacy configuration install
|
||||
|
||||
`configuration:install` validates the supplied canonical bundle, stores the exact authored files, and activates a new revision.
|
||||
|
||||
```http
|
||||
POST /api/v1/configurations/install
|
||||
```
|
||||
`POST /api/v1/triggers/webhook-secret` (`configuration:install`) creates or rotates the Bearer secret for a saved `webhook.received` trigger.
|
||||
|
||||
Request body:
|
||||
|
||||
```json
|
||||
{
|
||||
"projectSlug": "my-project",
|
||||
"files": [
|
||||
{
|
||||
"path": ".paseo/hub.yml",
|
||||
"content": "environments:\n production:\n kind: daemon\n daemon: build-server\n cwd: /workspace\nagents:\n codex:\n provider: codex\n"
|
||||
},
|
||||
{
|
||||
"path": ".paseo/workflows/deploy.yml",
|
||||
"content": "name: deploy\non: manual.run\nmax_runtime: 2h\nfilters:\n from_users: [automation]\nsteps:\n - id: deploy\n environment: production\n max_runtime: 90m\n idle_timeout: 10m\n agent: codex\n prompt:\n - include: partials/safety.md\n"
|
||||
},
|
||||
{
|
||||
"path": ".paseo/workflows/partials/safety.md",
|
||||
"content": "Follow the safety checklist."
|
||||
}
|
||||
]
|
||||
"triggerId": "00000000-0000-4000-8000-000000000001"
|
||||
}
|
||||
```
|
||||
|
||||
`projectSlug` picks the target project; the bearer credential fixes the organization. `files` contains `.paseo/hub.yml`, every direct workflow `.yml`, and each referenced workflow partial. Hub rejects missing, extra, duplicate, unsafe, or noncanonical paths.
|
||||
|
||||
Limits:
|
||||
|
||||
- Bundle: at most 100 files.
|
||||
- File path: at most 512 characters.
|
||||
- File content: at most 1,000,000 characters.
|
||||
- Prompt partials: at most 1,000,000 bytes each and 5,000,000 bytes in total.
|
||||
|
||||
On success, Hub returns `201`:
|
||||
On success, Hub returns `200` with `Cache-Control: no-store`:
|
||||
|
||||
```json
|
||||
{
|
||||
"projectSlug": "my-project",
|
||||
"versionId": "00000000-0000-4000-8000-000000000000",
|
||||
"version": 3,
|
||||
"active": true
|
||||
"path": "/webhooks/wh_0123456789abcdef0123456789abcdef",
|
||||
"secret": "whsec_..."
|
||||
}
|
||||
```
|
||||
|
||||
Common responses are `400` for a missing or malformed body, `404` for an inactive or unknown project in the key's organization, and `422` for invalid YAML or an invalid configuration. Validation problem details include field issues. A failed install does not replace the active revision.
|
||||
|
||||
Example:
|
||||
|
||||
```bash
|
||||
curl --fail-with-body -sS -X POST "$PASEO_HUB_URL/api/v1/configurations/install" \
|
||||
-H "Authorization: Bearer $PASEO_HUB_API_KEY" \
|
||||
-H "Content-Type: application/json" \
|
||||
--data @configuration-install.json
|
||||
```
|
||||
|
||||
`paseo hub deploy -p <project>` selects this legacy endpoint with the discovered local bundle. The command uses an exact-origin stored login when flags and environment credentials are absent. See [Deploy from the CLI](/docs/hub/configuration#deploy-from-the-cli).
|
||||
Each call replaces any previous secret immediately and shows the new secret only once. See [Inbound webhooks](/docs/hub/triggers/webhooks) for sending deliveries to `/webhooks/wh_...`.
|
||||
|
||||
## Manual run dispatch
|
||||
|
||||
`runs:dispatch` dispatches a configured `manual.run` trigger for a project.
|
||||
The trigger must exist in the active configuration, and `actor` must be listed
|
||||
in that trigger's `filters.from_users` allowlist.
|
||||
|
||||
```http
|
||||
POST /api/v1/manual-runs
|
||||
```
|
||||
|
||||
Request body:
|
||||
`POST /api/v1/manual-runs` (`runs:dispatch`) starts a configured `manual.run` trigger. `actor` must match that trigger's `filters.from_users` allowlist (or `*` when omitted).
|
||||
|
||||
```json
|
||||
{
|
||||
"projectSlug": "my-project",
|
||||
"expectedVersionId": "00000000-0000-4000-8000-000000000000",
|
||||
"trigger": "deploy",
|
||||
"projectSlug": "default",
|
||||
"trigger": "manual-task",
|
||||
"actor": "automation",
|
||||
"deliveryKey": "deploy-2026-08-04-001",
|
||||
"deliveryKey": "manual-task-2026-09-09-001",
|
||||
"input": "repo=project investigate the failed sync"
|
||||
}
|
||||
```
|
||||
|
||||
- `expectedVersionId` is optional. When supplied, Hub rejects the dispatch if that revision is no longer active.
|
||||
- `input` is the same string a provider message uses: leading `key=value` tokens are parsed as declared inputs, and the remainder becomes `${{ paseo.prompt }}`.
|
||||
- `deliveryKey` should be unique and stable per dispatch. Hub uses it for durable deduplication, but does not promise exactly-once dispatch or replay of an earlier response.
|
||||
- `deliveryKey` provides durable deduplication scoped to your organization and project.
|
||||
- `input` accepts leading `key=value` tokens for declared `inputs` followed by prompt text.
|
||||
|
||||
Omit `expectedVersionId` for standalone triggers. Passing the `revisionId` from trigger installation returns HTTP `409` (`configuration_changed`), even when the trigger is unchanged.
|
||||
|
||||
For legacy project bundles, `expectedVersionId` is optional. Set it to the active project configuration revision ID to reject dispatch if the configuration changes.
|
||||
|
||||
On success, Hub returns `200`:
|
||||
|
||||
```json
|
||||
{
|
||||
"deliveryKey": "deploy-2026-08-04-001",
|
||||
"deliveryKey": "manual-task-2026-09-09-001",
|
||||
"providerEventReceiptId": "00000000-0000-4000-8000-000000000000",
|
||||
"triggerRunId": "00000000-0000-4000-8000-000000000000",
|
||||
"configuredTriggerName": "deploy",
|
||||
"configuredTriggerName": "manual-task",
|
||||
"workflowStatus": "running"
|
||||
}
|
||||
```
|
||||
|
||||
Common responses are `400` for an invalid request, `403` when the actor is not allowed by the trigger, `404` for an unknown project, configuration, or trigger, and `409` when the daemon is offline, the expected configuration is no longer current, or dispatch conflicts. Each uses the problem-details shape above.
|
||||
|
||||
Example:
|
||||
|
||||
```bash
|
||||
@@ -235,39 +146,17 @@ curl --fail-with-body -sS -X POST "$PASEO_HUB_URL/api/v1/manual-runs" \
|
||||
-H "Authorization: Bearer $PASEO_HUB_API_KEY" \
|
||||
-H "Content-Type: application/json" \
|
||||
--data '{
|
||||
"projectSlug": "my-project",
|
||||
"trigger": "deploy",
|
||||
"projectSlug": "default",
|
||||
"trigger": "manual-task",
|
||||
"actor": "automation",
|
||||
"deliveryKey": "deploy-2026-08-04-001",
|
||||
"input": "repo=project investigate the failed sync"
|
||||
"deliveryKey": "manual-task-2026-09-09-001",
|
||||
"input": "investigate the failed sync"
|
||||
}'
|
||||
```
|
||||
|
||||
See [Hub workflows](/docs/hub/workflows) for input types, defaults, choices,
|
||||
rejected input, and manual invocation examples.
|
||||
|
||||
## Daemon enrollment
|
||||
|
||||
`daemons:enroll` issues a short-lived enrollment token for a daemon. The API
|
||||
key mints this token; it is not the daemon's long-lived credential and must not
|
||||
be used as one.
|
||||
|
||||
```http
|
||||
POST /api/v1/daemons/enrollment-tokens
|
||||
```
|
||||
|
||||
No request body is required. On success, Hub returns `201`:
|
||||
|
||||
```json
|
||||
{
|
||||
"token": "short-lived-enrollment-token",
|
||||
"expiresAt": "2026-08-04T12:10:00.000Z"
|
||||
}
|
||||
```
|
||||
|
||||
The token expires after 10 minutes and is consumed when the daemon enrolls.
|
||||
|
||||
`paseo hub connect [origin]` performs this request with `--api-key`, `PASEO_HUB_API_KEY`, or the matching stored login, then passes the one-time token to the daemon's enrollment operation. The daemon generates and keeps its own relationship credential.
|
||||
`POST /api/v1/daemons/enrollment-tokens` (`daemons:enroll`) issues a single-use enrollment token that expires in 10 minutes. No request body is required.
|
||||
|
||||
```bash
|
||||
curl --fail-with-body -sS -X POST \
|
||||
@@ -275,21 +164,17 @@ curl --fail-with-body -sS -X POST \
|
||||
-H "Authorization: Bearer $PASEO_HUB_API_KEY"
|
||||
```
|
||||
|
||||
Direct API consumers can pass the returned token to the daemon enrollment protocol. The Paseo CLI intentionally does not accept raw enrollment tokens; `connect` owns the authenticated single-flow exchange.
|
||||
Response (`201`):
|
||||
|
||||
An enrollment token cannot be reused. Revoking the API key immediately rejects
|
||||
future API requests and expires any unconsumed enrollment tokens that key
|
||||
issued. A race between revocation and issuance is resolved by Hub before a new
|
||||
token is stored.
|
||||
```json
|
||||
{
|
||||
"token": "short-lived-enrollment-token",
|
||||
"expiresAt": "2026-09-09T12:10:00.000Z"
|
||||
}
|
||||
```
|
||||
|
||||
## Keys, scopes, and audit information
|
||||
`paseo hub connect [origin]` calls this endpoint automatically and exchanges the token for the daemon's own long-lived relationship credential. Revoking the API key immediately blocks new API calls and expires any unconsumed enrollment tokens it issued.
|
||||
|
||||
The complete API-key secret is shown once, immediately after creation. Store it
|
||||
in your deployment's secret manager; Hub does not show it again. The dashboard
|
||||
retains only the key's prefix and shows its selected scopes, creation time,
|
||||
last-used time, and status.
|
||||
## Keys and audit trails
|
||||
|
||||
Hub updates `last used` after a key successfully authenticates for a scoped API
|
||||
operation. API operations retain the key attribution in Hub's audit evidence,
|
||||
so configuration revisions, manual dispatches, and daemon enrollment tokens
|
||||
can be traced to the organization key that created them.
|
||||
Hub displays an API key secret once at creation time. The dashboard keeps only the key prefix, scopes, creation time, last-used timestamp, and revocation status. Hub records key attribution on trigger installations, webhook rotations, manual dispatches, and daemon enrollment tokens.
|
||||
|
||||
+62
-157
@@ -1,48 +1,44 @@
|
||||
---
|
||||
title: Hub 公开 API
|
||||
description: 使用组织凭据安装触发器、管理旧版配置、发起运行和注册 daemon。
|
||||
description: 使用组织凭据校验和安装触发器、轮换 webhook 密钥、派发手动运行并注册 daemon。
|
||||
nav: 公开 API
|
||||
---
|
||||
|
||||
# Hub 公开 API {#hub-public-api}
|
||||
|
||||
Hub 公开 API 让自动化可以操作一个组织中的触发器、项目和 daemon。下文用 `PASEO_HUB_URL` 表示 Hub 的地址,例如 `https://hub.example.com`。
|
||||
Hub 公开 API 让脚本和 CI 流水线能够管理一个组织的触发器、webhook 密钥、手动运行和 daemon 注册。请将 `PASEO_HUB_URL` 设为你的 Hub 地址,例如 `https://hub.example.com`。
|
||||
|
||||
## API 参考 {#api-reference}
|
||||
|
||||
- [交互式 API 参考](https://hub.paseo.sh/api/reference)
|
||||
- [OpenAPI 3.1 文档](https://hub.paseo.sh/api/openapi.json)
|
||||
|
||||
这些是托管版 Paseo Hub 的标准参考端点。自托管的 Hub 在它自己的地址上提供相同的 `/api/reference` 和 `/api/openapi.json` 路径。
|
||||
自托管 Hub 在自己的地址下提供相同的 `/api/reference` 和 `/api/openapi.json` 端点。
|
||||
|
||||
## 身份验证 {#authentication}
|
||||
## 认证 {#authentication}
|
||||
|
||||
运行 `paseo hub login [origin]` 获得交互式的 CLI 访问权限。在浏览器中批准后,Paseo 会在 `PASEO_HOME` 下为这个确切的地址保存一个持久、可撤销的组织凭据。未显式指定地址时,CLI 依次使用 `PASEO_HUB_URL`、当前保存的登录,然后是 `https://hub.paseo.sh`。
|
||||
交互式 CLI 访问请运行 `paseo hub login [origin]`。Paseo 会在 `PASEO_HOME` 下为该精确地址保存一个可撤销的组织凭据。
|
||||
|
||||
用于自动化时,请在 Hub 控制台的 **API keys** 下创建组织 API 密钥。两种凭据都是 bearer token:
|
||||
自动化场景请在 Hub 的 **Settings → API keys** 下创建组织 API 密钥。两种凭据都作为 Bearer 令牌发送:
|
||||
|
||||
```http
|
||||
Authorization: Bearer paseo_pk_...
|
||||
Content-Type: application/json
|
||||
```
|
||||
|
||||
API 密钥的作用域是组织。拥有该密钥的组织决定了它能访问哪些项目和 daemon 注册令牌;这些请求中不需要添加组织 ID。通过该密钥无法访问其他组织的项目 slug。
|
||||
API 密钥限定在单个组织内,并绑定所选的一个或多个权限范围:
|
||||
|
||||
每个密钥有一个或多个可选的权限范围:
|
||||
| 权限范围 | 允许的操作 |
|
||||
| ------------------------ | ----------------------------------------------- |
|
||||
| `configuration:validate` | 列出触发器、列出可解析资源并校验触发器。 |
|
||||
| `configuration:install` | 安装触发器,以及创建或轮换触发器 webhook 密钥。 |
|
||||
| `runs:dispatch` | 派发已配置的 `manual.run` 触发器。 |
|
||||
| `daemons:enroll` | 签发短期 daemon 注册令牌。 |
|
||||
| `projects:read` | 列出组织中的项目。 |
|
||||
|
||||
| 权限范围 | 操作 |
|
||||
| ------------------------ | --------------------------------------- |
|
||||
| `projects:read` | 列出组织中的活动项目。 |
|
||||
| `configuration:validate` | 校验触发器或旧版配置,不改变 Hub 状态。 |
|
||||
| `configuration:install` | 安装触发器,或替换旧版项目的配置。 |
|
||||
| `runs:dispatch` | 为项目发起一个已配置的手动触发器。 |
|
||||
| `daemons:enroll` | 签发一个短期有效的 daemon 注册令牌。 |
|
||||
API 密钥不能用于登录控制台,也不能管理集成或组织成员。
|
||||
|
||||
API 密钥不授予控制台访问权限。它们不能管理连接、项目或组织成员。
|
||||
|
||||
CLI 凭据拥有当前 CLI 操作所需的权限范围,并且可以独立于 daemon 关系单独撤销。`paseo hub logout` 会删除当前的本地 CLI 凭据;它不会撤销或断开 daemon 身份。
|
||||
|
||||
API 失败时使用 RFC 9457 问题详情格式。缺失、无效或已撤销的凭据返回 `401`,类型为 `application/problem+json`:
|
||||
API 错误返回 RFC 9457 `application/problem+json` 格式并带有 `X-Request-ID` 响应头。缺少、无效或已撤销的凭据返回 `401` 和 `WWW-Authenticate: Bearer`:
|
||||
|
||||
```json
|
||||
{
|
||||
@@ -55,23 +51,23 @@ API 失败时使用 RFC 9457 问题详情格式。缺失、无效或已撤销的
|
||||
}
|
||||
```
|
||||
|
||||
有效但缺少端点所需权限范围的密钥会以相同格式返回 `403`。
|
||||
有效凭据但缺少所需权限范围时,以相同格式返回 `403`。
|
||||
|
||||
## 触发器校验和安装 {#trigger-validation-and-installation}
|
||||
## 触发器列表、校验与安装 {#trigger-list-validation-and-installation}
|
||||
|
||||
`paseo hub deploy --dry-run` 通过 `POST /api/v1/triggers/validate` 校验每个 `.paseo/triggers/*.yml` 文件。`paseo hub deploy` 先校验所有文件,再通过 `POST /api/v1/triggers/install` 逐个安装。
|
||||
- `GET /api/v1/triggers`(`configuration:validate`)列出组织的活动触发器及其可部署的 YAML 文档。
|
||||
- `POST /api/v1/triggers/validate`(`configuration:validate`)校验单个自包含触发器 YAML 文档,不修改 Hub 状态。
|
||||
- `POST /api/v1/triggers/install`(`configuration:install`)校验并安装单个触发器,按其 YAML `name` 创建或更新。
|
||||
|
||||
两个端点都接受一份自包含的文档:
|
||||
`POST /api/v1/triggers/validate` 和 `POST /api/v1/triggers/install` 接受相同的 JSON 请求体:
|
||||
|
||||
```json
|
||||
{
|
||||
"yaml": "name: manual-task\nenabled: true\non:\n manual.run: {}\nrun:\n target: { daemon: my-macbook, cwd: /workspace }\n agent: { provider: codex, model: gpt-5, mode: full-access }\n prompt: Complete the task and call hub.finish_execution.\n max_runtime: 1h\n idle_timeout: 5m\n"
|
||||
"yaml": "name: manual-task\nenabled: true\non:\n manual.run: {}\nrun:\n target: { daemon: my-macbook, cwd: /workspace }\n agent: { provider: codex, mode: full-access }\n prompt: |\n Complete the task and call finish_execution.\n ${{ paseo.prompt }}\n max_runtime: 1h\n idle_timeout: 5m\n"
|
||||
}
|
||||
```
|
||||
|
||||
请使用你的组织中可用的 daemon slug 和 Agent 运行时。两个操作都会请指定的 daemon 检查 Agent,因此它必须已连接并持有 `hub.execute`;它无法运行的 Agent 会作为字段问题报告,而不是在第一次运行时失败。见[保存时会对照 daemon 检查 Agent](/docs/hub/triggers#saving-checks-the-agent-against-the-daemon)。校验需要 `configuration:validate`,并返回 `200` 和 `{ "name": "manual-task", "valid": true }`。
|
||||
|
||||
安装需要 `configuration:install`。它按 YAML 中的 `name` 创建或更新组织的触发器,并返回 `201`:
|
||||
两个端点都会请目标 daemon 校验 `run.agent`,因此该 daemon 必须在线且持有 `hub.execute`。校验成功返回 `200` 和 `{ "name": "manual-task", "valid": true }`。安装成功返回 `201`:
|
||||
|
||||
```json
|
||||
{
|
||||
@@ -83,141 +79,64 @@ API 失败时使用 RFC 9457 问题详情格式。缺失、无效或已撤销的
|
||||
}
|
||||
```
|
||||
|
||||
无效的 YAML 或未知的组织资源会返回 `422` 及字段问题。每次安装都是独立的请求;后面的失败不会撤销前面已成功的安装。见[从 CLI 部署](/docs/hub/configuration#deploy-from-the-cli)。
|
||||
无效 YAML、未知集成或被拒绝的 Agent 设置会返回 `422` 及字段级错误详情。`paseo hub deploy --dry-run` 和 `paseo hub deploy` 会针对 `.paseo/triggers/*.yml` 调用这两个端点。
|
||||
|
||||
## 项目列表 {#project-list}
|
||||
## Webhook 密钥 {#webhook-secrets}
|
||||
|
||||
`GET /api/v1/projects` 返回 bearer 凭据所属组织中的活动项目。`paseo hub projects` 以表格形式显示项目。使用 `--json` 时,它返回 `{ "origin": "...", "projects": [...] }`,因此即使结果为空,也会记录解析出的 Hub。
|
||||
|
||||
```json
|
||||
{
|
||||
"projects": [
|
||||
{
|
||||
"id": "00000000-0000-4000-8000-000000000000",
|
||||
"slug": "my-project",
|
||||
"name": "My project"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
## 旧版配置校验 {#legacy-configuration-validation}
|
||||
|
||||
`POST /api/v1/configurations/validate` 接受与配置安装相同的 `projectSlug` 和完整的 `files` 文件包。它执行相同的编译和资源解析,但不会记录修订,也不会改变当前生效的配置。
|
||||
|
||||
成功时,Hub 返回 `200`:
|
||||
|
||||
```json
|
||||
{
|
||||
"projectSlug": "my-project",
|
||||
"valid": true
|
||||
}
|
||||
```
|
||||
|
||||
`paseo hub deploy --project <slug> --dry-run` 会用与实际部署完全相同的、在本地解析出的请求体调用此端点。
|
||||
|
||||
## 旧版配置安装 {#legacy-configuration-install}
|
||||
|
||||
`configuration:install` 会校验提供的标准文件包,原样保存编写的文件,并激活一个新的修订。
|
||||
|
||||
```http
|
||||
POST /api/v1/configurations/install
|
||||
```
|
||||
`POST /api/v1/triggers/webhook-secret`(`configuration:install`)为已保存的 `webhook.received` 触发器创建或轮换 Bearer 密钥。
|
||||
|
||||
请求体:
|
||||
|
||||
```json
|
||||
{
|
||||
"projectSlug": "my-project",
|
||||
"files": [
|
||||
{
|
||||
"path": ".paseo/hub.yml",
|
||||
"content": "environments:\n production:\n kind: daemon\n daemon: build-server\n cwd: /workspace\nagents:\n codex:\n provider: codex\n"
|
||||
},
|
||||
{
|
||||
"path": ".paseo/workflows/deploy.yml",
|
||||
"content": "name: deploy\non: manual.run\nmax_runtime: 2h\nfilters:\n from_users: [automation]\nsteps:\n - id: deploy\n environment: production\n max_runtime: 90m\n idle_timeout: 10m\n agent: codex\n prompt:\n - include: partials/safety.md\n"
|
||||
},
|
||||
{
|
||||
"path": ".paseo/workflows/partials/safety.md",
|
||||
"content": "Follow the safety checklist."
|
||||
}
|
||||
]
|
||||
"triggerId": "00000000-0000-4000-8000-000000000001"
|
||||
}
|
||||
```
|
||||
|
||||
`projectSlug` 选择目标项目;bearer 凭据确定组织。`files` 包含 `.paseo/hub.yml`、每个直接位于目录下的 workflow `.yml`,以及每个被引用的 workflow 片段。Hub 会拒绝缺失、多余、重复、不安全或非标准的路径。
|
||||
|
||||
限制:
|
||||
|
||||
- 文件包:最多 100 个文件。
|
||||
- 文件路径:最多 512 个字符。
|
||||
- 文件内容:最多 1,000,000 个字符。
|
||||
- 提示词片段:每个最多 1,000,000 字节,总计最多 5,000,000 字节。
|
||||
|
||||
成功时,Hub 返回 `201`:
|
||||
成功后 Hub 返回 `200` 及 `Cache-Control: no-store`:
|
||||
|
||||
```json
|
||||
{
|
||||
"projectSlug": "my-project",
|
||||
"versionId": "00000000-0000-4000-8000-000000000000",
|
||||
"version": 3,
|
||||
"active": true
|
||||
"path": "/webhooks/wh_0123456789abcdef0123456789abcdef",
|
||||
"secret": "whsec_..."
|
||||
}
|
||||
```
|
||||
|
||||
常见的响应有:请求体缺失或格式错误时返回 `400`,密钥所属组织中的项目不活动或未知时返回 `404`,YAML 无效或配置无效时返回 `422`。校验的问题详情包含字段问题。安装失败不会替换当前生效的修订。
|
||||
每次调用都会立即替换旧密钥,并且新密钥仅显示一次。向 `/webhooks/wh_...` 发送投递的方式见[入站 webhook](/docs/hub/triggers/webhooks)。
|
||||
|
||||
示例:
|
||||
## 手动运行派发 {#manual-run-dispatch}
|
||||
|
||||
```bash
|
||||
curl --fail-with-body -sS -X POST "$PASEO_HUB_URL/api/v1/configurations/install" \
|
||||
-H "Authorization: Bearer $PASEO_HUB_API_KEY" \
|
||||
-H "Content-Type: application/json" \
|
||||
--data @configuration-install.json
|
||||
```
|
||||
|
||||
`paseo hub deploy -p <project>` 会用在本地发现的文件包调用这个旧版端点。在没有参数和环境变量凭据时,该命令使用与地址完全匹配的已保存登录。见[从 CLI 部署](/docs/hub/configuration#deploy-from-the-cli)。
|
||||
|
||||
## 发起手动运行 {#manual-run-dispatch}
|
||||
|
||||
`runs:dispatch` 为项目发起一个已配置的 `manual.run` 触发器。该触发器必须存在于当前生效的配置中,并且 `actor` 必须列在该触发器的 `filters.from_users` 白名单中。
|
||||
|
||||
```http
|
||||
POST /api/v1/manual-runs
|
||||
```
|
||||
|
||||
请求体:
|
||||
`POST /api/v1/manual-runs`(`runs:dispatch`)启动一个已配置的 `manual.run` 触发器。`actor` 必须匹配该触发器的 `filters.from_users` 白名单(省略时为 `*`)。
|
||||
|
||||
```json
|
||||
{
|
||||
"projectSlug": "my-project",
|
||||
"expectedVersionId": "00000000-0000-4000-8000-000000000000",
|
||||
"trigger": "deploy",
|
||||
"projectSlug": "default",
|
||||
"trigger": "manual-task",
|
||||
"actor": "automation",
|
||||
"deliveryKey": "deploy-2026-08-04-001",
|
||||
"deliveryKey": "manual-task-2026-09-09-001",
|
||||
"input": "repo=project investigate the failed sync"
|
||||
}
|
||||
```
|
||||
|
||||
- `expectedVersionId` 是可选的。提供时,如果该修订已不再生效,Hub 会拒绝这次发起。
|
||||
- `input` 与 Provider 消息使用的字符串相同:开头的 `key=value` 标记会被解析为声明的输入,其余部分成为 `${{ paseo.prompt }}`。
|
||||
- `deliveryKey` 对每次发起都应唯一且稳定。Hub 用它进行持久化去重,但不保证恰好发起一次,也不保证重放之前的响应。
|
||||
- `deliveryKey` 提供限定在组织和项目内的持久去重。
|
||||
- `input` 接受以声明的 `inputs` 对应的 `key=value` 头部开头,后接提示词文本。
|
||||
|
||||
成功时,Hub 返回 `200`:
|
||||
派发独立触发器时,请省略 `expectedVersionId`。如果传入安装触发器时返回的 `revisionId`,即使触发器没有变化,Hub 也会返回 HTTP `409`(`configuration_changed`)。
|
||||
|
||||
对于旧版项目配置包,`expectedVersionId` 为可选项。将它设为当前生效的项目配置修订 ID,配置变更后 Hub 就会拒绝派发。
|
||||
|
||||
成功后 Hub 返回 `200`:
|
||||
|
||||
```json
|
||||
{
|
||||
"deliveryKey": "deploy-2026-08-04-001",
|
||||
"deliveryKey": "manual-task-2026-09-09-001",
|
||||
"providerEventReceiptId": "00000000-0000-4000-8000-000000000000",
|
||||
"triggerRunId": "00000000-0000-4000-8000-000000000000",
|
||||
"configuredTriggerName": "deploy",
|
||||
"configuredTriggerName": "manual-task",
|
||||
"workflowStatus": "running"
|
||||
}
|
||||
```
|
||||
|
||||
常见的响应有:请求无效时返回 `400`,触发器不允许该 actor 时返回 `403`,项目、配置或触发器未知时返回 `404`,daemon 离线、预期的配置已不是当前配置或发起冲突时返回 `409`。它们都使用上面的问题详情格式。
|
||||
|
||||
示例:
|
||||
|
||||
```bash
|
||||
@@ -225,36 +144,17 @@ curl --fail-with-body -sS -X POST "$PASEO_HUB_URL/api/v1/manual-runs" \
|
||||
-H "Authorization: Bearer $PASEO_HUB_API_KEY" \
|
||||
-H "Content-Type: application/json" \
|
||||
--data '{
|
||||
"projectSlug": "my-project",
|
||||
"trigger": "deploy",
|
||||
"projectSlug": "default",
|
||||
"trigger": "manual-task",
|
||||
"actor": "automation",
|
||||
"deliveryKey": "deploy-2026-08-04-001",
|
||||
"input": "repo=project investigate the failed sync"
|
||||
"deliveryKey": "manual-task-2026-09-09-001",
|
||||
"input": "investigate the failed sync"
|
||||
}'
|
||||
```
|
||||
|
||||
输入类型、默认值、可选值、被拒绝的输入以及手动调用示例,见 [Hub workflow](/docs/hub/workflows)。
|
||||
## Daemon 注册 {#daemon-enrollment}
|
||||
|
||||
## 注册 daemon {#daemon-enrollment}
|
||||
|
||||
`daemons:enroll` 为 daemon 签发一个短期有效的注册令牌。这个令牌由 API 密钥签发;它不是 daemon 的长期凭据,也不得当作长期凭据使用。
|
||||
|
||||
```http
|
||||
POST /api/v1/daemons/enrollment-tokens
|
||||
```
|
||||
|
||||
不需要请求体。成功时,Hub 返回 `201`:
|
||||
|
||||
```json
|
||||
{
|
||||
"token": "short-lived-enrollment-token",
|
||||
"expiresAt": "2026-08-04T12:10:00.000Z"
|
||||
}
|
||||
```
|
||||
|
||||
令牌在 10 分钟后过期,并在 daemon 注册时被消耗。
|
||||
|
||||
`paseo hub connect [origin]` 会使用 `--api-key`、`PASEO_HUB_API_KEY` 或匹配的已保存登录执行此请求,然后把这个一次性令牌传给 daemon 的注册操作。daemon 会生成并保存它自己的关系凭据。
|
||||
`POST /api/v1/daemons/enrollment-tokens`(`daemons:enroll`)签发一个 10 分钟后过期的一次性注册令牌。不需要请求体。
|
||||
|
||||
```bash
|
||||
curl --fail-with-body -sS -X POST \
|
||||
@@ -262,12 +162,17 @@ curl --fail-with-body -sS -X POST \
|
||||
-H "Authorization: Bearer $PASEO_HUB_API_KEY"
|
||||
```
|
||||
|
||||
直接使用 API 的调用方可以把返回的令牌传给 daemon 注册协议。Paseo CLI 有意不接受原始注册令牌;`connect` 负责完整的、经过身份验证的单一交换流程。
|
||||
响应(`201`):
|
||||
|
||||
注册令牌不能重复使用。撤销 API 密钥会立即拒绝之后的 API 请求,并使该密钥签发的所有未消耗的注册令牌过期。撤销与签发之间的竞争会在新令牌被保存之前由 Hub 解决。
|
||||
```json
|
||||
{
|
||||
"token": "short-lived-enrollment-token",
|
||||
"expiresAt": "2026-09-09T12:10:00.000Z"
|
||||
}
|
||||
```
|
||||
|
||||
## 密钥、权限范围和审计信息 {#keys-scopes-and-audit-information}
|
||||
`paseo hub connect [origin]` 会自动调用此端点,并用令牌换取 daemon 自己的长期关系凭据。撤销 API 密钥会立即阻止新的 API 调用,并使该密钥签发的未消耗注册令牌失效。
|
||||
|
||||
完整的 API 密钥只在创建后立即显示一次。请把它保存到你的部署所用的密钥管理器中;Hub 不会再次显示它。控制台只保留密钥的前缀,并显示它所选的权限范围、创建时间、最后使用时间和状态。
|
||||
## 密钥与审计记录 {#keys-and-audit-trails}
|
||||
|
||||
密钥在一次有权限范围的 API 操作中成功通过身份验证后,Hub 会更新 `last used`。API 操作会在 Hub 的审计记录中保留密钥归属,因此配置修订、手动发起和 daemon 注册令牌都可以追溯到创建它们的组织密钥。
|
||||
Hub 仅在创建时显示一次 API 密钥内容。控制台只保留密钥前缀、权限范围、创建时间、最近使用时间和撤销状态。Hub 会在触发器安装、webhook 轮换、手动派发和 daemon 注册令牌中保留密钥归属记录。
|
||||
|
||||
+41
-42
@@ -1,6 +1,6 @@
|
||||
---
|
||||
title: How Hub works
|
||||
description: How a provider event reaches a workflow and a Paseo daemon.
|
||||
description: How events, schedules, and webhooks match a trigger and start an agent on your Paseo daemon.
|
||||
nav: How it works
|
||||
order: 62
|
||||
category: Hub
|
||||
@@ -8,61 +8,60 @@ category: Hub
|
||||
|
||||
# How Hub works
|
||||
|
||||
Hub connects the places where requests arrive to the machines where your agents run.
|
||||
Hub connects external events, schedules, and webhooks to coding agents running on your Paseo daemons.
|
||||
|
||||
```text
|
||||
GitHub / Slack / Discord / manual request
|
||||
↓
|
||||
Hub
|
||||
matches a project trigger
|
||||
↓
|
||||
workflow
|
||||
runs ordered agent steps
|
||||
↓
|
||||
Paseo daemon
|
||||
starts the agent
|
||||
GitHub / Linear / Slack / Discord / Schedule / Webhook
|
||||
│
|
||||
▼
|
||||
Hub
|
||||
verifies input and matches triggers
|
||||
│
|
||||
▼
|
||||
Paseo daemon
|
||||
starts or continues an agent
|
||||
```
|
||||
|
||||
## The pieces
|
||||
## Core concepts
|
||||
|
||||
- A **connection** lets Hub receive events from GitHub, Slack, or Discord.
|
||||
- A **daemon** is a registered machine running the Paseo daemon.
|
||||
- A **project** groups one configuration with the connections and daemons it uses.
|
||||
- An **environment** names where a workflow step runs: a daemon, its working directory, and an optional worktree.
|
||||
- A **trigger** says which provider event can start a workflow and which events are allowed through.
|
||||
- A **workflow** is the ordered set of steps that runs after a trigger matches.
|
||||
- A **step** starts one agent execution, with its own prompt, agent selection, credentials, reply capabilities, and limits.
|
||||
|
||||
The configuration lives in `.paseo/hub.yml` plus convention-discovered `.paseo/workflows/*.yml` files when the project uses a GitHub source. A project has one active configuration revision at a time.
|
||||
- An **app** is the provider application configured for a self-hosted Hub under **Apps** (GitHub App, Linear OAuth app, Slack app, or Discord app). Hosted Hub operates its own apps.
|
||||
- An **integration** is a workspace, account, or server connected to your Hub organization under **Integrations**. Each connected account has a unique connection slug, such as `acme-github` or `acme-slack`, that triggers reference.
|
||||
- A **daemon** is a machine running the Paseo daemon and enrolled in your Hub organization under **Daemons**. Daemons accept agent launches only after you grant `hub.execute` from that machine.
|
||||
- A **trigger** is one self-contained rule that maps an event, schedule, or webhook to a target daemon, working directory, agent configuration, prompt, and optional tools or outputs.
|
||||
- [**Activity**](/docs/hub/activity) shows recent trigger runs and their status.
|
||||
|
||||
## From event to agent
|
||||
|
||||
1. A provider sends an event to Hub. GitHub and Slack use webhooks; Discord uses its gateway connection; manual runs use the Hub API.
|
||||
2. Hub verifies the provider event and identifies its project resource, such as a repository, workspace, or guild.
|
||||
3. Hub evaluates triggers and their filters, including the required `from_users` allowlist.
|
||||
4. A matching trigger creates a workflow run from the active configuration revision.
|
||||
5. The workflow evaluates its next step. A false `if` condition skips that step; a true condition starts it on the configured daemon.
|
||||
6. The daemon starts the agent and Hub records its replies, structured output, status, and completion.
|
||||
7. The next step sees the completed step's output. When no steps remain, the workflow run is complete.
|
||||
1. An event arrives via HTTPS webhooks (GitHub, Linear, Slack Webhooks, or inbound webhooks), an outbound connection (Slack Socket Mode or Discord gateway), or Hub's schedule clock.
|
||||
2. Hub verifies the sender or signature and looks up matching enabled triggers.
|
||||
3. For external provider events, Hub evaluates the trigger's connection, resource filters, and sender allowlist (`from_users`).
|
||||
4. For each matching trigger, Hub creates a run and sends the launch intent to the target daemon over the same RPC protocol used by the Paseo app and CLI.
|
||||
5. By default, events on the same Slack thread, Discord thread, GitHub issue or pull request, or Linear issue continue the existing agent session rather than starting a new one.
|
||||
6. The agent runs on your machine with the Hub MCP server attached. It calls `reply` to answer the conversation, calls any granted integration tools, and calls `finish_execution` when complete.
|
||||
|
||||
Complete configurations are in [Workflows](/docs/hub/workflows).
|
||||
## Authoring and validation
|
||||
|
||||
## Activation
|
||||
You can create and edit triggers in two ways:
|
||||
|
||||
When Hub syncs the bundle, it validates every source file and resolves its references:
|
||||
- In the Hub dashboard under **Triggers**, using the visual form or the YAML editor.
|
||||
- As `.paseo/triggers/*.yml` files in your repository, deployed with `paseo hub deploy`.
|
||||
|
||||
- `filters.repo`, `filters.workspace`, and `filters.guild` must name resources available through the organization's connections.
|
||||
- `environment.daemon` must match a registered daemon's friendly slug.
|
||||
- Step ids, expressions, input filters, output schemas, and durations must be valid.
|
||||
- Every finite environment or named-agent result must exist and validate.
|
||||
- Prompt partials must resolve below `.paseo/workflows/partials/` at the exact commit.
|
||||
Both paths use the same YAML schema. When you save or deploy, Hub validates the YAML and looks up the connections for event routing and the target daemon.
|
||||
|
||||
If activation fails, Hub keeps the previous active revision. The Configuration tab shows the failed sync and its validation error; Activity continues to reflect the last active revision.
|
||||
You can save dashboard edits while the daemon is offline if the target and agent settings stay the same. CLI deploys and direct API installs always require a connected target daemon. See [trigger validation](/docs/hub/triggers#saving-checks-the-agent-against-the-daemon).
|
||||
|
||||
Hub resolves `run.github.connection` when it launches the run. If the connection is unavailable or GitHub rejects the token request, the launch fails. See [GitHub access for agents](/docs/hub/github).
|
||||
|
||||
## Open in Paseo links
|
||||
|
||||
When Hub has a public HTTPS origin and a run has a recorded daemon agent, Hub appends an **Open in Paseo** link to conversation replies on GitHub, Linear, Slack, and Discord.
|
||||
|
||||
Clicking the link checks that the visitor is a signed-in member of that Hub organization before offering to open the exact agent in Paseo, view the execution in Hub, or install Paseo. Signed-out visitors and users outside the organization receive no run details.
|
||||
|
||||
Agents with scoped posting tools (`run.tools.slack` or `run.tools.discord`) also receive the same URL in their request context so digests and reports can link back to the run.
|
||||
|
||||
## Security boundaries
|
||||
|
||||
Triggers require a non-empty `from_users` allowlist for externally sourced events. Protect the configuration repository because anyone who can change the active configuration can choose which connections, daemons, and agent capabilities a project uses.
|
||||
Hub verifies inbound requests, enforces sender allowlists, mints scoped GitHub tokens, and authorizes every Hub MCP tool call on the server. It does not sandbox the coding agent process on your machine.
|
||||
|
||||
These controls do not sandbox the agent or make input safe. See [Hub security](/docs/hub/security) for the host boundary, provider-native policy, and defense-in-depth guidance.
|
||||
|
||||
GitHub credentials are never implied by the trigger. A step holds GitHub authority only when it declares a [`github` block](/docs/hub/github), whatever started the run.
|
||||
Protect access to your Hub organization and any repository that deploys `.paseo/triggers/*.yml`. Read [Hub security](/docs/hub/security) before widening allowlists or granting repository write permissions.
|
||||
|
||||
@@ -1,66 +1,65 @@
|
||||
---
|
||||
title: Hub 工作原理
|
||||
description: Provider 事件如何到达 workflow 和 Paseo daemon。
|
||||
title: Hub 的工作原理
|
||||
description: 事件、定时任务和 webhook 如何匹配触发器,并在你的 Paseo daemon 上启动 Agent。
|
||||
nav: 工作原理
|
||||
---
|
||||
|
||||
# Hub 工作原理 {#how-hub-works}
|
||||
# Hub 的工作原理 {#how-hub-works}
|
||||
|
||||
Hub 把请求到达的地方与运行 Agent 的机器连接起来。
|
||||
Hub 将外部事件、定时任务和 webhook 连接到在你 Paseo daemon 上运行的编程 Agent。
|
||||
|
||||
```text
|
||||
GitHub / Slack / Discord / manual request
|
||||
↓
|
||||
Hub
|
||||
matches a project trigger
|
||||
↓
|
||||
workflow
|
||||
runs ordered agent steps
|
||||
↓
|
||||
Paseo daemon
|
||||
starts the agent
|
||||
GitHub / Linear / Slack / Discord / Schedule / Webhook
|
||||
│
|
||||
▼
|
||||
Hub
|
||||
verifies input and matches triggers
|
||||
│
|
||||
▼
|
||||
Paseo daemon
|
||||
starts or continues an agent
|
||||
```
|
||||
|
||||
## 组成部分 {#the-pieces}
|
||||
## 核心概念 {#core-concepts}
|
||||
|
||||
- **连接**让 Hub 接收来自 GitHub、Slack 或 Discord 的事件。
|
||||
- **daemon** 是一台运行 Paseo daemon 的已注册机器。
|
||||
- **项目**把一份配置与它使用的连接和 daemon 组织在一起。
|
||||
- **环境**指定 workflow step 在哪里运行:一个 daemon、它的工作目录,以及可选的 worktree。
|
||||
- **触发器**说明哪个 Provider 事件可以启动 workflow,以及允许哪些事件通过。
|
||||
- **workflow** 是触发器匹配后运行的一组有序 step。
|
||||
- **step** 启动一次 Agent 执行,有自己的提示词、Agent 选择、凭据、回复能力和限制。
|
||||
|
||||
当项目使用 GitHub 来源时,配置位于 `.paseo/hub.yml` 以及按约定发现的 `.paseo/workflows/*.yml` 文件中。一个项目同一时间只有一个生效的配置版本。
|
||||
- **App** 是在自托管 Hub 的 **Apps** 下配置的 Provider 应用(GitHub App、Linear OAuth 应用、Slack 应用或 Discord 应用)。托管 Hub 运行自己的应用。
|
||||
- **Integration** 是在 **Integrations** 下连接到你 Hub 组织的工作区、账号或服务器。每个已连接的账号都有唯一的连接 slug(例如 `acme-github` 或 `acme-slack`),供触发器引用。
|
||||
- **Daemon** 是运行 Paseo daemon 并注册到你 Hub 组织 **Daemons** 下的机器。只有在机器上授予 `hub.execute` 后,daemon 才会接受 Agent 启动请求。
|
||||
- **Trigger** 是一条自包含规则,将事件、定时任务或 webhook 映射到目标 daemon、工作目录、Agent 配置、提示词,以及可选的工具或输出。
|
||||
- [**Activity**](/docs/hub/activity) 显示最近的触发器运行记录和状态。
|
||||
|
||||
## 从事件到 Agent {#from-event-to-agent}
|
||||
|
||||
1. Provider 向 Hub 发送事件。GitHub 和 Slack 使用 webhook;Discord 使用它的 gateway 连接;手动运行使用 Hub API。
|
||||
2. Hub 验证 Provider 事件,并识别它对应的项目资源,例如仓库、工作区或服务器。
|
||||
3. Hub 评估触发器及其过滤器,包括必填的 `from_users` 允许列表。
|
||||
4. 匹配的触发器根据当前生效的配置版本创建一次 workflow 运行。
|
||||
5. workflow 评估下一个 step。`if` 条件为假时跳过该 step;为真时在配置的 daemon 上启动它。
|
||||
6. daemon 启动 Agent,Hub 记录它的回复、结构化输出、状态和完成情况。
|
||||
7. 下一个 step 可以看到已完成 step 的输出。没有剩余 step 时,workflow 运行完成。
|
||||
1. 事件通过 HTTPS webhook(GitHub、Linear、Slack Webhooks 或入站 webhook)、出站连接(Slack Socket Mode 或 Discord gateway)或 Hub 定时时钟到达。
|
||||
2. Hub 验证发送者或签名,并查找匹配的已启用触发器。
|
||||
3. 对于外部 Provider 事件,Hub 会评估触发器的连接、资源过滤条件和发送者白名单(`from_users`)。
|
||||
4. 对每个匹配的触发器,Hub 创建一次运行,并通过 Paseo 应用和 CLI 使用的同一套 RPC 协议向目标 daemon 发送启动意图。
|
||||
5. 默认情况下,同一个 Slack 讨论串、Discord 讨论串、GitHub issue 或 Pull Request,以及同一个 Linear issue 上的事件会继续现有 Agent 会话,而不是启动新的 Agent。
|
||||
6. Agent 在你的机器上运行并挂载 Hub MCP 服务器。它调用 `reply` 回复对话,调用已授予的集成工具,并在完成后调用 `finish_execution`。
|
||||
|
||||
完整的配置示例见 [Workflow](/docs/hub/workflows)。
|
||||
## 编写与校验 {#authoring-and-validation}
|
||||
|
||||
## 激活 {#activation}
|
||||
你可以通过两种方式创建和编辑触发器:
|
||||
|
||||
Hub 同步配置包时,会校验每个源文件并解析其中的引用:
|
||||
- 在 Hub 控制台的 **Triggers** 页面使用可视化表单或 YAML 编辑器。
|
||||
- 在仓库中保存 `.paseo/triggers/*.yml` 文件,并通过 `paseo hub deploy` 部署。
|
||||
|
||||
- `filters.repo`、`filters.workspace` 和 `filters.guild` 必须指向通过组织的连接可以访问的资源。
|
||||
- `environment.daemon` 必须匹配一个已注册 daemon 的友好 slug。
|
||||
- step id、表达式、输入过滤器、输出 schema 和时长必须有效。
|
||||
- 每个有限的环境或命名 Agent 结果都必须存在并通过校验。
|
||||
- 提示词片段必须能在该提交中 `.paseo/workflows/partials/` 下解析到。
|
||||
两种方式使用相同的 YAML 结构。保存或部署触发器时,Hub 会校验 YAML,并查找用于事件路由的连接和目标 daemon。
|
||||
|
||||
如果激活失败,Hub 会保留之前生效的版本。Configuration 标签页会显示失败的同步及其校验错误;Activity 继续反映上一个生效的版本。
|
||||
只要目标和 Agent 设置不变,daemon 离线时也能在控制台保存修改。通过 CLI 部署或直接通过 API 安装时,目标 daemon 必须连接到 Hub。请参阅[触发器校验](/docs/hub/triggers#saving-checks-the-agent-against-the-daemon)。
|
||||
|
||||
Hub 在启动运行时解析 `run.github.connection`。如果连接不可用或 GitHub 拒绝签发令牌,运行就会启动失败。请参阅 [Agent 的 GitHub 访问权限](/docs/hub/github)。
|
||||
|
||||
## Open in Paseo 链接 {#open-in-paseo-links}
|
||||
|
||||
当 Hub 配置了公开 HTTPS 地址且运行记录了 daemon Agent 时,Hub 会在 GitHub、Linear、Slack 和 Discord 的对话回复中附带 **Open in Paseo** 链接。
|
||||
|
||||
点击链接时,Hub 会先验证访问者是否为该 Hub 组织的已登录成员,然后提供在 Paseo 中打开对应 Agent、在 Hub 中查看运行记录或安装 Paseo 的入口。未登录的访客和非组织成员不会看到任何运行数据。
|
||||
|
||||
拥有受控发送工具(`run.tools.slack` 或 `run.tools.discord`)的 Agent 也会在请求上下文中收到同一个 URL,方便摘要和报告主动链接回此次运行。
|
||||
|
||||
## 安全边界 {#security-boundaries}
|
||||
|
||||
对于来自外部的事件,触发器要求 `from_users` 允许列表不能为空。请保护好配置仓库,因为任何能够修改生效配置的人,都可以决定项目使用哪些连接、daemon 和 Agent 能力。
|
||||
Hub 负责验证入站请求、执行发送者白名单、签发受控 GitHub 令牌,并在服务端对每次 Hub MCP 工具调用做鉴权。它不会在你机器上为编程 Agent 进程提供沙箱隔离。
|
||||
|
||||
这些控制措施不会把 Agent 放进沙箱,也不会让输入变得安全。主机边界、Provider 原生策略和纵深防御方面的指导见 [Hub 安全](/docs/hub/security)。
|
||||
|
||||
触发器从不隐含 GitHub 凭据。无论运行由什么启动,只有当 step 声明了 [`github` 块](/docs/hub/github)时,它才拥有 GitHub 权限。
|
||||
请保护你的 Hub 组织访问权限,以及任何用于部署 `.paseo/triggers/*.yml` 的仓库。在扩大白名单或授予仓库写入权限之前,请先阅读 [Hub 安全](/docs/hub/security)。
|
||||
|
||||
@@ -1,283 +0,0 @@
|
||||
---
|
||||
title: Hub configuration reference
|
||||
description: Canonical Hub resource, workflow, agent, expression, and prompt fields.
|
||||
nav: Configuration reference
|
||||
order: 71
|
||||
category: Hub
|
||||
---
|
||||
|
||||
# Hub configuration reference
|
||||
|
||||
Hub accepts YAML in this layout:
|
||||
|
||||
```text
|
||||
.paseo/
|
||||
├── hub.yml
|
||||
└── workflows/
|
||||
├── <workflow>.yml
|
||||
└── partials/
|
||||
└── <partial>.md
|
||||
```
|
||||
|
||||
Only direct `.yml` children of `.paseo/workflows/` are workflows. Each file contains one trigger and its ordered steps. There is no manifest, `includes`, `uses`, reusable step, workflow call, or inheritance.
|
||||
|
||||
## `hub.yml`
|
||||
|
||||
`.paseo/hub.yml` contains named project resources. Names are map keys and are not repeated inside each object.
|
||||
|
||||
```yaml
|
||||
environments:
|
||||
paseo:
|
||||
kind: daemon
|
||||
daemon: laptop
|
||||
cwd: /Users/you/code/paseo
|
||||
hub:
|
||||
kind: daemon
|
||||
daemon: devbox
|
||||
cwd: /workspace/hub
|
||||
|
||||
agents:
|
||||
codex-safe:
|
||||
provider: codex
|
||||
model: gpt-5.5
|
||||
thinkingOptionId: xhigh
|
||||
options:
|
||||
sandbox_workspace_write:
|
||||
writable_roots: [/var/cache/npm]
|
||||
network_access: false
|
||||
claude:
|
||||
provider: claude
|
||||
mode: bypassPermissions
|
||||
```
|
||||
|
||||
The only top-level keys are `environments` and `agents`. A `triggers` key is rejected with a migration error.
|
||||
|
||||
### Environments
|
||||
|
||||
| Field | Required | Notes |
|
||||
| ---------- | ----------- | ------------------------------------------------------------------------------ |
|
||||
| `kind` | yes | `daemon`, `fly`, or `docker`; workflow steps must select a daemon environment. |
|
||||
| `daemon` | daemon only | Registered daemon slug, resolved when the revision activates. |
|
||||
| `cwd` | daemon only | Absolute working directory on the daemon. |
|
||||
| `image` | fly/docker | Image name. |
|
||||
| `worktree` | no | `branch-off`, `checkout-branch`, or `checkout-pr` target. |
|
||||
|
||||
For `worktree`, use `newBranch` and optional `base` with `branch-off`, `branch` with `checkout-branch`, or positive `prNumber` with `checkout-pr`.
|
||||
|
||||
```yaml
|
||||
environments:
|
||||
review:
|
||||
kind: daemon
|
||||
daemon: build-server
|
||||
cwd: /workspace/project
|
||||
worktree:
|
||||
mode: branch-off
|
||||
newBranch: trigger-${{ paseo.execution.id }}
|
||||
base: origin/main
|
||||
```
|
||||
|
||||
`newBranch` is a branch-name string. Embed `${{ paseo.execution.id }}`, which renders the execution's UUID, so every execution branches off `base` on its own branch and keeps it when Hub retries or recovers that execution.
|
||||
|
||||
One execution is one step run, so two steps selecting the same environment get separate branches.
|
||||
|
||||
`${{ paseo.execution.id }}` is the only expression `newBranch` accepts. `paseo.prompt`, `paseo.context`, `paseo.inputs.*`, `values.*`, `steps.<id>.outputs.*`, and provider event fields are unavailable here, and each one fails bundle activation at the authored field, such as `.paseo/hub.yml.environments.review.worktree.newBranch`.
|
||||
|
||||
`${{ paseo.execution.id }}` fails activation the same way anywhere else in a bundle. `branch` and `prNumber` take literal values.
|
||||
|
||||
An environment is a complete named object. A step selects its name; objects are not inherited, merged, or partially overridden.
|
||||
|
||||
### Named agents
|
||||
|
||||
Each agent is one complete provider configuration:
|
||||
|
||||
| Field | Required | Notes |
|
||||
| ------------------ | -------- | ---------------------------------------------------------------------- |
|
||||
| `provider` | yes | Provider ID. Hub runs unattended, so `claude`, `codex`, or `opencode`. |
|
||||
| `model` | no | Provider model ID. |
|
||||
| `mode` | no | Paseo mode ID. |
|
||||
| `thinkingOptionId` | no | Provider thinking option. |
|
||||
| `options` | no | JSON-safe provider-native options, preserving names and nesting. |
|
||||
|
||||
A named selection preserves the complete object, including structured options. Named agents have no parent, patch, or per-step override.
|
||||
|
||||
Hub passes `model`, `mode`, `thinkingOptionId`, and `options` to the Paseo daemon without renaming or flattening provider fields. The selected daemon validates them against its current provider schema when the trigger is saved or deployed, so a value it does not offer is refused then rather than at the first run; Hub does not translate provider-native options. See [Saving checks the agent against the daemon](/docs/hub/triggers#saving-checks-the-agent-against-the-daemon).
|
||||
|
||||
## Workflow files
|
||||
|
||||
`.paseo/workflows/review.yml`:
|
||||
|
||||
```yaml
|
||||
name: review
|
||||
on: manual.run
|
||||
max_runtime: 2h
|
||||
filters:
|
||||
from_users: [automation]
|
||||
inputs:
|
||||
repo:
|
||||
type: string
|
||||
required: true
|
||||
choices: [paseo, hub]
|
||||
steps:
|
||||
- id: inspect
|
||||
environment: ${{ paseo.inputs.repo }}
|
||||
max_runtime: 30m
|
||||
idle_timeout: 5m
|
||||
agent: codex-safe
|
||||
prompt:
|
||||
- text: ${{ paseo.prompt }}
|
||||
```
|
||||
|
||||
| Field | Required | Notes |
|
||||
| ------------- | -------- | --------------------------------------------------------- |
|
||||
| `name` | yes | Workflow name, unique across the bundle. |
|
||||
| `on` | yes | Provider event such as `manual.run` or `discord.mention`. |
|
||||
| `max_runtime` | yes | Hard limit for the complete run, up to 24h. |
|
||||
| `filters` | yes | Provider resource filters and the sender allowlist. |
|
||||
| `inputs` | no | Typed invocation headers. |
|
||||
| `values` | no | Named expressions. |
|
||||
| `steps` | yes | One or more ordered inline steps. |
|
||||
|
||||
### GitHub events and filters
|
||||
|
||||
Use one of these semantic event names for new GitHub workflows:
|
||||
|
||||
| `on` | Matches |
|
||||
| -------------------------------------- | ------------------------------------------------------------------------- |
|
||||
| `github.issue_created` | An `issues` delivery whose action is `opened`. |
|
||||
| `github.pull_request_created` | A `pull_request` delivery whose action is `opened`. |
|
||||
| `github.pull_request_ready_for_review` | A draft pull request is marked ready for review. |
|
||||
| `github.issue_comment_created` | An `issue_comment` delivery whose action is `created`, on an issue. |
|
||||
| `github.pull_request_comment_created` | An `issue_comment` delivery whose action is `created`, on a pull request. |
|
||||
| `github.issue_label_added` | An `issues` delivery whose action is `labeled`. |
|
||||
| `github.pull_request_label_added` | A `pull_request` delivery whose action is `labeled`. |
|
||||
|
||||
Existing configurations may continue to use `github.issues`, `github.issue_comment`, `github.pull_request_review`, `github.pull_request_review_comment`, and `github.push`. These legacy events retain their existing behavior.
|
||||
|
||||
`filters` supports these GitHub fields. `from_users` must be non-empty for every externally sourced workflow. All supplied filters compose with AND.
|
||||
|
||||
| Field | Type | Applies to | Meaning |
|
||||
| ------------ | ----------------------------------- | ------------------------------------------------------------- | ------------------------------------------------------------------------------- |
|
||||
| `from_users` | non-empty list of strings | all GitHub events | GitHub logins allowed to start the workflow. |
|
||||
| `repo` | non-empty string | all GitHub events | Repository in `owner/name` form. |
|
||||
| `connection` | string | all GitHub events | GitHub connection slug. |
|
||||
| `contains` | string | issue, pull-request, and comment events | Substring in the issue or pull-request title plus body, or in the comment body. |
|
||||
| `pattern` | string | issue, pull-request, and comment events | Start of that same text. |
|
||||
| `label` | non-empty string | `github.issue_label_added`, `github.pull_request_label_added` | The label added by the delivery. |
|
||||
| `labels` | non-empty list of non-empty strings | issue, pull-request, and comment events | Every listed label must be currently present on the issue or pull request. |
|
||||
|
||||
`label` and `labels` match GitHub labels case-insensitively. `label` checks the one changed label; `labels` checks the full current label set and requires every entry. For example, `labels: [bug, backend]` requires both `bug` and `backend`.
|
||||
|
||||
Use `label` only with a label-added event. It has no match on other events. Use `labels` to require the item state, including when a comment starts the workflow.
|
||||
|
||||
See [GitHub triggers](/docs/hub/triggers/github) for complete triage, pull-request review, and ready-for-agent workflows.
|
||||
|
||||
### Inputs and values
|
||||
|
||||
Inputs have `type: string | number | boolean`, plus optional `required`, `default`, and `choices`. `required` and `default` cannot be combined. Finite `choices` are required when an input can choose authority such as an environment or named agent.
|
||||
|
||||
Values bind expressions:
|
||||
|
||||
```yaml
|
||||
values:
|
||||
selected_environment: ${{ steps.classify.outputs.environment }}
|
||||
selected_agent: ${{ steps.classify.outputs.agent }}
|
||||
```
|
||||
|
||||
Expressions may read declared `paseo.inputs`, earlier `steps.<id>.outputs`, and `values`. The grammar supports paths, JSON literals, parentheses, `!`, `==`, `!=`, `&&`, `||`, and `??`.
|
||||
|
||||
An environment or dynamic named-agent expression must have a finite set of possible string results at activation. Every result must name a configured resource. Runtime selection never falls back to another environment or agent.
|
||||
|
||||
### Steps
|
||||
|
||||
| Field | Required | Notes |
|
||||
| ----------------- | -------- | -------------------------------------------------------------------------------------------------------------------- |
|
||||
| `id` | yes | Unique within the workflow. |
|
||||
| `environment` | yes | Literal environment name or finite expression resolving to one. |
|
||||
| `max_runtime` | yes | Step hard limit. |
|
||||
| `idle_timeout` | yes | Idle limit no longer than `max_runtime`. |
|
||||
| `startup_timeout` | no | Step startup waiting budget. See [startup timeout](/docs/hub/configuration#startup-timeout) for defaults and limits. |
|
||||
| `agent` | yes | Named agent, finite expression selecting a named agent, or complete static inline agent. |
|
||||
| `prompt` | yes | Ordered `text` and `include` blocks. |
|
||||
| `if` | no | Expression deciding whether the step runs. |
|
||||
| `env` | no | Environment variables from connection values. |
|
||||
| `output.schema` | no | JSON Schema for structured step output. |
|
||||
| `allow_outputs` | no | Provider output capabilities with optional `max` and `required`. |
|
||||
| `auto_archive` | no | Archive the agent after the step ends. |
|
||||
| `github` | no | Explicit GitHub authority for this step. |
|
||||
|
||||
An inline agent is static and complete:
|
||||
|
||||
```yaml
|
||||
agent:
|
||||
provider: codex
|
||||
model: gpt-5.5
|
||||
options:
|
||||
approval_policy: never
|
||||
sandbox_mode: read-only
|
||||
```
|
||||
|
||||
An expression-valued `agent` selects a named agent. Dynamic provider fields inside an inline object are rejected.
|
||||
|
||||
### Prompt semantics
|
||||
|
||||
```yaml
|
||||
prompt:
|
||||
- include: partials/review.md
|
||||
- text: |
|
||||
<user-prompt>
|
||||
${{ paseo.prompt }}
|
||||
</user-prompt>
|
||||
```
|
||||
|
||||
`${{ paseo.prompt }}` is the normalized request after the provider marker and declared leading `key=value` inputs are removed. It is not rewritten or augmented with event context.
|
||||
|
||||
`${{ paseo.context }}` opts that step into provider context materialization and renders the result as JSON in the prompt. It is available only in prompt text. Hub does not inject it unless the workflow authors that expression.
|
||||
|
||||
Includes resolve relative to `.paseo/workflows/`, so shared partials use `partials/<name>.md`. Missing files, absolute or traversing paths, symlinks, content mismatches, and files outside the partial tree are rejected.
|
||||
|
||||
### Output capabilities
|
||||
|
||||
Authority stays on the step that uses it:
|
||||
|
||||
```yaml
|
||||
allow_outputs:
|
||||
- type: discord.reply
|
||||
max: 1
|
||||
required: true
|
||||
```
|
||||
|
||||
Slack workflows use `slack.reply`; Discord workflows use `discord.reply`. The declaration grants `hub.reply`, and the prompt must tell the agent to call it. GitHub has no reply output; use an explicit [`github` block](/docs/hub/github).
|
||||
|
||||
Every step receives `hub.finish_execution`. The prompt must tell the agent when to call it; Hub does not append completion or reply instructions. If `output.schema` is present, `hub.finish_execution` requires an `output` value that matches the schema. If an `allow_outputs` entry is `required: true`, the agent must emit that output before finishing. `max` defaults to `1`.
|
||||
|
||||
## Migrating a monolithic file
|
||||
|
||||
Keep `environments` in `hub.yml`, convert the environment list to a named map, and move each former trigger into its own `.paseo/workflows/<name>.yml` file. Move shared prompt files to `.paseo/workflows/partials/`. Define complete named agent configurations under `agents` and replace dynamic provider fields with finite named-agent selection.
|
||||
|
||||
Hub does not read TOML or a monolithic `triggers` section, and the CLI does not rewrite either format.
|
||||
|
||||
See [Workflows](/docs/hub/workflows) for complete routing examples.
|
||||
|
||||
## Agent continuation
|
||||
|
||||
Self-contained dashboard trigger documents accept `run.continuation`:
|
||||
|
||||
| Value | Behavior |
|
||||
| -------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------- |
|
||||
| `{mode: conversation}` | Default. Reuse the project's agent for the event's conversation; create a new agent when the event has no conversation. |
|
||||
| `{mode: key, key: "support-${{ paseo.inputs.ticket }}"}` | Reuse the project's agent for the evaluated custom key. |
|
||||
| `{mode: new}` | Create a new agent for each arrival. |
|
||||
|
||||
Keys use the existing expression syntax and must resolve to a non-empty string of at most 512 characters. Custom keys and provider conversation identities occupy separate namespaces. The same key in different projects does not share an agent.
|
||||
|
||||
An existing session keeps its daemon, agent configuration, target, environment, and tool contracts. Changing those settings for the same key fails with an explanation; choose a different key or **New agent**. Prompts and output destinations belong to each arrival and may change. A worktree branch is chosen when the session is first created and reused on later arrivals.
|
||||
|
||||
A follow-up steers the active agent without extending its runtime deadline or credential expiry. With a `run.github` grant or connection token in `run.env`, follow-ups share the active agent’s credentials. Once all requests finish, Hub revokes leased tokens; the next arrival starts a new agent with fresh credentials. Agents without temporary credentials can be reused after completion.
|
||||
|
||||
### Upgrading
|
||||
|
||||
Upgrade the connected Paseo daemons before enabling the new Hub version. Hub requires the daemon's ordinary agent RPC and request receipt capabilities; an older host produces an actionable dispatch error.
|
||||
|
||||
Hub's database migration adds sessions and nullable execution associations. Existing executions retain their saved launch contract and execution-specific MCP endpoint until they finish. New arrivals for existing self-contained trigger documents use the conversation default. Historical agents are not backfilled into sessions.
|
||||
|
||||
Legacy multi-step workflow bundles keep their existing behavior. Converting one to a self-contained trigger writes `mode: new` explicitly; change it in the editor when ready to reuse agents.
|
||||
@@ -1,281 +0,0 @@
|
||||
---
|
||||
title: Hub 配置参考
|
||||
description: Hub 资源、workflow、Agent、表达式和提示词字段的标准参考。
|
||||
nav: 配置参考
|
||||
---
|
||||
|
||||
# Hub 配置参考 {#hub-configuration-reference}
|
||||
|
||||
Hub 接受以下结构的 YAML:
|
||||
|
||||
```text
|
||||
.paseo/
|
||||
├── hub.yml
|
||||
└── workflows/
|
||||
├── <workflow>.yml
|
||||
└── partials/
|
||||
└── <partial>.md
|
||||
```
|
||||
|
||||
只有 `.paseo/workflows/` 下直接的 `.yml` 子文件才是 workflow。每个文件包含一个触发器及其有序的 step。没有 manifest、`includes`、`uses`、可复用的 step、workflow 调用或继承。
|
||||
|
||||
## `hub.yml` {#hubyml}
|
||||
|
||||
`.paseo/hub.yml` 包含具名的项目资源。名称是映射的键,不会在每个对象内部重复。
|
||||
|
||||
```yaml
|
||||
environments:
|
||||
paseo:
|
||||
kind: daemon
|
||||
daemon: laptop
|
||||
cwd: /Users/you/code/paseo
|
||||
hub:
|
||||
kind: daemon
|
||||
daemon: devbox
|
||||
cwd: /workspace/hub
|
||||
|
||||
agents:
|
||||
codex-safe:
|
||||
provider: codex
|
||||
model: gpt-5.5
|
||||
thinkingOptionId: xhigh
|
||||
options:
|
||||
sandbox_workspace_write:
|
||||
writable_roots: [/var/cache/npm]
|
||||
network_access: false
|
||||
claude:
|
||||
provider: claude
|
||||
mode: bypassPermissions
|
||||
```
|
||||
|
||||
顶层只有 `environments` 和 `agents` 两个键。`triggers` 键会被拒绝,并给出迁移错误。
|
||||
|
||||
### 环境 {#environments}
|
||||
|
||||
| 字段 | 是否必填 | 说明 |
|
||||
| ---------- | ---------- | -------------------------------------------------------------------- |
|
||||
| `kind` | 是 | `daemon`、`fly` 或 `docker`;workflow 的 step 必须选择 daemon 环境。 |
|
||||
| `daemon` | 仅 daemon | 已注册的 daemon slug,在修订激活时解析。 |
|
||||
| `cwd` | 仅 daemon | daemon 上的绝对工作目录。 |
|
||||
| `image` | fly/docker | 镜像名称。 |
|
||||
| `worktree` | 否 | `branch-off`、`checkout-branch` 或 `checkout-pr` 目标。 |
|
||||
|
||||
对于 `worktree`,`branch-off` 使用 `newBranch` 和可选的 `base`,`checkout-branch` 使用 `branch`,`checkout-pr` 使用正整数 `prNumber`。
|
||||
|
||||
```yaml
|
||||
environments:
|
||||
review:
|
||||
kind: daemon
|
||||
daemon: build-server
|
||||
cwd: /workspace/project
|
||||
worktree:
|
||||
mode: branch-off
|
||||
newBranch: trigger-${{ paseo.execution.id }}
|
||||
base: origin/main
|
||||
```
|
||||
|
||||
`newBranch` 是一个分支名字符串。在其中嵌入 `${{ paseo.execution.id }}`,它会渲染为该次执行的 UUID,这样每次执行都会从 `base` 分出自己的分支,并在 Hub 重试或恢复该执行时保留这个分支。
|
||||
|
||||
一次执行就是一次 step 运行,因此选择同一环境的两个 step 会得到各自独立的分支。
|
||||
|
||||
`${{ paseo.execution.id }}` 是 `newBranch` 唯一接受的表达式。`paseo.prompt`、`paseo.context`、`paseo.inputs.*`、`values.*`、`steps.<id>.outputs.*` 以及 Provider 事件字段在这里都不可用,任何一个都会在编写它的字段处导致文件包激活失败,例如 `.paseo/hub.yml.environments.review.worktree.newBranch`。
|
||||
|
||||
`${{ paseo.execution.id }}` 出现在文件包中其他任何位置时,同样会导致激活失败。`branch` 和 `prNumber` 只接受字面值。
|
||||
|
||||
环境是一个完整的具名对象。step 选择它的名称;对象不会被继承、合并或部分覆盖。
|
||||
|
||||
### 具名 Agent {#named-agents}
|
||||
|
||||
每个 Agent 是一份完整的 Provider 配置:
|
||||
|
||||
| 字段 | 是否必填 | 说明 |
|
||||
| ------------------ | -------- | --------------------------------------------------------------------------------- |
|
||||
| `provider` | 是 | Provider ID。Hub 在无人值守的情况下运行,因此为 `claude`、`codex` 或 `opencode`。 |
|
||||
| `model` | 否 | Provider 的模型 ID。 |
|
||||
| `mode` | 否 | Paseo 模式 ID。 |
|
||||
| `thinkingOptionId` | 否 | Provider 的思考选项。 |
|
||||
| `options` | 否 | 可安全序列化为 JSON 的 Provider 原生选项,保留名称和嵌套结构。 |
|
||||
|
||||
具名选择会保留完整的对象,包括结构化的选项。具名 Agent 没有父级、补丁或按 step 的覆盖。
|
||||
|
||||
Hub 把 `model`、`mode`、`thinkingOptionId` 和 `options` 传给 Paseo daemon,不会重命名或展平 Provider 字段。保存或部署触发器时,所选的 daemon 会按它当前的 Provider schema 校验这些值,因此它不提供的值会在那时被拒绝,而不是等到第一次运行;Hub 不会转换 Provider 原生选项。见[保存时会对照 daemon 检查 Agent](/docs/hub/triggers#saving-checks-the-agent-against-the-daemon)。
|
||||
|
||||
## workflow 文件 {#workflow-files}
|
||||
|
||||
`.paseo/workflows/review.yml`:
|
||||
|
||||
```yaml
|
||||
name: review
|
||||
on: manual.run
|
||||
max_runtime: 2h
|
||||
filters:
|
||||
from_users: [automation]
|
||||
inputs:
|
||||
repo:
|
||||
type: string
|
||||
required: true
|
||||
choices: [paseo, hub]
|
||||
steps:
|
||||
- id: inspect
|
||||
environment: ${{ paseo.inputs.repo }}
|
||||
max_runtime: 30m
|
||||
idle_timeout: 5m
|
||||
agent: codex-safe
|
||||
prompt:
|
||||
- text: ${{ paseo.prompt }}
|
||||
```
|
||||
|
||||
| 字段 | 是否必填 | 说明 |
|
||||
| ------------- | -------- | ------------------------------------------------------- |
|
||||
| `name` | 是 | workflow 名称,在整个文件包中唯一。 |
|
||||
| `on` | 是 | Provider 事件,例如 `manual.run` 或 `discord.mention`。 |
|
||||
| `max_runtime` | 是 | 整次运行的硬性时间上限,最多 24h。 |
|
||||
| `filters` | 是 | Provider 资源过滤条件和发送者白名单。 |
|
||||
| `inputs` | 否 | 带类型的调用头部参数。 |
|
||||
| `values` | 否 | 具名表达式。 |
|
||||
| `steps` | 是 | 一个或多个有序的内联 step。 |
|
||||
|
||||
### GitHub 事件和过滤条件 {#github-events-and-filters}
|
||||
|
||||
新的 GitHub workflow 请使用以下语义化事件名之一:
|
||||
|
||||
| `on` | 匹配 |
|
||||
| -------------------------------------- | ----------------------------------------------------------------- |
|
||||
| `github.issue_created` | action 为 `opened` 的 `issues` 投递。 |
|
||||
| `github.pull_request_created` | action 为 `opened` 的 `pull_request` 投递。 |
|
||||
| `github.pull_request_ready_for_review` | 草稿 PR 被标记为可审查。 |
|
||||
| `github.issue_comment_created` | 在 issue 上、action 为 `created` 的 `issue_comment` 投递。 |
|
||||
| `github.pull_request_comment_created` | 在 Pull Request 上、action 为 `created` 的 `issue_comment` 投递。 |
|
||||
| `github.issue_label_added` | action 为 `labeled` 的 `issues` 投递。 |
|
||||
| `github.pull_request_label_added` | action 为 `labeled` 的 `pull_request` 投递。 |
|
||||
|
||||
已有的配置可以继续使用 `github.issues`、`github.issue_comment`、`github.pull_request_review`、`github.pull_request_review_comment` 和 `github.push`。这些旧版事件保持原有的行为。
|
||||
|
||||
`filters` 支持以下 GitHub 字段。对于每个由外部来源触发的 workflow,`from_users` 都必须非空。所有提供的过滤条件以 AND 组合。
|
||||
|
||||
| 字段 | 类型 | 适用于 | 含义 |
|
||||
| ------------ | -------------------------- | ------------------------------------------------------------- | ---------------------------------------------------------- |
|
||||
| `from_users` | 非空字符串列表 | 所有 GitHub 事件 | 允许启动该 workflow 的 GitHub 登录名。 |
|
||||
| `repo` | 非空字符串 | 所有 GitHub 事件 | `owner/name` 形式的仓库。 |
|
||||
| `connection` | 字符串 | 所有 GitHub 事件 | GitHub 连接的 slug。 |
|
||||
| `contains` | 字符串 | issue、Pull Request 和评论事件 | issue 或 Pull Request 的标题加正文中,或评论正文中的子串。 |
|
||||
| `pattern` | 字符串 | issue、Pull Request 和评论事件 | 同一段文本的开头。 |
|
||||
| `label` | 非空字符串 | `github.issue_label_added`、`github.pull_request_label_added` | 本次投递添加的标签。 |
|
||||
| `labels` | 由非空字符串组成的非空列表 | issue、Pull Request 和评论事件 | 每个所列标签都必须当前存在于该 issue 或 Pull Request 上。 |
|
||||
|
||||
`label` 和 `labels` 匹配 GitHub 标签时不区分大小写。`label` 检查发生变化的那一个标签;`labels` 检查当前完整的标签集合,并要求每一项都存在。例如,`labels: [bug, backend]` 要求同时存在 `bug` 和 `backend`。
|
||||
|
||||
`label` 只能与添加标签的事件一起使用,在其他事件上永远不会匹配。使用 `labels` 来要求条目所处的状态,包括由评论启动 workflow 的情况。
|
||||
|
||||
完整的分拣、Pull Request 审查和 ready-for-agent workflow,见 [GitHub 触发器](/docs/hub/triggers/github)。
|
||||
|
||||
### 输入和值 {#inputs-and-values}
|
||||
|
||||
输入的类型为 `type: string | number | boolean`,另有可选的 `required`、`default` 和 `choices`。`required` 和 `default` 不能同时使用。当某个输入可以选择权限相关的对象(例如环境或具名 Agent)时,必须提供有限的 `choices`。
|
||||
|
||||
值用于绑定表达式:
|
||||
|
||||
```yaml
|
||||
values:
|
||||
selected_environment: ${{ steps.classify.outputs.environment }}
|
||||
selected_agent: ${{ steps.classify.outputs.agent }}
|
||||
```
|
||||
|
||||
表达式可以读取已声明的 `paseo.inputs`、之前的 `steps.<id>.outputs` 以及 `values`。语法支持路径、JSON 字面量、括号、`!`、`==`、`!=`、`&&`、`||` 和 `??`。
|
||||
|
||||
用于选择环境或动态具名 Agent 的表达式,在激活时必须具有一个有限的、可能的字符串结果集合。每个结果都必须是一个已配置资源的名称。运行时的选择从不会退回到其他环境或 Agent。
|
||||
|
||||
### step {#steps}
|
||||
|
||||
| 字段 | 是否必填 | 说明 |
|
||||
| ----------------- | -------- | ---------------------------------------------------------------------------------------- |
|
||||
| `id` | 是 | 在 workflow 内唯一。 |
|
||||
| `environment` | 是 | 字面的环境名称,或解析为某个环境名称的有限表达式。 |
|
||||
| `max_runtime` | 是 | step 的硬性时间上限。 |
|
||||
| `idle_timeout` | 是 | 空闲时间上限,不得超过 `max_runtime`。 |
|
||||
| `startup_timeout` | 否 | step 启动的等待预算。默认值和限制见[启动超时](/docs/hub/configuration#startup-timeout)。 |
|
||||
| `agent` | 是 | 具名 Agent、选择具名 Agent 的有限表达式,或一份完整的静态内联 Agent。 |
|
||||
| `prompt` | 是 | 有序的 `text` 和 `include` 块。 |
|
||||
| `if` | 否 | 决定该 step 是否运行的表达式。 |
|
||||
| `env` | 否 | 来自连接值的环境变量。 |
|
||||
| `output.schema` | 否 | 结构化 step 输出的 JSON Schema。 |
|
||||
| `allow_outputs` | 否 | Provider 输出能力,可带 `max` 和 `required`。 |
|
||||
| `auto_archive` | 否 | step 结束后归档该 Agent。 |
|
||||
| `github` | 否 | 该 step 的显式 GitHub 权限。 |
|
||||
|
||||
内联 Agent 是静态且完整的:
|
||||
|
||||
```yaml
|
||||
agent:
|
||||
provider: codex
|
||||
model: gpt-5.5
|
||||
options:
|
||||
approval_policy: never
|
||||
sandbox_mode: read-only
|
||||
```
|
||||
|
||||
表达式形式的 `agent` 用于选择具名 Agent。内联对象中的动态 Provider 字段会被拒绝。
|
||||
|
||||
### 提示词语义 {#prompt-semantics}
|
||||
|
||||
```yaml
|
||||
prompt:
|
||||
- include: partials/review.md
|
||||
- text: |
|
||||
<user-prompt>
|
||||
${{ paseo.prompt }}
|
||||
</user-prompt>
|
||||
```
|
||||
|
||||
`${{ paseo.prompt }}` 是去掉 Provider 标记和已声明的开头 `key=value` 输入之后的规范化请求。它不会被改写,也不会附加事件上下文。
|
||||
|
||||
`${{ paseo.context }}` 让该 step 选择加入 Provider 上下文的具体化,并在提示词中把结果渲染为 JSON。它只能用在提示词文本中。除非 workflow 编写了这个表达式,否则 Hub 不会注入它。
|
||||
|
||||
include 相对于 `.paseo/workflows/` 解析,因此共享片段使用 `partials/<name>.md`。缺失的文件、绝对路径或越界路径、符号链接、内容不一致以及位于片段目录树之外的文件都会被拒绝。
|
||||
|
||||
### 输出能力 {#output-capabilities}
|
||||
|
||||
权限保留在使用它的 step 上:
|
||||
|
||||
```yaml
|
||||
allow_outputs:
|
||||
- type: discord.reply
|
||||
max: 1
|
||||
required: true
|
||||
```
|
||||
|
||||
Slack workflow 使用 `slack.reply`;Discord workflow 使用 `discord.reply`。这项声明授予 `hub.reply`,提示词必须告诉 Agent 调用它。GitHub 没有回复输出;请使用显式的 [`github` 块](/docs/hub/github)。
|
||||
|
||||
每个 step 都会获得 `hub.finish_execution`。提示词必须告诉 Agent 何时调用它;Hub 不会追加完成或回复的指示。如果存在 `output.schema`,`hub.finish_execution` 需要一个与该 schema 匹配的 `output` 值。如果某个 `allow_outputs` 条目为 `required: true`,Agent 必须在完成之前发出该输出。`max` 默认为 `1`。
|
||||
|
||||
## 迁移单体文件 {#migrating-a-monolithic-file}
|
||||
|
||||
把 `environments` 保留在 `hub.yml` 中,把环境列表转换为具名映射,并把原先的每个触发器移到它自己的 `.paseo/workflows/<name>.yml` 文件中。把共享的提示词文件移到 `.paseo/workflows/partials/`。在 `agents` 下定义完整的具名 Agent 配置,并用有限的具名 Agent 选择替换动态的 Provider 字段。
|
||||
|
||||
Hub 不读取 TOML 或单体的 `triggers` 部分,CLI 也不会改写这两种格式。
|
||||
|
||||
完整的路由示例见 [workflow](/docs/hub/workflows)。
|
||||
|
||||
## Agent 延续 {#agent-continuation}
|
||||
|
||||
自包含的控制台触发器文档接受 `run.continuation`:
|
||||
|
||||
| 值 | 行为 |
|
||||
| -------------------------------------------------------- | -------------------------------------------------------------------------- |
|
||||
| `{mode: conversation}` | 默认值。为事件所属的对话复用项目中的 Agent;事件没有对话时创建新的 Agent。 |
|
||||
| `{mode: key, key: "support-${{ paseo.inputs.ticket }}"}` | 为求值得到的自定义键复用项目中的 Agent。 |
|
||||
| `{mode: new}` | 每次到达都创建新的 Agent。 |
|
||||
|
||||
键使用现有的表达式语法,必须解析为长度不超过 512 个字符的非空字符串。自定义键和 Provider 的对话标识位于不同的命名空间。不同项目中的相同键不会共享 Agent。
|
||||
|
||||
已有的会话会保留它的 daemon、Agent 配置、目标、环境和工具契约。为同一个键修改这些设置会失败并给出说明;请选择另一个键或 **New agent**。提示词和输出目标属于每次到达,可以变化。worktree 分支在会话首次创建时选定,并在之后的到达中复用。
|
||||
|
||||
后续消息会引导正在运行的 Agent,但不会延长它的运行截止时间或凭据有效期。当 `run.env` 中有 `run.github` 授权或连接令牌时,后续消息共享正在运行的 Agent 的凭据。所有请求都完成后,Hub 会撤销租用的令牌;下一次到达会用新的凭据启动新的 Agent。没有临时凭据的 Agent 在完成后可以被复用。
|
||||
|
||||
### 升级 {#upgrading}
|
||||
|
||||
在启用新版 Hub 之前,请先升级已连接的 Paseo daemon。Hub 需要 daemon 的常规 Agent RPC 和请求回执能力;较旧的主机会产生一个可操作的发起错误。
|
||||
|
||||
Hub 的数据库迁移会添加会话以及可为空的执行关联。已有的执行会保留它们已保存的启动契约和执行专属的 MCP 端点,直到完成。已有自包含触发器文档的新到达使用对话默认值。历史上的 Agent 不会被回填到会话中。
|
||||
|
||||
旧版的多 step workflow 文件包保持原有行为。把它转换为自包含触发器时,会显式写入 `mode: new`;准备好复用 Agent 时,在编辑器中修改它。
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user