Compare commits

..
16 Commits
Author SHA1 Message Date
Mohamed Boudra c09a3d81e7 chore(release): cut 0.16.1 2026-11-17 07:06:25 +01:00
Mohamed Boudra 8c91adeba8 docs(changelog): prepare 0.16.1 stable 2026-11-17 07:01:17 +01:00
paseo-ai[bot] 0a8b7a6a1e fix: update lockfile signatures and Nix hash [skip ci]
(cherry picked from commit 0bac18f359)
2026-11-17 06:27:55 +01:00
Mohamed Boudra 18192dc48b fix(claude): keep the user's ask rules and hooks in Bypass (#9927)
In Bypass, Claude agents again show a permission card for asks from the user's permissions.ask rules (including managed policy), PreToolUse hooks that return ask, compound and piped commands that hit an ask rule, permissions.blockReadsOutsideWorkingDirectories, an organization's ask limit, and sandbox overrides. Claude's own checks are still approved without a card. Upgrades @anthropic-ai/claude-agent-sdk to 0.3.326, which passes the ask's source to canUseTool.

Closes #9916

(cherry picked from commit 3eedffc4ac)
2026-11-17 06:27:55 +01:00
Michael Thomas 162745d8e6 fix: size controls by the primary pointer, not any touch screen (#9909)
* feat(desktop): size controls by the primary pointer, not any touch screen

The desktop app gave touch-sized controls to every machine with a touch
screen, including Windows laptops driven by a trackpad. In Electron, ask
whether a mouse-like primary pointer drives the UI instead: Chromium
reports a fine primary pointer for those laptops and a coarse one for a
tablet with no mouse or trackpad attached.

Browsers and native keep the touch-screen check, so an iPad keeps touch
sizes with a trackpad attached. Swipe gestures still follow the
touch-screen capability.

Refs #9892

* feat(app): size controls by the primary pointer on every platform

Replace the Electron-only check with one rule everywhere: touch-sized
when touch is the primary input, `(pointer: coarse)`, rather than when a
touch screen exists at all. WebKit keeps touch primary on an iPad with a
trackpad attached, so iPad Safari stays touch-sized; Chromium reports a
fine primary pointer for a touch-screen laptop driven by its trackpad, in
the browser and the desktop app. Native is always touch-sized.

`hasTouchScreen()` and its `maxTouchPoints` fallback had no other caller
and are removed. Swipe gestures still follow the touch-screen capability.

Refs #9892

* test(app): exercise pointer sizing through the media source

* test(app): cover touch laptops with a primary pointer

---------

Co-authored-by: Mohamed Boudra <boudra.moha@gmail.com>
(cherry picked from commit e5352c9890)
2026-11-17 06:27:55 +01:00
paseo-bot[bot] 937a610006 fix(opencode): clear a question that a new message replaces (#9891)
With the default send setting, a message sent while an OpenCode agent
waits on a question steers the turn, and Paseo rejects the question in
OpenCode. The OpenCode session dropped the question from its own list
without reporting it resolved, so the agent manager and the app kept
showing it. Answering or dismissing it then failed with "No pending
permission request", and the prompt could not be closed.

The session now reports permission_resolved whenever OpenCode accepts a
reply, rejection, or answer, as the other providers do.

Fixes #9879

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit 038a9ca00d)
2026-11-17 06:27:55 +01:00
Angus Buick 2269c8a010 fix(app): draw the Add host text fields as inputs again (#9864) (#9865)
AdaptiveTextInput wraps its input with withUnistyles, and the pairing link and direct connection modals wrapped AdaptiveTextInput a second time. On web each wrapper is a display: contents element whose style lands on its direct child, so the outer style landed on the inner wrapper and the input lost its border, background and padding.

Drop the outer wrapper, AdaptiveTextInput already themes the placeholder colour. Also give the host password field a placeholder and focus it when pairing asks for a password.

(cherry picked from commit b95f1bbf31)
2026-11-17 06:27:55 +01:00
paseo-bot[bot] e0847ac82f Let idle cleanup release Codex chats opened only to read history (#9859)
A Codex session opened to read history reads the thread and disposes its
app-server right away, but canStopRuntime() vetoed it because it had no
client. Idle cleanup then kept every such chat loaded in the daemon.

Closes #9804

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
Co-authored-by: Spencer Shulem <1703265+Spshulem@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit 5a78c1cd16)
2026-11-17 06:27:55 +01:00
paseo-bot[bot] 9ba2950132 Keep Claude signed in when model discovery runs during a token refresh (#9855)
* Let Claude model discovery finish a token refresh instead of killing it

Model discovery stopped waiting after 5 s by aborting the SDK query and
tree-killing the CLI. A CLI that is still refreshing an expired OAuth
token at that moment has already rotated the refresh token, so the kill
leaves only the revoked token on disk and logs the user out.

The 5 s limit now only bounds the wait. A CLI that has not answered gets
its input ended and exits on its own; it is tree-killed only after a
60 s grace period or when the daemon shuts down.

Fixes #9314

* fix(server): let Claude model discovery finish a token refresh after it answers

Claude Code answers the model list before its startup token refresh has
saved the rotated refresh token. Discovery killed the CLI right after the
answer, so a refresh still in flight left the revoked token on disk and
every later Claude session failed until /login. Discovery now ends the
CLI's input and lets it exit on its own whether or not it answered, with
the existing grace period and shutdown kill as the bound.

Co-authored-by: daysun-k <8309193+daysun-k@users.noreply.github.com>

---------

Co-authored-by: daysun-k <8309193+daysun-k@users.noreply.github.com>
Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
(cherry picked from commit 8522d18ed8)
2026-11-17 06:27:55 +01:00
paseo-bot[bot] fbb7a2c094 fix(server): return only the newest reply as the last message after a restart (#9846)
After a daemon restart, an agent's timeline is rebuilt from provider
history, and those rows have no turn id. A reply the agent starts on its
own, such as Claude waking after a background subagent, follows the
previous reply with no user message between them, so the last assistant
message lookup joined the two and wait results and finish notifications
returned the old reply with the new one appended.

The timeline projection already treats a message id change as a new
message. Share that rule with the lookup, so both decide which rows are
chunks of one message the same way.

Closes #9814

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit be92e85a4e)
2026-11-17 06:27:55 +01:00
paseo-bot[bot] 4437186c49 fix(omp): show model names with slashes and underscores in full (#9836)
OMP model labels were built as `${provider}/${name}` and then cut at the
last `/`, so a free-text name such as "... ~60-70 tok/s on 0.2.10, 52/56)"
showed as "56)". Underscores were rewritten to spaces ("IQ3_S" -> "IQ3 S"),
and a colon inside the name cut everything before it.

Pi had the same bug, fixed in #9823. Move that label rule into a shared
model-label module and use it for both providers: free-text names are
kept, path-like names are shortened to their last segment, and a
"Vendor: " prefix is dropped only when it is a prefix.

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
Co-authored-by: Rahul Sharma <19687913+rms523@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit a302e65c85)
2026-11-17 06:27:55 +01:00
paseo-bot[bot] 4bba288c10 fix(server): see same-size edits saved in the tick a file was staged (#9854)
The private index snapshot behind index and All changes comparisons was a
fresh copy, newer than every entry, so Git skipped its same-timestamp
content check and a same-size save made right after staging read as
unchanged. The copy now keeps the source index's mtime, rounded down to
the second.

Closes #9827

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
(cherry picked from commit d49991318f)
2026-11-17 06:27:55 +01:00
Mohamed Boudra c48d1c1700 Dismiss chat errors and identify timed-out requests (#9837)
* fix(app): dismiss chat errors and identify timed-out requests

* test(client): assert subscription timeout codes

* refactor(app): keep toast errors on the existing string boundary

* test(app): remove redundant toast duration coverage

(cherry picked from commit e19980a6c9)
2026-11-17 06:27:55 +01:00
paseo-bot[bot] db3cfadc6c Show Pi model names with slashes and underscores in full (#9823)
* fix(pi): keep slashes and underscores in model display names

Pi model labels were built as `${provider}/${name}` and then cut at the
last `/`, so a free-text name such as "... ~60-70 tok/s, 52/56)" was shown
as "56)". Underscores were also rewritten to spaces ("IQ3_S" -> "IQ3 S").
The compact model trigger in the app repeated the last-`/` cut.

Build the Pi label from the model's own `name`/`id`: shorten only
path-like values with no whitespace (OpenRouter reports names like
"google/gemini-2.5-flash-lite"), and keep free-text names intact. The
compact trigger now strips only a leading provider namespace.

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

* test(pi): cover model labels through the catalog and drop stale ACP copies

acp-agent.test.ts still imported transformPiModels, which the Pi label
fix removed, so its modelTransformer test and a stale copy of the old
Pi label tests failed. The modelTransformer test now supplies its own
transformer, and the Pi label cases run through fetchCatalog with the
reported model names instead of an exported helper.

Co-authored-by: Rahul Sharma <19687913+rms523@users.noreply.github.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(pi): keep colons inside free-text model names

The vendor-prefix strip cut a free-text Pi name at its first ": ", so
"Qwen3 IQ3_S (tail skip: on, 52/56)" showed as "on, 52/56)". Strip only
when the text before ": " has no parenthesis or comma, which keeps
OpenRouter's "Vendor: Model" names shortened.

Co-authored-by: Rahul Sharma <19687913+rms523@users.noreply.github.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Rahul Sharma <19687913+rms523@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
(cherry picked from commit d15190803a)
2026-11-17 06:27:54 +01:00
Mohamed Boudra c54bc39e79 chore(release): cut 0.16.0 2026-11-16 06:07:10 +01:00
Mohamed Boudra 228e6f75ea docs(changelog): prepare 0.16.0 stable 2026-11-16 05:27:13 +01:00
113 changed files with 685 additions and 5214 deletions
+2 -3
View File
@@ -150,13 +150,12 @@ Users can also detach an existing subagent from the subagents track. Detach is d
`notifyOnFinish` defaults to `true` for agent-scoped creation and prompt follow-ups because most delegated work needs to report back to the creating agent. Set it to `false` for explicit reporting or no completion callback.
Agent-originated messages and automatic notifications share a recipient-daemon delivery module. A queued receipt acknowledges admission before provider dispatch. Idle recipients retain the two-second quiet window. While a recipient has a running or starting turn (including compaction), messages stay queued across quiet windows and are delivered together after that turn settles, including failure or cancellation. A ready batch is released when the daemon observes the recipient settle; the two-second timer also retries it. Agent callers using `steer`, including the default, wait for the turn to end; only explicit `interrupt` replaces a running turn. An explicit interrupt or a command the provider accepts out of band runs before earlier queued messages. Those messages stay queued and are delivered after the running or replacement turn ends. Human prompts dispatch directly with their existing behavior. Conflicting session-mode choices retain separate ordered dispatches.
Agent-originated messages and automatic notifications share a recipient-daemon delivery module. A queued receipt acknowledges admission before provider dispatch, allowing a child to report and finish in the same two-second quiet window. Human prompts dispatch directly. Conflicting explicit interruption or session-mode choices retain separate ordered dispatches.
The pending message window is in memory. Clean shutdown flushes it before closing agents; an abrupt
crash can lose queued prompts. A durable send receipt remains pending until actual dispatch
acknowledgment, so a lost window never becomes a completed receipt. Completion waits cover queued
admission within their original timeout and cancellation scope, and return permission checkpoints
while messages are waiting.
admission within their original timeout and cancellation scope.
Finish notification intent has a separate daemon-owned lifetime. The finish-subscriptions module
persists caller, child, host, and ownership policy through an injectable store; its JSON adapter uses
-10
View File
@@ -590,16 +590,6 @@ bookkeeping may scan opaque row sizes during a deferred write, never during host
before a requested cache row can paint. The row store is not encrypted. A cached timeline can contain
source code, prompts, and tool output; encrypted-at-rest storage is a separate security decision.
### Saved hosts
**AsyncStorage key:** `@paseo:daemon-registry`, an array of host profiles.
Every app build on a device shares this key, including an older build after a downgrade and a newer
one that saves a connection kind this build doesn't know. The key holds every saved host and its
password, so never remove it. Read each host and connection on its own, skip the ones this build
can't read, and write them back on every save. A value that isn't a JSON array is copied to
`@paseo:daemon-registry:unreadable` before the next save overwrites it.
### Draft Store
**AsyncStorage key:** `paseo-drafts` (version 2)
+1 -1
View File
@@ -6,7 +6,7 @@ Do not replace the Linux implementation with `fs.watch({ recursive: true })`. No
Closing an observation must remain safe after its root is renamed or removed. Workspace archive removes owned worktrees while releasing observation references, so teardown cannot assume the watched path still exists.
`unsubscribe()` is an awaited barrier. Once it resolves, no scan, reconciliation, queued event, native handle, or callback may remain. `updateIgnore()` is the equivalent barrier for excluded paths: events queued below a newly excluded root cannot be delivered after it resolves. Treat path disappearance while scanning, attaching, or receiving a watcher error as rename/archive churn. Surface permission and resource errors so WorkspaceGit can enter bounded polling. `subscribe()` accepts an abort signal; aborting it before it resolves stops the startup scan and rejects. WorkspaceGit aborts every subscription that misses its setup deadline, because an abandoned scan otherwise keeps walking the tree. A timed-out directory retries on the recovery ladder (30 seconds doubling to five minutes), and each consecutive timeout keeps doubling the delay up to one hour. Under sustained CPU load the next scan misses the deadline too, and each attempt repeats the full scan. An accepted subscription resets the timeout streak. Degraded polling keeps its own cadence throughout.
`unsubscribe()` is an awaited barrier. Once it resolves, no scan, reconciliation, queued event, native handle, or callback may remain. `updateIgnore()` is the equivalent barrier for excluded paths: events queued below a newly excluded root cannot be delivered after it resolves. Treat path disappearance while scanning, attaching, or receiving a watcher error as rename/archive churn. Surface permission and resource errors so WorkspaceGit can enter bounded polling.
Linux topology repair is trailing-debounced and scoped to the renamed path. A file rename needs one classification stat; a new or moved directory scans only its subtree. Full-tree scans are reserved for startup and ignore-set replacement. A subscription reports changes after `subscribe()` resolves, not the files that already existed. macOS FSEvents can still replay writes made moments before the stream started. Consumers read their initial state after `subscribe()` resolves; WorkspaceGit re-reads its checkout once observation setup completes, because its first refresh runs in parallel with setup. The Linux startup scan therefore emits nothing; only a scoped reconciliation of new topology reports files found before their directory's watcher was installed. Startup creates made every cold diff compute and discard a first revision. Benchmark startup cost with pre-populated trees.
-1
View File
@@ -29,7 +29,6 @@ The worker writes `$PASEO_HOME/terminal-worker/<pid>.json` (owner-only) with its
- Workers never query their own birth time or command line. Readers accept legacy identity fields but ignore them. Daemons through 0.15.1 report new records unreadable and cannot adopt them.
- Windows terminal programs have no recorded birth time and terminal lifecycle operations never launch PowerShell. Linux and macOS retain program birth-time checks through `ps` with `LC_ALL=C`; Linux also walks sessions to find surviving jobs.
- Unix socket paths have a byte budget (103 on macOS, 107 on Linux). Long dev homes use an owner-only fallback under `$TMPDIR/paseo-<uid>/` or `/tmp/paseo-<uid>/`. An existing directory must be a real `0700` directory owned by you; a shared root is never chmodded.
- A home on a filesystem that refuses Unix sockets (AFS, some network mounts) passes those checks and then fails the bind with `EPERM`, `EACCES`, `EOPNOTSUPP` or `ENOTSUP`. The worker moves on to the next directory on those codes only; any other listen error fails the start. The record carries the path the worker bound, so nothing else recomputes it.
- A kill cleanup that cannot confirm every process gone writes `closing-<recordId>.json` beside the worker record. The worker rewrites its own record whenever a terminal starts or exits, so the kill intent has to live in a file it never writes. A closing record is never adopted; the next stop or start retries it.
- An unreadable record of either kind makes `daemon status` and a kill restart fail with its path: a kill cleanup that met it could not check what it names, and leaves nothing else behind. A read that fails with `EPERM`, `EBUSY` or `EACCES` is retried for 250ms first: on Windows, opening a record while the worker renames its new copy over it fails that way for a moment.
+1 -1
View File
@@ -1 +1 @@
sha256-k7+5S/4tyAmHdZmUdhpuZ7GOc7hp9cG8wUBFdJI32ng=
sha256-hN+Klz3jXugHs5MsVzIQIwIa/HGbpdJ04qolKvbsOuk=
@@ -466,12 +466,12 @@ test("downloads a file over direct TCP with its original filename and bytes", as
await gotoWorkspace(page, workspace.workspaceId);
await openFileExplorer(page);
const daemonRequest = page.waitForRequest("**/api/files/download?*");
const downloaded = await downloadFileFromExplorer(page, fileName);
const requestUrl = new URL((await daemonRequest).url());
expect(requestUrl.port).toBe(getE2EDaemonPort());
expect(requestUrl.searchParams.get("token")).toBeTruthy();
expect(new URL(downloaded.url()).protocol).toBe("blob:");
const url = new URL(downloaded.url());
expect(url.protocol).toBe("http:");
expect(url.port).toBe(getE2EDaemonPort());
expect(url.pathname).toBe("/api/files/download");
expect(url.searchParams.get("token")).toBeTruthy();
expect(downloaded.suggestedFilename()).toBe(fileName);
const savedFile = testInfo.outputPath(fileName);
await downloaded.saveAs(savedFile);
@@ -479,45 +479,6 @@ test("downloads a file over direct TCP with its original filename and bytes", as
expect(await readFile(savedFile)).toEqual(source);
});
test("keeps the app open and shows the error when the host rejects a download", async ({
page,
}, testInfo) => {
const fileName = "removed-during-download.bin";
const filePath = path.join(workspace.workspaceDirectory, fileName);
const source = Buffer.from([0, 1, 2, 255]);
await writeFile(filePath, source);
await gotoWorkspace(page, workspace.workspaceId);
await openFileExplorer(page);
const workspaceUrl = page.url();
// The file disappears after the token is issued, so the real daemon answers 404.
await page.route(
"**/api/files/download?*",
async (route) => {
await rm(filePath);
await route.continue();
},
{ times: 1 },
);
await page
.getByTestId("file-explorer-tree-scroll")
.getByText(fileName, { exact: true })
.click({ button: "right" });
await page.getByRole("menuitem", { name: "Download", exact: true }).click();
await expect(
page.getByText("Failed to download file (HTTP 404).", { exact: true }),
).toBeVisible();
expect(page.url()).toBe(workspaceUrl);
await writeFile(filePath, source);
const downloaded = await downloadFileFromExplorer(page, fileName);
const savedFile = testInfo.outputPath(fileName);
await downloaded.saveAs(savedFile);
expect(await readFile(savedFile)).toEqual(source);
expect(page.url()).toBe(workspaceUrl);
});
test("downloads an unsupported binary from its preview with original filename and bytes", async ({
page,
}, testInfo) => {
@@ -2,16 +2,10 @@ import { copyPluginExample } from "../support/helpers/plugin-fixture";
import { expect, test as base, type Page } from "../support/fixtures";
import { gotoAppShell } from "../support/helpers/app";
import { connectNewWorkspaceDaemonClient } from "../support/helpers/new-workspace";
import { waitForSettledPosition } from "../support/helpers/sheet-layout";
async function openExample(page: Page, example: string) {
await page.getByRole("button", { name: `Open ${example}`, exact: true }).click();
const title = page.getByText(`Modal example: ${example}`, { exact: true });
// A compact sheet holds below the viewport and then slides up, so a pointer placed before it
// stops lands on whatever slides under it. The settle check starts once the slide has begun;
// two equal reads during the hold would otherwise count as settled.
await expect(title).toBeInViewport();
await waitForSettledPosition(title);
await expect(page.getByText(`Modal example: ${example}`, { exact: true })).toBeVisible();
}
async function closeExample(page: Page) {
@@ -208,35 +208,6 @@ test.describe("Plugin sidebar items", () => {
});
});
test("a short desktop sidebar keeps workspaces usable while navigation scrolls", async ({
page,
}) => {
await page.setViewportSize({ width: 1280, height: 480 });
await gotoAppShell(page);
await expect(botRow(page, "status")).toBeAttached();
const workspace = visibleTestId(page, `sidebar-workspace-row-${getServerId()}:${workspaceId}`);
await expect(workspace).toBeInViewport({ ratio: 1 });
await expect(botRow(page, "status")).not.toBeInViewport();
await test.step("navigation stays within half the sidebar", async () => {
const nav = await boxOf(visibleTestId(page, "sidebar-nav-scroll"));
expect(nav.height).toBeLessThanOrEqual(480 / 2 + 1);
});
await test.step("scrolling navigation reaches its last row without moving workspaces", async () => {
const before = await boxOf(workspace);
await visibleTestId(page, "sidebar-global-new-workspace").hover();
await page.mouse.wheel(0, 800);
await expect(botRow(page, "status")).toBeInViewport({ ratio: 1 });
await expect(workspace).toBeInViewport({ ratio: 1 });
expect((await boxOf(workspace)).y).toBe(before.y);
await qaScreenshot(page, "desktop-short-sidebar-nav-scrolled");
await botRow(page, "status").click();
await expect(page.getByText("Bot status details", { exact: true })).toBeVisible();
await page.getByRole("button", { name: "Close bot status", exact: true }).click();
});
});
test("a restored plugin screen waits for its catalog before rendering", async ({ page }) => {
await page.setViewportSize(WIDE);
await gotoWorkspace(page, workspaceId);
@@ -1,106 +0,0 @@
import { expect, type Page } from "@playwright/test";
import { test } from "../support/fixtures";
import { gotoAppShell, openSettings } from "../support/helpers/app";
import { renameHostFromSettings } from "../support/helpers/hosts";
import { getServerId } from "../support/helpers/server-id";
import { openHostSection, selectSettingsHost } from "../support/helpers/settings";
const REGISTRY_KEY = "@paseo:daemon-registry";
const SEED_NONCE_KEY = "@paseo:e2e-seed-nonce";
const DISABLE_DEFAULT_SEED_ONCE_KEY = "@paseo:e2e-disable-default-seed-once";
// What a build with a connection kind this one doesn't know leaves in the registry: an extra
// connection on a host this build can reach, and a host reached only through it.
const UNKNOWN_CONNECTION = { id: "future:garage", type: "futureKind", address: "garage" };
const UNKNOWN_HOST = {
serverId: "srv_e2e_unknown_connection_host",
label: "Unknown connection host",
connections: [{ id: "future:roof", type: "futureKind", address: "roof" }],
preferredConnectionId: "future:roof",
};
const OFFLINE_HOST = {
serverId: "srv_e2e_saved_offline_host",
label: "Saved offline host",
password: "e2e-fake-password",
connections: [{ id: "direct:127.0.0.1:59999", type: "directTcp", endpoint: "127.0.0.1:59999" }],
preferredConnectionId: "direct:127.0.0.1:59999",
};
interface StoredHost {
serverId: string;
label?: string;
password?: string;
connections: unknown[];
}
async function addUnreadableEntriesAndReload(page: Page): Promise<void> {
await page.evaluate(
({ keys, primaryServerId, unknownConnection, offlineHost, unknownHost }) => {
const nonce = localStorage.getItem(keys.nonce);
if (!nonce) {
throw new Error("Expected the e2e seed nonce before overriding the host registry.");
}
const registry: StoredHost[] = JSON.parse(localStorage.getItem(keys.registry) ?? "[]");
registry
.find((host) => host.serverId === primaryServerId)
?.connections.push(unknownConnection);
registry.push(offlineHost, unknownHost);
localStorage.setItem(keys.registry, JSON.stringify(registry));
localStorage.setItem(keys.disableSeedOnce, nonce);
},
{
keys: {
registry: REGISTRY_KEY,
nonce: SEED_NONCE_KEY,
disableSeedOnce: DISABLE_DEFAULT_SEED_ONCE_KEY,
},
primaryServerId: getServerId(),
unknownConnection: UNKNOWN_CONNECTION,
offlineHost: OFFLINE_HOST,
unknownHost: UNKNOWN_HOST,
},
);
await page.reload();
}
async function readStoredRegistry(page: Page): Promise<StoredHost[] | null> {
return page.evaluate((key) => JSON.parse(localStorage.getItem(key) ?? "null"), REGISTRY_KEY);
}
async function readStoredHost(page: Page, serverId: string): Promise<StoredHost | undefined> {
return (await readStoredRegistry(page))?.find((host) => host.serverId === serverId);
}
test("saved hosts survive a registry entry this build can't read, and saving keeps it", async ({
page,
}) => {
await gotoAppShell(page);
await addUnreadableEntriesAndReload(page);
await test.step("both readable hosts are listed", async () => {
await page.getByTestId("sidebar-hosts-trigger").click();
await expect(page.getByTestId(`sidebar-host-row-${getServerId()}`)).toBeVisible();
await expect(page.getByTestId(`sidebar-host-row-${OFFLINE_HOST.serverId}`)).toBeVisible();
await expect(page.getByTestId(`sidebar-host-row-${UNKNOWN_HOST.serverId}`)).toHaveCount(0);
await page.keyboard.press("Escape");
});
await test.step("renaming a host keeps its password and the entries it can't read", async () => {
await openSettings(page);
await selectSettingsHost(page, OFFLINE_HOST.serverId);
await openHostSection(page, OFFLINE_HOST.serverId, "host");
await renameHostFromSettings(page, "Renamed offline host");
await expect
.poll(() => readStoredHost(page, OFFLINE_HOST.serverId))
.toMatchObject({ label: "Renamed offline host", password: OFFLINE_HOST.password });
const stored = await readStoredRegistry(page);
expect(stored?.map((host) => host.serverId)).toEqual([
getServerId(),
OFFLINE_HOST.serverId,
UNKNOWN_HOST.serverId,
]);
expect(stored?.[0]?.connections).toContainEqual(UNKNOWN_CONNECTION);
expect(stored?.[2]).toEqual(UNKNOWN_HOST);
});
});
@@ -110,7 +110,6 @@ test.describe("Sidebar items in Appearance settings", () => {
await test.step("the sidebar starts in the default order", async () => {
await expectSidebarOrder(page, ["new-workspace", "history", "search", "schedules"]);
await expect(page.locator('[data-testid="sidebar-nav-separator"]:visible')).toHaveCount(1);
});
await test.step("the Sidebar section lists every item in the same order", async () => {
@@ -196,9 +195,6 @@ test.describe("Sidebar items in Appearance settings", () => {
await expectSidebarItemHidden(page, "history");
await expectSidebarItemHidden(page, "search");
await expectSidebarItemHidden(page, "schedules");
// Nothing is left above the Workspaces section: no drag strip, no empty divider.
await expect(page.locator('[data-testid="sidebar-nav-drag-strip"]:visible')).toHaveCount(0);
await expect(page.locator('[data-testid="sidebar-nav-separator"]:visible')).toHaveCount(0);
});
});
@@ -73,36 +73,35 @@ function labelRow(page: import("@playwright/test").Page, name: string) {
return page.getByTestId(`workspace-label-picker-row-${name}`);
}
async function box(locator: import("@playwright/test").Locator) {
const measured = await locator.boundingBox();
if (!measured) throw new Error("expected a visible element to measure");
return measured;
}
async function size(locator: import("@playwright/test").Locator) {
const { width, height } = await settled(locator);
await settled(locator);
const { width, height } = await box(locator);
return { width, height };
}
/**
* Waits until an element is on screen and stops moving, and returns where it settled.
* Waits until an element stops moving.
*
* The flyout scales in and the sidebar behind it re-lays out as the filter changes, so a rail
* measured mid-animation is not a rail — and a measurement built from two `boundingBox()` calls
* would take its two halves from two different frames. A row that has not been laid out yet has
* no box at all; that is not settled either, so the poll keeps waiting instead of failing.
* would take its two halves from two different frames.
*/
async function settled(locator: import("@playwright/test").Locator) {
const last: { box: Awaited<ReturnType<typeof locator.boundingBox>>; key: string | null } = {
box: null,
key: null,
};
let previous = "";
await expect
.poll(async () => {
const current = await locator.boundingBox();
const key = current ? JSON.stringify(current) : null;
const stable = key !== null && key === last.key;
last.box = current;
last.key = key;
const current = JSON.stringify(await box(locator));
const stable = current === previous;
previous = current;
return stable;
})
.toBe(true);
if (!last.box) throw new Error("a settled element has a box");
return last.box;
}
async function expectAssigned(
@@ -170,11 +170,6 @@ export interface ModelTriggerLabelState {
modelShown: boolean;
modelText: string;
modelTruncated: boolean;
/**
* The model label shows what its box fits right now: the full text when it fits, otherwise a
* truncation that fits. False while the control has yet to catch up with a reflow.
*/
modelFitsBox: boolean;
}
declare global {
@@ -199,18 +194,12 @@ function readModelTriggerLabelStateInPage(): ModelTriggerLabelState {
};
const modelShown = model !== undefined && shown(model);
const modelText = model?.textContent ?? "";
const overflows = (node: Element) => node.scrollWidth > node.clientWidth;
const modelOverflows = model !== undefined && overflows(model);
// The label's box is sized by an invisible copy of the full text, its first child, so the box
// follows a reflow at once while the shown text waits for the control's next layout event.
const fullTextSizer = model?.parentElement?.parentElement?.firstElementChild;
const fullTextFits = fullTextSizer ? !overflows(fullTextSizer) : true;
return {
modelShown,
modelText,
thinkingShown: modelShown && thinking !== undefined,
modelTruncated: modelText.endsWith("…") || modelOverflows,
modelFitsBox: !modelOverflows && modelText.endsWith("…") !== fullTextFits,
modelTruncated:
model !== undefined && (modelText.endsWith("…") || model.scrollWidth > model.clientWidth),
};
}
@@ -228,26 +217,13 @@ export async function recordModelTriggerFramesFromLoad(page: Page): Promise<void
})()`);
}
/**
* The model control's labels once it has caught up with its width: two reads 100ms apart agree
* and the model label shows what its box fits. A resize reflows the page at once, but the control
* chooses its labels again only when its layout events arrive, and on a slow runner that takes
* longer than 100ms. Until then the label can be clipped by the browser beside the thinking
* label, or truncated in a box that has since widened.
*/
/** The model control's labels once two reads 100ms apart agree. */
export async function readSettledModelTriggerLabels(page: Page): Promise<ModelTriggerLabelState> {
const deadline = Date.now() + 10_000;
let previous = await page.evaluate(readModelTriggerLabelStateInPage);
for (;;) {
await page.waitForTimeout(100);
const next = await page.evaluate(readModelTriggerLabelStateInPage);
const agrees = JSON.stringify(next) === JSON.stringify(previous);
if (agrees && next.modelFitsBox) return next;
if (Date.now() > deadline) {
throw new Error(
`the model control never settled on a label that fits its box: ${JSON.stringify(next)}`,
);
}
if (JSON.stringify(next) === JSON.stringify(previous)) return next;
previous = next;
}
}
@@ -97,15 +97,18 @@ export class ImportSessionFlow {
await target.scrollIntoViewIfNeeded();
await expect(target).toBeInViewport();
}
/**
* Scrolls the virtualized list, the only one that leaves rows unmounted. A row handle is no way
* in: the list unmounts rows as it scrolls, and a detached row has no scroller above it.
*/
private async scrollList(forward: boolean) {
await this.page.getByTestId("import-session-list").evaluate((list, advance) => {
list.scrollTop = advance ? list.scrollTop + list.clientHeight * 0.8 : 0;
list.dispatchEvent(new Event("scroll"));
}, forward);
await this.page
.locator('[data-testid^="import-session-session-"]')
.first()
.evaluate((row, advance) => {
let element = row.parentElement;
while (element && !["auto", "scroll"].includes(getComputedStyle(element).overflowY))
element = element.parentElement;
if (!element) throw new Error("Import list has no scroll owner");
element.scrollTop = advance ? element.scrollTop + element.clientHeight * 0.8 : 0;
element.dispatchEvent(new Event("scroll"));
}, forward);
}
async search(query: string) {
await this.page.getByTestId("import-session-search").fill(query);
@@ -117,18 +120,11 @@ export class ImportSessionFlow {
await this.page.getByTestId("import-session-search").fill("");
await expect(this.page.getByTestId("import-session-load-more")).toBeVisible();
}
/** Load more keeps the reader down the list instead of sending them back to the top. */
async loadMore() {
const loadMore = this.page.getByTestId("import-session-load-more");
const topRow = this.page.getByTestId((await this.rowIds())[0]!);
await expect(topRow).toBeInViewport();
await loadMore.click();
// The next page is the last and short, so the button leaves once it lands.
await expect(loadMore).toHaveCount(0);
await expect(this.page.getByText("Loading sessions...", { exact: true })).toHaveCount(0);
await expect(topRow).not.toBeInViewport();
await this.page.getByTestId("import-session-load-more").click();
await this.revealSession("fixture-root-20");
await expect(this.page.getByText("Root session 20", { exact: true })).toBeInViewport();
await expect(this.page.getByTestId("import-session-load-more")).toHaveCount(0);
}
async retryProvider(provider: string, label: string) {
await this.expectProviderError(label);
@@ -6,7 +6,7 @@ import {
type ChildProcess,
type SpawnOptions,
} from "node:child_process";
import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
import { mkdtemp, rm, writeFile } from "node:fs/promises";
import net from "node:net";
import { tmpdir } from "node:os";
import path from "node:path";
@@ -59,17 +59,7 @@ export async function getAvailableHostDaemonPort(): Promise<number> {
return port;
}
/**
* Resolves once this daemon answers on its port. An open TCP port is not
* enough: the port is released before the daemon binds it, and whatever takes
* it in between also accepts connections while the daemon exits with
* EADDRINUSE. Only the daemon's own status reports its server id.
*/
async function waitForServer(
port: number,
child: ChildProcess,
identity: { serverId: string; paseoHome: string },
): Promise<void> {
async function waitForServer(port: number, child: ChildProcess): Promise<void> {
const deadline = Date.now() + 90_000;
let lastError: unknown = null;
@@ -80,13 +70,22 @@ async function waitForServer(
);
}
try {
const serverId = await readServerId(port, identity.paseoHome);
if (serverId === identity.serverId) return;
lastError = new Error(`Port ${port} is served by ${serverId}, not ${identity.serverId}`);
await new Promise<void>((resolve, reject) => {
const socket = net.connect(port, "127.0.0.1", () => {
socket.end();
resolve();
});
socket.setTimeout(1_000, () => {
socket.destroy();
reject(new Error(`Connection timed out to isolated daemon port ${port}`));
});
socket.on("error", reject);
});
return;
} catch (error) {
lastError = error;
await new Promise((resolve) => setTimeout(resolve, 100));
}
await new Promise((resolve) => setTimeout(resolve, 100));
}
throw new Error(
@@ -96,25 +95,6 @@ async function waitForServer(
);
}
/**
* Reads the server id from the daemon's status route. The route needs a bearer
* on a password-protected daemon; the daemon accepts the local credential it
* writes into its home before listening, as the CLI does for local status.
*/
async function readServerId(port: number, paseoHome: string): Promise<string> {
const localCredential = await readFile(path.join(paseoHome, "local-credential"), "utf8").then(
(token) => token.trim(),
() => null,
);
const response = await fetch(`http://127.0.0.1:${port}/api/status`, {
headers: localCredential ? { authorization: `Bearer ${localCredential}` } : {},
signal: AbortSignal.timeout(1_000),
});
if (!response.ok) throw new Error(`Status request to port ${port} returned ${response.status}`);
const status = (await response.json()) as { serverId?: unknown };
return String(status.serverId);
}
function withMutableRelay(
config: NonNullable<IsolatedHostDaemonOptions["config"]>,
relay: NonNullable<IsolatedHostDaemonOptions["mutableRelay"]>,
@@ -141,7 +121,7 @@ export async function startIsolatedHostDaemon(
serverId: string,
options: IsolatedHostDaemonOptions = {},
): Promise<IsolatedHostDaemon> {
let port = await getAvailableHostDaemonPort();
const port = await getAvailableHostDaemonPort();
const metroPort = process.env.E2E_METRO_PORT;
if (!metroPort) throw new Error("E2E_METRO_PORT is required to start an isolated host daemon");
@@ -241,7 +221,7 @@ export async function startIsolatedHostDaemon(
});
try {
await waitForServer(port, spawned, { serverId, paseoHome });
await waitForServer(port, spawned);
return spawned;
} catch (error) {
throw new Error(
@@ -251,25 +231,8 @@ export async function startIsolatedHostDaemon(
}
};
// The reserved port is released before the daemon binds it, so another
// process can take it in between. Only the first start picks a new port:
// restart() keeps the endpoint the app already knows.
const startOnFreePort = async (): Promise<void> => {
for (let attempt = 1; ; attempt += 1) {
try {
await spawnDaemon();
return;
} catch (error) {
const lostPort = error instanceof Error && error.message.includes("EADDRINUSE");
if (!lostPort || attempt === 3) throw error;
await stopDaemon();
port = await getAvailableHostDaemonPort();
}
}
};
try {
await startOnFreePort();
await spawnDaemon();
} catch (error) {
await stopDaemon();
if (!options.preserveHome) {
@@ -17,13 +17,6 @@ import { isNative } from "@/constants/platform";
* On macOS, Electron handles edge resize natively.
*/
/**
* Marks a scroll viewport as window content: it and its descendants emit no window
* regions, because Electron does not clip app-region rects to scroll viewports.
* See the `[data-window-content]` rule in public/index.html.
*/
export const WINDOW_CONTENT_DATASET = { "window-content": "" };
export const titlebarDragSurfaceStyle: React.CSSProperties = {
cursor: "default",
// @ts-expect-error — WebkitAppRegion is not in CSSProperties
@@ -17,11 +17,6 @@ export function nextPageLimit(limit: number): number {
return PAGE_LIMITS.find((candidate) => candidate > limit) ?? limit;
}
/** The page Load more grew this limit from, or null for the first page. */
export function previousPageLimit(limit: number): number | null {
return PAGE_LIMITS.findLast((candidate) => candidate < limit) ?? null;
}
export function requiresImportSessionsHostUpgrade(input: {
supportsSnapshot: boolean;
workspaceId?: string | null;
@@ -1172,44 +1172,6 @@ describe("ImportSessionSheet", () => {
});
});
it("keeps the loaded list in place while Load more fetches the next page", async () => {
let releaseNextPage: () => void = () => undefined;
const nextPage = new Promise<void>((resolve) => {
releaseNextPage = resolve;
});
const fetchRecentProviderSessions = vi.fn(async (options: { limit?: number } | undefined) => {
if (options?.limit !== 15) await nextPage;
return {
requestId: "recent-provider-sessions",
entries: createPageOfEntries(options?.limit === 15 ? 15 : 20),
};
});
renderSheet(createRecentSessionsClient(fetchRecentProviderSessions, vi.fn()), {
cwd: null,
snapshot: { supportsSnapshot: true, entries: [createSnapshotEntry("claude")] },
});
fireEvent.click(await screen.findByTestId("import-session-load-more"));
// The list the user scrolled to Load more is the one they keep: replacing it would drop
// them back at the top, behind a loading state, until the larger page lands.
const list = screen.getByTestId("import-session-list");
await waitFor(() => {
expect(fetchRecentProviderSessions).toHaveBeenCalledWith({
providers: ["claude"],
limit: 45,
});
});
expect(screen.getByTestId("import-session-list")).toBe(list);
expect(screen.queryByText("Loading sessions...")).toBeNull();
releaseNextPage();
await waitFor(() => {
expect(screen.queryByTestId("import-session-load-more")).toBeNull();
});
expect(screen.getByTestId("import-session-list")).toBe(list);
});
it("stops the refresh spinner and retries only the failed provider", async () => {
const fetchRecentProviderSessions = vi.fn(
async (options: { providers?: string[] } | undefined) => {
@@ -1,6 +1,6 @@
import React, { type ReactNode, useCallback, useEffect, useMemo, useRef, useState } from "react";
import { Pressable, type PressableStateCallbackType, Text, View } from "react-native";
import { useMutation, useQueries, useQueryClient, type QueryClient } from "@tanstack/react-query";
import { keepPreviousData, useMutation, useQueries, useQueryClient } from "@tanstack/react-query";
import { useTranslation } from "react-i18next";
import type {
DaemonClient,
@@ -40,7 +40,6 @@ import {
resolveDirectoryLabel,
nextPageLimit,
PER_PROVIDER_LIMIT,
previousPageLimit,
type ProviderErrorRow,
resolveImportTarget,
resolveProvidersToFetch,
@@ -101,12 +100,11 @@ interface SessionsQueryConfig {
// Query's default retry would keep the header spinner turning and pile up
// in-flight daemon requests behind a dead provider (#2512).
retry: false;
placeholderData: () => RecentSessionsResponse | undefined;
placeholderData: typeof keepPreviousData;
queryFn: () => Promise<RecentSessionsResponse>;
}
function buildSessionsQueriesConfig(args: {
queryClient: QueryClient;
providersToFetch: AgentProvider[] | null;
visible: boolean;
client: RecentProviderSessionsClient | null;
@@ -115,24 +113,14 @@ function buildSessionsQueriesConfig(args: {
limit: number;
hostDisconnectedMessage?: string;
}): SessionsQueryConfig[] {
const { queryClient, providersToFetch, visible, client, cwd, query, limit } = args;
const { hostDisconnectedMessage } = args;
const { providersToFetch, visible, client, cwd, query, limit, hostDisconnectedMessage } = args;
if (providersToFetch === null) return [];
const enabled = visible && Boolean(client);
const previousLimit = previousPageLimit(limit);
return providersToFetch.map((provider) => ({
queryKey: buildSessionsQueryKey({ cwd, query, limit, provider }),
enabled,
retry: false as const,
// While Load more fetches the next page, keep showing the page it grew from. React Query's
// keepPreviousData cannot do this here: useQueries gives a changed key a new observer, which
// has no previous data, so the rows would vanish and the list would remount at the top.
placeholderData: () =>
previousLimit === null
? undefined
: queryClient.getQueryData<RecentSessionsResponse>(
buildSessionsQueryKey({ cwd, query, limit: previousLimit, provider }),
),
placeholderData: keepPreviousData,
queryFn: async () => {
if (!client) {
throw new Error(hostDisconnectedMessage ?? i18n.t("workspace.terminal.hostDisconnected"));
@@ -534,7 +522,6 @@ export function ImportSessionSheet({
const queriesConfig = useMemo(
() =>
buildSessionsQueriesConfig({
queryClient,
providersToFetch,
visible,
client,
@@ -543,7 +530,7 @@ export function ImportSessionSheet({
limit: pageLimit,
hostDisconnectedMessage: t("workspace.terminal.hostDisconnected"),
}),
[queryClient, providersToFetch, visible, client, scopeCwd, query, pageLimit, t],
[providersToFetch, visible, client, scopeCwd, query, pageLimit, t],
);
const queries = useQueries({ queries: queriesConfig });
+43 -89
View File
@@ -9,16 +9,7 @@ import {
type LucideIcon,
} from "lucide-react-native";
import { useTranslation } from "react-i18next";
import {
memo,
useCallback,
useEffect,
useMemo,
useRef,
useState,
type ReactNode,
type RefObject,
} from "react";
import { memo, useCallback, useEffect, useMemo, useRef, useState, type RefObject } from "react";
import {
Pressable,
ScrollView,
@@ -28,19 +19,12 @@ import {
View,
type LayoutChangeEvent,
} from "react-native";
import {
Gesture,
type GestureType,
ScrollView as GHScrollView,
} from "react-native-gesture-handler";
import { Gesture, ScrollView as GHScrollView } from "react-native-gesture-handler";
import Animated, { runOnJS, useAnimatedStyle, useSharedValue } from "react-native-reanimated";
import { scheduleOnRN } from "react-native-worklets";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { StyleSheet, useUnistyles } from "react-native-unistyles";
import {
TitlebarDragRegion,
WINDOW_CONTENT_DATASET,
} from "@/components/desktop/titlebar-drag-region";
import { TitlebarDragRegion } from "@/components/desktop/titlebar-drag-region";
import { SidebarCloseButton } from "@/components/headers/sidebar-close-button";
import {
resolveDesktopSidebarInsetLeft,
@@ -55,7 +39,7 @@ import { HostPicker } from "@/components/hosts/host-picker";
import { SidebarDisplayPreferencesMenu } from "@/components/sidebar/display-preferences/menu";
import { SidebarSeparator } from "@/components/sidebar/sidebar-separator";
import { SidebarToastRegion } from "@/components/sidebar/sidebar-toast-region";
import { SidebarNavRows, useVisibleSidebarNavItems } from "@/components/sidebar/sidebar-nav-rows";
import { SidebarNavRows } from "@/components/sidebar/sidebar-nav-rows";
import { SidebarFooterIconHighlight } from "@/components/sidebar/sidebar-footer-icon-highlight";
import { SidebarHelpMenu } from "@/components/sidebar/sidebar-help-menu";
import { SidebarFooterOverflowMenu } from "@/components/sidebar/sidebar-footer-overflow-menu";
@@ -638,7 +622,29 @@ function MobileSidebar({
>
<View style={styles.sidebarContent} pointerEvents="auto">
<WindowChromeSafeArea placement="below" />
<SidebarNavScroll closeGestureRef={closeGestureRef}>{navRows}</SidebarNavScroll>
{platformIsNative ? (
<GHScrollView
// Same contract as the workspace list: vertical drags scroll the nav
// block, a clear horizontal intent still activates the close pan.
simultaneousHandlers={closeGestureRef}
style={styles.mobileNavScroll}
showsVerticalScrollIndicator={false}
alwaysBounceVertical={false}
testID="sidebar-nav-scroll"
>
{navRows}
</GHScrollView>
) : (
<ScrollView
style={styles.mobileNavScroll}
showsVerticalScrollIndicator={false}
alwaysBounceVertical={false}
testID="sidebar-nav-scroll"
>
{navRows}
</ScrollView>
)}
<SidebarSeparator />
<SidebarViewSlot dismiss={handleWorkspacePress}>
<SidebarToastRegion active={active}>
@@ -683,47 +689,6 @@ function MobileSidebar({
);
}
interface SidebarNavScrollProps {
closeGestureRef: RefObject<GestureType | undefined>;
/** Web only: the viewport emits no window regions (see WINDOW_CONTENT_DATASET). */
windowContent?: boolean;
children: ReactNode;
}
// The capped, scrolling nav block shared by the mobile and desktop sidebars, with the
// divider below it. The divider is a sibling because Unistyles does not patch the
// gesture-handler ScrollView.
function SidebarNavScroll({ closeGestureRef, windowContent, children }: SidebarNavScrollProps) {
return (
<>
{platformIsNative ? (
<GHScrollView
// Same contract as the workspace list: vertical drags scroll the nav
// block, a clear horizontal intent still activates the close pan.
simultaneousHandlers={closeGestureRef}
style={styles.navScroll}
showsVerticalScrollIndicator={false}
alwaysBounceVertical={false}
testID="sidebar-nav-scroll"
>
{children}
</GHScrollView>
) : (
<ScrollView
dataSet={windowContent ? WINDOW_CONTENT_DATASET : undefined}
style={styles.navScroll}
showsVerticalScrollIndicator={false}
alwaysBounceVertical={false}
testID="sidebar-nav-scroll"
>
{children}
</ScrollView>
)}
<SidebarSeparator testID="sidebar-nav-separator" />
</>
);
}
function DesktopSidebar({
theme,
workspaceGroups,
@@ -844,14 +809,12 @@ function DesktopSidebar({
],
[insetsTop, insets.bottom, insets.left, overlay, divisionLayout],
);
// Below the window controls' row, or in the top band's place, the first row starts flush.
const inTopBand = useTopBand() !== null;
// Windows and Linux draw their window controls top-right, so the sidebar has no chrome
// row there. The strip above the scrolling rows is then its window drag surface.
const showsChromeRow = ownsTopLeft || Boolean(DEV_BUILD_LABEL);
// With every top item hidden the sidebar starts at the Workspaces section, as before the
// nav scroller existed: no strip above it and no divider below it.
const hasNavRows = useVisibleSidebarNavItems().length > 0;
const showsDragStrip = hasNavRows && !showsChromeRow && !inTopBand;
const sidebarHeaderGroupStyle = useMemo(
() => [styles.sidebarHeaderGroup, (ownsTopLeft || inTopBand) && styles.sidebarHeaderGroupFlush],
[ownsTopLeft, inTopBand],
);
return (
<MobilePanelOverlay
panel="agent-list"
@@ -862,7 +825,7 @@ function DesktopSidebar({
<Animated.View style={desktopSidebarStyle}>
<View style={desktopSidebarBorderStyle}>
<View style={styles.sidebarDragArea}>
{showsChromeRow ? (
{ownsTopLeft || DEV_BUILD_LABEL ? (
<View style={styles.desktopChromeRow}>
<TitlebarDragRegion />
{DEV_BUILD_LABEL ? (
@@ -879,21 +842,11 @@ function DesktopSidebar({
</View>
) : null}
</View>
) : null}
{showsDragStrip ? (
<View style={styles.desktopDragStrip} testID="sidebar-nav-drag-strip">
<TitlebarDragRegion />
</View>
) : null}
) : (
<TitlebarDragRegion />
)}
<SidebarNavRows style={sidebarHeaderGroupStyle} onBeforeNavigate={closeSidebar} />
</View>
{/* The drag overlay stays above this viewport: Electron does not clip
app-region rects to scroll viewports, so a scrolled-out row would
still claim its no-drag rect. */}
{hasNavRows ? (
<SidebarNavScroll closeGestureRef={closeGestureRef} windowContent>
<SidebarNavRows style={styles.sidebarHeaderGroup} onBeforeNavigate={closeSidebar} />
</SidebarNavScroll>
) : null}
<SidebarViewSlot dismiss={closeSidebar}>
<SidebarToastRegion active={active}>
@@ -982,18 +935,19 @@ const staticStyles = RNStyleSheet.create({
});
const styles = StyleSheet.create((theme) => ({
// The rows start flush: the chrome row, drag strip, or top band above them gives the inset.
sidebarHeaderGroup: {
paddingTop: theme.spacing[2],
gap: 2,
paddingBottom: theme.spacing[1.5],
borderBottomWidth: 1,
borderBottomColor: theme.colors.border,
},
desktopDragStrip: {
position: "relative",
height: theme.spacing[2],
sidebarHeaderGroupFlush: {
paddingTop: 0,
},
// The nav block caps at half the sidebar; a long item list scrolls inside the
// cap instead of crowding the workspace list off a short screen.
navScroll: {
mobileNavScroll: {
flexGrow: 0,
flexShrink: 1,
maxHeight: "50%",
@@ -35,19 +35,14 @@ interface SidebarNavRowsProps extends SidebarNavRowProps {
firstRowTrailing?: ReactNode;
}
/** The top-level items the user keeps visible, in display order. */
export function useVisibleSidebarNavItems() {
const { items } = useSidebarNavItems("header");
return useMemo(() => items.filter((item) => item.visible), [items]);
}
/**
* Top-level sidebar navigation, ordered and filtered by the user's
* `sidebarNavItems` preference. Renders nothing — not even the bordered group
* wrapper — when every item is hidden and there is no `firstRowTrailing`.
*/
export function SidebarNavRows({ style, onBeforeNavigate, firstRowTrailing }: SidebarNavRowsProps) {
const visibleItems = useVisibleSidebarNavItems();
const { items } = useSidebarNavItems("header");
const visibleItems = useMemo(() => items.filter((item) => item.visible), [items]);
const groupRef = useRef<View | null>(null);
if (visibleItems.length === 0 && !firstRowTrailing) return null;
-1
View File
@@ -2017,7 +2017,6 @@ export const ar: TranslationResources = {
hostUnavailable: "مضيف التنزيل غير متاح.",
cancelled: "تم إلغاء التنزيل.",
failed: "فشل تنزيل الملف.",
httpFailed: "فشل تنزيل الملف (HTTP {{status}}).",
shareFile: "مشاركة الملف",
shareFileNamed: "مشاركة{{fileName}}",
},
-1
View File
@@ -2045,7 +2045,6 @@ export const en = {
hostUnavailable: "Download host is unavailable.",
cancelled: "Download was cancelled.",
failed: "Failed to download file.",
httpFailed: "Failed to download file (HTTP {{status}}).",
shareFile: "Share file",
shareFileNamed: "Share {{fileName}}",
},
-1
View File
@@ -2066,7 +2066,6 @@ export const es: TranslationResources = {
hostUnavailable: "El host de descarga no está disponible.",
cancelled: "La descarga fue cancelada.",
failed: "No se pudo descargar el archivo.",
httpFailed: "No se pudo descargar el archivo (HTTP {{status}}).",
shareFile: "compartir archivo",
shareFileNamed: "Compartir{{fileName}}",
},
-1
View File
@@ -2065,7 +2065,6 @@ export const fr: TranslationResources = {
hostUnavailable: "L’hôte de téléchargement est indisponible.",
cancelled: "Téléchargement annulé.",
failed: "Impossible de télécharger le fichier.",
httpFailed: "Impossible de télécharger le fichier (HTTP {{status}}).",
shareFile: "Partager le fichier",
shareFileNamed: "Partager {{fileName}}",
},
-1
View File
@@ -2038,7 +2038,6 @@ export const ja: TranslationResources = {
hostUnavailable: "ダウンロードホストが利用できません。",
cancelled: "ダウンロードがキャンセルされました。",
failed: "ファイルのダウンロードに失敗しました。",
httpFailed: "ファイルのダウンロードに失敗しました (HTTP {{status}}).",
shareFile: "ファイルを共有",
shareFileNamed: "{{fileName}}を共有",
},
-1
View File
@@ -2028,7 +2028,6 @@ export const ko: TranslationResources = {
hostUnavailable: "다운로드 호스트를 사용할 수 없습니다.",
cancelled: "다운로드가 취소되었습니다.",
failed: "파일을 다운로드하지 못했습니다.",
httpFailed: "파일을 다운로드하지 못했습니다 (HTTP {{status}}).",
shareFile: "파일 공유",
shareFileNamed: "{{fileName}} 공유",
},
-1
View File
@@ -2051,7 +2051,6 @@ export const ptBR: TranslationResources = {
hostUnavailable: "Host de download indisponível.",
cancelled: "Download cancelado.",
failed: "Falha ao baixar arquivo.",
httpFailed: "Falha ao baixar arquivo (HTTP {{status}}).",
shareFile: "Compartilhar arquivo",
shareFileNamed: "Compartilhar {{fileName}}",
},
-1
View File
@@ -2051,7 +2051,6 @@ export const ru: TranslationResources = {
hostUnavailable: "Хост загрузки недоступен.",
cancelled: "Загрузка отменена.",
failed: "Не удалось загрузить файл.",
httpFailed: "Не удалось загрузить файл (HTTP {{status}}).",
shareFile: "Поделиться файлом",
shareFileNamed: "Поделиться {{fileName}}",
},
-1
View File
@@ -1994,7 +1994,6 @@ export const zhCN: TranslationResources = {
hostUnavailable: "下载 Host 不可用。",
cancelled: "下载已取消。",
failed: "下载文件失败。",
httpFailed: "下载文件失败 (HTTP {{status}}).",
shareFile: "共享文件",
shareFileNamed: "共享 {{fileName}}",
},
@@ -2256,59 +2256,6 @@ describe("HostRuntimeController", () => {
});
});
const REGISTRY_KEY = "@paseo:daemon-registry";
const futureConnection = { id: "future:1", type: "futureKind", address: "future.example.com" };
const directA: HostConnection = {
id: "direct:lan-a:6767",
type: "directTcp",
endpoint: "lan-a:6767",
};
const directB: HostConnection = {
id: "direct:lan-b:6767",
type: "directTcp",
endpoint: "lan-b:6767",
};
// What a build with a connection kind this one doesn't know leaves behind: an extra connection
// on a host this build can reach, and a host reached only through it.
const storedWithUnreadableEntries = [
{
...makeHost({ serverId: "srv_a", password: "secret-a" }),
connections: [futureConnection, directA],
},
makeHost({ serverId: "srv_b", password: "secret-b", connections: [directB] }),
{ serverId: "srv_future", label: "future host", connections: [futureConnection] },
];
async function bootWithRegistry(registry: string): Promise<{
store: HostRuntimeStore;
storage: HostRuntimeStorage;
}> {
const storage = createMemoryHostRuntimeStorage({
[REGISTRY_KEY]: registry,
"@paseo:e2e": "1",
});
const store = new HostRuntimeStore({
storage,
deps: {
createClient: () => new FakeDaemonClient() as unknown as DaemonClient,
connectToDaemon: async ({ host }) => ({
client: makeConnectedProbeClient(5) as unknown as DaemonClient,
serverId: host.serverId,
hostname: host.label ?? null,
}),
getClientId: async () => "cid_test_runtime",
},
revokePushNotifications: async () => undefined,
});
await store.boot();
return { store, storage };
}
async function readRegistry(storage: HostRuntimeStorage): Promise<unknown> {
const raw = await storage.getItem(REGISTRY_KEY);
return raw === null ? null : JSON.parse(raw);
}
describe("HostRuntimeStore", () => {
function gatewayRecoveryFixture() {
const parent = new FakeDaemonClient();
@@ -2739,98 +2686,6 @@ describe("HostRuntimeStore", () => {
session.clearSession(host.serverId);
});
it("keeps readable hosts when the registry holds entries this build can't read", async () => {
const { store, storage } = await bootWithRegistry(JSON.stringify(storedWithUnreadableEntries));
expect(store.getHosts().map((host) => [host.serverId, host.password])).toEqual([
["srv_a", "secret-a"],
["srv_b", "secret-b"],
]);
expect(store.getHosts()[0]?.connections.map((connection) => connection.id)).toEqual([
directA.id,
]);
expect(await readRegistry(storage)).toEqual(storedWithUnreadableEntries);
store.syncHosts([]);
});
it("keeps the entries it can't read when it saves the registry", async () => {
const { store, storage } = await bootWithRegistry(JSON.stringify(storedWithUnreadableEntries));
await store.renameHost("srv_b", "renamed");
expect(await readRegistry(storage)).toMatchObject([
{
serverId: "srv_a",
password: "secret-a",
connections: [{ id: directA.id }, futureConnection],
},
{ serverId: "srv_b", password: "secret-b", label: "renamed" },
storedWithUnreadableEntries[2],
]);
store.syncHosts([]);
});
it("moves a stored connection password to its host and keeps the connection it can't read", async () => {
const { store, storage } = await bootWithRegistry(
JSON.stringify([
{
serverId: "srv_legacy",
connections: [
{ type: "directTcp", endpoint: "lan-a:6767", password: "old-secret" },
futureConnection,
],
},
]),
);
expect(store.getHosts().map((host) => [host.serverId, host.password])).toEqual([
["srv_legacy", "old-secret"],
]);
await vi.waitFor(async () =>
expect(await readRegistry(storage)).toMatchObject([
{ serverId: "srv_legacy", password: "old-secret" },
]),
);
expect(await readRegistry(storage)).toMatchObject([
{ connections: [{ ...directA, useTls: false }, futureConnection] },
]);
const [written] = (await readRegistry(storage)) as Array<{ connections: unknown[] }>;
expect(written?.connections[0]).not.toHaveProperty("password");
store.syncHosts([]);
});
it("forgets an entry it can't read once that host is paired again and removed", async () => {
const { store, storage } = await bootWithRegistry(
JSON.stringify([{ serverId: "srv_future", connections: [futureConnection] }]),
);
expect(store.getHosts()).toEqual([]);
await store.upsertDirectConnection({ serverId: "srv_future", endpoint: directA.endpoint });
await vi.waitFor(async () =>
expect(await readRegistry(storage)).toMatchObject([
{ serverId: "srv_future", connections: [{ id: directA.id }] },
]),
);
await store.removeHost("srv_future");
expect(await readRegistry(storage)).toEqual([]);
store.syncHosts([]);
});
it("copies a registry that isn't JSON aside instead of deleting it", async () => {
const { store, storage } = await bootWithRegistry("{not json");
expect(store.getHosts()).toEqual([]);
expect(await storage.getItem(`${REGISTRY_KEY}:unreadable`)).toBe("{not json");
expect(await storage.getItem(REGISTRY_KEY)).toBe("{not json");
store.syncHosts([]);
});
it("marks the host registry loaded after boot reads storage", async () => {
const previousOverride = process.env.EXPO_PUBLIC_LOCAL_DAEMON;
process.env.EXPO_PUBLIC_LOCAL_DAEMON = "not-an-endpoint";
+28 -37
View File
@@ -17,16 +17,14 @@ import {
import {
connectionFromListen,
createRemoteSshHostConnection,
forgetUnreadableHost,
normalizeStoredHostProfile,
pinRelayProtectedSecurityInProfiles,
readHostRegistry,
upsertHostConnectionInProfiles,
registryHasConnection,
relayConnectionFromOffer,
writeHostRegistry,
StoredHostRegistrySchema,
type HostConnection,
type HostProfile,
type UnreadableHostEntries,
} from "@/types/host-connection";
import { defaultHostAppearance, type HostBadgeDisplay, type HostColor } from "@/hosts/appearance";
import {
@@ -45,7 +43,7 @@ import { isWeb } from "@/constants/platform";
import { connectToDaemon, getConnectionAuthFailureReason } from "@/utils/test-daemon-connection";
import { getOrCreateClientId } from "@/utils/client-id";
import { z } from "zod";
import { readValidatedString } from "@/storage/validated-storage";
import { readValidatedJson, readValidatedString } from "@/storage/validated-storage";
import {
selectBestConnection,
type ConnectionCandidate,
@@ -1694,7 +1692,6 @@ export class HostRuntimeStore {
private hostListVersion = 0;
private hostRegistryLoaded = false;
private hosts: HostProfile[] = [];
private unreadableHosts: UnreadableHostEntries = { hosts: [], connectionsByServerId: new Map() };
private hostAppearanceMutationTail: Promise<void> = Promise.resolve();
private hostRegistryStatus: HostRegistryStatus = "loading";
private deps: HostRuntimeControllerDeps;
@@ -1802,17 +1799,32 @@ export class HostRuntimeStore {
let shouldPersistHosts = false;
let profiles: HostProfile[] = [];
try {
const stored = await this.readStoredRegistry();
const stored = await readValidatedJson(
this.storage,
REGISTRY_STORAGE_KEY,
StoredHostRegistrySchema,
);
if (stored) {
// An entry this build can't read skips only that host or connection, and stays stored.
const registry = readHostRegistry(stored);
this.unreadableHosts = registry.unreadable;
// COMPAT(connectionPassword): added in v0.9.1, remove after 2027-03-24 with stored-password migration.
if (registry.movedConnectionPassword) {
shouldPersistHosts = true;
const normalizedProfiles: HostProfile[] = [];
for (const entry of stored) {
const profile = normalizeStoredHostProfile(entry);
if (!profile) {
await this.storage.removeItem(REGISTRY_STORAGE_KEY);
normalizedProfiles.length = 0;
break;
}
// COMPAT(connectionPassword): added in v0.9.1, remove after 2027-03-24 with stored-password migration.
if (
entry.connections.some(
(connection) => connection.type === "directTcp" && connection.password,
)
) {
shouldPersistHosts = true;
}
normalizedProfiles.push(profile);
}
profiles = registry.hosts.filter((entry) => !isPlaceholderServerId(entry.serverId));
if (profiles.length !== registry.hosts.length) {
profiles = normalizedProfiles.filter((entry) => !isPlaceholderServerId(entry.serverId));
if (profiles.length !== normalizedProfiles.length) {
shouldPersistHosts = true;
}
}
@@ -2308,7 +2320,6 @@ export class HostRuntimeStore {
async removeHost(serverId: string): Promise<void> {
await this.revokePushNotifications({ client: this.getClient(serverId), serverId });
const remaining = this.hosts.filter((daemon) => daemon.serverId !== serverId);
this.unreadableHosts = forgetUnreadableHost(this.unreadableHosts, serverId);
this.setHostsAndSync(remaining);
await this.persistHosts();
}
@@ -2397,27 +2408,7 @@ export class HostRuntimeStore {
}
private async persistHosts(hosts = this.hosts): Promise<void> {
await this.storage.setItem(
REGISTRY_STORAGE_KEY,
JSON.stringify(writeHostRegistry(hosts, this.unreadableHosts)),
);
}
/**
* Reads the stored registry without removing it. A value that isn't a JSON array is copied to
* `<key>:unreadable` first, because the next save overwrites the key.
*/
private async readStoredRegistry(): Promise<unknown[] | null> {
const raw = await this.storage.getItem(REGISTRY_STORAGE_KEY);
if (raw === null) return null;
try {
const value: unknown = JSON.parse(raw);
if (Array.isArray(value)) return value;
} catch {
// Not JSON: copied aside below.
}
await this.storage.setItem(`${REGISTRY_STORAGE_KEY}:unreadable`, raw);
return null;
await this.storage.setItem(REGISTRY_STORAGE_KEY, JSON.stringify(hosts));
}
private emitHostList(): void {
@@ -21,7 +21,8 @@ import {
import { useLocalDaemonServerId } from "@/hooks/use-is-local-daemon";
import { PairDeviceModal } from "@/desktop/components/pair-device-modal";
import { buildSettingsHostSectionRoute } from "@/utils/host-routes";
import { WINDOW_CONTENT_DATASET } from "@/components/desktop/titlebar-drag-region";
const WINDOW_CONTENT_DATASET = { "window-content": "" };
export function OpenProjectScreen() {
const { t } = useTranslation();
@@ -106,79 +106,6 @@ describe("workspace-pane-state", () => {
});
});
it("does not locate a file by an id retained from a previous target", () => {
const layout: WorkspaceLayout = {
root: {
kind: "pane",
pane: {
id: "main",
tabIds: ["file_/repo/a.ts", "agent_agent-a"],
focusedTabId: "agent_agent-a",
},
},
focusedPaneId: "main",
};
const tabs = [
createTab("file_/repo/a.ts", { kind: "file", path: "/repo/b.ts" }),
createTab("agent_agent-a", { kind: "agent", agentId: "agent-a" }),
];
const target: WorkspaceTab["target"] = { kind: "file", path: "/repo/a.ts" };
expect(resolveSideFileOpenPlacement({ layout, sourcePaneId: "main", tabs, target })).toEqual({
kind: "split-side-pane",
paneId: "main",
});
expect(deriveWorkspacePaneState({ layout, tabs, preferredTarget: target }).activeTabId).toBe(
"agent_agent-a",
);
});
it("matches a retained file instance when only the requested line range differs", () => {
const pane = {
id: "main",
tabIds: ["retained-file", "agent_agent-a"],
focusedTabId: "agent_agent-a",
};
const layout: WorkspaceLayout = { root: { kind: "pane", pane }, focusedPaneId: "main" };
const tabs = [
createTab("retained-file", { kind: "file", path: "/repo/a.ts", lineStart: 2 }),
createTab("agent_agent-a", { kind: "agent", agentId: "agent-a" }),
];
const target: WorkspaceTab["target"] = {
kind: "file",
path: "/repo/a.ts",
lineStart: 12,
lineEnd: 20,
};
expect(resolveSideFileOpenPlacement({ layout, sourcePaneId: "main", tabs, target })).toEqual({
kind: "open-in-source",
});
expect(deriveWorkspacePaneState({ layout, tabs, preferredTarget: target }).activeTabId).toBe(
"retained-file",
);
});
it("prefers an exact file navigation target over another instance of the same resource", () => {
const pane = {
id: "main",
tabIds: ["first", "second"],
focusedTabId: "first",
};
const tabs = [
createTab("first", { kind: "file", path: "/repo/a.ts", lineStart: 2 }),
createTab("second", { kind: "file", path: "/repo/a.ts", lineStart: 12 }),
];
expect(
deriveWorkspacePaneState({
pane,
tabs,
preferredTarget: { kind: "file", path: "/repo/a.ts", lineStart: 12 },
}).activeTabId,
).toBe("second");
});
it("resolves side file opens to an existing file tab", () => {
const layout: WorkspaceLayout = {
root: {
@@ -5,9 +5,12 @@ import {
} from "@/stores/workspace-layout-store";
import type { WorkspaceTab, WorkspaceTabTarget } from "@/workspace-tabs/model";
import type { WorkspaceTabDescriptor } from "@/screens/workspace/workspace-tabs-types";
import { normalizeWorkspaceTabTarget, workspaceTabTargetsEqual } from "@/workspace-tabs/identity";
import {
buildDeterministicWorkspaceTabId,
normalizeWorkspaceTabTarget,
workspaceTabTargetsEqual,
} from "@/workspace-tabs/identity";
import { findAdjacentPane } from "@/utils/split-navigation";
import { panelResourceKey } from "@/panels/panel-manifest";
export interface WorkspaceDerivedTab {
descriptor: WorkspaceTabDescriptor;
@@ -121,10 +124,8 @@ function getActiveTabId(input: {
}
const matchingTab =
input.tabs.find((tab) => workspaceTabTargetsEqual(tab.descriptor.target, preferredTarget)) ??
input.tabs.find(
(tab) => panelResourceKey(tab.descriptor.target) === panelResourceKey(preferredTarget),
);
return matchingTab?.descriptor.tabId ?? null;
null;
return matchingTab?.descriptor.tabId ?? buildDeterministicWorkspaceTabId(preferredTarget);
})();
if (preferredTabId && input.openTabIds.has(preferredTabId)) {
@@ -210,8 +211,10 @@ export function resolveSideFileOpenPlacement(input: {
tabs: WorkspaceTab[];
target: WorkspaceTabTarget;
}): WorkspaceSideFileOpenPlacement {
const targetKey = panelResourceKey(input.target);
const existingTab = input.tabs.find((tab) => panelResourceKey(tab.target) === targetKey);
const targetTabId = buildDeterministicWorkspaceTabId(input.target);
const existingTab = input.tabs.find(
(tab) => tab.tabId === targetTabId || workspaceTabTargetsEqual(tab.target, input.target),
);
if (existingTab) {
return { kind: "open-in-source" };
}
@@ -90,7 +90,6 @@ interface StartInput {
token?: ReturnType<typeof createTokenRequest>;
reader?: ReturnType<typeof createFileReader>;
saver?: ReturnType<typeof createFileSaver>;
fetchFile?: typeof fetch;
}
async function startDownload(input: StartInput): Promise<Download | undefined> {
@@ -109,7 +108,6 @@ async function startDownload(input: StartInput): Promise<Download | undefined> {
requestFileDownloadToken: token.request,
readFile: reader.read,
saveFile: saver.save,
fetchFile: input.fetchFile ?? (async () => new Response(FILE_BYTES)),
});
const { activeDownloadId, downloads } = useDownloadStore.getState();
return activeDownloadId ? downloads.get(activeDownloadId) : undefined;
@@ -205,57 +203,6 @@ describe("download store transport selection", () => {
expect(saver.savedFiles).toEqual([]);
});
it("fails with the HTTP status when a proxy in front of the host rejects the download", async () => {
const requests: Array<RequestInit | undefined> = [];
const download = await startDownload({
profile: profileWith([localTcpConnection]),
activeConnectionId: localTcpConnection.id,
fetchFile: async (_url, init) => {
requests.push(init);
return new Response("<h1>401 Authorization Required</h1>", {
status: 401,
headers: { "WWW-Authenticate": 'Basic realm="Paseo"' },
});
},
});
expect(download).toMatchObject({
status: "error",
message: i18n.t("downloads.httpFailed", { status: 401 }),
});
expect(requests).toEqual([{ credentials: "include", redirect: "error" }]);
});
it("fails with a readable message when the download request cannot reach the host", async () => {
const download = await startDownload({
profile: profileWith([localTcpConnection]),
activeConnectionId: localTcpConnection.id,
fetchFile: async () => {
throw new TypeError("Failed to fetch");
},
});
expect(download).toMatchObject({ status: "error", message: i18n.t("downloads.failed") });
});
it("fails with a readable message when the connection drops while the file is downloading", async () => {
const saver = createFileSaver();
const download = await startDownload({
profile: profileWith([localTcpConnection]),
activeConnectionId: localTcpConnection.id,
fetchFile: async () =>
new Response(
new ReadableStream({
start: (controller) => controller.error(new TypeError("network error")),
}),
),
saver,
});
expect(download).toMatchObject({ status: "error", message: i18n.t("downloads.failed") });
expect(saver.savedFiles).toEqual([]);
});
it("fails the download and saves nothing when the session read fails", async () => {
const reader = createFileReader(async () => {
throw new Error("Connection lost");
+34 -39
View File
@@ -4,6 +4,7 @@ import * as LegacyFileSystem from "expo-file-system/legacy";
import * as Sharing from "expo-sharing";
import type { HostProfile } from "@/types/host-connection";
import { buildDaemonWebSocketUrl } from "@/utils/daemon-endpoints";
import { openExternalUrl } from "@/utils/open-external-url";
import { isWeb } from "@/constants/platform";
import { i18n } from "@/i18n/i18next";
@@ -58,7 +59,6 @@ interface DownloadState {
/** Reads the whole file over the session socket; used when no direct HTTP endpoint is active. */
readFile: (path: string, maxBytes: number) => Promise<{ bytes: Uint8Array; size: number }>;
saveFile?: typeof saveDownloadedBytes;
fetchFile?: typeof fetch;
}) => Promise<void>;
updateProgress: (id: string, progress: DownloadProgress) => void;
@@ -86,7 +86,6 @@ export const useDownloadStore = create<DownloadState>()((set, get) => ({
requestFileDownloadToken,
readFile,
saveFile = saveDownloadedBytes,
fetchFile = fetch,
}) => {
const id = generateDownloadId();
const download: Download = {
@@ -145,11 +144,14 @@ export const useDownloadStore = create<DownloadState>()((set, get) => ({
throw new Error(i18n.t("downloads.hostUnavailable"));
}
const downloadUrl = buildDownloadUrl(downloadTarget.baseUrl, tokenResponse.token);
const downloadUrl = buildDownloadUrl(
downloadTarget.baseUrl,
tokenResponse.token,
isWeb ? downloadTarget.authCredentials : null,
);
if (isWeb) {
const file = await fetchDownload(fetchFile, downloadUrl);
saveBrowserFile(file, resolvedFileName);
triggerBrowserDownload(downloadUrl, resolvedFileName);
get().completeDownload(id);
return;
}
@@ -196,6 +198,11 @@ export const useDownloadStore = create<DownloadState>()((set, get) => ({
await shareSavedFile(result.uri, tokenResponse.mimeType, resolvedFileName);
} catch (error) {
const message = error instanceof Error ? error.message : i18n.t("downloads.failed");
if (isWeb) {
console.warn("[DownloadStore] Download failed:", message);
get().failDownload(id, message);
return;
}
get().failDownload(id, message);
}
},
@@ -276,6 +283,7 @@ function findMostRecentDownloadId(downloads: Map<string, Download>): string | nu
interface DownloadTarget {
baseUrl: string | null;
authHeader: string | null;
authCredentials: { username: string; password: string } | null;
}
/**
@@ -298,7 +306,7 @@ function resolveDaemonDownloadTarget(
buildDaemonWebSocketUrl(connection.endpoint, { useTls: connection.useTls ?? false }),
);
} catch {
return { baseUrl: null, authHeader: null };
return { baseUrl: null, authHeader: null, authCredentials: null };
}
if (parsed.protocol === "ws:") {
@@ -324,41 +332,23 @@ function resolveDaemonDownloadTarget(
? `Basic ${btoa(`${authCredentials.username}:${authCredentials.password}`)}`
: null;
return { baseUrl, authHeader };
return { baseUrl, authHeader, authCredentials };
}
function buildDownloadUrl(baseUrl: string, token: string): string {
function buildDownloadUrl(
baseUrl: string,
token: string,
authCredentials: { username: string; password: string } | null,
): string {
const url = new URL("/api/files/download", baseUrl);
url.searchParams.set("token", token);
if (authCredentials) {
url.username = authCredentials.username;
url.password = authCredentials.password;
}
return url.toString();
}
/**
* Fetches the file instead of navigating to it. The app runs on another origin than the host
* (paseo://app on desktop), so a link to the download URL navigates the whole window, and any
* response that is not the file (a proxy's 401 page, a 404) replaces the app.
*/
async function fetchDownload(fetchFile: typeof fetch, url: string): Promise<Blob> {
let response: Response;
try {
// Send the same cookies the host's WebSocket handshake sends, so a proxy in front of the
// host lets the download through. Refuse redirects: a proxy that redirects to a login page
// would otherwise be saved as the file.
response = await fetchFile(url, { credentials: "include", redirect: "error" });
} catch {
throw new Error(i18n.t("downloads.failed"));
}
if (!response.ok) {
throw new Error(i18n.t("downloads.httpFailed", { status: response.status }));
}
try {
// The body streams after the headers, so the connection can still drop here.
return await response.blob();
} catch {
throw new Error(i18n.t("downloads.failed"));
}
}
/**
* Saves bytes read over the session. Web and Electron hand them to the browser's download
* manager and return `null`; native writes the file and returns its URI for the share sheet.
@@ -371,7 +361,12 @@ async function saveDownloadedBytes({
if (isWeb) {
const buffer = new ArrayBuffer(bytes.byteLength);
new Uint8Array(buffer).set(bytes);
saveBrowserFile(new Blob([buffer], { type: mimeType ?? "application/octet-stream" }), fileName);
const url = URL.createObjectURL(
new Blob([buffer], { type: mimeType ?? "application/octet-stream" }),
);
triggerBrowserDownload(url, fileName);
// The browser may still be reading the blob while its save prompt is open.
setTimeout(() => URL.revokeObjectURL(url), 60_000);
return null;
}
// Resolve and write in one tick so two downloads of the same name cannot pick the same path.
@@ -395,12 +390,14 @@ async function shareSavedFile(
}
}
function saveBrowserFile(file: Blob, fileName: string) {
function triggerBrowserDownload(url: string, fileName: string) {
if (typeof document === "undefined") {
if (typeof window !== "undefined") {
void openExternalUrl(url);
}
return;
}
const url = URL.createObjectURL(file);
const link = document.createElement("a");
link.href = url;
link.download = fileName;
@@ -408,8 +405,6 @@ function saveBrowserFile(file: Blob, fileName: string) {
document.body.appendChild(link);
link.click();
link.remove();
// The browser may still be reading the blob while its save prompt is open.
setTimeout(() => URL.revokeObjectURL(url), 60_000);
}
function resolveDownloadTargetFile(fileName: string): FSFile {
@@ -3,7 +3,7 @@ import type { JsonValue } from "@getpaseo/protocol/agent-types";
import type { WorkspaceTab, WorkspaceTabTarget } from "@/workspace-tabs/model";
import { MIN_SPLIT_SIZE } from "@/stores/workspace-layout-constants";
import { panelResourceKey, panelSupportsHost } from "@/panels/panel-manifest";
import { allocateWorkspaceTabId, defaultWorkspaceLayoutIds } from "@/stores/workspace-layout-ids";
import { defaultWorkspaceLayoutIds } from "@/stores/workspace-layout-ids";
import type { WorkspaceLayoutNodeIdPrefix } from "@/stores/workspace-layout-ids";
import {
buildDeterministicWorkspaceTabId,
@@ -137,8 +137,6 @@ interface OpenTabInLayoutInput {
placement: WorkspaceTabPlacement;
/** Required so a new caller cannot silently opt out of Explorer placement rules. */
explorerSidebarPaneId: string | null;
/** Live sheets share the workspace's panel-instance namespace with its tabs. */
reservedTabIds?: ReadonlySet<string>;
}
interface CreateTabInLayoutInput extends OpenTabInLayoutInput {
@@ -263,7 +261,6 @@ interface ReorderPaneTabsInLayoutInput {
export interface WorkspaceTabReconcileState {
layout: WorkspaceLayout;
reservedTabIds?: ReadonlySet<string>;
pinnedAgentIds?: ReadonlySet<string> | null;
hiddenAgentIds?: ReadonlySet<string> | null;
explorerSidebarPaneId: string | null;
@@ -401,11 +398,15 @@ function normalizeWorkspaceTabs(input: unknown): WorkspaceTab[] {
if (!Array.isArray(input)) {
return [];
}
// Preserve colliding entries until the whole layout can assign each an identity.
const next: WorkspaceTab[] = [];
const seen = new Set<string>();
for (const value of input) {
const tab = normalizeWorkspaceTab(value);
if (tab) next.push(tab);
if (!tab || seen.has(tab.tabId)) {
continue;
}
seen.add(tab.tabId);
next.push(tab);
}
return next;
}
@@ -1021,65 +1022,13 @@ function insertSplitInternal(input: InsertSplitInternalInput): InsertSplitIntern
};
}
function repairDuplicateTabIds(root: SplitNodeInternal): {
root: SplitNodeInternal;
ambiguousIds: ReadonlySet<string>;
} {
const keepers = new Map<string, WorkspaceTab>();
const ambiguousIds = new Set<string>();
for (const tab of collectAllTabs(root)) {
const keeper = keepers.get(tab.tabId);
if (!keeper) {
keepers.set(tab.tabId, tab);
continue;
}
ambiguousIds.add(tab.tabId);
if (
buildDeterministicWorkspaceTabId(tab.target) === tab.tabId &&
buildDeterministicWorkspaceTabId(keeper.target) !== keeper.tabId
) {
keepers.set(tab.tabId, tab);
}
}
if (ambiguousIds.size === 0) return { root, ambiguousIds };
// Reserve every original id before assigning replacements, including hidden panes.
const occupiedIds = new Set(keepers.keys());
function repair(node: SplitNodeInternal): SplitNodeInternal {
if (node.kind === "group") {
return { ...node, group: { ...node.group, children: node.group.children.map(repair) } };
}
const focusedCandidates = node.pane.tabs.filter((tab) => tab.tabId === node.pane.focusedTabId);
const focusedTab =
focusedCandidates.find((tab) => keepers.get(tab.tabId) === tab) ?? focusedCandidates[0];
let focusedTabId = node.pane.focusedTabId;
const tabs = node.pane.tabs.map((tab) => {
if (keepers.get(tab.tabId) === tab) return tab;
const tabId = allocateWorkspaceTabId(
buildDeterministicWorkspaceTabId(tab.target),
occupiedIds,
);
occupiedIds.add(tabId);
if (tab === focusedTab) focusedTabId = tabId;
return { ...tab, tabId };
});
return {
...node,
pane: { ...node.pane, tabs, tabIds: tabs.map((tab) => tab.tabId), focusedTabId },
};
}
return { root: repair(root), ambiguousIds };
}
export function normalizeLayout(layout: unknown): WorkspaceLayout {
if (!layout || typeof layout !== "object") {
return createDefaultLayout();
}
const rawLayout = layout as WorkspaceLayout;
const { root, ambiguousIds } = repairDuplicateTabIds(
normalizeNode(rawLayout.root) ?? asInternalNode(createDefaultLayout().root),
);
const root = normalizeNode(rawLayout.root) ?? asInternalNode(createDefaultLayout().root);
const focusedPaneId =
rawLayout.focusedPaneId === null ? null : trimNonEmpty(rawLayout.focusedPaneId);
const resolvedFocusedPaneId =
@@ -1098,16 +1047,7 @@ export function normalizeLayout(layout: unknown): WorkspaceLayout {
openTabIds: new Set(collectAllTabs(root).map((tab) => tab.tabId)),
});
if (parentTabIdByTabId) {
// A duplicated id cannot identify either end of a parent relationship unambiguously.
for (const [childId, parentId] of Object.entries(parentTabIdByTabId)) {
if (ambiguousIds.has(childId) || ambiguousIds.has(parentId))
delete parentTabIdByTabId[childId];
}
if (Object.keys(parentTabIdByTabId).length > 0)
return { ...normalizedLayout, parentTabIdByTabId };
}
return normalizedLayout;
return parentTabIdByTabId ? { ...normalizedLayout, parentTabIdByTabId } : normalizedLayout;
}
export function findPaneById(root: SplitNode, paneId: string | null | undefined): SplitPane | null {
@@ -1424,9 +1364,7 @@ function insertNewTabIntoPane(
return null;
}
const occupiedIds = new Set(input.reservedTabIds);
for (const tab of collectAllTabs(layout.root)) occupiedIds.add(tab.tabId);
const tabId = allocateWorkspaceTabId(input.createTabId(), occupiedIds);
const tabId = input.createTabId();
const nextTab: WorkspaceTab = {
tabId,
target: input.target,
@@ -2346,7 +2284,6 @@ function openEntityTabWithoutFocusing(input: {
layout: WorkspaceLayout;
target: WorkspaceTabTarget;
explorerSidebarPaneId: string | null;
reservedTabIds: ReadonlySet<string> | undefined;
}): WorkspaceLayout {
return (
insertNewTabIntoPane({
@@ -2355,7 +2292,6 @@ function openEntityTabWithoutFocusing(input: {
now: Date.now(),
placement: AMBIENT_PLACEMENT,
explorerSidebarPaneId: input.explorerSidebarPaneId,
reservedTabIds: input.reservedTabIds,
createTabId: () => buildDeterministicWorkspaceTabId(input.target),
focus: false,
})?.layout ?? input.layout
@@ -2446,7 +2382,6 @@ function addMissingEntityTabs(input: {
hasActivePendingTerminalCreate: boolean;
hasActivePendingDraftCreate: boolean;
explorerSidebarPaneId: string | null;
reservedTabIds: ReadonlySet<string> | undefined;
}): WorkspaceLayout {
const {
autoOpenAgentIds,
@@ -2477,7 +2412,6 @@ function addMissingEntityTabs(input: {
layout: nextLayout,
target: { kind: "agent", agentId },
explorerSidebarPaneId,
reservedTabIds: input.reservedTabIds,
});
currentAgentIds.add(agentId);
}
@@ -2492,7 +2426,6 @@ function addMissingEntityTabs(input: {
layout: nextLayout,
target: { kind: "terminal", terminalId },
explorerSidebarPaneId,
reservedTabIds: input.reservedTabIds,
});
currentTerminalIds.add(terminalId);
}
@@ -2592,7 +2525,6 @@ export function reconcileWorkspaceTabs(
hasActivePendingTerminalCreate: snapshot.hasActivePendingTerminalCreate ?? false,
hasActivePendingDraftCreate: snapshot.hasActivePendingDraftCreate ?? false,
explorerSidebarPaneId: state.explorerSidebarPaneId,
reservedTabIds: state.reservedTabIds,
});
if (reconciledFocusedTabId) {
@@ -11,22 +11,6 @@ function createRandomIdValue(): string {
: `${Date.now()}-${Math.random().toString(16).slice(2)}`;
}
export function createWorkspaceTabInstanceId(): string {
return `tab_${createRandomIdValue()}`;
}
/** A resource-derived id may still belong to a preview slot showing another target. */
export function allocateWorkspaceTabId(
preferredId: string,
occupiedIds: ReadonlySet<string>,
): string {
let tabId = preferredId;
for (let suffix = 2; occupiedIds.has(tabId); suffix += 1) {
tabId = `${preferredId}:${suffix}`;
}
return tabId;
}
export const defaultWorkspaceLayoutIds: WorkspaceLayoutIdSource = {
createNodeId: (prefix) => `${prefix}_${createRandomIdValue()}`,
createFocusRestorationToken: () => `workspace-focus-${createRandomIdValue()}`,
@@ -59,84 +59,6 @@ it("skips unchanged reconciliations and immediately saves real layout changes",
);
});
it("hydrates a saved preview collision and persists the repaired identities", async () => {
const workspaceKey = "server:workspace";
const duplicateId = "file_a.ts";
const values = new Map([
[
"workspace-layout-state",
JSON.stringify({
version: 2,
state: {
layoutByWorkspace: {
[workspaceKey]: {
root: {
kind: "group",
group: {
id: "split",
direction: "horizontal",
sizes: [0.5, 0.5],
children: [
{ id: "main", path: "b.ts" },
{ id: "right", path: "a.ts" },
].map(({ id, path }) => ({
kind: "pane",
pane: {
id,
tabIds: [duplicateId],
focusedTabId: duplicateId,
tabs: [{ tabId: duplicateId, target: { kind: "file", path }, createdAt: 1 }],
},
})),
},
},
focusedPaneId: "right",
},
},
},
}),
],
]);
const storage: StateStorage = {
getItem: (name) => values.get(name) ?? null,
setItem: (name, value) => {
values.set(name, value);
},
removeItem: (name) => {
values.delete(name);
},
};
const store = createWorkspaceLayoutStore(undefined, storage);
await store.persist.rehydrate();
const layout = store.getState().layoutByWorkspace[workspaceKey];
const tabs = collectAllTabs(layout.root);
expect(tabs.filter((tab) => tab.target.kind === "file").map((tab) => tab.tabId)).toEqual([
"file_b.ts",
"file_a.ts",
]);
expect(
deriveWorkspacePaneState({ layout, tabs, paneId: "main" }).activeTab?.descriptor.target,
).toEqual({
kind: "file",
path: "b.ts",
});
expect(
deriveWorkspacePaneState({ layout, tabs, paneId: "right" }).activeTab?.descriptor.target,
).toEqual({
kind: "file",
path: "a.ts",
});
store.getState().focusTab(workspaceKey, "file_b.ts");
expect(store.getState().layoutByWorkspace[workspaceKey].focusedPaneId).toBe("main");
const reloaded = createWorkspaceLayoutStore(undefined, storage);
await reloaded.persist.rehydrate();
expect(reloaded.getState().layoutByWorkspace[workspaceKey]).toEqual(
store.getState().layoutByWorkspace[workspaceKey],
);
});
it("keeps the saved layout when the shell publishes its layout mode before hydration", async () => {
const values = new Map<string, string>();
const storage: StateStorage = {
@@ -906,91 +906,6 @@ describe("workspace-layout-store actions", () => {
).toEqual(override);
});
it("keeps reused file tabs unique and focuses the matching split pane", () => {
const workspaceKey = createWorkspaceKey();
const store = workspaceLayoutStore.getState();
const firstTabId = store.openTab({
workspaceKey,
target: { kind: "file", path: "src/a.ts" },
intent: "reveal",
})!;
store.replaceTab(workspaceKey, firstTabId, { kind: "file", path: "src/b.ts" });
const rightPaneId = store.splitPaneEmpty(workspaceKey, {
targetPaneId: "main",
position: "right",
});
if (!rightPaneId) throw new Error("Expected a right split pane");
const rightTabId = store.openTab({
workspaceKey,
target: { kind: "file", path: "src/a.ts" },
intent: "reveal",
placement: { mode: "pane", paneId: rightPaneId },
})!;
store.openTab({
workspaceKey,
target: { kind: "file", path: "src/b.ts" },
intent: "reveal",
});
store.focusTab(workspaceKey, rightTabId);
const layout = workspaceLayoutStore.getState().layoutByWorkspace[workspaceKey];
const fileTabs = collectAllTabs(layout.root).filter((tab) => tab.target.kind === "file");
expect({
fileTabCount: fileTabs.length,
uniqueFileTabCount: new Set(fileTabs.map((tab) => tab.tabId)).size,
fileTargets: fileTabs.map((tab) => tab.target),
focusedPaneId: layout.focusedPaneId,
}).toEqual({
fileTabCount: 2,
uniqueFileTabCount: 2,
fileTargets: [
{ kind: "file", path: "src/b.ts" },
{ kind: "file", path: "src/a.ts" },
],
focusedPaneId: rightPaneId,
});
});
it("allocates distinct ids across retained tabs, sheets, and background opens", () => {
const workspaceKey = createWorkspaceKey();
const layoutStore = createWorkspaceLayoutStore(workspaceLayoutIds);
const store = layoutStore.getState();
const fileTabId = store.openTab({
workspaceKey,
target: { kind: "file", path: "src/a.ts" },
intent: "reveal",
})!;
store.replaceTab(workspaceKey, fileTabId, { kind: "file", path: "src/b.ts" });
layoutStore.setState({ layoutMode: "compact" });
const sheetTabId = store.openTab({
workspaceKey,
target: { kind: "file", path: "src/a.ts" },
intent: "reveal",
})!;
const selectedSheet = selectSheetTab(layoutStore.getState(), {
workspaceKey,
target: { kind: "file", path: "src/a.ts" },
});
expect(selectedSheet?.tab.tabId).toBe(sheetTabId);
const backgroundTabId = store.openTab({
workspaceKey,
target: { kind: "file", path: "src/a.ts" },
intent: "background",
})!;
expect(new Set([fileTabId, sheetTabId, backgroundTabId]).size).toBe(3);
expect(layoutStore.getState().sheetsByWorkspace[workspaceKey]).toHaveLength(1);
expect(
collectAllTabs(layoutStore.getState().layoutByWorkspace[workspaceKey].root)
.filter((tab) => tab.target.kind === "file")
.map((tab) => tab.target),
).toEqual([
{ kind: "file", path: "src/b.ts" },
{ kind: "file", path: "src/a.ts" },
]);
});
it("keeps the tab instance when a panel receives a same-kind replacement", () => {
const workspaceKey = createWorkspaceKey();
const store = workspaceLayoutStore.getState();
@@ -3285,75 +3200,6 @@ describe("workspace-layout-store actions", () => {
]);
});
it("repairs persisted duplicate ids without losing tabs, pane focus, or unambiguous parents", () => {
const file = (tabId: string, path: string) => ({
tabId,
target: { kind: "file", path },
createdAt: 1,
state: { treeVisible: true, treeWidth: 280 },
});
const leftTabs = [file("file_a.ts", "b.ts"), file("file_a.ts", "c.ts")];
const rightTabs = [
file("file_a.ts", "a.ts"),
file("file_b.ts", "b.ts"),
file("file_b.ts:2", "b.ts"),
file("child", "child.ts"),
file("parent", "parent.ts"),
];
const layout = normalizeLayout({
root: {
kind: "group",
group: {
id: "root",
direction: "horizontal",
sizes: [0.4, 0.6],
children: [
{
kind: "pane",
pane: {
id: "main",
tabs: leftTabs,
tabIds: leftTabs.map((tab) => tab.tabId),
focusedTabId: "file_a.ts",
},
},
{
kind: "pane",
pane: {
id: "right",
tabs: rightTabs,
tabIds: rightTabs.map((tab) => tab.tabId),
focusedTabId: "file_a.ts",
hidden: true,
},
},
],
},
},
focusedPaneId: "main",
parentTabIdByTabId: {
"file_a.ts": "parent",
"file_b.ts": "file_a.ts",
child: "parent",
},
});
const tabs = collectAllTabs(layout.root);
expect(tabs).toHaveLength(7);
expect(new Set(tabs.map((tab) => tab.tabId)).size).toBe(7);
expect(tabs[0]).toEqual({ ...leftTabs[0], tabId: "file_b.ts:3" });
expect(tabs[1]).toEqual({ ...leftTabs[1], tabId: "file_c.ts" });
expect(tabs.slice(2)).toEqual(rightTabs);
expect(findPaneById(layout.root, "main")?.tabIds).toEqual(["file_b.ts:3", "file_c.ts"]);
expect(findPaneById(layout.root, "main")?.focusedTabId).toBe("file_b.ts:3");
expect(findPaneById(layout.root, "right")).toMatchObject({
hidden: true,
focusedTabId: "file_a.ts",
});
expect(layout.parentTabIdByTabId).toEqual({ child: "parent" });
expect(normalizeLayout(layout)).toEqual(layout);
});
it("hydrates duplicate Changes and Pull request instances without collapsing their ids or state", () => {
const tabs = [
{
@@ -5264,50 +5110,6 @@ describe("compact workspace sheet", () => {
expect(sheetTargets(store)).toEqual([fileTarget, nextTarget]);
});
it("reserves a retargeted sheet's id when reconciling a new root agent tab", () => {
seedAgents([
{ id: "root", parentAgentId: null, workspaceId: "sheet-ws" },
{ id: "child-a", parentAgentId: "root", workspaceId: "sheet-ws" },
{ id: "child-b", parentAgentId: "root", workspaceId: "sheet-ws" },
]);
const store = createCompactStore();
store.getState().openTab({
workspaceKey,
target: { kind: "agent", agentId: "child-a" },
intent: "reveal",
});
const sheetId = requireTopSheet(store).tab.tabId;
store.getState().replaceTab(workspaceKey, sheetId, { kind: "agent", agentId: "child-b" });
seedAgents([
{ id: "root", parentAgentId: null, workspaceId: "sheet-ws" },
{ id: "child-a", parentAgentId: null, workspaceId: "sheet-ws" },
{ id: "child-b", parentAgentId: "root", workspaceId: "sheet-ws" },
]);
store.getState().reconcileTabs(workspaceKey, {
agentsHydrated: true,
terminalsHydrated: true,
activeAgentIds: ["root", "child-a", "child-b"],
autoOpenAgentIds: ["child-a"],
knownTerminalIds: ["term-1"],
standaloneTerminalIds: ["term-1"],
});
const tab = collectAllTabs(store.getState().layoutByWorkspace[workspaceKey].root).find(
(candidate) => candidate.target.kind === "agent" && candidate.target.agentId === "child-a",
);
if (!tab) throw new Error("Expected the root agent's tab");
expect(tab.tabId).not.toBe(sheetId);
store.getState().closeTab(workspaceKey, tab.tabId);
expect(requireTopSheet(store).tab).toMatchObject({
tabId: sheetId,
target: { kind: "agent", agentId: "child-b" },
});
expect(
collectAllTabs(store.getState().layoutByWorkspace[workspaceKey].root),
).not.toContainEqual(tab);
});
it("closes the sheet when its agent stops being a subagent, leaving one tab for it", () => {
seedAgents([
{ id: "root", parentAgentId: null, workspaceId: "sheet-ws" },
@@ -7,8 +7,6 @@ import { WorkspaceLayoutPersistedStateSchema } from "./workspace-layout-storage"
import type { JsonValue } from "@getpaseo/protocol/agent-types";
import type { WorkspaceTab, WorkspaceTabTarget } from "@/workspace-tabs/model";
import {
allocateWorkspaceTabId,
createWorkspaceTabInstanceId,
defaultWorkspaceLayoutIds,
type WorkspaceLayoutIdSource,
} from "@/stores/workspace-layout-ids";
@@ -433,6 +431,14 @@ function trimNonEmpty(value: string | null | undefined): string | null {
return trimmed.length > 0 ? trimmed : null;
}
function createWorkspaceTabInstanceId(): string {
const value =
typeof globalThis.crypto?.randomUUID === "function"
? globalThis.crypto.randomUUID()
: `${Date.now()}-${Math.random().toString(16).slice(2)}`;
return `tab_${value}`;
}
function addAgentIdToWorkspaceSet(
state: Record<string, Set<string>>,
workspaceKey: string,
@@ -525,10 +531,7 @@ export function selectExplorerSidebarPaneId(
*/
export function selectSheetTab(
state: Pick<WorkspaceLayoutStore, "layoutMode" | "layoutByWorkspace" | "sheetsByWorkspace">,
input: Pick<OpenWorkspaceTabInput, "workspaceKey" | "target" | "parentTabId"> & {
/** A host outside the sheet stack owns its instance identity. */
preferredTabId?: string;
},
input: Pick<OpenWorkspaceTabInput, "workspaceKey" | "target" | "parentTabId">,
): SheetTab | null {
const workspaceKey = trimNonEmpty(input.workspaceKey);
const target = normalizeWorkspaceTabTarget(input.target);
@@ -536,14 +539,9 @@ export function selectSheetTab(
const policy = resolveSheetPolicy(state, workspaceKey, target, "reveal");
if (!policy) return null;
return placeTargetInSheet({
occupiedTabIds: collectWorkspaceTabIds(state, workspaceKey),
kept: input.preferredTabId
? undefined
: getSheets(state, workspaceKey).find(
(sheet) => panelResourceKey(sheet.tab.target) === panelResourceKey(target),
),
kept: undefined,
target,
createTabId: () => input.preferredTabId ?? buildDeterministicWorkspaceTabId(target),
intent: "reveal",
policy,
parentTabId: resolveOpenParentTabId(state, workspaceKey, input.parentTabId),
state: undefined,
@@ -640,7 +638,6 @@ function getOpenTabPlacement(
layout: WorkspaceLayout;
placement: WorkspaceTabPlacement;
explorerSidebarPaneId: string | null;
reservedTabIds: Set<string>;
} {
const layout = getWorkspaceLayout(state.layoutByWorkspace, workspaceKey);
const explorerSidebarPaneId = resolveExplorerSidebarPaneId(
@@ -673,7 +670,6 @@ function getOpenTabPlacement(
layout,
placement: resolvedPlacement,
explorerSidebarPaneId,
reservedTabIds: new Set(getSheets(state, workspaceKey).map((sheet) => sheet.tab.tabId)),
};
}
@@ -819,23 +815,11 @@ function resolveOpenParentTabId(
return findSheet(state, workspaceKey, parentTabId)?.parentTabId ?? parentTabId;
}
function collectWorkspaceTabIds(
state: Pick<WorkspaceLayoutStore, "layoutByWorkspace" | "sheetsByWorkspace">,
workspaceKey: string,
): Set<string> {
const layout = state.layoutByWorkspace[workspaceKey];
return new Set([
...(layout ? collectAllTabs(layout.root).map((tab) => tab.tabId) : []),
...getSheets(state, workspaceKey).map((sheet) => sheet.tab.tabId),
]);
}
function placeTargetInSheet(input: {
occupiedTabIds: ReadonlySet<string>;
/** The sheet whose tab the target keeps, if any. */
kept: SheetTab | undefined;
target: WorkspaceTabTarget;
createTabId: () => string;
intent: WorkspaceTabOpenIntent;
policy: CompactSheetPolicy;
parentTabId: string | null;
state: JsonValue | undefined;
@@ -845,7 +829,10 @@ function placeTargetInSheet(input: {
}
return {
tab: {
tabId: allocateWorkspaceTabId(input.createTabId(), input.occupiedTabIds),
tabId:
input.intent === "reveal"
? buildDeterministicWorkspaceTabId(input.target)
: createWorkspaceTabInstanceId(),
target: input.target,
createdAt: Date.now(),
...(input.state !== undefined ? { state: input.state } : {}),
@@ -866,7 +853,6 @@ function promoteSheetToTab(
): { tabId: string; patch: Partial<WorkspaceLayoutStore> } | null {
const { tab } = sheet;
const placement = getOpenTabPlacement(state, workspaceKey, tab.target, FOCUSED_PANE_PLACEMENT);
placement.reservedTabIds.delete(tab.tabId);
const input = {
...placement,
target: tab.target,
@@ -1136,13 +1122,9 @@ export function createWorkspaceLayoutStore(
const sheets = getSheets(get(), normalizedWorkspaceKey);
const { keptIndex } = sheetPlacement;
const sheet = placeTargetInSheet({
occupiedTabIds: collectWorkspaceTabIds(get(), normalizedWorkspaceKey),
kept: keptIndex === null ? undefined : sheets[keptIndex],
target: normalizedTarget,
createTabId: () =>
input.intent === "reveal"
? buildDeterministicWorkspaceTabId(normalizedTarget)
: createWorkspaceTabInstanceId(),
intent: input.intent,
policy: sheetPlacement.policy,
parentTabId,
state: input.state,
@@ -1724,14 +1706,9 @@ export function createWorkspaceLayoutStore(
explorerSidebarPaneId,
rawLayout.focusedPaneId,
);
const sheets = getSheets(state, normalizedWorkspaceKey);
const fittingSheets = sheets.filter(
(sheet) => !sheetAgentNoLongerFits(normalizedWorkspaceKey, sheet, snapshot),
);
const nextState = reconcileWorkspaceTabs(
{
layout: currentLayout,
reservedTabIds: new Set(fittingSheets.map((sheet) => sheet.tab.tabId)),
pinnedAgentIds: state.pinnedAgentIdsByWorkspace[normalizedWorkspaceKey] ?? null,
hiddenAgentIds: state.hiddenAgentIdsByWorkspace[normalizedWorkspaceKey] ?? null,
explorerSidebarPaneId,
@@ -1753,6 +1730,10 @@ export function createWorkspaceLayoutStore(
);
}
}
const sheets = getSheets(state, normalizedWorkspaceKey);
const fittingSheets = sheets.filter(
(sheet) => !sheetAgentNoLongerFits(normalizedWorkspaceKey, sheet, snapshot),
);
const sheetAgentGone = fittingSheets.length !== sheets.length;
if (
state.layoutByWorkspace[normalizedWorkspaceKey] &&
@@ -138,88 +138,6 @@ describe("useSubagentSheetTab", () => {
expect(result.current?.tab.tabId).toBe(tabId);
});
it("keeps an open menu sheet's id when an unrelated reused tab disappears", () => {
const row = seedParentWithChild();
const store = useWorkspaceLayoutStore.getState();
const reusedId = store.openTab({
workspaceKey,
target: { kind: "agent", agentId: "child" },
intent: "reveal",
asTab: true,
});
if (!reusedId) throw new Error("Expected a child tab");
store.replaceTab(workspaceKey, reusedId, { kind: "agent", agentId: "other" });
store.setLayoutMode("compact");
const { result } = renderHook(() => useSubagentSheetTab(workspaceKey, "parent-tab")(row));
const sheetId = result.current?.tab.tabId;
expect(result.current?.tab.target).toEqual({ kind: "agent", agentId: "child" });
expect(sheetId).not.toBe(reusedId);
act(() => {
store.reconcileTabs(workspaceKey, {
agentsHydrated: true,
terminalsHydrated: true,
activeAgentIds: ["parent", "child"],
autoOpenAgentIds: [],
knownTerminalIds: [],
standaloneTerminalIds: [],
});
});
expect(store.getWorkspaceTabs(workspaceKey).map((tab) => tab.tabId)).not.toContain(reusedId);
expect(result.current?.tab.tabId).toBe(sheetId);
expect(result.current?.tab.target).toEqual({ kind: "agent", agentId: "child" });
});
it("promotes a menu sheet to the subagent's own tab", () => {
const row = seedParentWithChild();
const store = useWorkspaceLayoutStore.getState();
store.setLayoutMode("compact");
const { result } = renderHook(() => useSubagentSheetTab(workspaceKey, "parent-tab")(row));
const sheet = result.current;
if (!sheet) throw new Error("Expected a menu sheet");
let promotedId: string | null = null;
act(() => {
promotedId = store.openTabInFront(workspaceKey, sheet);
});
expect(promotedId).toBe("agent_child");
expect(
store.getWorkspaceTabs(workspaceKey).filter((tab) => tab.target.kind === "agent"),
).toEqual([
expect.objectContaining({
tabId: "agent_child",
target: { kind: "agent", agentId: "child" },
}),
]);
});
it("does not reuse a menu id retained by a promoted tab showing another target", () => {
const row = seedParentWithChild();
const store = useWorkspaceLayoutStore.getState();
store.setLayoutMode("compact");
const { result } = renderHook(() => useSubagentSheetTab(workspaceKey, "parent-tab")(row));
const sheet = result.current;
if (!sheet) throw new Error("Expected a menu sheet");
act(() => {
store.openTabInFront(workspaceKey, sheet);
});
expect(result.current).toBeNull();
act(() => {
store.replaceTab(workspaceKey, sheet.tab.tabId, { kind: "agent", agentId: "other" });
});
expect(result.current?.tab.target).toEqual({ kind: "agent", agentId: "child" });
expect(result.current?.tab.tabId).not.toBe(sheet.tab.tabId);
expect(
store.getWorkspaceTabs(workspaceKey).filter((tab) => tab.target.kind === "agent"),
).toEqual([
expect.objectContaining({
tabId: sheet.tab.tabId,
target: { kind: "agent", agentId: "other" },
}),
]);
});
it("hands a re-rendered row the same sheet", () => {
const row = seedParentWithChild();
useWorkspaceLayoutStore.getState().setLayoutMode("compact");
+3 -10
View File
@@ -4,7 +4,6 @@ import {
useWorkspaceLayoutStore,
type SheetTab,
} from "@/stores/workspace-layout-store";
import { buildDeterministicWorkspaceTabId } from "@/workspace-tabs/identity";
import type { WorkspaceTabTarget } from "@/workspace-tabs/model";
import type { SubagentRow } from "./select";
@@ -33,9 +32,6 @@ export function useSubagentSheetTab(
const sheets = useWorkspaceLayoutStore((state) =>
workspaceKey ? state.sheetsByWorkspace[workspaceKey] : undefined,
);
// Menu pages never enter the sheet stack. Each starts from the subagent's own tab id, so opening
// it as a tab lands on that id, and keeps the id it was given across layout updates.
const tabIds = useMemo(() => new Map<string, string>(), []);
return useMemo(() => {
// One answer per row until the state it reads changes, so a re-render of the list hands an
// open sheet the same tab rather than a fresh one.
@@ -47,19 +43,16 @@ export function useSubagentSheetTab(
layoutByWorkspace: layout ? { [workspaceKey]: layout } : {},
sheetsByWorkspace: sheets ? { [workspaceKey]: sheets } : {},
};
const key = JSON.stringify([workspaceKey, parentTabId, row.kind, row.id]);
const key = `${row.kind}:${row.id}`;
const known = answers.get(key);
if (known !== undefined) return known;
const target = subagentRowTarget(row);
const sheet = selectSheetTab(state, {
workspaceKey,
target,
target: subagentRowTarget(row),
parentTabId,
preferredTabId: tabIds.get(key) ?? buildDeterministicWorkspaceTabId(target),
});
if (sheet) tabIds.set(key, sheet.tab.tabId);
answers.set(key, sheet);
return sheet;
};
}, [layout, layoutMode, parentTabId, sheets, tabIds, workspaceKey]);
}, [layout, layoutMode, parentTabId, sheets, workspaceKey]);
}
@@ -5,11 +5,9 @@ import {
normalizeStoredHostProfile,
orderHostsLocalFirst,
pinRelayProtectedSecurityInProfiles,
readHostRegistry,
relayConnectionFromOffer,
resolveActiveHostServerId,
upsertHostConnectionInProfiles,
writeHostRegistry,
type HostConnection,
type HostProfile,
} from "./host-connection";
@@ -89,25 +87,6 @@ describe("normalizeStoredHostProfile", () => {
expect(profile?.connections[0]).not.toHaveProperty("password");
});
it("drops a connection kind this build doesn't know and keeps the host", () => {
const profile = normalizeStoredHostProfile({
serverId: "srv_mixed",
password: "secret",
connections: [
{ id: "future:1", type: "futureKind", address: "future.example.com" },
{ id: "direct:lan:6767", type: "directTcp", endpoint: "lan:6767", futureField: true },
{ id: "direct:remote:6767", type: "directTcp", endpoint: "remote:6767" },
],
preferredConnectionId: "direct:remote:6767",
});
expect(profile?.password).toBe("secret");
expect(profile?.connections).toEqual([
{ id: "direct:remote:6767", type: "directTcp", endpoint: "remote:6767", useTls: false },
]);
expect(profile?.preferredConnectionId).toBe("direct:remote:6767");
});
it("preserves legacy relay ids when TLS is absent", () => {
const profile = normalizeStoredHostProfile({
serverId: "srv_relay",
@@ -198,59 +177,6 @@ describe("normalizeStoredHostProfile", () => {
});
});
describe("readHostRegistry and writeHostRegistry", () => {
const direct: HostConnection = {
id: "direct:lan:6767",
type: "directTcp",
endpoint: "lan:6767",
useTls: false,
};
const future = { id: "future:1", type: "futureKind", address: "future.example.com" };
it("writes back every entry it could not read", () => {
const unreadableHost = { serverId: "srv_future", connections: [future] };
const hostWithFutureField = { serverId: "srv_field", connections: [direct], futureField: 1 };
const stored = [
{ ...makeHost("srv_a"), connections: [direct, future] },
unreadableHost,
hostWithFutureField,
"not a host",
];
const { hosts, unreadable } = readHostRegistry(stored);
expect(hosts.map((host) => host.serverId)).toEqual(["srv_a"]);
expect(hosts[0]?.connections).toEqual([direct]);
expect(writeHostRegistry(hosts, unreadable)).toEqual([
{ ...hosts[0], connections: [direct, future] },
unreadableHost,
hostWithFutureField,
"not a host",
]);
});
it("writes a host saved again by this build in place of the entry it could not read", () => {
const { hosts, unreadable } = readHostRegistry([{ serverId: "srv_a", connections: [future] }]);
expect(hosts).toEqual([]);
const saved = { ...makeHost("srv_a"), connections: [direct] };
expect(writeHostRegistry([saved], unreadable)).toEqual([saved]);
});
it("moves a stored direct TCP password to its host next to a connection it can't read", () => {
const registry = readHostRegistry([
{
serverId: "srv_legacy",
connections: [future, { type: "directTcp", endpoint: "lan:6767", password: "old-secret" }],
},
]);
expect(registry.movedConnectionPassword).toBe(true);
expect(registry.hosts[0]?.password).toBe("old-secret");
expect(registry.hosts[0]?.connections).toEqual([direct]);
});
});
describe("createRemoteSshHostConnection", () => {
it("keeps optional SSH settings absent", () => {
expect(createRemoteSshHostConnection({ host: "build-box" })).toEqual({
+13 -102
View File
@@ -522,12 +522,12 @@ const StoredHostProfileSchema = z.strictObject({
label: z.string().optional(),
appearance: HostAppearanceSchema.optional(),
lifecycle: z.strictObject({}).optional(),
// Read one by one, so a connection kind another build wrote skips only that connection.
connections: z.array(z.unknown()).min(1),
connections: z.array(StoredHostConnectionSchema).min(1),
preferredConnectionId: z.string().nullable().optional(),
createdAt: z.string().datetime({ offset: true }).optional(),
updatedAt: z.string().datetime({ offset: true }).optional(),
});
export const StoredHostRegistrySchema = z.array(StoredHostProfileSchema);
type StoredHostConnection = z.infer<typeof StoredHostConnectionSchema>;
function normalizeStoredConnection(connection: StoredHostConnection): HostConnection | null {
@@ -590,37 +590,20 @@ function normalizeStoredConnection(connection: StoredHostConnection): HostConnec
}
export function normalizeStoredHostProfile(entry: unknown): HostProfile | null {
return readStoredHost(entry)?.profile ?? null;
}
interface StoredHostRead {
profile: HostProfile;
unreadableConnections: unknown[];
movedConnectionPassword: boolean;
}
function readStoredHost(entry: unknown): StoredHostRead | null {
const result = StoredHostProfileSchema.safeParse(entry);
if (!result.success) {
return null;
}
const record = result.data;
const serverId = record.serverId;
const storedConnections: StoredHostConnection[] = [];
const unreadableConnections: unknown[] = [];
for (const stored of record.connections) {
const parsed = StoredHostConnectionSchema.safeParse(stored);
if (parsed.success) storedConnections.push(parsed.data);
else unreadableConnections.push(stored);
}
// COMPAT(connectionPassword): added in v0.9.1, remove after 2027-03-24 once stored direct passwords have migrated.
const legacyPassword = storedConnections.find(
const legacyPassword = record.connections.find(
(connection) => connection.type === "directTcp" && connection.password,
);
const password =
record.password ?? (legacyPassword?.type === "directTcp" ? legacyPassword.password : undefined);
const connections = storedConnections
const connections = record.connections
.map((connection) => normalizeStoredConnection(connection))
.filter((connection): connection is HostConnection => connection !== null);
if (connections.length === 0) {
@@ -637,90 +620,18 @@ function readStoredHost(entry: unknown): StoredHostRead | null {
: (connections[0]?.id ?? null);
return {
profile: {
serverId,
...(password ? { password } : {}),
label,
appearance: record.appearance ?? defaultHostAppearance(),
lifecycle: defaultLifecycle(),
connections,
preferredConnectionId,
createdAt: record.createdAt ?? now,
updatedAt: record.updatedAt ?? now,
},
unreadableConnections,
movedConnectionPassword: legacyPassword !== undefined,
serverId,
...(password ? { password } : {}),
label,
appearance: record.appearance ?? defaultHostAppearance(),
lifecycle: defaultLifecycle(),
connections,
preferredConnectionId,
createdAt: record.createdAt ?? now,
updatedAt: record.updatedAt ?? now,
};
}
/**
* Stored registry entries this build can't read, such as a connection kind added by a newer
* build. `writeHostRegistry` writes them back so that build still finds them.
*/
export interface UnreadableHostEntries {
hosts: unknown[];
connectionsByServerId: Map<string, unknown[]>;
}
export function readHostRegistry(stored: unknown[]): {
hosts: HostProfile[];
unreadable: UnreadableHostEntries;
// COMPAT(connectionPassword): added in v0.9.1, remove after 2027-03-24 with stored-password migration.
movedConnectionPassword: boolean;
} {
const hosts: HostProfile[] = [];
const unreadable: UnreadableHostEntries = { hosts: [], connectionsByServerId: new Map() };
let movedConnectionPassword = false;
for (const entry of stored) {
const read = readStoredHost(entry);
if (!read) {
unreadable.hosts.push(entry);
continue;
}
hosts.push(read.profile);
if (read.unreadableConnections.length > 0) {
unreadable.connectionsByServerId.set(read.profile.serverId, read.unreadableConnections);
}
movedConnectionPassword ||= read.movedConnectionPassword;
}
return { hosts, unreadable, movedConnectionPassword };
}
export function writeHostRegistry(
hosts: HostProfile[],
unreadable: UnreadableHostEntries,
): unknown[] {
const savedServerIds = new Set(hosts.map((host) => host.serverId));
const written: unknown[] = hosts.map((host) => {
const kept = unreadable.connectionsByServerId.get(host.serverId);
return kept ? { ...host, connections: [...host.connections, ...kept] } : host;
});
for (const entry of unreadable.hosts) {
// A host this build saved again replaces the entry it couldn't read.
const serverId = readStoredServerId(entry);
if (serverId === null || !savedServerIds.has(serverId)) written.push(entry);
}
return written;
}
/** Drops the entries this build couldn't read for a host you removed. */
export function forgetUnreadableHost(
unreadable: UnreadableHostEntries,
serverId: string,
): UnreadableHostEntries {
const connectionsByServerId = new Map(unreadable.connectionsByServerId);
connectionsByServerId.delete(serverId);
return {
hosts: unreadable.hosts.filter((entry) => readStoredServerId(entry) !== serverId),
connectionsByServerId,
};
}
function readStoredServerId(entry: unknown): string | null {
if (typeof entry !== "object" || entry === null || !("serverId" in entry)) return null;
return typeof entry.serverId === "string" ? entry.serverId.trim() : null;
}
export function hostHasConnection(host: HostProfile, connection: HostConnection): boolean {
return host.connections.some((existing) => hostConnectionEquals(existing, connection));
}
+2 -2
View File
@@ -47,7 +47,7 @@ export function addSendOptions(cmd: Command): Command {
.addOption(
new Option(
"--behavior <behavior>",
"Active-turn behavior (agent default: steer waits for turn end; otherwise: interrupt)",
"Active-turn behavior (agent default: steer; otherwise: interrupt)",
).choices(["interrupt", "steer"]),
)
.option("--no-wait", "Return immediately without waiting for completion");
@@ -218,7 +218,7 @@ export async function runSendCommand(
status: receipt.deliveryStatus ?? "sent",
message:
receipt.deliveryStatus === "queued"
? "Message queued for delivery after two quiet seconds and the current turn ends, unless interrupt was requested"
? "Message queued for delivery after two quiet seconds"
: "Message sent, not waiting for completion",
},
schema: agentSendSchema,
+1 -1
View File
@@ -483,7 +483,7 @@ export interface SendMessageOptions {
sourceAgentServerId?: string;
sessionMode?: string;
messageId?: string;
/** Agent sources wait for turn end unless interrupt is explicit. Human sources default to interrupt. */
/** What happens when the agent is mid-turn. The daemon interrupts the turn when omitted. */
activeTurnBehavior?: ActiveTurnBehavior;
images?: Array<{ data: string; mimeType: string }>;
attachments?: SendAgentMessageRequest["attachments"];
@@ -1,64 +0,0 @@
import type { Page } from "@playwright/test";
import { test, expect } from "../../app/e2e/support/fixtures";
import { gotoAppShell } from "../../app/e2e/support/helpers/app";
// Windows and Linux draw their window controls top-right, so the desktop sidebar has no
// chrome row of its own. Its window-drag surface is the strip above the navigation rows.
const CUSTOM_CHROME_HOSTS = [
{ platform: "linux", windowChromeMode: "custom-linux" },
{ platform: "win32", windowChromeMode: "custom-windows" },
] as const;
async function installDesktopHost(
page: Page,
host: (typeof CUSTOM_CHROME_HOSTS)[number],
): Promise<void> {
await page.addInitScript((desktopHost) => {
window.paseoDesktop = {
...desktopHost,
events: { on: () => () => {} },
invoke: async (command: string) => {
if (command === "get_desktop_settings") {
return {
releaseChannel: "stable",
daemon: { manageBuiltInDaemon: true, keepRunningAfterQuit: true },
};
}
return null;
},
};
}, host);
}
async function sidebarDragGeometry(page: Page) {
const navScroll = page.locator('[data-testid="sidebar-nav-scroll"]:visible').first();
await expect(navScroll).toBeVisible();
return navScroll.evaluate((node) => {
const nav = node.getBoundingClientRect();
const dragRegions = [];
for (const element of document.querySelectorAll<HTMLElement>("*")) {
if (getComputedStyle(element).getPropertyValue("-webkit-app-region") !== "drag") continue;
const rect = element.getBoundingClientRect();
const overSidebar = rect.left < nav.right && rect.right > nav.left;
if (overSidebar && rect.height > 0) dragRegions.push({ top: rect.top, bottom: rect.bottom });
}
return { navTop: nav.top, navBottom: nav.bottom, dragRegions };
});
}
for (const host of CUSTOM_CHROME_HOSTS) {
test.describe(`Desktop sidebar on ${host.platform}`, () => {
test.use({ viewport: { width: 1280, height: 480 } });
test("keeps a window drag strip above the scrolling navigation", async ({ page }) => {
await installDesktopHost(page, host);
await gotoAppShell(page);
const geometry = await sidebarDragGeometry(page);
expect(geometry.dragRegions).not.toEqual([]);
for (const region of geometry.dragRegions) {
expect(region.bottom).toBeLessThanOrEqual(geometry.navTop + 1);
}
});
});
}
-2
View File
@@ -88,8 +88,6 @@ export interface PluginSessionOpenRequest {
readonly background: boolean;
readonly labels: Readonly<Record<string, string>>;
readonly metadata: Readonly<Record<string, JsonValue>>;
/** Instructions appended for this open; not saved on the agent. */
appendSystemPrompt?: string[];
tools: AgentToolDefinition[];
env: Record<string, string>;
mcpServers: NonNullable<AgentSessionConfig["mcpServers"]>;
@@ -14,19 +14,18 @@ const BASE_RECORD: StoredAgentRecord = {
config: null,
};
const ARCHIVE = {
archivedAt: "2025-01-03T00:00:00.000Z",
updatedAt: "2025-01-03T00:00:00.000Z",
};
test("archives a stored agent without changing terminal statuses", () => {
const statuses: Array<StoredAgentRecord["lastStatus"]> = ["idle", "error", "closed"];
for (const status of statuses) {
const archived = buildArchivedAgentRecord({ ...BASE_RECORD, lastStatus: status }, ARCHIVE);
const archived = buildArchivedAgentRecord(
{ ...BASE_RECORD, lastStatus: status },
{ archivedAt: "2025-01-03T00:00:00.000Z" },
);
expect(archived.lastStatus).toBe(status);
expect(archived.archivedAt).toBe("2025-01-03T00:00:00.000Z");
expect(archived.updatedAt).toBe(BASE_RECORD.updatedAt);
}
});
@@ -34,7 +33,10 @@ test("archives busy stored agents as idle", () => {
const statuses: Array<StoredAgentRecord["lastStatus"]> = ["initializing", "running"];
for (const status of statuses) {
const archived = buildArchivedAgentRecord({ ...BASE_RECORD, lastStatus: status }, ARCHIVE);
const archived = buildArchivedAgentRecord(
{ ...BASE_RECORD, lastStatus: status },
{ archivedAt: "2025-01-03T00:00:00.000Z" },
);
expect(archived.lastStatus).toBe("idle");
}
@@ -48,7 +50,7 @@ test("clears persisted attention when archiving", () => {
attentionReason: "finished",
attentionTimestamp: "2025-01-02T12:00:00.000Z",
},
ARCHIVE,
{ archivedAt: "2025-01-03T00:00:00.000Z" },
);
expect(archived).toMatchObject({
@@ -58,19 +60,11 @@ test("clears persisted attention when archiving", () => {
});
});
test("moves updatedAt to the archive time", () => {
const archived = buildArchivedAgentRecord(BASE_RECORD, ARCHIVE);
test("can stamp updatedAt to the archive timestamp", () => {
const archived = buildArchivedAgentRecord(BASE_RECORD, {
archivedAt: "2025-01-03T00:00:00.000Z",
updatedAt: "2025-01-03T00:00:00.000Z",
});
expect(archived.updatedAt).toBe("2025-01-03T00:00:00.000Z");
});
test("keeps a later updatedAt when the archive time is earlier", () => {
// Putting an original archive back after a failed unarchive must not move updatedAt backwards.
const archived = buildArchivedAgentRecord(
{ ...BASE_RECORD, updatedAt: "2025-01-04T00:00:00.000Z" },
ARCHIVE,
);
expect(archived.archivedAt).toBe("2025-01-03T00:00:00.000Z");
expect(archived.updatedAt).toBe("2025-01-04T00:00:00.000Z");
});
@@ -3,19 +3,19 @@ import type { StoredAgentRecord } from "./agent-storage.js";
export type ArchivedStoredAgentRecord = StoredAgentRecord & { archivedAt: string };
interface BuildArchivedAgentRecordOptions {
archivedAt: string;
/** When this archive happened. Re-archiving keeps the original archivedAt but still records it. */
updatedAt: string;
archivedAt?: string;
updatedAt?: string;
}
export function buildArchivedAgentRecord(
record: StoredAgentRecord,
options: BuildArchivedAgentRecordOptions,
options?: BuildArchivedAgentRecordOptions,
): ArchivedStoredAgentRecord {
const archivedAt = options?.archivedAt ?? new Date().toISOString();
return {
...record,
archivedAt: options.archivedAt,
updatedAt: latestTimestamp(record.updatedAt, options.updatedAt),
archivedAt,
updatedAt: options?.updatedAt ?? record.updatedAt,
lastStatus: normalizeArchivedStatus(record.lastStatus),
requiresAttention: false,
attentionReason: null,
@@ -23,13 +23,6 @@ export function buildArchivedAgentRecord(
};
}
// Archiving is the agent's latest change. An earlier archive time (an original archive put back
// after a failed unarchive) keeps the newer updatedAt, since clients drop an agent update that is
// older than the one they hold.
function latestTimestamp(current: string, archiveTime: string): string {
return Date.parse(archiveTime) > Date.parse(current) ? archiveTime : current;
}
function normalizeArchivedStatus(
status: StoredAgentRecord["lastStatus"],
): StoredAgentRecord["lastStatus"] {
File diff suppressed because it is too large Load Diff
@@ -29,7 +29,6 @@ import { z } from "zod";
import type { TerminalManager } from "../../terminal/terminal-manager.js";
import {
AgentTurnStartCanceledError,
getAgentStreamEventTurnId,
type AgentCapabilityFlags,
type AgentClient,
@@ -93,7 +92,6 @@ import {
import { limitAgentTimelineItemContent } from "./agent-timeline-content.js";
import {
AgentRunState,
type ForegroundPromptStart,
type ForegroundTurnWaiter,
type PendingForegroundRun,
} from "./agent-run-state.js";
@@ -636,12 +634,7 @@ function normalizePersistenceForConfig(
if (!handle) {
return null;
}
const {
mcpServers: _launchMcpServers,
pluginAppendSystemPrompt: _pluginAppendSystemPrompt,
daemonAppendSystemPrompt: _daemonAppendSystemPrompt,
...metadata
} = handle.metadata ?? {};
const { mcpServers: _launchMcpServers, ...metadata } = handle.metadata ?? {};
return {
...handle,
metadata: {
@@ -1124,10 +1117,6 @@ export class AgentManager {
return new Date(nextMs).toISOString();
}
hasPendingPermissions(agentId: string): boolean {
return (this.agents.get(agentId)?.pendingPermissions.size ?? 0) > 0;
}
hasInFlightRun(agentId: string): boolean {
const agent = this.agents.get(agentId);
if (!agent) {
@@ -1738,10 +1727,7 @@ export class AgentManager {
...(record ? { metadata: record.metadata, attention: extractAttention(record) } : {}),
workspaceId,
launchEnv,
persistence:
purpose === "interactive" && session.persistenceUpdatedOnResume
? (session.describePersistence() ?? handle)
: handle,
persistence: handle,
restoring: true,
});
}
@@ -2352,7 +2338,7 @@ export class AgentManager {
private async persistArchivedRecord(
record: StoredAgentRecord,
options: { archivedAt: string; updatedAt: string },
options: { archivedAt: string; updatedAt?: string },
): Promise<ArchivedStoredAgentRecord> {
const archivedRecord = buildArchivedAgentRecord(record, options);
await this.requireRegistry().upsert(archivedRecord);
@@ -2872,11 +2858,7 @@ export class AgentManager {
throw new Error(`Agent not found: ${agentId}`);
}
// Archiving is the agent's latest change, as markRecordArchived records it for a loaded agent.
const nextRecord = await this.persistArchivedRecord(record, {
archivedAt,
updatedAt: archivedAt,
});
const nextRecord = await this.persistArchivedRecord(record, { archivedAt });
await this.syncNativeArchiveState(record.provider, record.persistence, "archive");
@@ -3048,7 +3030,6 @@ export class AgentManager {
agentId: string,
prompt: AgentPromptInput,
options?: AgentRunOptions,
onAccepted?: () => void,
): Promise<boolean> {
if (this.collectingRuntimes.has(agentId) || !this.agents.has(agentId)) {
await this.waitForAgentClose(agentId);
@@ -3068,7 +3049,6 @@ export class AgentManager {
if (!handler) {
return false;
}
onAccepted?.();
this.touchUpdatedAt(agent);
if (options?.clientMessageId) {
this.recordSubmittedPrompt(agent, prompt, options.clientMessageId, "accepted");
@@ -3145,7 +3125,7 @@ export class AgentManager {
pendingRun: PendingForegroundRun;
prompt: AgentPromptInput;
options?: AgentRunOptions;
}): Promise<string | null> {
}): Promise<string> {
const { agent, agentId, pendingRun, prompt, options } = params;
try {
const result = await agent.session.startTurn(prompt, options);
@@ -3154,32 +3134,11 @@ export class AgentManager {
}
return result.turnId;
} catch (error) {
if (error instanceof AgentTurnStartCanceledError) {
if (!pendingRun.settled) {
if (options?.clientMessageId) {
this.recordSubmittedPrompt(agent, prompt, options.clientMessageId, "rejected", {
messageId: options.clientMessageId,
});
}
await this.handleStreamEvent(agent, {
type: "turn_canceled",
provider: agent.provider,
reason: "interrupted",
});
this.finalizeForegroundTurn(agent);
this.runs.settleForegroundRun(agentId, pendingRun.token);
}
return null;
}
if (pendingRun.settled) {
throw error;
}
if (isStaleProviderSessionError(error)) {
this.runs.settleForegroundStart(pendingRun, {
status: "failed",
error: error.message,
stale: true,
});
this.runs.settleForegroundStart(pendingRun, { status: "failed", error: error.message });
agent.pendingReplacement = false;
if (!agent.activeForegroundTurnId) agent.lifecycle = "idle";
this.runs.settleForegroundRun(agentId, pendingRun.token);
@@ -3235,17 +3194,15 @@ export class AgentManager {
agentId: string,
prompt: AgentPromptInput,
options?: AgentRunOptions,
promptStart?: ForegroundPromptStart,
): AsyncGenerator<AgentStreamEvent> {
await this.ensureInteractiveSession(agentId);
yield* this.streamAgent(agentId, prompt, options, promptStart);
yield* this.streamAgent(agentId, prompt, options);
}
private async *streamAfterRuntimeCollection(
agentId: string,
prompt: AgentPromptInput,
options?: AgentRunOptions,
promptStart?: ForegroundPromptStart,
): AsyncGenerator<AgentStreamEvent> {
await this.waitForAgentClose(agentId);
await ensureAgentLoaded(agentId, {
@@ -3253,20 +3210,19 @@ export class AgentManager {
agentStorage: this.requireRegistry(),
logger: this.logger,
});
yield* this.streamAgent(agentId, prompt, options, promptStart);
yield* this.streamAgent(agentId, prompt, options);
}
streamAgent(
agentId: string,
prompt: AgentPromptInput,
options?: AgentRunOptions,
promptStart?: ForegroundPromptStart,
): AsyncGenerator<AgentStreamEvent> {
if (this.collectingRuntimes.has(agentId) || (!this.agents.has(agentId) && this.registry))
return this.streamAfterRuntimeCollection(agentId, prompt, options, promptStart);
return this.streamAfterRuntimeCollection(agentId, prompt, options);
const existingAgent = this.requireSessionAgent(agentId);
if (this.historySessions.has(existingAgent.session))
return this.streamAfterHistoryLoad(agentId, prompt, options, promptStart);
return this.streamAfterHistoryLoad(agentId, prompt, options);
this.logger.trace(
{
agentId,
@@ -3301,10 +3257,9 @@ export class AgentManager {
agent.lastError = undefined;
const pendingRun = this.runs.createPendingRun(agentId);
promptStart?.bind(pendingRun);
const streamForwarder = async function* streamForwarder(this: AgentManager) {
let turnId: string | null;
let turnId: string;
let turnStream: ReturnType<AgentRunState["createTurnStream"]> | null = null;
turnId = await this.startPendingForegroundTurn({
agent,
@@ -3313,15 +3268,6 @@ export class AgentManager {
prompt,
options,
});
if (turnId === null) {
const canceledEvent: AgentStreamEvent = {
type: "turn_canceled",
provider: agent.provider,
reason: "interrupted",
};
yield canceledEvent;
return;
}
if (isReplacement) {
agent.pendingReplacement = false;
@@ -3476,10 +3422,9 @@ export class AgentManager {
agentId: string,
prompt: AgentPromptInput,
options?: AgentRunOptions,
promptStart?: ForegroundPromptStart,
): Promise<AsyncGenerator<AgentStreamEvent>> {
this.requireSessionAgent(agentId);
return this.replaceRunInForegroundLane(agentId, prompt, options, promptStart);
return this.replaceRunInForegroundLane(agentId, prompt, options);
}
async steerAgentRun(
@@ -3520,7 +3465,6 @@ export class AgentManager {
agentId: string,
prompt: AgentPromptInput,
options?: AgentSteerOptions,
promptStart?: ForegroundPromptStart,
): Promise<ActiveTurnSteerDispatchResult> {
// A turn that is still starting has no id to steer yet. Replacing it would drop its
// prompt, so wait until it is accepted (or fails) and steer the turn it became.
@@ -3568,7 +3512,6 @@ export class AgentManager {
expectedTurnId,
prompt,
stripSteerOptions(options),
promptStart,
),
};
}
@@ -3634,10 +3577,9 @@ export class AgentManager {
expectedTurnId: string,
prompt: AgentPromptInput,
options?: AgentRunOptions,
promptStart?: ForegroundPromptStart,
): Promise<AsyncGenerator<AgentStreamEvent>> {
this.assertSteerAdmissionOwnsTurn(agent, expectedTurnId);
return this.replaceRunInForegroundLane(agent.id, prompt, options, promptStart, (live) =>
return this.replaceRunInForegroundLane(agent.id, prompt, options, (live) =>
this.assertSteerAdmissionOwnsTurn(live, expectedTurnId),
);
}
@@ -3650,13 +3592,12 @@ export class AgentManager {
agentId: string,
prompt: AgentPromptInput,
options: AgentRunOptions | undefined,
promptStart?: ForegroundPromptStart,
assertAdmission?: (agent: ActiveManagedAgent) => void,
): Promise<AsyncGenerator<AgentStreamEvent>> {
// Replacements queue in arrival order; each one holds the foreground lane only while
// it cancels and reserves, so Stop is never stuck behind a replacement that is waiting.
return this.runQueuedMutation(this.replacementMutationTails, agentId, () =>
this.replaceRunWhenAdmitted(agentId, prompt, options, promptStart, assertAdmission),
this.replaceRunWhenAdmitted(agentId, prompt, options, assertAdmission),
);
}
@@ -3664,7 +3605,6 @@ export class AgentManager {
agentId: string,
prompt: AgentPromptInput,
options: AgentRunOptions | undefined,
promptStart?: ForegroundPromptStart,
assertAdmission?: (agent: ActiveManagedAgent) => void,
): Promise<AsyncGenerator<AgentStreamEvent>> {
let stalledStart: PendingForegroundRun | null = null;
@@ -3683,7 +3623,7 @@ export class AgentManager {
if (!this.hasInFlightRun(agent.id)) {
return {
status: "reserved" as const,
iterator: this.streamAgent(agent.id, prompt, options, promptStart),
iterator: this.streamAgent(agent.id, prompt, options),
};
}
agent.pendingReplacement = true;
@@ -3697,7 +3637,7 @@ export class AgentManager {
}
return {
status: "reserved" as const,
iterator: this.streamAgent(agent.id, prompt, options, promptStart),
iterator: this.streamAgent(agent.id, prompt, options),
};
} catch (error) {
agent.pendingReplacement = false;
@@ -3888,10 +3828,7 @@ export class AgentManager {
}
async cancelAgentRun(agentId: string): Promise<AgentRunCancellationResult> {
return this.runForegroundMutation(agentId, () => {
this.requireSessionAgent(agentId).pendingReplacement = false;
return this.cancelAgentRunNow(agentId);
});
return this.runForegroundMutation(agentId, () => this.cancelAgentRunNow(agentId));
}
private async cancelAgentRunNow(agentId: string): Promise<AgentRunCancellationResult> {
@@ -5176,9 +5113,6 @@ export class AgentManager {
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);
}
}
@@ -5448,6 +5382,7 @@ export class AgentManager {
!agent.pendingReplacement
) {
(agent as ActiveManagedAgent).lifecycle = "idle";
this.emitState(agent);
}
void this.refreshRuntimeInfo(agent);
}
@@ -5488,6 +5423,9 @@ export class AgentManager {
options,
);
this.resolvePendingPermissionsForAgent(agent, event.provider, options, "Turn failed");
if (!isForegroundEvent && !agent.activeForegroundTurnId) {
this.emitState(agent);
}
}
private onStreamTurnCanceled(params: {
@@ -5521,6 +5459,9 @@ export class AgentManager {
}
agent.lastError = undefined;
this.resolvePendingPermissionsForAgent(agent, event.provider, options, "Interrupted");
if (!isForegroundEvent && !agent.activeForegroundTurnId) {
this.emitState(agent);
}
}
private onStreamTurnStarted(params: {
@@ -6230,7 +6171,6 @@ export class AgentManager {
// A plugin changing during this open must still make the resulting session stale.
const generation = this.sessionOpenGeneration;
this.detachPluginTools(agentId);
let appendSystemPrompt: string[] | undefined;
let mcpServers: AgentSessionConfig["mcpServers"];
let mcpServerOwners: Record<string, string> | undefined;
if (this.pluginLifecycle) {
@@ -6252,14 +6192,12 @@ export class AgentManager {
env = transformed.env;
if (request.purpose === "interactive") {
this.attachedPluginTools.set(agentId, transformed.tools as AttachedAgentTool[]);
appendSystemPrompt = transformed.appendSystemPrompt;
mcpServers = transformed.mcpServers;
mcpServerOwners = transformed.mcpServerOwners;
}
}
const context: AgentLaunchContext = {
agentId,
...pluginPromptContext(appendSystemPrompt),
mcpServers,
mcpServerOwners,
env: {
@@ -6306,7 +6244,6 @@ export class AgentManager {
throw new Error(`MCP server '${name}' from plugin ${owner} collides with ${existingOwner}`);
}
}
launchConfig = { ...launchConfig, pluginAppendSystemPrompt: launchContext.appendSystemPrompt };
const merged =
Object.keys(launchContext.mcpServers ?? {}).length > 0
? {
@@ -6444,9 +6381,3 @@ export function commandMayHaveChangedExternalState(command: string): boolean {
/\bgit\s+fetch\b/.test(normalized)
);
}
function pluginPromptContext(
appendSystemPrompt: string[] | undefined,
): Pick<AgentLaunchContext, "appendSystemPrompt"> {
return appendSystemPrompt?.length ? { appendSystemPrompt } : {};
}
@@ -1,4 +1,3 @@
import { AgentTurnBusyError } from "../agent-prompt.js";
import { expect, test } from "vitest";
import { createAgentMessageDelivery, parseAgentMessages } from "./index.js";
import type { AgentPromptInput } from "../agent-sdk-types.js";
@@ -118,6 +117,7 @@ test("explicit interrupt and conflicting session modes retain ordered dispatch b
const delivery = createAgentMessageDelivery({
dispatch: async (request) => {
sent.push(request);
request.onDispatch("steered");
return "steered";
},
onError: (error) => {
@@ -313,555 +313,3 @@ test("runtime safety sees queued messages until provider dispatch settles", asyn
await delivery.close();
expect(delivery.hasPending("parent")).toBe(false);
});
test("messages wait across quiet windows and batch after the recipient turn ends", async () => {
const clock = createClock();
let running = true;
const sent: Array<readonly string[]> = [];
const delivery = createAgentMessageDelivery({
schedule: clock.schedule,
isRunning: () => running,
dispatch: async (request) => {
sent.push(request.messageIds);
return "turn_started";
},
onError: (error) => {
throw error;
},
});
const source = { kind: "agent-message" as const, agentId: "child" };
const report = delivery.enqueue({
recipientId: "parent",
messageId: "report",
source,
prompt: "report",
});
clock.advance(2000);
await Promise.resolve();
expect(sent).toEqual([]);
clock.advance(13000);
const finish = delivery.enqueue({
recipientId: "parent",
messageId: "finish",
source: { kind: "agent-notification", agentId: "child", event: "finished" },
prompt: "finished",
activeTurnBehavior: "steer",
});
clock.advance(2000);
await Promise.resolve();
expect(sent).toEqual([]);
running = false;
clock.advance(2000);
await Promise.all([report.dispatched, finish.dispatched]);
expect(sent).toEqual([["report", "finish"]]);
await delivery.close();
});
test("a turn starting during dispatch preparation keeps receipts queued and joins later arrivals", async () => {
const clock = createClock();
let busy = true;
const sent: Array<readonly string[]> = [];
const delivery = createAgentMessageDelivery({
schedule: clock.schedule,
dispatch: async (request) => {
if (busy) throw new AgentTurnBusyError("concurrent turn");
sent.push(request.messageIds);
return "turn_started";
},
onError: (error) => {
throw error;
},
});
const message = {
recipientId: "parent",
source: { kind: "agent-message" as const, agentId: "child" },
prompt: "report",
};
const first = delivery.enqueue({ ...message, messageId: "first" });
clock.advance(2000);
await new Promise<void>((resolve) => setImmediate(resolve));
expect(delivery.hasPending("parent")).toBe(true);
const second = delivery.enqueue({ ...message, messageId: "second" });
busy = false;
clock.advance(2000);
await Promise.all([first.dispatched, second.dispatched]);
expect(sent).toEqual([["first", "second"]]);
await delivery.close();
});
test("explicit interrupt bypasses a running turn while ordinary messages keep waiting", async () => {
const clock = createClock();
const sent: Array<readonly string[]> = [];
const delivery = createAgentMessageDelivery({
schedule: clock.schedule,
isRunning: () => true,
dispatch: async (request) => {
sent.push(request.messageIds);
return "turn_started";
},
onError: (error) => {
throw error;
},
});
const message = {
recipientId: "parent",
source: { kind: "agent-message" as const, agentId: "child" },
prompt: "report",
};
delivery.enqueue({ ...message, messageId: "wait" });
const interrupt = delivery.enqueue({
...message,
messageId: "interrupt",
activeTurnBehavior: "interrupt",
});
clock.advance(2000);
await interrupt.dispatched;
expect(sent).toEqual([["interrupt"]]);
expect(delivery.hasPending("parent")).toBe(true);
await delivery.close();
expect(sent).toEqual([["interrupt"], ["wait"]]);
});
test("shutdown flushes a dispatch that discovered a concurrent turn during preparation", async () => {
const clock = createClock();
let release!: () => void;
const preparing = new Promise<void>((resolve) => {
release = resolve;
});
const modes: boolean[] = [];
const delivery = createAgentMessageDelivery({
schedule: clock.schedule,
dispatch: async (request) => {
modes.push(request.idleOnly);
if (request.idleOnly) {
await preparing;
throw new AgentTurnBusyError("busy");
}
return "turn_started";
},
onError: () => {},
});
const receipt = delivery.enqueue({
recipientId: "parent",
prompt: "report",
source: { kind: "agent-message", agentId: "child" },
});
clock.advance(2000);
await new Promise<void>((resolve) => setImmediate(resolve));
const closing = delivery.close();
release();
await closing;
await expect(receipt.dispatched).resolves.toBe("turn_started");
expect(modes).toEqual([true, false]);
});
test("conflicting modes dispatch on separate turn ends without changing the active turn mode", async () => {
const clock = createClock();
let busy = false;
let mode = "initial";
let wake!: (recipientId: string) => void;
const sent: Array<{ ids: readonly string[]; mode?: string }> = [];
const delivery = createAgentMessageDelivery({
schedule: clock.schedule,
isRunning: () => busy,
subscribe: (listener) => {
wake = listener;
return () => {};
},
dispatch: async (request) => {
// Mode preparation precedes run admission in the real dispatcher.
mode = request.sessionMode ?? mode;
if (busy) throw new AgentTurnBusyError("concurrent turn");
sent.push({ ids: request.messageIds, mode });
busy = true;
return "turn_started";
},
onError: (error) => {
throw error;
},
});
const message = {
recipientId: "parent",
source: { kind: "agent-message" as const, agentId: "child" },
prompt: "message",
};
const a = delivery.enqueue({ ...message, messageId: "A", sessionMode: "plan" });
const b = delivery.enqueue({ ...message, messageId: "B", sessionMode: "default" });
clock.advance(2000);
await a.dispatched;
await new Promise<void>((resolve) => setImmediate(resolve));
expect(mode).toBe("plan");
expect(sent).toEqual([{ ids: ["A"], mode: "plan" }]);
busy = false;
wake("parent");
await b.dispatched;
expect(mode).toBe("default");
expect(sent).toEqual([
{ ids: ["A"], mode: "plan" },
{ ids: ["B"], mode: "default" },
]);
await delivery.close();
});
test("interrupts retain separate mode choices while the recipient is busy", async () => {
const clock = createClock();
const sent: Array<{ ids: readonly string[]; mode?: string }> = [];
const delivery = createAgentMessageDelivery({
schedule: clock.schedule,
isRunning: () => true,
dispatch: async (request) => {
sent.push({ ids: request.messageIds, mode: request.sessionMode });
return "turn_started";
},
onError: (error) => {
throw error;
},
});
const message = {
recipientId: "parent",
source: { kind: "agent-message" as const, agentId: "child" },
prompt: "message",
activeTurnBehavior: "interrupt" as const,
};
const a = delivery.enqueue({ ...message, messageId: "A", sessionMode: "plan" });
const b = delivery.enqueue({ ...message, messageId: "B", sessionMode: "default" });
clock.advance(2000);
await Promise.all([a.dispatched, b.dispatched]);
expect(sent).toEqual([
{ ids: ["A"], mode: "plan" },
{ ids: ["B"], mode: "default" },
]);
await delivery.close();
});
test("a settled-turn event releases a ready batch without waiting for the next timer sample", async () => {
const clock = createClock();
let running = true;
let settled: (id: string) => void = () => {};
let subscribed = true;
const sent: string[] = [];
const delivery = createAgentMessageDelivery({
schedule: clock.schedule,
isRunning: () => running,
subscribe: (listener) => {
settled = listener;
return () => {
subscribed = false;
};
},
dispatch: async (request) => {
sent.push(request.recipientId);
return "turn_started";
},
onError: (error) => {
throw error;
},
});
delivery.enqueue({
recipientId: "parent",
prompt: "report",
source: { kind: "agent-message", agentId: "child" },
});
clock.advance(2000);
expect(sent).toEqual([]);
running = false;
settled("parent");
await new Promise<void>((resolve) => setImmediate(resolve));
expect(sent).toEqual(["parent"]);
running = true;
await delivery.close();
expect(subscribed).toBe(false);
});
test.each([false, true])(
"completion waits report permission checkpoints without draining messages (initial: %s)",
async (initial) => {
const clock = createClock();
let permission = initial;
let changed: (id: string) => void = () => {};
let reported = false;
let sent = 0;
const delivery = createAgentMessageDelivery({
schedule: clock.schedule,
isRunning: () => true,
hasPendingPermission: () => permission,
subscribe: (listener) => {
changed = listener;
return () => {};
},
dispatch: async () => {
sent++;
return "turn_started";
},
onError: (error) => {
throw error;
},
});
delivery.enqueue({
recipientId: "child",
prompt: "follow up",
source: { kind: "agent-message", agentId: "parent" },
});
const wait = delivery.waitForDispatch("child", new AbortController().signal).then(() => {
reported = true;
return undefined;
});
permission = true;
changed("child");
await new Promise<void>((resolve) => setImmediate(resolve));
expect(reported).toBe(true);
expect(sent).toBe(0);
expect(delivery.hasPending("child")).toBe(true);
await wait;
await delivery.close();
},
);
test("a busy admission retry stays ready for the next settled-turn event", async () => {
const clock = createClock();
let running = false;
let raced = true;
let notify: (id: string) => void = () => {};
const sent: string[] = [];
const delivery = createAgentMessageDelivery({
schedule: clock.schedule,
isRunning: () => running,
subscribe: (listener) => {
notify = listener;
return () => {};
},
dispatch: async (request) => {
if (raced) {
running = true;
throw new AgentTurnBusyError("next turn started");
}
sent.push(request.recipientId);
return "turn_started";
},
onError: (error) => {
throw error;
},
});
delivery.enqueue({
recipientId: "parent",
prompt: "report",
source: { kind: "agent-message", agentId: "child" },
});
clock.advance(2000);
await new Promise<void>((resolve) => setImmediate(resolve));
raced = false;
running = false;
notify("parent");
await new Promise<void>((resolve) => setImmediate(resolve));
expect(sent).toEqual(["parent"]);
await delivery.close();
});
test("out-of-band acceptance owns callbacks and receipts; a failed attempt does not block waiting messages", async () => {
const clock = createClock();
let running = true;
let wake!: (recipientId: string) => void;
const callbacks: string[] = [];
const sent: string[] = [];
const errors: unknown[] = [];
const failure = new Error("recipient could not load");
const delivery = createAgentMessageDelivery({
schedule: clock.schedule,
isRunning: () => running,
subscribe: (listener) => {
wake = listener;
return () => {};
},
tryRunOutOfBand: async (request, onAccepted) => {
const text = parseAgentMessages(String(request.prompt))[0]!.text;
if (text === "failure") throw failure;
if (text !== "/handled") return false;
onAccepted();
callbacks.push("command ran");
return true;
},
dispatch: async (request) => {
sent.push(...parseAgentMessages(String(request.prompt)).map((message) => message.text));
return "turn_started";
},
onError: (error) => {
errors.push(error);
},
});
const message = {
recipientId: "parent",
source: { kind: "agent-message" as const, agentId: "child" },
};
const ordinary = delivery.enqueue({
...message,
prompt: "ordinary",
beforeDispatch: () => {
callbacks.push("ordinary");
},
});
const failed = delivery.enqueue({
...message,
prompt: "failure",
beforeDispatch: () => {
callbacks.push("failure");
},
});
const command = delivery.enqueue({
...message,
prompt: "/handled",
beforeDispatch: () => {
callbacks.push("command accepted");
},
onDispatch: (disposition) => {
callbacks.push(disposition);
},
});
clock.advance(2000);
await expect(failed.dispatched).rejects.toBe(failure);
await expect(command.dispatched).resolves.toBe("out_of_band");
expect(errors).toEqual([failure]);
expect(callbacks).toEqual(["command accepted", "command ran", "out_of_band"]);
expect(sent).toEqual([]);
running = false;
wake("parent");
await ordinary.dispatched;
expect(callbacks.at(-1)).toBe("ordinary");
expect(sent).toEqual(["ordinary"]);
await delivery.close();
});
test("shutdown waits for an in-flight out-of-band attempt and drains its unhandled message", async () => {
const clock = createClock();
let release!: () => void;
let attempted!: () => void;
const started = new Promise<void>((resolve) => {
attempted = resolve;
});
const gate = new Promise<void>((resolve) => {
release = resolve;
});
const dispatched: boolean[] = [];
const delivery = createAgentMessageDelivery({
schedule: clock.schedule,
isRunning: () => true,
tryRunOutOfBand: async () => {
attempted();
await gate;
return false;
},
dispatch: async (request) => {
dispatched.push(request.idleOnly);
return "turn_started";
},
onError: (error) => {
throw error;
},
});
const receipt = delivery.enqueue({
recipientId: "parent",
prompt: "ordinary",
source: { kind: "agent-message", agentId: "child" },
});
clock.advance(2000);
await started;
const closing = delivery.close();
release();
await closing;
await expect(receipt.dispatched).resolves.toBe("turn_started");
expect(dispatched).toEqual([false]);
});
test("a declined out-of-band message is offered once across running-turn retries", async () => {
const clock = createClock();
let running = true;
let accepts = false;
let offers = 0;
let dispatched = 0;
let wake!: (recipientId: string) => void;
const delivery = createAgentMessageDelivery({
schedule: clock.schedule,
isRunning: () => running,
subscribe: (listener) => {
wake = listener;
return () => {};
},
tryRunOutOfBand: async (_request, onAccepted) => {
offers++;
if (accepts) onAccepted();
return accepts;
},
dispatch: async () => {
dispatched++;
return "turn_started";
},
onError: (error) => {
throw error;
},
});
const receipt = delivery.enqueue({
recipientId: "parent",
prompt: "message",
source: { kind: "agent-message", agentId: "child" },
});
clock.advance(2000);
await new Promise<void>((resolve) => setImmediate(resolve));
expect(offers).toBe(1);
// A later provider state change does not reinterpret a declined message.
accepts = true;
for (let retry = 0; retry < 3; retry++) {
clock.advance(2000);
await new Promise<void>((resolve) => setImmediate(resolve));
}
expect(offers).toBe(1);
expect(dispatched).toBe(0);
running = false;
wake("parent");
await receipt.dispatched;
expect(dispatched).toBe(1);
await delivery.close();
});
test("a command with an explicit mode waits for turn end without an out-of-band offer", async () => {
const clock = createClock();
let running = true;
let offers = 0;
let wake!: (recipientId: string) => void;
const dispatched: Array<{ prompt: AgentPromptInput; sessionMode?: string }> = [];
const delivery = createAgentMessageDelivery({
schedule: clock.schedule,
isRunning: () => running,
subscribe: (listener) => {
wake = listener;
return () => {};
},
tryRunOutOfBand: async (_request, onAccepted) => {
offers++;
onAccepted();
return true;
},
dispatch: async (request) => {
dispatched.push(request);
return "out_of_band";
},
onError: (error) => {
throw error;
},
});
const receipt = delivery.enqueue({
recipientId: "parent",
prompt: "/handled",
sessionMode: "plan",
source: { kind: "agent-message", agentId: "child" },
});
clock.advance(2000);
await new Promise<void>((resolve) => setImmediate(resolve));
expect(offers).toBe(0);
expect(dispatched).toEqual([]);
running = false;
wake("parent");
await receipt.dispatched;
expect(dispatched).toHaveLength(1);
expect(dispatched[0]!.sessionMode).toBe("plan");
expect(parseAgentMessages(String(dispatched[0]!.prompt))![0]!.text).toBe("/handled");
await delivery.close();
});
@@ -1,4 +1,4 @@
import { AgentTurnBusyError, type PromptDispatchDisposition } from "../agent-prompt.js";
import type { PromptDispatchDisposition } from "../agent-prompt.js";
import { randomUUID } from "node:crypto";
import type { AgentPromptInput, AgentPromptContentBlock } from "../agent-sdk-types.js";
import { prepareAgentMessage, type AgentPromptSource } from "./envelope.js";
@@ -21,8 +21,6 @@ interface Receipt {
dispatched: Promise<PromptDispatchDisposition>;
}
interface Admitted extends Message {
sequence: number;
outOfBandDeclined: boolean;
receipt: Receipt;
resolve(disposition: PromptDispatchDisposition): void;
reject(error: unknown): void;
@@ -32,18 +30,12 @@ interface DispatchRequest {
messageIds: readonly string[];
prompt: AgentPromptInput;
activeTurnBehavior: "steer" | "interrupt";
idleOnly: boolean;
sessionMode?: string;
clearPendingPermissions: boolean;
unarchive: boolean;
onDispatch(disposition: PromptDispatchDisposition): void;
}
interface Dependencies {
/** Includes admitted starts and provider turns, including compaction. */
isRunning?: (recipientId: string) => boolean;
hasPendingPermission?: (recipientId: string) => boolean;
/** Notify when recipient state changes; admission still checks whether it is idle. */
subscribe?: (listener: (recipientId: string) => void) => () => void;
tryRunOutOfBand?(request: DispatchRequest, onAccepted: () => void): Promise<boolean>;
dispatch(request: DispatchRequest): Promise<PromptDispatchDisposition>;
onError(error: unknown, request: DispatchRequest): void;
/** Return a cancellation function. Production uses the daemon's event loop. */
@@ -55,7 +47,7 @@ export interface AgentMessageDelivery {
hasPending(recipientId: string): boolean;
/** Stop admission, flush pending messages, and await provider dispatch acknowledgments. */
close(): Promise<void>;
/** Completion waits include admitted messages, but return at permission checkpoints. */
/** Existing completion waits include agent messages admitted before the wait. */
waitForDispatch(recipientId: string, signal: AbortSignal): Promise<void>;
}
@@ -67,14 +59,12 @@ export function createAgentMessageDelivery(dependencies: Dependencies): AgentMes
const timer = setTimeout(callback, delayMs);
return () => clearTimeout(timer);
});
const pending = new Map<string, { messages: Admitted[]; ready: boolean; cancel(): void }>();
const pending = new Map<string, { messages: Admitted[]; cancel(): void }>();
const dispatching = new Map<string, Promise<void>>();
const receipts = new Map<string, Set<Receipt>>();
let sequence = 0;
let closed = false;
let closing: Promise<void> | undefined;
function requestFor(recipientId: string, messages: Admitted[]): DispatchRequest {
function dispatch(recipientId: string, messages: Admitted[]): void {
const prompts = messages.map(
(message) =>
prepareAgentMessage(message.prompt, message.source, message.receipt.messageId).prompt,
@@ -84,55 +74,39 @@ export function createAgentMessageDelivery(dependencies: Dependencies): AgentMes
: prompts.flatMap((entry): AgentPromptContentBlock[] =>
typeof entry === "string" ? [{ type: "text", text: entry }] : entry,
);
return {
const request: DispatchRequest = {
recipientId,
idleOnly: !closed && messages[0]!.activeTurnBehavior !== "interrupt",
messageIds: messages.map((message) => message.receipt.messageId),
prompt,
activeTurnBehavior: messages[0]!.activeTurnBehavior ?? "steer",
sessionMode: messages.find((message) => message.sessionMode)?.sessionMode,
clearPendingPermissions: messages.some((message) => message.clearPendingPermissions),
unarchive: messages.some((message) => message.unarchive !== false),
};
}
function dispatch(recipientId: string, messages: Admitted[]): void {
const request = requestFor(recipientId, messages);
queueDispatch(recipientId, async () => {
try {
for (const message of messages) message.beforeDispatch?.();
let disposition: PromptDispatchDisposition;
try {
disposition = await dependencies.dispatch(request);
} catch (error) {
if (!(error instanceof AgentTurnBusyError) || !closed) throw error;
// Shutdown drains admitted messages before closing the recipients.
disposition = await dependencies.dispatch({ ...request, idleOnly: false });
}
onDispatch: (disposition) => {
for (const message of messages) {
try {
message.onDispatch?.(disposition);
} catch (error) {
dependencies.onError(error, request);
}
message.resolve(disposition);
}
return undefined;
} catch (error) {
if (error instanceof AgentTurnBusyError && !closed) {
requeue(recipientId, messages);
return;
}
for (const message of messages) message.reject(error);
dependencies.onError(error, request);
throw error;
}
});
}
function queueDispatch(recipientId: string, operation: () => Promise<void>): void {
},
};
const previous = dispatching.get(recipientId) ?? Promise.resolve();
const dispatched = previous.catch(() => undefined).then(operation);
const dispatched = previous
.catch(() => undefined)
.then(async () => {
try {
for (const message of messages) message.beforeDispatch?.();
const disposition = await dependencies.dispatch(request);
for (const message of messages) message.resolve(disposition);
return undefined;
} catch (error) {
for (const message of messages) message.reject(error);
dependencies.onError(error, request);
throw error;
}
});
dispatching.set(recipientId, dispatched);
void dispatched
.finally(() => {
@@ -141,121 +115,30 @@ export function createAgentMessageDelivery(dependencies: Dependencies): AgentMes
.catch(() => undefined);
}
function requeue(recipientId: string, messages: Admitted[]): void {
const entry = pending.get(recipientId) ?? {
messages: [],
ready: true,
cancel: () => {},
};
entry.cancel();
entry.messages.push(...messages);
entry.messages.sort((a, b) => a.sequence - b.sequence);
entry.cancel = schedule(2000, () => flush(recipientId));
pending.set(recipientId, entry);
}
function flush(recipientId: string): void {
const entry = pending.get(recipientId);
if (!entry) return;
entry.ready = true;
entry.cancel();
if (!closed && dependencies.isRunning?.(recipientId)) {
const interrupts = entry.messages.filter(
(message) => message.activeTurnBehavior === "interrupt",
);
entry.messages = entry.messages.filter(
(message) => message.activeTurnBehavior !== "interrupt",
);
if (interrupts.length) dispatchGroups(recipientId, interrupts);
if (entry.messages.length && dependencies.tryRunOutOfBand) {
pending.delete(recipientId);
offerOutOfBand(recipientId, entry.messages);
} else if (entry.messages.length) {
entry.cancel = schedule(2000, () => flush(recipientId));
} else {
pending.delete(recipientId);
}
return;
}
pending.delete(recipientId);
dispatchGroups(recipientId, entry.messages);
}
function offerOutOfBand(recipientId: string, messages: Admitted[]): void {
queueDispatch(recipientId, async () => {
const waiting: Admitted[] = [];
for (const message of messages) {
if (
message.outOfBandDeclined ||
message.sessionMode !== undefined ||
closed ||
!dependencies.isRunning?.(recipientId)
) {
waiting.push(message);
continue;
}
const request = requestFor(recipientId, [message]);
try {
const accepted = await dependencies.tryRunOutOfBand!(request, () =>
message.beforeDispatch?.(),
);
if (!accepted) {
message.outOfBandDeclined = true;
waiting.push(message);
continue;
}
try {
message.onDispatch?.("out_of_band");
} catch (error) {
dependencies.onError(error, request);
}
message.resolve("out_of_band");
} catch (error) {
message.reject(error);
dependencies.onError(error, request);
}
}
if (waiting.length) requeue(recipientId, waiting);
if (closed || (pending.get(recipientId)?.ready && !dependencies.isRunning?.(recipientId)))
flush(recipientId);
});
}
function dispatchGroups(recipientId: string, messages: Admitted[]): void {
const groups: Admitted[][] = [];
entry.cancel();
let group: Admitted[] = [];
let mode: string | undefined;
for (const message of messages) {
for (const message of entry.messages) {
// Explicitly conflicting send options require separate, ordered dispatches.
if (
group.length &&
((message.activeTurnBehavior ?? "steer") !== (group[0]!.activeTurnBehavior ?? "steer") ||
(mode && message.sessionMode && mode !== message.sessionMode))
) {
groups.push(group);
dispatch(recipientId, group);
group = [];
mode = undefined;
}
group.push(message);
mode ??= message.sessionMode;
}
if (group.length) groups.push(group);
let started = false;
for (const batch of groups) {
if (!closed && started && batch[0]!.activeTurnBehavior !== "interrupt") {
requeue(recipientId, batch);
} else {
dispatch(recipientId, batch);
started = true;
}
}
if (group.length) dispatch(recipientId, group);
}
const unsubscribe = dependencies.subscribe?.((recipientId) => {
if (pending.get(recipientId)?.ready && !dependencies.isRunning?.(recipientId))
flush(recipientId);
});
return {
hasPending: (recipientId) => pending.has(recipientId) || dispatching.has(recipientId),
enqueue(message) {
@@ -272,47 +155,17 @@ export function createAgentMessageDelivery(dependencies: Dependencies): AgentMes
messageId: message.messageId ?? randomUUID(),
dispatched,
};
const owned = receipts.get(message.recipientId) ?? new Set<Receipt>();
owned.add(receipt);
receipts.set(message.recipientId, owned);
void dispatched
.finally(() => {
owned.delete(receipt);
if (!owned.size) receipts.delete(message.recipientId);
})
.catch(() => undefined);
const entry = pending.get(message.recipientId) ?? {
messages: [],
ready: false,
cancel: () => {},
};
const entry = pending.get(message.recipientId) ?? { messages: [], cancel: () => {} };
entry.cancel();
entry.ready = false;
entry.messages.push({
...message,
receipt,
resolve,
reject,
sequence: sequence++,
outOfBandDeclined: false,
});
entry.messages.push({ ...message, receipt, resolve, reject });
entry.cancel = schedule(2000, () => flush(message.recipientId));
pending.set(message.recipientId, entry);
return receipt;
},
async waitForDispatch(recipientId, signal) {
signal.throwIfAborted();
const admitted = Array.from(receipts.get(recipientId) ?? [], (receipt) => receipt.dispatched);
let unsubscribePermission: (() => void) | undefined;
const permission = new Promise<void>((resolve) => {
const check = () => {
if (dependencies.hasPendingPermission?.(recipientId)) resolve();
};
unsubscribePermission = dependencies.subscribe?.((agentId) => {
if (agentId === recipientId) check();
});
check();
});
const admitted =
pending.get(recipientId)?.messages.map((message) => message.receipt.dispatched) ?? [];
let aborted!: () => void;
const cancellation = new Promise<never>((_resolve, reject) => {
aborted = () => reject(new DOMException("Wait aborted", "AbortError"));
@@ -322,22 +175,17 @@ export function createAgentMessageDelivery(dependencies: Dependencies): AgentMes
await Promise.race([
Promise.all([dispatching.get(recipientId), ...admitted]),
cancellation,
permission,
]);
} finally {
signal.removeEventListener("abort", aborted);
unsubscribePermission?.();
}
},
close() {
if (closing) return closing;
closed = true;
unsubscribe?.();
for (const recipientId of pending.keys()) flush(recipientId);
// Each failure is reported and rejects its receipts; shutdown still drains other recipients.
closing = Promise.allSettled(
[...receipts.values()].flatMap((owned) => [...owned].map((receipt) => receipt.dispatched)),
).then(() => undefined);
closing = Promise.allSettled(dispatching.values()).then(() => undefined);
return closing;
},
};
@@ -337,7 +337,6 @@ describe("toAgentPayload", () => {
nativeHandle: { id: "native" } as unknown,
metadata: {
restored: new Date("2025-03-01T00:00:00.000Z"),
paseoInstructionReceipt: { threadId: "persist-99", digest: "internal-digest" },
empty: {},
mcpServers: {
hub: {
@@ -388,8 +387,6 @@ describe("toAgentPayload", () => {
sessionId: "persist-stored",
metadata: {
conversationId: "conversation-stored",
pluginAppendSystemPrompt: ["plugin instruction"],
daemonAppendSystemPrompt: "daemon instruction",
mcpServers: {
hub: {
type: "http",
@@ -405,8 +402,6 @@ describe("toAgentPayload", () => {
expect(record.persistence?.metadata).toEqual({
conversationId: "conversation-stored",
pluginAppendSystemPrompt: ["plugin instruction"],
daemonAppendSystemPrompt: "daemon instruction",
mcpServers: {
hub: {
type: "http",
@@ -495,9 +495,6 @@ function projectPersistenceHandleForWire(
return projected;
}
delete projected.metadata.mcpServers;
delete projected.metadata.pluginAppendSystemPrompt;
delete projected.metadata.daemonAppendSystemPrompt;
delete projected.metadata.paseoInstructionReceipt;
if (Object.keys(projected.metadata).length === 0) {
delete projected.metadata;
}
@@ -15,7 +15,6 @@ import { join } from "node:path";
import { createTestLogger } from "../../test-utils/test-logger.js";
import { AgentManager } from "./agent-manager.js";
import { waitForAgentRunStartWithTimeout } from "./agent-prompt.js";
import { ForegroundPromptStart } from "./agent-run-state.js";
import type {
AgentClient,
AgentRunResult,
@@ -162,7 +161,7 @@ class SlowStartAgentClient implements AgentClient {
async function createRunStartScenario(startDelayMs: number | null): Promise<{
agentManager: AgentManager;
agentId: string;
startRun: () => Promise<{ started: Promise<void> }>;
startRun: () => Promise<void>;
cleanup: () => Promise<void>;
}> {
const workdir = mkdtempSync(join(tmpdir(), "agent-run-start-budget-"));
@@ -179,16 +178,14 @@ async function createRunStartScenario(startDelayMs: number | null): Promise<{
return {
agentManager,
agentId: snapshot.id,
// Returns the sender's start, bound to the run streamAgent registers.
// streamAgent registers the pending run synchronously, so the wait always observes it.
startRun: async () => {
const start = new ForegroundPromptStart(snapshot.id);
const run = agentManager.streamAgent(snapshot.id, "start the run", undefined, start);
const run = agentManager.streamAgent(snapshot.id, "start the run");
drained = (async () => {
for await (const _event of run) {
// Drain whatever the turn produces.
}
})().catch(() => undefined);
return { started: start.started };
},
cleanup: async () => {
// Release any turn still held open, then close. The drain is deliberately not
@@ -210,8 +207,8 @@ test("waiting for a run start outlasts the slowest provider startup budget", asy
vi.useFakeTimers();
try {
const { started } = await scenario.startRun();
const wait = waitForAgentRunStartWithTimeout(scenario.agentManager, scenario.agentId, started);
await scenario.startRun();
const wait = waitForAgentRunStartWithTimeout(scenario.agentManager, scenario.agentId);
let settled = false;
const markSettled = () => {
settled = true;
@@ -236,8 +233,8 @@ test("waiting for a run start still gives up at the run start budget", async ()
vi.useFakeTimers();
try {
const { started } = await scenario.startRun();
const wait = waitForAgentRunStartWithTimeout(scenario.agentManager, scenario.agentId, started);
await scenario.startRun();
const wait = waitForAgentRunStartWithTimeout(scenario.agentManager, scenario.agentId);
const rejection = expect(wait).rejects.toThrow(
"codex run did not start within 60 seconds (phase: run start)",
);
@@ -3,7 +3,6 @@ import type { Logger } from "pino";
import type { AgentPromptInput, AgentRunOptions } from "./agent-sdk-types.js";
import type { AgentManager, ManagedAgent } from "./agent-manager.js";
import { ForegroundPromptStart } from "./agent-run-state.js";
import type { AgentStorage } from "./agent-storage.js";
import { ensureAgentLoaded } from "./agent-loading.js";
import { isStaleProviderSessionError } from "./stale-provider-session-error.js";
@@ -24,10 +23,7 @@ export type AgentRunController = Pick<
reloadAgentSession(agentId: string): Promise<unknown>;
};
export class AgentTurnBusyError extends Error {}
export interface StartAgentRunOptions {
idleOnly?: boolean;
/** Called after selecting the run, before consuming its events. */
onDispatch?: (disposition: PromptDispatchDisposition) => void;
replaceRunning?: boolean;
@@ -39,17 +35,11 @@ export interface StartAgentRunOptions {
export type PromptDispatchDisposition = "out_of_band" | "steered" | "turn_started";
/** A dispatched prompt. A started turn carries its sender's start outcome. */
export type PromptDispatchResult =
| { disposition: "turn_started"; started: Promise<void> }
| { disposition: Exclude<PromptDispatchDisposition, "turn_started"> };
async function steerOrReplaceActiveRun(
agentManager: AgentRunController,
agentId: string,
prompt: AgentPromptInput,
options: StartAgentRunOptions | undefined,
promptStart: ForegroundPromptStart,
): Promise<
| { disposition: "steered" }
| {
@@ -64,12 +54,7 @@ async function steerOrReplaceActiveRun(
const steerOptions = options.clearPendingPermissions
? { ...options.runOptions, clearPendingPermissions: true }
: options.runOptions;
const result = await agentManager.steerOrReplaceActiveTurn(
agentId,
prompt,
steerOptions,
promptStart,
);
const result = await agentManager.steerOrReplaceActiveTurn(agentId, prompt, steerOptions);
if (result.status === "steered") {
return { disposition: "steered" };
}
@@ -84,15 +69,14 @@ async function startOrReplaceRun(
agentId: string,
prompt: AgentPromptInput,
options: StartAgentRunOptions | undefined,
promptStart: ForegroundPromptStart,
): Promise<{
iterator: AsyncGenerator<import("./agent-sdk-types.js").AgentStreamEvent>;
replaced: boolean;
}> {
const replaced = Boolean(options?.replaceRunning && agentManager.hasInFlightRun(agentId));
const iterator = replaced
? await agentManager.replaceAgentRun(agentId, prompt, options?.runOptions, promptStart)
: agentManager.streamAgent(agentId, prompt, options?.runOptions, promptStart);
? await agentManager.replaceAgentRun(agentId, prompt, options?.runOptions)
: agentManager.streamAgent(agentId, prompt, options?.runOptions);
return { iterator, replaced };
}
@@ -110,7 +94,7 @@ export async function startAgentRun(
prompt: AgentPromptInput,
logger: Logger,
options?: StartAgentRunOptions,
): Promise<PromptDispatchResult> {
): Promise<{ disposition: PromptDispatchDisposition }> {
const snapshot = agentManager.getAgent(agentId);
logger.trace(
{
@@ -131,25 +115,16 @@ export async function startAgentRun(
options?.onDispatch?.("out_of_band");
return { disposition: "out_of_band" };
}
const promptStart = new ForegroundPromptStart(agentId);
try {
try {
await agentManager.reloadStalePluginSession(agentId);
return await startAgentRunInner(agentManager, agentId, prompt, logger, options, promptStart);
} catch (error) {
if (!isStaleProviderSessionError(error)) throw error;
logger.info(
{ agentId, err: error },
"Provider session went stale; reopening from persistence",
);
// The live session belongs to a retired plugin runtime. Reload swaps in a
// fresh session on the current runtime while preserving history and labels.
await agentManager.reloadAgentSession(agentId);
return await startAgentRunInner(agentManager, agentId, prompt, logger, options, promptStart);
}
await agentManager.reloadStalePluginSession(agentId);
return await startAgentRunInner(agentManager, agentId, prompt, logger, options);
} catch (error) {
promptStart.end();
throw error;
if (!isStaleProviderSessionError(error)) throw error;
logger.info({ agentId, err: error }, "Provider session went stale; reopening from persistence");
// The live session belongs to a retired plugin runtime. Reload swaps in a
// fresh session on the current runtime while preserving history and labels.
await agentManager.reloadAgentSession(agentId);
return await startAgentRunInner(agentManager, agentId, prompt, logger, options);
}
}
@@ -158,23 +133,17 @@ async function startAgentRunInner(
agentId: string,
prompt: AgentPromptInput,
logger: Logger,
options: StartAgentRunOptions | undefined,
promptStart: ForegroundPromptStart,
): Promise<PromptDispatchResult> {
options?: StartAgentRunOptions,
): Promise<{ disposition: PromptDispatchDisposition }> {
const snapshot = agentManager.getAgent(agentId);
const steered = options?.idleOnly
? null
: await steerOrReplaceActiveRun(agentManager, agentId, prompt, options, promptStart);
if (options?.idleOnly && agentManager.hasInFlightRun(agentId)) {
throw new AgentTurnBusyError(`Agent ${agentId} is running`);
}
const steered = await steerOrReplaceActiveRun(agentManager, agentId, prompt, options);
if (steered?.disposition === "steered") {
options?.onDispatch?.("steered");
return steered;
}
const { iterator, replaced } = steered
? { iterator: steered.iterator, replaced: true }
: await startOrReplaceRun(agentManager, agentId, prompt, options, promptStart);
: await startOrReplaceRun(agentManager, agentId, prompt, options);
logger.trace(
{
agentId,
@@ -196,7 +165,7 @@ async function startAgentRunInner(
"Provider session went stale; reopening from persistence",
);
await agentManager.reloadAgentSession(agentId);
const retry = await startOrReplaceRun(agentManager, agentId, prompt, options, promptStart);
const retry = await startOrReplaceRun(agentManager, agentId, prompt, options);
await drainAgentRunIterator(retry.iterator);
}
logger.trace(
@@ -218,11 +187,9 @@ async function startAgentRunInner(
"agent.session.iterator.error",
);
logger.error({ err: error, agentId }, "Agent stream failed");
} finally {
promptStart.end();
}
})();
return { disposition: "turn_started", started: promptStart.started };
return { disposition: "turn_started" };
}
/**
@@ -243,7 +210,6 @@ export async function unarchiveAgentState(
}
export interface SendPromptToAgentParams {
idleOnly?: boolean;
/** Awaited after the agent is loaded and its mode is set, before the prompt is handed to a run. */
beforeDispatch?: () => Promise<void>;
onDispatch?: StartAgentRunOptions["onDispatch"];
@@ -295,9 +261,8 @@ export interface StartCreatedAgentInitialPromptParams {
const AGENT_RUN_START_TIMEOUT_MS = 60_000;
export async function waitForAgentRunStartWithTimeout(
agentManager: Pick<AgentManager, "getAgent">,
agentManager: AgentManager,
agentId: string,
started: Promise<void>,
signal?: AbortSignal,
): Promise<void> {
const provider = agentManager.getAgent(agentId)?.provider ?? "provider";
@@ -312,28 +277,15 @@ export async function waitForAgentRunStartWithTimeout(
AGENT_RUN_START_TIMEOUT_MS,
);
const abortSignal = signal ? AbortSignal.any([startAbort.signal, signal]) : startAbort.signal;
let onAbort: (() => void) | null = null;
const aborted = new Promise<never>((_, reject) => {
onAbort = () => reject(createStartAbortError(abortSignal.reason));
if (abortSignal.aborted) onAbort();
else abortSignal.addEventListener("abort", onAbort, { once: true });
});
try {
await Promise.race([started, aborted]);
await agentManager.waitForAgentRunStart(agentId, {
signal: signal ? AbortSignal.any([startAbort.signal, signal]) : startAbort.signal,
});
} finally {
clearTimeout(startTimeout);
if (onAbort) abortSignal.removeEventListener("abort", onAbort);
}
}
function createStartAbortError(reason: unknown): Error {
let message = "wait_for_agent_start aborted";
if (typeof reason === "string") message = reason;
else if (reason instanceof Error) message = reason.message;
return Object.assign(new Error(message), { name: "AbortError" });
}
async function resolvePromptSource(
source: AgentPromptSource | undefined,
manager: Pick<AgentManager, "getAgent">,
@@ -359,7 +311,7 @@ async function resolvePromptSource(
*/
export async function sendPromptToAgent(
params: SendPromptToAgentParams,
): Promise<PromptDispatchResult> {
): Promise<{ disposition: PromptDispatchDisposition }> {
const source = await resolvePromptSource(params.source, params.agentManager, params.agentStorage);
const delivery = prepareAgentMessage(params.prompt, source, params.messageId);
return sendPreparedPromptToAgent({
@@ -374,14 +326,14 @@ export async function sendPromptToAgent(
/** Dispatch daemon-prepared context without reclassifying it as human input. */
export async function sendPreparedPromptToAgent(
params: Omit<SendPromptToAgentParams, "source" | "messageId">,
): Promise<PromptDispatchResult> {
): Promise<{ disposition: PromptDispatchDisposition }> {
const unarchive = params.unarchive ?? true;
const record = await params.agentStorage.get(params.agentId);
let archivedAtToRestore: string | null = null;
if (record?.archivedAt) {
if (!unarchive) {
return { disposition: "turn_started", started: Promise.resolve() };
return { disposition: "turn_started" };
}
if (await unarchiveAgentState(params.agentStorage, params.agentManager, params.agentId)) {
archivedAtToRestore = record.archivedAt;
@@ -403,17 +355,13 @@ export async function sendPreparedPromptToAgent(
throw error;
}
if (params.idleOnly && params.agentManager.hasInFlightRun(params.agentId)) {
throw new AgentTurnBusyError(`Agent ${params.agentId} is running`);
}
if (params.sessionMode) {
await params.agentManager.setAgentMode(params.agentId, params.sessionMode);
}
await params.beforeDispatch?.();
return await startAgentRun(params.agentManager, params.agentId, params.prompt, params.logger, {
replaceRunning: !params.idleOnly,
idleOnly: params.idleOnly,
replaceRunning: true,
onDispatch: params.onDispatch,
activeTurnBehavior: params.activeTurnBehavior,
clearPendingPermissions: params.clearPendingPermissions,
@@ -447,11 +395,7 @@ export async function startCreatedAgentInitialPrompt(
);
if (dispatchResult.disposition === "turn_started") {
await waitForAgentRunStartWithTimeout(
params.agentManager,
params.agentId,
dispatchResult.started,
);
await waitForAgentRunStartWithTimeout(params.agentManager, params.agentId);
}
const refreshedSnapshot = params.agentManager.getAgent(params.agentId) ?? params.snapshot ?? null;
@@ -13,7 +13,7 @@ export interface ForegroundTurnWaiter {
type ForegroundRunStart =
| { status: "pending" }
| { status: "started"; turnId: string }
| { status: "failed"; error: string; stale?: true };
| { status: "failed"; error: string };
export interface PendingForegroundRun {
token: string;
@@ -343,59 +343,3 @@ function settleTrackedRun(run: TrackedAgentRun): void {
run.settled = true;
run.resolveSettled();
}
/**
* Follows one sender's prompt to the foreground run that starts it. Each run created for the
* prompt, including a stale-session retry, is bound here, so `started` settles for this
* sender's prompt and never for another run the agent tracks.
*/
export class ForegroundPromptStart {
readonly started: Promise<void>;
private resolveStarted!: () => void;
private rejectStarted!: (error: Error) => void;
private run: PendingForegroundRun | null = null;
private done = false;
constructor(private readonly agentId: string) {
this.started = new Promise<void>((resolve, reject) => {
this.resolveStarted = resolve;
this.rejectStarted = reject;
});
// Steered and fire-and-forget dispatches never wait on the start.
this.started.catch(() => undefined);
}
/** A run was created for this prompt. */
bind(run: PendingForegroundRun): void {
this.run = run;
void Promise.race([run.turnStartedPromise, run.settledPromise]).then(() =>
this.settle(run, { ended: false }),
);
}
/** The prompt's dispatch is over; no further run will be created for it. */
end(): void {
this.settle(this.run, { ended: true });
}
private settle(run: PendingForegroundRun | null, { ended }: { ended: boolean }): void {
if (this.done || run !== this.run) return;
if (run?.start.status === "started") {
this.done = true;
this.resolveStarted();
return;
}
// A stale-session failure is retried with a new run; wait for it unless dispatch ended.
if (run?.start.status === "failed" && run.start.stale && !ended) return;
this.done = true;
this.rejectStarted(new Error(this.describeUnstarted(run)));
}
private describeUnstarted(run: PendingForegroundRun | null): string {
if (run?.start.status === "failed") return run.start.error;
if (run?.settled) {
return `Agent ${this.agentId} run was canceled before its turn started; its prompt was not delivered`;
}
return `Agent ${this.agentId} run finished before starting`;
}
}
@@ -528,14 +528,6 @@ export type AgentPermissionResponse =
interrupt?: boolean;
};
/** A requested turn was canceled before the provider accepted it. */
export class AgentTurnStartCanceledError extends Error {
constructor() {
super("Turn was canceled before starting");
this.name = "AgentTurnStartCanceledError";
}
}
export interface AgentRunResult {
sessionId: string;
finalText: string;
@@ -629,8 +621,6 @@ export interface AgentSessionConfig {
* persisted into agent config so daemon setting changes apply cleanly.
*/
daemonAppendSystemPrompt?: string;
/** Plugin instructions for this launch; never persisted. */
pluginAppendSystemPrompt?: string[];
modeId?: string;
model?: string;
thinkingOptionId?: string;
@@ -646,8 +636,6 @@ export interface AgentSessionConfig {
}
export interface AgentLaunchContext {
/** Launch-only instructions contributed by plugins. */
appendSystemPrompt?: string[];
/** Launch-only plugin MCP servers and their owners; never persisted. */
mcpServers?: Record<string, McpServerConfig>;
mcpServerOwners?: Record<string, string>;
@@ -700,8 +688,6 @@ export interface AgentUsageSession {
}
export interface AgentSession {
/** Persist the session's current handle immediately after an interactive resume. */
readonly persistenceUpdatedOnResume?: boolean;
usageSession?(): AgentUsageSession | null;
readonly provider: AgentProvider;
readonly id: string | null;
@@ -10,7 +10,6 @@ import { AgentManager } from "../agent-manager.js";
import { AgentStorage } from "../agent-storage.js";
import type { CreatePaseoWorktreeWorkflowResult } from "../../worktree-session.js";
import { createAgentCommand } from "./create.js";
import { ForegroundPromptStart } from "../agent-run-state.js";
import type { ManagedAgent } from "../agent-manager.js";
const logger = createTestLogger();
@@ -90,12 +89,9 @@ test("session create forwards clientMessageId to the initial prompt run options"
firstAgentContext: { attachments: [] },
});
expect(streamAgent).toHaveBeenCalledWith(
"agent-1",
"hello from create",
{ clientMessageId: "msg-create-1" },
expect.any(ForegroundPromptStart),
);
expect(streamAgent).toHaveBeenCalledWith("agent-1", "hello from create", {
clientMessageId: "msg-create-1",
});
});
test("session create validates the requested mode against the provider's modes", async () => {
@@ -498,26 +498,3 @@ test("finish recovery protects callers before durable intent has loaded", async
expect(recovered.hasPendingForCaller("parent")).toBe(true);
expect(recovered.hasPendingForCaller("unrelated")).toBe(false);
});
test("an undispatched follow-up does not block the running child's permission notification", async () => {
const state = await scenario();
await state.service.register(intent);
await until(() => state.observation.waits.length === 1);
await state.service.register(intent, true);
const result = outcome("running");
result.status = "permission";
result.final!.pendingPermissions = [
{
id: "approval",
provider: "codex",
name: "Bash",
kind: "tool",
input: { command: "run tests" },
} as NonNullable<typeof result.final>["pendingPermissions"][number],
];
state.observation.waits[0]!.result.resolve(result);
await until(() => state.delivery.prompts.length === 1);
expect(state.delivery.prompts[0]).toContain("needs permission");
expect(state.delivery.prompts[0]).toContain("approval");
expect(await state.store.list()).toHaveLength(2);
});
@@ -267,9 +267,7 @@ export function createFinishSubscriptions(deps: Dependencies): FinishSubscriptio
continue;
}
if (signal.aborted) return;
// A queued follow-up cannot start until the current permission is answered.
// Its pending registration must not hold the running turn's checkpoint.
if (pending.status !== "permission" || watch.pending) await decisions(group);
await decisions(group);
if (signal.aborted) return;
if (await suppressed(record, pending)) {
await remove(watch);
@@ -298,7 +298,7 @@ export function createHostResolver(input: {
status: agent.status,
guidance:
receipt.deliveryStatus === "queued"
? "Queued for delivery after two quiet seconds and the current turn ends, unless interrupt was requested. You will get notified when the prompted agent finishes, errors, or needs permission unless notifyOnFinish is false."
? "Queued for delivery after two quiet seconds. You will get notified when the prompted agent finishes, errors, or needs permission unless notifyOnFinish is false."
: "Dispatch acknowledged. Observe completion using get_agent_status/get_agent_activity or SDK/RPC subscriptions and wait APIs.",
});
},
@@ -1,4 +1,3 @@
import { AgentRunState, ForegroundPromptStart } from "./agent-run-state.js";
import {
createFinishSubscriptions,
createFinishObservation,
@@ -173,12 +172,11 @@ function registeredTool(
async function invokeToolWithParsedInput(
tool: RegisteredMcpToolWithHandler,
input: Record<string, unknown>,
awaitDispatch = true,
) {
const parsed = await tool.inputSchema.safeParseAsync(input);
expect(parsed.success).toBe(true);
const response = await tool.handler(parsed.data);
if (awaitDispatch && response.structuredContent.deliveryStatus === "queued") {
if (response.structuredContent.deliveryStatus === "queued") {
await toolDeliveries
.get(tool)!
.waitForDispatch(input.agentId as string, new AbortController().signal);
@@ -276,19 +274,11 @@ function buildAgentManagerSpies() {
effectiveOptionsFor: (_provider: string, own?: Record<string, unknown>) => own ?? {},
reloadStalePluginSession: async () => {},
hasInFlightRun: vi.fn().mockReturnValue(false),
hasPendingPermissions: () => false,
steerOrReplaceActiveTurn: async () => ({ status: "inactive" as const }),
tryRunOutOfBand: vi.fn().mockReturnValue(false),
subscribe: vi.fn().mockReturnValue(() => {}),
streamAgent: vi.fn(
(agentId: string, _prompt: unknown, _options: unknown, start?: ForegroundPromptStart) => {
const runs = new AgentRunState();
const run = runs.createPendingRun(agentId);
runs.settleForegroundStart(run, { status: "started", turnId: `${agentId}-turn` });
start?.bind(run);
return (async function* noop() {})();
},
),
streamAgent: vi.fn(() => (async function* noop() {})()),
waitForAgentRunStart: vi.fn().mockResolvedValue(undefined),
respondToPermission: vi.fn(),
cancelAgentRun: vi.fn(),
getPendingPermissions: vi.fn(),
@@ -633,12 +623,6 @@ class FakeBrowserToolsBroker {
}
class BoundaryAgentManagerFake {
subscribe() {
return () => {};
}
hasPendingPermissions() {
return false;
}
public getPluginTools(): [] {
return [];
}
@@ -893,9 +877,8 @@ function createPaseoWorktreeForMcpTest(options: {
async function createAgentMcpServer(
options: Parameters<typeof createAgentMcpServerWithDependencies>[0],
subscriptionStore?: FinishSubscriptionStore,
schedule?: (delayMs: number, callback: () => void) => () => void,
) {
const messages = createTestAgentMessages({ ...options, schedule });
const messages = createTestAgentMessages(options);
const records = new Map<string, FinishSubscription>();
const subscriptions = createFinishSubscriptions({
store: subscriptionStore ?? {
@@ -3694,15 +3677,15 @@ class HeldTurnAgentClient implements AgentClient {
describe("send_agent_prompt MCP tool", () => {
it.each([
{ agentScoped: true, behavior: undefined, available: true },
{ agentScoped: true, behavior: "interrupt", available: true },
{ agentScoped: true, behavior: "steer", available: true },
{ agentScoped: false, behavior: undefined, available: true },
{ agentScoped: false, behavior: "steer", available: true },
{ agentScoped: true, behavior: undefined, available: false },
{ agentScoped: true, behavior: undefined, available: true, steered: true },
{ agentScoped: true, behavior: "interrupt", available: true, steered: false },
{ agentScoped: true, behavior: "steer", available: true, steered: true },
{ agentScoped: false, behavior: undefined, available: true, steered: false },
{ agentScoped: false, behavior: "steer", available: true, steered: true },
{ agentScoped: true, behavior: undefined, available: false, steered: false },
] as const)(
"dispatches behavior $behavior for agent-scoped=$agentScoped, steering available=$available",
async ({ agentScoped, behavior, available }) => {
async ({ agentScoped, behavior, available, steered }) => {
const workdir = await mkdtemp(join(tmpdir(), "mcp-send-behavior-"));
const storage = new AgentStorage(join(workdir, "agents"), logger);
const client = new HeldTurnAgentClient("codex", true, {
@@ -3734,33 +3717,18 @@ describe("send_agent_prompt MCP tool", () => {
notifyOnFinish: false,
});
const originalTurn = manager.getAgent(child.id)!.activeTurnId;
const queued = agentScoped && behavior !== "interrupt";
const steered = !agentScoped && behavior === "steer";
const response = await invokeToolWithParsedInput(
tool,
{
agentId: child.id,
prompt: "New message",
notifyOnFinish: false,
...(behavior ? { activeTurnBehavior: behavior } : {}),
},
!queued,
);
const response = await invokeToolWithParsedInput(tool, {
agentId: child.id,
prompt: "New message",
notifyOnFinish: false,
...(behavior ? { activeTurnBehavior: behavior } : {}),
});
expect(response.structuredContent).toMatchObject({
success: true,
...(agentScoped
? { deliveryStatus: "queued" }
: { disposition: steered ? "steered" : "turn_started" }),
});
if (queued) {
expect(client.sessions[1]!.prompts).toHaveLength(1);
expect(client.sessions[1]!.steeredPrompts).toEqual([]);
expect(manager.getAgent(child.id)!.activeTurnId).toBe(originalTurn);
client.sessions[1]!.finishTurn();
await serverDeliveries
.get(server)!
.waitForDispatch(child.id, new AbortController().signal);
}
expect(client.sessions[1]!.prompts).toHaveLength(steered ? 1 : 2);
expect(client.sessions[1]!.steeredPrompts).toHaveLength(steered ? 1 : 0);
expect(manager.getAgent(child.id)!.activeTurnId === originalTurn).toBe(steered);
@@ -3772,16 +3740,18 @@ describe("send_agent_prompt MCP tool", () => {
it.each([
{ rejected: false, priorNotification: false },
{ rejected: false, priorNotification: true },
{ rejected: true, priorNotification: false },
{ rejected: true, priorNotification: true },
{ rejected: false, priorNotification: true },
])(
"keeps completion tied to queued dispatch acknowledgement (rejected: $rejected, prior notification: $priorNotification)",
"buffers completion until steer acknowledgement (rejected: $rejected, prior notification: $priorNotification)",
async ({ rejected, priorNotification }) => {
const workdir = await mkdtemp(join(tmpdir(), "mcp-queued-ack-"));
const workdir = await mkdtemp(join(tmpdir(), "mcp-send-behavior-"));
const storage = new AgentStorage(join(workdir, "agents"), logger);
const options: HeldTurnOptions = {};
const client = new HeldTurnAgentClient("codex", true, options);
const client = new HeldTurnAgentClient("codex", true, {
steerResult: "accepted",
finishDuringSteer: true,
rejectSteer: rejected,
});
const manager = new AgentManager({ clients: { codex: client }, registry: storage, logger });
let mcpClient: Client | undefined;
try {
@@ -3803,47 +3773,104 @@ describe("send_agent_prompt MCP tool", () => {
logger,
});
mcpClient = await connectInMemoryMcpClient(server);
await sendMcpAndAwaitDispatch(mcpClient, server, {
const send = (input: Record<string, unknown>) =>
sendMcpAndAwaitDispatch(mcpClient!, server, input);
await send({
agentId: child.id,
prompt: "Original work",
notifyOnFinish: priorNotification,
});
const session = client.sessions[1]!;
const release = session.holdTurnStart();
options.finishTurnsDuringStart = true;
if (rejected) session.rejectNextTurnStart(new Error("Start rejected"));
const response = await mcpClient.callTool({
name: "send_agent_prompt",
arguments: { agentId: child.id, prompt: "New message", notifyOnFinish: true },
const sending = send({
agentId: child.id,
prompt: "New message",
notifyOnFinish: true,
});
expect(response.structuredContent).toMatchObject({
success: true,
deliveryStatus: "queued",
});
const dispatch = serverDeliveries
.get(server)!
.waitForDispatch(child.id, new AbortController().signal);
const rejectedDispatch = rejected
? expect(dispatch).rejects.toThrow("Start rejected")
: null;
expect(client.sessions[0]!.prompts).toHaveLength(0);
session.finishTurn();
await vi.waitFor(() => expect(session.prompts).toHaveLength(2));
expect(client.sessions[0]!.prompts).toHaveLength(0);
release();
if (rejectedDispatch) await rejectedDispatch;
else await dispatch;
if (!rejected || priorNotification) {
await vi.waitFor(() => expect(client.sessions[0]!.prompts).toHaveLength(1), {
timeout: 5000,
});
expect(parseAgentMessage(client.sessions[0]!.prompts[0])).toMatchObject({
source: { kind: "agent-notification", agentId: child.id, event: "finished" },
});
} else {
await serverSubscriptions.get(server)!.close();
if (rejected) {
await expect(sending).rejects.toThrow("Steer rejected");
// Flush asynchronous notification work before checking that a rejected
// dispatch did not notify. Then prove a later successful send still can.
await new Promise((resolve) => setTimeout(resolve, 50));
expect(client.sessions[0]!.prompts).toHaveLength(0);
await send({
agentId: child.id,
prompt: "Retry after rejection",
});
client.sessions[1]!.finishTurn();
} else {
const response = await sending;
expect(response.structuredContent).toMatchObject({
success: true,
deliveryStatus: "queued",
});
}
await vi.waitFor(() => expect(client.sessions[0]!.prompts).toHaveLength(1));
expect(parseAgentMessage(client.sessions[0]!.prompts[0])).toMatchObject({
source: { kind: "agent-notification", agentId: child.id, event: "finished" },
});
} finally {
await mcpClient?.close();
await removeAgentStateDir(manager, storage, workdir);
}
},
);
it.each([false, true])(
"preserves the original notification after rejection (completion during send: %s)",
async (finishDuringSteer) => {
const workdir = await mkdtemp(join(tmpdir(), "mcp-send-behavior-"));
const storage = new AgentStorage(join(workdir, "agents"), logger);
const client = new HeldTurnAgentClient("codex", true, {
steerResult: "accepted",
finishDuringSteer,
rejectSteer: true,
});
const manager = new AgentManager({ clients: { codex: client }, registry: storage, logger });
let mcpClient: Client | undefined;
try {
const parent = await manager.createAgent(
{ provider: "codex", cwd: existingCwd },
undefined,
{
workspaceId: "wks_parent",
},
);
const child = await manager.createAgent(
{ provider: "codex", cwd: existingCwd },
undefined,
{
workspaceId: "wks_parent",
},
);
const server = await createAgentMcpServer({
agentManager: manager,
agentStorage: storage,
callerAgentId: parent.id,
providerSnapshotManager: createOpenCodeManager().manager,
logger,
});
mcpClient = await connectInMemoryMcpClient(server);
const send = (input: Record<string, unknown>) =>
sendMcpAndAwaitDispatch(mcpClient!, server, input);
await send({
agentId: child.id,
prompt: "Original work",
notifyOnFinish: true,
});
const sending = send({
agentId: child.id,
prompt: "New message",
notifyOnFinish: true,
});
await expect(sending).rejects.toThrow("Steer rejected");
if (!finishDuringSteer) {
await new Promise((resolve) => setTimeout(resolve, 50));
expect(client.sessions[0]!.prompts).toHaveLength(0);
client.sessions[1]!.finishTurn();
}
await vi.waitFor(() => expect(client.sessions[0]!.prompts).toHaveLength(1));
expect(parseAgentMessage(client.sessions[0]!.prompts[0])).toMatchObject({
source: { kind: "agent-notification", agentId: child.id, event: "finished" },
});
} finally {
await mcpClient?.close();
await removeAgentStateDir(manager, storage, workdir);
@@ -3985,7 +4012,7 @@ describe("send_agent_prompt MCP tool", () => {
const response = await tool.handler(parsed.data as Record<string, unknown>);
expect(response.structuredContent).toMatchObject({ deliveryStatus: "queued" });
expect(serverSubscriptionRecords.get(server)!.size).toBe(1);
expect(spies.agentManager.subscribe).not.toHaveBeenCalled();
await serverDeliveries
.get(server)!
.waitForDispatch("child-agent", new AbortController().signal);
@@ -4026,7 +4053,7 @@ describe("send_agent_prompt MCP tool", () => {
await tool.handler(parsed.data as Record<string, unknown>);
expect(serverSubscriptionRecords.get(server)!.size).toBe(0);
expect(spies.agentManager.subscribe).not.toHaveBeenCalled();
expect(spies.agentManager.waitForAgentEvent).not.toHaveBeenCalled();
});
@@ -4069,7 +4096,7 @@ describe("send_agent_prompt MCP tool", () => {
notifyOnFinish: false,
});
expect(serverSubscriptionRecords.get(server)!.size).toBe(0);
expect(spies.agentManager.subscribe).not.toHaveBeenCalled();
expect(spies.agentManager.waitForAgentEvent).not.toHaveBeenCalled();
});
@@ -4193,15 +4220,11 @@ describe("send_agent_prompt MCP tool", () => {
notifyOnFinish: false,
});
if (scenario !== "startup_failure") {
const response = await invokeToolWithParsedInput(
tool,
{
agentId: child.id,
prompt: "/side-command",
activeTurnBehavior: scenario === "out_of_band_interrupt" ? "interrupt" : "steer",
},
scenario !== "out_of_band",
);
const response = await invokeToolWithParsedInput(tool, {
agentId: child.id,
prompt: "/side-command",
activeTurnBehavior: scenario === "out_of_band_interrupt" ? "interrupt" : "steer",
});
expect(response.structuredContent).toMatchObject({
success: true,
deliveryStatus: "queued",
@@ -4213,9 +4236,6 @@ describe("send_agent_prompt MCP tool", () => {
});
expect(parentClient.sessions[0]!.prompts).toHaveLength(0);
childClient.sessions[0]!.finishTurn("Ongoing task done");
await serverDeliveries
.get(server)!
.waitForDispatch(child.id, new AbortController().signal);
await vi.waitFor(() => {
expect(parentClient.sessions[0]!.prompts).toHaveLength(1);
expect(parentClient.sessions[0]!.prompts[0]).toContain("finished.");
@@ -4223,11 +4243,7 @@ describe("send_agent_prompt MCP tool", () => {
} else {
childClient.sessions[0]!.rejectNextTurnStart(new Error("Requested turn could not start"));
await expect(
invokeToolWithParsedInput(tool, {
agentId: child.id,
prompt: "Replacement task",
activeTurnBehavior: "interrupt",
}),
invokeToolWithParsedInput(tool, { agentId: child.id, prompt: "Replacement task" }),
).rejects.toThrow("Requested turn could not start");
// A later real turn must not inherit a subscription from the rejected dispatch.
await invokeToolWithParsedInput(tool, {
@@ -4338,7 +4354,6 @@ describe("send_agent_prompt MCP tool", () => {
const sent = await invokeToolWithParsedInput(registeredTool(server, "send_agent_prompt"), {
agentId: childId,
prompt: "Stop and reply instead",
activeTurnBehavior: "interrupt",
});
expect(sent.structuredContent).toMatchObject({
success: true,
@@ -4502,7 +4517,7 @@ describe("send_agent_prompt MCP tool to an OMP child", () => {
const logger = createTestLogger();
const existingCwd = process.cwd();
async function setupOmpChild(schedule?: (delayMs: number, callback: () => void) => () => void) {
async function setupOmpChild() {
const workdir = await mkdtemp(join(tmpdir(), "mcp-omp-child-"));
const storage = new AgentStorage(join(workdir, "agents"), logger);
const parentClient = new HeldTurnAgentClient("claude", false);
@@ -4530,17 +4545,13 @@ describe("send_agent_prompt MCP tool to an OMP child", () => {
undefined,
{ workspaceId: "wks_parent" },
);
const server = await createAgentMcpServer(
{
agentManager,
agentStorage: storage,
callerAgentId: parent.id,
providerSnapshotManager: createOpenCodeManager().manager,
logger,
},
undefined,
schedule,
);
const server = await createAgentMcpServer({
agentManager,
agentStorage: storage,
callerAgentId: parent.id,
providerSnapshotManager: createOpenCodeManager().manager,
logger,
});
return {
agentManager,
storage,
@@ -4570,63 +4581,37 @@ describe("send_agent_prompt MCP tool to an OMP child", () => {
{ command: "follow-up", streamingBehavior: "followUp" },
{ command: "steer", streamingBehavior: "steer" },
] as const)(
"delivers /$command to a running OMP child while ordinary messages in the same quiet window wait",
"delivers /$command into a turn OMP started on its own, without aborting it",
async ({ command, streamingBehavior }) => {
let flush!: () => void;
const { agentManager, storage, workdir, ompSession, childId, tool } = await setupOmpChild(
(_delay, callback) => {
flush = callback;
return () => {};
},
);
const { agentManager, storage, workdir, parentClient, ompSession, childId, tool } =
await setupOmpChild();
try {
ompSession.beginTurn();
ompSession.streamAssistantText("background job finished, working on it");
await vi.waitFor(() => {
expect(agentManager.getAgent(childId)?.activeTurnId).toMatch(/^autonomous-/);
});
const activeTurnId = agentManager.getAgent(childId)?.activeTurnId;
const delivery = toolDeliveries.get(tool)!;
let ordinaryBeforeDispatch = 0;
const ordinary = delivery.enqueue({
recipientId: childId,
source: { kind: "agent-message", agentId: "parent" },
prompt: "ordinary follow-up",
beforeDispatch: () => {
ordinaryBeforeDispatch++;
},
const response = await invokeToolWithParsedInput(tool, {
agentId: childId,
prompt: `/${command} then summarize the logs`,
});
const response = await invokeToolWithParsedInput(
tool,
{
agentId: childId,
prompt: `/${command} then summarize the logs`,
},
false,
);
flush();
await vi.waitFor(() => {
expect(ompSession.prompts).toEqual([
{ message: "then summarize the logs", imageCount: 0, streamingBehavior },
]);
});
expect(ordinaryBeforeDispatch).toBe(0);
expect(agentManager.getAgent(childId)?.activeTurnId).toBe(activeTurnId);
expect(response.structuredContent).toMatchObject({
success: true,
deliveryStatus: "queued",
status: "running",
});
await vi.waitFor(() => {
expect(ompSession.prompts).toEqual([
{ message: "then summarize the logs", imageCount: 0, streamingBehavior },
]);
});
expect(ompSession.abortRequested).toBe(false);
expect(agentManager.getAgent(childId)?.lifecycle).toBe("running");
ompSession.finishTurn();
await ordinary.dispatched;
expect(ordinaryBeforeDispatch).toBe(1);
expect(ompSession.prompts).toHaveLength(2);
expect(ompSession.prompts[1]!.message).toContain("ordinary follow-up");
ompSession.beginTurn();
ompSession.finishTurn();
await expectOneFinishNotification(agentManager, parentClient, childId);
} finally {
await removeAgentStateDir(agentManager, storage, workdir);
}
@@ -1949,11 +1949,7 @@ function mapSessionConfig(
return {
cwd: config.cwd,
env: createProviderEnv({ baseEnv: {}, overlays: [launchContext?.env] }),
systemPrompt: combineSystemPrompts(
config.systemPrompt,
config.daemonAppendSystemPrompt,
...(config.pluginAppendSystemPrompt ?? []),
),
systemPrompt: combineSystemPrompts(config.systemPrompt, config.daemonAppendSystemPrompt),
mcpServers: { ...config.mcpServers },
toolPolicy: config.toolPolicy
? { preapproved: config.toolPolicy.preapproved.map((grant) => ({ ...grant })) }
@@ -1972,9 +1968,8 @@ function mapSessionConfig(
function combineSystemPrompts(
systemPrompt: string | undefined,
daemonPrompt: string | undefined,
...pluginPrompts: string[]
): string | undefined {
const parts = [systemPrompt, daemonPrompt, ...pluginPrompts].filter(
const parts = [systemPrompt, daemonPrompt].filter(
(value): value is string => typeof value === "string" && value.trim().length > 0,
);
return parts.length > 0 ? parts.join("\n\n") : undefined;
@@ -448,9 +448,6 @@ export function wrapSessionProvider(provider: AgentProvider, inner: AgentSession
get initialTimeline() {
return inner.initialTimeline;
},
get persistenceUpdatedOnResume() {
return inner.persistenceUpdatedOnResume;
},
get controls() {
return inner.controls;
},
@@ -153,56 +153,6 @@ describe("Claude SDK env", () => {
}
});
test("resume uses current plugin instructions and excludes them from persistence", async () => {
const prompts: unknown[] = [];
const queryFactory = ({ options }: ClaudeQueryInput) => {
prompts.push(options.systemPrompt);
return createQueryMock([
{
type: "system",
subtype: "init",
session_id: "persisted-session",
permissionMode: "default",
model: "opus",
},
{ type: "assistant", message: { content: "done" } },
{
type: "result",
subtype: "success",
usage: { input_tokens: 1, cache_read_input_tokens: 0, output_tokens: 1 },
total_cost_usd: 0,
},
]);
};
const client = new ClaudeAgentClient({
logger: createTestLogger(),
queryFactory,
resolveBinary: async () => "/test/claude/bin",
});
const first = await client.createSession({
provider: "claude",
cwd: process.cwd(),
pluginAppendSystemPrompt: ["Plugin instructions"],
});
await first.run("first");
const handle = first.describePersistence()!;
expect(handle.metadata).not.toHaveProperty("pluginAppendSystemPrompt");
await first.close();
const resumed = await client.resumeSession(handle, {
cwd: process.cwd(),
pluginAppendSystemPrompt: undefined,
});
try {
await resumed.run("after disable");
expect(prompts).toEqual([
{ type: "preset", preset: "claude_code", append: "Plugin instructions" },
{ type: "preset", preset: "claude_code", append: "" },
]);
} finally {
await resumed.close();
}
});
test("forwards launch-context env through Claude resume env", async () => {
let capturedEnv: Record<string, string | undefined> | undefined;
const launchContext: AgentLaunchContext = {
@@ -3049,11 +3049,7 @@ class ClaudeAgentSession implements AgentSession {
if (!this.claudeSessionId) {
return null;
}
const {
providerOptions: _providerOptions,
pluginAppendSystemPrompt: _pluginAppendSystemPrompt,
...persistedConfig
} = this.config;
const { providerOptions: _providerOptions, ...persistedConfig } = this.config;
this.persistence = {
provider: "claude",
sessionId: this.claudeSessionId,
@@ -3721,11 +3717,7 @@ class ClaudeAgentSession implements AgentSession {
private buildAppendedSystemPrompt(): string {
return (
composeSystemPromptParts(
this.config.systemPrompt,
this.config.daemonAppendSystemPrompt,
...(this.config.pluginAppendSystemPrompt ?? []),
) ?? ""
composeSystemPromptParts(this.config.systemPrompt, this.config.daemonAppendSystemPrompt) ?? ""
);
}
@@ -22,18 +22,6 @@ function isCodexInstalled(): boolean {
}
}
function supportsInstructionSnapshots(): boolean {
try {
const match = execFileSync("codex", ["--version"], { encoding: "utf8" }).match(
/(\d+)\.(\d+)\.(\d+)/,
);
if (!match) return false;
return Number(match[1]) > 0 || Number(match[2]) >= 121;
} catch {
return false;
}
}
function sse(events: unknown[]): string {
return events
.map((event) => {
@@ -145,7 +133,7 @@ async function startMockResponsesServer(sequence: string[]): Promise<{
}> {
const requestBodies: string[] = [];
let index = 0;
const server = createServer({ maxHeaderSize: 1024 * 1024 }, (req, res) => {
const server = createServer((req, res) => {
const chunks: Buffer[] = [];
req.on("data", (chunk) => chunks.push(Buffer.from(chunk)));
req.on("end", () => {
@@ -233,85 +221,6 @@ function waitForEvent<TEvent extends AgentStreamEvent>(params: {
}
describe("Codex app-server provider (local e2e)", () => {
test.runIf(supportsInstructionSnapshots())(
"delivers changed and removed instructions to the model across process restarts",
async () => {
const artifactDir = path.resolve(process.cwd(), "../../.artifacts");
mkdirSync(artifactDir, { recursive: true });
const cwd = mkdtempSync(path.join(artifactDir, "codex-snapshot-cwd-"));
const codexHome = mkdtempSync(path.join(artifactDir, "codex-snapshot-home-"));
const server = await startMockResponsesServer([]);
const client = new CodexAppServerAgentClient(createTestLogger());
const base = { provider: "codex" as const, cwd, modeId: "auto", model: "mock-model" };
const launch = { env: { CODEX_HOME: codexHome } };
const run = async (session: Awaited<ReturnType<typeof client.createSession>>) => {
const finished = waitForEvent({
session,
timeoutMs: 20_000,
label: "turn completion",
predicate: (
event,
): event is Extract<
AgentStreamEvent,
{ type: "turn_completed" | "turn_failed" | "turn_canceled" }
> =>
event.type === "turn_completed" ||
event.type === "turn_failed" ||
event.type === "turn_canceled",
});
await session.startTurn("continue");
const result = await finished;
if (result.type !== "turn_completed") throw new Error(JSON.stringify(result));
const handle = session.describePersistence();
if (!handle) throw new Error("Expected persisted Codex thread");
await session.close();
return handle;
};
try {
writeMockCodexConfig(codexHome, server.url);
let handle = await run(
await client.createSession(
{ ...base, pluginAppendSystemPrompt: ["old snapshot"] },
launch,
),
);
expect(server.requestBodies.at(-1)).toContain("old snapshot");
expect(server.requestBodies.at(-1)).not.toContain("paseo_instruction_snapshot");
handle = await run(
await client.resumeSession(
handle,
{ ...base, pluginAppendSystemPrompt: ["new snapshot"] },
launch,
),
);
expect(server.requestBodies.at(-1)).toContain("new snapshot");
expect(server.requestBodies.at(-1)?.match(/paseo_instruction_snapshot/g)).toHaveLength(2);
handle = await run(
await client.resumeSession(
handle,
{ ...base, pluginAppendSystemPrompt: ["new snapshot"] },
launch,
),
);
expect(server.requestBodies.at(-1)?.match(/paseo_instruction_snapshot/g)).toHaveLength(2);
await run(
await client.resumeSession(
handle,
{ ...base, pluginAppendSystemPrompt: undefined },
launch,
),
);
expect(server.requestBodies.at(-1)).toContain('\\"instructions\\":\\"\\"');
expect(server.requestBodies.at(-1)?.match(/paseo_instruction_snapshot/g)).toHaveLength(4);
} finally {
await server.close();
rmSync(cwd, { recursive: true, force: true });
rmSync(codexHome, { recursive: true, force: true });
}
},
60_000,
);
test.runIf(isCodexInstalled())(
"concurrent import scans initialize successfully in a fresh shared Codex home",
async () => {
@@ -7,7 +7,6 @@ import { tmpdir } from "node:os";
import path from "node:path";
import { PassThrough } from "node:stream";
import { fileURLToPath } from "node:url";
import { CodexInstructionSnapshot } from "./codex/instruction-snapshot.js";
import type {
AgentClient,
@@ -101,7 +100,6 @@ import {
import { createTestLogger } from "../../../test-utils/test-logger.js";
import { asInternals as castInternals, createStub } from "../../test-utils/class-mocks.js";
import { AgentManager } from "../agent-manager.js";
import { AgentStorage } from "../agent-storage.js";
import { buildProviderRegistry } from "../provider-registry.js";
interface CollaborationModeRecord {
@@ -175,9 +173,6 @@ function createSession(
) as CodexTestSession;
session.connectionState = "connected";
session.currentThreadId = "test-thread";
castInternals<{ instructionSnapshot: { recordNewThread(id: string): void } }>(
session,
).instructionSnapshot.recordNewThread("test-thread");
session.activeForegroundTurnId = "test-turn";
return session;
}
@@ -688,7 +683,7 @@ function codexAgentItem(text: string) {
// An AgentManager over a real Codex provider whose every spawn gets a fresh fake
// app-server serving `threads` from thread/read.
function createReopenableCodexAgent(threads: Record<string, unknown[]>, registry?: AgentStorage) {
function createReopenableCodexAgent(threads: Record<string, unknown[]>) {
const appServers: FakeCodexAppServer[] = [];
const provider = new CodexAppServerAgentClient(createTestLogger(), undefined, {
appServerProcess: createFakeCodexAppServerProcess(() => {
@@ -720,11 +715,7 @@ function createReopenableCodexAgent(threads: Record<string, unknown[]>, registry
},
resumeSession: (...args) => provider.resumeSession(...args),
};
const manager = new AgentManager({
clients: { codex: client },
registry,
logger: createTestLogger(),
});
const manager = new AgentManager({ clients: { codex: client }, logger: createTestLogger() });
const agentId = "00000000-0000-4000-8000-000000000001";
const handle = { provider: "codex", sessionId: "saved-thread" };
const config = createConfig({ cwd: process.cwd() });
@@ -737,9 +728,6 @@ function createReopenableCodexAgent(threads: Record<string, unknown[]>, registry
return {
manager,
agentId,
handle,
config,
appServers,
latestAppServer: () => appServers[appServers.length - 1],
threadMethods: (index: number) =>
appServers[index]
@@ -1418,216 +1406,6 @@ describe("Codex app-server provider", () => {
}
});
test("reopening drops disabled plugin instructions and starts with fresh collaboration settings", async () => {
const modes = {
data: [
{
name: "Code",
mode: "default",
model: null,
reasoning_effort: null,
},
],
};
const firstServer = createFakeCodexAppServer({ "collaborationMode/list": () => modes });
const first = await createProviderWithFakeAppServer(firstServer).createSession(
createConfig({ pluginAppendSystemPrompt: ["Plugin instructions"] }),
);
await first.startTurn("first");
const firstTurn = await firstServer.waitForTurnStart();
expect(
firstServer.requests().find((request) => request.method === "thread/start")?.params,
).toMatchObject({ developerInstructions: "Plugin instructions" });
expect(firstTurn).toMatchObject({
collaborationMode: {
settings: { developer_instructions: null },
},
});
const started = waitForNextEvent(first, "thread_started");
firstServer.startsTurn({ threadId: "thread-1" });
await started;
const handle = first.describePersistence()!;
expect(handle.metadata).not.toHaveProperty("pluginAppendSystemPrompt");
await first.close();
const secondServer = createFakeCodexAppServer({ "collaborationMode/list": () => modes });
const resumed = await createProviderWithFakeAppServer(secondServer).resumeSession(handle, {
pluginAppendSystemPrompt: undefined,
});
try {
const resume = secondServer.requests().find((request) => request.method === "thread/resume");
expect(resume?.params).not.toHaveProperty("developerInstructions");
await resumed.startTurn("after disable");
const secondTurn = await secondServer.waitForTurnStart();
expect(secondTurn).not.toHaveProperty("developerInstructions");
expect(secondTurn).toMatchObject({
collaborationMode: { settings: { developer_instructions: null } },
});
firstServer.assertNoErrors();
secondServer.assertNoErrors();
} finally {
await resumed.close();
}
});
test("reopen injects current instructions once, including an explicit empty snapshot", async () => {
const handlers = {
initialize: () => ({ userAgent: "codex/0.165.0" }),
"thread/inject_items": () => ({}),
};
const firstServer = createFakeCodexAppServer(handlers);
const first = await createProviderWithFakeAppServer(firstServer).createSession(
createConfig({ pluginAppendSystemPrompt: ["Old plugin"] }),
);
await first.startTurn("first");
const started = waitForNextEvent(first, "thread_started");
firstServer.startsTurn({ threadId: "thread-1" });
await started;
expect(
firstServer.requests().filter((request) => request.method === "thread/inject_items"),
).toEqual([]);
const original = first.describePersistence()!;
expect(original.metadata).toHaveProperty("paseoInstructionReceipt");
await first.close();
const changedServer = createFakeCodexAppServer(handlers);
const changed = await createProviderWithFakeAppServer(changedServer).resumeSession(original, {
pluginAppendSystemPrompt: ["New plugin"],
});
const injected = changedServer
.requests()
.filter((request) => request.method === "thread/inject_items");
expect(injected).toHaveLength(1);
expect(JSON.stringify(injected[0]?.params)).toContain("New plugin");
const changedHandle = changed.describePersistence()!;
expect(changedHandle.metadata?.paseoInstructionReceipt).not.toEqual(
original.metadata?.paseoInstructionReceipt,
);
await changed.close();
const sameServer = createFakeCodexAppServer(handlers);
const same = await createProviderWithFakeAppServer(sameServer).resumeSession(changedHandle, {
pluginAppendSystemPrompt: ["New plugin"],
});
expect(
sameServer.requests().filter((request) => request.method === "thread/inject_items"),
).toEqual([]);
await same.close();
const emptyServer = createFakeCodexAppServer(handlers);
const empty = await createProviderWithFakeAppServer(emptyServer).resumeSession(changedHandle, {
pluginAppendSystemPrompt: undefined,
});
const removal = emptyServer
.requests()
.filter((request) => request.method === "thread/inject_items");
expect(removal).toHaveLength(1);
expect(JSON.stringify(removal[0]?.params)).toContain('\\"instructions\\":\\"\\"');
await empty.close();
});
test("requires a compatible Codex version before creating a thread with plugin instructions", async () => {
const appServer = createFakeCodexAppServer({
initialize: () => ({ userAgent: "codex/0.120.0" }),
});
await expect(
createProviderWithFakeAppServer(appServer).createSession(
createConfig({ pluginAppendSystemPrompt: ["Plugin instructions"] }),
),
).rejects.toThrow("Update Codex to 0.121.0 or newer");
});
test("retries an instruction snapshot when injection fails", async () => {
const snapshot = new CodexInstructionSnapshot("current", undefined);
const request = vi
.fn()
.mockRejectedValueOnce(new Error("connection lost"))
.mockResolvedValue({});
await expect(snapshot.apply("thread-1", request, true)).rejects.toThrow("connection lost");
expect(snapshot.describe("thread-1")).toBeUndefined();
await snapshot.apply("thread-1", request, true);
expect(snapshot.describe("thread-1")).toEqual({
threadId: "thread-1",
digest: expect.any(String),
});
await snapshot.apply("thread-1", request, true);
expect(request).toHaveBeenCalledTimes(2);
});
test("keeps built-in Plan instructions while sending plugin instructions to the thread", async () => {
const appServer = createFakeCodexAppServer({
"collaborationMode/list": () => ({
data: [
{ name: "Plan", mode: "plan", model: null, reasoning_effort: "medium" },
{ name: "Default", mode: "default", model: null, reasoning_effort: null },
],
}),
});
const session = await createProviderWithFakeAppServer(appServer).createSession(
createConfig({
pluginAppendSystemPrompt: ["Plugin instructions"],
providerOptions: { plan_mode: true },
}),
);
try {
await session.startTurn("make a plan");
const start = appServer.requests().find((request) => request.method === "thread/start");
expect(start?.params).toMatchObject({ developerInstructions: "Plugin instructions" });
expect(await appServer.waitForTurnStart()).toMatchObject({
collaborationMode: { mode: "plan", settings: { developer_instructions: null } },
});
expect(
appServer.requests().find((request) => request.method === "turn/start")?.params,
).not.toHaveProperty("developerInstructions");
appServer.assertNoErrors();
} finally {
await session.close();
}
});
test.each([
{ instructions: undefined, expected: undefined },
{ instructions: ["Current plugin"], expected: "Current plugin" },
])(
"rebuilds restored instructions with an unavailable collaboration catalog: $expected",
async ({ instructions, expected }) => {
const appServer = createFakeCodexAppServer({
"collaborationMode/list": () => ({ data: [] }),
"thread/resume": () => ({
thread: { id: "saved-thread" },
collaborationMode: {
mode: "default",
settings: {
model: "gpt-5.4",
reasoning_effort: "medium",
developer_instructions: "Old plugin",
},
},
}),
});
const session = await createProviderWithFakeAppServer(appServer).resumeSession(
{ sessionId: "saved-thread" },
{ pluginAppendSystemPrompt: instructions },
);
try {
const resume = appServer.requests().find((request) => request.method === "thread/resume");
if (expected) expect(resume?.params).toMatchObject({ developerInstructions: expected });
else expect(resume?.params).not.toHaveProperty("developerInstructions");
await session.startTurn("after reopen");
const turn = await appServer.waitForTurnStart();
expect(turn).toMatchObject({
collaborationMode: {
mode: "default",
settings: { model: "gpt-5.4", developer_instructions: null },
},
});
appServer.assertNoErrors();
} finally {
await session.close();
}
},
);
test("keeps the default effort when a session without one is resumed after a restart", async () => {
const beforeRestart = createFakeCodexAppServer();
const firstSession = await createProviderWithFakeAppServer(beforeRestart).createSession(
@@ -2537,12 +2315,7 @@ describe("Codex app-server provider", () => {
]);
// Background terminal observation is independent of conversation history loading.
const historyMethods = (index: number) =>
codex
.threadMethods(index)
.filter(
(method) =>
method !== "thread/backgroundTerminals/list" && method !== "thread/inject_items",
);
codex.threadMethods(index).filter((method) => method !== "thread/backgroundTerminals/list");
expect(historyMethods(0)).toEqual([
"thread/loaded/list",
"thread/resume",
@@ -2556,34 +2329,6 @@ describe("Codex app-server provider", () => {
}
});
test("persists an acknowledged instruction snapshot before a turn on repeated opens", async () => {
const artifactDir = path.resolve(process.cwd(), "../../.artifacts");
mkdirSync(artifactDir, { recursive: true });
const dir = await mkdtemp(path.join(artifactDir, "codex-receipt-"));
const storage = new AgentStorage(dir, createTestLogger());
const codex = createReopenableCodexAgent({}, storage);
try {
let handle = codex.handle;
for (let i = 0; i < 3; i++) {
await codex.manager.resumeAgentFromPersistence(handle, codex.config, codex.agentId);
await storage.flush();
const saved = await storage.get(codex.agentId);
expect(saved?.persistence?.metadata?.paseoInstructionReceipt).toEqual(expect.any(Object));
handle = saved!.persistence!;
await codex.manager.closeAgent(codex.agentId);
}
expect(
codex.appServers
.flatMap((server) => server.requests())
.filter((request) => request.method === "thread/inject_items"),
).toHaveLength(1);
} finally {
if (codex.manager.getAgent(codex.agentId)) await codex.manager.closeAgent(codex.agentId);
await storage.flush();
rmSync(dir, { recursive: true, force: true });
}
});
test("rewinds an agent reopened without reading its Codex history", async () => {
const firstTurn = {
id: "turn-1",
@@ -3103,9 +2848,6 @@ describe("Codex app-server provider", () => {
const session = new CodexAppServerAgentSession(
createConfig({
cwd: "/workspace/project",
systemPrompt: "Agent instructions",
daemonAppendSystemPrompt: "Daemon instructions",
pluginAppendSystemPrompt: ["Plugin instructions"],
mcpServers: {
paseo: { type: "http", url: "http://127.0.0.1:6767/mcp/agents?callerAgentId=agent-1" },
},
@@ -3137,24 +2879,6 @@ describe("Codex app-server provider", () => {
await session.revertConversation({ messageId: "codex-first" });
const forkRequest = appServer.requests().find((request) => request.method === "thread/fork");
expect(forkRequest?.params).toMatchObject({
developerInstructions: "Agent instructions\n\nDaemon instructions\n\nPlugin instructions",
});
const rewindRequests = appServer
.requests()
.filter((request) =>
["thread/fork", "thread/rollback", "thread/inject_items"].includes(
String(request.method),
),
);
expect(rewindRequests.map((request) => request.method)).toEqual(
historyMode === "legacy"
? ["thread/fork", "thread/rollback", "thread/inject_items"]
: ["thread/fork", "thread/inject_items"],
);
expect(rewindRequests.at(-1)?.params).toMatchObject({ threadId: "forked-thread" });
expect(JSON.stringify(rewindRequests.at(-1)?.params)).toContain("Plugin instructions");
const forkConfigs = appServer
.requests()
.filter((request) => request.method === "thread/fork")
@@ -5428,7 +5152,7 @@ describe("Codex app-server provider", () => {
threadStart.resolve({ thread: { id: "thread-1" } });
await expect(interruptPromise).resolves.toBeUndefined();
await expect(resultPromise).resolves.toMatchObject({ canceled: true, timeline: [] });
await expect(resultPromise).rejects.toThrow("interrupted before reaching Codex");
expect(appServer.requests()).not.toContainEqual(
expect.objectContaining({ method: "turn/start" }),
);
@@ -3,7 +3,6 @@ import { applyProviderOptionsPatch } from "../option-controls.js";
import { assertChangesAreLive, validateProviderOptions } from "../provider-options.js";
import { CodexBackgroundInventory } from "./codex/background-inventory.js";
import {
AgentTurnStartCanceledError,
getAgentStreamEventTurnId,
type AgentPermissionAction,
type AgentCapabilityFlags,
@@ -56,8 +55,7 @@ import path from "node:path";
import { isDeepStrictEqual } from "node:util";
import { z } from "zod";
import { renderPromptAttachmentAsText } from "../prompt-attachments.js";
import { composeAgentSystemPrompt } from "../system-prompt.js";
import { CodexInstructionSnapshot } from "./codex/instruction-snapshot.js";
import { composeSystemPromptParts } from "../system-prompt.js";
import { CodexAsyncQuestions, codexAsyncQuestionToTimeline } from "./codex/async-questions.js";
import {
fileChangesToPreview,
@@ -3593,12 +3591,9 @@ interface ConsumedRootCompaction {
export class CodexAppServerAgentSession implements AgentSession {
readonly provider = CODEX_PROVIDER;
readonly capabilities = CODEX_APP_SERVER_CAPABILITIES;
readonly persistenceUpdatedOnResume = true;
private readonly logger: Logger;
private readonly config: AgentSessionConfig;
private readonly instructionSnapshot: CodexInstructionSnapshot;
private supportsInstructionSnapshots = false;
private readonly asyncQuestions: CodexAsyncQuestions;
private readonly codexHome: string;
private currentMode: string;
@@ -3711,13 +3706,6 @@ export class CodexAppServerAgentSession implements AgentSession {
reasoning_effort?: string | null;
developer_instructions?: string | null;
}> = [];
private restoredCollaborationMode: {
name: string;
mode: string;
model: string;
reasoning_effort: string | null;
developer_instructions?: never;
} | null = null;
private resolvedCollaborationMode: {
mode: string;
settings: Record<string, unknown>;
@@ -3763,10 +3751,6 @@ export class CodexAppServerAgentSession implements AgentSession {
this.providerOptions =
validateProviderOptions("codex", CodexProviderOptionsSchema, config.providerOptions) ?? {};
this.config = config;
this.instructionSnapshot = new CodexInstructionSnapshot(
composeAgentSystemPrompt(config),
resumeHandle?.metadata?.paseoInstructionReceipt,
);
this.harnessEnvironment = deps.environment ?? buildCodexAppServerEnv();
this.asyncQuestions = new CodexAsyncQuestions(resumeHandle?.metadata?.asyncQuestions);
this.codexHome = deps.codexHome ?? resolveCodexHomeDir(process.env);
@@ -3853,17 +3837,9 @@ export class CodexAppServerAgentSession implements AgentSession {
this.registerRequestHandlers();
try {
const userAgent = toObjectRecord(initialized)?.userAgent;
this.threadRollbackAvailable = codexServerHasThreadRollback(userAgent);
this.supportsInstructionSnapshots =
typeof userAgent === "string" && codexVersionAtLeast(userAgent, [0, 121, 0]);
if (
!this.currentThreadId &&
this.config.pluginAppendSystemPrompt?.length &&
!this.supportsInstructionSnapshots
) {
throw new Error("Update Codex to 0.121.0 or newer to apply agent instruction updates.");
}
this.threadRollbackAvailable = codexServerHasThreadRollback(
toObjectRecord(initialized)?.userAgent,
);
this.speedModels =
CodexModelListResponseSchema.parse(await client.request("model/list", {})).data ?? [];
@@ -4061,17 +4037,18 @@ export class CodexAppServerAgentSession implements AgentSession {
settings: Record<string, unknown>;
name: string;
} | null {
const match =
this.findCollaborationMode(this.planModeEnabled ? "plan" : "code") ??
this.restoredCollaborationMode;
const match = this.findCollaborationMode(this.planModeEnabled ? "plan" : "code");
if (!match) return null;
const settings: Record<string, unknown> = {};
if (match.model) settings.model = match.model;
if (match.reasoning_effort) settings.reasoning_effort = match.reasoning_effort;
// Codex applies thread instructions separately. Null asks it to supply the
// built-in collaboration mode instructions instead of replacing them.
settings.developer_instructions = match.developer_instructions ?? null;
const developerInstructions = composeSystemPromptParts(
match.developer_instructions,
this.config.systemPrompt,
this.config.daemonAppendSystemPrompt,
);
if (developerInstructions) settings.developer_instructions = developerInstructions;
if (this.config.model) settings.model = this.config.model;
const thinkingOptionId = normalizeCodexThinkingOptionId(this.config.thinkingOptionId);
if (thinkingOptionId) settings.reasoning_effort = thinkingOptionId;
@@ -4331,7 +4308,10 @@ export class CodexAppServerAgentSession implements AgentSession {
// the unnamespaced key emitted by earlier Paseo versions.
params.modelProvider = this.deps.customCodexConfig.model_provider;
}
const developerInstructions = composeAgentSystemPrompt(this.config);
const developerInstructions = composeSystemPromptParts(
this.config.systemPrompt,
this.config.daemonAppendSystemPrompt,
);
if (developerInstructions) {
params.developerInstructions = developerInstructions;
}
@@ -4342,11 +4322,11 @@ export class CodexAppServerAgentSession implements AgentSession {
try {
const loaded = toObjectRecord(await this.client.request("thread/loaded/list", {}));
const ids = Array.isArray(loaded?.data) ? loaded.data : [];
if (!ids.includes(this.currentThreadId)) {
const response = await this.client.request("thread/resume", params);
this.rememberResolvedSandboxPolicy(response);
this.rememberRestoredCollaborationMode(response);
if (ids.includes(this.currentThreadId)) {
return;
}
const response = await this.client.request("thread/resume", params);
this.rememberResolvedSandboxPolicy(response);
} catch (error) {
const threadId = this.currentThreadId;
const message = error instanceof Error ? error.message : String(error);
@@ -4360,34 +4340,12 @@ export class CodexAppServerAgentSession implements AgentSession {
}
const response = await this.client.request("thread/resume", params);
this.rememberResolvedSandboxPolicy(response);
this.rememberRestoredCollaborationMode(response);
this.logger.info({ threadId }, "Unarchived Codex thread to restore active Paseo agent");
} else {
this.logger.warn({ error, threadId }, "Failed to resume persisted Codex thread");
throw new Error(`Failed to resume Codex thread ${threadId}: ${message}`, { cause: error });
return;
}
this.logger.warn({ error, threadId }, "Failed to resume persisted Codex thread");
throw new Error(`Failed to resume Codex thread ${threadId}: ${message}`, { cause: error });
}
await this.instructionSnapshot.apply(
this.currentThreadId,
this.client.request.bind(this.client),
this.supportsInstructionSnapshots,
);
}
private rememberRestoredCollaborationMode(response: unknown): void {
const mode = toObjectRecord(toObjectRecord(response)?.collaborationMode);
const settings = toObjectRecord(mode?.settings);
if (typeof mode?.mode !== "string" || typeof settings?.model !== "string") return;
// The resumed mode can contain instructions from a previous launch. Keep its
// identity and model, and let Codex restore the built-in mode instructions.
this.restoredCollaborationMode = {
name: mode.mode,
mode: mode.mode,
model: settings.model,
reasoning_effort:
typeof settings.reasoning_effort === "string" ? settings.reasoning_effort : null,
};
this.refreshResolvedCollaborationMode();
}
private parseSlashCommandInput(text: string): { commandName: string; args?: string } | null {
@@ -4503,7 +4461,13 @@ export class CodexAppServerAgentSession implements AgentSession {
if (options?.outputSchema) {
params.outputSchema = normalizeCodexOutputSchema(options.outputSchema);
}
const developerInstructions = composeAgentSystemPrompt(this.config);
const developerInstructions = composeSystemPromptParts(
this.config.systemPrompt,
this.config.daemonAppendSystemPrompt,
);
if (developerInstructions) {
params.developerInstructions = developerInstructions;
}
const codexConfig = this.buildCodexInnerConfig();
if (codexConfig) {
params.config = codexConfig;
@@ -4697,7 +4661,7 @@ export class CodexAppServerAgentSession implements AgentSession {
// outlives it into the new turn.
await this.waitForInterruptedTurnCleanup();
if (pendingStart.cancelRequested) {
throw new AgentTurnStartCanceledError();
throw new Error("Codex turn start was interrupted before reaching Codex");
}
await this.client.request("turn/start", turnStart.params, TURN_START_TIMEOUT_MS);
return { turnId };
@@ -5262,9 +5226,6 @@ export class CodexAppServerAgentSession implements AgentSession {
systemPrompt: this.config.systemPrompt,
mcpServers: this.config.mcpServers,
asyncQuestions: this.asyncQuestions.serialize(),
...(this.instructionSnapshot.describe(threadId)
? { paseoInstructionReceipt: this.instructionSnapshot.describe(threadId) }
: {}),
},
};
}
@@ -5295,15 +5256,9 @@ export class CodexAppServerAgentSession implements AgentSession {
model: this.config.model ?? null,
serviceTier: this.serviceTier,
config: this.buildCodexInnerConfig(),
developerInstructions: composeAgentSystemPrompt(this.config),
userMessageTurns: this.codexUserMessageTurns(),
threadRollbackAvailable: this.threadRollbackAvailable,
setThreadId: async (threadId) => {
await this.instructionSnapshot.apply(
threadId,
this.client!.request.bind(this.client),
this.supportsInstructionSnapshots,
);
this.currentThreadId = threadId;
// Codex writes a forked thread's rollout when it forks it, even before any turn.
this.savedThreadId = threadId;
@@ -5839,7 +5794,6 @@ export class CodexAppServerAgentSession implements AgentSession {
this.cachedRuntimeInfo = null;
}
this.currentThreadId = threadId;
this.instructionSnapshot.recordNewThread(threadId);
}
private buildThreadStartRequest(model: string): {
@@ -5851,7 +5805,10 @@ export class CodexAppServerAgentSession implements AgentSession {
const approvalPolicy = this.hasWorkflowModeOverride ? preset.approvalPolicy : undefined;
const sandbox = this.hasWorkflowModeOverride ? preset.sandbox : undefined;
const innerConfig = this.buildCodexInnerConfig();
const developerInstructions = composeAgentSystemPrompt(this.config);
const developerInstructions = composeSystemPromptParts(
this.config.systemPrompt,
this.config.daemonAppendSystemPrompt,
);
const params: Record<string, unknown> = {
model,
cwd: this.config.cwd ?? null,
@@ -1,69 +0,0 @@
import { createHash } from "node:crypto";
import { CodexAppServerRpcError } from "./app-server-transport.js";
/** The receipt records only which snapshot was delivered to a particular native thread. */
interface InstructionReceipt {
threadId: string;
digest: string;
}
function readReceipt(value: unknown): InstructionReceipt | null {
if (!value || typeof value !== "object") return null;
const receipt = value as Record<string, unknown>;
if (typeof receipt.threadId !== "string" || typeof receipt.digest !== "string") return null;
if (!/^[a-f0-9]{64}$/.test(receipt.digest)) return null;
return { threadId: receipt.threadId, digest: receipt.digest };
}
export class CodexInstructionSnapshot {
private receipt: InstructionReceipt | null;
private readonly digest: string;
constructor(
private readonly instructions: string | undefined,
receipt: unknown,
) {
this.receipt = readReceipt(receipt);
this.digest = createHash("sha256")
.update(JSON.stringify({ version: 1, instructions: instructions ?? "" }))
.digest("hex");
}
/** A new thread receives its first snapshot through thread/start. */
recordNewThread(threadId: string): void {
this.receipt = { threadId, digest: this.digest };
}
describe(threadId: string): InstructionReceipt | undefined {
return this.receipt?.threadId === threadId ? { ...this.receipt } : undefined;
}
async apply(
threadId: string,
request: (method: string, params: unknown) => Promise<unknown>,
supported: boolean,
): Promise<void> {
if (this.receipt?.threadId === threadId && this.receipt.digest === this.digest) return;
if (!supported)
throw new Error("Update Codex to 0.121.0 or newer to apply agent instruction updates.");
const snapshot = JSON.stringify({ version: 1, instructions: this.instructions ?? "" });
const text =
"This is the complete current set of Paseo-supplied instructions. It supersedes all earlier Paseo-supplied instructions in the conversation, including earlier snapshots. An empty instruction string means there are no current Paseo-supplied instructions. Provider and collaboration instructions remain in effect.\n\n<paseo_instruction_snapshot>" +
snapshot +
"</paseo_instruction_snapshot>";
try {
await request("thread/inject_items", {
threadId,
items: [{ type: "message", role: "developer", content: [{ type: "input_text", text }] }],
});
} catch (error) {
if (error instanceof CodexAppServerRpcError && error.code === -32601) {
throw new Error("Update Codex to 0.121.0 or newer to apply agent instruction updates.", {
cause: error,
});
}
throw error;
}
this.receipt = { threadId, digest: this.digest };
}
}
@@ -49,7 +49,6 @@ export async function revertCodexConversation(input: {
model?: string | null;
serviceTier?: string | null;
config?: Record<string, unknown> | null;
developerInstructions?: string;
userMessageTurns: CodexUserMessageTurnIndex;
threadRollbackAvailable: boolean;
setThreadId: (threadId: string) => void | Promise<void>;
@@ -77,7 +76,6 @@ export async function revertCodexConversation(input: {
model: input.model ?? null,
serviceTier: input.serviceTier ?? null,
...(input.config ? { config: input.config } : {}),
...(input.developerInstructions ? { developerInstructions: input.developerInstructions } : {}),
// Paseo re-reads the rewound thread through paged history, not the fork reply.
excludeTurns: true,
persistExtendedHistory: true,
@@ -171,7 +171,7 @@ export function createFakeCodexAppServer(
const child = createCodexAppServerChildProcess();
const recordedRollbacks: JsonObject[] = [];
const responseHandlers: Record<string, FakeCodexAppServerHandler> = {
initialize: () => ({ userAgent: "codex/0.150.0" }),
initialize: () => ({}),
"collaborationMode/list": () => ({ data: [] }),
"config/read": () => ({ config: {} }),
getUserSavedConfig: () => ({ config: {} }),
@@ -189,7 +189,6 @@ export function createFakeCodexAppServer(
"thread/loaded/list": () => ({ data: [] }),
"thread/backgroundTerminals/list": () => ({ data: [], nextCursor: null }),
"thread/resume": () => ({}),
"thread/inject_items": () => ({}),
"turn/start": () => ({}),
"thread/fork": (params) => ({
thread: {
@@ -435,7 +435,6 @@ function buildResumeStartInput(input: {
systemPrompt: composeSystemPromptParts(
input.resumeConfig.config.systemPrompt,
input.resumeConfig.config.daemonAppendSystemPrompt,
...(input.resumeConfig.config.pluginAppendSystemPrompt ?? []),
),
};
}
@@ -2340,11 +2339,7 @@ export class OmpAgentClient implements AgentClient {
noSession: config.internal === true,
modeId: launchMode.modeId,
extraArgs: launchMode.extraArgs,
systemPrompt: composeSystemPromptParts(
config.systemPrompt,
config.daemonAppendSystemPrompt,
...(config.pluginAppendSystemPrompt ?? []),
),
systemPrompt: composeSystemPromptParts(config.systemPrompt, config.daemonAppendSystemPrompt),
env: launchContext?.env,
};
const runtimeSession = await this.resolveRuntime(config.providerOptions).startSession(
@@ -30,7 +30,6 @@ import {
type AgentDraftControls,
type AgentOptionControl,
type AgentLaunchContext,
type AgentResumeSessionOptions,
type AgentMode,
type AgentModelDefinition,
type AgentPermissionAction,
@@ -1522,7 +1521,6 @@ export class OpenCodeAgentClient implements AgentClient {
handle: AgentPersistenceHandle,
overrides?: Partial<AgentSessionConfig>,
launchContext?: AgentLaunchContext,
_options?: AgentResumeSessionOptions,
): Promise<AgentSession> {
const metadata = (handle.metadata ?? {}) as Partial<AgentSessionConfig>;
const cwd = overrides?.cwd ?? metadata.cwd;
@@ -3694,7 +3692,6 @@ class OpenCodeAgentSession implements AgentSession {
const systemPrompt = composeSystemPromptParts(
this.config.systemPrompt,
this.config.daemonAppendSystemPrompt,
...(this.config.pluginAppendSystemPrompt ?? []),
);
const model = this.parseModel(this.config.model);
const effectiveMode = resolveOpenCodeRuntimeAgentId(this.currentMode);
@@ -4032,7 +4029,6 @@ class OpenCodeAgentSession implements AgentSession {
const systemPrompt = composeSystemPromptParts(
this.config.systemPrompt,
this.config.daemonAppendSystemPrompt,
...(this.config.pluginAppendSystemPrompt ?? []),
);
const promptResponse = await this.client.session.promptAsync({
sessionID: this.sessionId,
@@ -4,7 +4,6 @@ import type {
AgentSessionConfig,
AgentLaunchContext,
AgentCreateSessionOptions,
AgentResumeSessionOptions,
AgentPersistenceHandle,
FetchCatalogOptions,
ProviderRefreshContext,
@@ -150,10 +149,9 @@ export class OpenCodeRuntimeClient implements AgentClient {
handle: AgentPersistenceHandle,
config?: Partial<AgentSessionConfig>,
launch?: AgentLaunchContext,
options?: AgentResumeSessionOptions,
) {
const client = await this.client();
const session = await client.resumeSession(handle, config, launch, options);
const session = await client.resumeSession(handle, config, launch);
return client === this.legacy ? session : withOpenCodeRuntimeNotice(session, 2, handle);
}
async fetchCatalog(options: FetchCatalogOptions, context?: ProviderRefreshContext) {
@@ -28,7 +28,6 @@ export class V2Harness {
readonly prompts: string[] = [];
readonly environments: Array<{ sessionID: string; variables: Record<string, string> }> = [];
readonly mcpAdds: string[] = [];
readonly instructions = new Map<string, string>();
releases = 0;
active = false;
activeReads = 0;
@@ -154,17 +153,7 @@ export class V2Harness {
environment: async (input) => {
this.environments.push(input);
},
instructions: {
entry: {
list: async () => [...this.instructions].map(([key, value]) => ({ key, value })),
put: async ({ key, value }) => {
this.instructions.set(key, String(value));
},
remove: async ({ key }) => {
this.instructions.delete(key);
},
},
},
instructions: { entry: { list: unexpected, put: unexpected, remove: unexpected } },
prompt: async (input, options) => {
const before = this.executions.length;
await this.prompt(input, options);
@@ -17,54 +17,6 @@ function terminalEvents(events: AgentStreamEvent[]) {
}
describe("OpenCode v2 session lifecycle", () => {
test("reopening replaces and removes plugin instructions", async () => {
const harness = new V2Harness();
const client = new OpenCodeV2AgentClient({
logger: createTestLogger(),
runtime: harness.runtime,
});
const created = await client.createSession({
provider: "opencode",
cwd: "/tmp/project",
pluginAppendSystemPrompt: ["first"],
});
expect(harness.instructions.get("paseo")).toBe("first");
const handle = created.describePersistence()!;
await created.close();
const resumed = await client.resumeSession(handle, {
cwd: "/tmp/project",
pluginAppendSystemPrompt: ["changed"],
});
expect(harness.instructions.get("paseo")).toBe("changed");
await resumed.close();
const cleared = await client.resumeSession(handle, {
cwd: "/tmp/project",
pluginAppendSystemPrompt: undefined,
});
expect(harness.instructions.has("paseo")).toBe(false);
await cleared.close();
});
test("opening history does not change an existing session instruction", async () => {
const harness = new V2Harness();
harness.instructions.set("paseo", "Existing plugin instruction");
const client = new OpenCodeV2AgentClient({
logger: createTestLogger(),
runtime: harness.runtime,
});
const session = await client.resumeSession(
{ provider: "opencode", sessionId: "session", metadata: { cwd: "/tmp/project" } },
{ cwd: "/tmp/project" },
undefined,
{ purpose: "history" },
);
try {
expect(harness.instructions.get("paseo")).toBe("Existing plugin instruction");
} finally {
await session.close();
}
});
test("refreshes the existing location before reading a forced catalog", async () => {
const harness = new V2Harness();
const refreshed: string[] = [];
@@ -17,7 +17,6 @@ import type {
AgentCapabilityFlags,
AgentClient,
AgentCreateSessionOptions,
AgentResumeSessionOptions,
AgentDraftControls,
AgentLaunchContext,
AgentPersistenceHandle,
@@ -132,7 +131,6 @@ export class OpenCodeV2AgentClient implements AgentClient {
handle: AgentPersistenceHandle,
overrides?: Partial<AgentSessionConfig>,
launch?: AgentLaunchContext,
options?: AgentResumeSessionOptions,
): Promise<AgentSession> {
const cwd = overrides?.cwd ?? handle.metadata?.cwd;
if (typeof cwd !== "string")
@@ -153,14 +151,7 @@ export class OpenCodeV2AgentClient implements AgentClient {
sessionID: handle.nativeHandle ?? handle.sessionId,
});
await applyResumeOverrides(connection.client, info, overrides);
return await this.attach(
connection,
info,
config,
launch,
true,
options?.purpose === "history",
);
return await this.attach(connection, info, config, launch, true);
} catch (error) {
await connection.release();
throw error;
@@ -172,7 +163,6 @@ export class OpenCodeV2AgentClient implements AgentClient {
config: AgentSessionConfig,
launch: AgentLaunchContext | undefined,
persist: boolean,
historyOnly = false,
) {
const acquire = () =>
this.runtime.acquire(
@@ -219,7 +209,6 @@ export class OpenCodeV2AgentClient implements AgentClient {
bindChild,
acquire,
moved,
historyOnly,
);
try {
await session.initialize(
@@ -75,7 +75,6 @@ export class OpenCodeV2Session implements AgentSession {
bindChild?: (id: string) => void,
private readonly acquire?: () => Promise<V2Connection>,
private readonly moved?: (connection: V2Connection) => void,
private readonly historyOnly = false,
) {
this.background = new OpenCodeBackgroundInventory({
id: info.id,
@@ -194,24 +193,16 @@ export class OpenCodeV2Session implements AgentSession {
});
await this.awaitMcp(server);
}
if (this.historyOnly) return;
const system = composeSystemPromptParts(
this.config.systemPrompt,
this.config.daemonAppendSystemPrompt,
...(this.config.pluginAppendSystemPrompt ?? []),
);
if (system) {
if (system)
await this.client.session.instructions.entry.put({
sessionID: this.id,
key: "paseo",
value: system,
});
} else {
const entries = await this.client.session.instructions.entry.list({ sessionID: this.id });
if (entries.some((entry) => entry.key === "paseo")) {
await this.client.session.instructions.entry.remove({ sessionID: this.id, key: "paseo" });
}
}
}
private async startStream() {
let ready!: () => void;
@@ -1887,7 +1887,6 @@ describe("PiRpcAgentSession", () => {
createConfig({
systemPrompt: "Agent prompt",
daemonAppendSystemPrompt: "Daemon prompt",
pluginAppendSystemPrompt: ["Plugin one", "Plugin two"],
}),
);
@@ -1906,9 +1905,7 @@ describe("PiRpcAgentSession", () => {
await expect(
applyPaseoExtensionSystemPrompt(actualLaunch.extensionPaths[0]!, "Pi project prompt"),
).resolves.toBe(
"Pi project prompt\n\nAgent prompt\n\nDaemon prompt\n\nPlugin one\n\nPlugin two",
);
).resolves.toBe("Pi project prompt\n\nAgent prompt\n\nDaemon prompt");
await session.close();
});
@@ -1931,7 +1928,6 @@ describe("PiRpcAgentSession", () => {
},
{
daemonAppendSystemPrompt: "Daemon prompt",
pluginAppendSystemPrompt: ["Plugin one", "Plugin two"],
},
);
@@ -1955,9 +1951,7 @@ describe("PiRpcAgentSession", () => {
]);
await expect(
applyPaseoExtensionSystemPrompt(actualLaunch.extensionPaths[0]!, "Pi project prompt"),
).resolves.toBe(
"Pi project prompt\n\nAgent prompt\n\nDaemon prompt\n\nPlugin one\n\nPlugin two",
);
).resolves.toBe("Pi project prompt\n\nAgent prompt\n\nDaemon prompt");
});
test("updates model and thinking through Pi runtime commands", async () => {
@@ -52,7 +52,7 @@ import {
type ResolvedProviderLaunch,
} from "../../provider-launch-config.js";
import { renderPromptAttachmentAsText } from "../../prompt-attachments.js";
import { composeAgentSystemPrompt } from "../../system-prompt.js";
import { composeSystemPromptParts } from "../../system-prompt.js";
import {
buildBinaryDiagnosticRows,
buildCommandResolutionDiagnosticRows,
@@ -2601,7 +2601,7 @@ export class PiRpcAgentClient implements AgentClient {
const mcp = await this.prepareMcpInjection(config.cwd, config.mcpServers, mcpEnv, runtime);
const mcpConfigFile = mcp?.kind === "adapter" ? mcp.configFile : null;
const paseoExtension = createPiPaseoExtensionFile({
systemPrompt: composeAgentSystemPrompt(config),
systemPrompt: composeSystemPromptParts(config.systemPrompt, config.daemonAppendSystemPrompt),
mcpServers: mcp?.kind === "builtin" ? mcp.servers : undefined,
});
let runtimeSession: PiRuntimeSession;
@@ -2670,7 +2670,10 @@ export class PiRpcAgentClient implements AgentClient {
);
const mcpConfigFile = mcp?.kind === "adapter" ? mcp.configFile : null;
const paseoExtension = createPiPaseoExtensionFile({
systemPrompt: composeAgentSystemPrompt(resumeConfig.config),
systemPrompt: composeSystemPromptParts(
resumeConfig.config.systemPrompt,
resumeConfig.config.daemonAppendSystemPrompt,
),
mcpServers: mcp?.kind === "builtin" ? mcp.servers : undefined,
});
const tempFiles = mcpConfigFile ? [mcpConfigFile, paseoExtension] : [paseoExtension];
@@ -1,5 +1,4 @@
import {
AgentTurnStartCanceledError,
getAgentStreamEventTurnId,
type AgentPromptInput,
type AgentRunOptions,
@@ -91,9 +90,6 @@ export async function runProviderTurn({
processEvent(event);
}
await completion;
} catch (error) {
if (!(error instanceof AgentTurnStartCanceledError)) throw error;
return { sessionId: await getSessionId(), finalText: "", timeline: [], canceled: true };
} finally {
unsubscribe();
}
@@ -8,15 +8,3 @@ export function composeSystemPromptParts(
return prompt.length > 0 ? prompt : undefined;
}
export function composeAgentSystemPrompt(config: {
systemPrompt?: string;
daemonAppendSystemPrompt?: string;
pluginAppendSystemPrompt?: string[];
}): string | undefined {
return composeSystemPromptParts(
config.systemPrompt,
config.daemonAppendSystemPrompt,
...(config.pluginAppendSystemPrompt ?? []),
);
}
@@ -1281,7 +1281,7 @@ function createToolCatalog(
.strict();
const commonSendAgentPromptInputSchema = {
activeTurnBehavior: ActiveTurnBehaviorSchema.optional().describe(
'Agent callers: "steer" (default) waits until the current turn ends; "interrupt" replaces it. Human callers: "steer" joins the turn, falling back to interrupt; default is interrupt.',
'How to send into a running turn: "steer" joins it, falling back to interrupt when unavailable; "interrupt" replaces it. Defaults to steer for agent callers and interrupt otherwise.',
),
agentId: z.string(),
prompt: z.string(),
@@ -1968,7 +1968,7 @@ function createToolCatalog(
{
title: "Send agent prompt",
description:
"Send a task. Agent callers receive an immediate queued receipt; delivery follows after two quiet seconds per recipient and waits for the current turn to end unless interrupt is requested. Completion reports include the target’s last response by default. Paseo supplies caller identity.",
"Send a task. Agent callers receive an immediate queued receipt; delivery follows after two quiet seconds per recipient. Completion reports include the target’s last response by default. Paseo supplies caller identity.",
inputSchema: sendAgentPromptInputSchema,
outputSchema: {
success: z.boolean(),
@@ -2045,13 +2045,13 @@ function createToolCatalog(
messageId: receipt.messageId,
status: agentManager.getAgent(agentId)?.lifecycle ?? "idle",
guidance: notifying
? `Queued for delivery after two quiet seconds and the current turn ends. ${PROMPTED_AGENT_NOTIFICATION_GUIDANCE}`
: "Queued for delivery after two quiet seconds and the current turn ends; provider dispatch has not occurred.",
? `Queued for delivery after two quiet seconds. ${PROMPTED_AGENT_NOTIFICATION_GUIDANCE}`
: "Queued for delivery after two quiet seconds; provider dispatch has not occurred.",
},
};
}
const dispatch = await sendPromptToAgent({
const { disposition } = await sendPromptToAgent({
agentManager,
agentStorage,
agentId,
@@ -2070,14 +2070,11 @@ function createToolCatalog(
});
// Return once the provider has accepted the turn, so the status reports it running.
const { disposition } = dispatch;
if (dispatch.disposition === "turn_started") {
await waitForAgentRunStartWithTimeout(agentManager, agentId, dispatch.started).catch(
(error) => {
rejectNotification();
throw error;
},
);
if (disposition === "turn_started") {
await waitForAgentRunStartWithTimeout(agentManager, agentId).catch((error) => {
rejectNotification();
throw error;
});
}
const currentSnapshot = agentManager.getAgent(agentId);
+2 -2
View File
@@ -128,7 +128,7 @@ export async function fanOutReconciledWorkspaceUpdates(input: {
);
}
import { VoiceAssistantWebSocketServer, isDaemonOriginAllowed } from "./websocket-server.js";
import { VoiceAssistantWebSocketServer } from "./websocket-server.js";
import { WorkspaceSetupRuntime } from "./workspace-setup-runtime.js";
import { createWorkspaceLabelService } from "./workspace-labels/index.js";
import { createGitHubService } from "../services/github-service.js";
@@ -813,7 +813,7 @@ export async function createPaseoDaemon(
app.use((req, res, next) => {
const origin = req.headers.origin;
if (origin && isDaemonOriginAllowed(origin, req.headers.host ?? null, allowedOrigins)) {
if (origin && (allowedOrigins.has("*") || allowedOrigins.has(origin))) {
res.setHeader("Access-Control-Allow-Origin", origin);
res.setHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, OPTIONS");
res.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization");
@@ -9,7 +9,7 @@ import {
symlinkSync,
} from "fs";
import { once } from "node:events";
import { get, type IncomingMessage } from "node:http";
import { get } from "node:http";
import { tmpdir } from "os";
import path from "path";
import { createDaemonTestContext, type DaemonTestContext } from "../test-utils/index.js";
@@ -69,29 +69,6 @@ describe("daemon E2E", () => {
}, 60000);
describe("file download tokens", () => {
test("lets a page on a loopback alias of the request's host and port fetch a download", async () => {
const cwd = tmpCwd();
writeFileSync(path.join(cwd, "download.bin"), "download bytes");
try {
// The web UI behind a remapped port (for example Docker -p 8080:6767): the page is at
// http://127.0.0.1:8080 and the app sends the request to localhost:8080. The WebSocket
// accepts this origin, so the download must as well.
const token = await ctx.client.requestDownloadToken(cwd, "download.bin");
const request = get({
host: "127.0.0.1",
port: ctx.daemon.port,
path: `/api/files/download?token=${token.token}`,
headers: { Host: "localhost:8080", Origin: "http://127.0.0.1:8080" },
});
const [response] = (await once(request, "response")) as [IncomingMessage];
response.resume();
expect(response.statusCode).toBe(200);
expect(response.headers["access-control-allow-origin"]).toBe("http://127.0.0.1:8080");
} finally {
rmSync(cwd, { recursive: true, force: true });
}
});
test.skipIf(process.platform !== "linux")(
"releases file descriptors after repeated HTTP download cancellations",
async () => {
@@ -95,7 +95,7 @@ test("an agent-sourced steer leaves the question pending and answerable", async
await client.sendAgentMessage(recipient.id, "Peer status check", {
sourceAgentId: sender.id,
});
// Permission checkpoints are reported while the peer message waits for turn end.
// The public wait includes admitted message delivery before reporting permission status.
const waiting = await client.waitForFinish(recipient.id);
expect(waiting.status).toBe("permission");
expect(waiting.final?.pendingPermissions).toMatchObject([
@@ -193,11 +193,10 @@ test("classifies a removed file as deleted", async () => {
});
await rm(target);
// macOS FSEvents can replay the write above as a create after the subscription starts,
// so the delete is the latest event for the path, not the first. Native recursive delivery
// can also be coalesced before the backend's deletion audit, hence the longer timeout.
// Native recursive delivery can be coalesced before the backend's deletion audit.
// Assert eventual classification without imposing Vitest's one-second default.
await expect
.poll(() => events.findLast((event) => event.path === target)?.type, { timeout: 10_000 })
.poll(() => events.find((event) => event.path === target)?.type, { timeout: 10_000 })
.toBe("delete");
await subscription.unsubscribe();
});
@@ -328,39 +327,6 @@ test("unsubscribe cancels reconciliation queued by a write burst", async () => {
expect(callback).toHaveBeenCalledTimes(callsAtClose);
}, 20_000);
test("aborting a pending subscription stops its startup scan and rejects", async () => {
const root = await createRoot();
// More directories than the Linux backend watches: a scan that keeps walking after the abort
// fails on the directory limit instead of rejecting with the abort reason.
await Promise.all(
Array.from({ length: 80 }, (_, outer) =>
Promise.all(
Array.from({ length: 70 }, (__, inner) =>
mkdir(join(root, `dir-${outer}`, `nested-${inner}`), { recursive: true }),
),
),
),
);
const observer = createObserver();
const controller = new AbortController();
const reason = new Error("setup deadline passed");
const callback = vi.fn();
const subscription = observer.subscribe(root, callback, { signal: controller.signal });
await new Promise((resolve) => setTimeout(resolve, 10));
controller.abort(reason);
await expect(subscription).rejects.toBe(reason);
expect(observer.getDiagnostics()).toMatchObject({
activeObservationCount: 0,
nativeHandleCount: 0,
pendingReconciliationWorkCount: 0,
});
await writeFile(join(root, "dir-0", "after-abort.txt"), "late");
await new Promise((resolve) => setTimeout(resolve, 100));
expect(callback).not.toHaveBeenCalled();
}, 20_000);
test("aggregate diagnostics return to their lifecycle baseline", async () => {
const root = await createRoot();
const observer = createObserver();
@@ -14,8 +14,6 @@ export interface FileChange {
export interface FileObserverOptions {
ignore?: string[];
// Aborting before `subscribe()` resolves stops the startup scan and rejects with the reason.
signal?: AbortSignal;
}
export type FileObserverCallback = (error: Error | null, events: FileChange[]) => void;
@@ -107,19 +105,7 @@ class FileObserverService implements FileObserver {
createBackend: this.createBackend,
onClosed: () => state.observations.delete(observation),
});
const { signal } = options;
signal?.throwIfAborted();
const abort = () => void observation.close();
signal?.addEventListener("abort", abort, { once: true });
try {
await observation.start();
} finally {
signal?.removeEventListener("abort", abort);
}
if (signal?.aborted) {
await observation.close();
throw signal.reason;
}
await observation.start();
if (this.closePromise) {
await observation.close();
throw new Error("File observer is closed");
@@ -1,46 +0,0 @@
import { mkdtemp, rm } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { expect, test } from "vitest";
import { createFileObserver } from "../index.js";
import { createNativeRecursiveBackend } from "./native-recursive.js";
import { createManagedObservation } from "./observation.js";
import { createObserverPaths } from "./paths.js";
// Aborting a subscription closes its observation while start() may still be
// reading the root, before the backend has started.
test("closing an observation before its backend starts leaves no native watcher open", async () => {
const root = await mkdtemp(join(tmpdir(), "observation-close-"));
const paths = createObserverPaths(process.platform);
let openWatchers = 0;
const observation = createManagedObservation({
root,
callback: () => {},
options: {},
paths,
metrics: createFileObserver().getDiagnostics(),
createBackend: (host) =>
createNativeRecursiveBackend(host, paths, () => {
openWatchers += 1;
let open = true;
return {
close: () => {
if (open) openWatchers -= 1;
open = false;
},
on: () => {},
};
}),
onClosed: () => {},
});
try {
const started = observation.start();
const closed = observation.close();
await started;
await closed;
expect(openWatchers).toBe(0);
} finally {
await rm(root, { recursive: true, force: true });
}
});
@@ -69,9 +69,6 @@ class Observation implements ManagedObservation, ObservationHost {
if (!rootStats.isDirectory()) {
throw new Error(`File observation requires a directory: ${this.root}`);
}
// An aborted subscription can close the observation while the root is being read; the backend
// must not start after its close has already finished.
if (!this.isActive()) return;
try {
await this.backend.start();
} catch (error) {
@@ -527,25 +527,13 @@ test("agent creation hooks change the provider and environment before the sessio
});
server.addHook("agent.open.before", async ({ request }) => {
console.log(JSON.stringify({ hook: "agent.open.before", request }));
return { ...request, appendSystemPrompt: [...(request.appendSystemPrompt ?? []), "Plugin instructions"], env: { ...request.env, HOOK_OPEN: "opened" } };
return { ...request, env: { ...request.env, HOOK_OPEN: "opened" } };
});
server.addHook("agent.create.after", async (event) => {
console.log(JSON.stringify({ hook: "agent.create.after", event }));
});`,
reportOpen: true,
});
const extraPlugin = path.join(directory, "extra-plugin");
await mkdir(extraPlugin);
await writeFile(
path.join(extraPlugin, "paseo-plugin.json"),
JSON.stringify({ id: "a-prompt", requirements: { paseo: ">=0.8.0" } }),
);
const writePrompt = (prompt: string) =>
writeFile(
path.join(extraPlugin, "index.server.ts"),
`export default function contribute(server) { server.addHook("agent.open.before", async ({ request }) => ({ ...request, appendSystemPrompt: [...(request.appendSystemPrompt ?? []), ${JSON.stringify(prompt)}] })); return () => {}; }`,
);
await writePrompt("First plugin");
const daemon = await createTestPaseoDaemon();
const client = new DaemonClient({ url: `ws://127.0.0.1:${daemon.port}/ws` });
try {
@@ -553,17 +541,15 @@ test("agent creation hooks change the provider and environment before the sessio
await client.fetchAgents({ subscribe: {} });
await client.patchDaemonConfig({ pluginsEnabled: true });
await client.installDirectoryPlugin(pluginDirectory);
await client.installDirectoryPlugin(extraPlugin);
const agent = await client.createAgent({
provider: "claude",
cwd: directory,
title: "Hook test",
systemPrompt: "Saved instructions",
});
expect(agent.provider).toBe(PROVIDER_ID);
expect(await daemon.daemon.agentStorage.get(agent.id)).toMatchObject({
provider: PROVIDER_ID,
config: { model: "shutdown-model", systemPrompt: "Saved instructions" },
config: { model: "shutdown-model" },
});
await expect
.poll(async () => {
@@ -583,32 +569,13 @@ test("agent creation hooks change the provider and environment before the sessio
},
{
hook: "provider.open",
config: {
env: { HOOK_CREATE: "created", HOOK_OPEN: "opened" },
systemPrompt: "Saved instructions\n\nFirst plugin\n\nPlugin instructions",
},
config: { env: { HOOK_CREATE: "created", HOOK_OPEN: "opened" } },
},
{
hook: "agent.create.after",
event: { agent: { id: agent.id, provider: PROVIDER_ID } },
},
]);
await writePrompt("Changed plugin");
await client.reloadPlugin("a-prompt");
await daemon.daemon.agentManager.reloadAgentSession(agent.id);
await client.disablePlugin("a-prompt");
await daemon.daemon.agentManager.reloadAgentSession(agent.id);
const opens = (await client.getPluginLogs("shutdown-provider-plugin"))
.filter((entry) => entry.message.startsWith('{"hook":"provider.open"'))
.map((entry) => JSON.parse(entry.message).config.systemPrompt);
expect(opens).toEqual([
"Saved instructions\n\nFirst plugin\n\nPlugin instructions",
"Saved instructions\n\nChanged plugin\n\nPlugin instructions",
"Saved instructions\n\nPlugin instructions",
]);
expect((await daemon.daemon.agentStorage.get(agent.id))?.config?.systemPrompt).toBe(
"Saved instructions",
);
await client.archiveAgent(agent.id);
} finally {
await client.close();
@@ -228,9 +228,7 @@ test.each([{ title: "Changed" }, { labels: { changed: "true" } }, { background:
},
paseo,
),
).rejects.toThrow(
"agent.open.before hooks can only change env, tools, mcpServers, and appendSystemPrompt",
);
).rejects.toThrow("agent.open.before hooks can only change env, tools, and mcpServers");
},
);
@@ -359,42 +357,3 @@ test("checkout-branch hooks reject a branch-off baseRef", async () => {
validateBeforeResult("worktree.create.before", request, { ...request, baseRef: "main" }),
).rejects.toThrow(/baseRef/);
});
test("session-open instructions compose, survive old hooks, and are ignored for history", async () => {
const hooks = new PluginHookHandlers(() => {});
hooks.addHook("agent.open.before", async ({ request }) => ({
...request,
appendSystemPrompt: [...(request.appendSystemPrompt ?? []), "first"],
}));
hooks.addHook("agent.open.before", async ({ request }) => {
const { appendSystemPrompt: _ignored, ...oldRequest } = request;
return oldRequest;
});
hooks.addHook("agent.open.before", async ({ request }) => ({
...request,
appendSystemPrompt: [...(request.appendSystemPrompt ?? []), "second"],
}));
const input = {
agentId: "agent",
workspaceId: null,
provider: "codex",
cwd: "/project",
reason: "resume",
purpose: "interactive",
env: {},
title: null,
labels: {},
metadata: {},
tools: [],
mcpServers: {},
};
const interactive = await hooks.invoke("interactive", "agent.open.before", input, paseo);
expect(interactive).toMatchObject({ appendSystemPrompt: ["first", "second"] });
const history = await hooks.invoke(
"history",
"agent.open.before",
{ ...input, purpose: "history" },
paseo,
);
expect(history).not.toHaveProperty("appendSystemPrompt");
});
@@ -108,7 +108,6 @@ const beforeSchemas = {
labels: z.record(z.string(), z.string()),
// Optional so a plugin that returns its own object keeps working; omitted means unchanged.
metadata: z.record(z.string(), z.custom<JsonValue>()).optional(),
appendSystemPrompt: z.array(z.string()).optional(),
tools: z.array(agentToolMetadataSchema),
env: z.record(z.string(), z.string()),
mcpServers: CreateAgentRequestMessageSchema.shape.config.shape.mcpServers.unwrap(),
@@ -249,18 +248,9 @@ export async function validateBeforeResult<Name extends keyof PluginWireBeforeRe
const previous = beforeSchemas["agent.open.before"].parse(input);
const next = beforeSchemas["agent.open.before"].parse(result);
if (changesSessionOpenTarget(previous, next)) {
throw new Error(
"agent.open.before hooks can only change env, tools, mcpServers, and appendSystemPrompt",
);
throw new Error("agent.open.before hooks can only change env, tools, and mcpServers");
}
return {
...result,
background: previous.background,
metadata: previous.metadata,
...(next.appendSystemPrompt === undefined && previous.appendSystemPrompt !== undefined
? { appendSystemPrompt: previous.appendSystemPrompt }
: {}),
};
return { ...result, background: previous.background, metadata: previous.metadata };
}
if (name === "agent.create.before") {
const previous = beforeSchemas["agent.create.before"].parse(input);
@@ -386,7 +376,6 @@ export class PluginHookHandlers implements PluginLifecycleRegistration {
if (request.purpose === "history") {
request.tools = [];
request.mcpServers = {};
delete request.appendSystemPrompt;
} else this.agentTools?.attach(request.agentId, tools);
return request;
}
@@ -38,7 +38,6 @@ import {
type ScheduleServiceOptions,
} from "./service.js";
import { ScheduleStore } from "./store.js";
import { ForegroundPromptStart } from "../agent/agent-run-state.js";
import type { ScheduleExecutionResult, StoredSchedule } from "@getpaseo/protocol/schedule/types";
interface ScheduleServiceInternals {
@@ -755,7 +754,6 @@ describe("ScheduleService", () => {
agent.id,
expect.stringContaining(`Schedule fired (id=${schedule.id}, run=`),
undefined,
expect.any(ForegroundPromptStart),
]);
});
-1
View File
@@ -8993,7 +8993,6 @@ export class Session {
await waitForAgentRunStartWithTimeout(
this.agentManager,
agentId,
result.started,
this.delivery.requestSignal,
);
}

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