Skip to content

Commit e050817

Browse files
committed
fix(screenshot): publish cropped output after scaling
1 parent 7d3b3e6 commit e050817

7 files changed

Lines changed: 325 additions & 107 deletions

File tree

‎packages/command-runtime/src/commands/capture/runtime/screenshot.ts‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -56,16 +56,18 @@ export const screenshotCommand: RuntimeCommand<
5656
if (options.scale !== undefined) {
5757
await resizePngFileToScale(reserved.path, options.scale);
5858
}
59+
(options.signal ?? runtime.signal)?.throwIfAborted();
5960
artifact = await reserved.publish();
6061
} catch (error) {
6162
await reserved.cleanup?.();
6263
throw error;
6364
}
6465

66+
const outputPath = reserved.publishedPath ?? reserved.path;
6567
return {
66-
path: reserved.path,
68+
path: outputPath,
6769
...(artifact ? { artifacts: [artifact] } : {}),
6870
...(displayRotation ? { displayRotation } : {}),
69-
...successText(`Saved screenshot: ${reserved.path}`),
71+
...successText(`Saved screenshot: ${outputPath}`),
7072
};
7173
};

‎packages/contracts/src/artifact-adapter.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,8 @@ export type ResolvedInputFile = {
5050

5151
export type ReservedOutputFile = {
5252
path: string;
53+
/** The client-visible destination after publication, when work uses a staging path. */
54+
publishedPath?: string;
5355
visibility: OutputVisibility;
5456
publish: () => Promise<ArtifactDescriptor | undefined>;
5557
cleanup?: () => Promise<void>;

‎packages/daemon/src/__tests__/support/screenshot-command-surface-fake.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,8 +31,9 @@ export const screenshotCommandSurface: CreateDaemonCommandSurface = async (confi
3131
surface: options.surface,
3232
},
3333
);
34+
await reserved.publish();
3435
return {
35-
path: reserved.path,
36+
path: reserved.publishedPath ?? reserved.path,
3637
...(captured?.displayRotation ? { displayRotation: captured.displayRotation } : {}),
3738
};
3839
} catch (error) {
Lines changed: 89 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,89 @@
1+
import fs from 'node:fs';
2+
import path from 'node:path';
3+
import { expect, test, vi } from 'vitest';
4+
import { mkdtempForTestSync } from '@agent-device/test-kit';
5+
import { createDaemonScreenshotArtifactAdapter } from './screenshot-artifact-adapter.ts';
6+
7+
const outputOptions = { field: 'path', ext: '.png', artifactType: 'screenshot' as const };
8+
9+
test('crop publication updates the regular symlink target without replacing the link', async () => {
10+
const root = mkdtempForTestSync('crop-symlink');
11+
const destination = path.join(root, 'latest.png');
12+
const target = path.join(root, 'dated.png');
13+
fs.writeFileSync(target, 'previous', { mode: 0o600 });
14+
fs.symlinkSync('dated.png', destination);
15+
const reserved = await createDaemonScreenshotArtifactAdapter(true, undefined).reserveOutput(
16+
{ kind: 'path', path: destination },
17+
outputOptions,
18+
);
19+
try {
20+
fs.writeFileSync(reserved.path, 'complete image');
21+
await reserved.publish();
22+
expect(reserved.publishedPath).toBe(destination);
23+
expect(fs.readlinkSync(destination)).toBe('dated.png');
24+
expect(fs.readFileSync(target, 'utf8')).toBe('complete image');
25+
if (process.platform !== 'win32') expect(fs.statSync(target).mode & 0o777).toBe(0o600);
26+
expect(fs.existsSync(path.dirname(reserved.path))).toBe(false);
27+
} finally {
28+
await reserved.cleanup?.();
29+
}
30+
});
31+
32+
test('a dangling destination symlink is refused without replacing it', async () => {
33+
const root = mkdtempForTestSync('crop-dangling');
34+
const destination = path.join(root, 'latest.png');
35+
fs.symlinkSync('missing.png', destination);
36+
await expect(
37+
createDaemonScreenshotArtifactAdapter(true, undefined).reserveOutput(
38+
{ kind: 'path', path: destination },
39+
outputOptions,
40+
),
41+
).rejects.toMatchObject({
42+
code: 'COMMAND_FAILED',
43+
details: { reason: 'screenshot_publication_failed', filesystemCode: 'ENOENT' },
44+
});
45+
expect(fs.readlinkSync(destination)).toBe('missing.png');
46+
expect(fs.existsSync(path.join(root, 'missing.png'))).toBe(false);
47+
});
48+
49+
test('a directory destination is refused before a capture is reserved', async () => {
50+
const destination = mkdtempForTestSync('crop-directory');
51+
await expect(
52+
createDaemonScreenshotArtifactAdapter(true, undefined).reserveOutput(
53+
{ kind: 'path', path: destination },
54+
outputOptions,
55+
),
56+
).rejects.toMatchObject({
57+
code: 'INVALID_ARGS',
58+
details: { reason: 'screenshot_destination_not_file' },
59+
});
60+
});
61+
62+
for (const existing of [true, false]) {
63+
test(`failed atomic publication preserves the ${existing ? 'existing' : 'absent'} destination with a typed reason`, async () => {
64+
const root = mkdtempForTestSync('crop-publish-failure');
65+
const destination = path.join(root, 'capture.png');
66+
if (existing) fs.writeFileSync(destination, 'previous');
67+
const reserved = await createDaemonScreenshotArtifactAdapter(true, undefined).reserveOutput(
68+
{ kind: 'path', path: destination },
69+
outputOptions,
70+
);
71+
fs.writeFileSync(reserved.path, 'complete image');
72+
const rename = vi.spyOn(fs, 'renameSync').mockImplementation(() => {
73+
throw Object.assign(new Error('disk full'), { code: 'ENOSPC' });
74+
});
75+
try {
76+
await expect(reserved.publish()).rejects.toMatchObject({
77+
code: 'COMMAND_FAILED',
78+
details: { reason: 'screenshot_publication_failed', filesystemCode: 'ENOSPC' },
79+
});
80+
if (existing) expect(fs.readFileSync(destination, 'utf8')).toBe('previous');
81+
else expect(fs.existsSync(destination)).toBe(false);
82+
expect(fs.readdirSync(root)).toEqual(existing ? ['capture.png'] : []);
83+
} finally {
84+
rename.mockRestore();
85+
await reserved.cleanup?.();
86+
}
87+
expect(fs.existsSync(path.dirname(reserved.path))).toBe(false);
88+
});
89+
}
Lines changed: 133 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,133 @@
1+
import { publishFileSync } from '@agent-device/host-kit/file';
2+
import { emitDiagnostic } from '@agent-device/host-kit/diagnostics';
3+
import type { ArtifactAdapter, ReservedOutputFile } from '@agent-device/contracts/artifact-adapter';
4+
import { AppError, errorMessage } from '@agent-device/kernel/errors';
5+
import { promises as fs } from 'node:fs';
6+
import os from 'node:os';
7+
import path from 'node:path';
8+
9+
export function createDaemonScreenshotArtifactAdapter(
10+
atomic: boolean,
11+
signal: AbortSignal | undefined,
12+
): ArtifactAdapter {
13+
return {
14+
resolveInput: async () => {
15+
throw new AppError('UNSUPPORTED_OPERATION', 'screenshot does not resolve input artifacts');
16+
},
17+
reserveOutput: async (ref) => {
18+
try {
19+
let tempRoot: string | undefined;
20+
let outputPath: string;
21+
if (ref?.kind === 'path') {
22+
outputPath = ref.path;
23+
} else {
24+
tempRoot = await fs.mkdtemp(path.join(os.tmpdir(), 'agent-device-screenshot-'));
25+
outputPath = path.join(tempRoot, 'screenshot.png');
26+
}
27+
await fs.mkdir(path.dirname(outputPath), { recursive: true });
28+
if (atomic && ref?.kind === 'path') {
29+
return await reserveCroppedOutput(outputPath, signal);
30+
}
31+
return {
32+
path: outputPath,
33+
visibility: 'client-visible',
34+
publish: async () => undefined,
35+
...(tempRoot
36+
? {
37+
cleanup: async () => {
38+
await fs.rm(tempRoot, { recursive: true, force: true });
39+
},
40+
}
41+
: {}),
42+
};
43+
} catch (error) {
44+
if (error instanceof AppError) throw error;
45+
throw screenshotPublicationError(
46+
error,
47+
ref?.kind === 'path' ? ref.path : '(temporary screenshot)',
48+
);
49+
}
50+
},
51+
createTempFile: async (options) => {
52+
const root = await fs.mkdtemp(path.join(os.tmpdir(), `${options.prefix}-`));
53+
return {
54+
path: path.join(root, `file${options.ext}`),
55+
visibility: 'internal',
56+
cleanup: async () => {
57+
await fs.rm(root, { recursive: true, force: true });
58+
},
59+
};
60+
},
61+
};
62+
}
63+
64+
function screenshotPublicationError(error: unknown, outputPath: string): AppError {
65+
return new AppError('COMMAND_FAILED', 'Failed to publish screenshot', {
66+
reason: 'screenshot_publication_failed',
67+
path: outputPath,
68+
...(error instanceof Error && 'code' in error ? { filesystemCode: error.code } : {}),
69+
cause: errorMessage(error),
70+
});
71+
}
72+
73+
async function reserveCroppedOutput(
74+
outputPath: string,
75+
signal: AbortSignal | undefined,
76+
): Promise<ReservedOutputFile> {
77+
const destination = await resolveScreenshotDestination(outputPath);
78+
const stagingRoot = await fs.mkdtemp(path.join(os.tmpdir(), 'agent-device-crop-'));
79+
const stagingPath = path.join(stagingRoot, `screenshot${path.extname(outputPath) || '.png'}`);
80+
const cleanup = async () => {
81+
await fs.rm(stagingRoot, { recursive: true, force: true }).catch((error: unknown) => {
82+
emitDiagnostic({
83+
level: 'warn',
84+
phase: 'screenshot_crop_cleanup_failed',
85+
data: { tempRoot: stagingRoot, error: errorMessage(error) },
86+
});
87+
});
88+
};
89+
return {
90+
path: stagingPath,
91+
publishedPath: outputPath,
92+
visibility: 'client-visible',
93+
publish: async () => {
94+
try {
95+
const contents = await fs.readFile(stagingPath);
96+
signal?.throwIfAborted();
97+
publishFileSync({ destination, contents, preserveExistingMode: true });
98+
} catch (error) {
99+
if (signal?.aborted) throw signal.reason;
100+
throw screenshotPublicationError(error, outputPath);
101+
}
102+
await cleanup();
103+
return undefined;
104+
},
105+
cleanup,
106+
};
107+
}
108+
109+
async function resolveScreenshotDestination(outputPath: string): Promise<string> {
110+
let destination: string;
111+
try {
112+
const entry = await fs.lstat(outputPath).catch((error: NodeJS.ErrnoException) => {
113+
if (error.code === 'ENOENT') return undefined;
114+
throw error;
115+
});
116+
destination = entry?.isSymbolicLink() ? await fs.realpath(outputPath) : outputPath;
117+
const target = await fs.stat(destination).catch((error: NodeJS.ErrnoException) => {
118+
if (error.code === 'ENOENT') return undefined;
119+
throw error;
120+
});
121+
if (target && !target.isFile()) {
122+
throw new AppError('INVALID_ARGS', 'Screenshot destination must be a regular file', {
123+
reason: 'screenshot_destination_not_file',
124+
path: outputPath,
125+
});
126+
}
127+
} catch (error) {
128+
if (error instanceof AppError) throw error;
129+
throw screenshotPublicationError(error, outputPath);
130+
}
131+
132+
return destination;
133+
}

0 commit comments

Comments
 (0)