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: release v2.67.0 review leftovers — 8 minor findings (#7398)
[._.]/ Adam Eivy4f74dcaeeacc
diff --git a/client/src/components/apps/SlashDoRunDrawer.jsx b/client/src/components/apps/SlashDoRunDrawer.jsxindex 4c459e1951..14651737fd 100644--- a/client/src/components/apps/SlashDoRunDrawer.jsx+++ b/client/src/components/apps/SlashDoRunDrawer.jsx@@ -23,6 +23,9 @@ import * as api from '../../services/api';* bare button used to. Reviewer fields are sent ONLY when the user edits them, so* an untouched drawer still resolves the app's configured claim-work reviewers* server-side rather than pinning whatever this form happened to display.+ * `prCompletion` is the exception: it is always sent for `/do:next` (seeded+ * from the claim-work default when untouched), because the prompt's completion+ * policy needs an explicit value.** Mount only while open (the parent conditionally renders it): the provider fetch* runs on mount unless the overview supplies its shared agent picker. Taskdiff --git a/client/src/components/cos/tabs/schedule/PromptEditor.jsx b/client/src/components/cos/tabs/schedule/PromptEditor.jsxindex 4eb210629f..d086ca7c9c 100644--- a/client/src/components/cos/tabs/schedule/PromptEditor.jsx+++ b/client/src/components/cos/tabs/schedule/PromptEditor.jsx@@ -2,6 +2,7 @@ import { useState, useEffect } from 'react';import {Shield, BadgeCheck, Hammer, Layers, GitBranch, FileText, Sparkles, Bot,Cpu, Workflow, Boxes, ScanSearch, ListChecks, PenLine, Clapperboard, Rocket,+ Shapes,} from 'lucide-react';import { pipelineStages } from './scheduleConstants';import TabPills from '../../../ui/TabPills';@@ -11,6 +12,12 @@ const STAGE_ICONS = [Cpu, Workflow, Boxes, ScanSearch, ListChecks, PenLine, Clapperboard, Rocket,];+// Stages are data-driven and unbounded, so the fixed icon table cannot cover+// them all. A stage past the end of STAGE_ICONS must still render a glyph:+// one iconless tab drops the whole `mobileCompact` bar to the `<select>`+// fallback (see TabPills' `iconRow` gate).+const FALLBACK_STAGE_ICON = Shapes;+export default function PromptEditor({ config, promptValue, setPromptValue, editingPrompt, setEditingPrompt, handleSavePrompt, updating, activeApps }) {const stages = pipelineStages(config);const stagePrompts = config.stagePrompts;@@ -108,7 +115,7 @@ export default function PromptEditor({ config, promptValue, setPromptValue, edittabs={stages.map((stage, i) => ({id: String(i),label: stage.name,- icon: STAGE_ICONS[i],+ icon: STAGE_ICONS[i] ?? FALLBACK_STAGE_ICON,trailing: stage.readOnly? <span className="text-[10px] text-gray-500">(read-only)</span>: undefined,diff --git a/client/src/components/cos/tabs/schedule/PromptEditor.test.jsx b/client/src/components/cos/tabs/schedule/PromptEditor.test.jsxindex 559a4d9d96..47db642886 100644--- a/client/src/components/cos/tabs/schedule/PromptEditor.test.jsx+++ b/client/src/components/cos/tabs/schedule/PromptEditor.test.jsx@@ -30,6 +30,37 @@ describe('PromptEditor', () => {});});+describe('PromptEditor — pipeline stages past the icon table', () => {+ it('gives every stage an icon so the mobileCompact bar stays an icon row', () => {+ // Stages are data-driven and unbounded against a 16-entry STAGE_ICONS+ // table. One iconless tab drops the whole bar to the <select> fallback+ // (TabPills' `iconRow` gate), so the 17th stage must still render a glyph.+ const stages = Array.from({ length: 17 }, (_, i) => ({ name: `Stage ${i + 1}` }));+ const { container } = render(+ <PromptEditor+ config={{+ taskMetadata: { pipeline: { stages } },+ stagePrompts: stages.map((stage) => `Prompt for ${stage.name}`),+ }}+ promptValue=""+ setPromptValue={() => {}}+ editingPrompt={false}+ setEditingPrompt={() => {}}+ handleSavePrompt={() => {}}+ updating={false}+ activeApps={[]}+ />+ );++ expect(container.querySelector('select')).toBeNull();+ const tabs = screen.getAllByRole('tab');+ expect(tabs).toHaveLength(17);+ for (const tab of tabs) {+ expect(tab.querySelector('svg')).not.toBeNull();+ }+ });+});+describe('PromptEditor — programmatic tasks', () => {it('offers no prompt at all for work PortOS performs itself', () => {// Distinct from 'runtime-generated': there is no agent and no prompt, sodiff --git a/docs/MANAGED_APP_FORGE_ACCOUNTS.md b/docs/MANAGED_APP_FORGE_ACCOUNTS.mdindex 2364343219..3757d133b7 100644--- a/docs/MANAGED_APP_FORGE_ACCOUNTS.md+++ b/docs/MANAGED_APP_FORGE_ACCOUNTS.md@@ -86,8 +86,12 @@ Set the field when it is not: an organization repo, a bot account, or any repowhose owner login differs from the account you push with.A pinned account is never second-guessed. If `gh` has no token for it, the run-gets no forge credential rather than silently falling back to a different-account's token.+gets no pinned forge credential — `resolveForgeTokenEnv` overlays nothing, and+`buildSafeEnv` strips the ambient `GH_TOKEN` from agent shells — rather than+silently falling back to a different account's token. (PortOS's own+`resolveForgeForRepo` probes still inherit the ambient environment when no+token is minted; the no-fallback guarantee covers the credential handed to the+run, not every ambient lookup PortOS performs itself.)## Relateddiff --git a/server/lib/gitForge.js b/server/lib/gitForge.jsindex 16e5029f5d..da3d97dd6f 100644--- a/server/lib/gitForge.js+++ b/server/lib/gitForge.js@@ -28,8 +28,12 @@ export function parseGitRemote(url) {const ssh = url.match(/^git@([^:]+):([^/]+)\/.+?(?:\.git)?$/);if (ssh) return { host: resolveSshHostAlias(ssh[1]), owner: ssh[2] };// HTTPS: https://HOST/OWNER/REPO[.git]+ // No alias resolution here: ssh config applies to SSH connections only, so+ // an `https://` remote colliding with an ssh alias must keep its literal+ // host — resolving it would point downstream `gh --repo` + token overlay at+ // the wrong API host.const https = url.match(/^https?:\/\/([^/]+)\/([^/]+)\/.+?(?:\.git)?$/);- if (https) return { host: resolveSshHostAlias(https[1]), owner: https[2] };+ if (https) return { host: https[1], owner: https[2] };return null;}diff --git a/server/lib/gitRemote.js b/server/lib/gitRemote.jsindex 7c8c461025..8008651c82 100644--- a/server/lib/gitRemote.js+++ b/server/lib/gitRemote.js@@ -56,6 +56,11 @@ export function parseGitRemoteUrl(url) {// Port first, then alias: an alias is written bare in ssh config, so// `github-acme:22` must have its port removed before the lookup.const normalizeHost = (h) => resolveSshHostAlias(stripPort(h));+ // URL-scheme hosts never consult ssh config — only the SSH branches+ // (scp-style and `ssh://`) resolve aliases. An `https://` remote colliding+ // with an ssh alias must keep its literal host, or downstream `gh --repo` ++ // token overlay target the wrong API host.+ const normalizeUrlHost = (scheme, h) => (scheme === 'ssh' ? normalizeHost(h) : stripPort(h));// SCP-style SSH: git@host:[port/]owner/repo(.git). repo segment cannot// contain '/'. The optional `(?:\d+\/)?` matches the GitHub-specific variant@@ -68,9 +73,9 @@ export function parseGitRemoteUrl(url) {// URL-style: scheme://[user@]host(:port)/owner/repo(.git) — repo segment// cannot contain '/'.- const urlMatch = trimmed.match(/^[a-zA-Z]+:\/\/(?:[^@/]+@)?([^/]+)\/([^/]+)\/([^/]+)$/);+ const urlMatch = trimmed.match(/^([a-zA-Z]+):\/\/(?:[^@/]+@)?([^/]+)\/([^/]+)\/([^/]+)$/);if (urlMatch) {- return { host: normalizeHost(urlMatch[1]), owner: urlMatch[2], repo: stripGit(urlMatch[3]) };+ return { host: normalizeUrlHost(urlMatch[1].toLowerCase(), urlMatch[2]), owner: urlMatch[3], repo: stripGit(urlMatch[4]) };}return null;diff --git a/server/lib/sshHostAlias.test.js b/server/lib/sshHostAlias.test.jsindex a3de208e8d..4e4135af62 100644--- a/server/lib/sshHostAlias.test.js+++ b/server/lib/sshHostAlias.test.js@@ -159,6 +159,19 @@ describe('remote-host parsers under a multi-account ssh alias', () => {expect(parseGitRemoteUrl('ssh://git@github-acme:22/acme/widget.git').host).toBe('github.com');});+ it('never resolves an ssh alias on a URL-scheme host ssh config cannot apply to', () => {+ // ssh config is consulted for SSH connections only. An `https://` remote+ // colliding with an ssh alias must keep its literal host at every parser,+ // or `gh --repo` + token overlay target the wrong API host — while the+ // `ssh://` form of the same alias still resolves.+ const https = 'https://github-acme/acme/widget.git';+ expect(parseGitRemote(https)).toEqual({ host: 'github-acme', owner: 'acme' });+ expect(parseGitRemoteUrl(https)).toEqual({ host: 'github-acme', owner: 'acme', repo: 'widget' });+ expect(hostFromOriginUrl(https)).toBe('github-acme');+ expect(parseGitRemoteUrl('ssh://git@github-acme/acme/widget.git').host).toBe('github.com');+ expect(hostFromOriginUrl('ssh://git@github-acme/acme/widget.git')).toBe('github.com');+ });+it('leaves an alias the ssh config does not declare alone', () => {expect(parseGitRemote('git@github-other:acme/widget.git')).toEqual({ host: 'github-other', owner: 'acme' });});diff --git a/server/lib/workTracker.js b/server/lib/workTracker.jsindex 2a8cfd9fea..872bab5b2c 100644--- a/server/lib/workTracker.js+++ b/server/lib/workTracker.js@@ -492,8 +492,12 @@ export function hostFromOriginUrl(url) {const trimmed = url.trim();if (!trimmed) return null;// scheme://[userinfo@]host[:port]/... — host is the run up to the next / : @- const scheme = trimmed.match(/^[a-zA-Z][a-zA-Z0-9+.-]*:\/\/(?:[^/@]+@)?([^/:]+)/);- if (scheme) return resolveSshHostAlias(scheme[1]) || null;+ // ssh config applies to SSH connections only: an `https://` remote whose host+ // collides with an ssh alias keeps its literal host, so only `ssh://` URLs+ // resolve aliases here. Otherwise downstream `gh --repo` + token overlay+ // target the wrong API host.+ const scheme = trimmed.match(/^([a-zA-Z][a-zA-Z0-9+.-]*):\/\/(?:[^/@]+@)?([^/:]+)/);+ if (scheme) return (scheme[1].toLowerCase() === 'ssh' ? resolveSshHostAlias(scheme[2]) : scheme[2]) || null;// scp-style [user@]host:pathconst scp = trimmed.match(/^(?:[^@/]+@)?([^/:]+):/);if (scp) return resolveSshHostAlias(scp[1]) || null;diff --git a/server/services/forgeAuth.js b/server/services/forgeAuth.jsindex 58577b4532..b42ece6ebe 100644--- a/server/services/forgeAuth.js+++ b/server/services/forgeAuth.js@@ -5,6 +5,7 @@*/// Aliased: `spawnCli`'s promise executor already binds `resolve` in its own scope.import { dirname, isAbsolute, resolve as resolvePath } from 'path';+import { realpath } from 'fs/promises';import { spawn } from '../lib/childProcess.js';import { execGitSafe } from '../lib/execGit.js';import { parseGitRemote, detectForgeCli, pickGhAccountForOwner } from '../lib/gitForge.js';@@ -101,8 +102,18 @@ async function resolveConfiguredAccount(dir) {if (!pinned.length) return null;const root = await resolveMainRepoRoot(dir).catch(() => null);if (!root) return null;- const target = resolvePath(root);- return pinned.find(app => resolvePath(app.repoPath) === target)?.forgeAccount || null;+ // Both sides through `realpath`: comparing `resolvePath()` strings alone+ // never matches a symlinked checkout against the registered repoPath, so the+ // pin is silently missed and auth falls back to the wrong account. Best+ // effort — an unreadable path falls back to the lexical resolution rather+ // than failing the lookup.+ const canonical = (p) => realpath(p).catch(() => resolvePath(p));+ const target = await canonical(root);+ for (const app of pinned) {+ if (typeof app?.repoPath !== 'string') continue;+ if ((await canonical(app.repoPath)) === target) return app.forgeAccount || null;+ }+ return null;}/**diff --git a/server/services/forgeAuth.test.js b/server/services/forgeAuth.test.jsindex a1034c9309..60483e4d1a 100644--- a/server/services/forgeAuth.test.js+++ b/server/services/forgeAuth.test.js@@ -1,5 +1,8 @@import { EventEmitter } from 'node:events';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { mkdirSync, mkdtempSync, rmSync, symlinkSync } from 'fs';+import { tmpdir } from 'os';+import { join } from 'path';vi.mock('../lib/childProcess.js', () => ({ spawn: vi.fn() }));// The managed-app registry read is the only thing forge auth needs from the app@@ -216,6 +219,26 @@ describe('per-app forge account pinning', () => {expect(env.GH_TOKEN).toBe('acme-bot-token');});+ it('matches a pin registered against the real path when the checkout is reached through a symlink', async () => {+ // A lexical compare never matches the symlinked side, so the pin was+ // silently missed and auth fell back to the wrong account.+ const home = mkdtempSync(join(tmpdir(), 'portos-forge-'));+ const real = join(home, 'repo');+ const link = join(home, 'link');+ mkdirSync(real);+ symlinkSync(real, link);+ try {+ listForgePinnedApps.mockResolvedValue([{ repoPath: real, forgeAccount: 'acme-bot' }]);+ respond({ stdout: '[email protected]:acme/widget.git\n' });+ respond({ stdout: `${link}/.git\n` });+ respond({ stdout: 'acme-bot-token\n' });+ respond({ stdout: '4242\tacme-bot\tAcme Bot\n' });+ await expect(resolveForgeTokenEnv(link)).resolves.toMatchObject({ GH_TOKEN: 'acme-bot-token' });+ } finally {+ rmSync(home, { recursive: true, force: true });+ }+ });+it('leaves an unpinned app on the inferred account with ambient commit identity', async () => {githubAccount();await expect(resolveForgeTokenEnv('/example/repo')).resolves.toEqual({ GH_TOKEN: 'test-owner-token' });diff --git a/server/services/modelPinAudit.js b/server/services/modelPinAudit.jsindex bc4233410c..5bcc539b0a 100644--- a/server/services/modelPinAudit.js+++ b/server/services/modelPinAudit.js@@ -191,7 +191,9 @@ function collectTaskSchedulePins({ schedule }) {*/async function collectAppOverridePins({ schedule }) {const { getActiveApps } = await loadAppsModule();- const apps = await getActiveApps().catch(() => []);+ // No local catch: an unreadable apps store must reach the collector-level+ // catch (counted toward `incomplete`), not silently read as "no overrides".+ const apps = await getActiveApps();return (apps || []).flatMap((app) =>Object.entries(app?.taskTypeOverrides || {}).flatMap(([taskType, override]) => pinIf({id: `app:${app.id}:${taskType}`,@@ -451,30 +453,36 @@ const PIN_SOURCES = Object.freeze([* A collector that throws must not take the whole audit down with it: one* unreadable store is a missing section, not a failed page.*- * @returns {Promise<Array<object>>}+ * Each failure is counted, so callers can tell "evaluated and healthy" apart+ * from "unevaluated after a store-read error" — the notifier must not retract+ * announced cards on the latter, or the next audit re-notifies.+ *+ * @returns {Promise<{pins: Array<object>, errors: number}>}*/async function collectModelPins() {const { loadSchedule } = await loadTaskScheduleModule();const { listProviders } = await loadProvidersModule();+ let errors = 0;const [settings, schedule, providers] = await Promise.all([- getSettings().catch(() => ({})),- loadSchedule().catch(() => null),+ getSettings().catch(() => { errors += 1; return {}; }),+ loadSchedule().catch(() => { errors += 1; return null; }),// The reviewer collector classifies provider RECORDS, so the catalog is one// of this function's own inputs — read here, beside the others, rather than// threaded in from both callers. `loadProviders` fronts a short TTL cache// that coalesces in-flight reads, so the reconciliation's own read of the// same catalog costs nothing extra.- listProviders().catch(() => []),+ listProviders().catch(() => { errors += 1; return []; }),]);const context = { settings, schedule, providers };const collected = await Promise.all(PIN_SOURCES.map(async ({ kind, collect }) => {const pins = await Promise.resolve(collect(context)).catch((error) => {console.error(`❌ Model pin collector ${kind} failed: ${error.message}`);+ errors += 1;return [];});return pins.map((pin) => ({ ...pin, kind }));}));- return collected.flat();+ return { pins: collected.flat(), errors };}/**@@ -485,12 +493,17 @@ async function collectModelPins() {* catalog of each record fronting its binary and the panel can union them. A* 200-model Ollama catalog is still not shipped to a page with no Ollama pin.*- * @returns {Promise<{pins: Array<object>, providers: Record<string, object>}>}+ * `incomplete` is true when any backing store or collector failed: the pin set+ * is then unevaluated, not healthy, and callers that retract on empty (the+ * retired-pin notifier) must skip the pass rather than withdraw announcements+ * the next audit would re-raise.+ *+ * @returns {Promise<{pins: Array<object>, providers: Record<string, object>, incomplete: boolean}>}*/export async function auditModelPins() {const { listProviders } = await loadProvidersModule();// The pin stores and the provider catalog are independent reads.- const [providerList, pins] = await Promise.all([listProviders(), collectModelPins()]);+ const [providerList, { pins, errors }] = await Promise.all([listProviders(), collectModelPins()]);const byId = Object.fromEntries(providerList.map((provider) => [provider.id, provider]));const stale = reconcileModelPins(pins, byId);const providers = Object.fromEntries(@@ -500,7 +513,7 @@ export async function auditModelPins() {available: catalogOfferings(byId[id]),}]),);- return { pins: stale, providers };+ return { pins: stale, providers, incomplete: errors > 0 };}/**@@ -521,7 +534,7 @@ export async function auditModelPins() {* @returns {Promise<{cleared: boolean, id: string}>}*/export async function clearModelPin(pinId) {- const pins = await collectModelPins();+ const { pins } = await collectModelPins();const pin = pins.find((candidate) => candidate.id === pinId);if (pin) await PIN_SOURCES.find((source) => source.kind === pin.kind).clear(pin);const { removeByMetadata } = await loadNotificationsModule();diff --git a/server/services/modelPinAudit.test.js b/server/services/modelPinAudit.test.jsindex 079ac44c5a..978026a3f6 100644--- a/server/services/modelPinAudit.test.js+++ b/server/services/modelPinAudit.test.js@@ -99,7 +99,21 @@ describe('auditModelPins', () => {getSettings.mockResolvedValue(settingsWith({imageGen: { agy: { model: 'gemini-3.6-flash-low' }, codex: { model: 'gpt-5-codex' } },}));- await expect(auditModelPins()).resolves.toEqual({ pins: [], providers: {} });+ await expect(auditModelPins()).resolves.toEqual({ pins: [], providers: {}, incomplete: false });+ });++ it('marks the audit incomplete rather than healthy when a store read fails', async () => {+ // An unevaluated pin set must not read as "nothing stale": the notifier+ // retracts on empty, so a transient read error would withdraw announced+ // cards and re-notify on the next audit.+ loadSchedule.mockRejectedValueOnce(new Error('schedule unreadable'));+ await expect(auditModelPins()).resolves.toEqual({ pins: [], providers: {}, incomplete: true });+ });++ it('marks the audit incomplete when a collector throws', async () => {+ getActiveApps.mockRejectedValueOnce(new Error('apps store unreadable'));+ const result = await auditModelPins();+ expect(result.incomplete).toBe(true);});it('ships a catalog only for the providers a stale pin actually names', async () => {diff --git a/server/services/modelPinAuditNotifier.js b/server/services/modelPinAuditNotifier.jsindex adb4947841..6abed59850 100644--- a/server/services/modelPinAuditNotifier.js+++ b/server/services/modelPinAuditNotifier.js@@ -169,7 +169,14 @@ async function reconcile(stalePins) {async function reportOnce() {const { auditModelPins } = await loadAuditModule();- const { pins, providers } = await auditModelPins();+ const { pins, providers, incomplete } = await auditModelPins();+ // A transient store-read error leaves collectors unevaluated, so an empty pin+ // set is "unknown", not "healthy": reconciling would retract announced cards+ // and the next audit would re-notify. Skip the pass; the next refresh retries.+ if (incomplete) {+ console.error('❌ Model pin audit incomplete — a pin store was unreadable; keeping announced cards');+ return;+ }// BEFORE the early return below and before announcing: an install whose last// stale pin was just repointed to a live model has an empty pin set and a// card that must still come down.diff --git a/server/services/modelPinAuditNotifier.test.js b/server/services/modelPinAuditNotifier.test.jsindex 5644ba11fd..d7ee5be02d 100644--- a/server/services/modelPinAuditNotifier.test.js+++ b/server/services/modelPinAuditNotifier.test.js@@ -179,6 +179,25 @@ describe('reportRetiredModelPins', () => {expect(removeNotification).toHaveBeenCalledTimes(1);});+ it('keeps announced cards when the audit is incomplete after a store-read error', async () => {+ const cards = backNotificationsWithAStore();+ auditModelPins.mockResolvedValue(audited(pin('settings:imageGen.agy.model')));+ await reportRetiredModelPins();+ expect(cards).toHaveLength(1);+ addNotification.mockClear();++ // A transient store-read error leaves the pin set unevaluated, so the empty+ // set is "unknown", not "healthy": reconciling it would retract the card+ // and the next audit would re-notify.+ auditModelPins.mockResolvedValue({ pins: [], providers: {}, incomplete: true });+ await reportRetiredModelPins();++ expect(cards).toHaveLength(1);+ expect(removeNotification).not.toHaveBeenCalled();+ expect(addNotification).not.toHaveBeenCalled();+ expect(errored.mock.calls[0][0]).toContain('incomplete');+ });+it('announces the new model even when retracting the old card FAILS', async () => {// The two guards are deliberately independent: `reconcile` normally takes// the superseded card down first, but it is non-fatal, so the dedupe keydiff --git a/server/services/promptSections/completion.js b/server/services/promptSections/completion.jsindex 587d54aae3..7193e360a2 100644--- a/server/services/promptSections/completion.js+++ b/server/services/promptSections/completion.js@@ -449,10 +449,13 @@ export function claimReviewersCsv(task, codeReviewDefaults, defaultReviewers) {* site, instead of three prose appends in `cosTaskGenerator.js` that a new claim* generator could forget.*- * @param {string} [reviewersCsv] - the emitted `--review-with` token list to pin;- * empty suppresses the block (`buildReviewerPinNote` returns '').- * @param {boolean} [leavePrOpen] - keep reviews and CI, but hand off before merge.- */+ * @param {string} [reviewersCsv] - the emitted `--review-with` token list to pin;+ * empty suppresses the block (`buildReviewerPinNote` returns '').+ * @param {boolean} [leavePrOpen] - keep reviews and CI, but hand off before merge.+ * @param {string|null} [prCompletion] - the claim's PR completion policy+ * (`PR_COMPLETIONS`): `MERGE_ON_GREEN` suppresses the reviewer pin and emits+ * the merge-on-green handoff instead; any other value keeps the pin.+ */export function buildClaimFlowCompletionSection({ isTui = false, sentinelPath = null, reviewersCsv = '', leavePrOpen = false, prCompletion = null } = {}) {const isMergeOnGreen = prCompletion === PR_COMPLETIONS.MERGE_ON_GREEN;const pin = isMergeOnGreen ? '' : buildReviewerPinNote(reviewersCsv);diff --git a/server/services/providerUsage.js b/server/services/providerUsage.jsindex 6617f0b85e..ae2e9b7439 100644--- a/server/services/providerUsage.js+++ b/server/services/providerUsage.js@@ -583,6 +583,12 @@ export function parseGrokUsage(text, { now = Date.now(), timezone } = {}) {const byWindow = new Map();// Grok 1.0 names the subscription in the window header:// `Weekly limit (SuperGrok)`. Last named frame wins on a repaint.+ // Anything else in those parens — a note, a timestamp, a repaint fragment —+ // is not a plan name, so only a single identifier-like token is accepted+ // (starts alphanumeric, letters/digits plus a few separators, carries a+ // letter) rather than echoing arbitrary panel text onto the Usage card. A+ // missing plan reads as unknown; a wrong one reads as fact.+ const PLAN_NAME = /^(?=.*[A-Za-z])[A-Za-z0-9][A-Za-z0-9.,_+-]{0,59}$/;let plan = null;const matches = [...str.matchAll(/(weekly|monthly)\s+limit(?:\s*\(([^)]+)\))?:?/gi)];@@ -590,7 +596,7 @@ export function parseGrokUsage(text, { now = Date.now(), timezone } = {}) {const m = matches[idx];const window = m[1].toLowerCase();const named = m[2]?.trim();- if (named) plan = named.slice(0, 60);+ if (named && PLAN_NAME.test(named)) plan = named;if (!GROK_WINDOWS[window]) continue;const startPos = m.index + m[0].length;diff --git a/server/services/providerUsage.test.js b/server/services/providerUsage.test.jsindex eca4be8bbd..6fff6093ca 100644--- a/server/services/providerUsage.test.js+++ b/server/services/providerUsage.test.js@@ -574,6 +574,14 @@ describe('parseGrokUsage', () => {it('leaves plan null when the window header names no tier', () => {expect(parseGrokUsage('Weekly limit: 42%', opts).plan).toBeNull();});++ it('ignores a parenthetical that is not shaped like a plan name', () => {+ // Any parenthetical after the window header used to become the plan, so a+ // note or timestamp in the panel ended up on the Usage card as the plan.+ expect(parseGrokUsage('Weekly limit (as of Tuesday): 42%', opts).plan).toBeNull();+ expect(parseGrokUsage('Weekly limit (8% used): 42%', opts).plan).toBeNull();+ expect(parseGrokUsage('Weekly limit (SuperGrok): 42%', opts).plan).toBe('SuperGrok');+ });});describe('TUI usage fetchers (via getProviderQuotas)', () => {