mirror of
https://github.com/bitbaum/loki.git
synced 2026-12-04 03:56:59 +01:00
feat(providers): one-tap switch to a provider that still has quota (#757)
* feat(providers): one-tap switch to a provider that still has quota When the agent building a project hits a rate limit, the way out already existed — four other agent CLIs, most with untouched quota. Taking it was the problem. The only chooser lived in the Terminal right rail, it offered every agent in a fixed order whether or not the connected builder had it installed, and taking it swapped the live PTY without recording the choice, so the next dispatch went straight back to the agent that had just run out. One ranking, three surfaces: - src/lib/provider-switch.ts — the whole decision as pure functions. Ranks the operator's order, filters on two pieces of OBSERVED evidence (the builder's installed-agent report, and recent runs that died with capacity language), and holds the three-state rule provider_quota is built on: an agent nothing was reported about is unknown, and unknown reads as usable. Nothing is hidden — a provider that cannot answer still appears, disabled, saying why. 18 inline checks in scripts/test/provider-switch.ts. - GET /api/providers — that ranking, once, for every surface. Accepts either the user_projects id or the entity id, because the Feedback row holds one and Control/Terminal hold the other. - ProviderSwitch — "Try <next>" plus a menu of the rest, now the PRIMARY control on a Needs-you / Failed feedback row (Retry steps down beside it), in the Control inbox, and in the Terminal rail. And it sticks: POST /api/feedback/<id>/dispatch takes an `agent`, records it as the project's agentPref, then dispatches on it — no scavenger hunt through project settings. The order is the operator's, not the fleet's: user_preferences.agent_order (migration 0072, nullable and additive) with a reorder list in Settings → Agent. Null means "never stated", and the fleet default applies. Two SSOT repairs the work ran into: - AGENT_FALLBACK_ORDER was defined TWICE (agent-registry.ts and agent-resolution.ts) — the server reroute and the client reroute each read their own copy. agent-registry now re-exports the client-safe leaf. - QUOTA_ALTERNATIVE_AGENTS is derived from that order instead of being a second hand-written list of the same five ids. - TerminalRunView.alternatives is gone; quotaDeath stays as the flag that asks the shared chooser. provider_quota is deliberately NOT an input: it meters the ai-kit inference chain (groq, openrouter) behind Loki's own chat, not the agent CLIs. The agent-CLI equivalent is the run evidence above — observed, never probed. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * fix(providers): never offer the agent the project would actually run on Self-review caught a gap in the chooser's exclusion rule. It read "current" straight off `user_projects.agent_pref`, so a project that has never had a preference set reported no current agent at all — and dispatch does not work that way. Such a project still runs, on DEFAULT_ADAPTER_ID, which means the escape offered from a Claude Code rate limit could be Claude Code. currentProviderFor() answers the question the exclusion is actually asking — which agent just died — in the order the evidence deserves: 1. what this project LAST RAN on (freshest run inside the window). A stored preference can be stale by one switch; a run is what happened. 2. else its stored preference. 3. else the fleet default, because that is what the next dispatch picks. A run on an agent the chooser cannot offer (openclaw) is not "current" — it falls through rather than excluding nothing. Three more checks in scripts/test/provider-switch.ts, 21 total. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
1 parent
6ed5d6edf9
commit
b71941be63
29 files changed
+10344
-123
No files matched your search
@@ -0,0 +1,21 @@
|
||||
-- Migration: user_preferences.agent_order — which provider to reach for next.
|
||||
--
|
||||
-- "Try next provider" needs an order, and until now the only one that existed
|
||||
-- was AGENT_FALLBACK_ORDER, a constant in the source. So the button offered the
|
||||
-- fleet's opinion rather than the operator's: it said "Try Cursor" to someone
|
||||
-- whose Cursor subscription had lapsed, and the only way to express otherwise
|
||||
-- was to set a per-project agent preference, one project at a time, after the
|
||||
-- switch had already gone to the wrong place.
|
||||
--
|
||||
-- One ordered string, not a rank-per-agent table: the only question ever asked
|
||||
-- of this column is "what is the whole order", and a list is how an ordered
|
||||
-- list is spelled.
|
||||
--
|
||||
-- NULL is a real answer and not a missing one — it means the operator never
|
||||
-- stated a preference, and the fleet default applies. Unknown ids inside the
|
||||
-- string are dropped on read (parseProviderOrder), so a retired agent id in an
|
||||
-- old row degrades to "not ranked" rather than breaking the chooser.
|
||||
--
|
||||
-- Nullable and additive. Every existing row keeps its meaning.
|
||||
|
||||
ALTER TABLE "user_preferences" ADD COLUMN IF NOT EXISTS "agent_order" text;
|
||||
File diff suppressed because it is too large.
Load diff
@@ -449,6 +449,13 @@
|
||||
"when": 1789620487077,
|
||||
"tag": "0071_feedback_collaboration",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 65,
|
||||
"version": "7",
|
||||
"when": 1789625943428,
|
||||
"tag": "0072_provider_order",
|
||||
"breakpoints": true
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,251 @@
|
||||
/**
|
||||
* Inline tests for the provider chooser (src/lib/provider-switch.ts).
|
||||
*
|
||||
* This is the policy behind "one tap to a provider that still has quota". The
|
||||
* properties worth pinning are the ones that were WRONG before it existed:
|
||||
*
|
||||
* • the agent that just hit the wall must never be offered as the way out
|
||||
* • an agent the builder never reported installed must not be a one-tap
|
||||
* button that quits a working CLI to launch a missing binary
|
||||
* • a builder that reported NOTHING means unknown, not "all unavailable" —
|
||||
* the control plane with no runner attached must still offer the switch
|
||||
* • a run that failed for a non-quota reason is not evidence about quota
|
||||
* • nothing is ever silently hidden: a provider that cannot answer still
|
||||
* appears, disabled, with the reason
|
||||
*
|
||||
* Run: npx tsx scripts/test/provider-switch.ts
|
||||
*/
|
||||
import assert from "node:assert/strict";
|
||||
import {
|
||||
PROVIDER_SPENT_WINDOW_MS,
|
||||
nextProvider,
|
||||
parseProviderOrder,
|
||||
preferredProviderOrder,
|
||||
currentProviderFor,
|
||||
rankProviders,
|
||||
serializeProviderOrder,
|
||||
spentProviders,
|
||||
} from "@/lib/provider-switch";
|
||||
import { AGENT_FALLBACK_ORDER } from "@/lib/agent-resolution";
|
||||
|
||||
let passed = 0;
|
||||
const check = (label: string, fn: () => void) => {
|
||||
fn();
|
||||
passed += 1;
|
||||
console.log(` ✓ ${label}`);
|
||||
};
|
||||
|
||||
const NOW = Date.parse("2026-09-17T12:00:00.000Z");
|
||||
const ago = (ms: number) => new Date(NOW - ms).toISOString();
|
||||
|
||||
// ── The operator's order ────────────────────────────────────────────────────
|
||||
|
||||
check("no saved order falls back to the fleet default", () => {
|
||||
assert.deepEqual(preferredProviderOrder(null), [...AGENT_FALLBACK_ORDER]);
|
||||
assert.deepEqual(preferredProviderOrder([]), [...AGENT_FALLBACK_ORDER]);
|
||||
});
|
||||
|
||||
check("a saved order wins, and unranked agents follow rather than vanish", () => {
|
||||
const order = preferredProviderOrder(["grok", "codex"]);
|
||||
assert.deepEqual(order.slice(0, 2), ["grok", "codex"]);
|
||||
assert.equal(order.length, AGENT_FALLBACK_ORDER.length, "every agent is still reachable");
|
||||
assert.ok(order.includes("claude"));
|
||||
});
|
||||
|
||||
check("junk and duplicates in a saved order are dropped, not trusted", () => {
|
||||
const order = preferredProviderOrder(["codex", "codex", "not-an-agent", ""]);
|
||||
assert.equal(order[0], "codex");
|
||||
assert.equal(order.filter((id) => id === "codex").length, 1);
|
||||
assert.equal(order.length, AGENT_FALLBACK_ORDER.length);
|
||||
});
|
||||
|
||||
check("the stored string round-trips, and an all-junk list stores as null", () => {
|
||||
assert.equal(serializeProviderOrder(["grok", "claude"]), "grok,claude");
|
||||
assert.deepEqual(parseProviderOrder("grok,claude"), ["grok", "claude"]);
|
||||
assert.equal(parseProviderOrder(""), null);
|
||||
assert.equal(parseProviderOrder(null), null);
|
||||
assert.equal(parseProviderOrder("nonsense"), null);
|
||||
assert.equal(serializeProviderOrder(["nonsense"]), null);
|
||||
});
|
||||
|
||||
// ── The ranking ─────────────────────────────────────────────────────────────
|
||||
|
||||
check("the agent that just died is never offered as the way out", () => {
|
||||
const options = rankProviders({ current: "claude" });
|
||||
assert.equal(
|
||||
options.some((o) => o.id === "claude"),
|
||||
false,
|
||||
);
|
||||
assert.equal(nextProvider(options)?.id !== "claude", true);
|
||||
});
|
||||
|
||||
check("the one-tap target is the first USABLE provider in the operator's order", () => {
|
||||
const options = rankProviders({
|
||||
current: "claude",
|
||||
order: ["grok", "codex", "cursor"],
|
||||
installed: ["claude", "codex", "cursor"],
|
||||
});
|
||||
// grok is ranked first but is not installed, so the tap goes to codex.
|
||||
assert.equal(nextProvider(options)?.id, "codex");
|
||||
});
|
||||
|
||||
check("an uninstalled provider still appears — disabled, with the reason", () => {
|
||||
const options = rankProviders({ current: "claude", installed: ["codex"] });
|
||||
const grok = options.find((o) => o.id === "grok");
|
||||
assert.ok(grok, "grok is listed rather than hidden");
|
||||
assert.equal(grok.usable, false);
|
||||
assert.equal(grok.block, "not-installed");
|
||||
assert.match(grok.reason ?? "", /not installed/i);
|
||||
});
|
||||
|
||||
check("NOTHING reported is unknown, not unavailable", () => {
|
||||
// A control plane with no runner attached knows nothing about any agent.
|
||||
// Drawing that as "every provider unavailable" disables the one control the
|
||||
// operator came for.
|
||||
for (const installed of [null, undefined, []]) {
|
||||
const options = rankProviders({ current: "claude", installed });
|
||||
assert.ok(nextProvider(options), "a switch is still offered");
|
||||
assert.equal(
|
||||
options.every((o) => o.usable),
|
||||
true,
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
check("a provider observed out of quota is excluded, and says so", () => {
|
||||
const options = rankProviders({
|
||||
current: "claude",
|
||||
order: ["codex", "grok"],
|
||||
spent: { codex: "Codex hit a limit 5m ago — it may still be spent." },
|
||||
});
|
||||
const codex = options.find((o) => o.id === "codex");
|
||||
assert.equal(codex?.usable, false);
|
||||
assert.equal(codex?.block, "spent");
|
||||
assert.equal(nextProvider(options)?.id, "grok");
|
||||
});
|
||||
|
||||
check("usable providers sort ahead of the ones that cannot answer", () => {
|
||||
const options = rankProviders({ current: "claude", installed: ["grok"] });
|
||||
const firstUnusable = options.findIndex((o) => !o.usable);
|
||||
const lastUsable = options.map((o) => o.usable).lastIndexOf(true);
|
||||
assert.ok(lastUsable < firstUnusable, "no usable row sits below an unusable one");
|
||||
});
|
||||
|
||||
check("nothing usable is a real answer — null, not a button that cannot work", () => {
|
||||
const options = rankProviders({ current: "claude", installed: ["claude"] });
|
||||
assert.equal(nextProvider(options), null);
|
||||
assert.ok(options.length > 0, "the reasons are still there to read");
|
||||
});
|
||||
|
||||
// ── Which agent is "current" ────────────────────────────────────────────────
|
||||
|
||||
check("a project with no stored preference still has a current agent", () => {
|
||||
// The gap this closes: agentPref null read as "nothing to exclude", so the
|
||||
// chooser offered Claude Code as the escape from a Claude Code rate limit.
|
||||
const current = currentProviderFor({ agentPref: null, defaultAdapter: "claude" });
|
||||
assert.equal(current, "claude");
|
||||
assert.equal(
|
||||
rankProviders({ current }).some((o) => o.id === "claude"),
|
||||
false,
|
||||
);
|
||||
});
|
||||
|
||||
check("what it last RAN on outranks what it is configured to run on", () => {
|
||||
const current = currentProviderFor({
|
||||
agentPref: "claude",
|
||||
projectRuns: [{ adapter: "grok" }, { adapter: "claude" }],
|
||||
defaultAdapter: "claude",
|
||||
});
|
||||
assert.equal(current, "grok", "freshest run wins — that is the one that just died");
|
||||
});
|
||||
|
||||
check("a run on an agent the chooser cannot offer is not 'current'", () => {
|
||||
const current = currentProviderFor({
|
||||
agentPref: "codex",
|
||||
projectRuns: [{ adapter: "openclaw" }],
|
||||
defaultAdapter: "claude",
|
||||
});
|
||||
assert.equal(current, "codex", "openclaw is not switchable — fall through to the preference");
|
||||
});
|
||||
|
||||
// ── The evidence ────────────────────────────────────────────────────────────
|
||||
|
||||
check("a recent capacity wall marks that provider spent", () => {
|
||||
const spent = spentProviders(
|
||||
[{ adapter: "codex", error: "rate limit exceeded", startedAt: ago(5 * 60_000) }],
|
||||
NOW,
|
||||
);
|
||||
assert.ok(spent.codex);
|
||||
assert.match(spent.codex, /Codex/);
|
||||
});
|
||||
|
||||
check("a failure that is not about capacity is not evidence about quota", () => {
|
||||
const spent = spentProviders(
|
||||
[{ adapter: "codex", error: "ENOENT: no such file or directory", startedAt: ago(60_000) }],
|
||||
NOW,
|
||||
);
|
||||
assert.deepEqual(spent, {}, "a crash on a bad path is not an empty tank");
|
||||
});
|
||||
|
||||
check("a successful run leaves no mark", () => {
|
||||
assert.deepEqual(spentProviders([{ adapter: "codex", startedAt: ago(60_000) }], NOW), {});
|
||||
assert.deepEqual(
|
||||
spentProviders([{ adapter: "codex", error: null, startedAt: ago(60_000) }], NOW),
|
||||
{},
|
||||
);
|
||||
});
|
||||
|
||||
check("a wall outside the window has expired — quota refills", () => {
|
||||
const spent = spentProviders(
|
||||
[
|
||||
{
|
||||
adapter: "grok",
|
||||
error: "quota exceeded",
|
||||
startedAt: ago(PROVIDER_SPENT_WINDOW_MS + 60_000),
|
||||
},
|
||||
],
|
||||
NOW,
|
||||
);
|
||||
assert.deepEqual(spent, {});
|
||||
});
|
||||
|
||||
check("an unknown adapter in the run log cannot inject a row", () => {
|
||||
const spent = spentProviders(
|
||||
[{ adapter: "openclaw", error: "rate limit", startedAt: ago(60_000) }],
|
||||
NOW,
|
||||
);
|
||||
assert.deepEqual(spent, {}, "only agents the chooser can offer may be marked spent");
|
||||
});
|
||||
|
||||
check("the freshest wall per provider wins, and older ones do not overwrite it", () => {
|
||||
const spent = spentProviders(
|
||||
[
|
||||
{ adapter: "codex", error: "rate limit", startedAt: ago(2 * 60_000) },
|
||||
{ adapter: "codex", error: "usage limit", startedAt: ago(40 * 60_000) },
|
||||
],
|
||||
NOW,
|
||||
);
|
||||
assert.match(spent.codex ?? "", /2m ago/);
|
||||
});
|
||||
|
||||
// ── End to end: the walk the report asks for ────────────────────────────────
|
||||
|
||||
check("a rate-limited Claude run offers one tap to a provider that can answer", () => {
|
||||
const runs = [
|
||||
{ adapter: "claude", error: "Claude usage limit reached", startedAt: ago(3 * 60_000) },
|
||||
{ adapter: "cursor", error: "rate limit exceeded", startedAt: ago(20 * 60_000) },
|
||||
];
|
||||
const options = rankProviders({
|
||||
current: "claude",
|
||||
order: ["cursor", "codex", "grok"],
|
||||
installed: ["claude", "cursor", "codex"],
|
||||
spent: spentProviders(runs, NOW),
|
||||
});
|
||||
const next = nextProvider(options);
|
||||
assert.equal(next?.id, "codex", "cursor is spent, grok is not installed → codex");
|
||||
// And the two that cannot answer still say why.
|
||||
assert.equal(options.find((o) => o.id === "cursor")?.block, "spent");
|
||||
assert.equal(options.find((o) => o.id === "grok")?.block, "not-installed");
|
||||
});
|
||||
|
||||
console.log(`\nprovider-switch: ${passed} checks passed`);
|
||||
@@ -1,15 +1,16 @@
|
||||
/**
|
||||
* Terminal Loki rail: commentary from work-phase, not a log dump; quota death
|
||||
* offers Claude Code / Codex / Cursor / Grok / Antigravity and hides the dead agent.
|
||||
* Terminal Loki rail: commentary from work-phase, not a log dump. Quota death is
|
||||
* now a FLAG here — which providers to offer, in what order, and whether each
|
||||
* can actually answer belongs to src/lib/provider-switch.ts and its own suite.
|
||||
*
|
||||
* Run: npx tsx scripts/test/terminal-run-view.ts
|
||||
*/
|
||||
import assert from "node:assert/strict";
|
||||
import {
|
||||
buildTerminalRunView,
|
||||
isQuotaDeath,
|
||||
nextActionForWork,
|
||||
presentTerminalRun,
|
||||
quotaDeathAlternatives,
|
||||
} from "@/lib/terminal-run-view";
|
||||
import { FEEDBACK_WORK_PHASE, WAITING_ON, type FeedbackWorkView } from "@/lib/feedback/work-phase";
|
||||
import { fleetSurfaceHref } from "@/lib/fleet-context";
|
||||
@@ -19,6 +20,7 @@ import {
|
||||
capacityFailureFromScreen,
|
||||
shouldReplacePtyAgent,
|
||||
} from "../../desktop/src/main/pty-runtime";
|
||||
import { AGENT_FALLBACK_ORDER } from "@/lib/agent-resolution";
|
||||
|
||||
let passed = 0;
|
||||
const check = (label: string, fn: () => void) => {
|
||||
@@ -37,39 +39,13 @@ const work = (over: Partial<FeedbackWorkView> = {}): FeedbackWorkView => ({
|
||||
});
|
||||
|
||||
check("quota language on the diagnostic is quota death", () => {
|
||||
const alts = quotaDeathAlternatives({
|
||||
diagnostic: "Claude rate limit: out of tokens until reset",
|
||||
currentAgent: "claude",
|
||||
});
|
||||
assert.ok(alts);
|
||||
assert.deepEqual(
|
||||
alts.map((a) => a.id),
|
||||
["codex", "cursor", "grok", "gemini"],
|
||||
);
|
||||
assert.equal(alts.find((a) => a.id === "gemini")?.label, "Antigravity");
|
||||
assert.equal(
|
||||
alts.some((a) => a.id === "claude" || a.label === "Hermes"),
|
||||
false,
|
||||
"dead agent and Hermes stay out of the chooser",
|
||||
);
|
||||
});
|
||||
|
||||
check("the dead agent is hidden from the chooser", () => {
|
||||
const alts = quotaDeathAlternatives({
|
||||
error: "insufficient quota",
|
||||
currentAgent: "grok",
|
||||
});
|
||||
assert.ok(alts);
|
||||
assert.equal(
|
||||
alts.some((a) => a.id === "grok"),
|
||||
false,
|
||||
);
|
||||
assert.ok(alts.some((a) => a.id === "cursor"));
|
||||
assert.equal(isQuotaDeath({ diagnostic: "Claude rate limit: out of tokens until reset" }), true);
|
||||
assert.equal(isQuotaDeath({ error: "insufficient quota" }), true);
|
||||
});
|
||||
|
||||
check("silence is not quota death", () => {
|
||||
assert.equal(quotaDeathAlternatives({ diagnostic: "Waiting for first output" }), null);
|
||||
assert.equal(quotaDeathAlternatives({ diagnostic: null, error: null }), null);
|
||||
assert.equal(isQuotaDeath({ diagnostic: "Waiting for first output" }), false);
|
||||
assert.equal(isQuotaDeath({ diagnostic: null, error: null }), false);
|
||||
});
|
||||
|
||||
check("a quota redraw is a blocker, not generation evidence", () => {
|
||||
@@ -98,8 +74,12 @@ check("next action prefers the queue reason over a badge", () => {
|
||||
);
|
||||
});
|
||||
|
||||
check("quota death overrides the queue reason with a chooser sentence", () => {
|
||||
assert.match(nextActionForWork(work({ queueReason: "Retry" }), true), /Claude Code|Codex|Grok/);
|
||||
check("quota death overrides the queue reason, without naming providers", () => {
|
||||
const line = nextActionForWork(work({ queueReason: "Retry" }), true);
|
||||
assert.match(line, /switch to a provider/i);
|
||||
// The rail's own chooser says WHICH — a sentence that named them went stale
|
||||
// the moment the chooser started filtering to what is installed.
|
||||
assert.doesNotMatch(line, /Claude Code|Codex|Cursor|Grok|Antigravity/);
|
||||
});
|
||||
|
||||
check("the view is phase + next action, not an event trail", () => {
|
||||
@@ -114,14 +94,13 @@ check("the view is phase + next action, not an event trail", () => {
|
||||
diagnostic: "rate limit: out of tokens",
|
||||
lastActivityAt: "2026-09-16T10:00:00.000Z",
|
||||
}),
|
||||
currentAgent: "claude",
|
||||
error: "rate limit",
|
||||
});
|
||||
assert.equal(view.runId, "run-1");
|
||||
assert.equal(view.stalled, true);
|
||||
assert.equal(view.quotaDeath, true);
|
||||
assert.equal(view.alternatives.length, 4);
|
||||
assert.match(view.nextAction, /Claude Code|Codex|Antigravity|Grok|Cursor/);
|
||||
assert.equal("alternatives" in view, false, "the ranking belongs to /api/providers now");
|
||||
assert.match(view.nextAction, /switch to a provider/i);
|
||||
assert.equal("events" in view, false);
|
||||
});
|
||||
|
||||
@@ -148,9 +127,20 @@ check("empty Terminal names Fleet Runner vs Kitty", () => {
|
||||
});
|
||||
|
||||
check("quota chooser is all coding agents, never Hermes", () => {
|
||||
// Membership, not sequence: the chooser's ORDER is now the operator's
|
||||
// preference (user_preferences.agent_order), and the list is derived from
|
||||
// AGENT_FALLBACK_ORDER so the two can never disagree about which agents exist.
|
||||
assert.deepEqual([...QUOTA_ALTERNATIVE_AGENTS.map((a) => a.id)].sort(), [
|
||||
"claude",
|
||||
"codex",
|
||||
"cursor",
|
||||
"gemini",
|
||||
"grok",
|
||||
]);
|
||||
assert.deepEqual(
|
||||
QUOTA_ALTERNATIVE_AGENTS.map((a) => a.id),
|
||||
["claude", "codex", "cursor", "grok", "gemini"],
|
||||
[...AGENT_FALLBACK_ORDER],
|
||||
"derived from the fallback order, not a second hand-written list",
|
||||
);
|
||||
assert.equal(QUOTA_ALTERNATIVE_AGENTS.find((a) => a.id === "gemini")?.label, "Antigravity");
|
||||
assert.equal(QUOTA_ALTERNATIVE_AGENTS.find((a) => a.id === "claude")?.label, "Claude Code");
|
||||
|
||||
@@ -49,6 +49,7 @@ export default async function SettingsPage() {
|
||||
currentCityUntil: null,
|
||||
writingVoice: null,
|
||||
memoryEnabled: true,
|
||||
agentOrder: null,
|
||||
}
|
||||
}
|
||||
projects={projects}
|
||||
|
||||
@@ -11,6 +11,8 @@ import { runToFeedbackSnapshot } from "@/lib/feedback/attach-work";
|
||||
import { getCurrentClaudeSessionForProject } from "@/db/queries/agent-sessions";
|
||||
import { DEFAULT_ADAPTER_ID, ORCHESTRATION_ADAPTER_IDS, type AdapterId } from "@/lib/orchestration";
|
||||
import { feedbackInjectAccepted } from "@/lib/feedback/dispatch-accept";
|
||||
import { isQuotaAlternativeId } from "@/config/quota-alternatives";
|
||||
import { updateUserProject } from "@/db/queries/user-projects";
|
||||
|
||||
/**
|
||||
* One-click Implement: queue a scoped agent run via injectPrompt.
|
||||
@@ -25,6 +27,17 @@ import { feedbackInjectAccepted } from "@/lib/feedback/dispatch-accept";
|
||||
|
||||
const DispatchBody = z.object({
|
||||
note: z.string().trim().max(500).optional(),
|
||||
/**
|
||||
* Switch provider and retry, in one tap.
|
||||
*
|
||||
* The whole point of the field is that it PERSISTS: a retry that ran on a
|
||||
* different agent but left `agentPref` pointing at the one that just hit a
|
||||
* rate limit sent the next dispatch straight back into the wall, and the
|
||||
* operator had to find the preference in project settings to make it stick.
|
||||
* So this writes the project's preference and then dispatches on it — one
|
||||
* decision recorded once, in the place every other dispatch path reads.
|
||||
*/
|
||||
agent: z.string().trim().max(40).optional(),
|
||||
});
|
||||
|
||||
/** Adapters Implement may start. openclaw is orchestration-listed but not launchable. */
|
||||
@@ -93,7 +106,19 @@ export async function POST(req: NextRequest, { params }: { params: Promise<{ id:
|
||||
}
|
||||
}
|
||||
|
||||
const adapter = resolveImplementAdapter(row.agentPref);
|
||||
// Provider switch: validate against the chooser's own id list, record it as
|
||||
// the project's preference, then dispatch on it. Rejected rather than
|
||||
// silently defaulted — a one-tap switch that quietly re-ran the spent agent
|
||||
// would look exactly like a switch that worked.
|
||||
const requestedAgent = dataOrResp.agent;
|
||||
if (requestedAgent && !isQuotaAlternativeId(requestedAgent)) {
|
||||
return jsonError(`Unknown provider: ${requestedAgent}`, 400);
|
||||
}
|
||||
if (requestedAgent && requestedAgent !== row.agentPref) {
|
||||
await updateUserProject(row.userProjectId, executionUserId, { agentPref: requestedAgent });
|
||||
}
|
||||
|
||||
const adapter = resolveImplementAdapter(requestedAgent ?? row.agentPref);
|
||||
const currentSession =
|
||||
adapter === "claude"
|
||||
? await getCurrentClaudeSessionForProject(
|
||||
|
||||
@@ -2,6 +2,7 @@ import { NextRequest, NextResponse } from "next/server";
|
||||
import { readJsonBody, z } from "@/lib/api/route-helpers";
|
||||
import { getSessionUserId } from "@/lib/session";
|
||||
import { getUserPreferences, upsertUserPreferences } from "@/db/queries/user-preferences";
|
||||
import { PROVIDER_IDS, serializeProviderOrder } from "@/lib/provider-switch";
|
||||
|
||||
const SUPPORTED_TIMEZONES = new Set(Intl.supportedValuesOf("timeZone"));
|
||||
|
||||
@@ -56,6 +57,14 @@ const PatchBody = z.object({
|
||||
.optional(),
|
||||
writingVoice: z.string().trim().max(600).nullable().optional(),
|
||||
memoryEnabled: z.boolean().optional(),
|
||||
// Accepted as a LIST and stored as one string, so the client never has to
|
||||
// know the storage shape and an unknown id can never reach the column.
|
||||
agentOrder: z
|
||||
.array(z.string())
|
||||
.max(PROVIDER_IDS.length)
|
||||
.transform(serializeProviderOrder)
|
||||
.nullable()
|
||||
.optional(),
|
||||
});
|
||||
|
||||
export async function GET() {
|
||||
|
||||
@@ -0,0 +1,95 @@
|
||||
/**
|
||||
* GET /api/providers?project=<userProjectId>
|
||||
*
|
||||
* The one answer to "who else could do this work right now" — ordered by the
|
||||
* operator's preference, filtered to providers that can actually answer, and
|
||||
* shared by every surface that shows a blocked run: the Feedback row, the
|
||||
* Control inbox, and the Terminal rail. One chooser, one ranking; three
|
||||
* surfaces that disagree about which provider to try next is the bug this
|
||||
* route exists to make impossible.
|
||||
*
|
||||
* Deliberately NOT part of /api/control or /api/terminal/context. Both are
|
||||
* per-surface assemblies on polling cadences, and a row that is Needs-you needs
|
||||
* this list once, when the operator looks at it.
|
||||
*/
|
||||
import { jsonOk, jsonError, z } from "@/lib/api/route-helpers";
|
||||
import { getApiUserId } from "@/lib/session";
|
||||
import { getUserProject, getUserProjectByEntityId } from "@/db/queries/user-projects";
|
||||
import { getUserPreferences } from "@/db/queries/user-preferences";
|
||||
import { getRuntimeSnapshot } from "@/db/queries/runtime-snapshots";
|
||||
import { listRecentRuns } from "@/db/queries/orchestration-runs";
|
||||
import { DEFAULT_ADAPTER_ID } from "@/lib/orchestration";
|
||||
import {
|
||||
PROVIDER_SPENT_WINDOW_MS,
|
||||
currentProviderFor,
|
||||
nextProvider,
|
||||
parseProviderOrder,
|
||||
rankProviders,
|
||||
spentProviders,
|
||||
} from "@/lib/provider-switch";
|
||||
|
||||
export const runtime = "nodejs";
|
||||
|
||||
const Query = z.object({ project: z.string().uuid().optional() });
|
||||
|
||||
/**
|
||||
* Callers hold different ids for the same project. The Feedback row knows the
|
||||
* ENTITY id (feedback is filed against entities); Control and Terminal hold the
|
||||
* user_projects id. Rather than make every caller look the other one up — or
|
||||
* make the chooser silently answer for "no project", which is how the spent
|
||||
* agent ends up offered as an alternative to itself — resolve either here.
|
||||
*/
|
||||
async function resolveProject(userId: string, id: string | undefined) {
|
||||
if (!id) return null;
|
||||
return (await getUserProject(id, userId)) ?? (await getUserProjectByEntityId(userId, id));
|
||||
}
|
||||
|
||||
export async function GET(req: Request) {
|
||||
const userId = await getApiUserId();
|
||||
if (!userId) return jsonError("Unauthorized", 401);
|
||||
|
||||
const parsed = Query.safeParse({
|
||||
project: new URL(req.url).searchParams.get("project") ?? undefined,
|
||||
});
|
||||
if (!parsed.success) return jsonError("Invalid project id", 400);
|
||||
|
||||
const project = await resolveProject(userId, parsed.data.project);
|
||||
|
||||
const [prefs, snapshot, runs] = await Promise.all([
|
||||
getUserPreferences(userId).catch(() => null),
|
||||
getRuntimeSnapshot(userId).catch(() => null),
|
||||
// Enough runs to see one capacity wall per agent inside the window; the
|
||||
// query is capped at 50 and the window does the rest of the filtering.
|
||||
listRecentRuns(userId, { limit: 50, sinceMs: PROVIDER_SPENT_WINDOW_MS }).catch(() => []),
|
||||
]);
|
||||
|
||||
// What this project would run on right now — see currentProviderFor. A
|
||||
// project with no stored preference still dispatches (on the default
|
||||
// adapter), and treating that as "no current agent" is how the chooser ended
|
||||
// up offering Claude Code as the escape from a Claude Code rate limit.
|
||||
const projectRuns = project
|
||||
? runs.filter((r) => r.projectKey.toLowerCase() === project.name.toLowerCase())
|
||||
: [];
|
||||
const current = project
|
||||
? currentProviderFor({
|
||||
agentPref: project.agentPref,
|
||||
projectRuns,
|
||||
defaultAdapter: DEFAULT_ADAPTER_ID,
|
||||
})
|
||||
: null;
|
||||
const spent = spentProviders(runs);
|
||||
const options = rankProviders({
|
||||
current,
|
||||
order: parseProviderOrder(prefs?.agentOrder ?? null),
|
||||
installed: snapshot?.installedAgents ?? null,
|
||||
spent,
|
||||
});
|
||||
|
||||
return jsonOk({
|
||||
current,
|
||||
options,
|
||||
next: nextProvider(options),
|
||||
/** False when no builder has reported a capability list — unknown, not empty. */
|
||||
installedKnown: (snapshot?.installedAgents ?? []).length > 0,
|
||||
});
|
||||
}
|
||||
@@ -43,6 +43,8 @@ export type TerminalTabContext = {
|
||||
agentPref: string | null;
|
||||
/** Registered project this tab resolves to — by name, else by pane cwd. */
|
||||
projectName: string | null;
|
||||
/** user_projects id for that project — what /api/providers scopes on. */
|
||||
projectId: string | null;
|
||||
/** Agent CLIs actually running in this tab's panes ("claude", "grok", …),
|
||||
* from the runner's pane topology. Empty when unknown or shell-only. */
|
||||
liveAgents: string[];
|
||||
@@ -116,6 +118,7 @@ export async function GET(req: Request) {
|
||||
dir: project?.dirPath ?? null,
|
||||
agentPref: project?.agentPref ?? null,
|
||||
projectName: project?.name ?? null,
|
||||
projectId: project?.id ?? null,
|
||||
liveAgents,
|
||||
};
|
||||
});
|
||||
|
||||
@@ -69,7 +69,6 @@ export async function GET(req: NextRequest) {
|
||||
runId: run.id,
|
||||
projectKey: run.projectKey,
|
||||
work,
|
||||
currentAgent: run.adapter,
|
||||
lastProgressAt: snap?.lastProgressAt ?? null,
|
||||
error: snap?.error ?? null,
|
||||
});
|
||||
|
||||
@@ -0,0 +1,107 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import { ChevronDown, Loader2, Repeat2 } from "lucide-react";
|
||||
import { useFetch } from "@/hooks/use-fetch";
|
||||
import { AgentSwitcherPopover } from "@/components/control/agent-switcher-popover";
|
||||
import { PROVIDER_BLOCK_NOTE, type ProviderOption } from "@/lib/provider-switch";
|
||||
|
||||
/**
|
||||
* "Try next provider" — the one control, wherever a run is blocked.
|
||||
*
|
||||
* Rendered on the Feedback row, in the Control inbox, and in the Terminal rail,
|
||||
* all from `/api/providers`, so the three surfaces cannot recommend different
|
||||
* agents for the same stuck project. The primary button is the operator's
|
||||
* FIRST preferred provider that can actually answer; the caret opens the rest,
|
||||
* with the ones that cannot answer still listed and disabled, saying why.
|
||||
*
|
||||
* It does not itself perform the switch: on Feedback that means re-dispatching
|
||||
* the report on a new agent, in Terminal it means swapping the live PTY. The
|
||||
* caller owns the verb; this owns the choice.
|
||||
*/
|
||||
export type ProviderSwitchResponse = {
|
||||
current: string | null;
|
||||
options: ProviderOption[];
|
||||
next: ProviderOption | null;
|
||||
installedKnown: boolean;
|
||||
};
|
||||
|
||||
export function ProviderSwitch({
|
||||
projectId,
|
||||
busy,
|
||||
compact,
|
||||
hint = "Runs this again on the provider you pick, and remembers it for this project.",
|
||||
onSwitch,
|
||||
}: {
|
||||
/** user_projects id — scopes "current" so the spent agent is never offered. */
|
||||
projectId: string | null;
|
||||
busy?: boolean;
|
||||
/** Inbox density: smaller buttons, same behaviour. */
|
||||
compact?: boolean;
|
||||
/** What picking one will do, in the caller's own terms. */
|
||||
hint?: string;
|
||||
onSwitch: (agentId: string) => void;
|
||||
}) {
|
||||
const [menuOpen, setMenuOpen] = useState(false);
|
||||
const { data, loading } = useFetch<ProviderSwitchResponse>(
|
||||
projectId ? `/api/providers?project=${projectId}` : "/api/providers",
|
||||
);
|
||||
|
||||
// Nothing to offer is a real state and must not render an empty control:
|
||||
// every alternative is spent or uninstalled, and the honest answer is the
|
||||
// reason on the row above, not a button that cannot do anything.
|
||||
const next = data?.next ?? null;
|
||||
if (loading && !data) {
|
||||
return (
|
||||
<span className="inline-flex items-center gap-1 text-micro text-text-muted">
|
||||
<Loader2 className="ui-spinner-xs" /> providers…
|
||||
</span>
|
||||
);
|
||||
}
|
||||
if (!next) return null;
|
||||
|
||||
const btnClass = compact ? "ui-btn-save ui-btn-sm gap-1.5" : "ui-btn-save gap-1.5";
|
||||
return (
|
||||
<span className="relative inline-flex items-center">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => onSwitch(next.id)}
|
||||
disabled={busy}
|
||||
className={btnClass}
|
||||
title={`Run this again on ${next.label} and remember it for this project`}
|
||||
>
|
||||
{busy ? <Loader2 className="ui-spinner-xs" /> : <Repeat2 className="h-3 w-3" />}
|
||||
Try {next.label}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setMenuOpen((v) => !v)}
|
||||
disabled={busy}
|
||||
className="ui-btn-icon"
|
||||
title="Choose a different provider"
|
||||
aria-label="Choose a different provider"
|
||||
aria-expanded={menuOpen}
|
||||
>
|
||||
<ChevronDown className="h-3.5 w-3.5" />
|
||||
</button>
|
||||
{menuOpen && (
|
||||
<AgentSwitcherPopover
|
||||
agents={(data?.options ?? []).map((o) => ({
|
||||
id: o.id,
|
||||
label: o.label,
|
||||
available: o.usable,
|
||||
...(o.reason ? { availabilityReason: o.reason } : {}),
|
||||
...(o.block ? { unavailableNote: PROVIDER_BLOCK_NOTE[o.block] } : {}),
|
||||
}))}
|
||||
activeAgentId={data?.current ?? ""}
|
||||
title="Try another provider"
|
||||
hint={hint}
|
||||
onSwitch={(id) => {
|
||||
if (id) onSwitch(id);
|
||||
}}
|
||||
onClose={() => setMenuOpen(false)}
|
||||
/>
|
||||
)}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
@@ -26,6 +26,7 @@ import { deriveFeedbackWork, FEEDBACK_WORK_PHASE } from "@/lib/feedback/work-pha
|
||||
import { fleetSurfaceHref } from "@/lib/fleet-context";
|
||||
import { livePageHref } from "@/lib/feedback/fix-shipping";
|
||||
import { FeedbackWorkBadge } from "@/components/feedback/FeedbackWorkBadge";
|
||||
import { ProviderSwitch } from "@/components/agents/ProviderSwitch";
|
||||
import type { FeedbackListItemWithWork } from "@/lib/feedback/attach-work";
|
||||
import type { ProjectFeedbackSummary } from "@/db/queries/site-feedback";
|
||||
import type { WidgetCoverageItem } from "@/db/queries/widget-tokens";
|
||||
@@ -572,6 +573,23 @@ function FeedbackTriage({
|
||||
)}
|
||||
</div>
|
||||
<ActionRail>
|
||||
{/* Same chooser the Feedback row and the Terminal rail use, so
|
||||
a blocked run is one tap from a provider that can answer
|
||||
without leaving Control for deep project settings. */}
|
||||
{broken && (
|
||||
<ProviderSwitch
|
||||
projectId={projectId}
|
||||
busy={busyId === f.id || batchBusy}
|
||||
compact
|
||||
onSwitch={(agent) =>
|
||||
act(
|
||||
f.id,
|
||||
() => postJson(`/api/feedback/${f.id}/dispatch`, { agent }),
|
||||
"Provider switch failed",
|
||||
)
|
||||
}
|
||||
/>
|
||||
)}
|
||||
{(notStarted || broken) && (
|
||||
<button
|
||||
type="button"
|
||||
|
||||
@@ -16,6 +16,14 @@ export type AgentEntry = {
|
||||
/** From the runner capability report. `undefined` = unknown (treated as usable). */
|
||||
available?: boolean;
|
||||
availabilityReason?: string;
|
||||
/**
|
||||
* Short suffix for a disabled row. Defaults to "not installed", which is the
|
||||
* only reason this popover knew about when it was the agent switcher alone.
|
||||
* The provider chooser also disables agents that ARE installed and merely out
|
||||
* of quota, and labelling those "(not installed)" was a false claim sitting
|
||||
* directly above a sentence that said otherwise.
|
||||
*/
|
||||
unavailableNote?: string;
|
||||
modelSuggestions?: string[];
|
||||
};
|
||||
|
||||
@@ -24,11 +32,17 @@ export function AgentSwitcherPopover({
|
||||
activeAgentId,
|
||||
onSwitch,
|
||||
onClose,
|
||||
title = "Switch agent",
|
||||
hint = "Quits the current CLI and launches the new one — no /quit in terminal.",
|
||||
}: {
|
||||
agents: AgentEntry[];
|
||||
activeAgentId: string;
|
||||
onSwitch: (agentId: string | null) => void;
|
||||
onClose: () => void;
|
||||
/** Heading. The default describes a LIVE tab swap; the provider chooser on a
|
||||
* queued run is not swapping anything yet, so it says what it actually does. */
|
||||
title?: string;
|
||||
hint?: string;
|
||||
}) {
|
||||
const ref = useRef<HTMLDivElement>(null);
|
||||
|
||||
@@ -52,12 +66,8 @@ export function AgentSwitcherPopover({
|
||||
ref={ref}
|
||||
className="absolute left-0 top-full z-50 mt-1.5 min-w-[130px] max-w-[calc(100vw-1.5rem)] rounded-xl border border-border-default bg-surface-overlay py-1.5 shadow-card"
|
||||
>
|
||||
<p className="px-3 pb-1 pt-0.5 text-micro uppercase tracking-wide text-text-muted">
|
||||
Switch agent
|
||||
</p>
|
||||
<p className="px-3 pb-1.5 text-micro leading-snug text-text-muted">
|
||||
Quits the current CLI and launches the new one — no /quit in terminal.
|
||||
</p>
|
||||
<p className="px-3 pb-1 pt-0.5 text-micro uppercase tracking-wide text-text-muted">{title}</p>
|
||||
<p className="px-3 pb-1.5 text-micro leading-snug text-text-muted">{hint}</p>
|
||||
{agents.map((agent) => {
|
||||
const isActive = agent.id === activeAgentId;
|
||||
// undefined availability = unknown (no runner report) → treat as usable;
|
||||
@@ -87,7 +97,7 @@ export function AgentSwitcherPopover({
|
||||
{isActive && <Check className="h-3 w-3 shrink-0" />}
|
||||
<span className={cn(isActive && "font-medium", !isActive && !unavailable && "pl-5")}>
|
||||
{agent.label}
|
||||
{unavailable && " (not installed)"}
|
||||
{unavailable && ` (${agent.unavailableNote ?? "not installed"})`}
|
||||
</span>
|
||||
</span>
|
||||
{unavailable && agent.availabilityReason && (
|
||||
|
||||
@@ -404,7 +404,7 @@ function Row({
|
||||
}: {
|
||||
f: InboxItem;
|
||||
busyId: string | null;
|
||||
dispatchFix: (id: string, note?: string) => void;
|
||||
dispatchFix: (id: string, opts?: { note?: string; agent?: string }) => void;
|
||||
setStatus: (id: string, status: FeedbackStatus) => void;
|
||||
feature: (id: string, featured: boolean) => void;
|
||||
/** On a project-scoped view the project is the heading, not a per-row chip. */
|
||||
@@ -416,7 +416,7 @@ function Row({
|
||||
projectName={f.projectName}
|
||||
project={hideProject ? null : { id: f.projectId, name: f.projectName }}
|
||||
busy={busyId === f.id}
|
||||
onDispatch={(note) => dispatchFix(f.id, note)}
|
||||
onDispatch={(opts) => dispatchFix(f.id, opts ?? {})}
|
||||
onResolve={() => setStatus(f.id, FEEDBACK_STATUS.RESOLVED)}
|
||||
onArchive={() => setStatus(f.id, FEEDBACK_STATUS.ARCHIVED)}
|
||||
onReopen={() => setStatus(f.id, FEEDBACK_STATUS.NEW)}
|
||||
|
||||
@@ -10,6 +10,7 @@ import type { FeedbackListItem } from "@/db/queries/site-feedback";
|
||||
import type { FeedbackListItemWithWork } from "@/lib/feedback/attach-work";
|
||||
import { FeedbackWorkBadge } from "@/components/feedback/FeedbackWorkBadge";
|
||||
import { FeedbackWatchButton, FeedbackWatchPanel } from "@/components/feedback/FeedbackWatch";
|
||||
import { ProviderSwitch } from "@/components/agents/ProviderSwitch";
|
||||
import { fleetSurfaceHref } from "@/lib/fleet-context";
|
||||
import { livePageHref } from "@/lib/feedback/fix-shipping";
|
||||
|
||||
@@ -37,7 +38,8 @@ export function FeedbackItemRow({
|
||||
/** Set on cross-project surfaces: renders a project chip linking home. */
|
||||
project?: { id: string; name: string } | null;
|
||||
busy: boolean;
|
||||
onDispatch: (note?: string) => void;
|
||||
/** Queue the fix. `agent` switches provider and records the preference. */
|
||||
onDispatch: (opts?: { note?: string; agent?: string }) => void;
|
||||
onResolve: () => void;
|
||||
onArchive: () => void;
|
||||
onReopen: () => void;
|
||||
@@ -87,9 +89,9 @@ export function FeedbackItemRow({
|
||||
setFollowAfterImplement(true);
|
||||
setWatchOpen(true);
|
||||
};
|
||||
const startImplement = (note?: string) => {
|
||||
const startImplement = (opts?: { note?: string; agent?: string }) => {
|
||||
markFollowing();
|
||||
onDispatch(note);
|
||||
onDispatch(opts);
|
||||
};
|
||||
// Somewhere for an agent to work. Rows from the per-project inbox carry no
|
||||
// flag and keep the one-click Implement; the server refuses the same case.
|
||||
@@ -300,12 +302,22 @@ export function FeedbackItemRow({
|
||||
{showWatch && (
|
||||
<FeedbackWatchButton open={watchOpen} onToggle={() => setWatchOpen((v) => !v)} />
|
||||
)}
|
||||
{/* A run that needs you is most often a run that ran out of
|
||||
quota, and the fix is a different provider — not the same one
|
||||
again. So the switch is the PRIMARY control here and Retry
|
||||
steps down beside it. ProviderSwitch renders nothing when it
|
||||
has no provider that can answer, and Retry is promoted back. */}
|
||||
<ProviderSwitch
|
||||
projectId={f.projectId}
|
||||
busy={busy}
|
||||
onSwitch={(agent) => startImplement({ agent })}
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => startImplement()}
|
||||
disabled={busy}
|
||||
className="ui-btn-save gap-1.5"
|
||||
title="Queue again — Watch opens so you can follow"
|
||||
className="ui-btn-secondary gap-1.5"
|
||||
title="Queue again on the same provider — Watch opens so you can follow"
|
||||
>
|
||||
{busy ? <Loader2 className="ui-spinner-xs" /> : <Rocket className="h-3 w-3" />}
|
||||
Retry
|
||||
@@ -443,12 +455,12 @@ export function FeedbackItemRow({
|
||||
placeholder="Instruction for the agent, e.g. 'only fix the mobile layout'"
|
||||
className="ui-input-compact flex-1"
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === "Enter" && note.trim()) startImplement(note.trim());
|
||||
if (e.key === "Enter" && note.trim()) startImplement({ note: note.trim() });
|
||||
}}
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => startImplement(note.trim() || undefined)}
|
||||
onClick={() => startImplement(note.trim() ? { note: note.trim() } : undefined)}
|
||||
disabled={busy}
|
||||
className="ui-btn-save gap-1.5"
|
||||
>
|
||||
|
||||
@@ -27,10 +27,19 @@ export function useFeedbackActions(refetch: () => void) {
|
||||
}
|
||||
}
|
||||
|
||||
const dispatchFix = (id: string, note?: string) =>
|
||||
/**
|
||||
* Queue (or re-queue) the fix. `agent` switches provider in the same tap:
|
||||
* the route records it as the project's preference before dispatching, so
|
||||
* the next run does not go back to the agent that just hit a rate limit.
|
||||
*/
|
||||
const dispatchFix = (id: string, opts: { note?: string; agent?: string } = {}) =>
|
||||
act(
|
||||
id,
|
||||
() => postJson(`/api/feedback/${id}/dispatch`, note ? { note } : {}),
|
||||
() =>
|
||||
postJson(`/api/feedback/${id}/dispatch`, {
|
||||
...(opts.note ? { note: opts.note } : {}),
|
||||
...(opts.agent ? { agent: opts.agent } : {}),
|
||||
}),
|
||||
"Could not queue the fix",
|
||||
);
|
||||
|
||||
|
||||
@@ -316,7 +316,7 @@ export function ProjectFeedbackSection({
|
||||
feedback={f}
|
||||
projectName={projectName}
|
||||
busy={busyId === f.id}
|
||||
onDispatch={(note) => dispatchFix(f.id, note)}
|
||||
onDispatch={(opts) => dispatchFix(f.id, opts ?? {})}
|
||||
onResolve={() => setStatus(f.id, FEEDBACK_STATUS.RESOLVED)}
|
||||
onArchive={() => setStatus(f.id, FEEDBACK_STATUS.ARCHIVED)}
|
||||
onReopen={() => setStatus(f.id, FEEDBACK_STATUS.NEW)}
|
||||
|
||||
@@ -0,0 +1,127 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import { ArrowDown, ArrowUp, Check, Loader2 } from "lucide-react";
|
||||
import { patchJson } from "@/lib/api/fetch";
|
||||
import { TOAST_SHORT_MS } from "@/lib/constants/timings";
|
||||
import { providerLabel } from "@/config/quota-alternatives";
|
||||
import { parseProviderOrder, preferredProviderOrder } from "@/lib/provider-switch";
|
||||
import type { UserPreferencesData } from "@/db/queries/user-preferences";
|
||||
|
||||
/**
|
||||
* The order the fleet reaches for a new provider in when one runs out.
|
||||
*
|
||||
* This is the half of "one-tap provider switch" that makes the tap predictable.
|
||||
* Without it the chooser had to pick from a hardcoded fleet default, so the
|
||||
* button said "Try Cursor" to an operator whose Cursor subscription lapsed
|
||||
* months ago — and the only way to change it was to set a per-project agent
|
||||
* preference, project by project, after the fact.
|
||||
*
|
||||
* Deliberately a list and not a per-agent toggle: an agent the operator does
|
||||
* not want is simply ranked last, and nothing is ever hidden from the chooser.
|
||||
* A provider that is genuinely unusable is already excluded by evidence (not
|
||||
* installed, or observed out of quota) — hiding it here as well would give two
|
||||
* different mechanisms the same job and no way to tell which one applied.
|
||||
*/
|
||||
export function ProviderOrderSettings({ initialPrefs }: { initialPrefs: UserPreferencesData }) {
|
||||
const [order, setOrder] = useState(() =>
|
||||
preferredProviderOrder(parseProviderOrder(initialPrefs.agentOrder)),
|
||||
);
|
||||
const [savedOrder, setSavedOrder] = useState(order);
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [saved, setSaved] = useState(false);
|
||||
const [error, setError] = useState("");
|
||||
|
||||
const dirty = order.join(",") !== savedOrder.join(",");
|
||||
|
||||
const move = (index: number, delta: number) => {
|
||||
const target = index + delta;
|
||||
if (target < 0 || target >= order.length) return;
|
||||
const next = [...order];
|
||||
const [item] = next.splice(index, 1);
|
||||
next.splice(target, 0, item!);
|
||||
setOrder(next);
|
||||
setSaved(false);
|
||||
};
|
||||
|
||||
const save = async () => {
|
||||
setSaving(true);
|
||||
setError("");
|
||||
setSaved(false);
|
||||
try {
|
||||
const res = await patchJson("/api/me/preferences", { agentOrder: order });
|
||||
if (!res.ok) {
|
||||
const body = (await res.json().catch(() => ({}))) as { error?: string };
|
||||
setError(body.error ?? "Failed to save");
|
||||
return;
|
||||
}
|
||||
setSavedOrder(order);
|
||||
setSaved(true);
|
||||
setTimeout(() => setSaved(false), TOAST_SHORT_MS);
|
||||
} catch {
|
||||
setError("Network error — try again");
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<section className="ui-settings-section">
|
||||
<div className="space-y-1">
|
||||
<h2 className="text-sm font-medium text-text-primary">Provider order</h2>
|
||||
<p className="text-xs text-text-secondary">
|
||||
When the agent building a project hits a rate limit, “Try next provider” walks this list
|
||||
from the top and offers the first one that can actually answer — installed on your
|
||||
builder, and not itself out of quota.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<ol className="space-y-2">
|
||||
{order.map((id, i) => (
|
||||
<li key={id} className="ui-list-item">
|
||||
<span className="flex min-w-0 items-baseline gap-2">
|
||||
<span className="text-micro text-text-muted">{i + 1}</span>
|
||||
<span className="truncate text-sm text-text-primary">{providerLabel(id)}</span>
|
||||
{i === 0 && <span className="ui-badge shrink-0">first choice</span>}
|
||||
</span>
|
||||
<span className="flex shrink-0 items-center gap-1">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => move(i, -1)}
|
||||
disabled={i === 0}
|
||||
className="ui-btn-icon"
|
||||
title={`Move ${providerLabel(id)} up`}
|
||||
aria-label={`Move ${providerLabel(id)} up`}
|
||||
>
|
||||
<ArrowUp className="h-3.5 w-3.5" />
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => move(i, 1)}
|
||||
disabled={i === order.length - 1}
|
||||
className="ui-btn-icon"
|
||||
title={`Move ${providerLabel(id)} down`}
|
||||
aria-label={`Move ${providerLabel(id)} down`}
|
||||
>
|
||||
<ArrowDown className="h-3.5 w-3.5" />
|
||||
</button>
|
||||
</span>
|
||||
</li>
|
||||
))}
|
||||
</ol>
|
||||
|
||||
{error && <p className="ui-error">{error}</p>}
|
||||
<div className="flex items-center gap-3">
|
||||
<button type="button" onClick={save} disabled={!dirty || saving} className="ui-btn-save">
|
||||
{saving ? <Loader2 className="ui-spinner-xs" /> : null}
|
||||
Save order
|
||||
</button>
|
||||
{saved && (
|
||||
<span className="flex items-center gap-1 text-xs text-status-positive">
|
||||
<Check className="h-3 w-3" /> Saved
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -9,6 +9,7 @@ import { PrivacySettings } from "./PrivacySettings";
|
||||
import { LocationSettings } from "./LocationSettings";
|
||||
import { VoiceSettings } from "./VoiceSettings";
|
||||
import { AiQuotaSettings } from "./AiQuotaSettings";
|
||||
import { ProviderOrderSettings } from "./ProviderOrderSettings";
|
||||
import { AgentTokenSettings } from "./AgentTokenSettings";
|
||||
import { BeaconSettings } from "./BeaconSettings";
|
||||
import { BillingSettings } from "./BillingSettings";
|
||||
@@ -151,6 +152,7 @@ export function SettingsTabs({
|
||||
{activeTab === "location" && <LocationSettings initialPrefs={userPrefs} />}
|
||||
{activeTab === "agent" && (
|
||||
<div className="space-y-6">
|
||||
<ProviderOrderSettings initialPrefs={userPrefs} />
|
||||
<AgentTokenSettings />
|
||||
<BeaconSettings />
|
||||
</div>
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
import { Loader2 } from "lucide-react";
|
||||
import { MarkdownText } from "@/components/ui/markdown-text";
|
||||
import { ProviderSwitch } from "@/components/agents/ProviderSwitch";
|
||||
import { useDispatchLiveStatus } from "@/hooks/use-dispatch-live-status";
|
||||
import { dispatchToneDotClass } from "@/lib/dispatch-status";
|
||||
import { presentTerminalRun, type TerminalRunView } from "@/lib/terminal-run-view";
|
||||
@@ -19,7 +20,7 @@ export function TerminalLokiRail({
|
||||
tab,
|
||||
runId,
|
||||
ptyLive,
|
||||
currentAgent,
|
||||
projectId,
|
||||
canSwitchAgent,
|
||||
onSwitchAgent,
|
||||
}: {
|
||||
@@ -27,7 +28,8 @@ export function TerminalLokiRail({
|
||||
tab: string | null;
|
||||
runId: string | null;
|
||||
ptyLive: boolean;
|
||||
currentAgent: string | null;
|
||||
/** user_projects id — lets the chooser exclude the agent that just died. */
|
||||
projectId: string | null;
|
||||
canSwitchAgent: boolean;
|
||||
onSwitchAgent: (agentId: string) => void;
|
||||
}) {
|
||||
@@ -39,7 +41,7 @@ export function TerminalLokiRail({
|
||||
commandId: string | null;
|
||||
runId: string | null;
|
||||
} | null>(null);
|
||||
const [switching, setSwitching] = useState<string | null>(null);
|
||||
const [switching, setSwitching] = useState(false);
|
||||
|
||||
const liveDispatch = useDispatchLiveStatus(
|
||||
injectAck?.commandId ?? null,
|
||||
@@ -82,12 +84,12 @@ export function TerminalLokiRail({
|
||||
};
|
||||
}, [load]);
|
||||
|
||||
const switchTo = async (agentId: string) => {
|
||||
setSwitching(agentId);
|
||||
const switchTo = (agentId: string) => {
|
||||
setSwitching(true);
|
||||
try {
|
||||
onSwitchAgent(agentId);
|
||||
} finally {
|
||||
window.setTimeout(() => setSwitching(null), 800);
|
||||
window.setTimeout(() => setSwitching(false), 800);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -104,9 +106,6 @@ export function TerminalLokiRail({
|
||||
);
|
||||
}
|
||||
|
||||
const alternatives = view?.quotaDeath
|
||||
? view.alternatives.filter((a) => a.id !== currentAgent)
|
||||
: [];
|
||||
const ptyAck =
|
||||
injectAck &&
|
||||
(ptyLive || view?.lastProgressAt ? "PTY is printing." : "Injected — waiting for PTY bytes.");
|
||||
@@ -142,23 +141,20 @@ export function TerminalLokiRail({
|
||||
</div>
|
||||
)}
|
||||
|
||||
{alternatives.length > 0 && (
|
||||
{/* The rail used to list every alternative agent in config order,
|
||||
whether or not the connected builder had it installed and whether or
|
||||
not it had hit its own limit ten minutes earlier. Now it is the same
|
||||
ranked, filtered chooser Feedback and Control show — one tap, the
|
||||
operator's preferred order, only providers that can answer. */}
|
||||
{view?.quotaDeath && canSwitchAgent && (
|
||||
<div className="mt-3 flex flex-col gap-1.5">
|
||||
<p className="text-xs font-medium text-text-primary">Try another provider</p>
|
||||
<div className="flex flex-wrap gap-1.5">
|
||||
{alternatives.map((a) => (
|
||||
<button
|
||||
key={a.id}
|
||||
type="button"
|
||||
className="ui-btn-secondary"
|
||||
disabled={!canSwitchAgent || switching === a.id}
|
||||
onClick={() => void switchTo(a.id)}
|
||||
>
|
||||
{switching === a.id ? <Loader2 className="ui-spinner-xs" /> : null}
|
||||
Try {a.label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
<ProviderSwitch
|
||||
projectId={projectId}
|
||||
busy={switching}
|
||||
hint="Quits the current CLI in this tab and launches the one you pick."
|
||||
onSwitch={switchTo}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
|
||||
@@ -478,7 +478,7 @@ export function TerminalSurface({
|
||||
tab={activeTab}
|
||||
runId={initialRunId}
|
||||
ptyLive={liveState === "live"}
|
||||
currentAgent={activeAgentId}
|
||||
projectId={tabContext?.projectId ?? null}
|
||||
canSwitchAgent={!agentSwitchDisabledReason}
|
||||
onSwitchAgent={(id) => void switchAgent(id)}
|
||||
/>
|
||||
|
||||
@@ -240,6 +240,7 @@ export const DEMO_SAFE_FAMILIES: readonly string[] = [
|
||||
"project-states",
|
||||
"projects",
|
||||
"prompts",
|
||||
"providers",
|
||||
"robots",
|
||||
"sessions",
|
||||
"setup",
|
||||
@@ -261,6 +262,11 @@ export const DEMO_SAFE_FAMILIES: readonly string[] = [
|
||||
// OrangeCat, and that route carries its own denyDemoInHandler call —
|
||||
// it cannot live in DEMO_HANDLER_ENFORCED because the matcher does
|
||||
// reach /api/crew, and this list is for families it excludes.
|
||||
// providers — read-only, and every input is the caller's own: their projects,
|
||||
// their preference row, their builder's capability report, their own
|
||||
// runs. It spends nothing to answer (the quota evidence is read from
|
||||
// runs already recorded, never probed from a vendor), so a demo
|
||||
// account asking who else could build is asking about itself.
|
||||
// share — the assignee's endpoint. It answers on a token, before and without
|
||||
// any session, exactly like /api/invitations/<token>. Gating the demo
|
||||
// account on it would protect nothing: a caller holding a share token
|
||||
|
||||
@@ -1,19 +1,46 @@
|
||||
/**
|
||||
* Agents offered when the current builder is quota-dead / inject-no-generate.
|
||||
*
|
||||
* SSOT for the Terminal Loki rail and Needs-you chooser. Hermes is not in this
|
||||
* list — it is a hosted fallback, not a one-tap swap. Antigravity is Gemini's
|
||||
* product name; the orchestration id stays `gemini`.
|
||||
* SSOT for the *membership and labels* of every provider chooser — the Terminal
|
||||
* Loki rail, the Needs-you row on Feedback, and the Control inbox. The ORDER a
|
||||
* chooser offers them in is not here: it is the operator's preferred order
|
||||
* (`user_preferences.agent_order`), defaulting to `AGENT_FALLBACK_ORDER`. This
|
||||
* list is derived from that default so the two can never disagree about WHICH
|
||||
* agents exist — a chooser that offered an agent the reroute policy had never
|
||||
* heard of was how "try next provider" and "auto-reroute" ended up disagreeing.
|
||||
*
|
||||
* Hermes is not in this list — it is a hosted fallback, not a one-tap swap.
|
||||
* Antigravity is Gemini's product name; the orchestration id stays `gemini`.
|
||||
*/
|
||||
import { AGENT_LABELS } from "@/lib/agent-labels";
|
||||
import { AGENT_LABELS, type AnyAgentId } from "@/lib/agent-labels";
|
||||
import { AGENT_FALLBACK_ORDER } from "@/lib/agent-resolution";
|
||||
|
||||
export const QUOTA_ALTERNATIVE_AGENTS = [
|
||||
{ id: "claude", label: "Claude Code" },
|
||||
{ id: "codex", label: AGENT_LABELS.codex },
|
||||
{ id: "cursor", label: AGENT_LABELS.cursor },
|
||||
{ id: "grok", label: AGENT_LABELS.grok },
|
||||
{ id: "gemini", label: "Antigravity" },
|
||||
] as const;
|
||||
/**
|
||||
* Names the vendor puts on the product, where they differ from the agent id's
|
||||
* generic label. `AGENT_LABELS.gemini` is "Gemini" (the model); the thing an
|
||||
* operator installs and switches to is called Antigravity.
|
||||
*/
|
||||
const PRODUCT_LABELS: Partial<Record<AnyAgentId, string>> = {
|
||||
claude: "Claude Code",
|
||||
gemini: "Antigravity",
|
||||
};
|
||||
|
||||
export type QuotaAlternativeId = (typeof QUOTA_ALTERNATIVE_AGENTS)[number]["id"];
|
||||
export type QuotaAlternativeId = (typeof AGENT_FALLBACK_ORDER)[number];
|
||||
export type QuotaAlternative = { id: QuotaAlternativeId; label: string };
|
||||
|
||||
export const QUOTA_ALTERNATIVE_AGENTS: readonly QuotaAlternative[] = AGENT_FALLBACK_ORDER.map(
|
||||
(id) => ({ id, label: PRODUCT_LABELS[id] ?? AGENT_LABELS[id] }),
|
||||
);
|
||||
|
||||
export const QUOTA_ALTERNATIVE_IDS: readonly QuotaAlternativeId[] = AGENT_FALLBACK_ORDER;
|
||||
|
||||
export function isQuotaAlternativeId(value: unknown): value is QuotaAlternativeId {
|
||||
return typeof value === "string" && (QUOTA_ALTERNATIVE_IDS as readonly string[]).includes(value);
|
||||
}
|
||||
|
||||
/** The chooser's display name for an agent id — never the bare id. */
|
||||
export function providerLabel(id: string): string {
|
||||
return (
|
||||
QUOTA_ALTERNATIVE_AGENTS.find((a) => a.id === id)?.label ?? AGENT_LABELS[id as AnyAgentId] ?? id
|
||||
);
|
||||
}
|
||||
@@ -13,6 +13,8 @@ export type UserPreferencesData = {
|
||||
currentCityUntil: string | null;
|
||||
writingVoice: string | null;
|
||||
memoryEnabled: boolean;
|
||||
/** Preferred provider order, comma-separated agent ids. Null = fleet default. */
|
||||
agentOrder: string | null;
|
||||
};
|
||||
|
||||
export function getActiveCity(prefs: UserPreferencesData | null): string {
|
||||
@@ -53,6 +55,7 @@ export async function getUserPreferences(userId: string): Promise<UserPreference
|
||||
currentCityUntil: null,
|
||||
writingVoice: null,
|
||||
memoryEnabled: true,
|
||||
agentOrder: null,
|
||||
};
|
||||
|
||||
return {
|
||||
@@ -64,6 +67,7 @@ export async function getUserPreferences(userId: string): Promise<UserPreference
|
||||
currentCityUntil: row.currentCityUntil,
|
||||
writingVoice: row.writingVoice,
|
||||
memoryEnabled: row.memoryEnabled,
|
||||
agentOrder: row.agentOrder,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -95,5 +99,6 @@ function toRow(d: UserPreferencesData) {
|
||||
currentCityUntil: d.currentCityUntil,
|
||||
writingVoice: d.writingVoice,
|
||||
memoryEnabled: d.memoryEnabled,
|
||||
agentOrder: d.agentOrder,
|
||||
};
|
||||
}
|
||||
@@ -24,6 +24,21 @@ export const userPreferences = pgTable(
|
||||
// Consent: may the fleet build its knowledge index (RAG embeddings) from the
|
||||
// user's data? Gates upsertKnowledgeBatch — the single write chokepoint.
|
||||
memoryEnabled: boolean("memory_enabled").notNull().default(true),
|
||||
/**
|
||||
* Which agent CLI to reach for first when the current one runs out of
|
||||
* quota — comma-separated agent ids, best first ("codex,claude,grok").
|
||||
*
|
||||
* Null is a real answer and not a missing one: it means the operator never
|
||||
* stated a preference, and the fleet's default order (AGENT_FALLBACK_ORDER)
|
||||
* applies. Stored as one ordered string rather than a rank-per-agent table
|
||||
* because the only question ever asked of it is "what is the whole order",
|
||||
* and a list is how an ordered list is spelled.
|
||||
*
|
||||
* Unknown ids are tolerated on read (parseProviderOrder drops them) so a
|
||||
* retired agent id in an old row degrades to "not ranked" instead of
|
||||
* breaking the chooser it feeds.
|
||||
*/
|
||||
agentOrder: text("agent_order"),
|
||||
updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
|
||||
},
|
||||
(t) => [index("idx_user_preferences_user_id").on(t.userId)],
|
||||
|
||||
@@ -25,17 +25,24 @@ import {
|
||||
effectiveModelSuggestions,
|
||||
} from "@/lib/agents";
|
||||
import type { AgentAdapter } from "@/lib/agents";
|
||||
import { looksLikeAgentCapacityIssue as detectCapacityIssue } from "@/lib/agent-resolution";
|
||||
import {
|
||||
AGENT_FALLBACK_ORDER,
|
||||
looksLikeAgentCapacityIssue as detectCapacityIssue,
|
||||
} from "@/lib/agent-resolution";
|
||||
|
||||
export const AGENT_IDS = ["codex", "claude", "gemini", "cursor", "grok"] as const;
|
||||
export const AGENT_FALLBACK_ORDER: readonly Agent[] = [
|
||||
"claude",
|
||||
"cursor",
|
||||
"codex",
|
||||
"gemini",
|
||||
"grok",
|
||||
];
|
||||
export type Agent = (typeof AGENT_IDS)[number];
|
||||
|
||||
/**
|
||||
* Re-export, not a second definition. This file used to declare its own
|
||||
* `AGENT_FALLBACK_ORDER` beside the one in agent-resolution.ts — the same five
|
||||
* ids, written twice, with nothing keeping them in step. The server reroute
|
||||
* (resolveNextAvailableAgent, here) and the client reroute
|
||||
* (resolveNextFallbackAgent, there) each read their own copy, so adding an
|
||||
* agent to one would have silently split the fleet's fallback policy in half.
|
||||
* agent-resolution.ts owns it because it is the client-safe leaf.
|
||||
*/
|
||||
export { AGENT_FALLBACK_ORDER } from "@/lib/agent-resolution";
|
||||
export type AgentOption = Agent | "openclaw";
|
||||
|
||||
export { ALL_AGENT_IDS, AGENT_LABELS, type AnyAgentId } from "./agent-labels";
|
||||
|
||||
@@ -0,0 +1,244 @@
|
||||
/**
|
||||
* "Try a provider that still has quota" — the whole decision, as pure functions.
|
||||
*
|
||||
* ── THE PROBLEM THIS SOLVES ─────────────────────────────────────────────────
|
||||
*
|
||||
* When the agent building a project hits a rate limit, the operator already
|
||||
* owns a way out: four other agent CLIs, most of them with untouched quota. The
|
||||
* cost of taking it was the problem. The only chooser lived in the Terminal
|
||||
* right rail, it offered every agent in a fixed order whether or not the
|
||||
* connected builder had it installed, and taking it swapped the live PTY
|
||||
* without recording the choice — so the next dispatch went straight back to the
|
||||
* agent that had just run out.
|
||||
*
|
||||
* So: one ranking, three inputs, used by every surface that can show a blocked
|
||||
* run (Feedback row, Control inbox, Terminal rail).
|
||||
*
|
||||
* ── WHAT COUNTS AS "CAN ACTUALLY ANSWER" ────────────────────────────────────
|
||||
*
|
||||
* Two pieces of evidence, both observed rather than polled:
|
||||
*
|
||||
* 1. INSTALLED — the connected builder's capability report
|
||||
* (`runtime_snapshots.installed_agents`). An agent the builder never
|
||||
* reported cannot be launched there, so offering it is offering a button
|
||||
* that quits a working CLI to start a binary that is not present.
|
||||
*
|
||||
* 2. SPENT — a recent run on that agent that died with capacity language
|
||||
* (`orchestration_runs.adapter` + payload error, read through
|
||||
* `looksLikeAgentCapacityIssue`). This is the agent-CLI equivalent of the
|
||||
* rate-limit headers `provider_quota` records: evidence from a call we
|
||||
* were making anyway, never a probe that spends quota to measure quota.
|
||||
*
|
||||
* `provider_quota` itself is deliberately NOT an input. That table meters the
|
||||
* ai-kit INFERENCE chain (groq, openrouter) that answers Loki's own chat and
|
||||
* form-assist calls. Claude Code and Codex are not links in that chain, and
|
||||
* wiring a groq counter into a Claude Code chooser would have been a number
|
||||
* that looks like evidence and is about a different system.
|
||||
*
|
||||
* ── ABSENT IS NOT EMPTY ─────────────────────────────────────────────────────
|
||||
*
|
||||
* The same three-state rule `provider_quota` is built on: an agent the builder
|
||||
* said nothing about is UNKNOWN, and unknown reads as usable. A control plane
|
||||
* with no runner connected knows nothing about anything, and drawing that as
|
||||
* "every provider is unavailable" would disable the one control the operator
|
||||
* came for. Only an explicit report excludes an agent — exactly the rule
|
||||
* `AgentSwitcherPopover` already holds for its disabled rows.
|
||||
*/
|
||||
import {
|
||||
QUOTA_ALTERNATIVE_AGENTS,
|
||||
isQuotaAlternativeId,
|
||||
providerLabel,
|
||||
type QuotaAlternativeId,
|
||||
} from "@/config/quota-alternatives";
|
||||
import { AGENT_FALLBACK_ORDER, looksLikeAgentCapacityIssue } from "@/lib/agent-resolution";
|
||||
|
||||
/** How long a capacity wall keeps a provider out of the chooser. */
|
||||
export const PROVIDER_SPENT_WINDOW_MS = 60 * 60 * 1000;
|
||||
|
||||
/**
|
||||
* WHY a provider cannot answer — typed, not just prose.
|
||||
*
|
||||
* The chooser prints a short suffix beside a disabled row, and "not installed"
|
||||
* was hardcoded there. A provider that is installed and merely out of quota
|
||||
* would then have read "(not installed)" beside a sentence saying it hit a
|
||||
* limit — two different claims about the same agent, one of them false.
|
||||
*/
|
||||
export type ProviderBlock = "not-installed" | "spent";
|
||||
|
||||
export const PROVIDER_BLOCK_NOTE: Record<ProviderBlock, string> = {
|
||||
"not-installed": "not installed",
|
||||
spent: "out of quota",
|
||||
};
|
||||
|
||||
export type ProviderOption = {
|
||||
id: QuotaAlternativeId;
|
||||
label: string;
|
||||
/** Offer it as a one-tap switch. False rows still render, disabled, with why. */
|
||||
usable: boolean;
|
||||
/** Why this one cannot answer. Null when it can. */
|
||||
reason: string | null;
|
||||
/** Which kind of "cannot". Null when usable. */
|
||||
block: ProviderBlock | null;
|
||||
};
|
||||
|
||||
/**
|
||||
* The operator's order, repaired.
|
||||
*
|
||||
* Saved order wins, unknown ids are dropped, and every agent the operator did
|
||||
* not rank is appended in default order rather than disappearing — a provider
|
||||
* missing from the chooser because it was missing from a preference list is
|
||||
* the same invisible dead end this whole feature exists to remove.
|
||||
*/
|
||||
export function preferredProviderOrder(
|
||||
saved: readonly string[] | null | undefined,
|
||||
): QuotaAlternativeId[] {
|
||||
const ranked: QuotaAlternativeId[] = [];
|
||||
for (const id of saved ?? []) {
|
||||
if (isQuotaAlternativeId(id) && !ranked.includes(id)) ranked.push(id);
|
||||
}
|
||||
for (const id of AGENT_FALLBACK_ORDER) {
|
||||
if (!ranked.includes(id)) ranked.push(id);
|
||||
}
|
||||
return ranked;
|
||||
}
|
||||
|
||||
/** Parse/serialize the stored order. One column, comma separated, ids only. */
|
||||
export function parseProviderOrder(stored: string | null | undefined): QuotaAlternativeId[] | null {
|
||||
if (!stored?.trim()) return null;
|
||||
const ids = stored
|
||||
.split(",")
|
||||
.map((s) => s.trim())
|
||||
.filter(isQuotaAlternativeId);
|
||||
return ids.length ? [...new Set(ids)] : null;
|
||||
}
|
||||
|
||||
export function serializeProviderOrder(order: readonly string[]): string | null {
|
||||
const ids = order.filter(isQuotaAlternativeId);
|
||||
return ids.length ? [...new Set(ids)].join(",") : null;
|
||||
}
|
||||
|
||||
export type ProviderRankInput = {
|
||||
/** The agent that just hit the wall. Excluded — switching to yourself is not a switch. */
|
||||
current?: string | null;
|
||||
/** The operator's preferred order (already parsed). Null = default order. */
|
||||
order?: readonly string[] | null;
|
||||
/**
|
||||
* Agent ids the connected builder reported installed. `null` or empty means
|
||||
* NOTHING WAS REPORTED, which is unknown, not unavailable — see the header.
|
||||
*/
|
||||
installed?: readonly string[] | null;
|
||||
/** id → why it is spent, from `spentProviders`. */
|
||||
spent?: Readonly<Record<string, string>>;
|
||||
};
|
||||
|
||||
/**
|
||||
* Every provider the operator could switch to, best first.
|
||||
*
|
||||
* Usable ones come first in the operator's order, then the ones that cannot
|
||||
* answer — also in that order, and never hidden. A provider silently missing
|
||||
* from the list is indistinguishable from a provider that does not exist, and
|
||||
* the operator's next question after "why is Codex not offered?" cannot be
|
||||
* answered by a list that omits it.
|
||||
*/
|
||||
export function rankProviders(input: ProviderRankInput): ProviderOption[] {
|
||||
const order = preferredProviderOrder(input.order);
|
||||
const current = (input.current ?? "").toLowerCase();
|
||||
const reported = input.installed && input.installed.length > 0 ? new Set(input.installed) : null;
|
||||
const spent = input.spent ?? {};
|
||||
|
||||
const options = order
|
||||
.filter((id) => id !== current)
|
||||
.map((id): ProviderOption => {
|
||||
if (reported && !reported.has(id)) {
|
||||
return {
|
||||
id,
|
||||
label: providerLabel(id),
|
||||
usable: false,
|
||||
reason: `${providerLabel(id)} is not installed on the connected builder.`,
|
||||
block: "not-installed",
|
||||
};
|
||||
}
|
||||
const spentReason = spent[id];
|
||||
if (spentReason) {
|
||||
return {
|
||||
id,
|
||||
label: providerLabel(id),
|
||||
usable: false,
|
||||
reason: spentReason,
|
||||
block: "spent",
|
||||
};
|
||||
}
|
||||
return { id, label: providerLabel(id), usable: true, reason: null, block: null };
|
||||
});
|
||||
|
||||
return [...options.filter((o) => o.usable), ...options.filter((o) => !o.usable)];
|
||||
}
|
||||
|
||||
/** The one-tap target: the first provider in the operator's order that can answer. */
|
||||
export function nextProvider(options: readonly ProviderOption[]): ProviderOption | null {
|
||||
return options.find((o) => o.usable) ?? null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Which agent this project would run on right now — the one to EXCLUDE.
|
||||
*
|
||||
* Not simply `agentPref`. A project that has never had a preference set still
|
||||
* dispatches, on the default adapter, and reading "current" as null there let
|
||||
* the chooser cheerfully offer Claude Code as the way out of a Claude Code rate
|
||||
* limit. So: what it last actually ran on, else what it would be told to run
|
||||
* on, else the fleet default.
|
||||
*/
|
||||
export function currentProviderFor(input: {
|
||||
agentPref?: string | null;
|
||||
/** Freshest-first runs for THIS project, as listRecentRuns returns them. */
|
||||
projectRuns?: readonly { adapter: string }[];
|
||||
defaultAdapter: string;
|
||||
}): string {
|
||||
const lastRun = input.projectRuns?.find((r) => isQuotaAlternativeId(r.adapter))?.adapter;
|
||||
if (lastRun) return lastRun;
|
||||
if (input.agentPref && isQuotaAlternativeId(input.agentPref)) return input.agentPref;
|
||||
return input.defaultAdapter;
|
||||
}
|
||||
|
||||
export type ProviderRunEvidence = {
|
||||
adapter: string;
|
||||
error?: string | null;
|
||||
startedAt: Date | string;
|
||||
};
|
||||
|
||||
/**
|
||||
* Providers with a capacity wall inside the window, and the moment they hit it.
|
||||
*
|
||||
* Reads runs we already record. A run that failed for any OTHER reason is not
|
||||
* evidence about quota and must not remove a provider from the chooser —
|
||||
* "Codex crashed on a bad path once" is not "Codex has no quota".
|
||||
*/
|
||||
export function spentProviders(
|
||||
runs: readonly ProviderRunEvidence[],
|
||||
nowMs: number = Date.now(),
|
||||
windowMs: number = PROVIDER_SPENT_WINDOW_MS,
|
||||
): Record<string, string> {
|
||||
const out: Record<string, string> = {};
|
||||
for (const run of runs) {
|
||||
if (!isQuotaAlternativeId(run.adapter)) continue;
|
||||
if (out[run.adapter]) continue;
|
||||
const error = run.error?.trim();
|
||||
if (!error || !looksLikeAgentCapacityIssue(error)) continue;
|
||||
const at = run.startedAt instanceof Date ? run.startedAt.getTime() : Date.parse(run.startedAt);
|
||||
if (!Number.isFinite(at) || nowMs - at > windowMs) continue;
|
||||
out[run.adapter] =
|
||||
`${providerLabel(run.adapter)} hit a limit ${minutesAgo(nowMs - at)} — it may still be spent.`;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function minutesAgo(deltaMs: number): string {
|
||||
const mins = Math.max(1, Math.round(deltaMs / 60_000));
|
||||
if (mins < 60) return `${mins}m ago`;
|
||||
return `${Math.round(mins / 60)}h ago`;
|
||||
}
|
||||
|
||||
/** Every provider id a chooser may name — for API validation. */
|
||||
export const PROVIDER_IDS: readonly QuotaAlternativeId[] = QUOTA_ALTERNATIVE_AGENTS.map(
|
||||
(a) => a.id,
|
||||
);
|
||||
@@ -3,7 +3,6 @@
|
||||
* the same work-phase + run_events hop Watch uses. Not a log dump.
|
||||
*/
|
||||
import { looksLikeAgentCapacityIssue } from "@/lib/agent-resolution";
|
||||
import { QUOTA_ALTERNATIVE_AGENTS, type QuotaAlternative } from "@/config/quota-alternatives";
|
||||
import { FEEDBACK_WORK_PHASE, type FeedbackWorkView } from "@/lib/feedback/work-phase";
|
||||
|
||||
export type TerminalRunView = {
|
||||
@@ -17,8 +16,17 @@ export type TerminalRunView = {
|
||||
diagnostic: string | null;
|
||||
terminalReady: boolean;
|
||||
lastProgressAt: string | null;
|
||||
/**
|
||||
* This run died on a capacity wall, so the rail offers the provider chooser.
|
||||
*
|
||||
* The list of WHICH providers is no longer computed here. It used to be —
|
||||
* every alternative in config order, unfiltered — and the rail rendered it
|
||||
* verbatim, offering agents the connected builder had never installed. The
|
||||
* ranking now lives in one place (`/api/providers` over
|
||||
* `src/lib/provider-switch.ts`) and is shared with Feedback and Control, so
|
||||
* this flag says only whether to ask it.
|
||||
*/
|
||||
quotaDeath: boolean;
|
||||
alternatives: QuotaAlternative[];
|
||||
};
|
||||
|
||||
export type TerminalRunPresentation = Pick<TerminalRunView, "label" | "stepSummary" | "nextAction">;
|
||||
@@ -42,20 +50,21 @@ export function presentTerminalRun(
|
||||
};
|
||||
}
|
||||
|
||||
export function quotaDeathAlternatives(input: {
|
||||
/** Did this run die because the agent ran out of capacity? */
|
||||
export function isQuotaDeath(input: {
|
||||
diagnostic?: string | null;
|
||||
error?: string | null;
|
||||
currentAgent?: string | null;
|
||||
}): QuotaAlternative[] | null {
|
||||
}): boolean {
|
||||
const text = [input.diagnostic, input.error].filter(Boolean).join(" ");
|
||||
if (!text || !looksLikeAgentCapacityIssue(text)) return null;
|
||||
const current = (input.currentAgent ?? "").toLowerCase();
|
||||
const list = QUOTA_ALTERNATIVE_AGENTS.filter((a) => a.id !== current);
|
||||
return list.length ? [...list] : null;
|
||||
return !!text && looksLikeAgentCapacityIssue(text);
|
||||
}
|
||||
|
||||
export function nextActionForWork(work: FeedbackWorkView, quotaDeath = false): string {
|
||||
if (quotaDeath) return "Quota empty — try Claude Code, Codex, Cursor, Grok, or Antigravity.";
|
||||
// Deliberately does not name the alternatives. It used to list all five, and
|
||||
// that sentence went stale the moment the chooser started filtering to the
|
||||
// ones actually installed — the prose promised Cursor while the button below
|
||||
// it said Cursor was not installed.
|
||||
if (quotaDeath) return "Quota empty — switch to a provider that still has some.";
|
||||
if (work.queueReason) return work.queueReason;
|
||||
if (work.detail) return work.detail;
|
||||
if (work.phase === FEEDBACK_WORK_PHASE.WORKING) {
|
||||
@@ -71,16 +80,10 @@ export function buildTerminalRunView(input: {
|
||||
runId: string;
|
||||
projectKey: string;
|
||||
work: FeedbackWorkView;
|
||||
currentAgent?: string | null;
|
||||
lastProgressAt?: string | null;
|
||||
error?: string | null;
|
||||
}): TerminalRunView {
|
||||
const alternatives = quotaDeathAlternatives({
|
||||
diagnostic: input.work.diagnostic,
|
||||
error: input.error,
|
||||
currentAgent: input.currentAgent,
|
||||
});
|
||||
const quotaDeath = alternatives !== null;
|
||||
const quotaDeath = isQuotaDeath({ diagnostic: input.work.diagnostic, error: input.error });
|
||||
return {
|
||||
runId: input.runId,
|
||||
projectKey: input.projectKey,
|
||||
@@ -95,6 +98,5 @@ export function buildTerminalRunView(input: {
|
||||
terminalReady: input.work.terminalReady === true,
|
||||
lastProgressAt: input.lastProgressAt ?? input.work.lastActivityAt ?? null,
|
||||
quotaDeath,
|
||||
alternatives: alternatives ?? [],
|
||||
};
|
||||
}
|
||||
Reference in new issue
Block a user