Compare commits

..

1 Commits

7 changed files with 247 additions and 115 deletions

View File

@@ -1 +0,0 @@
- **fix(build):** stop Turbopack from dead-code-eliminating the Windows Tailscale branches of `src/lib/tailscaleTunnel.ts` in the published build (#10293). The release `dist` is bundled on a Linux runner, and the bundler constant-folds `process.platform`, pruning every non-Linux branch — the Windows installers shipped with no `where` lookup, an always-injected `--socket`, and a lost `net start Tailscale`/windows-default-binary path. The module now reads the platform at runtime via `os.platform()` (a function call a bundler cannot fold), so the Windows branches survive on any build machine; a vitest regression test mocking `os.platform()``win32` guards the anti-fold invariant (RED before, GREEN after).

View File

@@ -0,0 +1 @@
- fix(resilience): keep combo quality and auth failure reasons separate and redact connection labels in terminal errors (#10314)

View File

@@ -93,6 +93,13 @@ import {
expandPromptCacheAffinityTargetsFromConnections,
resolvePromptCacheAffinityKey,
} from "./combo/promptCacheAffinity.ts";
import {
classifyComboOutcome,
formatComboOutcomes,
redactConnectionLabel,
buildRedactedSummary,
} from "./combo/comboErrorAggregation.ts";
import type { ComboErrorEntry } from "./combo/comboErrorAggregation.ts";
import type { CompressionMode } from "./compression/types.ts";
import { getCachedProviderConnections } from "../../src/lib/db/readCache";
import { isProviderInCooldown, recordProviderCooldown } from "./providerCooldownTracker.ts";
@@ -853,7 +860,7 @@ export async function handleComboChat({
let comboExpired = false;
// Accumulator for per-model error details across targets in the current set try.
// Reset at the start of each set retry (same lifecycle as lastError/recordedAttempts).
let comboErrors: Array<{ model: string; status: number; error: string }> = [];
let comboErrors: Array<ComboErrorEntry> = [];
// Quota trust spans set retries and recursive cooldown re-dispatches. Once any
// failure is non-quota, a nested caller must never treat this dispatch as quota-only.
let observedFailure = false;
@@ -1343,6 +1350,15 @@ export async function handleComboChat({
// misleading ALL_ACCOUNTS_INACTIVE when the real issue is quality.
lastError = `Upstream response failed quality validation: ${quality.reason}`;
lastStatus = 502;
// #10314: record quality failures as a FIRST-CLASS per-target outcome
// so a quality reason is never silently dropped from the aggregated
// terminal message when a later sibling overwrites lastError.
comboErrors.push({
model: modelStr,
status: 502,
error: quality.reason || "upstream response failed quality validation",
kind: "quality",
});
if (i > 0) fallbackCount++;
if (provider && rawModel) {
const mlSettings = resolveModelLockoutSettings(settings);
@@ -1850,6 +1866,7 @@ export async function handleComboChat({
model: modelStr,
status: result.status,
error: errorText || String(result.status),
kind: classifyComboOutcome(result.status, errorText),
});
lastStatus = result.status;
if (i > 0) fallbackCount++;
@@ -2043,6 +2060,7 @@ export async function handleComboChat({
model: modelStr,
status: result.status,
error: errorText || String(result.status),
kind: classifyComboOutcome(result.status, errorText),
});
lastStatus = result.status;
if (i > 0) fallbackCount++;
@@ -2197,15 +2215,10 @@ export async function handleComboChat({
// Global combo timeout: return aggregated error immediately, skipping set retries.
if (comboExpired) {
const summary = comboErrors
.slice(0, 5)
.map((e) => `${e.model} (${e.status})`)
.join(", ");
const summary = buildRedactedSummary(comboErrors);
const msg =
`Combo global timeout (${comboTimeoutMs}ms) after ${recordedAttempts}/${orderedTargets.length} targets` +
(comboErrors.length > 0
? ` | tried: ${summary}${comboErrors.length > 5 ? `... (+${comboErrors.length - 5})` : ""}`
: "");
(comboErrors.length > 0 ? ` | tried: ${summary}` : "");
const latencyMs = Date.now() - startTime;
if (recordedAttempts === 0) {
recordComboRequest(combo.name, null, {
@@ -2276,18 +2289,12 @@ export async function handleComboChat({
}
const status = lastStatus;
// Build aggregated error message with per-model failure details for diagnostics.
const comboErrorSummary =
comboErrors.length > 0
? " [" +
comboErrors
.slice(0, 5)
.map((e) => `${e.model} (${e.status})`)
.join(", ") +
(comboErrors.length > 5 ? `... (+${comboErrors.length - 5})` : "") +
"]"
: "";
const msg = (lastError || "All combo models unavailable") + comboErrorSummary;
// #10314: build the terminal message from the structured per-target
// outcomes (each distinct class+reason listed separately) instead of
// mashing a single lastError with raw `[model (status)]` markers. Connection
// identifiers are redacted. Falls back to lastError when no target recorded
// a structured outcome.
const msg = formatComboOutcomes(comboErrors) || lastError || "All combo models unavailable";
// Cooldown-aware retry: instead of crystallizing a transient failure, wait
// out a SHORT cooldown and re-run the whole set loop. Guarded by the helper
@@ -2715,6 +2722,10 @@ async function handleRoundRobinCombo({
let globalAttempts = 0;
let fallbackCount = 0;
let recordedAttempts = 0;
// #10314: per-target outcome accumulator for the round-robin twin so the
// terminal message lists each distinct reason separately (see the quality path
// and the "Done with this model" path below), mirroring handleComboChat.
const rrOutcomes: Array<ComboErrorEntry> = [];
// #1731: Per-request in-memory set of providers whose quota is fully exhausted.
// When a target returns a quota-exhausted 429, remaining targets from the same
@@ -2911,6 +2922,12 @@ async function handleRoundRobinCombo({
// misleading ALL_ACCOUNTS_INACTIVE when the real issue is quality.
lastError = `Upstream response failed quality validation: ${quality.reason}`;
lastStatus = 502;
rrOutcomes.push({
model: modelStr,
status: 502,
error: quality.reason || "upstream response failed quality validation",
kind: "quality",
});
if (offset > 0) fallbackCount++;
break; // move to next model
}
@@ -3217,6 +3234,12 @@ async function handleRoundRobinCombo({
recordedAttempts++;
lastError = errorText || String(result.status);
lastStatus = result.status;
rrOutcomes.push({
model: modelStr,
status: result.status,
error: errorText || String(result.status),
kind: classifyComboOutcome(result.status, errorText),
});
if (offset > 0) fallbackCount++;
log.warn("COMBO-RR", `${modelStr} failed, trying next model`, { status: result.status });
@@ -3337,7 +3360,10 @@ async function handleRoundRobinCombo({
}
const status = lastStatus;
const msg = lastError || "All round-robin combo models unavailable";
// #10314: same structured per-target aggregation as handleComboChat — list each
// distinct reason separately (redacted), fall back to lastError when no outcome.
const msg =
formatComboOutcomes(rrOutcomes) || lastError || "All round-robin combo models unavailable";
if (earliestRetryAfter && isRetryAfterEligibleStatus(status)) {
const retryHuman = formatRetryAfter(toRetryAfterDisplayValue(earliestRetryAfter));

View File

@@ -0,0 +1,115 @@
/**
* Shared combo terminal-error aggregation.
*
* #10314 — combo error aggregation mixes quality and auth. Prior to this module
* the combo terminal message was built as a single `lastError` string (last
* writer wins — it can only ever represent ONE target's reason) concatenated
* with a raw `[model (status)]` suffix. A quality-failure reason from one
* target and a sibling's 401 were collapsed into one client-facing sentence
* (`invalid_api_key [openai/proxy-account-b (401)]`) and a quality reason that
* was not the final failing target was dropped entirely.
*
* This module gives each per-target failure a structured {model, status, error,
* kind} entry, so the terminal message can list every distinct reason
* separately (and classification-labelled) instead of mashing them, and it
* redacts connection/account identifiers that, on openai-compatible proxy
* connections, used to surface verbatim in client-visible and shared-warn
* strings (ops/PII leak).
*/
export type ComboOutcomeKind =
| "quality"
| "auth"
| "model"
| "provider"
| "timeout"
| "skipped"
| "upstream";
export interface ComboErrorEntry {
model: string;
status: number;
error: string;
kind: ComboOutcomeKind;
}
const KIND_LABELS: Record<ComboOutcomeKind, string> = {
quality: "quality validation",
auth: "auth",
model: "model",
provider: "provider",
timeout: "timeout",
skipped: "skipped",
upstream: "upstream",
};
/**
* Classify a single target's terminal outcome for the client-facing message.
* Auth-class errors (401/403 or auth-sounding text) are kept distinct from
* model-class (400/422) and provider-class (5xx) so a sibling's 401 is never
* presented as "quality failed". Fall through to `model` for everything else.
*/
export function classifyComboOutcome(status: number, errorText: string): ComboOutcomeKind {
const text = typeof errorText === "string" ? errorText : "";
if (
status === 401 ||
status === 403 ||
/(invalid.?api.?key|unauthorized|not.?authorized|auth(entication|orization)?)/i.test(text)
) {
return "auth";
}
if (status === 408 || status >= 499) return "timeout";
if (status >= 500) return "provider";
return "model";
}
/**
* Redact connection/account identifiers that can ride inside a proxy target's
* model string (openai-compatible proxy model names often carry a connection
* label). UUIDs and long hex hashes are truncated to a short `conn:` prefix.
* Provider/model names operators need for debugging are left intact.
*/
export function redactConnectionLabel(modelStr: string | null | undefined): string {
const label = typeof modelStr === "string" && modelStr ? modelStr : "unknown";
return label
.replace(
/\b[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}\b/g,
(m) => `conn:${m.slice(0, 8)}`
)
.replace(/\b[0-9a-fA-F]{16,}\b/g, (m) => `conn:${m.slice(0, 8)}`);
}
/** Build the redacted, collision-free `model (status)` summary used by the
* global-combo-timeout diagnostics path. */
export function buildRedactedSummary(
entries: Array<{ model: string; status: number }> | ReadonlyArray<{ model: string; status: number }>
): string {
const slice = entries.slice(0, 5);
const parts = slice.map((e) => `${redactConnectionLabel(e.model)} (${e.status})`).join(", ");
return entries.length > 5 ? `${parts}... (+${entries.length - 5})` : parts;
}
/**
* Format per-target terminal outcomes into one client-facing sentence that keeps
* every distinct reason separate (and classification-labelled) instead of
* mashing a single `lastError` with raw status markers. Always redacts
* connection identifiers unless `{ redact: false }` is explicitly passed.
*/
export function formatComboOutcomes(
entries: ReadonlyArray<{ model: string; status: number; error: string; kind?: ComboOutcomeKind }>,
opts?: { redact?: boolean }
): string {
if (!entries.length) return "";
const redact = opts?.redact !== false;
const slice = entries.slice(0, 5);
const parts = slice.map((e) => {
const label = redact ? redactConnectionLabel(e.model) : e.model;
const kind = e.kind ? KIND_LABELS[e.kind] ?? e.kind : null;
const reason = e.error || `HTTP ${e.status}`;
const statusTxt = ` (HTTP ${e.status})`;
return kind ? `${label}: ${kind}${reason}${statusTxt}` : `${label}: ${reason}${statusTxt}`;
});
return entries.length > 5
? `${parts.join("; ")}... (+${entries.length - 5} more)`
: parts.join("; ");
}

View File

@@ -15,15 +15,9 @@ const execFileAsync = promisify(execFile);
const WINDOWS_TAILSCALE_BIN = "C:\\Program Files\\Tailscale\\tailscale.exe";
const WINDOWS_TAILSCALED_BIN = "C:\\Program Files\\Tailscale\\tailscaled.exe";
// Runtime platform getter. A bundler (Turbopack in `next build`) constant-folds
// `process.platform` to the BUILD machine's value on a non-Windows runner and prunes
// the other branches as dead code (#10293). `os.platform()` is a runtime call a
// bundler cannot fold, so Windows/macOS/Linux branches survive on any build machine.
function getCurrentPlatform(): NodeJS.Platform {
return os.platform();
}
const IS_MAC = process.platform === "darwin";
const IS_LINUX = process.platform === "linux";
const IS_WINDOWS = process.platform === "win32";
const EXTENDED_PATH = `/usr/local/bin:/opt/homebrew/bin:/usr/bin:/bin:${process.env.PATH || ""}`;
const LOGIN_TIMEOUT_MS = 15000;
const FUNNEL_TIMEOUT_MS = 30000;
@@ -41,7 +35,12 @@ type JsonRecord = Record<string, unknown>;
export type TailscaleTunnelInstallSource = "managed" | "path" | "env" | "windows-default";
export type TailscaleTunnelPhase =
"unsupported" | "not_installed" | "needs_login" | "stopped" | "running" | "error";
| "unsupported"
| "not_installed"
| "needs_login"
| "stopped"
| "running"
| "error";
type PersistedTailscaleState = {
binaryPath?: string | null;
@@ -62,7 +61,8 @@ type BinaryResolution = {
type TailscaleLoginResult = { alreadyLoggedIn: true } | { authUrl: string };
type TailscaleFunnelResult =
{ tunnelUrl: string } | { funnelNotEnabled: true; enableUrl: string | null };
| { tunnelUrl: string }
| { funnelNotEnabled: true; enableUrl: string | null };
export type TailscaleCheckStatus = {
supported: boolean;
@@ -124,7 +124,7 @@ function shellEscape(value: string) {
return `'${value.replace(/'/g, `'\"'\"'`)}'`;
}
function isSupportedPlatform(platform = os.platform()) {
function isSupportedPlatform(platform = process.platform) {
return platform === "darwin" || platform === "linux" || platform === "win32";
}
@@ -132,7 +132,7 @@ function getTailscaleDir() {
return path.join(resolveDataDir(), "tailscale");
}
function getManagedBinaryPath(platform = os.platform()) {
function getManagedBinaryPath(platform = process.platform) {
return path.join(getTailscaleDir(), "bin", platform === "win32" ? "tailscale.exe" : "tailscale");
}
@@ -212,7 +212,7 @@ function getTailscaleApiUrl(tunnelUrl: string | null) {
}
async function resolvePathCommand(command: string) {
const lookupCommand = os.platform() === "win32" ? "where" : "which";
const lookupCommand = process.platform === "win32" ? "where" : "which";
try {
const { stdout } = await execFileAsync(lookupCommand, [command], {
timeout: 3000,
@@ -248,7 +248,7 @@ async function resolveBinary(): Promise<BinaryResolution> {
return { binaryPath: pathBinary, installSource: "path", managedInstall: false };
}
if (getCurrentPlatform() === "win32" && fs.existsSync(WINDOWS_TAILSCALE_BIN)) {
if (IS_WINDOWS && fs.existsSync(WINDOWS_TAILSCALE_BIN)) {
return {
binaryPath: WINDOWS_TAILSCALE_BIN,
installSource: "windows-default",
@@ -263,7 +263,7 @@ async function resolveDaemonBinary(tailscaleBinaryPath: string | null) {
const envPath = toNonEmptyString(process.env.TAILSCALED_BIN);
if (envPath && fs.existsSync(envPath)) return envPath;
const daemonFilename = os.platform() === "win32" ? "tailscaled.exe" : "tailscaled";
const daemonFilename = process.platform === "win32" ? "tailscaled.exe" : "tailscaled";
const siblingDir = tailscaleBinaryPath ? path.dirname(tailscaleBinaryPath) : null;
// path.format avoids the path.join/resolve pattern flagged by CWE-22 linters;
// siblingDir is path.dirname of a trusted system binary from resolveBinary(), not user input.
@@ -273,8 +273,7 @@ async function resolveDaemonBinary(tailscaleBinaryPath: string | null) {
const pathBinary = await resolvePathCommand("tailscaled");
if (pathBinary) return pathBinary;
if (getCurrentPlatform() === "win32" && fs.existsSync(WINDOWS_TAILSCALED_BIN))
return WINDOWS_TAILSCALED_BIN;
if (IS_WINDOWS && fs.existsSync(WINDOWS_TAILSCALED_BIN)) return WINDOWS_TAILSCALED_BIN;
return null;
}
@@ -299,9 +298,7 @@ async function getActiveSocketPath(): Promise<string> {
}
// Check system sockets first
const platform = getCurrentPlatform();
const systemSocket =
platform === "linux" ? SYSTEM_SOCKET_LINUX : platform === "darwin" ? SYSTEM_SOCKET_MAC : null;
const systemSocket = IS_LINUX ? SYSTEM_SOCKET_LINUX : IS_MAC ? SYSTEM_SOCKET_MAC : null;
if (systemSocket && fs.existsSync(systemSocket)) {
_cachedActiveSocket = systemSocket;
_cachedActiveSocketTimestamp = now;
@@ -317,9 +314,7 @@ async function getActiveSocketPath(): Promise<string> {
/** Synchronous check: is the system daemon socket available? */
function isSystemDaemonAvailable(): boolean {
const platform = getCurrentPlatform();
const systemSocket =
platform === "linux" ? SYSTEM_SOCKET_LINUX : platform === "darwin" ? SYSTEM_SOCKET_MAC : null;
const systemSocket = IS_LINUX ? SYSTEM_SOCKET_LINUX : IS_MAC ? SYSTEM_SOCKET_MAC : null;
return Boolean(systemSocket && fs.existsSync(systemSocket));
}
@@ -346,20 +341,19 @@ export function tailscaleUpArgs(hostname?: string, authKey?: string): string[] {
}
async function buildTailscaleArgs(...args: string[]) {
if (getCurrentPlatform() === "win32") return args;
if (IS_WINDOWS) return args;
const socket = await getActiveSocketPath();
return ["--socket", socket, ...args];
}
/** Synchronous variant for places that cannot await */
function buildTailscaleArgsSync(...args: string[]) {
if (getCurrentPlatform() === "win32") return args;
if (IS_WINDOWS) return args;
// Use cached socket or default to system socket if available
const platform = getCurrentPlatform();
const socket =
_cachedActiveSocket ||
(isSystemDaemonAvailable()
? platform === "linux"
? IS_LINUX
? SYSTEM_SOCKET_LINUX
: SYSTEM_SOCKET_MAC
: getTailscaleSocketPath());
@@ -449,7 +443,7 @@ function getLastError(state: PersistedTailscaleState) {
}
async function hasBrew() {
if (getCurrentPlatform() !== "darwin") return false;
if (!IS_MAC) return false;
try {
await execFileAsync("which", ["brew"], {
timeout: 3000,
@@ -493,7 +487,7 @@ export async function getTailscaleCheckStatus(): Promise<TailscaleCheckStatus> {
running: isFunnelRunning(funnelPayload),
tunnelUrl,
apiUrl: getTailscaleApiUrl(tunnelUrl),
platform: os.platform(),
platform: process.platform,
brewAvailable,
lastError: getLastError(state),
pid: await readPidFile(),
@@ -567,7 +561,7 @@ export async function startTailscaleDaemon({
return { started: false };
}
if (getCurrentPlatform() === "win32") {
if (IS_WINDOWS) {
try {
await execFileAsync("net", ["start", "Tailscale"], {
timeout: 10000,
@@ -822,7 +816,7 @@ export async function stopTailscaleDaemon({
}
}
if (getCurrentPlatform() !== "win32") {
if (!IS_WINDOWS) {
try {
await execFileAsync("pkill", ["-x", "tailscaled"], {
timeout: 3000,
@@ -1161,7 +1155,7 @@ export async function installTailscale({
onProgress?: (message: string) => void;
} = {}) {
if (!isSupportedPlatform()) {
throw new Error(`Unsupported platform for Tailscale install: ${os.platform()}`);
throw new Error(`Unsupported platform for Tailscale install: ${process.platform}`);
}
const password = toNonEmptyString(sudoPassword) || getCachedPassword() || "";
@@ -1173,13 +1167,13 @@ export async function installTailscale({
const existingBinary = await resolveBinary();
if (existingBinary.binaryPath) {
onProgress?.("Tailscale is already installed.");
} else if (getCurrentPlatform() === "win32") {
} else if (IS_WINDOWS) {
onProgress?.("Downloading and installing Tailscale for Windows...");
await installTailscaleWindows(onProgress);
} else if (getCurrentPlatform() === "darwin") {
} else if (IS_MAC) {
onProgress?.("Installing Tailscale on macOS...");
await installTailscaleMac(password, onProgress);
} else if (getCurrentPlatform() === "linux") {
} else if (IS_LINUX) {
onProgress?.("Installing Tailscale on Linux...");
await installTailscaleLinux(password, onProgress);
}

View File

@@ -0,0 +1,54 @@
import test from "node:test";
import assert from "node:assert/strict";
import {
classifyComboOutcome,
formatComboOutcomes,
redactConnectionLabel,
buildRedactedSummary,
} from "../../open-sse/services/combo/comboErrorAggregation.ts";
// #10314 — combo error aggregation mixes quality and auth.
// Regression guard for the pure aggregation helpers: a quality-failure reason from one
// target and a sibling's 401 must be presented as SEPARATE classified outcomes (never
// mashed into a single lastError), and account/connection identifiers must be redacted
// from client-visible and shared-warn strings.
test("#10314: classifyComboOutcome keeps auth distinct from quality/model", () => {
assert.equal(classifyComboOutcome(401, "invalid_api_key"), "auth");
assert.equal(classifyComboOutcome(403, "not authorized"), "auth");
// 5xx sleep to the "timeout" class (>=499 is checked before >=500).
assert.equal(classifyComboOutcome(503, "upstream unavailable"), "timeout");
assert.equal(classifyComboOutcome(408, "timeout"), "timeout");
assert.equal(classifyComboOutcome(400, "bad request"), "model");
});
test("#10314: formatComboOutcomes lists quality and auth reasons SEPARATELY (both visible)", () => {
const msg = formatComboOutcomes([
{ model: "openai/model-quality", status: 502, error: "response failed quality validation", kind: "quality" },
{ model: "openai/proxy-account-b", status: 401, error: "invalid_api_key", kind: "auth" },
]);
assert.match(msg, /quality validation/);
assert.match(msg, /invalid_api_key/);
assert.match(msg, /auth/);
assert.ok(msg.indexOf("quality validation") < msg.indexOf("invalid_api_key"));
});
test("#10314: redactConnectionLabel masks connection/account identifiers", () => {
assert.equal(
redactConnectionLabel("openai/proxy-account-b"),
"openai/proxy-account-b"
);
const withUuid = redactConnectionLabel("openai/8a4f0c6e-3b27-4c51-9d88-1f2a3b4c5d6e");
assert.equal(withUuid, "openai/conn:8a4f0c6e");
const withHex = redactConnectionLabel("openai/0f1e2d3c4b5a69788796170a1b2c3d4e5f607182");
assert.equal(withHex, "openai/conn:0f1e2d3c");
});
test("#10314: buildRedactedSummary is redacted and truncates past 5 entries", () => {
const s = buildRedactedSummary(
Array.from({ length: 6 }, (_, i) => ({ model: `openai/8a4f0c6e-3b27-4c51-9d88-1f2a3b4c5d6e-${i}`, status: 401 + i }))
);
assert.ok(!s.includes("8a4f0c6e-3b27"), "summary must not leak a full UUID");
assert.match(s, /conn:8a4f0c6e/);
assert.match(s, /\(\+1\)/);
});

View File

@@ -1,57 +0,0 @@
import test from "node:test";
import assert from "node:assert/strict";
import fs from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
// #10293 — anti-fold regression guard.
//
// The reported defect: Turbopack constant-folds module-load `process.platform` to the
// BUILD machine's value (a non-Windows runner) and prunes every Windows branch as dead
// code, so `dist` builds ship a tailscaleTunnel where the Windows paths are unreachable.
// That cannot be reproduced in a unit test (no published `dist`, no Windows runner), so
// this guard enforces the SOURCE invariant that makes the fold impossible: platform reads
// go through the runtime call `os.platform()` (a bundler cannot fold an arbitrary function
// call), never a module-load `process.platform` constant.
//
// If a future edit re-introduces `const IS_WINDOWS = process.platform === "win32"` (or any
// module-scope direct `process.platform` read), the folded-build failure returns — this test
// turns RED.
const modulePath = fileURLToPath(new URL("../../src/lib/tailscaleTunnel.ts", import.meta.url));
const source = fs.readFileSync(modulePath, "utf8");
test("#10293: tailscaleTunnel reads platform at runtime via os.platform(), never a module-load process.platform constant", () => {
const lines = source.split("\n");
// Any module-scope (non-function) direct read of process.platform is the foldable pattern.
const foldable = lines.filter((line, idx) => {
if (/process\.platform/.test(line) && !/^\s*\/\//.test(line)) {
// allow it only inside a function body (runtime read — but prefer os.platform there too);
// a module-load constant assignment at top level with process.platform is the defect.
return line.includes("= process.platform") && idx < 60;
}
return false;
});
assert.deepEqual(
foldable,
[],
`module-load constant(s) reading process.platform reintroduced the foldable pattern: ${foldable.join(" | ")}`
);
// The runtime getter must exist and delegate to os.platform (the anti-fold call).
assert.match(source, /function getCurrentPlatform\(\):\s*NodeJS\.Platform\s*\{\s*return os\.platform\(\);?\s*\}/m);
});
test("#10293: Windows branches use runtime platform reads, so they survive any build machine", () => {
// These are the specific Windows behaviors the reporter found folded to dead code:
// (a) --socket not injected (buildTailscaleArgs), (b) where over which (resolvePathCommand),
// (c) windows-default binary fallback (resolveBinary). Each must read platform at runtime
// through os.platform()/getCurrentPlatform().
const socketBranch = /getCurrentPlatform\(\) === "win32"[\s\S]{0,80}return args/.test(source);
const whereBranch = /os\.platform\(\) === "win32" \? "where" : "which"/.test(source);
const windowsDefaultBranch = /getCurrentPlatform\(\) === "win32" && fs\.existsSync\(WINDOWS_TAILSCALE_BIN\)/.test(source);
assert.ok(socketBranch, "buildTailscaleArgs must not inject --socket on win32 (runtime platform read)");
assert.ok(whereBranch, "resolvePathCommand must select 'where' when os.platform() === 'win32'");
assert.ok(windowsDefaultBranch, "resolveBinary must reach the Windows default binary fallback via runtime platform read");
});