Files
rea/src/desktop/DesktopSessionObservations.test.ts
T
morluto 58a2c79155 refactor(desktop): name the desktop capture's window and application-refusal facts as a port (#11667)
* refactor(desktop): name the desktop capture's window and application-refusal facts as a port

The desktop capture workflows read ObservedWindow, WindowSample,
XpropUnavailableError, WindowMatching and LinuxApplicationRefusal from the
desktop provider's X11 observer, session observations and Linux inventory.
These are the facts a capture reports, not the provider's observers, so
they now live in src/ports/DesktopApplicationSession.ts. The provider
produces them from there and the application workflows read them from
there. application -> desktop entry imports: 28 -> 24.

Refs #11583

* refactor(desktop): name the capture content store the desktop workflows use as a port (#11669)

* refactor(desktop): name the capture content store the desktop workflows use as a port

DesktopSigningKeys, DesktopCheckpointRecorder and DesktopCaptureFailure
typed the store they receive as the desktop provider's DesktopContentStore
class and its RetainOutcome. src/ports/CaptureContentStore.ts now names
what they use (directory, retain, retainBytes, close, discard) and the
outcome; DesktopContentStore implements it. DesktopApplicationCapture still
constructs the class. application -> desktop entry imports: 24 -> 21.

Refs #11583

* refactor(desktop): report an unresolved desktop session cleanup through the session port (#11671)

DesktopCaptureFailure imported DesktopSessionCleanupError and
UnresolvedCleanup from the desktop provider's session runner only to
recognise and report a session whose launched processes could not all be
removed. Both are what a session reports, so they move to
src/ports/DesktopApplicationSession.ts beside the capture's other facts;
the session runner throws the port's error. application -> desktop entry
imports: 21 -> 20.

Refs #11583
2026-11-16 10:52:21 +08:00

312 lines
9.9 KiB
TypeScript

import { describe, expect, it, vi } from "vitest";
import { systemProcessOwnershipHost } from "../process/ProcessOwnershipObservation.js";
import type { ProcessLifecycle } from "../process/ProcessLifecycle.js";
import {
SessionObservations,
observedSession,
recordWindows,
sampleProcesses,
sampleTokenCarriers,
trackProcess,
type SessionProcfs,
} from "./DesktopSessionObservations.js";
import type { ObservedWindow } from "../ports/DesktopApplicationSession.js";
interface FakeProcess {
readonly parentPid: number;
readonly startTime: string;
/** Undefined models a zombie or a process whose environment is unreadable. */
readonly runId?: string;
readonly lifecycle?: ProcessLifecycle;
}
const procfs = (
table: Map<number, FakeProcess>,
tableReadable = true,
): SessionProcfs => ({
stat: async (pid) => {
const entry = table.get(pid);
return entry === undefined
? undefined
: {
parentPid: entry.parentPid,
startTime: entry.startTime,
lifecycle: entry.lifecycle ?? "non-zombie",
};
},
children: async (pid) =>
[...table]
.filter(([, entry]) => entry.parentPid === pid)
.map(([child]) => child),
runId: async (pid) => table.get(pid)?.runId,
command: async (pid) => `process ${String(pid)}`,
tokenCarriers: async (runId) =>
tableReadable
? [...table]
.filter(
([, entry]) =>
entry.runId === runId && entry.lifecycle !== "zombie",
)
.map(([pid]) => pid)
: undefined,
});
const window = (
id: string,
pid: number,
class_: string | null,
): ObservedWindow => ({
id,
pid,
class: class_,
instance: class_?.toLowerCase() ?? null,
title: null,
window_type: "normal",
});
const observe = (
table: Map<number, FakeProcess>,
byPid = true,
tableReadable = true,
) =>
new SessionObservations(
performance.now(),
{ runId: "run", launchPid: 100 },
{ names: new Set(["notes"]), byPid },
procfs(table, tableReadable),
);
const startedBy = (observations: SessionObservations) =>
Object.fromEntries(
observedSession(observations).processes.map((entry) => [
entry.pid,
entry.started_by_capture,
]),
);
const signal = new AbortController().signal;
describe("SessionObservations", () => {
it("counts a process as started when its parent chain reaches the launch, even without a readable token", async () => {
const table = new Map<number, FakeProcess>([
[100, { parentPid: 1, startTime: "10", runId: "run" }],
[101, { parentPid: 100, startTime: "11" }],
[150, { parentPid: 100, startTime: "15" }],
[201, { parentPid: 150, startTime: "20" }],
[300, { parentPid: 1, startTime: "30" }],
]);
const observations = observe(table);
await trackProcess(observations, 100, signal);
await recordWindows(
observations,
[window("0x1", 201, "Notes"), window("0x2", 300, "Notes")],
signal,
);
await sampleProcesses(observations, signal);
expect(startedBy(observations)).toEqual({
100: true,
101: true,
150: true,
201: true,
300: false,
});
});
it("records the launched process as started after it has already exited", async () => {
const observations = observe(new Map());
await trackProcess(observations, 100, signal);
expect(observedSession(observations).processes).toEqual([
expect.objectContaining({
pid: 100,
parent_pid: process.pid,
started_by_capture: true,
}),
]);
expect(observations.liveProcessIds()).toEqual([]);
});
it("treats a reused pid as a different process", async () => {
const table = new Map<number, FakeProcess>([
[100, { parentPid: 1, startTime: "10", runId: "run" }],
[101, { parentPid: 100, startTime: "11", runId: "run" }],
]);
const observations = observe(table);
await trackProcess(observations, 100, signal);
await sampleProcesses(observations, signal);
expect(observations.belongs(window("0x3", 101, "Other"))).toBe(true);
table.set(101, { parentPid: 1, startTime: "99" });
await sampleProcesses(observations, signal);
expect(observations.liveProcessIds()).toEqual([100]);
expect(observations.belongs(window("0x3", 101, "Other"))).toBe(false);
await recordWindows(observations, [window("0x4", 101, "Notes")], signal);
expect(
observedSession(observations).processes.map((entry) => [
entry.pid,
entry.started_by_capture,
]),
).toEqual([
[100, true],
[101, true],
[101, false],
]);
});
it("does not attribute a reused pid discovered while recording windows", async () => {
const table = new Map<number, FakeProcess>([
[100, { parentPid: 1, startTime: "10", runId: "run" }],
[101, { parentPid: 100, startTime: "11", runId: "run" }],
]);
const observations = observe(table);
await trackProcess(observations, 100, signal);
await sampleProcesses(observations, signal);
table.set(101, { parentPid: 1, startTime: "99" });
expect(
await recordWindows(observations, [window("0x8", 101, "Other")], signal),
).toBe(0);
expect(
await recordWindows(observations, [window("0x8", 101, "Other")], signal),
).toBe(0);
expect(observedSession(observations).windows[0]?.application).toBe(false);
expect(observations.firstWindowMs).toBeNull();
expect(
await recordWindows(observations, [window("0x9", 101, "Notes")], signal),
).toBe(1);
});
it("does not keep a zombie child alive, whether first seen as one or exiting later", async () => {
const table = new Map<number, FakeProcess>([
[100, { parentPid: 1, startTime: "10", runId: "run" }],
[101, { parentPid: 100, startTime: "11", lifecycle: "zombie" }],
[102, { parentPid: 100, startTime: "12" }],
]);
const observations = observe(table);
await trackProcess(observations, 100, signal);
await sampleProcesses(observations, signal);
await sampleProcesses(observations, signal);
expect(observations.liveProcessIds(true)).toEqual([100, 102]);
table.delete(100);
table.set(102, { parentPid: 1, startTime: "12", lifecycle: "zombie" });
await sampleProcesses(observations, signal);
await recordWindows(observations, [window("0x7", 102, "Other")], signal);
expect(observations.liveProcessIds(true)).toEqual([]);
expect(startedBy(observations)).toEqual({
100: true,
101: true,
102: true,
});
expect(observedSession(observations).processes).toHaveLength(3);
});
it("matches windows by name only when their pids are sandbox pids", async () => {
const table = new Map<number, FakeProcess>([
[100, { parentPid: 1, startTime: "10", runId: "run" }],
[2, { parentPid: 1, startTime: "2" }],
]);
const observations = observe(table, false);
await trackProcess(observations, 100, signal);
expect(observations.belongs(window("0x5", 100, "Other"))).toBe(false);
expect(
await recordWindows(observations, [window("0x6", 2, "Notes")], signal),
).toBe(1);
expect(
observedSession(observations).processes.map(({ pid }) => pid),
).toEqual([100]);
});
});
describe("sampleTokenCarriers", () => {
it("finds a worker whose launcher exited before any sample reached it", async () => {
const table = new Map<number, FakeProcess>([
[200, { parentPid: 1, startTime: "20", runId: "run" }],
[201, { parentPid: 200, startTime: "21" }],
[300, { parentPid: 1, startTime: "30", runId: "other" }],
]);
const observations = observe(table);
await trackProcess(observations, 100, signal);
await sampleProcesses(observations, signal);
expect(observations.liveProcessIds(true)).toEqual([]);
expect(await sampleTokenCarriers(observations, signal)).toBe(true);
await sampleProcesses(observations, signal);
expect(observations.liveProcessIds(true)).toEqual([200, 201]);
expect(startedBy(observations)).toEqual({
100: true,
200: true,
201: true,
});
});
it("reports an unreadable process table as unknown", async () => {
const observations = observe(
new Map([[200, { parentPid: 1, startTime: "20", runId: "run" }]]),
true,
false,
);
expect(await sampleTokenCarriers(observations, signal)).toBe(false);
expect(observations.liveProcessIds()).toEqual([]);
});
});
it("keeps a failed optional token-table probe unknown", async () => {
const observations = new SessionObservations(
performance.now(),
{ runId: "inert-observation", launchPid: process.pid },
{ names: new Set(), byPid: true },
);
const table = vi
.spyOn(systemProcessOwnershipHost, "listProcesses")
.mockRejectedValue(
Object.assign(new Error("table read failed"), { code: "EIO" }),
);
const environment = vi
.spyOn(systemProcessOwnershipHost, "environment")
.mockRejectedValue(
new Error("no token read is authorized after an unreadable table"),
);
try {
expect(
await sampleTokenCarriers(observations, new AbortController().signal),
).toBe(false);
expect(table).toHaveBeenCalledTimes(1);
expect(environment).not.toHaveBeenCalled();
} finally {
table.mockRestore();
environment.mockRestore();
}
});
it("keeps a failed optional process-token read unknown", async () => {
const observations = new SessionObservations(
performance.now(),
{ runId: "inert-observation", launchPid: process.pid },
{ names: new Set(), byPid: false },
);
const environment = vi
.spyOn(systemProcessOwnershipHost, "environment")
.mockRejectedValue(
Object.assign(new Error("token read failed"), { code: "EIO" }),
);
try {
await trackProcess(observations, process.pid, new AbortController().signal);
expect(environment).toHaveBeenCalledTimes(1);
expect(observedSession(observations).processes).toEqual([
expect.objectContaining({ pid: process.pid, started_by_capture: true }),
]);
} finally {
environment.mockRestore();
}
});