Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9d9e75c7bd | ||
|
|
6dde6ae2dd | ||
|
|
ce3b16df35 | ||
|
|
b5f4bf6e39 | ||
|
|
59c2e1ff2c | ||
|
|
b2679012ff | ||
|
|
1a54471e29 | ||
|
|
fdfb36428d | ||
|
|
0919277fd7 | ||
|
|
e3b032844b | ||
|
|
d6c66922c7 | ||
|
|
8fc0e2349f | ||
|
|
9aec7dc204 | ||
|
|
ba325922d2 | ||
|
|
cbaa8c7c90 | ||
|
|
3e0568aa93 | ||
|
|
c1d10b4e75 | ||
|
|
524116e111 | ||
|
|
1230337165 | ||
|
|
b3d860cce2 | ||
|
|
7b9c6a7d4a | ||
|
|
66f764eefd | ||
|
|
05fc260b96 | ||
|
|
1972864b19 | ||
|
|
cba515ef73 | ||
|
|
a0ed629b7d |
@@ -0,0 +1,63 @@
|
||||
# Brand assets
|
||||
|
||||
Canonical marks, lockups, and wordmark font for **Paseo** and **Paseo Hub**. These are the source assets that will replace the existing icons across the app, desktop client, website, docs, and Hub in follow-up work.
|
||||
|
||||
## Brand architecture
|
||||
|
||||
- **Paseo** (butterfly mark): the local client, daemon, CLI, SDK, and small account features (sign-in, share links, tunnels).
|
||||
- **Paseo Hub** (flower mark): the software factory, team features, hosted service, and paid plans (`Hub Free`, `Hub Solo`, `Hub Team`).
|
||||
- **Hub** (flower mark + `Hub`): used only where Paseo is already on screen, such as inside the Hub dashboard header.
|
||||
|
||||
## Specifications
|
||||
|
||||
### Marks
|
||||
|
||||
Both marks are single-line stroked paths on a `700 × 700` viewBox with `stroke-width="50"`, `stroke-linecap="round"`, and `stroke-linejoin="round"`. Both are optically centered to a `527`-unit ink footprint:
|
||||
|
||||
- **Paseo (`marks/paseo-*.svg`)**: refit of the hand-drawn butterfly (redraw B) with smooth curvature on the large wing and lower loop and a uniform `50` stroke width.
|
||||
- **Paseo Hub (`marks/paseo-hub-*.svg`)**: five-petal looped flower (variant A) with a `12°` clockwise petal lean, sized up to match the butterfly's `527` footprint with the same `50` stroke.
|
||||
|
||||
Colors:
|
||||
|
||||
- `white` (`#FFFFFF`) for dark surfaces (`#101615`, `#101010`, `#000000`)
|
||||
- `black` (`#000000`) for light surfaces
|
||||
- `green` (`#20744A`) brand accent
|
||||
|
||||
### Lockups
|
||||
|
||||
All lockups (`lockups/*.svg`) share a `144`-unit height (`140`-unit flower ink height with a `2`-unit margin on all sides) so stacked lockups align cleanly:
|
||||
|
||||
- **Font**: Plus Jakarta Sans SemiBold (`600`), bundled in `fonts/PlusJakartaSans-SemiBold.ttf` under the SIL Open Font License 1.1 (`fonts/OFL.txt`).
|
||||
- **Outlined text**: lockup SVGs outline the wordmark to `<path>` elements so they render identically everywhere without the font installed.
|
||||
- **Proportions**: marks are `15%` larger against text and `20%` closer than the original website header baseline (`24 px` box, `12 px` gap, `18 px` text).
|
||||
- **Optical balance**: in the `paseo` lockup, the butterfly is scaled to `94%` (`stroke-width` proportional) so `Paseo`, `Paseo Hub`, and `Hub` sit at equal visual weight when shown together.
|
||||
|
||||
## Files
|
||||
|
||||
```text
|
||||
assets/brand/
|
||||
build.mjs Regenerates all marks and lockups
|
||||
fonts/
|
||||
PlusJakartaSans-SemiBold.ttf
|
||||
OFL.txt
|
||||
marks/
|
||||
paseo-white.svg
|
||||
paseo-black.svg
|
||||
paseo-green.svg
|
||||
paseo-hub-white.svg
|
||||
paseo-hub-black.svg
|
||||
paseo-hub-green.svg
|
||||
lockups/
|
||||
paseo-white.svg
|
||||
paseo-black.svg
|
||||
paseo-hub-white.svg
|
||||
paseo-hub-black.svg
|
||||
hub-white.svg
|
||||
hub-black.svg
|
||||
```
|
||||
|
||||
## Regenerate
|
||||
|
||||
```sh
|
||||
node assets/brand/build.mjs
|
||||
```
|
||||
@@ -0,0 +1,93 @@
|
||||
Copyright 2020 The Plus Jakarta Sans Project Authors (https://github.com/tokotype/PlusJakartaSans)
|
||||
|
||||
This Font Software is licensed under the SIL Open Font License, Version 1.1.
|
||||
This license is copied below, and is also available with a FAQ at:
|
||||
http://scripts.sil.org/OFL
|
||||
|
||||
|
||||
-----------------------------------------------------------
|
||||
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
|
||||
-----------------------------------------------------------
|
||||
|
||||
PREAMBLE
|
||||
The goals of the Open Font License (OFL) are to stimulate worldwide
|
||||
development of collaborative font projects, to support the font creation
|
||||
efforts of academic and linguistic communities, and to provide a free and
|
||||
open framework in which fonts may be shared and improved in partnership
|
||||
with others.
|
||||
|
||||
The OFL allows the licensed fonts to be used, studied, modified and
|
||||
redistributed freely as long as they are not sold by themselves. The
|
||||
fonts, including any derivative works, can be bundled, embedded,
|
||||
redistributed and/or sold with any software provided that any reserved
|
||||
names are not used by derivative works. The fonts and derivatives,
|
||||
however, cannot be released under any other type of license. The
|
||||
requirement for fonts to remain under this license does not apply
|
||||
to any document created using the fonts or their derivatives.
|
||||
|
||||
DEFINITIONS
|
||||
"Font Software" refers to the set of files released by the Copyright
|
||||
Holder(s) under this license and clearly marked as such. This may
|
||||
include source files, build scripts and documentation.
|
||||
|
||||
"Reserved Font Name" refers to any names specified as such after the
|
||||
copyright statement(s).
|
||||
|
||||
"Original Version" refers to the collection of Font Software components as
|
||||
distributed by the Copyright Holder(s).
|
||||
|
||||
"Modified Version" refers to any derivative made by adding to, deleting,
|
||||
or substituting -- in part or in whole -- any of the components of the
|
||||
Original Version, by changing formats or by porting the Font Software to a
|
||||
new environment.
|
||||
|
||||
"Author" refers to any designer, engineer, programmer, technical
|
||||
writer or other person who contributed to the Font Software.
|
||||
|
||||
PERMISSION & CONDITIONS
|
||||
Permission is hereby granted, free of charge, to any person obtaining
|
||||
a copy of the Font Software, to use, study, copy, merge, embed, modify,
|
||||
redistribute, and sell modified and unmodified copies of the Font
|
||||
Software, subject to the following conditions:
|
||||
|
||||
1) Neither the Font Software nor any of its individual components,
|
||||
in Original or Modified Versions, may be sold by itself.
|
||||
|
||||
2) Original or Modified Versions of the Font Software may be bundled,
|
||||
redistributed and/or sold with any software, provided that each copy
|
||||
contains the above copyright notice and this license. These can be
|
||||
included either as stand-alone text files, human-readable headers or
|
||||
in the appropriate machine-readable metadata fields within text or
|
||||
binary files as long as those fields can be easily viewed by the user.
|
||||
|
||||
3) No Modified Version of the Font Software may use the Reserved Font
|
||||
Name(s) unless explicit written permission is granted by the corresponding
|
||||
Copyright Holder. This restriction only applies to the primary font name as
|
||||
presented to the users.
|
||||
|
||||
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
|
||||
Software shall not be used to promote, endorse or advertise any
|
||||
Modified Version, except to acknowledge the contribution(s) of the
|
||||
Copyright Holder(s) and the Author(s) or with their explicit written
|
||||
permission.
|
||||
|
||||
5) The Font Software, modified or unmodified, in part or in whole,
|
||||
must be distributed entirely under this license, and must not be
|
||||
distributed under any other license. The requirement for fonts to
|
||||
remain under this license does not apply to any document created
|
||||
using the Font Software.
|
||||
|
||||
TERMINATION
|
||||
This license becomes null and void if any of the above conditions are
|
||||
not met.
|
||||
|
||||
DISCLAIMER
|
||||
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
|
||||
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
|
||||
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
|
||||
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
|
||||
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
|
||||
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
|
||||
OTHER DEALINGS IN THE FONT SOFTWARE.
|
||||
|
After Width: | Height: | Size: 7.9 KiB |
|
After Width: | Height: | Size: 7.9 KiB |
|
After Width: | Height: | Size: 11 KiB |
|
After Width: | Height: | Size: 14 KiB |
|
After Width: | Height: | Size: 14 KiB |
|
After Width: | Height: | Size: 11 KiB |
|
After Width: | Height: | Size: 5.9 KiB |
|
After Width: | Height: | Size: 5.9 KiB |
|
After Width: | Height: | Size: 6.7 KiB |
|
After Width: | Height: | Size: 6.7 KiB |
|
After Width: | Height: | Size: 6.7 KiB |
|
After Width: | Height: | Size: 5.9 KiB |
@@ -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.
|
||||
|
||||
@@ -29,7 +29,12 @@ const ACP_PROVIDER = {
|
||||
|
||||
interface ProviderCatalogDaemonClient {
|
||||
getLastServerInfoMessage(): {
|
||||
features?: { fxProvider?: boolean; hopliteProvider?: boolean; plugins?: boolean };
|
||||
features?: {
|
||||
gooseProvider?: boolean;
|
||||
fxProvider?: boolean;
|
||||
hopliteProvider?: boolean;
|
||||
plugins?: boolean;
|
||||
};
|
||||
} | null;
|
||||
connect(): Promise<void>;
|
||||
close(): Promise<void>;
|
||||
@@ -204,3 +209,47 @@ test("model selector excludes Hoplite before opt-in", async ({ page }, testInfo)
|
||||
await client.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("adds bundled goose from the catalog", async ({ page }) => {
|
||||
const client = await connectDaemonClient<ProviderCatalogDaemonClient>({
|
||||
clientIdPrefix: "goose-catalog-e2e",
|
||||
});
|
||||
try {
|
||||
expect(client.getLastServerInfoMessage()?.features?.gooseProvider).toBe(true);
|
||||
await client.patchDaemonConfig({ removeProviders: ["goose"] });
|
||||
await gotoAppShell(page);
|
||||
await addGooseFromSettings(page, getServerId());
|
||||
expect((await client.getDaemonConfig()).config.providers?.goose).toEqual({ enabled: true });
|
||||
} finally {
|
||||
await client.patchDaemonConfig({ removeProviders: ["goose"] });
|
||||
await client.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("adds goose through ACP on an older host", async ({ page, outdatedDaemon }) => {
|
||||
const client = await connectDaemonClient<ProviderCatalogDaemonClient>({
|
||||
clientIdPrefix: "goose-catalog-old-host",
|
||||
port: Number(new URL(`http://${outdatedDaemon.endpoint}`).port),
|
||||
});
|
||||
try {
|
||||
expect(client.getLastServerInfoMessage()?.features?.gooseProvider).toBe(false);
|
||||
await seedSavedSettingsHosts(page, [outdatedDaemon]);
|
||||
await page.reload();
|
||||
await addGooseFromSettings(page, outdatedDaemon.serverId);
|
||||
expect((await client.getDaemonConfig()).config.providers?.goose).toMatchObject({
|
||||
extends: "acp",
|
||||
command: ["goose", "acp"],
|
||||
});
|
||||
} finally {
|
||||
await client.close();
|
||||
}
|
||||
});
|
||||
|
||||
async function addGooseFromSettings(page: import("@playwright/test").Page, serverId: string) {
|
||||
await openSettings(page);
|
||||
await openSettingsHost(page, serverId);
|
||||
await openSettingsHostSection(page, serverId, "providers");
|
||||
await openAddProvider(page);
|
||||
await installAcpCatalogProvider(page, "goose");
|
||||
await expectProviderInstalledInSettings(page, "goose");
|
||||
}
|
||||
|
||||
@@ -1598,6 +1598,237 @@ test("canvas diff replaces a selection with forward and backward drags", async (
|
||||
}
|
||||
});
|
||||
|
||||
test("canvas diff double-click selects the grapheme under the pointer, not the nearest caret", async ({
|
||||
context,
|
||||
page,
|
||||
}) => {
|
||||
const content = "call(foo bar)";
|
||||
const workspace = await createWorkspaceWithExactSelectionDiff(content);
|
||||
await context.grantPermissions(["clipboard-read", "clipboard-write"]);
|
||||
await useUnwrappedDiffLines(page);
|
||||
await openSelectionWorkspaceChanges(page, workspace);
|
||||
|
||||
await dragAddedTextRange(page, {
|
||||
lines: [content],
|
||||
clickCount: 2,
|
||||
fraction: 0.75,
|
||||
start: { line: 0, offset: 3 },
|
||||
end: { line: 0, offset: 3 },
|
||||
});
|
||||
await copyDiffSelectionWithKeyboard(page);
|
||||
await expectClipboardText(page, "call");
|
||||
|
||||
await dragAddedTextRange(page, {
|
||||
lines: [content],
|
||||
clickCount: 2,
|
||||
fraction: 0.1,
|
||||
start: { line: 0, offset: 4 },
|
||||
end: { line: 0, offset: 4 },
|
||||
});
|
||||
await copyDiffSelectionWithKeyboard(page);
|
||||
await expectClipboardText(page, "(");
|
||||
});
|
||||
|
||||
test("canvas diff double-click selects the clicked word and replaces an existing selection", async ({
|
||||
context,
|
||||
page,
|
||||
}) => {
|
||||
const content = "alpha bravo charlie delta";
|
||||
const workspace = await createWorkspaceWithExactSelectionDiff(content);
|
||||
await context.grantPermissions(["clipboard-read", "clipboard-write"]);
|
||||
await useUnwrappedDiffLines(page);
|
||||
await openSelectionWorkspaceChanges(page, workspace);
|
||||
|
||||
await dragAddedTextRange(page, {
|
||||
lines: [content],
|
||||
start: { line: 0, offset: 0 },
|
||||
end: { line: 0, offset: 4 },
|
||||
});
|
||||
await dragAddedTextRange(page, {
|
||||
lines: [content],
|
||||
clickCount: 2,
|
||||
start: { line: 0, offset: 8 },
|
||||
end: { line: 0, offset: 8 },
|
||||
});
|
||||
await copyDiffSelectionWithKeyboard(page);
|
||||
await expectClipboardText(page, "bravo");
|
||||
});
|
||||
|
||||
test("canvas diff double-click drag extends the selection word by word in both directions", async ({
|
||||
context,
|
||||
page,
|
||||
}) => {
|
||||
const content = "alpha bravo charlie delta";
|
||||
const workspace = await createWorkspaceWithExactSelectionDiff(content);
|
||||
await context.grantPermissions(["clipboard-read", "clipboard-write"]);
|
||||
await useUnwrappedDiffLines(page);
|
||||
await openSelectionWorkspaceChanges(page, workspace);
|
||||
|
||||
for (const [start, end, expectedText] of [
|
||||
[{ line: 0, offset: 8 }, { line: 0, offset: 14 }, "bravo charlie"],
|
||||
[{ line: 0, offset: 14 }, { line: 0, offset: 2 }, "alpha bravo charlie"],
|
||||
] as const) {
|
||||
await dragAddedTextRange(page, { lines: [content], clickCount: 2, start, end });
|
||||
await copyDiffSelectionWithKeyboard(page);
|
||||
await expectClipboardText(page, expectedText);
|
||||
}
|
||||
});
|
||||
|
||||
test("canvas diff double-click drag extends word by word across lines and wrapped lines", async ({
|
||||
context,
|
||||
page,
|
||||
}) => {
|
||||
const lines = ["alpha bravo", "charlie delta"];
|
||||
const workspace = await createWorkspaceWithExactSelectionDiff(lines.join("\n"));
|
||||
await context.grantPermissions(["clipboard-read", "clipboard-write"]);
|
||||
await useUnwrappedDiffLines(page);
|
||||
await openSelectionWorkspaceChanges(page, workspace);
|
||||
|
||||
for (const [start, end, expectedText] of [
|
||||
[{ line: 0, offset: 8 }, { line: 1, offset: 10 }, "bravo\ncharlie delta"],
|
||||
[{ line: 1, offset: 10 }, { line: 0, offset: 2 }, "alpha bravo\ncharlie delta"],
|
||||
] as const) {
|
||||
await dragAddedTextRange(page, { lines, clickCount: 2, start, end });
|
||||
await copyDiffSelectionWithKeyboard(page);
|
||||
await expectClipboardText(page, expectedText);
|
||||
}
|
||||
|
||||
const wrapped = `${"alpha ".repeat(40)}bravo charlie`;
|
||||
const wrappedWorkspace = await createWorkspaceWithExactSelectionDiff(wrapped);
|
||||
await configureDiffPresentation(page, { layout: "unified", wrapLines: true });
|
||||
await openSelectionWorkspaceChanges(page, wrappedWorkspace);
|
||||
await setOpenChangesPresentation(page, { layout: "unified", wrapLines: true });
|
||||
const bravoStart = 40 * "alpha ".length;
|
||||
await dragAddedTextRange(page, {
|
||||
lines: [wrapped],
|
||||
wrapped: true,
|
||||
clickCount: 2,
|
||||
start: { line: 0, offset: bravoStart + 2 },
|
||||
end: { line: 0, offset: bravoStart + 9 },
|
||||
});
|
||||
await copyDiffSelectionWithKeyboard(page);
|
||||
await expectClipboardText(page, "bravo charlie");
|
||||
});
|
||||
|
||||
test("canvas diff double-click drag keeps word selection on the split side", async ({
|
||||
context,
|
||||
page,
|
||||
}) => {
|
||||
const lines = ["RIGHT-ONE", "RIGHT-TWO"];
|
||||
const workspace = await createWorkspaceWithExactSelectionDiff(lines.join("\n"));
|
||||
await context.grantPermissions(["clipboard-read", "clipboard-write"]);
|
||||
await configureDiffPresentation(page, { layout: "split", wrapLines: false });
|
||||
await openSelectionWorkspaceChanges(page, workspace);
|
||||
await setOpenChangesPresentation(page, { layout: "split", wrapLines: false });
|
||||
|
||||
await dragAddedTextRange(page, {
|
||||
lines,
|
||||
side: "right",
|
||||
clickCount: 2,
|
||||
start: { line: 0, offset: 7 },
|
||||
end: { line: 1, offset: 3 },
|
||||
});
|
||||
await page.keyboard.press("ControlOrMeta+C");
|
||||
await expect.poll(() => page.evaluate(() => navigator.clipboard.readText())).toBe("ONE\nRIGHT");
|
||||
});
|
||||
|
||||
test("canvas diff triple-click selects the whole source line and replaces an existing selection", async ({
|
||||
context,
|
||||
page,
|
||||
}) => {
|
||||
const content = "alpha bravo";
|
||||
const workspace = await createWorkspaceWithExactSelectionDiff(content);
|
||||
await context.grantPermissions(["clipboard-read", "clipboard-write"]);
|
||||
await useUnwrappedDiffLines(page);
|
||||
await openSelectionWorkspaceChanges(page, workspace);
|
||||
|
||||
await dragAddedTextRange(page, {
|
||||
lines: [content],
|
||||
start: { line: 0, offset: 0 },
|
||||
end: { line: 0, offset: 3 },
|
||||
});
|
||||
await dragAddedTextRange(page, {
|
||||
lines: [content],
|
||||
clickCount: 3,
|
||||
start: { line: 0, offset: 8 },
|
||||
end: { line: 0, offset: 8 },
|
||||
});
|
||||
await copyDiffSelectionWithKeyboard(page);
|
||||
await expectClipboardText(page, content);
|
||||
});
|
||||
|
||||
test("canvas diff triple-click drag extends whole source lines in both directions", async ({
|
||||
context,
|
||||
page,
|
||||
}) => {
|
||||
const lines = ["alpha", "bravo", "charlie"];
|
||||
const workspace = await createWorkspaceWithExactSelectionDiff(lines.join("\n"));
|
||||
await context.grantPermissions(["clipboard-read", "clipboard-write"]);
|
||||
await useUnwrappedDiffLines(page);
|
||||
await openSelectionWorkspaceChanges(page, workspace);
|
||||
|
||||
for (const [start, end] of [
|
||||
[
|
||||
{ line: 0, offset: 2 },
|
||||
{ line: 2, offset: 3 },
|
||||
],
|
||||
[
|
||||
{ line: 2, offset: 3 },
|
||||
{ line: 0, offset: 1 },
|
||||
],
|
||||
] as const) {
|
||||
await dragAddedTextRange(page, { lines, clickCount: 3, start, end });
|
||||
await copyDiffSelectionWithKeyboard(page);
|
||||
await expectClipboardText(page, "alpha\nbravo\ncharlie");
|
||||
}
|
||||
});
|
||||
|
||||
test("canvas diff triple-click selects every wrapped fragment of a source line", async ({
|
||||
context,
|
||||
page,
|
||||
}) => {
|
||||
const content = `${"alpha ".repeat(80)}omega`;
|
||||
const workspace = await createWorkspaceWithExactSelectionDiff(content);
|
||||
await context.grantPermissions(["clipboard-read", "clipboard-write"]);
|
||||
await configureDiffPresentation(page, { layout: "unified", wrapLines: true });
|
||||
await openSelectionWorkspaceChanges(page, workspace);
|
||||
await setOpenChangesPresentation(page, { layout: "unified", wrapLines: true });
|
||||
|
||||
await dragAddedTextRange(page, {
|
||||
lines: [content],
|
||||
wrapped: true,
|
||||
clickCount: 3,
|
||||
start: { line: 0, offset: 20 },
|
||||
end: { line: 0, offset: 20 },
|
||||
});
|
||||
await copyDiffSelectionWithKeyboard(page);
|
||||
await expectClipboardText(page, content);
|
||||
});
|
||||
|
||||
test("canvas diff triple-click drag keeps whole source lines on the split side", async ({
|
||||
context,
|
||||
page,
|
||||
}) => {
|
||||
const lines = ["RIGHT-ONE", "RIGHT-TWO"];
|
||||
const workspace = await createWorkspaceWithExactSelectionDiff(lines.join("\n"));
|
||||
await context.grantPermissions(["clipboard-read", "clipboard-write"]);
|
||||
await configureDiffPresentation(page, { layout: "split", wrapLines: false });
|
||||
await openSelectionWorkspaceChanges(page, workspace);
|
||||
await setOpenChangesPresentation(page, { layout: "split", wrapLines: false });
|
||||
|
||||
await dragAddedTextRange(page, {
|
||||
lines,
|
||||
side: "right",
|
||||
clickCount: 3,
|
||||
start: { line: 1, offset: 3 },
|
||||
end: { line: 0, offset: 4 },
|
||||
});
|
||||
await page.keyboard.press("ControlOrMeta+C");
|
||||
await expect
|
||||
.poll(() => page.evaluate(() => navigator.clipboard.readText()))
|
||||
.toBe("RIGHT-ONE\nRIGHT-TWO");
|
||||
});
|
||||
|
||||
test("canvas diff copies only the selected split side", async ({ context, page }) => {
|
||||
const lines = ["RIGHT-ONE", "RIGHT-TWO"];
|
||||
const workspace = await createWorkspaceWithExactSelectionDiff(lines.join("\n"));
|
||||
@@ -2482,6 +2713,8 @@ async function dragAddedTextRange(
|
||||
side?: "left" | "right";
|
||||
wrapped?: boolean;
|
||||
horizontalOffset?: number;
|
||||
clickCount?: 1 | 2 | 3;
|
||||
fraction?: number;
|
||||
},
|
||||
): Promise<void> {
|
||||
const body = page.getByTestId("diff-file-0-body");
|
||||
@@ -2520,14 +2753,38 @@ async function dragAddedTextRange(
|
||||
columnLeft +
|
||||
gutterWidth +
|
||||
8 +
|
||||
localOffset * metrics.characterWidth -
|
||||
(localOffset + (input.fraction ?? 0)) * metrics.characterWidth -
|
||||
(input.horizontalOffset ?? 0),
|
||||
y: bounds.y + (1 + fragmentsBefore(line) + fragment + 0.5) * lineHeight,
|
||||
};
|
||||
};
|
||||
const start = point(input.start);
|
||||
const end = point(input.end);
|
||||
const clickCount = input.clickCount ?? 1;
|
||||
await page.mouse.move(start.x, start.y);
|
||||
if (clickCount > 1) {
|
||||
const isSinglePoint =
|
||||
input.start.line === input.end.line && input.start.offset === input.end.offset;
|
||||
if (isSinglePoint && clickCount === 2) {
|
||||
await page.mouse.dblclick(start.x, start.y);
|
||||
return;
|
||||
}
|
||||
if (isSinglePoint) {
|
||||
for (let count = 1; count <= clickCount; count += 1) {
|
||||
await page.mouse.down({ clickCount: count });
|
||||
await page.mouse.up({ clickCount: count });
|
||||
}
|
||||
return;
|
||||
}
|
||||
for (let count = 1; count < clickCount; count += 1) {
|
||||
await page.mouse.down({ clickCount: count });
|
||||
await page.mouse.up({ clickCount: count });
|
||||
}
|
||||
await page.mouse.down({ clickCount });
|
||||
await page.mouse.move(end.x, end.y, { steps: 12 });
|
||||
await page.mouse.up({ clickCount });
|
||||
return;
|
||||
}
|
||||
await page.mouse.down();
|
||||
await page.mouse.move(end.x, end.y, { steps: 12 });
|
||||
await page.mouse.up();
|
||||
|
||||
@@ -224,6 +224,7 @@ const CATALOG_DATA = [
|
||||
},
|
||||
{
|
||||
id: "goose",
|
||||
bundledProvider: { hostFeature: "gooseProvider" },
|
||||
title: "goose",
|
||||
description: "A local, extensible, open source AI agent that automates engineering tasks",
|
||||
version: "1.33.1",
|
||||
|
||||
@@ -2,6 +2,7 @@ import type { ParsedDiffFile } from "@getpaseo/protocol/messages";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
characterOffsetAtPoint,
|
||||
graphemeOffsetAtPoint,
|
||||
hitTestDiffDocument,
|
||||
orderedSelection,
|
||||
selectAllSource,
|
||||
@@ -43,6 +44,49 @@ describe("diff hit testing", () => {
|
||||
).toBe(combining?.end);
|
||||
});
|
||||
|
||||
it("keeps the nearest caret for character drags but hits the grapheme under word gestures", () => {
|
||||
const cell = changedCell(buildModel("call(foo)", { wrapLines: false, viewportWidth: 300 }));
|
||||
const graphemes = cell.fragments[0]!.graphemes;
|
||||
const lastOfWord = graphemes[3]!;
|
||||
const punctuation = graphemes[4]!;
|
||||
const beforeLastOfWord = graphemes
|
||||
.slice(0, 3)
|
||||
.reduce((width, grapheme) => width + grapheme.width, 0);
|
||||
const rightHalfOfWord = beforeLastOfWord + lastOfWord.width * 0.75;
|
||||
const leftHalfOfPunctuation = beforeLastOfWord + lastOfWord.width + punctuation.width * 0.1;
|
||||
|
||||
expect(characterOffsetAtPoint({ cell, x: rightHalfOfWord, y: 0, lineHeight: 18 })).toBe(
|
||||
punctuation.start,
|
||||
);
|
||||
expect(graphemeOffsetAtPoint({ cell, x: rightHalfOfWord, y: 0, lineHeight: 18 })).toBe(
|
||||
lastOfWord.start,
|
||||
);
|
||||
expect(characterOffsetAtPoint({ cell, x: leftHalfOfPunctuation, y: 0, lineHeight: 18 })).toBe(
|
||||
punctuation.start,
|
||||
);
|
||||
expect(graphemeOffsetAtPoint({ cell, x: leftHalfOfPunctuation, y: 0, lineHeight: 18 })).toBe(
|
||||
punctuation.start,
|
||||
);
|
||||
});
|
||||
|
||||
it("keeps wrapped fragment boundaries from stealing the grapheme under the pointer", () => {
|
||||
const cell = changedCell(buildModel("abcdef", { viewportWidth: 90 }));
|
||||
const firstFragment = cell.fragments[0]!;
|
||||
expect(cell.fragments.length).toBeGreaterThan(1);
|
||||
const lastGrapheme = firstFragment.graphemes.at(-1)!;
|
||||
const beforeLastGrapheme = firstFragment.graphemes
|
||||
.slice(0, -1)
|
||||
.reduce((width, grapheme) => width + grapheme.width, 0);
|
||||
const rightHalfOfLastGrapheme = beforeLastGrapheme + lastGrapheme.width * 0.75;
|
||||
|
||||
expect(characterOffsetAtPoint({ cell, x: rightHalfOfLastGrapheme, y: 0, lineHeight: 18 })).toBe(
|
||||
firstFragment.end,
|
||||
);
|
||||
expect(graphemeOffsetAtPoint({ cell, x: rightHalfOfLastGrapheme, y: 0, lineHeight: 18 })).toBe(
|
||||
lastGrapheme.start,
|
||||
);
|
||||
});
|
||||
|
||||
it("normalizes backwards selection and copies exact source including empty lines", () => {
|
||||
const model = buildModel("", { wrapLines: false });
|
||||
const cell = changedCell(model);
|
||||
|
||||
@@ -3,6 +3,7 @@ import type {
|
||||
DiffCell,
|
||||
DiffCharacterPosition,
|
||||
DiffDocumentModel,
|
||||
DiffFragment,
|
||||
DiffHit,
|
||||
DiffSelection,
|
||||
} from "./types";
|
||||
@@ -33,12 +34,7 @@ export function hitTestDiffDocument(input: {
|
||||
localX - file.gutterWidth - CODE_LEFT_PADDING + input.horizontalOffset,
|
||||
);
|
||||
const textY = input.documentY - row.top;
|
||||
const sourceOffset = characterOffsetAtPoint({
|
||||
cell,
|
||||
x: contentX,
|
||||
y: textY,
|
||||
lineHeight: input.model.lineHeight,
|
||||
});
|
||||
const point = { cell, x: contentX, y: textY, lineHeight: input.model.lineHeight };
|
||||
return {
|
||||
kind: "cell",
|
||||
target: cell.reviewTarget,
|
||||
@@ -47,8 +43,9 @@ export function hitTestDiffDocument(input: {
|
||||
rowIndex: row.index,
|
||||
cellIndex,
|
||||
side: cell.reviewTarget?.side ?? (cellIndex === 0 ? "old" : "new"),
|
||||
sourceOffset,
|
||||
sourceOffset: characterOffsetAtPoint(point),
|
||||
},
|
||||
graphemeOffset: graphemeOffsetAtPoint(point),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -58,11 +55,7 @@ export function characterOffsetAtPoint(input: {
|
||||
y: number;
|
||||
lineHeight: number;
|
||||
}): number {
|
||||
const fragmentIndex = Math.min(
|
||||
input.cell.fragments.length - 1,
|
||||
Math.max(0, Math.floor(input.y / input.lineHeight)),
|
||||
);
|
||||
const fragment = input.cell.fragments[fragmentIndex];
|
||||
const fragment = fragmentAtPoint(input);
|
||||
if (!fragment) return 0;
|
||||
let width = 0;
|
||||
for (const grapheme of fragment.graphemes) {
|
||||
@@ -72,6 +65,36 @@ export function characterOffsetAtPoint(input: {
|
||||
return fragment.end;
|
||||
}
|
||||
|
||||
/** The grapheme under the pointer, unlike `characterOffsetAtPoint`, which snaps to the nearest caret. */
|
||||
export function graphemeOffsetAtPoint(input: {
|
||||
cell: DiffCell;
|
||||
x: number;
|
||||
y: number;
|
||||
lineHeight: number;
|
||||
}): number {
|
||||
const fragment = fragmentAtPoint(input);
|
||||
if (!fragment) return 0;
|
||||
let width = 0;
|
||||
for (const grapheme of fragment.graphemes) {
|
||||
if (input.x < width + grapheme.width) return grapheme.start;
|
||||
width += grapheme.width;
|
||||
}
|
||||
const lastGrapheme = fragment.graphemes.at(-1);
|
||||
return lastGrapheme ? lastGrapheme.start : fragment.start;
|
||||
}
|
||||
|
||||
function fragmentAtPoint(input: {
|
||||
cell: DiffCell;
|
||||
y: number;
|
||||
lineHeight: number;
|
||||
}): DiffFragment | null {
|
||||
const fragmentIndex = Math.min(
|
||||
input.cell.fragments.length - 1,
|
||||
Math.max(0, Math.floor(input.y / input.lineHeight)),
|
||||
);
|
||||
return input.cell.fragments[fragmentIndex] ?? null;
|
||||
}
|
||||
|
||||
function rowAtOffset(
|
||||
rows: readonly DiffDocumentModel["rows"][number][],
|
||||
start: number,
|
||||
@@ -163,7 +186,7 @@ export function selectAllSource(
|
||||
return first && last ? { anchor: first, focus: last } : null;
|
||||
}
|
||||
|
||||
function comparePosition(left: DiffCharacterPosition, right: DiffCharacterPosition): number {
|
||||
export function comparePosition(left: DiffCharacterPosition, right: DiffCharacterPosition): number {
|
||||
return (
|
||||
left.rowIndex - right.rowIndex ||
|
||||
left.cellIndex - right.cellIndex ||
|
||||
|
||||
@@ -1,5 +1,38 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { hasPointerDragStarted } from "./pointer-gesture";
|
||||
import {
|
||||
hasPointerDragStarted,
|
||||
lineSelectionForDrag,
|
||||
wordSelectionForDrag,
|
||||
type LineAtPosition,
|
||||
type WordAtPosition,
|
||||
} from "./pointer-gesture";
|
||||
import type { DiffCharacterPosition } from "./types";
|
||||
|
||||
function positionAt(offset: number, rowIndex = 1, cellIndex = 0): DiffCharacterPosition {
|
||||
return { fileIndex: 0, rowIndex, cellIndex, side: "new", sourceOffset: offset };
|
||||
}
|
||||
|
||||
function wordAt(
|
||||
input: { offset: number; start: number; end: number },
|
||||
rowIndex = 1,
|
||||
cellIndex = 0,
|
||||
): WordAtPosition {
|
||||
return {
|
||||
position: positionAt(input.offset, rowIndex, cellIndex),
|
||||
word: { start: input.start, end: input.end },
|
||||
};
|
||||
}
|
||||
|
||||
function lineAt(
|
||||
input: { offset: number; end: number },
|
||||
rowIndex = 1,
|
||||
cellIndex = 0,
|
||||
): LineAtPosition {
|
||||
return {
|
||||
position: positionAt(input.offset, rowIndex, cellIndex),
|
||||
end: input.end,
|
||||
};
|
||||
}
|
||||
|
||||
describe("diff pointer gesture", () => {
|
||||
it("classifies pointer movement as a drag without requiring a character change", () => {
|
||||
@@ -26,3 +59,99 @@ describe("diff pointer gesture", () => {
|
||||
).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("diff word drag selection", () => {
|
||||
it("extends forward from the start of the anchor word to the end of the focus word", () => {
|
||||
expect(
|
||||
wordSelectionForDrag({
|
||||
anchor: wordAt({ offset: 8, start: 6, end: 11 }),
|
||||
focus: wordAt({ offset: 14, start: 12, end: 19 }),
|
||||
}),
|
||||
).toEqual({
|
||||
anchor: positionAt(6),
|
||||
focus: positionAt(19),
|
||||
});
|
||||
});
|
||||
|
||||
it("extends backward from the end of the anchor word to the start of the focus word", () => {
|
||||
expect(
|
||||
wordSelectionForDrag({
|
||||
anchor: wordAt({ offset: 15, start: 13, end: 20 }),
|
||||
focus: wordAt({ offset: 7, start: 6, end: 11 }),
|
||||
}),
|
||||
).toEqual({
|
||||
anchor: positionAt(6),
|
||||
focus: positionAt(20),
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps the anchor word whole while the pointer stays inside it", () => {
|
||||
const anchor = wordAt({ offset: 10, start: 6, end: 11 });
|
||||
const expected = { anchor: positionAt(6), focus: positionAt(11) };
|
||||
expect(
|
||||
wordSelectionForDrag({ anchor, focus: wordAt({ offset: 7, start: 6, end: 11 }) }),
|
||||
).toEqual(expected);
|
||||
expect(
|
||||
wordSelectionForDrag({ anchor, focus: wordAt({ offset: 9, start: 6, end: 11 }) }),
|
||||
).toEqual(expected);
|
||||
});
|
||||
|
||||
it("snaps both ends to word boundaries across rows", () => {
|
||||
expect(
|
||||
wordSelectionForDrag({
|
||||
anchor: wordAt({ offset: 3, start: 2, end: 5 }, 1),
|
||||
focus: wordAt({ offset: 2, start: 0, end: 4 }, 3),
|
||||
}),
|
||||
).toEqual({
|
||||
anchor: positionAt(2, 1),
|
||||
focus: positionAt(4, 3),
|
||||
});
|
||||
expect(
|
||||
wordSelectionForDrag({
|
||||
anchor: wordAt({ offset: 2, start: 0, end: 4 }, 3),
|
||||
focus: wordAt({ offset: 3, start: 2, end: 5 }, 1),
|
||||
}),
|
||||
).toEqual({
|
||||
anchor: positionAt(2, 1),
|
||||
focus: positionAt(4, 3),
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("diff line drag selection", () => {
|
||||
it("selects the whole clicked source line", () => {
|
||||
expect(
|
||||
lineSelectionForDrag({
|
||||
anchor: lineAt({ offset: 3, end: 12 }),
|
||||
focus: lineAt({ offset: 3, end: 12 }),
|
||||
}),
|
||||
).toEqual({
|
||||
anchor: positionAt(0),
|
||||
focus: positionAt(12),
|
||||
});
|
||||
});
|
||||
|
||||
it("extends forward to the end of the focus line while keeping the anchor line", () => {
|
||||
expect(
|
||||
lineSelectionForDrag({
|
||||
anchor: lineAt({ offset: 3, end: 12 }),
|
||||
focus: lineAt({ offset: 1, end: 7 }, 3),
|
||||
}),
|
||||
).toEqual({
|
||||
anchor: positionAt(0),
|
||||
focus: positionAt(7, 3),
|
||||
});
|
||||
});
|
||||
|
||||
it("extends backward from the start of the focus line to the end of the anchor line", () => {
|
||||
expect(
|
||||
lineSelectionForDrag({
|
||||
anchor: lineAt({ offset: 5, end: 9 }, 3),
|
||||
focus: lineAt({ offset: 2, end: 12 }, 1),
|
||||
}),
|
||||
).toEqual({
|
||||
anchor: positionAt(0, 1),
|
||||
focus: positionAt(9, 3),
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,5 +1,46 @@
|
||||
import { comparePosition } from "./hit-testing";
|
||||
import type { DiffCharacterPosition, DiffSelection } from "./types";
|
||||
import type { SourceWordRange } from "./word-boundaries";
|
||||
|
||||
const DRAG_THRESHOLD = 4;
|
||||
|
||||
export interface WordAtPosition {
|
||||
position: DiffCharacterPosition;
|
||||
word: SourceWordRange;
|
||||
}
|
||||
|
||||
export interface LineAtPosition {
|
||||
position: DiffCharacterPosition;
|
||||
/** UTF-16 length of the canonical source line. */
|
||||
end: number;
|
||||
}
|
||||
|
||||
export function wordSelectionForDrag(input: {
|
||||
anchor: WordAtPosition;
|
||||
focus: WordAtPosition;
|
||||
}): DiffSelection {
|
||||
const isBackward = comparePosition(input.focus.position, input.anchor.position) < 0;
|
||||
const start = isBackward ? input.focus : input.anchor;
|
||||
const end = isBackward ? input.anchor : input.focus;
|
||||
return {
|
||||
anchor: { ...start.position, sourceOffset: start.word.start },
|
||||
focus: { ...end.position, sourceOffset: end.word.end },
|
||||
};
|
||||
}
|
||||
|
||||
export function lineSelectionForDrag(input: {
|
||||
anchor: LineAtPosition;
|
||||
focus: LineAtPosition;
|
||||
}): DiffSelection {
|
||||
const isBackward = comparePosition(input.focus.position, input.anchor.position) < 0;
|
||||
const start = isBackward ? input.focus : input.anchor;
|
||||
const end = isBackward ? input.anchor : input.focus;
|
||||
return {
|
||||
anchor: { ...start.position, sourceOffset: 0 },
|
||||
focus: { ...end.position, sourceOffset: end.end },
|
||||
};
|
||||
}
|
||||
|
||||
export function hasPointerDragStarted(input: {
|
||||
startX: number;
|
||||
startY: number;
|
||||
|
||||
@@ -35,7 +35,13 @@ import {
|
||||
resolveRelayoutScrollTop,
|
||||
} from "./model";
|
||||
import { paintWebFileHeader, paintWebViewport } from "./paint.web";
|
||||
import { hasPointerDragStarted } from "./pointer-gesture";
|
||||
import {
|
||||
hasPointerDragStarted,
|
||||
lineSelectionForDrag,
|
||||
wordSelectionForDrag,
|
||||
type LineAtPosition,
|
||||
type WordAtPosition,
|
||||
} from "./pointer-gesture";
|
||||
import {
|
||||
createMeasuredAdvances,
|
||||
createAdditiveAdvances,
|
||||
@@ -44,6 +50,8 @@ import {
|
||||
} from "./text-measurement";
|
||||
import { retainDiffViewport } from "./viewport";
|
||||
import type {
|
||||
DiffCell,
|
||||
DiffCharacterPosition,
|
||||
DiffHit,
|
||||
DiffFileSection,
|
||||
DiffSelection,
|
||||
@@ -51,6 +59,7 @@ import type {
|
||||
DiffTypography,
|
||||
TextMeasurer,
|
||||
} from "./types";
|
||||
import { wordRangeAtOffset } from "./word-boundaries";
|
||||
import { useDiffDocumentWorkspaceCache } from "./workspace-cache";
|
||||
|
||||
const DEFAULT_MONO_STACK = "ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace";
|
||||
@@ -104,6 +113,11 @@ export function DiffSurface(props: DiffSurfaceProps) {
|
||||
startY: number;
|
||||
moved: boolean;
|
||||
dismissSelectionOnClick: boolean;
|
||||
granularity:
|
||||
| { kind: "character" }
|
||||
| { kind: "word"; anchor: WordAtPosition }
|
||||
| { kind: "line"; anchor: LineAtPosition };
|
||||
pointerType: string;
|
||||
} | null>(null);
|
||||
const frameRef = useRef<number | null>(null);
|
||||
const activeHeaderPathRef = useRef<string | null>(null);
|
||||
@@ -591,6 +605,31 @@ export function DiffSurface(props: DiffSurfaceProps) {
|
||||
desiredTypography,
|
||||
setSelection,
|
||||
]);
|
||||
const cellAt = useCallback((position: DiffCharacterPosition): DiffCell | null => {
|
||||
const currentModel = modelRef.current;
|
||||
if (!currentModel) return null;
|
||||
const row = currentModel.rows[position.rowIndex];
|
||||
return row?.kind === "line" ? row.cells[position.cellIndex] : null;
|
||||
}, []);
|
||||
const wordAt = useCallback(
|
||||
(hit: Extract<DiffHit, { kind: "cell" }>): WordAtPosition | null => {
|
||||
const cell = cellAt(hit.position);
|
||||
if (!cell) return null;
|
||||
return {
|
||||
position: { ...hit.position, sourceOffset: hit.graphemeOffset },
|
||||
word: wordRangeAtOffset(cell.content, hit.graphemeOffset),
|
||||
};
|
||||
},
|
||||
[cellAt],
|
||||
);
|
||||
const lineAt = useCallback(
|
||||
(hit: Extract<DiffHit, { kind: "cell" }>): LineAtPosition | null => {
|
||||
const cell = cellAt(hit.position);
|
||||
if (!cell) return null;
|
||||
return { position: hit.position, end: cell.content.length };
|
||||
},
|
||||
[cellAt],
|
||||
);
|
||||
const pointerDown = useCallback(
|
||||
(event: React.PointerEvent<HTMLDivElement>) => {
|
||||
if (event.button !== 0) return;
|
||||
@@ -602,18 +641,18 @@ export function DiffSurface(props: DiffSurfaceProps) {
|
||||
)
|
||||
)
|
||||
return;
|
||||
const dismissSelectionOnClick = selectionRef.current !== null;
|
||||
if (dismissSelectionOnClick) {
|
||||
setSelection(null);
|
||||
}
|
||||
const hit = pointHit(event);
|
||||
const hadSelection = selectionRef.current !== null;
|
||||
if (hadSelection) setSelection(null);
|
||||
if (hit?.kind !== "cell") return;
|
||||
dragRef.current = {
|
||||
anchor: hit.position,
|
||||
startX: event.clientX,
|
||||
startY: event.clientY,
|
||||
moved: false,
|
||||
dismissSelectionOnClick,
|
||||
dismissSelectionOnClick: hadSelection,
|
||||
granularity: { kind: "character" },
|
||||
pointerType: event.pointerType,
|
||||
};
|
||||
setSelection({ anchor: hit.position, focus: hit.position });
|
||||
event.currentTarget.focus();
|
||||
@@ -621,6 +660,38 @@ export function DiffSurface(props: DiffSurfaceProps) {
|
||||
},
|
||||
[pointHit, setSelection],
|
||||
);
|
||||
// The native click count honors the OS double-click setting and arrives on the
|
||||
// second mousedown, after pointerdown has opened the character drag.
|
||||
const mouseDown = useCallback(
|
||||
(event: React.MouseEvent<HTMLDivElement>) => {
|
||||
const drag = dragRef.current;
|
||||
if (!drag || event.button !== 0 || event.detail < 2 || drag.pointerType === "touch") return;
|
||||
const target = event.target;
|
||||
if (
|
||||
target instanceof Element &&
|
||||
target.closest(
|
||||
'[data-diff-header="true"], [data-diff-review="true"], [role="menuitem"], button, input, textarea',
|
||||
)
|
||||
)
|
||||
return;
|
||||
const hit = pointHitAt(event.clientX, event.clientY);
|
||||
if (hit?.kind !== "cell") return;
|
||||
if (event.detail >= 3) {
|
||||
const lineAnchor = lineAt(hit);
|
||||
if (!lineAnchor) return;
|
||||
drag.granularity = { kind: "line", anchor: lineAnchor };
|
||||
drag.dismissSelectionOnClick = false;
|
||||
setSelection(lineSelectionForDrag({ anchor: lineAnchor, focus: lineAnchor }));
|
||||
return;
|
||||
}
|
||||
const wordAnchor = wordAt(hit);
|
||||
if (!wordAnchor) return;
|
||||
drag.granularity = { kind: "word", anchor: wordAnchor };
|
||||
drag.dismissSelectionOnClick = false;
|
||||
setSelection(wordSelectionForDrag({ anchor: wordAnchor, focus: wordAnchor }));
|
||||
},
|
||||
[lineAt, pointHitAt, setSelection, wordAt],
|
||||
);
|
||||
const updateActiveHeader = useCallback(
|
||||
(target: EventTarget | null) => {
|
||||
const header =
|
||||
@@ -634,6 +705,32 @@ export function DiffSurface(props: DiffSurfaceProps) {
|
||||
},
|
||||
[paintStickyHeaderPool, schedulePaint],
|
||||
);
|
||||
const updateHoveredAffordance = useCallback(
|
||||
(hit: Extract<DiffHit, { kind: "cell" }>, clientX: number) => {
|
||||
const row = modelRef.current?.rows[hit.position.rowIndex];
|
||||
const file = modelRef.current?.files[hit.position.fileIndex];
|
||||
const sideIndex =
|
||||
row?.kind === "line" && row.cells.length === 2 && hit.position.side === "new" ? 1 : 0;
|
||||
if (row && file) {
|
||||
const columnWidth = viewport.width / (row.kind === "line" ? row.cells.length : 1);
|
||||
const gutterBorder = sideIndex * columnWidth + file.gutterWidth;
|
||||
const rootBounds = rootRef.current?.getBoundingClientRect();
|
||||
const pointerX = rootBounds ? clientX - rootBounds.left : Number.NaN;
|
||||
if (hit.target && Number.isFinite(pointerX)) {
|
||||
hasHoveredAffordanceRef.current = true;
|
||||
setHoveredAffordance({
|
||||
hit,
|
||||
left: gutterBorder - 12,
|
||||
top: row.top - scrollTopRef.current + (modelRef.current!.lineHeight - 22) / 2,
|
||||
});
|
||||
return;
|
||||
}
|
||||
}
|
||||
hasHoveredAffordanceRef.current = false;
|
||||
setHoveredAffordance(null);
|
||||
},
|
||||
[viewport.width],
|
||||
);
|
||||
const pointerMove = useCallback(
|
||||
(event: React.PointerEvent<HTMLDivElement>) => {
|
||||
updateActiveHeader(event.target);
|
||||
@@ -649,35 +746,29 @@ export function DiffSurface(props: DiffSurfaceProps) {
|
||||
}
|
||||
const hit = pointHit(event);
|
||||
if (hit?.kind === "cell") {
|
||||
const row = modelRef.current?.rows[hit.position.rowIndex];
|
||||
const file = modelRef.current?.files[hit.position.fileIndex];
|
||||
const sideIndex =
|
||||
row?.kind === "line" && row.cells.length === 2 && hit.position.side === "new" ? 1 : 0;
|
||||
if (row && file) {
|
||||
const columnWidth = viewport.width / (row.kind === "line" ? row.cells.length : 1);
|
||||
const gutterBorder = sideIndex * columnWidth + file.gutterWidth;
|
||||
const rootBounds = rootRef.current?.getBoundingClientRect();
|
||||
const pointerX = rootBounds ? event.clientX - rootBounds.left : Number.NaN;
|
||||
if (hit.target && Number.isFinite(pointerX)) {
|
||||
hasHoveredAffordanceRef.current = true;
|
||||
setHoveredAffordance({
|
||||
hit,
|
||||
left: gutterBorder - 12,
|
||||
top: row.top - scrollTopRef.current + (modelRef.current!.lineHeight - 22) / 2,
|
||||
});
|
||||
} else {
|
||||
hasHoveredAffordanceRef.current = false;
|
||||
setHoveredAffordance(null);
|
||||
}
|
||||
}
|
||||
updateHoveredAffordance(hit, event.clientX);
|
||||
} else {
|
||||
hasHoveredAffordanceRef.current = false;
|
||||
setHoveredAffordance(null);
|
||||
}
|
||||
if (!drag || hit?.kind !== "cell") return;
|
||||
if (drag.granularity.kind === "word") {
|
||||
const focusWord = wordAt(hit);
|
||||
if (focusWord) {
|
||||
setSelection(wordSelectionForDrag({ anchor: drag.granularity.anchor, focus: focusWord }));
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (drag.granularity.kind === "line") {
|
||||
const focusLine = lineAt(hit);
|
||||
if (focusLine) {
|
||||
setSelection(lineSelectionForDrag({ anchor: drag.granularity.anchor, focus: focusLine }));
|
||||
}
|
||||
return;
|
||||
}
|
||||
setSelection({ anchor: drag.anchor, focus: hit.position });
|
||||
},
|
||||
[pointHit, setSelection, updateActiveHeader, viewport.width],
|
||||
[lineAt, pointHit, setSelection, updateActiveHeader, updateHoveredAffordance, wordAt],
|
||||
);
|
||||
const pointerUp = useCallback(
|
||||
(event: React.PointerEvent<HTMLDivElement>) => {
|
||||
@@ -822,6 +913,7 @@ export function DiffSurface(props: DiffSurfaceProps) {
|
||||
data-overlay-scrollbar="true"
|
||||
tabIndex={0}
|
||||
onPointerDown={pointerDown}
|
||||
onMouseDown={mouseDown}
|
||||
onPointerMove={pointerMove}
|
||||
onPointerUp={pointerUp}
|
||||
onPointerCancel={cancelPointer}
|
||||
|
||||
@@ -208,6 +208,8 @@ export type DiffHit =
|
||||
kind: "cell";
|
||||
target: ReviewableDiffTarget | null;
|
||||
position: DiffCharacterPosition;
|
||||
/** The grapheme under the pointer, which word gestures select from. */
|
||||
graphemeOffset: number;
|
||||
};
|
||||
|
||||
export interface DiffSelection {
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
import { CharCategory, EditorState } from "@codemirror/state";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { wordRangeAtOffset } from "./word-boundaries";
|
||||
|
||||
describe("diff word boundaries", () => {
|
||||
it("selects the identifier under the offset", () => {
|
||||
expect(wordRangeAtOffset("alpha bravo charlie", 8)).toEqual({ start: 6, end: 11 });
|
||||
});
|
||||
|
||||
it("selects the surrounding whitespace when the offset is inside a run of spaces", () => {
|
||||
expect(wordRangeAtOffset("alpha bravo", 6)).toEqual({ start: 5, end: 8 });
|
||||
});
|
||||
|
||||
it("selects a run of punctuation without merging it into neighboring words", () => {
|
||||
expect(wordRangeAtOffset("call(foo, bar)", 4)).toEqual({ start: 4, end: 5 });
|
||||
expect(wordRangeAtOffset("call(foo, bar)", 6)).toEqual({ start: 5, end: 8 });
|
||||
expect(wordRangeAtOffset("fn()", 3)).toEqual({ start: 2, end: 4 });
|
||||
expect(wordRangeAtOffset("foo.bar", 3)).toEqual({ start: 3, end: 4 });
|
||||
expect(wordRangeAtOffset("foo.bar", 5)).toEqual({ start: 4, end: 7 });
|
||||
});
|
||||
|
||||
it("selects the final word when the offset reaches the end of the line", () => {
|
||||
expect(wordRangeAtOffset("alpha bravo", 11)).toEqual({ start: 6, end: 11 });
|
||||
expect(wordRangeAtOffset("alpha bravo", 99)).toEqual({ start: 6, end: 11 });
|
||||
});
|
||||
|
||||
it("selects the leading word when the offset is clamped at the start", () => {
|
||||
expect(wordRangeAtOffset("alpha bravo", 0)).toEqual({ start: 0, end: 5 });
|
||||
});
|
||||
|
||||
it("keeps combining sequences and emoji clusters whole", () => {
|
||||
const combining = "ai\u0301b";
|
||||
expect(wordRangeAtOffset(combining, 1)).toEqual({ start: 0, end: 4 });
|
||||
expect(wordRangeAtOffset(combining, 2)).toEqual({ start: 0, end: 4 });
|
||||
|
||||
const emoji = "hi 👨👩👧👦 there";
|
||||
const emojiStart = emoji.indexOf("👨");
|
||||
expect(wordRangeAtOffset(emoji, emojiStart)).toEqual({
|
||||
start: emojiStart,
|
||||
end: emojiStart + "👨👩👧👦".length,
|
||||
});
|
||||
});
|
||||
|
||||
it("treats tabs as whitespace and returns an empty range for empty content", () => {
|
||||
expect(wordRangeAtOffset("\tfoo", 0)).toEqual({ start: 0, end: 1 });
|
||||
expect(wordRangeAtOffset("", 0)).toEqual({ start: 0, end: 0 });
|
||||
});
|
||||
|
||||
it("matches CodeMirror word runs for offsets inside a word", () => {
|
||||
const content = "alpha bravo charlie";
|
||||
const state = EditorState.create({ doc: content });
|
||||
for (const offset of [0, 2, 8, 14, 18]) {
|
||||
const word = state.wordAt(offset);
|
||||
expect(word).not.toBeNull();
|
||||
expect(wordRangeAtOffset(content, offset)).toEqual({ start: word!.from, end: word!.to });
|
||||
}
|
||||
});
|
||||
|
||||
it("classifies leading graphemes with CodeMirror character categories", () => {
|
||||
const categorize = EditorState.create({ doc: "" }).charCategorizer(0);
|
||||
const clusters = ["a", "1", "_", "中", "👨👩👧👦", "\u0301", "\ufe0f", "\u00a0"];
|
||||
for (const cluster of clusters) {
|
||||
const isWord = categorize(cluster) === CharCategory.Word;
|
||||
expect(wordRangeAtOffset(`${cluster}x`, 0)).toEqual({
|
||||
start: 0,
|
||||
end: isWord ? cluster.length + 1 : cluster.length,
|
||||
});
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,88 @@
|
||||
import { CharCategory, EditorState } from "@codemirror/state";
|
||||
import { graphemeBoundaries } from "./model";
|
||||
|
||||
export interface SourceWordRange {
|
||||
start: number;
|
||||
end: number;
|
||||
}
|
||||
|
||||
interface SourceText {
|
||||
state: EditorState;
|
||||
boundaries: number[];
|
||||
categorize: (cluster: string) => CharCategory;
|
||||
}
|
||||
|
||||
// Word gestures query the same line repeatedly while dragging. Keep a bounded
|
||||
// set of parsed sources instead of rebuilding an EditorState on every move.
|
||||
const SOURCE_CACHE_LIMIT = 8;
|
||||
const sources = new Map<string, SourceText>();
|
||||
|
||||
/**
|
||||
* The run around `offset` that a double click selects: a word, a run of
|
||||
* whitespace, or a run of punctuation. Runs never cross grapheme boundaries.
|
||||
*/
|
||||
export function wordRangeAtOffset(content: string, offset: number): SourceWordRange {
|
||||
if (content.length === 0) return { start: 0, end: 0 };
|
||||
const source = sourceText(content);
|
||||
const { boundaries } = source;
|
||||
const clusterIndex = clusterIndexAt(boundaries, offset);
|
||||
const category = source.categorize(clusterText(content, boundaries, clusterIndex));
|
||||
if (category === CharCategory.Word) {
|
||||
const word = source.state.wordAt(boundaries[clusterIndex]);
|
||||
if (word) return { start: word.from, end: word.to };
|
||||
}
|
||||
let first = clusterIndex;
|
||||
while (first > 0 && categoryAt(source, content, boundaries, first - 1) === category) first -= 1;
|
||||
let last = clusterIndex;
|
||||
while (
|
||||
last < boundaries.length - 2 &&
|
||||
categoryAt(source, content, boundaries, last + 1) === category
|
||||
)
|
||||
last += 1;
|
||||
return { start: boundaries[first], end: boundaries[last + 1] };
|
||||
}
|
||||
|
||||
function sourceText(content: string): SourceText {
|
||||
const cached = sources.get(content);
|
||||
if (cached) {
|
||||
sources.delete(content);
|
||||
sources.set(content, cached);
|
||||
return cached;
|
||||
}
|
||||
const state = EditorState.create({ doc: content });
|
||||
const source: SourceText = {
|
||||
state,
|
||||
boundaries: graphemeBoundaries(content),
|
||||
categorize: state.charCategorizer(0),
|
||||
};
|
||||
sources.set(content, source);
|
||||
if (sources.size > SOURCE_CACHE_LIMIT) {
|
||||
const oldest = sources.keys().next();
|
||||
if (!oldest.done) sources.delete(oldest.value);
|
||||
}
|
||||
return source;
|
||||
}
|
||||
|
||||
function clusterIndexAt(boundaries: readonly number[], offset: number): number {
|
||||
let low = 0;
|
||||
let high = boundaries.length - 2;
|
||||
while (low < high) {
|
||||
const middle = (low + high + 1) >>> 1;
|
||||
if (boundaries[middle] <= offset) low = middle;
|
||||
else high = middle - 1;
|
||||
}
|
||||
return low;
|
||||
}
|
||||
|
||||
function categoryAt(
|
||||
source: SourceText,
|
||||
content: string,
|
||||
boundaries: readonly number[],
|
||||
index: number,
|
||||
): CharCategory {
|
||||
return source.categorize(clusterText(content, boundaries, index));
|
||||
}
|
||||
|
||||
function clusterText(content: string, boundaries: readonly number[], index: number): string {
|
||||
return content.slice(boundaries[index], boundaries[index + 1]);
|
||||
}
|
||||
@@ -150,3 +150,21 @@ describe("ACP provider catalog", () => {
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
it("adds bundled goose on capable hosts and uses the ACP config on older hosts", () => {
|
||||
const goose = findProvider("goose");
|
||||
expect(buildAcpProviderConfigPatch(goose, (feature) => feature === "gooseProvider")).toEqual({
|
||||
providers: { goose: { enabled: true } },
|
||||
});
|
||||
expect(buildAcpProviderConfigPatch(goose)).toEqual({
|
||||
providers: {
|
||||
goose: {
|
||||
extends: "acp",
|
||||
label: "goose",
|
||||
description: goose.description,
|
||||
command: ["goose", "acp"],
|
||||
env: {},
|
||||
},
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
@@ -19,12 +19,16 @@ export function buildAcpProviderConfigPatch(
|
||||
hostSupports: (feature: HostFeatureName) => boolean = () => false,
|
||||
): MutableDaemonConfigPatch {
|
||||
if (entry.bundledProvider) {
|
||||
const feature = entry.bundledProvider.hostFeature;
|
||||
if (hostSupports(feature)) {
|
||||
return { providers: { [entry.id]: { enabled: true } } };
|
||||
}
|
||||
// COMPAT(gooseProvider): added in v0.17.0, remove after 2027-05-20 once host floor includes the bundled adapter.
|
||||
// COMPAT(hopliteProvider): added after v0.11.2, remove after 2027-04-15 once host floor includes the bundled adapter.
|
||||
// COMPAT(fxProvider): added after v0.15.3, remove after 2027-05-09 once host floor includes the bundled adapter.
|
||||
if (!hostSupports(entry.bundledProvider.hostFeature)) {
|
||||
if (feature !== "gooseProvider") {
|
||||
throw new Error(`Update the host to add ${entry.title}.`);
|
||||
}
|
||||
return { providers: { [entry.id]: { enabled: true } } };
|
||||
}
|
||||
return {
|
||||
providers: {
|
||||
|
||||
@@ -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([]);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -23,6 +23,8 @@ import { z } from "zod";
|
||||
import type {
|
||||
AcpConfigAccess,
|
||||
AcpConfigChange,
|
||||
AcpConfigureContext,
|
||||
AcpRequest,
|
||||
AcpToolCallSnapshot,
|
||||
AcpTransformer,
|
||||
AcpVendorUpdate,
|
||||
@@ -261,10 +263,10 @@ async function discover(
|
||||
});
|
||||
try {
|
||||
let catalog = await runtime.discover(input.cwd);
|
||||
const config = runtime.configAccess();
|
||||
const context = runtime.configContext();
|
||||
for (const transformer of state.options.transformers ?? []) {
|
||||
if (transformer.discover) {
|
||||
catalog = await transformer.discover(catalog, { sessionId: "catalog", config });
|
||||
catalog = await transformer.discover(catalog, context);
|
||||
}
|
||||
}
|
||||
state.emit({ type: "catalog", requestId: input.requestId, catalog });
|
||||
@@ -902,16 +904,13 @@ class AcpRuntime {
|
||||
this.autoAccept = enableAutoAccept;
|
||||
return;
|
||||
}
|
||||
const access = this.configAccess();
|
||||
const context: AcpConfigureContext = {
|
||||
...this.configContext(),
|
||||
catalog: () => toProviderCatalog(this.modes, this.configOptions),
|
||||
apply: (nativeChange) => this.applyNativeConfigChange(nativeChange),
|
||||
};
|
||||
for (const transformer of this.transformers) {
|
||||
if (
|
||||
(await transformer.configure?.(change, {
|
||||
sessionId: this.options.boundarySessionId,
|
||||
config: access,
|
||||
catalog: () => toProviderCatalog(this.modes, this.configOptions),
|
||||
apply: (nativeChange) => this.applyNativeConfigChange(nativeChange),
|
||||
})) === "handled"
|
||||
) {
|
||||
if ((await transformer.configure?.(change, context)) === "handled") {
|
||||
return;
|
||||
}
|
||||
}
|
||||
@@ -951,7 +950,20 @@ class AcpRuntime {
|
||||
this.configOptions = response.configOptions;
|
||||
}
|
||||
|
||||
configAccess(): AcpConfigAccess {
|
||||
configContext() {
|
||||
return {
|
||||
sessionId: this.options.boundarySessionId,
|
||||
config: this.configAccess(),
|
||||
request: this.request,
|
||||
};
|
||||
}
|
||||
|
||||
private readonly request: AcpRequest = async (method, params) =>
|
||||
jsonValue(
|
||||
await this.call(this.connection.extMethod(method, params as Record<string, unknown>)),
|
||||
);
|
||||
|
||||
private configAccess(): AcpConfigAccess {
|
||||
return {
|
||||
read: async () => configValues(this.configOptions),
|
||||
set: async (id, value) => {
|
||||
@@ -989,6 +1001,10 @@ class AcpRuntime {
|
||||
modes: [...config.modes, { ...autoAcceptMode.mode, isUnattended: true }],
|
||||
};
|
||||
}
|
||||
const context = { sessionId: this.options.boundarySessionId };
|
||||
for (const transformer of this.transformers) {
|
||||
config = transformer.config?.(config, context) ?? config;
|
||||
}
|
||||
this.emit({
|
||||
type: "session.config",
|
||||
sessionId: this.options.boundarySessionId,
|
||||
|
||||
@@ -2320,3 +2320,135 @@ describe("ACP session history replay", () => {
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
it("sends extension requests from discovery and configure and preserves JSON-RPC errors", async () => {
|
||||
const { connector, instances } = connectorHarness({
|
||||
handleRequest(instance, request) {
|
||||
if (request.method === "_example/catalog") {
|
||||
instance.respond(request, { model: "vendor-model" });
|
||||
return true;
|
||||
}
|
||||
if (request.method === "_example/select") {
|
||||
instance.reject(request, "Vendor rejected the selection");
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
},
|
||||
});
|
||||
const registration = runAcpProvider({
|
||||
id: "extensions",
|
||||
label: "Extensions",
|
||||
connector,
|
||||
transformers: [
|
||||
{
|
||||
async discover(catalog, { request }) {
|
||||
expect(await request("_example/catalog", { scope: "all" })).toEqual({
|
||||
model: "vendor-model",
|
||||
});
|
||||
return { ...catalog, defaultModel: "vendor-model" };
|
||||
},
|
||||
async configure(change, { request }) {
|
||||
await expect(request("_example/select", { model: change.value })).rejects.toMatchObject({
|
||||
code: -32603,
|
||||
message: "Vendor rejected the selection",
|
||||
});
|
||||
return "handled";
|
||||
},
|
||||
},
|
||||
],
|
||||
});
|
||||
const connection = await registration.connect({
|
||||
versions: [1],
|
||||
capabilities: ["session.configure"],
|
||||
});
|
||||
const events: ProviderEvent[] = [];
|
||||
connection.onEvent((event) => events.push(event));
|
||||
try {
|
||||
await connection.send({ type: "catalog", requestId: "catalog" });
|
||||
expect(
|
||||
await waitForEvent(
|
||||
events,
|
||||
(event) => event.type === "catalog" || event.type === "request.failed",
|
||||
),
|
||||
).toMatchObject({ type: "catalog", catalog: { defaultModel: "vendor-model" } });
|
||||
expect(instances[1].requests).toContainEqual(
|
||||
expect.objectContaining({
|
||||
method: "_example/catalog",
|
||||
params: { scope: "all" },
|
||||
}),
|
||||
);
|
||||
|
||||
const input = openInput();
|
||||
await connection.send({ ...input, config: { ...input.config, model: "vendor-model" } });
|
||||
expect(
|
||||
await waitForEvent(
|
||||
events,
|
||||
(event) => event.type === "session.ready" || event.type === "request.failed",
|
||||
),
|
||||
).toMatchObject({ type: "session.ready" });
|
||||
expect(instances[2].requests).toContainEqual(
|
||||
expect.objectContaining({
|
||||
method: "_example/select",
|
||||
params: { model: "vendor-model" },
|
||||
}),
|
||||
);
|
||||
} finally {
|
||||
await connection.close();
|
||||
}
|
||||
});
|
||||
|
||||
it("rewrites the session-ready, notification and configure-commit config snapshots", async () => {
|
||||
const modelOption = {
|
||||
id: "model",
|
||||
name: "Model",
|
||||
category: "model",
|
||||
type: "select",
|
||||
currentValue: "first",
|
||||
options: ["first", "second", "third"].map((value) => ({ name: value, value })),
|
||||
};
|
||||
const { connector, instances } = connectorHarness({ configOptions: [modelOption] });
|
||||
const registration = runAcpProvider({
|
||||
id: "config-transformer",
|
||||
label: "Config Transformer",
|
||||
connector,
|
||||
transformers: [
|
||||
{
|
||||
config(state, { sessionId }) {
|
||||
return { ...state, model: `${sessionId}/${state.model}` };
|
||||
},
|
||||
},
|
||||
],
|
||||
});
|
||||
const connection = await registration.connect({
|
||||
versions: [1],
|
||||
capabilities: ["session.configure"],
|
||||
});
|
||||
const events: ProviderEvent[] = [];
|
||||
connection.onEvent((event) => events.push(event));
|
||||
const models = () =>
|
||||
events.flatMap((event) => (event.type === "session.config" ? [event.config.model] : []));
|
||||
try {
|
||||
await connection.send(openInput());
|
||||
await waitForEvent(events, (event) => event.type === "session.ready");
|
||||
expect(models()).toEqual(["session-1/first"]);
|
||||
|
||||
instances[1].notify("session/update", {
|
||||
sessionId: "connector-session",
|
||||
update: {
|
||||
sessionUpdate: "config_option_update",
|
||||
configOptions: [{ ...modelOption, currentValue: "second" }],
|
||||
},
|
||||
});
|
||||
await expect.poll(models).toEqual(["session-1/first", "session-1/second"]);
|
||||
|
||||
await connection.send({
|
||||
type: "session.configure",
|
||||
requestId: "configure",
|
||||
sessionId: "session-1",
|
||||
changes: { model: "third" },
|
||||
});
|
||||
await expect.poll(models).toEqual(["session-1/first", "session-1/second", "session-1/third"]);
|
||||
} finally {
|
||||
await connection.close();
|
||||
}
|
||||
});
|
||||
|
||||
@@ -70,12 +70,17 @@ export interface AcpConfigAccess {
|
||||
set(id: string, value: JsonValue): Promise<void>;
|
||||
}
|
||||
|
||||
/** Sends an ACP extension request to the agent. Rejects with the agent's JSON-RPC error. */
|
||||
export type AcpRequest = (method: string, params: JsonValue) => Promise<JsonValue>;
|
||||
|
||||
export interface AcpDiscoveryContext extends AcpContext {
|
||||
config: AcpConfigAccess;
|
||||
request: AcpRequest;
|
||||
}
|
||||
|
||||
export interface AcpConfigureContext extends AcpContext {
|
||||
config: AcpConfigAccess;
|
||||
request: AcpRequest;
|
||||
catalog(): ProviderCatalog;
|
||||
apply(change: AcpConfigChange): Promise<void>;
|
||||
}
|
||||
@@ -117,6 +122,8 @@ export interface AcpTransformer {
|
||||
context: AcpDiscoveryContext,
|
||||
): Promise<ProviderCatalog> | ProviderCatalog;
|
||||
configure?(change: AcpConfigChange, context: AcpConfigureContext): Promise<"handled" | "pass">;
|
||||
/** Rewrites every session config snapshot before Paseo sees it. */
|
||||
config?(state: ProviderConfigState, context: AcpContext): ProviderConfigState;
|
||||
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";
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import { z, type ZodType } from "zod";
|
||||
import { ProviderLaunchSchema } from "./provider.js";
|
||||
import type { JsonValue } from "@getpaseo/protocol/agent-types";
|
||||
|
||||
export interface UsageWindow {
|
||||
@@ -65,12 +66,13 @@ export interface UsageAccount {
|
||||
}
|
||||
|
||||
export const UsageScopeSchema = z.discriminatedUnion("kind", [
|
||||
z.object({ kind: z.literal("global") }),
|
||||
z.object({ kind: z.literal("global"), launch: ProviderLaunchSchema.optional() }),
|
||||
z.object({
|
||||
kind: z.literal("session"),
|
||||
provider: z.string(),
|
||||
model: z.string().optional(),
|
||||
env: z.record(z.string(), z.string()),
|
||||
launch: ProviderLaunchSchema.optional(),
|
||||
}),
|
||||
]);
|
||||
export type UsageScope = z.infer<typeof UsageScopeSchema>;
|
||||
@@ -79,6 +81,8 @@ export interface UsageSourceRegistration {
|
||||
id: string;
|
||||
label: string;
|
||||
icon?: string;
|
||||
/** Provider whose resolved launch is needed for discovery. */
|
||||
provider?: string;
|
||||
input: ZodType;
|
||||
/** Accounts for this scope only. The same key in any scope identifies the same account. */
|
||||
discover(scope: UsageScope): Promise<UsageAccount[]>;
|
||||
|
||||
@@ -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>;
|
||||
}
|
||||
@@ -814,7 +814,7 @@ describe("checkout PR schemas", () => {
|
||||
});
|
||||
|
||||
test.each(
|
||||
["hopliteProvider", "fxProvider"].flatMap((name) =>
|
||||
["hopliteProvider", "fxProvider", "gooseProvider"].flatMap((name) =>
|
||||
[undefined, false, true].map((value) => [name, value] as const),
|
||||
),
|
||||
)("accepts optional bundled provider capability (%s: %s)", (name, value) => {
|
||||
|
||||
@@ -4151,6 +4151,8 @@ export const ServerInfoStatusPayloadSchema = z
|
||||
hopliteProvider: z.boolean().optional(),
|
||||
// COMPAT(fxProvider): added after v0.15.3, remove after 2027-05-09 once host floor includes the bundled adapter.
|
||||
fxProvider: z.boolean().optional(),
|
||||
// COMPAT(gooseProvider): added in v0.17.0, remove after 2027-05-20 once host floor includes the bundled adapter.
|
||||
gooseProvider: z.boolean().optional(),
|
||||
// COMPAT(importSessionWorkspaceTarget): added in v0.1.110, remove gate after 2027-01-16.
|
||||
importSessionWorkspaceTarget: z.boolean().optional(),
|
||||
// COMPAT(importSessionSearch): added in v0.8.0, remove gate after 2027-03-02.
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -699,6 +699,7 @@ export interface AgentPermissionResult {
|
||||
}
|
||||
|
||||
export interface AgentUsageSession {
|
||||
launch?: import("@getpaseo/plugin/server/provider").ProviderLaunch;
|
||||
provider: string;
|
||||
model?: string;
|
||||
env: Record<string, string>;
|
||||
@@ -849,6 +850,9 @@ export interface AgentClientUpdateContext extends AgentClientInstallationContext
|
||||
}
|
||||
|
||||
export interface AgentClient {
|
||||
resolveUsageLaunch?(): Promise<
|
||||
import("@getpaseo/plugin/server/provider").ProviderLaunch | undefined
|
||||
>;
|
||||
readonly provider: AgentProvider;
|
||||
readonly capabilities: AgentCapabilityFlags;
|
||||
/**
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -2512,6 +2512,30 @@ describe("plugin provider launch and status", () => {
|
||||
}
|
||||
});
|
||||
|
||||
test("exposes the session launch for usage discovery", async () => {
|
||||
const harness = createProviderHarness();
|
||||
const registry = new PluginAgentClientRegistry(createTestLogger());
|
||||
registry.replace([{ ...harness.registration, command: [process.execPath, "acp"] }]);
|
||||
try {
|
||||
const client = registry.clients()[harness.registration.id]!;
|
||||
const session = await client.createSession(
|
||||
{ provider: harness.registration.id, cwd: "/workspace" },
|
||||
{ env: { HOME: "/session-home" } },
|
||||
);
|
||||
expect(session.usageSession?.()).toMatchObject({
|
||||
provider: harness.registration.id,
|
||||
model: "plugin-model",
|
||||
env: { HOME: "/session-home" },
|
||||
launch: { command: process.execPath, args: ["acp"], env: { HOME: "/session-home" } },
|
||||
sessionKey: expect.any(String),
|
||||
});
|
||||
await session.close();
|
||||
expect(session.usageSession?.()).toBeNull();
|
||||
} finally {
|
||||
await registry.shutdown();
|
||||
}
|
||||
});
|
||||
|
||||
test("resolves relative executable paths before sending launch data", async () => {
|
||||
const harness = createProviderHarness();
|
||||
const launches: Array<ProviderLaunch | undefined> = [];
|
||||
@@ -2764,3 +2788,29 @@ test("plugin provider import launches with runtime MCP servers and returns only
|
||||
await registry.shutdown();
|
||||
}
|
||||
});
|
||||
|
||||
test("resumes a goose session saved by the generic ACP provider", async () => {
|
||||
const logger = createTestLogger();
|
||||
const harness = createProviderHarness();
|
||||
const plugins = new PluginAgentClientRegistry(logger);
|
||||
plugins.replace([{ ...harness.registration, id: "goose" }]);
|
||||
const registry = buildProviderRegistry(logger, { pluginProviders: plugins.definitions() });
|
||||
const client = registry.goose.createClient(logger);
|
||||
|
||||
try {
|
||||
const session = await client.resumeSession(
|
||||
{
|
||||
provider: "goose",
|
||||
sessionId: "native-goose-session",
|
||||
nativeHandle: "native-goose-session",
|
||||
},
|
||||
{ provider: "goose", cwd: "/tmp" },
|
||||
);
|
||||
expect(harness.inputs.findLast((input) => input.type === "session.open")).toMatchObject({
|
||||
persistence: { version: 1, data: { sessionId: "native-goose-session" } },
|
||||
});
|
||||
await session.close();
|
||||
} finally {
|
||||
await plugins.shutdown();
|
||||
}
|
||||
});
|
||||
|
||||
@@ -137,6 +137,7 @@ function isProviderRequestReply(
|
||||
|
||||
class ProviderRuntime {
|
||||
private connection: ProviderConnection | null = null;
|
||||
connectedLaunch: ProviderLaunch | undefined;
|
||||
private connecting: Promise<ProviderConnection> | null = null;
|
||||
private closed = false;
|
||||
private generation = 0;
|
||||
@@ -192,6 +193,12 @@ class ProviderRuntime {
|
||||
return { command: launch.command, args: launch.args, env: launch.env };
|
||||
}
|
||||
|
||||
async resolveUsageLaunch(): Promise<ProviderLaunch | undefined> {
|
||||
const launch = await this.resolveEffectiveLaunch();
|
||||
if (!launch?.resolved) return undefined;
|
||||
return { command: launch.command, args: launch.args, env: launch.env };
|
||||
}
|
||||
|
||||
async inspectInstallation(signal: AbortSignal): Promise<ProviderInspection> {
|
||||
const inspect = this.registration.installation?.inspect;
|
||||
if (!inspect) throw new Error("Provider does not report its installation");
|
||||
@@ -425,8 +432,9 @@ class ProviderRuntime {
|
||||
}
|
||||
|
||||
private async establishConnection(generation: number): Promise<ProviderConnection> {
|
||||
const launch = await this.resolveLaunch();
|
||||
const rawConnection = await this.registration.connect({
|
||||
launch: await this.resolveLaunch(),
|
||||
launch,
|
||||
versions: [PROVIDER_PROTOCOL_VERSION],
|
||||
capabilities: PROVIDER_CAPABILITIES,
|
||||
});
|
||||
@@ -440,6 +448,7 @@ class ProviderRuntime {
|
||||
await rawConnection.close().catch(() => undefined);
|
||||
throw error;
|
||||
}
|
||||
this.connectedLaunch = launch;
|
||||
const connection = normalizeConnection(rawConnection);
|
||||
const unsubscribe = connection.onEvent((event) => this.accept(event));
|
||||
if (this.closed || generation !== this.generation) {
|
||||
@@ -1032,6 +1041,10 @@ class PluginAgentClient implements AgentClient {
|
||||
this.runtime.onSessionOpened((session, opened) => this.acceptChild(session, opened));
|
||||
}
|
||||
|
||||
resolveUsageLaunch() {
|
||||
return this.runtime.resolveUsageLaunch();
|
||||
}
|
||||
|
||||
get capabilities(): AgentCapabilityFlags {
|
||||
return agentCapabilities(this.runtime.negotiatedCapabilities);
|
||||
}
|
||||
@@ -1197,6 +1210,12 @@ class PluginAgentClient implements AgentClient {
|
||||
},
|
||||
bind,
|
||||
config.settings,
|
||||
this.runtime.connectedLaunch
|
||||
? {
|
||||
...this.runtime.connectedLaunch,
|
||||
env: { ...this.runtime.connectedLaunch.env, ...config.env },
|
||||
}
|
||||
: undefined,
|
||||
);
|
||||
bind(bridge);
|
||||
return session;
|
||||
@@ -1297,6 +1316,7 @@ class PluginAgentSession implements AgentSession {
|
||||
) => Promise<ProviderRuntimeSession>,
|
||||
private readonly onBind: (bridge: ProviderRuntimeSession) => void,
|
||||
givenOptions: Readonly<Record<string, JsonValue>>,
|
||||
private readonly usageLaunch: ProviderLaunch | undefined,
|
||||
) {
|
||||
this.subagentIdsBySession.set(bridge.id, null);
|
||||
// Every setting the session opened with that was not given, including ones nobody set.
|
||||
@@ -1312,6 +1332,17 @@ class PluginAgentSession implements AgentSession {
|
||||
this.unsubscribe = bridge.onEvent((event) => this.accept(event, true));
|
||||
}
|
||||
|
||||
usageSession() {
|
||||
if (this.closed || !this.usageLaunch) return null;
|
||||
return {
|
||||
provider: this.provider,
|
||||
model: this.bridge.config.model,
|
||||
env: this.usageLaunch.env,
|
||||
launch: this.usageLaunch,
|
||||
sessionKey: this.bridge.id,
|
||||
};
|
||||
}
|
||||
|
||||
get id(): string {
|
||||
return this.describePersistence()?.sessionId ?? this.bridge.id;
|
||||
}
|
||||
@@ -2143,6 +2174,10 @@ function decodePersistence(handle: AgentPersistenceHandle): ProviderPersistence
|
||||
if (fromMetadata !== undefined) {
|
||||
return ProviderPersistenceSchema.parse(fromMetadata);
|
||||
}
|
||||
// COMPAT(gooseProvider): added in v0.17.0, remove after 2027-05-20 once legacy handles have migrated.
|
||||
if (handle.provider === "goose" && !handle.sessionId.startsWith("plugin:")) {
|
||||
return { version: 1, data: { sessionId: handle.sessionId } };
|
||||
}
|
||||
return decodePersistenceId(handle.sessionId);
|
||||
}
|
||||
|
||||
|
||||
@@ -623,6 +623,7 @@ function wrapClientProvider(
|
||||
unarchiveNativeSession: unarchiveNativeSession
|
||||
? async (handle) => await unarchiveNativeSession({ ...handle, provider: inner.provider })
|
||||
: undefined,
|
||||
resolveUsageLaunch: inner.resolveUsageLaunch?.bind(inner),
|
||||
getCatalogCacheKey: inner.getCatalogCacheKey?.bind(inner),
|
||||
isAvailable: (signal, options) => inner.isAvailable(signal, options),
|
||||
getDiagnostic: inner.getDiagnostic?.bind(inner),
|
||||
|
||||
@@ -473,6 +473,12 @@ export class ProviderSnapshotManager {
|
||||
return client;
|
||||
}
|
||||
|
||||
async resolveUsageLaunch(provider: string) {
|
||||
const definition = this.generation.definitions[provider];
|
||||
if (!definition?.enabled) return undefined;
|
||||
return this.ensureClient(provider, definition).resolveUsageLaunch?.();
|
||||
}
|
||||
|
||||
async listProviders(input: ProviderSnapshotReadOptions = {}): Promise<ProviderSnapshotEntry[]> {
|
||||
const target = resolveProviderSnapshotTarget(input.cwd);
|
||||
if (input.wait) {
|
||||
|
||||
@@ -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"];
|
||||
@@ -3409,11 +3412,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(
|
||||
|
||||
@@ -181,6 +181,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";
|
||||
@@ -211,7 +212,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,
|
||||
@@ -677,6 +681,7 @@ export async function createPaseoDaemon(
|
||||
usageAgents: {
|
||||
hasAgent: (id) => agentManager.getAgent(id) !== null,
|
||||
usageSession: (id) => agentManager.usageSession(id),
|
||||
resolveLaunch: (provider) => providerSnapshotManager.resolveUsageLaunch(provider),
|
||||
},
|
||||
managedSources: new ManagedPluginSources(config.paseoHome, {
|
||||
registries: config.pluginRegistries,
|
||||
@@ -739,6 +744,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) => {
|
||||
@@ -1159,6 +1165,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) => {
|
||||
@@ -1217,6 +1225,8 @@ export async function createPaseoDaemon(
|
||||
setupAutoArchiveOnMerge({
|
||||
paseoHome: config.paseoHome,
|
||||
paseoWorktreesBaseRoot: config.worktreesRoot,
|
||||
worktreeManagers: pluginRuntime,
|
||||
workspaceArchiveOperations,
|
||||
daemonConfigStore,
|
||||
workspaceGitService,
|
||||
github,
|
||||
@@ -1225,6 +1235,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,
|
||||
@@ -1245,6 +1257,7 @@ export async function createPaseoDaemon(
|
||||
createPaseoWorktree: async (workflowInput, workflowOptions) => {
|
||||
return createRegisteredPaseoWorktree(workflowInput, {
|
||||
lifecycle: pluginRuntime,
|
||||
worktreeManagers: pluginRuntime,
|
||||
github,
|
||||
...(workflowOptions?.resolveDefaultBranch
|
||||
? {
|
||||
@@ -1305,6 +1318,8 @@ export async function createPaseoDaemon(
|
||||
{
|
||||
paseoHome: config.paseoHome,
|
||||
paseoWorktreesBaseRoot: config.worktreesRoot,
|
||||
worktreeManagers: pluginRuntime,
|
||||
workspaceArchiveOperations,
|
||||
github,
|
||||
workspaceGitService,
|
||||
agentManager,
|
||||
@@ -1322,6 +1337,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 },
|
||||
@@ -1329,6 +1345,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,
|
||||
@@ -1427,6 +1447,8 @@ export async function createPaseoDaemon(
|
||||
{
|
||||
paseoHome: config.paseoHome,
|
||||
paseoWorktreesBaseRoot: config.worktreesRoot,
|
||||
worktreeManagers: pluginRuntime,
|
||||
workspaceArchiveOperations,
|
||||
github,
|
||||
workspaceGitService,
|
||||
agentManager,
|
||||
@@ -1450,6 +1472,7 @@ export async function createPaseoDaemon(
|
||||
stopWorkspaceSetup: (workspaceIdToStop) => workspaceSetupRuntime.stop(workspaceIdToStop),
|
||||
assertWorkspaceAutomationAllowed: (guardedWorkspaceId) =>
|
||||
assertWorkspaceAutomationAllowedForWorkspace(workspaceRegistry, guardedWorkspaceId),
|
||||
isCheckoutUntrusted: (checkoutPath) => isCheckoutUntrusted(workspaceRegistry, checkoutPath),
|
||||
sessionLogger: logger,
|
||||
},
|
||||
{
|
||||
@@ -1576,6 +1599,9 @@ export async function createPaseoDaemon(
|
||||
daemonConfigStore,
|
||||
github,
|
||||
workspaceGitService,
|
||||
worktreeManagers: pluginRuntime,
|
||||
workspaceArchiveOperations,
|
||||
isCheckoutUntrusted: (checkoutPath) => isCheckoutUntrusted(workspaceRegistry, checkoutPath),
|
||||
findWorkspaceIdForCwd: findWorkspaceIdForCwdExternal,
|
||||
listActiveWorkspaces: listActiveWorkspacesExternal,
|
||||
archiveWorkspaceRecord: (workspaceId, archivedAt) =>
|
||||
@@ -1923,6 +1949,7 @@ export async function createPaseoDaemon(
|
||||
pluginRuntime,
|
||||
orchestrationSkills,
|
||||
workspaceLabelService,
|
||||
workspaceArchiveOperations,
|
||||
);
|
||||
pluginRuntime.bindPaseoSessionHost(wsServer);
|
||||
await pluginRuntime.start();
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
// Local ACP peer shaped like `goose acp`.
|
||||
const readline = require("node:readline");
|
||||
|
||||
const inventory = {
|
||||
openrouter: { name: "OpenRouter", model: "anthropic/claude-sonnet-4.5" },
|
||||
openai: { name: "OpenAI", model: "gpt-4o" },
|
||||
anthropic: { name: "Anthropic", model: "sonnet" },
|
||||
};
|
||||
let provider = "goose";
|
||||
let model = inventory.openrouter.model;
|
||||
|
||||
const select = (id, currentValue, values) => ({
|
||||
id,
|
||||
name: id,
|
||||
...(id === "model" ? { category: "model" } : {}),
|
||||
type: "select",
|
||||
currentValue,
|
||||
options: values.map((value) => ({ value, name: value })),
|
||||
});
|
||||
const configOptions = () => [
|
||||
select("provider", provider, ["goose", ...Object.keys(inventory)]),
|
||||
select("model", model, [inventory[provider === "goose" ? "openrouter" : provider].model]),
|
||||
];
|
||||
const send = (message) =>
|
||||
process.stdout.write(JSON.stringify({ jsonrpc: "2.0", ...message }) + "\n");
|
||||
|
||||
readline.createInterface({ input: process.stdin }).on("line", (line) => {
|
||||
const { id, method, params } = JSON.parse(line);
|
||||
if (id === undefined) return;
|
||||
let result;
|
||||
switch (method) {
|
||||
case "initialize":
|
||||
result = { protocolVersion: 1, agentCapabilities: { loadSession: true }, authMethods: [] };
|
||||
break;
|
||||
case "session/new":
|
||||
case "session/load":
|
||||
result = { sessionId: "goose-fixture", configOptions: configOptions() };
|
||||
break;
|
||||
case "_goose/unstable/providers/list":
|
||||
result = {
|
||||
entries: Object.entries(inventory).map(([providerId, entry]) => ({
|
||||
providerId,
|
||||
providerName: entry.name,
|
||||
configured: providerId !== "anthropic",
|
||||
models: [{ id: entry.model, name: entry.model }],
|
||||
})),
|
||||
};
|
||||
break;
|
||||
case "_goose/unstable/config/read":
|
||||
result = {
|
||||
value: params.key === "GOOSE_PROVIDER" ? "openrouter" : inventory.openrouter.model,
|
||||
};
|
||||
break;
|
||||
case "session/set_config_option":
|
||||
if (params.configId === "provider") {
|
||||
provider = params.value;
|
||||
model = inventory[provider === "goose" ? "openrouter" : provider].model;
|
||||
} else if (params.configId === "model") {
|
||||
if (params.value !== inventory[provider === "goose" ? "openrouter" : provider].model) {
|
||||
send({ id, error: { code: -32602, message: "Model unavailable for selected provider" } });
|
||||
return;
|
||||
}
|
||||
model = params.value;
|
||||
}
|
||||
result = { configOptions: configOptions() };
|
||||
break;
|
||||
case "session/prompt":
|
||||
send({
|
||||
method: "session/update",
|
||||
params: {
|
||||
sessionId: params.sessionId,
|
||||
update: {
|
||||
sessionUpdate: "agent_message_chunk",
|
||||
content: { type: "text", text: `${provider}/${model}` },
|
||||
},
|
||||
},
|
||||
});
|
||||
result = { stopReason: "end_turn" };
|
||||
break;
|
||||
case "session/close":
|
||||
result = {};
|
||||
break;
|
||||
default:
|
||||
send({ id, error: { code: -32601, message: "Method not found" } });
|
||||
return;
|
||||
}
|
||||
send({ id, result });
|
||||
});
|
||||
@@ -519,3 +519,60 @@ test("a provider update outlives the client that started it and a new client rea
|
||||
await daemon.close();
|
||||
}
|
||||
}, 60000);
|
||||
|
||||
test("bundled goose lists configured providers and switches models across providers", async () => {
|
||||
const root = await mkdtemp(path.join(os.tmpdir(), "paseo-goose-models-"));
|
||||
const daemon = await createTestPaseoDaemon({
|
||||
paseoHomeRoot: root,
|
||||
cleanup: false,
|
||||
mcpEnabled: false,
|
||||
builtinPlugins: new BuiltinPluginLoader(undefined, ["goose-provider"]),
|
||||
});
|
||||
const client = new DaemonClient({
|
||||
url: `ws://127.0.0.1:${daemon.port}/ws`,
|
||||
appVersion: "0.16.0",
|
||||
});
|
||||
const openRouterModel = "openrouter/anthropic/claude-sonnet-4.5";
|
||||
const openAiModel = "openai/gpt-4o";
|
||||
try {
|
||||
await client.connect();
|
||||
await client.fetchAgents({ subscribe: {} });
|
||||
expect(client.getLastServerInfoMessage()?.features?.gooseProvider).toBe(true);
|
||||
expect(
|
||||
(await client.getProvidersSnapshot()).entries.some((entry) => entry.provider === "goose"),
|
||||
).toBe(false);
|
||||
|
||||
await client.patchDaemonConfig({
|
||||
providers: {
|
||||
goose: {
|
||||
enabled: true,
|
||||
command: [process.execPath, path.resolve(import.meta.dirname, "goose-fixture.cjs")],
|
||||
},
|
||||
},
|
||||
});
|
||||
const catalog = await client.listProviderModels("goose", { cwd: root });
|
||||
expect(catalog.error).toBeNull();
|
||||
expect(catalog.models.map((model) => [model.id, model.isDefault === true])).toEqual([
|
||||
[openRouterModel, true],
|
||||
[openAiModel, false],
|
||||
]);
|
||||
|
||||
const agent = await client.createAgent({ provider: "goose", cwd: root, model: openAiModel });
|
||||
await client.sendMessage(agent.id, "Which provider and model are you running?");
|
||||
expect((await client.waitForFinish(agent.id, 10_000)).status).toBe("idle");
|
||||
await client.setAgentModel(agent.id, openRouterModel);
|
||||
await client.sendMessage(agent.id, "Which provider and model are you running now?");
|
||||
expect((await client.waitForFinish(agent.id, 10_000)).status).toBe("idle");
|
||||
expect((await client.fetchAgent(agent.id))?.agent.model).toBe(openRouterModel);
|
||||
const timeline = await client.fetchAgentTimeline(agent.id, { limit: 100 });
|
||||
expect(
|
||||
timeline.entries.flatMap(({ item }) =>
|
||||
item.type === "assistant_message" ? [item.text] : [],
|
||||
),
|
||||
).toEqual([openAiModel, openRouterModel]);
|
||||
} finally {
|
||||
await client.close();
|
||||
await daemon.close();
|
||||
await rm(root, { recursive: true, force: true });
|
||||
}
|
||||
}, 60_000);
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -1089,3 +1089,31 @@ describe("speech provider config normalization", () => {
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
test.each([
|
||||
["goose", "acp"],
|
||||
["/opt/bin/goose", "acp"],
|
||||
])(
|
||||
"migrates the legacy goose entry and preserves command overrides (%s %s)",
|
||||
(binary, subcommand) => {
|
||||
const command = [binary, subcommand];
|
||||
const overrides = {
|
||||
enabled: false,
|
||||
label: "My goose",
|
||||
env: { GOOSE_PROVIDER: "openai" },
|
||||
models: [{ id: "primary", label: "Primary" }],
|
||||
additionalModels: [{ id: "secondary", label: "Secondary" }],
|
||||
};
|
||||
const parsed = PersistedConfigSchema.parse({
|
||||
agents: {
|
||||
providers: {
|
||||
goose: { ...overrides, extends: "acp", description: "Old description", command },
|
||||
},
|
||||
},
|
||||
});
|
||||
expect(parsed.agents?.providers?.goose).toEqual({
|
||||
...overrides,
|
||||
...(command[0] === "goose" ? {} : { command }),
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
@@ -199,16 +199,32 @@ function isLegacyProviderEntry(value: unknown): boolean {
|
||||
}
|
||||
|
||||
function normalizeAgentProviders(value: unknown): unknown {
|
||||
if (!value || typeof value !== "object" || Array.isArray(value)) {
|
||||
return value;
|
||||
if (!isConfigRecord(value)) return value;
|
||||
|
||||
let rawProviders = value;
|
||||
const goose = configRecord(value.goose);
|
||||
// COMPAT(gooseProvider): added in v0.17.0, remove after 2027-05-20 once legacy configs have migrated.
|
||||
if (goose?.extends === "acp") {
|
||||
const { extends: _base, description: _description, command, ...overrides } = goose;
|
||||
const usesDefaultCommand =
|
||||
Array.isArray(command) &&
|
||||
command.length === 2 &&
|
||||
command[0] === "goose" &&
|
||||
command[1] === "acp";
|
||||
rawProviders = {
|
||||
...value,
|
||||
goose: {
|
||||
...overrides,
|
||||
...(command !== undefined && !usesDefaultCommand ? { command } : {}),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
const rawProviders = value as Record<string, unknown>;
|
||||
const hasLegacyEntries = Object.values(rawProviders).some((entry) =>
|
||||
isLegacyProviderEntry(entry),
|
||||
);
|
||||
if (!hasLegacyEntries) {
|
||||
return value;
|
||||
return rawProviders;
|
||||
}
|
||||
|
||||
const legacyEntries: Record<string, unknown> = {};
|
||||
@@ -224,7 +240,7 @@ function normalizeAgentProviders(value: unknown): unknown {
|
||||
|
||||
const parsedLegacyEntries = AgentProviderRuntimeSettingsMapSchema.safeParse(legacyEntries);
|
||||
if (!parsedLegacyEntries.success) {
|
||||
return value;
|
||||
return rawProviders;
|
||||
}
|
||||
|
||||
return {
|
||||
|
||||
@@ -9,12 +9,14 @@ export const builtinPlugins = [
|
||||
"copilot-usage-source",
|
||||
"cursor-usage-source",
|
||||
"fx-provider",
|
||||
"goose-provider",
|
||||
"grok-usage-source",
|
||||
"hoplite-provider",
|
||||
"kimi-usage-source",
|
||||
"minimax-usage-source",
|
||||
"muse-provider",
|
||||
"opencode-go-usage-source",
|
||||
"openrouter-host-usage-source",
|
||||
"worktree-include",
|
||||
"zai-usage-source",
|
||||
] as const;
|
||||
|
||||
@@ -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);
|
||||
@@ -669,12 +698,39 @@ export class PluginService {
|
||||
const registered: string[] = [];
|
||||
try {
|
||||
for (const source of metadata) {
|
||||
if (
|
||||
source.provider &&
|
||||
!this.runtime
|
||||
.getProviderRegistrations?.(pluginId)
|
||||
.some((provider) => provider.id === source.provider)
|
||||
) {
|
||||
throw new Error(
|
||||
`Usage source ${source.id} references a provider outside plugin ${pluginId}`,
|
||||
);
|
||||
}
|
||||
this.usageSources.register({
|
||||
id: source.id,
|
||||
label: source.label,
|
||||
icon: source.icon,
|
||||
discover: async (scope) => {
|
||||
const result = await this.runtime.discoverUsage(pluginId, source.id, scope);
|
||||
const launch =
|
||||
scope.kind === "global" && source.provider
|
||||
? await this.dependencies.usageAgents?.resolveLaunch?.(source.provider)
|
||||
: undefined;
|
||||
const scoped =
|
||||
scope.kind === "session" && source.provider !== scope.provider
|
||||
? {
|
||||
kind: "session" as const,
|
||||
provider: scope.provider,
|
||||
model: scope.model,
|
||||
env: scope.env,
|
||||
}
|
||||
: scope;
|
||||
const result = await this.runtime.discoverUsage(
|
||||
pluginId,
|
||||
source.id,
|
||||
scoped.kind === "global" && launch ? { ...scoped, launch } : scoped,
|
||||
);
|
||||
if (!Array.isArray(result))
|
||||
throw new Error(`Invalid usage discovery from ${source.id}`);
|
||||
return result;
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -41,9 +41,15 @@ export interface PluginProviderInstallationMetadata {
|
||||
export interface PluginUsageSourceMetadata {
|
||||
id: string;
|
||||
label: string;
|
||||
provider?: string;
|
||||
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 }
|
||||
@@ -83,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 }
|
||||
@@ -114,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[];
|
||||
@@ -121,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 }
|
||||
@@ -148,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({
|
||||
@@ -175,6 +196,7 @@ const usageSourceMetadataSchema = z
|
||||
.object({
|
||||
id: z.string().min(1),
|
||||
label: z.string().min(1),
|
||||
provider: z.string().min(1).optional(),
|
||||
icon: z.string().optional(),
|
||||
})
|
||||
.strict();
|
||||
@@ -292,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"),
|
||||
@@ -354,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"),
|
||||
@@ -362,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,
|
||||
@@ -448,6 +485,7 @@ export function createPluginWorker(options: {
|
||||
.map(async (source) => ({
|
||||
id: source.id,
|
||||
label: source.label,
|
||||
provider: source.provider,
|
||||
icon: source.icon
|
||||
? await readPluginProviderIcon(message.pluginDirectory, source.icon)
|
||||
: undefined,
|
||||
@@ -458,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),
|
||||
@@ -477,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 {
|
||||
@@ -518,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" });
|
||||
@@ -703,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);
|
||||
}
|
||||
@@ -768,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 };
|
||||
}
|
||||
|
||||
|
||||
@@ -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,112 @@ export class PluginRuntime {
|
||||
return request;
|
||||
}
|
||||
|
||||
hasWorktreeManager(options?: {
|
||||
operation?: "create" | "remove" | "restore";
|
||||
preferredPluginId?: string;
|
||||
}): boolean {
|
||||
const operation = options?.operation ?? "create";
|
||||
const supports = (manager: PluginWorktreeManagerCapabilities | null): boolean => {
|
||||
if (!manager) return false;
|
||||
if (operation === "remove") return manager.hasRemove;
|
||||
if (operation === "restore") return manager.hasRestore;
|
||||
return true;
|
||||
};
|
||||
if (options?.preferredPluginId) {
|
||||
return supports(this.plugins.get(options.preferredPluginId)?.worktreeManager ?? null);
|
||||
}
|
||||
for (const loaded of this.plugins.values()) {
|
||||
if (supports(loaded.worktreeManager)) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
async createWorktree(
|
||||
request: PluginWorktreeCreateInput,
|
||||
options?: { signal?: AbortSignal },
|
||||
): Promise<{ pluginId: string; path: string } | null> {
|
||||
const plugins = [...this.plugins.values()]
|
||||
.filter((plugin) => plugin.worktreeManager !== null)
|
||||
.sort((left, right) => left.id.localeCompare(right.id));
|
||||
// Share one 120s budget across the full serial manager chain so clients waiting on
|
||||
// create_paseo_worktree_request (150s) never time out while the daemon is still running managers.
|
||||
const deadline = Date.now() + WORKTREE_MANAGER_TIMEOUT_MS;
|
||||
for (const loaded of plugins) {
|
||||
const remainingMs = deadline - Date.now();
|
||||
if (remainingMs <= 0) {
|
||||
throw new Error(
|
||||
`Plugin ${loaded.id} worktree.create failed: Plugin RPC timed out: ${loaded.id}.worktree.create`,
|
||||
);
|
||||
}
|
||||
try {
|
||||
const raw = await this.request(
|
||||
loaded,
|
||||
{ type: "worktree.create", requestId: randomUUID(), request },
|
||||
{ signal: options?.signal, timeoutMs: remainingMs },
|
||||
);
|
||||
const parsed = worktreeCreateResultSchema.parse(raw ?? null);
|
||||
if (parsed !== null) {
|
||||
return { pluginId: loaded.id, path: parsed.path };
|
||||
}
|
||||
} catch (error) {
|
||||
throw new Error(`Plugin ${loaded.id} worktree.create failed: ${describeError(error)}`, {
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
async removeWorktree(
|
||||
request: PluginWorktreeRemoveRequest,
|
||||
options?: { preferredPluginId?: string; signal?: AbortSignal },
|
||||
): Promise<{ pluginId: string } | null> {
|
||||
if (!options?.preferredPluginId) return null;
|
||||
const loaded = this.plugins.get(options.preferredPluginId);
|
||||
if (!loaded?.worktreeManager?.hasRemove) return null;
|
||||
try {
|
||||
const raw = await this.request(
|
||||
loaded,
|
||||
{ type: "worktree.remove", requestId: randomUUID(), request },
|
||||
{ signal: options.signal },
|
||||
);
|
||||
const parsed = worktreeRemoveResultSchema.parse(raw ?? null);
|
||||
if (parsed !== null) {
|
||||
return { pluginId: loaded.id };
|
||||
}
|
||||
return null;
|
||||
} catch (error) {
|
||||
throw new Error(`Plugin ${loaded.id} worktree.remove failed: ${describeError(error)}`, {
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
async restoreWorktree(
|
||||
request: PluginWorktreeRestoreRequest,
|
||||
options?: { preferredPluginId?: string; signal?: AbortSignal },
|
||||
): Promise<{ pluginId: string; path: string } | null> {
|
||||
if (!options?.preferredPluginId) return null;
|
||||
const loaded = this.plugins.get(options.preferredPluginId);
|
||||
if (!loaded?.worktreeManager?.hasRestore) return null;
|
||||
try {
|
||||
const raw = await this.request(
|
||||
loaded,
|
||||
{ type: "worktree.restore", requestId: randomUUID(), request },
|
||||
{ signal: options.signal },
|
||||
);
|
||||
const parsed = worktreeRestoreResultSchema.parse(raw ?? null);
|
||||
if (parsed !== null) {
|
||||
return { pluginId: loaded.id, path: parsed.path };
|
||||
}
|
||||
return null;
|
||||
} catch (error) {
|
||||
throw new Error(`Plugin ${loaded.id} worktree.restore failed: ${describeError(error)}`, {
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
async getProviderCatalogCacheKey(
|
||||
pluginId: string,
|
||||
providerId: string,
|
||||
@@ -853,12 +1013,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 +1032,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 +1100,7 @@ export class PluginRuntime {
|
||||
subscriptionMethods: new Set(),
|
||||
subscriptions: new Map(),
|
||||
hooks: [],
|
||||
worktreeManager: null,
|
||||
providers: [],
|
||||
usageSources: [],
|
||||
child: null,
|
||||
@@ -1067,6 +1233,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 +1323,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;
|
||||
|
||||
@@ -2,11 +2,17 @@ import path from "node:path";
|
||||
import { initializeEnvironmentProxy } from "../../network/index.js";
|
||||
import { DaemonClient } from "../../test-utils/daemon-client.js";
|
||||
import { createTestPaseoDaemon } from "../../test-utils/paseo-daemon.js";
|
||||
import { BuiltinPluginLoader, resolveBuiltinPluginsRoot } from "../builtin/index.js";
|
||||
import {
|
||||
builtinPlugins,
|
||||
BuiltinPluginLoader,
|
||||
resolveBuiltinPluginsRoot,
|
||||
} from "../builtin/index.js";
|
||||
|
||||
const mode = process.argv[2];
|
||||
if (mode !== "builtin" && mode !== "directory") throw new Error("Expected builtin or directory");
|
||||
const sources = ["claude-usage-source", "codex-usage-source"];
|
||||
const sources = builtinPlugins.filter((id) =>
|
||||
["claude-usage-source", "codex-usage-source", "openrouter-host-usage-source"].includes(id),
|
||||
);
|
||||
// Built-ins run inside the daemon; directory plugins initialize their own subprocess network.
|
||||
if (mode === "builtin") initializeEnvironmentProxy();
|
||||
const daemon = await createTestPaseoDaemon({
|
||||
|
||||
@@ -392,6 +392,8 @@ dns.lookup = function(host, ...args) {
|
||||
HOME: root,
|
||||
USERPROFILE: root,
|
||||
CODEX_HOME: path.join(root, ".codex"),
|
||||
OPENROUTER_API_KEY: "fixture-openrouter",
|
||||
OPENROUTER_MANAGEMENT_KEY: "fixture-openrouter-management",
|
||||
CLAUDE_CONFIG_DIR: path.join(root, ".claude"),
|
||||
NODE_OPTIONS: `--require=${JSON.stringify(guard.replaceAll("\\", "/"))}`,
|
||||
https_proxy: `http://127.0.0.1:${address.port}`,
|
||||
@@ -402,6 +404,7 @@ dns.lookup = function(host, ...args) {
|
||||
);
|
||||
expect(tunnels).toContain("api.anthropic.com:443");
|
||||
expect(tunnels).toContain("chatgpt.com:443");
|
||||
expect(tunnels.filter((target) => target === "openrouter.ai:443")).toHaveLength(2);
|
||||
} finally {
|
||||
proxy.closeAllConnections();
|
||||
await new Promise<void>((resolve) => proxy.close(() => resolve()));
|
||||
@@ -410,3 +413,57 @@ dns.lookup = function(host, ...args) {
|
||||
},
|
||||
60_000,
|
||||
);
|
||||
|
||||
test("resolves a plugin provider launch for cold usage discovery", async () => {
|
||||
const root = await mkdtemp(path.join(os.tmpdir(), "paseo-usage-launch-"));
|
||||
const directory = path.join(root, "launch-source");
|
||||
await mkdir(directory, { recursive: true });
|
||||
await writeFile(
|
||||
path.join(directory, "paseo-plugin.json"),
|
||||
JSON.stringify({ id: "launch-source", requirements: { paseo: ">=0.9.2" } }),
|
||||
);
|
||||
await writeFile(
|
||||
path.join(directory, "index.server.ts"),
|
||||
`
|
||||
import { z } from 'zod';
|
||||
export default function contribute(server) {
|
||||
server.registerProvider({ id: 'usage-launch-fixture', label: 'Launch fixture', command: [${JSON.stringify(process.execPath)}, 'fixture-arg'], connect: async () => { throw new Error('Must not connect'); } });
|
||||
server.registerUsageSource({ id: 'launch-fixture', label: 'Launch fixture', provider: 'usage-launch-fixture', input: z.object({}),
|
||||
discover: async scope => scope.kind === 'global' && scope.launch?.args[0] === 'fixture-arg' ? [{ key: 'default', input: {} }] : [],
|
||||
fetch: async () => ({ status: 'available', windows: [{ id: 'weekly', label: 'Weekly', usedPct: 12 }] }) });
|
||||
return () => {};
|
||||
}`,
|
||||
);
|
||||
const daemon = await createTestPaseoDaemon({
|
||||
daemonVersion: "0.16.2",
|
||||
pluginsEnabled: false,
|
||||
builtinPlugins: new BuiltinPluginLoader(root, ["launch-source"]),
|
||||
});
|
||||
const client = new DaemonClient({
|
||||
url: `ws://127.0.0.1:${daemon.port}/ws`,
|
||||
appVersion: "0.16.2",
|
||||
});
|
||||
try {
|
||||
await client.connect();
|
||||
const result = await client.listUsageReports();
|
||||
expect(result.reports).toContainEqual(
|
||||
expect.objectContaining({
|
||||
id: "launch-fixture:default",
|
||||
report: expect.objectContaining({
|
||||
status: "available",
|
||||
windows: [{ id: "weekly", label: "Weekly", usedPct: 12 }],
|
||||
}),
|
||||
}),
|
||||
);
|
||||
await client.patchDaemonConfig({
|
||||
providers: {
|
||||
"usage-launch-fixture": { command: [path.join(root, "missing-cli")] },
|
||||
},
|
||||
});
|
||||
expect((await client.listUsageReports()).reports).toEqual([]);
|
||||
} finally {
|
||||
await client.close();
|
||||
await daemon.close();
|
||||
await rm(root, { recursive: true, force: true });
|
||||
}
|
||||
}, 60_000);
|
||||
|
||||
@@ -33,6 +33,9 @@ interface KnownReport {
|
||||
export interface AgentUsageLookup {
|
||||
hasAgent(id: string): boolean;
|
||||
usageSession(id: string): AgentUsageSession | null;
|
||||
resolveLaunch?(
|
||||
provider: string,
|
||||
): Promise<import("@getpaseo/plugin/server/provider").ProviderLaunch | undefined>;
|
||||
}
|
||||
|
||||
export interface ListUsageReportsOptions {
|
||||
@@ -134,6 +137,7 @@ export class UsageSourceRegistry {
|
||||
provider: session.provider,
|
||||
model: session.model,
|
||||
env: session.env,
|
||||
launch: session.launch,
|
||||
});
|
||||
const current = this.agents.usageSession(agentId);
|
||||
if (
|
||||
|
||||
@@ -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;
|
||||
@@ -5780,11 +5821,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),
|
||||
@@ -5796,6 +5840,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,
|
||||
@@ -6501,9 +6547,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> {
|
||||
@@ -6550,6 +6647,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 }
|
||||
@@ -6580,6 +6678,8 @@ export class Session {
|
||||
worktreeRoot: workspace.worktreeRoot,
|
||||
isPaseoOwnedWorktree: workspace.isPaseoOwnedWorktree,
|
||||
mainRepoRoot: workspace.mainRepoRoot,
|
||||
worktreeManagerPluginId: workspace.worktreeManagerPluginId,
|
||||
untrustedSource: workspace.untrustedSource,
|
||||
}));
|
||||
}
|
||||
|
||||
@@ -7434,24 +7534,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(
|
||||
@@ -7533,34 +7638,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);
|
||||
@@ -8128,6 +8240,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,
|
||||
@@ -8144,6 +8258,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),
|
||||
@@ -8206,7 +8322,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",
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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";
|
||||
@@ -2214,6 +2222,8 @@ export class VoiceAssistantWebSocketServer {
|
||||
hopliteProvider: this.providerSnapshotManager.supportsConfigRequiredProvider("hoplite"),
|
||||
// COMPAT(fxProvider): added after v0.15.3, remove after 2027-05-09 once host floor includes the bundled adapter.
|
||||
fxProvider: this.providerSnapshotManager.supportsConfigRequiredProvider("fx"),
|
||||
// COMPAT(gooseProvider): added in v0.17.0, remove after 2027-05-20 once host floor includes the bundled adapter.
|
||||
gooseProvider: this.providerSnapshotManager.supportsConfigRequiredProvider("goose"),
|
||||
// COMPAT(importSessionWorkspaceTarget): added in v0.1.110, remove gate after 2027-01-16.
|
||||
importSessionWorkspaceTarget: true,
|
||||
// COMPAT(importSessionSearch): added in v0.7.3, remove gate after 2027-03-02.
|
||||
|
||||
@@ -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,54 @@ test("a canceled archive with no matching agents leaves earlier closed agents ar
|
||||
});
|
||||
expect(restored).toEqual([]);
|
||||
});
|
||||
|
||||
test("archiving an outer worktree preserves an active nested checkout and its uncommitted files", async () => {
|
||||
const { repoDir } = createGitRepo();
|
||||
const rootDir = path.dirname(repoDir);
|
||||
const outerPath = path.join(rootDir, "worktrees", "team");
|
||||
const innerPath = path.join(outerPath, "topic");
|
||||
mkdirSync(path.dirname(outerPath), { recursive: true });
|
||||
execFileSync("git", ["worktree", "add", "-b", "team", outerPath], {
|
||||
cwd: repoDir,
|
||||
stdio: "pipe",
|
||||
});
|
||||
execFileSync("git", ["worktree", "add", "-b", "topic", innerPath], {
|
||||
cwd: repoDir,
|
||||
stdio: "pipe",
|
||||
});
|
||||
const dirtyFile = path.join(innerPath, "uncommitted.txt");
|
||||
writeFileSync(dirtyFile, "keep-inner");
|
||||
|
||||
const activeWorkspaces: ActiveWorkspaceRef[] = [
|
||||
{
|
||||
workspaceId: "ws-team",
|
||||
cwd: outerPath,
|
||||
kind: "worktree",
|
||||
worktreeRoot: outerPath,
|
||||
isPaseoOwnedWorktree: true,
|
||||
mainRepoRoot: repoDir,
|
||||
},
|
||||
{
|
||||
workspaceId: "ws-topic",
|
||||
cwd: innerPath,
|
||||
kind: "worktree",
|
||||
worktreeRoot: innerPath,
|
||||
isPaseoOwnedWorktree: true,
|
||||
mainRepoRoot: repoDir,
|
||||
},
|
||||
];
|
||||
const deps = createArchiveDeps({
|
||||
paseoHome: rootDir,
|
||||
activeWorkspaces,
|
||||
});
|
||||
|
||||
const result = await archiveByScope(deps, {
|
||||
scope: { kind: "workspace", workspaceId: "ws-team" },
|
||||
requestId: "archive-outer",
|
||||
});
|
||||
|
||||
expect(result.archivedWorkspaceIds).toEqual(["ws-team"]);
|
||||
expect(result.removedDirectory).toBe(false);
|
||||
expect(existsSync(outerPath)).toBe(true);
|
||||
expect(readFileSync(dirtyFile, "utf8")).toBe("keep-inner");
|
||||
});
|
||||
|
||||
@@ -19,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({
|
||||
@@ -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 });
|
||||
@@ -619,7 +689,7 @@ export async function archiveWorkspaceContents(
|
||||
}
|
||||
|
||||
// True when, after archiving
|
||||
// the in-scope records, no active workspace still points at targetDir. Derived
|
||||
// the in-scope records, no active workspace still points at or inside targetDir. Derived
|
||||
// from records each call — no stored counter.
|
||||
async function isDirectoryUnreferenced(
|
||||
activeWorkspaces: ActiveWorkspaceRef[],
|
||||
@@ -632,7 +702,13 @@ async function isDirectoryUnreferenced(
|
||||
for (const workspace of activeWorkspaces) {
|
||||
if (archivedWorkspaceIds.has(workspace.workspaceId)) continue;
|
||||
const backingDirectory = await resolveWorkspaceBackingDirectory(workspace, dependencies);
|
||||
if (matchesTarget(backingDirectory.path)) return false;
|
||||
if (
|
||||
matchesTarget(backingDirectory.path) ||
|
||||
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 };
|
||||
|
||||
@@ -75,7 +75,7 @@ describe("GitHub repository search", () => {
|
||||
]);
|
||||
});
|
||||
|
||||
it("searches accessible repositories for a typed query", async () => {
|
||||
it("respects an explicit visibility qualifier and normalizes the search result", async () => {
|
||||
const runner = createRunner([
|
||||
JSON.stringify([
|
||||
{
|
||||
@@ -96,7 +96,7 @@ describe("GitHub repository search", () => {
|
||||
});
|
||||
|
||||
await expect(
|
||||
service.searchRepositories({ cwd: "/tmp", query: " private project ", limit: 5 }),
|
||||
service.searchRepositories({ cwd: "/tmp", query: " is:private private project ", limit: 5 }),
|
||||
).resolves.toEqual([
|
||||
{
|
||||
id: "42",
|
||||
@@ -113,15 +113,15 @@ describe("GitHub repository search", () => {
|
||||
args: [
|
||||
"search",
|
||||
"repos",
|
||||
"private project",
|
||||
"is:private private project",
|
||||
"--json",
|
||||
"id,name,fullName,description,isPrivate,updatedAt,url",
|
||||
"--limit",
|
||||
"5",
|
||||
"--sort",
|
||||
"updated",
|
||||
"--order",
|
||||
"desc",
|
||||
"--limit",
|
||||
"5",
|
||||
],
|
||||
options: { cwd: "/tmp" },
|
||||
},
|
||||
@@ -131,4 +131,39 @@ describe("GitHub repository search", () => {
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("puts private matches first even when the general search omits some of them", async () => {
|
||||
const repository = (id: number, fullName: string, isPrivate: boolean) => ({
|
||||
id,
|
||||
name: fullName.split("/")[1],
|
||||
fullName,
|
||||
description: "An editor",
|
||||
isPrivate,
|
||||
updatedAt: "2026-07-14T08:00:00Z",
|
||||
url: `https://github.com/${fullName}`,
|
||||
});
|
||||
const privateEditor = repository(1, "example/editor", true);
|
||||
const publicEditor = repository(2, "public/recent-editor", false);
|
||||
const anotherPublicEditor = repository(3, "public/another-editor", false);
|
||||
const recentPrivateEditor = repository(4, "example/recent-editor", true);
|
||||
const service = createGitHubService({
|
||||
runner: async (args) => {
|
||||
if (args[0] === "config") {
|
||||
return { stdout: "https", stderr: "" };
|
||||
}
|
||||
const results = args.includes("--visibility=private")
|
||||
? [privateEditor, recentPrivateEditor]
|
||||
: [publicEditor, recentPrivateEditor, anotherPublicEditor];
|
||||
return { stdout: JSON.stringify(results), stderr: "" };
|
||||
},
|
||||
resolveGhPath: async () => "/usr/bin/gh",
|
||||
});
|
||||
|
||||
const results = await service.searchRepositories({ cwd: "/tmp", query: "editor", limit: 3 });
|
||||
expect(results.map((result) => result.nameWithOwner)).toEqual([
|
||||
"example/editor",
|
||||
"example/recent-editor",
|
||||
"public/recent-editor",
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -2639,26 +2639,34 @@ export function createGitHubService(options: CreateGitHubServiceOptions = {}): G
|
||||
return parseRepositoryList(stdout, cloneProtocol);
|
||||
}
|
||||
|
||||
const [stdout, cloneProtocol] = await Promise.all([
|
||||
run(
|
||||
[
|
||||
"search",
|
||||
"repos",
|
||||
query,
|
||||
"--json",
|
||||
"id,name,fullName,description,isPrivate,updatedAt,url",
|
||||
"--sort",
|
||||
"updated",
|
||||
"--order",
|
||||
"desc",
|
||||
"--limit",
|
||||
String(limit),
|
||||
],
|
||||
{ cwd: input.cwd },
|
||||
),
|
||||
const searchArgs = [
|
||||
"search",
|
||||
"repos",
|
||||
query,
|
||||
"--json",
|
||||
"id,name,fullName,description,isPrivate,updatedAt,url",
|
||||
"--limit",
|
||||
String(limit),
|
||||
];
|
||||
const hasVisibilityFilter = /(?:^|\s)-?is:(?:public|private|internal)(?=\s|$)/i.test(query);
|
||||
// The general search can hit its limit before returning a single private match.
|
||||
const [stdout, privateStdout, cloneProtocol] = await Promise.all([
|
||||
run([...searchArgs, "--sort", "updated", "--order", "desc"], { cwd: input.cwd }),
|
||||
hasVisibilityFilter
|
||||
? "[]"
|
||||
: run([...searchArgs, "--visibility=private"], { cwd: input.cwd }),
|
||||
resolveConfiguredCloneProtocol(input.cwd, run),
|
||||
]);
|
||||
return parseRepositorySearch(stdout, cloneProtocol);
|
||||
const repositories = parseRepositorySearch(stdout, cloneProtocol);
|
||||
const privateMatches = parseRepositorySearch(privateStdout, cloneProtocol);
|
||||
const ranked = new Map(
|
||||
[
|
||||
...privateMatches,
|
||||
...repositories.filter((repository) => repository.visibility === "private"),
|
||||
...repositories,
|
||||
].map((repository) => [repository.id, repository]),
|
||||
);
|
||||
return [...ranked.values()].slice(0, limit);
|
||||
},
|
||||
|
||||
async searchIssuesAndPrs(input) {
|
||||
|
||||
@@ -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,8 +47,10 @@ 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`,
|
||||
@@ -79,7 +81,7 @@ export async function validateWorktreePath(options: {
|
||||
if (relativeToCandidate !== null && relativeToCandidate !== "") {
|
||||
throw new Error(`Worktree hook returned 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.`,
|
||||
);
|
||||
|
||||
|
Before Width: | Height: | Size: 15 KiB After Width: | Height: | Size: 15 KiB |
|
Before Width: | Height: | Size: 3.3 KiB After Width: | Height: | Size: 5.9 KiB |
|
Before Width: | Height: | Size: 3.2 KiB After Width: | Height: | Size: 5.9 KiB |
@@ -89,6 +89,7 @@ import {
|
||||
PiIcon,
|
||||
} from "~/components/agent-icons";
|
||||
import { DiscordIcon, GitHubIcon, SlackIcon } from "~/components/brand-icons";
|
||||
import { PaseoHubMark } from "~/components/paseo-brand";
|
||||
import {
|
||||
MobileChat,
|
||||
MobileDiff,
|
||||
@@ -515,6 +516,7 @@ function TurnkeySection() {
|
||||
description={t("landing.runAnywhere.teamsDescription")}
|
||||
ctaHref={localize("/hub")}
|
||||
ctaLabel={t("landing.runAnywhere.teamsCta")}
|
||||
ctaIcon={PASEO_HUB_CTA_ICON}
|
||||
showIntegrationIcons
|
||||
/>
|
||||
</div>
|
||||
@@ -523,12 +525,15 @@ function TurnkeySection() {
|
||||
);
|
||||
}
|
||||
|
||||
const PASEO_HUB_CTA_ICON = <PaseoHubMark className="h-4 w-4 shrink-0" />;
|
||||
|
||||
function TurnkeyExtensionCard({
|
||||
icon: Icon,
|
||||
title,
|
||||
description,
|
||||
ctaHref,
|
||||
ctaLabel,
|
||||
ctaIcon,
|
||||
showIntegrationIcons = false,
|
||||
}: {
|
||||
icon: LucideIcon;
|
||||
@@ -536,6 +541,7 @@ function TurnkeyExtensionCard({
|
||||
description: string;
|
||||
ctaHref: string;
|
||||
ctaLabel: string;
|
||||
ctaIcon?: React.ReactNode;
|
||||
showIntegrationIcons?: boolean;
|
||||
}) {
|
||||
return (
|
||||
@@ -545,6 +551,7 @@ function TurnkeyExtensionCard({
|
||||
href={ctaHref}
|
||||
className="inline-flex items-center gap-1.5 rounded-full bg-foreground px-2.5 py-1.5 text-xs text-background transition-colors hover:bg-foreground/90"
|
||||
>
|
||||
{ctaIcon}
|
||||
{ctaLabel}
|
||||
<ArrowRight className="h-3.5 w-3.5" />
|
||||
</a>
|
||||
|
||||
@@ -1,21 +1,11 @@
|
||||
// Exact SVG paths from packages/app/src/components/icons/
|
||||
|
||||
import { OpenCodeIcon as OpenCodeBrandIcon, PiIcon as PiBrandIcon } from "../agent-icons";
|
||||
import { PaseoMark as CanonicalPaseoMark } from "../paseo-brand";
|
||||
|
||||
/** The Paseo brand swirl — public/logo.svg, drawn as a small sidebar avatar mark. */
|
||||
/** The Paseo butterfly mark, drawn as a small sidebar avatar or tool-call mark. */
|
||||
export function PaseoMark({ size = 13, className }: { size?: number; className?: string }) {
|
||||
return (
|
||||
<svg
|
||||
width={size}
|
||||
height={size}
|
||||
viewBox="0 0 700 700"
|
||||
fill="currentColor"
|
||||
aria-hidden="true"
|
||||
className={className}
|
||||
>
|
||||
<path d="M291.495 91.399C333.897 104.892 379.155 135.075 416.229 173.191C453.389 211.394 484.429 259.725 495.708 311.251C497.555 319.693 498.865 328.216 499.586 336.776C509.755 326.554 519.867 317.815 529.89 311.547C540.647 304.821 553.808 299.297 568.641 299.785C584.29 300.299 597.395 307.326 607.747 317.632C632.173 341.947 629.612 372.898 619.872 397.936C610.185 422.833 591.557 447.826 572.732 469.124C553.591 490.78 532.713 510.308 516.779 524.318C508.775 531.355 501.936 537.073 497.07 541.052C494.635 543.043 492.689 544.603 491.334 545.679C490.657 546.217 490.126 546.635 489.756 546.926C489.571 547.071 489.425 547.184 489.321 547.265C489.269 547.305 489.227 547.338 489.196 547.362C489.181 547.374 489.168 547.385 489.157 547.393C489.153 547.397 489.147 547.401 489.144 547.403C489.134 547.4 488.837 547.06 473.001 528.499L489.135 547.411C478.157 555.911 462.033 554.334 453.122 543.89C444.213 533.448 445.887 518.094 456.861 509.592C456.863 509.591 456.865 509.588 456.869 509.586C456.88 509.577 456.902 509.561 456.933 509.536C456.997 509.487 457.101 509.404 457.245 509.292C457.533 509.066 457.979 508.715 458.569 508.247C459.749 507.31 461.506 505.901 463.742 504.073C468.216 500.414 474.589 495.088 482.073 488.508C497.114 475.284 516.315 457.282 533.578 437.75C551.157 417.862 565.26 398.01 571.859 381.048C578.403 364.227 575.681 356.302 570.724 351.367C568.928 349.579 567.744 348.902 567.267 348.676C566.888 348.496 566.811 348.52 566.804 348.52C566.605 348.513 563.971 348.537 557.953 352.3C545.161 360.299 528.815 377.492 506.807 403.867C494.927 418.106 481.871 434.435 467.547 451.957C463.709 457.28 459.503 462.538 454.91 467.717L454.702 467.549C420.808 508.347 380.37 553.856 332.335 593.848C301.853 619.226 262.656 622.597 228.642 614.743C194.834 606.936 162.658 587.448 142.217 561.686C108.054 518.631 100.57 469.801 108.223 427.836C115.56 387.606 137.391 351.005 166.502 331.557C161.248 315.813 156.813 299.49 153.519 283.013C142.593 228.368 143.239 167.031 174.28 119.619C186.922 100.31 205.846 89.1535 227.387 85.2773C248.1 81.5504 270.278 84.648 291.495 91.399ZM378.642 206.356C345.773 172.563 307.463 147.917 275.208 137.654C259.096 132.527 246.171 131.514 236.828 133.195C228.314 134.727 222.227 138.497 217.721 145.38C196.712 177.468 193.858 224.004 203.82 273.827C206.532 287.394 210.127 300.834 214.345 313.817C236.45 310.276 260.156 311.463 281.22 317.11C319.621 327.403 357.501 355.419 357.501 405.654C357.501 435.255 339.111 465.136 307.278 473.815C273.211 483.103 238.854 464.822 213.105 427.541C203.716 413.947 194.443 397.766 185.947 379.89C174.028 392.223 163.08 411.953 158.673 436.118C153.128 466.518 158.514 501.286 183.085 532.253C195.993 548.522 217.742 562.031 240.771 567.349C263.594 572.619 284.147 569.24 298.664 557.154C349.383 514.927 390.709 466.547 426.366 422.952C448.879 390.86 453.195 356.06 445.578 321.265C436.703 280.718 411.425 240.06 378.642 206.356ZM306.296 405.722C306.296 384.769 292.223 370.736 267.284 364.051C256.012 361.03 244.156 360.087 233.095 360.771C240.361 375.935 248.168 389.513 255.897 400.704C275.647 429.298 289.989 427.822 293.247 426.934C298.737 425.437 306.296 418.161 306.296 405.722Z" />
|
||||
</svg>
|
||||
);
|
||||
return <CanonicalPaseoMark width={size} height={size} className={className} />;
|
||||
}
|
||||
|
||||
/** GitHub mark for the toolbar and PR panel. */
|
||||
|
||||
@@ -1,25 +1,11 @@
|
||||
// Small shared bits for the mobile mockups. The Paseo butterfly mark is the
|
||||
// app icon (packages/website/public/favicon.svg) with the black plate dropped,
|
||||
// so it can be tinted and placed on any tile. Tile fills are the app's identity
|
||||
// Small shared bits for the mobile mockups. Tile fills are the app's identity
|
||||
// palette — packages/app/src/styles/identity-colors.ts — surfaced as
|
||||
// `--color-mock-tile-*` tokens in styles.css.
|
||||
|
||||
const BUTTERFLY_D =
|
||||
"M291.495 91.399C333.897 104.892 379.155 135.075 416.229 173.191C453.389 211.394 484.429 259.725 495.708 311.251C497.555 319.693 498.865 328.216 499.586 336.776C509.755 326.554 519.867 317.815 529.89 311.547C540.647 304.821 553.808 299.297 568.641 299.785C584.29 300.299 597.395 307.326 607.747 317.632C632.173 341.947 629.612 372.898 619.872 397.936C610.185 422.833 591.557 447.826 572.732 469.124C553.591 490.78 532.713 510.308 516.779 524.318C508.775 531.355 501.936 537.073 497.07 541.052C494.635 543.043 492.689 544.603 491.334 545.679C490.657 546.217 490.126 546.635 489.756 546.926C489.571 547.071 489.425 547.184 489.321 547.265C489.269 547.305 489.227 547.338 489.196 547.362C489.181 547.374 489.168 547.385 489.157 547.393C489.153 547.397 489.147 547.401 489.144 547.403C489.134 547.4 488.837 547.06 473.001 528.499L489.135 547.411C478.157 555.911 462.033 554.334 453.122 543.89C444.213 533.448 445.887 518.094 456.861 509.592C456.863 509.591 456.865 509.588 456.869 509.586C456.88 509.577 456.902 509.561 456.933 509.536C456.997 509.487 457.101 509.404 457.245 509.292C457.533 509.066 457.979 508.715 458.569 508.247C459.749 507.31 461.506 505.901 463.742 504.073C468.216 500.414 474.589 495.088 482.073 488.508C497.114 475.284 516.315 457.282 533.578 437.75C551.157 417.862 565.26 398.01 571.859 381.048C578.403 364.227 575.681 356.302 570.724 351.367C568.928 349.579 567.744 348.902 567.267 348.676C566.888 348.496 566.811 348.52 566.804 348.52C566.605 348.513 563.971 348.537 557.953 352.3C545.161 360.299 528.815 377.492 506.807 403.867C494.927 418.106 481.871 434.435 467.547 451.957C463.709 457.28 459.503 462.538 454.91 467.717L454.702 467.549C420.808 508.347 380.37 553.856 332.335 593.848C301.853 619.226 262.656 622.597 228.642 614.743C194.834 606.936 162.658 587.448 142.217 561.686C108.054 518.631 100.57 469.801 108.223 427.836C115.56 387.606 137.391 351.005 166.502 331.557C161.248 315.813 156.813 299.49 153.519 283.013C142.593 228.368 143.239 167.031 174.28 119.619C186.922 100.31 205.846 89.1535 227.387 85.2773C248.1 81.5504 270.278 84.648 291.495 91.399ZM378.642 206.356C345.773 172.563 307.463 147.917 275.208 137.654C259.096 132.527 246.171 131.514 236.828 133.195C228.314 134.727 222.227 138.497 217.721 145.38C196.712 177.468 193.858 224.004 203.82 273.827C206.532 287.394 210.127 300.834 214.345 313.817C236.45 310.276 260.156 311.463 281.22 317.11C319.621 327.403 357.501 355.419 357.501 405.654C357.501 435.255 339.111 465.136 307.278 473.815C273.211 483.103 238.854 464.822 213.105 427.541C203.716 413.947 194.443 397.766 185.947 379.89C174.028 392.223 163.08 411.953 158.673 436.118C153.128 466.518 158.514 501.286 183.085 532.253C195.993 548.522 217.742 562.031 240.771 567.349C263.594 572.619 284.147 569.24 298.664 557.154C349.383 514.927 390.709 466.547 426.366 422.952C448.879 390.86 453.195 356.06 445.578 321.265C436.703 280.718 411.425 240.06 378.642 206.356ZM306.296 405.722C306.296 384.769 292.223 370.736 267.284 364.051C256.012 361.03 244.156 360.087 233.095 360.771C240.361 375.935 248.168 389.513 255.897 400.704C275.647 429.298 289.989 427.822 293.247 426.934C298.737 425.437 306.296 418.161 306.296 405.722Z";
|
||||
import { PaseoMark as CanonicalPaseoMark } from "../../paseo-brand";
|
||||
|
||||
export function PaseoMark({ size = 20, className }: { size?: number; className?: string }) {
|
||||
return (
|
||||
<svg
|
||||
width={size}
|
||||
height={size}
|
||||
viewBox="0 0 700 700"
|
||||
fill="currentColor"
|
||||
className={className}
|
||||
aria-hidden="true"
|
||||
>
|
||||
<path transform="translate(350,350) scale(1.05) translate(-350,-350)" d={BUTTERFLY_D} />
|
||||
</svg>
|
||||
);
|
||||
return <CanonicalPaseoMark width={size} height={size} className={className} />;
|
||||
}
|
||||
|
||||
/** A hashed identity tile — one letter on a muted identity fill. */
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
import { readFileSync } from "node:fs";
|
||||
import path from "node:path";
|
||||
import { renderToStaticMarkup } from "react-dom/server";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { HubLockup, PaseoHubLockup, PaseoHubMark, PaseoLockup, PaseoMark } from "./paseo-brand";
|
||||
|
||||
const REPO_ROOT = path.resolve(import.meta.dirname, "../../../..");
|
||||
const BRAND_ROOT = path.join(REPO_ROOT, "assets/brand");
|
||||
const WEBSITE_PUBLIC = path.join(REPO_ROOT, "packages/website/public");
|
||||
|
||||
function extractPathData(svg: string): string[] {
|
||||
return [...svg.matchAll(/\bd="([^"]+)"/g)].map((m) => m[1]);
|
||||
}
|
||||
|
||||
describe("paseo brand assets", () => {
|
||||
it("renders canonical Paseo and Paseo Hub marks with currentColor", () => {
|
||||
const paseoHtml = renderToStaticMarkup(<PaseoMark className="h-6 w-6" />);
|
||||
const hubHtml = renderToStaticMarkup(<PaseoHubMark className="h-6 w-6" />);
|
||||
const canonicalPaseo = readFileSync(path.join(BRAND_ROOT, "marks/paseo-white.svg"), "utf8");
|
||||
const canonicalHub = readFileSync(path.join(BRAND_ROOT, "marks/paseo-hub-white.svg"), "utf8");
|
||||
|
||||
expect(paseoHtml).toContain('viewBox="0 0 700 700"');
|
||||
expect(paseoHtml).toContain('stroke="currentColor"');
|
||||
expect(paseoHtml).toContain('stroke-width="50"');
|
||||
expect(extractPathData(paseoHtml)).toEqual(extractPathData(canonicalPaseo));
|
||||
|
||||
expect(hubHtml).toContain('viewBox="0 0 700 700"');
|
||||
expect(hubHtml).toContain('stroke="currentColor"');
|
||||
expect(hubHtml).toContain('stroke-width="50"');
|
||||
expect(extractPathData(hubHtml)).toEqual(extractPathData(canonicalHub));
|
||||
});
|
||||
|
||||
it("renders canonical Paseo, Paseo Hub, and Hub lockups at shared 144-unit height", () => {
|
||||
const cases = [
|
||||
{ Component: PaseoLockup, file: "lockups/paseo-white.svg", width: 580 },
|
||||
{ Component: PaseoHubLockup, file: "lockups/paseo-hub-white.svg", width: 842 },
|
||||
{ Component: HubLockup, file: "lockups/hub-white.svg", width: 461 },
|
||||
];
|
||||
|
||||
for (const { Component, file, width } of cases) {
|
||||
const html = renderToStaticMarkup(<Component className="h-6 w-auto" />);
|
||||
const canonical = readFileSync(path.join(BRAND_ROOT, file), "utf8");
|
||||
|
||||
expect(html).toContain(`viewBox="0 0 ${width} 144"`);
|
||||
expect(html).toContain(`width="${width}"`);
|
||||
expect(html).toContain('height="144"');
|
||||
expect(html).toContain('stroke="currentColor"');
|
||||
expect(html).toContain('fill="currentColor"');
|
||||
expect(extractPathData(html)).toEqual(extractPathData(canonical));
|
||||
}
|
||||
});
|
||||
|
||||
it("keeps public/logo.svg and public/favicon.svg aligned with assets/brand", () => {
|
||||
const canonicalPaseo = readFileSync(path.join(BRAND_ROOT, "marks/paseo-white.svg"), "utf8");
|
||||
const publicLogo = readFileSync(path.join(WEBSITE_PUBLIC, "logo.svg"), "utf8");
|
||||
const publicFavicon = readFileSync(path.join(WEBSITE_PUBLIC, "favicon.svg"), "utf8");
|
||||
|
||||
expect(publicLogo).toBe(canonicalPaseo);
|
||||
expect(publicFavicon).toContain('<rect width="700" height="700" rx="156" fill="#000000"');
|
||||
expect(extractPathData(publicFavicon)).toEqual(extractPathData(canonicalPaseo));
|
||||
});
|
||||
|
||||
it("ships a multi-size favicon.ico with 48, 32, and 16px entries", () => {
|
||||
const ico = readFileSync(path.join(WEBSITE_PUBLIC, "favicon.ico"));
|
||||
expect(ico.readUInt16LE(0)).toBe(0);
|
||||
expect(ico.readUInt16LE(2)).toBe(1);
|
||||
const count = ico.readUInt16LE(4);
|
||||
const sizes: number[] = [];
|
||||
for (let i = 0; i < count; i += 1) {
|
||||
sizes.push(ico[6 + i * 16] || 256);
|
||||
}
|
||||
expect(sizes).toEqual([48, 32, 16]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,154 @@
|
||||
// Canonical Paseo and Paseo Hub brand marks and lockups, sourced directly from
|
||||
// `assets/brand/` (see `assets/brand/README.md`).
|
||||
|
||||
import type * as React from "react";
|
||||
import hubLockupSvg from "../../../../assets/brand/lockups/hub-white.svg?raw";
|
||||
import paseoHubLockupSvg from "../../../../assets/brand/lockups/paseo-hub-white.svg?raw";
|
||||
import paseoLockupSvg from "../../../../assets/brand/lockups/paseo-white.svg?raw";
|
||||
import paseoHubMarkSvg from "../../../../assets/brand/marks/paseo-hub-white.svg?raw";
|
||||
import paseoMarkSvg from "../../../../assets/brand/marks/paseo-white.svg?raw";
|
||||
|
||||
interface ParsedMark {
|
||||
width: number;
|
||||
height: number;
|
||||
viewBox: string;
|
||||
path: string;
|
||||
strokeWidth: number;
|
||||
}
|
||||
|
||||
interface ParsedLockup extends ParsedMark {
|
||||
wordmarkPath: string;
|
||||
}
|
||||
|
||||
function readAttr(tag: string, name: string, source: string): string {
|
||||
const match = tag.match(new RegExp(`${name}="([^"]+)"`));
|
||||
if (!match) {
|
||||
throw new Error(`Missing ${name} attribute in canonical brand SVG (${source})`);
|
||||
}
|
||||
return match[1];
|
||||
}
|
||||
|
||||
function parseSvgHeader(svg: string, source: string) {
|
||||
const svgTag = svg.match(/<svg\b[^>]*>/)?.[0];
|
||||
if (!svgTag) {
|
||||
throw new Error(`Missing <svg> root in canonical brand SVG (${source})`);
|
||||
}
|
||||
const paths = [...svg.matchAll(/<path\b[^>]*\/?>/g)].map((m) => m[0]);
|
||||
return {
|
||||
width: Number(readAttr(svgTag, "width", source)),
|
||||
height: Number(readAttr(svgTag, "height", source)),
|
||||
viewBox: readAttr(svgTag, "viewBox", source),
|
||||
paths,
|
||||
};
|
||||
}
|
||||
|
||||
function parseMark(svg: string, source: string): ParsedMark {
|
||||
const { width, height, viewBox, paths } = parseSvgHeader(svg, source);
|
||||
if (paths.length !== 1) {
|
||||
throw new Error(`Expected 1 path in brand mark SVG (${source}), found ${paths.length}`);
|
||||
}
|
||||
return {
|
||||
width,
|
||||
height,
|
||||
viewBox,
|
||||
path: readAttr(paths[0], "d", source),
|
||||
strokeWidth: Number(readAttr(paths[0], "stroke-width", source)),
|
||||
};
|
||||
}
|
||||
|
||||
function parseLockup(svg: string, source: string): ParsedLockup {
|
||||
const { width, height, viewBox, paths } = parseSvgHeader(svg, source);
|
||||
if (paths.length !== 2) {
|
||||
throw new Error(`Expected 2 paths in brand lockup SVG (${source}), found ${paths.length}`);
|
||||
}
|
||||
return {
|
||||
width,
|
||||
height,
|
||||
viewBox,
|
||||
path: readAttr(paths[0], "d", source),
|
||||
strokeWidth: Number(readAttr(paths[0], "stroke-width", source)),
|
||||
wordmarkPath: readAttr(paths[1], "d", source),
|
||||
};
|
||||
}
|
||||
|
||||
const PASEO_MARK = parseMark(paseoMarkSvg, "marks/paseo-white.svg");
|
||||
const PASEO_HUB_MARK = parseMark(paseoHubMarkSvg, "marks/paseo-hub-white.svg");
|
||||
const PASEO_LOCKUP = parseLockup(paseoLockupSvg, "lockups/paseo-white.svg");
|
||||
const PASEO_HUB_LOCKUP = parseLockup(paseoHubLockupSvg, "lockups/paseo-hub-white.svg");
|
||||
const HUB_LOCKUP = parseLockup(hubLockupSvg, "lockups/hub-white.svg");
|
||||
|
||||
function BrandMark({ asset, props }: { asset: ParsedMark; props: React.SVGProps<SVGSVGElement> }) {
|
||||
return (
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
width={asset.width}
|
||||
height={asset.height}
|
||||
viewBox={asset.viewBox}
|
||||
fill="none"
|
||||
aria-hidden="true"
|
||||
{...props}
|
||||
>
|
||||
<path
|
||||
d={asset.path}
|
||||
stroke="currentColor"
|
||||
strokeWidth={asset.strokeWidth}
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
/>
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
function BrandLockup({
|
||||
asset,
|
||||
props,
|
||||
}: {
|
||||
asset: ParsedLockup;
|
||||
props: React.SVGProps<SVGSVGElement>;
|
||||
}) {
|
||||
return (
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
width={asset.width}
|
||||
height={asset.height}
|
||||
viewBox={asset.viewBox}
|
||||
fill="none"
|
||||
aria-hidden="true"
|
||||
{...props}
|
||||
>
|
||||
<path
|
||||
d={asset.path}
|
||||
stroke="currentColor"
|
||||
strokeWidth={asset.strokeWidth}
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
/>
|
||||
<path d={asset.wordmarkPath} fill="currentColor" />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
/** Canonical Paseo butterfly mark (700x700 viewBox, stroked with currentColor). */
|
||||
export function PaseoMark(props: React.SVGProps<SVGSVGElement>) {
|
||||
return <BrandMark asset={PASEO_MARK} props={props} />;
|
||||
}
|
||||
|
||||
/** Canonical Paseo Hub five-petal flower mark (700x700 viewBox, stroked with currentColor). */
|
||||
export function PaseoHubMark(props: React.SVGProps<SVGSVGElement>) {
|
||||
return <BrandMark asset={PASEO_HUB_MARK} props={props} />;
|
||||
}
|
||||
|
||||
/** Canonical Paseo lockup (butterfly mark at 94% optical scale + Plus Jakarta Sans SemiBold). */
|
||||
export function PaseoLockup(props: React.SVGProps<SVGSVGElement>) {
|
||||
return <BrandLockup asset={PASEO_LOCKUP} props={props} />;
|
||||
}
|
||||
|
||||
/** Canonical Paseo Hub lockup (flower mark + Plus Jakarta Sans SemiBold). */
|
||||
export function PaseoHubLockup(props: React.SVGProps<SVGSVGElement>) {
|
||||
return <BrandLockup asset={PASEO_HUB_LOCKUP} props={props} />;
|
||||
}
|
||||
|
||||
/** Canonical Hub lockup (flower mark + "Hub"), used where Paseo is already on screen. */
|
||||
export function HubLockup(props: React.SVGProps<SVGSVGElement>) {
|
||||
return <BrandLockup asset={HUB_LOCKUP} props={props} />;
|
||||
}
|
||||
@@ -3,6 +3,7 @@ import { PLUGINS_LINKED } from "~/plugins/launch";
|
||||
import "~/styles.css";
|
||||
import { DiscordIcon, GitHubIcon } from "~/components/brand-icons";
|
||||
import { LanguageSelector } from "~/components/language-selector";
|
||||
import { PaseoLockup } from "~/components/paseo-brand";
|
||||
import { useLocalizePath } from "~/i18n";
|
||||
import { useStars } from "~/routes/__root";
|
||||
|
||||
@@ -14,9 +15,12 @@ export function SiteHeader() {
|
||||
const { stars } = useStars();
|
||||
return (
|
||||
<header className="flex flex-col items-center gap-4 md:flex-row md:justify-between">
|
||||
<a href={localize("/")} className="flex items-center gap-3">
|
||||
<img src="/logo.svg" alt="Paseo" className="w-6 h-6" />
|
||||
<span className="text-lg font-medium">Paseo</span>
|
||||
<a
|
||||
href={localize("/")}
|
||||
aria-label="Paseo"
|
||||
className="inline-flex items-center text-foreground"
|
||||
>
|
||||
<PaseoLockup className="h-[22px] w-auto" />
|
||||
</a>
|
||||
<div className="flex flex-wrap items-center justify-center gap-4">
|
||||
{PLUGINS_LINKED && (
|
||||
|
||||
@@ -9,6 +9,7 @@ import { useTranslation } from "react-i18next";
|
||||
import { buildDocsNavTree, getDoc, getDocs } from "~/docs";
|
||||
import { splitLocalePath, useLocale, useLocalizePath } from "~/i18n";
|
||||
import { LanguageSelector } from "~/components/language-selector";
|
||||
import { PaseoLockup } from "~/components/paseo-brand";
|
||||
import "~/styles.css";
|
||||
|
||||
export const Route = createFileRoute("/{-$locale}/docs")({
|
||||
@@ -35,9 +36,12 @@ function DocsLayout() {
|
||||
{/* Mobile header */}
|
||||
<header className="lg:hidden sticky top-0 z-50 bg-background border-b border-border">
|
||||
<div className="flex items-center justify-between p-4">
|
||||
<Link to={localize("/")} className="flex items-center gap-3">
|
||||
<img src="/logo.svg" alt="Paseo" className="w-6 h-6" />
|
||||
<span className="text-lg font-medium">Paseo</span>
|
||||
<Link
|
||||
to={localize("/")}
|
||||
aria-label="Paseo"
|
||||
className="inline-flex items-center text-foreground"
|
||||
>
|
||||
<PaseoLockup className="h-[22px] w-auto" />
|
||||
</Link>
|
||||
<div className="flex items-center gap-3">
|
||||
<LanguageSelector />
|
||||
@@ -63,9 +67,12 @@ function DocsLayout() {
|
||||
{/* Desktop sidebar */}
|
||||
<aside className="hidden lg:block sticky top-0 h-screen w-60 shrink-0 border-r border-border p-6 overflow-y-auto">
|
||||
<div className="flex items-center justify-between gap-3 mb-8">
|
||||
<Link to={localize("/")} className="flex items-center gap-3">
|
||||
<img src="/logo.svg" alt="Paseo" className="w-6 h-6" />
|
||||
<span className="text-lg font-medium">Paseo</span>
|
||||
<Link
|
||||
to={localize("/")}
|
||||
aria-label="Paseo"
|
||||
className="inline-flex items-center text-foreground"
|
||||
>
|
||||
<PaseoLockup className="h-[22px] w-auto" />
|
||||
</Link>
|
||||
<LanguageSelector />
|
||||
</div>
|
||||
|
||||