Compare commits

..
2 Commits
Author SHA1 Message Date
Marcel Wysocki ad738c02b5 fix(server): stop the Linux watcher reporting a deleted directory under its own name (#9289)
inotify names a watched directory's own deletion after the directory, and
fs.watch passes that name as the filename. The Linux backend resolved it
against the directory, so removing `dir/` also reported a delete for
`dir/dir`, and removing `dir/nested/` one for `dir/nested/nested`.

When `<dir>/<basename(dir)>` is missing, the backend now checks whether the
watched directory itself is gone and drops the event in that case; the
parent watcher and reconciliation already report the directory. A real
child named like its directory is still reported.
2026-12-06 15:12:42 +00:00
neihyud c5caa9a009 Show provider CLI versions as plain text when the CLI styles its output (#10616)
Some provider CLIs color their `--version` output even when piped, and the
escape codes showed up in the provider settings version row. Strip them in
readCommandVersionOutput, which the version label, Codex version checks and
diagnostics all read from.

Fixes #10316
2026-12-06 14:12:41 +00:00
10 changed files with 407 additions and 404 deletions
@@ -30,7 +30,6 @@ import {
} from "@agentclientprotocol/sdk";
import { z } from "zod";
import type { JsonValue } from "@getpaseo/protocol/agent-types";
import { renderPromptAttachmentAsText } from "@getpaseo/protocol/prompt-attachment-text";
import {
createBoundedNdJsonStream,
ProviderStreamLimitError,
@@ -2875,9 +2874,8 @@ function toAcpPrompt(
return [{ type: "text", text: `/${prompt.input.name}${suffix}` }];
}
return prompt.input.content.map((content) => {
if (content.type === "image") return content;
if (content.type === "text") return { type: "text", text: content.text };
return { type: "text", text: renderPromptAttachmentAsText(content) };
if (content.type === "text" || content.type === "image") return content;
return { type: "text", text: JSON.stringify(content) };
});
}
-77
View File
@@ -1751,83 +1751,6 @@ readline.createInterface({ input: process.stdin }).on("line", (line) => {
},
);
it("sends attachments to the agent as readable text, not JSON", async () => {
const prompts: unknown[] = [];
const harness = connectorHarness({
handleRequest(instance, message) {
if (message.method !== "session/prompt") return false;
prompts.push((message.params as { prompt: unknown }).prompt);
instance.respond(message, { stopReason: "end_turn" });
return true;
},
});
const registration = runAcpProvider({
id: "attachment-acp",
label: "Attachment ACP",
connector: harness.connector,
});
const connection = await registration.connect({
versions: [1],
capabilities: ["prompt.message"],
});
const events: ProviderEvent[] = [];
connection.onEvent((event) => events.push(event));
try {
await connection.send(openInput());
await waitForEvent(events, (event) => event.type === "session.ready");
await connection.send({
type: "session.prompt",
sessionId: "session-1",
prompt: {
clientMessageId: "first",
delivery: "auto",
input: {
type: "message",
content: [
{ type: "text", text: "Read these" },
{
type: "uploaded_file",
id: "upload-1",
fileName: "notes.txt",
mimeType: "text/plain",
size: 14,
path: "/tmp/uploads/upload-1/notes.txt",
},
{
type: "forge_issue",
mimeType: "application/paseo-forge-issue",
number: 7,
title: "Broken thing",
url: "https://github.com/acme/app/issues/7",
},
{ type: "text", mimeType: "text/plain", title: "Pasted", text: "pasted body" },
],
},
},
});
await waitForEvent(
events,
(event) => event.type === "session.turn" && event.state === "completed",
);
expect(prompts).toEqual([
[
{ type: "text", text: "Read these" },
{
type: "text",
text: "Uploaded file: notes.txt\nPath: /tmp/uploads/upload-1/notes.txt\nMIME: text/plain\nSize: 14 bytes",
},
{
type: "text",
text: "GitHub Issue #7: Broken thing\nhttps://github.com/acme/app/issues/7",
},
{ type: "text", text: "pasted body" },
],
]);
} finally {
await connection.close();
}
});
it.each([
{ status: "failed", output: undefined, error: { message: "Tool failed" } },
{ status: "failed", output: null, error: { message: "Tool failed" } },
@@ -1,134 +0,0 @@
import { describe, expect, it } from "vitest";
import { renderPromptAttachmentAsText } from "./prompt-attachment-text.js";
describe("renderPromptAttachmentAsText", () => {
it("renders github_pr attachments as readable text", () => {
expect(
renderPromptAttachmentAsText({
type: "github_pr",
mimeType: "application/github-pr",
number: 123,
title: "Fix race in worktree setup",
url: "https://github.com/getpaseo/paseo/pull/123",
body: "PR body",
baseRefName: "main",
headRefName: "fix/worktree-race",
}),
).toContain("GitHub PR #123: Fix race in worktree setup");
});
it("renders GitLab change request attachments with MR numbering", () => {
expect(
renderPromptAttachmentAsText({
type: "forge_change_request",
mimeType: "application/paseo-forge-change-request",
forge: "gitlab",
number: 123,
title: "Fix race in worktree setup",
url: "https://gitlab.com/getpaseo/paseo/-/merge_requests/123",
body: "MR body",
projectPath: "getpaseo/paseo",
baseRefName: "main",
headRefName: "fix/worktree-race",
}),
).toContain("GitLab MR !123: Fix race in worktree setup");
});
it.each(["base", "uncommitted", "all"] as const)("renders %s reviews", (mode) => {
expect(
renderPromptAttachmentAsText({
type: "review",
mimeType: "application/paseo-review",
cwd: "/tmp/repo",
mode,
baseRef: "main",
comments: [
{
filePath: "src/index.ts",
side: "new",
lineNumber: 42,
body: "Please guard this nullable value.",
context: {
hunkHeader: "@@ -40,3 +40,4 @@",
targetLine: {
oldLineNumber: null,
newLineNumber: 42,
type: "add",
content: "const value = maybeNull.name;",
},
lines: [
{
oldLineNumber: 41,
newLineNumber: 41,
type: "context",
content: "const before = true;",
},
{
oldLineNumber: null,
newLineNumber: 42,
type: "add",
content: "const value = maybeNull.name;",
},
],
},
},
],
}),
).toBe(
[
`Paseo review attachment (${mode})`,
"CWD: /tmp/repo",
"Base: main",
"",
"Comment 1: src/index.ts:new:42",
"Please guard this nullable value.",
"@@ -40,3 +40,4 @@",
" 41 41 const before = true;",
"> - 42 +const value = maybeNull.name;",
].join("\n"),
);
});
it("renders github_issue attachments as readable text", () => {
expect(
renderPromptAttachmentAsText({
type: "github_issue",
mimeType: "application/github-issue",
number: 55,
title: "Issue",
url: "https://github.com/getpaseo/paseo/issues/55",
}),
).toContain("GitHub Issue #55: Issue");
});
it("renders text attachments as their client-provided prompt text", () => {
expect(
renderPromptAttachmentAsText({
type: "text",
mimeType: "text/plain",
title: "Browser element",
text: "<browser-element>button.primary</browser-element>",
}),
).toBe("<browser-element>button.primary</browser-element>");
});
it("renders uploaded file attachments as local file references", () => {
expect(
renderPromptAttachmentAsText({
type: "uploaded_file",
id: "upload_req-upload",
fileName: "notes.txt",
mimeType: "text/plain",
size: 11,
path: "/tmp/paseo/uploads/upload_req-upload/notes.txt",
}),
).toBe(
[
"Uploaded file: notes.txt",
"Path: /tmp/paseo/uploads/upload_req-upload/notes.txt",
"MIME: text/plain",
"Size: 11 bytes",
].join("\n"),
);
});
});
@@ -1,170 +0,0 @@
import type { z } from "zod";
import { getForgeDefinitionOrNeutral } from "./forge-manifest.js";
import type { AgentAttachmentSchema } from "./messages.js";
// Shared by built-in providers and the plugin ACP client so every agent reads attachments the same way.
// Accepts the schema input so plugin SDK attachments, whose forge is optional, render too.
type RenderableAttachment = z.input<typeof AgentAttachmentSchema>;
const REVIEW_LINE_MARKERS = { add: "+", remove: "-", context: " " } as const;
export function renderPromptAttachmentAsText(attachment: RenderableAttachment): string {
switch (attachment.type) {
case "forge_change_request": {
return renderChangeRequestAttachment({
forge: attachment.forge ?? "github",
number: attachment.number,
title: attachment.title,
url: attachment.url,
body: attachment.body,
projectPath: attachment.projectPath,
baseRefName: attachment.baseRefName,
headRefName: attachment.headRefName,
});
}
// COMPAT(githubAttachmentKinds): render legacy wire attachments until
// 2027-01-17, when supported client and daemon floors are >= v0.2.0.
case "github_pr": {
return renderChangeRequestAttachment({
forge: "github",
number: attachment.number,
title: attachment.title,
url: attachment.url,
body: attachment.body,
baseRefName: attachment.baseRefName,
headRefName: attachment.headRefName,
});
}
case "forge_issue": {
return renderIssueAttachment({
forge: attachment.forge ?? "github",
number: attachment.number,
title: attachment.title,
url: attachment.url,
body: attachment.body,
projectPath: attachment.projectPath,
});
}
// COMPAT(githubAttachmentKinds): render legacy wire attachments until
// 2027-01-17, when supported client and daemon floors are >= v0.2.0.
case "github_issue": {
return renderIssueAttachment({
forge: "github",
number: attachment.number,
title: attachment.title,
url: attachment.url,
body: attachment.body,
});
}
case "text": {
return attachment.text;
}
case "review": {
const lines = [`Paseo review attachment (${attachment.mode})`, `CWD: ${attachment.cwd}`];
if (attachment.baseRef) {
lines.push(`Base: ${attachment.baseRef}`);
}
attachment.comments.forEach((comment, index) => {
lines.push(
"",
`Comment ${index + 1}: ${comment.filePath}:${comment.side}:${comment.lineNumber}`,
comment.body,
comment.context.hunkHeader,
);
const target = comment.context.targetLine;
for (const line of comment.context.lines) {
const isTarget =
line.oldLineNumber === target.oldLineNumber &&
line.newLineNumber === target.newLineNumber &&
line.type === target.type &&
line.content === target.content;
const prefix = isTarget ? "> " : " ";
const oldLn = padLineNumber(line.oldLineNumber);
const newLn = padLineNumber(line.newLineNumber);
lines.push(`${prefix}${oldLn} ${newLn} ${REVIEW_LINE_MARKERS[line.type]}${line.content}`);
}
});
return lines.join("\n");
}
case "uploaded_file": {
return [
`Uploaded file: ${attachment.fileName}`,
`Path: ${attachment.path}`,
`MIME: ${attachment.mimeType}`,
`Size: ${attachment.size} bytes`,
].join("\n");
}
default:
throw new Error("unreachable");
}
}
function renderChangeRequestAttachment(input: {
forge: string;
number: number;
title: string;
url: string;
body?: string | null;
projectPath?: string;
baseRefName?: string | null;
headRefName?: string | null;
}): string {
const lines = [
`${formatForgeLabel(input.forge)} ${formatChangeRequestAbbrev(input.forge)} ${formatChangeRequestNumber(input.forge, input.number)}: ${input.title}`,
input.url,
];
if (input.projectPath) {
lines.push(`Project: ${input.projectPath}`);
}
if (input.baseRefName) {
lines.push(`Base: ${input.baseRefName}`);
}
if (input.headRefName) {
lines.push(`Head: ${input.headRefName}`);
}
if (input.body) {
lines.push("", input.body);
}
return lines.join("\n");
}
function renderIssueAttachment(input: {
forge: string;
number: number;
title: string;
url: string;
body?: string | null;
projectPath?: string;
}): string {
const lines = [
`${formatForgeLabel(input.forge)} Issue ${formatIssueNumber(input.forge, input.number)}: ${input.title}`,
input.url,
];
if (input.projectPath) {
lines.push(`Project: ${input.projectPath}`);
}
if (input.body) {
lines.push("", input.body);
}
return lines.join("\n");
}
function formatForgeLabel(forge: string): string {
return getForgeDefinitionOrNeutral(forge).displayName;
}
function formatChangeRequestAbbrev(forge: string): string {
return getForgeDefinitionOrNeutral(forge).changeRequestAbbrev;
}
function formatChangeRequestNumber(forge: string, number: number): string {
return `${getForgeDefinitionOrNeutral(forge).changeRequestNumberPrefix}${number}`;
}
function formatIssueNumber(forge: string, number: number): string {
return `${getForgeDefinitionOrNeutral(forge).issueNumberPrefix}${number}`;
}
function padLineNumber(lineNumber: number | null): string {
return (lineNumber?.toString() ?? "-").padStart(2);
}
@@ -9,6 +9,7 @@ import { MAX_IMAGE_DIMENSION } from "./preprocess-image.js";
import {
buildAgentBranchNameSeed,
buildAgentPrompt,
renderPromptAttachmentAsText,
resolveAgentPrompt,
} from "./prompt-attachments.js";
@@ -43,6 +44,136 @@ describe("prompt attachments", () => {
]);
});
it("renders github_pr attachments as readable text", () => {
expect(
renderPromptAttachmentAsText({
type: "github_pr",
mimeType: "application/github-pr",
number: 123,
title: "Fix race in worktree setup",
url: "https://github.com/getpaseo/paseo/pull/123",
body: "PR body",
baseRefName: "main",
headRefName: "fix/worktree-race",
}),
).toContain("GitHub PR #123: Fix race in worktree setup");
});
it("renders GitLab change request attachments with MR numbering", () => {
expect(
renderPromptAttachmentAsText({
type: "forge_change_request",
mimeType: "application/paseo-forge-change-request",
forge: "gitlab",
number: 123,
title: "Fix race in worktree setup",
url: "https://gitlab.com/getpaseo/paseo/-/merge_requests/123",
body: "MR body",
projectPath: "getpaseo/paseo",
baseRefName: "main",
headRefName: "fix/worktree-race",
}),
).toContain("GitLab MR !123: Fix race in worktree setup");
});
it.each(["base", "uncommitted", "all"] as const)("renders %s reviews", (mode) => {
expect(
renderPromptAttachmentAsText({
type: "review",
mimeType: "application/paseo-review",
cwd: "/tmp/repo",
mode,
baseRef: "main",
comments: [
{
filePath: "src/index.ts",
side: "new",
lineNumber: 42,
body: "Please guard this nullable value.",
context: {
hunkHeader: "@@ -40,3 +40,4 @@",
targetLine: {
oldLineNumber: null,
newLineNumber: 42,
type: "add",
content: "const value = maybeNull.name;",
},
lines: [
{
oldLineNumber: 41,
newLineNumber: 41,
type: "context",
content: "const before = true;",
},
{
oldLineNumber: null,
newLineNumber: 42,
type: "add",
content: "const value = maybeNull.name;",
},
],
},
},
],
}),
).toBe(
[
`Paseo review attachment (${mode})`,
"CWD: /tmp/repo",
"Base: main",
"",
"Comment 1: src/index.ts:new:42",
"Please guard this nullable value.",
"@@ -40,3 +40,4 @@",
" 41 41 const before = true;",
"> - 42 +const value = maybeNull.name;",
].join("\n"),
);
});
it("renders github_issue attachments as readable text", () => {
expect(
renderPromptAttachmentAsText({
type: "github_issue",
mimeType: "application/github-issue",
number: 55,
title: "Issue",
url: "https://github.com/getpaseo/paseo/issues/55",
}),
).toContain("GitHub Issue #55: Issue");
});
it("renders text attachments as their client-provided prompt text", () => {
expect(
renderPromptAttachmentAsText({
type: "text",
mimeType: "text/plain",
title: "Browser element",
text: "<browser-element>button.primary</browser-element>",
}),
).toBe("<browser-element>button.primary</browser-element>");
});
it("renders uploaded file attachments as local file references", () => {
expect(
renderPromptAttachmentAsText({
type: "uploaded_file",
id: "upload_req-upload",
fileName: "notes.txt",
mimeType: "text/plain",
size: 11,
path: "/tmp/paseo/uploads/upload_req-upload/notes.txt",
}),
).toBe(
[
"Uploaded file: notes.txt",
"Path: /tmp/paseo/uploads/upload_req-upload/notes.txt",
"MIME: text/plain",
"Size: 11 bytes",
].join("\n"),
);
});
it("returns undefined when firstAgentContext is empty", () => {
expect(buildAgentBranchNameSeed(undefined)).toBeUndefined();
expect(buildAgentBranchNameSeed({})).toBeUndefined();
@@ -1,17 +1,17 @@
import { getForgeDefinitionOrNeutral } from "@getpaseo/protocol/forge-manifest";
import type {
AgentAttachment,
FirstAgentContext,
UploadedFileAttachment,
UploadedImage,
} from "@getpaseo/protocol/messages";
import { renderPromptAttachmentAsText } from "@getpaseo/protocol/prompt-attachment-text";
import type { Logger } from "pino";
import { readUploadedImageFile } from "../file-upload/index.js";
import type { AgentPromptContentBlock, AgentPromptInput } from "./agent-sdk-types.js";
import { sniffRasterMimeType } from "./image-dimensions.js";
import { preprocessImages } from "./preprocess-image.js";
export { renderPromptAttachmentAsText };
const REVIEW_LINE_MARKERS = { add: "+", remove: "-", context: " " } as const;
export interface ResolvedAgentPrompt {
prompt: AgentPromptInput;
@@ -123,6 +123,167 @@ export async function resolveAgentPrompt(input: {
};
}
export function renderPromptAttachmentAsText(attachment: AgentAttachment): string {
switch (attachment.type) {
case "forge_change_request": {
return renderChangeRequestAttachment({
forge: attachment.forge,
number: attachment.number,
title: attachment.title,
url: attachment.url,
body: attachment.body,
projectPath: attachment.projectPath,
baseRefName: attachment.baseRefName,
headRefName: attachment.headRefName,
});
}
// COMPAT(githubAttachmentKinds): render legacy wire attachments until
// 2027-01-17, when supported client and daemon floors are >= v0.2.0.
case "github_pr": {
return renderChangeRequestAttachment({
forge: "github",
number: attachment.number,
title: attachment.title,
url: attachment.url,
body: attachment.body,
baseRefName: attachment.baseRefName,
headRefName: attachment.headRefName,
});
}
case "forge_issue": {
return renderIssueAttachment({
forge: attachment.forge,
number: attachment.number,
title: attachment.title,
url: attachment.url,
body: attachment.body,
projectPath: attachment.projectPath,
});
}
// COMPAT(githubAttachmentKinds): render legacy wire attachments until
// 2027-01-17, when supported client and daemon floors are >= v0.2.0.
case "github_issue": {
return renderIssueAttachment({
forge: "github",
number: attachment.number,
title: attachment.title,
url: attachment.url,
body: attachment.body,
});
}
case "text": {
return attachment.text;
}
case "review": {
const lines = [`Paseo review attachment (${attachment.mode})`, `CWD: ${attachment.cwd}`];
if (attachment.baseRef) {
lines.push(`Base: ${attachment.baseRef}`);
}
attachment.comments.forEach((comment, index) => {
lines.push(
"",
`Comment ${index + 1}: ${comment.filePath}:${comment.side}:${comment.lineNumber}`,
comment.body,
comment.context.hunkHeader,
);
const target = comment.context.targetLine;
for (const line of comment.context.lines) {
const isTarget =
line.oldLineNumber === target.oldLineNumber &&
line.newLineNumber === target.newLineNumber &&
line.type === target.type &&
line.content === target.content;
const prefix = isTarget ? "> " : " ";
const oldLn = padLineNumber(line.oldLineNumber);
const newLn = padLineNumber(line.newLineNumber);
lines.push(`${prefix}${oldLn} ${newLn} ${REVIEW_LINE_MARKERS[line.type]}${line.content}`);
}
});
return lines.join("\n");
}
case "uploaded_file": {
return [
`Uploaded file: ${attachment.fileName}`,
`Path: ${attachment.path}`,
`MIME: ${attachment.mimeType}`,
`Size: ${attachment.size} bytes`,
].join("\n");
}
default:
throw new Error("unreachable");
}
}
function renderChangeRequestAttachment(input: {
forge: string;
number: number;
title: string;
url: string;
body?: string | null;
projectPath?: string;
baseRefName?: string | null;
headRefName?: string | null;
}): string {
const lines = [
`${formatForgeLabel(input.forge)} ${formatChangeRequestAbbrev(input.forge)} ${formatChangeRequestNumber(input.forge, input.number)}: ${input.title}`,
input.url,
];
if (input.projectPath) {
lines.push(`Project: ${input.projectPath}`);
}
if (input.baseRefName) {
lines.push(`Base: ${input.baseRefName}`);
}
if (input.headRefName) {
lines.push(`Head: ${input.headRefName}`);
}
if (input.body) {
lines.push("", input.body);
}
return lines.join("\n");
}
function renderIssueAttachment(input: {
forge: string;
number: number;
title: string;
url: string;
body?: string | null;
projectPath?: string;
}): string {
const lines = [
`${formatForgeLabel(input.forge)} Issue ${formatIssueNumber(input.forge, input.number)}: ${input.title}`,
input.url,
];
if (input.projectPath) {
lines.push(`Project: ${input.projectPath}`);
}
if (input.body) {
lines.push("", input.body);
}
return lines.join("\n");
}
function formatForgeLabel(forge: string): string {
return getForgeDefinitionOrNeutral(forge).displayName;
}
function formatChangeRequestAbbrev(forge: string): string {
return getForgeDefinitionOrNeutral(forge).changeRequestAbbrev;
}
function formatChangeRequestNumber(forge: string, number: number): string {
return `${getForgeDefinitionOrNeutral(forge).changeRequestNumberPrefix}${number}`;
}
function formatIssueNumber(forge: string, number: number): string {
return `${getForgeDefinitionOrNeutral(forge).issueNumberPrefix}${number}`;
}
function padLineNumber(lineNumber: number | null): string {
return (lineNumber?.toString() ?? "-").padStart(2);
}
export type WorkspaceNamingContext = FirstAgentContext & { imageCount?: number };
export function buildAgentBranchNameSeed(
@@ -5,6 +5,7 @@ import { afterEach, describe, expect, test } from "vitest";
import {
buildCommandResolutionDiagnosticRows,
readCommandVersionOutput,
toDiagnosticErrorMessage,
} from "./diagnostic-utils.js";
@@ -127,6 +128,17 @@ describe("buildCommandResolutionDiagnosticRows", () => {
});
});
describe("readCommandVersionOutput", () => {
test("returns the version as plain text when the CLI styles it for a terminal", async () => {
const output = await readCommandVersionOutput({
command: process.execPath,
args: ["-e", String.raw`process.stdout.write("\x1b[1m\x1b[32mtool 1.2.3\x1b[0m\n")`],
});
expect(output).toBe("tool 1.2.3");
});
});
describe("toDiagnosticErrorMessage", () => {
test("returns message for plain Error", () => {
expect(toDiagnosticErrorMessage(new Error("boom"))).toBe("boom");
@@ -1,6 +1,7 @@
import { constants } from "node:fs";
import { access, stat } from "node:fs/promises";
import path from "node:path";
import stripAnsi from "strip-ansi";
import {
createProviderEnvSpec,
@@ -397,7 +398,8 @@ export async function readCommandVersionOutput(
timeout: 5_000,
signal: invocation.signal,
});
return stdout.trim() || stderr.trim();
// Some CLIs style `--version` for a terminal even when piped; callers show the text as is.
return stripAnsi(stdout).trim() || stripAnsi(stderr).trim();
}
async function resolveCommandVersion(invocation: BinaryDiagnosticVersionCommand): Promise<string> {
@@ -212,6 +212,61 @@ test("classifies a removed file as deleted", async () => {
await subscription.unsubscribe();
});
// inotify names a watched directory's own deletion after the directory, which
// reads like a child of the same name.
test.skipIf(process.platform !== "linux")(
"reports a removed directory tree at its own paths only",
async () => {
const root = await createRoot();
const removed = join(root, "removed");
const nested = join(removed, "nested");
await mkdir(nested, { recursive: true });
const observer = createObserver();
const events: FileChange[] = [];
const subscription = await observer.subscribe(root, (error, batch) => {
expect(error).toBeNull();
events.push(...batch);
});
await rm(removed, { recursive: true });
await expect
.poll(() => events.map((event) => event.path))
.toEqual(expect.arrayContaining([removed, nested]));
await expect
.poll(() => observer.getDiagnostics(), { timeout: 10_000 })
.toMatchObject({
pendingEventCount: 0,
pendingReconciliationWorkCount: 0,
reconciliationInFlightCount: 0,
});
expect(new Set(events.map((event) => `${event.type} ${event.path}`))).toEqual(
new Set([`delete ${removed}`, `delete ${nested}`]),
);
await subscription.unsubscribe();
},
);
test.skipIf(process.platform !== "linux")(
"reports a file named like its directory when it is created and removed",
async () => {
const root = await createRoot();
const directory = join(root, "same");
const target = join(directory, "same");
await mkdir(directory);
const events: FileChange[] = [];
const subscription = await subscribeToFileChanges(root, (error, batch) => {
expect(error).toBeNull();
events.push(...batch);
});
await writeFile(target, "created");
await expect.poll(() => events.find((event) => event.path === target)?.type).toBe("create");
await rm(target);
await expect.poll(() => events.findLast((event) => event.path === target)?.type).toBe("delete");
await subscription.unsubscribe();
},
);
test("observes files moved into the tree with their directory", async () => {
const root = await createRoot();
const outside = await createRoot();
@@ -1,6 +1,6 @@
import { type Dirent, type FSWatcher, watch } from "node:fs";
import { readdir, stat } from "node:fs/promises";
import { resolve } from "node:path";
import { basename, resolve } from "node:path";
import type { BackendDiagnostics, ObservationBackend, ObservationHost } from "./contracts.js";
import type { ObserverPaths } from "./paths.js";
import { isMissingPathError, toError } from "./paths.js";
@@ -31,6 +31,12 @@ const MAX_DIRECTORY_RESCANS = 3;
// observed, so files found before their directory was covered are creates.
type ReconcileMode = "baseline" | "changes";
interface Classification {
path: string;
// The watched directory whose watcher reported `path`.
directory: string;
}
interface DirectoryIdentity {
dev: bigint;
ino: bigint;
@@ -70,7 +76,7 @@ export function createLinuxBackend(
class LinuxBackend implements ObservationBackend {
private readonly watchers = new Map<string, WatchedDirectory>();
private readonly classifications = new Set<Promise<void>>();
private readonly classificationQueue: Array<{ path: string }> = [];
private readonly classificationQueue: Classification[] = [];
private readonly pendingScopes = new Set<string>();
private reconcileTail: Promise<void> = Promise.resolve();
private queueDepth = 0;
@@ -159,7 +165,7 @@ class LinuxBackend implements ObservationBackend {
const path = filename ? resolve(directory, filename.toString()) : directory;
if (!this.host.isIgnored(path)) {
if (eventType === "change") this.host.queueEvent("update", path);
else this.classify(path);
else this.classify({ path, directory });
}
if (eventType === "rename" || !filename) this.requestReconcile(path);
});
@@ -466,7 +472,7 @@ class LinuxBackend implements ObservationBackend {
return "ok";
}
private classify(path: string): void {
private classify(classification: Classification): void {
if (this.classificationQueue.length >= MAX_QUEUED_CLASSIFICATIONS) {
// This backend has no file-level inventory and no full-tree safety
// audit to fall back on (see the comment on MAX_QUEUED_CLASSIFICATIONS
@@ -480,7 +486,7 @@ class LinuxBackend implements ObservationBackend {
);
return;
}
this.classificationQueue.push({ path });
this.classificationQueue.push(classification);
this.pumpClassifications();
}
@@ -501,22 +507,15 @@ class LinuxBackend implements ObservationBackend {
) {
const next = this.classificationQueue.shift();
if (!next) return;
this.startClassification(next.path);
this.startClassification(next);
}
}
private startClassification(path: string): void {
private startClassification(pending: Classification): void {
this.host.metrics.nativeClassificationCount += 1;
let classification!: Promise<void>;
classification = stat(path)
.then(() => this.host.queueEvent("create", path))
.catch((error: unknown) => {
if (isMissingPathError(error)) {
this.host.queueEvent("delete", path);
return;
}
this.host.fail(toError(error));
})
classification = this.classifyPath(pending)
.catch((error: unknown) => this.host.fail(toError(error)))
.finally(() => {
this.classifications.delete(classification);
if (this.host.isActive()) this.pumpClassifications();
@@ -524,6 +523,32 @@ class LinuxBackend implements ObservationBackend {
this.classifications.add(classification);
}
private async classifyPath({ path, directory }: Classification): Promise<void> {
try {
await stat(path);
} catch (error) {
if (!isMissingPathError(error)) throw error;
if (!(await this.isOwnDeletion({ path, directory }))) this.host.queueEvent("delete", path);
return;
}
this.host.queueEvent("create", path);
}
// inotify names a watched directory's own deletion after the directory, so
// `<directory>/<basename(directory)>` is either a child of that name or the
// directory itself. Once the directory is gone, its parent's watcher and the
// reconciliation report it, and that delete covers a same-named child too.
private async isOwnDeletion({ path, directory }: Classification): Promise<boolean> {
if (path !== resolve(directory, basename(directory))) return false;
try {
await stat(directory);
return false;
} catch (error) {
if (isMissingPathError(error)) return true;
throw error;
}
}
private cancelQueued(): void {
if (this.timer) clearTimeout(this.timer);
this.timer = null;