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
route the card's model pins through ProviderModelSelector and one disabledReason
[._.]/ Adam Eivy4821e79e32e3
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex d72dd26ec5..5e91ecd6c6 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -6,7 +6,7 @@- **Quota burn's dispatch cap is now opt-in — `-1` (unlimited) is the default, so a plan stops when the *quota* says so rather than when a tally runs out.** `maxDispatchesPerWindow` counted how many burns one target window could spend, and at its old default of 5 it was routinely the first gate to close: a weekly window with days left and headroom above the reserve would sit idle at "dispatch cap reached (5/5)" — the exact "allowance expires unused" outcome the feature exists to prevent. It read as a safety property, but the gates that actually bound spend all measure live numbers: the reset horizon (`resetWithinHours`), the reserve (`reservePercent`, checked against the *tightest* window on the card), and the provider's own refusal, which blocks the family outright when the short window empties underneath a weekly plan. A count stacked on top of those adds no protection they don't already give. A hard ceiling is still available — set 1–50 on the family card — and the window is charged either way, so the card still shows how many burns it has spent (with no denominator when uncapped). `0` is deliberately not accepted: "never burn" is what switching the family off means, and the client's number field collapses anything below 1 to the sentinel so stepping the spinner down can't 400. Migration 226 lifts an existing plan that still carries the old default of 5 — a changed default reaches nobody otherwise, since the normalizer has written that 5 into every install's `quota-burn.json` — while any other stored value is a number the user chose and is left alone.-- **Retargeting a scheduled task at a different model no longer costs a trip through the config drawer.** Each card on CoS → Schedule now carries the provider, model and effort pins inline, right above its Run button — so the common loop of "point this task at a stronger model and run it on one app" is three clicks on the card instead of opening the drawer, scrolling to the provider block, changing it, and closing again. The pins write immediately, exactly as they do in the drawer (picking a provider clears the model and effort with it, since a model from the previous provider wouldn't resolve), and a failed write rolls the select back to what is actually stored rather than leaving the card claiming a setting the server never took. Run stays disabled while a pin is still being saved: the run reads the server-side config, not the inputs on screen, so triggering mid-write would quietly run the *previous* model — the failure this repo's "in-flight saves must gate dependent actions" rule exists to prevent, and one a tooltip would not have stopped. Leaving the provider on Default no longer means the model and effort selects have nothing to offer: Default now names the provider it currently resolves to and lists that provider's catalog, so "same provider, higher effort" doesn't require pinning the provider first — the same fallback the pipeline's LLM pickers already use. Effort only appears for providers that actually have a ladder, and it is narrowed by the picked model, so an Antigravity model with no tiers doesn't offer one. A pipeline task, whose provider and model are resolved per stage, gets a link to the stage config instead of a card-level pin that its runs would ignore. Card and drawer now share one implementation of the select/write/rollback trio (`useTaskModelPins`), so the two surfaces can't drift.+- **Retargeting a scheduled task at a different model no longer costs a trip through the config drawer.** Each card on CoS → Schedule now carries the provider, model and effort pins inline, right above its Run button — so the common loop of "point this task at a stronger model and run it on one app" is three clicks on the card instead of opening the drawer, scrolling to the provider block, changing it, and closing again. The pins write immediately, exactly as they do in the drawer (picking a provider clears the model and effort with it, since a model from the previous provider wouldn't resolve), and a failed write rolls the select back to what is actually stored rather than leaving the card claiming a setting the server never took. Run stays disabled while a pin is still being saved: the run reads the server-side config, not the inputs on screen, so triggering mid-write would quietly run the *previous* model — the failure this repo's "in-flight saves must gate dependent actions" rule exists to prevent, and one a tooltip would not have stopped. Leaving the provider on Default no longer means the model and effort selects have nothing to offer: Default now names the provider it currently resolves to and lists that provider's catalog, so "same provider, higher effort" doesn't require pinning the provider first — the same fallback the pipeline's LLM pickers already use. Effort only appears for providers that actually have a ladder, and it is narrowed by the picked model, so an Antigravity model with no tiers doesn't offer one. A pipeline task, whose provider and model are resolved per stage, gets a link to the stage config instead of a card-level pin that its runs would ignore. The card's three selects are the shared `ProviderModelSelector` rather than a fourth hand-rolled copy, so they inherit what that component exists to guarantee: a disabled provider isn't offered (unless the task is already pinned to it), and a task pinned to a local model that can't call tools says so — a scheduled task IS an agent run, and a non-tool-calling model narrates instead of working. Card and drawer share one implementation of the select/write/rollback trio (`useTaskModelPins`), so the two surfaces can't drift; the drawer's own Run button picked up the same in-flight gate on the way past, which it had been missing. And the Run button's disable is now one `disabledReason` string instead of a boolean per reason — the shape that let the first gate reach only one of the two call sites.- **The `cosAgents.js` barrel is gone, so an agent function no longer arrives from a specifier that says nothing about which layer it lives in.** The #2530 decomposition split a ~1090-line module into four focused siblings — `cosAgentIndex.js` (date-bucket index + on-disk archive layout), `cosAgentLifecycle.js` (register / update / complete / output / terminate), `cosAgentFeedback.js` (capture + classifier), `cosAgentArchive.js` (state-eviction sweeps) — then put an `export *` wall back in front of all four so no import path had to change. Three years of imports later, `updateAgent` and `getAgentsByDate` came from the same specifier despite sitting in different layers, and the wall is what made `cos.js` a *two*-hop forwarder of a lifecycle transition, which is the shape #3450's guard exists to delete. All ~20 production importers and ~14 `vi.mock` targets now name the module that declares what they asked for — several of which turn out to want only the index (`cosReports.js`, the peer cos-history merge) or only the lifecycle layer (the runner sync, the TUI output spooler, the completion cleanup), so the graph gets narrower as well as flatter. The four leaf modules are unchanged; the two test files that only ever exercised one of them are renamed to sit beside it (`cosAgentLifecycle.test.js`, `cosAgentIndex.merge.test.js`). The forwarder guard in `agentImportCycles.test.js` — which walks re-export edges rather than naming barrels, so a new one is covered the day it is written — now asserts `cos.js` is the *only* module forwarding a transition, and was bypass-probed both ways: planting a fresh `export *` barrel turns it red, and so does routing a production import of `completeAgent` back through `cos.js`. Its two module-loading assertions also take an explicit timeout: they transform `cos.js`'s whole service graph, which lands at 5–10s and straddles Vitest's 10s default, so the guard was one busy machine away from failing for a reason that had nothing to do with the invariant (#3450).@@ -35,7 +35,7 @@## Fixed- **Quota-burn tasks were queued and then never picked up, so the window they were meant to spend expired unspent anyway.** Three separate faults, each of which alone was enough to strand a burn. First, a queued burn inherited the per-app *review cooldown* — a 30-minute throttle re-stamped by every task that completes on that app. On an app that carries any other recurring CoS work (a perpetual claim-issue drain, which is itself exempt from the cooldown and therefore keeps completing) the cooldown never lapses, so the burn task sat in Pending indefinitely while agents ran past it. The cooldown was never this task's throttle: the burn plan's own gate ladder — the reset horizon, the family's reserve, and `maxDispatchesPerWindow` — is checked before the task is queued at all, so burns now bypass it, as pipeline continuations and perpetual drains already did. Tasks already queued carry no marker, so migration 225 back-fills it onto them rather than leaving them stranded — and a stranded burn is worse than late, because `addTask` dedupes on description + app, so a pending twin makes the runner report "an identical burn task is already pending" and that job in the plan is permanently unreachable. Second, the runner always walked the family's job plan from the top, and an `agent-prompt` job always probes as "work pending" (its probe only checks that an app and a provider resolve) — so job #1 won every dispatch forever and the other seven audits in an eight-job plan never ran once. The walk now resumes after the family's last dispatch, read from the run log rather than a second cursor file, and still runs the first job with pending work from there, so a probing job like `universe-bible-images` keeps its ordering. Third, the plan only advanced once per `checkIntervalMinutes` — at the 12-hour default, two dispatches a day against an allowance of five on a five-hour window. Each finished burn agent now re-evaluates its own family, so the plan is walked one agent at a time until a gate actually closes; the chain is bounded by the same ledger every other cycle charges, and switching the feature off ends it immediately. That re-evaluation reads only the burning family's quota card rather than respawning every enabled provider's TUI for numbers it then discards — a per-family scrape the usage page already asked for this way.-- **Quota Burn was watching the 5-hour window and calling it the weekly one, so its one real gate never gated anything — and it kept dispatching after the provider started refusing.** Every subscription family publishes two windows on the same card: a short rolling one (claude/codex `session` ≈ 5h, antigravity `5-hour`) and a long one (`week`, `month`). Selection picked "the soonest-resetting window", and the short one is nearly always the soonest — so a plan written against a weekly allowance showed "62% left · resets in 3h" on its card, `resetWithinHours: 24` was satisfied by a horizon that re-opened every five hours (making "only spend as the window is about to expire" bound nothing at all), and `maxDispatchesPerWindow: 5` silently meant *five burns every five hours* rather than five per week, because the dispatch ledger keyed on the short window's reset. A family now burns against its **target** window — the broadest one on the card, classified by period in the new `server/lib/quotaWindows.js` — and the card names which window its percentage and countdown describe, so the two can never be confused again. The **limiting** window (the narrowest) and the **tightest** window (least headroom, what `reservePercent` already guarded) stay separate concepts, because they answer different questions. A provider whose window vocabulary this can't classify falls back to soonest-reset ordering rather than parking.+- **Quota Burn was watching the 5-hour window and calling it the weekly one, so its one real gate never gated anything — and it kept dispatching after the provider started refusing.** Every subscription family publishes two windows on the same card: a short rolling one (claude/codex `session` ≈ 5h, antigravity `5-hour`) and a long one (`week`, `month`). Selection picked "the soonest-resetting window", and the short one is nearly always the soonest — so a plan written against a weekly allowance showed "62% left · resets in 3h" on its card, `resetWithinHours: 24` was satisfied by a horizon that re-opened every five hours (making "only spend as the window is about to expire" bound nothing at all), and `maxDispatchesPerWindow: 5` silently meant *five burns every five hours* rather than five per week, because the dispatch ledger keyed on the short window's reset. A family now burns against its **target** window — the broadest one in scope, classified by period in the new `server/lib/quotaWindows.js` — and the card names which window its percentage and countdown describe, so the two can never be confused again. The **limiting** window (the narrowest) and the **tightest** window (least headroom, what `reservePercent` already guarded) stay separate concepts, because they answer different questions; the per-family Window scope field still pins the target explicitly for anyone who wants the old behavior. A provider whose window vocabulary this can't classify falls back to soonest-reset ordering rather than parking.Which exposed the second half: what actually *stops* a burn is the short window emptying underneath it. Spending a weekly allowance runs task after task until the 5-hour window is gone, at which point every further dispatch fails instantly, wastes an agent spawn and leaves a red card in the CoS queue — while the weekly card the runner gates on still reads "60% left, resets in 2 days", so nothing in the reported numbers ever says stop. That got sharper, not milder, once each finished burn agent started dispatching the next one immediately: the chain now walks straight into the wall at agent speed instead of interval speed. A refusal is therefore recorded as a fact rather than inferred from a meter — and recorded *inside* the completion continuation, awaited before it re-evaluates the family, because a block written after that dispatch (or from a second `agent:completed` subscriber, whose ordering against the continuation is not guaranteed) arrives one wasted agent too late every single time. The family is blocked until the reset the provider stated in its own refusal, else the reset of its limiting window, else a bounded 5-hour TTL so a reset-less block can't hold forever; a burn that *succeeds* clears it immediately, the provider serving being more current evidence than any stated reset. Four deliberate narrowings: only agents the burn plan itself dispatched count (the limiting window's reset rides on the task beside the `quotaBurnFamily` the cooldown exemption and the continuation already read, rather than inventing a second provenance shape); a transient `429` is a retry and not a spent window, so it does not block; an analyzer "usage-limit" verdict is trusted only when it came from a structured provider marker, not a loose keyword sweep over an agent narrating a prompt that happens to be *about* quota handling; and the block is bypassable by the ▶ forced run, which is how a user retries one they believe is stale. A ledger that can't be read is never overwritten and never silently reads as "nothing blocked", and the reset-out-of-refusal-text parsing is now one shared `parseObservedReset` rather than a second copy of what the image-gen quota ledger already did.diff --git a/client/src/components/ProviderModelSelector.jsx b/client/src/components/ProviderModelSelector.jsxindex 4e717a6bd9..13b69d940b 100644--- a/client/src/components/ProviderModelSelector.jsx+++ b/client/src/components/ProviderModelSelector.jsx@@ -8,6 +8,12 @@* caller that already filtered (e.g. via the hook's default `enabled` filter) is* unaffected since re-filtering enabled entries is idempotent.* @param {string} props.selectedProviderId - Currently selected provider ID+ * @param {string} [props.effectiveProviderId] - The provider a blank selection+ * actually resolves to at run time (the install's active provider). The select+ * still shows the blank `emptyProviderOption`, but the model annotations,+ * tool-use warning and effort ladder resolve against this — otherwise "no+ * provider pinned" would also mean "no model or effort can be picked".+ * Defaults to `selectedProviderId`. See `resolveEffectiveProvider`.* @param {string} props.selectedModel - Currently selected model* @param {Array} props.availableModels - Models for the selected provider. Entries* may be plain strings, or `{ id, name }` objects (the world builder passes the@@ -62,6 +68,7 @@ function modelOption(m) {export default function ProviderModelSelector({providers,selectedProviderId,+ effectiveProviderId,selectedModel,availableModels,onProviderChange,@@ -85,7 +92,9 @@ export default function ProviderModelSelector({// the annotation only fires for local backends (the heuristic mislabels cloud// ids). `localToolUseHint` returns null for cloud/blank, so the warning stays// scoped to a genuinely tool-incapable local pin.- const selectedProvider = providers.find((p) => p.id === selectedProviderId);+ // Resolve against the effective provider (the pin, or what a blank selection+ // falls back to) — everything below describes what a run would actually use.+ const selectedProvider = providers.find((p) => p.id === (effectiveProviderId ?? selectedProviderId));// A blank model ("Default model") isn't a no-op: the agent resolver then runs// the provider's own defaultModel — which for an Ollama-backed provider can be// a non-tool model that silently wedges the stage. So evaluate the EFFECTIVEdiff --git a/client/src/components/cos/tabs/ScheduleTab.jsx b/client/src/components/cos/tabs/ScheduleTab.jsxindex 45d9cd7cfb..fbaada24ed 100644--- a/client/src/components/cos/tabs/ScheduleTab.jsx+++ b/client/src/components/cos/tabs/ScheduleTab.jsx@@ -50,8 +50,9 @@ export default function ScheduleTab({ apps, providers, activeProviderId }) {// Resolves a boolean so optimistic callers (the card's quick model pins) can// roll their local selection back — this handler owns the error toast, so it- // never rejects.- const handleUpdateTask = async (taskType, settings) => {+ // never rejects. Stable identity: every card holds it through useTaskModelPins,+ // so a fresh arrow per render would invalidate their memoized handlers.+ const handleUpdateTask = useCallback(async (taskType, settings) => {const result = await api.updateCosTaskInterval(taskType, settings, { silent: true }).catch(err => {toast.error(err.message);return null;@@ -62,9 +63,9 @@ export default function ScheduleTab({ apps, providers, activeProviderId }) {toast.success(`Updated ${taskType}`);fetchSchedule();return true;- };+ }, [fetchSchedule]);- const handleTriggerTask = async (taskType, appId = null) => {+ const handleTriggerTask = useCallback(async (taskType, appId = null) => {const result = await api.triggerCosOnDemandTask(taskType, appId, { silent: true }).catch(err => {toast.error(err.message);return null;@@ -73,7 +74,7 @@ export default function ScheduleTab({ apps, providers, activeProviderId }) {toast.success(`Triggered ${taskType} task${appId ? ' for app' : ''} - will run on next evaluation`);fetchSchedule();}- };+ }, [fetchSchedule]);const handleResetTask = async (taskType) => {const result = await api.resetCosTaskHistory(taskType, null, { silent: true }).catch(err => {@@ -86,7 +87,7 @@ export default function ScheduleTab({ apps, providers, activeProviderId }) {}};- const handleTriggerAppImprovement = (taskType, appId) => handleTriggerTask(taskType, appId);+ const handleTriggerAppImprovement = handleTriggerTask;const { handleUpdateOverride, handleBulkToggleOverride } = useAppOverrideActions(apps, fetchSchedule);diff --git a/client/src/components/cos/tabs/schedule/AppTaskCard.jsx b/client/src/components/cos/tabs/schedule/AppTaskCard.jsxindex 6fc5529379..0f8730a99f 100644--- a/client/src/components/cos/tabs/schedule/AppTaskCard.jsx+++ b/client/src/components/cos/tabs/schedule/AppTaskCard.jsx@@ -1,7 +1,7 @@-import { useState } from 'react';import { Clock, AlertTriangle, SlidersHorizontal, GitMerge } from 'lucide-react';import { timeAgo } from '../../../../utils/formatters';-import { describeNextRun, coverageTone } from './scheduleConstants';+import useTaskModelPins from '../../../../hooks/useTaskModelPins';+import { describeNextRun, coverageTone, pipelineStages, IMPROVEMENT_DISABLED_TITLE, SAVING_TITLE } from './scheduleConstants';import TaskHeader from './TaskHeader';import RunTaskButton from './RunTaskButton';import TaskModelQuickControls from './TaskModelQuickControls';@@ -10,9 +10,9 @@ import TaskModelQuickControls from './TaskModelQuickControls';// "retarget the model and run it" loop happen here; the rest of the// configuration lives in the slide-over drawer (opened via Configure).export default function AppTaskCard({ taskType, config, apps, onTrigger, onConfigure, onUpdate, providers, activeProviderId, improvementDisabled }) {- // A pin write is async; Run reads the server-side config, so it must stay- // disabled until the write lands (see TaskModelQuickControls).- const [savingPins, setSavingPins] = useState(false);+ // Owned here, not in the controls, so Run can gate on the same `saving` flag —+ // it reads the server-side config, so a run fired mid-write uses the old pins.+ const pins = useTaskModelPins({ taskType, config, providers, activeProviderId, onUpdate });const enabledCount = config.enabledAppCount ?? 0;const totalCount = config.totalAppCount ?? 0;const hasApps = totalCount > 0;@@ -21,7 +21,7 @@ export default function AppTaskCard({ taskType, config, apps, onTrigger, onConficonst nextRun = describeNextRun(config);// A pipeline task resolves provider/model per stage — a single card-level pin// would be ignored, so point at the drawer instead of offering one.- const pipelineStages = config.taskMetadata?.pipeline?.stages?.length || 0;+ const stageCount = pipelineStages(config).length;return (<div className="flex flex-col border border-port-border rounded-lg bg-port-card hover:border-port-border/60 transition-colors">@@ -68,24 +68,17 @@ export default function AppTaskCard({ taskType, config, apps, onTrigger, onConfi</button>{/* Quick model pins — the drawer's Global defaults, inline */}- {onUpdate && (pipelineStages > 0 ? (+ {onUpdate && (stageCount > 0 ? (<buttontype="button"onClick={() => onConfigure(taskType)}className="flex items-center gap-1.5 px-4 py-2.5 text-xs text-left text-gray-500 border-t border-port-border hover:text-gray-300 transition-colors"><GitMerge size={12} className="shrink-0" />- Provider/model is set per stage ({pipelineStages}) — configure+ Provider/model is set per stage ({stageCount}) — configure</button>) : (- <TaskModelQuickControls- taskType={taskType}- config={config}- providers={providers}- activeProviderId={activeProviderId}- onUpdate={onUpdate}- onSavingChange={setSavingPins}- />+ <TaskModelQuickControls pins={pins} providers={providers} />))}{/* Footer actions */}@@ -94,8 +87,7 @@ export default function AppTaskCard({ taskType, config, apps, onTrigger, onConfitaskType={taskType}apps={apps}onTrigger={onTrigger}- improvementDisabled={improvementDisabled}- saving={savingPins}+ disabledReason={improvementDisabled ? IMPROVEMENT_DISABLED_TITLE : (pins.saving ? SAVING_TITLE : '')}/><buttontype="button"diff --git a/client/src/components/cos/tabs/schedule/AppTaskCard.test.jsx b/client/src/components/cos/tabs/schedule/AppTaskCard.test.jsxindex 21341fe415..60959bd19b 100644--- a/client/src/components/cos/tabs/schedule/AppTaskCard.test.jsx+++ b/client/src/components/cos/tabs/schedule/AppTaskCard.test.jsx@@ -140,27 +140,35 @@ describe('AppTaskCard', () => {it('offers effort only for effort-capable providers', () => {renderCardWithPins({ providerId: 'claude-code' });- expect(screen.getByLabelText('Effort')).toBeTruthy();+ expect(screen.getByLabelText('Thinking effort')).toBeTruthy();expect(screen.getByRole('option', { name: 'xhigh' })).toBeTruthy();});it('hides effort for a provider with no ladder', () => {renderCardWithPins({ providerId: 'gemini' });- expect(screen.queryByLabelText('Effort')).toBeNull();+ expect(screen.queryByLabelText('Thinking effort')).toBeNull();});it('resolves model + effort options against the active provider when nothing is pinned', () => {renderCardWithPins({}, { activeProviderId: 'claude-code' });// Naming what "Default" resolves to is what makes the options below it readable.- expect(screen.getByRole('option', { name: 'Active: Claude Code' })).toBeTruthy();+ expect(screen.getByRole('option', { name: 'Default (active: Claude Code)' })).toBeTruthy();expect(screen.getByRole('option', { name: 'sonnet' })).toBeTruthy();- expect(screen.getByLabelText('Effort')).toBeTruthy();+ expect(screen.getByLabelText('Thinking effort')).toBeTruthy();});it('falls back to a bare Default when the active provider is unknown', () => {renderCardWithPins();- expect(within(screen.getByLabelText('Provider')).getByRole('option', { name: 'Default' })).toBeTruthy();- expect(screen.queryByLabelText('Effort')).toBeNull();+ expect(within(screen.getByLabelText('Provider')).getByRole('option', { name: 'Default (active provider)' })).toBeTruthy();+ expect(screen.queryByLabelText('Thinking effort')).toBeNull();+ });++ it('hides a disabled provider from the picker unless the task is pinned to it', () => {+ const withDisabled = [...providers, { id: 'retired', name: 'Retired CLI', enabled: false }];+ renderCardWithPins({}, { providers: withDisabled });+ expect(screen.queryByRole('option', { name: 'Retired CLI' })).toBeNull();+ renderCardWithPins({ providerId: 'retired' }, { providers: withDisabled });+ expect(screen.getAllByRole('option', { name: 'Retired CLI' }).length).toBe(1);});it('keeps a pinned model the provider no longer lists selectable', () => {diff --git a/client/src/components/cos/tabs/schedule/GlobalConfigControls.jsx b/client/src/components/cos/tabs/schedule/GlobalConfigControls.jsxindex f8900b8add..0b511b5c0a 100644--- a/client/src/components/cos/tabs/schedule/GlobalConfigControls.jsx+++ b/client/src/components/cos/tabs/schedule/GlobalConfigControls.jsx@@ -15,7 +15,7 @@ import useTaskModelPins from '../../../../hooks/useTaskModelPins';import EffortSelect from '../../EffortSelect';import PromptEditor from './PromptEditor';import RunTaskButton from './RunTaskButton';-import { INTERVAL_DESCRIPTIONS, toggleMetadataField } from './scheduleConstants';+import { INTERVAL_DESCRIPTIONS, toggleMetadataField, pipelineStages, IMPROVEMENT_DISABLED_TITLE, SAVING_TITLE } from './scheduleConstants';// Shown for the unpinned ('' → inherit) choice: the task type is global, so the// policy is whatever each target app configured, and PortOS's own self-improvement@@ -37,7 +37,7 @@ export default function GlobalConfigControls({ taskType, config, onUpdate, onTrimodel: selectedModel,effort: selectedEffort,provider: selectedProvider,- usingActiveProvider,+ defaultProviderLabel,availableModels,changeProvider: handleProviderChange,changeModel: handleModelChange,@@ -281,7 +281,7 @@ export default function GlobalConfigControls({ taskType, config, onUpdate, onTri</div>)}- {!config.taskMetadata?.pipeline?.stages?.length && (+ {pipelineStages(config).length === 0 && (<><FormField label="Provider (optional)" labelClassName="text-sm text-gray-400 block mb-2"><select@@ -290,9 +290,7 @@ export default function GlobalConfigControls({ taskType, config, onUpdate, onTridisabled={updating}className="w-full bg-port-card border border-port-border rounded px-3 py-2 text-white text-sm">- <option value="">- {usingActiveProvider ? `Default (active: ${selectedProvider.name})` : 'Default (active provider)'}- </option>+ <option value="">{defaultProviderLabel}</option>{providers?.map(provider => (<option key={provider.id} value={provider.id}>{provider.name}</option>))}@@ -307,10 +305,9 @@ export default function GlobalConfigControls({ taskType, config, onUpdate, onTridisabled={updating}className="w-full bg-port-card border border-port-border rounded px-3 py-2 text-white text-sm">+ {/* `availableModels` already carries a pin the provider no longer+ lists, so the select can't render blank and read as "Default". */}<option value="">Default model</option>- {selectedModel && !availableModels.includes(selectedModel) && (- <option value={selectedModel}>{selectedModel}</option>- )}{availableModels.map(model => (<option key={model} value={model}>{model}</option>))}@@ -525,7 +522,8 @@ export default function GlobalConfigControls({ taskType, config, onUpdate, onTritaskType={taskType}apps={apps}onTrigger={onTrigger}- improvementDisabled={improvementDisabled}+ // `updating` covers an in-flight pin write here, same race the card gates on.+ disabledReason={improvementDisabled ? IMPROVEMENT_DISABLED_TITLE : (updating ? SAVING_TITLE : '')}/>{config.type === 'once' && status.reason === 'once-completed' && (<buttondiff --git a/client/src/components/cos/tabs/schedule/PipelineStageConfig.jsx b/client/src/components/cos/tabs/schedule/PipelineStageConfig.jsxindex 63226eb7e2..1cfb90a299 100644--- a/client/src/components/cos/tabs/schedule/PipelineStageConfig.jsx+++ b/client/src/components/cos/tabs/schedule/PipelineStageConfig.jsx@@ -1,9 +1,10 @@import { filterSelectableModels } from '../../../../utils/providers';import { FormField } from '../../../ui/FormField';import EffortSelect from '../../EffortSelect';+import { pipelineStages } from './scheduleConstants';export default function PipelineStageConfig({ taskType, config, providers, onUpdate, updating, setUpdating }) {- const stages = config.taskMetadata?.pipeline?.stages || [];+ const stages = pipelineStages(config);const handleStageUpdate = async (stageIndex, field, value) => {setUpdating(true);diff --git a/client/src/components/cos/tabs/schedule/PromptEditor.jsx b/client/src/components/cos/tabs/schedule/PromptEditor.jsxindex e5e4a0e6b8..5510495973 100644--- a/client/src/components/cos/tabs/schedule/PromptEditor.jsx+++ b/client/src/components/cos/tabs/schedule/PromptEditor.jsx@@ -1,7 +1,8 @@import { useState, useEffect } from 'react';+import { pipelineStages } from './scheduleConstants';export default function PromptEditor({ config, promptValue, setPromptValue, editingPrompt, setEditingPrompt, handleSavePrompt, updating, activeApps }) {- const stages = config.taskMetadata?.pipeline?.stages;+ const stages = pipelineStages(config);const stagePrompts = config.stagePrompts;const hasPipeline = stages?.length > 0 && stagePrompts?.length > 0;const [activeTab, setActiveTab] = useState(0);diff --git a/client/src/components/cos/tabs/schedule/RunTaskButton.jsx b/client/src/components/cos/tabs/schedule/RunTaskButton.jsxindex a6aa661de0..5fc4cb429f 100644--- a/client/src/components/cos/tabs/schedule/RunTaskButton.jsx+++ b/client/src/components/cos/tabs/schedule/RunTaskButton.jsx@@ -1,20 +1,21 @@import { useState, useRef, useEffect } from 'react';import { Play, ChevronDown, Package } from 'lucide-react';-import { triggerButtonClass, IMPROVEMENT_DISABLED_TITLE, SAVING_TITLE } from './scheduleConstants';+import { triggerButtonClass } from './scheduleConstants';// Trigger an on-demand run. When the task targets managed apps, opens a picker// so the run carries app context; otherwise fires a plain global run. Shared by// the schedule card and the drawer's global-config controls so both stay in sync.//-// `saving` means a provider/model/effort pin is still being persisted. The run-// reads the server-side config, so triggering mid-write would run the previous-// settings — hence a hard disable rather than a tooltip.-export default function RunTaskButton({ taskType, apps, onTrigger, improvementDisabled, saving = false }) {+// `disabledReason` is the one gate: a non-empty string disables the button and+// becomes its tooltip (improvement switched off, a pin still being saved, …).+// A named boolean per reason would mean every new reason edits this component,+// and — as the pin-saving gate showed — reaching only whichever call site the+// author had in mind.+export default function RunTaskButton({ taskType, apps, onTrigger, disabledReason = '' }) {const [open, setOpen] = useState(false);const ref = useRef(null);const activeApps = apps?.filter(app => !app.archived) || [];- const disabled = improvementDisabled || saving;- const disabledTitle = improvementDisabled ? IMPROVEMENT_DISABLED_TITLE : SAVING_TITLE;+ const disabled = !!disabledReason;useEffect(() => {if (!open) return;@@ -30,7 +31,7 @@ export default function RunTaskButton({ taskType, apps, onTrigger, improvementDiif (activeApps.length === 0) {return (- <span title={disabled ? disabledTitle : 'Run this task immediately (bypasses schedule)'} className="inline-block">+ <span title={disabledReason || 'Run this task immediately (bypasses schedule)'} className="inline-block"><buttontype="button"onClick={() => !disabled && onTrigger(taskType)}@@ -48,7 +49,7 @@ export default function RunTaskButton({ taskType, apps, onTrigger, improvementDireturn (<div className="relative" ref={ref}>{/* Tooltip on the wrapper, not the button: most browsers skip hover events on disabled controls. */}- <span title={disabled ? disabledTitle : 'Run this task on a specific app'} className="inline-block">+ <span title={disabledReason || 'Run this task on a specific app'} className="inline-block"><buttontype="button"onClick={() => !disabled && setOpen(o => !o)}diff --git a/client/src/components/cos/tabs/schedule/TaskConfigDrawer.jsx b/client/src/components/cos/tabs/schedule/TaskConfigDrawer.jsxindex 0010c40c54..0474f689d2 100644--- a/client/src/components/cos/tabs/schedule/TaskConfigDrawer.jsx+++ b/client/src/components/cos/tabs/schedule/TaskConfigDrawer.jsx@@ -2,6 +2,7 @@ import { useState } from 'react';import Drawer from '../../../Drawer';import useDrawerTab from '../../../../hooks/useDrawerTab';import TaskHeader from './TaskHeader';+import { pipelineStages } from './scheduleConstants';import PipelineStageConfig from './PipelineStageConfig';import GlobalConfigControls from './GlobalConfigControls';import PerAppOverrideList from './PerAppOverrideList';@@ -37,7 +38,7 @@ export default function TaskConfigDrawer({}) {const [updating, setUpdating] = useState(false);- const stages = config?.taskMetadata?.pipeline?.stages || [];+ const stages = pipelineStages(config);const hasStages = stages.length > 0;const activeApps = apps?.filter(app => !app.archived) || [];const hasOverrides = activeApps.length > 0;diff --git a/client/src/components/cos/tabs/schedule/TaskHeader.jsx b/client/src/components/cos/tabs/schedule/TaskHeader.jsxindex eee96b56f1..52a11c1f89 100644--- a/client/src/components/cos/tabs/schedule/TaskHeader.jsx+++ b/client/src/components/cos/tabs/schedule/TaskHeader.jsx@@ -1,5 +1,5 @@import { GitMerge, Users } from 'lucide-react';-import { badge, statusDot, getTaskStatusGroup } from './scheduleConstants';+import { badge, statusDot, getTaskStatusGroup, pipelineStages } from './scheduleConstants';import IntervalBadge from './IntervalBadge';// Shared task identity row — status dot, monospace name, pipeline + swarm@@ -7,7 +7,7 @@ import IntervalBadge from './IntervalBadge';// drawer so the header stays consistent in one place.export default function TaskHeader({ taskType, config }) {const group = getTaskStatusGroup(config);- const stages = config.taskMetadata?.pipeline?.stages;+ const stages = pipelineStages(config);// Swarm (`/do:next --swarm`) is on when the global default carries a size ≥2.// Per-app overrides aren't reflected in this global header (the per-app row// shows its own override select).diff --git a/client/src/components/cos/tabs/schedule/TaskModelQuickControls.jsx b/client/src/components/cos/tabs/schedule/TaskModelQuickControls.jsxindex a60b23a7d8..673fde41a8 100644--- a/client/src/components/cos/tabs/schedule/TaskModelQuickControls.jsx+++ b/client/src/components/cos/tabs/schedule/TaskModelQuickControls.jsx@@ -1,72 +1,36 @@-import { FormField } from '../../../ui/FormField';-import EffortSelect from '../../EffortSelect';-import useTaskModelPins from '../../../../hooks/useTaskModelPins';--const LABEL_CLASS = 'block text-[10px] uppercase tracking-wide text-gray-500 mb-0.5';-const SELECT_CLASS = 'w-full bg-port-card border border-port-border rounded px-1.5 py-1 text-xs text-white disabled:opacity-60';+import ProviderModelSelector from '../../../ProviderModelSelector';// Compact provider/model/effort pins rendered directly on a schedule card, so// the common "point this task at a different model and run it" loop doesn't-// require opening the config drawer. Writes go through the same task-update-// path as the drawer's Global defaults tab (useTaskModelPins).+// require opening the config drawer. Presentational — the card owns the+// `useTaskModelPins` state so its Run button can gate on the same `saving` flag.//-// `onSavingChange` lifts the in-flight flag to the card, which disables Run-// while a pin is still being persisted — the run reads the server-side config,-// not these inputs.-export default function TaskModelQuickControls({ taskType, config, providers, activeProviderId, onUpdate, disabled = false, onSavingChange }) {- const { providerId, model, effort, provider, usingActiveProvider, availableModels, saving, changeProvider, changeModel, changeEffort } =- useTaskModelPins({ taskType, config, providers, activeProviderId, onUpdate, onBusyChange: onSavingChange });-- const locked = disabled || saving;- // Name what "Default" resolves to right now, so the model/effort options- // below it aren't from a provider the user has to guess at.- const defaultLabel = usingActiveProvider ? `Active: ${provider.name}` : 'Default';+// `highlightToolUse` is on because a scheduled task IS an agent run: a task+// pinned to a local model that can't call tools narrates instead of working.+export default function TaskModelQuickControls({ pins, providers, disabled = false }) {+ const {+ providerId, model, effort, effectiveProviderId, defaultProviderLabel,+ availableModels, saving, changeProvider, changeModel, changeEffort,+ } = pins;return (- <div className="flex flex-wrap items-end gap-2 px-4 py-2.5 border-t border-port-border">- <FormField label="Provider" className="min-w-[7rem] flex-1" labelClassName={LABEL_CLASS}>- <select- value={providerId}- onChange={(e) => changeProvider(e.target.value)}- disabled={locked}- className={SELECT_CLASS}- title="Provider for this task's runs — Default follows the active provider"- >- <option value="">{defaultLabel}</option>- {providers?.map(p => (- <option key={p.id} value={p.id}>{p.name}</option>- ))}- </select>- </FormField>-- <FormField label="Model" className="min-w-[7rem] flex-1" labelClassName={LABEL_CLASS}>- <select- value={model}- onChange={(e) => changeModel(e.target.value)}- disabled={locked}- className={SELECT_CLASS}- title="Model override — Default uses the provider's default model"- >- <option value="">Default</option>- {/* A pin the current provider no longer lists still renders, or the- select would show blank and read as "Default". */}- {model && !availableModels.includes(model) && <option value={model}>{model}</option>}- {availableModels.map(m => (- <option key={m} value={m}>{m}</option>- ))}- </select>- </FormField>-- <EffortSelect- provider={provider}- model={model}- value={effort}- onChange={changeEffort}- disabled={locked}- label="Effort"- fieldClassName="min-w-[7rem] flex-1"- labelClassName={LABEL_CLASS}- className={SELECT_CLASS}+ <div className="px-4 py-2.5 border-t border-port-border">+ <ProviderModelSelector+ providers={providers || []}+ selectedProviderId={providerId}+ effectiveProviderId={effectiveProviderId}+ selectedModel={model}+ availableModels={availableModels}+ onProviderChange={changeProvider}+ onModelChange={changeModel}+ effort={effort}+ onEffortChange={changeEffort}+ emptyProviderOption={defaultProviderLabel}+ emptyModelOption="Default model"+ alwaysShowModel+ compact+ highlightToolUse+ disabled={disabled || saving}/></div>);diff --git a/client/src/components/cos/tabs/schedule/scheduleConstants.js b/client/src/components/cos/tabs/schedule/scheduleConstants.jsindex 888661d008..e9cfb43cf7 100644--- a/client/src/components/cos/tabs/schedule/scheduleConstants.js+++ b/client/src/components/cos/tabs/schedule/scheduleConstants.js@@ -45,6 +45,10 @@ export const IMPROVEMENT_DISABLED_TITLE = 'Improvement is disabled — enable itexport const SAVING_TITLE = 'Saving provider/model settings — the run will use them once saved';+// The task's pipeline stages (always an array). A non-empty one means its+// provider/model are resolved per stage, so a task-level pin would be ignored.+export const pipelineStages = (config) => config?.taskMetadata?.pipeline?.stages || [];+export const triggerButtonClass = (disabled) =>`flex items-center gap-1 px-3 py-1.5 text-sm rounded transition-colors ${disabled ? 'bg-port-border/30 text-gray-500 cursor-not-allowed' : 'bg-port-accent/20 hover:bg-port-accent/30 text-port-accent'}`;diff --git a/client/src/hooks/README.md b/client/src/hooks/README.mdindex db2001c5f8..48cc20e2a0 100644--- a/client/src/hooks/README.md+++ b/client/src/hooks/README.md@@ -143,7 +143,7 @@ grep -i "what you want to do" client/src/hooks/README.md| `useAppDeploy` | Stream `deploy.sh` output via Socket.IO. | App deployment surfaces only. || `useAppOperation` | Socket-based app ops (update, standardize) with step tracking. | App operations UI. || `useAppOverrideActions` | Per-app scheduled-task override mutations (`{ handleUpdateOverride, handleBulkToggleOverride }`) with shared toast copy + silent flag; pass the tab's `refetch`. | Any surface hosting `PerAppOverrideList` (Schedule tab, Timeline tab) — don't re-copy the write-plus-toast-plus-refetch handlers. |-| `useTaskModelPins` | Provider/model/effort pins for one CoS scheduled task: optimistic write per change (`'' → null` clears; picking a provider clears model+effort), rollback when `onUpdate` resolves `false`, plus a `saving` flag to gate "Run Now". | Any surface that retargets a scheduled task's model (schedule card quick controls, config drawer Global defaults) — don't re-roll the select/PUT/rollback trio. |+| `useTaskModelPins` | Provider/model/effort pins for one CoS scheduled task: optimistic write per change (`'' → null` clears; picking a provider clears model+effort), rollback when `onUpdate` resolves falsy, a `saving` flag to gate "Run Now", plus the derived `availableModels` (stale pin kept selectable), `effectiveProviderId` and `defaultProviderLabel` a `ProviderModelSelector` needs. | Any surface that retargets a scheduled task's model (schedule card quick controls, config drawer Global defaults) — don't re-roll the select/PUT/rollback trio. || `useCanonPatch` | Optimistic canon-entry patch: rebuild the kind list with one entry mutated, apply locally, PATCH the universe, re-apply the server copy. Targets + staleness-guards on the loaded record's `universe.id` so a mid-flight universe swap can't cross-PATCH or resurrect stale state. `apply` is `setUniverse` or `onUniverseChange`. | Inline canon-field edits on a universe (UniverseCanonSection, NounsStage). Don't re-roll the optimistic-then-confirm dance. || `useCityAudio` | CyberCity ambient audio. | CyberCity only. || `useCityData` | CyberCity environment data + physics. | CyberCity only. |diff --git a/client/src/hooks/useTaskModelPins.js b/client/src/hooks/useTaskModelPins.jsindex d5219d0fdf..7a864ea4b7 100644--- a/client/src/hooks/useTaskModelPins.js+++ b/client/src/hooks/useTaskModelPins.js@@ -1,5 +1,5 @@-import { useState, useEffect, useCallback } from 'react';-import { filterSelectableModels } from '../utils/providers';+import { useState, useEffect, useCallback, useMemo } from 'react';+import { filterSelectableModels, mergeModelLists, resolveEffectiveProvider } from '../utils/providers';/*** Provider / model / effort pins for one CoS scheduled task, shared by the@@ -20,80 +20,68 @@ import { filterSelectableModels } from '../utils/providers';* @param {string} params.taskType - Task id (e.g. `code-review`).* @param {object} params.config - The live task config from the schedule payload.* @param {object[]} [params.providers] - Provider records, for resolving the model list.- * @param {string} [params.activeProviderId] - The install's active provider. With- * no provider pinned the task runs on it, so the model list and effort ladder- * resolve against it — otherwise "no provider pinned" would mean "no way to- * pin a model or effort either" (same fallback as the pipeline's LLM pickers).- * @param {function} params.onUpdate - `(taskType, settings) => Promise<boolean|void>`;- * resolving `false` (or rejecting) rolls the local selection back.+ * @param {string} [params.activeProviderId] - The install's active provider, which+ * an unpinned task runs on (see `resolveEffectiveProvider`).+ * @param {function} params.onUpdate - `(taskType, settings) => Promise<boolean>`;+ * resolving falsy (or rejecting) rolls the local selection back.* @param {function} [params.onBusyChange] - Mirrors `saving` into a caller-owned- * updating flag (the drawer disables its whole form off one).+ * updating flag (the drawer disables its whole form — and blocks Esc — off one).* @returns {{providerId: string, model: string, effort: string, provider: object|undefined,- * usingActiveProvider: boolean, availableModels: string[], saving: boolean,- * changeProvider: function, changeModel: function, changeEffort: function}}+ * effectiveProviderId: string, defaultProviderLabel: string, availableModels: string[],+ * saving: boolean, changeProvider: function, changeModel: function, changeEffort: function}}*/export function useTaskModelPins({ taskType, config, providers, activeProviderId, onUpdate, onBusyChange }) {- const [providerId, setProviderId] = useState(config?.providerId || '');- const [model, setModel] = useState(config?.model || '');- const [effort, setEffort] = useState(config?.effort || '');+ const persisted = useMemo(() => ({+ providerId: config?.providerId || '',+ model: config?.model || '',+ effort: config?.effort || '',+ }), [config?.providerId, config?.model, config?.effort]);++ const [pins, setPins] = useState(persisted);const [saving, setSaving] = useState(false);// Re-sync from the refetched config (and when the hosting surface switches task).- useEffect(() => {- setProviderId(config?.providerId || '');- setModel(config?.model || '');- setEffort(config?.effort || '');- }, [taskType, config?.providerId, config?.model, config?.effort]);-- const setBusy = useCallback((busy) => {- setSaving(busy);- onBusyChange?.(busy);- }, [onBusyChange]);-- const commit = useCallback(async (patch, rollback) => {- setBusy(true);- // Callers that own their own error toast resolve `false` on failure; the- // ones that resolve nothing (older call sites, tests) count as success.- const ok = await onUpdate(taskType, patch).catch(() => false);- if (ok === false) rollback();- setBusy(false);- }, [onUpdate, taskType, setBusy]);-- const restore = useCallback(() => {- setProviderId(config?.providerId || '');- setModel(config?.model || '');- setEffort(config?.effort || '');- }, [config?.providerId, config?.model, config?.effort]);+ useEffect(() => { setPins(persisted); }, [taskType, persisted]);- const changeProvider = useCallback((next) => {- setProviderId(next);- setModel('');- setEffort('');- return commit({ providerId: next === '' ? null : next, model: null, effort: null }, restore);- }, [commit, restore]);+ // One optimistic write for all three pins: apply locally, PUT ('' → null+ // clears the pin), restore the persisted values if the write didn't land.+ const change = useCallback(async (patch) => {+ setPins(prev => ({ ...prev, ...patch }));+ setSaving(true);+ onBusyChange?.(true);+ const settings = Object.fromEntries(+ Object.entries(patch).map(([field, value]) => [field, value === '' ? null : value])+ );+ const ok = await onUpdate(taskType, settings).catch(() => false);+ if (!ok) setPins(persisted);+ setSaving(false);+ onBusyChange?.(false);+ }, [onUpdate, taskType, persisted, onBusyChange]);- const changeModel = useCallback((next) => {- setModel(next);- return commit({ model: next === '' ? null : next }, restore);- }, [commit, restore]);+ // Provider is the only one that clears its siblings: a model (and the effort+ // ladder behind it) belongs to the provider it came from.+ const changeProvider = useCallback((next) => change({ providerId: next, model: '', effort: '' }), [change]);+ const changeModel = useCallback((next) => change({ model: next }), [change]);+ const changeEffort = useCallback((next) => change({ effort: next }), [change]);- const changeEffort = useCallback((next) => {- setEffort(next);- return commit({ effort: next === '' ? null : next }, restore);- }, [commit, restore]);+ const { provider, usingActive } = useMemo(+ () => resolveEffectiveProvider(providers, pins.providerId, activeProviderId),+ [providers, pins.providerId, activeProviderId]+ );- // With nothing pinned the run resolves to the active provider, so that's whose- // catalog the model/effort pickers must offer.- const resolvedProviderId = providerId || activeProviderId || '';- const provider = providers?.find(p => p.id === resolvedProviderId);+ // A pin the provider no longer lists stays selectable, or the select would+ // hold a value matching no option, render blank, and read as "Default".+ const availableModels = useMemo(() => {+ const selectable = filterSelectableModels(provider?.models);+ return pins.model ? mergeModelLists([pins.model], selectable) : selectable;+ }, [provider?.models, pins.model]);return {- providerId,- model,- effort,+ ...pins,provider,- usingActiveProvider: !providerId && !!provider,- availableModels: filterSelectableModels(provider?.models),+ effectiveProviderId: provider?.id || '',+ defaultProviderLabel: usingActive ? `Default (active: ${provider.name})` : 'Default (active provider)',+ availableModels,saving,changeProvider,changeModel,diff --git a/client/src/utils/README.md b/client/src/utils/README.mdindex 52b7602b90..3f10c1f130 100644--- a/client/src/utils/README.md+++ b/client/src/utils/README.md@@ -40,7 +40,7 @@ grep -i "what you want to do" client/src/utils/README.md| `urlNormalize` | `isUrl` detection, `normalizeUrl` (optional git/`requireDot` modes), `isHttpUrl` (explicit http(s) only — safe-href check), and `tiktokVideoId` / `tiktokEmbedSrc` (host-anchored TikTok video-id extraction + its Embed Player URL, so a reference embeds without loading TikTok's embed.js). || `platform` | `isMac` detection and `modKey` (⌘/Ctrl) for keyboard-shortcut display. || `navWorkingSet` | Recent/pinned nav persistence (`recordVisit`, `togglePin`, `isPinned`) plus `resolveRecentNavEntries` for mapping stored deep links back to their longest matching nav-manifest entry. |-| `providers` | AI-provider type predicates and helpers (`isCliProvider`, `isApiProvider`, `isCodexProvider`, `isAntigravityProvider`, `filterSelectableModels`, `resolveCliEffort` (mirror — what a stored effort actually runs as, so the picker can name a clamped level), `configuredDefaultIn` — the sentinel a provider's catalog carries, so a picker can render an option matching a sentinel-valued tier instead of a blank select — `getProviderTimeout`, configured-default sentinels, and the claude/codex/agy thinking-effort levels — `effortLevelsForProvider`, mirror of server `providerModels.js`). |+| `providers` | AI-provider type predicates and helpers (`isCliProvider`, `isApiProvider`, `isCodexProvider`, `isAntigravityProvider`, `filterSelectableModels`, `resolveCliEffort` (mirror — what a stored effort actually runs as, so the picker can name a clamped level), `configuredDefaultIn` — the sentinel a provider's catalog carries, so a picker can render an option matching a sentinel-valued tier instead of a blank select — `getProviderTimeout`, `resolveEffectiveProvider` — the provider a record actually runs on (its pin, else the active provider) plus whether it fell back, so a "Default" option can name what it resolves to — configured-default sentinels, and the claude/codex/agy thinking-effort levels — `effortLevelsForProvider`, mirror of server `providerModels.js`). || `layeredIntelligenceReasons` | Canonical gloss for the Layered Intelligence loop's run-outcome reason tokens, shared by the on-demand toast and the durable "Last run" line (`formatLiReason`, `liReasonTone`, `LI_NEUTRAL_REASONS`). |## Module loading / resiliencediff --git a/client/src/utils/providers.js b/client/src/utils/providers.jsindex 143cab51f1..58957aba20 100644--- a/client/src/utils/providers.js+++ b/client/src/utils/providers.js@@ -617,6 +617,27 @@ export const getProviderTimeout = (providers, stagePinnedId, activeProviderId) =return providers.find((p) => p.id === id)?.timeout;};+/**+ * The provider a record will ACTUALLY run on: its own pin when set, else the+ * install's active provider. Every picker that offers a "use the default"+ * option needs this — the model list, effort ladder, and "Default (active: X)"+ * label all have to resolve against the fallback, or leaving a record unpinned+ * silently means "no model or effort can be picked either".+ *+ * `usingActive` distinguishes the two so a caller can say which provider the+ * blank option currently means rather than just showing "Default".+ *+ * @param {Array} providers+ * @param {string|null|undefined} pinnedId - The record's own provider pin.+ * @param {string|null|undefined} activeProviderId - The install's active provider.+ * @returns {{provider: object|undefined, usingActive: boolean}}+ */+export const resolveEffectiveProvider = (providers, pinnedId, activeProviderId) => {+ const id = pinnedId || activeProviderId || '';+ const provider = id ? (providers || []).find((p) => p.id === id) : undefined;+ return { provider, usingActive: !pinnedId && !!provider };+};+/*** Tailwind chip classes for the provider type badge ('cli' / 'tui' / 'api').* Lifted out of AIProviders.jsx so other components can render the same