Skip to content

Commit 7d3b3e6

Browse files
committed
fix(capture): preserve crop outcomes and destination permissions
1 parent 8fd3d8f commit 7d3b3e6

5 files changed

Lines changed: 147 additions & 7 deletions

File tree

‎packages/daemon/src/execution/screenshot-runtime-execution.test.ts‎

Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -507,6 +507,72 @@ for (const failure of ['sparse', 'canceled'] as const) {
507507
}
508508
}
509509

510+
for (const outcome of ['capture failure', 'crop refusal', 'cancellation', 'published'] as const) {
511+
test(`staging cleanup failure preserves ${outcome}`, async () => {
512+
const controller = new AbortController();
513+
const captureFailure = new Error('capture transport failed');
514+
let stagedDirectory: string | undefined;
515+
const fixture = screenshotRuntimeFixture({
516+
onCapture: (input) => {
517+
stagedDirectory = path.dirname(input.outPath);
518+
writeSolidPng(input.outPath);
519+
if (outcome === 'capture failure') throw captureFailure;
520+
},
521+
snapshotResult: () => {
522+
if (outcome === 'cancellation') controller.abort();
523+
return {
524+
nodes: outcome === 'crop refusal' ? [] : CROP_TREE,
525+
backend: 'android',
526+
producer: 'android-uiautomator',
527+
};
528+
},
529+
});
530+
const session = makeSession('default', { device: ANDROID_EMULATOR });
531+
const outPath = path.join(mkdtempForTestSync('crop-cleanup-outcome'), 'capture.png');
532+
const sentinel = Buffer.from('old destination');
533+
fs.writeFileSync(outPath, sentinel);
534+
const req = screenshotRequest({
535+
positionals: [outPath],
536+
flags: { screenshotCropOn: 'label="Save"' },
537+
});
538+
const resolved = await resolveScreenshotGenericExecution({
539+
hostCwd: process.cwd(),
540+
createCommandSurface: testCreateCommandSurface,
541+
platformServices: daemonPlatformServicesFixture(),
542+
req,
543+
session,
544+
inspectFacts: fixture.inspectFacts,
545+
bindDevice: fixture.bindDevice,
546+
});
547+
const remove = fs.promises.rm;
548+
const cleanup = vi.spyOn(fs.promises, 'rm').mockImplementation(async (target, options) => {
549+
if (String(target) === stagedDirectory) throw new Error('staging removal refused');
550+
await remove(target, options);
551+
});
552+
try {
553+
const operation = executeResult(resolved, session, req, { signal: controller.signal });
554+
if (outcome === 'published') {
555+
await expect(operation).resolves.toMatchObject({ path: outPath, width: 40, height: 20 });
556+
expect(fs.readFileSync(outPath)).not.toEqual(sentinel);
557+
} else {
558+
if (outcome === 'capture failure') await expect(operation).rejects.toBe(captureFailure);
559+
if (outcome === 'crop refusal')
560+
await expect(operation).rejects.toMatchObject({
561+
details: { reason: SCREENSHOT_CROP_REASONS.targetNotFound },
562+
});
563+
if (outcome === 'cancellation')
564+
await expect(operation).rejects.toMatchObject({ name: 'AbortError' });
565+
expect(fs.readFileSync(outPath)).toEqual(sentinel);
566+
}
567+
expect(stagedDirectory).toBeDefined();
568+
if (stagedDirectory) expect(fs.existsSync(stagedDirectory)).toBe(true);
569+
} finally {
570+
cleanup.mockRestore();
571+
if (stagedDirectory) fs.rmSync(stagedDirectory, { recursive: true, force: true });
572+
}
573+
});
574+
}
575+
510576
test('a partial crop surfaces its warning once in the result record and annotates nothing', async () => {
511577
const fixture = screenshotRuntimeFixture({
512578
snapshotResult: () => ({

‎packages/daemon/src/execution/screenshot-runtime.ts‎

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import { publishFileSync } from '@agent-device/host-kit/file';
2+
import { emitDiagnostic } from '@agent-device/host-kit/diagnostics';
23
import { expandSessionPath } from '@agent-device/host-kit/session-paths';
34
import type { CommandFlags } from '@agent-device/contracts/command';
45
import {
@@ -10,7 +11,7 @@ import {
1011
import type { DeviceRotation } from '@agent-device/contracts/device';
1112
import type { ScreenshotRuntimeExecution } from '@agent-device/contracts/screenshot-runtime';
1213
import { isIosFamily, publicPlatformString } from '@agent-device/kernel/device';
13-
import { AppError } from '@agent-device/kernel/errors';
14+
import { AppError, errorMessage } from '@agent-device/kernel/errors';
1415
import type { ScreenshotOverlayRef } from '@agent-device/kernel/snapshot';
1516
import { promises as fs } from 'node:fs';
1617
import os from 'node:os';
@@ -420,12 +421,20 @@ function createBoundScreenshotBackend(
420421
const contents = await fs.readFile(capturePath);
421422
dispatchContext.signal?.throwIfAborted();
422423
_context.signal?.throwIfAborted();
423-
publishFileSync({ destination: outPath, contents });
424+
publishFileSync({ destination: outPath, contents, preserveExistingMode: true });
424425
crop.run.warnings.push(...buildScreenshotCropWarnings(outcome));
425426
}
426427
return facts.displayRotation ? { displayRotation: facts.displayRotation } : undefined;
427428
} finally {
428-
if (tempRoot) await fs.rm(tempRoot, { recursive: true, force: true });
429+
if (tempRoot) {
430+
await fs.rm(tempRoot, { recursive: true, force: true }).catch((error: unknown) => {
431+
emitDiagnostic({
432+
level: 'warn',
433+
phase: 'screenshot_crop_cleanup_failed',
434+
data: { tempRoot, error: errorMessage(error) },
435+
});
436+
});
437+
}
429438
}
430439
},
431440
};

‎packages/host-kit/src/internal/atomic-file.test.ts‎

Lines changed: 50 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { describe, expect, test } from 'vitest';
1+
import { describe, expect, test, vi } from 'vitest';
22
import fs from 'node:fs';
33
import path from 'node:path';
44
import { mkdtempForTestSync } from './tmp-dir.fixtures.ts';
@@ -42,4 +42,53 @@ describe('publishFileSync', () => {
4242
const siblings = fs.readdirSync(directory).filter((name) => name.startsWith('clean.txt.'));
4343
expect(siblings).toEqual([]);
4444
});
45+
46+
test.skipIf(process.platform === 'win32').each([0o600, 0o640])(
47+
'preserves existing mode %s before replacing its contents',
48+
(mode) => {
49+
const target = destination(`private-${mode}.png`);
50+
fs.writeFileSync(target, 'private old bytes');
51+
fs.chmodSync(target, mode);
52+
const previousUmask = process.umask(0o077);
53+
try {
54+
publishFileSync({
55+
destination: target,
56+
contents: 'private new bytes',
57+
preserveExistingMode: true,
58+
});
59+
expect(fs.readFileSync(target, 'utf8')).toBe('private new bytes');
60+
expect(fs.statSync(target).mode & 0o777).toBe(mode);
61+
} finally {
62+
process.umask(previousUmask);
63+
}
64+
},
65+
);
66+
67+
test('creates an absent destination when existing-mode preservation is requested', () => {
68+
const target = destination('previously-absent.png');
69+
publishFileSync({ destination: target, contents: 'new bytes', preserveExistingMode: true });
70+
expect(fs.readFileSync(target, 'utf8')).toBe('new bytes');
71+
});
72+
73+
test('a failed permission update leaves the existing destination unchanged', () => {
74+
const target = destination('permission-update-failed.png');
75+
fs.writeFileSync(target, 'old bytes');
76+
const failure = new Error('permission update failed');
77+
const chmod = vi.spyOn(fs, 'chmodSync').mockImplementation(() => {
78+
throw failure;
79+
});
80+
try {
81+
expect(() =>
82+
publishFileSync({ destination: target, contents: 'new bytes', preserveExistingMode: true }),
83+
).toThrow(failure);
84+
expect(fs.readFileSync(target, 'utf8')).toBe('old bytes');
85+
expect(
86+
fs
87+
.readdirSync(directory)
88+
.filter((name) => name.startsWith('permission-update-failed.png.')),
89+
).toEqual([]);
90+
} finally {
91+
chmod.mockRestore();
92+
}
93+
});
4594
});

‎packages/host-kit/src/internal/atomic-file.ts‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,14 +19,21 @@ export function publishFileSync(options: {
1919
destination: string;
2020
contents: string | Uint8Array;
2121
mode?: number;
22+
preserveExistingMode?: boolean;
2223
publish?: AtomicPublishMode;
2324
}): void {
2425
withAtomicPublishTempPathSync(options.destination, (temporaryPath) => {
26+
const existing = options.preserveExistingMode
27+
? fs.statSync(options.destination, { throwIfNoEntry: false })
28+
: undefined;
29+
const preservedMode = existing?.isFile() ? existing.mode & 0o777 : undefined;
30+
const mode = preservedMode ?? options.mode;
2531
const writeOptions = {
2632
encoding: typeof options.contents === 'string' ? ('utf8' as const) : undefined,
27-
...(options.mode === undefined ? {} : { mode: options.mode }),
33+
...(mode === undefined ? {} : { mode }),
2834
};
2935
fs.writeFileSync(temporaryPath, options.contents, writeOptions);
36+
if (preservedMode !== undefined) fs.chmodSync(temporaryPath, preservedMode);
3037
if (options.publish === 'link-exclusive') {
3138
fs.linkSync(temporaryPath, options.destination);
3239
} else {

‎test/integration/provider-scenarios/android-screenshot-crop.test.ts‎

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -92,7 +92,8 @@ for (const destinationExists of [true, false]) {
9292
async (world) => {
9393
await world.daemon.client().apps.open({ app: 'settings', ...world.selection });
9494
const destination = path.join(world.tempRoot, 'crop.png');
95-
if (destinationExists) fs.writeFileSync(destination, 'existing destination');
95+
if (destinationExists)
96+
fs.writeFileSync(destination, 'existing destination', { mode: 0o600 });
9697
const response = await world.daemon.callCommand('screenshot', [destination], {
9798
screenshotCropOn: 'label="Apps"',
9899
});
@@ -101,6 +102,9 @@ for (const destinationExists of [true, false]) {
101102
assert.equal(result.width, 32);
102103
assert.equal(result.height, 24);
103104
assertPngDimensions(destination, 32, 24);
105+
if (destinationExists && process.platform !== 'win32') {
106+
assert.equal(fs.statSync(destination).mode & 0o777, 0o600);
107+
}
104108
},
105109
);
106110
});
@@ -124,7 +128,12 @@ for (const destinationExists of [true, false]) {
124128
const response = await world.daemon.callCommand('screenshot', [destination], {
125129
screenshotCropOn: 'label="Apps"',
126130
});
127-
assert.ok(response.json?.error);
131+
assert.equal(response.json?.error?.data?.code, 'COMMAND_FAILED');
132+
assert.equal(response.json?.error?.message, 'Failed to capture screenshot');
133+
assert.equal(
134+
world.adbCalls.filter((args) => args.join(' ') === 'exec-out screencap -p').length,
135+
1,
136+
);
128137
if (destinationExists) assert.deepEqual(fs.readFileSync(destination), sentinel);
129138
else assert.equal(fs.existsSync(destination), false);
130139
},

0 commit comments

Comments
 (0)