Skip to content

Turn any idea, plan, or codebase into a beautiful interactive diagram. An agent skill for Claude Code, Codex, and more.

fix: preserve UNC browser URLs and release evidence bindings

sunsunsun26a37f6b7cd6
diff --git a/archify.zip b/archify.zip
index 6b8c7ffa..31d1bb73 100644
Binary files a/archify.zip and b/archify.zip differ
diff --git a/archify/bin/visual-check.mjs b/archify/bin/visual-check.mjs
index 58089ccd..47b4a443 100644
--- a/archify/bin/visual-check.mjs
+++ b/archify/bin/visual-check.mjs
@@ -953,7 +953,13 @@ function commitVisualEvidence(artifactPath, outputs, ownership, desiredPaths) {
for (const [finalPath, binding] of stagedBindings) {
const released = releaseRegularFileBinding(binding);
if (released.status !== 'released') {
- failures.push({ file: finalPath, reason: released.reason?.code });
+ failures.push({
+ file: finalPath,
+ reason: released.reason?.code,
+ bindingState: released.reason,
+ ...(released.reason?.recoveryDirectory
+ ? { recoveryDirectory: released.reason.recoveryDirectory } : {}),
+ });
}
}
stagedBindings.clear();
@@ -978,8 +984,10 @@ function commitVisualEvidence(artifactPath, outputs, ownership, desiredPaths) {
reason: captured?.reason?.code || 'staged entry missing or changed',
}],
);
- releaseStagedBindings();
- cleanupStagedEvidence(ownership, { removeDirectory: true });
+ failure.diagnostic.evidence.errors.push(
+ ...releaseStagedBindings(),
+ ...cleanupStagedEvidence(ownership, { removeDirectory: true }),
+ );
ownership.active = false;
return failure;
}
@@ -1144,7 +1152,9 @@ function commitVisualEvidence(artifactPath, outputs, ownership, desiredPaths) {
}
}
- const cleanupErrors = [];
+ // SMB keeps removed staging names pending until every bound handle closes.
+ // Publication and backup verification are complete before directory cleanup.
+ const cleanupErrors = releaseStagedBindings();
for (const backup of backups) {
const removed = unlinkOwnedEntry(backup.path, backup.identity, {
evidence: backup.evidence,
@@ -1234,6 +1244,7 @@ function commitVisualEvidence(artifactPath, outputs, ownership, desiredPaths) {
}
}
for (const backup of [...backups].reverse()) restoreOwnedBackup(backup, rollbackErrors);
+ rollbackErrors.push(...releaseStagedBindings());
rollbackErrors.push(...cleanupStagedEvidence(ownership, { removeDirectory: true }));
ownership.active = false;
if (conflict) {
@@ -1467,6 +1478,22 @@ async function evaluate(cdp, sessionId, expression, awaitPromise = false) {
return response.result?.value;
}
+export function chromeVisualArtifactUrl(artifactPath, theme, { platform = process.platform } = {}) {
+ const localhostUnc = platform === 'win32'
+ ? /^(?:\\\\\?\\UNC\\|\\\\)localhost\\(.+)$/i.exec(artifactPath)
+ : null;
+ if (localhostUnc) {
+ // WHATWG file URLs erase the localhost host, turning this UNC share into
+ // a drive-root path. Chromium retains the raw host for non-drive paths.
+ // Send this string directly to DevTools without reparsing it as a URL.
+ const encodedPath = localhostUnc[1].split('\\').map(encodeURIComponent).join('/');
+ return 'file://localhost/' + encodedPath + '?' + new URLSearchParams({ theme });
+ }
+ const url = pathToFileURL(artifactPath);
+ url.searchParams.set('theme', theme);
+ return url.href;
+}
+
export class ChromeVisualBrowser {
constructor(chromePath, {
env = process.env,
@@ -1524,14 +1551,13 @@ export class ChromeVisualBrowser {
mobile: false,
}, sessionId);
- const url = new URL(pathToFileURL(artifactPath).href);
- url.searchParams.set('theme', theme);
+ const url = chromeVisualArtifactUrl(artifactPath, theme);
const loaded = this.cdp.waitFor('Page.loadEventFired', sessionId);
// Navigation can fail before this waiter is awaited. Attach a rejection
// handler immediately so a later load failure never escapes as an
// unhandled rejection; awaiting `loaded` below still reports it normally.
loaded.catch(() => {});
- const navigation = await this.cdp.send('Page.navigate', { url: url.href }, sessionId);
+ const navigation = await this.cdp.send('Page.navigate', { url }, sessionId);
if (navigation.errorText) throw new Error(`Chrome navigation failed: ${navigation.errorText}`);
await loaded;
await evaluate(this.cdp, sessionId, `(function () {
diff --git a/archify/test/visual-check-browser-url.test.mjs b/archify/test/visual-check-browser-url.test.mjs
new file mode 100644
index 00000000..abf9760f
--- /dev/null
+++ b/archify/test/visual-check-browser-url.test.mjs
@@ -0,0 +1,55 @@
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+import path from 'node:path';
+import { pathToFileURL } from 'node:url';
+
+import { ChromeVisualBrowser, chromeVisualArtifactUrl } from '../bin/visual-check.mjs';
+
+test('Chrome inspection preserves localhost UNC shares instead of treating them as drive-root paths', () => {
+ for (const prefix of [String.raw`\\localhost`, String.raw`\\?\UNC\localhost`]) {
+ const artifact = `${prefix}\\share\\nested folder\\图 #%25.html`;
+ assert.equal(
+ chromeVisualArtifactUrl(artifact, 'dark', { platform: 'win32' }),
+ 'file://localhost/share/nested%20folder/%E5%9B%BE%20%23%2525.html?theme=dark',
+ );
+ }
+});
+
+test('Chrome inspection preserves localhost UNC paths beyond MAX_PATH', () => {
+ const directories = Array.from({ length: 10 }, (_, index) => `long-directory-${index}-${'x'.repeat(20)}`);
+ const artifact = `\\\\?\\UNC\\LOCALHOST\\share\\${directories.join('\\')}\\artifact-snapshot.html`;
+ assert.ok(artifact.length > 320);
+ assert.equal(
+ chromeVisualArtifactUrl(artifact, 'light', { platform: 'win32' }),
+ `file://localhost/share/${directories.join('/')}/artifact-snapshot.html?theme=light`,
+ );
+});
+
+test('Chrome inspection retains native file URL escaping and theme query semantics', () => {
+ const artifact = path.resolve('图 # 100%.html');
+ const expected = pathToFileURL(artifact);
+ expected.searchParams.set('theme', 'dark&unintended=value');
+ assert.equal(chromeVisualArtifactUrl(artifact, 'dark&unintended=value'), expected.href);
+});
+
+test('Chrome inspection sends the localhost UNC URL directly to DevTools without recanonicalizing it', async () => {
+ const artifact = String.raw`\\?\UNC\localhost\share\artifact-snapshot.html`;
+ const browser = Object.create(ChromeVisualBrowser.prototype);
+ const calls = [];
+ browser.sessionPromise = Promise.resolve('test-session');
+ browser.cdp = {
+ waitFor: () => Promise.resolve(),
+ async send(method, parameters) {
+ calls.push({ method, parameters });
+ return method === 'Page.navigate' ? { errorText: 'stop after navigation' } : {};
+ },
+ };
+ const platformDescriptor = Object.getOwnPropertyDescriptor(process, 'platform');
+ try {
+ Object.defineProperty(process, 'platform', { ...platformDescriptor, value: 'win32' });
+ await assert.rejects(browser.inspect({ artifactPath: artifact, width: 1440, height: 900, theme: 'dark' }), /stop after navigation/);
+ } finally {
+ Object.defineProperty(process, 'platform', platformDescriptor);
+ }
+ assert.equal(calls.find(({ method }) => method === 'Page.navigate').parameters.url, 'file://localhost/share/artifact-snapshot.html?theme=dark');
+});
diff --git a/archify/test/visual-check.test.mjs b/archify/test/visual-check.test.mjs
index bb3c2a03..7040fb43 100644
--- a/archify/test/visual-check.test.mjs
+++ b/archify/test/visual-check.test.mjs
@@ -2092,6 +2092,108 @@ test('visual-check retries transient remote ENOTEMPTY during staging cleanup', a
assert.deepEqual(stagingDirectories(outputDirectory), []);
});
+for (const scenario of ['successful evidence set', 'failure receipt', 'publication rollback']) {
+ test(`visual-check closes staged bindings before SMB cleanup for ${scenario}`, async (t) => {
+ const input = artifact(`smb-binding-cleanup-${scenario.replaceAll(' ', '-')}.html`);
+ const outDir = fs.mkdtempSync(path.join(tmp, 'smb-binding-cleanup-'));
+ t.after(() => fs.rmSync(outDir, { recursive: true, force: true }));
+ const openSync = fs.openSync.bind(fs);
+ const closeSync = fs.closeSync.bind(fs);
+ const renameSync = fs.renameSync.bind(fs);
+ const rmdirSync = fs.rmdirSync.bind(fs);
+ const linkSync = fs.linkSync.bind(fs);
+ const descriptors = new Map();
+ const quarantines = new Map();
+ let deferredRemovals = 0;
+ let publicationFailed = false;
+ const identityKey = (stat) => `${stat.dev}:${stat.ino}`;
+ t.mock.method(fs, 'openSync', (...args) => {
+ const descriptor = openSync(...args);
+ descriptors.set(descriptor, identityKey(fs.fstatSync(descriptor, { bigint: true })));
+ return descriptor;
+ });
+ t.mock.method(fs, 'closeSync', (descriptor) => {
+ closeSync(descriptor);
+ descriptors.delete(descriptor);
+ });
+ t.mock.method(fs, 'renameSync', (source, destination) => {
+ const directory = path.dirname(String(destination));
+ if (path.basename(directory).startsWith('.archify-remove-')) {
+ quarantines.set(directory, identityKey(fs.lstatSync(source, { bigint: true })));
+ }
+ return renameSync(source, destination);
+ });
+ t.mock.method(fs, 'rmdirSync', (directory, ...args) => {
+ const identity = quarantines.get(String(directory));
+ if (identity && [...descriptors.values()].includes(identity)) {
+ deferredRemovals += 1;
+ throw Object.assign(new Error('SMB deletion remains pending while a file handle is open'), {
+ code: 'ENOTEMPTY',
+ });
+ }
+ return rmdirSync(directory, ...args);
+ });
+ if (scenario === 'publication rollback') {
+ t.mock.method(fs, 'linkSync', (source, destination) => {
+ if (!publicationFailed && path.basename(String(source)) === 'capture-0.png') {
+ publicationFailed = true;
+ throw new Error('synthetic screenshot publication failure');
+ }
+ return linkSync(source, destination);
+ });
+ }
+
+ const result = await runVisualCheck({
+ artifactPath: input,
+ outDir,
+ chromePath: '/fake/chrome',
+ browserFactory: async () => fakeBrowser({
+ screenshotFailure: () => scenario === 'failure receipt',
+ }),
+ });
+
+ assert.ok(deferredRemovals > 0, 'the fixture must exercise an open-handle SMB deletion delay');
+ assert.equal(result.exitCode, scenario === 'successful evidence set' ? 0 : 1);
+ assert.equal(publicationFailed, scenario === 'publication rollback');
+ assert.deepEqual(stagingDirectories(outDir), []);
+ assert.equal(descriptors.size, 0);
+ assert.doesNotMatch(JSON.stringify(result.receipt.diagnostics), /ENOTEMPTY|cleanup is incomplete/);
+ });
+}
+
+test('visual-check reports a claimant retained by deferred staging cleanup', async (t) => {
+ const input = artifact('smb-binding-cleanup-claimant.html');
+ const outDir = fs.mkdtempSync(path.join(tmp, 'smb-cleanup-claimant-'));
+ t.after(() => fs.rmSync(outDir, { recursive: true, force: true }));
+ const rmdirSync = fs.rmdirSync.bind(fs);
+ const sentinel = 'external claimant retained during deferred cleanup\n';
+ let claimantPath;
+ t.mock.method(fs, 'rmdirSync', (directory, ...args) => {
+ if (!claimantPath && path.basename(String(directory)).startsWith('.archify-remove-')) {
+ claimantPath = path.join(directory, 'external-claimant');
+ fs.writeFileSync(claimantPath, sentinel, { flag: 'wx' });
+ }
+ return rmdirSync(directory, ...args);
+ });
+
+ const result = await runVisualCheck({
+ artifactPath: input,
+ outDir,
+ chromePath: '/fake/chrome',
+ browserFactory: async () => fakeBrowser(),
+ });
+
+ assert.equal(result.exitCode, 1);
+ assert.equal(result.receipt.publication?.status, 'committed-with-warning');
+ assert.equal(fs.readFileSync(claimantPath, 'utf8'), sentinel);
+ const cleanupError = result.receipt.publication.cleanupErrors.find(
+ (entry) => entry.recoveryDirectory === path.dirname(claimantPath),
+ );
+ assert.equal(cleanupError?.reason, 'removal-quarantine-cleanup-failed');
+ assert.equal(cleanupError?.bindingState.systemCode, 'ENOTEMPTY');
+ assert.equal(result.receipt.diagnostics.at(-1)?.code, 'viewer/evidence-cleanup-incomplete');
+});
+
test('visual-check rolls back when staged evidence changes after receipt binding', async (t) => {
const input = artifact('staged-content-changed-after-receipt-binding.html');
const outputs = sidecarPaths(input);