Compare commits

...
Author SHA1 Message Date
paseo-bot[bot] eba7d0ca14 fix(server): keep OpenCode parents usable after child worktree removal
OpenCode keeps the child session after its working directory is removed. Skip runtime reconciliation for that child when OpenCode returns LocationNotFoundError so the parent can resume and accept prompts.
2026-12-04 12:34:35 +00:00
paseo-bot[bot]andClaude Opus 5.5 35f0ff6ff1 Stop the relay E2E from losing its port to a parallel test (#12017)
* test(relay): let wrangler pick the relay port in the relay E2E

The relay E2E reserved a free port, closed it, then started wrangler on it.
Test files run three at a time, and another file could bind the port in
between: workerd failed with "Address already in use" and the test failed
with "Local relay did not stop". Wrangler now binds port 0 itself and the
test reads the port from its "Ready on" line.

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

* test(relay): read the relay port from a complete line, keep startup errors

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

---------

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-04 12:00:40 +00:00
paseo-bot[bot] b31565fbf7 fix(terminal): paste once on Linux middle-click (#12025)
Mouse tracking sends the click to the terminal application, while Chromium also pastes the primary selection on release. Suppress the native paste when the application owns the press, and leave the terminal paste available for the shell or forced selection.

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-12-04 10:43:42 +00:00
paseo-bot[bot] 8302319f54 Keep old replies out of finish notifications (#12014)
* fix(server): keep old replies out of finish notifications

A tool-only turn can finish without producing a reply. Scope the preview to the completed turn so the notification uses the existing generic body when that turn has no reply.

* fix(server): keep background finish previews through runtime refresh

---------

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-12-04 10:43:19 +00:00
babo-jeongukandClaude Opus 5.5 8b0c22ca31 fix(server): persist the last user message time once a submitted prompt is recorded (#12011)
Since the timeline moved to async SQLite commits, a prompt submitted through
Paseo set lastUserMessageAt in the commit callback without emitting state.
The stored record and the live agent_state kept the previous prompt's time
until the next state change, and a daemon crash in that window left the
record stale after restart.

Set lastUserMessageAt and emit state at the timeline commit point for every
user_message, and drop the two caller-side copies of that rule.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-04 10:42:59 +00:00
TheCouchCommanderandCodex 26175ed408 Coalesce Gitea and Forgejo PR status polling and honor rate limits (#12004)
* Coalesce Gitea PR status polling and honor rate limits

* Honor Forgejo proxy backoff and share Actions task reads

---------

Co-authored-by: Codex <codex@localhost>
2026-12-04 09:13:03 +00:00
paseo-bot[bot] 41e21d8d5f fix(desktop): keep the workspace aligned when editing chat drafts (#11983)
Anchor the top resize strip to the titlebar edge so titlebar padding cannot create horizontal overflow. Cover Page Down in the packaged desktop smoke test.

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-12-04 08:42:53 +00:00
paseo-bot[bot] 5700dc3ea1 Keep Android image previews sharp when zooming (#11989)
* fix(app): keep Android image previews sharp when zooming

Android decodes the image to the fitted layout size by default. A pinch scales that bitmap, so details lost during decoding cannot come back. Preserve the source resolution in the zoomable image viewer.

* Keep Android zoom detail within the native bitmap limit

* Remove the obsolete Git object in the plugin update test

---------

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-12-04 08:13:02 +00:00
Mohamed Boudra aabb5764d3 ci(website): isolate website tests from typecheck and clean up E2E specs (#11992)
* ci(website): isolate website tests from typecheck and clean up E2E specs

Website Playwright runs were bundled into the required typecheck job, so WebKit downloads and website timing failures blocked unrelated PRs. Moving website unit and E2E runs into a dedicated website-tests job keeps typecheck focused on build and type verification.

Also remove layout/geometry assertions and fake-clock mockup animation tests from packages/website/e2e, keeping interactive user journeys and placement-specific checks, and align Playwright CI workers and retries with the app and desktop suites.

* ci(website): include README sponsor tables in website path filter
2026-12-04 15:12:47 +07:00
Mohamed Boudra 4fe15a6918 fix(plugins): keep Git plugin revision lookup local in blobless clones (#11999)
Switching Git plugin clones to --filter=blob:none registered a promisor remote in the cloned repository, causing rev-parse to lazily fetch unadvertised or amended-away commits from origin (without GIT_ENV or credential rewrites) instead of failing revision verification. Set GIT_NO_LAZY_FETCH=1 on revParse so revision lookups stay strictly against the cloned refs and commit graph while checkout continues fetching blobs on demand. Also route managed-source.ts changes through the browser CI path filter.
2026-12-04 14:35:36 +07:00
Mohamed Boudra 32a5dd8bad test(e2e): approve AgentChat client plugins in browser specs (#11986)
Both AgentChat browser specs (#9602) were merged without calling approveClientPluginsInUi after per-host client plugin execution approval (#11717) landed, causing all 7 tests to time out waiting for the unapproved plugin's sidebar button.
2026-12-04 13:32:30 +07:00
paseo-bot[bot] 70f374f269 fix(desktop): save the stop-on-quit migration (#11984)
Desktop applied the reset in memory on every launch until another setting was saved. Save the reset and its marker together so the settings file reflects the quit policy after the first launch.

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-12-04 06:13:38 +00:00
e31ee658c2 Avoid downloading old files when installing Git plugins (#11980)
* perf(server): clone Git plugin sources without history blobs

- Use blobless clone filter when fetching Git plugin sources to improve install performance
- Add POSIX test verification for blobless git operations

Co-authored-by: RoundRedDot <roundreddot@gmail.com>

* fix(server): preserve credentials during filtered plugin checkout

Co-authored-by: RoundRedDot <roundreddot@gmail.com>

* Merge remote-tracking branch 'origin/main' into fix/plugin-blobless-auth-review

# Conflicts:
#	packages/server/src/server/plugins/managed-source.posix.test.ts

Co-authored-by: RoundRedDot <roundreddot@gmail.com>

* refactor(server): use named Git checkout arguments

Co-authored-by: RoundRedDot <roundreddot@gmail.com>

* Name the bare Git fixture explicitly

Co-authored-by: luke <luopeihuan@gmail.com>

---------

Co-authored-by: luke <luopeihuan@gmail.com>
Co-authored-by: RoundRedDot <roundreddot@gmail.com>
Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-12-04 06:12:59 +00:00
paseo-bot[bot] acde63e614 test(terminal): prove an obsolete worker's program gone by its socket, not its pid (#11967)
On Windows the inspector reports no birth times, so the hard-cut test
could only prove the program gone by its pid not answering. Windows
reuses a freed pid at once, so a busy runner could keep the pid alive
under another process for the whole 10 s wait. The program now listens
on a socket of its own, and the test waits for that socket to close.

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-12-04 06:00:53 +00:00
paseo-bot[bot] 25d9ed2985 fix(app): collapse turns with plugin-rendered work (#11974)
Calculate the summary from the work each card represents so a completed turn folds when a plugin renders its tools and reasoning.

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-12-04 05:12:58 +00:00
50 changed files with 1545 additions and 933 deletions
+11 -1
View File
@@ -72,7 +72,7 @@ browser:
- "packages/server/src/server/agent/providers/codex-app-server-agent.ts"
- "packages/server/src/server/agent/providers/claude/agent.ts"
- "packages/server/src/server/agent/plugin-provider.ts"
- "packages/server/src/server/plugins/{index,plugin-process,plugin-process-protocol,runtime}.ts"
- "packages/server/src/server/plugins/{index,managed-source,plugin-process,plugin-process-protocol,runtime}.ts"
- "packages/server/src/executable-resolution/**"
- "packages/plugin/src/server/provider.ts"
- "packages/app/src/!(desktop)/**"
@@ -88,6 +88,16 @@ browser:
relay:
- "packages/relay/**"
website:
- "packages/website/**"
- "packages/protocol/**"
- "public-docs/**"
- "CHANGELOG.md"
- "CHANGELOG.zh-CN.md"
- "README*.md"
- "assets/brand/**"
- "packages/app/assets/images/editor-apps/finder.png"
# cli-tests is also a daemon end-to-end suite: it drives a real daemon, built-in
# plugins and the plugin runtime included, so their changes run it too.
cli:
+32 -10
View File
@@ -43,6 +43,7 @@ jobs:
browser: ${{ steps.filter.outputs.browser }}
relay: ${{ steps.filter.outputs.relay }}
cli: ${{ steps.filter.outputs.cli }}
website: ${{ steps.filter.outputs.website }}
steps:
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0
with:
@@ -163,12 +164,11 @@ jobs:
- name: Run plugin SDK tests
run: npm run test --workspace=@getpaseo/plugin
# The locked Playwright installers do not support ubuntu-latest's Ubuntu 26.04.
typecheck:
name: typecheck
needs: changes
if: ${{ !cancelled() && (needs.changes.outputs.full != 'false' || needs.changes.outputs.quality != 'false') }}
runs-on: ubuntu-24.04
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
@@ -195,6 +195,32 @@ jobs:
- name: Typecheck all packages
run: npm run typecheck
- name: Verify public package contents
run: |
npm pack --dry-run --ignore-scripts --workspace=@getpaseo/protocol
npm pack --dry-run --ignore-scripts --workspace=@getpaseo/client
npm pack --dry-run --ignore-scripts --workspace=@getpaseo/server
# The locked Playwright installers do not support ubuntu-latest's Ubuntu 26.04.
website-tests:
name: website-tests
needs: changes
if: ${{ !cancelled() && (needs.changes.outputs.full != 'false' || needs.changes.outputs.website != 'false') }}
runs-on: ubuntu-24.04
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: "22"
cache: "npm"
- name: Install dependencies
run: node scripts/npm-retry.mjs ci
- name: Build protocol
run: npm run build:protocol
- name: Run website tests
run: npx vitest run packages/website/src --bail=1
@@ -222,7 +248,7 @@ jobs:
cp "${archive_debs[@]}" ~/website-browser-debs/
fi
- name: Verify website mockups
- name: Run website E2E tests
run: npm run test:e2e --workspace=@getpaseo/website
- name: Upload website test artifacts
@@ -230,16 +256,12 @@ jobs:
if: failure()
with:
name: website-playwright-results
path: packages/website/test-results/
path: |
packages/website/test-results/
packages/website/playwright-report/
if-no-files-found: ignore
retention-days: 7
- name: Verify public package contents
run: |
npm pack --dry-run --ignore-scripts --workspace=@getpaseo/protocol
npm pack --dry-run --ignore-scripts --workspace=@getpaseo/client
npm pack --dry-run --ignore-scripts --workspace=@getpaseo/server
server-tests-ubuntu:
name: server-tests (ubuntu-latest)
needs: changes
@@ -10,6 +10,7 @@ import {
type MockAgentWorkspace,
} from "../support/helpers/mock-agent";
import { connectNewWorkspaceDaemonClient } from "../support/helpers/new-workspace";
import { approveClientPluginsInUi } from "../support/helpers/plugin-execution-approval";
import { pluginRequirements } from "../support/helpers/plugin-fixture";
const PLUGIN_ID = "agent-chat-focus-e2e";
@@ -135,6 +136,7 @@ async function withEmbeds(
await client.patchDaemonConfig({ pluginsEnabled: true });
await client.installDirectoryPlugin(directory);
await gotoAppShell(page);
await approveClientPluginsInUi(page, [PLUGIN_ID]);
await page.getByRole("button", { name: SCREEN_TITLE, exact: true }).click();
const embed = (agentId: string) => page.getByTestId(`embed-${agentId}`);
for (const agent of agents) {
@@ -2,6 +2,7 @@ import { expect, test, type Page } from "../support/fixtures";
import { gotoAppShell } from "../support/helpers/app";
import { openAgentRoute, seedMockAgentWorkspace } from "../support/helpers/mock-agent";
import { connectNewWorkspaceDaemonClient } from "../support/helpers/new-workspace";
import { approveClientPluginsInUi } from "../support/helpers/plugin-execution-approval";
import { copyPluginExample } from "../support/helpers/plugin-fixture";
const PLUGIN_ID = "agent-chat-example";
@@ -14,6 +15,7 @@ function embed(page: Page) {
async function openAgentInEmbed(page: Page): Promise<void> {
await gotoAppShell(page);
await approveClientPluginsInUi(page, [PLUGIN_ID]);
await page.getByRole("button", { name: "Agents", exact: true }).click();
await page
.getByTestId("example-agent-list")
@@ -690,16 +690,20 @@ async function updateGitPlugin(page: Page, repository: string) {
async function failUpdateFromPluginPage(page: Page, repository: string) {
await publishGitPluginChange(repository, "Git plugin v3");
await page.reload();
const update = page.getByTestId("plugin-update").filter({ visible: true });
await expect(update).toHaveText("Update");
// Rewriting the commit the page checked leaves its update pointing at a commit the remote no
// longer serves. The next check offers the rewritten commit.
const update = page.getByRole("button", { name: "Update", exact: true });
await expect(update).toBeVisible();
// Remove the advertised commit from the fixture. A file:// remote can still serve an
// amended-away commit by SHA while its object remains in the repository.
execFileSync("git", ["commit", "--amend", "-m", "Git plugin v3, amended"], {
cwd: repository,
stdio: "ignore",
});
execFileSync("git", ["-c", "gc.reflogExpireUnreachable=now", "gc", "--prune=now"], {
cwd: repository,
stdio: "ignore",
});
await update.click();
await expect(update).toHaveText("Retry");
await expect(page.getByRole("button", { name: "Retry", exact: true })).toBeVisible();
await expect(page.getByText(/Git command failed/)).toBeVisible();
}
@@ -0,0 +1,59 @@
import assert from "node:assert/strict";
import { readFileSync, writeFileSync } from "node:fs";
import { PNG } from "pngjs";
// Generate resolution-chart.png in an Android test workspace with the "fixture" command.
// Open it from Files on a 1080 x 2400 emulator, pinch out by 4x at (540, 1250),
// then pass the zoomed screenshot from adb exec-out screencap -p to the "check" command.
// Generate a 6,000 x 5,000 PNG with "fixture-large" to exercise Android's bitmap size
// limit. Open it from Files at fit and pass the screenshot to the same "check" command.
// Pass the width and height from Expo Image's onLoad event to "check-decode" on an
// emulator with the default 100 MiB canvas limit.
const [command, path, height] = process.argv.slice(2);
assert.ok(
path && ["fixture", "fixture-large", "check", "check-decode"].includes(command),
"Use fixture <png>, fixture-large <png>, check <png>, or check-decode <width> <height>",
);
if (command === "check-decode") {
const width = Number(path);
const decodedHeight = Number(height);
assert.ok(width > 0 && decodedHeight > 0, "Provide the positive decoded dimensions");
assert.ok(
width * decodedHeight * 4 <= 100 * 1024 * 1024,
`Decoded bitmap exceeds 100 MiB at ${width} × ${decodedHeight}`,
);
} else if (command === "fixture" || command === "fixture-large") {
const size =
command === "fixture-large" ? { width: 6000, height: 5000 } : { width: 4000, height: 3000 };
const chart = new PNG(size);
const stripeWidth = command === "fixture-large" ? 240 : 3;
for (let x = 0; x < chart.width; x++) {
const shade = Math.floor(x / stripeWidth) % 2 === 0 ? 0 : 255;
chart.data.set([shade, shade, shade, 255], x * 4);
}
for (let y = 1; y < chart.height; y++) {
chart.data.copy(chart.data, y * chart.width * 4, 0, chart.width * 4);
}
writeFileSync(path, PNG.sync.write(chart));
} else {
const screenshot = PNG.sync.read(readFileSync(path));
assert.equal(screenshot.width, 1080, "Use a 1080 x 2400 emulator");
assert.equal(screenshot.height, 2400, "Use a 1080 x 2400 emulator");
// The center of each stripe should be nearly black or white. Antialiased edges
// may stay gray, so sample a wide span and allow for those pixels.
const row = 1200;
let dark = 0;
let light = 0;
for (let x = 340; x < 740; x++) {
const shade = screenshot.data[(row * screenshot.width + x) * 4];
if (shade < 35) dark++;
if (shade > 220) light++;
}
assert.ok(
dark >= 80 && light >= 80,
`Fine stripes lost contrast (${dark} dark, ${light} light pixels)`,
);
}
@@ -948,3 +948,46 @@ it.each([false, true])(
expect(opened.groupsByHostId.size).toBe(0);
},
);
it("folds a completed turn whose plugin replaces every tool and reasoning row", () => {
const present = createStreamPresentation();
const timestamp = new Date();
const tail: StreamItem[] = [
{ kind: "user_message", id: "prompt", text: "Work", timestamp },
{ kind: "thought", id: "reasoning", text: "Plan", status: "ready", timestamp },
toolCall("one", "Bash"),
{ kind: "assistant_message", id: "reply", text: "Done", timestamp },
];
const toolPlugin = installedTransform(installProbe("tool_call"));
const reasoningPlugin = installedTransform(installProbe("reasoning"));
const input = {
...presentationOptions,
tail,
head: [],
display: "collapseTurns" as const,
isTurnActive: false,
};
const transform: TimelineItemTransform = (item) =>
toolPlugin(item)?.flatMap((card) => [card, { ...card, id: `${card.id}/detail` }]) ??
reasoningPlugin(item);
const control = present({ ...input, transform: undefined });
expect(control.tail.map((item) => item.kind)).toEqual([
"user_message",
"turn_summary",
"assistant_message",
]);
const closed = present({ ...input, transform });
expect(closed.tail.map((item) => item.kind)).toEqual(control.tail.map((item) => item.kind));
expect(closed.turns.summaryRowsByHostId.get("prompt")?.tools).toEqual(
control.turns.summaryRowsByHostId.get("prompt")?.tools,
);
const opened = present({ ...input, transform, expandedTurnHostIds: new Set(["prompt"]) });
expect(opened.tail.map((item) => item.kind)).toEqual([
"user_message",
"turn_summary",
"plugin",
"plugin",
"plugin",
"assistant_message",
]);
});
@@ -45,9 +45,14 @@ function summarizeTurn(
getGroupedCalls: CollapseTurnsInput["getGroupedCalls"],
): OverviewSummary {
const calls: (ToolCallItem | ThoughtItem)[] = [];
const countedSources = new Set<string>();
for (const item of items) {
if ((item.kind === "tool_call" || item.kind === "thought") && !isTurnTrigger(item))
calls.push(...(getGroupedCalls(item.id) ?? [item]));
const source = item.kind === "plugin" ? item.source : item;
if (!source || (source.kind !== "tool_call" && source.kind !== "thought")) continue;
if (isTurnTrigger(source) || countedSources.has(source.id)) continue;
// One source tool call can render as several plugin cards.
countedSources.add(source.id);
calls.push(...(getGroupedCalls(source.id) ?? [source]));
}
return summarizeToolCalls(calls);
}
@@ -46,6 +46,7 @@ const DRAG_OVERLAY_STYLE: React.CSSProperties = {
const TOP_RESIZER_STYLE: React.CSSProperties = {
position: "absolute",
top: 0,
left: 0,
width: "100%",
height: 4,
// @ts-expect-error — WebkitAppRegion is not in CSSProperties
@@ -1,6 +1,6 @@
import { useCallback, useEffect, useMemo, useState } from "react";
import { Image } from "expo-image";
import { View, type StyleProp, type ViewStyle } from "react-native";
import { Platform, View, type StyleProp, type ViewStyle } from "react-native";
import { StyleSheet, withUnistyles } from "react-native-unistyles";
import type { ViewportFitOptions, ViewportSize } from "./geometry";
import { measureImage } from "./image-size";
@@ -84,7 +84,9 @@ export function ZoomableImage({
<ViewportImage
// No transition, so the image appears together with its toolbar.
transition={null}
contentFit="contain"
// The viewport already fits the image's aspect ratio. On Android, fill selects
// Expo Image's bitmap size cap while preserving detail below that cap for zoom.
contentFit={Platform.OS === "android" ? "fill" : "contain"}
onError={onError}
onLoad={handleLoad}
source={source}
@@ -475,6 +475,47 @@ describe("terminal emulator runtime in a real browser", () => {
expect(mounted.inputs).toEqual(["legacy renderer paste"]);
});
it.skipIf(!navigator.platform.includes("Linux")).each([
{
mode: "mouse tracking",
sequence: "\x1b[?1000h\x1b[?1006h",
shiftKey: false,
reportsMouse: true,
},
{ mode: "shell", sequence: "", shiftKey: false, reportsMouse: false },
{
mode: "forced selection",
sequence: "\x1b[?1000h\x1b[?1006h",
shiftKey: true,
reportsMouse: false,
},
])(
"routes a middle click in $mode to one input path",
async ({ sequence, shiftKey, reportsMouse }) => {
const mounted = createTerminalHost({ width: 720, height: 360 });
await new Promise<void>((resolve) =>
mounted.runtime.write({ data: terminalOutput(sequence + "ready"), onCommitted: resolve }),
);
const screen = mounted.host.querySelector(".xterm-screen")!;
const bounds = screen.getBoundingClientRect();
const mouse = {
button: 1,
bubbles: true,
cancelable: true,
shiftKey,
clientX: bounds.x + 2,
clientY: bounds.y + 2,
};
screen.dispatchEvent(new MouseEvent("mousedown", { ...mouse, buttons: 4 }));
const release = new MouseEvent("mouseup", mouse);
screen.dispatchEvent(release);
expect(mounted.inputs).toEqual(reportsMouse ? ["\x1b[<1;1;1M", "\x1b[<1;1;1m"] : []);
expect(release.defaultPrevented).toBe(reportsMouse);
},
);
it("pastes clipboard text on Ctrl+V without reading the clipboard image", async () => {
const mounted = createTerminalHost({ width: 720, height: 360, isMac: false });
await waitFor({ predicate: () => mounted.sizes.length > 0 });
@@ -124,6 +124,7 @@ interface TerminalEmulatorRuntimeDisposables {
clearFitTimeouts: () => void;
removeFontListeners: () => void;
removeFilePasteListener: () => void;
removeMiddleClickListeners: () => void;
removeUserInputListeners: () => void;
restoreDocumentStyles: () => void;
restoreViewportStyles: () => void;
@@ -782,6 +783,26 @@ export class TerminalEmulatorRuntime {
};
input.host.addEventListener("paste", filePasteHandler, true);
// Chromium pastes the Linux primary selection on middle-button release.
// If xterm sent the press to the PTY, the application owns that gesture.
let middlePressReported = false;
const recordMiddlePress = (event: MouseEvent): void => {
if (event.button === 1) {
middlePressReported = !event.shiftKey && terminal.modes.mouseTrackingMode !== "none";
}
};
const cancelReportedMiddleRelease = (event: MouseEvent): void => {
if (event.button === 1 && middlePressReported) {
middlePressReported = false;
event.preventDefault();
}
};
const terminalElement = terminal.element;
if (navigator.platform.includes("Linux")) {
terminalElement?.addEventListener("mousedown", recordMiddlePress, true);
terminalElement?.addEventListener("mouseup", cancelReportedMiddleRelease, true);
}
const resizeObserver = new ResizeObserver(() => {
fitAndEmitResize({ shouldClaim: false });
});
@@ -864,6 +885,10 @@ export class TerminalEmulatorRuntime {
removeFilePasteListener: () => {
input.host.removeEventListener("paste", filePasteHandler, true);
},
removeMiddleClickListeners: () => {
terminalElement?.removeEventListener("mousedown", recordMiddlePress, true);
terminalElement?.removeEventListener("mouseup", cancelReportedMiddleRelease, true);
},
removeUserInputListeners: () => {
for (const type of USER_INPUT_EVENT_TYPES) {
input.host.removeEventListener(type, recordUserInputEvent, true);
@@ -899,6 +924,7 @@ export class TerminalEmulatorRuntime {
disposables.clearFitTimeouts();
disposables.removeFontListeners();
disposables.removeFilePasteListener();
disposables.removeMiddleClickListeners();
disposables.removeUserInputListeners();
disposables.disposeFitAddon();
disposables.disposeWebglAddon();
+22 -1
View File
@@ -1215,6 +1215,27 @@ async function stopCliDaemon({ appPath, env }) {
});
}
async function expectPageDownKeepsWorkspaceAligned(page) {
const composer = page.getByRole("textbox", { name: "Message agent..." });
const newTab = page.getByRole("button", { name: "New tab", exact: true });
await composer.fill("Keep the workspace in place");
await composer.press("ArrowLeft");
const before = await newTab.boundingBox();
assert.ok(before, "Workspace tab controls are visible before Page Down");
await composer.press("PageDown");
await page.evaluate(
() =>
new Promise((resolve) => {
requestAnimationFrame(() => requestAnimationFrame(() => resolve()));
}),
);
const after = await newTab.boundingBox();
assert.ok(after, "Workspace tab controls are visible after Page Down");
assert.equal(after.x, before.x, "Page Down in the chat draft keeps the workspace aligned");
}
async function openSmokeWorkspace({ appPath, env, page, daemonHome }) {
const projectPath = path.join(daemonHome, "sandbox-smoke-project");
fs.mkdirSync(projectPath);
@@ -1242,7 +1263,7 @@ async function openSmokeWorkspace({ appPath, env, page, daemonHome }) {
await page.getByRole("button", { name: "Sandbox smoke workspace", exact: true }).click();
await page.waitForURL((url) => url.pathname.endsWith(`/workspace/${workspace.workspaceId}`));
await page.getByRole("button", { name: "Agent", exact: true }).click();
await page.getByRole("textbox", { name: "Message agent..." }).click();
await expectPageDownKeepsWorkspaceAligned(page);
console.log(`Packaged desktop smoke: renderer opened workspace ${workspace.workspaceId}`);
}
@@ -239,7 +239,7 @@ describe("desktop-settings", () => {
expect(persisted.settings.daemon.manageBuiltInDaemon).toBe(false);
});
it("does not rewrite existing settings while reading them", async () => {
it("does not rewrite migrated settings while reading them", async () => {
const userDataPath = await createTempUserDataDir();
directories.add(userDataPath);
const raw = JSON.stringify({
@@ -253,6 +253,7 @@ describe("desktop-settings", () => {
},
migrations: {
legacyRendererSettingsImported: false,
daemonStopOnQuitDefaultApplied: true,
},
});
await writeFile(settingsFilePath(userDataPath), raw);
@@ -265,7 +266,7 @@ describe("desktop-settings", () => {
expect(persisted).toBe(raw);
});
it("resets the pre-existing keep-running default so the daemon stops with the app", async () => {
it("persists the stop-on-quit migration on the first read", async () => {
const userDataPath = await createTempUserDataDir();
directories.add(userDataPath);
await writeFile(
@@ -276,7 +277,7 @@ describe("desktop-settings", () => {
releaseChannel: "stable",
daemon: { manageBuiltInDaemon: true, keepRunningAfterQuit: true },
},
migrations: { legacyRendererSettingsImported: true },
futureSetting: { value: 7 },
}),
);
const store = createDesktopSettingsStore({ userDataPath });
@@ -284,6 +285,12 @@ describe("desktop-settings", () => {
const settings = await store.get();
expect(settings.daemon.keepRunningAfterQuit).toBe(false);
const persisted = JSON.parse(await readFile(settingsFilePath(userDataPath), "utf8"));
expect(persisted).toMatchObject({
settings: { daemon: { manageBuiltInDaemon: true, keepRunningAfterQuit: false } },
migrations: { daemonStopOnQuitDefaultApplied: true },
futureSetting: { value: 7 },
});
});
it("keeps an explicit keep-running choice across restarts", async () => {
@@ -238,12 +238,9 @@ function hasLegacyRendererOwnedPatch(patch: DesktopSettingsPatch): boolean {
return patch.releaseChannel !== undefined || patch.daemon?.manageBuiltInDaemon !== undefined;
}
function coerceDocument(input: unknown): PersistedDesktopSettingsDocument {
const document = PersistedDocumentSchema.parse(input);
if (document.migrations.daemonStopOnQuitDefaultApplied) {
return document;
}
function applyDaemonStopOnQuitDefault(
document: PersistedDesktopSettingsDocument,
): PersistedDesktopSettingsDocument {
return {
...document,
settings: {
@@ -283,45 +280,39 @@ export function createDesktopSettingsStore({
cachedDocument = document;
}
async function loadDocumentUnlocked(): Promise<PersistedDesktopSettingsDocument> {
async function loadDocumentUnlocked({
recoverUnreadable = false,
} = {}): Promise<PersistedDesktopSettingsDocument> {
if (cachedDocument) {
return cachedDocument;
}
let raw: string;
let document: PersistedDesktopSettingsDocument;
try {
raw = await readFile(filePath, "utf8");
const raw = await readFile(filePath, "utf8");
document = PersistedDocumentSchema.parse(JSON.parse(raw));
} catch (error) {
if (!isNodeError(error) || error.code !== "ENOENT") {
if (!recoverUnreadable && (!isNodeError(error) || error.code !== "ENOENT")) {
throw error;
}
const document = buildDefaultDocument();
await writeDocument(document);
return document;
const defaults = buildDefaultDocument();
await writeDocument(defaults);
return defaults;
}
const document = coerceDocument(JSON.parse(raw));
if (!document.migrations.daemonStopOnQuitDefaultApplied) {
const migrated = applyDaemonStopOnQuitDefault(document);
await writeDocument(migrated);
return migrated;
}
cachedDocument = document;
return document;
}
async function initializeLegacyRendererMigrationUnlocked(): Promise<PersistedDesktopSettingsDocument> {
try {
return await loadDocumentUnlocked();
} catch {
const document = buildDefaultDocument();
await writeDocument(document);
return document;
}
}
return {
async get(): Promise<DesktopSettings> {
const document = await enqueueOperation(async () => {
if (cachedDocument) {
return cachedDocument;
}
return loadDocumentUnlocked();
});
const document = await enqueueOperation(() => loadDocumentUnlocked());
return toDesktopSettings(document.settings);
},
@@ -346,7 +337,7 @@ export function createDesktopSettingsStore({
async migrateLegacyRendererSettings(legacySettings: unknown): Promise<DesktopSettings> {
return enqueueOperation(async () => {
const current = await initializeLegacyRendererMigrationUnlocked();
const current = await loadDocumentUnlocked({ recoverUnreadable: true });
if (current.migrations.legacyRendererSettingsImported) {
return toDesktopSettings(current.settings);
}
@@ -2393,6 +2393,50 @@ async function createControlledInterruptFixture(options: {
};
}
test("a recorded submitted prompt persists and publishes its time while the turn runs", async () => {
const workdir = mkdtempSync(join(tmpdir(), "agent-manager-submitted-prompt-time-"));
const session = new ControlledInterruptSession(
{ provider: "codex", cwd: workdir },
"turn-submitted-prompt-time",
async () => undefined,
);
const client = new (class extends TestAgentClient {
override async createSession(): Promise<AgentSession> {
return session;
}
})();
const storage = new AgentStorage(join(workdir, "agents"), logger);
const manager = new AgentManager({ clients: { codex: client }, registry: storage, logger });
const states: ManagedAgent[] = [];
manager.subscribe(
(event) => {
if (event.type === "agent_state") states.push(event.agent);
},
{ replayState: false },
);
const agent = await manager.createAgent({ provider: "codex", cwd: workdir }, undefined, {
workspaceId: undefined,
});
try {
const run = manager.streamAgent(agent.id, "keep working", {
clientMessageId: "submitted-prompt",
});
void drainAsyncGenerator(run).catch(() => undefined);
await manager.waitForAgentRunStart(agent.id);
await manager.flush();
const live = manager.getAgent(agent.id);
expect(live?.lifecycle).toBe("running");
const recordedAt = live?.lastUserMessageAt;
expect(recordedAt).toBeInstanceOf(Date);
expect((await storage.get(agent.id))?.lastUserMessageAt).toBe(recordedAt?.toISOString());
expect(states.at(-1)?.lastUserMessageAt).toEqual(recordedAt);
} finally {
await manager.closeAgent(agent.id);
rmSync(workdir, { recursive: true, force: true });
}
});
class HeldRuntimeInfoSession extends TestAgentSession {
private readonly runtimeInfoRequested = deferred<void>();
private readonly runtimeInfoAllowed = deferred<void>();
@@ -503,13 +503,16 @@ export interface ManagedImportableSessionsResult {
providerErrors: ImportableSessionProviderError[];
}
export type AgentAttentionCallback = (params: {
export interface AgentAttentionEvent {
agentId: string;
provider: AgentProvider;
reason: "finished" | "error" | "permission";
finishedTurnId?: string;
/** When the agent's current unread attention started; null when the agent is read. */
attentionTimestamp: Date | null;
}) => void;
}
export type AgentAttentionCallback = (event: AgentAttentionEvent) => void;
export type AgentArchivedCallback = (agentId: string) => Promise<void> | void;
@@ -5118,7 +5121,7 @@ export class AgentManager {
);
if (!shouldHoldBusyForReplacement) {
this.touchUpdatedAt(mutableAgent);
this.emitState(mutableAgent);
this.emitState(mutableAgent, { finishedTurnId: turnId });
}
}
@@ -5957,12 +5960,12 @@ export class AgentManager {
});
}
async getLastAssistantMessage(agentId: string): Promise<string | null> {
async getLastAssistantMessage(agentId: string, turnId?: string): Promise<string | null> {
const scope: TimelineScope = { agentId };
if (!(await this.timeline.describe(scope))) {
return null;
}
return await this.timeline.lastAssistantMessage(scope);
return await this.timeline.lastAssistantMessage(scope, turnId);
}
private getLastAssistantMessageFromTimeline(
@@ -7025,20 +7028,18 @@ export class AgentManager {
flags,
});
if (!options?.fromHistory) {
if (isTurnTerminalEvent(event)) {
this.runs.settleTerminalRun(agent.id, eventTurnId);
if (isForegroundEvent) {
this.finalizeForegroundTurn(agent, eventTurnId);
} else if (terminalDisposition !== "stale" && !agent.activeForegroundTurnId) {
// Publish autonomous readiness only after the tracked run has settled.
this.emitState(agent);
}
}
if (flags.shouldDispatchEvent) {
this.dispatchStream(agent.id, event, { timestamp: new Date().toISOString() });
}
if (isTurnTerminalEvent(event)) {
this.finalizeStreamTurn({
agent,
event,
options,
isForegroundEvent,
eventTurnId,
terminalDisposition,
});
}
if (!options?.fromHistory && flags.shouldDispatchEvent) {
this.dispatchStream(agent.id, event, { timestamp: new Date().toISOString() });
}
this.traceHandleStreamEventEnd(agent, event, eventTurnId, flags);
@@ -7046,6 +7047,31 @@ export class AgentManager {
return flags.shouldNotifyWaiters;
}
private finalizeStreamTurn(params: Omit<StreamEventDispatch, "flags">): void {
const { agent, event, options, isForegroundEvent, eventTurnId, terminalDisposition } = params;
// Keep the idle transition next to its state emission. A runtime refresh during the
// timeline write must not publish the finish before we can supply its turn ID.
if (
event.type === "turn_completed" &&
terminalDisposition !== "stale" &&
!isForegroundEvent &&
!agent.activeForegroundTurnId &&
agent.lifecycle !== "idle" &&
!agent.pendingReplacement
) {
(agent as ActiveManagedAgent).lifecycle = agent.historySaveError ? "error" : "idle";
}
if (options?.fromHistory) return;
this.runs.settleTerminalRun(agent.id, eventTurnId);
if (isForegroundEvent) {
this.finalizeForegroundTurn(agent, eventTurnId);
} else if (terminalDisposition !== "stale" && !agent.activeForegroundTurnId) {
// Publish autonomous readiness only after the tracked run has settled.
this.emitState(agent, { finishedTurnId: eventTurnId });
}
}
private traceHandleStreamEventStart(
agent: ActiveManagedAgent,
event: AgentStreamEvent,
@@ -7137,8 +7163,8 @@ export class AgentManager {
/**
* Applies the event by type, then stamps a completed turn's metrics, returning the event as
* stamped. Handlers change the agent's state before they write, so a terminal event whose
* record fails to write still ends the turn; the failure is logged.
* stamped. A live terminal event still ends the turn when its record fails to write.
* In that case, the failure is logged.
*/
private async recordStreamEvent(params: StreamEventDispatch): Promise<AgentStreamEvent> {
const { agent, options, eventTurnId, terminalDisposition } = params;
@@ -7211,7 +7237,6 @@ export class AgentManager {
agent,
event,
eventTurnId,
isForegroundEvent,
terminalDisposition,
});
return undefined;
@@ -7287,10 +7312,6 @@ export class AgentManager {
}
await this.recordAndDispatchTimelineItem(agent.id, item, event.provider, event.turnId);
if (item.type === "user_message") {
agent.lastUserMessageAt = new Date();
this.emitState(agent);
}
flags.shouldNotifyWaiters = true;
}
}
@@ -7303,10 +7324,9 @@ export class AgentManager {
agent: ActiveManagedAgent;
event: Extract<AgentStreamEvent, { type: "turn_completed" }>;
eventTurnId: string | undefined;
isForegroundEvent: boolean;
terminalDisposition: ActiveTurnTerminalDisposition;
}): void {
const { agent, event, eventTurnId, isForegroundEvent, terminalDisposition } = params;
const { agent, event, eventTurnId, terminalDisposition } = params;
this.logger.trace(
{
agentId: agent.id,
@@ -7326,14 +7346,6 @@ export class AgentManager {
// data accumulated during streaming isn't lost when the provider omits
// it from the completion event.
agent.lastError = agent.historySaveError;
if (
!isForegroundEvent &&
!agent.activeForegroundTurnId &&
agent.lifecycle !== "idle" &&
!agent.pendingReplacement
) {
(agent as ActiveManagedAgent).lifecycle = agent.historySaveError ? "error" : "idle";
}
void this.refreshRuntimeInfo(agent);
}
@@ -7590,6 +7602,13 @@ export class AgentManager {
options?.onRecorded?.();
this.publishTimelineEvent(agentId, event, commit);
if (options?.notifyWaiters) this.notifyForegroundTurnWaiters(agentId, event);
if (item.type === "user_message") {
const agent = this.agents.get(agentId);
if (agent) {
agent.lastUserMessageAt = new Date();
this.emitState(agent);
}
}
if (
item.type === "tool_call" &&
item.status === "completed" &&
@@ -7754,7 +7773,6 @@ export class AgentManager {
...(options?.rejected ? { rejected: true } : {}),
onRecorded: () => {
this.touchUpdatedAt(agent);
if (item.type === "user_message") agent.lastUserMessageAt = new Date();
},
});
}
@@ -7837,9 +7855,12 @@ export class AgentManager {
return parts.join("\n\n");
}
private emitState(agent: ManagedAgent, options?: { persist?: boolean }): void {
private emitState(
agent: ManagedAgent,
options?: { persist?: boolean; finishedTurnId?: string },
): void {
// Keep attention as an edge-triggered unread signal, not a level signal.
this.checkAndSetAttention(agent);
this.checkAndSetAttention(agent, options?.finishedTurnId);
if (options?.persist !== false) {
this.enqueueBackgroundPersist(agent);
}
@@ -7872,7 +7893,7 @@ export class AgentManager {
}
}
private checkAndSetAttention(agent: ManagedAgent): void {
private checkAndSetAttention(agent: ManagedAgent, finishedTurnId?: string): void {
const previousStatus = this.previousStatuses.get(agent.id);
const currentStatus = agent.lifecycle;
@@ -7892,7 +7913,7 @@ export class AgentManager {
if (agent.attention.requiresAttention) {
// The unread finish stays the same; the notifier knows whether the user was told about it.
if (finished && agent.attention.attentionReason === "finished") {
this.broadcastAgentAttention(agent, "finished");
this.broadcastAgentAttention(agent, "finished", finishedTurnId);
}
return;
}
@@ -7903,7 +7924,7 @@ export class AgentManager {
attentionReason: "finished",
attentionTimestamp: new Date(),
};
this.broadcastAgentAttention(agent, "finished");
this.broadcastAgentAttention(agent, "finished", finishedTurnId);
}
}
@@ -7985,6 +8006,7 @@ export class AgentManager {
private broadcastAgentAttention(
agent: ManagedAgent,
reason: "finished" | "error" | "permission",
finishedTurnId?: string,
): void {
if (isDelegatedAgent(agent)) {
return;
@@ -7994,6 +8016,7 @@ export class AgentManager {
agentId: agent.id,
provider: agent.provider,
reason,
...(finishedTurnId === undefined ? {} : { finishedTurnId }),
attentionTimestamp: agent.attention.requiresAttention
? agent.attention.attentionTimestamp
: null,
@@ -14,9 +14,18 @@ export function continuesAssistantMessage(previous: MessageRow, next: MessageRow
);
}
export function lastAssistantMessageText(rows: readonly MessageRow[]): string | null {
export function lastAssistantMessageText(
rows: readonly MessageRow[],
turnId?: string,
): string | null {
function* newestFirst() {
for (let index = rows.length - 1; index >= 0; index--) yield rows[index];
const start =
turnId === undefined
? rows.length - 1
: rows.findLastIndex(
(row) => row.turnId === turnId && row.item.type === "assistant_message",
);
for (let index = start; index >= 0; index--) yield rows[index];
}
return readLastAssistantMessage(newestFirst());
}
@@ -5,6 +5,8 @@ import path from "node:path";
import { fileURLToPath } from "node:url";
import { afterEach, beforeEach, describe, expect, test } from "vitest";
import { DaemonClient } from "../../test-utils/daemon-client.js";
import { createTestPaseoDaemon } from "../../test-utils/paseo-daemon.js";
import { createTestLogger } from "../../../test-utils/test-logger.js";
import type { AgentLaunchContext, AgentSession, AgentSessionConfig } from "../agent-sdk-types.js";
import { OpenCodeBridge } from "./opencode/bridge.js";
@@ -315,3 +317,122 @@ describe.each<Mode>(["explicit", "discovered"])("OpenCode v2 %s shared service",
expect((await second!.run(afterClose)).finalText).toBe("RESULT HUB_OK_2");
}, 120_000);
});
test("v2 opens the parent timeline and accepts prompts after a child working directory is removed", async () => {
const fixture = await startFixture("explicit");
const { root, project, service, bridge } = fixture;
const childDirectory = path.join(root, "child");
async function connectToDaemon() {
const provider = new OpenCodeV2AgentClient({
logger: createTestLogger(),
bridge,
settings: {
env: {
[EXTERNAL_SERVER_URL_ENV]: service.url,
[EXTERNAL_SERVER_PASSWORD_ENV]: service.password,
},
},
});
const daemon = await createTestPaseoDaemon({
paseoHomeRoot: path.join(root, "daemon"),
staticDir: root,
cleanup: false,
agentClients: { opencode: provider },
});
const client = new DaemonClient({ url: `ws://127.0.0.1:${daemon.port}/ws` });
const close = async () => {
await client.close();
await daemon.close();
await provider.shutdown();
};
try {
await client.connect();
return { client, close };
} catch (error) {
await close();
throw error;
}
}
function providerHeaders() {
return {
Authorization: `Basic ${Buffer.from(`opencode:${service.password}`).toString("base64")}`,
};
}
function providerClient() {
return OpenCode.make({ baseUrl: service.url, headers: providerHeaders() });
}
let daemon: Awaited<ReturnType<typeof connectToDaemon>> | undefined;
try {
await mkdir(childDirectory);
daemon = await connectToDaemon();
const initialPrompt = scriptedCall("subagent", {
agent: "general",
description: "Create a child session",
prompt: "Say hello",
});
const parent = await daemon.client.createAgent({
cwd: project,
provider: "opencode",
model: SCRIPTED_MODEL,
initialPrompt,
});
expect((await daemon.client.waitForFinish(parent.id, 30_000)).status).toBe("idle");
const persistedParent = await daemon.client.fetchAgent(parent.id);
const parentSessionId = persistedParent?.agent.persistence?.sessionId;
expect(parentSessionId).toBeDefined();
const opencode = providerClient();
const { data: children } = await opencode.session.list({
parentID: parentSessionId,
limit: 100,
});
expect(children).toHaveLength(1);
const childId = children[0]!.id;
await opencode.session.move({ sessionID: childId, directory: childDirectory });
await expect
.poll(async () => (await opencode.session.get({ sessionID: childId })).location.directory)
.toBe(childDirectory);
const readTimeline = (client: DaemonClient) =>
client.fetchAgentTimeline(parent.id, {
direction: "tail",
limit: 0,
projection: "canonical",
});
const before = await readTimeline(daemon.client);
expect(
before.entries.some(
({ item }) => item.type === "user_message" && item.text === initialPrompt,
),
).toBe(true);
await daemon.close();
daemon = undefined;
await rm(childDirectory, { recursive: true });
await service.restart();
expect((await providerClient().session.get({ sessionID: childId })).id).toBe(childId);
const response = await fetch(new URL(`/api/session/${childId}/permission`, service.url), {
headers: providerHeaders(),
});
expect(response.status).toBe(404);
expect(await response.json()).toMatchObject({ _tag: "LocationNotFoundError" });
daemon = await connectToDaemon();
const after = await readTimeline(daemon.client);
expect(after.entries.map(({ item }) => item)).toEqual(before.entries.map(({ item }) => item));
const followUp = scriptedCall("shell", {
command: "printf parent-resumed",
description: "Confirm the parent can run a new turn",
});
await daemon.client.sendMessage(parent.id, followUp);
expect(await daemon.client.waitForFinish(parent.id, 30_000)).toMatchObject({
status: "idle",
lastMessage: expect.stringContaining("parent-resumed"),
});
expect(service.agentRequests.some(({ transcript }) => transcript.includes(followUp))).toBe(
true,
);
} finally {
await daemon?.close();
await stopFixture(fixture);
}
}, 90_000);
@@ -5,6 +5,7 @@ export class OpenCodeHttpError extends Error {
readonly operation: string,
readonly status: number | undefined,
readonly html: boolean,
readonly errorTag?: string,
) {
const statusLabel = status === undefined ? "" : ` (HTTP ${status})`;
super(
@@ -17,6 +18,15 @@ export class OpenCodeHttpError extends Error {
/** True when OpenCode answered 404, directly or as the cause of the client's transport error. */
export function isOpenCodeNotFound(error: unknown): boolean {
return getOpenCodeHttpError(error)?.status === 404;
}
export function isOpenCodeLocationNotFound(error: unknown): boolean {
const failure = getOpenCodeHttpError(error);
return failure?.status === 404 && failure.errorTag === "LocationNotFoundError";
}
function getOpenCodeHttpError(error: unknown): OpenCodeHttpError | undefined {
const failure = error instanceof OpenCodeHttpError ? error : (error as Error | null)?.cause;
return failure instanceof OpenCodeHttpError && failure.status === 404;
return failure instanceof OpenCodeHttpError ? failure : undefined;
}
@@ -47,9 +47,9 @@ export class ScriptedOpenCodeService {
private constructor(
readonly requests: ScriptedRequest[],
readonly root: string,
readonly url: string,
readonly password: string,
private readonly process: ChildProcess,
public url: string,
public password: string,
private process: ChildProcess,
private readonly llm: Server,
) {}
@@ -105,6 +105,26 @@ export class ScriptedOpenCodeService {
}),
);
await options.beforeStart?.({ configDirectory });
try {
const { url, password, child } = await this.launch(root);
return new ScriptedOpenCodeService(requests, root, url, password, child, llm);
} catch (error) {
llm.close();
await rm(root, { recursive: true, force: true });
throw error;
}
}
async restart() {
await this.stopProcess();
await rm(path.join(this.root, "state", "opencode", "service.json"), { force: true });
const { child, url, password } = await ScriptedOpenCodeService.launch(this.root);
this.process = child;
this.url = url;
this.password = password;
}
private static async launch(root: string) {
const child = spawn(
OPENCODE_V2_COMMAND,
["serve", "--service", "--hostname", "127.0.0.1", "--port", "0"],
@@ -124,11 +144,10 @@ export class ScriptedOpenCodeService {
const parsed = content ? (JSON.parse(content) as { url: string; password: string }) : null;
// The service registers before it serves requests.
if (parsed && (await isReady(parsed.url, parsed.password))) {
return new ScriptedOpenCodeService(requests, root, parsed.url, parsed.password, child, llm);
return { ...parsed, child };
}
if (child.exitCode !== null || Date.now() > deadline) {
llm.close();
await rm(root, { recursive: true, force: true });
child.kill();
throw new Error(`OpenCode v2 service did not register (exit ${child.exitCode})`);
}
await delay(100);
@@ -172,10 +191,17 @@ export class ScriptedOpenCodeService {
}
async stop(): Promise<void> {
await this.stopProcess();
await new Promise<void>((resolve) => this.llm.close(() => resolve()));
await rm(this.root, { recursive: true, force: true });
}
private async stopProcess(): Promise<void> {
const exited = new Promise<void>((resolve) => {
if (this.process.exitCode !== null) resolve();
if (this.process.exitCode !== null || this.process.signalCode !== null) resolve();
else this.process.once("exit", () => resolve());
});
if (this.process.exitCode !== null || this.process.signalCode !== null) return;
if (this.process.pid && process.platform !== "win32") {
try {
process.kill(-this.process.pid, "SIGTERM");
@@ -184,9 +210,8 @@ export class ScriptedOpenCodeService {
}
} else this.process.kill("SIGTERM");
await Promise.race([exited, delay(10_000)]);
if (this.process.exitCode === null) this.process.kill("SIGKILL");
await new Promise<void>((resolve) => this.llm.close(() => resolve()));
await rm(this.root, { recursive: true, force: true });
if (this.process.exitCode === null && this.process.signalCode === null)
this.process.kill("SIGKILL");
}
}
@@ -12,6 +12,7 @@ import type { AgentStreamEvent } from "../../../agent-sdk-types.js";
import type { ProviderSubagentInputEvent } from "../../../provider-subagents/store.js";
import { syncTailMessages } from "./history.js";
import { isOpenCodeLocationNotFound } from "../http-error.js";
import { buildOpenCodeSubagentSubtitle } from "../subagent-presentation.js";
import type { V2Api } from "./api.js";
@@ -63,8 +64,8 @@ export class SessionChildren {
try {
await adoptChild(id);
} catch (error) {
if (!isSessionNotFoundError(error)) throw error;
this.remove(id);
if (isSessionNotFoundError(error)) this.remove(id);
else if (!isOpenCodeLocationNotFound(error)) throw error;
}
}
}
@@ -201,10 +202,16 @@ export class SessionChildren {
});
}
private async reconcileChild(info: SessionInfo, parentID: string) {
await this.options.reconcilePermissions(info.id);
let child = this.children.get(info.id);
try {
await this.options.reconcilePermissions(info.id);
if (!child) await this.options.adoptChild?.(info.id);
} catch (error) {
// A child can outlive its worktree. Its runtime cannot be restored until the location returns.
if (isOpenCodeLocationNotFound(error)) return;
throw error;
}
if (!child) {
await this.options.adoptChild?.(info.id);
child = this.children.get(info.id) ?? { parentID, timeline: new V2Timeline(), history: [] };
this.children.set(info.id, child);
}
@@ -9,6 +9,7 @@ export async function validateOpenCodeResponse(
const html = contentType?.includes("text/html") ?? false;
if (response.ok && !html) return response;
let errorTag: string | undefined;
// The SDK needs the original body to decode the provider's missing-session error.
if (response.status === 404 && !html && contentType?.includes("application/json")) {
const body: unknown = await response
@@ -16,8 +17,10 @@ export async function validateOpenCodeResponse(
.json()
.catch(() => null);
if (isSessionNotFoundError(body)) return response;
if (body && typeof body === "object" && "_tag" in body && typeof body._tag === "string")
errorTag = body._tag;
}
const url = request instanceof Request ? request.url : String(request);
throw new OpenCodeHttpError(new URL(url).pathname, response.status, html);
throw new OpenCodeHttpError(new URL(url).pathname, response.status, html, errorTag);
}
@@ -813,8 +813,8 @@ export class TimelineProjection {
return last?.endSeq === seq && last.rowIndex >= 0 ? this.rows[last.rowIndex].item : null;
}
getLastAssistantMessage(): string | null {
return lastAssistantMessageText(this.rows);
getLastAssistantMessage(turnId?: string): string | null {
return lastAssistantMessageText(this.rows, turnId);
}
enrichSubmittedUserMessage(
@@ -212,6 +212,21 @@ describe.each(
expect(await timeline.lastAssistantMessage(root("a"))).toBe("Bye");
});
it("reads assistant text only from the requested turn", async () => {
const timeline = createTimeline();
const scope = root("a");
await timeline.create(scope);
await timeline.append(scope, [
{ turnId: "first", item: { type: "assistant_message", text: "Earlier reply" } },
{ turnId: "silent", item: { type: "user_message", text: "Run without replying" } },
{ turnId: "latest", item: { type: "assistant_message", text: "New reply" } },
]);
expect(await timeline.lastAssistantMessage(scope, "first")).toBe("Earlier reply");
expect(await timeline.lastAssistantMessage(scope, "silent")).toBeNull();
expect(await timeline.lastAssistantMessage(scope, "latest")).toBe("New reply");
});
it.each([
{
scenario: "the same reply",
@@ -450,8 +450,8 @@ export class AgentTimeline {
* The newest assistant reply, with its streamed chunks joined in order. Notifications within
* an identified reply can sit between its chunks. Null when there is no assistant message.
*/
lastAssistantMessage(scope: TimelineScope): Promise<string | null> {
return this.run(scope, () => this.backendFor(scope).lastAssistantMessage(scope));
lastAssistantMessage(scope: TimelineScope, turnId?: string): Promise<string | null> {
return this.run(scope, () => this.backendFor(scope).lastAssistantMessage(scope, turnId));
}
/**
@@ -214,7 +214,7 @@ export interface AgentTimelineBackend {
readRows(scope: TimelineScope): MaybePromise<ProjectedTimelineRow[]>;
lastItem(scope: TimelineScope): MaybePromise<AgentTimelineItem | null>;
/** The trailing run of assistant messages joined, skipping later non-assistant rows. */
lastAssistantMessage(scope: TimelineScope): MaybePromise<string | null>;
lastAssistantMessage(scope: TimelineScope, turnId?: string): MaybePromise<string | null>;
}
/** The scope has no history: it was never created, or it was deleted. */
@@ -273,8 +273,8 @@ export class MemoryTimelineBackend implements AgentTimelineBackend {
return state.projection.getLastItem(state.nextSeq - 1);
}
lastAssistantMessage(scope: TimelineScope): string | null {
return this.requireState(scope).projection.getLastAssistantMessage();
lastAssistantMessage(scope: TimelineScope, turnId?: string): string | null {
return this.requireState(scope).projection.getLastAssistantMessage(turnId);
}
private describe(state: MemoryTimelineState): TimelineHead {
@@ -494,13 +494,15 @@ export class SqliteTimelineBackend implements AgentTimelineBackend {
});
}
lastAssistantMessage(scope: TimelineScope): string | null {
lastAssistantMessage(scope: TimelineScope, turnId?: string): string | null {
return this.database.read((sql) => {
const { id } = requireScope(sql, scope);
const last = sql.get<{ seq_start: number }>(
`SELECT seq_start FROM timeline_rows WHERE ${ACTIVE} ` +
"AND item_type = 'assistant_message' ORDER BY seq_start DESC LIMIT 1",
id,
"AND item_type = 'assistant_message' " +
(turnId === undefined ? "" : "AND turn_id = ? ") +
"ORDER BY seq_start DESC LIMIT 1",
...(turnId === undefined ? [id] : [id, turnId]),
);
if (!last) return null;
const records = sql.iterate<Pick<RowRecord, "item_type" | "row">>(
@@ -198,7 +198,7 @@ export class DeferredTimelineBackend implements AgentTimelineBackend {
lastItem(scope: TimelineScope): Promise<AgentTimelineItem | null> {
return this.defer(() => this.inner.lastItem(scope));
}
lastAssistantMessage(scope: TimelineScope): Promise<string | null> {
return this.defer(() => this.inner.lastAssistantMessage(scope));
lastAssistantMessage(scope: TimelineScope, turnId?: string): Promise<string | null> {
return this.defer(() => this.inner.lastAssistantMessage(scope, turnId));
}
}
@@ -230,40 +230,37 @@ function parseEncryptedJson(sharedKey: Uint8Array, text: string): unknown {
return JSON.parse(plaintext);
}
async function getAvailablePort(): Promise<number> {
// Wrangler binds the port itself (`--port 0`) and reports it once it listens.
// Reserving a free port first and passing it in races other test files that
// bind ports between the reservation and wrangler's bind.
async function waitForRelayListening(relay: ChildProcess, timeout = 60000): Promise<number> {
return await new Promise((resolve, reject) => {
const server = net.createServer();
server.once("error", reject);
server.listen(0, "127.0.0.1", () => {
const address = server.address();
if (!address || typeof address === "string") {
server.close(() => reject(new Error("Failed to acquire port")));
return;
}
server.close(() => resolve(address.port));
});
const output: string[] = [];
const cleanup = () => {
clearTimeout(timer);
relay.stdout?.off("data", onData);
relay.stderr?.off("data", onData);
relay.off("exit", onExit);
};
const fail = (reason: string) => {
cleanup();
reject(new Error(`${reason}. Recent output:\n${output.slice(-20).join("")}`));
};
const onData = (data: Buffer) => {
output.push(data.toString());
const ready = /Ready on http:\/\/127\.0\.0\.1:(\d+)\r?\n/.exec(output.join(""));
if (!ready) return;
cleanup();
resolve(Number(ready[1]));
};
const onExit = (code: number | null) => fail(`Local relay exited with code ${code}`);
const timer = setTimeout(() => fail(`Local relay did not listen within ${timeout}ms`), timeout);
relay.stdout?.on("data", onData);
relay.stderr?.on("data", onData);
relay.once("exit", onExit);
});
}
async function waitForServer(port: number, timeout = 15000): Promise<void> {
const start = Date.now();
while (Date.now() - start < timeout) {
try {
await new Promise<void>((resolve, reject) => {
const socket = net.connect(port, "127.0.0.1", () => {
socket.end();
resolve();
});
socket.on("error", reject);
});
return;
} catch {
await new Promise((r) => setTimeout(r, 100));
}
}
throw new Error(`Server did not start on port ${port} within ${timeout}ms`);
}
async function waitForRelayWebSocketReady(port: number, timeout = 60000): Promise<void> {
const start = Date.now();
while (Date.now() - start < timeout) {
@@ -333,7 +330,6 @@ async function waitForCapturedLog(
await waitForRelayWebSocketReady(relayPort, 60000);
return;
}
relayPort = options.port ?? (await getAvailablePort());
const relayDir = path.resolve(process.cwd(), "../relay");
const relayArgs = [
"wrangler",
@@ -342,7 +338,7 @@ async function waitForCapturedLog(
"--ip",
"127.0.0.1",
"--port",
String(relayPort),
String(options.port ?? 0),
"--live-reload=false",
"--show-interactive-dev-session=false",
];
@@ -386,7 +382,7 @@ async function waitForCapturedLog(
}
});
await waitForServer(relayPort, 30000);
relayPort = await waitForRelayListening(relayProcess);
await waitForRelayWebSocketReady(relayPort, 60000);
};
@@ -394,6 +390,7 @@ async function waitForCapturedLog(
if (!relayProcess) return;
const process = relayProcess;
relayProcess = null;
if (process.exitCode !== null || process.signalCode !== null) return;
const exited = once(process, "exit");
process.kill("SIGTERM");
await withTimeout(exited, 10000, "Local relay did not stop");
@@ -1,6 +1,10 @@
import { MockLoadTestAgentClient } from "./agent/providers/mock-load-test-agent.js";
import {
MockLoadTestAgentClient,
MockLoadTestAgentSession,
} from "./agent/providers/mock-load-test-agent.js";
import { createPaseoApi } from "@getpaseo/client";
import type { AgentManager } from "./agent/agent-manager.js";
import type { AgentStreamEvent } from "./agent/agent-sdk-types.js";
import { AgentStorage } from "./agent/agent-storage.js";
import { createTestLogger } from "../test-utils/test-logger.js";
import { execFileSync } from "node:child_process";
@@ -1386,6 +1390,124 @@ test("dictation failure belongs only to its requesting source and releases speec
}
});
test("a tool-only turn uses the generic finish notification", async () => {
const daemon = await createTestPaseoDaemon({ mcpEnabled: false });
const client = new DaemonClient({ url: `ws://127.0.0.1:${daemon.port}/ws` });
const bodies: string[] = [];
const unsubscribe = client.onAgentAttentionRequired((event) => {
if (event.reason === "finished" && event.notification) bodies.push(event.notification.body);
});
try {
await client.connect();
await client.observeEvents(["agent_attention_required"], { notifications: true }).ready;
const agent = await client.createAgent({
provider: "claude",
cwd: daemon.staticDir,
modeId: "bypassPermissions",
});
await client.sendMessage(agent.id, "Respond with exactly: Previous report is ready.");
await expect.poll(() => bodies).toEqual(["Previous report is ready."]);
await client.clearAgentAttention(agent.id);
await client.sendMessage(agent.id, "Run echo hello without replying");
await expect.poll(() => bodies.length).toBe(2);
expect(bodies[1]).toBe("Finished working.");
} finally {
unsubscribe();
await client.close();
await daemon.close();
}
});
test("background finish notifications preview only the completed turn", async () => {
class BackgroundSession extends MockLoadTestAgentSession {
private readonly subscribers = new Set<Parameters<MockLoadTestAgentSession["subscribe"]>[0]>();
model: string | undefined;
override subscribe(callback: Parameters<MockLoadTestAgentSession["subscribe"]>[0]) {
const unsubscribe = super.subscribe(callback);
this.subscribers.add(callback);
return () => {
this.subscribers.delete(callback);
unsubscribe();
};
}
override async getRuntimeInfo() {
const info = await super.getRuntimeInfo();
return { ...info, model: this.model ?? info.model };
}
publish(event: AgentStreamEvent) {
for (const subscriber of this.subscribers) subscriber(event);
}
}
class BackgroundClient extends MockLoadTestAgentClient {
session!: BackgroundSession;
override async createSession(config: Parameters<MockLoadTestAgentClient["createSession"]>[0]) {
this.session = new BackgroundSession({ config, sessionId: "background-notifications" });
return this.session;
}
}
const provider = new BackgroundClient();
const daemon = await createTestPaseoDaemon({
mcpEnabled: false,
isDev: true,
agentClients: { mock: provider },
});
const client = new DaemonClient({ url: `ws://127.0.0.1:${daemon.port}/ws` });
const bodies: string[] = [];
const unsubscribe = client.onAgentAttentionRequired((event) => {
if (event.reason === "finished" && event.notification) bodies.push(event.notification.body);
});
try {
await client.connect();
await client.observeEvents(["agent_attention_required"], { notifications: true }).ready;
const agent = await client.createAgent({ provider: "mock", cwd: daemon.staticDir });
for (const [turnId, reply, model, expectedBody] of [
["first", "Previous report is ready.", undefined, "Previous report is ready."],
["silent", undefined, undefined, "Finished working."],
["latest", "The new report is ready.", "changed-model", "The new report is ready."],
] as const) {
const index = bodies.length;
const session = provider.session;
session.publish({ type: "turn_started", provider: "mock", turnId });
await expect
.poll(async () => (await client.fetchAgent(agent.id))?.agent.status)
.toBe("running");
if (reply) {
session.publish({
type: "timeline",
provider: "mock",
turnId,
item: { type: "assistant_message", text: reply },
});
}
session.model = model;
session.publish({
type: "turn_completed",
provider: "mock",
turnId,
usage: { inputTokens: 1, outputTokens: 1 },
});
await expect.poll(() => bodies.length).toBe(index + 1);
expect(bodies[index]).toBe(expectedBody);
await client.clearAgentAttention(agent.id);
}
} finally {
unsubscribe();
await client.close();
await daemon.close();
}
});
test("a legacy socket cannot borrow a modern sibling's directory observation", async () => {
const daemon = await createTestPaseoDaemon({ mcpEnabled: false });
const admin = new DaemonClient({ url: `ws://127.0.0.1:${daemon.port}/ws`, appVersion: "0.8.0" });
@@ -1,6 +1,8 @@
import { mkdir, rename, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
import { existsSync, readFileSync } from "node:fs";
import { createServer } from "node:http";
import { createServer, type IncomingMessage, type ServerResponse } from "node:http";
import { spawn } from "node:child_process";
import { once } from "node:events";
import { tmpdir } from "node:os";
import path from "node:path";
import { pathToFileURL } from "node:url";
@@ -36,6 +38,66 @@ async function commitAll(repository: string, message: string): Promise<string> {
return stdout.trim();
}
async function serveGitHttp({
request,
response,
root,
}: {
request: IncomingMessage;
response: ServerResponse;
root: string;
}) {
const url = new URL(request.url!, "http://localhost");
const chunks: Buffer[] = [];
for await (const chunk of request) chunks.push(chunk as Buffer);
const body = Buffer.concat(chunks);
const child = spawn("git", ["http-backend"], {
env: {
...process.env,
GIT_PROJECT_ROOT: root,
GIT_HTTP_EXPORT_ALL: "1",
PATH_INFO: url.pathname,
QUERY_STRING: url.search.slice(1),
REQUEST_METHOD: request.method,
CONTENT_TYPE: request.headers["content-type"],
CONTENT_LENGTH: String(body.length),
HTTP_GIT_PROTOCOL: request.headers["git-protocol"] as string | undefined,
},
});
const closed = once(child, "close");
child.stdin.end(body);
const output: Buffer[] = [];
for await (const chunk of child.stdout) output.push(chunk as Buffer);
const [code] = await closed;
const data = Buffer.concat(output);
const end = data.indexOf("\r\n\r\n");
if (code !== 0 || end < 0) throw new Error("git http-backend failed");
for (const line of data.subarray(0, end).toString().split("\r\n")) {
const colon = line.indexOf(":");
if (colon < 0) continue;
const name = line.slice(0, colon);
const value = line.slice(colon + 1).trim();
if (name.toLowerCase() === "status") response.statusCode = Number(value.slice(0, 3));
else response.setHeader(name, value);
}
response.end(data.subarray(end + 4));
}
function createGitFixtureServer({ root, posts }: { root: string; posts: string[] }) {
return createServer((request, response) => {
if (
request.headers.authorization !==
`Basic ${Buffer.from("fixture:fake-secret").toString("base64")}`
) {
response.writeHead(401, { "WWW-Authenticate": 'Basic realm="fixture"' }).end();
return;
}
const url = new URL(request.url!, "http://localhost");
if (request.method === "POST") posts.push(url.pathname);
void serveGitHttp({ request, response, root }).catch(() => response.writeHead(500).end());
});
}
/** Points https://github.com/fixture/repository.git at a local repository for the callback. */
async function withGitHubFixture(repository: string, run: () => Promise<void>): Promise<void> {
const overlay = {
@@ -120,6 +182,128 @@ describe("managed Git plugin sources", () => {
});
}, 30_000);
it("downloads only the files of the installed commit, not every blob in history", async () => {
const repository = await createRepository();
// A file that exists only in history, like screenshots a plugin repository later dropped.
await writeFile(path.join(repository, "history-only.bin"), "x".repeat(256 * 1024));
await commitAll(repository, "add a large asset");
const { stdout: historyBlob } = await runGitCommand(["rev-parse", "HEAD:history-only.bin"], {
cwd: repository,
});
await rm(path.join(repository, "history-only.bin"));
await commitAll(repository, "drop the asset");
await runGitCommand(["config", "uploadpack.allowFilter", "true"], { cwd: repository });
await runGitCommand(["config", "uploadpack.allowAnySHA1InWant", "true"], { cwd: repository });
const home = await mkdtemp(path.join(tmpdir(), "paseo-plugin-git-home-"));
roots.push(home);
const sources = new ManagedPluginSources(home);
let candidate = await sources.prepareInstall({
source: `git:${pathToFileURL(repository).href}`,
});
candidate = await sources.place("managed-example", candidate);
expect(await readFile(path.join(candidate.directory, "index.server.ts"), "utf8")).toContain(
"export default",
);
const { stdout: checkoutRoot } = await runGitCommand(["rev-parse", "--show-toplevel"], {
cwd: candidate.directory,
});
const { stdout: missing } = await runGitCommand(
["rev-list", "--objects", "--all", "--missing=print"],
{ cwd: checkoutRoot.trim() },
);
expect(missing.split("\n")).toContain(`?${historyBlob.trim()}`);
}, 30_000);
it("fetches filtered checkout blobs for credentialed Git installs and updates", async () => {
const repository = await createRepository();
const root = await mkdtemp(path.join(tmpdir(), "paseo-plugin-smart-http-"));
roots.push(root);
await runGitCommand(["clone", "--bare", repository, "plugin.git"], { cwd: root });
const bare = path.join(root, "plugin.git");
await runGitCommand(["--git-dir", bare, "config", "uploadpack.allowFilter", "true"], {
cwd: root,
});
const posts: string[] = [];
const server = createGitFixtureServer({ root, posts });
await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
const address = server.address();
if (!address || typeof address === "string") throw new Error("Expected HTTP port");
const home = await mkdtemp(path.join(tmpdir(), "paseo-plugin-credential-filter-"));
roots.push(home);
const previous = process.env.GIT_CONFIG_PARAMETERS;
process.env.GIT_CONFIG_PARAMETERS = [previous, "'credential.helper='"]
.filter(Boolean)
.join(" ");
try {
const remote = `http://fixture:fake-secret@127.0.0.1:${address.port}/plugin.git`;
const sources = new ManagedPluginSources(home);
let candidate = await sources.prepareInstall({ source: remote });
candidate = await sources.place("managed-example", candidate);
sources.commit("managed-example", candidate.record);
expect(await readFile(path.join(candidate.directory, "index.server.ts"), "utf8")).toContain(
"export default",
);
expect(posts.length).toBeGreaterThanOrEqual(2);
expect(new Set(posts)).toEqual(new Set(["/plugin.git/git-upload-pack"]));
const installFetches = posts.length;
const config = await readFile(path.join(candidate.directory, ".git", "config"), "utf8");
expect(config).not.toMatch(/fixture:fake-secret/);
expect(config).toContain("https://paseo.invalid/plugin.git");
expect(config).toContain("partialclonefilter = blob:none");
await writeFile(
path.join(repository, "index.server.ts"),
"export default () => 'updated';\n",
);
const revision = await commitAll(repository, "update");
await runGitCommand(["push", bare, "main"], { cwd: repository });
const preview = await sources.preview("managed-example", candidate.directory);
expect(preview.target).toEqual({ kind: "git", commit: revision });
const updated = await sources.prepareUpdate(preview.proposal!, candidate.directory);
expect(await readFile(path.join(updated.directory, "index.server.ts"), "utf8")).toContain(
"updated",
);
expect(posts.length - installFetches).toBeGreaterThanOrEqual(2);
} finally {
if (previous === undefined) delete process.env.GIT_CONFIG_PARAMETERS;
else process.env.GIT_CONFIG_PARAMETERS = previous;
server.closeAllConnections();
await new Promise<void>((resolve) => server.close(() => resolve()));
}
}, 30_000);
it("rejects updating to a reviewed commit after the remote amends it away", async () => {
const repository = await createRepository();
const home = await mkdtemp(path.join(tmpdir(), "paseo-plugin-git-home-"));
roots.push(home);
const remote = pathToFileURL(repository).href;
const sources = new ManagedPluginSources(home);
let candidate = await sources.prepareInstall({ source: `git:${remote}` });
candidate = await sources.place("managed-example", candidate);
sources.commit("managed-example", candidate.record);
await writeFile(path.join(repository, "index.server.ts"), "export default () => 'v2';\n");
await commitAll(repository, "update v2");
const preview = await sources.preview("managed-example", candidate.directory);
expect(preview.outcome).toBe("update");
// Rewriting the commit without running gc leaves the unreferenced commit in the remote's
// object store; revision resolution must not lazily fetch commits absent from remote refs.
await writeFile(
path.join(repository, "index.server.ts"),
"export default () => 'v2-amended';\n",
);
await runGitCommand(["add", "-A"], { cwd: repository });
await runGitCommand(["commit", "--amend", "-m", "update v2 amended"], { cwd: repository });
await expect(sources.prepareUpdate(preview.proposal!, candidate.directory)).rejects.toThrow(
/Git command failed/,
);
}, 30_000);
it("offers current default HEAD after installing a tag", async () => {
const repository = await createRepository();
const home = await mkdtemp(path.join(tmpdir(), "paseo-plugin-git-home-"));
@@ -194,7 +194,7 @@ export class ManagedPluginSources {
const commit = await resolveRequestedRef(sourceRoot, input.ref);
if (target?.kind === "git" && commit !== target.commit)
throw new Error("Git target changed since review");
await checkout(sourceRoot, commit);
await checkout({ checkoutRoot: sourceRoot, commit, remote });
record = { kind: "git", remote };
}
const directory = path.resolve(sourceRoot, pluginPath);
@@ -502,7 +502,7 @@ function assertPluginPath(checkoutRoot: string, directory: string): void {
}
}
async function clone(remote: string, checkoutRoot: string): Promise<void> {
function gitRemote(remote: string) {
const publicRemote = redactRemoteCredentials(remote);
const cloneRemote = publicRemote === remote ? remote : "https://paseo.invalid/plugin.git";
const envOverlay =
@@ -514,12 +514,23 @@ async function clone(remote: string, checkoutRoot: string): Promise<void> {
GIT_CONFIG_KEY_0: `url.${remote}.insteadOf`,
GIT_CONFIG_VALUE_0: cloneRemote,
};
return { cloneRemote, envOverlay };
}
async function clone(remote: string, checkoutRoot: string): Promise<void> {
const { cloneRemote, envOverlay } = gitRemote(remote);
try {
await runGitCommand(["clone", "--no-checkout", "--", cloneRemote, checkoutRoot], {
cwd: path.dirname(checkoutRoot),
envOverlay,
timeout: GIT_TIMEOUT_MS,
});
// A blobless clone keeps every commit and ref for revision lookups, and checkout fetches
// only the files of the chosen commit. A full clone of a plugin repository with large
// assets in its history can outlast GIT_TIMEOUT_MS on an ordinary connection.
await runGitCommand(
["clone", "--no-checkout", "--filter=blob:none", "--", cloneRemote, checkoutRoot],
{
cwd: path.dirname(checkoutRoot),
envOverlay,
timeout: GIT_TIMEOUT_MS,
},
);
} catch (error) {
throw redactRemoteError(error, remote);
}
@@ -545,17 +556,30 @@ function redactRemoteError(error: unknown, remote: string): Error {
return new Error(message);
}
async function checkout(checkoutRoot: string, commit: string): Promise<void> {
await runGitCommand(["checkout", "--detach", commit], {
cwd: checkoutRoot,
envOverlay: GIT_ENV,
timeout: GIT_TIMEOUT_MS,
});
await runGitCommand(["submodule", "update", "--init", "--recursive"], {
cwd: checkoutRoot,
envOverlay: GIT_ENV,
timeout: GIT_TIMEOUT_MS,
});
async function checkout({
checkoutRoot,
commit,
remote,
}: {
checkoutRoot: string;
commit: string;
remote: string;
}): Promise<void> {
const { envOverlay } = gitRemote(remote);
try {
await runGitCommand(["checkout", "--detach", commit], {
cwd: checkoutRoot,
envOverlay,
timeout: GIT_TIMEOUT_MS,
});
await runGitCommand(["submodule", "update", "--init", "--recursive"], {
cwd: checkoutRoot,
envOverlay,
timeout: GIT_TIMEOUT_MS,
});
} catch (error) {
throw redactRemoteError(error, remote);
}
}
async function resolveRequestedRef(
@@ -576,17 +600,7 @@ async function resolveRequestedRef(
async function resolveRemoteCommit(remote: string, cwd: string, ref?: string): Promise<string> {
if (ref?.startsWith("-")) throw new Error("Plugin Git ref cannot start with '-'");
if (ref && /^[0-9a-f]{40,64}$/.test(ref)) return ref;
const publicRemote = redactRemoteCredentials(remote);
const cloneRemote = publicRemote === remote ? remote : "https://paseo.invalid/plugin.git";
const envOverlay =
cloneRemote === remote
? GIT_ENV
: {
...GIT_ENV,
GIT_CONFIG_COUNT: "1",
GIT_CONFIG_KEY_0: `url.${remote}.insteadOf`,
GIT_CONFIG_VALUE_0: cloneRemote,
};
const { cloneRemote, envOverlay } = gitRemote(remote);
try {
const names = ref
? [`refs/heads/${ref}`, `refs/tags/${ref}^{}`, `refs/tags/${ref}`, ref]
@@ -636,7 +650,12 @@ async function refExists(cwd: string, ref: string): Promise<boolean> {
}
async function revParse(cwd: string, ref: string): Promise<string> {
const { stdout } = await runGitCommand(["rev-parse", "--verify", ref], { cwd });
// Blobless clones register a promisor remote; keep revision lookups local so rev-parse
// does not lazily fetch unadvertised commits or bypass credentialed remote rewriting.
const { stdout } = await runGitCommand(["rev-parse", "--verify", ref], {
cwd,
envOverlay: { ...GIT_ENV, GIT_NO_LAZY_FETCH: "1" },
});
return stdout.trim();
}
@@ -880,24 +880,26 @@ class FakeAgentSession implements AgentSession {
}
}
const assistantText = this.buildAssistantText(textPrompt);
const assistantChunkA: AgentStreamEvent = {
type: "timeline",
provider: this.providerName,
item: { type: "assistant_message", text: assistantText.slice(0, 6) },
};
await this.appendHistoryEvent(assistantChunkA);
this.notifySubscribers(assistantChunkA);
const assistantChunkBText = assistantText.slice(6);
if (assistantChunkBText.length > 0) {
const assistantChunkB: AgentStreamEvent = {
if (textPrompt !== "Run echo hello without replying") {
const assistantText = this.buildAssistantText(textPrompt);
const assistantChunkA: AgentStreamEvent = {
type: "timeline",
provider: this.providerName,
item: { type: "assistant_message", text: assistantChunkBText },
item: { type: "assistant_message", text: assistantText.slice(0, 6) },
};
await this.appendHistoryEvent(assistantChunkB);
this.notifySubscribers(assistantChunkB);
await this.appendHistoryEvent(assistantChunkA);
this.notifySubscribers(assistantChunkA);
const assistantChunkBText = assistantText.slice(6);
if (assistantChunkBText.length > 0) {
const assistantChunkB: AgentStreamEvent = {
type: "timeline",
provider: this.providerName,
item: { type: "assistant_message", text: assistantChunkBText },
};
await this.appendHistoryEvent(assistantChunkB);
this.notifySubscribers(assistantChunkB);
}
}
await this.beforeTurnComplete?.(prompt);
@@ -1,3 +1,4 @@
import type { AgentAttentionEvent } from "./agent/agent-manager.js";
import { mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import path from "node:path";
@@ -58,13 +59,7 @@ import { VoiceAssistantWebSocketServer } from "./websocket-server.js";
interface WebSocketServerInternals {
sessions: Map<unknown, unknown>;
broadcastAgentAttention(params: {
agentId: string;
reason: string;
preview?: string;
providerId?: string;
timestamp?: string;
}): Promise<void>;
broadcastAgentAttention(params: AgentAttentionEvent): Promise<void>;
}
function createLogger() {
@@ -288,6 +283,7 @@ describe("VoiceAssistantWebSocketServer notification payloads", () => {
agentId: "agent-1",
provider: "claude",
reason: "finished",
finishedTurnId: "turn-1",
attentionTimestamp: new Date(),
});
@@ -303,7 +299,7 @@ describe("VoiceAssistantWebSocketServer notification payloads", () => {
},
},
]);
expect(getLastAssistantMessage).toHaveBeenCalledWith("agent-1");
expect(getLastAssistantMessage).toHaveBeenCalledWith("agent-1", "turn-1");
});
it("sends push notifications regardless of UI label presence", async () => {
@@ -323,11 +319,12 @@ describe("VoiceAssistantWebSocketServer notification payloads", () => {
agentId: "agent-2",
provider: "claude",
reason: "finished",
finishedTurnId: "turn-2",
attentionTimestamp: new Date(),
});
expect(pushNotifications.sent).toHaveLength(1);
expect(getLastAssistantMessage).toHaveBeenCalledWith("agent-2");
expect(getLastAssistantMessage).toHaveBeenCalledWith("agent-2", "turn-2");
});
it("routes a hidden stale focused browser tab's notification to the present Electron web client", async () => {
+10 -9
View File
@@ -48,7 +48,11 @@ import { getCachedHostMachineKind } from "./host-machine-kind.js";
import { getHostName } from "./host-name.js";
import { randomUUID } from "node:crypto";
import { monitorEventLoopDelay } from "node:perf_hooks";
import type { AgentManager, AgentMetricsSnapshot } from "./agent/agent-manager.js";
import type {
AgentAttentionEvent,
AgentManager,
AgentMetricsSnapshot,
} from "./agent/agent-manager.js";
import type { AgentStorage } from "./agent/agent-storage.js";
import type { DownloadTokenStore } from "./file-download/token-store.js";
import type { TerminalManager } from "../terminal/terminal-manager.js";
@@ -108,7 +112,6 @@ function resolveAgentMessageQueueStore(
return store ?? createMemoryAgentMessageQueueStore();
}
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";
import { attachMutableProviderConfigOwner } from "./agent/mutable-provider-config-owner.js";
import type {
@@ -3641,12 +3644,7 @@ export class VoiceAssistantWebSocketServer {
};
}
private async broadcastAgentAttention(params: {
agentId: string;
provider: AgentProvider;
reason: "finished" | "error" | "permission";
attentionTimestamp: Date | null;
}): Promise<void> {
private async broadcastAgentAttention(params: AgentAttentionEvent): Promise<void> {
const agent = this.agentManager.getAgent(params.agentId);
if (!agent?.workspaceId) {
return;
@@ -3674,7 +3672,10 @@ export class VoiceAssistantWebSocketServer {
);
const allStates = notificationEntries.map((e) => e.state);
const nowMs = Date.now();
const assistantMessage = await this.agentManager.getLastAssistantMessage(params.agentId);
const assistantMessage =
params.reason === "finished" && params.finishedTurnId !== undefined
? await this.agentManager.getLastAssistantMessage(params.agentId, params.finishedTurnId)
: null;
const notification = buildAgentAttentionNotificationPayload({
reason: params.reason,
serverId: this.serverId,
@@ -2,8 +2,9 @@ import { createWorkspaceRuntimeStore } from "./workspace-runtime-store/index.js"
import { execFileSync } from "node:child_process";
import { mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join, resolve as resolvePath } from "node:path";
import { basename, join, resolve as resolvePath } from "node:path";
import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
import { createGiteaService, TeaCommandError } from "../services/gitea-service.js";
import { createGitHubService } from "../services/github-service.js";
import type { CurrentPullRequestStatus, ForgeService } from "../services/forge-service.js";
import { defaultForgeRegistry } from "../services/forge-registry.js";
@@ -1297,6 +1298,7 @@ describe("WorkspaceGitServiceImpl primitive refresh entrypoint", () => {
headRef: "feature",
headSha: "1111111111111111111111111111111111111111",
reason: "self-heal-forge-pr-status",
pollRemoteUrl: "https://forge-self-heal.test/acme/repo.git",
});
expect(listener).toHaveBeenCalledWith(
expect.objectContaining({
@@ -1316,6 +1318,168 @@ describe("WorkspaceGitServiceImpl primitive refresh entrypoint", () => {
}
});
test.each(["healthy", "retry-after", "cli-error"] as const)(
"Forgejo self-heal shares repository reads and host cooldowns (%s)",
async (scenario) => {
const host = "forgejo-status.test";
const origin = `https://${host}`;
const worktree = (branch: string) => join(REPO_CWD, branch);
const branches = ["one", "two", "three"] as const;
const repoFor = (cwd: string) =>
["four", "five"].includes(basename(cwd)) ? "other" : "repo";
const remoteFor = (cwd: string) => `${origin}/acme/${repoFor(cwd)}.git`;
const reads: string[] = [];
const statusRequests: string[] = [];
let rejectionSent = false;
let revision = 1;
const pull = (
repo: string,
branch: string,
number: number,
state: string,
merged = false,
) => ({
number,
html_url: `${origin}/acme/${repo}/pulls/${number}`,
title: `${branch} v${revision}`,
state,
merged,
head: { ref: branch, sha: String(number).repeat(40) },
base: { ref: "main" },
});
const forge = createGiteaService({
resolveTeaPath: async () => "/fake/tea",
resolveRemoteUrl: async (cwd) => remoteFor(cwd),
now: () => Date.now(),
runner: async (args, { cwd }) => {
const repo = repoFor(cwd);
const endpoint = args.at(-1) ?? "";
const includesHeaders = args.includes("-i");
const cliList = args[0] === "pr" && args[1] === "list";
const open = cliList || endpoint.includes("state=open");
const terminal = endpoint.includes("state=all");
const json = (data: unknown) => ({
stdout: (includesHeaders ? "HTTP/1.1 200 OK\r\n\r\n" : "") + JSON.stringify(data),
stderr: "",
});
if (includesHeaders || cliList || terminal) statusRequests.push(endpoint);
if (!open && !terminal) {
if (endpoint.includes("/commits/"))
return json({ state: "", statuses: [], total_count: 0 });
if (endpoint.includes("/actions/")) return json({ workflow_runs: [], total_count: 0 });
return json({ full_name: `acme/${repo}`, default_branch: "main" });
}
reads.push(`${repo}:${open ? "open" : "terminal"}`);
if (scenario !== "healthy" && !rejectionSent) {
rejectionSent = true;
if (scenario === "retry-after" && includesHeaders) {
return {
stdout: "{}",
stderr:
"agent-vault: routing HTTP/HTTPS through MITM proxy (<agent-vault-proxy>:14322)\n" +
"agent-vault: agent-vault connected. Starting /usr/bin/env...\n\n" +
"HTTP/1.1 429 Too Many Requests\r\nRetry-After: 19\r\n\r\n",
};
}
throw new TeaCommandError({ args, cwd, exitCode: 1, stderr: "Too Many Requests" });
}
if (terminal)
return json([pull(repo, "two", 2, "closed", true), pull(repo, "three", 3, "closed")]);
if (repo === "other")
return json([pull(repo, "four", 4, "open"), pull(repo, "five", 5, "open")]);
const item = pull(repo, "one", 1, "open");
return json(
cliList
? [
{
index: "1",
state: "open",
title: item.title,
url: item.html_url,
head: item.head.ref,
},
]
: [item],
);
},
});
const unregister = defaultForgeRegistry.register("forgejo-status-test", {
createService: () => forge,
matchesHost: (candidate) => candidate === host,
});
const service = createService({
getCheckoutSnapshotFacts: async (cwd) =>
createCheckoutFacts(cwd, {
currentBranch: basename(cwd),
remoteUrl: remoteFor(cwd),
pullRequestLookupTarget: { headRef: basename(cwd) },
}),
getCheckoutStatus: async (cwd) =>
createCheckoutStatus(cwd, { currentBranch: basename(cwd), remoteUrl: remoteFor(cwd) }),
});
const statuses = new Map<string, WorkspaceGitRuntimeSnapshot["forge"]["pullRequest"]>();
const observe = (branch: string) =>
service.registerWorkspace({ cwd: worktree(branch) }, (snapshot) => {
statuses.set(branch, snapshot.forge.pullRequest);
});
const expectStatuses = (version: number) => {
expect(
branches.map((branch) => [statuses.get(branch)?.state, statuses.get(branch)?.title]),
).toEqual([
["open", `one v${version}`],
["merged", `two v${version}`],
["closed", `three v${version}`],
]);
};
try {
branches.forEach(observe);
if (scenario !== "healthy") {
const cooldownMs = scenario === "retry-after" ? 19_000 : 60_000;
await vi.advanceTimersByTimeAsync(cooldownMs - 1);
observe("four");
await vi.advanceTimersByTimeAsync(1);
observe("five");
await vi.advanceTimersByTimeAsync(119_999);
expect(reads).toEqual(["repo:open"]);
expect(statusRequests).toHaveLength(1);
await vi.advanceTimersByTimeAsync(1);
expect(reads).toEqual(["repo:open", "other:open"]);
expect(statuses.get("five")?.title).toBe("five v1");
await vi.advanceTimersByTimeAsync(120_000);
expect(reads).toEqual([
"repo:open",
"other:open",
"repo:open",
"repo:terminal",
"other:open",
]);
expect(statuses.get("four")?.title).toBe("four v1");
} else {
await vi.advanceTimersByTimeAsync(120_000);
expect(reads).toEqual(["repo:open", "repo:terminal"]);
}
expectStatuses(1);
reads.length = 0;
revision = 2;
await vi.advanceTimersByTimeAsync(120_000);
expect(reads).toEqual(
scenario === "healthy"
? ["repo:open", "repo:terminal"]
: ["repo:open", "repo:terminal", "other:open"],
);
expectStatuses(2);
} finally {
service.dispose();
unregister();
}
},
);
test("generic forge self-heal uses the fast poll window while checks are pending", async () => {
const forge = {
...createGitHubServiceStub(),
@@ -3425,6 +3425,7 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService {
cwd: target.cwd,
...pollTarget,
reason: "self-heal-forge-pr-status",
pollRemoteUrl: target.latestGit?.remoteUrl ?? undefined,
});
if (!closed && this.isActiveObservedWorkspaceTarget(target)) {
latestStatus = status;
@@ -442,6 +442,8 @@ export interface CurrentPullRequestLookup {
headRef: string;
headSha?: string;
headRepositoryOwner?: string;
/** Repository remote already resolved by workspace status polling. */
pollRemoteUrl?: string;
/** Local branch name when it differs from the PR source ref. */
currentBranch?: string;
}
@@ -363,7 +363,7 @@ function isSubmittedGiteaReview(review: GiteaReview): boolean {
return state !== "PENDING" && state !== "REQUEST_REVIEW";
}
function parseTeaHttpStreams(
export function parseTeaHttpStreams(
stdout: string,
stderr: string,
): {
@@ -375,7 +375,9 @@ function parseTeaHttpStreams(
if (fromStdout.status !== null) {
return fromStdout;
}
const fromStderr = parseCliHttpResponse(stderr);
// Proxy startup diagnostics can precede Tea's HTTP headers on stderr.
const statusLine = stderr.search(/^HTTP\/\d(?:\.\d)?[ \t]+\d{3}\b/m);
const fromStderr = parseCliHttpResponse(statusLine === -1 ? stderr : stderr.slice(statusLine));
if (fromStderr.status !== null) {
return { status: fromStderr.status, headers: fromStderr.headers, body: stdout.trim() };
}
@@ -470,6 +470,60 @@ describe("createGiteaService getReferenceRepository", () => {
});
describe("createGiteaService", () => {
it("shares Actions tasks across concurrent open PR status polls", async () => {
const repo = "repos/example-user/sample-repo";
const pulls = [1, 2, 3].map((number) => {
const pull = currentPullRequestApi({
number,
state: "open",
headRef: `feature-${number}`,
headSha: String(number).repeat(40),
});
pull.title = `Feature ${number}`;
return pull;
});
const tasks = pulls.map((pull) => ({
id: pull.number,
name: pull.title,
head_sha: pull.head.sha,
status: "success",
}));
const { service, calls } = makeService((args) => {
const endpoint = args.at(-1);
const json = (body: unknown) => ok(`HTTP/1.1 200 OK\r\n\r\n${JSON.stringify(body)}`);
if (endpoint === `${repo}/pulls?state=open&limit=50&page=1`) return json(pulls);
if (endpoint?.startsWith(`${repo}/commits/`)) {
return json({ state: "", statuses: [], total_count: 0 });
}
if (endpoint === `${repo}/actions/tasks?limit=50&page=1`) {
return json({ total_count: tasks.length, workflow_runs: tasks });
}
throw new Error(`unexpected call: ${args.join(" ")}`);
});
const statuses = await Promise.all(
pulls.map((pull) =>
service.getCurrentPullRequestStatus({
cwd: `/worktrees/${pull.head.ref}`,
headRef: pull.head.ref,
pollRemoteUrl: "https://gitea.com/example-user/sample-repo.git",
reason: "self-heal-forge-pr-status",
}),
),
);
expect(statuses).toMatchObject(
pulls.map((pull) => ({ title: pull.title, checks: [{ name: pull.title }] })),
);
expect(calls.map((args) => args.at(-1)).sort()).toEqual(
[
`${repo}/pulls?state=open&limit=50&page=1`,
`${repo}/actions/tasks?limit=50&page=1`,
...pulls.map((pull) => `${repo}/commits/${pull.head.sha}/status`),
].sort(),
);
});
it("maps a tea pr list item to the neutral current PR status by head branch", async () => {
const { service, calls } = makeService((args) => {
if (args[0] === "pr" && args[1] === "list")
+192 -77
View File
@@ -78,7 +78,8 @@ import {
type GiteaCombinedCommitStatus,
type GiteaCommitStatus,
} from "./gitea-checks.js";
import { createGiteaChangeRequestSource } from "./gitea-change-requests.js";
import { createGiteaChangeRequestSource, parseTeaHttpStreams } from "./gitea-change-requests.js";
import { ChangeRequestRateLimitError, parseRetryAfterMs } from "./change-request-poller.js";
import { isGiteaStatusFacts, type GiteaStatusFacts } from "./gitea-facts.js";
const TEA_ENV = {
@@ -111,6 +112,8 @@ const ISSUE_LIST_FIELDS = "index,state,author,url,title,body,labels,comments,cre
const CURRENT_PR_LOOKUP_PAGE_SIZE = 50;
const CURRENT_PR_OPEN_LOOKUP_MAX_PAGES = 4;
// Cover shortly staggered worktree polls without carrying data into the next poll cycle.
const CURRENT_PR_LIST_SHARE_MS = 15_000;
const TIMELINE_PAGE_SIZE = 50;
const TIMELINE_MAX_PAGES_PER_BUCKET = 4;
@@ -141,6 +144,17 @@ export interface TeaCommandRunnerOptions {
executablePath?: string;
}
interface TeaStatusReadOptions extends TeaCommandRunnerOptions {
statusHost?: string;
statusRepositoryKey?: string;
}
interface CurrentPullRequestCheckRead extends TeaStatusReadOptions {
repoOwner: string;
repoName: string;
sha: string;
}
export interface TeaCommandResult {
stdout: string;
stderr: string;
@@ -992,14 +1006,14 @@ function classifyGiteaTimelineErrorKind(stderr: string): PullRequestTimelineErro
}
/**
* Re-throw only tea auth / CLI-missing failures, letting every other error be
* swallowed by a best-effort caller. Background status polling wraps its checks
* load in its own catch, so this stays invisible there; on the explicit,
* user-triggered check-details path it lets an expired token surface the real
* remediation instead of a misleading "check not found".
* Keep rate limits and auth failures visible through optional check reads.
*/
function rethrowTeaAuthFailure(error: unknown): void {
if (error instanceof TeaAuthenticationError || error instanceof TeaCliMissingError) {
function rethrowTeaCheckReadFailure(error: unknown): void {
if (
error instanceof ChangeRequestRateLimitError ||
error instanceof TeaAuthenticationError ||
error instanceof TeaCliMissingError
) {
throw error;
}
}
@@ -1235,6 +1249,8 @@ export function createGiteaService(options: CreateGiteaServiceOptions = {}): For
const resolveRemoteUrl = options.resolveRemoteUrl ?? defaultResolveRemoteUrl;
const resolveCurrentBranch = options.resolveCurrentBranch ?? defaultResolveCurrentBranch;
const now = options.now ?? Date.now;
const statusPausedUntilByHost = new Map<string, number>();
const sharedStatusReads = new Map<string, { result: Promise<string>; expiresAt: number }>();
const currentPrHeadShaCache = new Map<string, { sha: string; expiresAt: number }>();
async function runRaw(
@@ -1252,9 +1268,81 @@ export function createGiteaService(options: CreateGiteaServiceOptions = {}): For
}
}
async function run(args: string[], runOptions: TeaCommandRunnerOptions): Promise<string> {
const result = await runRaw(args, runOptions);
return result.stdout.trim();
function assertStatusHostAvailable(host: string): void {
const resetAtMs = statusPausedUntilByHost.get(host);
if (resetAtMs === undefined) return;
if (resetAtMs > now()) throw new ChangeRequestRateLimitError({ host, resetAtMs });
statusPausedUntilByHost.delete(host);
}
function pauseStatusHost(host: string, headers: ReadonlyMap<string, string>): never {
const resetAtMs = Math.max(
statusPausedUntilByHost.get(host) ?? 0,
parseRetryAfterMs(headers, now(), { forceOnMissing: true })!,
);
statusPausedUntilByHost.set(host, resetAtMs);
throw new ChangeRequestRateLimitError({ host, resetAtMs });
}
async function runStatusRead(
args: string[],
runOptions: TeaCommandRunnerOptions,
host: string,
): Promise<string> {
const readArgs = args[0] === "api" ? ["api", "-i", ...args.slice(1)] : args;
const result = await runRaw(readArgs, runOptions).catch((error: unknown) => {
if (error instanceof TeaCommandError) {
const response = parseTeaHttpStreams(error.stdout ?? "", error.stderr);
if (response.status === 429 || /\bToo Many Requests\b/i.test(error.stderr)) {
pauseStatusHost(host, response.headers);
}
}
throw error;
});
const response = parseTeaHttpStreams(result.stdout, result.stderr);
if (response.status === 429) pauseStatusHost(host, response.headers);
if (response.status !== null && (response.status < 200 || response.status >= 300)) {
throw new TeaCommandError({
args: readArgs,
cwd: runOptions.cwd,
exitCode: 0,
stderr: `Gitea API returned HTTP ${response.status}`,
});
}
assertStatusHostAvailable(host);
return response.body;
}
async function run(args: string[], runOptions: TeaStatusReadOptions): Promise<string> {
const { statusHost, statusRepositoryKey, ...commandOptions } = runOptions;
if (!statusHost) {
return (await runRaw(args, commandOptions)).stdout.trim();
}
assertStatusHostAvailable(statusHost);
if (!statusRepositoryKey) return runStatusRead(args, commandOptions, statusHost);
// Share repository reads, then let each caller select its own branch.
const key = JSON.stringify([statusRepositoryKey, args]);
const nowMs = now();
for (const [readKey, read] of sharedStatusReads) {
if (read.expiresAt <= nowMs) sharedStatusReads.delete(readKey);
}
const shared = sharedStatusReads.get(key);
if (shared) return shared.result;
const read = {
result: runStatusRead(args, commandOptions, statusHost),
expiresAt: Infinity,
};
sharedStatusReads.set(key, read);
try {
const result = await read.result;
read.expiresAt = now() + CURRENT_PR_LIST_SHARE_MS;
return result;
} catch (error) {
sharedStatusReads.delete(key);
throw error;
}
}
const changeRequests = createGiteaChangeRequestSource({
@@ -1284,7 +1372,7 @@ export function createGiteaService(options: CreateGiteaServiceOptions = {}): For
async function runJsonArray<T>(
args: string[],
runOptions: TeaCommandRunnerOptions,
runOptions: TeaStatusReadOptions,
itemSchema: z.ZodType<T>,
): Promise<T[]> {
const stdout = await run(args, runOptions);
@@ -1296,7 +1384,7 @@ export function createGiteaService(options: CreateGiteaServiceOptions = {}): For
async function runJson<T>(
args: string[],
runOptions: TeaCommandRunnerOptions,
runOptions: TeaStatusReadOptions,
schema: z.ZodType<T>,
): Promise<T> {
const stdout = await run(args, runOptions);
@@ -1435,12 +1523,20 @@ export function createGiteaService(options: CreateGiteaServiceOptions = {}): For
async function loadCurrentPullRequestStatus(
input: CurrentPullRequestLookup,
): Promise<CurrentPullRequestStatus | null> {
const match = await findCurrentPullRequestForHeadRef(input);
const location = input.pollRemoteUrl ? parseGitRemoteLocation(input.pollRemoteUrl) : null;
const statusRead = {
cwd: input.cwd,
statusHost: location?.host,
statusRepositoryKey: location
? JSON.stringify([location.host, location.port, location.path])
: undefined,
};
const match = await findCurrentPullRequestForHeadRef(input, location, statusRead);
if (!match) {
return null;
}
const status = toCurrentPullRequestStatus(match);
return loadCurrentPullRequestChecks(input.cwd, match, status);
return loadCurrentPullRequestChecks(match, status, statusRead);
}
async function resolveCurrentRepoIdentity(
@@ -1470,10 +1566,20 @@ export function createGiteaService(options: CreateGiteaServiceOptions = {}): For
async function findCurrentPullRequestForHeadRef(
input: CurrentPullRequestLookup,
location?: ReturnType<typeof parseGitRemoteLocation>,
statusRead: TeaStatusReadOptions = { cwd: input.cwd },
): Promise<GiteaPrListItem | null> {
const repoIdentity = await resolveCurrentRepoIdentity(input.cwd);
const repoIdentity = location
? parseGitHubRemoteIdentity(location.path)
: await resolveCurrentRepoIdentity(input.cwd);
const repoPath = repositoryApiPath(repoIdentity);
const expectedHeadOwner = repoIdentity?.owner ?? null;
const openMatch = await findOpenPullRequestForHeadRef(input, expectedHeadOwner);
const openMatch = await findOpenPullRequestForHeadRef(
input.headRef,
expectedHeadOwner,
repoPath,
statusRead,
);
if (openMatch) {
return openMatch;
}
@@ -1481,13 +1587,12 @@ export function createGiteaService(options: CreateGiteaServiceOptions = {}): For
// tea discovers repository context from any configured git remote, while
// the default remote resolver reads origin only. Preserve that broader
// discovery for repositories whose primary remote has another name.
const repoPath = repositoryApiPath(repoIdentity);
const recentItems = await runJsonArray(
[
"api",
`${repoPath}/pulls?state=all&sort=recentupdate&page=1&limit=${CURRENT_PR_LOOKUP_PAGE_SIZE}`,
],
{ cwd: input.cwd },
statusRead,
GiteaCurrentPullRequestApiSchema,
);
const candidates = recentItems.filter((item) => {
@@ -1518,7 +1623,14 @@ export function createGiteaService(options: CreateGiteaServiceOptions = {}): For
candidates[0] ??
null;
if (match && mapGiteaState(match.state) !== "open") {
const repository = await readRepository(input.cwd, repoPath).catch(() => null);
const repository = await runJson(
["api", repoPath],
statusRead,
GiteaRepositoryApiSchema,
).catch((error: unknown) => {
if (error instanceof ChangeRequestRateLimitError) throw error;
return null;
});
if (isOnDefaultBranch(input, repository?.default_branch)) {
return null;
}
@@ -1527,23 +1639,30 @@ export function createGiteaService(options: CreateGiteaServiceOptions = {}): For
}
async function findOpenPullRequestForHeadRef(
input: {
cwd: string;
headRef: string;
headSha?: string;
},
headRef: string,
expectedHeadOwner: string | null,
repoPath: string,
statusRead: TeaStatusReadOptions,
): Promise<GiteaPrListItem | null> {
for (let page = 1; page <= CURRENT_PR_OPEN_LOOKUP_MAX_PAGES; page += 1) {
const items = await listPullRequestItems({
cwd: input.cwd,
state: "open",
limit: CURRENT_PR_LOOKUP_PAGE_SIZE,
page,
});
const match = items.find((item) =>
matchesCurrentHeadRef(item, input.headRef, expectedHeadOwner),
);
const items = statusRead.statusHost
? (
await runJsonArray(
[
"api",
`${repoPath}/pulls?state=open&limit=${CURRENT_PR_LOOKUP_PAGE_SIZE}&page=${page}`,
],
statusRead,
GiteaCurrentPullRequestApiSchema,
)
).map(currentPullRequestApiToListItem)
: await listPullRequestItems({
cwd: statusRead.cwd,
state: "open",
limit: CURRENT_PR_LOOKUP_PAGE_SIZE,
page,
});
const match = items.find((item) => matchesCurrentHeadRef(item, headRef, expectedHeadOwner));
if (match) {
return match;
}
@@ -1555,28 +1674,32 @@ export function createGiteaService(options: CreateGiteaServiceOptions = {}): For
}
async function loadCurrentPullRequestChecks(
cwd: string,
item: GiteaPrListItem,
status: CurrentPullRequestStatus,
statusRead: TeaStatusReadOptions,
): Promise<CurrentPullRequestStatus> {
const number = parseGiteaInt(item.index);
if (number === null || !status.repoOwner || !status.repoName) {
return status;
}
try {
const pr = await runJson(
["pr", String(number), "-o", "json"],
{ cwd },
GiteaPullRequestViewSchema,
);
if (!pr.headSha) {
const sha =
(statusRead.statusHost ? item.headSha : undefined) ??
(
await runJson(
["pr", String(number), "-o", "json"],
{ cwd: statusRead.cwd, statusHost: statusRead.statusHost },
GiteaPullRequestViewSchema,
)
).headSha;
if (!sha) {
return status;
}
const checksInput = {
cwd,
...statusRead,
repoOwner: status.repoOwner,
repoName: status.repoName,
sha: pr.headSha,
sha,
};
const [combined, actionTasks] = await Promise.all([
loadCombinedCommitStatusBestEffort(checksInput),
@@ -1588,42 +1711,37 @@ export function createGiteaService(options: CreateGiteaServiceOptions = {}): For
actionTasks,
);
return applyGiteaChecks(
{ ...status, headSha: pr.headSha },
{ ...status, headSha: sha },
combined,
actionTasks,
actionRequiredRunIds,
);
} catch {
} catch (error) {
if (error instanceof ChangeRequestRateLimitError) throw error;
return status;
}
}
async function loadCombinedCommitStatusBestEffort(input: {
cwd: string;
repoOwner: string;
repoName: string;
sha: string;
}): Promise<GiteaCombinedCommitStatus> {
async function loadCombinedCommitStatusBestEffort(
input: CurrentPullRequestCheckRead,
): Promise<GiteaCombinedCommitStatus> {
try {
return await loadCombinedCommitStatus(input);
} catch (error) {
rethrowTeaAuthFailure(error);
rethrowTeaCheckReadFailure(error);
return { state: "", statuses: [], total_count: 0 };
}
}
async function loadCombinedCommitStatus(input: {
cwd: string;
repoOwner: string;
repoName: string;
sha: string;
}): Promise<GiteaCombinedCommitStatus> {
async function loadCombinedCommitStatus(
input: CurrentPullRequestCheckRead,
): Promise<GiteaCombinedCommitStatus> {
const owner = encodeURIComponent(input.repoOwner);
const repo = encodeURIComponent(input.repoName);
const sha = encodeURIComponent(input.sha);
return runJson(
["api", `repos/${owner}/${repo}/commits/${sha}/status`],
{ cwd: input.cwd },
{ cwd: input.cwd, statusHost: input.statusHost },
GiteaCombinedCommitStatusSchema,
);
}
@@ -1633,7 +1751,7 @@ export function createGiteaService(options: CreateGiteaServiceOptions = {}): For
// (waiting run, no tasks, pending shadows). Skipping the fetch otherwise keeps
// the common running/finished path at two requests.
async function loadActionRequiredRunIdsBestEffort(
input: { cwd: string; repoOwner: string; repoName: string; sha: string },
input: CurrentPullRequestCheckRead,
combined: GiteaCombinedCommitStatus,
actionTasks: GiteaActionTask[],
): Promise<ReadonlySet<number>> {
@@ -1656,30 +1774,27 @@ export function createGiteaService(options: CreateGiteaServiceOptions = {}): For
const runs = await loadGiteaActionPages(input, "runs", `head_sha=${sha}`);
return deriveGiteaActionRequiredRunIds(runs, input.sha);
} catch (error) {
rethrowTeaAuthFailure(error);
rethrowTeaCheckReadFailure(error);
return new Set();
}
}
async function loadActionTasksBestEffort(input: {
cwd: string;
repoOwner: string;
repoName: string;
sha: string;
}): Promise<GiteaActionTask[]> {
async function loadActionTasksBestEffort(
input: CurrentPullRequestCheckRead,
): Promise<GiteaActionTask[]> {
try {
const tasks = await loadActionTasks(input);
const matchingTasks = tasks.filter((task) => task.head_sha === input.sha);
const latestTasks = latestGiteaActionTasksByWorkflow(matchingTasks);
return await enrichActionTaskApprovalsBestEffort(input, latestTasks);
} catch (error) {
rethrowTeaAuthFailure(error);
rethrowTeaCheckReadFailure(error);
return [];
}
}
async function enrichActionTaskApprovalsBestEffort(
input: { cwd: string; repoOwner: string; repoName: string; sha: string },
input: CurrentPullRequestCheckRead,
tasks: GiteaActionTask[],
): Promise<GiteaActionTask[]> {
if (!tasks.some((task) => task.status.toLowerCase() === "blocked")) return tasks;
@@ -1703,7 +1818,7 @@ export function createGiteaService(options: CreateGiteaServiceOptions = {}): For
: task,
);
} catch (error) {
rethrowTeaAuthFailure(error);
rethrowTeaCheckReadFailure(error);
return tasks;
}
}
@@ -1715,7 +1830,7 @@ export function createGiteaService(options: CreateGiteaServiceOptions = {}): For
// until total_count is exhausted, a page comes back empty, or the bounded
// max-pages cap is hit. SHA matches need not be contiguous across pages.
async function loadGiteaActionPages(
input: { cwd: string; repoOwner: string; repoName: string },
input: CurrentPullRequestCheckRead,
endpoint: "tasks" | "runs",
query?: string,
): Promise<unknown[]> {
@@ -1730,7 +1845,11 @@ export function createGiteaService(options: CreateGiteaServiceOptions = {}): For
"api",
`repos/${owner}/${repo}/actions/${endpoint}?${queryPrefix}limit=${GITEA_ACTION_PAGE_LIMIT}&page=${page}`,
],
{ cwd: input.cwd },
{
cwd: input.cwd,
statusHost: input.statusHost,
statusRepositoryKey: endpoint === "tasks" ? input.statusRepositoryKey : undefined,
},
GiteaActionsListResponseSchema,
);
if (response.workflow_runs.length === 0) break;
@@ -1741,11 +1860,7 @@ export function createGiteaService(options: CreateGiteaServiceOptions = {}): For
return items;
}
async function loadActionTasks(input: {
cwd: string;
repoOwner: string;
repoName: string;
}): Promise<GiteaActionTask[]> {
async function loadActionTasks(input: CurrentPullRequestCheckRead): Promise<GiteaActionTask[]> {
return parseGiteaActionTasks(await loadGiteaActionPages(input, "tasks"));
}
@@ -26,7 +26,7 @@ import {
rmSync,
writeFileSync,
} from "node:fs";
import { delimiter, join } from "node:path";
import { basename, delimiter, join } from "node:path";
import { tmpdir } from "node:os";
import pino from "pino";
import {
@@ -1667,25 +1667,53 @@ async function startManagerWithWorkerProtocol(
}
}
// Whether the program still accepts connections on its socket. Unlike its pid, which Windows
// hands to another process as soon as the program ends and records without a birth time, the
// socket closes with the program and nothing else answers on it.
async function programListens(socketPath: string): Promise<boolean> {
return await new Promise((resolve) => {
const socket = createConnection(socketPath);
socket.once("connect", () => {
socket.destroy();
resolve(true);
});
socket.once("error", () => resolve(false));
});
}
// A terminal running an idle program in a worker that reports `protocolVersion`, left running
// after its daemon lets go (stop --keep-terminals).
// after its daemon lets go (stop --keep-terminals). The program listens on `programSocket`.
async function leaveWorkerWithTerminal(
paseoHome: string,
protocolVersion: number,
): Promise<{ terminalId: string; programPid: number; workerPid: number; cwd: string }> {
): Promise<{
terminalId: string;
programPid: number;
programSocket: string;
workerPid: number;
cwd: string;
}> {
const cwd = mkdtempSync(join(tmpdir(), "worker-terminal-manager-protocol-"));
temporaryDirs.push(cwd);
const programSocket =
process.platform === "win32"
? `\\\\.\\pipe\\paseo-test-program-${basename(cwd)}`
: join(cwd, "program.sock");
const previous = await startManagerWithWorkerProtocol(paseoHome, protocolVersion);
const session = await previous.createTerminal({
workspaceId: "ws-protocol",
cwd,
...nodeTerminalCommand("setInterval(() => {}, 1000);"),
...nodeTerminalCommand(
`require("node:net").createServer().listen(${JSON.stringify(programSocket)}); setInterval(() => {}, 1000);`,
),
});
await waitForCondition(() => programListens(programSocket), 10000);
const [record] = await workerRecords(paseoHome);
await previous.detach();
return {
terminalId: session.id,
programPid: (await recordedTerminalPids(paseoHome)).get(session.id)!,
programSocket,
workerPid: record!.pid,
cwd,
};
@@ -1697,24 +1725,14 @@ it.each([1, 4, 5])(
const paseoHome = createTemporaryHome();
const old = await leaveWorkerWithTerminal(paseoHome, version);
const [record] = await workerRecords(paseoHome);
const program = record!.terminals.find((entry) => entry.id === old.terminalId)!;
const inspector = createTerminalWorkerProcessInspector();
manager = await startRealWorkerManager({ paseoHome });
expect(await readUnconfirmedTerminalCleanup(paseoHome)).toEqual([]);
// Startup launches a replacement worker after cleanup. Either old PID may already
// belong to another process, so verify that the recorded birth identities are gone.
// Startup launches a replacement worker after cleanup. The program's PID may already
// belong to another process, so its own socket is what proves it gone.
await waitForCondition(() => !isProcessAlive(record!.pid), 10000);
await expect
.poll(
async () =>
!isProcessAlive(program.pid) ||
classifyTerminalProgramProcess(program, await inspector.inspect(program.pid)).status ===
"unrelated",
{ timeout: 10000 },
)
.toBe(true);
await expect.poll(() => programListens(old.programSocket), { timeout: 10000 }).toBe(false);
expect(manager.getTerminal(old.terminalId)).toBeUndefined();
const workers = await workerRecords(paseoHome);
expect(workers).toHaveLength(1);
-99
View File
@@ -1,4 +1,3 @@
import copy from "../src/i18n/resources/en.json" with { type: "json" };
import { expect, test, waitForHydration, type Page } from "./fixtures";
async function openHub(page: Page, width = 1024) {
@@ -28,45 +27,6 @@ async function readPreviewOnFocus(page: Page) {
});
}
async function useLargerText(page: Page, size = "125%") {
await page.addStyleTag({ content: `html { font-size: ${size}; }` });
}
async function expectSourceLabelFits(page: Page, name: string, text = name) {
const label = page.getByRole("tab", { name }).getByText(text, { exact: true });
await expect(label).toBeVisible();
expect(await label.evaluate((element) => element.scrollWidth <= element.clientWidth)).toBe(true);
}
async function expectPreviewRowsFit(page: Page, source: string, ...rows: string[]) {
const name = new RegExp(`^${source}`);
await page.getByRole("tab", { name }).click();
const preview = page.getByRole("tabpanel", { name });
await preview.scrollIntoViewIfNeeded();
for (const row of rows) {
const text = preview.getByText(row, { exact: true }).filter({ visible: true });
await expect(text.first()).toBeVisible();
for (const match of await text.all()) {
await expect
.poll(() =>
match.evaluate((element) => {
const frame = element.closest('[role="img"]')!.getBoundingClientRect();
const range = document.createRange();
range.selectNodeContents(element);
return Array.from(range.getClientRects()).every(
(rect) =>
rect.left >= frame.left - 1 &&
rect.right <= frame.right + 1 &&
rect.top >= frame.top - 1 &&
rect.bottom <= frame.bottom + 1,
);
}),
)
.toBe(true);
}
}
}
async function focusProSeatHelp(page: Page) {
// Hydration scrolls the window back to the top, which would carry the tooltip off screen.
await waitForHydration(page);
@@ -79,15 +39,6 @@ async function focusProSeatHelp(page: Page) {
return pro.getByRole("tooltip");
}
test("Hub fits a viewport narrower than its page frame", async ({ page }) => {
await openHub(page);
const { contentWidth, viewportWidth } = await page.evaluate(() => ({
contentWidth: document.documentElement.scrollWidth,
viewportWidth: document.documentElement.clientWidth,
}));
expect(contentWidth).toBeLessThanOrEqual(viewportWidth);
});
for (const width of [320, 768, 1024]) {
test(`the complete Pro seat explanation is visible on keyboard focus at ${width}px`, async ({
page,
@@ -115,53 +66,3 @@ test("keyboard focus enters the selected preview with its current content", asyn
await expect(page.getByRole("tabpanel", { name: /^GitHub/ })).toBeFocused();
expect((await atFocus.jsonValue()).label).toMatch(/^GitHub issue/);
});
test("source names fit on a narrow phone", async ({ page }) => {
await openHub(page, 320);
await expectSourceLabelFits(page, "Schedules");
await expectSourceLabelFits(page, "Webhooks");
});
test("source names remain readable with larger text on a phone", async ({ page }) => {
await openHub(page, 375);
await useLargerText(page);
for (const name of ["GitHub", "Discord", "Schedules", "Webhooks"]) {
await expectSourceLabelFits(page, name);
}
});
test("desktop source descriptions fit with larger text", async ({ page }) => {
await openHub(page, 1280);
await useLargerText(page);
for (const { name, description } of Object.values(copy.hub.sources)) {
await expectSourceLabelFits(page, name, description);
}
});
test("Hub previews have room for their final rows with larger text", async ({ page }) => {
await page.emulateMedia({ reducedMotion: "reduce" });
await openHub(page, 1280);
await useLargerText(page);
await waitForHydration(page);
await expectPreviewRowsFit(page, "GitHub", "Open in Paseo");
await expectPreviewRowsFit(page, "Discord", "Message #engineering");
});
test("preview results fit on a narrow phone with larger text", async ({ page }) => {
await page.emulateMedia({ reducedMotion: "reduce" });
await openHub(page, 320);
await useLargerText(page);
await waitForHydration(page);
await expectPreviewRowsFit(page, "Discord", "Fix stale worktrees", "getpaseo/paseo#2825");
await expectPreviewRowsFit(page, "Schedules", "tests passed");
});
test("Hub previews keep their rows visible with twice the default font size", async ({ page }) => {
await page.emulateMedia({ reducedMotion: "reduce" });
await openHub(page, 320);
await useLargerText(page, "200%");
await waitForHydration(page);
await expectPreviewRowsFit(page, "Slack", "Open in Paseo");
await expectPreviewRowsFit(page, "Linear", "PAS-418");
await expectPreviewRowsFit(page, "Discord", "tests passed", "Message #engineering");
});
+15 -353
View File
@@ -1,115 +1,8 @@
import { expect, test, waitForHydration, type Locator, type Page } from "./fixtures";
import { expect, test, waitForHydration, type Page } from "./fixtures";
const desktopName =
"Paseo desktop app with coding agents, a conversation, and a code diff open side by side";
/** Opens the homepage once it has hydrated, so the router's scroll reset cannot undo a later scroll. */
async function openHomepage(page: Page, window = { width: 1512, height: 930 }) {
await page.setViewportSize(window);
await page.goto("/");
await waitForHydration(page);
}
/** The scene advances at most 64 ms per frame. Drive its frames independently of CI paint speed. */
async function openHomepageWithSceneClock(
page: Page,
viewport?: { width: number; height: number },
) {
await page.clock.install();
await openHomepage(page, viewport);
await page.clock.pauseAt(await page.evaluate(() => Date.now() + 1000));
}
async function centerMockup(mockup: Locator) {
await mockup.evaluate((element) =>
element.scrollIntoView({ block: "center", behavior: "instant" }),
);
}
/**
* Plays the scene clock until `shows` is visible. Bringing the mockup on screen starts the opening
* scene a few page tasks later: the start line's IntersectionObserver fires, then React runs the
* effect that starts the player. A clock advance sent right after the scroll can run before that.
*/
async function playUntilVisible(page: Page, shows: Locator) {
await expect
.poll(
async () => {
await page.clock.runFor(1000);
return shows.isVisible();
},
// The page clock is paused, so waiting between checks only spends the test's time.
{ intervals: [0], timeout: 15_000 },
)
.toBe(true);
}
async function finishPanelSwap(page: Page, mockup: Locator, outgoingPanel: Locator) {
await expect
.poll(async () => {
await page.clock.runFor(250);
// Playwright's clock drives JavaScript frames. Native animations use the document timeline.
await mockup.evaluate((element) => {
for (const animation of element.getAnimations({ subtree: true })) {
if (Number.isFinite(animation.effect?.getComputedTiming().endTime)) animation.finish();
}
});
return outgoingPanel.count();
})
.toBe(0);
}
async function viewPhones(page: Page) {
await page.getByRole("img", { name: "Paseo agent chat", exact: true }).scrollIntoViewIfNeeded();
}
async function expectScreenContentInsidePhone(page: Page, name: string, time: string) {
const phone = page.getByRole("img", { name, exact: true });
const clock = phone.getByText(time, { exact: true });
await expect(clock).toBeVisible();
await expect(async () => {
const frame = await phone.boundingBox();
const content = await clock.boundingBox();
expect(frame).not.toBeNull();
expect(content).not.toBeNull();
if (!frame || !content) throw new Error("Phone screen is not rendered");
expect(content.x).toBeGreaterThanOrEqual(frame.x);
expect(content.y).toBeGreaterThanOrEqual(frame.y);
expect(content.x + content.width).toBeLessThanOrEqual(frame.x + frame.width);
expect(content.y + content.height).toBeLessThanOrEqual(frame.y + frame.height);
}).toPass({ timeout: 5000 });
}
async function cornerProportion(mockup: Locator) {
return mockup.evaluate((element) => {
const radius = getComputedStyle(element).borderTopLeftRadius.split(" ")[0];
if (radius.endsWith("%")) return Number.parseFloat(radius) / 100;
return Number.parseFloat(radius) / element.getBoundingClientRect().width;
});
}
async function resizeToPhone(page: Page) {
await page.setViewportSize({ width: 390, height: 844 });
await page.getByRole("img", { name: desktopName, exact: true }).scrollIntoViewIfNeeded();
}
test("the three phone mockups show their screen content", async ({ page }) => {
await openHomepage(page);
await viewPhones(page);
await expectScreenContentInsidePhone(page, "Paseo workspace drawer", "18:54");
await expectScreenContentInsidePhone(page, "Paseo agent chat", "18:53");
await expectScreenContentInsidePhone(page, "Paseo diff view", "18:55");
});
test("desktop mockup corners shrink in proportion on a phone", async ({ page }) => {
await openHomepage(page);
const mockup = page.getByRole("img", { name: desktopName, exact: true });
const desktopCorner = await cornerProportion(mockup);
expect(desktopCorner).toBeGreaterThan(0);
await resizeToPhone(page);
await expect.poll(() => cornerProportion(mockup)).toBeCloseTo(desktopCorner, 3);
});
/** Each hero pill and one thing only its finished scene draws. */
const HERO_SCENES = [
{ pill: "Orchestration", shows: "Pi · GLM-5.2" },
@@ -119,259 +12,28 @@ const HERO_SCENES = [
{ pill: "Plugins", shows: "app-tests (macos)" },
];
/** Clicks a hero pill until its scene starts. A click before hydration selects nothing. */
async function playScene(page: Page, pill: string, opensWith: Locator) {
await expect(async () => {
await page.getByRole("button", { name: pill, exact: true }).click();
await expect(opensWith).toBeVisible({ timeout: 500 });
}).toPass({ timeout: 10_000 });
async function openHomepage(page: Page) {
await page.emulateMedia({ reducedMotion: "reduce" });
await page.goto("/");
await waitForHydration(page);
}
test("each hero pill shows its finished scene when motion is reduced", async ({ page }) => {
await page.emulateMedia({ reducedMotion: "reduce" });
await openHomepage(page);
async function selectHeroScene(page: Page, pill: string, expectedText: string) {
const button = page.getByRole("button", { name: pill, exact: true });
await button.click();
await expect(button).toHaveAttribute("aria-pressed", "true");
const mockup = page.getByRole("img", { name: desktopName, exact: true });
await mockup.scrollIntoViewIfNeeded();
// Last to first, so the opening scene is also reached by a click.
for (const scene of HERO_SCENES.toReversed()) {
await playScene(page, scene.pill, mockup.getByText(scene.shows, { exact: true }).first());
}
});
await expect(mockup.getByText(expectedText, { exact: true }).first()).toBeVisible();
}
test("the hero opens on orchestration across providers and machines", async ({ page }) => {
await page.emulateMedia({ reducedMotion: "reduce" });
test("switches between hero scenes via the scene pills", async ({ page }) => {
await openHomepage(page);
const mockup = page.getByRole("img", { name: desktopName, exact: true });
await expect(page.getByRole("button", { name: "Orchestration", exact: true })).toHaveAttribute(
"aria-pressed",
"true",
);
for (const agent of ["Codex · GPT-5.6-Sol", "OpenCode · Kimi K3", "Pi · GLM-5.2"]) {
await expect(mockup.getByText(agent, { exact: true })).toBeVisible();
}
// The task on another machine carries that host's badge in its tool call and its subagent row.
for (const remoteTask of ["OpenCode · fix/menu-bar-icon", "OpenCode · Kimi K3"]) {
const row = mockup.getByText(remoteTask, { exact: true }).locator("xpath=..");
await expect(row.getByText("mac-mini", { exact: true })).toBeVisible();
// Last to first, so the opening scene is also reached by a click.
for (const scene of HERO_SCENES.toReversed()) {
await selectHeroScene(page, scene.pill, scene.shows);
}
});
test("the orchestration scene plays from an empty chat to the open roster of subagents", async ({
page,
}) => {
await openHomepageWithSceneClock(page);
const mockup = page.getByRole("img", { name: desktopName, exact: true });
const composer = mockup.getByText("Message the agent, tag @files, or use /commands and /skills");
await playScene(page, "Orchestration", composer);
await expect(mockup.getByText("Create agent", { exact: true })).toHaveCount(0);
await expect(mockup.getByText("3 subagents", { exact: true })).toHaveCount(0);
// The orchestrator lists the issues and the agent profiles, launches three agents and says so,
// then the pointer clicks the pill and the roster opens. Ten seconds outlasts the scene.
await page.clock.runFor(10_000);
await expect(mockup.getByText("3 subagents", { exact: true })).toBeVisible();
await expect(mockup.getByText("gh issue list --label ready", { exact: true })).toBeVisible();
await expect(mockup.getByText("List agent profiles", { exact: true })).toBeVisible();
await expect(
mockup.getByText(
"I will launch the UI agent on your mac-mini, because that issue is specific to macOS.",
),
).toBeVisible();
await expect(mockup.getByText("Create agent", { exact: true })).toHaveCount(3);
await expect(
mockup.getByText("All three are launched. Paseo will notify me when each one finishes."),
).toBeVisible();
await expect(mockup.getByText("Pi · GLM-5.2", { exact: true })).toBeVisible();
});
test("the opening scene waits until most of the mockup is on screen", async ({ page }) => {
await openHomepageWithSceneClock(page);
const mockup = page.getByRole("img", { name: desktopName, exact: true });
const request = mockup.getByText("Fix the issues labeled ready, one worktree each.");
await expect(mockup).not.toBeInViewport({ ratio: 0.6 });
// A scene that started at load sends the request within three seconds.
await page.clock.runFor(4500);
await expect(request).toHaveCount(0);
await centerMockup(mockup);
await expect(mockup).toBeInViewport({ ratio: 0.6 });
await playUntilVisible(page, request);
});
test("the opening scene starts in a window shorter than most of the mockup", async ({ page }) => {
await openHomepageWithSceneClock(page, { width: 1400, height: 320 });
const mockup = page.getByRole("img", { name: desktopName, exact: true });
const request = mockup.getByText("Fix the issues labeled ready, one worktree each.");
await centerMockup(mockup);
await expect(mockup).toBeInViewport();
await expect(mockup).not.toBeInViewport({ ratio: 0.6 });
await playUntilVisible(page, request);
});
test("the plugins scene installs the panel, then changes it on request", async ({ page }) => {
await openHomepageWithSceneClock(page);
const mockup = page.getByRole("img", { name: desktopName, exact: true });
const changesPanel = mockup.getByText("Uncommitted", { exact: true });
const pluginPanel = mockup.getByText("Recently merged", { exact: true });
const failingCheck = mockup.getByText("app-tests (macos)", { exact: true });
await playScene(page, "Plugins", page.getByRole("button", { name: "Plugins", pressed: true }));
await expect(changesPanel).toBeVisible();
await expect(pluginPanel).toHaveCount(0);
// Installing the plugin swaps the docked panel for the one the agent built.
await page.clock.runFor(5500);
await expect(pluginPanel).toBeVisible();
await finishPanelSwap(page, mockup, changesPanel);
await expect(failingCheck).toHaveCount(0);
// The second request reloads the plugin and the open panel lists the failing check.
await page.clock.runFor(6000);
await expect(failingCheck).toBeVisible();
await expect(
mockup.getByText("paseo plugin reload release-radar", { exact: true }),
).toBeVisible();
});
test("the code review scene comments on a line and sends the feedback to an agent", async ({
page,
}) => {
await openHomepageWithSceneClock(page);
const mockup = page.getByRole("img", { name: desktopName, exact: true });
const comment = mockup.getByText("Add “write”. The agent edits files too.", { exact: true });
const sendFeedback = mockup.getByText("Send feedback (1)", { exact: true });
await playScene(
page,
"Code review",
page.getByRole("button", { name: "Code review", pressed: true }),
);
await expect(comment).toHaveCount(0);
// The pointer opens the editor on a line, and the typed comment is saved under that line.
await page.clock.runFor(3500);
await expect(sendFeedback).toBeVisible();
await expect(comment).toBeVisible();
// Send feedback asks which agent, and the sent comment leaves the diff.
await page.clock.runFor(1300);
await expect(mockup.getByText("Claude Code", { exact: true })).toHaveCount(2);
await page.clock.runFor(1500);
await expect(mockup.getByText("Feedback sent to Codex", { exact: true })).toBeVisible();
await finishPanelSwap(page, mockup, sendFeedback);
await finishPanelSwap(page, mockup, comment);
});
test("picking a scene brings the pills and the whole mockup on screen", async ({ page }) => {
await openHomepage(page);
const mockup = page.getByRole("img", { name: desktopName, exact: true });
await expect(mockup).not.toBeInViewport({ ratio: 0.9 });
await playScene(page, "Remote", page.getByRole("button", { name: "Remote", pressed: true }));
await expect(mockup).toBeInViewport({ ratio: 0.99 });
await expect(page.getByRole("button", { name: "Remote", exact: true })).toBeInViewport({
ratio: 1,
});
});
test("picking a scene in a window too short for the mockup keeps the pills on screen", async ({
page,
}) => {
await openHomepage(page);
await page.setViewportSize({ width: 1280, height: 600 });
const mockup = page.getByRole("img", { name: desktopName, exact: true });
await expect(mockup).not.toBeInViewport();
await playScene(page, "Remote", page.getByRole("button", { name: "Remote", pressed: true }));
await expect(mockup).toBeInViewport({ ratio: 0.7 });
await expect(page.getByRole("button", { name: "Remote", exact: true })).toBeInViewport({
ratio: 1,
});
});
test("picking a scene while the hero is still sliding in keeps the pills on screen", async ({
page,
}) => {
// Reduced motion makes the scroll instant, so the test does not wait for one to settle.
await page.emulateMedia({ reducedMotion: "reduce" });
await openHomepage(page, { width: 1280, height: 700 });
const mockup = page.getByRole("img", { name: desktopName, exact: true });
await playScene(page, "Remote", page.getByRole("button", { name: "Remote", pressed: true }));
// The hero slides up 40px as it enters. The test waits for that to end, puts the same 40px back
// on the container, picks a scene, and lets the slide end again. A click during a real slide
// does the same, but only inside the first second after load.
const sliding = page
.getByRole("button", { name: "Remote", exact: true })
.locator("xpath=../../../..");
await expect(sliding).toHaveCSS("transform", "none");
await page.evaluate(() => window.scrollTo(0, 0));
await expect(mockup).not.toBeInViewport({ ratio: 0.99 });
const slideBy = (pixels: number) =>
sliding.evaluate((container, y) => {
container.style.transform = y === 0 ? "none" : `translateY(${y}px)`;
}, pixels);
const codeReview = page.getByRole("button", { name: "Code review", exact: true });
await slideBy(40);
await codeReview.click();
await slideBy(0);
expect(await page.evaluate(() => window.scrollY)).toBeGreaterThan(0);
await expect(codeReview).toBeInViewport({ ratio: 1 });
});
test("the remote scene lists hosts with how each connects and its round trip time", async ({
page,
}) => {
await openHomepage(page);
const mockup = page.getByRole("img", { name: desktopName, exact: true });
await expect(async () => {
await page.getByRole("button", { name: "Remote", exact: true }).click();
await expect(mockup.getByText("Hosts", { exact: true })).toBeVisible({ timeout: 500 });
}).toPass({ timeout: 10_000 });
for (const fact of ["Local", "Relay", "Tailscale", "SSH", "38ms", "mo@workstation"]) {
await expect(mockup.getByText(fact, { exact: true })).toBeVisible();
}
});
/** Opacity as rendered: the element's own times every ancestor's. */
async function renderedOpacity(locator: Locator) {
return locator.evaluate((element) => {
let opacity = 1;
for (let node: Element | null = element; node; node = node.parentElement) {
opacity *= Number.parseFloat(getComputedStyle(node).opacity);
}
return opacity;
});
}
test("the plugin demo plays through to the panel the agent built", async ({ page }) => {
await openHomepage(page);
const builtPanelRow = page.getByText("Add Gruvbox theme", { exact: true });
expect(await renderedOpacity(builtPanelRow)).toBe(0);
// Hydration can reset the scroll position, so keep the demo in view until it finishes.
const heading = page.getByRole("heading", { name: "Ask Paseo to change Paseo" });
await expect(async () => {
await heading.scrollIntoViewIfNeeded();
expect(await renderedOpacity(builtPanelRow)).toBe(1);
}).toPass({ timeout: 15_000 });
expect(await renderedOpacity(page.getByText("Review queue is in your sidebar."))).toBe(1);
});
test("the plugin demo shows its finished state when motion is reduced", async ({ page }) => {
await page.emulateMedia({ reducedMotion: "reduce" });
await openHomepage(page);
const builtPanelRow = page.getByText("Add Gruvbox theme", { exact: true });
const panel = builtPanelRow.locator("xpath=ancestor::div[contains(@class, 'md:border-l')]");
const heading = page.getByRole("heading", { name: "Ask Paseo to change Paseo" });
const section = heading.locator("xpath=ancestor::section[1]");
// The section fades in when it scrolls into view. The demo inside must already be finished
// when that fade ends; the staged demo would still be hiding the row for seconds.
await expect(async () => {
await heading.scrollIntoViewIfNeeded();
expect(await renderedOpacity(section)).toBe(1);
}).toPass();
expect(await renderedOpacity(builtPanelRow)).toBe(1);
expect(await panel.evaluate((element) => getComputedStyle(element).transform)).toBe("none");
});
+3 -101
View File
@@ -16,51 +16,6 @@ function pluginCards(page: Page, section: string): Locator {
.filter({ hasNotText: /^See all$/ });
}
test("scrolls mobile plugin carousels without widening the page", async ({ page }) => {
await page.setViewportSize({ width: 390, height: 844 });
await openPlugins(page);
await expectPageWithinViewport(page);
await scrollPluginCarousel(page, "Featured");
await scrollPluginCarousel(page, "What’s new");
await expectPageWithinViewport(page);
});
// Graphite's fixture description ends in raw README HTML with an unbreakable srcset URL.
test("keeps browse grids within a phone's width when a description has an unbreakable word", async ({
page,
}) => {
await page.setViewportSize({ width: 390, height: 844 });
await page.goto("/plugins/all");
await expect(page.getByRole("heading", { level: 1, name: /^All plugins/ })).toBeVisible();
await expectPageWithinViewport(page);
});
async function expectPageWithinViewport(page: Page) {
expect(await page.evaluate(() => document.documentElement.scrollWidth)).toBeLessThanOrEqual(
await page.evaluate(() => document.documentElement.clientWidth),
);
await page.evaluate(() => window.scrollTo({ left: 1000, behavior: "instant" }));
expect(await page.evaluate(() => window.scrollX)).toBe(0);
}
async function scrollPluginCarousel(page: Page, section: string) {
const cards = pluginCards(page, section);
// The cards share a non-semantic scrolling container.
const strip = cards.first().locator("..");
await strip.evaluate((element) =>
element.scrollIntoView({ block: "center", behavior: "instant" }),
);
expect(await strip.evaluate((element) => element.scrollWidth)).toBeGreaterThan(
await strip.evaluate((element) => element.clientWidth),
);
await expect(cards.last()).not.toBeInViewport();
await strip.evaluate((element) =>
element.scrollTo({ left: element.scrollWidth, behavior: "instant" }),
);
await expect(cards.last()).toBeInViewport({ ratio: 1 });
await expect(cards.first()).not.toBeInViewport();
}
test("browses from the directory into a category, a plugin, and its author", async ({
page,
context,
@@ -585,9 +540,7 @@ test.describe("registry fixture layout", () => {
await page.goto(`/plugins/${plugin.id}`);
const tiles = page.getByRole("link", { name: /^Dracula (screenshot|video) \d$/ });
await expect(tiles).toHaveCount(3);
const layout = await tiles.evaluateAll(galleryTiles);
expect(layout.map((tile) => tile.href)).toEqual(plugin.media);
expect(new Set(layout.map((tile) => tile.size)).size).toBe(1);
expect(await tiles.evaluateAll(tileHrefs)).toEqual(plugin.media);
const preview = tiles.nth(1).locator("video");
await expect(preview).toHaveAttribute("preload", "metadata");
await expect(preview).not.toHaveAttribute("controls");
@@ -600,8 +553,6 @@ test.describe("registry fixture layout", () => {
await expect(playing).toHaveAttribute("src", video);
await expect(playing).toHaveAttribute("controls", "");
await expect.poll(() => playing.evaluate(isPaused)).toBe(false);
// The fixture video is 320x240, so it has to scale up to fill the viewer.
await expect.poll(() => playing.evaluate(viewerFill)).toBeCloseTo(1, 2);
await page.keyboard.press("Escape");
await expect(viewer).toBeHidden();
await expect(page.locator("dialog video")).toHaveCount(0);
@@ -621,30 +572,6 @@ test.describe("registry fixture layout", () => {
await expect(viewer).toBeHidden();
});
test("peeks the next gallery tile at the strip's edge, and fills the row with two", async ({
page,
}) => {
// Wide screens show two tiles and part of the third; phones show one and part of the second.
for (const [width, expected] of [
[1280, [1, 1, "peeks"]],
[375, [1, "peeks", 0]],
] as const) {
await page.setViewportSize({ width, height: 720 });
await page.goto("/plugins/omercnet/dracula");
await expectPageWithinViewport(page);
const three = page.getByRole("link", { name: /^Dracula (screenshot|video) \d$/ });
const shares = await three.evaluateAll(visibleShares);
expect(shares.map((share) => (share > 0.1 && share < 0.5 ? "peeks" : share))).toEqual(
expected,
);
}
await page.setViewportSize({ width: 1280, height: 720 });
await page.goto("/plugins/gpambrozio/herald");
const two = page.getByRole("link", { name: /^Herald screenshot \d$/ });
expect(await two.evaluateAll(visibleShares)).toEqual([1, 1]);
});
test("steps through the viewer with arrow keys and buttons, wrapping at the ends", async ({
page,
}) => {
@@ -741,27 +668,8 @@ test.describe("registry fixture layout", () => {
});
});
function galleryTiles(links: Element[]) {
return links.map((link) => ({
href: link.getAttribute("href"),
size: `${link.clientWidth}x${link.clientHeight}`,
}));
}
/** How much of each tile's width the gallery strip shows, rounded to hundredths. */
function visibleShares(links: Element[]) {
const strip = links[0].parentElement!.getBoundingClientRect();
return links.map((link) => {
const tile = link.getBoundingClientRect();
const shown = Math.min(tile.right, strip.right) - Math.max(tile.left, strip.left);
return Math.round((Math.max(shown, 0) / tile.width) * 100) / 100;
});
}
/** The share of the viewer's room the media fills along its limiting axis; 1 fills it. */
function viewerFill(media: HTMLElement) {
const box = media.getBoundingClientRect();
return Math.max(box.width / (window.innerWidth * 0.9), box.height / (window.innerHeight * 0.85));
function tileHrefs(links: Element[]) {
return links.map((link) => link.getAttribute("href"));
}
function isPaused(video: HTMLVideoElement) {
@@ -785,12 +693,6 @@ async function expectThumbnailCard(card: Locator, source: string, id: string) {
{ timeout: 15_000 },
)
.toBe(true);
const box = await image.evaluate((element) => {
const rect = element.parentElement!.getBoundingClientRect();
return { width: rect.width, height: rect.height };
});
expect(box.width).toBeGreaterThan(0);
expect(box.width / box.height).toBeCloseTo(1.6, 2);
}
test("keeps author content inert through SSR and hydration", async ({
-54
View File
@@ -21,57 +21,3 @@ for (const path of PAGES) {
);
});
}
test("keeps the invitation beside a sponsor instead of alone on its own row", async ({ page }) => {
await page.setViewportSize({ width: 1280, height: 800 });
await test.step("homepage keeps all sponsors and the invitation in one row", async () => {
await page.goto("/");
const sponsors = page.getByRole("region", { name: "Sponsors", exact: true });
const firstLogo = await sponsors.getByRole("img", { name: SPONSORS[0].name }).boundingBox();
const invitation = await sponsors.getByRole("link", { name: "Become a sponsor" }).boundingBox();
expect(invitation!.y).toBeLessThan(firstLogo!.y + firstLogo!.height);
});
await test.step("docs column pairs the invitation beside the last sponsor", async () => {
await page.goto("/docs/connectivity");
const sponsors = page.getByRole("region", { name: "Sponsors", exact: true });
const lastLogo = await sponsors
.getByRole("img", { name: SPONSORS[SPONSORS.length - 1].name })
.boundingBox();
const invitation = await sponsors.getByRole("link", { name: "Become a sponsor" }).boundingBox();
expect(invitation!.y).toBeLessThan(lastLogo!.y + lastLogo!.height);
});
});
test("arranges sponsors in two columns on mobile without overflowing", async ({ page }) => {
await page.setViewportSize({ width: 375, height: 812 });
for (const path of ["/", "/docs/connectivity", "/sponsor"]) {
await test.step(`${path} renders two sponsors per row on mobile`, async () => {
await page.goto(path);
const sponsors = page.getByRole("region", { name: "Sponsors", exact: true });
const first = await sponsors.getByRole("img", { name: SPONSORS[0].name }).boundingBox();
const second = await sponsors.getByRole("img", { name: SPONSORS[1].name }).boundingBox();
const third = await sponsors.getByRole("img", { name: SPONSORS[2].name }).boundingBox();
const invitation = await sponsors
.getByRole("link", { name: "Become a sponsor" })
.boundingBox();
expect(second!.x).toBeGreaterThan(first!.x + first!.width);
expect(second!.y).toBeLessThan(first!.y + first!.height);
expect(invitation!.x).toBeGreaterThan(third!.x + third!.width);
expect(invitation!.y).toBeLessThan(third!.y + third!.height);
const hasHorizontalOverflow = await page.evaluate(
() => document.documentElement.scrollWidth > window.innerWidth,
);
expect(hasHorizontalOverflow).toBe(false);
});
}
});
+2 -1
View File
@@ -5,7 +5,8 @@ const baseURL = process.env.WEBSITE_TEST_URL ?? "http://127.0.0.1:8187";
export default defineConfig({
testDir: "./e2e",
workers: process.env.CI ? 4 : 1,
workers: process.env.CI ? 2 : undefined,
retries: process.env.CI ? 1 : 0,
use: { baseURL, screenshot: "only-on-failure", trace: "retain-on-failure" },
projects: [
{ name: "chromium", use: { ...devices["Desktop Chrome"] } },
+30 -3
View File
@@ -22,6 +22,7 @@ const gatedCiJobs = new Map([
["quality", { name: "quality", contracts: ["format", "quality", "relay", "sdk"] }],
["sdk-tests-windows", { name: "sdk-tests (windows-latest)", contract: "sdk" }],
["typecheck", { name: "typecheck", contract: "quality" }],
["website-tests", { name: "website-tests", contract: "website" }],
["server-tests-ubuntu", { name: "server-tests (ubuntu-latest)", contracts: ["server", "hub"] }],
["server-tests-windows", { name: "server-tests (windows-latest)", contracts: ["server", "hub"] }],
[
@@ -299,7 +300,7 @@ test("PR routing declares stable behavior ownership", () => {
"packages/server/src/server/agent/providers/codex-app-server-agent.ts",
"packages/server/src/server/agent/providers/claude/agent.ts",
"packages/server/src/server/agent/plugin-provider.ts",
"packages/server/src/server/plugins/{index,plugin-process,plugin-process-protocol,runtime}.ts",
"packages/server/src/server/plugins/{index,managed-source,plugin-process,plugin-process-protocol,runtime}.ts",
"packages/server/src/executable-resolution/**",
"packages/plugin/src/server/provider.ts",
"packages/app/src/!(desktop)/**",
@@ -313,6 +314,16 @@ test("PR routing declares stable behavior ownership", () => {
"packages/react-native-enriched-markdown/**",
],
relay: ["packages/relay/**"],
website: [
"packages/website/**",
"packages/protocol/**",
"public-docs/**",
"CHANGELOG.md",
"CHANGELOG.zh-CN.md",
"README*.md",
"assets/brand/**",
"packages/app/assets/images/editor-apps/finder.png",
],
cli: ["packages/cli/**", "packages/server/**", "packages/plugin/**", "plugins/**"],
});
});
@@ -379,7 +390,7 @@ test("browser and desktop tests have exclusive, directory-owned suites", () => {
"packages/server/src/server/agent/providers/codex-app-server-agent.ts",
"packages/server/src/server/agent/providers/claude/agent.ts",
"packages/server/src/server/agent/plugin-provider.ts",
"packages/server/src/server/plugins/{index,plugin-process,plugin-process-protocol,runtime}.ts",
"packages/server/src/server/plugins/{index,managed-source,plugin-process,plugin-process-protocol,runtime}.ts",
"packages/server/src/executable-resolution/**",
"packages/plugin/src/server/provider.ts",
"packages/app/src/!(desktop)/**",
@@ -553,10 +564,26 @@ test("iOS App Store review queue EAS workflows and Fastlane lanes stay wired and
assert.equal(unitTests.status, 0, `${unitTests.stdout}\n${unitTests.stderr}`);
});
test("website tests run in their own website-gated job without blocking typecheck", () => {
const jobs = jobBlocks(readFileSync(ciWorkflowPath, "utf8"));
const typecheck = jobs.get("typecheck").join("\n");
const website = jobs.get("website-tests").join("\n");
assert.match(typecheck, /^ runs-on: ubuntu-latest$/m);
assert.doesNotMatch(typecheck, /playwright|website-browser-debs|packages\/website/);
assert.match(website, /^ runs-on: ubuntu-24\.04$/m);
assert.match(website, /run: npm run build:protocol$/m);
assert.match(website, /run: npx vitest run packages\/website\/src --bail=1$/m);
assert.match(website, /npx playwright install --with-deps chromium webkit/);
assert.match(website, /run: npm run test:e2e --workspace=@getpaseo\/website$/m);
assert.match(website, /name: website-playwright-results/);
});
test("eight Playwright shards share two-worker coverage", () => {
const source = readFileSync(ciWorkflowPath, "utf8");
const jobs = jobBlocks(source);
assert.equal(jobs.size, 22);
assert.equal(jobs.size, 23);
for (let shard = 1; shard <= 8; shard++) {
const job = jobs.get(`playwright-${shard}`).join("\n");
assert.match(job, new RegExp(`PLAYWRIGHT_SHARD: "${shard}/8"`));