Compare commits

..
191 changed files with 1262 additions and 8259 deletions
+2 -2
View File
@@ -39,11 +39,11 @@
<img src="https://paseo.sh/mobile-mockup.png" alt="Paseo mobile app" width="100%">
</p>
Paseo is an open source agentic development environment for desktop, mobile, web, and CLI. Open the desktop app and work: agents, editor, terminals, diffs, pull requests, and a browser in one window. Run many agents at once, each in its own worktree, on one machine or several. The mobile app is the full app, native on iOS and Android.
Paseo is a desktop, mobile, web, and CLI app for coding agents. Open the desktop app and work: agents, editor, terminals, diffs, pull requests, and a browser in one window. Run many agents at once, each in its own worktree, on one machine or several. The mobile app is the full app, native on iOS and Android.
- **Parallel agents:** Run many agents at once, each in its own worktree.
- **Built-in orchestration:** Agents in Paseo can create worktrees, launch other agents, and talk to them, across providers.
- **Complete development workflow:** Edit files, review diffs, open pull requests, and run terminals, in split panes you arrange how you want.
- **Full IDE:** Edit files, review diffs, open pull requests, and run terminals, in split panes you arrange how you want.
- **Self-hosted:** Agents run on your machine with your full dev environment. Use your tools, your configs, and your skills.
- **Multi-provider:** Claude Code, Codex, Copilot, OpenCode, Pi, Antigravity, and Muse Code through the same interface. Pick the right model for each job.
- **Voice control:** Dictate tasks or talk through problems in voice mode. Hands-free when you need it.
+2 -28
View File
@@ -69,11 +69,11 @@ the marker. Closing a tab sets that client's label to `false`. Any `true` client
open. Detach clears the parent and every open-tab label. The surviving child therefore becomes a
normal root agent immediately, and closing its still-open tab archives it.
Runtime ownership is resolved from explicit workspace ID and caller context, never from `cwd`. Workspace creation is a separate operation with `local | worktree` isolation; agent creation reuses that workspace unless a new workspace is explicitly requested.
Runtime ownership is resolved from explicit workspace ID and caller context, never from `cwd`. Workspace creation is a separate operation with `local | worktree` isolation; agent creation only selects an existing workspace.
Users can also detach an existing subagent from the subagents track. Detach is deliberately a manual lifecycle gesture, not an agent-facing MCP tool. It removes the parent and open-tab lifecycle labels: it does not stop, archive, move, or restart the agent. The agent keeps its current `cwd` and `workspaceId`, leaves the former parent's track, and behaves like a root agent for tab close, workspace activity, and future parent archive.
`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` only for truly fire-and-forget agents or prompts.
`notifyOnFinish` defaults to `true` for agent-scoped creation and background prompt follow-ups because most delegated work needs to report back to the creating agent. Set it to `false` only for truly fire-and-forget agents or prompts.
Permission requests are notification checkpoints, not the end of that subscription. The caller is notified again after a permission response when the child finishes, errors, or requests another permission.
The permission notification includes the normalized request plus the child and request IDs, so the caller can inspect it and respond without fetching agent status.
A watched child that closes before its finish event also notifies the caller so delegated work cannot disappear silently during archive or workspace teardown.
@@ -84,32 +84,6 @@ Some providers can create their own child sessions inside one provider runtime.
The provider still owns the underlying runtime. Paseo keeps an agent record so the child can be opened, tracked, archived, and cascaded with the parent, but prompts and history hydration route through the provider adapter for that native child handle.
## Background workspaces
`workspace.background` controls discovery only. Background workspaces contain ordinary durable
agents and terminals: provider history, plugin hooks, parentage, archive, and restart recovery
keep their normal behavior. Visibility is creation-only; selecting an existing workspace cannot
change it. New workspaces default to false, inherit the caller workspace's value when an agent
creates one without an override, and accept explicit true or false.
The daemon derives agent discovery from workspace ownership. Default workspace and agent lists,
including History requests, exclude background work; `filter.includeBackground` includes it.
Exact-ID operations bypass discovery filtering. The app replicates both kinds and filters only
its sidebar with **Show background**, so direct navigation and restored tabs remain available.
Sequenced directories keep complete canonical collections. A filtered read must never replace
those collections with its subset. Inclusive and default observations have distinct cursor
scopes, so changing scope requires a fresh snapshot rather than reusing an incomplete cache.
Clients gate creation and inclusive discovery on `features.backgroundWorkspaces`.
### Private daemon helpers
Branch-name and commit-message generators still use private disposable internal runtimes.
`AgentManager` does not persist them or their provider sessions, excludes them from public
discovery and plugin hooks, and drops their timelines on archive. An archived helper retains
its exact-ID result briefly to cover completion before a waiter attaches. This internal
lifecycle is separate from public workspace visibility and is not a public creation option.
## Archive
Archive is a **soft delete**: the agent record stays on disk with `archivedAt` set, the runtime is closed, and the agent disappears from active lists. Archive is **global** — it lives on the server and propagates to every connected client.
-4
View File
@@ -345,10 +345,6 @@ join active work or reuse committed stages. A persisted resource alone cannot pr
that a provider accepted its initial prompt. Interrupted side effects with no conclusive
receipt return an unknown outcome instead of being repeated.
Agent registration commits creation. Rejecting the first prompt is a turn error on that
agent; reporting creation failure leaves an orphaned agent and invites another Create.
Receipt replay must not resend the prompt.
`packages/client/src/creation/` owns capability selection and legacy orchestration.
Callers always pass the initial prompt to agent creation. On an older host, the client
adapts keyed creation to the legacy create/send sequence; it cannot continue that
-2
View File
@@ -61,8 +61,6 @@ Core direct providers: `claude` (in `providers/claude/agent.ts`), `codex` (`code
Claude first-party model metadata lives in `packages/server/src/server/agent/providers/claude/model-manifest.ts`. When adding or updating a Claude model, update that manifest only; the model picker thinking options and Claude-specific feature gates are derived from the manifest. Do not add model-specific Claude capability lists in feature code.
Keep the curated Claude catalog: `supportedModels()` has historically omitted older versions and carries less metadata. Discovery is only an opt-in visibility gate, not a replacement catalog or an entitlement guarantee. Claude Code v2.1.197 added `resolvedModel` to disambiguate alias rows; a bare family alias does not establish access to a particular version. Explicit user-configured models must remain selectable when discovery fails or omits them.
Paseo tools are not implemented as MCP tools internally. They live in a shared tool catalog under `packages/server/src/server/agent/tools/`; MCP is only the fallback adapter. The daemon resolves `agents.providers.<provider>.paseoTools` by the exact provider ID. The catalog policy belongs to the caller: it filters the tools exposed to the current agent. When that agent calls `create_agent`, the child receives the policy for the child provider ID; the caller's policy is not inherited.
A provider that can register runtime tools directly should set `supportsNativePaseoTools: true` and consume the already-filtered `launchContext.paseoTools` in `createSession`/`resumeSession`. When native tools are present, `AgentManager` strips the internal Paseo MCP server from the provider launch config so the provider does not receive the same tools twice. Providers that only know MCP should keep `supportsMcpServers: true` and let the daemon inject `/mcp/agents`; the MCP server builds the same policy-filtered catalog for that caller. Filtering is enforced at catalog registration in both paths. Browser tools remain subject to the daemon browser-tools setting and browser-host availability.
+5 -19
View File
@@ -223,7 +223,7 @@ submission. Overlapping sends settle independently rather than collapsing to one
message.
Daemons advertising `server_info.features.canonicalSubmittedPrompts` guarantee that every accepted
human prompt carrying a client message id is recorded and streamed as a canonical `user_message` with that
prompt carrying a client message id is recorded and streamed as a canonical `user_message` with that
same id. This includes daemon-handled commands that do not allocate a foreground turn; their submitted
row is recorded before handler output. The app tracks submission transactions only for hosts with this
capability. Older hosts keep the shipped untracked optimistic-row behavior and roll that row back on RPC
@@ -238,25 +238,11 @@ foreground control ownership remains a separate daemon concern. Cancellation req
with that record rather than in a React component, so an old request cannot clear a newer one. Submissions
remain a separate pre-turn registry and retire on canonical acknowledgement.
Canonical turns and visible responses are different boundaries. Agent-originated prompts and lifecycle
notifications project into tool rows, so they do not create a human-message boundary. Legacy system
prompts, including schedule injections, remain hidden. One visible response can span several canonical
turns; layout and copy group that response together while lifecycle, timing, tool sequences, and exact
Canonical turns and visible responses are different boundaries. System-injected prompts are absent from
the Paseo timeline, so one visible response can span several canonical turns without a user message
between them. Layout and copy group that response together; lifecycle, timing, tool sequences, and exact
fork positions retain the canonical `turnId` boundaries.
Agent-message XML belongs to the daemon's `agent/agent-messages` boundary. Prompt delivery encodes
provenance; acceptance, provider echoes, import, and replay share its projection. The delivery ID is
also the projected call ID, so a provider echo cannot create a second row. Sender IDs are opaque and
do not imply local ownership or authorization. Capture the sender title at delivery: archived or
removed senders must remain understandable without a live directory lookup.
The optional `agentMessage` payload carries event, sender, and delivered text. Shared client
presentation (`protocol/agent-message-display`) owns its heading and expanded details. The daemon
must not construct UI labels or prepend sender labels to the semantic message body. The existing
`tool_call` / `plain_text` envelope is a compatibility adapter: older clients still parse the row and
expand its body. New clients use the typed payload, never infer the event from a tool name or parse
XML. Stream reduction and disk-cache serialization preserve the payload without rendering it.
The compatibility boundary for older daemons is snapshot normalization: running/idle status becomes an
anonymous active turn or idle state once, and downstream code consumes the same activity shape. The app
does not combine anonymous lifecycle events, timestamps, timeline rows, and resume coverage to infer a
@@ -264,7 +250,7 @@ second running state. Disconnect preserves the last replicated turn until cache
advances it; replica removal remains the destructive close boundary. Elapsed time comes only from turn
liveness, never from submission records or whichever timeline rows happen to be mounted.
For human prompts, the daemon records one canonical submitted user row at acceptance. Its wire `messageId` is the
The daemon records one canonical submitted user row at acceptance. Its wire `messageId` is the
submission's `clientMessageId`, so the row is born with its final identity and remains immutable on
the wire. A correlated provider echo records the provider's native identity internally without
dispatching another timeline event. Rewind resolves the wire identity to that provider identity at
+1 -1
View File
@@ -1 +1 @@
sha256-CK96G7MWsmd/VDvkuaFJ23U04EGNmeiXdTYbmR8RDDQ=
sha256-AKY6OMZgHeyn/To/2zsmtfb5C4fKniUp8gvpEYaR7/o=
-2
View File
@@ -2,7 +2,6 @@ const fs = require("node:fs");
const path = require("node:path");
const pkg = require("./package.json");
const withAndroidAsyncStorageSize = require("./plugins/with-android-async-storage-size");
const withAndroidOptionalCamera = require("./plugins/with-android-optional-camera");
const withAndroidProfileable = require("./plugins/with-android-profileable");
const withFdroidAutolinking = require("./plugins/with-fdroid-autolinking");
const withPasteInput = require("./plugins/with-paste-input");
@@ -146,7 +145,6 @@ export default {
withAndroidScroll,
[withAndroidAsyncStorageSize, 64],
...buildProfile.cameraPlugins,
withAndroidOptionalCamera,
[
"expo-splash-screen",
{
-61
View File
@@ -1,61 +0,0 @@
import { createRequire } from "node:module";
import { afterEach, describe, expect, it } from "vitest";
// Load the copies the Expo CLI uses for prebuild, not older hoisted ones.
const requireFromExpo = createRequire(require.resolve("expo/package.json"));
const requireFromExpoCli = createRequire(requireFromExpo.resolve("@expo/cli/package.json"));
const { getPrebuildConfigAsync } = requireFromExpoCli("@expo/prebuild-config");
const { compileModsAsync } = requireFromExpoCli(
"@expo/config-plugins/build/plugins/mod-compiler.js",
);
interface ManifestEntry {
$: Record<string, string>;
}
const originalFdroidFlag = process.env.PASEO_FDROID_BUILD;
async function resolveAndroidManifest() {
const { exp } = await getPrebuildConfigAsync(__dirname, { platforms: ["android"] });
await compileModsAsync(exp, {
projectRoot: __dirname,
introspect: true,
platforms: ["android"],
assertMissingModProviders: false,
});
return exp._internal.modResults.android.manifest.manifest;
}
describe("Android app config", () => {
afterEach(() => {
if (originalFdroidFlag === undefined) {
delete process.env.PASEO_FDROID_BUILD;
} else {
process.env.PASEO_FDROID_BUILD = originalFdroidFlag;
}
});
it.each([
["Google Play", "0"],
["F-Droid", "1"],
])(
"%s build installs on devices without a camera",
async (_build, fdroidFlag) => {
process.env.PASEO_FDROID_BUILD = fdroidFlag;
const manifest = await resolveAndroidManifest();
const permissions = (manifest["uses-permission"] ?? []).map(
(entry: ManifestEntry) => entry.$["android:name"],
);
const features = (manifest["uses-feature"] ?? []).map((entry: ManifestEntry) => entry.$);
expect(permissions).toContain("android.permission.CAMERA");
expect(features).toEqual(
expect.arrayContaining([
{ "android:name": "android.hardware.camera", "android:required": "false" },
{ "android:name": "android.hardware.camera.autofocus", "android:required": "false" },
]),
);
},
30_000,
);
});
@@ -284,6 +284,7 @@ async function expectRejectedSubmissionRestored(
await expectComposerDraft(page, input.prompt);
await expectComposerEditable(page);
await expectAttachmentPill(page, "composer-image-attachment-pill");
await expect(page.getByTestId("user-message").filter({ hasText: input.prompt })).toHaveCount(0);
if (input.preservesActiveTurn) {
await expect(page.getByTestId("turn-working-indicator")).toBeVisible();
return;
@@ -294,21 +295,13 @@ async function expectRejectedSubmissionRestored(
async function retryRestoredSubmission(page: Page, prompt: string): Promise<void> {
await page.getByRole("textbox", { name: "Message agent..." }).first().press("Enter");
const attempts = page.getByTestId("user-message").filter({ hasText: prompt });
await expect(attempts).toHaveCount(2);
const userMessage = attempts.last();
const userMessage = page.getByTestId("user-message").filter({ hasText: prompt });
await expect(userMessage).toHaveCount(1);
await expect(userMessage).toHaveAttribute("aria-busy", "false", { timeout: 30_000 });
await expect(userMessage.getByRole("button", { name: "Open image attachment" })).toBeVisible();
await expect(page.getByTestId("composer-image-attachment-pill")).toHaveCount(0);
}
async function expectRejectedPromptBeforeError(page: Page, prompt: string, errorMessage: string) {
const messages = page.getByTestId("user-message").or(page.getByTestId("assistant-message"));
await expect(messages).toHaveCount(2);
await expect(messages.nth(0)).toContainText(prompt);
await expect(messages.nth(1)).toContainText(`[System Error] ${errorMessage}`);
}
async function configureSteerInSettings(page: Page): Promise<void> {
const modifier = process.platform === "darwin" ? "Meta" : "Control";
await page.keyboard.press(`${modifier}+Comma`);
@@ -1180,14 +1173,13 @@ test.describe("Agent message submission", () => {
await toasts.expectNeverShown("agent-updating-toast");
});
test("retains a rejected submission before its error and accepts its retry", async ({
test("restores a rejected submission and accepts its retry", async ({
page,
rejectionScenario,
}) => {
const prompt = "Restore this rejected submission.";
await submitMessageThatWillBeRejected(page, prompt);
await expectRejectedSubmissionRestored(page, { prompt, ...rejectionScenario });
await expectRejectedPromptBeforeError(page, prompt, rejectionScenario.errorMessage);
await retryRestoredSubmission(page, prompt);
});
@@ -1217,7 +1209,6 @@ test.describe("Agent message submission", () => {
errorMessage: "Requested mock steer transport failure",
preservesActiveTurn: true,
});
await expect(page.getByTestId("user-message").filter({ hasText: prompt })).toHaveCount(0);
expect(gate.getClientRequestCount("send_agent_message_request")).toBe(sendsBefore + 1);
expect(gate.getClientRequestCount("cancel_agent_request")).toBe(cancelsBefore);
@@ -1,14 +1,7 @@
import type { Locator } from "@playwright/test";
import { writeFile } from "node:fs/promises";
import path from "node:path";
import { expect, test, type Page } from "../support/fixtures";
import { openAgentRoute, seedMockAgentWorkspace } from "../support/helpers/mock-agent";
import { gateNextAgentMessage } from "../support/helpers/agent-message-gate";
import {
fillComposerDraft,
expectComposerDraft,
attachFileFromMenu,
} from "../support/helpers/composer";
import { ensureExplorerSidebar, openFilesPanel } from "../support/helpers/workspace-tabs";
const APP_SETTINGS_KEY = "@paseo:app-settings";
@@ -33,19 +26,14 @@ async function openComposerDiff(page: Page) {
await composerChangesPill(page).click();
}
async function seedChangedAgent(
repoPrefix: string,
featureValues?: Record<string, unknown>,
files: Array<{ path: string; content: string }> = [],
) {
async function seedChangedAgent(repoPrefix: string) {
const workspace = await seedMockAgentWorkspace({
repoPrefix,
featureValues,
title: "Composer diff stat",
repo: {
withRemote: true,
// Exclude the local remote before the daemon starts observing this checkout.
files: [{ path: ".gitignore", content: "/remote.git/\n" }, ...files],
files: [{ path: ".gitignore", content: "/remote.git/\n" }],
},
});
try {
@@ -168,691 +156,3 @@ test("composer diff stat reveals Changes, then opens the diff in the focused pan
await workspace.cleanup();
}
});
async function tapFirstAddedDiffLine(
page: Page,
surface: Locator = page.getByTestId("working-diff-panel"),
) {
const body = surface.getByTestId("diff-file-0-body");
await expect(body).toBeVisible({ timeout: 30000 });
const bounds = await body.boundingBox();
if (!bounds) throw new Error("Expanded diff body has no bounds");
const fontSize = await surface
.getByTestId("git-diff-canvas")
.evaluate((element) => Number.parseFloat(getComputedStyle(element).fontSize));
await page.touchscreen.tap(bounds.x + 120, bounds.y + Math.round(fontSize * 1.5) * 2.5);
}
async function openReviewDiff(page: Page, workspace: Awaited<ReturnType<typeof seedChangedAgent>>) {
await page.setViewportSize({ width: 1400, height: 900 });
await openAgentRoute(page, { workspaceId: workspace.workspaceId, agentId: workspace.agentId });
await expect(composerChangesPill(page)).toBeVisible({ timeout: 30000 });
if (await page.getByTestId("workspace-tab-working_diff").count()) {
await selectDiffTab(page);
} else {
await revealComposerChangesInExplorer(page);
await openComposerDiff(page);
}
await expect(page.getByTestId("diff-file-0-body")).toBeVisible();
}
async function saveReviewComment(page: Page, body: string) {
await page.getByRole("textbox", { name: "Review comment" }).fill(body);
await page.getByRole("button", { name: "Save review comment", exact: true }).click();
await expect(page.getByRole("button", { name: "Bottom sheet backdrop" })).toHaveCount(0);
}
async function cancelReviewComment(page: Page) {
await page.getByRole("button", { name: "Cancel review comment", exact: true }).click();
await expect(page.getByRole("button", { name: "Bottom sheet backdrop" })).toHaveCount(0);
}
test.describe("review comments", () => {
test.use({ hasTouch: true });
test("compact review comments open a sheet and preserve saved comments through save, edit, cancel and reload", async ({
page,
}) => {
const workspace = await seedChangedAgent("compact-review-comment-");
try {
await test.step("Open a compact sheet with reachable input and actions", async () => {
await openReviewDiff(page, workspace);
await showCompactLayout(page);
await tapFirstAddedDiffLine(page);
await expectCompactCommentSheet(page);
});
await test.step("Save, discard an edit, then save an updated comment", async () => {
await saveReviewComment(page, " Please simplify this. ");
await expectSavedReview(page, "Please simplify this.");
await editSavedReview(page, "Please simplify this.");
await fillReviewComment(page, "Discard this edit");
await cancelReviewComment(page);
await expectSavedReview(page, "Please simplify this.");
await editSavedReview(page, "Please simplify this.");
await saveReviewComment(page, "Updated comment");
await expectSavedReview(page, "Updated comment");
});
await test.step("Discard a new comment and retain the saved one after reload", async () => {
await tapFirstAddedDiffLine(page);
await fillReviewComment(page, "Discard new comment");
await cancelReviewComment(page);
await expectReviewAbsent(page, "Discard new comment");
await reloadReview(page);
await expectSavedReview(page, "Updated comment");
});
} finally {
await workspace.cleanup();
}
});
test("wide review comments retain inline editing", async ({ page }) => {
const workspace = await seedChangedAgent("wide-review-comment-");
try {
await test.step("Save and cancel an inline edit on a wide screen", async () => {
await openReviewDiff(page, workspace);
await tapFirstAddedDiffLine(page);
await expectInlineCommentEditor(page);
await saveReviewComment(page, "Wide comment");
await expectSavedReview(page, "Wide comment");
await editSavedReview(page, "Wide comment");
await expectInlineCommentEditor(page);
await cancelReviewComment(page);
await expectSavedReview(page, "Wide comment");
});
await test.step("The existing composer still sends the review", async () => {
await sendReviewThroughComposer(page, workspace.agentId);
await selectDiffTab(page);
await expectReviewAbsent(page, "Wide comment");
});
} finally {
await workspace.cleanup();
}
});
});
async function sendReviewThroughComposer(page: Page, agentId: string) {
await page.getByTestId(`workspace-tab-agent_${agentId}`).click();
await expect(page.getByTestId("composer-review-attachment-pill")).toBeVisible();
await page.getByRole("textbox", { name: "Message agent..." }).fill("Address this review");
await page.getByRole("button", { name: "Send message", exact: true }).click();
await expect(page.getByText("Address this review", { exact: true }).first()).toBeVisible();
await expect(page.getByTestId("composer-review-attachment-pill")).toHaveCount(0);
}
async function addSavedReview(
page: Page,
body: string,
surface: Locator = page.getByTestId("working-diff-panel"),
) {
await tapFirstAddedDiffLine(page, surface);
await saveReviewComment(page, body);
await expectSavedReview(page, body, surface);
}
async function expectSavedReview(
page: Page,
body: string,
surface: Locator = page.getByTestId("working-diff-panel"),
) {
await expect(surface.getByText(body, { exact: true })).toBeVisible();
}
async function editSavedReview(page: Page, expectedBody: string) {
await page
.getByTestId("working-diff-panel")
.getByRole("button", { name: "Edit review comment", exact: true })
.click();
await expect(page.getByRole("textbox", { name: "Review comment" })).toHaveValue(expectedBody);
}
async function sendFeedback(page: Page, count: number) {
await page.getByRole("button", { name: `Send feedback (${count})`, exact: true }).click();
}
async function expectFeedbackSent(page: Page, recipient: string) {
await expect(page.getByText(`Feedback sent to ${recipient}`, { exact: true })).toBeVisible();
await expect(page.getByTestId("working-diff-panel")).toBeVisible();
}
test.describe("send review feedback", () => {
test.use({ hasTouch: true });
test("compact feedback sends directly to the only workspace agent and preserves its composer draft", async ({
page,
}) => {
const workspace = await seedChangedAgent("review-feedback-single-");
try {
await test.step("Save a review without changing the chat draft", async () => {
await openReviewDiff(page, workspace);
await selectAgentTab(page, workspace.agentId);
await fillComposerDraft(page, "Keep this thought");
await attachFileFromMenu(page, {
name: "unrelated.txt",
mimeType: "text/plain",
buffer: Buffer.from("Unrelated draft attachment"),
});
await selectDiffTab(page);
await showCompactLayout(page);
await addSavedReview(page, "Please simplify this.");
});
await test.step("Send directly and stay on the diff", async () => {
await sendFeedback(page, 1);
await expectFeedbackSent(page, "Composer diff stat");
await expectReviewAbsent(page, "Please simplify this.");
await captureFeedback(page, "single");
});
await test.step("Return to the untouched composer draft", async () => {
await showWideLayout(page);
await selectAgentTab(page, workspace.agentId);
await expectComposerDraft(page, "Keep this thought");
await expect(page.getByText("unrelated.txt", { exact: true })).toBeVisible();
await expect(page.getByTestId("composer-review-attachment-pill")).toHaveCount(0);
});
} finally {
await workspace.cleanup();
}
});
test("feedback pending ownership follows the draft across Diff and compact Changes", async ({
page,
}) => {
const workspace = await seedChangedAgent("review-shared-pending-");
const gate = await gateNextAgentMessage(page);
try {
await test.step("Send feedback from the Diff tab and hold its real request", async () => {
await openReviewDiff(page, workspace);
await showCompactLayout(page);
await addSavedReview(page, "One draft across surfaces");
await sendFeedback(page, 1);
await gate.waitForRequest();
});
await test.step("The compact Changes surface observes the same pending operation", async () => {
await revealCompactChanges(page);
await expect(
compactReviewSurface(page).getByRole("button", {
name: "Sending feedback (1)",
exact: true,
}),
).toBeDisabled();
expect(gate.requestCount()).toBe(1);
gate.accept();
await expect(
compactReviewSurface(page).getByText("Feedback sent to Composer diff stat", {
exact: true,
}),
).toBeVisible();
});
} finally {
await workspace.cleanup();
}
});
test("an unsaved review survives presentation changes and acknowledgement before Save", async ({
page,
}) => {
const workspace = await seedChangedAgent("review-editor-ownership-");
const gate = await gateNextAgentMessage(page);
try {
await test.step("Carry unsaved inline text into the compact sheet and back", async () => {
await openReviewDiff(page, workspace);
await tapFirstAddedDiffLine(page);
await fillReviewComment(page, "Body across presentations");
await showCompactLayout(page);
await expectReviewEditorBody(page, "Body across presentations");
await showWideLayout(page);
await expectReviewEditorBody(page, "Body across presentations");
await saveReviewComment(page, "Body across presentations");
});
await test.step("Keep an open edit saveable after acknowledgement removes its original", async () => {
await sendFeedback(page, 1);
await gate.waitForRequest();
await editSavedReview(page, "Body across presentations");
await fillReviewComment(page, "Keep this unsaved edit");
gate.accept();
await expectFeedbackSent(page, "Composer diff stat");
await expectReviewEditorBody(page, "Keep this unsaved edit");
await showCompactLayout(page);
await expectReviewEditorBody(page, "Keep this unsaved edit");
await saveReviewComment(page, "Keep this unsaved edit");
await expectSavedReview(page, "Keep this unsaved edit");
});
} finally {
await workspace.cleanup();
}
});
test("saved feedback preserves navigation across multiple diff files", async ({ page }) => {
const workspace = await seedMultiFileReview();
try {
await test.step("Save compact feedback and retain both floating actions", async () => {
await openCompactReviewExplorer(page, workspace);
await addSavedReview(page, "Keep file navigation available", compactReviewSurface(page));
await expectReviewNavigationReachable(page);
});
await test.step("Jump to another file without covering the feedback action", async () => {
await jumpToReviewFile(page, "z-last.ts");
await scrollReviewToLastLine(page);
await expectReviewNavigationReachable(page);
await captureFeedback(page, "navigation-compact");
});
await test.step("Wide file navigation and feedback remain reachable", async () => {
await openReviewDiff(page, workspace);
await navigateWideReviewFile(page, "README.md");
await expectFeedbackReachable(page);
await expectSavedReview(page, "Keep file navigation available");
await captureFeedback(page, "navigation-wide");
});
} finally {
await workspace.cleanup();
}
});
test("feedback sends only matching comments and preserves orphaned comments", async ({
page,
}) => {
const workspace = await seedMultiFileReview();
try {
await test.step("A saved comment whose diff disappears has no sendable context", async () => {
await openReviewDiff(page, workspace);
await showCompactLayout(page);
await addSavedReview(page, "Retain this orphan");
await setReadmeDiff(workspace, false);
await expectUnmatchedFeedback(page);
});
await test.step("Send the matching subset with an accurate count", async () => {
await addSavedReview(page, "Send this matching comment");
await sendFeedback(page, 1);
await expectFeedbackSent(page, "Composer diff stat");
await expectReviewAbsent(page, "Send this matching comment");
await expectUnmatchedFeedback(page);
});
await test.step("Restoring the missing diff reveals the unsent comment", async () => {
await setReadmeDiff(workspace, true);
await expectSavedReview(page, "Retain this orphan");
await expectFeedbackReachable(page);
});
} finally {
await workspace.cleanup();
}
});
test("zero open agent tabs retain feedback with a disabled reason", async ({ page }) => {
const workspace = await seedChangedAgent("review-feedback-zero-");
try {
await test.step("Close the agent tab while keeping the review", async () => {
await openReviewDiff(page, workspace);
await addSavedReview(page, "Keep until an agent is opened");
await closeAgentTab(page, workspace.agentId);
});
await test.step("The disabled action explains why in wide and compact layouts", async () => {
await expectFeedbackUnavailable(page);
await captureFeedback(page, "zero-wide");
await showCompactLayout(page);
await expectFeedbackUnavailable(page);
await expectSavedReview(page, "Keep until an agent is opened");
await captureFeedback(page, "zero-compact");
});
} finally {
await workspace.cleanup();
}
});
test("only open tabs in this workspace appear in compact and wide recipient menus", async ({
page,
}) => {
const workspace = await seedChangedAgent("review-feedback-multiple-");
const other = await seedChangedAgent("review-feedback-other-");
try {
const second = await createReviewRecipient(workspace, "Second reviewer");
const historical = await createReviewRecipient(workspace, "Closed historical agent");
await test.step("Open two local tabs and a tab in another workspace", async () => {
await openReviewDiff(page, other);
await addSavedReview(page, "Other workspace review");
await openReviewDiff(page, workspace);
await closeAgentTab(page, historical.id);
await openAgentRoute(page, { workspaceId: workspace.workspaceId, agentId: second.id });
await selectDiffTab(page);
await addSavedReview(page, "Review for second agent");
});
await test.step("The wide menu includes only local open agents", async () => {
await captureWideFeedbackAppearance(page);
});
await test.step("Escape returns keyboard focus to feedback so the chooser can reopen", async () => {
await openFeedbackWithKeyboard(page);
await dismissRecipientMenu(page);
await expectFeedbackFocused(page);
await reopenFeedbackWithKeyboard(page);
await dismissRecipientMenu(page);
await expectFeedbackFocused(page);
});
await test.step("Choose the second agent in the compact menu and stay on the diff", async () => {
await showCompactLayout(page);
await captureFeedback(page, "cta-compact");
await sendFeedback(page, 1);
await expectRecipientMenu(page);
await captureFeedback(page, "menu-compact");
await chooseFeedbackRecipient(page, "Second reviewer");
await expectFeedbackSent(page, "Second reviewer");
await expectReviewAbsent(page, "Review for second agent");
});
await test.step("The other workspace's saved review remains", async () => {
await openReviewDiff(page, other);
await expectSavedReview(page, "Other workspace review");
});
} finally {
await workspace.cleanup();
await other.cleanup();
}
});
test("failed feedback remains editable and retries through the real provider", async ({
page,
}) => {
const workspace = await seedChangedAgent("review-feedback-retry-", { mockPromptRejections: 1 });
try {
await test.step("A provider rejection retains the saved review", async () => {
await openReviewDiff(page, workspace);
await showCompactLayout(page);
await addSavedReview(page, "Initial feedback");
await sendFeedback(page, 1);
await expectFeedbackFailure(page);
await expectSavedReview(page, "Initial feedback");
await captureFeedback(page, "failure");
});
await test.step("Edit the retained feedback and retry successfully", async () => {
await editSavedReview(page, "Initial feedback");
await saveReviewComment(page, "Corrected feedback");
await sendFeedback(page, 1);
await expectFeedbackSent(page, "Composer diff stat");
await expectReviewAbsent(page, "Corrected feedback");
});
} finally {
await workspace.cleanup();
}
});
test("pending feedback blocks repeat submission and preserves edits and additions", async ({
page,
}) => {
const workspace = await seedChangedAgent("review-feedback-pending-");
const gate = await gateNextAgentMessage(page);
try {
await test.step("Hold the real request while feedback is pending", async () => {
await openReviewDiff(page, workspace);
await showCompactLayout(page);
await addSavedReview(page, "Sent version");
await sendFeedback(page, 1);
const request = await gate.waitForRequest();
expect(request.agentId).toBe(workspace.agentId);
expect(request.text).toBe("Please address this code review.");
expect(request.attachments).toMatchObject([
{
type: "review",
cwd: workspace.cwd,
comments: [
{
filePath: "README.md",
lineNumber: 2,
body: "Sent version",
context: { targetLine: { content: "export const one = 1;", newLineNumber: 2 } },
},
],
},
]);
await expectFeedbackPending(page);
});
await test.step("Save an edit and another comment before acknowledgement", async () => {
await editSavedReview(page, "Sent version");
await saveReviewComment(page, "Edited during send");
await addSavedReview(page, "Added during send");
await expectFeedbackPending(page);
expect(gate.requestCount()).toBe(1);
await captureFeedback(page, "pending");
});
await test.step("A real acknowledgement preserves both new versions", async () => {
gate.accept();
await expectFeedbackSent(page, "Composer diff stat");
await expectSavedReview(page, "Edited during send");
await expectSavedReview(page, "Added during send");
await expectReviewAbsent(page, "Sent version");
});
} finally {
await workspace.cleanup();
}
});
});
async function showCompactLayout(page: Page) {
await page.setViewportSize({ width: 390, height: 844 });
}
async function showWideLayout(page: Page) {
await page.setViewportSize({ width: 1400, height: 900 });
}
async function selectAgentTab(page: Page, agentId: string) {
await page.getByTestId(`workspace-tab-agent_${agentId}`).click({ position: { x: 12, y: 13 } });
}
async function selectDiffTab(page: Page) {
await page.getByTestId("workspace-tab-working_diff").click({ position: { x: 12, y: 13 } });
}
async function fillReviewComment(page: Page, body: string) {
await page.getByRole("textbox", { name: "Review comment" }).fill(body);
}
async function expectReviewAbsent(page: Page, body: string) {
await expect(page.getByTestId("working-diff-panel").getByText(body, { exact: true })).toHaveCount(
0,
);
}
async function reloadReview(page: Page) {
await page.reload();
await expect(page.getByTestId("working-diff-panel")).toBeVisible({ timeout: 30000 });
}
async function expectInlineCommentEditor(page: Page) {
await expect(page.getByTestId("inline-review-editor")).toBeVisible();
await expect(page.getByTestId("review-comment-sheet")).toHaveCount(0);
}
async function expectCompactCommentSheet(page: Page) {
await expect(page.getByTestId("review-comment-sheet")).toBeVisible();
await expect(page.getByText("README.md · +2", { exact: true })).toBeVisible();
await expect(page.getByRole("textbox", { name: "Review comment" })).toBeInViewport({ ratio: 1 });
for (const action of ["Save", "Cancel"])
await expect(
page.getByRole("button", { name: `${action} review comment`, exact: true }),
).toBeInViewport({ ratio: 1 });
await expect(page.getByTestId("inline-review-editor")).toHaveCount(0);
await expect(
page.getByRole("button", { name: "Save review comment", exact: true }),
).toBeDisabled();
}
function feedbackButton(page: Page) {
return page.getByRole("button", { name: "Send feedback (1)", exact: true });
}
async function openFeedbackWithKeyboard(page: Page) {
await feedbackButton(page).focus();
await expectFeedbackFocused(page);
await reopenFeedbackWithKeyboard(page);
}
async function reopenFeedbackWithKeyboard(page: Page) {
await page.keyboard.press("Enter");
await expectRecipientMenu(page);
const recipient = page.getByRole("menuitem", { name: "Composer diff stat", exact: true });
await recipient.focus();
await expect(recipient).toBeFocused();
}
async function expectFeedbackFocused(page: Page) {
await expect(feedbackButton(page)).toBeFocused();
}
async function captureWideFeedbackAppearance(page: Page) {
for (const colorScheme of ["light", "dark"] as const) {
await page.emulateMedia({ colorScheme });
await expectSavedReview(page, "Review for second agent");
await captureFeedback(page, `cta-wide-${colorScheme}-closed`);
await sendFeedback(page, 1);
await expectRecipientMenu(page);
await captureFeedback(page, `cta-wide-${colorScheme}-open`);
await dismissRecipientMenu(page);
}
await page.emulateMedia({ colorScheme: "light" });
}
async function captureFeedback(page: Page, name: string) {
await page.screenshot({ path: `/tmp/phase2-feedback-${name}.png` });
}
async function closeAgentTab(page: Page, agentId: string) {
await page.getByTestId(`workspace-tab-agent_${agentId}`).click({ button: "right" });
await page.getByTestId(`workspace-tab-context-agent_${agentId}-close`).click();
await expect(page.getByTestId(`workspace-tab-agent_${agentId}`)).toHaveCount(0);
}
async function expectFeedbackUnavailable(page: Page) {
await expect(page.getByRole("button", { name: "Send feedback (1)", exact: true })).toBeDisabled();
await expect(
page.getByText("Open an agent tab in this workspace to send feedback.", { exact: true }),
).toBeVisible();
}
async function createReviewRecipient(
workspace: Awaited<ReturnType<typeof seedChangedAgent>>,
title: string,
) {
return workspace.client.createAgent({
provider: "mock",
cwd: workspace.cwd,
workspaceId: workspace.workspaceId,
title,
modeId: "load-test",
model: "e2e-fast-stream",
});
}
async function expectRecipientMenu(page: Page) {
for (const name of ["Composer diff stat", "Second reviewer"]) {
await expect(page.getByRole("menuitem", { name, exact: true })).toBeInViewport({ ratio: 1 });
}
await expect(page.getByRole("menuitem")).toHaveCount(2);
}
async function dismissRecipientMenu(page: Page) {
await page.keyboard.press("Escape");
await expect(page.getByRole("menuitem")).toHaveCount(0);
}
async function chooseFeedbackRecipient(page: Page, name: string) {
await page.getByRole("menuitem", { name, exact: true }).click();
}
async function expectFeedbackFailure(page: Page) {
await expect(
page.getByText("Requested mock prompt rejection", { exact: true }).first(),
).toBeVisible();
await expect(page.getByRole("button", { name: "Send feedback (1)", exact: true })).toBeEnabled();
}
async function expectFeedbackPending(page: Page, count = 1) {
await expect(
page.getByRole("button", { name: `Sending feedback (${count})`, exact: true }),
).toBeDisabled();
}
async function seedMultiFileReview() {
const workspace = await seedChangedAgent("review-feedback-navigation-", undefined, [
{ path: "z-last.ts", content: "export const final = 0;\n" },
]);
await writeFile(
path.join(workspace.cwd, "z-last.ts"),
Array.from({ length: 120 }, (_, index) => `export const value${index} = ${index};`).join("\n") +
"\n",
);
await workspace.client.checkoutRefresh(workspace.cwd);
return workspace;
}
async function expectFeedbackReachable(page: Page) {
await expect(page.getByRole("button", { name: "Send feedback (1)", exact: true })).toBeInViewport(
{ ratio: 1 },
);
}
async function expectReviewNavigationReachable(page: Page) {
await expectFeedbackReachable(page);
const jump = page.getByRole("button", { name: "Jump to file", exact: true });
await expect(jump).toBeInViewport({ ratio: 1 });
const navigationBounds = await jump.boundingBox();
const feedbackBounds = await page
.getByRole("button", { name: "Send feedback (1)", exact: true })
.boundingBox();
if (!navigationBounds || !feedbackBounds) throw new Error("Review actions have no bounds");
expect(feedbackBounds.y + feedbackBounds.height).toBeLessThanOrEqual(navigationBounds.y);
}
async function jumpToReviewFile(page: Page, name: string) {
await page.getByRole("button", { name: "Jump to file", exact: true }).click();
const sheet = page.getByTestId("changes-jump-to-file-sheet");
await page
.getByTestId("changes-file-tree")
.filter({ visible: true })
.getByText(name, { exact: true })
.click();
await expect(sheet).toHaveCount(0);
await expect(reviewFileHeader(compactReviewSurface(page), name)).toBeInViewport();
}
async function navigateWideReviewFile(page: Page, name: string) {
const explorer = await ensureExplorerSidebar(page);
await explorer.getByTestId("changes-tree-panel").getByText(name, { exact: true }).click();
await expect(reviewFileHeader(page.getByTestId("working-diff-panel"), name)).toBeInViewport();
}
async function setReadmeDiff(
workspace: Awaited<ReturnType<typeof seedChangedAgent>>,
changed: boolean,
) {
await writeFile(
path.join(workspace.cwd, "README.md"),
changed ? "# Temp Repo\nexport const one = 1;\nexport const two = 2;\n" : "# Temp Repo\n",
);
await workspace.client.checkoutRefresh(workspace.cwd);
}
async function expectUnmatchedFeedback(page: Page) {
await expect(page.getByRole("button", { name: "Send feedback (0)", exact: true })).toBeDisabled();
await expect(
page.getByText("Saved comments no longer match this diff.", { exact: true }),
).toBeVisible();
}
function compactReviewSurface(page: Page) {
return page.getByTestId("explorer-content-area").filter({ visible: true });
}
async function openCompactReviewExplorer(
page: Page,
workspace: Awaited<ReturnType<typeof seedChangedAgent>>,
) {
await showWideLayout(page);
await openAgentRoute(page, { workspaceId: workspace.workspaceId, agentId: workspace.agentId });
await selectAgentTab(page, workspace.agentId);
await showCompactLayout(page);
await composerChangesPill(page).click();
await expect(compactReviewSurface(page).getByTestId("diff-file-0-body")).toBeVisible();
}
function reviewFileHeader(surface: Locator, name: string) {
return surface.locator(`[data-diff-header-path="${name}"]`).getByTestId(/^diff-file-\d+$/);
}
async function scrollReviewToLastLine(page: Page) {
const surface = compactReviewSurface(page);
const bounds = await surface.boundingBox();
if (!bounds) throw new Error("Compact review has no bounds");
await page.mouse.move(bounds.x + 120, bounds.y + 200);
await page.mouse.wheel(0, 10000);
await expect
.poll(async () => {
const body = await surface.getByTestId("diff-file-1-body").boundingBox();
const feedback = await page
.getByRole("button", { name: "Send feedback (1)", exact: true })
.boundingBox();
if (!body || !feedback) return false;
return body.y + body.height <= feedback.y;
})
.toBe(true);
}
async function revealCompactChanges(page: Page) {
await page.getByTestId("workspace-explorer-toggle").first().click();
await page.getByTestId("explorer-header").getByText("Changes", { exact: true }).click();
await expect(compactReviewSurface(page).getByTestId("diff-file-0-body")).toBeVisible();
}
async function expectReviewEditorBody(page: Page, body: string) {
await expect(page.getByRole("textbox", { name: "Review comment", exact: true })).toHaveValue(
body,
);
}
@@ -128,46 +128,3 @@ for (const scenario of [
await creation.expectAgentCount(1);
});
}
for (const entry of [
{
name: "agent draft",
open: (creation: Awaited<ReturnType<typeof createCreationScenario>>) =>
creation.openAgentDraft(),
button: "Send message",
settled: async (_creation: Awaited<ReturnType<typeof createCreationScenario>>) => {},
},
{
name: "new workspace",
open: (creation: Awaited<ReturnType<typeof createCreationScenario>>) =>
creation.openWorkspaceForm("local"),
button: "Create",
settled: (creation: Awaited<ReturnType<typeof createCreationScenario>>) =>
creation.expectOneCreatedWorkspace(),
},
]) {
test(`${entry.name} becomes an agent tab when the first prompt is rejected`, async ({
creation,
promptRejection,
page,
}, testInfo) => {
void promptRejection;
const prompt =
"Continue the attached conversation.\n" + "Earlier conversation context.\n".repeat(100);
await entry.open(creation);
await creation.submitPrompt(prompt, entry.button);
await entry.settled(creation);
await creation.expectCreatedAgentError();
await creation.expectPromptBeforeError(prompt);
await page.screenshot({ path: testInfo.outputPath("created-agent-prompt-error.png") });
await creation.reloadAgent();
await creation.expectPromptBeforeError(prompt);
await creation.submitPrompt("emit 1 coalesced agent stream updates for a corrected prompt.");
await creation.expectPromptVisible(
"emit 1 coalesced agent stream updates for a corrected prompt.",
);
await creation.expectAssistantReply();
await creation.expectAgentCount(1);
await expect(page.getByText("agent_request_key_conflict", { exact: true })).toHaveCount(0);
});
}
@@ -1,7 +1,6 @@
import { test, expect, type Page } from "../support/fixtures";
import { gotoAppShell } from "../support/helpers/app";
import { seedWorkspace } from "../support/helpers/seed-client";
import { openAgentRoute } from "../support/helpers/mock-agent";
import { getServerId } from "../support/helpers/server-id";
function workspaceRowTestId(workspaceId: string): string {
@@ -74,75 +73,3 @@ test.describe("Sidebar workspace rename", () => {
}
});
});
async function toggleBackgroundWorkspaces(page: Page): Promise<void> {
await page.getByLabel("Display preferences", { exact: true }).click();
await page.getByRole("menuitem", { name: "Show background", exact: true }).click();
await page.keyboard.press("Escape");
}
async function expectWorkspaceInSidebar(page: Page, workspaceId: string): Promise<void> {
// Rows have no single accessible role: their nested title and actions share this container.
await expect(page.getByTestId(workspaceRowTestId(workspaceId))).toBeVisible({ timeout: 30_000 });
}
async function expectWorkspaceHidden(page: Page, workspaceId: string): Promise<void> {
await expect(page.getByTestId(workspaceRowTestId(workspaceId))).toHaveCount(0);
}
async function reconnectApp(page: Page): Promise<void> {
await page.reload();
await expect(page.getByLabel("Display preferences", { exact: true })).toBeVisible();
}
async function expectWorkerOpen(page: Page): Promise<void> {
await expect(page.getByRole("textbox", { name: "Message agent..." })).toBeEditable({
timeout: 30_000,
});
await expect(page.getByText("Background reviewer", { exact: true }).first()).toBeVisible();
await expect(page.getByText("Background review prompt", { exact: true }).first()).toBeVisible();
}
test("background workspace stays directly accessible across sidebar toggles and reconnect", async ({
page,
}, testInfo) => {
const workspace = await seedWorkspace({
repoPrefix: "sidebar-background-",
title: "Background review",
background: true,
});
try {
const worker = await workspace.client.createAgent({
provider: "mock",
cwd: workspace.repoPath,
workspaceId: workspace.workspaceId,
title: "Background reviewer",
initialPrompt: "Background review prompt",
model: "e2e-fast-stream",
modeId: "load-test",
});
await test.step("Default sidebar hides background work", async () => {
await gotoAppShell(page);
await expectWorkspaceHidden(page, workspace.workspaceId);
});
await test.step("Show background exposes the fully replicated workspace", async () => {
await toggleBackgroundWorkspaces(page);
await expectWorkspaceInSidebar(page, workspace.workspaceId);
await reconnectApp(page);
await expectWorkspaceInSidebar(page, workspace.workspaceId);
});
await test.step("Direct agent navigation survives hiding and reconnect", async () => {
await toggleBackgroundWorkspaces(page);
await expectWorkspaceHidden(page, workspace.workspaceId);
await openAgentRoute(page, { workspaceId: workspace.workspaceId, agentId: worker.id });
await expectWorkerOpen(page);
await expectWorkspaceHidden(page, workspace.workspaceId);
await reconnectApp(page);
await expectWorkerOpen(page);
await expectWorkspaceHidden(page, workspace.workspaceId);
await page.screenshot({ path: testInfo.outputPath("background-direct-open.png") });
});
} finally {
await workspace.cleanup();
}
});
@@ -13,7 +13,6 @@ import { delayBrowserAgentCreatedStatus } from "./helpers/new-workspace";
export const test = base.extend<{
startup: { release(): Promise<void>; fail(): Promise<void> };
promptRejection: void;
creation: Awaited<ReturnType<typeof createCreationScenario>>;
promptRetry: ReturnType<typeof createPromptRetryScenario>;
agentRetries: Awaited<ReturnType<typeof retryNextAgentCreation>>;
@@ -66,37 +65,6 @@ export default function contribute(server) {
await client.close();
}
},
promptRejection: async ({ page }, provide) => {
void page;
const client = await connectNewWorkspaceDaemonClient();
const plugin = await copyPluginExample("lifecycle-logger");
const previous = await client.getDaemonConfig();
try {
await writeFile(
path.join(plugin.directory, "index.server.ts"),
`
export default function contribute(server) {
return server.before("agent.create", ({ request }) => ({
...request,
config: {
...request.config,
model: "e2e-fast-stream",
featureValues: { ...request.config.featureValues, mockPromptRejections: 1 },
},
}));
}
`,
);
await client.patchDaemonConfig({ pluginsEnabled: true });
await client.installDirectoryPlugin(plugin.directory);
await provide();
} finally {
await client.removePlugin("lifecycle-logger");
await client.patchDaemonConfig({ pluginsEnabled: previous.config.pluginsEnabled });
await plugin.cleanup();
await client.close();
}
},
creation: async ({ page }, provide) => {
const creation = await createCreationScenario(page);
try {
@@ -6,8 +6,6 @@ type WebSocketMessage = string | Buffer;
interface SendAgentMessageRequest {
type: "send_agent_message_request";
requestId: string;
text: unknown;
attachments: unknown;
agentId: string;
/** Absent when the client sends into an idle agent. */
activeTurnBehavior?: string;
@@ -31,8 +29,6 @@ function readSendRequest(message: WebSocketMessage): SendAgentMessageRequest | n
return {
type: "send_agent_message_request",
requestId: request.requestId,
text: request.text,
attachments: request.attachments,
agentId: request.agentId,
activeTurnBehavior:
typeof request.activeTurnBehavior === "string" ? request.activeTurnBehavior : undefined,
@@ -78,7 +74,6 @@ export async function gateNextAgentMessage(page: Page) {
return {
waitForRequest,
requestCount: () => requests.length,
accept(index = 0) {
const heldMessage = heldMessages[index];
if (!serverSocket || !heldMessage) {
@@ -98,6 +98,7 @@ async function createCodexRestoreJourney(page: Page, client: SeedDaemonClient, i
settings: { modeId: "full-access", thinkingOptionId: "low" },
title: "Codex worktree restore reproduction",
initialPrompt: `Reply with exactly ${REPLY} and nothing else. Do not use tools.`,
background: true,
}),
);
agentId = agent.agentId;
@@ -182,47 +182,6 @@ export async function createCreationScenario(page: Page) {
await this.expectWorkspaceReadyBeforeAgentCompletion();
expect((await project.client.fetchAgents()).entries).toHaveLength(0);
},
async expectCreatedAgentError() {
await requests.settled();
await expect(
page
.getByTestId("assistant-message")
.filter({ hasText: "[System Error] Requested mock prompt rejection", visible: true }),
).toBeVisible();
await expect(
page
.locator('[data-testid^="workspace-tab-agent_"][aria-selected="true"]')
.filter({ visible: true }),
).toBeVisible();
await expect(
page.locator('[data-testid^="workspace-tab-draft_"]').filter({ visible: true }),
).toHaveCount(0);
await expect(page.getByRole("textbox", { name: "Message agent..." }).first()).toBeEditable();
await expect(page.getByTestId("turn-working-indicator")).toHaveCount(0);
},
async expectPromptBeforeError(prompt: string) {
const messages = page
.getByTestId("user-message")
.or(page.getByTestId("assistant-message"))
.filter({ visible: true });
await expect(messages).toHaveCount(2);
await expect(messages.nth(0)).toContainText(prompt);
await expect(messages.nth(1)).toContainText("[System Error]");
await expect(messages.nth(1)).toBeInViewport();
},
async reloadAgent() {
await page.reload();
await expect(page.getByText("Updating messages", { exact: true })).toHaveCount(0);
await this.expectCreatedAgentError();
},
async expectAssistantReply() {
await expect(
page
.getByTestId("assistant-message")
.filter({ visible: true, hasNotText: "[System Error]" })
.first(),
).toBeVisible();
},
async expectStartupFailure() {
await expect(page.getByText(/Creation startup failed for test/).first()).toBeVisible();
},
@@ -66,7 +66,6 @@ export interface SeedDaemonClient {
worktreeSlug?: string;
};
title?: string;
background?: boolean;
}): Promise<{
workspace: SeedWorkspaceDescriptor | null;
error: string | null;
@@ -224,7 +223,6 @@ export interface SeededWorkspace {
export async function seedWorkspace(options: {
repoPrefix: string;
title?: string;
background?: boolean;
port?: number;
/** Repo fixture options; only applies to git projects (the default). */
repo?: Parameters<typeof createTempGitRepo>[1];
@@ -240,7 +238,6 @@ export async function seedWorkspace(options: {
const created = await client.createWorkspace({
source: { kind: "directory", path: project.path },
title: options.title,
background: options.background,
});
if (!created.workspace) {
throw new Error(created.error ?? `Failed to create workspace ${project.path}`);
@@ -1,24 +0,0 @@
const { withAndroidManifest } = require("expo/config-plugins");
// Requesting CAMERA implies these features are required, which hides the app
// on Google Play for devices without a camera. Pairing works without QR scanning.
const OPTIONAL_CAMERA_FEATURES = ["android.hardware.camera", "android.hardware.camera.autofocus"];
function withAndroidOptionalCamera(config) {
return withAndroidManifest(config, (modConfig) => {
const manifest = modConfig.modResults.manifest;
const features = manifest["uses-feature"] ?? [];
for (const name of OPTIONAL_CAMERA_FEATURES) {
const existing = features.find((feature) => feature.$["android:name"] === name);
if (existing) {
existing.$["android:required"] = "false";
} else {
features.push({ $: { "android:name": name, "android:required": "false" } });
}
}
manifest["uses-feature"] = features;
return modConfig;
});
}
module.exports = withAndroidOptionalCamera;
-1
View File
@@ -792,7 +792,6 @@ const AgentStreamViewComponent = forwardRef<AgentStreamViewHandle, AgentStreamVi
detail={data.detail}
cwd={context.cwd}
metadata={data.metadata}
agentMessage={data.agentMessage}
isLastInSequence={isLastInSequence}
onOpenFilePath={handleToolCallOpenFile}
maxDetailHeight={maxDetailHeight}
+5 -9
View File
@@ -1,4 +1,3 @@
import type { AgentMessage } from "@getpaseo/protocol/agent-message";
import { ASSISTANT_IMAGE_DEFAULT_ASPECT_RATIO } from "@/utils/assistant-image-metadata";
import { LoadingSpinner } from "@/components/ui/loading-spinner";
import { TaskListRow } from "@/components/task-list-row";
@@ -3023,7 +3022,6 @@ function areExpandableBadgePropsEqual(previous: ExpandableBadgeProps, next: Expa
}
interface ToolCallProps {
agentMessage?: AgentMessage;
toolName: string;
args?: unknown;
result?: unknown;
@@ -3043,7 +3041,6 @@ interface ToolCallProps {
}
export const ToolCall = memo(function ToolCall({
agentMessage,
toolName,
args,
result,
@@ -3084,7 +3081,6 @@ export const ToolCall = memo(function ToolCall({
const presentation = useMemo(
() =>
buildToolCallPresentation({
agentMessage,
toolName,
status,
error: error ?? null,
@@ -3093,7 +3089,7 @@ export const ToolCall = memo(function ToolCall({
cwd,
resolveIcon: resolveToolCallIcon,
}),
[toolName, status, error, effectiveDetail, metadata, cwd, agentMessage],
[toolName, status, error, effectiveDetail, metadata, cwd],
);
const handleOpenFile = useMemo(() => {
const openFilePath = presentation.openFilePath;
@@ -3109,7 +3105,7 @@ export const ToolCall = memo(function ToolCall({
toolName,
displayName: presentation.displayName,
summary: presentation.summary,
detail: presentation.detail,
detail: effectiveDetail,
errorText: presentation.errorText,
icon: presentation.icon,
showLoadingSkeleton: presentation.isLoadingDetails,
@@ -3121,12 +3117,12 @@ export const ToolCall = memo(function ToolCall({
shouldRenderInline,
openToolCall,
toolName,
presentation.detail,
presentation.displayName,
presentation.summary,
presentation.errorText,
presentation.icon,
presentation.isLoadingDetails,
effectiveDetail,
]);
useEffect(() => {
@@ -3162,7 +3158,7 @@ export const ToolCall = memo(function ToolCall({
return (
<ToolCallDetailsContent
toolName={toolName}
detail={presentation.detail}
detail={effectiveDetail}
errorText={presentation.errorText}
maxHeight={maxDetailHeight}
showLoadingSkeleton={presentation.isLoadingDetails}
@@ -3171,7 +3167,7 @@ export const ToolCall = memo(function ToolCall({
}, [
shouldRenderInline,
toolName,
presentation.detail,
effectiveDetail,
presentation.errorText,
presentation.isLoadingDetails,
maxDetailHeight,
@@ -63,7 +63,11 @@ import {
type SidebarWorkspacePlacement,
} from "@/hooks/use-sidebar-workspaces-list";
import { useSidebarOrderStore } from "@/stores/sidebar-order-store";
import { useSidebarViewStore, type SidebarGroupMode } from "@/stores/sidebar-view-store";
import {
hasActiveSidebarLabelFilter,
useSidebarViewStore,
type SidebarGroupMode,
} from "@/stores/sidebar-view-store";
import { useShowShortcutBadges } from "@/hooks/use-show-shortcut-badges";
import {
ContextMenu,
@@ -1915,6 +1919,9 @@ export function SidebarWorkspaceList({
const onToggleWorkspacePin = useSidebarWorkspacePinController();
const getPinnedWorkspaceOrder = useSidebarOrderStore((state) => state.getPinnedWorkspaceOrder);
const setPinnedWorkspaceOrder = useSidebarOrderStore((state) => state.setPinnedWorkspaceOrder);
const hasActiveLabelFilter = useSidebarViewStore((state) =>
hasActiveSidebarLabelFilter(state.labelFilter),
);
const handlePinnedWorkspaceReorder = useCallback(
(reorderedWorkspaces: SidebarWorkspacePlacement[]) => {
const reorderedWorkspaceKeys = reorderedWorkspaces.map((workspace) => workspace.workspaceKey);
@@ -1946,10 +1953,11 @@ export function SidebarWorkspaceList({
// this whole subtree, which unmounted the header — and the header is where the display menu's
// trigger lives, so filtering the last row away closed the menu you were filtering from.
//
// Background visibility can also hide the last project. Keep the header mounted
// whenever a local filter empties an otherwise populated directory, so users can
// reach the display menu to reveal their work again.
const sidebarFilterEmpty = hasProjectsBeforeFilter && projects.length === 0;
// Only the label filter can get here. The project filter resolves against the projects it can
// see and falls back to "all projects" when nothing matches, so it either keeps at least one
// project or is not applied at all — it can narrow this list but never empty it.
const sidebarFilterEmpty =
hasActiveLabelFilter && hasProjectsBeforeFilter && projects.length === 0;
// Project mode is the one that keeps its project headers; every other grouping mode is a flat
// list of grouped rows, so a new mode lands in the grouped branch rather than silently in this
@@ -301,13 +301,6 @@ export function SidebarDisplayPreferencesMenu(): ReactElement {
sheetTitle={t("sidebar.display.heading")}
testID="sidebar-display-preferences-content"
>
<MenuItem
selected={preferences.showBackground}
closeOnSelect={false}
onSelect={preferences.toggleBackground}
>
{t("sidebar.display.showBackground")}
</MenuItem>
<MenuSubTrigger
id="grouping"
value={t(GROUPING_LABEL_KEYS[preferences.grouping])}
@@ -16,8 +16,6 @@ import { DEFAULT_SIDEBAR_ROW_ITEMS, type SidebarRowItem, type SidebarRowItems }
export type SidebarTrailingChoice = Exclude<SidebarWorkspaceTrailing, "none">;
export interface SidebarDisplayPreferences {
showBackground: boolean;
toggleBackground: () => void;
grouping: SidebarGroupMode;
setGrouping: (mode: SidebarGroupMode) => void;
titleSource: WorkspaceTitleSource;
@@ -50,8 +48,6 @@ export interface SidebarDisplayPreferences {
* this for a value and set it; where it lands is this module's problem.
*/
export function useSidebarDisplayPreferences(): SidebarDisplayPreferences {
const showBackground = useSidebarViewStore((state) => state.showBackground);
const toggleBackground = useSidebarViewStore((state) => state.toggleBackground);
const grouping = useSidebarViewStore((state) => state.groupMode);
const setGrouping = useSidebarViewStore((state) => state.setGroupMode);
const hostFilters = useSidebarViewStore((state) => state.hostFilters);
@@ -108,8 +104,6 @@ export function useSidebarDisplayPreferences(): SidebarDisplayPreferences {
return useMemo(
() => ({
showBackground,
toggleBackground,
grouping,
setGrouping,
titleSource: workspaceTitleSource,
@@ -131,8 +125,6 @@ export function useSidebarDisplayPreferences(): SidebarDisplayPreferences {
clearLabelFilter,
}),
[
showBackground,
toggleBackground,
grouping,
setGrouping,
workspaceTitleSource,
@@ -57,7 +57,6 @@ export function SidebarModelProvider({
}) {
const { t } = useTranslation();
const list = useSidebarWorkspacesList({ enabled: active });
const showBackground = useSidebarViewStore((state) => state.showBackground);
const groupMode = useSidebarViewStore((state) => state.groupMode);
const labelFilter = useSidebarViewStore((state) => state.labelFilter);
const projectFilters = useSidebarViewStore((state) => state.projectFilters);
@@ -108,12 +107,9 @@ export function SidebarModelProvider({
workspaces: [...workspaceEntriesByKey.values()],
projectFilters: resolvedProjectFilters,
});
const filtered = filterWorkspacesByLabels({
workspaces: byProject.filter((workspace) => showBackground || !workspace.background),
...labelFilter,
});
const filtered = filterWorkspacesByLabels({ workspaces: byProject, ...labelFilter });
return new Map(filtered.map((workspace) => [workspace.workspaceKey, workspace]));
}, [showBackground, labelFilter, resolvedProjectFilters, workspaceEntriesByKey]);
}, [labelFilter, resolvedProjectFilters, workspaceEntriesByKey]);
const visibleWorkspaceKeys = useMemo(
() => new Set(filteredWorkspaceEntriesByKey.keys()),
[filteredWorkspaceEntriesByKey],
@@ -128,19 +124,16 @@ export function SidebarModelProvider({
const included = new Set(resolvedProjectFilters);
projects = projects.filter((project) => included.has(project.viewKey));
}
if (hasActiveLabelFilter || !showBackground) {
if (hasActiveLabelFilter) {
projects = projects.flatMap((project) => {
const workspaces = project.workspaces.filter((workspace) =>
visibleWorkspaceKeys.has(workspace.workspaceKey),
);
return workspaces.length > 0 || (!hasActiveLabelFilter && project.workspaces.length === 0)
? [{ ...project, workspaces }]
: [];
return workspaces.length > 0 ? [{ ...project, workspaces }] : [];
});
}
return projects;
}, [
showBackground,
hasActiveLabelFilter,
hasActiveProjectFilter,
resolvedProjectFilters,
@@ -174,7 +174,6 @@ export function Button({
...props
}: PropsWithChildren<
Omit<PressableProps, "style"> & {
ref?: React.Ref<View>;
variant?: ButtonVariant;
size?: ButtonSize;
leftIcon?: LeftIcon;
@@ -1,67 +1,47 @@
import { forwardRef, useMemo } from "react";
import { Text, type View } from "react-native";
import type { LucideIcon } from "lucide-react-native";
import { StyleSheet } from "react-native-unistyles";
import { PressHighlight } from "@/components/ui/press-highlight";
import { ICON_SIZE } from "@/styles/theme";
import { ICON_SIZE, SPACING } from "@/styles/theme";
import {
FLOATING_ACTION_BUTTON_SIZE,
FLOATING_ACTION_BUTTON_INSET,
} from "./floating-action-layout";
export {
FLOATING_ACTION_BUTTON_CLEARANCE,
floatingActionsClearance,
} from "./floating-action-layout";
const FLOATING_ACTION_BUTTON_SIZE = 56;
const FLOATING_ACTION_BUTTON_INSET = SPACING[4];
/** Space a scrolling surface keeps below its content so the button traps nothing. */
export const FLOATING_ACTION_BUTTON_CLEARANCE =
FLOATING_ACTION_BUTTON_SIZE + FLOATING_ACTION_BUTTON_INSET;
export interface FloatingActionButtonProps {
icon: LucideIcon;
/** Names the action for assistive technology. */
/** Names the action; the button carries no label. */
accessibilityLabel: string;
onPress: () => void;
label?: string;
disabled?: boolean;
bottomInset?: number;
testID?: string;
}
/**
* Pins an action to the bottom-right of its nearest positioned ancestor.
* The surface reserves scroll clearance and uses bottomInset to separate stacked actions.
* The one floating action a scrolling surface can offer. It pins itself to the
* bottom-right of its nearest positioned ancestor, so the ancestor decides what
* the button may cover.
*/
export const FloatingActionButton = forwardRef<View, FloatingActionButtonProps>(
function FloatingActionButton(
{ icon: Icon, accessibilityLabel, onPress, label, disabled = false, bottomInset = 0, testID },
ref,
) {
const accessibilityState = useMemo(() => ({ disabled }), [disabled]);
const buttonStyle = useMemo(
() => [
styles.button,
label && styles.labeled,
disabled && styles.disabled,
{ bottom: FLOATING_ACTION_BUTTON_INSET + bottomInset },
],
[bottomInset, disabled, label],
);
return (
<PressHighlight
ref={ref}
accessibilityRole="button"
accessibilityLabel={accessibilityLabel}
accessibilityState={accessibilityState}
disabled={disabled}
onPress={onPress}
style={buttonStyle}
highlightStyle={styles.pressed}
testID={testID}
>
<Icon size={ICON_SIZE.lg} color={styles.glyph.color} />
{label ? <Text style={styles.label}>{label}</Text> : null}
</PressHighlight>
);
},
);
export function FloatingActionButton({
icon: Icon,
accessibilityLabel,
onPress,
testID,
}: FloatingActionButtonProps) {
return (
<PressHighlight
accessibilityRole="button"
accessibilityLabel={accessibilityLabel}
onPress={onPress}
style={styles.button}
highlightStyle={styles.pressed}
testID={testID}
>
<Icon size={ICON_SIZE.lg} color={styles.glyph.color} />
</PressHighlight>
);
}
const styles = StyleSheet.create((theme) => ({
button: {
@@ -76,15 +56,6 @@ const styles = StyleSheet.create((theme) => ({
backgroundColor: theme.colors.surface3,
...theme.shadow.md,
},
labeled: {
width: "auto",
minWidth: FLOATING_ACTION_BUTTON_SIZE,
paddingHorizontal: theme.spacing[4],
flexDirection: "row",
gap: theme.spacing[2],
},
label: { color: theme.colors.foreground, fontSize: theme.fontSize.base },
disabled: { opacity: theme.opacity[50] },
pressed: {
backgroundColor: theme.colors.interactionHighlight,
},
@@ -1,17 +0,0 @@
import { describe, expect, it } from "vitest";
import {
floatingActionsClearance,
FLOATING_ACTION_BUTTON_CLEARANCE,
} from "./floating-action-layout";
describe("floating action scroll clearance", () => {
it("keeps the last diff line above Jump to file before and after feedback is added", () => {
const jump = FLOATING_ACTION_BUTTON_CLEARANCE;
const feedback = FLOATING_ACTION_BUTTON_CLEARANCE + 44;
expect(floatingActionsClearance([jump, 0], 34)).toBe(106);
expect(floatingActionsClearance([jump, feedback], 34)).toBe(222);
expect(floatingActionsClearance([0, feedback], 34)).toBe(150);
expect(floatingActionsClearance([jump, feedback], 0)).toBe(188);
expect(floatingActionsClearance([0, 0], 34)).toBe(0);
});
});
@@ -1,15 +0,0 @@
import { SPACING } from "@/styles/theme";
export const FLOATING_ACTION_BUTTON_SIZE = 56;
export const FLOATING_ACTION_BUTTON_INSET = SPACING[4];
export const FLOATING_ACTION_BUTTON_CLEARANCE =
FLOATING_ACTION_BUTTON_SIZE + FLOATING_ACTION_BUTTON_INSET;
/** Reserve the stacked actions and the safe-area inset once for their scrolling surface. */
export function floatingActionsClearance(
actionClearances: readonly number[],
bottomInset: number,
): number {
const clearance = actionClearances.reduce((total, action) => total + action, 0);
return clearance > 0 ? clearance + bottomInset : 0;
}
@@ -245,12 +245,3 @@ describe("bottom sheet visibility tracker", () => {
expect(context.backPress.press()).toBe(false);
});
});
it("does not cancel the owner's editor when the compact sheet leaves the tree on resize", () => {
const context = setup();
openSheet(context);
context.tracker.attachController(null);
context.tracker.handleSheetDismiss();
expect(context.closeCount()).toBe(0);
expect(context.backPress.press()).toBe(false);
});
@@ -121,9 +121,6 @@ export function createBottomSheetVisibilityTracker(opts: {
}
},
handleSheetDismiss() {
// Portal cleanup reports dismissal after the sheet leaves the tree. It is
// presentation teardown, so the owner keeps its desired state.
if (!controller) return;
if (visible) {
setPhase("dismissing");
notifyClose();
@@ -315,7 +315,6 @@ function reviewActionsForFirstAddition(): NonNullable<
commentsByTarget: new Map(),
editor: { target, commentId: null, body: "" },
onStartComment() {},
onChangeEditorBody() {},
onCancelEditor() {},
onSaveEditor() {},
onEditComment() {},
@@ -389,7 +389,6 @@ describe("diff document model", () => {
commentId: null,
},
onStartComment() {},
onChangeEditorBody() {},
onCancelEditor() {},
onSaveEditor() {},
onEditComment() {},
@@ -791,7 +790,6 @@ function reviewActionsWithEditor(
commentsByTarget: new Map(),
editor: target ? { target, body: "", commentId: null } : null,
onStartComment() {},
onChangeEditorBody() {},
onCancelEditor() {},
onSaveEditor() {},
onEditComment() {},
+20 -47
View File
@@ -1,5 +1,3 @@
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { floatingActionsClearance } from "@/components/ui/floating-action-button";
import { useState, useCallback, useMemo, type ReactElement, type ReactNode } from "react";
import { useTranslation } from "react-i18next";
import type { TFunction } from "i18next";
@@ -33,7 +31,6 @@ import {
import { type ParsedDiffFile } from "@/git/use-diff-query";
import type { ChangesState } from "@/panels/changes/state";
import { defaultChangesState } from "@/panels/changes/state";
import { ReviewCommentSheet, ReviewFeedbackAction } from "@/review";
import { DiffDocument, type WorkingDiffMode } from "@/git/diff-document";
import { ChangedFilesTree } from "@/git/changed-files-tree";
import { JUMP_TO_FILE_CLEARANCE, JumpToFile } from "@/git/jump-to-file";
@@ -1551,9 +1548,7 @@ export function ChangesSurface({
isDiffLoading,
reviewActions,
reviewAttachment,
reviewFeedback,
} = useWorkingDiff({
presentation,
serverId,
workspaceId: workspaceId ?? undefined,
cwd,
@@ -1734,7 +1729,6 @@ export function ChangesSurface({
],
);
const { bottom: bottomInset } = useSafeAreaInsets();
const hasChanges = files.length > 0;
const jumpToFileInset = jumpToFileClearance({
isCompact: isMobile,
@@ -1784,41 +1778,27 @@ export function ChangesSurface({
});
const diffContent: ReactElement = (
<View style={styles.diffContainer}>
<DiffBodyContent
isStatusLoading={isStatusLoading}
statusErrorMessage={statusErrorMessage}
notGit={notGit}
isDiffLoading={isDiffLoading}
diffErrorMessage={diffErrorMessage}
diffTooLarge={diffTooLarge}
hasChanges={hasChanges}
emptyMessage={emptyMessage}
emptyAction={emptyAction}
checkingRepositoryLabel={t("workspace.git.diff.checkingRepository")}
notRepositoryLabel={t("workspace.git.diff.notRepository")}
>
<DiffDocument
files={files}
contentInsetBottom={floatingActionsClearance(
[jumpToFileInset, reviewFeedback.clearance],
bottomInset,
)}
collapseState={collapseState}
displayPreferences={sharedDisplayPreferences}
mode={workingMode}
/>
</DiffBodyContent>
<ReviewFeedbackAction
bottomOffset={jumpToFileInset}
enabled={enabled}
hasDiff={presentation !== "tree"}
model={reviewFeedback.model}
state={reviewFeedback.state}
serverId={serverId}
workspaceId={workspaceId}
<DiffBodyContent
isStatusLoading={isStatusLoading}
statusErrorMessage={statusErrorMessage}
notGit={notGit}
isDiffLoading={isDiffLoading}
diffErrorMessage={diffErrorMessage}
diffTooLarge={diffTooLarge}
hasChanges={hasChanges}
emptyMessage={emptyMessage}
emptyAction={emptyAction}
checkingRepositoryLabel={t("workspace.git.diff.checkingRepository")}
notRepositoryLabel={t("workspace.git.diff.notRepository")}
>
<DiffDocument
files={files}
contentInsetBottom={jumpToFileInset}
collapseState={collapseState}
displayPreferences={sharedDisplayPreferences}
mode={workingMode}
/>
</View>
</DiffBodyContent>
);
const bodyContent = (
<ChangesBody
@@ -1954,13 +1934,6 @@ export function ChangesSurface({
) : null}
</View>
<ReviewCommentSheet
enabled={enabled}
editor={reviewActions.sheetEditor}
reviewActions={reviewActions}
onChangeBody={reviewActions.onChangeEditorBody}
/>
<ChangesCommits
presentation={presentation}
serverId={serverId}
@@ -1,7 +1,6 @@
import { useCallback, useMemo, useState } from "react";
import { useTranslation } from "react-i18next";
import { View } from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { StyleSheet, withUnistyles } from "react-native-unistyles";
import { FolderTree } from "lucide-react-native";
import {
@@ -54,7 +53,6 @@ export interface JumpToFileProps {
/** Compact overview of a loaded diff: a floating action that opens the changed-files tree. */
export function JumpToFile({ files, mode, onSelectFile }: JumpToFileProps) {
const { t } = useTranslation();
const { bottom } = useSafeAreaInsets();
const [isOpen, setIsOpen] = useState(false);
// The sheet is a transient overview, so it always opens fully expanded and
// never writes to the panel's persisted folder state.
@@ -85,7 +83,6 @@ export function JumpToFile({ files, mode, onSelectFile }: JumpToFileProps) {
<>
<FloatingActionButton
icon={FolderTree}
bottomInset={bottom}
accessibilityLabel={title}
onPress={open}
testID="changes-jump-to-file"
+1 -12
View File
@@ -7,7 +7,6 @@ import {
buildReviewDraftKey,
useInlineReviewController,
useReviewAttachmentSnapshot,
useReviewFeedback,
} from "@/review";
import { useCheckoutDiffQuery } from "@/git/use-diff-query";
import { useCheckoutStatusQuery } from "@/git/use-status-query";
@@ -20,7 +19,6 @@ interface UseWorkingDiffOptions {
ignoreWhitespace: boolean;
enabled: boolean;
queryScope?: string;
presentation?: string;
}
export function useWorkingDiff({
@@ -30,7 +28,6 @@ export function useWorkingDiff({
ignoreWhitespace,
enabled,
queryScope,
presentation,
}: UseWorkingDiffOptions) {
const {
status,
@@ -84,7 +81,7 @@ export function useWorkingDiff({
}),
[baseRef, cwd, diffMode, ignoreWhitespace, serverId, workspaceId],
);
const reviewActions = useInlineReviewController({ reviewDraftKey, presentation });
const reviewActions = useInlineReviewController({ reviewDraftKey });
const reviewAttachment = useReviewAttachmentSnapshot({
key: reviewDraftKey,
diffFiles: files,
@@ -93,13 +90,6 @@ export function useWorkingDiff({
baseRef,
});
const reviewFeedback = useReviewFeedback({
serverId,
workspaceId,
reviewDraftKey,
attachment: reviewAttachment,
});
return {
status,
isStatusLoading,
@@ -117,7 +107,6 @@ export function useWorkingDiff({
isDiffLoading,
reviewActions,
reviewAttachment,
reviewFeedback,
};
}
@@ -27,7 +27,6 @@ export interface SidebarWorkspacePlacement {
workspaceDirectory?: string;
projectKind: WorkspaceStructureProject["projectKind"];
workspaceKind: WorkspaceDescriptor["workspaceKind"];
background?: boolean;
name: string;
}
@@ -165,7 +164,6 @@ export function createSidebarWorkspaceEntry(input: {
input.workspace.worktreeSlug ?? shortenPath(input.workspace.workspaceDirectory),
projectKind: input.workspace.projectKind,
workspaceKind: input.workspace.workspaceKind,
background: input.workspace.background,
name: input.workspace.name,
title: input.workspace.title ?? null,
pinnedAt: input.workspace.pinnedAt,
-13
View File
@@ -30,7 +30,6 @@ export const ar: TranslationResources = {
back: "خلف",
loading: "تحميل...",
actions: {
save: "حفظ",
back: "خلف",
cancel: "يلغي",
close: "يغلق",
@@ -1148,7 +1147,6 @@ export const ar: TranslationResources = {
done: "تم",
},
display: {
showBackground: "إظهار مساحات العمل في الخلفية",
trigger: "تفضيلات العرض",
heading: "العرض",
grouping: {
@@ -2006,17 +2004,6 @@ export const ar: TranslationResources = {
accessibility: "تم استخدام نافذة السياق{{percentage}}%",
},
review: {
feedback: {
send: "إرسال الملاحظات ({{count}})",
sending: "جارٍ إرسال الملاحظات ({{count}})",
chooseAgent: "اختر وكيلاً",
sent: "تم إرسال الملاحظات إلى {{recipient}}",
"no-agents": "افتح علامة تبويب وكيل في مساحة العمل هذه لإرسال الملاحظات.",
disconnected: "اتصل بالمضيف لإرسال الملاحظات.",
"no-context": "لم تعد التعليقات المحفوظة تتطابق مع هذا الفرق.",
failed: "تعذر إرسال الملاحظات. حاول مرة أخرى.",
prompt: "يرجى معالجة مراجعة الكود هذه.",
},
comment: {
add: "إضافة تعليق المراجعة",
edit: "تحرير تعليق المراجعة",
-13
View File
@@ -26,7 +26,6 @@ export const en = {
back: "Back",
loading: "Loading...",
actions: {
save: "Save",
back: "Back",
cancel: "Cancel",
close: "Close",
@@ -1156,7 +1155,6 @@ export const en = {
done: "Done",
},
display: {
showBackground: "Show background",
trigger: "Display preferences",
heading: "Display",
grouping: {
@@ -2031,17 +2029,6 @@ export const en = {
accessibility: "Context window {{percentage}}% used",
},
review: {
feedback: {
send: "Send feedback ({{count}})",
sending: "Sending feedback ({{count}})",
chooseAgent: "Choose an agent",
sent: "Feedback sent to {{recipient}}",
"no-agents": "Open an agent tab in this workspace to send feedback.",
disconnected: "Connect to the host to send feedback.",
"no-context": "Saved comments no longer match this diff.",
failed: "Failed to send feedback. Try again.",
prompt: "Please address this code review.",
},
comment: {
add: "Add review comment",
edit: "Edit review comment",
-13
View File
@@ -31,7 +31,6 @@ export const es: TranslationResources = {
back: "Atrás",
loading: "Cargando...",
actions: {
save: "Guardar",
back: "Atrás",
cancel: "Cancelar",
close: "Cerrar",
@@ -1184,7 +1183,6 @@ export const es: TranslationResources = {
done: "Terminado",
},
display: {
showBackground: "Mostrar espacios en segundo plano",
trigger: "Preferencias de visualización",
heading: "Visualización",
grouping: {
@@ -2054,17 +2052,6 @@ export const es: TranslationResources = {
accessibility: "Ventana de contexto{{percentage}}% utilizada",
},
review: {
feedback: {
send: "Enviar comentarios ({{count}})",
sending: "Enviando comentarios ({{count}})",
chooseAgent: "Elegir un agente",
sent: "Comentarios enviados a {{recipient}}",
"no-agents": "Abre una pestaña de agente en este espacio de trabajo para enviar comentarios.",
disconnected: "Conéctate al host para enviar comentarios.",
"no-context": "Los comentarios guardados ya no coinciden con este diff.",
failed: "No se pudieron enviar los comentarios. Inténtalo de nuevo.",
prompt: "Por favor, atiende esta revisión de código.",
},
comment: {
add: "Agregar comentario de revisión",
edit: "Editar comentario de revisión",
-14
View File
@@ -31,7 +31,6 @@ export const fr: TranslationResources = {
back: "Retour",
loading: "Chargement…",
actions: {
save: "Enregistrer",
back: "Retour",
cancel: "Annuler",
close: "Fermer",
@@ -1175,7 +1174,6 @@ export const fr: TranslationResources = {
done: "Terminé",
},
display: {
showBackground: "Afficher les espaces en arrière-plan",
trigger: "Préférences d’affichage",
heading: "Affichage",
grouping: {
@@ -2051,18 +2049,6 @@ export const fr: TranslationResources = {
accessibility: "Fenêtre de contexte : {{percentage}} % utilisés",
},
review: {
feedback: {
send: "Envoyer les commentaires ({{count}})",
sending: "Envoi des commentaires ({{count}})",
chooseAgent: "Choisir un agent",
sent: "Commentaires envoyés à {{recipient}}",
"no-agents":
"Ouvrez un onglet d’agent dans cet espace de travail pour envoyer les commentaires.",
disconnected: "Connectez-vous à l’hôte pour envoyer les commentaires.",
"no-context": "Les commentaires enregistrés ne correspondent plus à ce diff.",
failed: "Échec de l’envoi des commentaires. Réessayez.",
prompt: "Veuillez traiter cette revue de code.",
},
comment: {
add: "Ajouter un commentaire de revue",
edit: "Modifier le commentaire de revue",
-14
View File
@@ -31,7 +31,6 @@ export const ja: TranslationResources = {
back: "戻る",
loading: "読み込み中...",
actions: {
save: "保存",
back: "戻る",
cancel: "キャンセル",
close: "閉じる",
@@ -1161,7 +1160,6 @@ export const ja: TranslationResources = {
done: "完了",
},
display: {
showBackground: "バックグラウンドを表示",
trigger: "表示設定",
heading: "表示",
grouping: {
@@ -2026,18 +2024,6 @@ export const ja: TranslationResources = {
accessibility: "コンテキストウィンドウ{{percentage}}%使用",
},
review: {
feedback: {
send: "フィードバックを送信 ({{count}})",
sending: "フィードバックを送信中 ({{count}})",
chooseAgent: "エージェントを選択",
sent: "{{recipient}} にフィードバックを送信しました",
"no-agents":
"フィードバックを送信するには、このワークスペースでエージェントタブを開いてください。",
disconnected: "フィードバックを送信するにはホストに接続してください。",
"no-context": "保存したコメントはこの差分と一致しなくなりました。",
failed: "フィードバックを送信できませんでした。もう一度お試しください。",
prompt: "このコードレビューに対応してください。",
},
comment: {
add: "レビューコメントを追加",
edit: "レビューコメントを編集",
-13
View File
@@ -30,7 +30,6 @@ export const ko: TranslationResources = {
back: "뒤로",
loading: "불러오는 중...",
actions: {
save: "저장",
back: "뒤로",
cancel: "취소",
close: "닫기",
@@ -1155,7 +1154,6 @@ export const ko: TranslationResources = {
done: "완료",
},
display: {
showBackground: "백그라운드 표시",
trigger: "표시 설정",
heading: "표시",
grouping: {
@@ -2016,17 +2014,6 @@ export const ko: TranslationResources = {
accessibility: "컨텍스트 윈도우 {{percentage}}% 사용됨",
},
review: {
feedback: {
send: "피드백 보내기 ({{count}})",
sending: "피드백 전송 중 ({{count}})",
chooseAgent: "에이전트 선택",
sent: "{{recipient}}에게 피드백을 보냈습니다",
"no-agents": "피드백을 보내려면 이 작업 공간에서 에이전트 탭을 여세요.",
disconnected: "피드백을 보내려면 호스트에 연결하세요.",
"no-context": "저장된 댓글이 더 이상 이 변경 사항과 일치하지 않습니다.",
failed: "피드백 전송에 실패했습니다. 다시 시도하세요.",
prompt: "이 코드 리뷰를 반영해 주세요.",
},
comment: {
add: "리뷰 댓글 추가",
edit: "리뷰 댓글 편집",
-13
View File
@@ -31,7 +31,6 @@ export const ptBR: TranslationResources = {
back: "Voltar",
loading: "Carregando...",
actions: {
save: "Salvar",
back: "Voltar",
cancel: "Cancelar",
close: "Fechar",
@@ -1174,7 +1173,6 @@ export const ptBR: TranslationResources = {
done: "Concluído",
},
display: {
showBackground: "Mostrar espaços em segundo plano",
trigger: "Preferências de exibição",
heading: "Exibição",
grouping: {
@@ -2039,17 +2037,6 @@ export const ptBR: TranslationResources = {
accessibility: "Janela de contexto {{percentage}}% usada",
},
review: {
feedback: {
send: "Enviar comentários ({{count}})",
sending: "Enviando comentários ({{count}})",
chooseAgent: "Escolher um agente",
sent: "Comentários enviados para {{recipient}}",
"no-agents": "Abra uma aba de agente neste espaço de trabalho para enviar comentários.",
disconnected: "Conecte-se ao host para enviar comentários.",
"no-context": "Os comentários salvos não correspondem mais a este diff.",
failed: "Falha ao enviar comentários. Tente novamente.",
prompt: "Por favor, atenda a esta revisão de código.",
},
comment: {
add: "Adicionar comentário de revisão",
edit: "Editar comentário de revisão",
-13
View File
@@ -31,7 +31,6 @@ export const ru: TranslationResources = {
back: "Назад",
loading: "Загрузка...",
actions: {
save: "Сохранить",
back: "Назад",
cancel: "Отмена",
close: "Закрыть",
@@ -1165,7 +1164,6 @@ export const ru: TranslationResources = {
done: "Готово",
},
display: {
showBackground: "Показать фоновые пространства",
trigger: "Настройки отображения",
heading: "Отображение",
grouping: {
@@ -2039,17 +2037,6 @@ export const ru: TranslationResources = {
accessibility: "Использовано {{percentage}}% контекстного окна",
},
review: {
feedback: {
send: "Отправить отзыв ({{count}})",
sending: "Отправка отзыва ({{count}})",
chooseAgent: "Выберите агента",
sent: "Отзыв отправлен: {{recipient}}",
"no-agents": "Откройте вкладку агента в этой рабочей области, чтобы отправить отзыв.",
disconnected: "Подключитесь к хосту, чтобы отправить отзыв.",
"no-context": "Сохранённые комментарии больше не соответствуют этому diff.",
failed: "Не удалось отправить отзыв. Повторите попытку.",
prompt: "Пожалуйста, учтите эту проверку кода.",
},
comment: {
add: "Добавить комментарий к ревью",
edit: "Изменить комментарий к ревью",
-13
View File
@@ -30,7 +30,6 @@ export const zhCN: TranslationResources = {
back: "返回",
loading: "加载中...",
actions: {
save: "保存",
back: "返回",
cancel: "取消",
close: "关闭",
@@ -1140,7 +1139,6 @@ export const zhCN: TranslationResources = {
done: "已完成",
},
display: {
showBackground: "显示后台工作区",
trigger: "显示偏好",
heading: "显示",
grouping: {
@@ -1984,17 +1982,6 @@ export const zhCN: TranslationResources = {
accessibility: "上下文窗口已使用 {{percentage}}%",
},
review: {
feedback: {
send: "发送反馈 ({{count}})",
sending: "正在发送反馈 ({{count}})",
chooseAgent: "选择智能体",
sent: "已向 {{recipient}} 发送反馈",
"no-agents": "请在此工作区打开智能体标签页以发送反馈。",
disconnected: "请连接到主机以发送反馈。",
"no-context": "保存的评论不再匹配此差异。",
failed: "发送反馈失败。请重试。",
prompt: "请处理此代码审查。",
},
comment: {
add: "添加 review 评论",
edit: "编辑 review 评论",
-106
View File
@@ -1,106 +0,0 @@
import { useCallback, useMemo } from "react";
import { Text, View } from "react-native";
import { useTranslation } from "react-i18next";
import { StyleSheet } from "react-native-unistyles";
import { AdaptiveModalSheet } from "@/components/adaptive-modal-sheet";
import { FormTextInput } from "@/components/ui/form-field";
import { Button } from "@/components/ui/button";
import type { InlineReviewActions, InlineReviewEditorState } from "./geometry";
export function ReviewCommentSheet({
editor,
reviewActions,
onChangeBody,
enabled,
}: {
enabled: boolean | undefined;
editor: InlineReviewEditorState | null;
reviewActions: InlineReviewActions;
onChangeBody: (body: string) => void;
}) {
if (enabled === false || !editor) return null;
return (
<OpenReviewCommentSheet
editor={editor}
reviewActions={reviewActions}
onChangeBody={onChangeBody}
/>
);
}
function OpenReviewCommentSheet({
editor,
reviewActions,
onChangeBody,
}: {
editor: InlineReviewEditorState;
reviewActions: InlineReviewActions;
onChangeBody: (body: string) => void;
}) {
const { t } = useTranslation();
const context = `${editor.target.filePath} · ${editor.target.side === "old" ? "−" : "+"}${editor.target.lineNumber}`;
const header = useMemo(
() => ({
title: t("review.comment.label"),
subtitle: <Text style={styles.context}>{context}</Text>,
}),
[context, t],
);
const { onSaveEditor, onCancelEditor } = reviewActions;
const handleSave = useCallback(() => onSaveEditor(editor.body), [onSaveEditor, editor.body]);
const canSave = editor.body.trim().length > 0;
const footer = useMemo(
() => (
<View style={styles.actions}>
<Button
size="md"
variant="secondary"
accessibilityLabel={t("review.comment.cancelAccessibility")}
onPress={onCancelEditor}
>
{t("review.comment.cancel")}
</Button>
<Button
size="md"
variant="default"
accessibilityLabel={t("review.comment.saveAccessibility")}
disabled={!canSave}
onPress={handleSave}
>
{t("common.actions.save")}
</Button>
</View>
),
[canSave, handleSave, onCancelEditor, t],
);
return (
<AdaptiveModalSheet
visible
header={header}
onClose={onCancelEditor}
snapPoints={COMMENT_SNAP_POINTS}
scrollable={false}
testID="review-comment-sheet"
footer={footer}
>
<FormTextInput
key={editor.target.key + (editor.commentId ?? "new")}
size="md"
multiline
accessibilityLabel={t("review.comment.label")}
placeholder={t("review.comment.placeholder")}
initialValue={editor.body}
onChangeText={onChangeBody}
style={styles.input}
/>
</AdaptiveModalSheet>
);
}
const COMMENT_SNAP_POINTS = ["50%", "90%"];
const styles = StyleSheet.create((theme) => ({
context: { color: theme.colors.foregroundMuted, fontSize: theme.fontSize.sm },
input: { flex: 1, minHeight: 0, textAlignVertical: "top" },
actions: { flex: 1, flexDirection: "row", justifyContent: "flex-end", gap: theme.spacing[2] },
}));
@@ -1,145 +0,0 @@
import { describe, expect, it } from "vitest";
import { createReviewEditor, createReviewEditorScope, type ReviewCommentWriter } from "./index";
import type { ReviewDraftComment } from "../state";
import type { ReviewableDiffTarget } from "@/utils/diff-layout";
const target: ReviewableDiffTarget = {
key: "src/example.ts:new:2",
filePath: "src/example.ts",
side: "new",
lineNumber: 2,
hunkHeader: "@@ -1,2 +1,2 @@",
hunkIndex: 0,
lineIndex: 2,
oldLineNumber: null,
newLineNumber: 2,
lineType: "add",
content: "const value = next;",
};
function memoryWriter() {
const drafts = new Map<string, ReviewDraftComment[]>();
let sequence = 0;
const writer: ReviewCommentWriter = {
saveComment: ({ key, id, comment }) => {
const current = drafts.get(key) ?? [];
if (id && current.some((saved) => saved.id === id)) {
drafts.set(
key,
current.map((saved) => (saved.id === id ? { ...saved, ...comment } : saved)),
);
} else {
const saved = {
...comment,
id: String(++sequence),
createdAt: "2026-10-09T00:00:00Z",
updatedAt: "2026-10-09T00:00:00Z",
};
drafts.set(key, [...current, saved]);
}
},
deleteComment: ({ key, id }) => {
drafts.set(
key,
(drafts.get(key) ?? []).filter((comment) => comment.id !== id),
);
},
};
return { writer, comments: (key: string) => drafts.get(key) ?? [] };
}
describe("review editor", () => {
it("saves trimmed comments, edits the same record, and cancels without altering saved comments", () => {
const storage = memoryWriter();
const editor = createReviewEditor("first", storage.writer);
editor.start(target);
editor.setBody(" First comment ");
editor.save(editor.getState()!.body);
expect(editor.getState()).toBeNull();
const saved = storage.comments("first")[0]!;
expect(saved).toMatchObject({
filePath: target.filePath,
side: "new",
lineNumber: 2,
body: "First comment",
});
editor.edit(target, saved);
editor.setBody("Discarded edit");
editor.cancel();
expect(storage.comments("first")).toEqual([saved]);
editor.edit(target, saved);
editor.save(" Updated comment ");
expect(storage.comments("first")).toEqual([{ ...saved, body: "Updated comment" }]);
editor.start(target);
editor.setBody("Discarded new comment");
editor.cancel();
expect(storage.comments("first")).toHaveLength(1);
});
it("keeps an open edit saveable after its submitted record is acknowledged", () => {
const storage = memoryWriter();
const editor = createReviewEditor("first", storage.writer);
editor.start(target);
editor.save("Submitted body");
const saved = storage.comments("first")[0]!;
editor.edit(target, saved);
editor.setBody("Typed before acknowledgement");
storage.writer.deleteComment({ key: "first", id: saved.id });
expect(editor.getState()!.body).toBe("Typed before acknowledgement");
editor.save(editor.getState()!.body);
expect(storage.comments("first")).toMatchObject([
{
body: "Typed before acknowledgement",
filePath: target.filePath,
lineNumber: target.lineNumber,
},
]);
});
it("rejects empty saves and repeated saves after the editor closes", () => {
const storage = memoryWriter();
const editor = createReviewEditor("first", storage.writer);
editor.start(target);
editor.save(" \n ");
expect(editor.getState()).toEqual({ target, commentId: null, body: "" });
expect(storage.comments("first")).toEqual([]);
editor.save("Saved once");
editor.save("Duplicate");
expect(storage.comments("first").map((comment) => comment.body)).toEqual(["Saved once"]);
});
it("isolates draft ownership and closes an editor when its saved comment is deleted", () => {
const storage = memoryWriter();
const first = createReviewEditor("first", storage.writer);
const second = createReviewEditor("second", storage.writer);
first.start(target);
first.save("First workspace");
const saved = storage.comments("first")[0]!;
first.edit(target, saved);
expect(second.getState()).toBeNull();
second.start(target);
second.save("Second workspace");
first.delete(saved.id);
expect(first.getState()).toBeNull();
expect(storage.comments("first")).toEqual([]);
expect(storage.comments("second").map((comment) => comment.body)).toEqual(["Second workspace"]);
});
});
it("retains an open editor through remounts without exposing it on another surface or draft", async () => {
const storage = memoryWriter();
const scope = createReviewEditorScope(storage.writer);
const editor = scope.forDraft("first", "diff");
const unsubscribe = editor.subscribe(() => {});
editor.start(target);
editor.setBody("Unsaved wide body");
unsubscribe();
await Promise.resolve();
const compact = scope.forDraft("first", "diff");
expect(compact.getState()!.body).toBe("Unsaved wide body");
expect(scope.forDraft("first", "combined").getState()).toBeNull();
expect(scope.forDraft("second", "diff").getState()).toBeNull();
compact.save(compact.getState()!.body);
expect(storage.comments("first")[0]!.body).toBe("Unsaved wide body");
expect(scope.forDraft("first", "diff").getState()).toBeNull();
});
-84
View File
@@ -1,84 +0,0 @@
import type { ReviewableDiffTarget } from "@/utils/diff-layout";
import type { InlineReviewEditorState } from "../geometry";
import type { ReviewDraftComment } from "../state";
export interface ReviewCommentWriter {
saveComment: (input: {
key: string;
id: string | null;
comment: Pick<ReviewDraftComment, "filePath" | "side" | "lineNumber" | "body">;
}) => void;
deleteComment: (input: { key: string; id: string }) => void;
}
/** One editor belongs to one review draft; replacing the draft creates a fresh editor. */
export function createReviewEditor(key: string, writer: ReviewCommentWriter) {
return buildReviewEditor(key, writer, () => {});
}
function buildReviewEditor(key: string, writer: ReviewCommentWriter, onUnused: () => void) {
let editor: InlineReviewEditorState | null = null;
const listeners = new Set<() => void>();
function publish(next: InlineReviewEditorState | null) {
editor = next;
listeners.forEach((listener) => listener());
if (!editor && listeners.size === 0) onUnused();
}
return {
getState: () => editor,
subscribe: (listener: () => void) => {
listeners.add(listener);
return () => {
listeners.delete(listener);
queueMicrotask(() => {
if (!editor && listeners.size === 0) onUnused();
});
};
},
start: (target: ReviewableDiffTarget) => publish({ target, commentId: null, body: "" }),
edit: (target: ReviewableDiffTarget, comment: ReviewDraftComment) =>
publish({ target, commentId: comment.id, body: comment.body }),
setBody: (body: string) => {
if (editor) publish({ ...editor, body });
},
cancel: () => publish(null),
save: (body: string) => {
const trimmedBody = body.trim();
if (!editor || !trimmedBody) return;
writer.saveComment({
key,
id: editor.commentId,
comment: {
filePath: editor.target.filePath,
side: editor.target.side,
lineNumber: editor.target.lineNumber,
body: trimmedBody,
},
});
publish(null);
},
delete: (id: string) => {
writer.deleteComment({ key, id });
if (editor?.commentId === id) publish(null);
},
};
}
/** An open draft survives presentation remounts; each presentation owns its editor for that draft. */
export function createReviewEditorScope(writer: ReviewCommentWriter) {
const editors = new Map<string, ReturnType<typeof createReviewEditor>>();
return {
forDraft(key: string, presentation: string) {
const owner = JSON.stringify([key, presentation]);
let model = editors.get(owner);
if (!model) {
const created = buildReviewEditor(key, writer, () => {
if (editors.get(owner) === created) editors.delete(owner);
});
model = created;
editors.set(owner, model);
}
return model;
},
};
}
@@ -1,272 +0,0 @@
import { describe, expect, it } from "vitest";
import {
createReviewFeedback,
createReviewFeedbackScope,
type ReviewFeedbackPorts,
type ReviewFeedbackSnapshot,
type FeedbackAttachment,
type FeedbackRecipient,
} from "./index";
import type { ReviewDraftComment } from "../state";
function makeComment(id: string, body = id): ReviewDraftComment {
return {
id,
body,
filePath: "sample.ts",
side: "new",
lineNumber: 2,
createdAt: "2026-10-09T00:00:00Z",
updatedAt: "2026-10-09T00:00:00Z",
};
}
function makeRecipient(agentId: string): FeedbackRecipient {
return {
agentId,
tab: {
key: `agent_${agentId}`,
tabId: `agent_${agentId}`,
kind: "agent",
target: { kind: "agent", agentId },
},
};
}
function makeAttachment(comments: readonly ReviewDraftComment[]): FeedbackAttachment | null {
if (!comments.length) return null;
const line = {
type: "add" as const,
content: "const value = 1",
oldLineNumber: null,
newLineNumber: 2,
};
return {
kind: "review",
reviewDraftKey: "draft",
commentCount: comments.length,
attachment: {
type: "review",
mimeType: "application/paseo-review",
cwd: "/workspace",
mode: "uncommitted",
baseRef: null,
comments: comments.map((comment) => ({
filePath: comment.filePath,
side: comment.side,
lineNumber: comment.lineNumber,
body: comment.body,
context: { hunkHeader: "@@ -1 +1 @@", targetLine: line, lines: [line] },
})),
},
};
}
function setup(agentIds: string[], unavailableIds: string[] = [], create = createReviewFeedback) {
let comments = [makeComment("first")];
let recipients = agentIds.map(makeRecipient);
let connected = true;
let rejectSend: ((error: Error) => void) | null = null;
let resolveSend: (() => void) | null = null;
const sends: Array<{ recipient: FeedbackRecipient; attachment: FeedbackAttachment }> = [];
const read = (): ReviewFeedbackSnapshot => ({
comments,
recipients,
connected,
attachment: makeAttachment(comments.filter((comment) => !unavailableIds.includes(comment.id))),
});
const ports: ReviewFeedbackPorts = {
read,
send: (recipient, attachment) => {
sends.push({ recipient, attachment });
return new Promise<void>((resolve, reject) => {
resolveSend = resolve;
rejectSend = reject;
});
},
clearSent: (sent) => {
comments = comments.filter(
(current) =>
!sent.some(
(prior) =>
prior.id === current.id &&
prior.updatedAt === current.updatedAt &&
prior.body === current.body,
),
);
},
failedMessage: () => "Failed to send",
};
const model = create(ports);
return {
model,
ports,
sends,
comments: () => comments,
setComments: (next: ReviewDraftComment[]) => {
comments = next;
model.refresh();
},
setRecipients: (ids: string[]) => {
recipients = ids.map(makeRecipient);
model.refresh();
},
disconnect: () => {
connected = false;
model.refresh();
},
succeed: () => resolveSend!(),
fail: () => rejectSend!(new Error("Host rejected feedback")),
};
}
describe("review feedback", () => {
it("counts only attached comments, freezes the sending count, and retains orphans", async () => {
const feedback = setup(["one"], ["orphan"]);
feedback.setComments([makeComment("first"), makeComment("orphan")]);
expect(feedback.model.getState()).toMatchObject({ commentCount: 2, sendableCommentCount: 1 });
const pending = feedback.model.press();
feedback.setComments([makeComment("first"), makeComment("orphan"), makeComment("added")]);
expect(feedback.model.getState()).toMatchObject({
phase: { kind: "sending", commentCount: 1 },
sendableCommentCount: 2,
});
expect(feedback.sends[0]!.attachment.commentCount).toBe(1);
feedback.succeed();
await pending;
expect(feedback.comments()).toEqual([makeComment("orphan"), makeComment("added")]);
});
it("retains an entirely orphaned draft without claiming any comments are sendable", async () => {
const feedback = setup(["one"], ["first"]);
expect(feedback.model.getState()).toMatchObject({
commentCount: 1,
sendableCommentCount: 0,
disabledReason: "no-context",
canSend: false,
});
await feedback.model.press();
expect(feedback.sends).toEqual([]);
expect(feedback.comments()).toEqual([makeComment("first")]);
});
it("retains comments and explains why no workspace agent can receive them", async () => {
const feedback = setup([]);
await feedback.model.press();
expect(feedback.model.getState()).toMatchObject({
canSend: false,
disabledReason: "no-agents",
commentCount: 1,
});
expect(feedback.sends).toEqual([]);
expect(feedback.comments()).toEqual([makeComment("first")]);
});
it("sends once to the only recipient and clears only sent versions", async () => {
const feedback = setup(["one"]);
const pending = feedback.model.press();
await feedback.model.press();
await feedback.model.send("one");
expect(feedback.sends).toEqual([
{ recipient: makeRecipient("one"), attachment: makeAttachment([makeComment("first")]) },
]);
feedback.setComments([makeComment("first", "Edited during send"), makeComment("added")]);
feedback.succeed();
await pending;
expect(feedback.comments()).toEqual([
makeComment("first", "Edited during send"),
makeComment("added"),
]);
expect(feedback.model.getState().phase).toEqual({
kind: "sent",
recipient: makeRecipient("one"),
});
});
it("clears unchanged sent comments while preserving additions", async () => {
const feedback = setup(["one"]);
const pending = feedback.model.press();
feedback.setComments([makeComment("first"), makeComment("added")]);
feedback.succeed();
await pending;
expect(feedback.comments()).toEqual([makeComment("added")]);
});
it("asks for a recipient when several tabs exist and validates the selection again", async () => {
const feedback = setup(["one", "two"]);
await feedback.model.press();
expect(feedback.model.getState().phase).toEqual({ kind: "choosing" });
expect(feedback.sends).toEqual([]);
feedback.setRecipients(["one"]);
await feedback.model.send("two");
expect(feedback.sends).toEqual([]);
const pending = feedback.model.send("one");
feedback.succeed();
await pending;
expect(feedback.comments()).toEqual([]);
});
it("retains comments on failure and retries using the latest saved version", async () => {
const feedback = setup(["one"]);
const failed = feedback.model.press();
feedback.fail();
await failed;
expect(feedback.model.getState().phase).toEqual({
kind: "failed",
message: "Host rejected feedback",
});
expect(feedback.comments()).toEqual([makeComment("first")]);
feedback.setComments([makeComment("first", "Corrected before retry")]);
const retried = feedback.model.press();
feedback.succeed();
await retried;
expect(feedback.sends).toHaveLength(2);
expect(feedback.sends[1]!.attachment.attachment.comments[0]!.body).toBe(
"Corrected before retry",
);
expect(feedback.comments()).toEqual([]);
});
it("keeps workspace drafts independent and prevents disconnected sends", async () => {
const first = setup(["one"]);
const second = setup(["other"]);
first.disconnect();
await first.model.press();
expect(first.model.getState().disabledReason).toBe("disconnected");
const pending = second.model.press();
second.succeed();
await pending;
expect(first.comments()).toEqual([makeComment("first")]);
expect(first.sends).toEqual([]);
expect(second.comments()).toEqual([]);
});
});
describe("shared review submission ownership", () => {
it("blocks another surface and reconnects to the pending draft while other drafts remain usable", async () => {
const scope = createReviewFeedbackScope();
const first = setup(["one"], [], (ports) => scope.connect("workspace-one", ports));
const second = scope.connect("workspace-one", first.ports);
const other = setup(["other"], [], (ports) => scope.connect("workspace-other", ports));
const unsubscribe = first.model.subscribe(() => {});
const pending = first.model.press();
unsubscribe();
await Promise.resolve();
const reconnected = scope.connect("workspace-one", first.ports);
expect(second.getState()).toMatchObject({ canSend: false, phase: { kind: "sending" } });
await second.press();
await reconnected.send("one");
expect(first.sends).toHaveLength(1);
const otherPending = other.model.press();
expect(other.sends).toHaveLength(1);
first.fail();
await pending;
expect(second.getState().phase).toEqual({ kind: "failed", message: "Host rejected feedback" });
const retry = second.press();
first.succeed();
await retry;
expect(first.sends).toHaveLength(2);
other.succeed();
await otherPending;
});
it("opens only the active surface's recipient chooser", async () => {
const scope = createReviewFeedbackScope();
const first = setup(["one", "two"], [], (ports) => scope.connect("same", ports));
const second = scope.connect("same", first.ports);
await first.model.press();
expect(first.model.getState().phase).toEqual({ kind: "choosing" });
expect(second.getState().phase).toEqual({ kind: "idle" });
first.model.closeMenu();
expect(first.model.getState().phase).toEqual({ kind: "idle" });
});
});
-177
View File
@@ -1,177 +0,0 @@
import type { ComposerAttachment } from "@/attachments/types";
import type { ReviewDraftComment } from "../state";
import type { WorkspaceTabDescriptor } from "@/screens/workspace/workspace-tabs-types";
export interface FeedbackRecipient {
agentId: string;
tab: WorkspaceTabDescriptor;
}
export type FeedbackAttachment = Extract<ComposerAttachment, { kind: "review" }>;
export interface ReviewFeedbackSnapshot {
comments: readonly ReviewDraftComment[];
attachment: FeedbackAttachment | null;
recipients: readonly FeedbackRecipient[];
connected: boolean;
}
export interface ReviewFeedbackPorts {
read: () => ReviewFeedbackSnapshot;
send: (recipient: FeedbackRecipient, attachment: FeedbackAttachment) => Promise<void>;
clearSent: (comments: readonly ReviewDraftComment[]) => void;
failedMessage: () => string;
}
export type FeedbackPhase =
| { kind: "idle" }
| { kind: "choosing" }
| { kind: "sending"; recipient: FeedbackRecipient; commentCount: number }
| { kind: "failed"; message: string }
| { kind: "sent"; recipient: FeedbackRecipient };
export interface ReviewFeedbackState {
phase: FeedbackPhase;
commentCount: number;
sendableCommentCount: number;
recipients: readonly FeedbackRecipient[];
disabledReason: "no-agents" | "disconnected" | "no-context" | null;
canSend: boolean;
}
export function createReviewFeedback(ports: ReviewFeedbackPorts) {
return createFeedbackView(ports, createFeedbackWorkflow());
}
/** Surfaces share submission ownership while keeping their chooser and live inputs local. */
export function createReviewFeedbackScope() {
const workflows = new Map<string, ReturnType<typeof createFeedbackWorkflow>>();
return {
connect(key: string, ports: ReviewFeedbackPorts) {
let workflow = workflows.get(key);
if (!workflow) {
const created = createFeedbackWorkflow(() => {
if (workflows.get(key) === created) workflows.delete(key);
});
workflow = created;
workflows.set(key, workflow);
}
return createFeedbackView(ports, workflow);
},
};
}
function createFeedbackWorkflow(onUnused: () => void = () => {}) {
let phase: FeedbackPhase = { kind: "idle" };
const observers = new Set<() => void>();
function releaseIfUnused() {
queueMicrotask(() => {
if (observers.size === 0 && phase.kind !== "sending") onUnused();
});
}
return {
getPhase: () => phase,
changePhase(next: FeedbackPhase) {
phase = next;
observers.forEach((observer) => observer());
releaseIfUnused();
},
subscribe(observer: () => void) {
observers.add(observer);
return () => {
observers.delete(observer);
releaseIfUnused();
};
},
};
}
function createFeedbackView(
ports: ReviewFeedbackPorts,
workflow: ReturnType<typeof createFeedbackWorkflow>,
) {
let choosing = false;
const choosingPhase: FeedbackPhase = { kind: "choosing" };
const getPhase = () => (choosing ? choosingPhase : workflow.getPhase());
let state = deriveState(ports.read(), getPhase());
const listeners = new Set<() => void>();
function publish() {
state = deriveState(ports.read(), getPhase());
listeners.forEach((listener) => listener());
}
async function send(agentId: string) {
const snapshot = ports.read();
const current = deriveState(snapshot, workflow.getPhase());
const recipient = snapshot.recipients.find((candidate) => candidate.agentId === agentId);
if (!current.canSend || !recipient || !snapshot.attachment) return;
const attachment = snapshot.attachment;
const sentComments = snapshot.comments.filter((comment) =>
attachment.attachment.comments.some(
(sent) =>
sent.filePath === comment.filePath &&
sent.side === comment.side &&
sent.lineNumber === comment.lineNumber &&
sent.body === comment.body,
),
);
choosing = false;
workflow.changePhase({ kind: "sending", recipient, commentCount: attachment.commentCount });
publish();
try {
await ports.send(recipient, attachment);
ports.clearSent(sentComments);
workflow.changePhase({ kind: "sent", recipient });
} catch (error) {
workflow.changePhase({
kind: "failed",
message: error instanceof Error ? error.message : ports.failedMessage(),
});
}
publish();
}
return {
getState: () => {
if (state.phase !== getPhase()) state = deriveState(ports.read(), getPhase());
return state;
},
subscribe: (listener: () => void) => {
listeners.add(listener);
const unsubscribe = workflow.subscribe(() => {
choosing = false;
publish();
});
return () => {
listeners.delete(listener);
unsubscribe();
};
},
refresh: publish,
press: async () => {
const snapshot = ports.read();
if (!deriveState(snapshot, workflow.getPhase()).canSend) return;
if (snapshot.recipients.length === 1) {
await send(snapshot.recipients[0]!.agentId);
} else {
choosing = true;
publish();
}
},
closeMenu: () => {
if (choosing) {
choosing = false;
publish();
}
},
send,
};
}
function deriveState(snapshot: ReviewFeedbackSnapshot, phase: FeedbackPhase): ReviewFeedbackState {
let disabledReason: ReviewFeedbackState["disabledReason"] = null;
if (snapshot.recipients.length === 0) disabledReason = "no-agents";
else if (!snapshot.connected) disabledReason = "disconnected";
else if (!snapshot.attachment) disabledReason = "no-context";
return {
phase,
commentCount: snapshot.comments.length,
sendableCommentCount: snapshot.attachment?.commentCount ?? 0,
recipients: snapshot.recipients,
disabledReason,
canSend: snapshot.comments.length > 0 && disabledReason === null && phase.kind !== "sending",
};
}
@@ -1,284 +0,0 @@
import { useCallback, useMemo, type ReactNode } from "react";
import { Text, View } from "react-native";
import { Send } from "lucide-react-native";
import { useTranslation } from "react-i18next";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { StyleSheet } from "react-native-unistyles";
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem } from "@/components/ui/dropdown-menu";
import { useMenuContext } from "@/components/ui/menu";
import { Button } from "@/components/ui/button";
import { buttonControlHeight } from "@/components/ui/control-geometry";
import { useIsCompactFormFactor } from "@/constants/layout";
import { SPACING } from "@/styles/theme";
import { FloatingActionButton } from "@/components/ui/floating-action-button";
import {
WorkspaceTabPresentationResolver,
WorkspaceTabIcon,
type WorkspaceTabPresentation,
} from "@/screens/workspace/workspace-tab-presentation";
import type { FeedbackRecipient, ReviewFeedbackState, createReviewFeedback } from "./index";
type FeedbackModel = ReturnType<typeof createReviewFeedback>;
interface ReviewFeedbackActionProps {
bottomOffset: number;
model: FeedbackModel;
state: ReviewFeedbackState;
serverId: string;
workspaceId: string;
}
export function ReviewFeedbackAction({
enabled,
hasDiff,
...props
}: Omit<ReviewFeedbackActionProps, "workspaceId"> & {
workspaceId?: string | null;
enabled: boolean | undefined;
hasDiff: boolean;
}) {
if (enabled === false || !hasDiff) return null;
return <OpenReviewFeedbackAction {...props} workspaceId={props.workspaceId ?? ""} />;
}
function OpenReviewFeedbackAction({
model,
state,
serverId,
workspaceId,
bottomOffset,
}: ReviewFeedbackActionProps) {
const { t } = useTranslation();
const { bottom } = useSafeAreaInsets();
const isCompact = useIsCompactFormFactor();
const onOpenChange = useCallback(
(open: boolean) => {
if (!open) model.closeMenu();
},
[model],
);
const noteStyle = useMemo(
() => [
styles.note,
!isCompact && styles.centered,
{
bottom:
bottom +
bottomOffset +
(isCompact ? 88 : buttonControlHeight.sm + SPACING[4] + SPACING[2]),
},
],
[bottom, bottomOffset, isCompact],
);
const sending = state.phase.kind === "sending";
const label = t(sending ? "review.feedback.sending" : "review.feedback.send", {
count: state.phase.kind === "sending" ? state.phase.commentCount : state.sendableCommentCount,
});
const unavailableNotice =
state.disabledReason && state.commentCount > 0 ? (
<Text style={styles.text}>{t(`review.feedback.${state.disabledReason}`)}</Text>
) : null;
let notice: ReactNode = unavailableNotice;
if (state.phase.kind === "failed")
notice = <Text style={styles.error}>{state.phase.message}</Text>;
else if (state.phase.kind === "sent")
notice = (
<>
<SentNotice
recipient={state.phase.recipient}
serverId={serverId}
workspaceId={workspaceId}
/>
{unavailableNotice}
</>
);
return (
<>
{state.commentCount > 0 ? (
<DropdownMenu
open={state.phase.kind === "choosing"}
onOpenChange={onOpenChange}
compactMode="sheet"
>
<FeedbackTrigger
model={model}
label={label}
disabled={!state.canSend}
bottomInset={bottom + bottomOffset}
/>
<DropdownMenuContent
side="top"
align="center"
sheetTitle={t("review.feedback.chooseAgent")}
>
{state.recipients.map((recipient) => (
<RecipientOption
key={recipient.tab.key}
recipient={recipient}
model={model}
serverId={serverId}
workspaceId={workspaceId}
/>
))}
</DropdownMenuContent>
</DropdownMenu>
) : null}
{notice ? (
<View style={noteStyle} accessibilityRole="alert">
{notice}
</View>
) : null}
</>
);
}
function FeedbackTrigger({
model,
label,
disabled,
bottomInset,
}: {
model: FeedbackModel;
label: string;
disabled: boolean;
bottomInset: number;
}) {
const { triggerRef } = useMenuContext("FeedbackTrigger");
const isCompact = useIsCompactFormFactor();
const press = useCallback(() => {
void model.press();
}, [model]);
if (!isCompact) {
return (
<View
pointerEvents="box-none"
style={[styles.wideAction, { bottom: bottomInset + SPACING[4] }]}
>
<Button
ref={triggerRef}
variant="default"
size="sm"
leftIcon={Send}
accessibilityLabel={label}
disabled={disabled}
onPress={press}
>
{label}
</Button>
</View>
);
}
return (
<FloatingActionButton
ref={triggerRef}
icon={Send}
label={label}
accessibilityLabel={label}
disabled={disabled}
bottomInset={bottomInset}
onPress={press}
/>
);
}
function RecipientOption({
recipient,
model,
serverId,
workspaceId,
}: {
recipient: FeedbackRecipient;
model: FeedbackModel;
serverId: string;
workspaceId: string;
}) {
const choose = useCallback(() => {
void model.send(recipient.agentId);
}, [model, recipient.agentId]);
const render = useCallback(
(presentation: WorkspaceTabPresentation) => (
<RecipientRow presentation={presentation} onSelect={choose} />
),
[choose],
);
return (
<WorkspaceTabPresentationResolver
tab={recipient.tab}
serverId={serverId}
workspaceId={workspaceId}
>
{render}
</WorkspaceTabPresentationResolver>
);
}
function RecipientRow({
presentation,
onSelect,
}: {
presentation: WorkspaceTabPresentation;
onSelect: () => void;
}) {
const leading = useMemo(
() => <WorkspaceTabIcon presentation={presentation} backdrop="surface0" />,
[presentation],
);
return (
<DropdownMenuItem leading={leading} onSelect={onSelect}>
{presentation.label}
</DropdownMenuItem>
);
}
function SentNotice({
recipient,
serverId,
workspaceId,
}: {
recipient: FeedbackRecipient;
serverId: string;
workspaceId: string;
}) {
const { t } = useTranslation();
const render = useCallback(
(presentation: WorkspaceTabPresentation) => (
<Text style={styles.text}>
{t("review.feedback.sent", { recipient: presentation.label })}
</Text>
),
[t],
);
return (
<WorkspaceTabPresentationResolver
tab={recipient.tab}
serverId={serverId}
workspaceId={workspaceId}
>
{render}
</WorkspaceTabPresentationResolver>
);
}
const styles = StyleSheet.create((theme) => ({
wideAction: { position: "absolute", left: 0, right: 0, alignItems: "center" },
centered: { alignItems: "center" },
note: {
position: "absolute",
right: theme.spacing[4],
left: theme.spacing[4],
alignItems: "flex-end",
},
text: {
color: theme.colors.foreground,
fontSize: theme.fontSize.sm,
backgroundColor: theme.colors.surface1,
padding: theme.spacing[2],
borderRadius: theme.borderRadius.md,
},
error: {
color: theme.colors.destructive,
fontSize: theme.fontSize.sm,
backgroundColor: theme.colors.surface1,
padding: theme.spacing[2],
borderRadius: theme.borderRadius.md,
},
}));
@@ -1,120 +0,0 @@
import { useEffect, useMemo, useRef, useSyncExternalStore } from "react";
import {
useReviewDraftComments,
getReviewDraftComments,
clearSentReviewDraftComments,
} from "../store";
import { useWorkspaceLayoutStore } from "@/stores/workspace-layout-store";
import { buildWorkspaceTabPersistenceKey } from "@/workspace-tabs/model";
import { deriveWorkspaceTabModel } from "@/screens/workspace/workspace-tab-model";
import { useHostRuntimeClient, useHostRuntimeIsConnected } from "@/runtime/host-runtime";
import { useAppSettings } from "@/hooks/use-settings";
import { dispatchComposerAgentMessage } from "@/composer/actions";
import { createMessageSubmissionWriter } from "@/composer/submission/writer";
import { useSessionStore, selectAgentTurnPresentation } from "@/stores/session-store";
import { FLOATING_ACTION_BUTTON_CLEARANCE } from "@/components/ui/floating-action-button";
import { useIsCompactFormFactor } from "@/constants/layout";
import { buttonControlHeight } from "@/components/ui/control-geometry";
import { SPACING } from "@/styles/theme";
import { i18n } from "@/i18n/i18next";
import {
createReviewFeedbackScope,
type FeedbackAttachment,
type FeedbackRecipient,
} from "./index";
const feedbackScope = createReviewFeedbackScope();
export function useReviewFeedback(input: {
reviewDraftKey: string;
serverId: string;
workspaceId?: string;
attachment: FeedbackAttachment | null;
}) {
const { serverId, reviewDraftKey, workspaceId } = input;
const isCompact = useIsCompactFormFactor();
const workspaceKey = workspaceId
? buildWorkspaceTabPersistenceKey({ serverId, workspaceId })
: null;
const client = useHostRuntimeClient(serverId);
const connected = useHostRuntimeIsConnected(serverId);
const { settings } = useAppSettings();
const comments = useReviewDraftComments(reviewDraftKey);
const layout = useWorkspaceLayoutStore((store) =>
workspaceKey ? store.layoutByWorkspace[workspaceKey] : undefined,
);
// The adapter keeps live host and diff inputs available to commands without reconstructing the workflow.
const live = useRef({
client,
connected,
attachment: input.attachment,
sendBehavior: settings.sendBehavior,
});
live.current = {
client,
connected,
attachment: input.attachment,
sendBehavior: settings.sendBehavior,
};
const model = useMemo(
() =>
feedbackScope.connect(reviewDraftKey, {
read: () => ({
comments: getReviewDraftComments(reviewDraftKey) ?? [],
attachment: live.current.attachment,
connected: live.current.connected,
recipients: readRecipients(workspaceKey),
}),
send: async (recipient, attachment) => {
const { client: targetClient, sendBehavior } = live.current;
if (!targetClient) throw new Error(i18n.t("workspace.terminal.hostDisconnected"));
const activeTurnBehavior = sendBehavior === "steer" ? "steer" : "interrupt";
await dispatchComposerAgentMessage({
client: targetClient,
agentId: recipient.agentId,
text: i18n.t("review.feedback.prompt"),
attachments: [attachment],
encodeImages: async () => [],
submission: createMessageSubmissionWriter(serverId),
activeTurnBehavior,
activeTurnId:
activeTurnBehavior === "steer"
? (selectAgentTurnPresentation(
useSessionStore.getState().sessions[serverId],
recipient.agentId,
).turnId ?? undefined)
: undefined,
});
},
clearSent: (sentComments) =>
clearSentReviewDraftComments({ key: reviewDraftKey, comments: sentComments }),
failedMessage: () => i18n.t("review.feedback.failed"),
}),
[reviewDraftKey, serverId, workspaceKey],
);
useEffect(() => {
model.refresh();
}, [model, comments, layout, connected, input.attachment]);
const state = useSyncExternalStore(model.subscribe, model.getState, model.getState);
return {
model,
state,
clearance:
state.commentCount > 0
? (isCompact ? FLOATING_ACTION_BUTTON_CLEARANCE : buttonControlHeight.sm + SPACING[4]) + 44
: 0,
};
}
function readRecipients(workspaceKey: string | null): FeedbackRecipient[] {
const tabs = workspaceKey
? useWorkspaceLayoutStore.getState().getWorkspaceTabs(workspaceKey)
: [];
const descriptors = deriveWorkspaceTabModel({ tabs }).tabs;
const recipients: FeedbackRecipient[] = [];
for (const { descriptor } of descriptors) {
if (descriptor.target.kind === "agent")
recipients.push({ agentId: descriptor.target.agentId, tab: descriptor });
}
return recipients;
}
-1
View File
@@ -19,7 +19,6 @@ export interface InlineReviewActions {
onStartComment: (target: ReviewableDiffTarget) => void;
onEditComment: (target: ReviewableDiffTarget, comment: ReviewDraftComment) => void;
onCancelEditor: () => void;
onChangeEditorBody: (body: string) => void;
onSaveEditor: (body: string) => void;
onDeleteComment: (id: string) => void;
}
-5
View File
@@ -31,8 +31,3 @@ export {
SMALL_ACTION_HIT_SLOP,
useInlineReviewController,
} from "./surface";
export { ReviewCommentSheet } from "./comment-sheet";
export { useReviewFeedback } from "./feedback/use-feedback";
export { ReviewFeedbackAction } from "./feedback/surface";
+1 -56
View File
@@ -2,16 +2,7 @@ import { describe, expect, it } from "vitest";
import type { StateStorage } from "zustand/middleware";
import type { ParsedDiffFile } from "@/git/use-diff-query";
import { createValidatedPersistStorage } from "@/storage/validated-persist-storage";
import {
buildReviewAttachmentSnapshot,
buildReviewDraftKey,
addReviewDraftComment,
saveReviewDraftComment,
clearSentReviewDraftComments,
getReviewDraftComments,
resetReviewDraftStore,
useReviewDraftStore,
} from "./store";
import { buildReviewAttachmentSnapshot, buildReviewDraftKey } from "./store";
import {
addCommentToState,
clearReviewInState,
@@ -313,49 +304,3 @@ describe("buildReviewAttachmentSnapshot", () => {
});
});
});
describe("successful feedback cleanup", () => {
it("clears sent versions only, preserving edits, additions and other workspace drafts", () => {
resetReviewDraftStore();
const first = addReviewDraftComment({ key: "first", comment: makeComment() });
const edited = addReviewDraftComment({
key: "first",
comment: makeComment({ id: "edited", body: "Before send" }),
});
const other = addReviewDraftComment({ key: "other", comment: makeComment({ id: "other" }) });
useReviewDraftStore.getState().updateComment({
key: "first",
id: edited.id,
updates: { body: "After send" },
updatedAt: edited.updatedAt,
});
const added = addReviewDraftComment({ key: "first", comment: makeComment({ id: "added" }) });
clearSentReviewDraftComments({ key: "first", comments: [first, edited] });
expect(getReviewDraftComments("first")).toEqual([{ ...edited, body: "After send" }, added]);
expect(getReviewDraftComments("other")).toEqual([other]);
resetReviewDraftStore();
});
});
it("saves an acknowledged open edit as a new version and keeps subsequent edits on that record", () => {
resetReviewDraftStore();
const submitted = addReviewDraftComment({ key: "first", comment: makeComment() });
clearSentReviewDraftComments({ key: "first", comments: [submitted] });
saveReviewDraftComment({
key: "first",
id: submitted.id,
comment: { ...submitted, body: "Open edit after acknowledgement" },
});
const restored = getReviewDraftComments("first")![0]!;
expect(restored.body).toBe("Open edit after acknowledgement");
expect(restored.id).not.toBe(submitted.id);
clearSentReviewDraftComments({ key: "first", comments: [submitted] });
expect(getReviewDraftComments("first")).toEqual([restored]);
saveReviewDraftComment({
key: "first",
id: restored.id,
comment: { ...restored, body: "Saved again" },
});
expect(getReviewDraftComments("first")).toMatchObject([{ id: restored.id, body: "Saved again" }]);
resetReviewDraftStore();
});
-40
View File
@@ -320,43 +320,3 @@ export function useReviewAttachmentSnapshot(input: {
[comments, input.key, input.cwd, input.mode, input.baseRef, input.diffFiles],
);
}
/** Acknowledgement removes only the versions included in that submission. */
export function clearSentReviewDraftComments(input: {
key: string;
comments: readonly ReviewDraftComment[];
}): void {
const sentById = new Map(input.comments.map((comment) => [comment.id, comment]));
useReviewDraftStore.setState((state) => {
const current = state.drafts[input.key];
if (!current) return state;
const remaining = current.filter((comment) => {
const sent = sentById.get(comment.id);
return !sent || sent.updatedAt !== comment.updatedAt || sent.body !== comment.body;
});
if (remaining.length === current.length) return state;
return { drafts: { ...state.drafts, [input.key]: remaining } };
});
}
/** Acknowledgement can remove the original while the user still has an edit open. */
export function saveReviewDraftComment(input: {
key: string;
id: string | null;
comment: Pick<ReviewDraftComment, "filePath" | "side" | "lineNumber" | "body">;
}): void {
const store = useReviewDraftStore.getState();
if (input.id && store.drafts[input.key]?.some((comment) => comment.id === input.id)) {
store.updateComment({ key: input.key, id: input.id, updates: { body: input.comment.body } });
} else {
store.addComment({
key: input.key,
comment: {
filePath: input.comment.filePath,
side: input.comment.side,
lineNumber: input.comment.lineNumber,
body: input.comment.body,
},
});
}
}
+56 -40
View File
@@ -9,24 +9,45 @@ import { useReviewDraftStore, type ReviewDraftComment } from "./store";
import { buildReviewableDiffTargetKey, type ReviewableDiffTarget } from "@/utils/diff-layout";
import {
getInlineReviewThreadState,
getSplitInlineReviewThreadState,
type InlineReviewActions,
} from "./geometry";
import {
getInlineReviewThreadViewportStyle,
getSplitInlineReviewThreadState,
groupInlineReviewCommentsByTarget,
InlineReviewEditor,
InlineReviewGutterCell,
InlineReviewThread,
SMALL_ACTION_HIT_SLOP,
useInlineReviewController,
} from "./surface";
type InlineReviewActions,
} from "./index";
void testI18n;
const { pressablePropsByLabel } = vi.hoisted(() => {
const { theme, pressablePropsByLabel } = vi.hoisted(() => {
Object.assign(globalThis, { __DEV__: false });
return { pressablePropsByLabel: new Map<string, Record<string, unknown>>() };
return {
theme: {
spacing: { 1: 4, 2: 8, 3: 12 },
borderWidth: { 1: 1 },
borderRadius: { base: 4, md: 6, lg: 8, xl: 12, full: 999 },
opacity: { 50: 0.5 },
fontSize: { xs: 11, sm: 13 },
fontWeight: { normal: "400", medium: "500" },
lineHeight: { diff: 18 },
colors: {
accent: "#0a84ff",
accentForeground: "#fff",
border: "#555",
destructive: "#ff453a",
foreground: "#fff",
foregroundMuted: "#aaa",
surface1: "#111",
surface2: "#222",
surface3: "#333",
palette: { white: "#fff" },
},
},
pressablePropsByLabel: new Map<string, Record<string, unknown>>(),
};
});
vi.mock("react-native", async (importOriginal) => {
@@ -67,16 +88,13 @@ vi.mock("react-native", async (importOriginal) => {
};
});
vi.mock("react-native-unistyles", async () => {
const { darkTheme: theme } = await import("@/styles/theme");
return {
StyleSheet: {
create: (factory: unknown) => (typeof factory === "function" ? factory(theme) : factory),
},
withUnistyles: <T,>(component: T) => component,
useUnistyles: () => ({ theme, rt: { breakpoint: "md" } }),
};
});
vi.mock("react-native-unistyles", () => ({
StyleSheet: {
create: (factory: unknown) => (typeof factory === "function" ? factory(theme) : factory),
},
withUnistyles: <T,>(component: T) => component,
useUnistyles: () => ({ theme, rt: { breakpoint: "md" } }),
}));
vi.mock("@/constants/platform", () => ({
getIsElectron: () => false,
@@ -85,6 +103,19 @@ vi.mock("@/constants/platform", () => ({
isWeb: true,
}));
vi.mock("lucide-react-native", () => {
const createIcon = (name: string) => (props: Record<string, unknown>) =>
React.createElement("span", { ...props, "data-icon": name });
return {
Check: createIcon("Check"),
CircleDot: createIcon("CircleDot"),
Pencil: createIcon("Pencil"),
Plus: createIcon("Plus"),
Trash2: createIcon("Trash2"),
X: createIcon("X"),
};
});
function target(overrides: Partial<ReviewableDiffTarget> = {}): ReviewableDiffTarget {
return {
filePath: "src/example.ts",
@@ -116,7 +147,6 @@ function buildReviewActions(overrides: Partial<InlineReviewActions> = {}): Inlin
onStartComment: vi.fn(),
onEditComment: vi.fn(),
onCancelEditor: vi.fn(),
onChangeEditorBody: () => {},
onSaveEditor: vi.fn(),
onDeleteComment: vi.fn(),
...overrides,
@@ -282,9 +312,8 @@ describe("git diff inline review helpers", () => {
it("keeps the line number visible and only floats the plus for line hover", () => {
const reviewTarget = target();
const { queryByTestId, queryByText, rerender } = render(
const { container, queryByText, rerender } = render(
<InlineReviewGutterCell
actionTestID="add-comment-glyph"
reviewTarget={reviewTarget}
comments={EMPTY_COMMENTS}
isEditorOpen={false}
@@ -295,11 +324,10 @@ describe("git diff inline review helpers", () => {
);
expect(queryByText("2")).toBeTruthy();
expect(queryByTestId("add-comment-glyph")).toBeNull();
expect(container.querySelector("[data-icon='Plus']")).toBeNull();
rerender(
<InlineReviewGutterCell
actionTestID="add-comment-glyph"
reviewTarget={reviewTarget}
comments={COMMENT_LIST}
isEditorOpen={false}
@@ -310,11 +338,10 @@ describe("git diff inline review helpers", () => {
);
expect(queryByText("2")).toBeTruthy();
expect(queryByTestId("add-comment-glyph")).toBeNull();
expect(container.querySelector("[data-icon='Plus']")).toBeNull();
rerender(
<InlineReviewGutterCell
actionTestID="add-comment-glyph"
reviewTarget={reviewTarget}
comments={EMPTY_COMMENTS}
isEditorOpen
@@ -325,11 +352,10 @@ describe("git diff inline review helpers", () => {
);
expect(queryByText("2")).toBeTruthy();
expect(queryByTestId("add-comment-glyph")).toBeNull();
expect(container.querySelector("[data-icon='Plus']")).toBeNull();
rerender(
<InlineReviewGutterCell
actionTestID="add-comment-glyph"
reviewTarget={reviewTarget}
comments={COMMENT_LIST}
isEditorOpen={false}
@@ -341,7 +367,7 @@ describe("git diff inline review helpers", () => {
);
expect(queryByText("2")).toBeTruthy();
expect(queryByTestId("add-comment-glyph")).toBeTruthy();
expect(container.querySelector("[data-icon='Plus']")).toBeTruthy();
});
});
@@ -358,7 +384,7 @@ describe("InlineReviewEditor", () => {
const onCancel = vi.fn();
const onSave = vi.fn();
const { getByTestId } = render(
<ReviewEditorFixture
<InlineReviewEditor
initialBody=" initial "
onCancel={onCancel}
onSave={onSave}
@@ -378,7 +404,7 @@ describe("InlineReviewEditor", () => {
const onCancel = vi.fn();
const onSave = vi.fn();
const { getByTestId } = render(
<ReviewEditorFixture
<InlineReviewEditor
initialBody="ready"
onCancel={onCancel}
onSave={onSave}
@@ -402,7 +428,7 @@ describe("InlineReviewEditor", () => {
removeEventListener: vi.fn(),
});
const { getByTestId, queryByText } = render(
<ReviewEditorFixture
<InlineReviewEditor
initialBody="ready"
onCancel={vi.fn()}
onSave={vi.fn()}
@@ -446,13 +472,3 @@ describe("InlineReviewThread", () => {
expect(actions.onDeleteComment).toHaveBeenCalledWith("comment-1");
});
});
function ReviewEditorFixture({
initialBody,
...props
}: Omit<React.ComponentProps<typeof InlineReviewEditor>, "body" | "onChangeBody"> & {
initialBody: string;
}) {
const [body, onChangeBody] = React.useState(initialBody);
return <InlineReviewEditor {...props} body={body} onChangeBody={onChangeBody} />;
}
+84 -50
View File
@@ -1,11 +1,4 @@
import React, {
useCallback,
useEffect,
useMemo,
useRef,
useState,
useSyncExternalStore,
} from "react";
import React, { useCallback, useEffect, useMemo, useRef, useState } from "react";
import type { ReactNode } from "react";
import { useTranslation } from "react-i18next";
import { Pencil, Plus, Trash2 } from "lucide-react-native";
@@ -24,17 +17,10 @@ import {
EditingTextInput as TextInput,
type EditingTextInputHandle,
} from "@/components/ui/text-input";
import { useIsCompactFormFactor } from "@/constants/layout";
import { createReviewEditorScope } from "./editor";
import { isWeb } from "@/constants/platform";
import { inlineUnistylesStyle } from "@/styles/unistyles-inline-style";
import type { Theme } from "@/styles/theme";
import {
useReviewDraftComments,
useReviewDraftStore,
saveReviewDraftComment,
type ReviewDraftComment,
} from "./store";
import { useReviewDraftComments, useReviewDraftStore, type ReviewDraftComment } from "./store";
import { buildReviewableDiffTargetKey, type ReviewableDiffTarget } from "@/utils/diff-layout";
import {
INLINE_REVIEW_EDITOR_HEIGHT,
@@ -112,42 +98,92 @@ export function groupInlineReviewCommentsByTarget(
return grouped;
}
const reviewEditors = createReviewEditorScope({
saveComment: saveReviewDraftComment,
deleteComment: (input) => useReviewDraftStore.getState().deleteComment(input),
});
export function useInlineReviewController(input: {
reviewDraftKey: string;
presentation?: string;
}): InlineReviewActions & {
sheetEditor: InlineReviewEditorState | null;
onChangeEditorBody: (body: string) => void;
} {
const isCompact = useIsCompactFormFactor();
export function useInlineReviewController(input: { reviewDraftKey: string }): InlineReviewActions {
const reviewComments = useReviewDraftComments(input.reviewDraftKey);
const commentsByTarget = useMemo(
() => groupInlineReviewCommentsByTarget(reviewComments),
[reviewComments],
);
const model = useMemo(
() => reviewEditors.forDraft(input.reviewDraftKey, input.presentation ?? "diff"),
[input.reviewDraftKey, input.presentation],
const [editor, setEditor] = useState<InlineReviewEditorState | null>(null);
const addComment = useReviewDraftStore((state) => state.addComment);
const updateComment = useReviewDraftStore((state) => state.updateComment);
const deleteComment = useReviewDraftStore((state) => state.deleteComment);
useEffect(() => {
setEditor(null);
}, [input.reviewDraftKey]);
const handleStartComment = useCallback((target: ReviewableDiffTarget) => {
setEditor({ target, commentId: null, body: "" });
}, []);
const handleEditComment = useCallback(
(target: ReviewableDiffTarget, comment: ReviewDraftComment) => {
setEditor({ target, commentId: comment.id, body: comment.body });
},
[],
);
const editor = useSyncExternalStore(model.subscribe, model.getState, model.getState);
return useMemo(
const handleCancelEditor = useCallback(() => {
setEditor(null);
}, []);
const handleSaveEditor = useCallback(
(body: string) => {
const trimmedBody = body.trim();
if (!editor || trimmedBody.length === 0) {
return;
}
if (editor.commentId) {
updateComment({
key: input.reviewDraftKey,
id: editor.commentId,
updates: { body: trimmedBody },
});
} else {
addComment({
key: input.reviewDraftKey,
comment: {
filePath: editor.target.filePath,
side: editor.target.side,
lineNumber: editor.target.lineNumber,
body: trimmedBody,
},
});
}
setEditor(null);
},
[addComment, editor, input.reviewDraftKey, updateComment],
);
const handleDeleteComment = useCallback(
(id: string) => {
deleteComment({ key: input.reviewDraftKey, id });
setEditor((current) => (current?.commentId === id ? null : current));
},
[deleteComment, input.reviewDraftKey],
);
return useMemo<InlineReviewActions>(
() => ({
commentsByTarget,
editor: isCompact ? null : editor,
sheetEditor: isCompact ? editor : null,
onChangeEditorBody: model.setBody,
onStartComment: model.start,
onEditComment: model.edit,
onCancelEditor: model.cancel,
onSaveEditor: model.save,
onDeleteComment: model.delete,
editor,
onStartComment: handleStartComment,
onEditComment: handleEditComment,
onCancelEditor: handleCancelEditor,
onSaveEditor: handleSaveEditor,
onDeleteComment: handleDeleteComment,
}),
[commentsByTarget, editor, isCompact, model],
[
commentsByTarget,
editor,
handleCancelEditor,
handleDeleteComment,
handleEditComment,
handleSaveEditor,
handleStartComment,
],
);
}
@@ -285,8 +321,7 @@ export function InlineReviewThread({
const editorElement = editor ? (
<InlineReviewEditor
key={editingCommentId ?? "new"}
body={editor.body}
onChangeBody={reviewActions.onChangeEditorBody}
initialBody={editor.body}
onCancel={reviewActions.onCancelEditor}
onSave={reviewActions.onSaveEditor}
testID="inline-review-editor"
@@ -393,20 +428,19 @@ export function getInlineReviewThreadViewportStyle({
}
export function InlineReviewEditor({
body,
onChangeBody,
initialBody,
onCancel,
onSave,
testID,
}: {
body: string;
onChangeBody: (body: string) => void;
initialBody: string;
onCancel: () => void;
onSave: (body: string) => void;
testID?: string;
}) {
const { t } = useTranslation();
const inputRef = useRef<EditingTextInputHandle | null>(null);
const [body, setBody] = useState(initialBody);
const [isFocused, setIsFocused] = useState(false);
const trimmedBody = body.trim();
const canSave = trimmedBody.length > 0;
@@ -472,7 +506,7 @@ export function InlineReviewEditor({
placeholderTextColor={styles.placeholderColor.color}
multiline
initialValue={body}
onChangeText={onChangeBody}
onChangeText={setBody}
onFocus={handleFocus}
onBlur={handleBlur}
style={inputStyle}
@@ -33,10 +33,6 @@ type ProjectListResult = Awaited<ReturnType<DaemonClient["listProjects"]>>;
type AgentFetchResult = Awaited<ReturnType<DaemonClient["fetchAgents"]>>;
class FakeDirectoryClient {
supportsBackgroundWorkspaces(): boolean {
return false;
}
supportsWorkspaceLabels = false;
listWorkspaceLabelsCalls = 0;
fetchAgentsCalls = 0;
@@ -535,7 +535,6 @@ export class DirectorySync {
let subscribe = initialSubscribe;
while (true) {
const query: Parameters<DaemonClient["observeWorkspaces"]>[0] = {
...(client.supportsBackgroundWorkspaces() ? { includeBackground: true } : {}),
sort: [{ key: "activity_at", direction: "desc" }],
page: cursor ? { limit: PAGE_LIMIT, cursor } : { limit: PAGE_LIMIT },
...(supportsDirectorySync
@@ -635,7 +634,6 @@ export class DirectorySync {
const limit = input.page?.limit ?? PAGE_LIMIT;
const query: Omit<FetchAgentsOptions, "subscribe"> = {
...(input.filter ? { filter: input.filter } : { scope: "active" as const }),
...(client.supportsBackgroundWorkspaces() ? { includeBackground: true } : {}),
sort: AGENT_SORT,
page: cursor ? { limit, cursor } : { limit },
...(!input.filter && cursor === null && this.supportsDirectorySync()
@@ -52,9 +52,6 @@ it("requests the managed connection credential through desktop main without a we
});
class FakeDaemonClient {
supportsBackgroundWorkspaces(): boolean {
return false;
}
private state: ConnectionState = { status: "idle" };
private listeners = new Set<(status: ConnectionState) => void>();
private error: string | null = null;
@@ -859,36 +859,3 @@ describe("ReplicaCache", () => {
expect(storage.cleanups).toBe(1);
});
});
it("retains semantic agent messages across disk-cache reconstruction", async () => {
const storage = new MemoryStorage();
const writer = createCache(storage);
const value = timeline();
value.items = [
{
kind: "tool_call",
id: "delivery",
timestamp: new Date(1),
timelineCursor: { epoch: "epoch-1", seq: 12 },
payload: {
source: "agent",
data: {
provider: "codex",
callId: "delivery",
name: "agent_message",
status: "completed",
error: null,
detail: { type: "plain_text", text: "Done" },
agentMessage: {
event: "finished",
sender: { id: "remote::worker", title: "Reviewer" },
text: "Done",
},
},
},
},
];
writer.commitTimeline(SERVER_ID, "agent-1", value);
await writer.flush();
expect(await createCache(storage).readTimeline(SERVER_ID, "agent-1")).toEqual(value);
});
@@ -421,7 +421,6 @@ function serializeAgentToolCall(data: AgentToolCallData): StoredToolCall {
name: data.name,
detail: data.detail,
...(data.metadata ? { metadata: data.metadata } : {}),
...(data.agentMessage ? { agentMessage: data.agentMessage } : {}),
};
switch (data.status) {
case "running":
@@ -585,7 +584,6 @@ function deserializeBuiltinTimelineItem(
error: tool.error,
detail: tool.detail,
...(tool.metadata ? { metadata: tool.metadata } : {}),
...(tool.agentMessage ? { agentMessage: tool.agentMessage } : {}),
},
},
};
-2
View File
@@ -113,7 +113,6 @@ export interface WorkspaceDescriptor {
worktreeSlug?: WorkspaceDescriptorPayload["worktreeSlug"];
projectKind: WorkspaceDescriptorPayload["projectKind"];
workspaceKind: WorkspaceDescriptorPayload["workspaceKind"];
background?: boolean;
name: string;
title?: string | null;
pinnedAt?: string | null;
@@ -151,7 +150,6 @@ export function normalizeWorkspaceDescriptor(
worktreeSlug: payload.worktreeSlug,
projectKind: payload.projectKind,
workspaceKind: payload.workspaceKind,
background: payload.background ?? false,
name: payload.name,
title: payload.title ?? null,
pinnedAt: payload.pinnedAt ?? null,
@@ -32,7 +32,6 @@ function createMemoryStorage(entries: Record<string, string | null>): MemoryStor
describe("sidebar view store", () => {
beforeEach(() => {
useSidebarViewStore.setState({
showBackground: false,
groupMode: "project",
hostFilters: [],
projectFilters: [],
@@ -85,7 +84,6 @@ describe("sidebar view store", () => {
},
}),
).toEqual({
showBackground: false,
groupMode: "status",
hostFilters: [],
projectFilters: [],
@@ -100,7 +98,6 @@ describe("sidebar view store", () => {
hostFilter: "host-a",
}),
).toEqual({
showBackground: false,
groupMode: "status",
hostFilters: ["host-a"],
projectFilters: [],
@@ -115,7 +112,6 @@ describe("sidebar view store", () => {
hostFilters: ["host-a", "host-b"],
}),
).toEqual({
showBackground: false,
groupMode: "status",
hostFilters: ["host-a", "host-b"],
projectFilters: [],
@@ -226,7 +222,6 @@ describe("sidebar view store", () => {
projectFilters: ["project-a", "project-b"],
}),
).toEqual({
showBackground: false,
groupMode: "project",
hostFilters: ["host-a"],
projectFilters: ["project-a", "project-b"],
@@ -236,7 +231,6 @@ describe("sidebar view store", () => {
it("never keeps project filters from state the schema rejects", () => {
expect(migrateSidebarViewState({ projectFilters: "project-a" })).toEqual({
showBackground: false,
groupMode: "project",
hostFilters: [],
projectFilters: [],
+1 -11
View File
@@ -9,7 +9,7 @@ export type SidebarGroupMode = "project" | "status";
const SIDEBAR_VIEW_STORAGE_KEY = "sidebar-view";
const LEGACY_SIDEBAR_GROUP_MODE_STORAGE_KEY = "sidebar-group-mode";
const SIDEBAR_VIEW_STORE_VERSION = 7;
const SIDEBAR_VIEW_STORE_VERSION = 6;
/**
* The key standing for "this workspace carries no labels at all".
@@ -47,7 +47,6 @@ function toggleFilterEntry(list: readonly string[], key: string): string[] {
interface SidebarViewStoreState {
groupMode: SidebarGroupMode;
showBackground: boolean;
// Empty means "all hosts". A non-empty list pins the sidebar to those hosts.
hostFilters: string[];
/**
@@ -62,7 +61,6 @@ interface SidebarViewStoreState {
*/
projectFilters: string[];
labelFilter: SidebarLabelFilter;
toggleBackground: () => void;
setGroupMode: (mode: SidebarGroupMode) => void;
toggleHostFilter: (serverId: string) => void;
clearHostFilters: () => void;
@@ -76,7 +74,6 @@ interface SidebarViewStoreState {
interface SidebarViewPersistedState {
groupMode: SidebarGroupMode;
showBackground: boolean;
hostFilters: string[];
projectFilters: string[];
labelFilter: SidebarLabelFilter;
@@ -87,7 +84,6 @@ const SidebarLabelFilterSchema = z.object({
labels: z.array(z.string()),
});
const SidebarViewPersistedStateSchema = z.strictObject({
showBackground: z.boolean().optional(),
groupMode: PersistedSidebarGroupModeSchema.optional(),
hostFilters: z.array(z.string()).optional(),
hostFilter: z.string().nullable().optional(),
@@ -126,7 +122,6 @@ export function migrateSidebarViewState(persistedState: unknown): SidebarViewPer
const result = SidebarViewPersistedStateSchema.safeParse(persistedState);
if (!result.success) {
return {
showBackground: false,
groupMode: "project",
hostFilters: [],
projectFilters: [],
@@ -138,7 +133,6 @@ export function migrateSidebarViewState(persistedState: unknown): SidebarViewPer
const legacyGroupMode = readLegacyGroupMode(state);
if (legacyGroupMode) {
return {
showBackground: false,
groupMode: legacyGroupMode,
hostFilters: [],
projectFilters: [],
@@ -147,7 +141,6 @@ export function migrateSidebarViewState(persistedState: unknown): SidebarViewPer
}
return {
showBackground: state.showBackground ?? false,
groupMode: state.groupMode === "status" ? "status" : "project",
hostFilters: readHostFilters(state),
projectFilters: state.projectFilters ?? [],
@@ -185,12 +178,10 @@ export function createSidebarViewStorage(
export const useSidebarViewStore = create<SidebarViewStoreState>()(
persist(
(set) => ({
showBackground: false,
groupMode: "project",
hostFilters: [],
projectFilters: [],
labelFilter: emptyLabelFilter(),
toggleBackground: () => set((state) => ({ showBackground: !state.showBackground })),
setGroupMode: (mode) => set({ groupMode: mode }),
toggleHostFilter: (serverId) =>
set((state) => ({ hostFilters: toggleFilterEntry(state.hostFilters, serverId) })),
@@ -237,7 +228,6 @@ export const useSidebarViewStore = create<SidebarViewStoreState>()(
SidebarViewPersistedStateSchema,
),
partialize: (state) => ({
showBackground: state.showBackground ?? false,
groupMode: state.groupMode,
hostFilters: state.hostFilters,
projectFilters: state.projectFilters,
@@ -92,42 +92,3 @@ describe("tool-call presentation", () => {
expect(presentation.icon).toBe(fakeIcons.brain);
});
});
it.each([
["message", "Message from QA messenger"],
["finished", "QA messenger finished"],
["errored", "QA messenger errored"],
["permission-required", "QA messenger needs permission"],
["closed", "QA messenger closed"],
] as const)("presents %s from structured provenance without a second label", (event, heading) => {
const presentation = buildToolCallPresentation({
toolName: "internal_name_should_not_be_visible",
status: "completed",
error: null,
detail: { type: "plain_text", label: "legacy summary", text: "legacy body" },
agentMessage: {
event,
sender: { id: "server::sender", title: "QA messenger" },
text: "The delivered message.",
},
resolveIcon: fakeResolveIcon,
});
expect(presentation.displayName).toBe(heading);
expect(presentation.summary).toBeUndefined();
expect(presentation.detail).toEqual({
type: "plain_text",
icon: "bot",
text: "From agent: server::sender\n\nThe delivered message.",
});
});
it("uses an opaque sender ID when no title is available", () => {
const presentation = buildToolCallPresentation({
toolName: "agent_message",
status: "completed",
error: null,
agentMessage: { event: "message", sender: { id: "remote::worker" }, text: "Hello" },
resolveIcon: fakeResolveIcon,
});
expect(presentation.displayName).toBe("Message from remote::worker");
});
+5 -14
View File
@@ -1,5 +1,3 @@
import type { AgentMessage } from "@getpaseo/protocol/agent-message";
import { buildAgentMessageDisplay } from "@getpaseo/protocol/agent-message-display";
import type { PlanOutcome } from "@/components/plan-card";
import type { ComponentType } from "react";
import type { ToolCallDetail } from "@getpaseo/protocol/agent-types";
@@ -15,7 +13,6 @@ type ToolCallStatus = "executing" | "running" | "completed" | "failed" | "cancel
export type ToolCallPresentationIcon = ComponentType<{ size?: number; color?: string }>;
interface BuildToolCallPresentationInput {
agentMessage?: AgentMessage;
toolName: string;
status: ToolCallStatus;
error: unknown;
@@ -26,7 +23,6 @@ interface BuildToolCallPresentationInput {
}
export interface ToolCallPresentation {
detail: ToolCallDetail | undefined;
displayName: string;
summary?: string;
errorText?: string;
@@ -55,13 +51,9 @@ function displayDetail(detail: ToolCallDetail | undefined): ToolCallDetail {
export function buildToolCallPresentation(
input: BuildToolCallPresentationInput,
): ToolCallPresentation {
const detail = input.agentMessage
? buildAgentMessageDisplay(input.agentMessage).detail
: input.detail;
const detailForDisplay = displayDetail(detail);
const detailForDisplay = displayDetail(input.detail);
const displayModel = buildToolCallDisplayModel({
name: input.toolName,
agentMessage: input.agentMessage,
status: displayStatus(input.status),
error: input.error ?? null,
detail: detailForDisplay,
@@ -69,22 +61,21 @@ export function buildToolCallPresentation(
cwd: input.cwd,
});
const isLoadingDetails = isPendingToolCallDetail({
detail,
detail: input.detail,
status: input.status,
error: input.error,
});
const hasDetails = Boolean(input.error) || hasMeaningfulToolCallDetail(detail);
const hasDetails = Boolean(input.error) || hasMeaningfulToolCallDetail(input.detail);
return {
detail,
displayName: displayModel.displayName,
summary: displayModel.summary,
errorText: displayModel.errorText,
icon: input.resolveIcon(input.toolName, detail),
icon: input.resolveIcon(input.toolName, input.detail),
isLoadingDetails,
hasDetails,
canOpenDetails: hasDetails || isLoadingDetails,
openFilePath: extractToolCallFilePath(detail),
openFilePath: extractToolCallFilePath(input.detail),
isPlan: input.detail?.type === "plan",
planOutcome: input.detail?.type === "plan" ? resolvePlanOutcome(input) : undefined,
};
-25
View File
@@ -2305,28 +2305,3 @@ describe("notification timeline items", () => {
expect(new Set(state.map((item) => item.id)).size).toBe(state.length);
});
});
it("retains agent-message provenance through live delivery and repeated history", () => {
const agentMessage = {
event: "finished" as const,
sender: { id: "remote::worker", title: "Reviewer" },
text: "Done",
};
const event = {
type: "timeline",
provider: "codex",
item: {
type: "tool_call",
callId: "delivery",
name: "agent_message",
status: "completed",
error: null,
detail: { type: "plain_text", text: "Done" },
agentMessage,
},
} satisfies AgentStreamEventPayload;
const live = reduceStreamUpdate([], event, new Date(1));
const replay = reduceStreamUpdate(live, event, new Date(2));
expect(replay).toHaveLength(1);
expect(replay[0]).toMatchObject({ payload: { data: { agentMessage } } });
});
-3
View File
@@ -1,4 +1,3 @@
import type { AgentMessage } from "@getpaseo/protocol/agent-message";
import type {
AgentProvider,
AgentTimelineItem,
@@ -746,7 +745,6 @@ interface OrchestratorToolCallData {
}
export interface AgentToolCallData {
agentMessage?: AgentMessage;
provider: AgentProvider;
callId: string;
name: string;
@@ -1448,7 +1446,6 @@ function reduceTimelineToolCall(
error: item.error,
detail: item.detail,
metadata: item.metadata,
...(item.agentMessage ? { agentMessage: item.agentMessage } : {}),
},
timestamp,
timelineCursor,
+1 -5
View File
@@ -22,11 +22,7 @@ export default defineConfig({
test: {
name: "unit",
environment: "node",
include: [
"src/**/*.{test,spec}.{ts,tsx}",
"native-release-version.test.ts",
"app.config.test.ts",
],
include: ["src/**/*.{test,spec}.{ts,tsx}", "native-release-version.test.ts"],
setupFiles: [path.resolve(__dirname, "vitest.setup.ts")],
exclude: [...configDefaults.exclude, "e2e/**", "src/**/*.browser.{test,spec}.{ts,tsx}"],
},
+3 -30
View File
@@ -46,25 +46,10 @@ describe("canonical CLI surface", () => {
expect(help).toContain("--forge <forge>");
});
it("uses --no-wait for execution, --internal for visibility, and reserves detach for ownership", () => {
it("uses background for execution and reserves detach for ownership", () => {
const run = createCli().commands.find((command) => command.name() === "run");
const help = run?.helpInformation();
expect(help).toContain("--no-wait");
expect(help).not.toContain("--background");
expect(help).not.toContain("--background");
expect(help).not.toContain("--detach");
});
it("hides internal agents and workspaces from listings unless --internal is passed", () => {
const cli = createCli();
const ls = cli.commands.find((command) => command.name() === "ls");
const workspace = cli.commands.find((command) => command.name() === "workspace");
const workspaceLs = workspace?.commands.find((command) => command.name() === "ls");
const workspaceCreate = workspace?.commands.find((command) => command.name() === "create");
expect(ls?.helpInformation()).toContain("--background");
expect(workspaceLs?.helpInformation()).toContain("--background");
expect(workspaceCreate?.helpInformation()).toContain("--background");
expect(run?.helpInformation()).toContain("--background");
expect(run?.helpInformation()).not.toContain("--detach");
});
it("offers thinking configuration when running, updating, and scheduling agents", () => {
@@ -111,15 +96,3 @@ describe("canonical CLI surface", () => {
).toContain("--id <id>");
});
});
it("preserves omitted and explicit false workspace background intent", () => {
const readOptions = (args: string[]) => {
const workspace = createCli().commands.find((command) => command.name() === "workspace")!;
const create = workspace.commands.find((command) => command.name() === "create")!;
create.parseOptions(args);
return create.opts();
};
expect(readOptions([]).background).toBeUndefined();
expect(readOptions(["--background"]).background).toBe(true);
expect(readOptions(["--no-background"]).background).toBe(false);
});
-2
View File
@@ -3,7 +3,6 @@ import { Command, Option } from "commander";
import { createAgentCommand } from "./commands/agent/index.js";
import { createDaemonCommand } from "./commands/daemon/index.js";
import { createPermitCommand } from "./commands/permit/index.js";
import { createUsageCommand } from "./commands/usage/index.js";
import { createProviderCommand } from "./commands/provider/index.js";
import { createPluginCommand } from "./commands/plugin/index.js";
import { createProjectCommand } from "./commands/project/index.js";
@@ -149,7 +148,6 @@ export function createCli(): Command {
// Provider commands
program.addCommand(createProviderCommand());
program.addCommand(createUsageCommand());
program.addCommand(createPluginCommand());
// Speech model commands
+2 -9
View File
@@ -23,21 +23,15 @@ describe("buildAgentLsFetchOptions", () => {
});
});
it("asks the daemon for internal agents only with --internal", () => {
expect(buildAgentLsFetchOptions({ background: true, global: true })).toEqual({
filter: { includeBackground: true },
});
});
it("fetches global non-archived agents for -g", () => {
expect(buildAgentLsFetchOptions({ global: true })).toEqual({});
});
it("includes archived and background agents with -a", () => {
it("keeps -a within the active scope", () => {
expect(buildAgentLsFetchOptions({ all: true })).toEqual({
scope: "active",
filter: {
includeArchived: true,
includeBackground: true,
},
});
});
@@ -46,7 +40,6 @@ describe("buildAgentLsFetchOptions", () => {
expect(buildAgentLsFetchOptions({ all: true, global: true })).toEqual({
filter: {
includeArchived: true,
includeBackground: true,
},
});
});
+4 -10
View File
@@ -12,9 +12,8 @@ type FetchAgentsOptions = NonNullable<
export function addLsOptions(cmd: Command): Command {
return cmd
.description("List agents. By default excludes archived agents.")
.option("-a, --all", "Include archived and background agents")
.option("-a, --all", "Include archived agents")
.option("-g, --global", "List agents across all directories")
.option("--background", "Include background workspace agents")
.option(
"--label <key=value>",
"Filter by label (can be used multiple times)",
@@ -110,8 +109,6 @@ export interface AgentLsOptions extends CommandOptions {
all?: boolean;
/** -g: List agents across all directories */
global?: boolean;
/** --background: Include background workspace agents */
background?: boolean;
/** Filter by specific status */
status?: string;
/** Filter by specific cwd */
@@ -136,7 +133,7 @@ function parseLabelFilters(labels: string[] | undefined): Record<string, string>
}
export function buildAgentLsFetchOptions(
options: Pick<AgentLsOptions, "all" | "global" | "background" | "label" | "thinking">,
options: Pick<AgentLsOptions, "all" | "global" | "label" | "thinking">,
): FetchAgentsOptions {
const labelFilters = parseLabelFilters(options.label);
const normalizedThinkingOptionId = options.thinking?.trim();
@@ -145,9 +142,6 @@ export function buildAgentLsFetchOptions(
if (options.all) {
daemonFilter.includeArchived = true;
}
if (options.background || options.all) {
daemonFilter.includeBackground = true;
}
if (Object.keys(labelFilters).length > 0) {
daemonFilter.labels = labelFilters;
}
@@ -156,7 +150,7 @@ export function buildAgentLsFetchOptions(
}
const fetchOptions: FetchAgentsOptions = {};
if (!options.global && !options.all) {
if (!options.global) {
fetchOptions.scope = "active";
}
if (Object.keys(daemonFilter).length > 0) {
@@ -169,7 +163,7 @@ export function buildAgentLsFetchOptions(
* Agent ls command semantics:
* - `paseo agent ls` → active non-archived agents
* - `paseo agent ls -g` → global non-archived agents
* - `paseo agent ls -a` → all agents, including archived and background
* - `paseo agent ls -a` → active agents, including archived
* - `paseo agent ls -ag` → global agents, including archived
*/
export async function runLsCommand(
+11 -24
View File
@@ -1,10 +1,9 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { DaemonConnectionError } from "@getpaseo/client/internal/daemon-client";
import { resolveCallerAgentId as resolveRunCallerAgentId } from "../../utils/caller-agent.js";
import {
resolveExistingRunWorkspace,
resolveRunCallerAgentId,
runRunCommand,
waitsForFinish,
type AgentRunOptions,
} from "./run";
@@ -22,15 +21,6 @@ function daemonWithAgents(...agentIds: string[]) {
};
}
describe("run wait policy", () => {
it("waits by default and stops waiting on --no-wait or a legacy alias", () => {
expect(waitsForFinish({})).toBe(true);
expect(waitsForFinish({ wait: false })).toBe(false);
expect(waitsForFinish({ background: true })).toBe(false);
expect(waitsForFinish({ detach: true })).toBe(false);
});
});
describe("managed agent caller context", () => {
it("uses a trimmed PASEO_AGENT_ID when the target daemon runs that agent", async () => {
await expect(
@@ -48,20 +38,17 @@ describe("managed agent caller context", () => {
).resolves.toBeUndefined();
});
it.each(["DAEMON_CONNECTION_LOST", "DAEMON_REQUEST_TIMEOUT"] as const)(
"preserves %s instead of dropping the caller",
async (code) => {
const disconnectedDaemon = {
async fetchAgent(): Promise<never> {
throw new DaemonConnectionError("Caller lookup transport failed", code);
},
};
it("fails instead of dropping the caller when the lookup loses its connection", async () => {
const disconnectedDaemon = {
async fetchAgent(): Promise<never> {
throw new DaemonConnectionError("Connection lost before message could be sent");
},
};
await expect(
resolveRunCallerAgentId(disconnectedDaemon, { PASEO_AGENT_ID: "parent-agent" }),
).rejects.toBeInstanceOf(DaemonConnectionError);
},
);
await expect(
resolveRunCallerAgentId(disconnectedDaemon, { PASEO_AGENT_ID: "parent-agent" }),
).rejects.toBeInstanceOf(DaemonConnectionError);
});
it("omits blank caller ids", async () => {
await expect(
+37 -24
View File
@@ -4,7 +4,7 @@ import {
StructuredAgentResponseError,
} from "@getpaseo/server/agent-response";
import type { AgentSnapshotPayload } from "@getpaseo/protocol/messages";
import { resolveCallerAgentId } from "../../utils/caller-agent.js";
import { DaemonConnectionError } from "@getpaseo/client/internal/daemon-client";
import { connectToDaemon } from "../../utils/client.js";
import type {
CommandOptions,
@@ -27,13 +27,10 @@ export function addRunOptions(cmd: Command): Command {
cmd
.description("Create and start an agent with a task")
.argument("<prompt>", "The task/prompt for the agent")
.option("--no-wait", "Return immediately without waiting for completion")
// COMPAT(backgroundRunFlag): --background was the documented spelling of
// --no-wait. Added in v0.2.0; remove after 2027-04-01.
.addOption(new Option("-d, --background", "Legacy alias for --no-wait").hideHelp())
.option("-d, --background", "Run in background")
// COMPAT(detachRunFlag): --detach used to mean background execution, not
// ownership transfer. Added in v0.2.0; remove after 2027-01-17.
.addOption(new Option("--detach", "Legacy alias for --no-wait").hideHelp())
.addOption(new Option("--detach", "Legacy alias for --background").hideHelp())
.option("--title <title>", "Assign a title to the agent")
.addOption(new Option("--name <name>", "Hidden alias for --title").hideHelp())
.option(
@@ -114,7 +111,6 @@ export const agentRunSchema: OutputSchema<AgentRunResult> = {
};
export interface AgentRunOptions extends CommandOptions {
wait?: boolean;
background?: boolean;
detach?: boolean;
title?: string;
@@ -393,25 +389,19 @@ function validateRunOptions(prompt: string, options: AgentRunOptions, outputSche
} satisfies CommandError;
}
if (options.background) {
console.error("Warning: --background (-d) is deprecated. Use --no-wait instead.");
}
validateRunWorkspaceOptions(options);
if (outputSchema && !waitsForFinish(options)) {
if (outputSchema && runsInBackground(options)) {
throw {
code: "INVALID_OPTIONS",
message: "--output-schema cannot be used with --no-wait",
message: "--output-schema cannot be used with --background",
details: "Structured output requires waiting for the agent to finish",
} satisfies CommandError;
}
}
export function waitsForFinish(
options: Pick<AgentRunOptions, "wait" | "background" | "detach">,
): boolean {
return options.wait !== false && !options.background && !options.detach;
function runsInBackground(options: Pick<AgentRunOptions, "background" | "detach">): boolean {
return Boolean(options.background || options.detach);
}
function parseWaitTimeoutOption(waitTimeout: string | undefined): number {
@@ -567,10 +557,7 @@ async function resolveRunWorkspace(
// TODO: thread the run `prompt` as firstAgentContext so workspace-level
// title/branch generation picks up the task description (U8/U6 deferred).
const source = buildRunWorkspaceSource(options, cwd);
const result = await client.createWorkspace({
source,
...(callerAgentId ? { callerAgentId } : {}),
});
const result = await client.createWorkspace({ source });
if (!result.workspace) {
throw {
@@ -624,7 +611,7 @@ export async function runRunCommand(
const env = parseRunEnv(options.env);
const requestEnv = Object.keys(env).length > 0 ? env : undefined;
const callerAgentId = await resolveCallerAgentId(client);
const callerAgentId = await resolveRunCallerAgentId(client);
const workspace = await resolveRunWorkspace(client, options, cwd, callerAgentId);
const workspaceId = workspace.id;
const runCwd = workspace.cwd;
@@ -720,8 +707,8 @@ export async function runRunCommand(
labels: Object.keys(labels).length > 0 ? labels : undefined,
});
// Default run behavior is foreground: wait for completion unless --no-wait is set.
if (waitsForFinish(options)) {
// Default run behavior is foreground: wait for completion unless background execution is set.
if (!runsInBackground(options)) {
const state = await client.waitForFinish(agent.id, waitTimeoutMs);
await client.close();
@@ -757,3 +744,29 @@ export async function runRunCommand(
throw error;
}
}
export interface RunCallerLookupClient {
fetchAgent(options: { agentId: string }): Promise<{ agent: { id: string } } | null>;
}
// PASEO_AGENT_ID names an agent on the daemon that launched this shell. A run
// sent to another daemon (--host or --home) has no caller there, so it runs as
// a top-level agent instead of failing on an unknown caller.
export async function resolveRunCallerAgentId(
client: RunCallerLookupClient,
env: { PASEO_AGENT_ID?: string } = process.env,
): Promise<string | undefined> {
const agentId = env.PASEO_AGENT_ID?.trim();
if (!agentId) {
return undefined;
}
const caller = await client.fetchAgent({ agentId }).catch((error: unknown) => {
// A daemon without this agent answers with an error. A lost or timed-out
// connection is not an answer, so it must not drop the caller.
if (error instanceof DaemonConnectionError) {
throw error;
}
return null;
});
return caller?.agent.id === agentId ? agentId : undefined;
}
+1 -4
View File
@@ -192,10 +192,7 @@ export async function runSendCommand(
options.image && options.image.length > 0 ? await readImageFiles(options.image) : undefined;
// Send the message
await client.sendAgentMessage(agentIdArg, promptInput, {
images,
sourceAgentId: process.env.PASEO_AGENT_ID?.trim() || undefined,
});
await client.sendAgentMessage(agentIdArg, promptInput, { images });
// If --no-wait, return immediately
if (options.wait === false) {
@@ -1,279 +0,0 @@
import { describe, expect, it } from "vitest";
import type { UsageReportEntry } from "@getpaseo/protocol/messages";
import { render } from "../../output/index.js";
import { createCli } from "../../cli.js";
import { runUsageCommand } from "./index.js";
const options = { daemonTarget: { kind: "endpoint" as const, host: "example.test:1234" } };
const reports: UsageReportEntry[] = [
{
id: "plugin.source:work.account",
sourceId: "plugin.source",
sourceLabel: "Plugin Source",
account: { label: "Work" },
fetchedAt: "2026-10-09T12:00:00Z",
icon: "<svg />",
report: {
status: "available",
planLabel: "Pro",
windows: [
{
id: "5h",
label: "Five hours",
usedPct: 12.5,
remainingPct: 87.5,
resetsAt: "2026-10-09T17:00:00Z",
runsOutAt: "2026-10-09T16:00:00Z",
shortfallPct: 4.25,
},
{ id: "week", label: "Weekly", usedPct: null, remainingPct: 0 },
{ id: "extra", label: "Extra", usedPct: 0 },
],
balances: [
{
id: "credit",
label: "Credit",
used: 0,
remaining: 2.5,
limit: 10,
unit: "usd",
resetsAt: "2026-11-01T00:00:00Z",
},
{ id: "requests", label: "Requests", remaining: null, unit: "requests" },
],
details: [{ id: "tier", label: "Tier", value: "Enterprise" }],
},
},
{
id: "plugin.source:personal",
sourceId: "plugin.source",
sourceLabel: "Plugin Source",
account: {},
fetchedAt: "2026-10-09T12:00:00Z",
report: {
status: "unavailable",
problem: { kind: "rejected", status: 401, refreshedBy: "codex login" },
},
loginErrors: [
{
harness: "Claude Code",
report: {
status: "unavailable",
problem: { kind: "expired", expiresAt: "2026-10-08T00:00:00Z", refreshedBy: "claude" },
},
},
{
harness: "Codex",
report: {
status: "unavailable",
problem: { kind: "rejected", status: 401, refreshedBy: "codex login" },
},
},
{ harness: "Other", report: { status: "error", error: "Login service failed" } },
],
},
{
id: "other:broken",
sourceId: "other",
sourceLabel: "Other",
account: {},
fetchedAt: "2026-10-09T12:00:00Z",
report: { status: "error", error: "Source failed" },
},
{
id: "other:noquota",
sourceId: "other",
sourceLabel: "Other",
account: {},
fetchedAt: "2026-10-09T12:00:00Z",
report: {
status: "unavailable",
problem: { kind: "no_quota", detail: "No quota for this plan" },
},
},
];
function host(entries = reports, supported = true) {
const requests: Array<Parameters<NonNullable<Parameters<typeof runUsageCommand>[2]>>[0]> = [];
const queries: Array<
{ agentId?: string; forceRefresh?: boolean; reportIds?: string[] } | undefined
> = [];
let closed = 0;
return {
requests,
queries,
get closed() {
return closed;
},
connect: async (input: (typeof requests)[number]) => {
requests.push(input);
return {
getLastServerInfoMessage: () => ({ features: { usageSources: supported } }),
listUsageReports: async (query?: (typeof queries)[number]) => {
queries.push(query);
const selected = query?.reportIds
? entries.filter((entry) => query.reportIds!.includes(entry.id))
: entries;
return { requestId: "request", reports: selected };
},
close: async () => {
closed++;
},
};
},
};
}
it("preserves complete JSON entries, numeric values and quiet full IDs", async () => {
const daemon = host();
const result = await runUsageCommand(options, { kind: "list" }, daemon.connect);
expect(JSON.parse(render(result, { format: "json" }))).toEqual(reports);
expect(render(result, { quiet: true })).toBe(reports.map((entry) => entry.id).join("\n"));
expect(daemon.requests).toEqual([{ target: options.daemonTarget }]);
expect(daemon.closed).toBe(1);
});
it("lists all windows, balances, missing values, failures and remedies", async () => {
const result = await runUsageCommand(options, { kind: "list" }, host().connect);
const text = render(result, { noColor: true });
for (const expected of [
"REPORT ID",
"SOURCE",
"ACCOUNT",
"STATUS",
"USAGE",
"FETCHED",
"Five hours: 12.5% used, 87.5% remaining",
"Weekly: - used, 0% remaining",
"Extra: 0% used, - remaining",
"Credit: 0 used, 2.5 remaining, 10 limit (usd)",
"Requests: - used, - remaining, - limit (requests)",
"Login expired at 2026-10-08T00:00:00Z. Run claude",
"Login rejected (HTTP 401). Run codex login",
"Other: Login service failed",
"Source failed",
"No quota for this plan",
])
expect(text).toContain(expected);
expect(render(result, { noHeaders: true })).not.toContain("REPORT ID");
});
it("inspects exact opaque IDs and includes resets, forecasts, details and login failures", async () => {
const daemon = host();
const result = await runUsageCommand(
options,
{ kind: "inspect", id: reports[0]!.id },
daemon.connect,
);
expect(JSON.parse(render(result, { format: "json" }))).toEqual(reports[0]);
const text = render(result);
for (const expected of [
"Source ID: plugin.source",
"Plan: Pro",
"Resets: 2026-10-09T17:00:00Z",
"Runs out: 2026-10-09T16:00:00Z",
"Shortfall: 4.25%",
"Resets: -",
"Resets: 2026-11-01T00:00:00Z",
"Tier: Enterprise",
])
expect(text).toContain(expected);
const failure = await runUsageCommand(
options,
{ kind: "inspect", id: reports[1]!.id },
daemon.connect,
);
expect(render(failure)).toContain("Login failures:\n Claude Code: Login expired at");
expect(render(failure)).toContain(" Other: Login service failed");
});
it("discovers before inspecting, then refreshes only the selected report", async () => {
const daemon = host();
await runUsageCommand(
{ ...options, refresh: true },
{ kind: "inspect", id: reports[0]!.id },
daemon.connect,
);
expect(daemon.queries).toEqual([undefined, { reportIds: [reports[0]!.id], forceRefresh: true }]);
});
it("rejects agent selection combined with inspect before connecting", async () => {
const daemon = host();
await expect(
runUsageCommand(
{ ...options, agent: "agent-A" },
{ kind: "inspect", id: reports[0]!.id },
daemon.connect,
),
).rejects.toMatchObject({ code: "INVALID_OPTIONS" });
expect(daemon.requests).toEqual([]);
});
it("passes agent account selection and refresh without converting it to token consumption", async () => {
const daemon = host();
await runUsageCommand(
{ ...options, agent: "agent-123", refresh: true },
{ kind: "list" },
daemon.connect,
);
expect(daemon.queries).toEqual([{ agentId: "agent-123", forceRefresh: true }]);
});
it("returns an empty array in JSON and explains empty discovery in human output", async () => {
const result = await runUsageCommand(options, { kind: "list" }, host([]).connect);
expect(render(result, { format: "json" })).toBe("[]");
expect(render(result)).toBe("No usage reports returned");
expect(render(result, { quiet: true })).toBe("");
});
it("rejects unknown IDs and prefixes and closes the client", async () => {
const daemon = host();
await expect(
runUsageCommand(options, { kind: "inspect", id: "plugin.source:work" }, daemon.connect),
).rejects.toEqual({
code: "REPORT_NOT_FOUND",
message: "Unknown usage report: plugin.source:work",
});
expect(daemon.closed).toBe(1);
});
it("gates unsupported hosts before any request and closes the connection", async () => {
const daemon = host(reports, false);
await expect(runUsageCommand(options, { kind: "list" }, daemon.connect)).rejects.toMatchObject({
code: "UNSUPPORTED_HOST",
});
expect(daemon.queries).toEqual([]);
expect(daemon.closed).toBe(1);
});
it("propagates connection and request failures", async () => {
await expect(
runUsageCommand(options, { kind: "list" }, async () => {
throw new Error("Connection failed");
}),
).rejects.toThrow("Connection failed");
let closed = false;
const connect = async () => ({
getLastServerInfoMessage: () => ({ features: { usageSources: true } }),
listUsageReports: async () => {
throw new Error("Request failed");
},
close: async () => {
closed = true;
},
});
await expect(runUsageCommand(options, { kind: "list" }, connect)).rejects.toThrow(
"Request failed",
);
expect(closed).toBe(true);
});
describe("usage CLI registration", () => {
it("registers default, ls and inspect with the accepted selectors", () => {
const usage = createCli().commands.find((command) => command.name() === "usage")!;
expect(usage.commands.map((command) => command.name())).toEqual(["ls", "inspect"]);
expect(usage.helpInformation()).toContain("--agent <id>");
expect(usage.commands[0]!.helpInformation()).toContain("--refresh");
expect(usage.commands[1]!.helpInformation()).toContain("<report-id>");
});
});
-95
View File
@@ -1,95 +0,0 @@
import { Command } from "commander";
import type { DaemonClient } from "@getpaseo/client/internal/daemon-client";
import type { UsageReportEntry } from "@getpaseo/protocol/messages";
import { connectToDaemon, type ConnectOptions } from "../../utils/client.js";
import { addJsonAndDaemonHostOptions } from "../../utils/command-options.js";
import { withOutput, type CommandOptions, type CommandResult } from "../../output/index.js";
import { usageSchema } from "./presentation.js";
interface UsageOptions extends CommandOptions {
agent?: string;
refresh?: boolean;
}
type UsageSelection = { kind: "list" } | { kind: "inspect"; id: string };
interface UsageClient {
getLastServerInfoMessage(): { features?: { usageSources?: boolean } } | null;
listUsageReports: DaemonClient["listUsageReports"];
close: DaemonClient["close"];
}
type ConnectUsage = (options: ConnectOptions) => Promise<UsageClient>;
export async function runUsageCommand(
options: UsageOptions,
selection: UsageSelection,
connect: ConnectUsage = connectToDaemon,
): Promise<CommandResult<UsageReportEntry>> {
const conflictingSelectors = selection.kind === "inspect" && options.agent !== undefined;
if (conflictingSelectors) {
throw {
code: "INVALID_OPTIONS",
message:
"--agent cannot be combined with usage inspect. Use usage ls --agent <id> for agent account usage, or usage inspect <report-id> for an exact report.",
};
}
const client = await connect({ target: options.daemonTarget });
try {
if (client.getLastServerInfoMessage()?.features?.usageSources !== true) {
throw { code: "UNSUPPORTED_HOST", message: "Update the host to use usage reports." };
}
if (selection.kind === "list") {
const { reports } = await client.listUsageReports({
agentId: options.agent,
forceRefresh: options.refresh,
});
return { type: "list", data: reports, schema: usageSchema };
}
// Report-ID queries only select known accounts. Discover before selecting, including on cold hosts.
const { reports } = await client.listUsageReports();
let entry = reports.find((report) => report.id === selection.id);
if (entry && options.refresh) {
const refreshed = await client.listUsageReports({
reportIds: [selection.id],
forceRefresh: true,
});
entry = refreshed.reports.find((report) => report.id === selection.id);
}
if (!entry) {
throw { code: "REPORT_NOT_FOUND", message: `Unknown usage report: ${selection.id}` };
}
return { type: "single", data: entry, schema: usageSchema };
} finally {
await client.close().catch(() => {});
}
}
function addListOptions(command: Command): Command {
return addJsonAndDaemonHostOptions(command)
.option(
"--agent <id>",
"Show account quota associated with this agent (not agent token consumption)",
)
.option("--refresh", "Refresh usage instead of using the host cache");
}
export function createUsageCommand(): Command {
const usage = addListOptions(new Command("usage").description("Show account usage reports"));
const list = (options: CommandOptions, _command: Command) =>
runUsageCommand(options, { kind: "list" });
usage.action(withOutput(list));
addListOptions(usage.command("ls").description("List account quotas and balances")).action(
withOutput(list),
);
addJsonAndDaemonHostOptions(
usage
.command("inspect")
.description("Show a complete account usage report")
.argument("<report-id>", "Exact opaque Report ID")
.option("--refresh", "Refresh the selected report instead of using the host cache"),
).action(
withOutput((id: string, options: CommandOptions, _command: Command) =>
runUsageCommand(options, { kind: "inspect", id }),
),
);
return usage;
}
@@ -1,137 +0,0 @@
import type {
UsageReportEntry,
UsageReport,
UsageProblem,
ProviderUsageWindow,
ProviderUsageBalance,
} from "@getpaseo/protocol/messages";
import { renderTable, type OutputSchema } from "../../output/index.js";
function value(input: string | number | null | undefined): string {
return input == null ? "-" : String(input);
}
function percent(input: number | null | undefined): string {
return input == null ? "-" : `${input}%`;
}
function problemText(problem: UsageProblem): string {
if (problem.kind === "no_quota") return problem.detail;
const remedy = problem.refreshedBy
? `Run ${problem.refreshedBy} to refresh login.`
: "Sign in again.";
if (problem.kind === "expired") return `Login expired at ${problem.expiresAt}. ${remedy}`;
return `Login rejected (HTTP ${problem.status}). ${remedy}`;
}
function failureText(report: UsageReport): string {
if (report.status === "error") return report.error;
if (report.status === "unavailable") return problemText(report.problem);
return "-";
}
function windowText(window: ProviderUsageWindow): string {
return `${window.label}: ${percent(window.usedPct)} used, ${percent(window.remainingPct)} remaining`;
}
function balanceText(balance: ProviderUsageBalance): string {
return `${balance.label}: ${value(balance.used)} used, ${value(balance.remaining)} remaining, ${value(balance.limit)} limit (${balance.unit})`;
}
function summary(entry: UsageReportEntry): string[] {
const { report } = entry;
if (report.status !== "available") {
const lines = [failureText(report)];
for (const login of entry.loginErrors ?? [])
lines.push(`${login.harness}: ${failureText(login.report)}`);
return lines;
}
const lines = report.windows.map(windowText);
lines.push(...(report.balances ?? []).map(balanceText));
return lines.length ? lines : ["-"];
}
interface SummaryRow {
id: string;
source: string;
account: string;
status: string;
usage: string;
fetched: string;
}
const summarySchema: OutputSchema<SummaryRow> = {
idField: "id",
columns: [
{ header: "REPORT ID", field: "id" },
{ header: "SOURCE", field: "source" },
{ header: "ACCOUNT", field: "account" },
{ header: "STATUS", field: "status" },
{ header: "USAGE", field: "usage" },
{ header: "FETCHED", field: "fetched" },
],
};
function inspect(entry: UsageReportEntry): string {
const lines = [
`Report ID: ${entry.id}`,
`Source: ${entry.sourceLabel}`,
`Source ID: ${entry.sourceId}`,
`Account: ${value(entry.account.label)}`,
`Status: ${entry.report.status}`,
`Fetched: ${value(entry.fetchedAt)}`,
];
const { report } = entry;
if (report.status === "available") {
lines.push(`Plan: ${value(report.planLabel)}`, "Windows:");
if (!report.windows.length) lines.push(" -");
for (const window of report.windows) {
lines.push(` ${windowText(window)} [${window.id}]`, ` Resets: ${value(window.resetsAt)}`);
if (window.runsOutAt != null) lines.push(` Runs out: ${window.runsOutAt}`);
if (window.shortfallPct != null) lines.push(` Shortfall: ${percent(window.shortfallPct)}`);
}
lines.push("Balances:");
if (!report.balances?.length) lines.push(" -");
for (const balance of report.balances ?? []) {
lines.push(
` ${balanceText(balance)} [${balance.id}]`,
` Resets: ${value(balance.resetsAt)}`,
);
}
lines.push("Details:");
if (!report.details?.length) lines.push(" -");
for (const detail of report.details ?? []) lines.push(` ${detail.label}: ${detail.value}`);
} else {
lines.push(`Reason: ${failureText(report)}`);
}
if (entry.loginErrors?.length) {
lines.push("Login failures:");
for (const login of entry.loginErrors)
lines.push(` ${login.harness}: ${failureText(login.report)}`);
}
return lines.join("\n");
}
export const usageSchema: OutputSchema<UsageReportEntry> = {
idField: "id",
columns: [],
renderHuman(result, options) {
if (result.type === "single") return inspect(result.data);
if (!result.data.length) return "No usage reports returned";
const rows: SummaryRow[] = [];
for (const entry of result.data) {
for (const [index, usage] of summary(entry).entries()) {
const first = index === 0;
rows.push({
id: first ? entry.id : "",
source: first ? entry.sourceLabel : "",
account: first ? value(entry.account.label) : "",
status: first ? entry.report.status : "",
usage,
fetched: first ? value(entry.fetchedAt) : "",
});
}
}
return renderTable<SummaryRow>({ type: "list", data: rows, schema: summarySchema }, options);
},
};
@@ -1,6 +1,5 @@
import type { Command } from "commander";
import { connectToDaemon, getDaemonHost } from "../../utils/client.js";
import { resolveCallerAgentId } from "../../utils/caller-agent.js";
import type { CommandError, CommandOptions, SingleResult } from "../../output/index.js";
import { toWorkspaceRow, workspaceSchema, type WorkspaceRow } from "./shared.js";
@@ -16,7 +15,6 @@ export interface WorkspaceCreateOptions extends CommandOptions {
branch?: string;
prNumber?: string;
forge?: string;
background?: boolean;
}
interface WorktreeSourceBase {
@@ -146,12 +144,9 @@ export async function runCreateCommand(
});
try {
const callerAgentId = await resolveCallerAgentId(client);
const payload = await client.createWorkspace({
source: buildWorkspaceSource(options),
...(options.title ? { title: options.title } : {}),
...(options.background !== undefined ? { background: options.background } : {}),
...(callerAgentId ? { callerAgentId } : {}),
});
if (!payload.workspace) {
throw new Error(payload.error ?? "Workspace creation failed");
+4 -9
View File
@@ -34,17 +34,12 @@ export function createWorkspaceCommand(): Command {
.option("--base <ref>", "Base ref (--mode branch-off)")
.option("--branch <name>", "Existing branch (--mode checkout-branch)")
.option("--pr-number <n>", "Pull request or change request number (--mode checkout-pr)")
.option("--forge <forge>", "Forge for --mode checkout-pr (default: source checkout)")
.option("--background", "Create a background workspace")
.option("--no-background", "Create a visible workspace instead of inheriting background"),
.option("--forge <forge>", "Forge for --mode checkout-pr (default: source checkout)"),
).action(withOutput(runCreateCommand));
addJsonAndDaemonHostOptions(
workspace
.command("ls")
.description("List active workspaces")
.option("--background", "Include background workspaces"),
).action(withOutput(runLsCommand));
addJsonAndDaemonHostOptions(workspace.command("ls").description("List active workspaces")).action(
withOutput(runLsCommand),
);
addJsonAndDaemonHostOptions(
workspace
+3 -20
View File
@@ -1,22 +1,10 @@
import type { Command } from "commander";
import { connectToDaemon, getDaemonHost } from "../../utils/client.js";
import type { CommandError, ListResult } from "../../output/index.js";
import {
toWorkspaceRow,
workspaceSchema,
workspaceWithBackgroundSchema,
type WorkspaceRow,
} from "./shared.js";
export interface WorkspaceLsOptions {
host?: string;
daemonTarget: import("../../utils/daemon-target.js").DaemonTarget;
/** --background: Include background workspaces */
background?: boolean;
}
import { toWorkspaceRow, workspaceSchema, type WorkspaceRow } from "./shared.js";
export async function runLsCommand(
options: WorkspaceLsOptions,
options: { host?: string; daemonTarget: import("../../utils/daemon-target.js").DaemonTarget },
_command: Command,
): Promise<ListResult<WorkspaceRow>> {
const host = getDaemonHost({ target: options.daemonTarget });
@@ -32,17 +20,12 @@ export async function runLsCommand(
let cursor: string | undefined;
do {
const payload = await client.fetchWorkspaces({
...(options.background ? { filter: { includeBackground: true } } : {}),
page: { limit: 200, ...(cursor ? { cursor } : {}) },
});
workspaces.push(...payload.entries.map(toWorkspaceRow));
cursor = payload.pageInfo.nextCursor ?? undefined;
} while (cursor);
return {
type: "list",
data: workspaces,
schema: options.background ? workspaceWithBackgroundSchema : workspaceSchema,
};
return { type: "list", data: workspaces, schema: workspaceSchema };
} finally {
await client.close().catch(() => undefined);
}
@@ -7,7 +7,6 @@ export interface WorkspaceRow {
name: string;
isolation: "local" | "worktree";
cwd: string;
background: boolean;
}
export const workspaceSchema: OutputSchema<WorkspaceRow> = {
@@ -21,15 +20,6 @@ export const workspaceSchema: OutputSchema<WorkspaceRow> = {
],
};
/** `--background` listings add a column so hidden workspaces stand out. */
export const workspaceWithBackgroundSchema: OutputSchema<WorkspaceRow> = {
...workspaceSchema,
columns: [
...workspaceSchema.columns,
{ header: "BACKGROUND", field: (row) => (row.background ? "yes" : ""), width: 8 },
],
};
export function toWorkspaceRow(workspace: WorkspaceDescriptorPayload): WorkspaceRow {
return {
workspaceId: workspace.id,
@@ -37,6 +27,5 @@ export function toWorkspaceRow(workspace: WorkspaceDescriptorPayload): Workspace
name: workspace.name,
isolation: workspace.workspaceKind === "worktree" ? "worktree" : "local",
cwd: workspace.workspaceDirectory,
background: workspace.background === true,
};
}
-21
View File
@@ -1,21 +0,0 @@
import { DaemonConnectionError } from "@getpaseo/client/internal/daemon-client";
interface CallerLookupClient {
fetchAgent(options: { agentId: string }): Promise<{ agent: { id: string } } | null>;
}
// PASEO_AGENT_ID belongs to the daemon that launched this shell. Commands
// targeting another daemon (--host or --home) have no caller on that daemon.
export async function resolveCallerAgentId(
client: CallerLookupClient,
env: { PASEO_AGENT_ID?: string } = process.env,
): Promise<string | undefined> {
const agentId = env.PASEO_AGENT_ID?.trim();
if (!agentId) return undefined;
const caller = await client.fetchAgent({ agentId }).catch((error: unknown) => {
// A missing agent is a daemon answer; a lost or timed-out connection is not.
if (error instanceof DaemonConnectionError) throw error;
return null;
});
return caller?.agent.id === agentId ? agentId : undefined;
}
+8 -12
View File
@@ -53,12 +53,8 @@ try {
console.log("Test 1: run --help shows options");
const result = await $`npx paseo run --help`.nothrow();
assert.strictEqual(result.exitCode, 0, "run --help should exit 0");
assert(result.stdout.includes("--no-wait"), "help should mention --no-wait flag");
assert(
!result.stdout.includes("--internal"),
"help should not mention removed --internal flag",
);
assert(!result.stdout.includes("--background"), "help should hide legacy --background syntax");
assert(result.stdout.includes("-d"), "help should mention -d flag");
assert(result.stdout.includes("--background"), "help should mention --background flag");
assert(!result.stdout.includes("--detach"), "help should hide legacy --detach syntax");
assert(result.stdout.includes("--title"), "help should mention --title option");
assert(result.stdout.includes("--provider"), "help should mention --provider option");
@@ -182,18 +178,18 @@ try {
console.log("✓ run --output-schema flag is accepted\n");
}
// Test 10: run --output-schema cannot be used with --no-wait
// Test 10: run --output-schema cannot be used with --background
{
console.log("Test 10: run --output-schema cannot be used with --no-wait");
console.log("Test 10: run --output-schema cannot be used with --background");
const result =
await $`PASEO_HOME=${paseoHome} npx paseo --host localhost:${port} run --no-wait --output-schema ${schemaPath} "test prompt"`.nothrow();
assert.notStrictEqual(result.exitCode, 0, "should fail with --no-wait and --output-schema");
await $`PASEO_HOME=${paseoHome} npx paseo --host localhost:${port} run --background --output-schema ${schemaPath} "test prompt"`.nothrow();
assert.notStrictEqual(result.exitCode, 0, "should fail with --background and --output-schema");
const output = result.stdout + result.stderr;
assert(
output.includes("--output-schema cannot be used with --no-wait"),
output.includes("--output-schema cannot be used with --background"),
"error should explain background incompatibility",
);
console.log("✓ run --output-schema cannot be used with --no-wait\n");
console.log("✓ run --output-schema cannot be used with --background\n");
}
// Test 11: -q (quiet) flag is accepted with run
@@ -2,7 +2,6 @@
import assert from "node:assert";
import { basename } from "node:path";
import { createPaseoClient } from "@getpaseo/client";
import { createE2ETestContext } from "./helpers/test-daemon.ts";
console.log("=== Workspace Rename Command ===\n");
@@ -52,61 +51,8 @@ try {
)?.name,
basename(ctx.workDir),
);
await verifyWorkspaceCallerContext();
} finally {
await ctx.stop();
}
console.log("=== Workspace Rename Command Tests Passed ===");
async function verifyWorkspaceCallerContext() {
const sdk = createPaseoClient({ url: `${ctx.wsUrl}/ws`, reconnect: { enabled: false } });
try {
await sdk.connect();
const parentWorkspace = await sdk.workspaces.create({
source: { kind: "directory", path: ctx.workDir },
background: true,
});
// Creation without a prompt stays idle; this visibility test runs no provider turn.
const parent = await parentWorkspace.agents.create({ config: { provider: "claude/haiku" } });
const cases = [
{ caller: parent.id, background: undefined, expected: true },
{ caller: parent.id, background: false, expected: false },
{ caller: parent.id, background: true, expected: true },
{ caller: "foreign-or-missing-agent", background: undefined, expected: false },
{ caller: "foreign-or-missing-agent", background: true, expected: true },
{ caller: "foreign-or-missing-agent", background: false, expected: false },
{ caller: "", background: undefined, expected: false },
{ caller: "", background: true, expected: true },
];
for (const entry of cases) {
const result = await ctx.paseo(
[
"workspace",
"create",
"--host",
`127.0.0.1:${ctx.port}`,
"--isolation",
"local",
"--path",
ctx.workDir,
...(entry.background === undefined
? []
: [entry.background ? "--background" : "--no-background"]),
"--json",
],
{ env: { PASEO_AGENT_ID: entry.caller } },
);
assert.strictEqual(result.exitCode, 0, result.stderr);
assert.strictEqual(
JSON.parse(result.stdout).background,
entry.expected,
JSON.stringify(entry),
);
}
console.log("✓ workspace create caller inheritance, foreign/blank defaults, and overrides");
} finally {
await sdk.close();
}
}
-152
View File
@@ -1,152 +0,0 @@
#!/usr/bin/env npx tsx
import assert from "node:assert/strict";
import { mkdir, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { createE2ETestContext } from "./helpers/test-daemon.ts";
import { connectToDaemon } from "../src/utils/client.ts";
import { resolveCliVersion } from "../src/version.ts";
const context = await createE2ETestContext();
try {
const directory = join(context.workDir, "usage-plugin");
await mkdir(directory);
await writeFile(
join(directory, "paseo-plugin.json"),
JSON.stringify({
id: "cli-usage",
requirements: { paseo: `>=${resolveCliVersion()}` },
}),
);
await writeFile(
join(directory, "index.server.ts"),
`
import { z } from 'zod';
export default function contribute(server) {
const counts = new Map();
server.registerUsageSource({
id: 'cli-usage', label: 'CLI usage fixture', input: z.object({ key: z.string() }),
discover: async () => [
{ key: 'work.account', label: 'Work', input: { key: 'work' } },
{ key: 'personal', input: { key: 'personal' } },
{ key: 'broken', harness: 'Harness A', input: { key: 'rejected' } },
{ key: 'broken', harness: 'Harness B', input: { key: 'expired' } },
{ key: 'error', input: { key: 'error' } },
],
fetch: async ({key}) => {
counts.set(key, (counts.get(key) ?? 0) + 1);
if (key === 'rejected') return {status: 'unavailable', problem: {kind: 'rejected', status: 401, refreshedBy: 'codex login'}};
if (key === 'expired') return {status: 'unavailable', problem: {kind: 'expired', expiresAt: '2026-10-08T00:00:00Z', refreshedBy: 'claude'}};
if (key === 'error') throw new Error('Quota service failed');
return { status: 'available', planLabel: 'Pro', windows: [
{ id: 'session', label: 'Session', usedPct: counts.get(key), remainingPct: 99, resetsAt: '2026-10-09T17:00:00Z', runsOutAt: '2026-10-09T16:00:00Z', shortfallPct: 4.25 },
{ id: 'weekly', label: 'Weekly', usedPct: null, remainingPct: 0 },
], balances: [
{ id: 'credits', label: 'Credits', remaining: 2.5, unit: 'credits' },
{ id: 'tokens', label: 'Tokens', used: 0, limit: 100, unit: 'tokens' },
], details: [{ id: 'tier', label: 'Tier', value: 'Enterprise' }] };
},
});
return () => {};
}`,
);
const client = await connectToDaemon({ target: { kind: "instance", home: context.paseoHome } });
try {
await client.patchDaemonConfig({ pluginsEnabled: true });
await client.installDirectoryPlugin(directory, "cli-usage");
} finally {
await client.close();
}
async function ok(args: string[]) {
const result = await context.paseo(args);
assert.equal(result.exitCode, 0, result.stderr);
assert.equal(result.stderr, "");
return result.stdout;
}
// The first usage request is inspect: no earlier usage discovery has populated known IDs.
const cold = JSON.parse(await ok(["usage", "inspect", "cli-usage:work.account", "--json"]));
assert.equal(cold.id, "cli-usage:work.account");
assert.equal(cold.report.windows[0].usedPct, 1);
for (const args of [
["usage", "--agent", "agent-A", "inspect", cold.id, "--json"],
["usage", "inspect", cold.id, "--agent", "agent-A", "--json"],
]) {
const conflicting = await context.paseo(args);
assert.equal(conflicting.exitCode, 1, `Expected selector rejection: ${args.join(" ")}`);
assert.equal(conflicting.stdout, "");
assert.deepEqual(JSON.parse(conflicting.stderr).error, {
code: "INVALID_OPTIONS",
message:
"--agent cannot be combined with usage inspect. Use usage ls --agent <id> for agent account usage, or usage inspect <report-id> for an exact report.",
});
}
const list = JSON.parse(await ok(["usage", "ls", "--json"]));
const defaultList = JSON.parse(await ok(["usage", "--json"]));
assert.deepEqual(defaultList, list);
assert.deepEqual(list.map((entry: { id: string }) => entry.id).sort(), [
"cli-usage:broken",
"cli-usage:error",
"cli-usage:personal",
"cli-usage:work.account",
]);
const work = list.find((entry: { id: string }) => entry.id === cold.id);
assert.deepEqual(work, cold);
const table = await ok(["usage", "ls", "--no-color"]);
for (const text of [
"REPORT ID",
"Credits: - used, 2.5 remaining, - limit (credits)",
"Tokens: 0 used, - remaining, 100 limit (tokens)",
"Weekly: - used, 0% remaining",
"Harness A: Login rejected (HTTP 401). Run codex login",
"Harness B: Login expired at",
"Quota service failed",
])
assert.ok(table.includes(text), text);
const quiet = await ok(["usage", "ls", "--quiet"]);
assert.deepEqual(
quiet.trim().split("\n").sort(),
list.map((entry: { id: string }) => entry.id).sort(),
);
assert.ok(!(await ok(["usage", "ls", "--no-headers"])).includes("REPORT ID"));
const detail = await ok(["usage", "inspect", cold.id]);
for (const text of [
"Plan: Pro",
"Resets: 2026-10-09T17:00:00Z",
"Runs out: 2026-10-09T16:00:00Z",
"Shortfall: 4.25%",
"Tier: Enterprise",
])
assert.ok(detail.includes(text), text);
const refreshed = JSON.parse(await ok(["usage", "inspect", cold.id, "--refresh", "--json"]));
assert.equal(refreshed.report.windows[0].usedPct, 2);
const personal = JSON.parse(await ok(["usage", "inspect", "cli-usage:personal", "--json"]));
assert.equal(personal.report.windows[0].usedPct, 1);
const allRefreshed = JSON.parse(await ok(["usage", "ls", "--refresh", "--json"]));
assert.equal(
allRefreshed.find((entry: { id: string }) => entry.id === cold.id).report.windows[0].usedPct,
3,
);
for (const id of ["cli-usage:work", "missing"]) {
const unknown = await context.paseo(["usage", "inspect", id, "--json"]);
assert.equal(unknown.exitCode, 1);
assert.equal(unknown.stdout, "");
assert.equal(JSON.parse(unknown.stderr).error.code, "REPORT_NOT_FOUND");
}
const agentFailure = await context.paseo(["usage", "ls", "--agent", "missing-agent", "--json"]);
assert.equal(agentFailure.exitCode, 1);
assert.equal(agentFailure.stdout, "");
assert.match(JSON.parse(agentFailure.stderr).error.message, /Unknown agent/);
const remove = await context.paseo(["plugin", "remove", "cli-usage", "--json"]);
assert.equal(remove.exitCode, 0, remove.stderr);
assert.equal((await ok(["usage", "ls", "--json"])).trim(), "[]");
assert.equal((await ok(["usage"])).trim(), "No usage reports returned");
const connection = await context.paseo(["usage", "ls", "--host", "127.0.0.1:1", "--json"]);
assert.equal(connection.exitCode, 1);
assert.equal(connection.stdout, "");
assert.equal(JSON.parse(connection.stderr).error.code, "DAEMON_UNREACHABLE");
console.log(
"Usage CLI: cold inspect, default/ls, complete JSON, mixed statuses, all windows/balances, inspect details, refresh, IDs, errors and empty discovery passed.",
);
} finally {
await context.stop();
}
-202
View File
@@ -3100,162 +3100,6 @@ test("sends worktree target and autoArchive in create_agent_request", async () =
await expect(createPromise).rejects.toThrow("worktree auto archive sentinel");
});
test("sends internal in create_agent_request when the host advertises internal agents", async () => {
const logger = createMockLogger();
const mock = createMockTransport();
const client = new DaemonClient({
url: "ws://test",
clientId: "clsk_unit_test",
logger,
reconnect: { enabled: false },
transportFactory: () => mock.transport,
});
clients.push(client);
const connectPromise = client.connect();
mock.triggerOpen({ features: { backgroundWorkspaces: true } });
await connectPromise;
const createPromise = client.createAgent({
provider: "codex",
cwd: "/tmp/project",
background: true,
});
expect(mock.sent).toHaveLength(1);
const request = parseSentFrame(mock.sent[0]);
expect(request).toEqual(
expect.objectContaining({
type: "create_agent_request",
config: { provider: "codex", cwd: "/tmp/project" },
background: true,
}),
);
mock.triggerMessage(
wrapSessionMessage({
type: "status",
payload: {
status: "agent_create_failed",
requestId: request.requestId,
error: "internal agent sentinel",
},
}),
);
await expect(createPromise).rejects.toThrow("internal agent sentinel");
});
test("rejects an internal create before sending when the host predates internal agents", async () => {
const logger = createMockLogger();
const mock = createMockTransport();
const client = new DaemonClient({
url: "ws://test",
clientId: "clsk_unit_test",
logger,
reconnect: { enabled: false },
transportFactory: () => mock.transport,
});
clients.push(client);
const connectPromise = client.connect();
mock.triggerOpen({ features: {} });
await connectPromise;
await expect(
client.createAgent({ provider: "codex", cwd: "/tmp/project", background: true }),
).rejects.toThrow("Update the host to use background workspaces.");
expect(mock.sent).toHaveLength(0);
});
test("sends internal workspace creation and internal listings only to hosts that support them", async () => {
const logger = createMockLogger();
const mock = createMockTransport();
const client = new DaemonClient({
url: "ws://test",
clientId: "clsk_unit_test",
logger,
reconnect: { enabled: false },
transportFactory: () => mock.transport,
});
clients.push(client);
const connectPromise = client.connect();
// workspaceMultiplicity keeps the fetch on the real workspace directory RPC.
mock.triggerOpen({
features: { workspaceMultiplicity: true, backgroundWorkspaces: true },
});
await connectPromise;
void client
.createWorkspace({ source: { kind: "directory", path: "/tmp/project" }, background: true })
.catch(() => undefined);
void client.fetchWorkspaces({ filter: { includeBackground: true } }).catch(() => undefined);
void client.fetchAgents({ filter: { includeBackground: true } }).catch(() => undefined);
expect(mock.sent.map((frame) => parseSentFrame(frame))).toEqual(
expect.arrayContaining([
expect.objectContaining({ type: "workspace.create.request", background: true }),
expect.objectContaining({
type: "fetch_workspaces_request",
filter: { includeBackground: true },
}),
expect.objectContaining({
type: "fetch_agents_request",
filter: { includeBackground: true },
}),
]),
);
});
test("rejects internal workspace creation and internal listings before sending on older hosts", async () => {
const logger = createMockLogger();
const mock = createMockTransport();
const client = new DaemonClient({
url: "ws://test",
clientId: "clsk_unit_test",
logger,
reconnect: { enabled: false },
transportFactory: () => mock.transport,
});
clients.push(client);
const connectPromise = client.connect();
mock.triggerOpen({ features: {} });
await connectPromise;
await expect(
client.createWorkspace({
source: { kind: "directory", path: "/tmp/project" },
background: true,
}),
).rejects.toThrow("Update the host to use background workspaces.");
await expect(client.fetchWorkspaces({ filter: { includeBackground: true } })).rejects.toThrow(
"Update the host to use background workspaces.",
);
expect(mock.sent).toHaveLength(0);
// Agent listings gate on the older internalAgents feature.
const olderMock = createMockTransport();
const olderClient = new DaemonClient({
url: "ws://test",
clientId: "clsk_unit_test",
logger,
reconnect: { enabled: false },
transportFactory: () => olderMock.transport,
});
clients.push(olderClient);
const olderConnect = olderClient.connect();
olderMock.triggerOpen({ features: {} });
await olderConnect;
await expect(olderClient.fetchAgents({ filter: { includeBackground: true } })).rejects.toThrow(
"Update the host to use background workspaces.",
);
expect(olderMock.sent).toHaveLength(0);
});
test("sends structured attachments with create_agent_request", async () => {
const logger = createMockLogger();
const mock = createMockTransport();
@@ -7481,49 +7325,3 @@ test("usage request timeout detaches its update listener", async () => {
vi.useRealTimers();
}
});
test.each([false, true])(
"agent provenance requires host support=%s while human sends remain compatible",
async (supported) => {
const transport = createMockTransport();
const client = new DaemonClient({
url: "ws://test",
clientId: "provenance",
transportFactory: () => transport.transport,
reconnect: { enabled: false },
});
clients.push(client);
const connecting = client.connect();
transport.triggerOpen({ features: { agentMessageProvenance: supported } });
await connecting;
if (!supported) {
await expect(
client.sendAgentMessage("recipient", "review", { sourceAgentId: "server::sender" }),
).rejects.toThrow("Update the Paseo host");
expect(transport.sent).toHaveLength(0);
}
const send = client.sendAgentMessage("recipient", "review", {
messageId: "delivery",
...(supported ? { sourceAgentId: "server::sender" } : {}),
});
const request = parseSentFrame(transport.sent[0]);
expect(request).toMatchObject({
type: "send_agent_message_request",
text: "review",
messageId: "delivery",
});
expect(request.sourceAgentId).toBe(supported ? "server::sender" : undefined);
transport.triggerMessage(
wrapSessionMessage({
type: "send_agent_message_response",
payload: {
requestId: request.requestId,
agentId: "recipient",
accepted: true,
error: null,
},
}),
);
await send;
},
);
+15 -61
View File
@@ -424,7 +424,6 @@ export interface DaemonClientTrace {
}
export interface SendMessageOptions {
sourceAgentId?: string;
messageId?: string;
/** What happens when the agent is mid-turn. The daemon interrupts the turn when omitted. */
activeTurnBehavior?: ActiveTurnBehavior;
@@ -460,7 +459,6 @@ export interface CreateAgentRequestOptions extends AgentConfigOverrides {
git?: GitSetupOptions;
worktree?: CreateAgentRequestMessage["worktree"];
autoArchive?: CreateAgentRequestMessage["autoArchive"];
background?: CreateAgentRequestMessage["background"];
// COMPAT(createAgentWorktree): low-level old callers may still send the
// create-agent worktree field. Added in v0.2.0; remove after 2027-01-17.
worktreeName?: string;
@@ -471,9 +469,6 @@ export interface CreateAgentRequestOptions extends AgentConfigOverrides {
export interface CreateWorkspaceRequestOptions {
source: WorkspaceCreateRequest["source"];
title?: string;
/** Workspace discovery visibility; contents retain normal durability. */
background?: boolean;
callerAgentId?: string;
idempotencyKey?: string;
workspaceId?: string;
agent?: Omit<
@@ -1200,25 +1195,6 @@ export function supportsUsageReports(features: ServerInfoStatusPayload["features
return features?.usageSources === true || features?.providerUsageList === true;
}
function buildFetchAgentsRequest(
options: FetchAgentsOptions | undefined,
requestId: string,
): SessionInboundMessage {
return SessionInboundMessageSchema.parse({
type: "fetch_agents_request",
requestId,
...(options?.scope ? { scope: options.scope } : {}),
...(options?.filter ? { filter: options.filter } : {}),
...(options?.sort ? { sort: options.sort } : {}),
...(options?.page ? { page: options.page } : {}),
...(options?.subscribe ? { subscribe: options.subscribe } : {}),
...(options?.sync ? { sync: options.sync } : {}),
...(options?.includeBackground !== undefined
? { includeBackground: options.includeBackground }
: {}),
});
}
export class DaemonClient {
private readonly providerSnapshotUpdates = new ProviderSnapshotUpdates({
active: (message) => this.owned.owns(message),
@@ -2365,8 +2341,6 @@ export class DaemonClient {
observeAgents(
options: Omit<FetchAgentsOptions, "subscribe"> = {},
): OwnedSubscription<FetchAgentsPayload> {
if (options.includeBackground || options.filter?.includeBackground)
this.requireBackgroundWorkspaces();
const { signal, requestId, timeout, ...query } = options;
return this.observe(
"fetch_agents_response",
@@ -2378,8 +2352,6 @@ export class DaemonClient {
observeWorkspaces(
options: Omit<FetchWorkspacesOptions, "subscribe"> = {},
): OwnedSubscription<FetchWorkspacesPayload> {
if (options.includeBackground || options.filter?.includeBackground)
this.requireBackgroundWorkspaces();
const { signal, requestId, ...query } = options;
return this.observe(
"fetch_workspaces_response",
@@ -2395,8 +2367,6 @@ export class DaemonClient {
async fetchAgents(
options?: FetchAgentsOptions,
): Promise<FetchAgentsPayload & { subscription?: OwnedSubscription<FetchAgentsPayload> }> {
if (options?.includeBackground || options?.filter?.includeBackground)
this.requireBackgroundWorkspaces();
if (options?.subscribe) {
if (options.subscribe.subscriptionId !== undefined)
throw new Error("Subscription IDs are assigned by the host");
@@ -2404,7 +2374,16 @@ export class DaemonClient {
return { ...(await subscription.ready), subscription };
}
const resolvedRequestId = this.createRequestId(options?.requestId);
const message = buildFetchAgentsRequest(options, resolvedRequestId);
const message = SessionInboundMessageSchema.parse({
type: "fetch_agents_request",
requestId: resolvedRequestId,
...(options?.scope ? { scope: options.scope } : {}),
...(options?.filter ? { filter: options.filter } : {}),
...(options?.sort ? { sort: options.sort } : {}),
...(options?.page ? { page: options.page } : {}),
...(options?.subscribe ? { subscribe: options.subscribe } : {}),
...(options?.sync ? { sync: options.sync } : {}),
});
return this.sendRequest({
requestId: resolvedRequestId,
message,
@@ -2423,7 +2402,6 @@ export class DaemonClient {
}
async fetchAgentHistory(options?: FetchAgentHistoryOptions): Promise<FetchAgentHistoryPayload> {
if (options?.filter?.includeBackground) this.requireBackgroundWorkspaces();
const resolvedRequestId = this.createRequestId(options?.requestId);
const message = SessionInboundMessageSchema.parse({
type: "fetch_agent_history_request",
@@ -2487,8 +2465,6 @@ export class DaemonClient {
): Promise<
FetchWorkspacesPayload & { subscription?: OwnedSubscription<FetchWorkspacesPayload> }
> {
if (options?.includeBackground || options?.filter?.includeBackground)
this.requireBackgroundWorkspaces();
if (options?.subscribe) {
if (options.subscribe.subscriptionId !== undefined)
throw new Error("Subscription IDs are assigned by the host");
@@ -2498,8 +2474,12 @@ export class DaemonClient {
const resolvedRequestId = this.createRequestId(options?.requestId);
const message = SessionInboundMessageSchema.parse({
type: "fetch_workspaces_request",
...options,
requestId: resolvedRequestId,
...(options?.filter ? { filter: options.filter } : {}),
...(options?.sort ? { sort: options.sort } : {}),
...(options?.page ? { page: options.page } : {}),
...(options?.subscribe ? { subscribe: options.subscribe } : {}),
...(options?.sync ? { sync: options.sync } : {}),
});
return this.sendRequest({
requestId: resolvedRequestId,
@@ -2872,19 +2852,7 @@ export class DaemonClient {
legacyWorkspace: (input) => this.createLegacyWorkspace(input, input.requestId),
});
// Background workspaces are gated once at the transport boundary.
private requireBackgroundWorkspaces(): void {
if (this.lastServerInfoMessage?.features?.backgroundWorkspaces !== true) {
throw new Error("Update the host to use background workspaces.");
}
}
supportsBackgroundWorkspaces(): boolean {
return this.lastServerInfoMessage?.features?.backgroundWorkspaces === true;
}
async createAgent(options: CreateAgentRequestOptions): Promise<AgentSnapshotPayload> {
if (options.background !== undefined) this.requireBackgroundWorkspaces();
const result = await this.creations.createAgent({
...options,
config: resolveAgentConfig(options),
@@ -2917,7 +2885,6 @@ export class DaemonClient {
...(options.git ? { git: options.git } : {}),
...(options.worktree ? { worktree: options.worktree } : {}),
...(options.autoArchive !== undefined ? { autoArchive: options.autoArchive } : {}),
...(options.background !== undefined ? { background: options.background } : {}),
...(options.worktreeName ? { worktreeName: options.worktreeName } : {}),
...(options.labels && Object.keys(options.labels).length > 0
? { labels: options.labels }
@@ -3480,12 +3447,6 @@ export class DaemonClient {
text: string,
options?: SendMessageOptions,
): Promise<void> {
if (
options?.sourceAgentId &&
this.lastServerInfoMessage?.features?.agentMessageProvenance !== true
) {
throw new Error("Update the Paseo host to send messages with agent provenance.");
}
const requestId = this.createRequestId();
const messageId = options?.messageId ?? crypto.randomUUID();
const message = SessionInboundMessageSchema.parse({
@@ -3493,7 +3454,6 @@ export class DaemonClient {
requestId,
agentId,
text,
sourceAgentId: options?.sourceAgentId,
...(messageId ? { messageId } : {}),
...(options?.activeTurnBehavior ? { activeTurnBehavior: options.activeTurnBehavior } : {}),
...(options?.images ? { images: options.images } : {}),
@@ -4592,9 +4552,6 @@ export class DaemonClient {
requestId?: string,
): Promise<WorkspaceCreatePayload> {
const resolvedRequestId = this.createRequestId(requestId ?? input.requestId);
if (input.background !== undefined || input.callerAgentId) this.requireBackgroundWorkspaces();
if (input.agent?.background !== undefined)
throw new Error("Configure background on the workspace, not its initial agent.");
const result = await this.creations.createWorkspace({
...input,
requestId: resolvedRequestId,
@@ -4626,8 +4583,6 @@ export class DaemonClient {
? { idempotencyKey: input.idempotencyKey }
: {}),
...(input.title !== undefined ? { title: input.title } : {}),
...(input.background !== undefined ? { background: input.background } : {}),
...(input.callerAgentId ? { callerAgentId: input.callerAgentId } : {}),
...(input.firstAgentContext !== undefined
? { firstAgentContext: input.firstAgentContext }
: {}),
@@ -6977,7 +6932,6 @@ function resolveAgentConfig(options: CreateAgentRequestOptions): AgentSessionCon
attachments: _attachments,
worktree: _worktree,
autoArchive: _autoArchive,
background: _background,
env: _env,
workspaceId: _workspaceId,
initialPrompt: _initialPrompt,
-55
View File
@@ -691,61 +691,6 @@ test("plugin-shaped PR workspace create and agent create use the existing daemon
await client.close();
});
test("agents.create forwards internal on the request, outside the agent config", async () => {
const { client, ws } = await connectClient({
providerUsageList: true,
providersSnapshotCwd: true,
ownedSubscriptions: true,
backgroundWorkspaces: true,
});
const createPromise = client.agents.create({
config: { provider: "codex/gpt-5.4" },
cwd: "/repo/sdk",
title: "Summary helper",
background: true,
autoArchive: true,
});
const request = parseSentSessionMessage(ws.sent.at(-1));
expect(request).toMatchObject({
type: "create_agent_request",
config: { provider: "codex", model: "gpt-5.4", cwd: "/repo/sdk", title: "Summary helper" },
background: true,
autoArchive: true,
});
expect(request.config).not.toHaveProperty("internal");
ws.message(
sessionMessage({
type: "status",
payload: {
status: "agent_created",
requestId: request.requestId,
agentId: "agent_helper",
agent: createAgent({ id: "agent_helper" }),
},
}),
);
const agent = await createPromise;
expect(agent.id).toBe("agent_helper");
await client.close();
});
test("agents.create with internal fails before sending on a host without internal agents", async () => {
const { client, ws } = await connectClient();
const sentBefore = ws.sent.length;
await expect(
client.agents.create({
config: { provider: "codex/gpt-5.4" },
cwd: "/repo/sdk",
background: true,
}),
).rejects.toThrow("Update the host to use background workspaces.");
expect(ws.sent).toHaveLength(sentBefore);
await client.close();
});
test("agent handles delegate create, send, timeline refetch, archive, and local updates", async () => {
const { client, ws } = await connectClient();
const createdAgent = createAgent();
-5
View File
@@ -257,8 +257,6 @@ export interface PaseoAgentCreateOptions {
git?: CreateAgentRequestMessage["git"];
worktree?: CreateAgentRequestMessage["worktree"];
autoArchive?: CreateAgentRequestMessage["autoArchive"];
/** Visibility intent for a NEW workspace. Existing targets reject this option. */
background?: CreateAgentRequestMessage["background"];
requestId?: string;
labels?: Record<string, string>;
}
@@ -782,12 +780,9 @@ function createWorkspaceHandleFactory(
const refresh = async (options?: { requestId?: string }) => {
let cursor: string | undefined;
let requestId = options?.requestId;
// A ref addresses one workspace by id, so a background one resolves too.
const filter = daemonClient.supportsBackgroundWorkspaces() ? { includeBackground: true } : {};
do {
const result = await daemonClient.fetchWorkspaces({
requestId,
filter,
page: { limit: 200, ...(cursor ? { cursor } : {}) },
});
const match = result.entries.find((entry) => entry.id === id);
@@ -287,6 +287,7 @@ async function createCallerAgent(daemonPort, workspaceId = workspaceIds[0]) {
provider: "mock/ten-second-stream",
settings: { modeId: "load-test" },
initialPrompt: "Remain available while the browser bridge regression runs.",
background: true,
},
});
const result = response.structuredContent;
@@ -1,25 +0,0 @@
import type { AgentMessage } from "./agent-message.js";
import type { ToolCallDetail } from "./agent-types.js";
/** Presentation shared by clients; never used to encode provider prompts. */
export function buildAgentMessageDisplay(message: AgentMessage): {
displayName: string;
detail: ToolCallDetail;
} {
const sender = message.sender.title ?? message.sender.id;
const headings: Record<AgentMessage["event"], string> = {
message: `Message from ${sender}`,
finished: `${sender} finished`,
errored: `${sender} errored`,
"permission-required": `${sender} needs permission`,
closed: `${sender} closed`,
};
return {
displayName: headings[message.event],
detail: {
type: "plain_text",
icon: "bot",
text: `From agent: ${message.sender.id}\n\n${message.text}`,
},
};
}
-13
View File
@@ -1,13 +0,0 @@
import { z } from "zod";
/** Semantic provenance, independent of provider envelopes and timeline presentation. */
export const AgentMessageSchema = z.object({
event: z.enum(["message", "finished", "errored", "permission-required", "closed"]),
sender: z.object({
id: z.string().min(1),
title: z.string().min(1).optional(),
}),
text: z.string(),
});
export type AgentMessage = z.infer<typeof AgentMessageSchema>;
-2
View File
@@ -1,4 +1,3 @@
import type { AgentMessage } from "./agent-message.js";
import type { AgentAttachment } from "./messages.js";
export type AgentProvider = string;
@@ -312,7 +311,6 @@ export type ToolCallDetail =
};
interface ToolCallBase {
agentMessage?: AgentMessage;
[key: string]: unknown;
type: "tool_call";
callId: string;
@@ -1,51 +0,0 @@
import { describe, expect, test } from "vitest";
import { SessionInboundMessageSchema } from "./messages.js";
describe("create request internal field", () => {
test("accepts internal on create_agent_request", () => {
const parsed = SessionInboundMessageSchema.parse({
type: "create_agent_request",
requestId: "create-agent-internal",
config: {
provider: "codex",
cwd: "/repo/app",
},
internal: true,
});
expect(parsed).toEqual({
type: "create_agent_request",
requestId: "create-agent-internal",
config: {
provider: "codex",
cwd: "/repo/app",
},
internal: true,
labels: {},
});
});
test("accepts internal on agent.create.request", () => {
const parsed = SessionInboundMessageSchema.parse({
type: "agent.create.request",
requestId: "agent-create-internal",
config: {
provider: "codex",
cwd: "/repo/app",
},
internal: true,
});
expect(parsed).toEqual({
type: "agent.create.request",
requestId: "agent-create-internal",
config: {
provider: "codex",
cwd: "/repo/app",
},
internal: true,
labels: {},
});
});
});
-28
View File
@@ -1,6 +1,5 @@
import { describe, expect, test } from "vitest";
import {
AgentTimelineItemPayloadSchema,
FileExplorerRequestSchema,
PaseoWorktreeArchiveRequestSchema,
parseServerInfoStatusPayload,
@@ -521,30 +520,3 @@ describe("viewed timeline subscription messages", () => {
});
});
});
test("agent messages are an optional semantic payload on existing tool rows", () => {
const legacy = {
type: "tool_call",
callId: "delivery",
name: "agent_message",
status: "completed",
error: null,
detail: { type: "plain_text", text: "Done" },
};
const agentMessage = {
event: "finished",
sender: { id: "server::worker", title: "Reviewer" },
text: "Done",
};
expect(AgentTimelineItemPayloadSchema.parse(legacy)).toEqual(legacy);
expect(AgentTimelineItemPayloadSchema.parse({ ...legacy, agentMessage })).toEqual({
...legacy,
agentMessage,
});
expect(
AgentTimelineItemPayloadSchema.safeParse({
...legacy,
agentMessage: { ...agentMessage, sender: { id: 42 } },
}).success,
).toBe(false);
});
-34
View File
@@ -1,4 +1,3 @@
import { AgentMessageSchema } from "./agent-message.js";
import { PluginRegistryIdentitySchema } from "./plugin-registry.js";
import { AgentProfileSchema, AgentSkillSelectionSchema } from "./agent-profile.js";
export {
@@ -626,7 +625,6 @@ const ToolCallDetailPayloadSchema: z.ZodType<ToolCallDetail, unknown> = z.discri
);
const ToolCallBasePayloadSchema = z.object({
agentMessage: AgentMessageSchema.optional(),
type: z.literal("tool_call"),
callId: z.string(),
name: z.string(),
@@ -839,8 +837,6 @@ export const AgentSnapshotPayloadSchema = z.object({
attentionTimestamp: z.string().nullable().optional(),
archivedAt: z.string().nullable().optional(),
providerUnavailable: z.boolean().optional(),
// Private helper marker, retained for exact-ID snapshots and older wire messages.
internal: z.boolean().optional(),
});
export type AgentSnapshotPayload = z.infer<typeof AgentSnapshotPayloadSchema>;
@@ -912,9 +908,6 @@ const AgentDirectoryFilterSchema = z.object({
includeArchived: z.boolean().optional(),
requiresAttention: z.boolean().optional(),
thinkingOptionId: z.string().nullable().optional(),
// Retained for wire parsing; private helpers are excluded from public discovery.
includeInternal: z.boolean().optional(),
includeBackground: z.boolean().optional(),
});
export const DeleteAgentRequestMessageSchema = z.object({
@@ -1242,7 +1235,6 @@ export const FetchAgentsRequestMessageSchema = z.object({
type: z.literal("fetch_agents_request"),
requestId: z.string(),
scope: z.enum(["active"]).optional(),
includeBackground: z.boolean().optional(),
filter: AgentDirectoryFilterSchema.optional(),
sort: z
.array(
@@ -1276,7 +1268,6 @@ const WorkspaceStateBucketSchema = z.enum([
]);
export const FetchWorkspacesRequestMessageSchema = z.object({
includeBackground: z.boolean().optional(),
type: z.literal("fetch_workspaces_request"),
requestId: z.string(),
filter: z
@@ -1285,9 +1276,6 @@ export const FetchWorkspacesRequestMessageSchema = z.object({
projectId: z.string().optional(),
// Unused: accepted so older clients still parse, but the server does not filter on it.
idPrefix: z.string().optional(),
// Retained for wire parsing of older requests.
includeInternal: z.boolean().optional(),
includeBackground: z.boolean().optional(),
})
.optional(),
sort: z
@@ -1366,8 +1354,6 @@ export const SendAgentMessageRequestSchema = z.object({
/** Accepts full ID, unique prefix, or exact full title (server resolves). */
agentId: z.string(),
text: z.string(),
/** Opaque sender identity for agent-originated prompts. */
sourceAgentId: z.string().min(1).optional(),
messageId: z.string().optional(), // Client-provided ID for deduplication
activeTurnBehavior: ActiveTurnBehaviorSchema.optional(),
images: z.array(ImageAttachmentSchema).optional(),
@@ -1724,13 +1710,6 @@ export const CreateAgentRequestMessageSchema = z.object({
git: GitSetupOptionsSchema.optional(),
worktree: CreateAgentWorktreeTargetSchema.optional(),
autoArchive: z.boolean().optional(),
// An ephemeral helper: the daemon never persists, lists, flags or announces
// it, and plugin lifecycle hooks skip it. Lives on the request rather than
// in the config schema, which is reused for updates. Retained for wire parsing;
// public internal creation is no longer supported.
internal: z.boolean().optional(),
// Workspace creation intent, rejected when selecting an existing workspace.
background: z.boolean().optional(),
labels: z.record(z.string(), z.string()).default({}),
requestId: z.string(),
});
@@ -2650,10 +2629,6 @@ export const WorkspaceCreateRequestSchema = z.object({
title: z.string().optional(),
// Optional prompt context for workspace-level name/branch generation.
firstAgentContext: FirstAgentContextSchema.optional(),
// Retained for wire parsing; public internal creation is no longer supported.
internal: z.boolean().optional(),
background: z.boolean().optional(),
callerAgentId: z.string().optional(),
source: z.discriminatedUnion("kind", [
z.object({
kind: z.literal("directory"),
@@ -3579,11 +3554,6 @@ export const ServerInfoStatusPayloadSchema = z
creationLifecycle: z.boolean().optional(),
// COMPAT(hubAgentRpc): added in v0.8.0; remove gate after 2027-03-05.
hubAgentRpc: z.boolean().optional(),
// COMPAT(internalAgents): added in v0.9.0; remove gate after 2027-03-17.
internalAgents: z.boolean().optional(),
// COMPAT(internalWorkspaces): added in v0.9.0; remove gate after 2027-03-17.
internalWorkspaces: z.boolean().optional(),
backgroundWorkspaces: z.boolean().optional(),
providersSnapshot: z.boolean().optional(),
usageSources: z.boolean().optional(),
// COMPAT(providersSnapshotCwd): added in v0.3.2, remove gate after 2027-02-10.
@@ -3725,7 +3695,6 @@ export const ServerInfoStatusPayloadSchema = z
ownedSubscriptions: z.boolean().optional(),
// COMPAT(canonicalSubmittedPrompts): added in v0.2.6, remove gate after 2027-01-30.
canonicalSubmittedPrompts: z.boolean().optional(),
agentMessageProvenance: z.boolean().optional(),
// COMPAT(agentTurnIdentity): accept peers that observed pre-release v0.2.6 through 2027-01-31.
agentTurnIdentity: z.boolean().optional(),
// COMPAT(stableProjectIdentity): added in v0.1.109, remove gate after 2027-01-15.
@@ -4050,9 +4019,6 @@ export const WorkspaceDescriptorPayloadSchema = z
pinnedAt: z.string().nullable().optional(),
// COMPAT(workspaceLabels): added in v0.5.0, remove optional after 2027-08-14.
labels: z.array(z.string()).optional(),
// Retained for wire parsing of older daemon descriptors.
internal: z.boolean().optional(),
background: z.boolean().optional(),
archivingAt: z.string().nullable().optional().default(null),
status: WorkspaceStateBucketSchema,
// Best-effort workspace status entry timestamp. Old daemons omit the

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