Open-source, local-first social media research agent for Instagram, TikTok, and LinkedIn. Jev routes read-only steps; socai CLI captures cited browser evidence.
JavaScript agent-skillsai-agentsbrowser-agentbrowser-automationdecision-modeldeep-researchinstagramjevlinkedinlocal-firstopen-sourceosintresearch-agentsocaisocial-listeningsocial-mediasocial-media-researchsocmintsystem-onetiktok
feat: add download report.md button to evidence report section
Barshan Majumdar4e3375dc76d9
diff --git a/package.json b/package.jsonindex baea9f4..f38aa28 100644--- a/package.json+++ b/package.json@@ -27,7 +27,7 @@"scripts": {"start": "node ./bin/jev-social.js","dev": "node --watch ./bin/jev-social.js serve --no-open",- "check": "node --check ./bin/jev-social.js && node --check ./src/server.js && node --check ./public/app.js",+ "check": "node --check ./bin/jev-social.js && node --check ./src/server.js && node --check ./public/app.js && node --check ./public/report-download.js","test": "node --test"},"engines": {diff --git a/public/app.js b/public/app.jsindex 73eb268..6cfbc20 100644--- a/public/app.js+++ b/public/app.js@@ -1,3 +1,9 @@+import {+ downloadReport,+ getReportMarkdown,+ isReportDownloadable,+} from "./report-download.js";+const $ = (selector) => document.querySelector(selector);const elements = {searchView: $("#search-view"),@@ -13,6 +19,7 @@ const elements = {evidenceTable: $("#evidence-table"),reportSection: $("#research-report-section"),output: $("#socai-output"),+ downloadReportBtn: $("#download-report"),elapsed: $("#elapsed-time"),dialog: $("#detail-dialog"),detail: $("#detail-content"),@@ -21,6 +28,7 @@ const elements = {let timer;let startedAt = 0;let activeController;+let currentRun;elements.searchForm.addEventListener("submit", async (event) => {event.preventDefault();@@ -54,6 +62,16 @@ $("#back-to-search").addEventListener("click", () => {if (location.hash === "#results") history.back();else showSearchView();});+elements.downloadReportBtn?.addEventListener("click", () => {+ const fallbackReport = elements.output?.dataset?.markdown || elements.output?.textContent || "";+ const report = currentRun ? getReportMarkdown(currentRun) : fallbackReport;+ if (!isReportDownloadable(report)) return;+ downloadReport({ run: currentRun, report });+});+if (typeof window !== "undefined") {+ window.renderRun = renderRun;+ window.downloadReport = downloadReport;+}$("#close-detail").addEventListener("click", () => elements.dialog.close());elements.dialog.addEventListener("click", (event) => {if (event.target === elements.dialog) elements.dialog.close();@@ -125,6 +143,11 @@ function showResultView({ push = false } = {}) {function showSearchView() {activeController?.abort();+ currentRun = undefined;+ if (elements.downloadReportBtn) {+ elements.downloadReportBtn.disabled = true;+ elements.downloadReportBtn.classList.add("hidden");+ }elements.resultView.classList.add("hidden");elements.searchView.classList.remove("hidden");elements.activity.classList.add("hidden");@@ -174,6 +197,7 @@ function clearError() {}function renderRun(run) {+ showResultView();elements.activity.classList.add("hidden");elements.resultView.classList.remove("has-live-evidence", "is-running");elements.reportSection.classList.remove("hidden");@@ -204,13 +228,26 @@ function renderRun(run) {}});}+ currentRun = run;renderTable(items);- renderMarkdown(elements.output, run.report || run.finalSocaiOutput || "socai completed without a report.");+ const reportMarkdown = getReportMarkdown(run);+ if (elements.output) elements.output.dataset.markdown = reportMarkdown;+ const canDownload = isReportDownloadable(reportMarkdown);+ if (elements.downloadReportBtn) {+ elements.downloadReportBtn.disabled = !canDownload;+ elements.downloadReportBtn.classList.toggle("hidden", !canDownload);+ }+ renderMarkdown(elements.output, reportMarkdown || "socai completed without a report.");revealReport(elements.output);elements.result.classList.remove("hidden");}function resetLiveWorkspace() {+ currentRun = undefined;+ if (elements.downloadReportBtn) {+ elements.downloadReportBtn.disabled = true;+ elements.downloadReportBtn.classList.add("hidden");+ }$("#run-status").textContent = "";$("#action-list").replaceChildren();elements.resultView.classList.remove("has-live-evidence");diff --git a/public/index.html b/public/index.htmlindex f2b0879..6059954 100644--- a/public/index.html+++ b/public/index.html@@ -5,6 +5,9 @@<meta name="viewport" content="width=device-width, initial-scale=1" /><meta name="color-scheme" content="light" /><title>Jev × socai · social research</title>+ <link rel="preconnect" href="https://fonts.googleapis.com" />+ <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />+ <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&family=Roboto+Mono:wght@500;700;800&display=swap" /><link rel="stylesheet" href="/styles.css" /></head><body>@@ -92,7 +95,13 @@</section><section id="research-report-section" class="report-section">- <div class="section-head"><p class="eyebrow">EVIDENCE REPORT</p><span>Sources and captured details</span></div>+ <div class="section-head">+ <div>+ <p class="eyebrow">EVIDENCE REPORT</p>+ <span>Sources and captured details</span>+ </div>+ <button id="download-report" class="report-download-btn hidden" type="button" disabled>Download report.md</button>+ </div><article id="socai-output" class="research-report"></article><details id="action-history"><summary>Steps chosen by Jev</summary><ol id="action-list"></ol></details></section>diff --git a/public/report-download.js b/public/report-download.jsnew file mode 100644index 0000000..3e0e914--- /dev/null+++ b/public/report-download.js@@ -0,0 +1,238 @@+/**+ * Client-side report download helpers.+ *+ * Provides safe filename generation, Markdown sanitization to redact local+ * filesystem paths and raw run JSON, and browser download triggering.+ */++/**+ * Generate a safe, human-readable filename for an evidence report.+ *+ * @param {object|string} [source] - A run object, options object, or query string.+ * @param {object} [options]+ * @param {string} [options.query]+ * @param {string} [options.platform]+ * @returns {string} Safe filename ending with '.md'.+ */+export function generateReportFilename(source = {}, options = {}) {+ let query = "";+ let platform = "";++ if (typeof source === "string") {+ query = source;+ platform = options.platform || "";+ } else if (source && typeof source === "object") {+ query = source.query || source.request || options.query || "";+ platform = source.platform || source.requestedPlatform || options.platform || "";+ }++ const safePlatform = typeof platform === "string"+ ? platform.trim().toLowerCase().replace(/[^a-z0-9]/g, "")+ : "";++ const cleanQuery = stripFilesystemPaths(query);+ let slug = slugify(cleanQuery);++ if (slug.length > 50) {+ slug = slug.slice(0, 50).replace(/-[^-]*$/, "");+ if (!slug) slug = slugify(cleanQuery).slice(0, 50);+ }++ if (safePlatform && safePlatform !== "auto") {+ if (slug.startsWith(`${safePlatform}-`)) {+ slug = slug.slice(safePlatform.length + 1);+ } else if (slug === safePlatform) {+ slug = "";+ }+ }++ const parts = ["report"];+ if (safePlatform && safePlatform !== "auto") {+ parts.push(safePlatform);+ }+ if (slug) {+ parts.push(slug);+ }++ return `${parts.join("-")}.md`;+}++/**+ * Strip filesystem paths, drive letters, and traversal patterns from input text.+ *+ * @param {string} text+ * @returns {string}+ */+export function stripFilesystemPaths(text) {+ if (typeof text !== "string") return "";+ return text+ .replace(/file:\/\/\/[^\s"'`<>)]*\/+/gi, " ")+ .replace(/\b[A-Za-z]:[/\\]+(?:[^/\s"'`<>)]+[/\\]+)*/g, " ")+ .replace(/(?:^|[\s("'`])(?:\/(?:Users|home|tmp|var|private|etc|usr|opt|bin|Windows|Program Files)\/(?:[^/\s"'`<>)]+[/\\]+)*)/gi, " ")+ .replace(/(?:\.{1,2}[/\\]+)+/g, " ")+ .replace(/[/\\]+/g, " ")+ .replace(/\s+/g, " ")+ .trim();+}++/**+ * Create a clean, filename-safe slug from text while preserving Unicode letters/numbers.+ *+ * @param {string} text+ * @returns {string}+ */+export function slugify(text) {+ if (typeof text !== "string") return "";+ return text+ .normalize("NFKD")+ .toLowerCase()+ .replace(/[^\p{L}\p{N}]+/gu, "-")+ .replace(/^-+|-+$/g, "");+}++/**+ * Sanitize Markdown report text before downloading or displaying.+ * Redacts any local filesystem paths and rejects raw run JSON dumps.+ *+ * @param {string} raw - Markdown content.+ * @returns {string} Sanitized UTF-8 Markdown text.+ */+export function sanitizeReportMarkdown(raw) {+ if (typeof raw !== "string") return "";+ let text = raw;++ // Do not expose raw run JSON payload if accidentally supplied as a string+ const trimmed = text.trim();+ if (trimmed.startsWith("{") && trimmed.endsWith("}")) {+ try {+ const parsed = JSON.parse(trimmed);+ if (parsed && typeof parsed === "object") {+ if (typeof parsed.report === "string" && parsed.report.trim()) {+ text = parsed.report;+ } else if (typeof parsed.finalSocaiOutput === "string" && parsed.finalSocaiOutput.trim()) {+ text = parsed.finalSocaiOutput;+ } else {+ return "";+ }+ }+ } catch {+ // not valid JSON, treat as standard text+ }+ }++ // Redact file:// URLs+ text = text.replace(/file:\/\/\/[^\s"'`<>)]+/gi, "[redacted path]");++ // Redact Windows absolute paths+ text = text.replace(/\b[A-Za-z]:\\[^\s"'`<>)\r\n]+/g, "[redacted path]");+ text = text.replace(/\b[A-Za-z]:\/[^\s"'`<>)\r\n]+/g, "[redacted path]");++ // Redact Unix absolute paths in common roots+ text = text.replace(/(^|[\s("'`])(\/(?:Users|home|tmp|var|private|etc|usr|opt|bin|Windows|Program Files)\/[^\s"'`<>)\r\n]*)/gi, (match, prefix) => {+ return `${prefix}[redacted path]`;+ });++ // Redact common path variable assignments+ text = text.replace(/\b((?:run_dir|local_path|output_dir|artifact_path|report_path)\s*[:=]\s*)([^\s\r\n]+)/gi, "$1[redacted path]");++ return text;+}++/**+ * Extract downloadable Markdown text from a run object or string.+ * Returns empty string if no valid report is available.+ *+ * @param {object|string} run+ * @returns {string}+ */+export function getReportMarkdown(run) {+ if (!run) return "";+ if (typeof run === "string") {+ const trimmed = run.trim();+ if (!trimmed || trimmed === "socai completed without a report.") return "";+ return sanitizeReportMarkdown(run);+ }+ if (typeof run === "object") {+ const candidate = typeof run.report === "string" && run.report.trim()+ ? run.report+ : typeof run.finalSocaiOutput === "string" && run.finalSocaiOutput.trim()+ ? run.finalSocaiOutput+ : "";+ if (!candidate || candidate === "socai completed without a report.") return "";+ return sanitizeReportMarkdown(candidate);+ }+ return "";+}++/**+ * Determine whether a run object or string has a non-empty, downloadable report.+ *+ * @param {object|string} source+ * @returns {boolean}+ */+export function isReportDownloadable(source) {+ const markdown = typeof source === "string" ? source.trim() : getReportMarkdown(source);+ if (!markdown) return false;+ if (markdown === "socai completed without a report.") return false;+ return markdown.length > 0;+}++/**+ * Download the report as a UTF-8 Markdown file in the browser,+ * or return the sanitized payload when running in headless/test environments.+ *+ * @param {object} [options]+ * @param {object} [options.run] - Full run object.+ * @param {string} [options.report] - Raw markdown report text.+ * @param {string} [options.filename] - Custom filename override.+ * @param {object} [options.document] - Injectable Document for testing.+ * @param {function} [options.Blob] - Injectable Blob constructor for testing.+ * @param {object} [options.URL] - Injectable URL interface for testing.+ * @returns {object} Result descriptor { ok: boolean, filename?: string, content?: string, size?: number, error?: string }+ */+export function downloadReport(options = {}) {+ const run = options.run || (options.report ? null : options);+ const rawReport = options.report || getReportMarkdown(run);+ const content = sanitizeReportMarkdown(rawReport);++ if (!isReportDownloadable(content)) {+ return { ok: false, error: "No non-empty report available for download." };+ }++ const filename = options.filename || generateReportFilename(run || options);+ return downloadMarkdownFile(filename, content, options);+}++/**+ * Trigger client-side download of UTF-8 Markdown content.+ *+ * @param {string} filename+ * @param {string} content+ * @param {object} [options]+ * @returns {object}+ */+export function downloadMarkdownFile(filename, content, options = {}) {+ const doc = options.document || (typeof document !== "undefined" ? document : null);+ const BlobClass = options.Blob || (typeof Blob !== "undefined" ? Blob : null);+ const urlInterface = options.URL || (typeof URL !== "undefined" ? URL : null);++ if (!doc || !BlobClass || !urlInterface?.createObjectURL) {+ return { ok: true, filename, content, clientSide: false };+ }++ const blob = new BlobClass([content], { type: "text/markdown;charset=utf-8" });+ const objectUrl = urlInterface.createObjectURL(blob);+ const anchor = doc.createElement("a");+ anchor.href = objectUrl;+ anchor.download = filename;+ anchor.hidden = true;+ doc.body.append(anchor);+ anchor.click();+ anchor.remove();++ if (typeof urlInterface.revokeObjectURL === "function") {+ setTimeout(() => urlInterface.revokeObjectURL(objectUrl), 1500);+ }++ return { ok: true, filename, size: blob.size, clientSide: true };+}diff --git a/public/styles.css b/public/styles.cssindex f8162ab..940605e 100644--- a/public/styles.css+++ b/public/styles.css@@ -7,8 +7,8 @@--pink: #ff2ea6;--pink-soft: #ffd3ec;--green: #17a66a;- --mono: "SFMono-Regular", Consolas, "Liberation Mono", monospace;- --sans: Inter, "Helvetica Neue", Arial, sans-serif;+ --mono: "Roboto Mono", "SFMono-Regular", Consolas, "Liberation Mono", Menlo, monospace;+ --sans: "Inter", -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;}* { box-sizing: border-box; }@@ -69,7 +69,7 @@ h1 em { color: transparent; font-style: normal; -webkit-text-stroke: 1.5px var(-.result-view { min-height: 0; display: flex; flex-direction: column; background: #fff; }.result-toolbar { flex: 0 0 76px; display: grid; grid-template-columns: 180px 1fr 180px; align-items: center; gap: 20px; padding: 0 22px; border-bottom: 1px solid var(--ink); background: var(--ice); }.result-heading { min-width: 0; text-align: center; }-.result-heading h2 { margin: 5px 0 0; overflow: hidden; font-size: 15px; font-weight: 700; text-overflow: ellipsis; white-space: nowrap; }+.result-heading h2 { margin: 5px 0 0; overflow: hidden; font: 700 15px/1.2 var(--mono); letter-spacing: -.03em; text-overflow: ellipsis; white-space: nowrap; }.back-button { justify-self: start; border: 0; padding: 8px 0; background: transparent; font: 700 11px var(--mono); }.time-readout { justify-self: end; display: grid; text-align: right; }.time-readout small { color: var(--muted); font: 8px var(--mono); letter-spacing: .13em; }@@ -93,8 +93,12 @@ h1 em { color: transparent; font-style: normal; -webkit-text-stroke: 1.5px var(-.result-canvas { flex: 1; min-height: 0; overflow-y: auto; padding: 24px; background: #fff; }.canvas-head, .section-head { display: flex; align-items: end; justify-content: space-between; gap: 20px; }-.canvas-head h3 { margin: 5px 0 0; font-size: 22px; letter-spacing: -.035em; }-.canvas-head > span, .section-head > span { color: var(--muted); font: 8px var(--mono); letter-spacing: .08em; text-transform: uppercase; }+.canvas-head h3 { margin: 5px 0 0; font: 800 20px/1.2 var(--mono); letter-spacing: -.035em; }+.canvas-head > span, .section-head > span, .section-head span { color: var(--muted); font: 8px var(--mono); letter-spacing: .08em; text-transform: uppercase; }+.report-download-btn { display: inline-flex; align-items: center; justify-content: center; min-height: 32px; padding: 0 12px; border: 1px solid var(--ink); background: #fff; color: var(--ink); font: 700 10px/1 var(--mono); letter-spacing: .04em; text-transform: uppercase; cursor: pointer; white-space: nowrap; transition: transform .12s ease, box-shadow .12s ease; }+.report-download-btn:hover:not(:disabled) { transform: translate(-1px, -1px); box-shadow: 2px 2px 0 var(--pink); }+.report-download-btn:active:not(:disabled) { transform: translate(0, 0); box-shadow: none; }+.report-download-btn:disabled { opacity: .4; cursor: not-allowed; pointer-events: none; }.cards { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 14px; margin-top: 16px; }.waiting-evidence { grid-column: 1 / -1; min-height: 120px; display: grid; place-items: center; border: 1px dashed var(--line); color: var(--muted); background: linear-gradient(180deg, var(--paper), #fff); font: 10px var(--mono); animation: waiting-pulse 1.8s ease-in-out infinite; }@keyframes waiting-pulse { 50% { color: var(--ink); border-color: var(--pink); } }@@ -133,9 +137,13 @@ td { line-height: 1.45; }tr:last-child td { border-bottom: 0; }.report-section { margin-top: 30px; }.research-report { padding: clamp(22px, 4vw, 42px); border: 1px solid var(--line); background: linear-gradient(180deg, #f7fcff 0%, #fff 34%); box-shadow: 0 14px 50px rgba(43, 69, 91, .08); }-.research-report h2, .research-report h3, .research-report h4, .research-report h5 { margin: 1.3em 0 .55em; letter-spacing: -.025em; }+.research-report h2, .research-report h3, .research-report h4, .research-report h5 { margin: 1.4em 0 .6em; color: var(--ink); font-family: var(--mono); letter-spacing: -.03em; }.research-report h2:first-child, .research-report h3:first-child { margin-top: 0; }-.research-report p, .research-report li { color: #313843; font: 14px/1.75 var(--sans); }+.research-report h2 { font-size: 20px; font-weight: 800; border-bottom: 1px solid var(--line); padding-bottom: 8px; }+.research-report h3 { font-size: 15px; font-weight: 750; }+.research-report h4 { font-size: 13px; font-weight: 700; }+.research-report p, .research-report li { color: #2b313a; font: 14px/1.75 var(--sans); letter-spacing: -.01em; }+.research-report strong { color: var(--ink); font-weight: 700; }.research-report ul { margin: .5em 0 1.25em; padding-left: 1.4em; }.research-report ol { margin: .5em 0 1.25em; padding-left: 1.4em; }.research-report a { color: #c90075; text-decoration-thickness: 1px; text-underline-offset: 3px; }@@ -176,12 +184,15 @@ tr:last-child td { border-bottom: 0; }.result-canvas { padding: 16px; }.detail-content { grid-template-columns: 1fr; }.detail-content .detail-media { min-height: 360px; }+ .report-section .section-head { flex-wrap: wrap; gap: 12px; }}@media (max-width: 500px) {.top-actions a { padding: 0 9px; font-size: 8px; }.result-heading .eyebrow { display: none; }.time-readout strong { font-size: 15px; }.cards { grid-template-columns: 1fr; }+ .report-section .section-head { flex-direction: column; align-items: stretch; gap: 10px; }+ .report-download-btn { width: 100%; min-height: 36px; }}@media (prefers-reduced-motion: reduce) {.gradient-scan, .spinner, .activity-message.message-swap, .card-enter, .card-update, .waiting-evidence { animation: none; }diff --git a/src/process.js b/src/process.jsindex 1795b11..228fbab 100644--- a/src/process.js+++ b/src/process.js@@ -85,7 +85,13 @@ export function runProcess(command, args, options = {}) {reject(error);return;}- const child = spawn(command, args, {+ let spawnCommand = command;+ let spawnArgs = args;+ if (process.platform === "win32" && /\.[cm]?js$/i.test(command)) {+ spawnCommand = process.execPath;+ spawnArgs = [command, ...args];+ }+ const child = spawn(spawnCommand, spawnArgs, {cwd,env: childEnvironment(env),windowsHide: true,diff --git a/src/server.js b/src/server.jsindex e9e0e8f..a09335a 100644--- a/src/server.js+++ b/src/server.js@@ -20,6 +20,10 @@ const STATIC_FILES = {"/": ["index.html", "text/html; charset=utf-8"],"/app.js": ["app.js", "text/javascript; charset=utf-8"],"/styles.css": ["styles.css", "text/css; charset=utf-8"],+ "/report-download.js": ["report-download.js", "text/javascript; charset=utf-8"],+ "/platforms/instagram.png": ["platforms/instagram.png", "image/png"],+ "/platforms/tiktok.png": ["platforms/tiktok.png", "image/png"],+ "/platforms/linkedin.svg": ["platforms/linkedin.svg", "image/svg+xml"],};export async function startServer({ port = 8766, open = true, env = process.env } = {}) {@@ -59,6 +63,10 @@ async function handleRequest(request, response, env, mediaRegistry) {? await serveMedia(request, response, media): sendJson(response, 404, { error: { code: "MEDIA_NOT_FOUND", message: "Media not found." } });}+ if (request.method === "GET" && url.pathname === "/favicon.ico") {+ response.writeHead(204, { "Cache-Control": "public, max-age=86400" });+ return response.end();+ }if (request.method === "GET" && STATIC_FILES[url.pathname]) {const [filename, contentType] = STATIC_FILES[url.pathname];const content = await readFile(path.join(PUBLIC_DIR, filename));@@ -67,7 +75,7 @@ async function handleRequest(request, response, env, mediaRegistry) {"Cache-Control": "no-store","X-Content-Type-Options": "nosniff","Content-Security-Policy":- "default-src 'self'; img-src 'self' https: data:; media-src 'self' https: blob:; style-src 'self'; script-src 'self'; connect-src 'self'; base-uri 'none'; form-action 'self'; frame-ancestors 'none'",+ "default-src 'self'; img-src 'self' https: data:; media-src 'self' https: blob:; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; font-src 'self' https://fonts.gstatic.com; script-src 'self'; connect-src 'self'; base-uri 'none'; form-action 'self'; frame-ancestors 'none'",});return response.end(content);}diff --git a/test/report-download.test.js b/test/report-download.test.jsnew file mode 100644index 0000000..7222bd9--- /dev/null+++ b/test/report-download.test.js@@ -0,0 +1,269 @@+import assert from "node:assert/strict";+import test from "node:test";+import {+ downloadMarkdownFile,+ downloadReport,+ generateReportFilename,+ getReportMarkdown,+ isReportDownloadable,+ sanitizeReportMarkdown,+ slugify,+ stripFilesystemPaths,+} from "../public/report-download.js";++test("generateReportFilename produces safe and readable Markdown filenames", () => {+ assert.equal(generateReportFilename(), "report.md");+ assert.equal(generateReportFilename(""), "report.md");+ assert.equal(generateReportFilename({}), "report.md");++ assert.equal(+ generateReportFilename({ query: "emerging AI creators", platform: "instagram" }),+ "report-instagram-emerging-ai-creators.md",+ );+ assert.equal(+ generateReportFilename({ query: "wearable devices", platform: "tiktok" }),+ "report-tiktok-wearable-devices.md",+ );+ assert.equal(+ generateReportFilename({ query: "AI product managers", platform: "linkedin" }),+ "report-linkedin-ai-product-managers.md",+ );++ // Platform "auto" is omitted from the filename prefix+ assert.equal(+ generateReportFilename({ query: "find robotics startups", platform: "auto" }),+ "report-find-robotics-startups.md",+ );++ // Platform only (no query or empty query)+ assert.equal(+ generateReportFilename({ platform: "instagram" }),+ "report-instagram.md",+ );++ // Avoid duplicating platform if the query already starts with it+ assert.equal(+ generateReportFilename({ query: "tiktok viral dances", platform: "tiktok" }),+ "report-tiktok-viral-dances.md",+ );+ assert.equal(+ generateReportFilename({ query: "tiktok", platform: "tiktok" }),+ "report-tiktok.md",+ );++ // Unicode support+ assert.equal(+ generateReportFilename({ query: "寻找人工智能创作者", platform: "tiktok" }),+ "report-tiktok-寻找人工智能创作者.md",+ );++ // Strips directory traversals and unsafe path separators+ assert.equal(+ generateReportFilename({ query: "../../etc/passwd", platform: "instagram" }),+ "report-instagram-etc-passwd.md",+ );+ assert.equal(+ generateReportFilename({ query: "C:\\Windows\\System32\\cmd.exe", platform: "linkedin" }),+ "report-linkedin-cmd-exe.md",+ );+ assert.equal(+ generateReportFilename({ query: "test<foo>:bar*baz?qux\"one|two" }),+ "report-test-foo-bar-baz-qux-one-two.md",+ );++ // Long queries are truncated cleanly without trailing hyphens+ const longQuery = "a-very-long-search-query-that-exceeds-the-maximum-allowed-slug-length-for-file-naming";+ const filename = generateReportFilename({ query: longQuery, platform: "tiktok" });+ assert.ok(filename.length < 80);+ assert.match(filename, /^report-tiktok-[a-z0-9-]+[a-z0-9]\.md$/);+ assert.ok(!filename.includes("--"));+});++test("stripFilesystemPaths removes local path indicators and drive letters", () => {+ assert.equal(stripFilesystemPaths("file:///Users/demo/report.json"), "report.json");+ assert.equal(stripFilesystemPaths("C:\\Users\\demo\\report.json"), "report.json");+ assert.equal(stripFilesystemPaths("D:/projects/jev-social/data.txt"), "data.txt");+ assert.equal(stripFilesystemPaths("/tmp/private/run_123"), "run_123");+ assert.equal(stripFilesystemPaths("/Users/alice/Library/notes.md"), "notes.md");+ assert.equal(stripFilesystemPaths("../../sensitive/file"), "sensitive file");+ assert.equal(stripFilesystemPaths("normal search terms"), "normal search terms");+});++test("slugify creates normalized hyphen-separated slugs preserving Unicode characters", () => {+ assert.equal(slugify("Hello World!"), "hello-world");+ assert.equal(slugify(" multiple spaces and---hyphens "), "multiple-spaces-and-hyphens");+ assert.equal(slugify("Café & Croissant"), "cafe-croissant");+ assert.equal(slugify("人工智能 2026"), "人工智能-2026");+ assert.equal(slugify(""), "");+});++test("sanitizeReportMarkdown redacts local filesystem paths and preserves valid markdown/URLs", () => {+ const input = [+ "# Captured evidence",+ "",+ "Request: Emerging creators",+ "",+ "[Source](https://www.instagram.com/p/abc/)",+ "",+ "Execution info: run_dir: /tmp/private/run-987",+ "Evidence stored at local_path: /Users/alice/Library/Caches/jev/media.mp4",+ "Windows path: C:\\Users\\Barshan\\AppData\\Local\\Temp\\socai\\run.log",+ "File URI: file:///tmp/scratch/debug.txt",+ "",+ "Normal text and https://tiktok.com/@creator/video/123 remain intact.",+ ].join("\n");++ const sanitized = sanitizeReportMarkdown(input);++ // Markdown structure and HTTP URLs must be preserved+ assert.match(sanitized, /# Captured evidence/);+ assert.match(sanitized, /\[Source\]\(https:\/\/www\.instagram\.com\/p\/abc\/\)/);+ assert.match(sanitized, /https:\/\/tiktok\.com\/@creator\/video\/123/);++ // Local filesystem paths must be redacted+ assert.ok(!sanitized.includes("/tmp/private/run-987"));+ assert.ok(!sanitized.includes("/Users/alice/Library/Caches"));+ assert.ok(!sanitized.includes("C:\\Users\\Barshan"));+ assert.ok(!sanitized.includes("file:///tmp/scratch"));+ assert.match(sanitized, /run_dir:\s*\[redacted path\]/);+ assert.match(sanitized, /local_path:\s*\[redacted path\]/);+ assert.match(sanitized, /\[redacted path\]/);+});++test("sanitizeReportMarkdown rejects raw run JSON dumps without a report", () => {+ const rawRunJson = JSON.stringify({+ id: "run-12345",+ status: "completed",+ actions: [{ command: "socai instagram search" }],+ result: { items: [] },+ });++ // A raw run object with no report string must NOT be dumped to the file+ assert.equal(sanitizeReportMarkdown(rawRunJson), "");++ // If a JSON string with an embedded report is passed, only the report is extracted+ const jsonWithReport = JSON.stringify({+ id: "run-12345",+ report: "# Evidence report\nFound 5 creators.",+ });+ assert.equal(sanitizeReportMarkdown(jsonWithReport), "# Evidence report\nFound 5 creators.");+});++test("getReportMarkdown and isReportDownloadable accurately detect downloadable reports", () => {+ assert.equal(isReportDownloadable(null), false);+ assert.equal(isReportDownloadable(undefined), false);+ assert.equal(isReportDownloadable(""), false);+ assert.equal(isReportDownloadable(" "), false);+ assert.equal(isReportDownloadable("socai completed without a report."), false);+ assert.equal(isReportDownloadable({}), false);+ assert.equal(isReportDownloadable({ status: "failed" }), false);+ assert.equal(isReportDownloadable({ report: "" }), false);+ assert.equal(isReportDownloadable({ report: " " }), false);+ assert.equal(isReportDownloadable({ report: "socai completed without a report." }), false);++ const validRun = {+ request: "AI creators",+ platform: "tiktok",+ report: "# Captured evidence\n\nRequest: AI creators\n- Item 1",+ };+ assert.equal(isReportDownloadable(validRun), true);+ assert.equal(getReportMarkdown(validRun), "# Captured evidence\n\nRequest: AI creators\n- Item 1");++ // Fallback to finalSocaiOutput if report field is absent+ const outputRun = {+ request: "AI creators",+ finalSocaiOutput: "# From output\nFound evidence.",+ };+ assert.equal(isReportDownloadable(outputRun), true);+ assert.equal(getReportMarkdown(outputRun), "# From output\nFound evidence.");+});++test("downloadReport returns structured metadata in headless environments without errors", () => {+ // Empty / unavailable report+ const emptyResult = downloadReport({ report: "" });+ assert.equal(emptyResult.ok, false);+ assert.match(emptyResult.error, /No non-empty report/);++ // Valid report with run object+ const run = {+ query: "wearable AI",+ platform: "tiktok",+ report: "# Evidence\nTikTok results.\nlocal_path: /tmp/secret.mp4",+ };+ const result = downloadReport({ run });+ assert.equal(result.ok, true);+ assert.equal(result.filename, "report-tiktok-wearable-ai.md");+ assert.equal(result.clientSide, false);+ assert.match(result.content, /# Evidence/);+ assert.ok(!result.content.includes("/tmp/secret.mp4"));+ assert.match(result.content, /\[redacted path\]/);+});++test("downloadMarkdownFile interacts with DOM and Blob APIs when present", () => {+ let createdBlobContent = null;+ let createdBlobType = null;+ class MockBlob {+ constructor(parts, options) {+ createdBlobContent = parts.join("");+ createdBlobType = options?.type;+ this.size = Buffer.byteLength(createdBlobContent, "utf8");+ }+ }++ let createdUrl = null;+ let revokedUrl = null;+ const mockURL = {+ createObjectURL(blob) {+ createdUrl = `blob:http://127.0.0.1/${Math.random()}`;+ return createdUrl;+ },+ revokeObjectURL(url) {+ revokedUrl = url;+ },+ };++ let appendedChild = null;+ let clicked = false;+ let removed = false;+ const mockAnchor = {+ href: "",+ download: "",+ style: {},+ click() {+ clicked = true;+ },+ remove() {+ removed = true;+ },+ };++ const mockDocument = {+ createElement(tag) {+ assert.equal(tag, "a");+ return mockAnchor;+ },+ body: {+ append(element) {+ appendedChild = element;+ },+ },+ };++ const result = downloadMarkdownFile("test-report.md", "# Findings\n- Item", {+ document: mockDocument,+ Blob: MockBlob,+ URL: mockURL,+ });++ assert.equal(result.ok, true);+ assert.equal(result.clientSide, true);+ assert.equal(result.filename, "test-report.md");+ assert.equal(createdBlobContent, "# Findings\n- Item");+ assert.equal(createdBlobType, "text/markdown;charset=utf-8");+ assert.equal(mockAnchor.download, "test-report.md");+ assert.equal(mockAnchor.href, createdUrl);+ assert.equal(mockAnchor.hidden, true);+ assert.equal(clicked, true);+ assert.equal(removed, true);+ assert.equal(appendedChild, mockAnchor);+});