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
Report privacy-safe browser readiness (#43)
Asklv6a9502d5a727
diff --git a/bin/jev-social.js b/bin/jev-social.jsindex de71a9d..d593ef1 100755--- a/bin/jev-social.js+++ b/bin/jev-social.js@@ -47,7 +47,7 @@ try {jevConfigured: Boolean(resolveApiKey(config)),jevModel: process.env.OPENROUTER_JEV_MODEL || "~typesafe/jev-latest",configPath: getConfigPath(),- socai: await probeSocai(config),+ socai: await probeSocai(config, process.env, undefined, { includeReadiness: true }),},null,2,diff --git a/docs/troubleshooting.md b/docs/troubleshooting.mdindex b44763b..2489c97 100644--- a/docs/troubleshooting.md+++ b/docs/troubleshooting.md@@ -47,7 +47,7 @@ By default (using `existing` or `managed` Chrome modes without external endpoint| State | What Happened | What You See | How to Resolve || --- | --- | --- | --- || **Missing `socai` executable** | The `socai` CLI is not installed or not discoverable at the resolved binary path. | Status indicator displays `socai unavailable`, or terminal reports `spawn ENOENT` / command not found. | On macOS and Windows, run `npx --yes github:socai-io/jev-social onboard` (or `npm start -- onboard`). On Linux, install the CLI package from source via Cargo (`cargo install --git https://github.com/socai-io/socai.git socai-cli`) and set `SOCAI_BIN`. |-| **Browser connection failure** | `socai` cannot connect to Chrome or its DevTools protocol (CDP) endpoint. | Error indicates connection refusal (e.g. `ECONNREFUSED 127.0.0.1:9222`), socket error, or browser launch timeout. | Follow your active connection mode below. Ensure the target Chrome instance is running with remote debugging enabled and accept any remote-debugging permission prompts. Avoid blanket process-killing commands. |+| **Browser connection failure** | `socai` cannot connect to Chrome or its DevTools protocol (CDP) endpoint. | The readiness strip shows `Chrome unavailable`, `Chrome permission needed`, `Chrome disconnected`, or `Remote browser unavailable` with a short local action. | Follow your active connection mode below. Ensure the target Chrome instance is running with remote debugging enabled and accept any remote-debugging permission prompts. Avoid blanket process-killing commands. || **Login-required / challenge gate** | The platform blocked unauthenticated access with a login modal, redirect (e.g. `authwall`), or CAPTCHA. | Status displays a partial result notice with the specific gate reason (for example, `Partial results · The platform requires attention: login_required`). | Open the platform in the specific user-accessible Chrome session or profile selected by `socai` (`existing` or `managed` mode), complete authentication or challenges, and verify browsing before re-running. (If using hosted `remote` mode, switch to `existing` or `managed` mode to authenticate interactively.) || **Valid empty result** | The platform loaded successfully and the search executed cleanly, but returned 0 matching records. | Evidence cards, table, and heading remain hidden. Depending on subsequent decisions, the run can finalize as `partial` (`Partial results · Jev stopped without usable evidence.`), `step_limit` (if max steps are reached), or `decision_failed` (if a subsequent model decision call fails). | The initial search executed cleanly without matching records on the platform. Broaden or rephrase your search query. (If a subsequent decision failed, verify model API connectivity). || **Early decision or classification failure** | Jev encountered an error during classification or the very first action decision before any browser operations ran. | Classification failures emit an error before a run exists. A first action-decision failure saves a failed checkpoint with no captured posts. | Ensure your query is a supported read-only social research goal, specify `--platform` explicitly, or check your OpenRouter key and network connection. |@@ -82,11 +82,33 @@ The browser API endpoint `/api/status` returns sanitized status and omits local"instagram": true,"tiktok": true,"linkedin": true+ },+ "readiness": {+ "schemaVersion": 1,+ "cliAvailable": true,+ "daemonRunning": true,+ "daemonCompatible": true,+ "browserConnected": true,+ "browserState": "connected",+ "profileMode": "existing",+ "activeProfileMode": "existing",+ "errorCode": null,+ "platforms": {+ "instagram": { "available": true, "loginState": "unknown", "operations": ["search", "get-posts"] },+ "tiktok": { "available": true, "loginState": "unknown", "operations": ["search", "get-videos"] },+ "linkedin": { "available": true, "loginState": "unknown", "operations": ["search", "get-posts"] }+ }}}}```+The readiness probe is observational: it calls `socai status --json`, which does not start the daemon, launch Chrome, connect a browser, or show a permission prompt. Jev Social validates and allowlists that response before returning it. WebSocket URLs, ports, cookies, profile paths, session tokens, and the CLI's free-form `next_step` text are never exposed through `/api/status`.++An older `socai` build that does not support `status --json` remains usable. The UI reports `Chrome state unknown` and recommends updating `socai`; it does not repeatedly attempt a browser connection or block a research run.++When socai can identify platform authentication independently, the platform picker labels it as `(signed in)` or `(sign in)`. An `unknown` login state remains unlabeled: it is not treated as either authenticated or logged out.+*(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.)*For local operator diagnostics including the resolved configuration file path and binary path, run the CLI status command:@@ -110,6 +132,12 @@ Expected output:"instagram": true,"tiktok": true,"linkedin": true+ },+ "readiness": {+ "browserConnected": true,+ "browserState": "connected",+ "profileMode": "existing",+ "activeProfileMode": "existing"}}}diff --git a/public/app.js b/public/app.jsindex 6633e2f..88fa32c 100644--- a/public/app.js+++ b/public/app.js@@ -19,6 +19,7 @@ const elements = {resultView: $("#result-view"),searchForm: $("#search-form"),platformNotice: $("#platform-notice"),+ browserHint: $("#browser-hint"),activity: $("#activity"),activityTitle: $("#activity-title"),activityMessage: $("#activity-message"),@@ -229,16 +230,21 @@ async function refreshStatus() {const view = deriveStatusView(status);setStatus("jev", view.jev.ready, view.jev.label);setStatus("socai", view.socai.ready, view.socai.label);+ setStatus("browser", view.browser.ready, view.browser.label);+ if (elements.browserHint) {+ elements.browserHint.textContent = view.browser.hint;+ elements.browserHint.classList.toggle("hidden", !view.browser.hint);+ }if (view.error) showError(new Error(view.error));- updatePlatformOptions(view.capabilities);+ updatePlatformOptions(view.capabilities, view.platforms);updatePromptButtons(document.querySelectorAll(".prompt-example-btn"), view.capabilities);} catch (error) {showError(error);}}-function updatePlatformOptions(caps = {}) {+function updatePlatformOptions(caps = {}, platformStatuses = {}) {const platformSelect = $("#platform");if (!platformSelect) return;const previousValue = platformSelect.value;@@ -257,8 +263,17 @@ function updatePlatformOptions(caps = {}) {switchedToAuto = true;}} else {- option.title = "";- option.textContent = label;+ const loginState = platformStatuses[val]?.loginState || "unknown";+ if (loginState === "authenticated") {+ option.title = `${label} login detected by socai`;+ option.textContent = `${label} (signed in)`;+ } else if (loginState === "unauthenticated") {+ option.title = `${label} requires a login in the selected Chrome profile`;+ option.textContent = `${label} (sign in)`;+ } else {+ option.title = "";+ option.textContent = label;+ }}}diff --git a/public/index.html b/public/index.htmlindex c470bc9..566480c 100644--- a/public/index.html+++ b/public/index.html@@ -56,9 +56,11 @@<div class="readiness" aria-live="polite"><span><i id="jev-dot"></i><b id="jev-status">Jev checking</b></span><span><i id="socai-dot"></i><b id="socai-status">socai checking</b></span>+ <span><i id="browser-dot"></i><b id="browser-status">Chrome checking</b></span></div><button class="button primary" type="submit">Run social research <span>↗</span></button></div>+ <div id="browser-hint" class="browser-hint hidden" role="status" aria-live="polite"></div></form><div class="prompt-examples" aria-label="Example research goals">diff --git a/public/status.js b/public/status.jsindex 0c24f7a..84dce80 100644--- a/public/status.js+++ b/public/status.js@@ -7,8 +7,10 @@ export function deriveStatusView(status = {}) {return {error: configError,capabilities,+ platforms: platformStatuses(capabilities),jev: { ready: false, label: "Configuration unavailable" },socai: { ready: false, label: "Configuration unavailable" },+ browser: { ready: false, label: "Configuration unavailable", hint: "" },};}@@ -26,10 +28,57 @@ export function deriveStatusView(status = {}) {return {error: "",capabilities,+ platforms: platformStatuses(capabilities, status.socai?.readiness?.platforms),jev: {ready: Boolean(status.jevConfigured),label: status.jevConfigured ? "Jev ready" : "Jev needs a key",},socai: { ready: allReady, label: socaiLabel },+ browser: browserStatus(status.socai?.readiness, installed),};}++function platformStatuses(capabilities, readinessPlatforms = {}) {+ return Object.fromEntries(PLATFORMS.map((platform) => {+ const loginState = readinessPlatforms[platform]?.loginState;+ return [platform, {+ available: Boolean(capabilities[platform]),+ loginState: ["authenticated", "unauthenticated"].includes(loginState) ? loginState : "unknown",+ }];+ }));+}++function browserStatus(readiness, installed) {+ if (!installed) return { ready: false, label: "Chrome unavailable", hint: "Install socai to enable browser research." };+ if (!readiness || readiness.browserConnected === null) {+ return {+ ready: false,+ label: "Chrome state unknown",+ hint: "Update socai to enable read-only browser diagnostics.",+ };+ }+ if (readiness.browserConnected && readiness.browserState === "connected") {+ const profile = readiness.activeProfileMode || readiness.profileMode;+ const suffix = profile && profile !== "unknown" ? ` · ${profile}` : "";+ return { ready: true, label: `Chrome connected${suffix}`, hint: "" };+ }+ if (readiness.browserState === "connecting") {+ return { ready: false, label: "Chrome connecting", hint: "socai is establishing read-only browser access." };+ }++ const safeGuidance = {+ BROWSER_NOT_CONNECTED: ["Chrome on demand", "A read-only research run will connect Chrome when needed."],+ DAEMON_UNAVAILABLE: ["Chrome on demand", "A read-only research run will start socai when needed."],+ BROWSER_DISCONNECTED: ["Chrome disconnected", "Reconnect from socai before starting research."],+ BROWSER_PERMISSION_REQUIRED: ["Chrome permission needed", "Allow Chrome data access and remote debugging, then try again."],+ BROWSER_ENDPOINT_UNREACHABLE: ["Chrome unavailable", "Start Chrome or choose the managed browser profile, then try again."],+ REMOTE_SESSION_UNAVAILABLE: ["Remote browser unavailable", "Check the remote browser service, then try again."],+ DAEMON_STATUS_UNAVAILABLE: ["Chrome state unknown", "Update or restart socai once to enable browser diagnostics."],+ BROWSER_CONNECTION_FAILED: ["Chrome connection failed", "Check the socai browser setup, then try again."],+ };+ const [label, hint] = safeGuidance[readiness.errorCode] || [+ "Chrome state unknown",+ "Browser access will be checked when research starts.",+ ];+ return { ready: false, label, hint };+}diff --git a/public/styles.css b/public/styles.cssindex 0bfdd37..06c631a 100644--- a/public/styles.css+++ b/public/styles.css@@ -59,6 +59,7 @@ h1 em { color: transparent; font-style: normal; -webkit-text-stroke: 1.5px var(-.readiness i { width: 7px; height: 7px; border: 1px solid var(--ink); border-radius: 50%; }.readiness i.ready { border-color: var(--green); background: var(--green); }.readiness b { font-weight: 500; }+.browser-hint { padding: 7px 12px; border-top: 1px solid var(--line); background: #fff8d9; color: #454027; font: 500 10px/1.45 var(--mono); }.button { min-height: 38px; border: 1px solid var(--ink); padding: 0 16px; background: #fff; font-size: 12px; font-weight: 750; }.button.primary { margin-left: auto; color: #fff; background: var(--ink); }.button.primary:hover { color: var(--ink); background: var(--pink); }diff --git a/src/server.js b/src/server.jsindex 6b87441..2ec9b22 100644--- a/src/server.js+++ b/src/server.js@@ -13,7 +13,7 @@ import { errorPayload } from "./errors.js";import { loadLocalEnv } from "./env.js";import { saveOnboarding } from "./onboard.js";import { listRuns, markInterruptedRuns, readRun } from "./runs.js";-import { probeSocai } from "./socai.js";+import { probeSocai, unknownSocaiReadiness } from "./socai.js";const PUBLIC_DIR = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../public");const MEDIA_TTL_MS = 60 * 60_000;@@ -94,11 +94,16 @@ async function handleRequest(request, response, env, mediaRegistry) {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 } },+ socai: {+ installed: false,+ version: null,+ capabilities: { instagram: false, tiktok: false, linkedin: false },+ readiness: unknownSocaiReadiness(false),+ },configError: "Configuration could not be read.",});}- const socai = await probeSocai(config, env);+ const socai = await probeSocai(config, env, undefined, { includeReadiness: true });return sendJson(response, 200, {jevConfigured: Boolean(resolveApiKey(config, env)),jevModel: env.OPENROUTER_JEV_MODEL || "~typesafe/jev-latest",@@ -106,6 +111,7 @@ async function handleRequest(request, response, env, mediaRegistry) {installed: socai.installed,version: socai.version ?? null,capabilities: socai.capabilities,+ readiness: socai.readiness,...(socai.error ? { error: socai.error } : {}),},});diff --git a/src/socai.js b/src/socai.jsindex ebf1d2f..c0db557 100644--- a/src/socai.js+++ b/src/socai.js@@ -4,6 +4,33 @@ import { formatCommand, runProcess } from "./process.js";import { buildActionArgs } from "./actions.js";const PLATFORMS = ["instagram", "tiktok", "linkedin"];+const BROWSER_STATES = new Set(["connected", "connecting", "disconnected", "unknown"]);+const PROFILE_MODES = new Set(["existing", "managed", "auto", "remote", "unknown"]);+const LOGIN_STATES = new Set(["authenticated", "unauthenticated", "unknown"]);+const BROWSER_ERROR_CODES = new Set([+ "BROWSER_NOT_CONNECTED",+ "BROWSER_DISCONNECTED",+ "BROWSER_PERMISSION_REQUIRED",+ "REMOTE_SESSION_UNAVAILABLE",+ "BROWSER_ENDPOINT_UNREACHABLE",+ "BROWSER_CONNECTION_FAILED",+ "DAEMON_STATUS_UNAVAILABLE",+ "DAEMON_UNAVAILABLE",+]);+const STATUS_OPERATIONS = new Set([+ "search",+ "get-posts",+ "get-videos",+ "get-notes",+ "profile",+ "author",+ "company",+ "company-people",+ "related-people",+ "history",+ "page_state",+ "author_scan",+]);export async function actionCapabilities({ config = {}, env = process.env, platform, signal, capabilities }) {if (!PLATFORMS.includes(platform)) throw new AppError("Unsupported platform.", { code: "INVALID_PLATFORM" });@@ -43,7 +70,7 @@ export async function resolveSocaiBin(config = {}, env = process.env) {return configuredSocaiBin(config, env) || (await defaultInstalledSocaiBin());}-export async function probeSocai(config = {}, env = process.env, signal) {+export async function probeSocai(config = {}, env = process.env, signal, { includeReadiness = false } = {}) {const bin = await resolveSocaiBin(config, env);try {const root = await runProcess(bin, ["--help"], { timeoutMs: 15_000, env, signal });@@ -54,17 +81,24 @@ export async function probeSocai(config = {}, env = process.env, signal) {bin,version: null,capabilities: { instagram: false, tiktok: false, linkedin: false },+ readiness: unknownSocaiReadiness(false),error: concise(root.stderr || root.stdout),};}- const version = await getSocaiVersion(bin, env, signal);const capabilities = { instagram: false, tiktok: false, linkedin: false };- await Promise.all(- PLATFORMS.map(async (platform) => {+ const [version, readiness] = await Promise.all([+ getSocaiVersion(bin, env, signal),+ includeReadiness+ ? readSocaiReadiness(bin, env, signal)+ : Promise.resolve(unknownSocaiReadiness(true)),+ ...PLATFORMS.map(async (platform) => {capabilities[platform] = await platformSupported(bin, platform, env, signal);}),- );- return { installed: true, bin, version, capabilities };+ ]);+ if (readiness.schemaVersion === null) {+ for (const platform of PLATFORMS) readiness.platforms[platform].available = capabilities[platform];+ }+ return { installed: true, bin, version, capabilities, readiness };} catch (error) {if (error?.code === "SOCAI_ABORTED" || error?.name === "AbortError" || signal?.aborted) {throw abortedError();@@ -74,11 +108,101 @@ export async function probeSocai(config = {}, env = process.env, signal) {bin,version: null,capabilities: { instagram: false, tiktok: false, linkedin: false },+ readiness: unknownSocaiReadiness(false),error: error.code === "ENOENT" ? "socai executable not found" : concise(error.message),};}}+export function unknownSocaiReadiness(cliAvailable = true) {+ return {+ schemaVersion: null,+ cliAvailable: Boolean(cliAvailable),+ daemonRunning: null,+ daemonCompatible: null,+ browserConnected: null,+ browserState: "unknown",+ profileMode: "unknown",+ activeProfileMode: null,+ errorCode: null,+ platforms: Object.fromEntries(+ PLATFORMS.map((platform) => [platform, { available: false, loginState: "unknown", operations: [] }]),+ ),+ };+}++export async function readSocaiReadiness(bin, env = process.env, signal, { timeoutMs = 5_000 } = {}) {+ try {+ const result = await runProcess(bin, ["status", "--json"], {+ timeoutMs,+ maxOutputBytes: 128 * 1024,+ env,+ signal,+ });+ if (result.aborted) throw abortedError();+ if (result.timedOut || result.overflowed) {+ return unknownSocaiReadiness(true);+ }+ const readiness = normalizeSocaiReadiness(JSON.parse(result.stdout.trim()));+ return readiness.schemaVersion === 1 ? readiness : unknownSocaiReadiness(true);+ } catch (error) {+ if (error?.code === "SOCAI_ABORTED" || error?.name === "AbortError" || signal?.aborted) {+ throw abortedError();+ }+ return unknownSocaiReadiness(true);+ }+}++export function normalizeSocaiReadiness(value) {+ const valid = value+ && typeof value === "object"+ && !Array.isArray(value)+ && value.schema_version === 1+ && typeof value.cli_available === "boolean"+ && typeof value.daemon_running === "boolean"+ && typeof value.daemon_compatible === "boolean"+ && typeof value.browser_connected === "boolean"+ && BROWSER_STATES.has(value.browser_state)+ && PROFILE_MODES.has(value.profile_mode)+ && (value.active_profile_mode === null || PROFILE_MODES.has(value.active_profile_mode))+ && Array.isArray(value.platforms);+ if (!valid) return unknownSocaiReadiness(true);++ const platforms = unknownSocaiReadiness(value.cli_available).platforms;+ for (const candidate of value.platforms) {+ if (!candidate || typeof candidate !== "object" || !PLATFORMS.includes(candidate.id)) continue;+ const loginState = LOGIN_STATES.has(candidate.login_state) ? candidate.login_state : "unknown";+ const operations = Array.isArray(candidate.operations)+ ? [...new Set(candidate.operations.filter((operation) => STATUS_OPERATIONS.has(operation)))]+ : [];+ platforms[candidate.id] = {+ available: candidate.available === true,+ loginState,+ operations,+ };+ }++ let errorCode = null;+ if (typeof value.error_code === "string" && BROWSER_ERROR_CODES.has(value.error_code)) {+ errorCode = value.error_code;+ } else if (value.browser_state === "disconnected" && value.error_code !== null) {+ errorCode = "BROWSER_CONNECTION_FAILED";+ }++ return {+ schemaVersion: 1,+ cliAvailable: value.cli_available,+ daemonRunning: value.daemon_running,+ daemonCompatible: value.daemon_compatible,+ browserConnected: value.browser_connected,+ browserState: value.browser_state,+ profileMode: value.profile_mode,+ activeProfileMode: value.active_profile_mode,+ errorCode,+ platforms,+ };+}+/*** 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`).diff --git a/test/server.test.js b/test/server.test.jsindex 0349002..8b73502 100644--- a/test/server.test.js+++ b/test/server.test.js@@ -102,6 +102,24 @@ test("/api/status returns exact sanitized shape and no leaked paths or env variaconst 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] === "status" && args[1] === "--json") console.log(JSON.stringify({+ schema_version: 1,+ cli_available: true,+ cli_version: "2",+ daemon_running: true,+ daemon_compatible: true,+ browser_connected: false,+ browser_state: "disconnected",+ profile_mode: "existing",+ active_profile_mode: null,+ error_code: "BROWSER_ENDPOINT_UNREACHABLE",+ next_step: "connect ws://127.0.0.1:9222/devtools/browser/private-token",+ profile_path: "/Users/private/Chrome/Profile 1",+ platforms: [+ { id: "instagram", available: true, login_state: "unknown", operations: ["search", "get-posts", "/Users/private/leak"] },+ { id: "tiktok", available: true, login_state: "unknown", operations: ["search", "get-videos"] },+ ],+}));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;@@ -132,12 +150,31 @@ else process.exitCode = 2;tiktok: true,linkedin: false,},+ readiness: {+ schemaVersion: 1,+ cliAvailable: true,+ daemonRunning: true,+ daemonCompatible: true,+ browserConnected: false,+ browserState: "disconnected",+ profileMode: "existing",+ activeProfileMode: null,+ errorCode: "BROWSER_ENDPOINT_UNREACHABLE",+ platforms: {+ instagram: { available: true, loginState: "unknown", operations: ["search", "get-posts"] },+ tiktok: { available: true, loginState: "unknown", operations: ["search", "get-videos"] },+ linkedin: { available: false, loginState: "unknown", operations: [] },+ },+ },},});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.ok(!text.includes("9222"), "Browser ports must not leak");+ assert.ok(!text.includes("private-token"), "Browser session tokens must not leak");+ assert.ok(!text.includes("Profile 1"), "Browser profile paths must not leak");assert.equal(body.configPath, undefined);assert.equal(body.socai.bin, undefined, "/api/status must omit bin property");} finally {diff --git a/test/socai.test.js b/test/socai.test.jsindex e68aab8..7cf07b4 100644--- a/test/socai.test.js+++ b/test/socai.test.js@@ -9,6 +9,7 @@ import {buildTikTokVideoArgs,parseJsonOutput,probeSocai,+ readSocaiReadiness,runSocaiResearch,runSocaiSearch,} from "../src/socai.js";@@ -208,7 +209,7 @@ if (args[0] === "--version") {try {const env = { ...process.env, SOCAI_BIN: mock };- const status = await probeSocai({}, env);+ const status = await probeSocai({}, env, undefined, { includeReadiness: true });assert.equal(status.installed, true);assert.equal(status.version, "0.5.6-beta.1");assert.deepEqual(status.capabilities, {@@ -216,6 +217,22 @@ if (args[0] === "--version") {tiktok: true,linkedin: false,});+ assert.deepEqual(status.readiness, {+ schemaVersion: null,+ cliAvailable: true,+ daemonRunning: null,+ daemonCompatible: null,+ browserConnected: null,+ browserState: "unknown",+ profileMode: "unknown",+ activeProfileMode: null,+ errorCode: null,+ platforms: {+ instagram: { available: true, loginState: "unknown", operations: [] },+ tiktok: { available: true, loginState: "unknown", operations: [] },+ linkedin: { available: false, loginState: "unknown", operations: [] },+ },+ });assert.equal(status.bin, mock, "probeSocai must retain bin internally for CLI callers");assert.equal(status.configPath, undefined);} finally {@@ -223,6 +240,169 @@ if (args[0] === "--version") {}});+test("probeSocai normalizes the observational browser status contract", async () => {+ const directory = await mkdtemp(path.join(os.tmpdir(), "jev-social-readiness-"));+ const mock = path.join(directory, "socai-mock.mjs");+ const statusPayload = {+ schema_version: 1,+ cli_available: true,+ cli_version: "2",+ daemon_running: true,+ daemon_compatible: true,+ browser_connected: true,+ browser_state: "connected",+ profile_mode: "auto",+ active_profile_mode: "existing",+ error_code: null,+ next_step: "open ws://127.0.0.1:9222/devtools/browser/private",+ private_profile_path: "/Users/private/Chrome/Profile 1",+ platforms: [+ { id: "instagram", available: true, login_state: "authenticated", operations: ["search", "get-posts", "/Users/private/leak"] },+ { id: "tiktok", available: true, login_state: "unknown", operations: ["search", "get-videos"] },+ { id: "unknown-site", available: true, login_state: "authenticated", operations: ["search"] },+ ],+ };+ await writeFile(+ mock,+ `#!/usr/bin/env node+const args = process.argv.slice(2);+if (args[0] === "--version") console.log("socai 0.7.0");+else if (args[0] === "--help") console.log("socai root");+else if (args[0] === "status" && args[1] === "--json") console.log(${JSON.stringify(JSON.stringify(statusPayload))});+else if (["instagram", "tiktok"].includes(args[0]) && args.at(-1) === "--help") console.log("Commands: search");+else process.exitCode = 1;+`,+ { mode: 0o755 },+ );++ try {+ const status = await probeSocai({}, { ...process.env, SOCAI_BIN: mock }, undefined, { includeReadiness: true });+ assert.deepEqual(status.readiness, {+ schemaVersion: 1,+ cliAvailable: true,+ daemonRunning: true,+ daemonCompatible: true,+ browserConnected: true,+ browserState: "connected",+ profileMode: "auto",+ activeProfileMode: "existing",+ errorCode: null,+ platforms: {+ instagram: { available: true, loginState: "authenticated", operations: ["search", "get-posts"] },+ tiktok: { available: true, loginState: "unknown", operations: ["search", "get-videos"] },+ linkedin: { available: false, loginState: "unknown", operations: [] },+ },+ });+ const serialized = JSON.stringify(status.readiness);+ assert.doesNotMatch(serialized, /9222|websocket|private|Profile 1|unknown-site/i);+ } finally {+ await rm(directory, { recursive: true, force: true });+ }+});++test("probeSocai treats malformed status output as unknown without making an installed CLI unavailable", async () => {+ const directory = await mkdtemp(path.join(os.tmpdir(), "jev-social-readiness-invalid-"));+ 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.7.0");+else if (args[0] === "--help") console.log("socai root");+else if (args[0] === "status") console.log('{"schema_version":1,"browser_connected":"yes","profile_mode":"/Users/private"}');+else process.exitCode = 1;+`,+ { mode: 0o755 },+ );++ try {+ const status = await probeSocai({}, { ...process.env, SOCAI_BIN: mock }, undefined, { includeReadiness: true });+ assert.equal(status.installed, true);+ assert.equal(status.readiness.browserState, "unknown");+ assert.equal(status.readiness.browserConnected, null);+ assert.doesNotMatch(JSON.stringify(status.readiness), /Users|private/);+ } finally {+ await rm(directory, { recursive: true, force: true });+ }+});++test("readSocaiReadiness accepts a valid v1 payload even when the CLI exits nonzero", async () => {+ const directory = await mkdtemp(path.join(os.tmpdir(), "jev-social-readiness-nonzero-"));+ const mock = path.join(directory, "socai-mock.mjs");+ await writeFile(+ mock,+ `#!/usr/bin/env node+console.log(JSON.stringify({+ schema_version: 1, cli_available: true, daemon_running: true, daemon_compatible: true,+ browser_connected: false, browser_state: "disconnected", profile_mode: "remote",+ active_profile_mode: null, error_code: "REMOTE_SESSION_UNAVAILABLE", platforms: []+}));+process.exitCode = 7;+`,+ { mode: 0o755 },+ );+ try {+ const readiness = await readSocaiReadiness(mock);+ assert.equal(readiness.errorCode, "REMOTE_SESSION_UNAVAILABLE");+ assert.equal(readiness.profileMode, "remote");+ } finally {+ await rm(directory, { recursive: true, force: true });+ }+});++test("readSocaiReadiness times out to unknown without failing CLI availability", async () => {+ const directory = await mkdtemp(path.join(os.tmpdir(), "jev-social-readiness-timeout-"));+ const mock = path.join(directory, "socai-mock.mjs");+ await writeFile(mock, "#!/usr/bin/env node\nsetTimeout(() => {}, 30_000);\n", { mode: 0o755 });+ try {+ const readiness = await readSocaiReadiness(mock, process.env, undefined, { timeoutMs: 40 });+ assert.equal(readiness.cliAvailable, true);+ assert.equal(readiness.browserConnected, null);+ } finally {+ await rm(directory, { recursive: true, force: true });+ }+});++test("ordinary capability probes do not invoke the optional browser readiness command", async () => {+ const directory = await mkdtemp(path.join(os.tmpdir(), "jev-social-readiness-optional-"));+ const mock = path.join(directory, "socai-mock.mjs");+ await writeFile(+ mock,+ `#!/usr/bin/env node+const args = process.argv.slice(2);+if (args[0] === "status") setTimeout(() => {}, 30_000);+else if (args[0] === "--version") console.log("socai 0.6.0");+else if (args[0] === "--help") console.log("socai root");+else if (args.at(-1) === "--help") console.log("Commands: search");+else process.exitCode = 1;+`,+ { mode: 0o755 },+ );+ try {+ const started = Date.now();+ const status = await probeSocai({}, { ...process.env, SOCAI_BIN: mock });+ assert.equal(status.installed, true);+ assert.ok(Date.now() - started < 2_000, "non-status callers must not wait for browser diagnostics");+ assert.equal(status.readiness.browserConnected, null);+ } finally {+ await rm(directory, { recursive: true, force: true });+ }+});++test("readSocaiReadiness aborts a running status probe promptly", async () => {+ const directory = await mkdtemp(path.join(os.tmpdir(), "jev-social-readiness-abort-"));+ const mock = path.join(directory, "socai-mock.mjs");+ await writeFile(mock, "#!/usr/bin/env node\nsetTimeout(() => {}, 30_000);\n", { mode: 0o755 });+ try {+ const controller = new AbortController();+ const pending = readSocaiReadiness(mock, process.env, controller.signal);+ setTimeout(() => controller.abort(), 40);+ await assert.rejects(pending, (error) => error.code === "SOCAI_ABORTED");+ } 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");diff --git a/test/status.test.js b/test/status.test.jsindex 80b16af..85bb8f0 100644--- a/test/status.test.js+++ b/test/status.test.js@@ -15,6 +15,7 @@ test("malformed configuration is surfaced without replacing it with misleading rassert.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.deepEqual(view.browser, { ready: false, label: "Configuration unavailable", hint: "" });assert.doesNotMatch(JSON.stringify(view), /Jev needs a key|socai unavailable/);});@@ -31,4 +32,83 @@ test("healthy status retains versioned per-platform readiness", () => {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)" });+ assert.deepEqual(view.browser, {+ ready: false,+ label: "Chrome state unknown",+ hint: "Update socai to enable read-only browser diagnostics.",+ });+});++test("connected browser readiness names the active profile without exposing connection details", () => {+ const view = deriveStatusView({+ jevConfigured: true,+ socai: {+ installed: true,+ version: "0.7.0",+ capabilities: { instagram: true, tiktok: true, linkedin: true },+ readiness: {+ browserConnected: true,+ browserState: "connected",+ profileMode: "managed",+ activeProfileMode: "existing",+ errorCode: null,+ },+ },+ });++ assert.deepEqual(view.browser, { ready: true, label: "Chrome connected · existing", hint: "" });+ assert.deepEqual(view.platforms.instagram, { available: true, loginState: "unknown" });+});++test("platform login state remains separate from CLI capability and browser connection", () => {+ const view = deriveStatusView({+ jevConfigured: true,+ socai: {+ installed: true,+ capabilities: { instagram: true, tiktok: true, linkedin: false },+ readiness: {+ browserConnected: true,+ browserState: "connected",+ profileMode: "existing",+ activeProfileMode: "existing",+ errorCode: null,+ platforms: {+ instagram: { available: true, loginState: "authenticated", operations: ["search"] },+ tiktok: { available: true, loginState: "unauthenticated", operations: ["search"] },+ },+ },+ },+ });++ assert.deepEqual(view.platforms, {+ instagram: { available: true, loginState: "authenticated" },+ tiktok: { available: true, loginState: "unauthenticated" },+ linkedin: { available: false, loginState: "unknown" },+ });});++for (const [errorCode, expected] of [+ ["BROWSER_PERMISSION_REQUIRED", ["Chrome permission needed", "Allow Chrome data access and remote debugging, then try again."]],+ ["BROWSER_ENDPOINT_UNREACHABLE", ["Chrome unavailable", "Start Chrome or choose the managed browser profile, then try again."]],+ ["REMOTE_SESSION_UNAVAILABLE", ["Remote browser unavailable", "Check the remote browser service, then try again."]],+]) {+ test(`browser readiness maps ${errorCode} to safe local guidance`, () => {+ const view = deriveStatusView({+ jevConfigured: true,+ socai: {+ installed: true,+ capabilities: { instagram: true, tiktok: true, linkedin: true },+ readiness: {+ browserConnected: false,+ browserState: "disconnected",+ profileMode: errorCode === "REMOTE_SESSION_UNAVAILABLE" ? "remote" : "existing",+ activeProfileMode: null,+ errorCode,+ },+ },+ });++ assert.deepEqual(view.browser, { ready: false, label: expected[0], hint: expected[1] });+ assert.equal(view.error, "", "browser diagnostics must not trigger the global error toast");+ });+}