Skip to content

Instantly share code, notes, and snippets.

@mayesidev
Created October 26, 2026 09:43
Show Gist options
  • Select an option

  • Save mayesidev/42693b6090414a549f89f9464873adac to your computer and use it in GitHub Desktop.

Select an option

Save mayesidev/42693b6090414a549f89f9464873adac to your computer and use it in GitHub Desktop.
T3 Code desktop preview download isolation: reproduction and sanitized before/after evidence
Desktop preview download isolation reproduction
The before/after transcripts use the original 7,167-byte Solarized theme fixture. The standalone script uses a small valid theme JSON payload; the destination defect does not depend on the payload.
Install the checkout dependencies with vp i, then run the script using that checkout's Electron executable. First argument: repository root. Second argument: upstream (record the old behavior) or fixed (assert the corrected app destination). Example from the repository root:
t3_download_probe_electron="$(cd apps/desktop && node -e 'process.stdout.write(require("electron"))')"
env -u ELECTRON_RUN_AS_NODE "$t3_download_probe_electron" /path/to/reproduce.cjs "$PWD" fixed
The script imports the actual DesktopBrowserHost and uses Playwright connectOverCDP through its relay. It creates disposable app/preview windows, an isolated Electron profile, and a loopback-only WebSocket. It selects save destinations programmatically, checks exact preview-download contents, and tests active/hidden/released preview states and cancellation. On the fixed source it additionally checks preview denial/reallow. The native Settings/save-dialog flow was checked separately by the reporter, who selected the destination and whose saved output was verified byte for byte. Windows/Linux runtime verification was not performed.
{
"platform": "macOS 27.0.1 arm64",
"electron": "44.9.3",
"chromium": "152.0.7977.167",
"themeFixtureBytes": 7167,
"results": [
{
"phase": "preview-active",
"state": "completed",
"selectedPathExists": true,
"unexpectedTemporaryFileCount": 0
},
{
"phase": "preview-item",
"filename": "solarized.json",
"placed": true
},
{
"phase": "preview-copy",
"failure": null,
"suggestedFilename": "solarized.json",
"bytes": 7167,
"contentsMatch": true
},
{
"phase": "preview-hidden",
"state": "completed",
"selectedPathExists": true,
"unexpectedTemporaryFileCount": 0
},
{
"phase": "app-cancelled",
"state": "cancelled",
"selectedPathExists": false,
"unexpectedTemporaryFileCount": 0
},
{
"phase": "preview-denied-app-export",
"state": "completed",
"selectedPathExists": true,
"unexpectedTemporaryFileCount": 0
},
{
"phase": "preview-item",
"filename": "denied.txt",
"placed": false
},
{
"phase": "preview-denied",
"failure": "canceled"
},
{
"phase": "preview-item",
"filename": "restored.json",
"placed": true
},
{
"phase": "preview-allowed-again",
"failure": null,
"contentsMatch": true
},
{
"phase": "relay-released",
"state": "completed",
"selectedPathExists": true,
"unexpectedTemporaryFileCount": 0
}
]
}
{
"platform": "macOS 27.0.1 arm64",
"electron": "44.9.3",
"chromium": "152.0.7977.167",
"themeFixtureBytes": 7167,
"results": [
{
"phase": "preview-active",
"state": "completed",
"selectedPathExists": false,
"unexpectedTemporaryFileCount": 1
},
{
"phase": "preview-item",
"filename": "solarized.json",
"placed": true
},
{
"phase": "preview-copy",
"failure": null,
"suggestedFilename": "solarized.json",
"bytes": 7167,
"contentsMatch": true
},
{
"phase": "preview-hidden",
"state": "completed",
"selectedPathExists": false,
"unexpectedTemporaryFileCount": 1
},
{
"phase": "app-cancelled",
"state": "cancelled",
"selectedPathExists": false,
"unexpectedTemporaryFileCount": 0
},
{
"phase": "relay-released",
"state": "completed",
"selectedPathExists": false,
"unexpectedTemporaryFileCount": 1
}
]
}
const { app, BrowserWindow } = require("electron");
const fs = require("node:fs");
const path = require("node:path");
const { pathToFileURL } = require("node:url");
const { createRequire } = require("node:module");
const repo = path.resolve(process.argv[2] || process.cwd());
const source = path.join(repo, "apps/desktop/src/preview");
const label = process.argv[3] || "fixed";
const own = createRequire(path.join(repo, "apps/desktop/package.json"));
const playwright = own("playwright-core");
const { wsServer: WebSocketServer } = own(
path.join(path.dirname(own.resolve("playwright-core")), "lib/utilsBundle.js"),
);
const root = fs.mkdtempSync(path.join(require("node:os").tmpdir(), `t3-download-${label}-`));
app.setPath("userData", path.join(root, "profile"));
const contents = JSON.stringify({
version: 1,
id: "download-probe",
name: "Download Probe",
appearance: "light",
colors: { canvas: "#fdfdfd" },
variants: { dark: { canvas: "#101014" } },
});
const rows = [];
const timer = setTimeout(() => {
console.log(JSON.stringify({ label, root, timeout: true, rows }));
app.exit(2);
}, 30000);
app
.whenReady()
.then(async () => {
const Effect = await import(pathToFileURL(own.resolve("effect/Effect")).href);
const Stream = await import(pathToFileURL(own.resolve("effect/Stream")).href);
const Host = await import(pathToFileURL(path.join(source, "DesktopBrowserHost.ts")).href);
const host = await Effect.runPromise(Host.make);
const key = { threadId: "download-probe", tabId: "preview-probe" };
const main = new BrowserWindow({
show: false,
webPreferences: { sandbox: true, contextIsolation: true, nodeIntegration: false },
});
const guest = new BrowserWindow({
show: false,
webPreferences: { partition: "persist:download-probe", sandbox: true },
});
await main.loadURL("data:text/html,<title>App export</title>");
await guest.loadURL("data:text/html,<title>Preview export</title>");
guest.webContents.debugger.attach("1.3");
host.attach(key, { webContents: guest.webContents, debugger: guest.webContents.debugger });
let socket;
let downloadPath;
let ready;
const attached = new Promise((resolve) => {
ready = resolve;
});
const subscription = Effect.runFork(
Stream.runForEach(host.events, (line) =>
Effect.sync(() => {
const event = JSON.parse(new TextDecoder().decode(line));
if (event.type === "attached") ready();
if (event.type === "cdp" && socket?.readyState === 1) socket.send(event.message);
}),
),
);
await attached;
const server = new WebSocketServer({ host: "127.0.0.1", port: 0 });
await new Promise((resolve) => server.once("listening", resolve));
server.on("connection", (ws) => {
socket = ws;
ws.on("message", (raw) => {
const message = JSON.parse(raw.toString());
if (
message.method === "Browser.setDownloadBehavior" &&
typeof message.params.downloadPath === "string"
)
downloadPath = message.params.downloadPath;
Effect.runPromise(
host.handleCommandLine(JSON.stringify({ type: "cdp", ...key, message: raw.toString() })),
).catch((e) => {
rows.push({ error: String(e) });
app.exit(1);
});
});
ws.on("close", () => {
Effect.runPromise(
host.handleCommandLine(JSON.stringify({ type: "release", ...key })),
).catch(() => {});
});
});
guest.webContents.session.on("will-download", (_e, item, source) => {
const placed = host.placeDownload(source, item);
rows.push({
phase: "preview-item",
filename: item.getFilename(),
placed,
path: item.getSavePath(),
});
});
const browser = await playwright.chromium.connectOverCDP(
`ws://127.0.0.1:${server.address().port}`,
{ timeout: 10000 },
);
const page = browser.contexts()[0].pages()[0];
async function mainExport(phase, cancel = false) {
const selected = path.join(root, phase + ".json");
const before = new Set(fs.existsSync(downloadPath) ? fs.readdirSync(downloadPath) : []);
const completed = new Promise((resolve) =>
main.webContents.session.once("will-download", (_e, item, source) => {
const misplaced = host.placeDownload(source, item);
if (misplaced) throw new Error("Preview captured app download");
item.once("done", (_e, state) => resolve(state));
if (cancel) item.cancel();
else item.setSavePath(selected);
}),
);
await main.webContents.executeJavaScript(
`(()=>{const a=document.createElement('a');a.href=URL.createObjectURL(new Blob([${JSON.stringify(contents)}],{type:'application/json'}));a.download='solarized.json';a.click()})()`,
true,
);
const state = await completed;
const diverted = fs.existsSync(downloadPath)
? fs.readdirSync(downloadPath).filter((name) => !before.has(name))
: [];
const saved = fs.existsSync(selected);
rows.push({ phase, state, selectedPathExists: saved, divertedFiles: diverted });
if (label === "fixed" && !cancel && (!saved || state !== "completed" || diverted.length))
throw new Error("App export was redirected");
if (cancel && (saved || state !== "cancelled" || diverted.length))
throw new Error("Cancellation produced a file");
}
await mainExport("preview-active");
const downloaded = page.waitForEvent("download");
await page.evaluate((text) => {
const a = document.createElement("a");
a.href = URL.createObjectURL(new Blob([text], { type: "application/json" }));
a.download = "solarized.json";
a.click();
}, contents);
const download = await downloaded;
const copy = path.join(root, "preview-copy.json");
await download.saveAs(copy);
const failure = await download.failure();
rows.push({
phase: "preview-copy",
failure,
suggestedFilename: download.suggestedFilename(),
bytes: fs.statSync(copy).size,
contentsMatch: fs.readFileSync(copy, "utf8") === contents,
});
if (failure || fs.readFileSync(copy, "utf8") !== contents)
throw new Error("Preview capture failed");
guest.hide();
await mainExport("preview-hidden");
await mainExport("app-cancelled", true);
if (label === "fixed") {
const cdp = await browser.newBrowserCDPSession();
await cdp.send("Browser.setDownloadBehavior", { behavior: "deny", eventsEnabled: true });
await mainExport("preview-denied-app-export");
const deniedEvent = page.waitForEvent("download");
await page.evaluate(() => {
const a = document.createElement("a");
a.href = URL.createObjectURL(new Blob(["denied"]));
a.download = "denied.txt";
a.click();
});
const denied = await deniedEvent;
rows.push({ phase: "preview-denied", failure: await denied.failure() });
await cdp.send("Browser.setDownloadBehavior", {
behavior: "allowAndName",
downloadPath,
eventsEnabled: true,
});
const restoredEvent = page.waitForEvent("download");
await page.evaluate((text) => {
const a = document.createElement("a");
a.href = URL.createObjectURL(new Blob([text], { type: "application/json" }));
a.download = "restored.json";
a.click();
}, contents);
const restored = await restoredEvent;
const restoredPath = path.join(root, "restored-preview.json");
await restored.saveAs(restoredPath);
if (fs.readFileSync(restoredPath, "utf8") !== contents)
throw new Error("Preview download did not recover after denial");
rows.push({
phase: "preview-allowed-again",
failure: await restored.failure(),
contentsMatch: true,
});
}
await browser.close();
await mainExport("relay-released");
const report = {
label,
root,
source,
electron: process.versions.electron,
chrome: process.versions.chrome,
rows,
};
fs.writeFileSync(path.join(root, "transcript.json"), JSON.stringify(report, null, 2));
console.log(JSON.stringify(report));
clearTimeout(timer);
server.close();
guest.destroy();
main.destroy();
app.quit();
})
.catch((error) => {
console.log(JSON.stringify({ label, root, error: String(error), stack: error.stack, rows }));
app.exit(1);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment