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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix: close the review's third round — status ops, shutdown races, redaction
[._.]/ Adam Eivyc3b8f9afa242
diff --git a/server/lib/codexAccount.js b/server/lib/codexAccount.jsindex 588c62d549..d4e52b380c 100644--- a/server/lib/codexAccount.js+++ b/server/lib/codexAccount.js@@ -154,13 +154,15 @@ export const redactCodexMessage = (value) => {// matter what an upstream error decides to quote at us.const clamped = value.length > 400 ? `${value.slice(0, 400)}…` : value;return clamped- // `key=<value>` / `key: <value>` where the key is credential-shaped AND the- // value LOOKS like a credential — long, and not plain prose. Requiring both- // is what keeps "The secret: sauce" intact while masking- // "refresh_token: eyJhbGciOi…". A short value cannot carry a usable secret.+ // `key=<value>` / `key: <value>` where the key is credential-shaped and the+ // value is long enough to BE one. The length floor is what keeps "The secret:+ // sauce" intact while masking "refresh_token: eyJhbGciOi…" — and it is the+ // only exemption, because a long all-letters value after such a key is a+ // passphrase, not a sentence. The value class runs to the next whitespace or+ // quote so a trailing "!" cannot leave half a secret behind..replace(- /\b([A-Za-z0-9_-]*(?:token|secret|password|passwd|credential|api[_-]?key|access[_-]?key|cookie|signature)[A-Za-z0-9_-]*)(\s*[=:]\s*)("?)([A-Za-z0-9._~+/=-]{12,})\3/gi,- (match, key, sep, quote, secret) => (/^[A-Za-z]+$/.test(secret) ? match : `${key}${sep}${quote}${REDACTED}${quote}`),+ /\b([A-Za-z0-9_-]*(?:token|secret|password|passwd|credential|api[_-]?key|access[_-]?key|cookie|signature)[A-Za-z0-9_-]*)(\s*[=:]\s*)("?)([^\s"']{12,})\3?/gi,+ `$1$2${REDACTED}`,)// An inline authorization credential under ANY scheme — Bearer, Basic,// Token, and whatever a future provider invents. Anchored on the headerdiff --git a/server/lib/codexTurn.js b/server/lib/codexTurn.jsindex e9152fe790..23b8f4b96b 100644--- a/server/lib/codexTurn.js+++ b/server/lib/codexTurn.js@@ -50,6 +50,7 @@ export const CODEX_TURN_RPC = Object.freeze({/** Server notifications a running turn projects into text/usage. */export const CODEX_TURN_NOTIFICATIONS = Object.freeze({+ turnStarted: 'turn/started',agentMessageDelta: 'item/agentMessage/delta',itemCompleted: 'item/completed',turnCompleted: 'turn/completed',@@ -363,6 +364,12 @@ export const applyCodexTurnEvent = (acc, method, params) => {if (!acc.turnId && typeof params.turnId === 'string' && params.turnId) acc.turnId = params.turnId;switch (method) {+ case CODEX_TURN_NOTIFICATIONS.turnStarted:+ // The earliest frame that carries the id, and the only one at all when a+ // turn produces no deltas. Without it a lost `turn/start` response leaves+ // the turn un-interruptible, so cancelling it would keep burning quota.+ if (!acc.turnId && typeof params.turn?.id === 'string') acc.turnId = params.turn.id;+ return false;case CODEX_TURN_NOTIFICATIONS.agentMessageDelta:appendText(acc, params.delta);return false;@@ -389,16 +396,12 @@ export const applyCodexTurnEvent = (acc, method, params) => {return true;case CODEX_TURN_NOTIFICATIONS.turnCompleted: {const turn = params.turn;- // Once the id is latched, a completion must name it, or it cannot finish- // this turn — it would otherwise hand the caller whatever streamed so far- // as a success. A frame naming a DIFFERENT turn is somebody else's and is- // ignored; one naming NO turn is malformed, and fails this turn now rather- // than leaving it to wait out its full deadline.+ // A completion naming a DIFFERENT turn is somebody else's. One naming no+ // turn at all is still ours: the frame already reached this accumulator by+ // thread, and PortOS's threads are ephemeral with exactly one turn — so+ // rejecting it would discard a finished answer and hang the call until its+ // deadline over a field the server merely left off the envelope.if (acc.turnId && typeof turn?.id === 'string' && turn.id !== acc.turnId) return false;- if (acc.turnId && typeof turn?.id !== 'string') {- acc.status = 'malformed';- return true;- }// A frame with no status is MALFORMED, and defaulting it to 'completed'// would hand the caller whatever text had streamed so far as a finished// answer. `finalizeCodexTurn` errors on anything that is not 'completed',diff --git a/server/lib/codexTurn.test.js b/server/lib/codexTurn.test.jsindex 409ed061bf..a1e8c0a678 100644--- a/server/lib/codexTurn.test.js+++ b/server/lib/codexTurn.test.js@@ -266,15 +266,28 @@ describe('turn projection', () => {expect(finalizeCodexTurn(acc).text).toBe('message one. message two.');});- it('fails on an anonymous completion once the turn id is latched', () => {- // An unnamed `turn/completed` cannot finish this turn — it would hand the- // caller the partial text streamed so far as a success. Terminal rather than- // ignored, so the call fails now instead of waiting out its full deadline.+ it('accepts an anonymous completion on its own thread', () => {+ // The frame already reached this accumulator BY THREAD, and PortOS's threads+ // are ephemeral with exactly one turn — so rejecting it over an id the+ // server left off the envelope would discard a finished answer and hang the+ // call until its deadline.const acc = createTurnAccumulator({ threadId: 't', turnId: 'turn-1' });- delta(acc, '{"answer":"hal');+ delta(acc, 'the answer');expect(complete(acc, { status: 'completed' })).toBe(true);- expect(finalizeCodexTurn(acc).text).toBeUndefined();+ expect(finalizeCodexTurn(acc).text).toBe('the answer');+ });++ it('latches the turn id from turn/started, the first frame that carries one', () => {+ // A turn that streams no deltas emits nothing else with an id, so without+ // this a lost `turn/start` response leaves it un-interruptible — and+ // cancelling it would keep burning subscription quota.+ const acc = createTurnAccumulator({ threadId: 't' });+ applyCodexTurnEvent(acc, CODEX_TURN_NOTIFICATIONS.turnStarted, {+ threadId: 't', turn: { id: 'turn-7', items: [], status: 'inProgress' },+ });++ expect(acc.turnId).toBe('turn-7');});it('still ignores a completion that names a different turn', () => {diff --git a/server/services/aiProvider.js b/server/services/aiProvider.jsindex d085e33894..3f120a5d38 100644--- a/server/services/aiProvider.js+++ b/server/services/aiProvider.js@@ -187,7 +187,7 @@ async function ensureLMStudioModelLoaded(provider, statusOp) {return target.id;}-async function postChatCompletion(provider, model, prompt, { temperature, max_tokens, timeout }) {+async function postChatCompletion(provider, model, prompt, { temperature, max_tokens, timeout, signal }) {const headers = { 'Content-Type': 'application/json' };if (provider.apiKey) {// Never send the API key to an arbitrary/metadata host (SSRF / key@@ -203,6 +203,13 @@ async function postChatCompletion(provider, model, prompt, { temperature, max_toconst controller = new AbortController();const timer = setTimeout(() => controller.abort(), timeout);+ // The caller's cancellation, folded into the same controller as the deadline.+ // Without it, pressing Stop leaves the request running to its full timeout —+ // most visible on the subscription's fallback leg, which is exactly where a+ // user is waiting and most likely to give up.+ const onAbort = () => controller.abort();+ if (signal?.aborted) controller.abort();+ else signal?.addEventListener('abort', onAbort, { once: true });let response;try {@@ -214,9 +221,11 @@ async function postChatCompletion(provider, model, prompt, { temperature, max_to});} catch (err) {clearTimeout(timer);+ signal?.removeEventListener('abort', onAbort);return { error: `Provider request failed: ${err.message}` };}clearTimeout(timer);+ signal?.removeEventListener('abort', onAbort);if (!response.ok) {const errorText = await response.text().catch(() => 'Unknown error');@@ -411,6 +420,12 @@ export async function callProviderAISimple(provider, model, prompt, options = {}// subscription quota for an answer nobody is waiting for. The HTTP path// manages its own AbortController from `timeout`.signal = null,+ // Internal: the status op an outer attempt already opened. `startAIOp` mints+ // a fresh id per call and the client tracks ops BY ID, so a fallback leg that+ // opened its own would leave the outer one's loading toast spinning forever+ // — nothing ever terminates it. Reusing the handle keeps the whole handoff+ // one op: "falling back to X…" → "done".+ __statusOp = null,} = options;if (provider.type !== 'api' && !isSubscriptionText(provider)) {return { error: 'This operation requires an API-based provider' };@@ -421,14 +436,14 @@ export async function callProviderAISimple(provider, model, prompt, options = {}// There is no stage name or run `source` here to classify by, so a creative// caller declares itself with `creative: true` and the stamp happens here.const body = creative ? withCreativeLatitude(prompt) : prompt;- const opts = { temperature, max_tokens, timeout: provider.timeout || DEFAULT_PROVIDER_TIMEOUT_MS };+ const opts = { temperature, max_tokens, timeout: provider.timeout || DEFAULT_PROVIDER_TIMEOUT_MS, signal };// Always emit status events (server logs + UI toasts) for AI calls. Callers// can pass `op` to give the toast a meaningful label; otherwise it's labeled// generically by provider+model so the user still sees model loads etc.const effectiveOp = op || `ai-call:${provider.id}`;const effectiveLabel = opLabel || `Calling ${provider.name || provider.id}…`;- const statusOp = startAIOp({+ const statusOp = __statusOp ?? startAIOp({op: effectiveOp,label: effectiveLabel,providerId: provider.id,@@ -472,7 +487,9 @@ export async function callProviderAISimple(provider, model, prompt, options = {}// gets the same treatment any direct call would — including the creative// stamp, which is applied per-transport rather than carried on `body`. The// shared `op` groups both attempts under one toast.- return callProviderAISimple(attempt.fallback, attempt.fallbackModel, prompt, options);+ return callProviderAISimple(attempt.fallback, attempt.fallbackModel, prompt, {+ ...options, __statusOp: statusOp,+ });}if (isOllamaProvider(provider)) {diff --git a/server/services/aiProvider.test.js b/server/services/aiProvider.test.jsindex eeea9f543f..e6dcf8dc83 100644--- a/server/services/aiProvider.test.js+++ b/server/services/aiProvider.test.js@@ -156,6 +156,7 @@ describe('callProviderAISimple completion classification', () => {// ---------------------------------------------------------------------------const { getAllProviders } = await import('./providers.js');+const { startAIOp } = await import('./aiStatusEvents.js');const { resolveTextProvider, resolveAPIProvider } = await import('./aiProvider.js');const { ERROR_CATEGORIES } = await import('../lib/aiToolkit/errorDetection.js');const codexAppServer = await import('./codexAppServer.js');@@ -232,6 +233,7 @@ describe('callProviderAISimple through the ChatGPT subscription', () => {const peekAccount = vi.spyOn(codexAppServer, 'peekCodexAccountReadiness');beforeEach(() => {+ startAIOp.mockClear();statusOp.update.mockClear();statusOp.complete.mockClear();statusOp.error.mockClear();@@ -309,6 +311,11 @@ describe('callProviderAISimple through the ChatGPT subscription', () => {// raised `max_tokens` for — and only ever on the failure path, where nobody// is watching.expect(sent).toMatchObject({ max_tokens: 1500, temperature: 0.9 });+ // ONE op across both legs. `startAIOp` mints a fresh id per call and the+ // client tracks ops by id, so a fallback that opened its own would leave the+ // first leg's loading toast spinning forever with nothing to terminate it.+ expect(startAIOp).toHaveBeenCalledTimes(1);+ expect(statusOp.complete).toHaveBeenCalledTimes(1);});it('fails closed when the provider named no fallback — never picks an API key on its own', async () => {diff --git a/server/services/codexAppServer.js b/server/services/codexAppServer.jsindex cd5f969b3a..9f97cf6251 100644--- a/server/services/codexAppServer.js+++ b/server/services/codexAppServer.js@@ -115,6 +115,8 @@ let textTransportBench = null;let textTurnCwd = null;/** Coalesces concurrent first-calls so only one scratch directory is created. */let creatingTextTurnCwd = null;+/** Set by `stopCodexAppServer`, so a handshake that lands mid-shutdown is dropped. */+let stopped = false;const codexError = (code, message, options = {}) => new ServerError(message, {status: options.status ?? 502,@@ -208,13 +210,20 @@ const handleNotification = (method, params) => {}if (method !== CODEX_NOTIFICATIONS.loginCompleted) return;readinessCache = null;+ // A sign-in that actually completed changed the ACCOUNT, whoever started it —+ // so the cached catalog belongs to whoever was signed in before, and an+ // auth/quota bench was benching a subscription that is no longer the current+ // one. Both are invalidated ahead of the correlation check below, because a+ // login another Codex client on this host started switches accounts just as+ // completely as one PortOS started.+ if (params?.success !== false) {+ modelsCache = null;+ clearCodexTextTransportBench();+ }const loginId = typeof params?.loginId === 'string' ? params.loginId : null;- // A completion for a login PortOS did not start (another Codex client on this- // host) still invalidates the cache above, but must not settle ours.+ // A completion for a login PortOS did not start still invalidates the caches+ // above, but must not settle ours.if (!pendingLogin || (loginId && loginId !== pendingLogin.loginId)) return;- // A completed sign-in is a user action that really did change the account, so- // unlike a background readiness poll it may clear an auth/quota bench.- if (params?.success !== false) clearCodexTextTransportBench();settleLogin(params?.success === false ? 'failed' : 'completed');};@@ -405,7 +414,17 @@ const connect = async () => {if (connection && !connection.closed) return connection;if (!connecting) {connecting = openConnection()- .then((target) => { connection = target; return target; })+ .then((target) => {+ // Shutdown may have run while this handshake was in flight. Publishing+ // now would leave a dead handle behind that the next call would replace+ // with a fresh child — after the graceful-shutdown hook already ran.+ if (stopped) {+ stopTarget(target, codexError(CODEX_ERROR_CODES.exited, 'PortOS shut down the Codex app-server.'));+ throw codexError(CODEX_ERROR_CODES.exited, 'PortOS is shutting down the Codex app-server.');+ }+ connection = target;+ return target;+ }).finally(() => { connecting = null; connectingTarget = null; });}return connecting;@@ -864,28 +883,38 @@ export async function runCodexTextTurn({* orphaned Codex process behind. Safe to call when nothing is running.*/export async function stopCodexAppServer() {+ // Set FIRST and never cleared: `connect()` checks it before publishing a+ // handshake that finished mid-shutdown, so a late resolve cannot leave a live+ // `connection` behind for the next call to reuse — or, worse, hand it a closed+ // one and have it spawn a replacement child after the shutdown hook ran.+ stopped = true;settleLogin(null);readinessCache = null;modelsCache = null;- const scratch = textTurnCwd;++ // The child goes down BEFORE any await. `teardown` decides whether to fail+ // live turns by comparing `connection` to the dying target, so `connection`+ // must still point at it here; and an await first would let a concurrent+ // connect publish itself into the gap.+ const target = connection || connectingTarget;+ if (target && !target.closed) {+ stopTarget(target, codexError(CODEX_ERROR_CODES.exited, 'PortOS is shutting down the Codex app-server.'));+ console.log('🔌 Codex app-server stopped');+ }+ connection = null;++ // Drain a scratch directory that is still being created, or its `mkdtemp`+ // resolves after shutdown and leaves the directory behind for good.+ const pending = creatingTextTurnCwd+ ? await creatingTextTurnCwd.catch(() => null)+ : null;+ const scratch = textTurnCwd || pending;textTurnCwd = null;creatingTextTurnCwd = null;if (scratch) {await rm(scratch, { recursive: true, force: true }).catch((err) => console.error(`❌ Failed to remove the Codex text scratch directory: ${err.message}`));}- const target = connection || connectingTarget;- if (!target || target.closed) {- connection = null;- return;- }- // `teardown` decides whether to fail live turns by comparing `connection` to- // the dying target — so `connection` must still point at it here. Nulling- // first left every in-flight turn waiting on a notification that could never- // arrive, until its own 5-minute deadline.- stopTarget(target, codexError(CODEX_ERROR_CODES.exited, 'PortOS is shutting down the Codex app-server.'));- connection = null;- console.log('🔌 Codex app-server stopped');}/** Test-only: drop every module-level handle so a suite starts clean. */@@ -901,4 +930,5 @@ export function __resetCodexAppServer() {textTransportBench = null;textTurnCwd = null;creatingTextTurnCwd = null;+ stopped = false;}diff --git a/server/services/codexAppServer.turn.test.js b/server/services/codexAppServer.turn.test.jsindex c14fdf29e3..40ff01d0c7 100644--- a/server/services/codexAppServer.turn.test.js+++ b/server/services/codexAppServer.turn.test.js@@ -363,9 +363,13 @@ describe('shutdown while a turn is live', () => {await awaitRequest(child, 'turn/start', { turn: { id: 'turn-1', items: [], status: 'inProgress' } });expect(spawn).toHaveBeenCalledTimes(1);+ // The expectation is attached BEFORE the shutdown, the way a real caller is+ // already awaiting its turn: shutdown now fails the turn synchronously, and+ // an unawaited rejection surfacing between here and the assertion would be+ // reported as unhandled.+ const rejected = expect(promise).rejects.toMatchObject({ code: CODEX_ERROR_CODES.exited });await stopCodexAppServer();-- await expect(promise).rejects.toMatchObject({ code: CODEX_ERROR_CODES.exited });+ await rejected;expect(spawn).toHaveBeenCalledTimes(1);});});@@ -388,3 +392,36 @@ describe('a catalog that will not stop paginating', () => {expect(peekCodexModels()).toBeNull();});});++describe('shutdown racing a connect', () => {+ it('drops a handshake that lands mid-shutdown instead of leaving a dead handle', async () => {+ // The published handle would be a CLOSED one, and the next call would see+ // that and spawn a replacement — a fresh app-server started after the+ // graceful-shutdown hook already ran.+ const connecting = getCodexAccountReadiness({ fresh: true });+ let initialize = null;+ await vi.waitFor(() => { initialize = child.take('initialize'); expect(initialize).toBeTruthy(); });++ const stopping = stopCodexAppServer();+ child.reply(initialize, {});+ await stopping;++ await expect(connecting).resolves.toMatchObject({ status: 'unknown' });+ expect(spawn).toHaveBeenCalledTimes(1);+ });+});++describe('a new sign-in is a different account', () => {+ it('drops the cached model catalog when a login completes', async () => {+ // Otherwise account B is offered account A's models for up to the 10m TTL.+ const listing = listCodexModels();+ await handshake();+ await awaitRequest(child, 'model/list', { data: [{ id: 'model-alpha', supportedReasoningEfforts: [] }] });+ await listing;+ expect(peekCodexModels()).not.toBeNull();++ child.notify('account/login/completed', { loginId: 'other-client', success: true });++ expect(peekCodexModels()).toBeNull();+ });+});