Compare commits

...
Author SHA1 Message Date
paseo-bot[bot] 744878bf62 refactor(agents): name finish notification options 2026-10-13 13:26:03 +02:00
paseo-bot[bot] e1ce819d11 fix(agents): retain complete failure outcomes through delivery
Capture the failure reason when the terminal notification is queued, preserve provider diagnostics at their producer, and apply the existing notification text budget. Failed responses also keep their completion timing when their footer is anchored to error activity.
2026-10-13 13:20:08 +02:00
paseo-bot[bot] 6d7aaf5461 test(app): distinguish timeline errors from submission failures
A rejected prompt displays its reason in both the submission status and the timeline. Scope the timeline assertions to the notification row.
2026-10-13 13:05:09 +02:00
paseo-bot[bot] 9e596e3377 fix(agents): preserve failure reasons and failed-turn forking
Typed failure activity no longer appears in assistant replies. Attach the response footer to the error cursor and read lastError for failed schedules and child notifications so those consumers retain their behavior.
2026-10-13 12:59:06 +02:00
paseo-bot[bot] e5efa7324d test(server): expect failure activity during agent creation
Verify fetched and live creation timelines use the typed error item when an initial provider prompt is rejected.
2026-10-13 05:03:13 +02:00
paseo-bot[bot]andAndonis 303ee418cc test(server): verify failure activity on current timeline paths
Keep daemon failures separate from preceding assistant output and verify live error delivery, including assistant text that resembles the legacy error marker. Update startup failure and successful session-replacement assertions for typed errors.

Co-authored-by: Andonis <qq3290949433@gmail.com>
2026-10-13 04:57:22 +02:00
paseo-bot[bot] b282bbb944 Merge remote-tracking branch 'origin/main' into bot/fix-4262-131bae8c 2026-10-13 04:53:51 +02:00
paseo-bot[bot]andMarcelo Barbosa b0f054de90 Reach IPv6-only workspace services through their proxy URLs (#6753)
* fix(server): reach IPv6-only workspace services

Workspace service forwarding and health probes forced IPv4 loopback,
returning 502 and unhealthy for a reachable IPv6-only service. Select
between both literal loopback addresses for HTTP, upgrades, and probes,
without relying on the system's localhost DNS entries.

Co-authored-by: Marcelo Barbosa <celocb@gmail.com>

* test(server): keep proxy POST mechanics in a helper

---------

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
Co-authored-by: Marcelo Barbosa <celocb@gmail.com>
2026-10-13 03:57:12 +02:00
CtrlCreeper e8108d9092 fix(app): only offer Remove for providers defined in config.json (#6568)
* fix(app): only offer Remove for providers defined in config.json

Plugin-registered providers (Antigravity, Muse Code) share source: "custom"
with config-defined ones, so Settings → Providers offered Remove on them.
The removeProviders patch only deletes config.json entries, so the action
succeeded silently while the plugin re-registered the provider.

Gate the Remove menu on the provider having an extends entry in config —
the actual definition custom providers live behind. Plugin providers keep
their enable/disable switch.

Fixes #6349

* Address review: named ownership check, E2E coverage for plugin providers

- Name the config-owned provider check instead of combining three
  conditions inline in canRemove.
- Replace the JSDOM component tests with a Playwright case in the
  existing provider-removal suite: a plugin-registered provider renders
  without the Remove action and survives a removeProviders patch.
2026-10-13 02:59:26 +02:00
paseo-bot[bot]andOuyang Xingyuan 9eaf7ad0c1 Render local images in Markdown file previews (#6750)
* fix(app): render local relative images in markdown file preview

File preview dropped relative images because it only accepted http/data URIs and never resolved paths against the opened markdown file.

* test(app): cover local relative images in markdown preview e2e

* fix(app): show local images in Markdown file previews

Carry forward document-relative image loading and preserve the host home
directory when resolving images beside home-relative Markdown files.
Decode file URIs once, and require decoded images in the file-pane regression.

Co-authored-by: Ouyang Xingyuan <galaxyroaming@qq.com>

* fix(app): resolve local Markdown image URL suffixes

---------

Co-authored-by: Ouyang Xingyuan <galaxyroaming@qq.com>
Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-10-13 01:51:07 +02:00
paseo-bot[bot] be0acb2935 fix(app): keep Diff updates alive after the first edit (#6745)
Hidden retained panels overwrite shared query metadata when a clean checkout becomes dirty. Resolve subscription demand from attached observers so a hidden panel cannot cancel the visible Diff tab.

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-10-13 00:53:44 +02:00
Andonis 3e977b5e7b fix(server): keep system errors separate from replies 2026-09-03 15:56:42 +08:00
40 changed files with 1449 additions and 174 deletions
+3
View File
@@ -93,3 +93,6 @@ app.json
# Heap snapshots dumped by --heapsnapshot-near-heap-limit; keep them for debugging.
*.heapsnapshot
# Project-local Serena configuration and memories.
.serena/
+1 -1
View File
@@ -4,7 +4,7 @@ Paseo proxies HTTP traffic to services running inside your workspaces. Localhost
## How it works
When a `paseo.json` script of `"type": "service"` starts, Paseo assigns it a local port and registers a route in the service proxy. Incoming requests whose `Host` header matches the script's generated hostname are forwarded to that port.
When a `paseo.json` script of `"type": "service"` starts, Paseo assigns it a local port and registers a route in the service proxy. Incoming requests whose `Host` header matches the script's generated hostname are forwarded to that port. HTTP requests, WebSocket upgrades, and service health checks select the reachable IPv4 or IPv6 loopback address. Services can bind to `127.0.0.1` or `::1` without changing their proxy URL.
The generated hostname is built from the script name, branch, and project:
@@ -303,10 +303,12 @@ async function retryRestoredSubmission(page: Page, prompt: string): Promise<void
}
async function expectRejectedPromptBeforeError(page: Page, prompt: string, errorMessage: string) {
const messages = page.getByTestId("user-message").or(page.getByTestId("assistant-message"));
const messages = page
.getByTestId("user-message")
.or(page.getByTestId("timeline-notification").filter({ hasText: errorMessage }));
await expect(messages).toHaveCount(2);
await expect(messages.nth(0)).toContainText(prompt);
await expect(messages.nth(1)).toContainText(`[System Error] ${errorMessage}`);
await expect(messages.nth(1)).toHaveText(errorMessage);
}
async function configureSteerInSettings(page: Page): Promise<void> {
@@ -51,7 +51,7 @@ test.describe("Assistant fork menu", () => {
await openAgentRoute(page, session);
await expectComposerVisible(page);
await submitMessage(page, "Emit a synthetic turn failure.");
await expect(page.getByText("[System Error] Requested mock provider failure")).toBeVisible({
await expect(page.getByText("Requested mock provider failure")).toBeVisible({
timeout: 30_000,
});
@@ -0,0 +1,122 @@
import { appendFile } from "node:fs/promises";
import path from "node:path";
import type { Page } from "@playwright/test";
import { test, expect } from "../support/fixtures";
import { openChangesTreePanel } from "../support/helpers/workspace-tabs";
function changesTree(page: Page) {
return page.getByTestId("changes-tree-panel").filter({ visible: true });
}
async function expectEmptyChanges(page: Page) {
await expect(changesTree(page).getByText("No changes to display", { exact: true })).toBeVisible();
}
async function editReadme(repoPath: string, text: string) {
await appendFile(path.join(repoPath, "README.md"), text);
}
async function expectReadmeChanges(page: Page, additions: number) {
await expect(changesTree(page).getByText("README.md", { exact: true })).toBeVisible({
timeout: 30_000,
});
await expect(changesTree(page)).toContainText(`+${additions}`);
}
async function openEmptyDiff(page: Page) {
await changesTree(page).getByTestId("changes-options-menu").click();
await page.getByTestId("changes-open-tab").click();
await expect(
page
.getByTestId("working-diff-panel")
.filter({ visible: true })
.getByText("No changes to display", { exact: true }),
).toBeVisible();
}
async function expectReadmeDiff(page: Page, additions: number) {
await expect(
page.getByTestId("working-diff-panel").filter({ visible: true }).getByTestId("diff-file-0"),
).toHaveAccessibleName(`README.md, +${additions}, -0`, { timeout: 30_000 });
}
async function openDiffFromNewTabMenu(page: Page) {
await page.getByTestId("workspace-new-tab-button").filter({ visible: true }).first().click();
await page.getByTestId("workspace-new-tab-menu-diff").filter({ visible: true }).first().click();
await expect(
page
.getByTestId("working-diff-panel")
.filter({ visible: true })
.getByText("No changes to display", { exact: true }),
).toBeVisible();
}
async function refreshDiff(page: Page) {
await page
.getByTestId("working-diff-panel")
.filter({ visible: true })
.getByTestId("changes-refresh")
.click();
}
async function reloadWorkspace(page: Page) {
await page.reload();
}
test("Changes follows the first edit to a clean workspace without reloading", async ({
page,
withWorkspace,
}) => {
const workspace = await withWorkspace();
await page.setViewportSize({ width: 1400, height: 900 });
await workspace.navigateTo();
await openChangesTreePanel(page);
await expectEmptyChanges(page);
await editReadme(workspace.repoPath, "first edit\n");
await expectReadmeChanges(page, 1);
await editReadme(workspace.repoPath, "second edit\n");
await expectReadmeChanges(page, 2);
});
test("the full diff follows the first edit to a clean workspace without reloading", async ({
page,
withWorkspace,
}) => {
const workspace = await withWorkspace();
await page.setViewportSize({ width: 1400, height: 900 });
await workspace.navigateTo();
await openChangesTreePanel(page);
await expectEmptyChanges(page);
await openEmptyDiff(page);
await editReadme(workspace.repoPath, "first edit\n");
await expectReadmeDiff(page, 1);
await editReadme(workspace.repoPath, "second edit\n");
await expectReadmeDiff(page, 2);
});
test("a directly opened Diff tab follows the first edit without an active Changes tree", async ({
page,
withWorkspace,
}) => {
const workspace = await withWorkspace();
await page.setViewportSize({ width: 1400, height: 900 });
await workspace.navigateTo();
await openDiffFromNewTabMenu(page);
await editReadme(workspace.repoPath, "first edit\n");
await expectReadmeDiff(page, 1);
await editReadme(workspace.repoPath, "second edit\n");
await expectReadmeDiff(page, 2);
await refreshDiff(page);
await expectReadmeDiff(page, 2);
await reloadWorkspace(page);
await expectReadmeDiff(page, 2);
await editReadme(workspace.repoPath, "third edit\n");
await expectReadmeDiff(page, 3);
});
@@ -2,6 +2,7 @@ import { mkdir, readFile, writeFile } from "node:fs/promises";
import path from "node:path";
import { expect, test, type Page } from "../support/fixtures";
import {
expandFolder,
openFileExplorer,
openFileFromExplorer,
expectFileTabOpen,
@@ -70,6 +71,14 @@ async function selectFileView(page: Page, view: "Preview" | "Source"): Promise<v
await expect(option).toHaveAttribute("aria-selected", "true");
}
async function expectMarkdownImageLoaded(page: Page, name: string): Promise<void> {
const image = page.getByRole("img", { name, exact: true });
await expect(image).toBeVisible();
await expect
.poll(() => image.locator("img").evaluate((element: HTMLImageElement) => element.naturalWidth))
.toBeGreaterThan(0);
}
function watchRequestsTo(page: Page, origin: string): string[] {
const requests: string[] = [];
page.on("request", (request) => {
@@ -684,6 +693,40 @@ test.describe("CodeMirror workspace file editing", () => {
await expect.poll(() => image.getAttribute("src")).not.toBe(initialSource);
});
test("renders local relative images inside Markdown preview", async ({ page, withWorkspace }) => {
test.setTimeout(90_000);
const workspace = await withWorkspace({ prefix: "file-md-relative-image-" });
await mkdir(path.join(workspace.repoPath, "docs"), { recursive: true });
await mkdir(path.join(workspace.repoPath, "data", "cache"), { recursive: true });
await writeFile(path.join(workspace.repoPath, "docs", "sibling.png"), RED_PIXEL);
await writeFile(path.join(workspace.repoPath, "data", "cache", "hero.png"), RED_PIXEL);
await writeFile(
path.join(workspace.repoPath, "docs", "guide.md"),
[
"# Guide",
"",
"![sibling](./sibling.png)",
"",
"![hero](../data/cache/hero.png?v=2#preview)",
"",
].join("\n"),
"utf8",
);
await workspace.navigateTo();
await openFileExplorer(page);
await expandFolder(page, "docs");
await openFileFromExplorer(page, "guide.md");
await expectFileTabOpen(page, "docs/guide.md");
const visibleFilePane = page.getByTestId("workspace-file-pane").filter({ visible: true });
await expect(visibleFilePane.getByText("Guide", { exact: true })).toBeVisible();
await expectMarkdownImageLoaded(page, "sibling");
await expectMarkdownImageLoaded(page, "hero");
await visibleFilePane.screenshot({
path: test.info().outputPath("markdown-relative-images.png"),
});
});
test("previews and refreshes an HTML plan while preserving source access", async ({
page,
withWorkspace,
@@ -10,16 +10,29 @@ import {
openSettingsHost,
openSettingsHostSection,
} from "../support/helpers/settings";
import { copyPluginExample } from "../support/helpers/plugin-fixture";
const CUSTOM_PROVIDER = {
id: "junie",
name: "Junie",
} as const;
const PLUGIN_PROVIDER = {
id: "direct-example",
name: "Direct provider example",
pluginId: "provider-direct-example",
} as const;
interface ProviderRemovalDaemonClient {
connect(): Promise<void>;
close(): Promise<void>;
patchDaemonConfig(config: { removeProviders?: string[] }): Promise<unknown>;
getDaemonConfig(): Promise<{ config: { pluginsEnabled?: boolean } }>;
patchDaemonConfig(config: {
removeProviders?: string[];
pluginsEnabled?: boolean;
}): Promise<unknown>;
installDirectoryPlugin(path: string): Promise<unknown>;
removePlugin(pluginId: string): Promise<void>;
getProvidersSnapshot(): Promise<{
entries: Array<{ provider: string; source?: "builtin" | "custom" }>;
}>;
@@ -93,4 +106,45 @@ test.describe("provider removal", () => {
await client.close().catch(() => undefined);
}
});
test("does not offer Remove for a plugin-registered provider", async ({ page }) => {
test.setTimeout(120_000);
const client = await connectDaemonClient<ProviderRemovalDaemonClient>({
clientIdPrefix: "provider-removal-e2e",
});
const plugin = await copyPluginExample("provider-direct");
try {
const previous = await client.getDaemonConfig();
try {
await client.patchDaemonConfig({ pluginsEnabled: true });
await client.installDirectoryPlugin(plugin.directory);
await gotoAppShell(page);
await openSettings(page);
await openSettingsHost(page, getServerId());
await openSettingsHostSection(page, getServerId(), "providers");
const pluginProviderRow = page.getByRole("button", {
name: `${PLUGIN_PROVIDER.name} provider details`,
exact: true,
});
await expect(pluginProviderRow).toBeVisible();
await expect(page.getByTestId(`provider-actions-${PLUGIN_PROVIDER.id}`)).toHaveCount(0);
// The provider survives a removeProviders patch pointed at it: the
// plugin, not config.json, owns the definition.
await client.patchDaemonConfig({ removeProviders: [PLUGIN_PROVIDER.id] });
await expect(pluginProviderRow).toBeVisible();
} finally {
await client.removePlugin(PLUGIN_PROVIDER.pluginId).catch(() => undefined);
await client
.patchDaemonConfig({ pluginsEnabled: previous.config.pluginsEnabled })
.catch(() => undefined);
}
} finally {
await client.close().catch(() => undefined);
await plugin.cleanup();
}
});
});
+10 -8
View File
@@ -186,8 +186,9 @@ export async function createCreationScenario(page: Page) {
await requests.settled();
await expect(
page
.getByTestId("assistant-message")
.filter({ hasText: "[System Error] Requested mock prompt rejection", visible: true }),
.getByTestId("timeline-notification")
.filter({ hasText: "Requested mock prompt rejection" })
.filter({ visible: true }),
).toBeVisible();
await expect(
page
@@ -203,11 +204,15 @@ export async function createCreationScenario(page: Page) {
async expectPromptBeforeError(prompt: string) {
const messages = page
.getByTestId("user-message")
.or(page.getByTestId("assistant-message"))
.or(
page
.getByTestId("timeline-notification")
.filter({ hasText: "Requested mock prompt rejection" }),
)
.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)).toHaveText("Requested mock prompt rejection");
await expect(messages.nth(1)).toBeInViewport();
},
async reloadAgent() {
@@ -217,10 +222,7 @@ export async function createCreationScenario(page: Page) {
},
async expectAssistantReply() {
await expect(
page
.getByTestId("assistant-message")
.filter({ visible: true, hasNotText: "[System Error]" })
.first(),
page.getByTestId("assistant-message").filter({ visible: true }).first(),
).toBeVisible();
},
async expectStartupFailure() {
@@ -82,7 +82,7 @@ function layoutFor(input: { platform: "web" | "native"; isTurnActive: boolean })
isTurnActive: input.isTurnActive,
history: strategy.orderTail([userMessage("user"), assistant]),
liveHead: [],
timingByAssistantId: timingFor(assistant.id),
timingByResponseItemId: timingFor(assistant.id),
}),
};
}
@@ -126,7 +126,7 @@ describe("turn footer spacing", () => {
isTurnActive,
history: strategy.orderTail([userMessage("user"), first]),
liveHead: strategy.orderHead([last]),
timingByAssistantId: timingFor(last.id),
timingByResponseItemId: timingFor(last.id),
});
const firstLayout = layout.history.find((item) => item.item.id === first.id);
const lastLayout = layout.liveHead.find((item) => item.item.id === last.id);
+32 -3
View File
@@ -105,7 +105,7 @@ function layoutFor(input: {
strategy,
streamHead: input.head ?? [],
}),
timingByAssistantId: timingFor(...(input.timingIds ?? [])),
timingByResponseItemId: timingFor(...(input.timingIds ?? [])),
});
}
@@ -149,6 +149,35 @@ function findLayoutItem(layout: StreamLayout, id: string): StreamLayoutItem {
}
describe("layoutStream", () => {
it.each(["web", "android"] as const)(
"hosts failed response footers on the error row on %s",
(platform) => {
const error: StreamItem = {
kind: "notification",
sourceType: "error",
level: "error",
id: "error-1",
message: "Provider failed",
timestamp: timestamp(2),
timelineCursor: { epoch: "timeline-1", seq: 42 },
};
const user = userMessage("user-1", 1);
const latest = layoutFor({ platform, tail: [user, error] });
expect(latest.auxiliaryTurnFooter?.itemId).toBe(error.id);
const completed = layoutFor({
platform,
tail: [user, error, userMessage("user-2", 3)],
isTurnActive: true,
});
expect(findLayoutItem(completed, error.id).completedFooter?.itemId).toBe(error.id);
const afterReply = layoutFor({
platform,
tail: [user, assistantMessage("assistant-1", 2), error],
});
expect(afterReply.auxiliaryTurnFooter?.itemId).toBe(error.id);
},
);
it("places one response footer after an adjacent tagged tool-only turn", () => {
const priorAssistant = assistantMessage("prior", 1, undefined, "turn-1");
const nextTool = toolCall("next-tool", 2, "turn-2");
@@ -172,7 +201,7 @@ describe("layoutStream", () => {
isTurnActive: true,
history,
liveHead,
timingByAssistantId: timingFor(priorAssistant.id),
timingByResponseItemId: timingFor(priorAssistant.id),
});
liveHead[0] = { ...liveHead[0]!, turnId: "turn-2" };
@@ -181,7 +210,7 @@ describe("layoutStream", () => {
isTurnActive: true,
history,
liveHead,
timingByAssistantId: timingFor(priorAssistant.id),
timingByResponseItemId: timingFor(priorAssistant.id),
});
expect(footerOwners(first)).toEqual([]);
+28 -25
View File
@@ -39,13 +39,13 @@ export interface StreamLayoutInput {
isTurnActive: boolean;
history: StreamItem[];
liveHead: StreamItem[];
timingByAssistantId: Map<string, TurnTiming>;
timingByResponseItemId: Map<string, TurnTiming>;
}
interface LayoutSegmentInput {
strategy: StreamStrategy;
items: StreamItem[];
timingByAssistantId: Map<string, TurnTiming>;
timingByResponseItemId: Map<string, TurnTiming>;
auxiliaryTurnFooter: TurnFooterHost | null;
hasAuxiliaryFooter: boolean;
frameOrder: StreamFrameChildOrder;
@@ -57,8 +57,8 @@ interface LayoutSegmentInput {
phase: "streaming" | "complete";
}
interface AssistantFooterSource {
item: Extract<StreamItem, { kind: "assistant_message" }>;
interface ResponseFooterSource {
item: Extract<StreamItem, { kind: "assistant_message" | "notification" }>;
items: StreamItem[];
index: number;
}
@@ -67,23 +67,23 @@ function createTurnFooterHost(input: {
item: StreamItem;
items: StreamItem[];
index: number;
timingByAssistantId: Map<string, TurnTiming>;
timingByResponseItemId: Map<string, TurnTiming>;
}): TurnFooterHost {
return {
itemId: input.item.id,
items: input.items,
timing: input.timingByAssistantId.get(input.item.id),
timing: input.timingByResponseItemId.get(input.item.id),
startIndex: input.index,
};
}
function findLatestAssistantInResponse(input: {
function findLatestFooterSourceInResponse(input: {
strategy: StreamStrategy;
items: StreamItem[];
startIndex: number;
boundaryAboveItems?: StreamItem[] | null;
boundaryAboveIndex?: number | null;
}): AssistantFooterSource | null {
}): ResponseFooterSource | null {
let items = input.items;
let index = input.startIndex;
let canCrossBoundary = true;
@@ -99,7 +99,10 @@ function findLatestAssistantInResponse(input: {
if (!item || (laterItem && !continuesResponse(item, laterItem))) {
return null;
}
if (item.kind === "assistant_message") {
if (
item.kind === "assistant_message" ||
(item.kind === "notification" && item.sourceType === "error")
) {
return { item, items, index };
}
laterItem = item;
@@ -131,20 +134,20 @@ function resolveAuxiliaryTurnFooter(input: StreamLayoutInput): TurnFooterHost |
return null;
}
const assistant = findLatestAssistantInResponse({
const source = findLatestFooterSourceInResponse({
strategy: input.strategy,
items: footerItems,
startIndex: latestIndex,
});
if (!assistant) {
if (!source) {
return null;
}
return createTurnFooterHost({
item: assistant.item,
items: assistant.items,
index: assistant.index,
timingByAssistantId: input.timingByAssistantId,
item: source.item,
items: source.items,
index: source.index,
timingByResponseItemId: input.timingByResponseItemId,
});
}
@@ -154,7 +157,7 @@ function resolveCompletedFooter(input: {
index: number;
item: StreamItem;
belowItem: StreamItem | null;
timingByAssistantId: Map<string, TurnTiming>;
timingByResponseItemId: Map<string, TurnTiming>;
auxiliaryTurnFooter: TurnFooterHost | null;
boundaryAboveItems: StreamItem[] | null;
boundaryAboveIndex: number | null;
@@ -163,21 +166,21 @@ function resolveCompletedFooter(input: {
return null;
}
const assistant = findLatestAssistantInResponse({
const source = findLatestFooterSourceInResponse({
strategy: input.strategy,
items: input.items,
startIndex: input.index,
boundaryAboveItems: input.boundaryAboveItems,
boundaryAboveIndex: input.boundaryAboveIndex,
});
if (!assistant || input.auxiliaryTurnFooter?.itemId === assistant.item.id) {
if (!source || input.auxiliaryTurnFooter?.itemId === source.item.id) {
return null;
}
return createTurnFooterHost({
item: assistant.item,
items: assistant.items,
index: assistant.index,
timingByAssistantId: input.timingByAssistantId,
item: source.item,
items: source.items,
index: source.index,
timingByResponseItemId: input.timingByResponseItemId,
});
}
@@ -306,7 +309,7 @@ function layoutSegmentItem(
index,
item,
belowItem,
timingByAssistantId: input.timingByAssistantId,
timingByResponseItemId: input.timingByResponseItemId,
auxiliaryTurnFooter: input.auxiliaryTurnFooter,
boundaryAboveItems: input.boundaryAboveItems,
boundaryAboveIndex: input.boundaryAboveIndex,
@@ -377,7 +380,7 @@ export function layoutStream(input: StreamLayoutInput): StreamLayout {
history = layoutSegment({
strategy: input.strategy,
items: input.history,
timingByAssistantId: input.timingByAssistantId,
timingByResponseItemId: input.timingByResponseItemId,
auxiliaryTurnFooter,
hasAuxiliaryFooter,
frameOrder,
@@ -397,7 +400,7 @@ export function layoutStream(input: StreamLayoutInput): StreamLayout {
const liveHead = layoutSegment({
strategy: input.strategy,
items: input.liveHead,
timingByAssistantId: input.timingByAssistantId,
timingByResponseItemId: input.timingByResponseItemId,
auxiliaryTurnFooter,
hasAuxiliaryFooter,
frameOrder,
+6 -6
View File
@@ -69,8 +69,8 @@ describe("buildAgentStreamRenderModel", () => {
historyStart: 2,
});
expect(model.turnTiming.byAssistantId.has("hidden-a")).toBe(false);
expect(model.turnTiming.byAssistantId.get("visible-a")).toEqual({
expect(model.turnTiming.byResponseItemId.has("hidden-a")).toBe(false);
expect(model.turnTiming.byResponseItemId.get("visible-a")).toEqual({
completedAt: tail[3]?.timestamp,
durationMs: 1000,
});
@@ -184,7 +184,7 @@ describe("buildAgentStreamRenderModel", () => {
});
expect(model.turnTiming.runningStartedAt).toBe(tail[0]?.timestamp);
expect(model.turnTiming.byAssistantId.has("live-a")).toBe(false);
expect(model.turnTiming.byResponseItemId.has("live-a")).toBe(false);
});
it("maps completed turn timing to assistant ids across committed history and live head", () => {
@@ -201,7 +201,7 @@ describe("buildAgentStreamRenderModel", () => {
});
expect(model.turnTiming.runningStartedAt).toBe(null);
expect(model.turnTiming.byAssistantId.get("live-a")).toEqual({
expect(model.turnTiming.byResponseItemId.get("live-a")).toEqual({
completedAt: head[0]?.timestamp,
durationMs: 3000,
});
@@ -220,7 +220,7 @@ describe("buildAgentStreamRenderModel", () => {
});
expect(model.segments.historyMounted.map((item) => item.id)).toEqual(["a1", "u1"]);
expect(model.turnTiming.byAssistantId.get("a1")).toEqual({
expect(model.turnTiming.byResponseItemId.get("a1")).toEqual({
completedAt: tail[1]?.timestamp,
durationMs: 3000,
});
@@ -238,6 +238,6 @@ describe("buildAgentStreamRenderModel", () => {
isMobileBreakpoint: false,
});
expect(model.turnTiming.byAssistantId.size).toBe(0);
expect(model.turnTiming.byResponseItemId.size).toBe(0);
});
});
@@ -32,7 +32,12 @@ function assistantMessage(
describe("resolveAssistantTurnForkBoundary", () => {
it("forks a failed assistant turn from its Paseo timeline cursor without a provider message id", () => {
const failedTurn = {
...assistantMessage("assistant-error", 2),
kind: "notification" as const,
sourceType: "error" as const,
level: "error" as const,
message: "Provider failed",
id: "error-1",
timestamp: timestamp(2),
timelineCursor: { epoch: "timeline-1", seq: 42 },
};
@@ -10,6 +10,11 @@ export function resolveAssistantTurnForkBoundary(input: {
supportsTimelineCursor: boolean;
}): AssistantTurnForkBoundary | undefined {
const item = input.items[input.startIndex];
if (item?.kind === "notification" && item.sourceType === "error") {
return input.supportsTimelineCursor && item.timelineCursor
? { boundaryCursor: item.timelineCursor }
: undefined;
}
if (item?.kind !== "assistant_message") {
return undefined;
}
@@ -53,7 +53,7 @@ function layoutFor(items: StreamItem[], isTurnActive: boolean) {
isTurnActive,
history: model.segments.historyMounted,
liveHead: model.segments.liveHead,
timingByAssistantId: model.turnTiming.byAssistantId,
timingByResponseItemId: model.turnTiming.byResponseItemId,
}),
};
}
@@ -123,7 +123,7 @@ describe("canonical turn membership", () => {
const completedItems = [...build(turnId), assistant("done", 9, turnId)];
const completed = layoutFor(completedItems, false);
expect(completedFooterIds(completed.layout)).toEqual(["done"]);
expect(completed.model.turnTiming.byAssistantId.get("done")).toMatchObject({
expect(completed.model.turnTiming.byResponseItemId.get("done")).toMatchObject({
completedAt: at(9),
durationMs: 8000,
});
+2 -2
View File
@@ -593,12 +593,12 @@ const AgentStreamViewComponent = forwardRef<AgentStreamViewHandle, AgentStreamVi
isTurnActive,
history: baseRenderModel.history,
liveHead: baseRenderModel.segments.liveHead,
timingByAssistantId: baseRenderModel.turnTiming.byAssistantId,
timingByResponseItemId: baseRenderModel.turnTiming.byResponseItemId,
}),
[
baseRenderModel.history,
baseRenderModel.segments.liveHead,
baseRenderModel.turnTiming.byAssistantId,
baseRenderModel.turnTiming.byResponseItemId,
isTurnActive,
streamRenderStrategy,
],
+1 -1
View File
@@ -2161,7 +2161,7 @@ export const Notification = memo(function Notification({
[resolvedDisableOuterSpacing, config.bg],
);
return (
<View style={containerStyle}>
<View style={containerStyle} testID="timeline-notification">
<View style={notificationStylesheet.content}>
<View style={notificationStylesheet.row}>
<View style={notificationStylesheet.iconContainer}>
+65
View File
@@ -199,6 +199,71 @@ function providerUpdate(generatedAt: string): ProvidersSnapshotUpdateMessage {
}
describe("server data push router", () => {
it("keeps a visible diff subscribed when a hidden panel switches to the same comparison", () => {
const queryClient = new QueryClient();
const fake = createFakeClient();
const serverId = "server-1";
const cwd = "/repo";
const options = (mode: "base" | "uncommitted", enabled: boolean) => {
const queryKey = checkoutDiffQueryKey(
serverId,
cwd,
mode,
mode === "base" ? "main" : undefined,
);
return {
queryKey,
queryFn: skipToken as typeof skipToken,
gcTime: Infinity,
meta: checkoutDiffPushRoute({
enabled,
serverId,
cwd,
subscriptionId: `checkoutDiff:${JSON.stringify(queryKey)}`,
compare: { mode, ...(mode === "base" ? { baseRef: "main" } : {}) },
}),
};
};
const visible = new QueryObserver(queryClient, options("base", true));
const hidden = new QueryObserver(queryClient, options("base", false));
const unsubscribeVisible = visible.subscribe(() => {});
const unsubscribeHidden = hidden.subscribe(() => {});
const unmount = mountServerDataPushRouter({ queryClient, client: fake.client, serverId });
try {
visible.setOptions(options("uncommitted", true));
hidden.setOptions(options("uncommitted", false));
const subscription = fake.subscribeCheckoutDiffCalls.findLast(
(call) => call.compare.mode === "uncommitted",
)!;
const files = [
{
path: "README.md",
isNew: false,
isDeleted: false,
additions: 1,
deletions: 0,
hunks: [],
},
];
fake.emit({
type: "checkout_diff_update",
payload: { subscriptionId: subscription.subscriptionId, cwd, files, error: null },
});
expect(queryClient.getQueryData(options("uncommitted", true).queryKey)).toMatchObject({
files,
});
expect(fake.unsubscribeCheckoutDiffCalls).not.toContain(subscription.subscriptionId);
unsubscribeVisible();
expect(fake.unsubscribeCheckoutDiffCalls).toContain(subscription.subscriptionId);
} finally {
unsubscribeVisible();
unsubscribeHidden();
unmount();
queryClient.clear();
}
});
it("retains equal diff files without reconstructing changed file bodies", () => {
const queryClient = new QueryClient();
const fake = createFakeClient();
+9 -1
View File
@@ -494,6 +494,14 @@ function getActiveServerDataRoute(
if (query.getObserversCount() === 0) {
return null;
}
// Query metadata belongs to the last observer that updated its options. A
// retained hidden panel must not cancel demand from another visible panel.
const observerRoutes = query.observers
.map((observer) => getServerDataRoute({ meta: observer.options.meta }))
.filter((route): route is ServerDataRoute => route !== null);
if (observerRoutes.length > 0) {
return observerRoutes.find((route) => route.enabled && route.serverId === serverId) ?? null;
}
const route = getServerDataRoute(query);
if (route) {
return route.enabled && route.serverId === serverId ? route : null;
@@ -590,7 +598,7 @@ function canEventChangeDesiredSubscriptions(type: QueryCacheNotifyEvent["type"])
);
}
function getServerDataRoute(query: Query): ServerDataRoute | null {
function getServerDataRoute(query: Pick<Query, "meta">): ServerDataRoute | null {
const meta = query.meta;
if (!isRecord(meta) || !isRecord(meta.serverData)) {
return null;
@@ -0,0 +1,165 @@
import { describe, expect, it } from "vitest";
import { resolveMarkdownFileDirectory, resolveMarkdownPreviewImageSource } from "./image-source";
describe("resolveMarkdownFileDirectory", () => {
it("uses the parent of an absolute markdown path", () => {
expect(
resolveMarkdownFileDirectory({
markdownPath: "/Users/test/project/docs/guide.md",
workspaceRoot: "/Users/test/project",
}),
).toBe("/Users/test/project/docs");
});
it("joins a workspace-relative markdown path to the workspace root", () => {
expect(
resolveMarkdownFileDirectory({
markdownPath: "docs/星谷云/guide.md",
workspaceRoot: "/Users/test/project",
}),
).toBe("/Users/test/project/docs/星谷云");
});
it("preserves the host home directory for home-relative markdown paths", () => {
expect(
resolveMarkdownFileDirectory({
markdownPath: "~/.paseo/plans/note.md",
workspaceRoot: "/Users/test/project",
}),
).toBe("~/.paseo/plans");
});
});
describe("resolveMarkdownPreviewImageSource", () => {
it("passes through remote and data URIs", () => {
expect(
resolveMarkdownPreviewImageSource({
source: "https://example.com/image.png",
markdownPath: "docs/guide.md",
workspaceRoot: "/Users/test/project",
}),
).toBe("https://example.com/image.png");
expect(
resolveMarkdownPreviewImageSource({
source: "data:image/png;base64,abc",
markdownPath: "docs/guide.md",
workspaceRoot: "/Users/test/project",
}),
).toBe("data:image/png;base64,abc");
});
it("resolves a sibling image against the markdown file", () => {
expect(
resolveMarkdownPreviewImageSource({
source: "./images/hero.png",
markdownPath: "docs/guide.md",
workspaceRoot: "/Users/test/project",
}),
).toBe("/Users/test/project/docs/images/hero.png");
});
it("ignores local URL query strings and fragments", () => {
expect(
resolveMarkdownPreviewImageSource({
source: "./images/hero.png?v=2#preview",
markdownPath: "docs/guide.md",
workspaceRoot: "/workspace",
}),
).toBe("/workspace/docs/images/hero.png");
});
it("preserves encoded filename characters when stripping URL suffixes", () => {
expect(
resolveMarkdownPreviewImageSource({
source: "./hero%23draft%3Fv.png?v=2#preview",
markdownPath: "docs/guide.md",
workspaceRoot: "/workspace",
}),
).toBe("/workspace/docs/hero#draft?v.png");
});
it("preserves remote URL query strings and fragments", () => {
const source = "https://example.com/hero.png?v=2#preview";
expect(resolveMarkdownPreviewImageSource({ source, markdownPath: "docs/guide.md" })).toBe(
source,
);
});
it("resolves parent-relative images that stay inside the workspace", () => {
expect(
resolveMarkdownPreviewImageSource({
source: "../../data/cache/xinggu_docs/12-linkedin/token.png",
markdownPath: "docs/星谷云/12-LinkedIn.md",
workspaceRoot: "/Users/test/project",
}),
).toBe("/Users/test/project/data/cache/xinggu_docs/12-linkedin/token.png");
});
it("keeps absolute and home-relative image paths", () => {
expect(
resolveMarkdownPreviewImageSource({
source: "/tmp/screenshot.png",
markdownPath: "docs/guide.md",
workspaceRoot: "/Users/test/project",
}),
).toBe("/tmp/screenshot.png");
expect(
resolveMarkdownPreviewImageSource({
source: "~/.paseo/screenshots/output.png",
markdownPath: "docs/guide.md",
workspaceRoot: "/Users/test/project",
}),
).toBe("~/.paseo/screenshots/output.png");
});
it("normalizes file URIs into host paths", () => {
expect(
resolveMarkdownPreviewImageSource({
source: "file:///tmp/paseo-preview.png",
markdownPath: "docs/guide.md",
workspaceRoot: "/Users/test/project",
}),
).toBe("/tmp/paseo-preview.png");
});
it("resolves images beside a home-relative document without using the workspace root", () => {
expect(
resolveMarkdownPreviewImageSource({
source: "screenshots/output.png",
markdownPath: "~/.paseo/plans/note.md",
workspaceRoot: "/Users/test/project",
}),
).toBe("~/.paseo/plans/screenshots/output.png");
});
it("decodes a file URI exactly once", () => {
expect(
resolveMarkdownPreviewImageSource({
source: "file:///tmp/hero%2520image.png",
markdownPath: "docs/guide.md",
workspaceRoot: "/workspace",
}),
).toBe("/tmp/hero%20image.png");
});
it("resolves parent segments from a home-relative document", () => {
expect(
resolveMarkdownPreviewImageSource({
source: "../images/hero.png",
markdownPath: "~/docs/guide.md",
workspaceRoot: "/workspace",
}),
).toBe("~/images/hero.png");
});
it("resolves Windows relative images against a drive-rooted markdown file", () => {
expect(
resolveMarkdownPreviewImageSource({
source: "..\\images\\hero.png",
markdownPath: "C:\\Users\\test\\repo\\docs\\guide.md",
workspaceRoot: "C:\\Users\\test\\repo",
}),
).toBe("C:/Users/test/repo/images/hero.png");
});
});
@@ -0,0 +1,150 @@
import { localFileSourceToPath } from "@/attachments/utils";
import { isAbsolutePath } from "@/utils/path";
function trimTrailingSeparators(value: string): string {
if (value === "/" || /^[A-Za-z]:[\\/]?$/.test(value)) {
return value.replace(/\\/g, "/");
}
return value.replace(/[\\/]+$/, "");
}
function normalizePathSegments(value: string): string {
const segments: string[] = [];
for (const segment of value.split("/")) {
if (!segment || segment === ".") {
continue;
}
if (segment === "..") {
if (segments.length > 0) {
segments.pop();
}
continue;
}
segments.push(segment);
}
return segments.join("/");
}
function normalizeAbsolutePath(value: string): string | null {
const normalizedInput = trimTrailingSeparators(value.replace(/\\/g, "/"));
if (isHomeRelativePath(normalizedInput)) {
return `~/${normalizePathSegments(normalizedInput.slice(2))}`;
}
if (!isAbsolutePath(normalizedInput)) {
return null;
}
const drivePath = /^([A-Za-z]:)\/(.*)$/.exec(normalizedInput);
if (drivePath) {
return trimTrailingSeparators(`${drivePath[1]}/${normalizePathSegments(drivePath[2])}`);
}
const prefix = normalizedInput.startsWith("//") ? "//" : "/";
return trimTrailingSeparators(
`${prefix}${normalizePathSegments(normalizedInput.replace(/^\/+/, ""))}`,
);
}
function parentDirectory(path: string): string | null {
const normalized = trimTrailingSeparators(path.replace(/\\/g, "/"));
if (!normalized) {
return null;
}
if (normalized === "/" || /^[A-Za-z]:\/?$/.test(normalized)) {
return normalized.endsWith("/") ? normalized : `${normalized}/`;
}
const index = normalized.lastIndexOf("/");
if (index < 0) {
return null;
}
if (index === 0) {
return "/";
}
const parent = normalized.slice(0, index);
if (/^[A-Za-z]:$/.test(parent)) {
return `${parent}/`;
}
return parent;
}
function joinAbsolute(baseDirectory: string, relativePath: string): string | null {
const directory = trimTrailingSeparators(baseDirectory.replace(/\\/g, "/"));
const relative = relativePath.replace(/\\/g, "/").replace(/^\/+/, "");
if (!directory) {
return null;
}
return normalizeAbsolutePath(`${directory}/${relative}`);
}
function isHomeRelativePath(value: string): boolean {
return value === "~" || value.startsWith("~/") || value.startsWith("~\\");
}
function decodeRelativeSource(source: string): string {
try {
return decodeURIComponent(source);
} catch {
return source;
}
}
export function resolveMarkdownFileDirectory(input: {
markdownPath: string;
workspaceRoot?: string;
}): string | null {
const markdownPath = input.markdownPath.trim().replace(/\\/g, "/");
if (!markdownPath) {
return null;
}
if (isAbsolutePath(markdownPath) || isHomeRelativePath(markdownPath)) {
const absolute = normalizeAbsolutePath(markdownPath);
return absolute ? parentDirectory(absolute) : null;
}
const workspaceRoot = input.workspaceRoot?.trim();
if (!workspaceRoot || !isAbsolutePath(workspaceRoot)) {
return null;
}
const absoluteMarkdown = joinAbsolute(workspaceRoot, markdownPath);
return absoluteMarkdown ? parentDirectory(absoluteMarkdown) : null;
}
export function resolveMarkdownPreviewImageSource(input: {
source: string;
markdownPath: string;
workspaceRoot?: string;
}): string | null {
const source = input.source.trim();
if (!source) {
return null;
}
if (/^(https?:|data:|blob:)/i.test(source)) {
return source;
}
const pathSource = source.replace(/[?#].*$/, "");
const path = localFileSourceToPath(
pathSource.startsWith("file://") ? pathSource : decodeRelativeSource(pathSource),
);
if (!path) {
return null;
}
if (isHomeRelativePath(path) || isAbsolutePath(path)) {
return path;
}
const directory = resolveMarkdownFileDirectory({
markdownPath: input.markdownPath,
workspaceRoot: input.workspaceRoot,
});
if (!directory) {
return path;
}
return joinAbsolute(directory, path);
}
@@ -1,11 +1,59 @@
import { useMemo } from "react";
import type { DaemonClient } from "@getpaseo/client/internal/daemon-client";
import type { ASTNode, RenderRules } from "react-native-markdown-display";
import { Text, View } from "react-native";
import { StyleSheet } from "react-native-unistyles";
import { MarkdownRenderer } from "@/components/markdown/renderer";
import {
createSharedMarkdownRules,
MarkdownRenderer,
type MarkdownStyles,
} from "@/components/markdown/renderer";
import { parseMarkdownPreviewDocument } from "./document";
import { resolveMarkdownPreviewImageSource } from "./image-source";
import { FileMarkdownPreviewImage } from "./preview-image";
export function FileMarkdownPreview({ source }: { source: string }) {
export function FileMarkdownPreview({
source,
filePath,
workspaceRoot,
client,
serverId,
}: {
source: string;
filePath: string;
workspaceRoot?: string;
client?: DaemonClient | null;
serverId?: string;
}) {
const document = useMemo(() => parseMarkdownPreviewDocument(source), [source]);
const rules = useMemo<RenderRules>(
() => ({
...createSharedMarkdownRules(),
image: (node: ASTNode, _children, _parent: ASTNode[], _styles: MarkdownStyles) => {
const resolved = resolveMarkdownPreviewImageSource({
source: String(node.attributes?.src ?? ""),
markdownPath: filePath,
workspaceRoot,
});
if (!resolved) {
return null;
}
return (
<FileMarkdownPreviewImage
key={node.key}
source={resolved}
occurrenceKey={`${filePath}:${node.key}`}
alt={typeof node.attributes?.alt === "string" ? node.attributes.alt : undefined}
client={client}
workspaceRoot={workspaceRoot}
serverId={serverId}
/>
);
},
}),
[client, filePath, serverId, workspaceRoot],
);
return (
<View style={styles.outerGutter}>
@@ -31,7 +79,7 @@ export function FileMarkdownPreview({ source }: { source: string }) {
))}
</View>
) : null}
<MarkdownRenderer text={document.body} />
<MarkdownRenderer text={document.body} rules={rules} />
</View>
</View>
);
@@ -0,0 +1,151 @@
import { useCallback, useMemo, useState } from "react";
import type { DaemonClient } from "@getpaseo/client/internal/daemon-client";
import { useTranslation } from "react-i18next";
import { Image, Pressable, Text, View, type StyleProp, type ViewStyle } from "react-native";
import { StyleSheet, withUnistyles } from "react-native-unistyles";
import { useAssistantImage } from "@/assistant-image/use-assistant-image";
import { AttachmentLightbox, type ImageLightboxSource } from "@/components/attachment-lightbox";
import { LoadingSpinner } from "@/components/ui/loading-spinner";
import type { Theme } from "@/styles/theme";
const ThemedLoadingSpinner = withUnistyles(LoadingSpinner);
const foregroundMutedColorMapping = (theme: Theme) => ({
color: theme.colors.foregroundMuted,
});
const PREVIEW_IMAGE_MIN_HEIGHT = 160;
export function FileMarkdownPreviewImage({
source,
occurrenceKey,
alt,
client,
workspaceRoot,
serverId,
}: {
source: string;
occurrenceKey: string;
alt?: string;
client?: DaemonClient | null;
workspaceRoot?: string;
serverId?: string;
}) {
const { t } = useTranslation();
const [viewerOpen, setViewerOpen] = useState(false);
const openViewer = useCallback(() => setViewerOpen(true), []);
const closeViewer = useCallback(() => setViewerOpen(false), []);
const image = useAssistantImage({
source,
occurrenceKey,
client,
workspaceRoot,
serverId,
});
const binding = image.status === "failed" ? null : image.binding;
const aspectRatio = image.status === "failed" ? null : image.aspectRatio;
const imageUri = binding?.uri ?? "";
const imageSource = useMemo(() => ({ uri: imageUri }), [imageUri]);
const imageSizeStyle = useMemo<ViewStyle>(() => {
if (aspectRatio) {
return { aspectRatio };
}
return { height: PREVIEW_IMAGE_MIN_HEIGHT };
}, [aspectRatio]);
const surfaceStyle = useMemo<StyleProp<ViewStyle>>(
() => [styles.surface, imageSizeStyle],
[imageSizeStyle],
);
const lightboxSource = useMemo<ImageLightboxSource | null>(() => {
if (!viewerOpen || !imageUri) return null;
return {
type: "uri",
uri: imageUri,
contentSize: aspectRatio ? { width: aspectRatio, height: 1 } : undefined,
};
}, [aspectRatio, imageUri, viewerOpen]);
if (image.status === "failed") {
return (
<View style={[styles.frame, styles.state]} testID="markdown-preview-image-failed">
<Text style={styles.errorText}>{image.message}</Text>
</View>
);
}
if (!binding) {
return (
<View style={[styles.frame, styles.state]} testID="markdown-preview-image-loading">
<ThemedLoadingSpinner size="small" uniProps={foregroundMutedColorMapping} />
</View>
);
}
return (
<View style={styles.frame} testID="markdown-preview-image">
<Pressable
accessibilityLabel={t("composer.attachments.openImage")}
accessibilityRole="button"
disabled={image.status !== "loaded"}
onPress={openViewer}
style={surfaceStyle}
>
<View style={styles.image} accessibilityRole="image" accessibilityLabel={alt}>
<Image
ref={binding.onRef}
source={imageSource}
style={styles.image}
resizeMode="contain"
onLoad={binding.onLoad}
onError={binding.onError}
/>
{image.status === "loading" ? (
<View pointerEvents="none" style={styles.loadingOverlay}>
<ThemedLoadingSpinner size="small" uniProps={foregroundMutedColorMapping} />
</View>
) : null}
</View>
</Pressable>
<AttachmentLightbox source={lightboxSource} onClose={closeViewer} />
</View>
);
}
const styles = StyleSheet.create((theme) => ({
frame: {
width: "100%",
marginBottom: theme.spacing[4],
},
surface: {
width: "100%",
overflow: "hidden",
borderRadius: theme.borderRadius.md,
backgroundColor: theme.colors.surface2,
},
image: {
width: "100%",
height: "100%",
},
state: {
minHeight: PREVIEW_IMAGE_MIN_HEIGHT,
alignItems: "center",
justifyContent: "center",
paddingHorizontal: theme.spacing[4],
paddingVertical: theme.spacing[6],
backgroundColor: theme.colors.surface2,
borderRadius: theme.borderRadius.md,
},
loadingOverlay: {
position: "absolute",
top: 0,
right: 0,
bottom: 0,
left: 0,
alignItems: "center",
justifyContent: "center",
},
errorText: {
color: theme.colors.foregroundMuted,
fontSize: theme.fontSize.base,
textAlign: "center",
},
}));
+28 -1
View File
@@ -54,6 +54,9 @@ interface FilePreviewBodyProps {
location: WorkspaceFileLocation;
navigationRevision: number;
imagePreviewUri: string | null;
workspaceRoot: string;
client: DaemonClient | null;
serverId: string;
}
type TextExplorerFile = ExplorerFile & { kind: "text" };
@@ -135,6 +138,9 @@ function FilePreviewBody({
location,
navigationRevision,
imagePreviewUri,
workspaceRoot,
client,
serverId,
}: FilePreviewBodyProps) {
const { t } = useTranslation();
const filePath = location.path;
@@ -182,7 +188,13 @@ function FilePreviewBody({
style={styles.previewContent}
showsVerticalScrollIndicator
>
<FileMarkdownPreview source={preview.content ?? ""} />
<FileMarkdownPreview
source={preview.content ?? ""}
filePath={filePath}
workspaceRoot={workspaceRoot}
client={client}
serverId={serverId}
/>
</RNScrollView>
</View>
);
@@ -297,6 +309,7 @@ export function FilePane({
return (
<FilePanePresentation
serverId={serverId}
workspaceRoot={normalizedWorkspaceRoot}
client={client}
readTarget={readTarget}
preview={preview}
@@ -338,6 +351,7 @@ function isEditableTextFile(input: {
function FilePanePresentation({
serverId,
workspaceRoot,
client,
readTarget,
preview,
@@ -359,6 +373,7 @@ function FilePanePresentation({
imagePreviewUri,
}: {
serverId: string;
workspaceRoot: string;
client: DaemonClient | null;
readTarget: { cwd: string; path: string } | null;
preview: ExplorerFile | null;
@@ -393,6 +408,8 @@ function FilePanePresentation({
return (
<EditableFilePane
key={`${serverId}:${readTarget.cwd}:${readTarget.path}`}
serverId={serverId}
workspaceRoot={workspaceRoot}
client={client}
cwd={readTarget.cwd}
path={readTarget.path}
@@ -449,12 +466,17 @@ function FilePanePresentation({
location={location}
navigationRevision={navigationRevision}
imagePreviewUri={imagePreviewUri}
workspaceRoot={workspaceRoot}
client={client}
serverId={serverId}
/>
</View>
);
}
function EditableFilePane({
serverId,
workspaceRoot,
client,
cwd,
path,
@@ -470,6 +492,8 @@ function EditableFilePane({
location,
navigationRevision,
}: {
serverId: string;
workspaceRoot: string;
client: DaemonClient;
cwd: string;
path: string;
@@ -622,6 +646,9 @@ function EditableFilePane({
location={location}
navigationRevision={navigationRevision}
imagePreviewUri={null}
workspaceRoot={workspaceRoot}
client={client}
serverId={serverId}
/>
)}
</View>
@@ -328,7 +328,7 @@ export function ProvidersSection({ serverId }: ProvidersSectionProps) {
const isConnected = useHostRuntimeIsConnected(serverId);
const supportsProviderRemoval = useHostFeature(serverId, "providerRemoval");
const { entries, isLoading, refresh } = useProvidersSnapshot(serverId);
const { patchConfig } = useDaemonConfig(serverId);
const { config, patchConfig } = useDaemonConfig(serverId);
const openProviderSettings = useProviderSettingsStore((state) => state.open);
const [pendingProviderId, setPendingProviderId] = useState<string | null>(null);
const [removingProviderId, setRemovingProviderId] = useState<string | null>(null);
@@ -338,6 +338,12 @@ export function ProvidersSection({ serverId }: ProvidersSectionProps) {
const providerDefinitions = useMemo(() => buildProviderDefinitions(entries), [entries]);
const hasServer = serverId.length > 0;
/** Custom providers are deletable only when config.json holds their `extends` definition. */
const isConfigOwnedProvider = useCallback(
(providerId: string) => Boolean(config?.providers?.[providerId]?.extends),
[config],
);
const handleOpenProviderSettings = useCallback(
(providerId: string) => {
openProviderSettings({ serverId, provider: providerId });
@@ -444,7 +450,11 @@ export function ProvidersSection({ serverId }: ProvidersSectionProps) {
enabled={entry.enabled ?? true}
isToggling={pendingProviderId === def.id}
isRemoving={removingProviderId === def.id}
canRemove={supportsProviderRemoval && entry.source === "custom"}
canRemove={
supportsProviderRemoval &&
entry.source === "custom" &&
isConfigOwnedProvider(def.id)
}
isFirst={index === 0}
onPress={handleOpenProviderSettings}
onToggleEnabled={handleToggleEnabled}
+30 -5
View File
@@ -22,6 +22,31 @@ function assistant(id: string, timestamp: Date): StreamItem {
}
describe("deriveStreamTurnTiming", () => {
it("retains completed timing for a failed response with or without assistant text", () => {
const userAt = new Date("2026-05-15T00:00:00.000Z");
const failedAt = new Date("2026-05-15T00:00:07.000Z");
const error: StreamItem = {
kind: "notification",
sourceType: "error",
level: "error",
id: "error-1",
message: "Provider failed",
timestamp: failedAt,
};
for (const replies of [[], [assistant("assistant-1", new Date("2026-05-15T00:00:03.000Z"))]]) {
const timing = deriveStreamTurnTiming({
isTurnActive: false,
activeTurnStartedAt: null,
tail: [user("user-1", userAt), ...replies, error],
head: [],
});
assert.deepEqual(timing.byResponseItemId.get(error.id), {
completedAt: failedAt,
durationMs: 7000,
});
}
});
it("starts elapsed time from the submitted prompt", () => {
const submittedAt = new Date("2026-05-15T00:00:00.000Z");
@@ -51,7 +76,7 @@ describe("deriveStreamTurnTiming", () => {
});
assert.equal(timing.runningStartedAt, secondUserAt);
assert.equal(timing.byAssistantId.has("a2"), false);
assert.equal(timing.byResponseItemId.has("a2"), false);
});
it("derives completed turn timing from user and assistant item timestamps", () => {
@@ -69,7 +94,7 @@ describe("deriveStreamTurnTiming", () => {
head: [],
});
assert.deepEqual(timing.byAssistantId.get("a1"), {
assert.deepEqual(timing.byResponseItemId.get("a1"), {
completedAt: assistantAt,
durationMs: 7000,
});
@@ -95,8 +120,8 @@ describe("deriveStreamTurnTiming", () => {
completedAt: lastAssistantAt,
durationMs: 7000,
};
assert.deepEqual(timing.byAssistantId.get("a1"), expected);
assert.deepEqual(timing.byAssistantId.get("a2"), expected);
assert.deepEqual(timing.byResponseItemId.get("a1"), expected);
assert.deepEqual(timing.byResponseItemId.get("a2"), expected);
});
it("preserves the completion timestamp when a canonical turn has no visible prompt", () => {
@@ -120,7 +145,7 @@ describe("deriveStreamTurnTiming", () => {
head: [],
});
assert.deepEqual(timing.byAssistantId.get("hidden-prompt-a2"), {
assert.deepEqual(timing.byResponseItemId.get("hidden-prompt-a2"), {
completedAt: hiddenPromptTurnAt,
durationMs: null,
});
+13 -10
View File
@@ -7,7 +7,7 @@ export interface TurnTiming {
}
export interface StreamTurnTiming {
byAssistantId: Map<string, TurnTiming>;
byResponseItemId: Map<string, TurnTiming>;
runningStartedAt: Date | null;
}
@@ -17,14 +17,14 @@ export function deriveStreamTurnTiming(params: {
tail: StreamItem[];
head: StreamItem[];
}): StreamTurnTiming {
const byAssistantId = new Map<string, TurnTiming>();
const byResponseItemId = new Map<string, TurnTiming>();
let currentUserAt: Date | null = null;
let currentLastItemAt: Date | null = null;
let currentAssistantIds: string[] = [];
let currentResponseItemIds: string[] = [];
let previousItem: StreamItem | null = null;
const flushCompletedTurn = () => {
if (!currentLastItemAt || currentAssistantIds.length === 0) {
if (!currentLastItemAt || currentResponseItemIds.length === 0) {
return;
}
const timing: TurnTiming = {
@@ -33,8 +33,8 @@ export function deriveStreamTurnTiming(params: {
? Math.max(0, currentLastItemAt.getTime() - currentUserAt.getTime())
: null,
};
for (const id of currentAssistantIds) {
byAssistantId.set(id, timing);
for (const id of currentResponseItemIds) {
byResponseItemId.set(id, timing);
}
};
@@ -43,11 +43,14 @@ export function deriveStreamTurnTiming(params: {
flushCompletedTurn();
currentUserAt = item.kind === "user_message" ? item.timestamp : null;
currentLastItemAt = null;
currentAssistantIds = [];
currentResponseItemIds = [];
}
currentLastItemAt = item.timestamp;
if (item.kind === "assistant_message") {
currentAssistantIds.push(item.id);
if (
item.kind === "assistant_message" ||
(item.kind === "notification" && item.sourceType === "error")
) {
currentResponseItemIds.push(item.id);
}
previousItem = item;
};
@@ -65,7 +68,7 @@ export function deriveStreamTurnTiming(params: {
}
return {
byAssistantId,
byResponseItemId,
runningStartedAt,
};
}
@@ -3966,11 +3966,7 @@ test("a prompt after provider replacement reopens the stale session", async () =
expect(timeline.filter((item) => item.type === "user_message")).toMatchObject([
{ text: "continue after reload", clientMessageId: "stale-session-retry" },
]);
expect(
timeline.some(
(item) => item.type === "assistant_message" && item.text.includes("[System Error]"),
),
).toBe(false);
expect(timeline.some((item) => item.type === "error")).toBe(false);
} finally {
await manager.closeAgent(created.id).catch(() => undefined);
await manager.flush().catch(() => undefined);
@@ -7032,47 +7028,78 @@ test("ignores stale autonomous terminals without lowering the active turn lifecy
});
});
test("preserves terminal fallback when no active turn identity was observed", async () => {
const workdir = mkdtempSync(join(tmpdir(), "agent-manager-untracked-terminal-"));
const storage = new AgentStorage(join(workdir, "agents"), logger);
let capturedSession: TestAgentSession | null = null;
test.each(["Task completed.", "[System Error] untracked failure"])(
"preserves terminal fallback and separates untracked failure activity after %s",
async (assistantText) => {
const workdir = mkdtempSync(join(tmpdir(), "agent-manager-untracked-terminal-"));
const storage = new AgentStorage(join(workdir, "agents"), logger);
let capturedSession: TestAgentSession | null = null;
class LiveEventClient extends TestAgentClient {
override async createSession(config: AgentSessionConfig): Promise<AgentSession> {
capturedSession = new TestAgentSession(config);
return capturedSession;
class LiveEventClient extends TestAgentClient {
override async createSession(config: AgentSessionConfig): Promise<AgentSession> {
capturedSession = new TestAgentSession(config);
return capturedSession;
}
}
}
const manager = new AgentManager({
clients: { codex: new LiveEventClient() },
registry: storage,
logger,
idFactory: () => "00000000-0000-4000-8000-000000000136",
});
const snapshot = await manager.createAgent({ provider: "codex", cwd: workdir }, undefined, {
workspaceId: undefined,
});
capturedSession!.pushEvent({
type: "turn_failed",
provider: "codex",
turnId: "untracked-turn",
error: "untracked failure",
});
await vi.waitFor(() => {
const failed = manager.getAgent(snapshot.id);
expect(failed?.lifecycle).toBe("error");
expect(failed?.lastError).toBe("untracked failure");
});
expect(manager.getTimeline(snapshot.id)).toContainEqual(
expect.objectContaining({
const manager = new AgentManager({
clients: { codex: new LiveEventClient() },
registry: storage,
logger,
idFactory: () => "00000000-0000-4000-8000-000000000136",
});
const snapshot = await manager.createAgent({ provider: "codex", cwd: workdir }, undefined, {
workspaceId: undefined,
});
const events: AgentManagerEvent[] = [];
manager.subscribe((event) => events.push(event), { agentId: snapshot.id, replayState: false });
await manager.appendTimelineItem(snapshot.id, {
type: "assistant_message",
text: expect.stringContaining("untracked failure"),
}),
);
});
text: assistantText,
messageId: "assistant-1",
});
capturedSession!.pushEvent({
type: "turn_failed",
provider: "codex",
turnId: "untracked-turn",
error: "untracked failure",
});
await vi.waitFor(() => {
const failed = manager.getAgent(snapshot.id);
expect(failed?.lifecycle).toBe("error");
expect(failed?.lastError).toBe("untracked failure");
});
expect(manager.getTimeline(snapshot.id)).toContainEqual(
expect.objectContaining({
type: "error",
message: expect.stringContaining("untracked failure"),
}),
);
const projected = projectTimelineRows({
rows: await manager.getTimelineRows(snapshot.id),
mode: "projected",
});
expect(projected.map((entry) => entry.item)).toEqual([
{
type: "assistant_message",
text: assistantText,
messageId: "assistant-1",
},
{ type: "error", message: "untracked failure" },
]);
expect(events).toContainEqual(
expect.objectContaining({
type: "agent_stream",
event: expect.objectContaining({
type: "timeline",
item: { type: "error", message: "untracked failure" },
}),
}),
);
},
);
test("cancelAgentRun waits for an acknowledged autonomous interrupt to settle", async () => {
const workdir = mkdtempSync(join(tmpdir(), "agent-manager-live-cancel-"));
@@ -8357,7 +8384,7 @@ test("streamAgent clears pending run when startTurn fails before a turn id exist
clientMessageId: "rejected-prompt",
messageId: "rejected-prompt",
},
{ type: "assistant_message", text: "[System Error] Invalid request: missing field `text`" },
{ type: "error", message: "Invalid request: missing field `text`" },
]);
await expect(manager.runAgent(agent.id, "second turn")).resolves.toEqual(
@@ -9184,7 +9211,7 @@ test("archiveAgent cascade surfaces partial child archive failures", async () =>
);
});
test("turn_failed emits a system error assistant timeline message and keeps error lifecycle", async () => {
test("turn_failed emits error activity and keeps error lifecycle", async () => {
const workdir = mkdtempSync(join(tmpdir(), "agent-manager-turn-failed-"));
const storagePath = join(workdir, "agents");
const storage = new AgentStorage(storagePath, logger);
@@ -9252,12 +9279,9 @@ test("turn_failed emits a system error assistant timeline message and keeps erro
const systemErrors = manager
.getTimeline(agent.id)
.filter(
(item): item is Extract<AgentTimelineItem, { type: "assistant_message" }> =>
item.type === "assistant_message" && item.text.includes("[System Error]"),
);
.filter((item): item is Extract<AgentTimelineItem, { type: "error" }> => item.type === "error");
expect(systemErrors).toHaveLength(1);
expect(systemErrors[0]?.text).toContain("invalid model id");
expect(systemErrors[0]?.message).toContain("invalid model id");
});
test("turn_failed surfaces provider code and diagnostic in system error message", async () => {
@@ -9324,17 +9348,16 @@ test("turn_failed surfaces provider code and diagnostic in system error message"
await expect(manager.runAgent(agent.id, "hello")).rejects.toThrow("Provider execution failed");
expect(manager.getAgent(agent.id)?.lastError).toBe("Provider execution failed");
expect(manager.getAgent(agent.id)?.lastError).toBe(
"Provider execution failed\n\ncode: 126\n\nNo preset version installed for command claude",
);
const systemError = manager
.getTimeline(agent.id)
.find(
(item): item is Extract<AgentTimelineItem, { type: "assistant_message" }> =>
item.type === "assistant_message" && item.text.includes("[System Error]"),
);
expect(systemError?.text).toContain("Provider execution failed");
expect(systemError?.text).toContain("code: 126");
expect(systemError?.text).toContain("No preset version installed for command claude");
.find((item): item is Extract<AgentTimelineItem, { type: "error" }> => item.type === "error");
expect(systemError?.message).toContain("Provider execution failed");
expect(systemError?.message).toContain("code: 126");
expect(systemError?.message).toContain("No preset version installed for command claude");
});
test("permission request notifies once without forcing unread attention state", async () => {
@@ -551,8 +551,6 @@ interface AgentMetadataPatch {
labels?: AgentLabelPatch;
}
const SYSTEM_ERROR_PREFIX = "[System Error]";
function attachPersistenceCwd(
handle: AgentPersistenceHandle | null,
cwd: string,
@@ -4633,13 +4631,8 @@ export class AgentManager {
if (!isForegroundEvent && !agent.activeForegroundTurnId) {
agent.lifecycle = "error";
}
agent.lastError = event.error;
await this.appendSystemErrorTimelineMessage(
agent,
event.provider,
this.formatTurnFailedMessage(event),
options,
);
agent.lastError = this.formatTurnFailedMessage(event);
await this.appendSystemErrorTimelineMessage(agent, event.provider, agent.lastError, options);
this.resolvePendingPermissionsForAgent(agent, event.provider, options, "Turn failed");
if (!isForegroundEvent && !agent.activeForegroundTurnId) {
this.emitState(agent);
@@ -4883,13 +4876,12 @@ export class AgentManager {
return;
}
const text = `${SYSTEM_ERROR_PREFIX} ${normalized}`;
const lastItem = await this.getLastItemFromStores(agent.id);
if (lastItem?.type === "assistant_message" && lastItem.text === text) {
if (lastItem?.type === "error" && lastItem.message === normalized) {
return;
}
const item: AgentTimelineItem = { type: "assistant_message", text };
const item: AgentTimelineItem = { type: "error", message: normalized };
const row = this.recordTimeline(agent.id, item);
this.dispatchStream(
agent.id,
@@ -15,6 +15,7 @@ import { join } from "node:path";
import { createTestLogger } from "../../test-utils/test-logger.js";
import { AgentManager } from "./agent-manager.js";
import { createTestAgentClients } from "../test-utils/fake-agent-client.js";
import { AgentStorage } from "./agent-storage.js";
import { setupFinishNotification, waitForAgentRunStartWithTimeout } from "./agent-prompt.js";
import type { AgentManagerEvent, ManagedAgent } from "./agent-manager.js";
@@ -861,3 +862,101 @@ test("a human pasting an agent envelope stays a human message through provider r
clientMessageId: "human-submission",
});
});
test.each([
{
error: "Requested fake provider failure",
code: "126",
diagnostic: "Provider executable failed",
closeChild: true,
},
{ error: "long failure " + "x".repeat(5000), closeChild: false },
])(
"errored finish notifications preserve a bounded failure while delivery waits ($closeChild)",
async ({ closeChild, ...failure }) => {
const workdir = mkdtempSync(join(tmpdir(), "agent-finish-error-"));
const logger = createTestLogger();
let releaseRead!: () => void;
let signalRead!: () => void;
const blocked = new Promise<void>((resolve) => {
releaseRead = resolve;
});
const readStarted = new Promise<void>((resolve) => {
signalRead = resolve;
});
class HoldingStorage extends AgentStorage {
blockedAgentId: string | null = null;
override async get(id: string) {
if (id === this.blockedAgentId) {
signalRead();
await blocked;
}
return super.get(id);
}
}
const storage = new HoldingStorage(join(workdir, "agents"), logger);
await storage.initialize();
const prompts: string[] = [];
const manager = new AgentManager({
logger,
registry: storage,
clients: createTestAgentClients({
turnFailure: failure,
onStartTurn(prompt) {
prompts.push(typeof prompt === "string" ? prompt : JSON.stringify(prompt));
},
}),
});
try {
const parent = await manager.createAgent(
{ provider: "claude", cwd: workdir, modeId: "bypassPermissions" },
undefined,
{ workspaceId: undefined },
);
const child = await manager.createAgent(
{ provider: "claude", cwd: workdir, modeId: "bypassPermissions" },
undefined,
{ workspaceId: undefined },
);
await manager.runAgent(child.id, "Earlier successful request");
const earlierReply = await manager.getLastAssistantMessage(child.id);
expect(earlierReply).toBeTruthy();
storage.blockedAgentId = parent.id;
setupFinishNotification({
agentManager: manager,
agentStorage: storage,
childAgentId: child.id,
callerAgentId: parent.id,
logger,
});
await expect(manager.runAgent(child.id, "Emit a turn failure")).rejects.toThrow(
failure.error,
);
await readStarted;
if (closeChild) await manager.closeAgent(child.id);
releaseRead();
const fullReason = [
failure.error,
...(failure.code ? [`code: ${failure.code}`] : []),
...(failure.diagnostic ? [failure.diagnostic] : []),
].join("\n\n");
const expectedReason =
fullReason.length > 4000
? `${fullReason.slice(0, 4000)}\n[truncated ${fullReason.length - 4000} chars; use get_agent_activity for the full response]`
: fullReason;
await vi.waitFor(() =>
expect(
parseAgentMessage(prompts.find((prompt) => prompt.includes("errored.")) ?? "")?.text,
).toContain(`<agent-error>\n${expectedReason}\n</agent-error>`),
);
expect(
parseAgentMessage(prompts.find((prompt) => prompt.includes("errored.")) ?? "")?.text,
).not.toContain("<agent-response>");
if (!closeChild) await manager.closeAgent(child.id);
await manager.closeAgent(parent.id);
} finally {
releaseRead();
rmSync(workdir, { recursive: true, force: true });
}
},
);
@@ -430,9 +430,17 @@ interface FinishNotificationBodyInput {
title: string;
reason: FinishNotificationReason;
lastAssistantMessage: string | null;
lastError?: string;
permissionRequest?: AgentPermissionRequest;
}
function limitFinishNotificationMessage(message: string): string {
const text = message.trim();
if (text.length <= FINISH_NOTIFICATION_MESSAGE_LIMIT) return text;
const omitted = text.length - FINISH_NOTIFICATION_MESSAGE_LIMIT;
return `${text.slice(0, FINISH_NOTIFICATION_MESSAGE_LIMIT)}\n[truncated ${omitted} chars; use get_agent_activity for the full response]`;
}
function formatFinishNotificationBody(params: FinishNotificationBodyInput): string {
const statusLine = `Agent ${params.childAgentId} (${params.title}) ${params.reason}.`;
const sections = [statusLine];
@@ -450,18 +458,21 @@ function formatFinishNotificationBody(params: FinishNotificationBodyInput): stri
)}\n</permission-request>`,
);
}
let lastAssistantMessage = params.lastAssistantMessage?.trim();
if (lastAssistantMessage) {
if (lastAssistantMessage.length > FINISH_NOTIFICATION_MESSAGE_LIMIT) {
const omitted = lastAssistantMessage.length - FINISH_NOTIFICATION_MESSAGE_LIMIT;
lastAssistantMessage = `${lastAssistantMessage.slice(0, FINISH_NOTIFICATION_MESSAGE_LIMIT)}\n[truncated ${omitted} chars; use get_agent_activity for the full response]`;
}
sections.push(`<agent-response>\n${lastAssistantMessage}\n</agent-response>`);
if (params.reason === "errored" && params.lastError) {
sections.push(
`<agent-error>\n${limitFinishNotificationMessage(params.lastError)}\n</agent-error>`,
);
}
if (params.lastAssistantMessage?.trim()) {
sections.push(
`<agent-response>\n${limitFinishNotificationMessage(params.lastAssistantMessage)}\n</agent-response>`,
);
}
return sections.join("\n\n");
}
interface NotifySafelyOptions {
lastError?: string;
terminal?: boolean;
permissionRequest?: AgentPermissionRequest;
}
@@ -505,7 +516,7 @@ export function setupFinishNotification(params: SetupFinishNotificationParams):
async function notify(
reason: FinishNotificationReason,
permissionRequest?: AgentPermissionRequest,
{ permissionRequest, lastError }: Pick<NotifySafelyOptions, "permissionRequest" | "lastError">,
): Promise<void> {
const callerRecord = await agentStorage.get(callerAgentId);
if (callerRecord?.archivedAt) {
@@ -517,12 +528,14 @@ export function setupFinishNotification(params: SetupFinishNotificationParams):
return;
}
const title = record?.title ?? childAgentId;
const lastAssistantMessage = await agentManager.getLastAssistantMessage(childAgentId);
const lastAssistantMessage =
reason === "errored" ? null : await agentManager.getLastAssistantMessage(childAgentId);
const body = formatFinishNotificationBody({
childAgentId,
title,
reason,
lastAssistantMessage,
lastError,
permissionRequest,
});
@@ -546,7 +559,7 @@ export function setupFinishNotification(params: SetupFinishNotificationParams):
if (stopped) return;
if (options.terminal ?? true) stop();
notificationQueue = notificationQueue
.then(() => notify(reason, options.permissionRequest))
.then(() => notify(reason, options))
.catch((error) => {
logger.error(
{ err: error, childAgentId, callerAgentId, reason },
@@ -572,7 +585,7 @@ export function setupFinishNotification(params: SetupFinishNotificationParams):
// Prior terminal state is not this task's outcome. A failure before turn start
// is reported by the dispatch acknowledgement instead of a finish callback.
if (agent.lifecycle === "error" && hasSeenTurn) {
notifySafely("errored");
notifySafely("errored", { lastError: agent.lastError });
return;
}
// Idle is published before the terminal stream event for both completion
@@ -374,7 +374,7 @@ test.each(["agent", "workspace"] as const)(
clientMessageId: agent.clientMessageId,
messageId: agent.clientMessageId,
},
{ type: "assistant_message", text: `[System Error] ${rejection}` },
{ type: "error", message: rejection },
];
expect(
(await client.fetchAgentTimeline(created.id)).entries.map((entry) => entry.item),
@@ -0,0 +1,27 @@
import http from "node:http";
import net from "node:net";
// A host can support IPv6 loopback without listing ::1 for localhost in DNS.
const lookupLoopback: net.LookupFunction = (_hostname, _options, callback) => {
callback(null, [
{ address: "127.0.0.1", family: 4 },
{ address: "::1", family: 6 },
]);
};
export function connectToLocalService(port: number): net.Socket {
return net.connect({ host: "localhost", port, autoSelectFamily: true, lookup: lookupLoopback });
}
export function requestLocalService(
options: Pick<http.RequestOptions, "port" | "path" | "method" | "headers">,
onResponse: (response: http.IncomingMessage) => void,
): http.ClientRequest {
const requestOptions = {
...options,
hostname: "localhost",
autoSelectFamily: true,
lookup: lookupLoopback,
};
return http.request(requestOptions, onResponse);
}
@@ -1776,6 +1776,57 @@ describe("ScheduleService", () => {
expect(storedAgent?.archivedAt).toBeTruthy();
});
test.each(["new-agent", "agent"] as const)(
"scheduled %s failures preserve the provider reason",
async (targetType) => {
const manager = new AgentManager({
logger: createTestLogger(),
clients: createTestAgentClients({
turnFailure: {
error: "Requested fake provider failure",
code: "126",
diagnostic: "Provider executable failed",
},
}),
registry: agentStorage,
});
const service = createScheduleService({
paseoHome: tempDir,
logger: createTestLogger(),
agentManager: manager,
agentStorage,
providerSnapshotManager: NO_UNATTENDED_SCHEDULE_POLICY,
now: () => now,
});
const agent = await manager.createAgent(
{ provider: "claude", cwd: tempDir, modeId: "bypassPermissions" },
undefined,
{ workspaceId: undefined },
);
await manager.runAgent(agent.id, "Earlier successful request");
const earlierReply = await manager.getLastAssistantMessage(agent.id);
expect(earlierReply).toBeTruthy();
const schedule = await service.create({
prompt: "Emit a turn failure",
cadence: { type: "every", everyMs: 60_000 },
target:
targetType === "agent"
? { type: "agent", agentId: agent.id }
: {
type: "new-agent",
config: { provider: "claude", cwd: tempDir, archiveOnFinish: false },
},
maxRuns: 1,
});
await service.runOnce(schedule.id);
expect((await service.inspect(schedule.id)).runs[0]).toMatchObject({
status: "failed",
error: "Requested fake provider failure\n\ncode: 126\n\nProvider executable failed",
});
await manager.closeAgent(agent.id);
},
);
test("records prompt-start failures as failed and archives the scheduled agent", async () => {
class StartFailureScheduleSession implements AgentSession {
readonly provider = "claude";
@@ -912,6 +912,12 @@ export class ScheduleService {
requireSchedule(updatedSchedule, params.scheduleId);
}
private scheduledAgentFailure(agentId: string): Error {
return new Error(
this.agentManager.getAgent(agentId)?.lastError ?? `Scheduled agent ${agentId} failed`,
);
}
private async executeSchedule(
schedule: StoredSchedule,
runId: string,
@@ -945,7 +951,7 @@ export class ScheduleService {
throw new Error(`Scheduled agent ${agent.id} is waiting for permission`);
}
if (waitResult.status === "error") {
throw new Error(waitResult.lastMessage ?? `Scheduled agent ${agent.id} failed`);
throw this.scheduledAgentFailure(agent.id);
}
return {
agentId: agent.id,
@@ -1013,7 +1019,7 @@ export class ScheduleService {
throw new Error(`Scheduled agent ${agent.id} is waiting for permission`);
}
if (waitResult.status === "error") {
throw new Error(waitResult.lastMessage ?? `Scheduled agent ${agent.id} failed`);
throw this.scheduledAgentFailure(agent.id);
}
const timelineText = curateAgentActivity(result.timeline);
return {
@@ -99,14 +99,14 @@ function createStubTerminalManager(
};
}
async function startTcpServer(): Promise<TcpServerHandle> {
async function startTcpServer(host = "127.0.0.1"): Promise<TcpServerHandle> {
const server = net.createServer((socket) => {
socket.end();
});
await new Promise<void>((resolve, reject) => {
server.once("error", reject);
server.listen(0, "127.0.0.1", () => {
server.listen(0, host, () => {
server.off("error", reject);
resolve();
});
@@ -153,6 +153,45 @@ describe("ScriptHealthMonitor", () => {
servers.clear();
});
it.each(["127.0.0.1", "::1"])("reports a service bound only to %s as healthy", async (host) => {
const service = await startTcpServer(host);
servers.add(service.server);
const serviceProxy = new ScriptRouteStore();
serviceProxy.registerWorkspaceService({
workspaceId: "workspace-a",
projectSlug: "repo",
branchName: "main",
scriptName: "api",
port: service.port,
});
const updates: ScriptHealthEntry[][] = [];
const monitor = new ScriptHealthMonitor({
serviceProxy,
onChange: (_workspaceId, scripts) => updates.push(scripts),
pollIntervalMs: 10,
probeTimeoutMs: 100,
graceMs: 0,
failuresBeforeStopped: 1,
});
monitor.start();
try {
await vi.waitFor(() => {
expect(updates).toEqual([
[
{
scriptName: "api",
hostname: "api--repo.localhost",
port: service.port,
health: "healthy",
},
],
]);
});
} finally {
monitor.stop();
}
});
it("starts new service routes in pending and transitions to healthy after the grace period", async () => {
vi.useFakeTimers();
@@ -1,4 +1,4 @@
import net from "node:net";
import { connectToLocalService } from "./local-service-connection.js";
import type { ServiceProxyHealthTarget, ServiceProxySubsystem } from "./service-proxy.js";
export type ScriptHealthState = "pending" | "healthy" | "unhealthy";
@@ -208,7 +208,7 @@ export class ScriptHealthMonitor {
private probeRoute(port: number): Promise<boolean> {
return new Promise((resolve) => {
const socket = net.connect({ host: "127.0.0.1", port });
const socket = connectToLocalService(port);
let settled = false;
const finish = (healthy: boolean) => {
@@ -32,15 +32,20 @@ function readServerSourceFiles(dir = path.resolve(import.meta.dirname)): string[
}
interface HttpGetOptions {
hostname?: string;
path?: string;
headers?: Record<string, string>;
}
function httpGet(port: number, host: string, options: HttpGetOptions = {}) {
const { path: requestPath = "/api/health", headers: extraHeaders = {} } = options;
const {
hostname = "127.0.0.1",
path: requestPath = "/api/health",
headers: extraHeaders = {},
} = options;
return new Promise<{ status: number; body: string }>((resolve, reject) => {
const req = http.get(
{ hostname: "127.0.0.1", port, path: requestPath, headers: { host, ...extraHeaders } },
{ hostname, port, path: requestPath, headers: { host, ...extraHeaders } },
(res) => {
let body = "";
res.on("data", (chunk: Buffer) => {
@@ -53,6 +58,31 @@ function httpGet(port: number, host: string, options: HttpGetOptions = {}) {
});
}
function httpPost(port: number, host: string, requestPath: string, payload: string) {
return new Promise<{ status: number; body: string }>((resolve, reject) => {
const request = http.request(
{
hostname: "127.0.0.1",
port,
method: "POST",
path: requestPath,
headers: { host, "content-type": "application/json" },
},
(res) => {
let body = "";
res.on("data", (chunk: Buffer) => {
body += chunk.toString();
});
res.on("end", () => resolve({ status: res.statusCode ?? 0, body }));
res.on("error", reject);
},
);
request.on("error", reject);
request.write(payload.slice(0, 5));
request.end(payload.slice(5));
});
}
describe("service proxy subsystem shape", () => {
it("keeps production imports behind the service-proxy entrypoint", () => {
const offenders: string[] = [];
@@ -303,6 +333,7 @@ describe("service proxy subsystem shape", () => {
});
interface ForwardedFixture {
upstreamPort: number;
daemonPort: number;
hostname: string;
close(): Promise<void>;
@@ -313,11 +344,16 @@ interface ForwardedFixture {
* echoes the headers it received so tests can assert what actually crossed the
* proxy, not what a helper returned.
*/
async function startForwardedHeadersFixture(): Promise<ForwardedFixture> {
const upstreamPort = await findFreePort();
async function startForwardedHeadersFixture(upstreamHost = "127.0.0.1"): Promise<ForwardedFixture> {
const upstream = http.createServer((req, res) => {
res.writeHead(200, { "content-type": "application/json" });
res.end(JSON.stringify(req.headers));
let body = "";
req.on("data", (chunk: Buffer) => {
body += chunk.toString();
});
req.on("end", () => {
res.writeHead(200, { "content-type": "application/json" });
res.end(JSON.stringify({ ...req.headers, method: req.method, url: req.url, body }));
});
});
const upgradeSockets: net.Socket[] = [];
upstream.on("upgrade", (req, socket) => {
@@ -331,7 +367,11 @@ async function startForwardedHeadersFixture(): Promise<ForwardedFixture> {
`HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nX-Echo-Length: ${payload.length}\r\n\r\n${payload}`,
);
});
await new Promise<void>((resolve) => upstream.listen(upstreamPort, "127.0.0.1", resolve));
await new Promise<void>((resolve, reject) => {
upstream.once("error", reject);
upstream.listen(0, upstreamHost, resolve);
});
const upstreamPort = (upstream.address() as net.AddressInfo).port;
const serviceProxy = createServiceProxySubsystem({ logger });
const route = serviceProxy.registerWorkspaceService({
@@ -354,6 +394,7 @@ async function startForwardedHeadersFixture(): Promise<ForwardedFixture> {
await new Promise<void>((resolve) => daemon.listen(daemonPort, "127.0.0.1", resolve));
return {
upstreamPort,
daemonPort,
hostname: route.hostname,
async close() {
@@ -416,6 +457,59 @@ function upgradeThroughProxy(
});
}
describe("service proxy loopback services", () => {
it.each(["127.0.0.1", "::1"])("forwards HTTP to a service bound only to %s", async (host) => {
const fixture = await startForwardedHeadersFixture(host);
try {
const direct = await httpGet(fixture.upstreamPort, fixture.hostname, { hostname: host });
expect(direct.status).toBe(200);
const response = await httpGet(fixture.daemonPort, fixture.hostname);
expect(response.status).toBe(200);
expect(JSON.parse(response.body).host).toBe(fixture.hostname);
} finally {
await fixture.close();
}
});
it.each(["127.0.0.1", "::1"])(
"streams POST bodies to a service bound only to %s",
async (host) => {
const fixture = await startForwardedHeadersFixture(host);
try {
const payload = JSON.stringify({ message: "hello" });
const response = await httpPost(
fixture.daemonPort,
fixture.hostname,
"/submit?q=one%20two",
payload,
);
expect(response.status).toBe(200);
expect(JSON.parse(response.body)).toMatchObject({
host: fixture.hostname,
"content-type": "application/json",
method: "POST",
url: "/submit?q=one%20two",
body: payload,
});
} finally {
await fixture.close();
}
},
);
it.each(["127.0.0.1", "::1"])("forwards upgrades to a service bound only to %s", async (host) => {
const fixture = await startForwardedHeadersFixture(host);
try {
const headers = await upgradeThroughProxy(fixture.daemonPort, fixture.hostname);
expect(headers.host).toBe(fixture.hostname);
expect(headers.upgrade).toBe("websocket");
} finally {
await fixture.close();
}
});
});
describe("service proxy forwarded headers", () => {
it("forwards the client authority with its port so services build reachable URLs", async () => {
const fixture = await startForwardedHeadersFixture();
+4 -3
View File
@@ -1,5 +1,6 @@
import http, { createServer as createHTTPServer } from "node:http";
import net from "node:net";
import { connectToLocalService, requestLocalService } from "./local-service-connection.js";
import { createHash } from "node:crypto";
import { existsSync, unlinkSync } from "node:fs";
import type { IncomingMessage } from "node:http";
@@ -328,9 +329,8 @@ function proxyHttpRequest({
}): void {
const forwardedHeaders = buildForwardedHeaders({ req, route, protocol: req.protocol });
const proxyReq = http.request(
const proxyReq = requestLocalService(
{
hostname: "127.0.0.1",
port: route.port,
path: req.originalUrl,
method: req.method,
@@ -368,7 +368,8 @@ function proxyUpgradeRequest({
route: ServiceProxyRoute;
logger: Logger;
}): void {
const targetSocket = net.connect({ host: "127.0.0.1", port: route.port }, () => {
const targetSocket = connectToLocalService(route.port);
targetSocket.on("connect", () => {
const forwardedHeaders = buildForwardedHeaders({ req, route, protocol: "http" });
forwardedHeaders.connection = "Upgrade";
forwardedHeaders.upgrade = req.headers.upgrade ?? "websocket";
@@ -52,6 +52,7 @@ interface Deferred<T> {
}
interface FakeAgentSessionOptions {
turnFailure?: TestAgentClientOptions["turnFailure"];
providerName: string;
config: AgentSessionConfig;
supportsMcpServers?: boolean;
@@ -64,6 +65,10 @@ interface FakeAgentSessionOptions {
}
export interface TestAgentClientOptions {
turnFailure?: Pick<
Extract<AgentStreamEvent, { type: "turn_failed" }>,
"error" | "code" | "diagnostic"
>;
beforeCreateSession?: (config: AgentSessionConfig) => Promise<void>;
closeSession?: () => Promise<void>;
onStartTurn?: (prompt: AgentPromptInput, config: AgentSessionConfig) => void;
@@ -343,6 +348,7 @@ class FakeAgentSession implements AgentSession {
private readonly closeSession: (() => Promise<void>) | undefined;
private readonly onStartTurn: TestAgentClientOptions["onStartTurn"];
private readonly beforeTurnComplete: ((prompt: AgentPromptInput) => Promise<void>) | undefined;
private readonly turnFailure: TestAgentClientOptions["turnFailure"];
private readonly historyEvents: readonly AgentStreamEvent[] | undefined;
constructor(options: FakeAgentSessionOptions) {
@@ -358,6 +364,7 @@ class FakeAgentSession implements AgentSession {
this.onStartTurn = options.onStartTurn;
this.beforeTurnComplete = options.beforeTurnComplete;
this.historyEvents = options.historyEvents;
this.turnFailure = options.turnFailure;
this.historyPath = path.join(
tmpdir(),
"paseo-fake-provider-history",
@@ -761,6 +768,7 @@ class FakeAgentSession implements AgentSession {
type: "turn_failed",
provider: this.providerName,
error: "Requested fake provider failure",
...this.turnFailure,
};
await this.appendHistoryEvent(failed);
this.notifySubscribers(failed);
@@ -1235,6 +1243,7 @@ class FakeAgentClient implements AgentClient {
onStartTurn: this.options.onStartTurn,
beforeTurnComplete: this.options.beforeTurnComplete,
historyEvents: this.options.historyEvents,
turnFailure: this.options.turnFailure,
});
}
@@ -1262,6 +1271,7 @@ class FakeAgentClient implements AgentClient {
onStartTurn: this.options.onStartTurn,
beforeTurnComplete: this.options.beforeTurnComplete,
historyEvents: this.options.historyEvents,
turnFailure: this.options.turnFailure,
});
}