Files
moltbot/test/scripts/install-sh.test.ts
Peter Steinberger f91de52f0d refactor: move runtime state to SQLite
* refactor: remove stale file-backed shims

* fix: harden sqlite state ci boundaries

* refactor: store matrix idb snapshots in sqlite

* fix: satisfy rebased CI guardrails

* refactor: store current conversation bindings in sqlite table

* refactor: store tui last sessions in sqlite table

* refactor: reset sqlite schema history

* refactor: drop unshipped sqlite table migration

* refactor: remove plugin index file rollback

* refactor: drop unshipped sqlite sidecar migrations

* refactor: remove runtime commitments kv migration

* refactor: preserve kysely sync result types

* refactor: drop unshipped sqlite schema migration table

* test: keep session usage coverage sqlite-backed

* refactor: keep sqlite migration doctor-only

* refactor: isolate device legacy imports

* refactor: isolate push voicewake legacy imports

* refactor: isolate remaining runtime legacy imports

* refactor: tighten sqlite migration guardrails

* test: cover sqlite persisted enum parsing

* refactor: isolate legacy update and tui imports

* refactor: tighten sqlite state ownership

* refactor: move legacy imports behind doctor

* refactor: remove legacy session row lookup

* refactor: canonicalize memory transcript locators

* refactor: drop transcript path scope fallbacks

* refactor: drop runtime legacy session delivery pruning

* refactor: store tts prefs only in sqlite

* refactor: remove cron store path runtime

* refactor: use cron sqlite store keys

* refactor: rename telegram message cache scope

* refactor: read memory dreaming status from sqlite

* refactor: rename cron status store key

* refactor: stop remembering transcript file paths

* test: use sqlite locators in agent fixtures

* refactor: remove file-shaped commitments and cron store surfaces

* refactor: keep compaction transcript handles out of session rows

* refactor: derive transcript handles from session identity

* refactor: derive runtime transcript handles

* refactor: remove gateway session locator reads

* refactor: remove transcript locator from session rows

* refactor: store raw stream diagnostics in sqlite

* refactor: remove file-shaped transcript rotation

* refactor: hide legacy trajectory paths from runtime

* refactor: remove runtime transcript file bridges

* refactor: repair database-first rebase fallout

* refactor: align tests with database-first state

* refactor: remove transcript file handoffs

* refactor: sync post-compaction memory by transcript scope

* refactor: run codex app-server sessions by id

* refactor: bind codex runtime state by session id

* refactor: pass memory transcripts by sqlite scope

* refactor: remove transcript locator cleanup leftovers

* test: remove stale transcript file fixtures

* refactor: remove transcript locator test helper

* test: make cron sqlite keys explicit

* test: remove cron runtime store paths

* test: remove stale session file fixtures

* test: use sqlite cron keys in diagnostics

* refactor: remove runtime delivery queue backfill

* test: drop fake export session file mocks

* refactor: rename acp session read failure flag

* refactor: rename acp row session key

* refactor: remove session store test seams

* refactor: move legacy session parser tests to doctor

* refactor: reindex managed memory in place

* refactor: drop stale session store wording

* refactor: rename session row helpers

* refactor: rename sqlite session entry modules

* refactor: remove transcript locator leftovers

* refactor: trim file-era audit wording

* refactor: clean managed media through sqlite

* fix: prefer explicit agent for exports

* fix: use prepared agent for session resets

* fix: canonicalize legacy codex binding import

* test: rename state cleanup helper

* docs: align backup docs with sqlite state

* refactor: drop legacy Pi usage auth fallback

* refactor: move legacy auth profile imports to doctor

* refactor: keep Pi model discovery auth in memory

* refactor: remove MSTeams legacy learning key fallback

* refactor: store model catalog config in sqlite

* refactor: use sqlite model catalog at runtime

* refactor: remove model json compatibility aliases

* refactor: store auth profiles in sqlite

* refactor: seed copied auth profiles in sqlite

* refactor: make auth profile runtime sqlite-addressed

* refactor: migrate hermes secrets into sqlite auth store

* refactor: move plugin install config migration to doctor

* refactor: rename plugin index audit checks

* test: drop auth file assumptions

* test: remove legacy transcript file assertions

* refactor: drop legacy cli session aliases

* refactor: store skill uploads in sqlite

* refactor: keep subagent attachments in sqlite vfs

* refactor: drop subagent attachment cleanup state

* refactor: move legacy session aliases to doctor

* refactor: require node 24 for sqlite state runtime

* refactor: move provider caches into sqlite state

* fix: harden virtual agent filesystem

* refactor: enforce database-first runtime state

* refactor: rename compaction transcript rotation setting

* test: clean sqlite refactor test types

* refactor: consolidate sqlite runtime state

* refactor: model session conversations in sqlite

* refactor: stop deriving cron delivery from session keys

* refactor: stop classifying sessions from key shape

* refactor: hydrate announce targets from typed delivery

* refactor: route heartbeat delivery from typed sqlite context

* refactor: tighten typed sqlite session routing

* refactor: remove session origin routing shadow

* refactor: drop session origin shadow fixtures

* perf: query sqlite vfs paths by prefix

* refactor: use typed conversation metadata for sessions

* refactor: prefer typed session routing metadata

* refactor: require typed session routing metadata

* refactor: resolve group tool policy from typed sessions

* refactor: delete dead session thread info bridge

* Show Codex subscription reset times in channel errors (#80456)

* feat(plugin-sdk): consolidate session workflow APIs

* fix(agents): allow read-only agent mount reads

* [codex] refresh plugin regression fixtures

* fix(agents): restore compaction gateway logs

* test: tighten gateway startup assertions

* Redact persisted secret-shaped payloads [AI] (#79006)

* test: tighten device pair notify assertions

* test: tighten hermes secret assertions

* test: assert matrix client error shapes

* test: assert config compat warnings

* fix(heartbeat): remap cron-run exec events to session keys (#80214)

* fix(codex): route btw through native side threads

* fix(auth): accept friendly OpenAI order for Codex profiles

* fix(codex): rotate auth profiles inside harness

* fix: keep browser status page probe within timeout

* test: assert agents add outputs

* test: pin cron read status

* fix(agents): avoid Pi resource discovery stalls

Co-authored-by: dataCenter430 <titan032000@gmail.com>

* fix: retire timed-out codex app-server clients

* test: tighten qa lab runtime assertions

* test: check security fix outputs

* test: verify extension runtime messages

* feat(wake): expose typed sessionKey on wake protocol + system event CLI

* fix(gateway): await session_end during shutdown drain and track channel + compaction lifecycle paths (#57790)

* test: guard talk consult call helper

* fix(codex): scale context engine projection (#80761)

* fix(codex): scale context engine projection

* fix: document Codex context projection scaling

* fix: document Codex context projection scaling

* fix: document Codex context projection scaling

* fix: document Codex context projection scaling

* chore: align Codex projection changelog

* chore: realign Codex projection changelog

* fix: isolate Codex projection patch

---------

Co-authored-by: Eva (agent) <eva+agent-78055@100yen.org>
Co-authored-by: Josh Lehman <josh@martian.engineering>

* refactor: move agent runtime state toward piless

* refactor: remove cron session reaper

* refactor: move session management to sqlite

* refactor: finish database-first state migration

* chore: refresh generated sqlite db types

* refactor: remove stale file-backed shims

* test: harden kysely type coverage

# Conflicts:
#	.agents/skills/kysely-database-access/SKILL.md
#	src/infra/kysely-sync.types.test.ts
#	src/proxy-capture/store.sqlite.test.ts
#	src/state/openclaw-agent-db.test.ts
#	src/state/openclaw-state-db.test.ts

* refactor: remove cron store path runtime

* refactor: keep compaction transcript handles out of session rows

* refactor: derive embedded transcripts from sqlite identity

* refactor: remove embedded transcript locator handoff

* refactor: remove runtime transcript file bridges

* refactor: remove transcript file handoffs

* refactor: remove MSTeams legacy learning key fallback

* refactor: store model catalog config in sqlite

* refactor: use sqlite model catalog at runtime

# Conflicts:
#	docs/cli/secrets.md
#	docs/gateway/authentication.md
#	docs/gateway/secrets.md

* fix: keep oauth sibling sync sqlite-local

# Conflicts:
#	src/commands/onboard-auth.test.ts

* refactor: remove task session store maintenance

# Conflicts:
#	src/commands/tasks.ts

* refactor: keep diagnostics in state sqlite

* refactor: enforce database-first runtime state

* refactor: consolidate sqlite runtime state

* Show Codex subscription reset times in channel errors (#80456)

* fix(codex): refresh subscription limit resets

* fix(codex): format reset times for channels

* Update CHANGELOG with latest changes and fixes

Updated CHANGELOG with recent fixes and improvements.

* fix(codex): keep command load failures on codex surface

* fix(codex): format account rate limits as rows

* fix(codex): summarize account limits as usage status

* fix(codex): simplify account limit status

* test: tighten subagent announce queue assertion

* test: tighten session delete lifecycle assertions

* test: tighten cron ops assertions

* fix: track cron execution milestones

* test: tighten hermes secret assertions

* test: assert matrix sync store payloads

* test: assert config compat warnings

* fix(codex): align btw side thread semantics

* fix(codex): honor codex fallback blocking

* fix(agents): avoid Pi resource discovery stalls

* test: tighten codex event assertions

* test: tighten cron assertions

* Fix Codex app-server OAuth harness auth

* refactor: move agent runtime state toward piless

* refactor: move device and push state to sqlite

* refactor: move runtime json state imports to doctor

* refactor: finish database-first state migration

* chore: refresh generated sqlite db types

* refactor: clarify cron sqlite store keys

* refactor: remove stale file-backed shims

* refactor: bind codex runtime state by session id

* test: expect sqlite trajectory branch export

* refactor: rename session row helpers

* fix: keep legacy device identity import in doctor

* refactor: enforce database-first runtime state

* refactor: consolidate sqlite runtime state

* build: align pi contract wrappers

* chore: repair database-first rebase

* refactor: remove session file test contracts

* test: update gateway session expectations

* refactor: stop routing from session compatibility shadows

* refactor: stop persisting session route shadows

* refactor: use typed delivery context in clients

* refactor: stop echoing session route shadows

* refactor: repair embedded runner rebase imports

# Conflicts:
#	src/agents/pi-embedded-runner/run/attempt.tool-call-argument-repair.ts

* refactor: align pi contract imports

* refactor: satisfy kysely sync helper guard

* refactor: remove file transcript bridge remnants

* refactor: remove session locator compatibility

* refactor: remove session file test contracts

* refactor: keep rebase database-first clean

* refactor: remove session file assumptions from e2e

* docs: clarify database-first goal state

* test: remove legacy store markers from sqlite runtime tests

* refactor: remove legacy store assumptions from runtime seams

* refactor: align sqlite runtime helper seams

* test: update memory recall sqlite audit mock

* refactor: align database-first runtime type seams

* test: clarify doctor cron legacy store names

* fix: preserve sqlite session route projections

* test: fix copilot token cache test syntax

* docs: update database-first proof status

* test: align database-first test fixtures

* docs: update database-first proof status

* refactor: clean extension database-first drift

* test: align agent session route proof

* test: clarify doctor legacy path fixtures

* chore: clean database-first changed checks

* chore: repair database-first rebase markers

* build: allow baileys git subdependency

* chore: repair exp-vfs rebase drift

* chore: finish exp-vfs rebase cleanup

* chore: satisfy rebase lint drift

* chore: fix qqbot rebase type seam

* chore: fix rebase drift leftovers

* fix: keep auth profile oauth secrets out of sqlite

* fix: repair rebase drift tests

* test: stabilize pairing request ordering

* test: use source manifests in plugin contract checks

* fix: restore gateway session metadata after rebase

* fix: repair database-first rebase drift

* fix: clean up database-first rebase fallout

* test: stabilize line quick reply receipt time

* fix: repair extension rebase drift

* test: keep transcript redaction tests sqlite-backed

* fix: carry injected transcript redaction through sqlite

* chore: clean database branch rebase residue

* fix: repair database branch CI drift

* fix: repair database branch CI guard drift

* fix: stabilize oauth tls preflight test

* test: align database branch fast guards

* test: repair build artifact boundary guards

* chore: clean changelog rebase markers

---------

Co-authored-by: pashpashpash <nik@vault77.ai>
Co-authored-by: Eva <eva@100yen.org>
Co-authored-by: stainlu <stainlu@newtype-ai.org>
Co-authored-by: Jason Zhou <jason.zhou.design@gmail.com>
Co-authored-by: Ruben Cuevas <hi@rubencu.com>
Co-authored-by: Pavan Kumar Gondhi <pavangondhi@gmail.com>
Co-authored-by: Shakker <shakkerdroid@gmail.com>
Co-authored-by: Kaspre <36520309+Kaspre@users.noreply.github.com>
Co-authored-by: dataCenter430 <titan032000@gmail.com>
Co-authored-by: Kaspre <kaspre@gmail.com>
Co-authored-by: pandadev66 <nova.full.stack@outlook.com>
Co-authored-by: Eva <admin@100yen.org>
Co-authored-by: Eva (agent) <eva+agent-78055@100yen.org>
Co-authored-by: Josh Lehman <josh@martian.engineering>
Co-authored-by: jeffjhunter <support@aipersonamethod.com>
2026-05-13 13:15:12 +01:00

564 lines
20 KiB
TypeScript

import { spawnSync } from "node:child_process";
import { chmodSync, mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { describe, expect, it } from "vitest";
const SCRIPT_PATH = "scripts/install.sh";
function runInstallShell(script: string, env: NodeJS.ProcessEnv = {}) {
return spawnSync("bash", ["-c", script], {
encoding: "utf8",
env: {
...process.env,
OPENCLAW_INSTALL_SH_NO_RUN: "1",
...env,
},
});
}
describe("install.sh", () => {
const script = readFileSync(SCRIPT_PATH, "utf8");
it("runs apt-get through noninteractive wrappers", () => {
expect(script).toContain("apt_get()");
expect(script).toContain('DEBIAN_FRONTEND="${DEBIAN_FRONTEND:-noninteractive}"');
expect(script).toContain('NEEDRESTART_MODE="${NEEDRESTART_MODE:-a}"');
expect(script).toContain("sudo env DEBIAN_FRONTEND=");
expect(script).toContain("-o Dpkg::Options::=--force-confdef");
expect(script).toContain("-o Dpkg::Options::=--force-confold");
const rawAptInstalls = script
.split("\n")
.filter((line) => /\b(?:sudo\s+)?apt-get\s+install\b/.test(line));
expect(rawAptInstalls).toStrictEqual([]);
});
it("exports noninteractive apt env during Linux startup", () => {
expect(script).toMatch(
/detect_os_or_die\s+if \[\[ "\$OS" == "linux" \]\]; then\s+export DEBIAN_FRONTEND="\$\{DEBIAN_FRONTEND:-noninteractive\}"\s+export NEEDRESTART_MODE="\$\{NEEDRESTART_MODE:-a\}"\s+fi/m,
);
expect(script).toContain(
'run_quiet_step "Configuring NodeSource repository" sudo -E bash "$tmp"',
);
});
it("loads nvm before checking Node.js so stale system Node does not win", () => {
expect(script).toMatch(
/# Step 2: Node\.js\s+load_nvm_for_node_detection\s+if ! check_node; then/,
);
const tmp = mkdtempSync(join(tmpdir(), "openclaw-install-nvm-"));
const home = join(tmp, "home");
const systemBin = join(tmp, "system-bin");
const nvmBin = join(home, ".nvm/versions/node/v24.13.0/bin");
mkdirSync(systemBin, { recursive: true });
mkdirSync(nvmBin, { recursive: true });
mkdirSync(join(home, ".nvm"), { recursive: true });
const systemNode = join(systemBin, "node");
const nvmNode = join(nvmBin, "node");
writeFileSync(
systemNode,
[
"#!/bin/sh",
'if [ "${1:-}" = "-p" ]; then echo "8 11"; exit 0; fi',
"echo v8.11.3",
"",
].join("\n"),
);
writeFileSync(
nvmNode,
[
"#!/bin/sh",
'if [ "${1:-}" = "-p" ]; then echo "24 13"; exit 0; fi',
"echo v24.13.0",
"",
].join("\n"),
);
chmodSync(systemNode, 0o755);
chmodSync(nvmNode, 0o755);
writeFileSync(
join(home, ".nvm/nvm.sh"),
[
'NVM_DIR="${NVM_DIR:-$HOME/.nvm}"',
"export NVM_DIR",
"nvm() {",
' if [ "$1" = "use" ]; then',
' export PATH="$NVM_DIR/versions/node/v24.13.0/bin:$PATH"',
" return 0",
" fi",
" return 0",
"}",
"",
].join("\n"),
);
let result: ReturnType<typeof runInstallShell> | undefined;
try {
result = runInstallShell(
[
`cd ${JSON.stringify(process.cwd())}`,
`source ${JSON.stringify(SCRIPT_PATH)}`,
"set +e",
"load_nvm_for_node_detection",
"check_node",
"status=$?",
'printf "status=%s\\npath=%s\\nversion=%s\\n" "$status" "$(command -v node)" "$(node -v)"',
"exit $status",
].join("\n"),
{
HOME: home,
NVM_DIR: join(tmp, "stale-nvm"),
PATH: `${systemBin}:/usr/bin:/bin`,
TERM: "dumb",
},
);
} finally {
rmSync(tmp, { force: true, recursive: true });
}
expect(result?.status).toBe(0);
const output = result?.stdout ?? "";
expect(output).toContain("status=0");
expect(output).toContain(`path=${nvmNode}`);
expect(output).toContain("version=v24.13.0");
});
it("promotes a supported Linux Node binary over stale PATH entries", () => {
const tmp = mkdtempSync(join(tmpdir(), "openclaw-install-node-promote-"));
const staleBin = join(tmp, "usr-local-bin");
const supportedBin = join(tmp, "usr-bin");
mkdirSync(staleBin, { recursive: true });
mkdirSync(supportedBin, { recursive: true });
const staleNode = join(staleBin, "node");
const supportedNode = join(supportedBin, "node");
writeFileSync(
staleNode,
[
"#!/bin/sh",
'if [ "${1:-}" = "-p" ]; then echo "20 20"; exit 0; fi',
"echo v20.20.0",
"",
].join("\n"),
);
writeFileSync(
supportedNode,
[
"#!/bin/sh",
'if [ "${1:-}" = "-p" ]; then echo "24 13"; exit 0; fi',
"echo v24.13.0",
"",
].join("\n"),
);
chmodSync(staleNode, 0o755);
chmodSync(supportedNode, 0o755);
let result: ReturnType<typeof runInstallShell> | undefined;
try {
result = runInstallShell(
[
`cd ${JSON.stringify(process.cwd())}`,
`source ${JSON.stringify(SCRIPT_PATH)}`,
"set +e",
"OS=linux",
"promote_supported_node_binary",
"promote_status=$?",
"ensure_default_node_active_shell",
"active_status=$?",
'printf "promote=%s\\nactive=%s\\npath=%s\\nversion=%s\\n" "$promote_status" "$active_status" "$(command -v node)" "$(node -v)"',
"exit $active_status",
].join("\n"),
{
PATH: `${staleBin}:${supportedBin}:/usr/bin:/bin`,
TERM: "dumb",
},
);
} finally {
rmSync(tmp, { force: true, recursive: true });
}
expect(result?.status).toBe(0);
const output = result?.stdout ?? "";
expect(output).toContain("promote=0");
expect(output).toContain("active=0");
expect(output).toContain(`path=${supportedNode}`);
expect(output).toContain("version=v24.13.0");
});
it("persists a supported Linux Node path before noninteractive shell guards", () => {
const tmp = mkdtempSync(join(tmpdir(), "openclaw-install-linux-node-path-"));
const home = join(tmp, "home");
const oldBin = join(tmp, "old/bin");
const installedBin = join(tmp, "usr/bin");
mkdirSync(home, { recursive: true });
mkdirSync(oldBin, { recursive: true });
mkdirSync(installedBin, { recursive: true });
const oldNode = join(oldBin, "node");
const installedNode = join(installedBin, "node");
writeFileSync(
join(home, ".bashrc"),
[
"case $- in",
" *i*) ;;",
" *) return ;;",
"esac",
`export PATH="${installedBin}:$PATH"`,
"",
].join("\n"),
);
writeFileSync(
oldNode,
[
"#!/usr/bin/env bash",
'if [[ "${1:-}" == "-p" ]]; then echo "20 20"; exit 0; fi',
'if [[ "${1:-}" == "-v" ]]; then echo "v20.20.0"; exit 0; fi',
"",
].join("\n"),
);
writeFileSync(
installedNode,
[
"#!/usr/bin/env bash",
'if [[ "${1:-}" == "-p" ]]; then echo "24 13"; exit 0; fi',
'if [[ "${1:-}" == "-v" ]]; then echo "v24.13.0"; exit 0; fi',
"",
].join("\n"),
);
chmodSync(oldNode, 0o755);
chmodSync(installedNode, 0o755);
let result: ReturnType<typeof runInstallShell> | undefined;
try {
result = runInstallShell(`
set -euo pipefail
source "${SCRIPT_PATH}"
OS=linux
HOME=${JSON.stringify(home)}
PATH=${JSON.stringify(`${oldBin}:${installedBin}:/usr/bin:/bin`)}
ui_info() { :; }
activate_supported_node_on_path
printf 'first=%s\\n' "$(sed -n '1p' "$HOME/.bashrc")"
HOME=${JSON.stringify(home)} PATH=${JSON.stringify(`${oldBin}:${installedBin}:/usr/bin:/bin`)} bash -c 'source_rc() { . "$HOME/.bashrc"; }; source_rc; printf "node=%s\\n" "$(command -v node)"'
`);
} finally {
rmSync(tmp, { force: true, recursive: true });
}
expect(result?.status).toBe(0);
expect(result?.stdout).toContain(`first=export PATH="${installedBin}:$PATH"`);
expect(result?.stdout).toContain(`node=${installedNode}`);
});
it("warns before redirecting an unwritable npm prefix", () => {
const tmp = mkdtempSync(join(tmpdir(), "openclaw-install-npm-prefix-"));
const home = join(tmp, "home");
const events = join(tmp, "events.log");
mkdirSync(home, { recursive: true });
let result: ReturnType<typeof runInstallShell> | undefined;
try {
result = runInstallShell(`
set -euo pipefail
source "${SCRIPT_PATH}"
OS=linux
HOME=${JSON.stringify(home)}
prefix=${JSON.stringify(join(tmp, "root-owned-prefix"))}
events=${JSON.stringify(events)}
npm() {
if [[ "$1" == "config" && "$2" == "get" && "$3" == "prefix" ]]; then
printf '%s\\n' "$prefix"
return 0
fi
if [[ "$1" == "config" && "$2" == "set" && "$3" == "prefix" ]]; then
printf 'npm-set:%s\\n' "$4" >> "$events"
return 0
fi
return 1
}
ui_info() { printf 'info:%s\\n' "$*" >> "$events"; }
ui_warn() { printf 'warn:%s\\n' "$*" >> "$events"; }
ui_success() { printf 'success:%s\\n' "$*" >> "$events"; }
fix_npm_permissions
cat "$events"
`);
} finally {
rmSync(tmp, { force: true, recursive: true });
}
expect(result?.status).toBe(0);
const lines = (result?.stdout ?? "").trim().split("\n");
const warningIndex = lines.findIndex((line) =>
line.includes("The installer will switch npm's user prefix"),
);
const npmSetIndex = lines.findIndex((line) => line.startsWith("npm-set:"));
const noSudoWarningIndex = lines.findIndex((line) => line.includes("Avoid sudo npm i -g"));
expect(warningIndex).toBeGreaterThanOrEqual(0);
expect(npmSetIndex).toBeGreaterThan(warningIndex);
expect(noSudoWarningIndex).toBeGreaterThan(npmSetIndex);
expect(result?.stdout).toContain("npm global prefix is not writable");
expect(result?.stdout).toContain("npm normally writes that setting to ~/.npmrc");
expect(result?.stdout).toContain("npm i -g openclaw@latest");
expect(result?.stdout).toContain("using this user prefix");
expect(result?.stdout).not.toContain("has been saved");
});
it("persists npm prefix PATH before noninteractive shell guards", () => {
const tmp = mkdtempSync(join(tmpdir(), "openclaw-install-npm-prefix-shell-"));
const home = join(tmp, "home");
mkdirSync(home, { recursive: true });
writeFileSync(
join(home, ".bashrc"),
[
"case $- in",
" *i*) ;;",
" *) return ;;",
"esac",
'export PATH="$HOME/.npm-global/bin:$PATH"',
"",
].join("\n"),
);
let result: ReturnType<typeof runInstallShell> | undefined;
try {
result = runInstallShell(`
set -euo pipefail
source "${SCRIPT_PATH}"
OS=linux
HOME=${JSON.stringify(home)}
PATH=/usr/bin:/bin
prefix=${JSON.stringify(join(tmp, "root-owned-prefix"))}
npm() {
if [[ "$1" == "config" && "$2" == "get" && "$3" == "prefix" ]]; then
printf '%s\\n' "$prefix"
return 0
fi
if [[ "$1" == "config" && "$2" == "set" && "$3" == "prefix" ]]; then
return 0
fi
return 1
}
ui_info() { :; }
ui_warn() { :; }
ui_success() { :; }
fix_npm_permissions
printf 'first=%s\\n' "$(sed -n '1p' "$HOME/.bashrc")"
HOME=${JSON.stringify(home)} PATH=/usr/bin:/bin bash -c 'source_rc() { . "$HOME/.bashrc"; }; source_rc; printf "path=%s\\n" "\${PATH%%:*}"'
`);
} finally {
rmSync(tmp, { force: true, recursive: true });
}
expect(result?.status).toBe(0);
expect(result?.stdout).toContain('first=export PATH="$HOME/.npm-global/bin:$PATH"');
expect(result?.stdout).toContain(`path=${home}/.npm-global/bin`);
});
it("uses a quoted absolute openclaw path in follow-up commands when npm bin is not on the original PATH", () => {
const tmp = mkdtempSync(join(tmpdir(), "openclaw-install-command-"));
const npmBin = join(tmp, "npm bin");
const visibleBin = join(tmp, "visible-bin");
mkdirSync(npmBin, { recursive: true });
mkdirSync(visibleBin, { recursive: true });
const openclawBin = join(npmBin, "openclaw");
writeFileSync(openclawBin, "#!/bin/sh\nexit 0\n");
chmodSync(openclawBin, 0o755);
let result: ReturnType<typeof runInstallShell> | undefined;
try {
result = runInstallShell(`
set -euo pipefail
source "${SCRIPT_PATH}"
ORIGINAL_PATH=${JSON.stringify(`${visibleBin}:/usr/bin:/bin`)}
printf 'missing=%s\\n' "$(openclaw_command_for_user "${openclawBin}")"
ORIGINAL_PATH=${JSON.stringify(`${npmBin}:${visibleBin}:/usr/bin:/bin`)}
printf 'present=%s\\n' "$(openclaw_command_for_user "${openclawBin}")"
`);
} finally {
rmSync(tmp, { recursive: true, force: true });
}
expect(result?.status).toBe(0);
expect(result?.stdout).toContain(`missing=${openclawBin.replace(/ /g, "\\ ")}`);
expect(result?.stdout).toContain("present=openclaw");
});
});
describe("install.sh macOS Homebrew Node behavior", () => {
const script = readFileSync(SCRIPT_PATH, "utf8");
it("stops when Homebrew node installation fails", () => {
expect(script).toContain(
'if ! run_quiet_step "Installing node@${NODE_DEFAULT_MAJOR}" brew install "node@${NODE_DEFAULT_MAJOR}"; then',
);
const failedInstallIndex = script.indexOf(
'if ! run_quiet_step "Installing node@${NODE_DEFAULT_MAJOR}" brew install "node@${NODE_DEFAULT_MAJOR}"; then',
);
const brewLinkIndex = script.indexOf(
'brew link "node@${NODE_DEFAULT_MAJOR}" --overwrite --force',
);
expect(failedInstallIndex).toBeGreaterThanOrEqual(0);
expect(brewLinkIndex).toBeGreaterThan(failedInstallIndex);
});
it("aborts before brew link when Homebrew node installation fails at runtime", () => {
const result = runInstallShell(`
set -euo pipefail
source "${SCRIPT_PATH}"
OS=macos
run_quiet_step() { echo "run_quiet_step:$*"; return 1; }
brew() { echo "brew:$*"; return 0; }
ensure_macos_default_node_active() { echo "ensure-called"; return 0; }
if install_node; then
echo "install_node returned success"
else
echo "install_node returned failure"
fi
`);
expect(result.status).toBe(1);
expect(result.stdout).toContain(
"Re-run with --verbose or run 'brew install node@24' directly, then rerun the installer.",
);
expect(result.stdout).not.toContain("brew:link");
expect(result.stdout).not.toContain("ensure-called");
});
it("separates missing Homebrew node from PATH shadowing", () => {
const missingNodeGuardIndex = script.indexOf(
'if [[ -z "$brew_node_prefix" || ! -x "${brew_node_prefix}/bin/node" ]]; then',
);
const pathAdviceIndex = script.indexOf("Add this to your shell profile and restart shell:");
expect(missingNodeGuardIndex).toBeGreaterThanOrEqual(0);
expect(script).toContain(
'ui_error "Homebrew node@${NODE_DEFAULT_MAJOR} is not installed on disk"',
);
expect(script).toContain('echo " export PATH=\\"${brew_node_prefix}/bin:\\$PATH\\""');
expect(pathAdviceIndex).toBeGreaterThan(missingNodeGuardIndex);
});
it("does not print PATH advice when Homebrew node is missing at runtime", () => {
const result = runInstallShell(`
set -euo pipefail
source "${SCRIPT_PATH}"
OS=macos
missing_prefix="$(mktemp -d)/node@24"
brew() {
if [[ "$1" == "--prefix" ]]; then
echo "$missing_prefix"
return 0
fi
return 0
}
node_major_version() { echo 16; }
if ensure_macos_default_node_active; then
echo "ensure returned success"
else
echo "ensure returned failure"
fi
`);
expect(result.status).toBe(0);
expect(result.stdout).toContain("Homebrew node@24 is not installed on disk");
expect(result.stdout).toContain("ensure returned failure");
expect(result.stdout).not.toContain("Node.js v24 was installed");
expect(result.stdout).not.toContain("Add this to your shell profile");
});
it("falls back when gum reports raw-mode ioctl failures", () => {
expect(script).toContain("setrawmode|inappropriate ioctl");
expect(script).toContain(
'if "$GUM" spin --spinner dot --title "$title" -- "$@" >"$gum_out" 2>"$gum_err"; then',
);
expect(script).toContain(
'if is_gum_raw_mode_failure "$gum_out" || is_gum_raw_mode_failure "$gum_err"; then',
);
expect(script).toContain(
'ui_warn "Spinner unavailable in this terminal; continuing without spinner"',
);
expect(script).toContain('"$@"\n return $?');
});
it("reruns spinner-wrapped commands when gum reports ioctl failure", () => {
const dir = mkdtempSync(join(tmpdir(), "openclaw-install-sh-gum-"));
try {
const gumPath = join(dir, "gum");
const commandPath = join(dir, "command");
const markerPath = join(dir, "marker");
writeFileSync(
gumPath,
"#!/usr/bin/env bash\nprintf 'inappropriate ioctl for device\\n'\nexit 0\n",
{ mode: 0o755 },
);
writeFileSync(commandPath, `#!/usr/bin/env bash\nprintf 'ran' >"${markerPath}"\n`, {
mode: 0o755,
});
const result = runInstallShell(`
set -euo pipefail
source "${SCRIPT_PATH}"
gum_is_tty() { return 0; }
GUM="${gumPath}"
run_with_spinner "Installing node" "${commandPath}"
cat "${markerPath}"
`);
expect(result.status).toBe(0);
expect(result.stdout).toContain(
"Spinner unavailable in this terminal; continuing without spinner",
);
expect(result.stdout).toContain("ran");
} finally {
rmSync(dir, { recursive: true, force: true });
}
});
});
describe("install.sh duplicate OpenClaw install detection", () => {
it("warns with concrete package paths and versions for duplicate npm roots", () => {
const result = runInstallShell(`
set -euo pipefail
source "${SCRIPT_PATH}"
root="$(mktemp -d)"
trap 'rm -rf "$root"' EXIT
mkdir -p "$root/brew/openclaw" "$root/fnm/openclaw"
printf '{"version":"2026.3.7"}\\n' > "$root/brew/openclaw/package.json"
printf '{"version":"2026.3.1"}\\n' > "$root/fnm/openclaw/package.json"
collect_openclaw_npm_root_candidates() { printf '%s\\n' "$root/brew" "$root/fnm"; }
OPENCLAW_BIN="$root/fnm/.bin/openclaw"
ui_warn() { echo "WARN: $*"; }
warn_duplicate_openclaw_global_installs
`);
expect(result.status).toBe(0);
expect(result.stdout).toContain("Multiple OpenClaw global installs detected");
expect(result.stdout).toContain("2026.3.7");
expect(result.stdout).toContain("2026.3.1");
expect(result.stdout).toContain("/brew/openclaw");
expect(result.stdout).toContain("/fnm/openclaw");
expect(result.stdout).toContain("Active openclaw:");
expect(result.stdout).toContain("npm uninstall -g openclaw");
});
it("stays quiet when only one OpenClaw npm root exists", () => {
const result = runInstallShell(`
set -euo pipefail
source "${SCRIPT_PATH}"
root="$(mktemp -d)"
trap 'rm -rf "$root"' EXIT
mkdir -p "$root/only/openclaw"
printf '{"version":"2026.3.7"}\\n' > "$root/only/openclaw/package.json"
collect_openclaw_npm_root_candidates() { printf '%s\\n' "$root/only"; }
ui_warn() { echo "WARN: $*"; }
warn_duplicate_openclaw_global_installs
`);
expect(result.status).toBe(0);
expect(result.stdout).not.toContain("Multiple OpenClaw global installs detected");
});
});