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
4 changed files with 111 additions and 17 deletions
@@ -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;