fix(desktop): keep automatically named checkpoints distinct (#13387)

This commit is contained in:
morluto authored and GitHub committed 2026-11-22 10:53:22 +00:00
1 parent 1a613fd0d5
commit 0b62db4d63
5 files changed
+124 -84

No files matched your search

@@ -428,65 +428,6 @@ it.skipIf(process.platform !== "linux")(
describe.skipIf(process.platform !== "linux")(
"captureDesktopApplication on Linux",
() => {
it("records the window, a requested checkpoint and the state change with its content", async () => {
const { root, home, environment } = await fixture();
const output = join(root, "out");
const statePath = join(home, ".config/fakeapp/state.ini");
let checkpointAt: number | undefined;
const nextRequest = (): SessionRequest | undefined => {
if (checkpointAt === undefined) {
if (readFileSyncSafe(statePath) !== "count=1\n") return undefined;
checkpointAt = performance.now();
return { kind: "checkpoint", name: "written" };
}
// Leave time for window samples before stopping.
return performance.now() - checkpointAt > 1500
? { kind: "stop" }
: undefined;
};
const evidence = await captureDesktopApplication(
request(output),
host(environment, nextRequest),
);
if ("error" in evidence) throw new Error(JSON.stringify(evidence));
expect(evidence.operation).toBe("capture_desktop_application");
const capture = desktopApplicationCaptureSchema.parse(
evidence.normalized_result,
);
expect(capture.session).toMatchObject({
end_reason: "stop_requested",
window_match: { class: "FakeApp", instance: "fakeapp" },
});
expect(capture.session.first_window_ms).not.toBeNull();
expect(capture.host).toMatchObject({
hostname: hostname(),
user: userInfo().username,
});
expect(
capture.state.checkpoints.map((checkpoint) => checkpoint.name),
).toEqual(["baseline", "written", "stop", "exit"]);
expect(capture.state.checkpoints[0]?.retained).toEqual([
{ path: statePath, sha256: sha256("count=0\n"), size: 8 },
]);
const change = capture.state.checkpoints[1]?.changes.find(
(candidate) => candidate.path === statePath,
);
expect(change).toMatchObject({
kind: "modified",
before: { sha256: sha256("count=0\n") },
after: { sha256: sha256("count=1\n") },
in_state_directory: true,
});
expect(
await readFile(join(output, "content", sha256("count=1\n")), "utf8"),
).toBe("count=1\n");
expect(
JSON.parse(await readFile(join(output, "capture.json"), "utf8")),
).toEqual(JSON.parse(JSON.stringify(evidence)));
});
it("keeps a baseline-only capture when cancelled before any checkpoint", async () => {
const { root, home, environment } = await fixture();
const output = join(root, "out");
@@ -635,15 +576,50 @@ describe.skipIf(process.platform !== "linux")(
const capture = desktopApplicationCaptureSchema.parse(
evidence.normalized_result,
);
expect(evidence.operation).toBe("capture_desktop_application");
expect(capture.session).toMatchObject({
end_reason: "stop_requested",
window_match: { class: "FakeApp", instance: "fakeapp" },
first_window_ms: expect.any(Number),
});
expect(capture.host).toMatchObject({
hostname: hostname(),
user: userInfo().username,
});
expect(capture.state.checkpoints.map(({ name }) => name)).toEqual([
"baseline",
"seed",
"stop",
"exit",
]);
expect(capture.state.checkpoints[0]?.retained).toEqual([
{ path: statePath, sha256: sha256("count=0\n"), size: 8 },
]);
const seed = capture.state.checkpoints[1];
// The acknowledgement comes after the checkpoint is taken and carries its counts and the file the app wrote.
if (seed === undefined) throw new Error("Expected the recorded seed");
expect(seed.changes.find(({ path }) => path === statePath)).toMatchObject(
{
kind: "modified",
before: { sha256: sha256("count=0\n") },
after: { sha256: sha256("count=1\n") },
in_state_directory: true,
},
);
expect(
await readFile(join(output, "content", sha256("count=1\n")), "utf8"),
).toBe("count=1\n");
expect(
JSON.parse(await readFile(join(output, "capture.json"), "utf8")),
).toEqual(JSON.parse(JSON.stringify(evidence)));
// The acknowledgement carries the counts from the recorded checkpoint.
expect(parsed[2]).toEqual({
kind: "checkpoint",
name: "seed",
trigger: "request",
at_ms: seed?.at_ms,
entries: seed?.entries,
changes: seed?.changes.length,
at_ms: seed.at_ms,
entries: seed.entries,
changes: seed.changes.length,
retained_files: 1,
retained_bytes: 8,
changed_files: [".config/fakeapp/state.ini"],
@@ -234,18 +234,4 @@ describe("draftDesktopApplicationTask between named checkpoints", () => {
},
});
});
it("refuses an unknown checkpoint under its own operation", async () => {
const result = await draftDesktopApplicationTask(
await folder(),
readers,
undefined,
{ seed: "saved" },
);
expect(result).toMatchObject({
operation: "describe_desktop_application_task",
issues: [{ path: ["seed_checkpoint"], reason: "invalid_value" }],
});
});
});
+65 -1
View File
@@ -16,7 +16,10 @@ import * as runTokenObservations from "../process/ProcessRunTokenObservations.js
import { isProcessOwnershipInspectionCancellation } from "../process/ProcessInspectionCancellation.js";
import { assertArtifactReadActive } from "../resources/ArtifactFileOperation.js";
import { runDesktopSession } from "./DesktopApplicationSession.js";
import type { DesktopSessionPlan } from "../ports/DesktopApplicationSession.js";
import type {
DesktopSessionPlan,
SessionRequest,
} from "../ports/DesktopApplicationSession.js";
import { X11WindowObserver } from "./X11WindowObserver.js";
vi.mock("../process/TokenOwnedTermination.js", async (importOriginal) => {
@@ -138,6 +141,67 @@ const inertSessionPorts = () => {
};
};
it.skipIf(process.platform === "win32")(
"assigns distinct names to unnamed requests at an occupied timestamp",
async () => {
const root = await createTestTempDirectory("desktop-session-names-");
const inert = inertSessionPorts();
vi.spyOn(
sessionObservations.SessionObservations.prototype,
"now",
).mockReturnValue(500);
vi.spyOn(sessionObservations, "sampleProcesses").mockResolvedValue(
undefined,
);
vi.mocked(terminateTokenOwnedProcesses).mockImplementationOnce(
async (owner, grace) => {
await inert.finish();
const actual = await vi.importActual<
typeof import("../process/TokenOwnedTermination.js")
>("../process/TokenOwnedTermination.js");
return actual.terminateTokenOwnedProcesses(owner, grace, inert.host);
},
);
const requests: SessionRequest[] = [
{ kind: "checkpoint", name: "checkpoint-500" },
{ kind: "checkpoint", name: "checkpoint-500-2" },
{ kind: "checkpoint", name: undefined },
{ kind: "checkpoint", name: undefined },
{ kind: "checkpoint", name: "checkpoint-500-3" },
{ kind: "stop" },
];
const names: string[] = [];
const refusals: string[] = [];
try {
const outcome = await runDesktopSession({
...shellPlan(root, "exit 0"),
argv: inert.argv,
pollIntervalMs: 0,
nextRequest: () => requests.shift() ?? { kind: "stop" },
checkpoint: async (name) => {
names.push(name);
},
report: async (_message, event) => {
if (event?.kind === "checkpoint_refused") refusals.push(event.name);
},
});
expect(outcome.session.end_reason).toBe("stop_requested");
expect(names).toEqual([
"checkpoint-500",
"checkpoint-500-2",
"checkpoint-500-3",
"checkpoint-500-4",
"stop",
"exit",
]);
expect(refusals).toEqual(["checkpoint-500-3"]);
} finally {
await inert.finish();
vi.restoreAllMocks();
}
},
);
describe.skipIf(process.platform !== "linux")("runDesktopSession", () => {
it("releases the application once when the exit checkpoint fails after release", async () => {
const root = await createTestTempDirectory("desktop-session-");
+11 -3
View File
@@ -111,8 +111,9 @@ const checkpointNow = (
observations: SessionObservations,
name: string,
trigger: CheckpointTrigger,
atMs = observations.now(),
): Promise<void> =>
plan.checkpoint(name, trigger, observations.now(), {
plan.checkpoint(name, trigger, atMs, {
openedFiles: new Set(observations.openedFiles.keys()),
titles: [...observations.windows.values()]
.filter((window) => window.application)
@@ -135,9 +136,16 @@ const requestCheckpoint = async (
});
return;
}
const chosen = name ?? `checkpoint-${String(observations.now())}`;
const atMs = observations.now();
let chosen = name;
if (chosen === undefined) {
const base = `checkpoint-${String(atMs)}`;
chosen = base;
for (let suffix = 2; taken.has(chosen); suffix += 1)
chosen = `${base}-${String(suffix)}`;
}
taken.add(chosen);
await checkpointNow(plan, observations, chosen, "request");
await checkpointNow(plan, observations, chosen, "request", atMs);
};
/**
+9 -3
View File
@@ -141,11 +141,12 @@ it("exports and drafts between the checkpoints the command names", async () => {
expect(
parseEvidence(JSON.parse(drafted.stdout)).normalized_result,
).toMatchObject({ checkpoints: { baseline: "seed", final: "end" } });
expect(refused.exitCode).toBe(1);
expect(JSON.parse(refused.stdout)).toMatchObject({
code: "invalid_request",
details: {
operation: "describe_desktop_application_task",
issues: [{ path: ["end_checkpoint"] }],
issues: [{ path: ["end_checkpoint"], reason: "invalid_value" }],
},
});
});
@@ -244,8 +245,13 @@ it("names a dconf database that changed by the seed but could not be read, so th
// At baseline the database did not exist yet, so nothing was lost.
const before = await exportAt("baseline", "baseline");
expect(unread).toHaveLength(1);
expect(unread[0]).toContain("dconf is not installed (dconf-cli)");
expect(unread).toEqual([
expect.stringContaining(
"changed by the seed checkpoint but could not be read",
),
]);
if (process.platform === "linux")
expect(unread[0]).toContain("dconf is not installed (dconf-cli)");
expect(
await readFile(join(root, "bundle/envs/notes/notes_app.py"), "utf8"),
).toContain('DCONF = ""');