Skip to content

Open-source, local-first social media research agent for Instagram, TikTok, and LinkedIn. Jev routes read-only steps; socai CLI captures cited browser evidence.

fix(preflight): expose CLI capabilities safely (#25)

Ayush_Kumar_Singh46c0db23864b
diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md
index ff2a3c0..9021c08 100644
--- a/docs/troubleshooting.md
+++ b/docs/troubleshooting.md
@@ -12,13 +12,13 @@ Jev Social directs your Chrome browser through the [socai](https://github.com/so
> ```bash
> # macOS / Linux (inspect paths)
> echo "Jev Social runs: ${JEV_SOCIAL_HOME:-$HOME/.jev-social}/runs"
-> SOCAI_CONFIG_RUNS="$(/path/from-api-status config get runs.dir 2>/dev/null)"
+> SOCAI_CONFIG_RUNS="$(/path/from-status config get runs.dir 2>/dev/null)"
> echo "socai artifacts: ${SOCAI_RUNS_DIR:-${SOCAI_CONFIG_RUNS:-$HOME/.socai/runs}}"
> ```
> ```powershell
> # Windows PowerShell (inspect paths)
> $jevDir = if ($env:JEV_SOCIAL_HOME) { Join-Path $env:JEV_SOCIAL_HOME "runs" } else { "$HOME\.jev-social\runs" }
-> $configuredRuns = (& /path/from-api-status config get runs.dir 2>$null)
+> $configuredRuns = (& /path/from-status config get runs.dir 2>$null)
> $socaiDir = if ($env:SOCAI_RUNS_DIR) { $env:SOCAI_RUNS_DIR } elseif ($configuredRuns) { $configuredRuns } else { "$HOME\.socai\runs" }
> Write-Host "Jev Social runs: $jevDir"
> Write-Host "socai artifacts: $socaiDir"
@@ -59,7 +59,7 @@ By default (using `existing` or `managed` Chrome modes without external endpoint
Run these diagnostic commands to verify readiness without exposing API credentials or browser secrets:
-### 1. Check Configuration & Capabilities via `/api/status`
+### 1. Check Configuration & Capabilities
Jev Social resolves your OpenRouter key from `OPENROUTER_API_KEY`, lowercase `openrouter` in `.env`, or saved onboarding config (`config.json`). Checking only `$OPENROUTER_API_KEY` in your shell can falsely report "missing" when a key is already configured.
@@ -69,21 +69,7 @@ Query the local status endpoint to verify the effective `jevConfigured` state an
curl -s http://127.0.0.1:8766/api/status
```
-> [!NOTE]
-> **Privacy note:** `/api/status` returns `configPath` and `socai.bin`. If sharing output in public issues or chat, redact these local filesystem paths.
-
-To inspect status with local paths filtered out, pipe the response through Node or `jq`:
-
-```bash
-# Filtered diagnostic (Node.js)
-curl -s http://127.0.0.1:8766/api/status | node -e '
- const fs = require("fs");
- const { jevConfigured, jevModel, socai } = JSON.parse(fs.readFileSync(0, "utf8"));
- console.log(JSON.stringify({ jevConfigured, jevModel, socai: { installed: socai?.installed, capabilities: socai?.capabilities } }, null, 2));
-'
-```
-
-Expected output on an official `socai v0.6+` build (or a development build with social commands enabled):
+The browser API endpoint `/api/status` returns sanitized status and omits local filesystem paths:
```json
{
@@ -91,6 +77,7 @@ Expected output on an official `socai v0.6+` build (or a development build with
"jevModel": "~typesafe/jev-latest",
"socai": {
"installed": true,
+ "version": "0.6.0",
"capabilities": {
"instagram": true,
"tiktok": true,
@@ -102,12 +89,35 @@ Expected output on an official `socai v0.6+` build (or a development build with
*(Note: Platform capabilities are build-dependent. The official social CLI requires `v0.6+` or a development build with social subcommands enabled; older tagged releases such as `v0.5.6` registered only `xhs` and `dy`, so `instagram`, `tiktok`, and `linkedin` will all probe `false`. On `v0.6+` builds, `linkedin` evaluates to `true` or `false` depending on whether that specific build enables the LinkedIn subcommand.)*
-You can also run the CLI status command:
+For local operator diagnostics including the resolved configuration file path and binary path, run the CLI status command:
```bash
npm start -- status
```
+Expected output:
+
+```json
+{
+ "jevConfigured": true,
+ "jevModel": "~typesafe/jev-latest",
+ "configPath": "/home/user/.jev-social/config.json",
+ "socai": {
+ "installed": true,
+ "bin": "/home/user/.socai/bin/socai",
+ "version": "0.6.0",
+ "capabilities": {
+ "instagram": true,
+ "tiktok": true,
+ "linkedin": true
+ }
+ }
+}
+```
+
+> [!NOTE]
+> **Privacy note:** `npm start -- status` outputs `configPath` and `socai.bin` for local operator diagnostics. If sharing CLI output in public issues or chat, redact these local filesystem paths. The browser API endpoint (`/api/status`) automatically keeps paths sanitized.
+
### 2. Verify the Resolved `socai` Binary
Jev Social resolves the `socai` binary in the following order:
@@ -116,11 +126,11 @@ Jev Social resolves the `socai` binary in the following order:
3. Local development build candidates (`target/debug` or `target/release`).
4. System `PATH`.
-Because resolution is not pinned to a single binary and may differ from what is on your current shell `PATH`, test the exact binary resolved by Jev Social (found in the `socai.bin` field of `/api/status`, represented as `/path/from-api-status` below):
+Because resolution is not pinned to a single binary and may differ from what is on your current shell `PATH`, test the exact binary resolved by Jev Social (found in the `socai.bin` field of `npm start -- status`, represented as `/path/from-status` below):
```bash
-# Replace /path/from-api-status with your resolved binary path from /api/status:
-/path/from-api-status --version
+# Replace /path/from-status with your resolved binary path from `npm start -- status`:
+/path/from-status --version
```
### 3. Installing or Reinstalling `socai`
@@ -150,16 +160,16 @@ Because resolution is not pinned to a single binary and may differ from what is
```bash
# Select profile connection mode: existing, managed, auto, or remote (requires Pro)
-/path/from-api-status config set chrome.profile existing
+/path/from-status config set chrome.profile existing
# Select a custom Chrome profile / user data directory (applies to managed and auto modes):
-/path/from-api-status config set chrome.profile_dir /path/to/profile/dir
+/path/from-status config set chrome.profile_dir /path/to/profile/dir
# Stop the running daemon so new chrome.* settings take effect:
-/path/from-api-status stop
+/path/from-status stop
# Inspect active configuration:
-/path/from-api-status config get
+/path/from-status config get
```
### Connection Modes & Precedence in `socai v0.6.0`
@@ -171,7 +181,7 @@ Because resolution is not pinned to a single binary and may differ from what is
- **`remote` (Hosted)**: A hosted cloud browser mode that requires **socai Pro** and provisions temporary remote sessions via `socai-server` (unless an explicit `SOCAI_CDP_*` endpoint override is set). Because hosted remote containers lack local GUI interaction, users cannot interactively solve login gates or CAPTCHAs in hosted `remote` mode; authoritative `socai` guidance is to retry later or switch to `existing` or `managed` mode to authenticate.
> [!TIP]
-> If changing `chrome.*` configuration while the background `socai` daemon or browser is running, run `/path/from-api-status stop` (or `socai stop`) so the daemon reloads settings on the next run.
+> If changing `chrome.*` configuration while the background `socai` daemon or browser is running, run `/path/from-status stop` (or `socai stop`) so the daemon reloads settings on the next run.
Jev Social forwards connection overrides (`SOCAI_CDP_URL`, `SOCAI_CDP_WS`, `SOCAI_CHROME_USER_DATA_DIR`, and `SOCAI_CHROME_EXECUTABLE`) to child processes during runtime discovery. (Note: `socai` does not read `SOCAI_CHROME_PROFILE`; use `socai config set chrome.profile` to configure the connection mode.)
@@ -196,7 +206,7 @@ Jev Social forwards connection overrides (`SOCAI_CDP_URL`, `SOCAI_CDP_WS`, `SOCA
- **Issue**: TikTok may present an interactive puzzle/slider challenge or restrict video detail and comments for unauthenticated sessions.
- **Resolution**: Complete any active puzzle verification within a user-accessible Chrome session/profile selected by `socai` (`existing` or `managed` mode). Test direct platform access using the resolved `socai` executable:
```bash
- /path/from-api-status tiktok search "wearable AI" --num 4 --pretty
+ /path/from-status tiktok search "wearable AI" --num 4 --pretty
```
### LinkedIn
@@ -210,7 +220,7 @@ Jev Social forwards connection overrides (`SOCAI_CDP_URL`, `SOCAI_CDP_WS`, `SOCA
Confirm that `socai.capabilities.linkedin` evaluates to `true` (it evaluates to `false` on builds without the LinkedIn subcommand enabled).
- Test subcommand availability directly on the resolved executable:
```bash
- /path/from-api-status linkedin --help
+ /path/from-status linkedin --help
```
- **Resolution**: Sign into LinkedIn within a user-accessible Chrome session/profile selected by `socai` (`existing` or `managed` mode; switch to `existing` or `managed` if on hosted `remote` mode). Once your authenticated session is active and `socai.capabilities.linkedin` is `true`, run research through Jev Social:
```bash
@@ -218,7 +228,7 @@ Jev Social forwards connection overrides (`SOCAI_CDP_URL`, `SOCAI_CDP_WS`, `SOCA
```
On builds where the `linkedin` subcommand is supported by the resolved binary:
```bash
- /path/from-api-status linkedin search "AI product managers" --num 4 --pretty
+ /path/from-status linkedin search "AI product managers" --num 4 --pretty
```
---
diff --git a/package.json b/package.json
index da65a9c..e1fca61 100644
--- a/package.json
+++ b/package.json
@@ -29,7 +29,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 && node --check ./public/evidence-preview.js && node --check ./public/run-route.js && node --check ./public/report-download.js && node --check ./public/prompts.js",
+ "check": "node --check ./bin/jev-social.js && node --check ./src/server.js && node --check ./public/app.js && node --check ./public/evidence-preview.js && node --check ./public/run-route.js && node --check ./public/report-download.js && node --check ./public/prompts.js && node --check ./public/status.js",
"test": "node --test"
},
"engines": {
diff --git a/public/app.js b/public/app.js
index 727a6db..536e83b 100644
--- a/public/app.js
+++ b/public/app.js
@@ -8,14 +8,16 @@ import {
nextPreviewCandidate,
selectSummaryCards,
} from "./evidence-preview.js";
-import { bindPromptButtons } from "./prompts.js";
+import { bindPromptButtons, platformLabel, updatePromptButtons } from "./prompts.js";
import { parseRunRoute, resultHash } from "./run-route.js";
+import { deriveStatusView } from "./status.js";
const $ = (selector) => document.querySelector(selector);
const elements = {
searchView: $("#search-view"),
resultView: $("#result-view"),
searchForm: $("#search-form"),
+ platformNotice: $("#platform-notice"),
activity: $("#activity"),
activityTitle: $("#activity-title"),
activityMessage: $("#activity-message"),
@@ -43,6 +45,7 @@ let restorePoll;
elements.searchForm.addEventListener("submit", async (event) => {
event.preventDefault();
clearError();
+ clearPlatformNotice();
resetLiveWorkspace();
const query = $("#query").value.trim();
$("#result-title").textContent = query;
@@ -99,6 +102,8 @@ bindPromptButtons({
queryElement: $("#query"),
platformElement: $("#platform"),
});
+$("#query")?.addEventListener("input", clearPlatformNotice);
+$("#platform")?.addEventListener("change", clearPlatformNotice);
function handleStreamEvent(event) {
if (event.stage === "result") return;
@@ -216,15 +221,62 @@ async function restoreRunFromRoute() {
async function refreshStatus() {
try {
const status = await api("/api/status");
- setStatus("jev", status.jevConfigured, status.jevConfigured ? "Jev ready" : "Jev needs a key");
- const caps = status.socai.capabilities || {};
- const ready = status.socai.installed && (caps.instagram || caps.tiktok || caps.linkedin);
- setStatus("socai", ready, ready ? "socai ready" : "socai unavailable");
+ const view = deriveStatusView(status);
+ setStatus("jev", view.jev.ready, view.jev.label);
+ setStatus("socai", view.socai.ready, view.socai.label);
+ if (view.error) showError(new Error(view.error));
+
+ updatePlatformOptions(view.capabilities);
+ updatePromptButtons(document.querySelectorAll(".prompt-example-btn"), view.capabilities);
} catch (error) {
showError(error);
}
}
+function updatePlatformOptions(caps = {}) {
+ const platformSelect = $("#platform");
+ if (!platformSelect) return;
+ const previousValue = platformSelect.value;
+ let switchedToAuto = false;
+
+ for (const option of platformSelect.options) {
+ const val = option.value;
+ if (val === "auto") continue;
+ const isAvailable = Boolean(caps[val]);
+ option.disabled = !isAvailable;
+ const label = platformLabel(val);
+ if (!isAvailable) {
+ option.title = `${label} search isn't available in this socai build`;
+ option.textContent = `${label} (unavailable)`;
+ if (previousValue === val) {
+ switchedToAuto = true;
+ }
+ } else {
+ option.title = "";
+ option.textContent = label;
+ }
+ }
+
+ if (switchedToAuto) {
+ platformSelect.value = "auto";
+ showPlatformNotice(`${platformLabel(previousValue)} search isn't available in this socai build. Switched to Jev auto.`);
+ }
+}
+
+function showPlatformNotice(message) {
+ if (elements.platformNotice) {
+ elements.platformNotice.textContent = message;
+ elements.platformNotice.classList.remove("hidden");
+ }
+}
+
+function clearPlatformNotice() {
+ if (elements.platformNotice) {
+ elements.platformNotice.textContent = "";
+ elements.platformNotice.classList.add("hidden");
+ }
+}
+
function setStatus(prefix, ready, label) {
$(`#${prefix}-dot`).classList.toggle("ready", ready);
$(`#${prefix}-status`).textContent = label;
diff --git a/public/index.html b/public/index.html
index c77ed91..3592a45 100644
--- a/public/index.html
+++ b/public/index.html
@@ -42,6 +42,7 @@
<form id="search-form" class="composer">
<textarea id="query" name="query" required autocomplete="off" rows="3" placeholder="Find emerging AI creators and their most engaging posts"></textarea>
+ <div id="platform-notice" class="platform-notice hidden" role="status" aria-live="polite"></div>
<div class="composer-controls">
<label class="field-group">
<span>PLATFORM</span>
diff --git a/public/prompts.js b/public/prompts.js
index e0f566b..2e15c7f 100644
--- a/public/prompts.js
+++ b/public/prompts.js
@@ -66,6 +66,9 @@ export function bindPromptButtons({ buttons, queryElement, platformElement, onSe
if (event && typeof event.preventDefault === "function") {
event.preventDefault();
}
+ if (button.disabled || (typeof button.getAttribute === "function" && button.getAttribute("aria-disabled") === "true")) {
+ return;
+ }
const platform = button.dataset?.platform;
const query = button.dataset?.query;
const prompt = getPromptForPlatform(platform) || { platform, query };
@@ -82,3 +85,41 @@ export function bindPromptButtons({ buttons, queryElement, platformElement, onSe
for (const cleanup of cleanups) cleanup();
};
}
+
+export function updatePromptButtons(buttons, capabilities = {}) {
+ if (!buttons) return;
+ const list = Array.from(buttons);
+ for (const button of list) {
+ const platform = button.dataset?.platform;
+ if (!platform) continue;
+ const isSupported = capabilities[platform] !== false;
+ button.disabled = !isSupported;
+ if (!isSupported) {
+ const label = platformLabel(platform);
+ const explanation = `${label} search isn't available in this socai build`;
+ button.title = explanation;
+ if (typeof button.setAttribute === "function") {
+ button.setAttribute("aria-description", explanation);
+ button.setAttribute("aria-disabled", "true");
+ }
+ } else {
+ button.title = "";
+ if (typeof button.removeAttribute === "function") {
+ button.removeAttribute("title");
+ button.removeAttribute("aria-description");
+ button.removeAttribute("aria-disabled");
+ }
+ }
+ }
+}
+
+const PLATFORM_LABELS = {
+ instagram: "Instagram",
+ tiktok: "TikTok",
+ linkedin: "LinkedIn",
+};
+
+export function platformLabel(platform = "") {
+ const key = String(platform || "").toLowerCase();
+ return PLATFORM_LABELS[key] || (key.charAt(0).toUpperCase() + key.slice(1));
+}
diff --git a/public/status.js b/public/status.js
new file mode 100644
index 0000000..0c24f7a
--- /dev/null
+++ b/public/status.js
@@ -0,0 +1,35 @@
+const PLATFORMS = ["instagram", "tiktok", "linkedin"];
+
+export function deriveStatusView(status = {}) {
+ const capabilities = status.socai?.capabilities || {};
+ const configError = typeof status.configError === "string" ? status.configError.trim() : "";
+ if (configError) {
+ return {
+ error: configError,
+ capabilities,
+ jev: { ready: false, label: "Configuration unavailable" },
+ socai: { ready: false, label: "Configuration unavailable" },
+ };
+ }
+
+ const installed = Boolean(status.socai?.installed);
+ const available = PLATFORMS.filter((platform) => capabilities[platform]);
+ const allReady = installed && available.length === PLATFORMS.length;
+ let socaiLabel = "socai unavailable";
+ if (installed) {
+ const version = status.socai?.version ? ` v${status.socai.version}` : "";
+ if (allReady) socaiLabel = `socai${version} ready`;
+ else if (available.length) socaiLabel = `socai${version} (${available.length}/${PLATFORMS.length} ready)`;
+ else socaiLabel = `socai${version} (no platforms)`;
+ }
+
+ return {
+ error: "",
+ capabilities,
+ jev: {
+ ready: Boolean(status.jevConfigured),
+ label: status.jevConfigured ? "Jev ready" : "Jev needs a key",
+ },
+ socai: { ready: allReady, label: socaiLabel },
+ };
+}
diff --git a/public/styles.css b/public/styles.css
index 6c82033..0bfdd37 100644
--- a/public/styles.css
+++ b/public/styles.css
@@ -49,6 +49,7 @@ h1 em { color: transparent; font-style: normal; -webkit-text-stroke: 1.5px var(-
.composer { border: 1.5px solid var(--ink); background: #fff; box-shadow: 7px 7px 0 rgba(255, 46, 166, .72); }
.composer textarea { display: block; width: 100%; min-height: 112px; resize: vertical; padding: 18px; border: 0; outline: 0; background: #fff; font-size: 16px; line-height: 1.55; }
.composer textarea::placeholder { color: #9ba0aa; }
+.platform-notice { margin: 0; padding: 8px 18px; border-top: 1px solid var(--line); background: var(--ice); color: var(--ink); font: 500 11px/1.4 var(--mono); }
.composer-controls { min-height: 64px; display: flex; align-items: end; gap: 11px; padding: 10px; border-top: 1px solid var(--line); background: #f3f8fc; }
.field-group { display: grid; gap: 5px; }
.field-group > span { font: 700 8px var(--mono); letter-spacing: .12em; }
@@ -69,6 +70,7 @@ h1 em { color: transparent; font-style: normal; -webkit-text-stroke: 1.5px var(-
.prompt-example-btn:hover { border-color: var(--ink); transform: translate(-1px, -1px); box-shadow: 2px 2px 0 var(--ink); }
.prompt-example-btn:active { transform: translate(0, 0); box-shadow: 1px 1px 0 var(--ink); }
.prompt-example-btn:focus-visible { outline: 2px solid var(--ink); outline-offset: 2px; box-shadow: 0 0 0 3px var(--pink); }
+.prompt-example-btn:disabled, .prompt-example-btn[aria-disabled="true"] { opacity: .45; cursor: not-allowed; pointer-events: none; border-color: var(--line) !important; transform: none !important; box-shadow: none !important; }
.prompt-example-btn .prompt-platform { color: var(--pink); font: 700 9px var(--mono); letter-spacing: .06em; text-transform: uppercase; }
.prompt-example-btn .prompt-text { color: var(--ink); }
diff --git a/src/app.js b/src/app.js
index 35ed3ec..7301ec2 100644
--- a/src/app.js
+++ b/src/app.js
@@ -6,7 +6,7 @@ import { AppError } from "./errors.js";
import { readConfig, resolveApiKey } from "./config.js";
import { extractSearchQuery } from "./query.js";
import { saveRun } from "./runs.js";
-import { actionCapabilities, runSocaiAction } from "./socai.js";
+import { actionCapabilities, probeSocai, runSocaiAction, sanitizeCliErrorText } from "./socai.js";
export async function runSearch(
{ query, platform = "auto", limit = 4, maxSteps = 12 },
@@ -16,18 +16,53 @@ export async function runSearch(
if (!request) throw new AppError("Search query cannot be empty.", { code: "EMPTY_QUERY" });
if (!Number.isInteger(limit) || limit < 1 || limit > 100) throw new AppError("limit must be between 1 and 100.", { code: "INVALID_LIMIT" });
if (!Number.isInteger(maxSteps) || maxSteps < 1 || maxSteps > 30) throw new AppError("maxSteps must be between 1 and 30.", { code: "INVALID_STEP_LIMIT" });
+
+ const normalizedPlatform = (platform || "auto").toLowerCase();
+ if (normalizedPlatform !== "auto" && !["instagram", "tiktok", "linkedin"].includes(normalizedPlatform)) {
+ throw new AppError(`Unsupported platform: ${platform}`, { code: "INVALID_PLATFORM" });
+ }
+
const config = await readConfig(env);
+ const probe = await probeSocai(config, env, signal);
+ const capabilities = probe.capabilities || { instagram: false, tiktok: false, linkedin: false };
+
+ if (normalizedPlatform !== "auto") {
+ if (!probe.installed || !capabilities[normalizedPlatform]) {
+ throw new AppError(
+ `The installed socai CLI does not support ${normalizedPlatform} search. Install a compatible build or set SOCAI_BIN.`,
+ {
+ code: "SOCAI_CAPABILITY_MISSING",
+ details: { platform: normalizedPlatform },
+ },
+ );
+ }
+ } else {
+ if (!probe.installed || !Object.values(capabilities).some(Boolean)) {
+ throw new AppError(
+ "No supported social search platforms are available in the installed socai CLI.",
+ {
+ code: "SOCAI_CAPABILITY_MISSING",
+ },
+ );
+ }
+ }
+
const apiKey = resolveApiKey(config, env);
if (!apiKey && !client) throw new AppError("Set OPENROUTER_API_KEY first.", { code: "ONBOARDING_REQUIRED" });
const startedAt = Date.now();
const model = env.OPENROUTER_JEV_MODEL || "~typesafe/jev-latest";
const decisionOptions = { apiKey, model, client, signal };
onEvent?.({ stage: "classifying", message: "Jev is choosing the social platform…" });
- const classification = await classifySearch({ goal: request, requestedPlatform: platform, ...decisionOptions });
+ const classification = await classifySearch({
+ goal: request,
+ requestedPlatform: normalizedPlatform,
+ capabilities,
+ ...decisionOptions,
+ });
if (!classification.platform) throw new AppError("This request is not a supported read-only social task.", { code: "UNSUPPORTED_TASK" });
if (classification.confidence < 0.35) throw new AppError("Jev is uncertain about the platform. Select one explicitly.", { code: "LOW_CLASSIFICATION_CONFIDENCE" });
const selectedPlatform = classification.platform;
- const commands = await actionCapabilities({ config, env, platform: selectedPlatform, signal });
+ const commands = await actionCapabilities({ config, env, platform: selectedPlatform, signal, capabilities });
const searchQuery = extractSearchQuery(request);
const createdAt = new Date().toISOString();
const id = `${createdAt.replace(/[-:.TZ]/g, "").slice(0, 14)}-${crypto.randomBytes(3).toString("hex")}`;
@@ -160,11 +195,11 @@ export async function runSearch(
}
function safeProgress(message) {
- const text = String(message || "").trim();
- if (!text || text.startsWith("@@SOCAI_EVENT@@") || /^[{[]/.test(text)) return "";
- if (/^\d{4}-\d{2}-\d{2}T\S+\s+(?:TRACE|DEBUG|INFO|WARN|ERROR)\b/.test(text)) return "";
- if (/^at\s+(?:<anonymous>|[\w.]+)(?::|\s|$)/.test(text)) return "";
- if (/\b(?:run_dir|report_path|local_path|output_dir|artifact_path)\b\s*[:=]/i.test(text)) return "";
- if (/(?:^|\s)(?:\/Users\/|\/home\/|\/tmp\/|[A-Za-z]:\\)/.test(text)) return "";
- return text;
+ const raw = String(message || "").trim();
+ if (!raw || raw.startsWith("@@SOCAI_EVENT@@") || /^[{[]/.test(raw)) return "";
+ if (/^\d{4}-\d{2}-\d{2}T\S+\s+(?:TRACE|DEBUG|INFO|WARN|ERROR)\b/.test(raw)) return "";
+ if (/^at\s+(?:<anonymous>|[\w.]+)(?::|\s|$)/.test(raw)) return "";
+ const sanitized = sanitizeCliErrorText(raw);
+ if (/^(?:run_dir|report_path|local_path|output_dir|artifact_path)\s*[:=]\s*\[path\]$/i.test(sanitized)) return "";
+ return sanitized;
}
diff --git a/src/classifier.js b/src/classifier.js
index 11b58cc..e7f74a8 100644
--- a/src/classifier.js
+++ b/src/classifier.js
@@ -7,16 +7,35 @@ const ROUTE_TO_PLATFORM = {
linkedin_search: "linkedin",
};
+const WORKFLOW_DEFINITIONS = {
+ instagram: {
+ workflow: "Read-only Instagram search via the socai CLI",
+ route: "instagram_search",
+ criterion: "Search or research Instagram content, profiles, posts, or reels.",
+ },
+ tiktok: {
+ workflow: "Read-only TikTok search via the socai CLI",
+ route: "tiktok_search",
+ criterion: "Search or research TikTok content, creators, or videos.",
+ },
+ linkedin: {
+ workflow: "Read-only LinkedIn search via the socai CLI",
+ route: "linkedin_search",
+ criterion: "Search or research LinkedIn people, companies, posts, or professional experience.",
+ },
+};
+
export async function classifySearch({
goal,
requestedPlatform = "auto",
+ capabilities = { instagram: true, tiktok: true, linkedin: true },
apiKey,
model = process.env.OPENROUTER_JEV_MODEL || "~typesafe/jev-latest",
client,
fetchImpl = fetch,
signal,
}) {
- const normalizedPlatform = requestedPlatform.toLowerCase();
+ const normalizedPlatform = (requestedPlatform || "auto").toLowerCase();
if (normalizedPlatform !== "auto" && !SUPPORTED_PLATFORMS.has(normalizedPlatform)) {
throw new AppError(`Unsupported platform: ${requestedPlatform}`, {
code: "INVALID_PLATFORM",
@@ -26,16 +45,28 @@ export async function classifySearch({
throw new AppError("Search query cannot be empty.", { code: "EMPTY_QUERY" });
}
+ const activePlatforms = [...SUPPORTED_PLATFORMS].filter((p) => capabilities?.[p] !== false);
+
+ if (normalizedPlatform !== "auto" && !activePlatforms.includes(normalizedPlatform)) {
+ throw new AppError(`The installed socai CLI does not support ${normalizedPlatform} search.`, {
+ code: "SOCAI_CAPABILITY_MISSING",
+ details: { platform: normalizedPlatform },
+ });
+ }
+
+ const supportedWorkflows = activePlatforms.map((p) => WORKFLOW_DEFINITIONS[p].workflow);
+ const routeCriteria = {};
+ for (const p of activePlatforms) {
+ routeCriteria[WORKFLOW_DEFINITIONS[p].route] = WORKFLOW_DEFINITIONS[p].criterion;
+ }
+ routeCriteria.unsupported = "Anything else, including posting, liking, following, messaging, or an ambiguous auto route.";
+
const request = {
model,
state: {
request: goal.trim(),
requested_platform: normalizedPlatform,
- supported_workflows: [
- "Read-only Instagram search via the socai CLI",
- "Read-only TikTok search via the socai CLI",
- "Read-only LinkedIn search via the socai CLI",
- ],
+ supported_workflows: supportedWorkflows,
},
questions: {
route: {
@@ -48,13 +79,7 @@ export async function classifySearch({
"Do not invent another platform or an action that changes remote state.",
],
},
- criteria: {
- instagram_search: "Search or research Instagram content, profiles, posts, or reels.",
- tiktok_search: "Search or research TikTok content, creators, or videos.",
- linkedin_search: "Search or research LinkedIn people, companies, posts, or professional experience.",
- unsupported:
- "Anything else, including posting, liking, following, messaging, or an ambiguous auto route.",
- },
+ criteria: routeCriteria,
},
},
};
diff --git a/src/server.js b/src/server.js
index 0c9d0c9..e777c05 100644
--- a/src/server.js
+++ b/src/server.js
@@ -22,6 +22,7 @@ const STATIC_FILES = {
"/evidence-preview.js": ["evidence-preview.js", "text/javascript; charset=utf-8"],
"/run-route.js": ["run-route.js", "text/javascript; charset=utf-8"],
"/prompts.js": ["prompts.js", "text/javascript; charset=utf-8"],
+ "/status.js": ["status.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"],
@@ -84,13 +85,27 @@ async function handleRequest(request, response, env, mediaRegistry) {
return response.end(content);
}
if (request.method === "GET" && url.pathname === "/api/status") {
- const config = await readConfig(env);
+ let config;
+ try {
+ config = await readConfig(env);
+ } catch {
+ return sendJson(response, 200, {
+ jevConfigured: false,
+ jevModel: env.OPENROUTER_JEV_MODEL || "~typesafe/jev-latest",
+ socai: { installed: false, version: null, capabilities: { instagram: false, tiktok: false, linkedin: false } },
+ configError: "Configuration could not be read.",
+ });
+ }
const socai = await probeSocai(config, env);
return sendJson(response, 200, {
jevConfigured: Boolean(resolveApiKey(config, env)),
jevModel: env.OPENROUTER_JEV_MODEL || "~typesafe/jev-latest",
- configPath: getConfigPath(env),
- socai,
+ socai: {
+ installed: socai.installed,
+ version: socai.version ?? null,
+ capabilities: socai.capabilities,
+ ...(socai.error ? { error: socai.error } : {}),
+ },
});
}
if (request.method === "POST" && url.pathname === "/api/onboard") {
diff --git a/src/socai.js b/src/socai.js
index ad5561f..ebf1d2f 100644
--- a/src/socai.js
+++ b/src/socai.js
@@ -5,15 +5,33 @@ import { buildActionArgs } from "./actions.js";
const PLATFORMS = ["instagram", "tiktok", "linkedin"];
-export async function actionCapabilities({ config = {}, env = process.env, platform, signal }) {
+export async function actionCapabilities({ config = {}, env = process.env, platform, signal, capabilities }) {
if (!PLATFORMS.includes(platform)) throw new AppError("Unsupported platform.", { code: "INVALID_PLATFORM" });
const bin = await resolveSocaiBin(config, env);
+
+ const isSearchSupported = capabilities && typeof capabilities[platform] === "boolean"
+ ? capabilities[platform]
+ : await platformSupported(bin, platform, env, signal);
+
const result = await runProcess(bin, [platform, "--help"], { env, signal, timeoutMs: 15_000 });
if (result.aborted) throw abortedError();
- if (result.code !== 0 || result.timedOut) throw new AppError(`Could not read socai ${platform} commands.`, { code: "SOCAI_CAPABILITY_MISSING" });
+ if (result.code !== 0 || result.timedOut) {
+ if (isSearchSupported) {
+ return ["search"];
+ }
+ throw new AppError(`Could not read socai ${platform} commands.`, { code: "SOCAI_CAPABILITY_MISSING" });
+ }
const help = `${result.stdout}\n${result.stderr}`;
const names = ["search", "get-posts", "get-videos", "profile", "author", "company", "history", "page_state"];
- return names.filter((name) => new RegExp(`(?:^|\\s)${name}(?=\\s|$)`, "m").test(help));
+
+ const discovered = names.filter((name) => new RegExp(`(?:^|\\s)${name}(?=\\s|$)`, "m").test(help));
+ if (!isSearchSupported) {
+ return discovered.filter((name) => name !== "search");
+ }
+ if (!discovered.includes("search")) {
+ discovered.unshift("search");
+ }
+ return discovered;
}
export async function runSocaiAction({ action, config = {}, env = process.env, signal, onProgress }) {
@@ -25,30 +43,86 @@ export async function resolveSocaiBin(config = {}, env = process.env) {
return configuredSocaiBin(config, env) || (await defaultInstalledSocaiBin());
}
-export async function probeSocai(config = {}, env = process.env) {
+export async function probeSocai(config = {}, env = process.env, signal) {
const bin = await resolveSocaiBin(config, env);
try {
- const root = await runProcess(bin, ["--help"], { timeoutMs: 15_000, env });
+ const root = await runProcess(bin, ["--help"], { timeoutMs: 15_000, env, signal });
+ if (root.aborted) throw abortedError();
if (root.code !== 0) {
- return { installed: false, bin, error: concise(root.stderr || root.stdout) };
+ return {
+ installed: false,
+ bin,
+ version: null,
+ capabilities: { instagram: false, tiktok: false, linkedin: false },
+ error: concise(root.stderr || root.stdout),
+ };
}
- const capabilities = {};
+ const version = await getSocaiVersion(bin, env, signal);
+ const capabilities = { instagram: false, tiktok: false, linkedin: false };
await Promise.all(
PLATFORMS.map(async (platform) => {
- capabilities[platform] = await platformSupported(bin, platform, env);
+ capabilities[platform] = await platformSupported(bin, platform, env, signal);
}),
);
- return { installed: true, bin, capabilities };
+ return { installed: true, bin, version, capabilities };
} catch (error) {
- return { installed: false, bin, error: error.code === "ENOENT" ? "socai executable not found" : error.message };
+ if (error?.code === "SOCAI_ABORTED" || error?.name === "AbortError" || signal?.aborted) {
+ throw abortedError();
+ }
+ return {
+ installed: false,
+ bin,
+ version: null,
+ capabilities: { instagram: false, tiktok: false, linkedin: false },
+ error: error.code === "ENOENT" ? "socai executable not found" : concise(error.message),
+ };
}
}
-export async function platformSupported(bin, platform, env = process.env, signal) {
+/**
+ * Extracts sanitized semver from `socai --version` output.
+ * Assumes the CLI output includes the primary semver token (e.g. `socai 0.5.6` or `0.5.6-beta.1`).
+ * If verbose builds output multiple version numbers, the primary/first semver token is selected.
+ */
+export async function getSocaiVersion(bin, env = process.env, signal) {
try {
- const result = await runProcess(bin, [platform, "--help"], { timeoutMs: 15_000, env, signal });
+ const result = await runProcess(bin, ["--version"], { timeoutMs: 15_000, env, signal });
if (result.aborted) throw abortedError();
- return result.code === 0 && /\bsearch\b/i.test(`${result.stdout}\n${result.stderr}`);
+ const output = `${result.stdout}\n${result.stderr}`.trim();
+ const match = output.match(/\b\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?\b/);
+ return match ? match[0] : null;
+ } catch (error) {
+ if (error?.code === "SOCAI_ABORTED" || error?.name === "AbortError" || signal?.aborted) {
+ throw abortedError();
+ }
+ return null;
+ }
+}
+
+export async function platformSupported(bin, platform, env = process.env, signal) {
+ try {
+ // Probe the concrete subcommand's help rather than pattern-matching the
+ // parent command's prose — a platform may mention "search" in an error
+ // or disclaimer string without the subcommand actually existing.
+ const subcommand = await runProcess(bin, [platform, "search", "--help"], {
+ timeoutMs: 15_000,
+ env,
+ signal,
+ }).catch((error) => {
+ if (error?.name === "AbortError") throw abortedError();
+ return null;
+ });
+ if (subcommand?.aborted) throw abortedError();
+ if (subcommand && subcommand.code === 0) return true;
+
+ const parent = await runProcess(bin, [platform, "--help"], { timeoutMs: 15_000, env, signal });
+ if (parent.aborted) throw abortedError();
+ if (parent.code !== 0) return false;
+ const output = `${parent.stdout}\n${parent.stderr}`;
+ return (
+ /(?:commands|subcommands|available commands|actions):\s*[^\n]*\bsearch\b/i.test(output) ||
+ /(?:^|\n)\s*search(?:\s{2,}[^\n]*|\s*\[[^\n]*|\s*$)/m.test(output)
+ );
} catch (error) {
if (error?.code === "SOCAI_ABORTED" || error?.name === "AbortError") throw abortedError();
return false;
@@ -122,7 +196,7 @@ export async function runSocaiSearch({
`This socai binary does not expose '${platform} search'. Install a compatible build or set SOCAI_BIN.`,
{
code: "SOCAI_CAPABILITY_MISSING",
- details: { bin, platform },
+ details: { platform },
},
);
}
@@ -152,7 +226,6 @@ export async function runSocaiResearch({
if (!capability || capability.code !== 0) {
throw new AppError("This socai binary does not expose 'socai research'. Build the dev-compatible CLI or set SOCAI_BIN.", {
code: "SOCAI_RESEARCH_CAPABILITY_MISSING",
- details: { bin },
});
}
return runSocaiJson(bin, buildResearchArgs(platform, task, { maxSteps }), {
@@ -184,7 +257,6 @@ export async function runSocaiTikTokVideos({
if (!capability || capability.code !== 0) {
throw new AppError("This socai binary does not expose 'tiktok get-videos'. Install the dev-compatible build or set SOCAI_BIN.", {
code: "SOCAI_VIDEO_CAPABILITY_MISSING",
- details: { bin },
});
}
return runSocaiJson(bin, buildTikTokVideoArgs(locators, { numComments }), {
@@ -207,9 +279,8 @@ async function runSocaiJson(bin, args, { env, onProgress, signal, timeoutMs = 8
signal,
});
} catch (error) {
- throw new AppError(`Could not start socai CLI: ${error.message}`, {
+ throw new AppError(`Could not start socai CLI: ${concise(error.message)}`, {
code: "SOCAI_NOT_FOUND",
- details: { bin },
});
}
@@ -224,20 +295,18 @@ async function runSocaiJson(bin, args, { env, onProgress, signal, timeoutMs = 8
throw new AppError(`socai CLI timed out after ${Math.round(timeoutMs / 60_000)} minutes.`, {
code: "SOCAI_TIMEOUT",
status: 504,
- details: { command },
});
}
if (result.overflowed) {
throw new AppError("socai CLI output exceeded the 24 MB safety limit.", {
code: "SOCAI_OUTPUT_TOO_LARGE",
- details: { command },
});
}
if (result.code !== 0) {
throw new AppError(`socai CLI failed: ${concise(result.stderr || result.stdout)}`, {
code: "SOCAI_FAILED",
status: 502,
- details: { command, exitCode: result.code, ...(result.signal ? { signal: result.signal } : {}) },
+ details: { exitCode: result.code, ...(result.signal ? { signal: result.signal } : {}) },
});
}
@@ -278,8 +347,142 @@ export function parseJsonOutput(output) {
});
}
+function isPathLike(val) {
+ if (!val) return false;
+ let decoded = val;
+ for (let pass = 0; pass < 3; pass += 1) {
+ try {
+ const next = decodeURIComponent(decoded);
+ if (next === decoded) break;
+ decoded = next;
+ } catch {
+ break;
+ }
+ }
+ return (
+ /^[A-Za-z]:[/\\]/i.test(decoded) ||
+ /^[A-Za-z]:[^/\\\s]+[/\\]/i.test(decoded) ||
+ /^file:\/\/\//i.test(decoded) ||
+ /^~[/\\]/.test(decoded) ||
+ /^\.{1,2}[/\\]/.test(decoded) ||
+ /^[/\\](?![/\\])[^/?#\\]+(?:[/\\][^/?#\\]+)*$/.test(decoded) ||
+ /^\/(?!\/)[^/?#]+(?:[/\\][^/?#]+)*$/.test(decoded) ||
+ /^\/(?:Users|home|root|tmp|var|opt|usr|etc|Volumes|private|mnt|media|srv|dev|proc|sys)\b/i.test(decoded) ||
+ /^(?:\/[a-zA-Z0-9._~-]+){2,}/.test(decoded) ||
+ /^[/\\]{2}/.test(decoded) ||
+ /\b[A-Za-z]:[/\\]/i.test(decoded) ||
+ /^[a-zA-Z0-9_.-]+[/\\].+$/.test(decoded) ||
+ /^[a-zA-Z0-9_.-]+[/\\][a-zA-Z0-9_.-]+(?:[/\\][a-zA-Z0-9_.-]+)*$/.test(decoded) ||
+ /\b(?:[a-zA-Z0-9_.-]+[/\\]){2,}[a-zA-Z0-9_.-]+/.test(decoded)
+ );
+}
+
+function sanitizeUrl(urlStr) {
+ try {
+ const url = new URL(urlStr);
+ if (url.search) {
+ const parts = url.search.slice(1).split("&");
+ const sanitizedParts = parts.map((part) => {
+ const eqIdx = part.indexOf("=");
+ if (eqIdx === -1) {
+ return isPathLike(part) ? "[path]" : part;
+ }
+ const key = part.slice(0, eqIdx);
+ const val = part.slice(eqIdx + 1);
+ return isPathLike(val) ? `${key}=[path]` : part;
+ });
+ url.search = `?${sanitizedParts.join("&")}`;
+ }
+ if (url.hash) {
+ const hashContent = url.hash.slice(1);
+ if (hashContent.includes("&") || hashContent.includes("=")) {
+ const parts = hashContent.split("&");
+ const sanitizedParts = parts.map((part) => {
+ const eqIdx = part.indexOf("=");
+ if (eqIdx === -1) {
+ return isPathLike(part) ? "[path]" : part;
+ }
+ const key = part.slice(0, eqIdx);
+ const val = part.slice(eqIdx + 1);
+ return isPathLike(val) ? `${key}=[path]` : part;
+ });
+ url.hash = `#${sanitizedParts.join("&")}`;
+ } else if (isPathLike(hashContent)) {
+ url.hash = "#[path]";
+ }
+ }
+ return url.toString().replace(/%5Bpath%5D/gi, "[path]");
+ } catch {
+ return urlStr;
+ }
+}
+
+export function sanitizeCliErrorText(text) {
+ if (typeof text !== "string") return "";
+
+ // 1. Preserve HTTP/HTTPS URLs by replacing with temporary placeholders after sanitizing query/fragment paths
+ const urls = [];
+ const withUrlsPreserved = text.replace(/https?:\/\/[^\s"'`<>]+/gi, (url) => {
+ const match = url.match(/^(.*?)([.,;:!?)]*)$/);
+ const cleanUrl = match ? match[1] : url;
+ const trailing = match ? match[2] : "";
+ urls.push(sanitizeUrl(cleanUrl));
+ return `__URL_PLACEHOLDER_${urls.length - 1}__${trailing}`;
+ });
+
+ // 2. Perform path redactions
+ const redacted = withUrlsPreserved
+ // 1. Local file URLs
+ .replace(/\bfile:\/\/\/?(?:[A-Za-z]:)?[^\s"'`<>),;!?]+/gi, "[path]")
+ // 2. Quoted paths
+ .replace(/(["'`])(?:\/|~\/|[A-Za-z]:[/\\]|\\\\|\.{1,2}[/\\])[^"'`]*\1/g, "[path]")
+ // 3. Unquoted paths with spaces that end in a filename extension
+ .replace(
+ /(?:^|[\s"'`([<{=:])(?:\/|~\/|[A-Za-z]:[/\\]|\\\\|\.{1,2}[/\\]|[a-zA-Z][a-zA-Z0-9_.-]*[/\\])[^\s:)]*(?:[ \t][^\s:)]*)+\.[a-zA-Z0-9_-]{1,16}(?=\s|[,;!?)]|$)/gi,
+ (match) => {
+ const leadingChar = match.match(/^[\s"'`([<{=:]/)?.[0] || "";
+ return `${leadingChar}[path]`;
+ },
+ )
+ // 4. Other unquoted paths with spaces (e.g. /Volumes/My Disk/socai or C:\Program Files\socai\socai.exe)
+ .replace(
+ /(?:^|[\s"'`([<{=:])(?:\/|~\/|[A-Za-z]:[/\\]|\\\\|\.{1,2}[/\\]|[a-zA-Z][a-zA-Z0-9_.-]*[/\\])(?=[^:\r\n)]*\s+[^:\r\n)]*[/\\])(?:[^\s:)]|(?<! )\s(?! ))*?(?=\s+(?:ENOENT|EACCES|EPERM|EEXIST|not found|no such file|is not recognized|exited with|failed with|script|because|while|when|but|and|or|then|after|before|retrying)\b|(?::|[,;!?)]|\.(?:\s|$))(?:\s|$|\b)|\s{2}|$)/gi,
+ (match) => {
+ const leadingChar = match.match(/^[\s"'`([<{=:]/)?.[0] || "";
+ const pathPart = match.slice(leadingChar.length);
+ const trailingPunct = pathPart.match(/[).,;:!?]+$/)?.[0] || "";
+ return `${leadingChar}[path]${trailingPunct}`;
+ },
+ )
+ // 5. General paths (single token or standard paths)
+ .replace(/(?:^|[\s"'`([<{=:])(?:[A-Za-z]:[/\\]|[A-Za-z]:[a-zA-Z0-9._~-]+[/\\]|~[/\\]|(?:\.{1,2}[/\\]+)|[/\\](?:[a-zA-Z0-9._~-]+[/\\])*|[a-zA-Z][a-zA-Z0-9._~-]*[/\\])[^\s"'`<>:=)]+/g, (match) => {
+ const leadingChar = match.match(/^[\s"'`([<{=:]/)?.[0] || "";
+ const pathPart = match.slice(leadingChar.length);
+ const trailingPunct = pathPart.match(/[).,;:!?]+$/)?.[0] || "";
+ return `${leadingChar}[path]${trailingPunct}`;
+ })
+ // 6. Remaining one-token relative paths, including Unicode and dot/scope prefixes
+ .replace(/(?:^|[\s"'`([<{=:])(?=[^\s"'`<>:=)]*\p{L})(?:[^\s"'`<>:=)]+[/\\])+[^\s"'`<>:=)]+/gu, (match) => {
+ const leadingChar = match.match(/^[\s"'`([<{=:]/)?.[0] || "";
+ const pathPart = match.slice(leadingChar.length);
+ const trailingPunct = pathPart.match(/[).,;:!?]+$/)?.[0] || "";
+ return `${leadingChar}[path]${trailingPunct}`;
+ })
+ // 7. Relative paths with a filename, such as logs/error.txt
+ .replace(/\b(?:[A-Za-z]:)?(?:[a-zA-Z0-9_.-]+[/\\])+[a-zA-Z0-9_.-]+\.[a-zA-Z0-9_-]+\b/g, "[path]")
+ // 8. Relative multi-segment paths like foo/bar/baz
+ .replace(/\b(?:[a-zA-Z0-9_.-]+[/\\]){2,}[a-zA-Z0-9_.-]+/g, "[path]")
+ // 9. Deduplicate and trim
+ .replace(/(?:\[path\](?:\s+\[path\])*)/g, "[path]")
+ .replace(/\s+/g, " ")
+ .trim();
+
+ // 3. Restore preserved URLs
+ return redacted.replace(/__URL_PLACEHOLDER_(\d+)__/g, (_, index) => urls[Number(index)] || "");
+}
+
function concise(value, maxLength = 800) {
- const normalized = String(value || "unknown error").replace(/\s+/g, " ").trim();
+ const normalized = sanitizeCliErrorText(String(value || "unknown error"));
return normalized.length > maxLength ? `${normalized.slice(0, maxLength)}…` : normalized;
}
diff --git a/test/app.test.js b/test/app.test.js
index 65fe2e1..57126b3 100644
--- a/test/app.test.js
+++ b/test/app.test.js
@@ -1,5 +1,5 @@
import assert from "node:assert/strict";
-import { mkdtemp, rm, writeFile } from "node:fs/promises";
+import { chmod, mkdtemp, rm, writeFile } from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import test from "node:test";
@@ -30,6 +30,8 @@ else if (command === 'search') {
]});
} else if (command === 'get-posts') {
console.error('run_dir: /tmp/private/run');
+ console.error('cannot open /opt/company/private/config.json; retrying safely');
+ console.error('artifact_path=/tmp/private/report.md but upload failed');
result({ok:true,posts:[{ok:true,url:args[3],entity:{caption:'A handmade bowl stored at /tmp/private/raw.json',thumbnail_url:'https://cdn.example/art.jpg',local_path:'/tmp/private/post.json',stdout:'raw private output',cookies:[{name:'sid',value:'secret-cookie'}],dom:'<html>private DOM</html>'},comments:[{text:'Love the glaze'}]}]});
} else if (command === 'get-videos') {
result({ok:true,videos:[{ok:true,locator:args[3],entity:{url:args[3],title:'Selected video',video:args.includes('--download-media')?{local_path:'/tmp/video.mp4'}:{}}}]});
@@ -78,7 +80,10 @@ test("runSearch lets Jev choose a specific post, then finish without an autonomo
assert.ok(!run.evidenceCommands.some((command) => /research|\/first\//.test(command)));
assert.match(run.report, /Love the glaze/);
assert.ok(events.some((event) => event.stage === 'planning'));
+ assert.ok(events.some((event) => event.message === 'cannot open [path]; retrying safely'));
+ assert.ok(events.some((event) => event.message === 'artifact_path=[path] but upload failed'));
assert.ok(!JSON.stringify(events).includes('/tmp/private'));
+ assert.ok(!JSON.stringify(events).includes('/opt/company'));
assert.ok(!run.result.items.some((item) => item.url.includes('evil.example')));
} finally { await rm(directory,{recursive:true,force:true}); }
});
@@ -157,6 +162,137 @@ test("an invented action never reaches the CLI", async () => {
} finally { await rm(directory,{recursive:true,force:true}); }
});
+test("requesting explicit unsupported platform fails with SOCAI_CAPABILITY_MISSING before any model call", async () => {
+ const directory = await mkdtemp(path.join(os.tmpdir(), "jev-social-missing-plat-"));
+ const mock = path.join(directory, "socai-mock.mjs");
+ await writeFile(
+ mock,
+ `#!/usr/bin/env node
+const args = process.argv.slice(2);
+if (args[0] === "--version") console.log("socai 0.5.6");
+else if (args[0] === "--help") console.log("socai root");
+else if (args[0] === "instagram" && args[1] === "--help") console.log("Commands: search");
+else if (args[0] === "tiktok" && args[1] === "--help") console.log("Commands: search");
+else if (args[0] === "linkedin" && args[1] === "--help") process.exitCode = 1;
+else process.exitCode = 2;
+`,
+ { mode: 0o755 },
+ );
+
+ const env = { ...process.env, SOCAI_BIN: mock, JEV_SOCIAL_HOME: directory };
+ let modelCallCount = 0;
+ const client = {
+ async systemOne() {
+ modelCallCount += 1;
+ return { answers: { route: { type: "choice", choice: "linkedin_search", confidence: 0.9 } } };
+ },
+ };
+
+ try {
+ await assert.rejects(
+ runSearch({ query: "find AI PMs", platform: "linkedin" }, { env, client }),
+ (error) => {
+ assert.equal(error.code, "SOCAI_CAPABILITY_MISSING");
+ assert.equal(error.details?.platform, "linkedin");
+ assert.ok(!JSON.stringify(error).includes(directory));
+ return true;
+ },
+ );
+ assert.equal(modelCallCount, 0, "No model calls should be made for explicitly unsupported platform");
+ } finally {
+ await rm(directory, { recursive: true, force: true });
+ }
+});
+
+test("auto-routing never offers an unavailable platform to Jev classifier", async () => {
+ const directory = await mkdtemp(path.join(os.tmpdir(), "jev-social-autoroute-"));
+ const mock = path.join(directory, "socai-mock.mjs");
+ await writeFile(
+ mock,
+ `#!/usr/bin/env node
+const args = process.argv.slice(2);
+if (args[0] === "--version") console.log("socai 0.5.6");
+else if (args[0] === "--help") console.log("socai root");
+else if (args[0] === "instagram" && args[1] === "--help") console.log("Commands: search");
+else if (args[0] === "tiktok" && args[1] === "--help") console.log("Commands: search");
+else if (args[0] === "linkedin" && args[1] === "--help") process.exitCode = 1;
+else if (args[0] === "instagram" && args[1] === "search") {
+ console.log(JSON.stringify({ ok: true, results: [{ url: "https://instagram.com/p/123", title: "Instagram art" }] }));
+}
+else process.exitCode = 2;
+`,
+ { mode: 0o755 },
+ );
+
+ const env = { ...process.env, SOCAI_BIN: mock, JEV_SOCIAL_HOME: directory };
+ let capturedRequest;
+ const client = {
+ async systemOne(request) {
+ if (request.questions.route) {
+ capturedRequest = request;
+ return {
+ answers: {
+ route: { type: "choice", choice: "instagram_search", confidence: 0.95 },
+ },
+ };
+ }
+ const criteria = request.questions.action?.criteria || {};
+ const choice = Object.keys(criteria).find((k) => k === "finish") || Object.keys(criteria)[0];
+ return {
+ answers: {
+ action: { type: "choice", choice, confidence: 0.99 },
+ },
+ };
+ },
+ };
+
+ try {
+ const run = await runSearch({ query: "find creatives", platform: "auto" }, { env, client });
+ assert.equal(run.platform, "instagram");
+ assert.ok(capturedRequest, "Classifier should be invoked for auto routing");
+ assert.deepEqual(
+ capturedRequest.state.supported_workflows,
+ [
+ "Read-only Instagram search via the socai CLI",
+ "Read-only TikTok search via the socai CLI",
+ ],
+ "LinkedIn workflow must not be offered when unavailable",
+ );
+ assert.equal(capturedRequest.questions.route.criteria.linkedin_search, undefined);
+ assert.ok(capturedRequest.questions.route.criteria.instagram_search);
+ assert.ok(capturedRequest.questions.route.criteria.tiktok_search);
+ assert.ok(capturedRequest.questions.route.criteria.unsupported);
+ } finally {
+ await rm(directory, { recursive: true, force: true });
+ }
+});
+
+test("runSearch aborts promptly when cancelled during preflight probe", async () => {
+ const directory = await mkdtemp(path.join(os.tmpdir(), "jev-social-abort-search-"));
+ const mock = path.join(directory, "socai-mock.mjs");
+ await writeFile(
+ mock,
+ `#!/usr/bin/env node
+setTimeout(() => {}, 30_000);
+`,
+ { mode: 0o755 },
+ );
+ await chmod(mock, 0o755);
+
+ const env = { ...process.env, SOCAI_BIN: mock, JEV_SOCIAL_HOME: directory };
+ try {
+ const controller = new AbortController();
+ const searchPromise = runSearch({ query: "art", platform: "instagram" }, { env, signal: controller.signal });
+ setTimeout(() => controller.abort(), 50);
+
+ await assert.rejects(searchPromise, (err) => {
+ return err.code === "SOCAI_ABORTED" || err.name === "AbortError";
+ });
+ } finally {
+ await rm(directory, { recursive: true, force: true });
+ }
+});
+
test("an interrupted run checkpoints completed actions and public evidence", async () => {
const { directory, env } = await fixture();
const controller = new AbortController();
diff --git a/test/classifier.test.js b/test/classifier.test.js
index 20c5e58..28b7173 100644
--- a/test/classifier.test.js
+++ b/test/classifier.test.js
@@ -141,3 +141,60 @@ test("classifySearch fails closed on a malformed Jev decision", async () => {
(error) => error.code === "INVALID_JEV_RESPONSE",
);
});
+
+test("classifySearch dynamically filters workflows and route criteria based on capability set", async () => {
+ let request;
+ const client = {
+ async systemOne(value) {
+ request = value;
+ return {
+ answers: {
+ route: { type: "choice", choice: "instagram_search", confidence: 0.9 },
+ },
+ };
+ },
+ };
+
+ const capabilities = { instagram: true, tiktok: false, linkedin: false };
+ const result = await classifySearch({
+ goal: "find creators",
+ requestedPlatform: "auto",
+ capabilities,
+ client,
+ });
+
+ assert.equal(result.platform, "instagram");
+ assert.deepEqual(request.state.supported_workflows, [
+ "Read-only Instagram search via the socai CLI",
+ ]);
+ assert.deepEqual(Object.keys(request.questions.route.criteria), [
+ "instagram_search",
+ "unsupported",
+ ]);
+});
+
+test("classifySearch throws SOCAI_CAPABILITY_MISSING when requested platform is disabled in capabilities", async () => {
+ let called = false;
+ const client = {
+ async systemOne() {
+ called = true;
+ return { answers: { route: { type: "choice", choice: "linkedin_search", confidence: 0.9 } } };
+ },
+ };
+
+ const capabilities = { instagram: true, tiktok: true, linkedin: false };
+ await assert.rejects(
+ classifySearch({
+ goal: "find product managers",
+ requestedPlatform: "linkedin",
+ capabilities,
+ client,
+ }),
+ (error) => {
+ assert.equal(error.code, "SOCAI_CAPABILITY_MISSING");
+ assert.equal(error.details?.platform, "linkedin");
+ return true;
+ },
+ );
+ assert.equal(called, false, "Model must not be called when platform is not in capabilities");
+});
diff --git a/test/onboard.test.js b/test/onboard.test.js
index 14e6ae5..b4a6d58 100644
--- a/test/onboard.test.js
+++ b/test/onboard.test.js
@@ -22,3 +22,21 @@ test("environment-only OpenRouter keys are not persisted during onboarding", asy
await rm(directory, { recursive: true, force: true });
}
});
+
+test("saveOnboarding reports the resolved socai bin path for CLI output", async () => {
+ const directory = await mkdtemp(path.join(os.tmpdir(), "jev-social-onboard-bin-"));
+ const mockBin = path.join(directory, "mock-socai.mjs");
+ const env = {
+ ...process.env,
+ JEV_SOCIAL_HOME: directory,
+ OPENROUTER_API_KEY: "test-key",
+ SOCAI_BIN: mockBin,
+ };
+ try {
+ const result = await saveOnboarding({ verify: false, persistApiKey: true, socaiBin: mockBin, env });
+ assert.equal(result.socai.bin, mockBin, "socai.bin must be present in saveOnboarding result for CLI callers");
+ assert.notEqual(result.socai.bin, undefined);
+ } finally {
+ await rm(directory, { recursive: true, force: true });
+ }
+});
diff --git a/test/prompts.test.js b/test/prompts.test.js
index a40c98a..a4f0167 100644
--- a/test/prompts.test.js
+++ b/test/prompts.test.js
@@ -132,3 +132,57 @@ test("bindPromptButtons registers click listeners, prevents default submit, and
cleanup();
assert.equal(clickListener, null);
});
+
+test("updatePromptButtons visibly disables unsupported platforms with accessible explanations", async () => {
+ const { updatePromptButtons } = await import("../public/prompts.js");
+ const attributes = new Map();
+ const mockButton = {
+ dataset: { platform: "linkedin", query: "find PMs" },
+ disabled: false,
+ setAttribute(name, value) {
+ attributes.set(name, value);
+ },
+ removeAttribute(name) {
+ attributes.delete(name);
+ },
+ getAttribute(name) {
+ return attributes.get(name);
+ },
+ };
+
+ updatePromptButtons([mockButton], { instagram: true, tiktok: true, linkedin: false });
+ assert.equal(mockButton.disabled, true);
+ assert.equal(mockButton.title, "LinkedIn search isn't available in this socai build");
+ assert.equal(attributes.get("aria-description"), "LinkedIn search isn't available in this socai build");
+ assert.equal(attributes.get("aria-disabled"), "true");
+
+ let clicked = false;
+ const mockQuery = { value: "" };
+ const mockPlatform = { value: "auto" };
+ let listener = null;
+ mockButton.addEventListener = (_type, cb) => {
+ listener = cb;
+ };
+ mockButton.removeEventListener = () => {
+ listener = null;
+ };
+
+ bindPromptButtons({
+ buttons: [mockButton],
+ queryElement: mockQuery,
+ platformElement: mockPlatform,
+ onSelect() {
+ clicked = true;
+ },
+ });
+
+ listener({ preventDefault() {} });
+ assert.equal(clicked, false, "Disabled button click must not trigger onSelect");
+ assert.equal(mockQuery.value, "", "Disabled button must not set query value");
+
+ updatePromptButtons([mockButton], { instagram: true, tiktok: true, linkedin: true });
+ assert.equal(mockButton.disabled, false);
+ assert.equal(mockButton.title, "");
+ assert.equal(attributes.has("aria-description"), false);
+ assert.equal(attributes.has("aria-disabled"), false);
+});
diff --git a/test/server.test.js b/test/server.test.js
index 4d0f74c..6026bc1 100644
--- a/test/server.test.js
+++ b/test/server.test.js
@@ -17,6 +17,11 @@ test("local APIs require exact same-origin JSON and typed onboarding fields", as
assert.match(previewModule.headers.get("content-type"), /^text\/javascript/);
assert.match(await previewModule.text(), /selectSummaryCards/);
+ const statusModule = await fetch(`${url}/status.js`);
+ assert.equal(statusModule.status, 200);
+ assert.match(statusModule.headers.get("content-type"), /^text\/javascript/);
+ assert.match(await statusModule.text(), /deriveStatusView/);
+
const wrongOrigin = await fetch(`${url}/api/onboard`, {
method: "POST",
headers: {
@@ -80,3 +85,78 @@ test("saved socai media is exposed through an opaque range-capable local URL", a
await rm(directory, { recursive: true, force: true });
}
});
+
+test("/api/status returns exact sanitized shape and no leaked paths or env variables", async () => {
+ const directory = await mkdtemp(path.join(os.tmpdir(), "jev-social-status-"));
+ const mock = path.join(directory, "socai-mock.mjs");
+ await writeFile(
+ mock,
+ `#!/usr/bin/env node
+const args = process.argv.slice(2);
+if (args[0] === "--version") console.log("socai 0.5.6");
+else if (args[0] === "--help") console.log("socai root");
+else if (args[0] === "instagram" && args[1] === "--help") console.log("Commands: search");
+else if (args[0] === "tiktok" && args[1] === "--help") console.log("Commands: search");
+else if (args[0] === "linkedin" && args[1] === "--help") process.exitCode = 1;
+else process.exitCode = 2;
+`,
+ { mode: 0o755 },
+ );
+
+ const env = {
+ ...process.env,
+ SOCAI_BIN: mock,
+ OPENROUTER_API_KEY: "secret-key-123",
+ OPENROUTER_JEV_MODEL: "~typesafe/jev-latest",
+ };
+ const { server, url } = await startServer({ port: 0, open: false, env });
+ try {
+ const response = await fetch(`${url}/api/status`);
+ assert.equal(response.status, 200);
+ const body = await response.json();
+ assert.deepEqual(body, {
+ jevConfigured: true,
+ jevModel: "~typesafe/jev-latest",
+ socai: {
+ installed: true,
+ version: "0.5.6",
+ capabilities: {
+ instagram: true,
+ tiktok: true,
+ linkedin: false,
+ },
+ },
+ });
+ const text = JSON.stringify(body);
+ assert.ok(!text.includes("secret-key-123"), "API key must not leak");
+ assert.ok(!text.includes(directory), "Filesystem path must not leak");
+ assert.ok(!text.includes("socai-mock.mjs"), "Binary filename must not leak");
+ assert.equal(body.configPath, undefined);
+ assert.equal(body.socai.bin, undefined, "/api/status must omit bin property");
+ } finally {
+ await new Promise((resolve, reject) => server.close((error) => (error ? reject(error) : resolve())));
+ await rm(directory, { recursive: true, force: true });
+ }
+});
+
+test("/api/status never leaks config path when readConfig fails", async () => {
+ const directory = await mkdtemp(path.join(os.tmpdir(), "jev-social-err-status-"));
+ await writeFile(path.join(directory, "config.json"), "{ invalid JSON syntax !!!");
+ const badEnv = {
+ ...process.env,
+ JEV_SOCIAL_HOME: directory,
+ };
+ const { server, url } = await startServer({ port: 0, open: false, env: badEnv });
+ try {
+ const response = await fetch(`${url}/api/status`);
+ assert.equal(response.status, 200);
+ const body = await response.json();
+ assert.equal(body.jevConfigured, false);
+ assert.equal(body.configError, "Configuration could not be read.");
+ const text = JSON.stringify(body);
+ assert.ok(!text.includes(directory), "Filesystem path must not leak when readConfig fails");
+ } finally {
+ await new Promise((resolve, reject) => server.close((error) => (error ? reject(error) : resolve())));
+ await rm(directory, { recursive: true, force: true });
+ }
+});
diff --git a/test/socai.test.js b/test/socai.test.js
index a08a1c3..e68aab8 100644
--- a/test/socai.test.js
+++ b/test/socai.test.js
@@ -179,3 +179,360 @@ test("runSocaiSearch cancels an in-flight capability probe", async () => {
await rm(directory, { recursive: true, force: true });
}
});
+
+test("probeSocai extracts semver version, evaluates per-platform capabilities, and leaks no paths", async () => {
+ const directory = await mkdtemp(path.join(os.tmpdir(), "jev-social-probe-"));
+ const mock = path.join(directory, "socai-mock.mjs");
+ await writeFile(
+ mock,
+ `#!/usr/bin/env node
+const args = process.argv.slice(2);
+if (args[0] === "--version") {
+ console.log("socai version 0.5.6-beta.1 (x86_64-linux)");
+} else if (args[0] === "--help") {
+ console.log("socai root help");
+} else if (args[0] === "instagram" && args[1] === "--help") {
+ console.log("Commands: search");
+} else if (args[0] === "tiktok" && args[1] === "--help") {
+ console.log("Commands: search");
+} else if (args[0] === "linkedin" && args[1] === "--help") {
+ console.log("Unknown platform");
+ process.exitCode = 1;
+} else {
+ process.exitCode = 2;
+}
+`,
+ { mode: 0o755 },
+ );
+ await chmod(mock, 0o755);
+
+ try {
+ const env = { ...process.env, SOCAI_BIN: mock };
+ const status = await probeSocai({}, env);
+ assert.equal(status.installed, true);
+ assert.equal(status.version, "0.5.6-beta.1");
+ assert.deepEqual(status.capabilities, {
+ instagram: true,
+ tiktok: true,
+ linkedin: false,
+ });
+ assert.equal(status.bin, mock, "probeSocai must retain bin internally for CLI callers");
+ assert.equal(status.configPath, undefined);
+ } finally {
+ await rm(directory, { recursive: true, force: true });
+ }
+});
+
+test("sanitizeCliErrorText redacts all types of system paths including /opt, /usr, /var, tildes and spawn ENOENT", async () => {
+ const { sanitizeCliErrorText } = await import("../src/socai.js");
+
+ assert.equal(
+ sanitizeCliErrorText("Error: cannot exec /opt/homebrew/bin/socai"),
+ "Error: cannot exec [path]",
+ );
+ assert.equal(
+ sanitizeCliErrorText("spawn /usr/local/bin/socai ENOENT"),
+ "spawn [path] ENOENT",
+ );
+ assert.equal(
+ sanitizeCliErrorText("spawn /Volumes/My Disk/socai ENOENT"),
+ "spawn [path] ENOENT",
+ );
+ assert.equal(
+ sanitizeCliErrorText("spawn '/Volumes/My Disk/socai' ENOENT"),
+ "spawn [path] ENOENT",
+ );
+ assert.equal(
+ sanitizeCliErrorText("Error: C:\\Program Files\\socai\\socai.exe not found"),
+ "Error: [path] not found",
+ );
+ assert.equal(
+ sanitizeCliErrorText('"C:\\Program Files\\socai\\socai.exe" is not recognized'),
+ "[path] is not recognized",
+ );
+ assert.equal(
+ sanitizeCliErrorText("/usr/local/bin/socai exited with code 1"),
+ "[path] exited with code 1",
+ );
+ assert.equal(
+ sanitizeCliErrorText("socai: /var/log/socai.err: Permission denied"),
+ "socai: [path]: Permission denied",
+ );
+ assert.equal(
+ sanitizeCliErrorText("cannot load configuration from ~/.socai/config.json"),
+ "cannot load configuration from [path]",
+ );
+ assert.equal(
+ sanitizeCliErrorText("error in ./bin/socai script"),
+ "error in [path] script",
+ );
+ assert.equal(
+ sanitizeCliErrorText("socai v0.5.6 (3/3 ready)"),
+ "socai v0.5.6 (3/3 ready)",
+ "Non-path phrases like (3/3 ready) must not be corrupted",
+ );
+ assert.equal(
+ sanitizeCliErrorText("See https://example.com/docs/troubleshooting"),
+ "See https://example.com/docs/troubleshooting",
+ "HTTPS URLs must be preserved intact",
+ );
+ assert.equal(
+ sanitizeCliErrorText("See http://internal.local/status"),
+ "See http://internal.local/status",
+ "HTTP URLs must be preserved intact",
+ );
+ assert.equal(
+ sanitizeCliErrorText("Visit https://socai.dev/auth?token=abc for help (logged to /var/log/socai.err)"),
+ "Visit https://socai.dev/auth?token=abc for help (logged to [path])",
+ "URLs must remain intact while local filesystem paths in same error are redacted",
+ );
+ assert.equal(
+ sanitizeCliErrorText("Docs https://example.com/help?log=/Users/alice/private.txt"),
+ "Docs https://example.com/help?log=[path]",
+ "Query parameters containing local paths must be redacted",
+ );
+ assert.equal(
+ sanitizeCliErrorText("Docs https://example.com/help#C:\\Users\\Alice\\secret.txt"),
+ "Docs https://example.com/help#[path]",
+ "Fragments containing local paths must be redacted",
+ );
+ assert.equal(
+ sanitizeCliErrorText("See https://example.com/help?topic=login&path=C:%5CUsers%5CAlice%5Csecret.txt"),
+ "See https://example.com/help?topic=login&path=[path]",
+ "Preserve non-path query parameters while redacting path-valued query parameters",
+ );
+ assert.equal(
+ sanitizeCliErrorText("See https://example.com/help?log=/secrets.env#log=logs/error.txt"),
+ "See https://example.com/help?log=[path]#log=[path]",
+ "Root-level and one-separator paths in URLs must be redacted",
+ );
+ assert.equal(
+ sanitizeCliErrorText("See https://example.com/help?log=%252FUsers%252Falice%252Fsecret.txt"),
+ "See https://example.com/help?log=[path]",
+ "Double-encoded filesystem paths must be redacted",
+ );
+ assert.equal(
+ sanitizeCliErrorText("cannot open /nix/store/abcd/config because the login expired"),
+ "cannot open [path] because the login expired",
+ "Progress sanitization must preserve useful prose after an uncommon POSIX path",
+ );
+ assert.equal(
+ sanitizeCliErrorText("retrying after file:///tmp/private/session.json failed"),
+ "retrying after [path] failed",
+ "Local file URLs must be redacted without losing surrounding prose",
+ );
+ assert.equal(
+ sanitizeCliErrorText(String.raw`retrying after \temp\secret.txt failed`),
+ "retrying after [path] failed",
+ "Rooted Windows paths must be redacted",
+ );
+ assert.equal(
+ sanitizeCliErrorText("See https://example.com/help?log=%255Ctemp%255Csecret.txt&topic=login"),
+ "See https://example.com/help?log=[path]&topic=login",
+ "Double-encoded rooted Windows paths in URLs must be redacted",
+ );
+ assert.equal(
+ sanitizeCliErrorText("cannot open /nix/store/abcd/config and check your login"),
+ "cannot open [path] and check your login",
+ "Conjunctions after paths must remain visible",
+ );
+ assert.equal(
+ sanitizeCliErrorText("retrying logs/my private/error.txt after authentication"),
+ "retrying [path] after authentication",
+ "Relative paths containing spaces must be fully redacted",
+ );
+ assert.equal(
+ sanitizeCliErrorText("failed at project/config but session remains usable"),
+ "failed at [path] but session remains usable",
+ "Single-separator relative paths must be redacted",
+ );
+ assert.equal(
+ sanitizeCliErrorText(String.raw`cannot open \\server\share\secret.txt; retrying safely`),
+ "cannot open [path]; retrying safely",
+ "UNC paths must be redacted",
+ );
+ assert.equal(
+ sanitizeCliErrorText("See https://example.com/help?log=logs/my%20private/error.txt&topic=login"),
+ "See https://example.com/help?log=[path]&topic=login",
+ "Encoded relative paths containing spaces in URLs must be redacted",
+ );
+ assert.equal(
+ sanitizeCliErrorText("cannot open /nix/store/abcd/config so check your login"),
+ "cannot open [path] so check your login",
+ "Arbitrary prose after a path without spaces must remain visible",
+ );
+ for (const relativePath of [".config/secrets", "2026/secrets", "@scope/private", "日本語/秘密.txt"]) {
+ assert.equal(
+ sanitizeCliErrorText(`failed reading ${relativePath} but retrying`),
+ "failed reading [path] but retrying",
+ `Relative path ${relativePath} must be redacted`,
+ );
+ }
+ for (const spacedPath of ["/tmp/private report.txt", "logs/private report.txt"]) {
+ assert.equal(
+ sanitizeCliErrorText(`cannot open ${spacedPath}; retrying`),
+ "cannot open [path]; retrying",
+ `Path ending in a spaced filename ${spacedPath} must be fully redacted`,
+ );
+ }
+ assert.equal(
+ sanitizeCliErrorText("retrying logs/my private/error.txt so authenticate again"),
+ "retrying [path] so authenticate again",
+ "Filename extensions must provide a prose-independent path boundary",
+ );
+});
+
+test("platformSupported returns false when help text mentions 'search' but the subcommand is absent", async () => {
+ const { platformSupported } = await import("../src/socai.js");
+ const directory = await mkdtemp(path.join(os.tmpdir(), "jev-social-neg-help-"));
+ const mock = path.join(directory, "socai-mock.mjs");
+ await writeFile(
+ mock,
+ `#!/usr/bin/env node
+const args = process.argv.slice(2);
+if (args[0] === "linkedin" && args[1] === "--help") {
+ console.log("linkedin search is unavailable in this build\\nCommands: profile company");
+} else if (args[0] === "linkedin" && args[1] === "search" && args[2] === "--help") {
+ console.error("unknown command: search");
+ process.exitCode = 1;
+} else {
+ process.exitCode = 2;
+}
+`,
+ { mode: 0o755 },
+ );
+ await chmod(mock, 0o755);
+
+ try {
+ const isSupported = await platformSupported(mock, "linkedin");
+ assert.equal(isSupported, false, "Disclaimers mentioning search must not trigger false positive");
+ } finally {
+ await rm(directory, { recursive: true, force: true });
+ }
+});
+
+test("platformSupported returns true only when the subcommand help genuinely succeeds", async () => {
+ const { platformSupported } = await import("../src/socai.js");
+ const directory = await mkdtemp(path.join(os.tmpdir(), "jev-social-pos-help-"));
+ const mock = path.join(directory, "socai-mock.mjs");
+ await writeFile(
+ mock,
+ `#!/usr/bin/env node
+const args = process.argv.slice(2);
+if (args[0] === "instagram" && args[1] === "search" && args[2] === "--help") {
+ console.log("Usage: socai instagram search <query>");
+} else {
+ process.exitCode = 2;
+}
+`,
+ { mode: 0o755 },
+ );
+ await chmod(mock, 0o755);
+
+ try {
+ const isSupported = await platformSupported(mock, "instagram");
+ assert.equal(isSupported, true, "Subcommand search --help exit 0 must report platform supported");
+ } finally {
+ await rm(directory, { recursive: true, force: true });
+ }
+});
+
+test("actionCapabilities and platformSupported agree when platform help mentions search but subcommand fails", async () => {
+ const { actionCapabilities, platformSupported } = await import("../src/socai.js");
+ const directory = await mkdtemp(path.join(os.tmpdir(), "jev-social-agree-"));
+ const mock = path.join(directory, "socai-mock.mjs");
+ await writeFile(
+ mock,
+ `#!/usr/bin/env node
+const args = process.argv.slice(2);
+if (args[0] === "linkedin" && args[1] === "--help") {
+ console.log("linkedin search is unavailable in this build\\nCommands: profile company");
+} else if (args[0] === "linkedin" && args[1] === "search" && args[2] === "--help") {
+ console.error("unknown command: search");
+ process.exitCode = 1;
+} else {
+ process.exitCode = 2;
+}
+`,
+ { mode: 0o755 },
+ );
+ await chmod(mock, 0o755);
+
+ try {
+ const isSupported = await platformSupported(mock, "linkedin");
+ assert.equal(isSupported, false);
+
+ const env = { ...process.env, SOCAI_BIN: mock };
+ const commandsWithoutCap = await actionCapabilities({ env, platform: "linkedin" });
+ assert.deepEqual(commandsWithoutCap, ["profile", "company"], "Must not include search when subcommand probe fails");
+
+ const commandsWithCap = await actionCapabilities({ env, platform: "linkedin", capabilities: { linkedin: false } });
+ assert.deepEqual(commandsWithCap, ["profile", "company"], "Must respect precomputed capabilities");
+ } finally {
+ await rm(directory, { recursive: true, force: true });
+ }
+});
+
+test("actionCapabilities and platformSupported agree in positive-probe/failed-parent case", async () => {
+ const { actionCapabilities, platformSupported } = await import("../src/socai.js");
+ const directory = await mkdtemp(path.join(os.tmpdir(), "jev-social-pos-agree-"));
+ const mock = path.join(directory, "socai-mock.mjs");
+ await writeFile(
+ mock,
+ `#!/usr/bin/env node
+const args = process.argv.slice(2);
+if (args[0] === "instagram" && args[1] === "search" && args[2] === "--help") {
+ console.log("Usage: socai instagram search <query>");
+} else if (args[0] === "instagram" && args[1] === "--help") {
+ console.error("parent platform help failed");
+ process.exitCode = 1;
+} else {
+ process.exitCode = 2;
+}
+`,
+ { mode: 0o755 },
+ );
+ await chmod(mock, 0o755);
+
+ try {
+ const isSupported = await platformSupported(mock, "instagram");
+ assert.equal(isSupported, true, "Concrete search probe succeeding must make platform supported");
+
+ const env = { ...process.env, SOCAI_BIN: mock };
+ const commandsWithoutCap = await actionCapabilities({ env, platform: "instagram" });
+ assert.deepEqual(commandsWithoutCap, ["search"], "Must expose search when subcommand succeeds despite parent failure");
+
+ const commandsWithCap = await actionCapabilities({ env, platform: "instagram", capabilities: { instagram: true } });
+ assert.deepEqual(commandsWithCap, ["search"], "Must respect precomputed capability and expose search despite parent failure");
+ } finally {
+ await rm(directory, { recursive: true, force: true });
+ }
+});
+
+test("probeSocai forwards cancellation signal promptly without waiting for timeout", async () => {
+ const { probeSocai } = await import("../src/socai.js");
+ const directory = await mkdtemp(path.join(os.tmpdir(), "jev-social-abort-probe-"));
+ const mock = path.join(directory, "socai-mock.mjs");
+ await writeFile(
+ mock,
+ `#!/usr/bin/env node
+setTimeout(() => {}, 30_000);
+`,
+ { mode: 0o755 },
+ );
+ await chmod(mock, 0o755);
+
+ try {
+ const controller = new AbortController();
+ const env = { ...process.env, SOCAI_BIN: mock };
+ const probePromise = probeSocai({}, env, controller.signal);
+ // Abort shortly after spawning
+ setTimeout(() => controller.abort(), 50);
+
+ await assert.rejects(probePromise, (err) => {
+ return err.code === "SOCAI_ABORTED" || err.name === "AbortError";
+ });
+ } finally {
+ await rm(directory, { recursive: true, force: true });
+ }
+});
diff --git a/test/status.test.js b/test/status.test.js
new file mode 100644
index 0000000..80b16af
--- /dev/null
+++ b/test/status.test.js
@@ -0,0 +1,34 @@
+import assert from "node:assert/strict";
+import test from "node:test";
+import { deriveStatusView } from "../public/status.js";
+
+test("malformed configuration is surfaced without replacing it with misleading readiness labels", () => {
+ const view = deriveStatusView({
+ jevConfigured: false,
+ configError: "Configuration could not be read.",
+ socai: {
+ installed: false,
+ capabilities: { instagram: false, tiktok: false, linkedin: false },
+ },
+ });
+
+ assert.equal(view.error, "Configuration could not be read.");
+ assert.deepEqual(view.jev, { ready: false, label: "Configuration unavailable" });
+ assert.deepEqual(view.socai, { ready: false, label: "Configuration unavailable" });
+ assert.doesNotMatch(JSON.stringify(view), /Jev needs a key|socai unavailable/);
+});
+
+test("healthy status retains versioned per-platform readiness", () => {
+ const view = deriveStatusView({
+ jevConfigured: true,
+ socai: {
+ installed: true,
+ version: "0.6.0",
+ capabilities: { instagram: true, tiktok: true, linkedin: false },
+ },
+ });
+
+ assert.equal(view.error, "");
+ assert.deepEqual(view.jev, { ready: true, label: "Jev ready" });
+ assert.deepEqual(view.socai, { ready: false, label: "socai v0.6.0 (2/3 ready)" });
+});