Compare 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
7 changed files with 99 additions and 512 deletions
+1 -1
View File
@@ -180,7 +180,7 @@ The following are not feature-parity claims:
| Image conversion/image clipboard | Unavailable. The picker accepts PNG/JPEG without conversion. |
| Mermaid/HTML/document previews | Mermaid and HTML show source. Document previews report unavailable. No embedded browser backend. |
| Terminals | The mobile view expects an Expo `PaseoTerminal` component. No GPUI implementation yet. |
| Diffs | `surface.gpui.tsx` lays diff lines out with React Native views and text. No inline review, drag selection, or scroll-to-file yet. |
| Diffs | The mobile surface uses React Native Skia. No GPUI drawing backend yet. |
| Plugins | The existing loader evaluates JS and injects host React/RN. No end-to-end plugin verification on GPUI yet. |
| Other platforms | Linux x86_64 and macOS arm64 have been exercised. Windows remains unverified. |
+1 -45
View File
@@ -1,7 +1,6 @@
import { readFileSync, realpathSync, statSync } from "node:fs";
import { realpathSync, statSync } from "node:fs";
import { createRequire } from "node:module";
import path from "node:path";
import ts from "typescript";
import { afterEach, describe, expect, test } from "vitest";
const require = createRequire(import.meta.url);
@@ -227,14 +226,6 @@ const CASES = [
native: path.join(APP_DIR, "src/components/desktop/caption-button.tsx"),
web: path.join(APP_DIR, "src/components/desktop/caption-button.tsx"),
},
{
label: "diff surface",
origin: path.join(APP_DIR, "src/git/diff-document/index.tsx"),
specifier: "./surface",
gpui: path.join(APP_DIR, "src/git/diff-document/surface.gpui.tsx"),
native: path.join(APP_DIR, "src/git/diff-document/surface.native.tsx"),
web: path.join(APP_DIR, "src/git/diff-document/surface.web.tsx"),
},
{
label: "window layout",
origin: path.join(APP_DIR, "src/utils/desktop-window.tsx"),
@@ -333,39 +324,4 @@ describe("GPUI Metro platform rule", () => {
}
}
});
test("the GPUI diff surface's import graph never reaches React Native Skia", () => {
const config = require(path.join(GPUI_DIR, "desktop/metro.config.js")) as MetroConfig;
const resolver = require(require.resolve("metro-resolver", { paths: [GPUI_DIR] })) as {
resolve: (...args: unknown[]) => unknown;
};
const entry = path.join(APP_DIR, "src/git/diff-document/surface.gpui.tsx");
const sourceRoot = path.join(APP_DIR, "src") + path.sep;
const visited = new Set<string>();
const bareSpecifiers = new Set<string>();
const pending = [entry];
while (pending.length > 0) {
const file = pending.pop()!;
if (visited.has(file)) continue;
visited.add(file);
const { importedFiles } = ts.preProcessFile(readFileSync(file, "utf8"), true, true);
for (const { fileName: specifier } of importedFiles) {
if (!specifier.startsWith(".") && !specifier.startsWith("@/")) {
bareSpecifiers.add(specifier);
continue;
}
const ctx = createResolutionContext(file, config.resolver.sourceExts, true, resolver);
const resolved = config.resolver.resolveRequest(ctx, specifier, "desktop").filePath;
if (resolved?.startsWith(sourceRoot) && /\.[cm]?[jt]sx?$/.test(resolved)) {
pending.push(resolved);
}
}
}
expect(visited.size).toBeGreaterThan(1);
expect([...bareSpecifiers].filter((name) => name.includes("react-native-skia"))).toEqual([]);
expect(
[...visited].filter((file) => /diff-document[\\/](text|paint)\.native\./.test(file)),
).toEqual([]);
});
});
@@ -4,7 +4,7 @@ import type { DiffFileSection } from "./types";
import type { DiffDocumentProps } from "./types";
interface DocumentFileHeaderProps {
file: Pick<DiffFileSection, "file" | "fileIndex" | "path" | "isCollapsed">;
file: DiffFileSection;
selectedPath: string | null;
mode: DiffDocumentProps["mode"];
onToggleFile: (path: string) => void;
@@ -1,176 +0,0 @@
import { renderToStaticMarkup } from "react-dom/server";
import { describe, expect, it } from "vitest";
import type { ParsedDiffFile } from "@getpaseo/protocol/messages";
import { DiffSurface } from "./surface.gpui";
import type { DiffPalette, DiffSurfaceProps } from "./types";
const PALETTE: DiffPalette = {
surface: "rgb(1, 2, 3)",
headerSurface: "rgb(1, 2, 3)",
border: "rgb(9, 9, 9)",
foreground: "rgb(240, 240, 240)",
foregroundMuted: "rgb(120, 120, 120)",
addition: "rgb(0, 200, 0)",
deletion: "rgb(200, 0, 0)",
additionBackground: "rgba(0, 128, 0, 0.15)",
deletionBackground: "rgba(128, 0, 0, 0.1)",
emptyBackground: "rgb(1, 2, 3)",
selection: "rgb(0, 0, 255)",
headerActiveSurface: "rgb(4, 5, 6)",
headerBorder: "rgb(7, 8, 9)",
statusSuccess: "rgb(0, 200, 0)",
statusDanger: "rgb(200, 0, 0)",
statusWarning: "rgb(200, 200, 0)",
syntax: { keyword: "rgb(255, 0, 255)" },
};
const GREETING_FILE: ParsedDiffFile = {
path: "src/greeting.ts",
isNew: false,
isDeleted: false,
additions: 1,
deletions: 1,
hunks: [
{
oldStart: 10,
oldCount: 2,
newStart: 10,
newCount: 2,
lines: [
{ type: "header", content: "@@ -10,2 +10,2 @@ export function greet()" },
{ type: "context", content: "const greeting = prefix;" },
{ type: "remove", content: 'return "hello";' },
{
type: "add",
content: "return `hi`;",
tokens: [
{ text: "return", style: "keyword" },
{ text: " `hi`;", style: null },
],
},
],
},
],
};
function renderSurface(overrides: Partial<DiffSurfaceProps> = {}): string {
const props = {
files: [GREETING_FILE],
mode: { kind: "commit" },
displayPreferences: {
layout: "unified",
wrapLines: true,
codeFontSize: 13,
monoFontFamily: "Menlo",
},
palette: PALETTE,
headerTypography: { family: "Inter", size: 14, statSize: 12 },
collapsedFilePaths: new Set<string>(),
onToggleFile: () => {},
selectedPath: null,
onSelectPath: () => {},
...overrides,
} as DiffSurfaceProps;
return renderToStaticMarkup(<DiffSurface {...props} />);
}
describe("GPUI DiffSurface", () => {
it("renders hunk headers and added, removed, and context lines with their line numbers", () => {
const markup = renderSurface();
expect(markup).toContain("@@ -10,2 +10,2 @@ export function greet()");
expect(markup).toContain("const greeting = prefix;");
expect(markup).toContain("hello");
expect(markup).toContain("hi");
expect(markup).toContain('data-testid="diff-line-context"');
expect(markup).toContain('data-testid="diff-line-remove"');
expect(markup).toContain('data-testid="diff-line-add"');
// context line 10 (old and new), removed old line 11, added new line 11
expect(markup).toMatch(/>10</);
expect(markup).toMatch(/>11</);
});
it("paints added and removed rows with the palette backgrounds", () => {
const markup = renderSurface();
expect(markup).toContain("rgba(0,128,0,0.15)");
expect(markup).toContain("rgba(128,0,0,0.10)");
});
it("colors syntax tokens from the palette and leaves unstyled tokens in the foreground", () => {
const markup = renderSurface();
expect(markup).toMatch(/color:rgba\(255,0,255,1\.00\)[^>]*>return</);
});
it("renders every file in the document", () => {
const other: ParsedDiffFile = {
...GREETING_FILE,
path: "src/other.ts",
hunks: [
{
oldStart: 1,
oldCount: 0,
newStart: 1,
newCount: 1,
lines: [
{ type: "header", content: "@@ -0,0 +1 @@" },
{ type: "add", content: "export const other = 1;" },
],
},
],
};
const markup = renderSurface({ files: [GREETING_FILE, other] });
expect(markup).toContain("greeting.ts");
expect(markup).toContain("other.ts");
expect(markup).toContain("export const other = 1;");
});
it("hides the body of a collapsed file", () => {
const markup = renderSurface({ collapsedFilePaths: new Set(["src/greeting.ts"]) });
expect(markup).toContain("greeting.ts");
expect(markup).not.toContain("const greeting = prefix;");
});
it("colors line numbers by line type", () => {
const markup = renderSurface();
expect(markup).toMatch(/color:rgba\(0,200,0,1\.00\)[^>]*>11</);
expect(markup).toMatch(/color:rgba\(200,0,0,1\.00\)[^>]*>11</);
expect(markup).toMatch(/color:rgba\(120,120,120,1\.00\)[^>]*>10</);
});
it("renders no rows for an empty diff", () => {
const markup = renderSurface({ files: [] });
expect(markup).not.toContain("diff-line-");
});
it("explains files whose diff is not shown", () => {
const binary: ParsedDiffFile = { ...GREETING_FILE, hunks: [], status: "binary" };
const markup = renderSurface({ files: [binary] });
expect(markup).toContain('data-testid="diff-status"');
expect(markup).not.toContain("diff-line-");
});
it("renders split preferences as unified rows", () => {
const markup = renderSurface({
displayPreferences: {
layout: "split",
wrapLines: true,
codeFontSize: 13,
monoFontFamily: "Menlo",
},
});
expect(markup).toContain('data-testid="diff-line-remove"');
expect(markup).toContain('data-testid="diff-line-add"');
});
it("keeps scrollable space below the last line for floating controls", () => {
expect(renderSurface({ contentInsetBottom: 73 })).toContain("padding-bottom:73px");
});
});
@@ -1,273 +0,0 @@
import { memo, useMemo } from "react";
import { useTranslation } from "react-i18next";
import { ScrollView, StyleSheet, Text, View, type TextStyle, type ViewStyle } from "react-native";
import type { ParsedDiffFile } from "@getpaseo/protocol/messages";
import { lineNumberGutterWidth } from "@/components/code-insets";
import { buildUnifiedDiffLines } from "@/utils/diff-layout";
import { compactHighlightTokens, formatDiffContentText } from "@/utils/diff-rendering";
import { DocumentFileHeader } from "./document-file-header";
import type { DiffPalette, DiffSurfaceProps } from "./types";
// GPUI has no Skia canvas, so this surface lays each diff line out with plain React Native
// views and text. The canvas-only features of the mobile surface (inline review threads,
// drag selection, scroll-to-file) are not part of it. It always lays lines out unified: the
// split layout is offered only where `isWeb` holds, so callers never pass it on GPUI.
type LineType = "add" | "remove" | "context" | "header";
interface CodeStyle {
fontFamily: string;
fontSize: number;
lineHeight: number;
}
interface LineCell {
type: LineType;
content: string;
lineNumber: number | null;
tokens?: ParsedDiffFile["hunks"][number]["lines"][number]["tokens"];
}
const MONOSPACE = "monospace";
const CODE_PADDING = 8;
export function DiffSurface(props: DiffSurfaceProps) {
const { displayPreferences, palette } = props;
const code = useMemo<CodeStyle>(
() => ({
fontFamily: displayPreferences.monoFontFamily.trim() || MONOSPACE,
fontSize: displayPreferences.codeFontSize,
lineHeight: Math.round(displayPreferences.codeFontSize * 1.5),
}),
[displayPreferences.monoFontFamily, displayPreferences.codeFontSize],
);
const contentStyle = useMemo<ViewStyle>(
() => ({ paddingBottom: props.contentInsetBottom ?? 0 }),
[props.contentInsetBottom],
);
return (
<ScrollView
style={[styles.fill, { backgroundColor: palette.surface }]}
contentContainerStyle={contentStyle}
>
{props.files.map((file, fileIndex) => (
<FileSection
key={file.path}
file={file}
fileIndex={fileIndex}
surface={props}
code={code}
/>
))}
</ScrollView>
);
}
interface FileSectionProps {
file: ParsedDiffFile;
fileIndex: number;
surface: DiffSurfaceProps;
code: CodeStyle;
}
function FileSection({ file, fileIndex, surface, code }: FileSectionProps) {
const isCollapsed = surface.collapsedFilePaths.has(file.path);
const section = useMemo(
() => ({ file, fileIndex, path: file.path, isCollapsed }),
[file, fileIndex, isCollapsed],
);
return (
<View>
<DocumentFileHeader
file={section}
selectedPath={surface.selectedPath}
mode={surface.mode}
onToggleFile={surface.onToggleFile}
onSelectPath={surface.onSelectPath}
/>
{isCollapsed ? null : (
<FileBody
file={file}
wrapLines={surface.displayPreferences.wrapLines}
palette={surface.palette}
code={code}
/>
)}
</View>
);
}
interface FileBodyProps {
file: ParsedDiffFile;
wrapLines: boolean;
palette: DiffPalette;
code: CodeStyle;
}
const FileBody = memo(function FileBody({ file, wrapLines, palette, code }: FileBodyProps) {
const { t } = useTranslation();
const bodyStyle = useMemo<ViewStyle>(
() => ({ borderTopWidth: StyleSheet.hairlineWidth, borderColor: palette.border }),
[palette.border],
);
const rows = useMemo(
() => (file.status === "binary" || file.status === "too_large" ? [] : bodyRows(file)),
[file],
);
const gutterWidth = useMemo(
() => lineNumberGutterWidth(maxLineNumber(file), code.fontSize),
[file, code.fontSize],
);
if (file.status === "binary" || file.status === "too_large") {
const label =
file.status === "binary"
? t("workspace.git.diff.binaryFile")
: t("workspace.git.diff.tooLarge");
return (
<View style={[bodyStyle, styles.status]} testID="diff-status">
<ColoredText color={palette.foregroundMuted} fontFamily={code.fontFamily}>
{label}
</ColoredText>
</View>
);
}
const lines = rows.map((row) => (
<LineRow
key={row.key}
cell={row.cell}
palette={palette}
code={code}
gutterWidth={gutterWidth}
wrapLines={wrapLines}
/>
));
if (wrapLines) return <View style={bodyStyle}>{lines}</View>;
return (
<ScrollView horizontal style={bodyStyle} contentContainerStyle={styles.unwrappedContent}>
<View style={styles.unwrappedRows}>{lines}</View>
</ScrollView>
);
});
function bodyRows(file: ParsedDiffFile): Array<{ key: string; cell: LineCell }> {
return buildUnifiedDiffLines(file).map((entry) => ({
key: entry.key,
cell: {
type: entry.line.type,
content: entry.line.content,
lineNumber: entry.lineNumber,
tokens: entry.line.tokens,
},
}));
}
function maxLineNumber(file: ParsedDiffFile): number {
return file.hunks.reduce(
(max, hunk) => Math.max(max, hunk.oldStart + hunk.oldCount, hunk.newStart + hunk.newCount),
0,
);
}
interface CellProps {
palette: DiffPalette;
code: CodeStyle;
gutterWidth: number;
wrapLines: boolean;
}
function LineRow({ cell, ...rest }: CellProps & { cell: LineCell }) {
return (
<View testID={`diff-line-${cell.type}`} style={rowStyle(cell.type, rest.palette)}>
<LineCellContent cell={cell} {...rest} />
</View>
);
}
function LineCellContent({
cell,
palette,
code,
gutterWidth,
wrapLines,
}: CellProps & { cell: LineCell }) {
const isHeader = cell.type === "header";
const textStyle = useMemo<TextStyle>(
() => ({
...code,
color: isHeader ? palette.foregroundMuted : palette.foreground,
}),
[code, isHeader, palette.foreground, palette.foregroundMuted],
);
const tokens = isHeader || !cell.tokens ? [] : compactHighlightTokens(cell.tokens);
return (
<View style={styles.cell}>
{isHeader ? null : (
<Text
numberOfLines={1}
style={[
textStyle,
styles.gutter,
{ width: gutterWidth, color: lineNumberColor(cell.type, palette) },
]}
>
{cell.lineNumber == null ? " " : cell.lineNumber}
</Text>
)}
<Text
numberOfLines={wrapLines ? undefined : 1}
style={[styles.code, textStyle, isHeader ? undefined : styles.codeInset]}
>
{tokens.length > 0
? tokens.map((token, index) => (
<ColoredText
// Tokens carry no identity beyond their position in the line.
// eslint-disable-next-line react/no-array-index-key
key={index}
color={(token.style && palette.syntax[token.style]) || palette.foreground}
>
{token.text}
</ColoredText>
))
: formatDiffContentText(cell.content)}
</Text>
</View>
);
}
function ColoredText({
color,
fontFamily,
children,
}: {
color: string;
fontFamily?: string;
children: string;
}) {
const style = useMemo<TextStyle>(() => ({ color, fontFamily }), [color, fontFamily]);
return <Text style={style}>{children}</Text>;
}
function rowStyle(type: LineType, palette: DiffPalette): ViewStyle {
if (type === "add") return { backgroundColor: palette.additionBackground };
if (type === "remove") return { backgroundColor: palette.deletionBackground };
return {};
}
function lineNumberColor(type: LineType, palette: DiffPalette): string {
if (type === "add") return palette.addition;
if (type === "remove") return palette.deletion;
return palette.foregroundMuted;
}
const styles = StyleSheet.create({
fill: { flex: 1 },
status: { paddingHorizontal: 12, paddingVertical: 12 },
unwrappedContent: { minWidth: "100%" },
unwrappedRows: { minWidth: "100%", alignSelf: "flex-start" },
cell: { flexDirection: "row", alignItems: "flex-start" },
gutter: { textAlign: "right", paddingRight: 4, flexShrink: 0 },
code: { flex: 1, minWidth: 0 },
codeInset: { paddingLeft: CODE_PADDING },
});
@@ -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;