fix(desktop): keep export and task drafts on the admitted capture (#13418)

* fix(desktop): keep export and task drafts on the admitted capture

* test(desktop): format the capture provenance checks
This commit is contained in:
morluto authored and GitHub committed 2026-11-22 13:02:47 +00:00
1 parent c445f56ae3
commit cbafdaa8e3
4 files changed
+252 -198

No files matched your search

@@ -5,6 +5,7 @@ import {
mkdir,
readFile,
realpath,
rename,
symlink,
writeFile,
} from "node:fs/promises";
@@ -19,6 +20,7 @@ import { SafeOutputTree } from "../../resources/SafeOutputTree.js";
import { ArtifactResourceScope } from "../../resources/ArtifactResourceScope.js";
import type { AnalysisCleanupLease } from "../../resources/AnalysisCleanupLease.js";
import { AnalysisError } from "../../domain/analysisErrorBase.js";
import { safeParseEvidence } from "../../domain/evidenceValidation.js";
import {
AnalysisCancelledError,
AnalysisInputError,
@@ -38,10 +40,13 @@ import { renderBuildBundle } from "../../domain/desktop/appBuild.js";
import { parseOneLineSources } from "../../domain/desktop/aptRepositories.js";
import { readDownloadInstall } from "./DesktopExportInstall.js";
import { exportDesktopApplication } from "./DesktopApplicationExport.js";
import { draftDesktopApplicationTask } from "./DesktopTaskDraft.js";
import {
DATABASE,
EDITED_NOTE,
HOME,
NOTE,
SETTINGS,
capture,
change,
checkpoint,
@@ -69,26 +74,6 @@ const exportCapture = async (
return { result, directory };
};
/** Export the fixture capture with its package's apt sources replaced. */
const exportWithSources = async (
sources: readonly string[],
origins?: readonly (string | null)[],
) => {
const local = capture();
const { result } = await exportCapture({
...local,
application: {
...local.application,
package: {
...local.application.package,
sources: [...sources],
...(origins === undefined ? {} : { source_origins: [...origins] }),
},
},
});
return result;
};
/** Export the fixture capture walked under other spellings, with its baseline files and files created later. */
const exportWalked = (walk: {
readonly home?: string;
@@ -166,60 +151,130 @@ afterEach(() => {
vi.restoreAllMocks();
});
describe("exportDesktopApplication", () => {
it("writes a computer app bundle with owned paths and the baseline seed", async () => {
const { result, directory } = await exportCapture(capture());
if (result instanceof Error) throw result;
expect(result.operation).toBe("export_desktop_application");
expect(result.normalized_result).toMatchObject({
environment: "notes",
paths: [".config/notes", ".local/share/notes", "Documents"],
seed_files: [".config/notes/settings.ini", ".local/share/notes/notes.db"],
unseeded_files: [],
});
expect(
await readFile(join(directory, "envs/notes/env.toml"), "utf8"),
).toContain('module = "notes_app.py:Notes"');
const module = await readFile(
join(directory, "envs/notes/notes_app.py"),
"utf8",
);
expect(module).toContain('packages=Packages(apt=["notes"])');
expect(module).toContain('window={"class": "Notes"}');
expect(module).toContain("@reset_data");
expect(
await readFile(
join(directory, "envs/notes/seed/.config/notes/settings.ini"),
"utf8",
),
).toBe("[ui]\nwrap=false\n");
});
it.each([
[[], []],
[
["https://ppa.launchpadcontent.net/a/b/ubuntu noble/main amd64 Packages"],
["LP-PPA-a-b"],
],
])(
"refuses an application not installed from the Ubuntu 24.04 archive (%j)",
async (sources, origins) => {
const refused = await exportWithSources(sources, origins);
expect(refused instanceof Error ? refused.message : "").toContain(
"export_desktop_application",
);
it("exports and drafts state from the same capture each cites", async () => {
const local = capture();
const original = {
...local,
application: {
...local.application,
package: {
...local.application.package,
sources: ["http://mirror.local/ubuntu noble/universe amd64 Packages"],
source_origins: ["Ubuntu"],
},
},
};
const folder = await writeCaptureFolder(original);
const capturePath = join(folder, "capture.json");
const originalJson = await readFile(capturePath, "utf8");
const source = safeParseEvidence(JSON.parse(originalJson));
if (!source.ok) throw new Error("Invalid original capture fixture");
const replacement = await writeCaptureFolder({
...original,
state: {
...original.state,
checkpoints: [
checkpoint(
"replacement",
"baseline",
[],
[
retained(SETTINGS, "[ui]\nwrap=true\n"),
retained(DATABASE, "SQLite format 3\0v1"),
],
),
],
},
});
const replacementJson = await readFile(
join(replacement, "capture.json"),
"utf8",
);
const replaceAfterClose = async () => {
const nextCapture = join(folder, "next-capture.json");
await writeFile(nextCapture, replacementJson);
const close = OwnedFileHandle.prototype.close;
return vi
.spyOn(OwnedFileHandle.prototype, "close")
.mockImplementationOnce(async function (this: OwnedFileHandle) {
await close.call(this);
await rename(nextCapture, capturePath);
});
};
const exportRead = await replaceAfterClose();
const directory = join(folder, "bundle");
const result = await exportDesktopApplication(
{ capture: folder, directory, name: undefined, tasks: [] },
readers,
);
it("accepts an application from an Ubuntu 24.04 mirror", async () => {
const result = await exportWithSources(
["http://mirror.local/ubuntu noble/universe amd64 Packages"],
["Ubuntu"],
);
if (result instanceof Error) throw result;
expect(result.operation).toBe("export_desktop_application");
expect(result.parameters.capture_evidence_id).toBe(source.value.evidence_id);
expect(await readFile(capturePath, "utf8")).toBe(replacementJson);
expect(
await readFile(
join(directory, "envs/notes/seed/.config/notes/settings.ini"),
"utf8",
),
).toBe("[ui]\nwrap=false\n");
expect(result.normalized_result).toMatchObject({
environment: "notes",
checkpoints: { seed: "baseline", end: "edited" },
paths: [".config/notes", ".local/share/notes", "Documents"],
seed_files: [".config/notes/settings.ini", ".local/share/notes/notes.db"],
unseeded_files: [],
});
expect(
await readFile(join(directory, "envs/notes/env.toml"), "utf8"),
).toContain('module = "notes_app.py:Notes"');
const module = await readFile(
join(directory, "envs/notes/notes_app.py"),
"utf8",
);
expect(module).toContain('packages=Packages(apt=["notes"])');
expect(module).toContain('window={"class": "Notes"}');
expect(module).toContain("@reset_data");
expect(result).not.toBeInstanceOf(Error);
exportRead.mockRestore();
await writeFile(capturePath, originalJson);
await replaceAfterClose();
const draft = await draftDesktopApplicationTask(folder, readers);
if (draft instanceof Error) throw draft;
expect(draft.parameters.capture_evidence_id).toBe(source.value.evidence_id);
expect(await readFile(capturePath, "utf8")).toBe(replacementJson);
expect(draft.normalized_result).toMatchObject({
checkpoints: { baseline: "baseline", final: "edited" },
task: {
checks: expect.arrayContaining([
expect.objectContaining({ kind: "lines_present", lines: ["milk"] }),
]),
},
});
});
describe("exportDesktopApplication", () => {
it("refuses an unconfigured PPA before writing a bundle", async () => {
const local = capture();
const { result, directory } = await exportCapture({
...local,
application: {
...local.application,
package: {
...local.application.package,
sources: [
"https://ppa.launchpadcontent.net/a/b/ubuntu noble/main amd64 Packages",
],
source_origins: ["LP-PPA-a-b"],
},
},
});
expect(result).toMatchObject({
_tag: "AnalysisInputError",
operation: "export_desktop_application",
issues: [expect.objectContaining({ path: ["capture"] })],
});
expect(await exists(directory)).toBe(false);
});
it("prefixes a derived name the bundle name check refuses", async () => {
@@ -990,6 +1045,13 @@ describe("exportDesktopApplication of lock files and folders the app held files
expect(readme).toContain(
"`~/.config/notes/.lock`, `~/Documents/.~lock.today.txt#`",
);
const heldOpen = result.limitations.find((limitation) =>
limitation.startsWith("The application held files open in"),
);
expect(heldOpen).toContain("held files open in ~/Documents,");
expect(heldOpen).toContain(
"the seed holds ~/Documents/today.txt from there",
);
});
it("seeds project lock files the capture recognized as documents and a lock-named file the caller selected, and leaves out a *.lock file directly in a state directory", async () => {
@@ -1065,19 +1127,6 @@ describe("exportDesktopApplication of lock files and folders the app held files
"~/.config/notes/.lock, ~/.config/notes/db.lock, ~/Documents/.~lock.today.txt#.",
);
});
it("names the seed files under a folder the app held files open in, rather than saying nothing there is seeded", async () => {
const { result } = await exportLocked();
const heldOpen = result.limitations.find((limitation) =>
limitation.startsWith("The application held files open in"),
);
expect(heldOpen).toContain("held files open in ~/Documents,");
expect(heldOpen).toContain(
"the seed holds ~/Documents/today.txt from there",
);
expect(heldOpen).not.toContain("nothing there is seeded");
});
});
describe("exportDesktopApplication of a lock named for the file beside it", () => {
@@ -1204,58 +1253,47 @@ const withWritten = (
};
};
describe("exportDesktopApplication of Poedit's locks and a seed's mode", () => {
it("leaves out a lock in the home and Lucene's write.lock, and never owns the home's lock", async () => {
const index = `${HOME}/.local/share/notes/TranslationMemory`;
const { result } = await exportLocked(
withWritten([
// wxWidgets' single-instance lock, which holds a PID and must stay 0600.
[`${HOME}/poedit.lock`, "4242\n", "opened", 0o600],
[`${index}/write.lock`, "", "state", 0o644],
[`${index}/segments_2`, "seg\n", "state", 0o644],
]),
["4242\n", "", "seg\n"],
);
it("keeps captured seed modes and omits Poedit and Lucene runtime locks", async () => {
const index = `${HOME}/.local/share/notes/TranslationMemory`;
const { result, directory } = await exportLocked(
withWritten([
// wxWidgets' single-instance lock, which holds a PID and must stay 0600.
[`${HOME}/poedit.lock`, "4242\n", "opened", 0o600],
[`${index}/write.lock`, "", "state", 0o644],
[`${index}/segments_2`, "seg\n", "state", 0o644],
[`${HOME}/.config/notes/secret.ini`, "[s]\n", "state", 0o600],
[`${HOME}/.config/notes/run.sh`, "#!/bin/sh\n", "state", 0o755],
]),
["4242\n", "", "seg\n", "[s]\n", "#!/bin/sh\n"],
);
const exported = z
.object({ seed_files: z.array(z.string()), paths: z.array(z.string()) })
.parse(result.normalized_result);
expect(exported.seed_files).toContain(
".local/share/notes/TranslationMemory/segments_2",
);
expect(exported.seed_files).not.toContain("poedit.lock");
expect(exported.seed_files).not.toContain(
".local/share/notes/TranslationMemory/write.lock",
);
expect(exported.paths).not.toContain("poedit.lock");
expect(
result.limitations.find((limitation) =>
limitation.startsWith("Left out of the seed: lock files"),
),
).toContain("~/.local/share/notes/TranslationMemory/write.lock");
// Nothing tells the agent to own the home's lock.
expect(
result.limitations.filter((limitation) =>
limitation.includes("~/poedit.lock"),
),
).toEqual([]);
});
it("keeps a seed file's captured mode when it is not the bundle's 0644", async () => {
const { directory } = await exportLocked(
withWritten([
[`${HOME}/.config/notes/secret.ini`, "[s]\n", "state", 0o600],
[`${HOME}/.config/notes/run.sh`, "#!/bin/sh\n", "state", 0o755],
]),
["[s]\n", "#!/bin/sh\n"],
);
expect(
await readFile(join(directory, "envs/notes/notes_app.py"), "utf8"),
).toContain(
'SEED_MODES = {".config/notes/run.sh": 0o755, ".config/notes/secret.ini": 0o600}',
);
});
const exported = z
.object({ seed_files: z.array(z.string()), paths: z.array(z.string()) })
.parse(result.normalized_result);
expect(exported.seed_files).toContain(
".local/share/notes/TranslationMemory/segments_2",
);
expect(exported.seed_files).not.toContain("poedit.lock");
expect(exported.seed_files).not.toContain(
".local/share/notes/TranslationMemory/write.lock",
);
expect(exported.paths).not.toContain("poedit.lock");
expect(
result.limitations.find((limitation) =>
limitation.startsWith("Left out of the seed: lock files"),
),
).toContain("~/.local/share/notes/TranslationMemory/write.lock");
// Nothing tells the agent to own the home's lock.
expect(
result.limitations.filter((limitation) =>
limitation.includes("~/poedit.lock"),
),
).toEqual([]);
expect(
await readFile(join(directory, "envs/notes/notes_app.py"), "utf8"),
).toContain(
'SEED_MODES = {".config/notes/run.sh": 0o755, ".config/notes/secret.ini": 0o600}',
);
});
describe("exportDesktopApplication of the app's logs", () => {
@@ -1951,11 +1989,18 @@ const exportDownload = async (
};
it("bounds download-install input and preserves cancellation", async () => {
const oversized = await exportDownload(downloadCapture(), {
text: "a".repeat(64 * 1024),
});
expect(oversized.result).toMatchObject({
const path = join(
await createTestTempDirectory("download-install-limit-"),
"install.json",
);
const exact = JSON.stringify(APPIMAGE_INSTALL).padEnd(64 * 1024, " ");
await writeFile(path, exact);
await expect(readDownloadInstall(path)).resolves.toEqual(APPIMAGE_INSTALL);
await writeFile(path, exact + " ");
await expect(readDownloadInstall(path)).rejects.toMatchObject({
_tag: "AnalysisInputError",
userMessage: expect.stringContaining("at most 65536 bytes"),
issues: [expect.objectContaining({ path: ["download_install"] })],
});
const controller = new AbortController();
@@ -2402,8 +2447,10 @@ describe("exportDesktopApplication launch document by a title", () => {
});
});
const FALLBACK_NOTES_COMMAND = `command=["sh", "-c", "cd \\"$HOME\\" 2>/dev/null; exec 'notes'"]`;
describe("exportDesktopApplication launch document", () => {
it("opens the seed's one document when the desktop entry takes files", async () => {
it("opens the sole captured document only when the desktop entry takes files", async () => {
const { result, module, readme } = await exportSeeded("notes %U");
expect(module).toContain(
@@ -2412,8 +2459,35 @@ describe("exportDesktopApplication launch document", () => {
expect(readme).toContain(
"At launch the app opens `~/Documents/today.txt`, the seed's one document.",
);
expect(readme).toContain("`~/Documents/today.txt`");
expect(launchLimitations(result.limitations)).toEqual([]);
expect(result.parameters.synthetic_seed).toBe(false);
expect(
result.limitations.filter(
(line) =>
line.startsWith("The seed is") || line.startsWith("The seed was"),
),
).toEqual([
"The seed is the user's real state at the seed checkpoint; keep the bundle local.",
]);
expect(readme).toContain(
"The seed is the user's real data. Keep this bundle local; do not publish it.",
);
expect(readme).not.toContain("`envs/notes/seed/`");
for (const [exec, reason] of [
["notes", "Exec takes no file"],
[null, "without a desktop entry"],
] as const) {
const fallback = await exportSeeded(exec);
const launch = launchLimitations(fallback.result.limitations);
expect(fallback.module, String(exec)).toContain(FALLBACK_NOTES_COMMAND);
expect(launch, String(exec)).toEqual([expect.stringContaining(reason)]);
expect(
fallback.result.limitations.filter((line) => !launch.includes(line)),
String(exec),
).toEqual(result.limitations);
expect(fallback.readme, String(exec)).toContain(launch[0]);
}
});
it.each([
@@ -2447,24 +2521,6 @@ describe("exportDesktopApplication launch document", () => {
},
);
it.each(["notes", null])(
"launches as captured, and says why in the README and limitations, when Exec is %j",
async (exec) => {
const opened = await exportSeeded("notes %U");
const { result, module, readme } = await exportSeeded(exec);
const launch = launchLimitations(result.limitations);
expect(module).toContain(
`command=["sh", "-c", "cd \\"$HOME\\" 2>/dev/null; exec 'notes'"]`,
);
expect(launch).toHaveLength(1);
expect(
result.limitations.filter((line) => !launch.includes(line)),
).toEqual(opened.result.limitations);
for (const line of launch) expect(readme).toContain(line);
},
);
it("launches as captured from a baseline seed, which holds no document", async () => {
const local = capture();
const { result, directory } = await exportCapture({
@@ -2489,9 +2545,7 @@ describe("exportDesktopApplication launch document", () => {
expect(launchLimitations(result.limitations)).toEqual([]);
expect(
await readFile(join(directory, "envs/notes/notes_app.py"), "utf8"),
).toContain(
`command=["sh", "-c", "cd \\"$HOME\\" 2>/dev/null; exec 'notes'"]`,
);
).toContain(FALLBACK_NOTES_COMMAND);
});
it("names the environment for a desktop entry id ending in a version by the id without it", async () => {
@@ -2518,31 +2572,22 @@ describe("exportDesktopApplication launch document", () => {
expect(result.normalized_result).toMatchObject({ environment: "glabels" });
});
it("says a seed made for the task was made for it, and a captured one is the user's own", async () => {
const made = await exportSeeded("notes %U", { syntheticSeed: true });
const captured = await exportSeeded("notes %U");
const notice = (syntheticSeed: boolean) =>
syntheticSeed
? "The seed was made for this task, not taken from a user's own data; read `envs/notes/seed/` before publishing the bundle."
: "The seed is the user's real data. Keep this bundle local; do not publish it.";
const limitation = (syntheticSeed: boolean) =>
syntheticSeed
? "The seed was made for the task, not taken from a user's own data; read it before publishing the bundle."
: "The seed is the user's real state at the seed checkpoint; keep the bundle local.";
it("identifies synthetic seed provenance in both the Evidence and bundle", async () => {
const { result, readme } = await exportSeeded("notes %U", {
syntheticSeed: true,
});
expect(made.result.parameters).toMatchObject({ synthetic_seed: true });
expect(captured.result.parameters).toMatchObject({ synthetic_seed: false });
for (const [exported, synthetic] of [
[made, true],
[captured, false],
] as const) {
expect(exported.result.limitations).toContain(limitation(synthetic));
expect(exported.result.limitations).not.toContain(limitation(!synthetic));
expect(exported.readme).toContain(notice(synthetic));
expect(exported.readme).not.toContain(notice(!synthetic));
}
expect(made.readme).toContain("`envs/notes/seed/`");
expect(captured.readme).not.toContain("`envs/notes/seed/`");
expect(result.parameters.synthetic_seed).toBe(true);
expect(result.limitations).toContain(
"The seed was made for the task, not taken from a user's own data; read it before publishing the bundle.",
);
expect(result.limitations).not.toContain(
"The seed is the user's real state at the seed checkpoint; keep the bundle local.",
);
expect(readme).toContain(
"The seed was made for this task, not taken from a user's own data; read `envs/notes/seed/` before publishing the bundle.",
);
expect(readme).not.toContain("The seed is the user's real data.");
});
});
@@ -357,12 +357,10 @@ const runExport = async (
readers: DesktopExportReaders,
signal: AbortSignal | undefined,
) => {
const { evidence, capture } = await readDesktopCapture(
request.capture,
signal,
);
const source = await readDesktopCapture(request.capture, signal);
const { evidence, capture } = source;
const stateEvidence = await inspectDesktopApplicationState(
request.capture,
source,
readers,
signal,
{ viewPolicy: request.viewPolicy },
@@ -108,11 +108,17 @@ const inputError = (userMessage: string, remediationAction: string) =>
{ path: ["capture"], reason: "invalid_value", message: userMessage },
]);
interface AdmittedDesktopCapture {
readonly folder: string;
readonly evidence: Evidence;
readonly capture: DesktopApplicationCapture;
}
/** Admit `capture.json` only as complete desktop capture Evidence. */
export const readDesktopCapture = async (
folder: string,
signal: AbortSignal | undefined,
): Promise<{ evidence: Evidence; capture: DesktopApplicationCapture }> => {
): Promise<AdmittedDesktopCapture> => {
const resources = new ArtifactResourceScope();
const outcome = await resources
.run(async () => {
@@ -153,7 +159,7 @@ export const readDesktopCapture = async (
`The capture result is malformed (${describeValidationFailure(capture.error)}).`,
"Capture the application again.",
);
return { evidence: evidence.value, capture: capture.data };
return { folder, evidence: evidence.value, capture: capture.data };
})
.then(ok, (cause: unknown) => err(cause));
try {
@@ -545,13 +551,17 @@ const stateLimitations = (policy: DesktopViewPolicy) => [
/** Read a capture folder into the application's state view. */
const inspectState = async (
folder: string,
source: string | AdmittedDesktopCapture,
readers: DesktopStateReaders,
signal: AbortSignal | undefined,
options: DesktopStateViewOptions,
): Promise<Evidence> => {
const policy = desktopViewPolicy(options.viewPolicy);
const { evidence, capture } = await readDesktopCapture(folder, signal);
const { folder, evidence, capture } =
typeof source === "string"
? await readDesktopCapture(source, signal)
: source;
if (isAborted(signal)) throw cancelledBy(OPERATION, signal);
const names = applicationNames(capture);
const facts = roleFacts(capture);
const index = indexState(capture);
@@ -635,7 +645,7 @@ export interface DesktopStateViewOptions {
/** Inspect one capture folder, returning its state view Evidence or a failure. */
export const inspectDesktopApplicationState = async (
folder: string,
source: string | AdmittedDesktopCapture,
readers: DesktopStateReaders,
signal?: AbortSignal,
options: DesktopStateViewOptions = {},
@@ -650,7 +660,7 @@ export const inspectDesktopApplicationState = async (
admitted.error.issues,
options.viewPolicy,
);
return await inspectState(folder, readers, signal, {
return await inspectState(source, readers, signal, {
...options,
...(options.viewPolicy === undefined
? {}
+3 -2
View File
@@ -63,9 +63,10 @@ const draft = async (
selection: DraftSelection,
viewPolicy: DesktopViewPolicyInput | undefined,
): Promise<Evidence> => {
const { evidence, capture } = await readDesktopCapture(folder, signal);
const source = await readDesktopCapture(folder, signal);
const { evidence, capture } = source;
const stateEvidence = await inspectDesktopApplicationState(
folder,
source,
readers,
signal,
{ viewPolicy },