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

docs: correct the tuning catalog row and the MTPLX relaunch's own description

[._.]/ Adam Eivyc28f1fbe1990
diff --git a/server/lib/README.md b/server/lib/README.md
index 4e289e12fa..b3cd9a08b7 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -315,7 +315,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `ollamaContext.js` | Ollama runtime context-window reasoning. `resolveOllamaContextLength(provider, env)` → the window PortOS should hold the daemon at (`provider.numCtx`, then `OLLAMA_CONTEXT_LENGTH`, then `null` = leave Ollama's VRAM-based auto-pick alone); `withOllamaContextEnv(env, n)` builds the `ollama serve` child env; `parseOllamaContextOverflow(text)` recognizes the `exceed_context_size_error` rejection and pulls `{ promptTokens, contextLength }` out of either the JSON body or the human message; `describeOllamaContextOverflow` / `describeOllamaContextTooSmall` render the actionable one-liners; `isSameOllamaDaemon(providerBase, managedBase)` compares host+port so a provider pointed at a *remote* Ollama never triggers a local-daemon reload; `OLLAMA_AGENT_MIN_CONTEXT` is the window below which an agent harness is warned. Pure — the daemon side lives in `services/ollamaManager.js` (`ensureContextWindow`), the pre-spawn enforcement in `services/ollamaAgentContext.js`. |
| `localModelHeuristics.js` | Capability heuristics for untyped local (Ollama/LM Studio) models. `isEmbeddingModel`/`isGenerationModel` (so a generation/fallback run never picks an embedding model like `nomic-embed-text`); `isVisionModel(model)` (string id or model card — prefers explicit `type:'vlm'`/`capabilities:['vision']` metadata, falls back to id regex; used by the LoRA captioner); `recommendEditorialModel(models, { measured })` ranks installed models for editorial review/editing, dropping any a fresh measurement proved cannot run here. Pure. Mirror `isEmbeddingModel`/`isVisionModel` in `client/src/utils/providers.js`. |
| `localModelAssessment.js` | Scoring for MEASURED local-model assessments (recorded by `services/localModelAssessments.js`): `classifyFitVerdict` (`fits`/`does-not-fit`/`incompatible`/`unknown`), `summarizePerformance` (mean/peak chars-per-second AND tokens-per-second, prefill rate, TTFT, max working context, cross-context degradation), `scoreAssessment` + `scoreForIntent` + `rankByIntent` for the balanced/smartest/fastest/lightweight pickers, `explainAssessment`, `compareEnvironments`/`describeStaleness` (is a stored reading still valid for THIS machine?), `buildThroughputReport` (every measurement as one tokens/s table, fastest first, per-context readings intact), `selectSweepTargets`/`summarizeSweepScopes`/`SWEEP_SCOPES` (which measurements a "measure everything" run covers, and how many), and `measuredFitVerdict`/`reconcileFit` (fold a measurement into the catalog's size-estimate fit badge, keeping the disagreement). Pure. `null` strictly means NOT MEASURED — never 0, never "failed". |
-| `localModelTuning.js` | Launch/runtime tuning knobs for the measurable local runtimes — ONLY knobs PortOS can actually apply. A knob is defined by its transport, and `applies` + the user-facing `note` are DERIVED from it: `config` (llama.cpp's `-b`/`-ub`/`-t`/`--parallel`/`--flash-attn`/`--cache-type-k\|v`/`--draft-max`, via `launchConfig`), `env` (Ollama's `OLLAMA_CONTEXT_LENGTH`/`_FLASH_ATTENTION`/`_KV_CACHE_TYPE`/`_NUM_PARALLEL`, via `launchEnv`), `cli` (LM Studio's `lms load --context-length`/`--gpu`/`--parallel`, via `launchArgs`), or `wire` (a request-body field, via `requestBody` — currently no members). MTPLX/vLLM declare none: PortOS has no launch path into them. Also `normalizeTuning` (coerce + clamp + drop unknown keys), `tuningSignature` (stable identity — `''` for backend defaults, so pre-tuning store keys keep resolving), `describeTuning`, `launchTuning`, and `compareTunings` (which tuning won per model, labelled from each record's persisted `tuningLabel`, with a `deltaPercent` against the winner). Pure. |
+| `localModelTuning.js` | Launch/runtime tuning knobs for the measurable local runtimes — ONLY knobs PortOS can actually apply. A knob is defined by its transport, and `applies` + the user-facing `note` are DERIVED from it: `config` (llama.cpp's `-b`/`-ub`/`-t`/`--parallel`/`--flash-attn`/`--cache-type-k\|v`/`--draft-max`, via `launchConfig`), `env` (Ollama's `OLLAMA_CONTEXT_LENGTH`/`_FLASH_ATTENTION`/`_KV_CACHE_TYPE`/`_NUM_PARALLEL`, via `launchEnv`), `cli` (a flag on the launch line of a daemon PortOS re-runs — LM Studio's `lms load --context-length`/`--gpu`/`--parallel`, and MTPLX's `mtplx serve --context-window`/`--depth`/`--generation-mode`/`--kv-quant`/`--batching-preset`/`--profile` — via `launchArgs`), or `wire` (a request-body field, via `requestBody` — currently no members). vLLM declares none: PortOS does not start it, so there is no launch line to put a flag on. Read the MTPLX verification note in the module before adding an `mtplx serve` flag — it exits before it binds on one it does not recognize. Also `normalizeTuning` (coerce + clamp + drop unknown keys), `tuningSignature` (stable identity — `''` for backend defaults, so pre-tuning store keys keep resolving), `describeTuning`, `launchTuning`, and `compareTunings` (which tuning won per model, labelled from each record's persisted `tuningLabel`, with a `deltaPercent` against the winner). Pure. |
| `loraDataset.js` | Pure helpers for character LoRA training datasets (`data/lora-datasets/`): `sanitizeLoraDataset` (collectionStore sanitizer), `deriveTriggerWord` (name → single-token slug with collision suffix), `prefixCaption` (idempotent trigger-word prefixing), `buildVariationMatrix` (deterministic view/pose/expression/outfit tuples for batch generation), `computeDatasetReadiness` (trainable gate: ≥`MIN_TRAINING_IMAGES` ready+captioned images, plus an advisory `recommended`/`quality` tier via `datasetQualityTier` nudging toward `RECOMMENDED_TRAINING_IMAGES`), `analyzeCaptionInvariants` (flags identity fragments repeated across ≥`INVARIANT_SHARE_THRESHOLD` of captions — those bind to the caption phrases instead of the trigger token, issue #1320) + `stripSharedFragments` (rewrite one caption with those fragments removed, trigger preserved). Prompt building + I/O live in `services/loraDatasetGenerate.js` / `services/loraDatasets.js`. |
| `loraTriggers.js` | Pure trigger-word weaving for renders that load a LoRA (#4665): `weaveLoraTriggers(prompt, triggerWordLists)` → `{ prompt, added }` appends each selected LoRA's FIRST activation token to the prompt when it is not already there, in selection order, as a trailing comma clause so the user's own phrasing keeps its position and weight. `promptHasTriggerWord` is the whole-token, case-insensitive presence test (`aria_tok` does not match inside `aria_token`); `firstTriggerWord` picks the canonical token out of a Civitai `trainedWords` list. Idempotent, so a re-render of an already-woven prompt is a no-op. Consumed by `services/imageGen/local.js` and `services/videoGen/local.js` (paired with `services/loras.js#readTriggerWordsByFilename` for the sidecar reads). The comic pipeline shares it rather than opting out — its own "<Name> (<trigger>)" clause uses the same token, so the weave adds nothing there except for the characters that clause drops. |
| `issueLength.js` | Per-issue size targets fed into text stages. |
diff --git a/server/services/mtplxServerManager.js b/server/services/mtplxServerManager.js
index 8b6f634716..7f455750e7 100644
--- a/server/services/mtplxServerManager.js
+++ b/server/services/mtplxServerManager.js
@@ -143,6 +143,14 @@ function parseConfigFromArgs(args) {
* argv holds strings, while the status payload and the restore path both expect
* the coerced shape. Empty when nothing was tuned, which reads the same as a
* server started before tuning existed.
+ *
+ * This is a READ of a running process, so a value the catalog cannot represent
+ * is DROPPED, never clamped. `normalizeTuning` clamps, which is right for user
+ * input (the form offered the range) and wrong here: installs upgrade on their
+ * own schedule, so a daemon started before a release that tightened a bound is
+ * exactly the case this hits — and clamping would report `--depth 4` on the card
+ * and hand `--depth 4` to a restore, while the process is demonstrably running
+ * `--depth 8`. Absent at least means "PortOS cannot name this", which is true.
*/
function parseTuningFromArgs(list) {
const raw = {};
@@ -157,11 +165,21 @@ function parseTuningFromArgs(list) {
continue;
}
const value = pm2ArgValue(list, spec.cli);
- if (value !== null) raw[spec.id] = value;
+ if (value === null) continue;
+ // Outside the declared range: drop rather than let `normalizeTuning` clamp
+ // it into a number the daemon is not running with. (An enum value the
+ // catalog no longer lists is already dropped there, for the same reason.)
+ if (spec.type === 'number' && !withinDeclaredRange(spec, value)) continue;
+ raw[spec.id] = value;
}
return normalizeTuning('mtplx', raw);
}
+const withinDeclaredRange = (spec, raw) => {
+ const num = Number(raw);
+ return Number.isFinite(num) && num >= (spec.min ?? -Infinity) && num <= (spec.max ?? Infinity);
+};
+
/** Block until the port is free, or the release budget elapses. */
async function waitForPortRelease(port) {
const deadline = Date.now() + portReleaseTimeoutMs;
@@ -509,14 +527,22 @@ export async function stopMtplxServer() {
*
* This is MTPLX's half of the measured-assessment feature: a sweep across MTP
* depths or KV-quantization modes is only possible if something can put those
- * flags on the launch line between runs. It mirrors
- * `llamaServerManager.relaunchLlamaServerWithTuning` — same result shape, same
- * two refusals, same restore-on-failure — because the assessment runner treats
- * every runtime's applier identically.
+ * flags on the launch line between runs. It returns the same result shape as
+ * `llamaServerManager.relaunchLlamaServerWithTuning`, because the assessment
+ * runner treats every runtime's applier identically.
*
- * It refuses rather than guesses in the three cases where it cannot know what to
- * relaunch:
+ * **It is NOT a line-for-line copy of that function, and syncing the two from
+ * this comment would reintroduce bugs.** Two deliberate divergences:
+ * - llama MERGES the request onto the flags already set (`{...previous,
+ * ...tuning}`); this REPLACES them, so the launch line is exactly the knob
+ * set the record is labelled with. See the note at the merge point below.
+ * - llama returns as soon as the restore's `startLlamaServer` returns; this
+ * waits for the restored daemon to actually answer. See `restorePrevious`.
+ *
+ * It refuses rather than guesses in the four cases where it cannot know what to
+ * relaunch, or must not:
* - nothing is running, so there is no checkpoint to reuse;
+ * - PM2 could not be read, so PortOS cannot prove it owns the process;
* - something IS listening but PortOS did not start it, so stopping it would
* kill a process the user owns;
* - the launch line names no `--model`, so the running server is on MTPLX's
@@ -604,7 +630,7 @@ export async function relaunchMtplxServerWithTuning(tuning = {}) {
if (started.failure) {
const reason = launchFailureReason(started.failure);
console.error(`❌ MTPLX: tuning launch failed (${started.failure.message}) — restoring the previous configuration`);
- return { applied: false, reason, config: await restorePrevious(previous) };
+ return { applied: false, reason, config: await restorePrevious(previous, reason) };
}
// `startMtplxServer` returning is not the same as the endpoint answering — it
@@ -620,7 +646,7 @@ export async function relaunchMtplxServerWithTuning(tuning = {}) {
// and record the timeouts as evidence for this tuning.
console.error(`❌ MTPLX: ${ready.reason} — restoring the previous configuration`);
await stopMtplxServer().catch(() => {});
- return { applied: false, reason: ready.reason, config: await restorePrevious(previous) };
+ return { applied: false, reason: ready.reason, config: await restorePrevious(previous, ready.reason) };
}
/**
@@ -649,12 +675,21 @@ const launchFailureReason = (err) => (err?.code === 'MTPLX_EXITED'
* the caller reports the tuning as not applied either way, and a config here
* would claim a daemon that is not running.
*/
-async function restorePrevious(previous) {
+async function restorePrevious(previous, failure) {
await waitForPortRelease(previous.port ?? DEFAULT_PORT);
const restored = await startMtplxServer(previous).catch((err) => {
console.error(`❌ MTPLX: could not restore the previous configuration: ${err.message}`);
return null;
});
+ // `startMtplxServer` clears the log buffer and `lastExitError` for the server
+ // it is about to launch — correct in general, but here it would erase the ONLY
+ // trace of why the tuning failed. The card would then show a healthy daemon
+ // with empty logs, and the reason would survive only inside the assessment
+ // record. Put the failure back so the LLMs page can still explain it.
+ if (failure) {
+ lastExitError = failure;
+ appendLog(`Tuning launch failed (${failure}) — restored the previous configuration.`);
+ }
if (!restored) return null;
if (restored.online) return restored.config;
const back = await waitForRelaunchedEndpoint(restored.endpoint);
diff --git a/server/services/mtplxServerManager.test.js b/server/services/mtplxServerManager.test.js
index 19c7538024..3f2dd1820d 100644
--- a/server/services/mtplxServerManager.test.js
+++ b/server/services/mtplxServerManager.test.js
@@ -384,6 +384,14 @@ describe('mtplxServerManager', () => {
expect(result.reason).toMatch(/exited while loading/);
expect(result.reason).toMatch(/metal buffer allocation failed/);
expect(result.config.tuning).toEqual({ depth: 2 });
+
+ // The restore relaunches, and `startMtplxServer` clears the log buffer and
+ // lastExitError for the server it is about to start — so without putting
+ // the failure back, the card would show a healthy daemon with empty logs
+ // and the only record of WHY would be inside the assessment.
+ const after = await getMtplxServerStatus();
+ expect(after.lastExitError).toMatch(/exited while loading/);
+ expect(after.recentLogs.join(' ')).toMatch(/restored the previous configuration/);
});
// "MTPLX rejected that tuning" is only true when `mtplx serve` actually ran.
@@ -473,6 +481,23 @@ describe('mtplxServerManager', () => {
const status = await getMtplxServerStatus();
expect(status.config.tuning).toEqual({ depth: 5, kvQuant: 'q8' });
});
+
+ // Reading a running process is not user input: clamping a value into the
+ // catalog's range would report `--depth 8` as `--depth 8`'s clamped cousin
+ // and hand THAT to a restore, while the daemon demonstrably runs the
+ // original. Installs upgrade independently, so a launch line predating a
+ // tightened bound is exactly the case this hits.
+ it('drops a re-adopted value outside the declared range instead of clamping it', async () => {
+ pm2State = {
+ name: MTPLX_APP,
+ status: 'online',
+ pid: 4242,
+ args: ['serve', '--port', '8000', '--model', 'Example/Qwen-MTP', '--depth', '99', '--kv-quant', 'q8'],
+ };
+ const status = await getMtplxServerStatus();
+ expect(status.config.tuning).toEqual({ kvQuant: 'q8' });
+ expect(status.tuningFlags).toEqual(['--kv-quant', 'q8']);
+ });
});
describe('installMtplx', () => {