Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

fix: resolve agent review-prompt API origin instead of hardcoding :5555 (#5656)

Adam Eivy3a9fc45b869b
diff --git a/server/lib/README.md b/server/lib/README.md
index 3cfd0d7ff7..885a9a2182 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -317,7 +317,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `httpsState.js` | Captures whether PortOS booted with HTTPS active. |
| `bareUrl.js` | `parseBareUrl(text)` — returns the normalized URL when a captured string is nothing *but* a URL (bare host gets `https://`), else null. Drives the brain-capture short-circuit that files a pasted URL straight to Links instead of running the classifier. Stricter than the client's `urlNormalize.js` `isUrl` (needs a plausible TLD; http/https/`git@` only) because it picks a storage destination rather than a hint. |
| `isSafeHref.js` | Pure http(s)-only scheme check (`isSafeHref`) for user-supplied URL fields that get rendered as a clickable `<a href>` — rejects `javascript:`/`data:`/etc. stored-XSS payloads. Mirrors client `urlNormalize.js`'s `isHttpUrl`. |
-| `networkExposure.js` | Runtime scheme/bind/cert snapshot plus the shared ordered Tailscale, MagicDNS, certificate, and trusted-launch setup guide used by CLI and UI. |
+| `networkExposure.js` | Runtime scheme/bind/cert snapshot plus the shared ordered Tailscale, MagicDNS, certificate, and trusted-launch setup guide used by CLI and UI; `localApiBaseUrl()` resolves the plain-HTTP loopback origin (mirror port under HTTPS, API port otherwise) for local scripts and agent-facing curl snippets. |
## Search & indexing
diff --git a/server/lib/networkExposure.js b/server/lib/networkExposure.js
index 11594a566a..987fc97493 100644
--- a/server/lib/networkExposure.js
+++ b/server/lib/networkExposure.js
@@ -91,6 +91,27 @@ export function getNetworkExposureStatus() {
};
}
+/**
+ * Plain-HTTP base URL for reaching this install's own API from the same
+ * machine — what local scripts, curl snippets, and the shell commands PortOS
+ * hands its CoS agents should target.
+ *
+ * When HTTPS is active, `:5555` is TLS-only and a plain-HTTP request to it
+ * fails at the transport layer; the loopback-only HTTP mirror (`PORTS.API_LOCAL`,
+ * overridable via `PORTOS_HTTP_PORT`) is the right target. When HTTPS is off,
+ * the API port itself already speaks HTTP and no mirror is bound.
+ *
+ * Uses `127.0.0.1` rather than `localhost` because the mirror listener binds to
+ * 127.0.0.1 specifically — a `::1`-preferring resolver can miss it.
+ */
+export function localApiBaseUrl() {
+ const status = getNetworkExposureStatus();
+ const port = status.loopbackMirror.enabled
+ ? status.loopbackMirror.port
+ : status.bind.port;
+ return `http://127.0.0.1:${port}`;
+}
+
const setupStep = (id, title, status, detail, action = null) => ({
id,
title,
diff --git a/server/lib/networkExposure.test.js b/server/lib/networkExposure.test.js
index 242dda8f95..dba3c16100 100644
--- a/server/lib/networkExposure.test.js
+++ b/server/lib/networkExposure.test.js
@@ -36,6 +36,7 @@ import {
getNetworkExposureSetupStatus,
getNetworkExposureStatus,
isLoopbackHost,
+ localApiBaseUrl,
} from './networkExposure.js';
describe('networkExposure.isLoopbackHost', () => {
@@ -55,6 +56,44 @@ describe('networkExposure.isLoopbackHost', () => {
});
});
+describe('networkExposure.localApiBaseUrl', () => {
+ const ORIGINAL_ENV = { ...process.env };
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ delete process.env.PORT;
+ delete process.env.PORTOS_HTTP_PORT;
+ statSync.mockReturnValue(undefined);
+ hasTailscaleCert.mockReturnValue(false);
+ getSelfHost.mockReturnValue(null);
+ });
+
+ afterEach(() => {
+ process.env = { ...ORIGINAL_ENV };
+ });
+
+ // Under HTTPS the API port is TLS-only, so handing a plain-HTTP caller that
+ // port fails at the transport layer — the mirror is the only correct target.
+ it('resolves to the loopback HTTP mirror port when HTTPS is active', () => {
+ getHttpsEnabledAtBoot.mockReturnValue({ value: true, initialized: true });
+ expect(localApiBaseUrl()).toBe('http://127.0.0.1:5553');
+ });
+
+ it('honors PORTOS_HTTP_PORT for the mirror', () => {
+ getHttpsEnabledAtBoot.mockReturnValue({ value: true, initialized: true });
+ process.env.PORTOS_HTTP_PORT = '5999';
+ expect(localApiBaseUrl()).toBe('http://127.0.0.1:5999');
+ });
+
+ it('resolves to the bound API port when HTTPS is off and no mirror is bound', () => {
+ getHttpsEnabledAtBoot.mockReturnValue({ value: false, initialized: true });
+ expect(localApiBaseUrl()).toBe('http://127.0.0.1:5555');
+
+ process.env.PORT = '6000';
+ expect(localApiBaseUrl()).toBe('http://127.0.0.1:6000');
+ });
+});
+
describe('networkExposure.getNetworkExposureStatus', () => {
const ORIGINAL_ENV = { ...process.env };
diff --git a/server/services/agentPromptBuilder.test.js b/server/services/agentPromptBuilder.test.js
index 257d4bfd07..727f2a6944 100644
--- a/server/services/agentPromptBuilder.test.js
+++ b/server/services/agentPromptBuilder.test.js
@@ -2112,7 +2112,7 @@ describe('buildLightContextPrompt', () => {
// loopback API — without it the lmstudio/ollama reviewer kinds have no
// way to actually run a review.
expect(prompt).toMatch(/POST the diff to PortOS's local reviewer endpoint/);
- expect(prompt).toMatch(/http:\/\/localhost:5555\/api\/code-review\/local/);
+ expect(prompt).toMatch(/http:\/\/127\.0\.0\.1:5555\/api\/code-review\/local/);
expect(prompt).toMatch(/gh pr diff 9 \| jq/);
expect(prompt).toMatch(/jq -er '\.findings \| select\(type == "string" and length > 0\)'/);
expect(prompt).toMatch(/Never treat an absent or malformed response as clean/);
diff --git a/server/services/promptSections/reviewLifecycle.js b/server/services/promptSections/reviewLifecycle.js
index bf5b331ac7..3141a019f9 100644
--- a/server/services/promptSections/reviewLifecycle.js
+++ b/server/services/promptSections/reviewLifecycle.js
@@ -6,6 +6,7 @@ import { DEFAULT_REVIEWER, DEFAULT_REVIEW_STOP_MODE, LOCAL_LLM_REVIEWERS, MODEL_
import { oversizedBodyPointer } from '../../lib/slashdoInvocation.js';
import { detectForgeCli } from '../../lib/gitForge.js';
import { shellQuote } from '../../lib/shellQuote.js';
+import { localApiBaseUrl } from '../../lib/networkExposure.js';
import { INLINE_REVIEW_LOOP_STEP } from './constants.js';
import { normalizeForgeCli } from './forge.js';
@@ -346,8 +347,10 @@ export function buildReviewLoopFollowUpSection(metadata = {}, { verbose = false,
// per-reviewer-kind bullet that actually applies to the configured list.
// `lmstudio`/`ollama` don't have CLIs the agent can spawn — PortOS exposes
// `POST /api/code-review/local` which runs the configured local model against
- // the diff and returns findings text. The agent always reaches it via
- // `http://localhost:5555` (the canonical loopback API port).
+ // the diff and returns findings text. The agent reaches it over plain HTTP at
+ // `localApiBaseUrl()` — the loopback HTTP mirror port when this install booted
+ // with HTTPS (where the API port is TLS-only and a plain-HTTP curl would fail
+ // at the transport layer), the API port otherwise.
// A pinned local-LLM model can't ride the endpoint's server-side default: that
// reads the GLOBAL settings scalar and has never seen this task. So when the
// user pinned one on the reviewer's row, name it in the request body — `model`
@@ -384,6 +387,7 @@ export function buildReviewLoopFollowUpSection(metadata = {}, { verbose = false,
...(localLlmPins.some(p => p.effort) ? ['effort: "…"'] : []),
'diff: .'
].join(', ');
+ const apiBase = localApiBaseUrl();
const diffCommand = localOnly
? `git diff ${renderedBaseBranch}...HEAD`
: reviewForgeCli === 'glab'
@@ -392,7 +396,7 @@ export function buildReviewLoopFollowUpSection(metadata = {}, { verbose = false,
const localLlmInvocation = `POST the diff to PortOS's local reviewer endpoint and extract its review text before evaluating it. Substitute the active reviewer name for \`<lmstudio|ollama>\`:
\`\`\`bash
REVIEW_RESPONSE=$(mktemp)
-HTTP_STATUS=$(${diffCommand} | jq -Rs '{ backend: "<lmstudio|ollama>", diff: . }' | curl -sS -X POST http://localhost:5555/api/code-review/local -H 'Content-Type: application/json' -d @- -o "$REVIEW_RESPONSE" -w '%{http_code}') || {
+HTTP_STATUS=$(${diffCommand} | jq -Rs '{ backend: "<lmstudio|ollama>", diff: . }' | curl -sS -X POST ${apiBase}/api/code-review/local -H 'Content-Type: application/json' -d @- -o "$REVIEW_RESPONSE" -w '%{http_code}') || {
echo "Local reviewer failed: request transport error" >&2
STATUS=cli-error
exit 1
@@ -532,7 +536,7 @@ Only a successfully extracted \`.findings\` value is the review text; treat it l
const challengeProtocolNote = [
'**Challenge protocol (dispute a wrong rejection — use sparingly):** If a reviewer raises a BLOCKING finding you have strong, specific evidence is a false positive (it misread the diff, flagged intended behavior, or contradicts a documented repo convention), do NOT silently "fix" it or accept a false block — dispute it **exactly once** for this task:',
'```bash',
- `curl -sS -X POST http://localhost:5555/api/cos/tasks/${sourceTaskId}/challenge -H 'Content-Type: application/json' -d '{"reason":"<why the finding is wrong>","evidence":"<file:line or diff quote>","reviewer":"<disputed reviewer>"}'`,
+ `curl -sS -X POST ${apiBase}/api/cos/tasks/${sourceTaskId}/challenge -H 'Content-Type: application/json' -d '{"reason":"<why the finding is wrong>","evidence":"<file:line or diff quote>","reviewer":"<disputed reviewer>"}'`,
'```',
`A \`409\` (\`CHALLENGE_EXHAUSTED\` = the one challenge is spent, or \`CHALLENGE_BUDGET_EXHAUSTED\` = the task is out of retry budget) means you can't dispute — then fix the finding or, if genuinely blocked, ${localOnly ? 'stop without pushing or opening a PR/MR' : 'post a PR comment and stop'}. After filing, RE-CHECK: re-run the disputed reviewer (or another configured reviewer) against the current diff, then resolve — overturned → \`POST .../challenge/resolve\` with \`{"outcome":"upheld"}\` and continue to ${localOnly ? 'the PR/MR creation step' : 'merge'}; confirmed → fix it, or send \`{"outcome":"escalated"}\` to hand the dispute to the user.` + (hasLocalLlm ? ' For a local reviewer you may instead POST `{"recheck":{"backend":"<lmstudio|ollama>","diff":"<unified diff>"}}` and let the server re-run it and auto-derive the outcome.' : ''),
].join('\n');
diff --git a/server/services/promptSections/reviewLifecycle.test.js b/server/services/promptSections/reviewLifecycle.test.js
new file mode 100644
index 0000000000..e68848241b
--- /dev/null
+++ b/server/services/promptSections/reviewLifecycle.test.js
@@ -0,0 +1,59 @@
+/**
+ * The review-lifecycle prompt hands CoS agents two copy-pasteable `curl`
+ * commands aimed at this install's own API. Those must resolve through
+ * `localApiBaseUrl()` rather than a hardcoded origin: on an install that ran
+ * `npm run setup:cert`, `:5555` is TLS-only and a plain-HTTP request to it dies
+ * at the transport layer, so the local-LLM reviewer reports `cli-error` and the
+ * challenge-protocol dispute silently cannot be filed (#5656).
+ */
+
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
+
+vi.mock('../../lib/httpsState.js', () => ({
+ getHttpsEnabledAtBoot: vi.fn(() => ({ value: false, initialized: true })),
+}));
+
+import { getHttpsEnabledAtBoot } from '../../lib/httpsState.js';
+import { buildReviewLoopFollowUpSection } from './reviewLifecycle.js';
+
+const metadata = {
+ reviewLoopFollowUp: true,
+ reviewLoopPRUrl: 'https://github.com/example-org/example-repo/pull/9',
+ reviewLoopPRBranch: 'feature-branch',
+ reviewLoopPRNumber: 9,
+ reviewLoopReviewers: ['lmstudio'],
+ sourceTaskId: 'task-example',
+};
+
+describe('reviewLifecycle agent-facing API origin', () => {
+ const ORIGINAL_ENV = { ...process.env };
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ delete process.env.PORT;
+ delete process.env.PORTOS_HTTP_PORT;
+ });
+
+ afterEach(() => {
+ process.env = { ...ORIGINAL_ENV };
+ });
+
+ it('points both agent curl commands at the loopback HTTP mirror when HTTPS is active', () => {
+ getHttpsEnabledAtBoot.mockReturnValue({ value: true, initialized: true });
+
+ const section = buildReviewLoopFollowUpSection(metadata);
+
+ expect(section).not.toContain(':5555');
+ expect(section).toContain('http://127.0.0.1:5553/api/code-review/local');
+ expect(section).toContain('http://127.0.0.1:5553/api/cos/tasks/task-example/challenge');
+ });
+
+ it('uses the API port directly when HTTPS is off and no mirror is bound', () => {
+ getHttpsEnabledAtBoot.mockReturnValue({ value: false, initialized: true });
+
+ const section = buildReviewLoopFollowUpSection(metadata);
+
+ expect(section).toContain('http://127.0.0.1:5555/api/code-review/local');
+ expect(section).toContain('http://127.0.0.1:5555/api/cos/tasks/task-example/challenge');
+ });
+});